diff --git a/browser-host/relay-broker-api.test.mjs b/browser-host/relay-broker-api.test.mjs index 486ab60abb..2d8483ce02 100644 --- a/browser-host/relay-broker-api.test.mjs +++ b/browser-host/relay-broker-api.test.mjs @@ -4105,6 +4105,66 @@ test("details routes are narrow, require the live owner, and do not widen lifecy } }); +test("later Admin additions cross the broker and replay the exact saved event after restart", async () => { + const h = await harness(success); + let first; + let restored; + let live; + let records = []; + const storage = { + load: () => structuredClone(records), + save: (next) => { + records = structuredClone(next); + }, + }; + try { + const transport = await connectBrokerTransport(h.base); + first = createOutbox(transport.viewer, transport.writer, storage); + await first.outbox.ready(); + const id = first.outbox.send({ + kind: 9000, + content: "", + tags: [ + ["h", "11111111-1111-4111-8111-111111111111"], + ["p", getPublicKey(new Uint8Array(32).fill(5))], + ["role", "admin"], + ], + }); + await vi.waitFor(() => + expect(first.outbox.snapshot()[0]?.delivery).toBe("failed"), + ); + // Signing succeeds through the purpose-bound route. Publication needs a live socket. + const signed = first.outbox.snapshot()[0]?.signed; + expect(signed).toBeDefined(); + const saved = JSON.parse(JSON.stringify(signed)); + expect(verifyEvent(structuredClone(saved))).toBe(true); + expect(saved.tags).toContainEqual(["role", "admin"]); + expect(saved.tags.at(-1)?.[0]).toBe("client-id"); + expect(h.publications).toHaveLength(0); + expect((await h.post("sign", saved)).status).toBe(400); + expect((await h.post("publish", saved)).status).toBe(400); + first.dispose(); + wallClock += 10000; + const resumed = await connectBrokerTransport(h.base); + live = await openBrokerSocket(resumed); + restored = createOutbox(resumed.viewer, resumed.writer, storage); + await restored.outbox.ready(); + restored.outbox.retry(id); + await vi.waitFor(() => + expect(restored.outbox.snapshot()[0]?.delivery).toBe("accepted"), + ); + expect(h.publications).toEqual([saved]); + expect( + JSON.parse(JSON.stringify(restored.outbox.snapshot()[0]?.signed)), + ).toEqual(saved); + } finally { + first?.dispose(); + restored?.dispose(); + live?.dispose(); + await h.close(); + } +}); + test("member administration uses isolated shape-limited routes and the current community socket", async () => { const h = await harness(success); let live; @@ -4161,6 +4221,26 @@ test("member administration uses isolated shape-limited routes and the current c { ...template, tags: [...template.tags, ["h", id]] }, { ...template, tags: null }, { ...template, tags: [null] }, + ...[ + [...template.tags, ["client-id", "invalid"]], + [ + ...template.tags, + ["client-id", "22222222-2222-4222-8222-222222222222"], + ["p", target], + ], + [ + template.tags[0], + ["p", transport.viewer], + template.tags[2], + ["client-id", "22222222-2222-4222-8222-222222222222"], + ], + [ + template.tags[0], + template.tags[1], + ["role", "owner"], + ["client-id", "22222222-2222-4222-8222-222222222222"], + ], + ].map((tags) => ({ ...template, tags })), ]; for (const event of invalid) for (const route of [ diff --git a/browser-host/relay-broker.mjs b/browser-host/relay-broker.mjs index 1b9fbbbded..e94a0442d4 100644 --- a/browser-host/relay-broker.mjs +++ b/browser-host/relay-broker.mjs @@ -24,7 +24,10 @@ import { communityGitRepository, parseGitRead, } from "../src/features/repos/git.ts"; -import { validateMemberAdministrationTemplate } from "../src/features/channel-members/administration-protocol.ts"; +import { + isAdminAddition, + validateMemberAdministrationTemplate, +} from "../src/features/channel-members/administration-protocol.ts"; import { validateLifecycleTemplate } from "../src/features/relay/channel-lifecycle-protocol.ts"; import { validateDetailsTemplate } from "../src/features/relay/channel-details-protocol.ts"; import { validateArchiveRequestTemplate } from "../src/features/relay/identity-archive-protocol.ts"; @@ -2973,7 +2976,8 @@ export function relayBrokerPlugin({ if (signing || publishing) { if (administration) { try { - validateMemberAdministrationTemplate(filters, viewer); + if (!isAdminAddition(filters, viewer)) + validateMemberAdministrationTemplate(filters, viewer); } catch { return json(res, 400, { error: "Invalid member administration command", diff --git a/docs/buzz-help.md b/docs/buzz-help.md index 0b5f4a3341..cdc937eae2 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -430,8 +430,19 @@ and are asked to sign in again in Buzz. the full, scrollable list of names. Messages and huddle entries split groups. - **Solo** organizes your chats with agents. Choose **New chat**, select or tag - an agent, and send a message. Solo conversations continue at the chat's top - level rather than requiring a new thread for each reply. Where available, use + an agent, and send a message. Your agents become chat admins before the opening + message is delivered, including agents added by workspace defaults; you remain + owner. Ownership is verified from their signed profiles. Your agents added + later to a Solo chat you own also join as admins, whether from the composer or + Chat access. Other people's agents get ordinary participation; later additions + use Bot. Existing members keep their saved roles. + If admin setup is interrupted, **Retry** on the opening message attempts to + finish it without restoring later demotions or removals. If setup is blocked, + choose **Abandon admin setup** in Outbox as soon as the chat exists. This keeps + the chat and current roles and stops unfinished setup in other windows. Then + retry the opening message, or send a new one if the original has expired. + Solo conversations continue at the chat's top level + rather than requiring a new thread for each reply. Where available, use **Model and effort** in the composer before sending; Solo keeps those choices for that chat until you reset them in the same control, even if its available models change. If a loaded catalog no longer offers a saved choice, the diff --git a/docs/solo/README.md b/docs/solo/README.md index e9e240156c..9233802d80 100644 --- a/docs/solo/README.md +++ b/docs/solo/README.md @@ -100,6 +100,25 @@ behavior on the label, so a rename touches copy only. agents: answer as one channel-scoped, top-level conversation. It is not access authority. The in-app agent harness reads it from the channel list; remote harnesses that only read `about` need to learn the label. +- New Solo chats grant Admin to the creator's agents whose signed profiles verify + that ownership, including agents included through workspace defaults. Agents + owned by someone else keep ordinary participation. The app uses the existing + member-administration commands before releasing the opening message to local + agents or the relay. When the viewer owns the Solo chat, their own new agents + added later through the composer or Chat access receive Admin; other agents + join as Bot. Existing members keep + their saved roles; retries retain the original addition's role and command ID. + The create's local Outbox receipt retains the opening + admin targets across interruptions; retries reconstruct the same grants and + confirm their recorded IDs before sending. A recorded grant stays complete + after a later demotion or removal. Expired, unrecorded grants are never re-dated. + Outbox offers **Abandon admin setup** once the create is delivered. Confirming + retires its recovery receipt while keeping the chat and granted + roles. Grant publication and retirement share the receipt’s durable ownership + lock, so another window’s unfinished signature cannot publish after abandonment. + After confirming, retry the opening message with current roles or send a new + message if its signed timestamp has expired. This needs no relay update + and does not migrate existing members' roles or change tool-created grants. - The Buzz tools' `channel_create` with `solo` sends the same create for any caller, including the standalone stdio server: signed by the caller, with the label and any `members` it names. The caller is the creator, so an agent's diff --git a/docs/solo/sharing.md b/docs/solo/sharing.md index d40d97ce75..1f2224a5c5 100644 --- a/docs/solo/sharing.md +++ b/docs/solo/sharing.md @@ -39,8 +39,11 @@ people, agents and channels** for an owner who can add agents) filters current access and lists people under **Not in this chat**, each with an **Add** button; Enter adds the highlighted person. Adding is immediate and uses the Solo share rule (`canShareSoloChat`), with per-person **Adding…**, error and **Retry** states. The -owner's selectable agents are offered too and join as Bot, even with a Guest -admission default, without starting a run. Composer mentions use the same grant. +owner's selectable agents are offered too. Agents whose signed profiles verify +that the chat owner owns them join as Admin; other agents join as Bot, even with +a Guest admission default, without starting a run. Composer mentions use the +same rule; other participants' composer additions use Bot. +Existing members keep their roles, and retries finish the original saved grant. Where the viewer cannot add agents, a note says to mention an agent in the chat instead. Current access uses the channel groups (**People**, **Agents**) with Owner and diff --git a/src/bundled/channels/ChannelMembersDialog.test.tsx b/src/bundled/channels/ChannelMembersDialog.test.tsx index 16b10bb418..ff1a9eea76 100644 --- a/src/bundled/channels/ChannelMembersDialog.test.tsx +++ b/src/bundled/channels/ChannelMembersDialog.test.tsx @@ -27,6 +27,7 @@ import type { VerifiedProfileAuthority } from "../../features/relay/verified-pro import { keypair, metadata, + ownedProfile, profile, roster, signed, @@ -116,6 +117,7 @@ async function setup( pendingMemberNames?: Promise; channelCreation?: boolean; memberWrites?: boolean; + agentOwner?: "viewer" | "other"; searchProfiles?: ( query: string, limit: number, @@ -142,8 +144,9 @@ async function setup( const viewer = keypair(), relay = options.relay ?? keypair(), person = keypair(); + const agentKey = keypair(); const agent = { - pubkey: "ab".repeat(32), + pubkey: agentKey.pubkey, name: "Fixture agent", relayUrl: "wss://relay.example.test", owner: viewer.pubkey, @@ -214,6 +217,17 @@ async function setup( ? managedProfile(person, keypair(), 1) : profile(person, { name: "Morgan" }); const stableEvents = [ + ...(localAgent + ? [ + eventDto( + await ownedProfile( + agentKey, + options.agentOwner === "other" ? person : viewer, + "Fixture agent", + ), + ), + ] + : []), signed(relay, { kind: 39000, content: "", @@ -246,6 +260,20 @@ async function setup( profile(viewer, { name: "Carl" }), personProfile, ]; + const currentRoster = () => + type === "solo" + ? signed(relay, { + kind: 39002, + created_at: clock, + content: "", + tags: [ + ["d", id], + ...members.map((key) => + key === viewer.pubkey ? ["p", key, "", "owner"] : ["p", key], + ), + ], + }) + : roster(relay, id, members, clock); const query = vi.fn(async (filters: Parameters[1][]) => { if (filters.some((filter) => filter.search)) { if (searchFailure) throw new Error("Search offline"); @@ -282,8 +310,8 @@ async function setup( roster(relay, forkId, forkMembers, clock), ] : []; - return [roster(relay, id, members, clock), ...fork, ...stableEvents].filter( - (event) => filters.some((filter) => matchesEvent(event, filter)), + return [currentRoster(), ...fork, ...stableEvents].filter((event) => + filters.some((filter) => matchesEvent(event, filter)), ); }); const readAgentLibrary = vi.fn( @@ -380,7 +408,8 @@ async function setup( viewer, replaceRoster: (keys: string[]) => { members.splice(0, members.length, ...keys); - live?.receive([roster(relay, id, members, ++clock)]); + clock++; + live?.receive([currentRoster()]); }, delayRoster: () => { applyAddition = false; @@ -2231,7 +2260,7 @@ it("shares the identity presentation with invitation rows without assigning a ch expect( within(row).queryByText("Agent", { exact: true }), ).not.toBeInTheDocument(); - expect(within(row).queryByText(/Managed by/)).not.toBeInTheDocument(); + expect(within(row).getByText("Managed by Carl (you)")).toBeVisible(); expect( row.querySelector('[data-avatar-shape="squircle"]'), ).toBeInTheDocument(); @@ -3236,7 +3265,7 @@ it("lets the Solo owner add an agent without sending a message", async () => { ).toEqual([ ["h", "11111111-1111-4111-8111-111111111111"], ["p", t.agent.pubkey], - ["role", "bot"], + ["role", "admin"], ]); await t.user.click(screen.getByRole("button", { name: "Close" })); await t.user.click(t.trigger); @@ -3467,12 +3496,21 @@ it.each([false, true])( }, ); -it.each(["private", "public"] as const)( - "adds the Solo owner's agent as Bot in a %s chat with a Guest default", - async (visibility) => { +it.each( + (["private", "public"] as const).flatMap((visibility) => + (["viewer", "other"] as const).map((agentOwner) => ({ + visibility, + agentOwner, + role: agentOwner === "viewer" ? "admin" : "bot", + })), + ), +)( + "adds an agent owned by $agentOwner as $role in a $visibility Solo chat with a Guest default", + async ({ visibility, agentOwner, role }) => { const t = await setup("solo", false, true, undefined, undefined, { visibility, joinRole: "guest", + agentOwner, }); await t.user.type(screen.getByRole("searchbox"), "Fixture agent"); await t.user.click( @@ -3480,7 +3518,7 @@ it.each(["private", "public"] as const)( ); await screen.findByText("Fixture agent added."); expect(t.publish).toHaveBeenCalledOnce(); - expect(t.publish.mock.calls[0]?.[0].tags).toContainEqual(["role", "bot"]); + expect(t.publish.mock.calls[0]?.[0].tags).toContainEqual(["role", role]); }, ); diff --git a/src/bundled/channels/ChannelsPage.solo.test.tsx b/src/bundled/channels/ChannelsPage.solo.test.tsx index 1cc4fb8ec2..50f0b252ae 100644 --- a/src/bundled/channels/ChannelsPage.solo.test.tsx +++ b/src/bundled/channels/ChannelsPage.solo.test.tsx @@ -52,6 +52,14 @@ vi.mock( ); composerDOMFixture(); +// Navigation fixtures deliberately never finish display-profile loading. +// Ownership authority is exercised in the Solo/admin session tests. +vi.mock("../../features/relay/solo-admins", async (original) => ({ + ...(await original()), + ownedSoloAgents: vi.fn< + typeof import("../../features/relay/solo-admins").ownedSoloAgents + >(async (_profiles, _viewer, keys) => new Set(keys)), +})); const owners: ReturnType[] = []; afterEach(() => { cleanup(); diff --git a/src/bundled/channels/OutboxStatus.test.tsx b/src/bundled/channels/OutboxStatus.test.tsx index 2644910a5f..a150dc8ccd 100644 --- a/src/bundled/channels/OutboxStatus.test.tsx +++ b/src/bundled/channels/OutboxStatus.test.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { soloAdminRecovery } from "../../features/relay/solo-admins"; import "@testing-library/jest-dom/vitest"; import { afterEach, assert, expect, it, vi } from "vitest"; import { @@ -7,6 +8,7 @@ import { render, screen, waitFor, + within, } from "@testing-library/react"; import { HELD_RETRY_REFUSED, @@ -61,6 +63,33 @@ function show(item: OutgoingEvent) { return { retry, add, acknowledge }; } +it("labels a setup with unconfirmed creation and withholds abandonment and removal", () => { + const viewer = keypair(); + const agent = keypair().pubkey; + const event = signed(viewer, { + kind: 9007, + content: "", + tags: [ + ["h", "chat"], + ["p", agent], + ], + }); + show({ + event, + delivery: "unknown", + recovery: soloAdminRecovery("chat", [agent], [agent]), + }); + expect( + screen.getByText("Opening agent admin setup · Unconfirmed"), + ).toBeVisible(); + expect( + screen.queryByRole("button", { name: "Abandon admin setup" }), + ).not.toBeInTheDocument(); + expect( + screen.queryByRole("button", { name: "Remove from outbox" }), + ).not.toBeInTheDocument(); +}); + it("does not offer generic retry for guarded invitations from either profile or composer", () => { const { retry } = show({ ...invitation, guarded: true }); expect( @@ -525,3 +554,171 @@ it.each(["agent", "team", "solo", "agent-share"] as const)( } }, ); + +it("abandons expired admin setup durably through Outbox and releases the chat gate", async () => { + const viewer = keypair(), + relay = keypair(), + agent = keypair(); + const channel = crypto.randomUUID(); + const creation = signed(viewer, { + kind: 9007, + created_at: Math.floor(Date.now() / 1000) - 16 * 60, + content: "", + tags: [ + ["h", channel], + ["p", agent.pubkey], + ], + }); + let records: readonly OutgoingEvent[] = [ + { + event: eventDto(creation), + signed: creation, + delivery: "accepted", + recovery: soloAdminRecovery(channel, [agent.pubkey], [agent.pubkey]), + }, + ]; + const events = new Map([[creation.id, creation]]); + const now = Date.now(); + const clock = vi + .spyOn(Date, "now") + .mockReturnValue((creation.created_at + 14 * 60) * 1000); + let failRemoval = false; + const storage = { + load: () => structuredClone(records), + save: (next: readonly OutgoingEvent[]) => { + if (failRemoval && !next.some((item) => item.recovery)) + throw new Error("Storage unavailable"); + records = structuredClone(next); + }, + }; + const adminSign = vi.fn(async (template) => + signed(viewer, template), + ); + const publish = vi.fn(async (event: RelayEvent) => { + events.set(event.id, event); + }); + const open = () => + createRelaySession( + { + viewer: viewer.pubkey, + relayAuthor: relay.pubkey, + channelIdentity: true, + media: () => undefined, + query: async (filters) => + [ + ...events.values(), + metadata(relay, channel, "Work", creation.created_at, [ + ["t", "stream"], + ["t", "buzz.solo"], + ["private"], + ["P", viewer.pubkey], + ]), + signed(relay, { + kind: 39002, + content: "", + tags: [ + ["d", channel], + ["p", viewer.pubkey, "", "owner"], + ["p", agent.pubkey, "", "member"], + ], + }), + ].filter((event) => + filters.some((filter) => matchesEvent(event, filter)), + ), + writer: { + kinds: [9, 9007], + sign: async (template) => signed(viewer, template), + publish, + }, + memberAdministration: { sign: adminSign, publish }, + }, + { outboxStorage: storage }, + ); + const first = open(); + let resumed: ReturnType | undefined; + try { + const session = first.session; + const outbox = session.outbox; + assert.exists(outbox); + await outbox.ready(); + session.channels.ensureList(); + await vi.waitFor(() => + expect(session.channels.list().status).toBe("ready"), + ); + const view = render( + , + ); + fireEvent.click(screen.getByText("Outbox · 1 items")); + const remove = () => + screen.getByRole("button", { name: "Abandon admin setup" }); + await screen.findByRole("button", { name: "Abandon admin setup" }); + expect(screen.getByText(/Opening agent admin setup · Sent/)).toBeVisible(); + expect( + screen.queryByRole("button", { name: "Remove from outbox" }), + ).not.toBeInTheDocument(); + fireEvent.click(remove()); + let confirmation = screen.getByRole("alertdialog", { + name: "Abandon admin setup?", + }); + expect( + within(confirmation).getByText(/Retry your opening message/), + ).toBeVisible(); + fireEvent.click( + within(confirmation).getByRole("button", { name: "Cancel" }), + ); + expect(outbox.snapshot().some((item) => item.recovery)).toBe(true); + clock.mockReturnValue(now); + await expect(session.channelWrites.prepareOpening(channel)).rejects.toThrow( + "expired", + ); + failRemoval = true; + fireEvent.click(remove()); + confirmation = screen.getByRole("alertdialog", { + name: "Abandon admin setup?", + }); + const confirm = within(confirmation).getByRole("button", { + name: "Abandon admin setup", + }); + fireEvent.click(confirm); + expect(await screen.findByRole("alert")).toHaveTextContent( + "Storage unavailable", + ); + expect(outbox.snapshot().some((item) => item.recovery)).toBe(true); + await expect(session.channelWrites.prepareOpening(channel)).rejects.toThrow( + "expired", + ); + failRemoval = false; + fireEvent.click(confirm); + await waitFor(() => expect(outbox.snapshot()).toHaveLength(0)); + expect(records.some((item) => item.recovery)).toBe(false); + expect(session.channels.get?.(channel)?.members).toContain(agent.pubkey); + view.unmount(); + const sent = session.messages.send( + channel, + "Continue with the current roles", + [agent.pubkey], + ); + await vi.waitFor(() => expect(events.has(sent)).toBe(true)); + first.dispose(); + resumed = open(); + await resumed.session.outbox?.ready(); + resumed.session.channels.ensureList(); + await vi.waitFor(() => + expect(resumed?.session.channels.list().status).toBe("ready"), + ); + const next = resumed.session.messages.send(channel, "After restart", [ + agent.pubkey, + ]); + await vi.waitFor(() => expect(events.has(next)).toBe(true)); + expect(adminSign).not.toHaveBeenCalled(); + expect(publish.mock.calls.every(([event]) => event.kind === 9)).toBe(true); + } finally { + first.dispose(); + resumed?.dispose(); + clock.mockRestore(); + } +}); diff --git a/src/bundled/channels/OutboxStatus.tsx b/src/bundled/channels/OutboxStatus.tsx index 8d70565478..7a74fe1ea5 100644 --- a/src/bundled/channels/OutboxStatus.tsx +++ b/src/bundled/channels/OutboxStatus.tsx @@ -1,12 +1,18 @@ import { Button } from "../../shared/design-system/ui/Button"; +import { AlertDialog } from "../../shared/design-system/ui/AlertDialog"; import { isWorkflowOperation } from "../../features/workflows/protocol"; -import { useState, useSyncExternalStore } from "react"; +import { useRef, useState, useSyncExternalStore } from "react"; import type { RelayProfiler } from "../../features/relay/profiling"; import { RelayTimings } from "./RelayTimings"; import { PRODUCT_FEEDBACK_KIND } from "../../features/relay/product-feedback"; -import { HELD_RETRY_REFUSED, type Outbox } from "../../features/relay/outbox"; +import { + HELD_RETRY_REFUSED, + type Outbox, + type OutboxRecovery, +} from "../../features/relay/outbox"; import type { RelaySession } from "../../features/relay/session"; import { isBatchAddition } from "../../features/channel-members/members"; +import { soloAdminSetup } from "../../features/relay/solo-admins"; /** A batch names everyone its Retry re-adds. */ function additionLabel(tags: readonly (readonly string[])[]) { @@ -30,12 +36,33 @@ export function OutboxStatus({ outbox.subscribe, outbox.snapshot, outbox.snapshot, - ).filter((item) => item.event.kind !== PRODUCT_FEEDBACK_KIND); + ) + .filter((item) => item.event.kind !== PRODUCT_FEEDBACK_KIND) + .map((item) => { + const setup = soloAdminSetup(item); + const abandonSetup = + item.delivery === "accepted" || item.delivery === "seen" + ? setup?.recovery + : undefined; + return { ...item, setup, abandonSetup }; + }); const [error, setError] = useState(); + const [abandon, setAbandon] = useState<{ + id: string; + recovery: OutboxRecovery; + }>(); + const [abandoning, setAbandoning] = useState(false); + const summary = useRef(null); + const abandonButton = useRef(null); + const cancel = useRef(null); + const closeAbandon = () => { + setError(undefined); + setAbandon(undefined); + }; return (
- Outbox · {operations.length} items + Outbox · {operations.length} items

Removing an item from the outbox does not delete a sent message.

    (
  • - {item.event.kind === 9000 - ? additionLabel(item.event.tags) - : item.event.content.slice(0, 100)}{" "} + {item.setup + ? "Opening agent admin setup" + : item.event.kind === 9000 + ? additionLabel(item.event.tags) + : item.event.content.slice(0, 100)}{" "} ·{" "} { { @@ -131,34 +160,87 @@ export function OutboxStatus({ (item.delivery === "failed" || item.delivery === "unknown") && ( {HELD_RETRY_REFUSED} )}{" "} - {item.delivery !== "sending" && ( + {(!item.setup || item.abandonSetup || item.delivery === "failed") && + item.delivery !== "sending" && ( + + )} +
  • + ))} +
+ {abandon && ( + + abandonButton.current?.isConnected + ? abandonButton.current + : summary.current + } + pending={abandoning} + onClose={closeAbandon} + actions={ + <> + - )} - - ))} - - {error &&

{error}

} + + } + > + {error &&

{error}

} +
+ )} + {!abandon && error &&

{error}

}
); diff --git a/src/features/channel-members/administration-protocol.ts b/src/features/channel-members/administration-protocol.ts index 98a173bfbd..93ffc0758f 100644 --- a/src/features/channel-members/administration-protocol.ts +++ b/src/features/channel-members/administration-protocol.ts @@ -247,6 +247,33 @@ export function memberAdministrationTemplate( }; } +/** The exact single-Admin addition saved by Outbox, including its retry ID. + * This uses the existing administration boundary; ordinary writes stay closed. */ +export function isAdminAddition(event: EventTemplate, viewer: string): boolean { + const tags = event?.tags; + if (!Array.isArray(tags)) return false; + const client = tags.at(-1); + if ( + event.kind !== 9000 || + tags.length !== 4 || + tags[2]?.[0] !== "role" || + tags[2]?.[1] !== "admin" || + client?.length !== 2 || + client[0] !== "client-id" + ) + return false; + try { + lifecycleChannelId(client[1] ?? ""); + validateMemberAdministrationTemplate( + { ...event, tags: tags.slice(0, -1) }, + viewer, + ); + return true; + } catch { + return false; + } +} + /** Purpose-bound broker admission; relay remains the authoritative ACL boundary. */ export function validateMemberAdministrationTemplate( event: EventTemplate, diff --git a/src/features/relay/channel-writes.ts b/src/features/relay/channel-writes.ts index 9207199fcd..dcfe01bfe8 100644 --- a/src/features/relay/channel-writes.ts +++ b/src/features/relay/channel-writes.ts @@ -2,12 +2,20 @@ import { canonicalDetailsName } from "./channel-details-protocol"; import { exactLifecycleTag } from "./channel-lifecycle-protocol"; import { channelIdentityUnsupported, channelLabelTags } from "./channel-labels"; import { SOLO_NAMED_LABEL, SOLO_LABEL } from "../solo/labels"; -import type { Outbox } from "./outbox"; +import type { Outbox, OutboxRecovery } from "./outbox"; +import type { RelayWriter } from "./transport"; +import { + promoteSoloAdmins, + soloAdminKey, + soloAdminRecovery, + soloAgentOwnership, +} from "./solo-admins"; import { isBatchAddition } from "../channel-members/members"; import { withdraw } from "./withdraw"; import type { ChannelQueries, ChannelSummary } from "./contracts"; import type { RelayReader } from "./reader"; import type { EventData } from "./events"; +import type { ProfileQueries } from "./profile-directory"; export const DEFAULT_TEMPORARY_CHANNEL_TTL_SECONDS = 7 * 24 * 60 * 60; @@ -41,11 +49,14 @@ export function createChannelWrites( agents?: { selectable: () => readonly string[]; archived: (pubkey: string) => boolean; + profiles?: Pick; + viewer?: string; }, relayAuthor?: string, /** Signed roster discovery, including channels this viewer cannot open. */ discovery: RelayReader = reader, channelIdentity = false, + adminWriter?: RelayWriter, ) { const available = !!outbox?.supports(9007); function writer(addition = false) { @@ -455,8 +466,6 @@ export function createChannelWrites( if (active?.() === false) throw new DOMException("Channel addition cancelled", "AbortError"); const original = await refreshMembership(id); - // Solo agents must be able to reply even with a saved Guest admission default. - const roleTags = original.channelType === "solo" ? [["role", "bot"]] : []; if (active?.() === false) throw new DOMException("Channel addition cancelled", "AbortError"); const unique = [...new Set(keys)].filter( @@ -503,14 +512,35 @@ export function createChannelWrites( item.event.tags.some( ([name, value]) => name === "p" && value === key, ) && - roles.length === roleTags.length && - roles.every((tag) => tag.length === 2 && tag[1] === "bot") + roles.length === (original.channelType === "solo" ? 1 : 0) && + // Recovery finishes the saved grant even if the viewer's role changed. + roles.every( + (tag) => + tag.length === 2 && (tag[1] === "bot" || tag[1] === "admin"), + ) ); }); if (previous && Date.now() / 1000 - previous.event.created_at >= 15 * 60) throw new Error( `This agent-add request expired. Open Outbox, remove the “Add agent ${key.slice(0, 12)}” item, then add the agent again. Check channel membership first if the request was unconfirmed.`, ); + let owned: (() => boolean) | undefined; + if ( + original.channelType === "solo" && + !previous && + original.viewerRole === "owner" + ) { + owned = await freshOwnership(key); + } + const roleTags = + original.channelType === "solo" + ? [ + [ + "role", + original.viewerRole === "owner" && owned?.() ? "admin" : "bot", + ], + ] + : []; const operation = previous?.event.id ?? writer(!!active).send( @@ -531,8 +561,73 @@ export function createChannelWrites( if (original?.channelType === "solo") await refresh(id, { members: unique }); } + /** Cached discovery is not evidence for a new automatic Admin grant. */ + async function freshOwnership(key: string) { + const events = await discovery.read( + [{ kinds: [0], authors: [key], limit: 1, consistency: "strong" }], + { signal, fresh: true, priority: "foreground" }, + ); + const owned = await soloAgentOwnership( + agents?.profiles, + agents?.viewer, + key, + ); + return () => + owned() && + events.some( + (event) => + event.kind === 0 && + event.pubkey === key && + event.id === agents?.profiles?.event?.(key)?.id, + ); + } /** Solo chats this device is starting, until they can take events. */ const starts = new Map>(); + const adminSetups = new Map>(); + /** Publication retries also call this after reload. The create's local + * receipt retains the original recipients until every grant is recorded. */ + function prepareOpening(id: string): Promise | undefined { + const pending = (receipts ?? outbox) + ?.snapshot() + .find((item) => item.recovery?.key === soloAdminKey(id)); + if (!pending) return; + const active = adminSetups.get(id); + if (active) return active; + const work = (async () => { + const source = writer(); + const withRecovery = source.withRecovery; + const finishRecovery = source.finishRecovery; + if (!adminWriter || !relayAuthor || !withRecovery || !finishRecovery) + throw new Error("This connection cannot set up chat admins."); + await created(pending.event.id); + const saved = await source.recovery(soloAdminKey(id)); + if (!saved?.recovery) + throw new Error( + "Chat admin setup ended in another window. Retry this message to continue.", + ); + const recovery = saved.recovery; + await promoteSoloAdmins( + saved, + { + ...adminWriter, + publish: (event, signal, checkOwnership) => + withRecovery(saved.event.id, recovery, () => { + checkOwnership(); + return adminWriter.publish(event, signal); + }), + }, + discovery, + relayAuthor, + signal, + freshOwnership, + ); + signal.throwIfAborted(); + await finishRecovery(saved.event.id, recovery); + })(); + adminSetups.set(id, work); + void work.catch(() => {}).finally(() => adminSetups.delete(id)); + return work; + } /** The Canvas of each chat this device is starting ("" for none), until * its save lands; see `startingCanvas`. */ const canvases = new Map(); @@ -594,6 +689,7 @@ export function createChannelWrites( refreshMembership, memberChannels, listsMember, + prepareOpening, createChannel( id: string, title: string, @@ -651,6 +747,7 @@ export function createChannelWrites( members: readonly string[] = [], active?: () => boolean, labels: readonly string[] = [], + recovery?: OutboxRecovery, ) { writer(); identifier(id); @@ -683,7 +780,7 @@ export function createChannelWrites( ...[...new Set(members)].map((key) => ["p", key]), ], }, - undefined, + recovery, active, ); }, @@ -701,8 +798,15 @@ export function createChannelWrites( /** The chat's Canvas, and the work that saves it once the chat * exists; nothing waits for it, and a failure leaves a working chat. */ setup?: { canvas: string; apply(): Promise }, - options?: { labels?: readonly string[]; active?: () => boolean }, + options?: { + labels?: readonly string[]; + active?: () => boolean; + admins?: readonly string[]; + }, ) { + const recovery = soloAdminRecovery(id, members, options?.admins); + if (recovery && (!adminWriter || !relayAuthor)) + throw new Error("This connection cannot set up chat admins."); const create = api.create( id, title, @@ -711,6 +815,7 @@ export function createChannelWrites( members, options?.active, options?.labels, + recovery, ); channels.start?.({ id, diff --git a/src/features/relay/outbox-recovery.test.ts b/src/features/relay/outbox-recovery.test.ts index 07a5f720ea..9f47424b77 100644 --- a/src/features/relay/outbox-recovery.test.ts +++ b/src/features/relay/outbox-recovery.test.ts @@ -803,3 +803,148 @@ it("does not expose replacement intent to an earlier queued save", async () => { ).toBe(true); } }); + +it("fences a fresh local recovery against another owner's durable dismissal", async () => { + const store = memory(); + const a = setup(store); + await a.outbox.ready(); + const id = a.outbox.send({ ...input, kind: 9007 }, recovery); + await vi.waitFor(() => expect(store.load()[0]?.delivery).toBe("accepted")); + const b = setup(store); + await b.outbox.ready(); + await b.outbox.dismiss(id, recovery); + const publish = vi.fn(async () => {}); + assert.exists(a.outbox.withRecovery); + await expect(a.outbox.withRecovery(id, recovery, publish)).rejects.toThrow( + "removed or changed", + ); + expect(publish).not.toHaveBeenCalled(); + assert.exists(a.outbox.finishRecovery); + await expect(a.outbox.finishRecovery(id, recovery)).rejects.toThrow( + "removed or changed", + ); + expect(await a.outbox.recovery(recovery.key)).toBeUndefined(); + expect(a.outbox.snapshot()).toEqual([]); + a.outbox.send({ ...input, content: "New explicit Send" }); + await vi.waitFor(() => expect(a.publish).toHaveBeenCalledTimes(2)); + expect(store.load().some((item) => item.event.id === id)).toBe(false); +}); + +it("holds shared recovery ownership through publication before dismissal can commit", async () => { + const store = memory(); + const event = signed(viewer, { ...input, kind: 9007 }); + store.save([{ event, signed: event, delivery: "accepted", recovery }]); + let tail = Promise.resolve(); + let requests = 0; + const queued = gate(); + const shared: OutboxStorage = { + ...store, + async lock(id, run) { + expect(id).toBe(event.id); + const before = tail; + const next = gate(); + tail = next.promise; + if (++requests === 2) queued.release(); + await before; + try { + return await run(); + } finally { + next.release(); + } + }, + }; + const a = setup(shared), + b = setup(shared); + await Promise.all([a.outbox.ready(), b.outbox.ready()]); + const entered = gate(), + release = gate(); + const order: string[] = []; + assert.exists(a.outbox.withRecovery); + try { + const publication = a.outbox.withRecovery(event.id, recovery, async () => { + entered.release(); + await release.promise; + order.push("published"); + }); + await entered.promise; + const dismissal = b.outbox.dismiss(event.id, recovery).then(() => { + order.push("dismissed"); + }); + await queued.promise; + expect(order).toEqual([]); + expect(store.load()).toHaveLength(1); + release.release(); + await Promise.all([publication, dismissal]); + expect(order).toEqual(["published", "dismissed"]); + expect(store.load()).toEqual([]); + await expect(a.outbox.dismiss(event.id, recovery)).resolves.toBeUndefined(); + expect(a.outbox.snapshot()).toEqual([]); + } finally { + release.release(); + } +}); + +it.each(["key", "value"] as const)( + "refuses dismissal, publication and completion after shared recovery %s changes", + async (field) => { + const store = memory(); + const event = signed(viewer, { ...input, kind: 9007 }); + store.save([{ event, signed: event, delivery: "accepted", recovery }]); + const h = setup(store); + await h.outbox.ready(); + const changed = { ...recovery, [field]: "different owner" }; + store.save([ + { event, signed: event, delivery: "accepted", recovery: changed }, + ]); + const publish = vi.fn(async () => {}); + assert.exists(h.outbox.withRecovery); + assert.exists(h.outbox.finishRecovery); + await expect(h.outbox.dismiss(event.id, recovery)).rejects.toThrow( + "removed or changed", + ); + await expect( + h.outbox.withRecovery(event.id, recovery, publish), + ).rejects.toThrow("removed or changed"); + await expect(h.outbox.finishRecovery(event.id, recovery)).rejects.toThrow( + "removed or changed", + ); + expect(publish).not.toHaveBeenCalled(); + expect(store.load()[0]?.recovery).toEqual(changed); + }, +); + +it("does not release dependent work by joining a pending abandonment", async () => { + const store = memory(); + const event = signed(viewer, { ...input, kind: 9007 }); + store.save([{ event, signed: event, delivery: "seen", recovery }]); + const deleting = gate(), + release = gate(); + const h = setup({ + ...store, + async save(records) { + if (!records.length) { + deleting.release(); + await release.promise; + } + store.save(records); + }, + }); + await h.outbox.ready(); + assert.exists(h.outbox.finishRecovery); + const deliver = vi.fn(); + try { + const abandonment = h.outbox.dismiss(event.id, recovery); + await deleting.promise; + const completion = h.outbox + .finishRecovery(event.id, recovery) + .then(deliver); + const refused = expect(completion).rejects.toThrow("removed or changed"); + release.release(); + await abandonment; + await refused; + expect(deliver).not.toHaveBeenCalled(); + expect(store.load()).toEqual([]); + } finally { + release.release(); + } +}); diff --git a/src/features/relay/outbox-storage.ts b/src/features/relay/outbox-storage.ts index fc1cb502a3..f02f57932d 100644 --- a/src/features/relay/outbox-storage.ts +++ b/src/features/relay/outbox-storage.ts @@ -52,6 +52,7 @@ export async function purgeOutboxStorage(scope: string) { export function browserOutboxStorage(scope: string): OutboxStorage { let database: Promise | undefined; let persisted = new Map(); + let legacyIds = new Set(); let ownershipRevision = 0; const forgotten = new Map(); const open = () => (database ??= openDatabase()); @@ -63,6 +64,7 @@ export function browserOutboxStorage(scope: string): OutboxStorage { forget(id) { forgotten.set(id, ++ownershipRevision); persisted.delete(id); + legacyIds.delete(id); }, async load(options) { const db = await open(); @@ -99,10 +101,14 @@ export function browserOutboxStorage(scope: string): OutboxStorage { }, ); // A first save migrates legacy records into the per-event store. - if (!options?.readOnly) + if (!options?.readOnly) { persisted = migrated ? new Map(records.map((item) => [item.event.id, item])) : new Map(); + legacyIds = new Set( + migrated ? [] : records.map((item) => item.event.id), + ); + } return records; }, async save(operations, options) { @@ -114,6 +120,8 @@ export function browserOutboxStorage(scope: string): OutboxStorage { durability: "strict", }); const events = tx.objectStore("events"); + const partitions = tx.objectStore("partitions"); + const migration = legacyIds.size ? partitions.get(scope) : undefined; for (const [id, operation] of next) { const old = persisted.get(id); if ( @@ -129,17 +137,33 @@ export function browserOutboxStorage(scope: string): OutboxStorage { old.guarded === operation.guarded ) continue; - events.put({ scope, id, operation }); + if (id === options?.force || (!old && !legacyIds.has(id))) { + events.put({ scope, id, operation }); + } else { + // Another window may have removed this row. Check in the same + // transaction as the update, including while migrating legacy rows. + const key = events.getKey([scope, id]); + key.onsuccess = () => { + if ( + key.result !== undefined || + (!old && migration?.result !== true) + ) + events.put({ scope, id, operation }); + }; + } } for (const id of persisted.keys()) if (!next.has(id)) events.delete([scope, id]); - tx.objectStore("partitions").put(true, scope); + for (const id of legacyIds) + if (!next.has(id)) events.delete([scope, id]); + partitions.put(true, scope); tx.oncomplete = () => { // A read can relinquish an ID while this transaction is pending. // Do not let completion reclaim deletion ownership of that ID. persisted = new Map( [...next].filter(([id]) => (forgotten.get(id) ?? 0) <= revision), ); + legacyIds.clear(); resolve(); }; tx.onabort = () => diff --git a/src/features/relay/outbox.ts b/src/features/relay/outbox.ts index d7c8bd6f6e..5a9784980d 100644 --- a/src/features/relay/outbox.ts +++ b/src/features/relay/outbox.ts @@ -70,6 +70,16 @@ export interface Outbox { ready(): Promise; /** Fresh shared-journal ownership without importing another window's operations. */ recovery(key: string): Promise; + /** Verify the exact durable receipt and retain its dismissal lock through + * dependent publication. Signing must happen before acquiring this lock. + * Older Outboxes may omit this; dependent publication must fail closed. */ + withRecovery?( + id: string, + recovery: OutboxRecovery, + run: () => Promise, + ): Promise; + /** Complete under exact ownership, without joining an independent dismissal. */ + finishRecovery?(id: string, recovery: OutboxRecovery): Promise; send( input: OutboxInput, recovery?: OutboxRecovery, @@ -338,6 +348,17 @@ export function createOutbox( let storageError: string | undefined; let hydrated = false; let durable = Promise.resolve(); + let ownership = Promise.resolve(); + function locked(id: string, run: () => Promise): Promise { + if (storage.lock) return storage.lock(id, run); + // Memory/single-window stores still serialize publication with dismissal. + const work = ownership.then(run, run); + ownership = work.then( + () => {}, + () => {}, + ); + return work; + } const notify = () => { visible = Object.freeze([ ...completed.entries().map(([, item]) => item), @@ -911,6 +932,42 @@ export function createOutbox( else schedule(event.id, intent); return { id: event.id, persisted: intent }; } + async function withRecovery( + id: string, + recovery: OutboxRecovery, + run: () => Promise, + dismissAbsent = false, + ): Promise { + await outbox.ready(); + await durable.catch(() => {}); + await locked(id, async () => { + const shared = (await storage.load({ readOnly: true })).find( + (item) => item.event.id === id, + ); + if (closed) throw abortError(); + if ( + shared?.recovery?.key !== recovery.key || + shared.recovery.value !== recovery.value + ) { + // This includes fresh local receipts: they cannot reclaim a durable + // dismissal through a later unrelated journal save. + storage.forget?.(id); + restoredReceipts.delete(id); + completed.delete(id); + snapshot = Object.freeze( + snapshot.filter((item) => item.event.id !== id), + ); + notify(); + // Only dismissal is idempotent. Missing ownership must still fence + // dependent publication and successful recovery completion. + if (!shared && dismissAbsent) return; + throw new Error( + "This operation was removed or changed in another window. Retry the message to continue.", + ); + } + await run(); + }); + } const outbox: Outbox = Object.freeze({ snapshot: () => finalSnapshot ?? snapshot, subscribe: (listener: () => void) => subscribe(listeners, listener), @@ -943,6 +1000,12 @@ export function createOutbox( } return shared; }, + withRecovery, + async finishRecovery(id: string, recovery: OutboxRecovery) { + await withRecovery(id, recovery, () => persist(id, "dismiss")); + admissionGates.delete(id); + sendHolds.delete(id); + }, async recover(id: string, recovery: OutboxRecovery, consume?: () => void) { const adopt = async () => { await outbox.ready(); @@ -1159,7 +1222,9 @@ export function createOutbox( ), ); const remove = () => persist(id, "dismiss"); - const work = (storage.lock ? storage.lock(id, remove) : remove()) + const work = ( + owner ? withRecovery(id, owner, remove, true) : locked(id, remove) + ) .then(() => { admissionGates.delete(id); sendHolds.delete(id); diff --git a/src/features/relay/session-agent-admission.test.ts b/src/features/relay/session-agent-admission.test.ts index 416919e95f..97185feeb9 100644 --- a/src/features/relay/session-agent-admission.test.ts +++ b/src/features/relay/session-agent-admission.test.ts @@ -1,12 +1,19 @@ import { expect, it, vi } from "vitest"; import { createRelaySession } from "./session"; import { PublishRejected } from "./outbox"; -import { keypair, roster, signed } from "./testing"; +import { keypair, ownedProfile, roster, signed } from "./testing"; import { matchesEvent } from "./projection"; -import type { RelayEvent } from "./events"; +import { eventDto, type RelayEvent } from "./events"; import { SOLO_LABEL } from "../solo/labels"; -function setup(visibility: "private" | "public" = "private") { +type ViewerRole = "owner" | "admin" | "member"; + +function setup( + visibility: "private" | "public" = "private", + initialRole: ViewerRole = "member", + ownership: "viewer" | "other" | "missing" = "viewer", +) { + let viewerRole = initialRole; const viewer = keypair(), relay = keypair(), agent = keypair(); @@ -18,6 +25,7 @@ function setup(visibility: "private" | "public" = "private") { let denied = false; let foreignRoster = false; let libraryFailure = false; + let profileResponse: "missing" | "unavailable" | undefined; let afterPublish = () => {}; let omitMembership = false; const archived: string[] = []; @@ -36,20 +44,48 @@ function setup(visibility: "private" | "public" = "private") { } return signed(viewer, template); }); - const secondAgent = keypair().pubkey; + const second = keypair(), + other = keypair(); + const secondAgent = second.pubkey; + let agentProfile = + ownership === "missing" + ? Promise.resolve( + signed(agent, { + kind: 0, + tags: [], + content: JSON.stringify({ owner: viewer.pubkey }), + }), + ) + : ownedProfile(agent, ownership === "viewer" ? viewer : other); + const secondProfile = ownedProfile(second, other); const meta = (id: string, type: string, extra: string[][] = []) => signed(relay, { kind: 39000, content: "", tags: [["d", id], ["t", type], ["name", id], ...extra], }); + const membership = (id: string, keys: string[]) => + signed(relay, { + kind: 39002, + created_at: clock, + content: "", + tags: [ + ["d", id], + ...keys.map((key) => + key === viewer.pubkey ? ["p", key, "", viewerRole] : ["p", key], + ), + ], + }); const publish = vi.fn(async (_event: RelayEvent) => { const target = _event.tags.find(([name]) => name === "h")?.[1]; if (denied) throw new PublishRejected("Only channel admins can add agents"); + const added = _event.tags.flatMap(([tag, key]) => + tag === "p" && key ? [key] : [], + ); if (!omitMembership && target === parent) - members = [viewer.pubkey, agent.pubkey]; + members = [...new Set([...members, ...added])]; if (!omitMembership && target === child) - childMembers = [viewer.pubkey, agent.pubkey]; + childMembers = [...new Set([...childMembers, ...added])]; clock++; afterPublish(); }); @@ -75,6 +111,11 @@ function setup(visibility: "private" | "public" = "private") { publish, }, query: async (filters) => { + if ( + profileResponse === "unavailable" && + filters.some((filter) => filter.kinds?.includes(0)) + ) + throw new Error("Profile read unavailable"); if ( holdRoster && filters.some( @@ -95,6 +136,9 @@ function setup(visibility: "private" | "public" = "private") { roster(agent, child, [viewer.pubkey, agent.pubkey], clock + 1), ]; const events = [ + ...(profileResponse === "missing" + ? [] + : [eventDto(await agentProfile), eventDto(await secondProfile)]), signed(relay, { kind: 13535, created_at: clock, @@ -107,8 +151,8 @@ function setup(visibility: "private" | "public" = "private") { ["t", SOLO_LABEL], ["join_role", "guest"], ]), - roster(relay, parent, members, clock), - roster(relay, child, childMembers, clock), + membership(parent, members), + membership(child, childMembers), ]; return events.filter((event) => filters.some((filter) => matchesEvent(event, filter)), @@ -123,6 +167,27 @@ function setup(visibility: "private" | "public" = "private") { child, agent: agent.pubkey, secondAgent, + async transferAgent(receive = true) { + const profile = await ownedProfile(agent, other); + agentProfile = Promise.resolve( + signed(agent, { + kind: 0, + tags: profile.tags, + content: profile.content, + created_at: clock + 10, + }), + ); + if (!receive) return; + await owner.session.read( + [{ kinds: [0], authors: [agent.pubkey], limit: 1 }], + { fresh: true }, + ); + expect( + owner.session.profiles + .event?.(agent.pubkey) + ?.tags.find(([tag]) => tag === "auth")?.[1], + ).toBe(other.pubkey); + }, archive: (key: string) => { clock++; archived.push(key); @@ -133,6 +198,9 @@ function setup(visibility: "private" | "public" = "private") { failLibraryRefresh: () => { libraryFailure = true; }, + profileResponse: (response: "missing" | "unavailable") => { + profileResponse = response; + }, afterPublish: (callback: () => void) => { afterPublish = callback; }, @@ -161,6 +229,10 @@ function setup(visibility: "private" | "public" = "private") { return signingRequested; }, releaseSigning: () => releaseSigning?.(), + setViewerRole: (role: ViewerRole) => { + viewerRole = role; + clock++; + }, setDenied: (value: boolean) => { denied = value; }, @@ -178,10 +250,104 @@ function setup(visibility: "private" | "public" = "private") { }; } -it.each(["private", "public"] as const)( - "adds an outside agent as Bot with a Guest default in a %s Solo chat", - async (visibility) => { - const test = setup(visibility); +it.each(["other", "missing"] as const)( + "adds a selectable agent as Bot when its signed ownership is %s", + async (ownership) => { + const test = setup("private", "owner", ownership); + try { + await test.ready(); + await test.owner.session.channelWrites.addAgents(test.child, [ + test.agent, + ]); + expect(test.publish.mock.calls[0]?.[0].tags).toContainEqual([ + "role", + "bot", + ]); + } finally { + test.owner.dispose(); + } + }, +); + +it("refreshes cached ownership before choosing a new Solo agent's role", async () => { + const test = setup("private", "owner"); + try { + await test.ready(); + await test.owner.session.profiles.ensure([test.agent]); + const cached = test.owner.session.profiles.event?.(test.agent); + expect(cached).toBeDefined(); + await test.transferAgent(false); + expect(test.owner.session.profiles.event?.(test.agent)).toBe(cached); + await test.owner.session.channelWrites.addAgents(test.child, [test.agent]); + expect(test.publish).toHaveBeenCalledOnce(); + expect(test.publish.mock.calls[0]?.[0].tags).toContainEqual([ + "role", + "bot", + ]); + expect(test.owner.session.profiles.event?.(test.agent)).not.toBe(cached); + } finally { + test.owner.dispose(); + } +}); + +it.each(["missing", "unavailable"] as const)( + "does not use cached ownership for a later addition when the profile read is %s", + async (response) => { + const test = setup("private", "owner"); + try { + await test.ready(); + await test.owner.session.profiles.ensure([test.agent]); + test.profileResponse(response); + const adding = test.owner.session.channelWrites.addAgents(test.child, [ + test.agent, + ]); + if (response === "unavailable") { + await expect(adding).rejects.toThrow("Profile read unavailable"); + expect(test.publish).not.toHaveBeenCalled(); + } else { + await adding; + expect(test.publish).toHaveBeenCalledOnce(); + expect(test.publish.mock.calls[0]?.[0].tags).toContainEqual([ + "role", + "bot", + ]); + } + } finally { + test.owner.dispose(); + } + }, +); + +it("chooses each new agent's role separately in a mixed-ownership Solo addition", async () => { + const test = setup("private", "owner"); + try { + await test.ready(); + await test.owner.session.channelWrites.addAgents(test.child, [ + test.agent, + test.secondAgent, + ]); + expect( + test.publish.mock.calls.map(([event]) => + event.tags.filter(([tag]) => tag === "role"), + ), + ).toEqual([[["role", "admin"]], [["role", "bot"]]]); + } finally { + test.owner.dispose(); + } +}); + +it.each( + (["private", "public"] as const).flatMap((visibility) => + (["owner", "admin", "member"] as const).map((viewerRole) => ({ + visibility, + viewerRole, + addedRole: viewerRole === "owner" ? "admin" : "bot", + })), + ), +)( + "adds an agent as $addedRole for a $viewerRole in a $visibility Solo chat with a Guest default", + async ({ visibility, viewerRole, addedRole }) => { + const test = setup(visibility, viewerRole); try { await test.ready(); await test.owner.session.channelWrites.addAgents(test.child, [ @@ -194,7 +360,7 @@ it.each(["private", "public"] as const)( tags: expect.arrayContaining([ ["h", test.child], ["p", test.agent], - ["role", "bot"], + ["role", addedRole], ]), }); expect( @@ -276,24 +442,63 @@ it("reports channel-specific uncertainty when an accepted addition lacks roster } }); -it("keeps channel permission failures and retries the same saved invitation", async () => { - const test = setup(); +it.each([ + { initialRole: "member", retryRole: "member", addedRole: "bot" }, + { initialRole: "member", retryRole: "owner", addedRole: "bot" }, + { initialRole: "owner", retryRole: "member", addedRole: "admin" }, + { + initialRole: "owner", + retryRole: "owner", + addedRole: "admin", + transferred: true, + }, +] as const)( + "keeps the saved $addedRole invitation when $initialRole retries as $retryRole", + async ({ initialRole, retryRole, addedRole, ...options }) => { + const test = setup("private", initialRole); + try { + await test.ready(); + test.setDenied(true); + await expect( + test.owner.session.channelWrites.addAgents(test.child, [test.agent]), + ).rejects.toThrow(/Only channel admins/); + expect( + test.owner.session.channels + .list() + .channels.find((item) => item.id === test.child)?.members, + ).not.toContain(test.agent); + const first = test.publish.mock.calls[0]?.[0]; + expect(first?.tags).toContainEqual(["role", addedRole]); + if ("transferred" in options) { + await test.transferAgent(); + test.profileResponse("unavailable"); + } + test.setViewerRole(retryRole); + test.setDenied(false); + await test.owner.session.channelWrites.addAgents(test.child, [ + test.agent, + ]); + expect(test.publish.mock.calls[1]?.[0]).toEqual(first); + expect(test.publish).toHaveBeenCalledTimes(2); + } finally { + test.owner.dispose(); + } + }, +); +it("preserves ordinary channel admission defaults for an owner", async () => { + const test = setup("private", "owner"); try { await test.ready(); - test.setDenied(true); - await expect( - test.owner.session.channelWrites.addAgents(test.child, [test.agent]), - ).rejects.toThrow(/Only channel admins/); - expect( - test.owner.session.channels - .list() - .channels.find((item) => item.id === test.child)?.members, - ).not.toContain(test.agent); - const first = test.publish.mock.calls[0]?.[0].id; - test.setDenied(false); - await test.owner.session.channelWrites.addAgents(test.child, [test.agent]); - expect(test.publish.mock.calls[1]?.[0].id).toBe(first); - expect(test.publish).toHaveBeenCalledTimes(2); + await test.owner.session.channelWrites.addAgents(test.parent, [test.agent]); + expect(test.publish).toHaveBeenCalledOnce(); + const tags = test.publish.mock.calls[0]?.[0].tags ?? []; + expect(tags).toEqual( + expect.arrayContaining([ + ["h", test.parent], + ["p", test.agent], + ]), + ); + expect(tags.filter(([name]) => name === "role")).toEqual([]); } finally { test.owner.dispose(); } diff --git a/src/features/relay/session.ts b/src/features/relay/session.ts index 51578d4bc0..c02278a50c 100644 --- a/src/features/relay/session.ts +++ b/src/features/relay/session.ts @@ -368,6 +368,10 @@ export function createRelaySession( if (event.kind === 9007 || event.kind === 9000) return; const id = event.tags.find(([name]) => name === "h")?.[1]; if (!id) return; + // Opening agents receive admin before either local wake or publication. + const opening = + event.kind === 9 ? channelWrites.prepareOpening(id) : undefined; + if (opening) return opening; const ready = channelWrites.starting(id); if (ready && event.kind === 9) hearStarting(event, id); return ready; @@ -1814,6 +1818,8 @@ export function createRelaySession( { selectable: () => agentChoices.snapshot().selectable.map((agent) => agent.pubkey), + profiles: profiles.queries, + viewer: transport?.viewer ?? "", archived: (pubkey) => agentUnavailable( { @@ -1827,6 +1833,7 @@ export function createRelaySession( transport?.relayAuthor, { read: (filters, settings) => readVerified(filters, settings, false) }, transport?.channelIdentity === true, + transport?.memberAdministration, ); startingChannel = (id) => channelWrites.starting(id); // Roster authority invalidates in-flight reads, including account-owned diff --git a/src/features/relay/solo-admins.integration.test.ts b/src/features/relay/solo-admins.integration.test.ts new file mode 100644 index 0000000000..9671b0cb1d --- /dev/null +++ b/src/features/relay/solo-admins.integration.test.ts @@ -0,0 +1,445 @@ +import { assert, afterEach, expect, it, vi } from "vitest"; +import { createRelaySession } from "./session"; +import { keypair, metadata, ownedProfile, signed } from "./testing"; +import { matchesEvent } from "./projection"; +import { SOLO_LABEL } from "../solo/labels"; +import { soloAdminKey } from "./solo-admins"; +import { validateMemberAdministrationTemplate } from "../channel-members/administration-protocol"; +import { PublishRejected, type OutgoingEvent } from "./outbox"; +import { eventDto, type ReadFilter, type RelayEvent } from "./events"; +import type { EventTemplate } from "nostr-tools"; + +const sessions: ReturnType[] = []; +afterEach(() => { + for (const session of sessions.splice(0)) session.dispose(); +}); + +function setup() { + const viewer = keypair(), + relay = keypair(); + const channel = crypto.randomUUID(); + const agentKeys = [keypair(), keypair()] as const; + const agents: [string, string] = [agentKeys[0].pubkey, agentKeys[1].pubkey]; + const workspaceKey = keypair(); + const workspaceAgent = workspaceKey.pubkey; + const profiles = Promise.all( + [...agentKeys, workspaceKey].map((key) => ownedProfile(key, viewer)), + ); + let beforeLock = async () => {}; + const profileOverrides = new Map(); + let omitProfiles = false; + let failProfiles = false; + let journal: readonly OutgoingEvent[] = []; + const events = new Map(); + const roles = new Map(); + const genericPublish = vi.fn(async (event: RelayEvent) => { + if (event.kind === 9000) + throw new Error("Elevated commands require their dedicated host route"); + events.set(event.id, event); + if (event.kind === 9007) { + roles.set(viewer.pubkey, "owner"); + for (const [tag, key] of event.tags) + if (tag === "p" && key) roles.set(key, "member"); + } + }); + const adminPublish = vi.fn(async (event: RelayEvent) => { + validateMemberAdministrationTemplate(event, viewer.pubkey); + if (events.has(event.id)) return; + events.set(event.id, event); + const agent = event.tags.find(([tag]) => tag === "p")?.[1]; + assert.exists(agent); + roles.set(agent, "admin"); + }); + const transport = { + viewer: viewer.pubkey, + relayAuthor: relay.pubkey, + channelIdentity: true as const, + media: () => undefined, + query: async (filters: readonly ReadFilter[]) => { + if (failProfiles && filters.some((filter) => filter.kinds?.includes(0))) + throw new Error("Profile read unavailable"); + const roster = signed(relay, { + kind: 39002, + content: "", + tags: [ + ["d", channel], + ...[...roles].map(([key, role]) => ["p", key, "", role]), + ], + }); + return [ + ...(omitProfiles ? [] : await profiles).map((profile) => + eventDto(profileOverrides.get(profile.pubkey) ?? profile), + ), + ...events.values(), + ...(roles.size + ? [ + roster, + metadata(relay, channel, "Work", Math.floor(Date.now() / 1000), [ + ["t", "stream"], + ["private"], + ["t", SOLO_LABEL], + ["P", viewer.pubkey], + ]), + ] + : []), + ].filter((event) => + filters.some((filter) => matchesEvent(event, filter)), + ); + }, + writer: { + kinds: [9, 9000, 9007], + sign: async (template: EventTemplate) => signed(viewer, template), + publish: genericPublish, + }, + memberAdministration: { + sign: async (template: EventTemplate) => { + validateMemberAdministrationTemplate(template, viewer.pubkey); + return signed(viewer, template); + }, + publish: adminPublish, + }, + }; + const open = async () => { + const owner = createRelaySession(transport, { + outboxStorage: { + async lock(_id, run) { + await beforeLock(); + return run(); + }, + load: () => structuredClone(journal), + save: (next) => { + journal = structuredClone(next); + }, + }, + }); + sessions.push(owner); + await owner.session.outbox?.ready(); + owner.session.channels.ensureList(); + await vi.waitFor(() => + expect(owner.session.channels.list().status).toBe("ready"), + ); + return owner; + }; + const start = (owner: Awaited>) => { + const creation = owner.session.channelWrites.start( + channel, + "Work", + [...agents, workspaceAgent], + undefined, + false, + undefined, + { admins: [...agents, workspaceAgent] }, + ); + void creation.ready.catch(() => {}); + const message = owner.session.messages.send( + channel, + "Work on this", + agents, + ); + return { creation, message }; + }; + return { + channel, + viewer, + async transferAgent( + owner: Awaited>, + index: number, + receive = true, + ) { + const agent = agentKeys[index]; + assert.exists(agent); + const profile = await ownedProfile(agent, keypair()); + const previous = (await profiles).find( + (event) => event.pubkey === agent.pubkey, + ); + assert.exists(previous); + const changed = signed(agent, { + ...profile, + created_at: previous.created_at + 1, + }); + profileOverrides.set(agent.pubkey, changed); + if (!receive) return; + await owner.session.read( + [{ kinds: [0], authors: [agent.pubkey], limit: 1 }], + { fresh: true }, + ); + expect(owner.session.profiles.event?.(agent.pubkey)?.id).toBe(changed.id); + }, + omitProfiles: () => { + omitProfiles = true; + }, + failProfiles: () => { + failProfiles = true; + }, + beforeLock: (run: () => Promise) => { + beforeLock = run; + }, + agents, + workspaceAgent, + roles, + events, + genericPublish, + adminPublish, + transport, + open, + start, + }; +} + +it("confirms a lost grant ACK and holds the opening message and local wake until every admin is ready", async () => { + const h = setup(); + const owner = await h.open(); + const heard = vi.fn(); + owner.session.subscribeLive(heard, { replay: true }); + let release = () => {}; + const held = new Promise((resolve) => { + release = resolve; + }); + const publish = h.adminPublish.getMockImplementation(); + assert.exists(publish); + h.adminPublish + .mockImplementationOnce(async (event) => { + await publish(event); + throw new Error("ACK lost"); + }) + .mockImplementationOnce(async (event) => { + await held; + await publish(event); + }); + try { + const { message } = h.start(owner); + await vi.waitFor(() => expect(h.adminPublish).toHaveBeenCalledTimes(2)); + expect(h.roles.get(h.agents[0])).toBe("admin"); + expect(h.roles.get(h.agents[1])).toBe("member"); + expect(h.genericPublish.mock.calls.map(([event]) => event.kind)).toEqual([ + 9007, + ]); + expect(heard).not.toHaveBeenCalled(); + expect( + owner.session.outbox + ?.snapshot() + .some((item) => item.recovery?.key === soloAdminKey(h.channel)), + ).toBe(true); + release(); + await vi.waitFor(() => expect(h.events.has(message)).toBe(true)); + expect(h.agents.map((key) => h.roles.get(key))).toEqual(["admin", "admin"]); + expect(h.roles.get(h.workspaceAgent)).toBe("admin"); + expect(h.roles.get(h.viewer.pubkey)).toBe("owner"); + expect(h.adminPublish).toHaveBeenCalledTimes(3); + expect(h.adminPublish.mock.calls.map(([event]) => event.tags)).toEqual( + [...h.agents, h.workspaceAgent].map((key) => [ + ["h", h.channel], + ["p", key], + ["role", "admin"], + ]), + ); + const create = h.genericPublish.mock.calls.find( + ([event]) => event.kind === 9007, + )?.[0]; + assert.exists(create); + expect( + h.adminPublish.mock.calls.every( + ([event]) => + event.pubkey === h.viewer.pubkey && + event.created_at === create.created_at, + ), + ).toBe(true); + expect( + owner.session.outbox + ?.snapshot() + .some((item) => item.recovery?.key === soloAdminKey(h.channel)), + ).toBe(false); + } finally { + release(); + } +}); + +it("resumes a partial setup from the durable outbox after restart without restoring a later demotion", async () => { + const h = setup(); + const first = await h.open(); + const publish = h.adminPublish.getMockImplementation(); + assert.exists(publish); + h.adminPublish + .mockImplementationOnce(publish) + .mockRejectedValueOnce(new Error("offline")); + const { message } = h.start(first); + await vi.waitFor(() => + expect( + first.session.outbox?.snapshot().find((item) => item.event.id === message) + ?.delivery, + ).toBe("failed"), + ); + expect(h.events.has(message)).toBe(false); + h.roles.set(h.agents[0], "bot"); + first.dispose(); + const resumed = await h.open(); + resumed.session.outbox?.retry(message); + await vi.waitFor(() => expect(h.events.has(message)).toBe(true)); + expect(h.roles.get(h.agents[0])).toBe("bot"); + expect(h.roles.get(h.agents[1])).toBe("admin"); + expect( + h.adminPublish.mock.calls.filter( + ([event]) => event.tags[1]?.[1] === h.agents[0], + ), + ).toHaveLength(1); + const second = h.adminPublish.mock.calls.filter( + ([event]) => event.tags[1]?.[1] === h.agents[1], + ); + expect(second).toHaveLength(2); + expect(second[0]?.[0].id).toBe(second[1]?.[0].id); + expect( + h.genericPublish.mock.calls.filter(([event]) => event.kind === 9), + ).toHaveLength(1); +}); + +it("abandons expired setup while signing is held without granting or releasing its message", async () => { + const h = setup(); + const sign = h.transport.memberAdministration.sign; + let release = () => {}; + let started = () => {}; + const held = new Promise((resolve) => { + release = resolve; + }); + const signing = new Promise((resolve) => { + started = resolve; + }); + h.transport.memberAdministration.sign = async (template) => { + started(); + await held; + return sign(template); + }; + const owner = await h.open(); + const clock = vi.spyOn(Date, "now"); + try { + const { message } = h.start(owner); + await signing; + const outbox = owner.session.outbox; + assert.exists(outbox); + const receipt = outbox + .snapshot() + .find((item) => item.recovery?.key === soloAdminKey(h.channel)); + assert.exists(receipt); + const active = owner.session.channelWrites.prepareOpening(h.channel); + assert.exists(active); + const outcome = active.then( + () => undefined, + (error: unknown) => error, + ); + clock.mockReturnValue(Date.now() + 16 * 60 * 1000); + await outbox.dismiss(receipt.event.id, receipt.recovery); + release(); + const error = await outcome; + expect(h.adminPublish).not.toHaveBeenCalled(); + expect(error).toBeInstanceOf(Error); + expect(h.agents.map((key) => h.roles.get(key))).toEqual([ + "member", + "member", + ]); + expect(h.events.has(message)).toBe(false); + await vi.waitFor(() => + expect( + outbox.snapshot().find((item) => item.event.id === message)?.delivery, + ).toBe("failed"), + ); + const oldMessage = outbox + .snapshot() + .find((item) => item.event.id === message); + assert.exists(oldMessage); + assert.exists(oldMessage.event.created_at); + expect(oldMessage.event.created_at).toBeLessThan( + Date.now() / 1000 - 15 * 60, + ); + // Model the relay's timestamp rejection: Retry preserves the old event. + h.genericPublish.mockRejectedValueOnce( + new PublishRejected("Event too old"), + ); + outbox.retry(message); + await vi.waitFor(() => + expect( + outbox.snapshot().find((item) => item.event.id === message), + ).toMatchObject({ + delivery: "failed", + error: "Event too old", + }), + ); + expect(h.genericPublish.mock.lastCall?.[0]).toEqual(oldMessage.signed); + const fresh = owner.session.messages.send( + h.channel, + "Continue with current roles", + h.agents, + ); + await vi.waitFor(() => expect(h.events.has(fresh)).toBe(true)); + expect(h.events.has(message)).toBe(false); + expect( + outbox.snapshot().find((item) => item.event.id === message)?.event, + ).toEqual(oldMessage.event); + expect(h.adminPublish).not.toHaveBeenCalled(); + } finally { + release(); + clock.mockRestore(); + } +}); + +it.each(["transferred", "missing", "unavailable"] as const)( + "refreshes cached ownership before opening grants when the relay profile is %s", + async (change) => { + const h = setup(); + const owner = await h.open(); + await owner.session.profiles.ensure(h.agents); + const cached = owner.session.profiles.event?.(h.agents[0]); + assert.exists(cached); + if (change === "transferred") await h.transferAgent(owner, 0, false); + else if (change === "missing") h.omitProfiles(); + else h.failProfiles(); + expect(owner.session.profiles.event?.(h.agents[0])).toBe(cached); + const { creation, message } = h.start(owner); + await creation.ready; + await expect( + owner.session.channelWrites.prepareOpening(h.channel), + ).rejects.toThrow( + change === "unavailable" + ? "Profile read unavailable" + : "not verified as owned", + ); + expect(h.adminPublish).not.toHaveBeenCalled(); + expect(h.events.has(message)).toBe(false); + expect( + owner.session.outbox + ?.snapshot() + .some((item) => item.recovery?.key === soloAdminKey(h.channel)), + ).toBe(true); + }, +); + +it("checks the current profile inside the shared publication lock after signing", async () => { + const h = setup(); + const owner = await h.open(); + const sign = h.transport.memberAdministration.sign; + h.transport.memberAdministration.sign = async (template) => { + const event = await sign(template); + h.beforeLock(async () => { + h.beforeLock(async () => {}); + await h.transferAgent(owner, 0); + }); + return event; + }; + const { creation, message } = h.start(owner); + await creation.ready; + await expect( + owner.session.channelWrites.prepareOpening(h.channel), + ).rejects.toThrow("not verified as owned"); + expect(h.adminPublish).not.toHaveBeenCalled(); + expect(h.roles.get(h.agents[0])).toBe("member"); + expect(h.events.has(message)).toBe(false); + await vi.waitFor(() => + expect( + owner.session.outbox?.snapshot().find((item) => item.event.id === message) + ?.delivery, + ).toBe("failed"), + ); + expect( + owner.session.outbox + ?.snapshot() + .some((item) => item.recovery?.key === soloAdminKey(h.channel)), + ).toBe(true); +}); diff --git a/src/features/relay/solo-admins.test.ts b/src/features/relay/solo-admins.test.ts new file mode 100644 index 0000000000..f4df5582a6 --- /dev/null +++ b/src/features/relay/solo-admins.test.ts @@ -0,0 +1,327 @@ +import { assert, expect, it, vi } from "vitest"; +import { + soloAdminSetup, + ownedSoloAgents, + promoteSoloAdmins, + soloAdminRecovery, + soloAgentOwnership, +} from "./solo-admins"; +import { keypair, ownedProfile, signed } from "./testing"; +import { matchesEvent } from "./projection"; +import type { OutgoingEvent } from "./outbox"; +import { eventDto, type ReadFilter, type RelayEvent } from "./events"; + +it("grants ownership only from the current verified NIP-OA profile, never library hints", async () => { + const viewer = keypair(), + other = keypair(); + const own = keypair(), + shared = keypair(), + unsigned = keypair(), + hinted = keypair(); + const heads = new Map([ + [own.pubkey, eventDto(await ownedProfile(own, viewer))], + [shared.pubkey, eventDto(await ownedProfile(shared, other))], + [unsigned.pubkey, await ownedProfile(unsigned, viewer)], + [ + hinted.pubkey, + eventDto( + signed(hinted, { + kind: 0, + content: JSON.stringify({ owner: viewer.pubkey }), + tags: [], + }), + ), + ], + ]); + const ensure = vi.fn(async () => {}); + expect( + await ownedSoloAgents( + { ensure, event: (key) => heads.get(key) }, + viewer.pubkey, + [...heads.keys(), own.pubkey], + ), + ).toEqual(new Set([own.pubkey])); + expect(ensure).toHaveBeenCalledExactlyOnceWith([...heads.keys()]); +}); + +it("does not grant from an ownership head replaced while its attestation is checked", async () => { + const viewer = keypair(), + agent = keypair(); + const previous = eventDto(await ownedProfile(agent, viewer)); + const changed = eventDto( + signed(agent, { + kind: 0, + content: "{}", + tags: [], + created_at: previous.created_at + 1, + }), + ); + const event = vi.fn().mockReturnValueOnce(previous).mockReturnValue(changed); + expect( + await ownedSoloAgents({ ensure: async () => {}, event }, viewer.pubkey, [ + agent.pubkey, + ]), + ).toEqual(new Set()); +}); + +function setup() { + const owner = keypair(), + relay = keypair(); + const agents: [string, string] = [keypair().pubkey, keypair().pubkey]; + const channel = crypto.randomUUID(); + const create = signed(owner, { + kind: 9007, + content: "", + created_at: Math.floor(Date.now() / 1000), + tags: [["h", channel], ...agents.map((key) => ["p", key])], + }); + const creation: OutgoingEvent = { + event: create, + delivery: "accepted", + recovery: soloAdminRecovery(channel, agents, agents), + }; + const records = new Map(); + const roles = new Map(agents.map((key) => [key, "member"])); + const read = vi.fn(async (filters: readonly ReadFilter[]) => { + const roster = signed(relay, { + kind: 39002, + content: "", + tags: [ + ["d", channel], + ["p", owner.pubkey, "", "owner"], + ...[...roles].map(([key, role]) => ["p", key, "", role]), + ], + }); + return [...records.values(), roster].filter((event) => + filters.some((filter) => matchesEvent(event, filter)), + ); + }); + const publish = vi.fn( + async ( + event: RelayEvent, + _signal: AbortSignal, + _checkOwnership: () => void, + ) => { + const agent = event.tags.find(([tag]) => tag === "p")?.[1]; + assert.exists(agent); + records.set(event.id, event); + roles.set(agent, "admin"); + }, + ); + const writer = { + sign: vi.fn(async (template: Parameters[1]) => + signed(owner, template), + ), + publish, + }; + const controller = new AbortController(); + const owned = vi.fn( + async (_key: string): Promise<() => boolean> => + () => + true, + ); + const run = (saved = creation) => + promoteSoloAdmins( + saved, + writer, + { read }, + relay.pubkey, + controller.signal, + owned, + ); + return { + agents, + creation, + records, + roles, + read, + writer, + publish, + owned, + run, + }; +} + +it("does not restore a removed opening agent when replaying a stale creation receipt", async () => { + const h = setup(); + await h.run(); + h.roles.delete(h.agents[0]); + await h.run(structuredClone(h.creation)); + expect(h.publish).toHaveBeenCalledTimes(2); + expect(h.roles.has(h.agents[0])).toBe(false); +}); + +it("refuses an unrecorded opening grant after ownership changes without replacing the saved intent", async () => { + const h = setup(); + const saved = structuredClone(h.creation); + h.owned.mockResolvedValue(() => false); + await expect(h.run()).rejects.toThrow("not verified as owned"); + expect(h.writer.sign).not.toHaveBeenCalled(); + expect(h.publish).not.toHaveBeenCalled(); + expect(structuredClone(h.creation)).toEqual(saved); +}); + +it("confirms recorded opening grants after an ownership change without issuing new grants", async () => { + const h = setup(); + await h.run(); + h.owned.mockClear().mockResolvedValue(() => false); + await h.run(); + expect(h.owned).not.toHaveBeenCalled(); + expect(h.publish).toHaveBeenCalledTimes(2); +}); + +it.each(["owner", "guest", "absent"])( + "preserves an opening agent changed to %s before its grant", + async (role) => { + const h = setup(); + if (role === "absent") h.roles.delete(h.agents[0]); + else h.roles.set(h.agents[0], role); + await expect(h.run()).rejects.toThrow("access changed"); + expect(h.publish).not.toHaveBeenCalled(); + }, +); + +it("keeps uncertainty recoverable when a publish claims success but no command is recorded", async () => { + const h = setup(); + h.publish.mockResolvedValue(undefined); + await expect(h.run()).rejects.toThrow("unconfirmed"); + expect(h.publish).toHaveBeenCalledOnce(); +}); + +it("does not turn a failed role read into a permission grant", async () => { + const h = setup(); + h.read.mockRejectedValueOnce(new Error("read offline")); + await expect(h.run()).rejects.toThrow("read offline"); + expect(h.writer.sign).not.toHaveBeenCalled(); + expect(h.publish).not.toHaveBeenCalled(); +}); + +it("never re-dates an expired grant, but can still confirm recorded grants after expiry", async () => { + const h = setup(); + await h.run(); + const now = Date.now(); + const clock = vi.spyOn(Date, "now").mockReturnValue(now + 16 * 60 * 1000); + try { + await h.run(); + h.records.clear(); + await expect(h.run()).rejects.toThrow("expired"); + expect(h.publish).toHaveBeenCalledTimes(2); + } finally { + clock.mockRestore(); + } +}); + +it("rejects recovery that grants a nonmember admin, without signing", async () => { + const h = setup(); + assert.exists(h.creation.recovery); + await expect( + h.run({ + ...h.creation, + recovery: { + ...h.creation.recovery, + value: JSON.stringify([keypair().pubkey]), + }, + }), + ).rejects.toThrow("initial chat agents"); + expect(h.writer.sign).not.toHaveBeenCalled(); +}); + +it("recognizes a valid opening-admin receipt before delivery or expiry", () => { + const h = setup(); + const recovery = h.creation.recovery; + assert.exists(recovery); + expect(soloAdminSetup(h.creation)?.recovery).toEqual(recovery); + expect(soloAdminSetup({ ...h.creation, delivery: "unknown" })).toBeDefined(); + for (const item of [ + { ...h.creation, recovery: undefined }, + { + ...h.creation, + recovery: { key: "another-owner", value: recovery.value }, + }, + { + ...h.creation, + recovery: { key: recovery.key, value: "invalid JSON" }, + }, + { + ...h.creation, + recovery: { + key: recovery.key, + value: JSON.stringify([keypair().pubkey]), + }, + }, + { ...h.creation, event: { ...h.creation.event, kind: 9000 } }, + ]) + expect(soloAdminSetup(item)).toBeUndefined(); +}); + +it("invalidates a verified ownership guard when its head is replaced or evicted", async () => { + const viewer = keypair(), + agent = keypair(); + const initial = eventDto(await ownedProfile(agent, viewer)); + let head: RelayEvent | undefined = initial; + const owns = await soloAgentOwnership( + { event: () => head }, + viewer.pubkey, + agent.pubkey, + ); + expect(owns()).toBe(true); + head = eventDto(await ownedProfile(agent, keypair())); + expect(owns()).toBe(false); + head = undefined; + expect(owns()).toBe(false); +}); + +it("rechecks the next opening target after publishing the previous grant", async () => { + const h = setup(); + const publish = h.publish.getMockImplementation(); + assert.exists(publish); + h.publish.mockImplementationOnce(async (event) => { + await publish(event, new AbortController().signal, () => {}); + h.owned.mockResolvedValue(() => false); + }); + await expect(h.run()).rejects.toThrow("not verified as owned"); + expect(h.publish).toHaveBeenCalledOnce(); + expect(h.writer.sign).toHaveBeenCalledOnce(); + expect(h.roles.get(h.agents[1])).toBe("member"); +}); + +it.each(["roster read", "signing", "publication lock"])( + "refuses an unrecorded grant if ownership changes during %s", + async (boundary) => { + const h = setup(); + let current = true; + h.owned.mockResolvedValue(() => current); + if (boundary === "roster read") { + const read = h.read.getMockImplementation(); + assert.exists(read); + h.read.mockImplementation(async (filters) => { + const result = await read(filters); + if (filters.some((filter) => filter.kinds?.includes(39002))) + current = false; + return result; + }); + } else if (boundary === "signing") { + const sign = h.writer.sign.getMockImplementation(); + assert.exists(sign); + h.writer.sign.mockImplementation(async (template) => { + const result = await sign(template); + current = false; + return result; + }); + } else { + // Like the production journal: another holder can change the profile + // before this callback acquires permission to publish. + h.writer.publish = vi.fn(async (_event, _signal, checkOwnership) => { + await Promise.resolve(); + current = false; + checkOwnership(); + }); + } + await expect(h.run()).rejects.toThrow("not verified as owned"); + expect(h.records.size).toBe(0); + expect(h.roles.get(h.agents[0])).toBe("member"); + expect(h.writer.sign).toHaveBeenCalledTimes( + boundary === "roster read" ? 0 : 1, + ); + }, +); diff --git a/src/features/relay/solo-admins.ts b/src/features/relay/solo-admins.ts new file mode 100644 index 0000000000..6f44b47c65 --- /dev/null +++ b/src/features/relay/solo-admins.ts @@ -0,0 +1,198 @@ +import { getEventHash } from "nostr-tools"; +import { attestedOwner } from "../agents/owner-attestation"; +import { hasEventProof, type RelayEvent } from "./events"; +import type { ProfileQueries } from "./profile-directory"; +import { memberAdministrationTemplate } from "../channel-members/administration-protocol"; +import type { OutboxRecovery, OutgoingEvent } from "./outbox"; +import type { RelayReader } from "./reader"; +import type { RelayWriter } from "./transport"; + +export const soloAdminKey = (channel: string) => + `solo-initial-admins:${channel}`; + +/** A verified head is authority only while it remains the directory's head. */ +export async function soloAgentOwnership( + profiles: Pick | undefined, + viewer: string | undefined, + key: string, +): Promise<() => boolean> { + const head = profiles?.event?.(key); + const owned = !!( + viewer && + head && + hasEventProof(head) && + head.kind === 0 && + head.pubkey === key && + (await attestedOwner(head)) === viewer + ); + return () => owned && profiles?.event?.(key) === head; +} + +/** Library inclusion is discovery, never authority to grant chat Admin. */ +export async function ownedSoloAgents( + profiles: Pick | undefined, + viewer: string | undefined, + keys: readonly string[], +): Promise> { + const owned = new Set(); + if (!profiles || !viewer || !keys.length) return owned; + const unique = [...new Set(keys)]; + await profiles.ensure(unique); + await Promise.all( + unique.map(async (key) => { + if ((await soloAgentOwnership(profiles, viewer, key))()) owned.add(key); + }), + ); + return new Set(unique.filter((key) => owned.has(key))); +} + +/** Local recovery only; the relay still receives an ordinary channel create. */ +export function soloAdminRecovery( + channel: string, + members: readonly string[], + admins: readonly string[] = [], +): OutboxRecovery | undefined { + if (!admins.length) return; + const unique = [...new Set(admins)]; + if ( + unique.length > 32 || + unique.some((key) => !/^[0-9a-f]{64}$/.test(key) || !members.includes(key)) + ) + throw new Error("Opening admins must be initial chat agents."); + return { key: soloAdminKey(channel), value: JSON.stringify(unique) }; +} + +/** Recognize a saved setup independently of its delivery state. */ +export function soloAdminSetup(item: OutgoingEvent) { + try { + return readSoloAdminSetup(item); + } catch { + return; + } +} + +function readSoloAdminSetup(item: OutgoingEvent) { + const create = item.event; + const channel = create.tags.find(([tag]) => tag === "h")?.[1]; + if ( + create.kind !== 9007 || + !channel || + item.recovery?.key !== soloAdminKey(channel) + ) + return; + const admins: unknown = JSON.parse(item.recovery.value); + if ( + Array.isArray(admins) && + admins.length > 0 && + admins.every( + (key): key is string => typeof key === "string" && key !== create.pubkey, + ) && + soloAdminRecovery( + channel, + create.tags.flatMap(([tag, key]) => (tag === "p" && key ? [key] : [])), + admins, + )?.value === item.recovery.value + ) + return { channel, admins, recovery: item.recovery }; +} + +/** Reconstruct the exact same promotions after interruption. Their timestamp + * and channel come from the saved create, so retries never invent a new grant + * that could undo a later demotion or removal. */ +export async function promoteSoloAdmins( + creation: OutgoingEvent, + writer: Omit & { + publish( + event: RelayEvent, + signal: AbortSignal, + checkOwnership: () => void, + ): Promise; + }, + reader: RelayReader, + relayAuthor: string, + signal: AbortSignal, + owned?: (key: string, targets: readonly string[]) => Promise<() => boolean>, +) { + const create = creation.event; + const setup = readSoloAdminSetup(creation); + if (!setup) throw new Error("The saved chat admin setup is invalid."); + const { channel, admins } = setup; + const read = (filters: Parameters[0]) => + reader.read(filters, { signal, fresh: true, priority: "foreground" }); + for (const admin of admins) { + signal.throwIfAborted(); + const template = { + ...memberAdministrationTemplate(channel, create.pubkey, { + pubkey: admin, + expectedRole: "member", + role: "admin", + }), + created_at: create.created_at, + }; + const id = getEventHash({ ...template, pubkey: create.pubkey }); + const recorded = async () => + ( + await read([ + { + kinds: [9000], + ids: [id], + authors: [create.pubkey], + limit: 1, + consistency: "strong", + }, + ]) + ).some((event) => event.id === id && event.pubkey === create.pubkey); + // A recorded grant remains complete even when its recipient was demoted. + if (await recorded()) continue; + if (Date.now() / 1000 - create.created_at >= 15 * 60) + throw new Error( + "Chat admin setup expired. Abandon setup in Outbox to continue with current roles, or start a new chat.", + ); + const ownership = await owned?.(admin, admins); + const checkOwnership = () => { + if (!ownership?.()) + throw new Error( + "An opening agent is not verified as owned by the chat creator. Retry this message or choose Abandon admin setup in Outbox to continue with current roles.", + ); + }; + checkOwnership(); + const rosters = await read([ + { + kinds: [39002], + authors: [relayAuthor], + "#d": [channel], + limit: 1, + consistency: "strong", + }, + ]); + const roster = rosters.find( + (event) => + event.kind === 39002 && + event.pubkey === relayAuthor && + event.tags.some(([tag, value]) => tag === "d" && value === channel), + ); + const role = roster?.tags.find( + ([tag, key]) => tag === "p" && key === admin, + )?.[3]; + if (!role || !["member", "bot", "admin"].includes(role)) + throw new Error( + "An opening agent's access changed. Choose Abandon admin setup in Outbox to continue with current roles.", + ); + checkOwnership(); + const signed = await writer.sign(template, signal); + signal.throwIfAborted(); + if (signed.id !== id || signed.pubkey !== create.pubkey) + throw new Error("The signer changed the chat admin command."); + try { + checkOwnership(); + await writer.publish(signed, signal, checkOwnership); + } catch (error) { + if (!(await recorded())) throw error; + } + // An OK alone is not proof of the requested role change. + if (!(await recorded())) + throw new Error( + "Chat admin setup is unconfirmed. Retry the opening message.", + ); + } +} diff --git a/src/features/relay/testing.ts b/src/features/relay/testing.ts index 11bcada592..54aae7e18a 100644 --- a/src/features/relay/testing.ts +++ b/src/features/relay/testing.ts @@ -1,5 +1,5 @@ import { schnorr } from "@noble/curves/secp256k1.js"; -import { hexToBytes } from "nostr-tools/utils"; +import { bytesToHex, hexToBytes } from "nostr-tools/utils"; import { finalizeEvent, generateSecretKey, @@ -23,6 +23,30 @@ export function signed( ): RelayEvent { return finalizeEvent({ created_at: 1_700_000_000, ...template }, key.secret); } +/** A real NIP-OA delegation on an agent's signed profile. */ +export async function ownedProfile( + agent: Key, + owner: Key, + name?: string, +): Promise { + const conditions = "kind=0"; + const digest = await crypto.subtle.digest( + "SHA-256", + new TextEncoder().encode(`nostr:agent-auth:${agent.pubkey}:${conditions}`), + ); + return signed(agent, { + kind: 0, + content: JSON.stringify(name ? { name } : {}), + tags: [ + [ + "auth", + owner.pubkey, + conditions, + bytesToHex(schnorr.sign(new Uint8Array(digest), owner.secret)), + ], + ], + }); +} /** The native `relay_verify_signatures` command, with real BIP-340 checks. */ export const nativeSignatureChecks = (args: unknown) => ( diff --git a/src/features/relay/transport.ts b/src/features/relay/transport.ts index 182827f287..ec404d53c1 100644 --- a/src/features/relay/transport.ts +++ b/src/features/relay/transport.ts @@ -1,3 +1,4 @@ +import { isAdminAddition } from "../channel-members/administration-protocol.ts"; import type { ArtifactIncrementalReader } from "./artifact-incremental-reader.ts"; import type { VerifiedProfileAuthority } from "./verified-profile"; import type { ReminderHost } from "./reminders"; @@ -580,6 +581,7 @@ export async function connectBrokerTransport( "invalid-response", "Relay broker session is malformed", ); + const viewer = session.viewer; let traffic: LiveSubscription | undefined; const presence = presenceObservation(); const relayHttpUrl = relayHttpBase(session.relayHttpUrl, session.relayUrl); @@ -589,6 +591,8 @@ export async function connectBrokerTransport( "X-Buzz-Live-ID": traffic?.identity?.() ?? "", }); const publish = async (event: RelayEvent, signal: AbortSignal) => { + if (session.memberAdministration === true && isAdminAddition(event, viewer)) + return routeWriter("member-administration").publish(event, signal); const result = await fetch(`${endpoint}/publish`, { method: "POST", credentials: "same-origin", @@ -600,6 +604,11 @@ export async function connectBrokerTransport( return acceptPublish(result, event.id); }; const sign = async (template: EventTemplate, signal: AbortSignal) => { + if ( + session.memberAdministration === true && + isAdminAddition(template, viewer) + ) + return routeWriter("member-administration").sign(template, signal); const result = await fetch(`${endpoint}/sign`, { method: "POST", credentials: "same-origin", @@ -613,7 +622,7 @@ export async function connectBrokerTransport( return event; }; /** Dedicated shape-limited host sign/publish routes, separate from the outbox writer. */ - const routeWriter = (route: string): RelayWriter => ({ + const routeWriter = (route: string) => ({ async sign(template: EventTemplate, signal: AbortSignal) { const response = await fetch(`${endpoint}/${route}-sign`, { method: "POST", diff --git a/src/features/solo/SoloDraft.test.tsx b/src/features/solo/SoloDraft.test.tsx index acc588dc2f..b4add93984 100644 --- a/src/features/solo/SoloDraft.test.tsx +++ b/src/features/solo/SoloDraft.test.tsx @@ -38,6 +38,7 @@ import { ToastProvider } from "../../shared/design-system/ui/Toast"; import { ChatNotStarted, createChannelWrites } from "../relay/channel-writes"; import { createOutbox } from "../relay/outbox"; import { keypair, signed } from "../relay/testing"; +import { ownedSoloAgents } from "../relay/solo-admins"; import { SOLO_LABEL } from "./labels"; import { attachmentDraft } from "../messages/attachment-draft"; import type { @@ -89,6 +90,10 @@ vi.mock("../channel-navigation/solo-navigation", async (original) => ({ })); composerDOMFixture(); +vi.mock("../relay/solo-admins", async (original) => ({ + ...(await original()), + ownedSoloAgents: vi.fn(), +})); afterEach(cleanup); afterEach(() => regionNavigation.set(undefined)); afterEach(() => { @@ -97,6 +102,9 @@ afterEach(() => { delete (HTMLElement.prototype as Partial).scrollIntoView; }); beforeEach(() => { + vi.mocked(ownedSoloAgents).mockImplementation( + async (_profiles, _viewer, keys) => new Set(keys), + ); localStorage.clear(); Object.defineProperty(navigator, "locks", { configurable: true, @@ -314,12 +322,60 @@ it("uses restored explicit mentions, not a separate picker", async () => { undefined, false, undefined, + { admins: ["b".repeat(64)] }, ); expect(test.channelWrites.addAgents).not.toHaveBeenCalled(); expect(test.messages.send).toHaveBeenCalledWith(id, "@Outside agent Help", [ "b".repeat(64), ]); }); + +it.each([true, false])( + "applies verified ownership equally to workspace defaults (owned=%s)", + async (workspaceOwned) => { + const test = await projectSetup(["b".repeat(64)]); + const admins = workspaceOwned + ? ["a".repeat(64), "b".repeat(64)] + : ["a".repeat(64)]; + vi.mocked(ownedSoloAgents).mockResolvedValueOnce(new Set(admins)); + writeView( + "test", + "solo:project:work:new-draft", + taggedDraft("Use the workspace"), + ); + render( + , + ); + await userEvent.click(screen.getByRole("button", { name: "Send message" })); + await waitFor(() => expect(test.messages.send).toHaveBeenCalledOnce()); + expect(test.channelWrites.start.mock.calls[0]?.[2]).toEqual([ + "a".repeat(64), + "b".repeat(64), + ]); + expect(startOptions(test)).toMatchObject({ admins }); + expect(test.messages.send.mock.calls[0]?.[2]).toEqual(["a".repeat(64)]); + }, +); + +it("sends to a shared opening agent without requesting Admin", async () => { + const test = setup(); + vi.mocked(ownedSoloAgents).mockResolvedValueOnce(new Set()); + writeView( + "test", + "solo:new-draft", + taggedDraft("Help with this", "b".repeat(64), "Outside agent"), + ); + render(); + await userEvent.click(screen.getByRole("button", { name: "Send message" })); + await waitFor(() => expect(test.messages.send).toHaveBeenCalledOnce()); + expect(startOptions(test)).toMatchObject({ admins: [] }); + expect(test.messages.send.mock.calls[0]?.[2]).toEqual(["b".repeat(64)]); +}); type User = ReturnType; it.each([ { @@ -465,6 +521,7 @@ it("a refused start gives its prompt, files and settings back to a blank New cha undefined, true, undefined, + { admins: ["a".repeat(64)] }, ); expect(test.messages.send).toHaveBeenLastCalledWith( retry, @@ -866,6 +923,7 @@ it("keeps the chosen agent through draft remount, first send, refused-start reco undefined, false, undefined, + { admins: ["b".repeat(64)] }, ); expect(test.messages.send).toHaveBeenLastCalledWith(retry, "Hello", [ "b".repeat(64), @@ -1116,6 +1174,7 @@ it.each([true, false])( undefined, false, undefined, + { admins: ["a".repeat(64)] }, ); expect(test.messages.send).toHaveBeenCalledWith( id, @@ -2143,6 +2202,7 @@ it.each([false, true])( authority.pubkey, undefined, true, + { sign, publish }, ); const agent = { pubkey: viewer.pubkey, name: "Viewer", managed: true }; const eligible = { @@ -2264,6 +2324,9 @@ it.each(["remember", "off"])( await waitFor(() => expect(started).toHaveBeenCalledOnce()); expect(f.messages.send).toHaveBeenCalledOnce(); expect(f.channelWrites.create).toHaveBeenCalledOnce(); + expect((f.channelWrites.start.mock.calls[0] as unknown[])[6]).toEqual({ + admins: recipients.map((recipient) => recipient.pubkey), + }); const id = started.mock.calls[0]?.[0]; expect(readView("first-followup", `draft:${id}`, null)).toEqual({ text: "", @@ -3444,6 +3507,7 @@ it("shows an editable ordinary source link and sends it to the pill's default ag undefined, false, undefined, + { admins: ["a".repeat(64)] }, ); expect(t.messages.send).toHaveBeenCalledWith( id, @@ -3643,6 +3707,7 @@ function soloDraftWithInventory( undefined, false, undefined, + { admins: [aaron.pubkey] }, ); expect(test.messages.send).toHaveBeenCalledWith(id, "@Aaron hi", [ aaron.pubkey, @@ -3796,6 +3861,9 @@ it.each([false, true])( expect(test.channelWrites.start.mock.calls[0]?.[2]).toEqual( prepareStart.mock.calls[0]?.[1].members, ); + expect(startOptions(test)).toMatchObject({ + admins: ["a".repeat(64), "b".repeat(64)], + }); expect(test.messages.send.mock.calls[0]?.[0]).toBe( prepareStart.mock.calls[0]?.[1].channelId, ); @@ -3985,7 +4053,10 @@ it("a region's New chat starts a labeled chat its source can find, without filin await waitFor(() => expect(onStarted).toHaveBeenCalledOnce()); const id = test.channelWrites.create.mock.calls[0]?.[0] ?? ""; // Unguarded, so the Outbox replays it after a restart like any New chat. - expect(startOptions(test)).toEqual({ labels: [REGION] }); + expect(startOptions(test)).toEqual({ + admins: ["a".repeat(64)], + labels: [REGION], + }); expect(readView("test", regionStartKey(id), null)).toEqual({ region: REGION, workspace: "work", diff --git a/src/features/solo/SoloDraft.tsx b/src/features/solo/SoloDraft.tsx index 5ecd5171fb..d1be2776e1 100644 --- a/src/features/solo/SoloDraft.tsx +++ b/src/features/solo/SoloDraft.tsx @@ -19,6 +19,7 @@ import { } from "./workspace"; import { useCallback, useEffect, useRef, useState } from "react"; import type { RelaySession } from "../relay/session"; +import { ownedSoloAgents } from "../relay/solo-admins"; import { readView, writeView, @@ -474,6 +475,10 @@ export function SoloDraft({ "Solo chats can only use your available agents. Check mentions and workspace defaults.", ); } + const admins = [ + ...(await ownedSoloAgents(session.profiles, session.viewer, members)), + ]; + if (!mounted.current) return; // Read at Send: the region's source may have stopped since. const regionOwner = () => { const current = region @@ -574,7 +579,7 @@ export function SoloDraft({ } : undefined, // Unguarded, so a restart can retry it like any New chat. - ...(region ? [{ labels: [region] }] : []), + { admins, ...(region ? { labels: [region] } : {}) }, ); } catch (reason) { if (startKey) writeView(scope, startKey, null); diff --git a/tests/browser/find-on-screen.spec.mjs b/tests/browser/find-on-screen.spec.mjs index 0ac511ca94..5bc720d1ac 100644 --- a/tests/browser/find-on-screen.spec.mjs +++ b/tests/browser/find-on-screen.spec.mjs @@ -44,6 +44,10 @@ test.afterAll(async () => { const bar = (page) => page.locator("search"); const field = (page) => page.getByRole("searchbox", { name: "Find on screen" }); +const openFind = async (page) => { + await page.waitForFunction(() => typeof window.openFind === "function"); + await page.evaluate(() => window.openFind()); +}; const box = (locator) => locator.evaluate((element) => { const { x, y, width, height } = element.getBoundingClientRect(); @@ -78,7 +82,7 @@ test("the bar keeps the window's top-right corner inside a dialog", async ({ const errors = watchPageErrors(page); await page.setViewportSize({ width: 1200, height: 800 }); await page.goto(url); - await page.evaluate(() => window.openFind()); + await openFind(page); await expect(field(page)).toBeFocused(); const outside = await box(bar(page)); await field(page).press("Escape"); @@ -86,7 +90,7 @@ test("the bar keeps the window's top-right corner inside a dialog", async ({ await page.evaluate(() => window.setModal(true)); const dialog = page.getByRole("dialog", { name: "Members" }); await expect(dialog).toBeVisible(); - await page.evaluate(() => window.openFind()); + await openFind(page); await expect(dialog.locator("search")).toHaveCount(1); await expect(field(page)).toBeFocused(); expect(await box(bar(page))).toEqual(outside); @@ -105,7 +109,7 @@ test("stepping reveals each match in a long code block", async ({ page }) => { const errors = watchPageErrors(page); await page.setViewportSize({ width: 900, height: 700 }); await page.goto(url); - await page.evaluate(() => window.openFind()); + await openFind(page); await field(page).fill("needle"); const status = page.locator("search [role=status]"); await expect(status).toHaveText("1 of 2"); diff --git a/tests/browser/fixture.mjs b/tests/browser/fixture.mjs index ff2aae97e1..b7d5af97f4 100644 --- a/tests/browser/fixture.mjs +++ b/tests/browser/fixture.mjs @@ -34,6 +34,7 @@ export const historySize = 640; // broker/subscriber and model only the upstream relay policy with ephemeral keys. export const test = base.extend({ productionBroker: [false, { option: true }], + openingAdminSetup: [false, { option: true }], enabledPlugins: [[], { option: true }], builderlab: [{}, { option: true }], /** The production broker's live setup deadline. It runs in Node, so the @@ -133,6 +134,7 @@ export const test = base.extend({ browserName, browser, productionBroker, + openingAdminSetup, enabledPlugins, builderlab, liveSetupTimeoutMs, @@ -282,16 +284,27 @@ export const test = base.extend({ const key = generateSecretKey(); soloAgentKeys.push(key); const pubkey = getPublicKey(key); - // A NIP-OA owner attestation marks a real agent profile; the app reads - // only its shape. Outside agents belong to someone else. - const owner = soloAgentNames.includes(name) - ? viewer - : getPublicKey(generateSecretKey()); + // Real ownership proofs: Admin admission verifies the delegation, + // independently of whether the identity appears in the library. + const ownerKey = soloAgentNames.includes(name) + ? userKey + : generateSecretKey(); + const owner = getPublicKey(ownerKey); + const delegation = createHash("sha256") + .update(`nostr:agent-auth:${pubkey}:`) + .digest(); servedProfiles.set( pubkey, sign( 0, - [["auth", owner, "", "0".repeat(128)]], + [ + [ + "auth", + owner, + "", + bytesToHex(schnorr.sign(delegation, ownerKey)), + ], + ], JSON.stringify({ name, is_agent: true }), key, ), @@ -1082,6 +1095,17 @@ export const test = base.extend({ .map((entry) => entry.event); }; const answer = (community, filter) => { + if (openingAdminSetup && (filter.ids || filter.kinds?.includes(9007))) + return [ + report.setupCreation, + ...report.publications.map((item) => item.event), + ].filter( + (event) => + event && + (filter.ids + ? filter.ids.includes(event.id) + : filter.kinds.includes(event.kind)), + ); // These ordinary fixture channels have no Huddle creation receipt. if (filter.kinds?.length === 1 && filter.kinds[0] === 9007) return []; // The real relay can return both current metadata and rosters in one query. @@ -2185,6 +2209,26 @@ export const test = base.extend({ return acceptReadPublication(community, event); if (event.kind === 30078 || event.kind === 20002) return acceptReadPublication(community, event); + if (openingAdminSetup && [9000, 9].includes(event.kind)) { + // This receiver's clock is independently controlled by the journey. + expect( + Math.abs(report.setupReceiverTime - event.created_at), + ).toBeLessThanOrEqual(900); + if (event.kind === 9000) { + expect( + event.tags.filter(([tag]) => tag === "role"), + ).toEqual([ + [ + "role", + report.setupCreation + ? "admin" + : expect.stringMatching(/^(admin|bot)$/), + ], + ]); + report.publications.push({ community, event }); + return; + } + } expect([9, 7]).toContain(event.kind); const channel = event.tags.find(([k]) => k === "h")?.[1]; const history = histories.get(`${community}/${channel}`); @@ -2204,6 +2248,7 @@ export const test = base.extend({ : {}), discovery: (community) => ({ self: getPublicKey(relayKey), + ...(openingAdminSetup ? { supported_nips: [29] } : {}), // Solo details publications below retain label changes as well as names. ...(ownSoloChannels.length ? { supported_extensions: ["nip-cl"] } @@ -2842,6 +2887,34 @@ export const test = base.extend({ servedProfiles.set(event.pubkey, event); return event; }, + // A real, newer NIP-OA head; the client still admits it through a read. + transferSoloAgent(pubkey) { + const index = soloAgents.findIndex( + (agent) => agent.pubkey === pubkey, + ); + expect(index).toBeGreaterThanOrEqual(0); + const previous = servedProfiles.get(pubkey); + const ownerKey = generateSecretKey(); + const digest = createHash("sha256") + .update(`nostr:agent-auth:${pubkey}:`) + .digest(); + const event = sign( + 0, + [ + [ + "auth", + getPublicKey(ownerKey), + "", + bytesToHex(schnorr.sign(digest, ownerKey)), + ], + ], + previous.content, + soloAgentKeys[index], + previous.created_at + 1, + ); + servedProfiles.set(pubkey, event); + return event; + }, // Configure pre-existing members before opening the app. Reads stay at // the modeled relay, without a second browser-owned HTTP request. serveMembers(id, pubkeys) { diff --git a/tests/browser/message-management.spec.mjs b/tests/browser/message-management.spec.mjs index 20684c32da..da371a0478 100644 --- a/tests/browser/message-management.spec.mjs +++ b/tests/browser/message-management.spec.mjs @@ -11,6 +11,78 @@ test.use({ historyCounts: { alpha: 2, beta: 1 }, }); +// Separate app windows retain their own row/confirmation while sharing the +// production IndexedDB receipt and Web Lock. A DOM emulator cannot prove this. +test("discarding an orphan already removed by another window closes confirmation", async ({ + page, + context, + app, +}, testInfo) => { + const message = app.sign({ + kind: 9, + created_at: Math.floor(Date.now() / 1000) - 3600, + content: "Orphaned follow-up", + tags: [["h", "alpha"]], + }); + await page.addInitScript( + ({ scope, message }) => { + localStorage.setItem( + `buzz-outbox-v1:${scope}`, + JSON.stringify([ + { + event: message, + signed: message, + delivery: "unknown", + recovery: { key: "follow-up:orphan", value: "orphan" }, + }, + ]), + ); + }, + { scope: `https://primary.example:${app.viewer}`, message }, + ); + const confirm = async (window) => { + await open(window, app); + const row = window.locator(`[data-message-id="${message.id}"]`); + await expect(row).toBeVisible(); + await hoverMessage(row); + await row.getByRole("button", { name: "More message actions" }).click(); + await window + .getByRole("menuitem", { name: "Remove from this device", exact: true }) + .click(); + return window.getByRole("alertdialog", { + name: "Remove message from this device?", + exact: true, + }); + }; + const a = await confirm(page); + const other = await context.newPage(); + app.watchPageErrors(other); + try { + const b = await confirm(other); + await b.getByRole("button", { name: "Remove", exact: true }).click(); + await expect(b).toHaveCount(0); + await expect(other.getByText(message.content, { exact: true })).toHaveCount( + 0, + ); + await expect(a).toBeVisible(); + await a.getByRole("button", { name: "Remove", exact: true }).click(); + await expect(a).toHaveCount(0); + await expect(page.getByText(message.content, { exact: true })).toHaveCount( + 0, + ); + expect( + app.report.publications.filter(({ event }) => + [5, 9].includes(event.kind), + ), + ).toEqual([]); + await page.screenshot({ + path: testInfo.outputPath("discarded-in-both-windows.png"), + }); + } finally { + await other.close(); + } +}); + // Real shared-row/portal integration, keyboard focus and responsive geometry; // failure, retry, identity and permission matrices stay in lower-layer tests. test("manage a channel message, peer unread state, and its thread", async ({ diff --git a/tests/browser/outbox-storage.spec.mjs b/tests/browser/outbox-storage.spec.mjs index 38d1f7bf43..85309ff3e0 100644 --- a/tests/browser/outbox-storage.spec.mjs +++ b/tests/browser/outbox-storage.spec.mjs @@ -51,6 +51,115 @@ test("forgetting a stale receipt relinquishes its journal deletion ownership", a expect(ids).toEqual(["next", "old"]); }); +for (const journal of ["indexeddb", "legacy"]) + test(`a late creation echo respects durable setup removal (${journal})`, async ({ + page, + context, + sourceOrigin, + }) => { + await context.route(`${sourceOrigin}/outbox-storage-test`, (route) => + route.fulfill({ contentType: "text/html", body: "" }), + ); + await page.goto(`${sourceOrigin}/outbox-storage-test`); + const { finalizeEvent } = await import("nostr-tools"); + const member = "a".repeat(64); + const creation = finalizeEvent( + { + kind: 9007, + created_at: 1, + content: "", + tags: [ + ["h", "chat"], + ["p", member], + ], + }, + new Uint8Array(32).fill(7), + ); + const result = await page.evaluate( + async ({ creation, member, journal }) => { + const { browserOutboxStorage, purgeOutboxStorage } = await import( + "/src/features/relay/outbox-storage.ts" + ); + const { createOutbox } = await import("/src/features/relay/outbox.ts"); + const { soloAdminRecovery } = await import( + "/src/features/relay/solo-admins.ts" + ); + const recovery = soloAdminRecovery("chat", [member], [member]); + const scope = `setup-removal-${crypto.randomUUID()}`; + const aStore = browserOutboxStorage(scope); + const bStore = browserOutboxStorage(scope); + const operation = { + event: creation, + signed: creation, + recovery, + delivery: "accepted", + }; + if (journal === "legacy") + localStorage.setItem( + `buzz-outbox-v1:${scope}`, + JSON.stringify([operation]), + ); + else await aStore.save([operation]); + const unexpected = async () => { + throw new Error("Unexpected delivery"); + }; + const writer = { sign: unexpected, publish: unexpected }; + const a = createOutbox(creation.pubkey, writer, aStore); + const b = createOutbox(creation.pubkey, writer, bStore); + try { + await Promise.all([a.ready, b.ready]); + if ( + !a.outbox.snapshot()[0]?.recovery || + !b.outbox.snapshot()[0]?.recovery + ) + throw new Error("Both windows must hold the saved setup"); + b.observe([creation]); + await b.outbox.dismiss(creation.id, recovery); + const afterDismiss = (await bStore.load({ readOnly: true })).length; + a.observe([creation]); + let ran = false; + const publication = await a.outbox + .withRecovery(creation.id, recovery, async () => { + ran = true; + }) + .then( + () => "completed", + (error) => error.message, + ); + const completion = await a.outbox + .finishRecovery(creation.id, recovery) + .then( + () => "completed", + (error) => error.message, + ); + return { + afterDismiss, + ran, + publication, + completion, + remaining: (await bStore.load({ readOnly: true })).length, + }; + } finally { + a.dispose(); + b.dispose(); + await purgeOutboxStorage(scope); + } + }, + { creation, member, journal }, + ); + expect(result).toEqual({ + afterDismiss: 0, + ran: false, + publication: expect.stringContaining( + "removed or changed in another window", + ), + completion: expect.stringContaining( + "removed or changed in another window", + ), + remaining: 0, + }); + }); + for (const mode of ["dismiss-first", "adopt-first", "peer-accepted"]) test(`receipt adoption serializes queue consumption with dismissal (${mode})`, async ({ page, diff --git a/tests/browser/solo-admin-abandonment.spec.mjs b/tests/browser/solo-admin-abandonment.spec.mjs new file mode 100644 index 0000000000..2e2469f118 --- /dev/null +++ b/tests/browser/solo-admin-abandonment.spec.mjs @@ -0,0 +1,313 @@ +import { test, expect } from "./fixture.mjs"; +import { openPage } from "./navigation.mjs"; +import { openChannelDetails } from "./channel-details.mjs"; + +const channel = "11111111-1111-4111-8111-111111111111"; +const chat = "33333333-3333-4333-8333-333333333333"; +test.use({ + productionBroker: true, + openingAdminSetup: true, + channelLifecycle: true, + channelIds: [channel, chat], + channelNames: { [channel]: "Project updates", [chat]: "Recovery chat" }, + soloChannels: [chat], + ownSoloChannels: [chat], + soloAgentNames: ["Recovery agent"], + soloOutsideAgentNames: ["Shared helper"], + savedCommunities: ["primary"], + historyCounts: { [channel]: 0, [chat]: 0 }, +}); + +// Restored opening intent exercises the production session, broker and signer; +// the draft's owned subset and workspace selection are covered in SoloDraft. +test("opening recovery grants a quiet owned default without promoting its shared recipient", async ({ + page, + app, +}, info) => { + const createdAt = Math.floor(Date.now() / 1000); + const [owned, shared] = app.soloAgents; + const creation = app.sign({ + kind: 9007, + created_at: createdAt, + content: "", + tags: [ + ["h", chat], + ["p", owned.pubkey], + ["p", shared.pubkey], + ], + }); + const message = app.sign({ + kind: 9, + created_at: createdAt, + content: "Only the shared helper is addressed", + tags: [ + ["h", chat], + ["p", shared.pubkey], + ], + }); + app.report.setupCreation = creation; + app.report.setupReceiverTime = createdAt; + await page.addInitScript( + ({ scope, creation, message, owned }) => { + localStorage.setItem( + `buzz-outbox-v1:${scope}`, + JSON.stringify([ + { + event: creation, + signed: creation, + delivery: "accepted", + recovery: { + key: `solo-initial-admins:${creation.tags[0][1]}`, + value: JSON.stringify([owned]), + }, + }, + { event: message, signed: message, delivery: "failed" }, + ]), + ); + }, + { + scope: `https://primary.example:${app.viewer}`, + creation, + message, + owned: owned.pubkey, + }, + ); + const outbox = await openOutbox(page, app.origin); + const row = outbox.getByRole("listitem").filter({ hasText: message.content }); + await row.getByRole("button", { name: "Retry", exact: true }).click(); + await expect + .poll( + () => + app.report.publications.filter(({ event }) => event.kind === 9).length, + ) + .toBe(1); + const grants = app.report.publications.filter( + ({ event }) => event.kind === 9000, + ); + expect(grants).toHaveLength(1); + expect(grants[0].event.tags).toContainEqual(["p", owned.pubkey]); + expect(grants[0].event.tags).not.toContainEqual(["p", shared.pubkey]); + expect( + app.report.publications.find(({ event }) => event.kind === 9).event, + ).toEqual(message); + await expect(outbox.getByRole("alert")).toHaveCount(0); + await outbox.screenshot({ + path: info.outputPath("OWNED_DEFAULT_SHARED_RECIPIENT.png"), + }); +}); + +async function openOutbox(page, origin) { + await page.goto(origin); + await openPage(page, "Messages"); + await page + .getByRole("button", { name: "Project updates", exact: true }) + .click(); + await openChannelDetails(page); + const panel = page.getByRole("complementary", { + name: "Channel settings", + exact: true, + }); + await panel.getByText("Diagnostics", { exact: true }).click(); + const summary = panel.locator("summary").filter({ hasText: /^Outbox ·/ }); + await summary.click(); + return summary.locator(".."); +} + +// Browser-only: separate windows share the production IndexedDB journal and +// Web Locks while each has its own session, signing request and cancellation. +for (const mode of ["cross-window", "same-window", "failed-storage"]) + test(`expired setup abandonment fences held signing (${mode})`, async ({ + page, + context, + app, + }) => { + const createdAt = Math.floor(Date.now() / 1000); + const agent = app.soloAgents[0].pubkey; + const creation = app.sign({ + kind: 9007, + created_at: createdAt, + content: "", + tags: [ + ["h", chat], + ["p", agent], + ], + }); + const message = app.sign({ + kind: 9, + created_at: createdAt, + content: "Opening work", + tags: [ + ["h", chat], + ["p", agent], + ], + }); + const recovery = { + key: `solo-initial-admins:${chat}`, + value: JSON.stringify([agent]), + }; + app.report.setupCreation = creation; + const scope = `https://primary.example:${app.viewer}`; + app.report.setupReceiverTime = createdAt + 895; + await page.clock.setFixedTime(new Date((createdAt + 899) * 1000)); + if (mode === "same-window") { + await page.setViewportSize({ width: 840, height: 900 }); + await page.addInitScript(() => { + localStorage.setItem("buzz-font-scale.v1", "1.5"); + }); + } + await page.addInitScript( + ({ scope, creation, message, recovery }) => { + localStorage.setItem( + `buzz-outbox-v1:${scope}`, + JSON.stringify([ + { + event: creation, + signed: creation, + delivery: "accepted", + recovery, + }, + { event: message, signed: message, delivery: "failed" }, + ]), + ); + }, + { scope, creation, message, recovery }, + ); + let release = () => {}; + let signingStarted = false; + const held = new Promise((resolve) => { + release = resolve; + }); + await page.route("**/member-administration-sign", async (route) => { + const response = await route.fetch(); + expect(response.status()).toBe(200); + signingStarted = true; + await held; + await route.fulfill({ response }); + }); + let other; + try { + const a = await openOutbox(page, app.origin); + const row = a.getByRole("listitem").filter({ hasText: "Opening work" }); + await row.getByRole("button", { name: "Retry", exact: true }).click(); + await expect.poll(() => signingStarted).toBe(true); + if (mode !== "same-window") + await page.clock.setFixedTime(new Date((createdAt + 900) * 1000)); + other = mode === "same-window" ? page : await context.newPage(); + if (other !== page) { + app.watchPageErrors(other); + await other.clock.setFixedTime(new Date((createdAt + 900) * 1000)); + } + const b = other === page ? a : await openOutbox(other, app.origin); + const setup = b.getByRole("listitem").filter({ + hasText: "Opening agent admin setup", + }); + await expect( + setup.getByRole("button", { name: "Remove from outbox" }), + ).toHaveCount(0); + if (mode === "failed-storage") + await other.evaluate( + ({ scope, id }) => { + const remove = IDBObjectStore.prototype.delete; + IDBObjectStore.prototype.delete = function (key) { + if (Array.isArray(key) && key[0] === scope && key[1] === id) { + IDBObjectStore.prototype.delete = remove; + this.transaction.abort(); + } + return remove.call(this, key); + }; + }, + { scope, id: creation.id }, + ); + const abandon = setup.getByRole("button", { + name: "Abandon admin setup", + exact: true, + }); + await abandon.click(); + const confirmation = other.getByRole("alertdialog", { + name: "Abandon admin setup?", + }); + if (mode === "same-window") { + const cancel = confirmation.getByRole("button", { + name: "Cancel", + exact: true, + }); + await expect(cancel).toBeFocused(); + await cancel.click(); + await expect(abandon).toBeFocused(); + await abandon.click(); + } + await confirmation + .getByRole("button", { name: "Abandon admin setup", exact: true }) + .click(); + if (mode === "failed-storage") + await expect(confirmation.getByRole("alert")).toBeVisible(); + else + await expect( + b.getByRole("button", { name: "Abandon admin setup", exact: true }), + ).toHaveCount(0); + // Dismissal's UI completes only after the strict IndexedDB commit. + release(); + if (mode === "failed-storage") { + await expect + .poll( + () => + app.report.publications.filter(({ event }) => event.kind === 9) + .length, + ) + .toBe(1); + const grants = app.report.publications.filter( + ({ event }) => event.kind === 9000, + ); + expect(grants).toHaveLength(1); + expect(app.report.setupReceiverTime - grants[0].event.created_at).toBe( + 895, + ); + expect( + app.report.publications.find(({ event }) => event.kind === 9).event, + ).toEqual(message); + } else { + await expect(row).toContainText("Not sent"); + expect( + app.report.publications.filter(({ event }) => + [9000, 9].includes(event.kind), + ), + ).toEqual([]); + await expect( + row.getByRole("button", { name: "Retry", exact: true }), + ).toBeEnabled(); + if (mode === "cross-window") { + await other + .getByRole("button", { name: "Recovery chat", exact: true }) + .click(); + const composer = other.getByRole("textbox", { + name: "Message your agents", + exact: true, + }); + await composer.fill("Continue with current roles"); + await composer.press("Enter"); + await expect + .poll( + () => + app.report.publications.filter(({ event }) => event.kind === 9) + .length, + ) + .toBe(1); + expect( + app.report.publications.filter(({ event }) => event.kind === 9000), + ).toEqual([]); + const fresh = app.report.publications.find( + ({ event }) => event.kind === 9, + ).event; + expect(fresh.id).not.toBe(message.id); + expect(fresh.content).toBe("Continue with current roles"); + } + } + } finally { + release(); + await page.unrouteAll({ behavior: "wait" }); + if (other && other !== page) { + await other.unrouteAll({ behavior: "wait" }); + await other.close(); + } + } + }); diff --git a/tests/browser/solo-ownership-transfer.spec.mjs b/tests/browser/solo-ownership-transfer.spec.mjs new file mode 100644 index 0000000000..ef29b864a5 --- /dev/null +++ b/tests/browser/solo-ownership-transfer.spec.mjs @@ -0,0 +1,282 @@ +import { test, expect } from "./fixture.mjs"; +import { openPage } from "./navigation.mjs"; +import { openChannelDetails } from "./channel-details.mjs"; + +const channel = "11111111-1111-4111-8111-111111111111"; +const chat = "33333333-3333-4333-8333-333333333333"; +test.use({ + productionBroker: true, + colorScheme: "dark", + pluginFixtures: true, + openingAdminSetup: true, + channelLifecycle: true, + channelIds: [channel, chat], + channelNames: { [channel]: "Project updates", [chat]: "Recovery chat" }, + soloChannels: [chat], + ownSoloChannels: [chat], + soloAgentNames: ["First agent", "Transferring agent"], + savedCommunities: ["primary"], + historyCounts: { [channel]: 0, [chat]: 0 }, +}); + +for (const opening of [true, false]) + test(`${opening ? "opening" : "later addition"} rechecks a received ownership transfer before the next grant`, async ({ + page, + app, + }, info) => { + const createdAt = Math.floor(Date.now() / 1000); + const keys = app.soloAgents.map((agent) => agent.pubkey); + app.report.setupReceiverTime = createdAt; + const creation = app.sign({ + kind: 9007, + created_at: createdAt, + content: "", + tags: [["h", chat], ...keys.map((key) => ["p", key])], + }); + const message = app.sign({ + kind: 9, + created_at: createdAt, + content: "Opening ownership transfer", + tags: [["h", chat], ...keys.map((key) => ["p", key])], + }); + if (opening) { + app.report.setupCreation = creation; + await page.addInitScript( + ({ scope, creation, message, keys }) => { + localStorage.setItem( + `buzz-outbox-v1:${scope}`, + JSON.stringify([ + { + event: creation, + signed: creation, + delivery: "accepted", + recovery: { + key: `solo-initial-admins:${creation.tags[0][1]}`, + value: JSON.stringify(keys), + }, + }, + { event: message, signed: message, delivery: "failed" }, + ]), + ); + }, + { + scope: `https://primary.example:${app.viewer}`, + creation, + message, + keys, + }, + ); + } else { + // Model absent members, then their relay-confirmed roles. The real reader + // verifies each relay-signed roster; no client membership state is injected. + await page.route("**/api/relay/primary/query", async (route) => { + const response = await route.fetch(); + const events = await response.json(); + await route.fulfill({ + response, + json: events.map((event) => { + if ( + event.kind !== 39002 || + !event.tags.some(([tag, value]) => tag === "d" && value === chat) + ) + return event; + const tags = event.tags.filter( + ([tag, key]) => tag !== "p" || !keys.includes(key), + ); + for (const key of keys) { + const grant = app.report.publications.find( + ({ event }) => + event.kind === 9000 && + event.tags.some( + ([tag, value]) => tag === "p" && value === key, + ), + ); + if (grant) + tags.push([ + "p", + key, + "", + grant.event.tags.find(([tag]) => tag === "role")[1], + ]); + } + return app.signRelay({ + ...event, + tags, + created_at: + event.created_at + 100 + app.report.publications.length, + }); + }), + }); + }); + } + let release; + const held = new Promise((resolve) => { + release = resolve; + }); + let signingStarted = false; + await page.route("**/member-administration-sign", async (route) => { + const response = await route.fetch(); + expect(response.status()).toBe(200); + signingStarted = true; + await held; + await route.fulfill({ response }); + }); + try { + await page.goto(app.origin); + await openPage(page, "Messages"); + await page + .getByRole("button", { name: "Project updates", exact: true }) + .click(); + let outbox; + if (opening) { + await openChannelDetails(page); + const panel = page.getByRole("complementary", { + name: "Channel settings", + exact: true, + }); + await panel.getByText("Diagnostics", { exact: true }).click(); + const summary = panel + .locator("summary") + .filter({ hasText: /^Outbox ·/ }); + await summary.click(); + outbox = summary.locator(".."); + await outbox + .getByRole("listitem") + .filter({ hasText: message.content }) + .getByRole("button", { name: "Retry", exact: true }) + .click(); + } else { + await page.evaluate( + async ({ chat, keys }) => { + const session = window.fixtureRelay.snapshot().session; + await session.agentChoices.refresh("templates"); + window.ownershipAddition = "pending"; + void session.channelWrites.addAgents(chat, keys).then( + () => { + window.ownershipAddition = "complete"; + }, + (error) => { + window.ownershipAddition = String(error); + }, + ); + }, + { chat, keys }, + ); + } + await expect.poll(() => signingStarted).toBe(true); + const profile = app.transferSoloAgent(keys[1]); + await page.evaluate(async (key) => { + await window.fixtureRelay + .snapshot() + .session.read([{ kinds: [0], authors: [key], limit: 1 }], { + fresh: true, + }); + }, keys[1]); + await expect + .poll(() => + page.evaluate((key) => { + const profiles = window.fixtureRelay.snapshot().session.profiles; + return { id: profiles.event(key)?.id, owner: profiles.owner(key) }; + }, keys[1]), + ) + .toEqual({ id: profile.id, owner: profile.tags[0][1] }); + release(); + if (opening) { + await expect + .poll( + async () => + app.report.publications.some(({ event }) => event.kind === 9) || + ( + await page.evaluate( + (id) => + window.fixtureRelay + .snapshot() + .session.outbox.snapshot() + .find((item) => item.event.id === id)?.error ?? "", + message.id, + ) + ).includes("not verified as owned"), + ) + .toBe(true); + } else { + await expect + .poll(() => page.evaluate(() => window.ownershipAddition)) + .toBe("complete"); + } + const grants = app.report.publications + .filter(({ event }) => event.kind === 9000) + .map(({ event }) => ({ + key: event.tags.find(([tag]) => tag === "p")[1], + role: event.tags.find(([tag]) => tag === "role")[1], + })); + await info.attach("received-transfer-grants", { + body: JSON.stringify({ profile, grants }, null, 2), + contentType: "application/json", + }); + expect(grants).toEqual( + opening + ? [{ key: keys[0], role: "admin" }] + : [ + { key: keys[0], role: "admin" }, + { key: keys[1], role: "bot" }, + ], + ); + if (opening) { + expect( + app.report.publications.filter(({ event }) => event.kind === 9), + ).toHaveLength(0); + await expect( + outbox.getByRole("listitem").filter({ hasText: message.content }), + ).toContainText("Not sent"); + expect( + await page.evaluate( + (id) => + window.fixtureRelay + .snapshot() + .session.outbox.snapshot() + .find((item) => item.event.id === id)?.error, + message.id, + ), + ).toContain("not verified as owned"); + const setup = outbox.getByRole("listitem").filter({ + hasText: "Opening agent admin setup", + }); + await setup.screenshot({ + path: info.outputPath("OPENING_ADMIN_SETUP_OUTBOX.png"), + }); + await setup + .getByRole("button", { name: "Abandon admin setup" }) + .click(); + const confirmation = page.getByRole("alertdialog", { + name: "Abandon admin setup?", + }); + await confirmation.screenshot({ + path: info.outputPath("ABANDON_ADMIN_SETUP.png"), + }); + await confirmation + .getByRole("button", { name: "Abandon admin setup" }) + .click(); + await expect(setup).toHaveCount(0); + await outbox + .getByRole("listitem") + .filter({ hasText: message.content }) + .getByRole("button", { name: "Retry", exact: true }) + .click(); + await expect + .poll(() => + app.report.publications + .filter(({ event }) => event.kind === 9) + .map(({ event }) => event), + ) + .toEqual([message]); + expect( + app.report.publications.filter(({ event }) => event.kind === 9000), + ).toHaveLength(1); + } + await page.screenshot({ + path: info.outputPath("RECEIVED_OWNERSHIP_TRANSFER.png"), + }); + } finally { + release(); + } + });