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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crates/plugin-manager/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ pub fn bundled_manifests() -> Vec<Manifest> {
.expect("agents manifest"),
serde_json::from_str(include_str!("../../../src/bundled/workflows/manifest.json"))
.expect("workflows manifest"),
serde_json::from_str(include_str!("../../../src/bundled/sessions/manifest.json"))
.expect("sessions manifest"),
]
}
fn is_bundled(id: &str) -> bool {
Expand Down
1 change: 1 addition & 0 deletions crates/plugin-manager/tests/management.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,7 @@ fn bundled_plugins_have_independent_flags_and_all_ids_are_reserved() {
);
for id in [
"buzz.terminal",
"buzz.sessions",
"buzz.bestie",
"buzz.projects",
"buzz.agents",
Expand Down
95 changes: 92 additions & 3 deletions dev/relay-broker-api.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { test, expect, vi, beforeEach, afterEach } from "vitest";
import { finalizeEvent, getPublicKey, verifyEvent } from "nostr-tools";
import { relayBrokerPlugin } from "./relay-broker.mjs";
import { connectBrokerTransport } from "../src/features/relay/transport.ts";
import { PublishRejected } from "../src/features/relay/outbox.ts";
import { createOutbox, PublishRejected } from "../src/features/relay/outbox.ts";

// Only wall time is controlled. Real timers/performance.now still exercise HTTP pacing.
let wallClock;
Expand All @@ -18,7 +18,7 @@ beforeEach(() => {
afterEach(() => vi.restoreAllMocks());

// Real browser HTTP -> production broker. Ephemeral key; upstream I/O is entirely local.
async function harness(respond) {
async function harness(respond, capabilities = {}) {
const key = new Uint8Array(32);
key[31] = 7;
const viewer = getPublicKey(key);
Expand All @@ -36,7 +36,7 @@ async function harness(respond) {
relayUrl: fixtureRelayUrl,
communityAliases: fixtureAliases,
identity: () => key,
authority: async () => ({ relayAuthor: viewer }),
authority: async () => ({ relayAuthor: viewer, ...capabilities }),
upstreamFetch: async (url, init) => {
const upstreamUrl = String(url);
const authorization = new Headers(init?.headers).get("Authorization");
Expand Down Expand Up @@ -494,3 +494,92 @@ test("both real sign and publish routes admit direct replies but reject arbitrar
await h.close();
}
});

test.each([undefined, "22222222-2222-4222-8222-222222222222"])(
"real outbox creates, invites and sends without Sessions support (parent: %s)",
async (parent) => {
const h = await harness(
(call) =>
Response.json(
call.url.endsWith("/events")
? { accepted: true, event_id: call.body.id }
: [],
),
{ channelCreation: true },
);
let owner;
try {
const transport = await connectBrokerTransport(h.base);
expect(transport.writer.kinds).toContain(9007);
expect(transport.writer.kinds).not.toContain(9050);
owner = createOutbox(transport.viewer, transport.writer, {
load: () => [],
save: () => {},
});
const id = "11111111-1111-4111-8111-111111111111";
const creationId = owner.outbox.send({
kind: 9007,
content: "",
tags: [
["h", id],
["name", "Work"],
["visibility", "private"],
["channel_type", "stream"],
[
"about",
`Buzz session (buzz.sessions/v1)${parent ? `\nparent:${parent}` : ""}`,
],
],
});
await vi.waitFor(() =>
expect(
owner.local.snapshot().find((row) => row.event.id === creationId)
?.delivery,
).toBe("accepted"),
);
const invitationId = owner.outbox.send({
kind: 9000,
content: "",
tags: [
["h", id],
["p", "a".repeat(64)],
],
});
await vi.waitFor(() =>
expect(
owner.local.snapshot().find((row) => row.event.id === invitationId)
?.delivery,
).toBe("accepted"),
);
const messageId = owner.outbox.send({
kind: 9,
content: "Hello",
tags: [
["h", id],
["p", "a".repeat(64)],
],
});
await vi.waitFor(() =>
expect(
owner.local.snapshot().find((row) => row.event.id === messageId)
?.delivery,
).toBe("accepted"),
);
expect(
h.calls
.filter((call) => call.url.endsWith("/events"))
.map((call) => call.body.kind),
).toEqual([9007, 9000, 9]);
const denied = await h.post("sign", {
kind: 9050,
created_at: 1700000000,
content: JSON.stringify({ action: "create", title: "Work" }),
tags: [["h", id]],
});
expect(denied.status).toBe(400);
} finally {
owner?.dispose();
await h.close();
}
},
);
22 changes: 20 additions & 2 deletions dev/relay-broker.mjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { validSessionCommand } from "./session-commands.mjs";
import {
validateWorkflowEvent,
WORKFLOW_KINDS,
Expand Down Expand Up @@ -191,6 +192,8 @@ async function relayAuthority(fetch, relay) {
throw new Error("Relay did not advertise its identity");
return {
relayAuthor: author,
channelCreation:
Array.isArray(nip11.supported_nips) && nip11.supported_nips.includes(29),
...(readSnapshotCommunity(nip11.read_state_snapshot)
? { readStateCommunity: readSnapshotCommunity(nip11.read_state_snapshot) }
: {}),
Expand Down Expand Up @@ -549,7 +552,14 @@ export function relayBrokerPlugin({
viewer,
...(await getAuthority(relay)),
relayUrl: relay,
writeKinds: [7, 9, ...WORKFLOW_KINDS],
writeKinds: [
7,
9,
...WORKFLOW_KINDS,
...((await getAuthority(relay)).channelCreation
? [9000, 9007]
: []),
],
workflowReads: true,
sidebarPreferences: true,
readState: true,
Expand Down Expand Up @@ -891,7 +901,15 @@ export function relayBrokerPlugin({
const signing = route === "/api/relay/sign";
const publishing = route === "/api/relay/publish";
if (signing || publishing) {
if (![7, 9].includes(filters?.kind)) {
if ([9000, 9007].includes(filters?.kind)) {
const authority = await getAuthority(relay);
const supported = authority.channelCreation;
if (!supported || !validSessionCommand(filters))
return json(res, 400, {
error: "Session operation unavailable or invalid",
sent: false,
});
} else if (![7, 9].includes(filters?.kind)) {
try {
validateWorkflowEvent(
{ ...filters, pubkey: signing ? viewer : filters.pubkey },
Expand Down
51 changes: 51 additions & 0 deletions dev/session-commands.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { sessionMetadata } from "../src/features/sessions/metadata.ts";
// Host signing allowlist. No arbitrary kinds, roles or metadata edits.
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
export function validSessionCommand(event) {
if (
!event ||
!Number.isSafeInteger(event.created_at) ||
!Array.isArray(event.tags) ||
typeof event.content !== "string"
)
return false;
if (
!event.tags.every(
(tag) =>
Array.isArray(tag) && tag.every((value) => typeof value === "string"),
)
)
return false;
let tags = event.tags;
if ([9000, 9007].includes(event.kind) && tags.at(-1)?.[0] === "client-id") {
const clientId = tags.at(-1);
if (clientId.length !== 2 || !uuid.test(clientId[1])) return false;
tags = tags.slice(0, -1);
}
const [h, p] = tags;
if (h?.length !== 2 || h[0] !== "h" || !uuid.test(h[1])) return false;
if (event.kind === 9007) {
const expected = ["h", "name", "visibility", "channel_type", "about"];
return (
event.content === "" &&
tags.length === expected.length &&
tags.every(
(tag, index) => tag.length === 2 && tag[0] === expected[index],
) &&
!!tags[1][1].trim() &&
[...tags[1][1]].length <= 120 &&
tags[2][1] === "private" &&
tags[3][1] === "stream" &&
sessionMetadata(tags[4][1]) !== undefined
);
}
if (event.kind === 9000)
return (
event.content === "" &&
tags.length === 2 &&
p?.length === 2 &&
p[0] === "p" &&
/^[0-9a-f]{64}$/.test(p[1])
);
return false;
}
107 changes: 107 additions & 0 deletions dev/session-commands.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { expect, it } from "vitest";
import { validSessionCommand } from "./session-commands.mjs";
const id = "11111111-1111-4111-8111-111111111111";
const event = (body, tags = [["h", id]]) => ({
kind: 9050,
created_at: 1,
content: JSON.stringify(body),
tags,
});
it("rejects custom session commands", () => {
expect(validSessionCommand(event({ action: "create", title: "Work" }))).toBe(
false,
);
expect(
validSessionCommand(
event({ action: "move", parent_id: id, confirm_history: true }),
),
).toBe(false);
});
it("allows only ordinary invitations, without extra roles", () => {
const invite = {
kind: 9000,
created_at: 1,
content: "",
tags: [
["h", id],
["p", "a".repeat(64)],
],
};
expect(validSessionCommand(invite)).toBe(true);
expect(
validSessionCommand({
...invite,
tags: [...invite.tags, ["role", "admin"]],
}),
).toBe(false);
expect(validSessionCommand({ ...invite, kind: 9001 })).toBe(false);
});

it("allows only private stream creation marked for Sessions", () => {
const create = {
kind: 9007,
created_at: 1,
content: "",
tags: [
["h", id],
["name", "Work"],
["visibility", "private"],
["channel_type", "stream"],
["about", "Buzz session (buzz.sessions/v1)"],
],
};
expect(validSessionCommand(create)).toBe(true);
const child = (description) => ({
...create,
tags: create.tags.map((tag) =>
tag[0] === "about" ? ["about", description] : tag,
),
});
expect(
validSessionCommand(child(`Buzz session (buzz.sessions/v1)\nparent:${id}`)),
).toBe(true);
for (const parent of ["invalid", `${id}\nrole:owner`, `${id}extra`]) {
expect(
validSessionCommand(
child(`Buzz session (buzz.sessions/v1)\nparent:${parent}`),
),
).toBe(false);
}
for (const [index, value] of [
[2, "open"],
[3, "dm"],
[4, "arbitrary"],
[1, " "],
]) {
expect(
validSessionCommand({
...create,
tags: create.tags.map((tag, i) =>
i === index ? [tag[0], value] : tag,
),
}),
).toBe(false);
}
expect(
validSessionCommand({
...create,
tags: [...create.tags, ["p", "a".repeat(64)]],
}),
).toBe(false);
expect(validSessionCommand({ ...create, content: "extra" })).toBe(false);
});

it("accepts one trailing outbox identifier for invitations and rejects ambiguous envelopes", () => {
const invite = (tags) => ({ kind: 9000, created_at: 1, content: "", tags });
const h = ["h", id],
p = ["p", "a".repeat(64)],
client = ["client-id", id];
expect(validSessionCommand(invite([h, p, client]))).toBe(true);
for (const tags of [
[h, p, client, client],
[client, h, p],
[h, p, ["client-id", "invalid"]],
[h, p, [...client, "extra"]],
])
expect(validSessionCommand(invite(tags))).toBe(false);
});
Loading
Loading