Skip to content
Closed
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
12 changes: 10 additions & 2 deletions browser-host/relay-authority.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { connectBrokerTransport } from "../src/features/relay/transport.ts";

const self = getPublicKey(generateSecretKey());
const contact = getPublicKey(generateSecretKey());
const community = "9b353519-f4fe-4757-aef4-bec6cc0ae54c";
async function harness(info, identity = generateSecretKey()) {
let handler;
const requests = [];
Expand Down Expand Up @@ -52,15 +53,22 @@ it.each([
["nip-ar", false],
[["nip-ar"], true],
])(
"offers artifact writes only with a NIP-AR advertisement: %j",
"offers artifact writes and community scope only with a NIP-AR advertisement: %j",
async (supported_extensions, supported) => {
const h = await harness(() =>
Response.json({ self, supported_extensions }),
Response.json({
self,
supported_extensions,
artifacts: { community_scope: { version: 1, community_id: community } },
}),
);
try {
const transport = await h.connect();
expect(transport.writer.kinds.includes(45010)).toBe(supported);
expect(transport.configArtifacts !== undefined).toBe(supported);
expect(transport.artifactCommunity).toBe(
supported ? community : undefined,
);
if (supported) {
const event = await transport.configArtifacts.sign(
{
Expand Down
111 changes: 111 additions & 0 deletions browser-host/relay-broker-api.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ import { createOutbox, PublishRejected } from "../src/features/relay/outbox.ts";
import { createRelaySession } from "../src/features/relay/session.ts";
import { feedbackEvent } from "../src/features/relay/product-feedback.ts";
import { archiveRequestTemplate } from "../src/features/relay/identity-archive-protocol.ts";
import {
ARTIFACT_TYPE_POLICY_KIND,
typePolicyTemplate,
} from "../src/features/relay/artifact-community.ts";

// Only wall time is controlled. Real timers/performance.now still exercise HTTP admission.
let wallClock;
Expand Down Expand Up @@ -3523,6 +3527,113 @@ test("identity archive requests use dedicated exact-shape routes behind archive
}
});

test("type policy commands use dedicated exact-shape routes for the relay's own community", async () => {
const community = "9b353519-f4fe-4757-aef4-bec6cc0ae54c";
const template = typePolicyTemplate(
community,
"example.settings",
"admins",
"0",
Math.floor(Date.now() / 1000),
);
const respond = () => Response.json([]);
const unavailable = await harness(respond);
try {
expect(
(await unavailable.post("artifact-type-policy-sign", template)).status,
).toBe(400);
} finally {
await unavailable.close();
}
const h = await harness(respond, { artifactCommunity: community });
const viewerKey = Uint8Array.from({ length: 32 }, (_, i) =>
i === 31 ? 7 : 0,
);
let live;
try {
const transport = await connectBrokerTransport(h.base);
expect(transport.writer.kinds).not.toContain(ARTIFACT_TYPE_POLICY_KIND);
const other = {
...template,
tags: [
["community", "11111111-1111-4111-8111-111111111111"],
...template.tags.slice(1),
],
};
expect((await h.post("artifact-type-policy-sign", other)).status).toBe(400);
expect(
(
await h.post(
"artifact-type-policy-publish",
finalizeEvent(other, viewerKey),
)
).status,
).toBe(400);
const signal = new AbortController().signal;
expect((await h.post("sign", template)).status).toBe(400);
live = await openBrokerSocket(transport);
const result = await transport.artifactTypePolicy.set(
{ type: "example.settings", policy: "admins", prev: "0" },
signal,
);
const [signed] = h.publications;
expect(result).toEqual({ id: signed.id, ok: true, message: "" });
expect(verifyEvent(signed)).toBe(true);
const { kind, content, tags } = template;
expect(signed).toMatchObject({ kind, content, tags });
expect((await h.post("publish", signed)).status).toBe(400);
const foreign = finalizeEvent(
{ ...template, tags: template.tags.map((tag) => [...tag]) },
new Uint8Array(32).fill(5),
);
expect((await h.post("artifact-type-policy-publish", foreign)).status).toBe(
400,
);
expect(h.publications).toHaveLength(1);
} finally {
live?.dispose();
await h.close();
}
});

test("the type policy read sends one exact type as the relay's policy filter", async () => {
const community = "9b353519-f4fe-4757-aef4-bec6cc0ae54c";
const revision = "e".repeat(64);
const h = await harness(() => Response.json({ policy: "admins", revision }), {
artifactCommunity: community,
});
try {
for (const body of [
{ type: "example.settings", kinds: [45010] },
{ type: ["example.settings"] },
[{ type: "example.settings" }],
{ type: "Example.Settings" },
])
expect((await h.post("artifact-type-policy", body)).status).toBe(400);
expect(h.calls).toEqual([]);
const transport = await connectBrokerTransport(h.base);
await expect(
transport.artifactTypePolicy.read(
"example.settings",
new AbortController().signal,
),
).resolves.toEqual({ policy: "admins", revision });
expect(h.calls).toHaveLength(1);
expect(h.calls[0]).toMatchObject({
url: `${fixtureRelayUrl}/query`,
body: [
{
artifact: "policy",
scope: "community",
"#type": ["example.settings"],
},
],
});
} finally {
await h.close();
}
});

test("lifecycle uses dedicated shape-limited host routes, never the message writer", async () => {
const h = await harness((call) =>
Response.json(
Expand Down
69 changes: 69 additions & 0 deletions browser-host/relay-broker-live.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ async function harness(
authority: async () => ({
relayAuthor: getPublicKey(key),
artifactSupport: true,
...options.authority,
}),
upstreamFetch: async (url, init) => {
upstream.push(String(url));
Expand Down Expand Up @@ -1059,6 +1060,12 @@ test("production interest controls preserve socket/global routes and pending wri

test.each([
["restricted: not a member", true, "Relay request failed (503)"],
[
"blocked: you are banned from this community",
true,
"Relay request failed (503)",
],
["auth-required: sign in first", true, "Relay request failed (503)"],
[
'invalid: an open channel named "Launch" already exists',
true,
Expand Down Expand Up @@ -1118,6 +1125,42 @@ test.each([
},
);

test.each([
["restricted: only owners and admins may set it", false],
["auth-required: sign in first", true],
])(
"a type policy command refused with %s returns the reason only when final",
async (reason, unsent) => {
const community = "9b353519-f4fe-4757-aef4-bec6cc0ae54c";
const h = await harness(0, undefined, {
authority: { artifactCommunity: community },
});
let traffic;
try {
browserFetch(h.base);
const transport = await connectBrokerTransport(h.base);
traffic = transport.subscribe(callbacks);
await until(() => h.requests.length >= 1);
const result = transport.artifactTypePolicy.set(
{ type: "example.settings", policy: "admins", prev: "0" },
new AbortController().signal,
);
await until(() => h.publications.length === 1);
const [{ event }] = h.publications;
await h.sockets[0].receive(["OK", event.id, false, reason]);
expect(await result).toEqual({
id: event.id,
ok: false,
message: unsent ? "" : reason,
});
} finally {
traffic?.dispose();
vi.unstubAllGlobals();
await h.close();
}
},
);

test("lost publication receipt stays unknown; reconnect never automatically republishes", async () => {
const h = await harness();
let traffic;
Expand Down Expand Up @@ -2380,6 +2423,32 @@ test("a sync close that overtakes its open keeps the late open from taking a hos
}
});

test("a community artifact sync reaches the relay exactly as requested", async () => {
const h = await harness();
const filter = {
artifact: "current",
scope: "community",
"#type": ["example.settings"],
};
try {
const stream = await h.post(["a"]);
const streamId = stream.response.headers.get("x-buzz-live-id");
await until(() => h.requests.length === 3);
const open = await fetch(`${h.base}/api/relay/stream-artifact-sync`, {
method: "POST",
headers: { Origin: h.base, "Content-Type": "application/json" },
body: JSON.stringify({ streamId, id: "s1", filter }),
});
expect(open.status).toBe(200);
await open.text();
await until(() => h.requests.length === 4);
expect(h.requests[3].filters).toEqual([filter]);
stream.abort();
} finally {
await h.close();
}
});

test("a stream admits as many syncs as the session does", async () => {
const h = await harness();
const filter = {
Expand Down
60 changes: 55 additions & 5 deletions browser-host/relay-broker.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,11 @@ import {
ARTIFACT_SYNC_MAX_VIEWS,
artifactSyncFilter,
} from "../src/features/relay/artifact-sync-filter.ts";
import {
communityScope,
typePolicyFilter,
validTypePolicy,
} from "../src/features/relay/artifact-community.ts";
import {
assertSidebarStarIntent,
mutateSidebarStar,
Expand Down Expand Up @@ -331,6 +336,10 @@ async function relayAuthority(fetch, relay) {
const author = nip11.self ?? nip11.pubkey;
if (typeof author !== "string" || !/^[0-9a-f]{64}$/.test(author))
throw new Error("Relay did not advertise its identity");
const artifactSupport =
Array.isArray(nip11.supported_extensions) &&
nip11.supported_extensions.includes("nip-ar");
const artifactCommunity = communityScope(nip11.artifacts, artifactSupport);
return {
relayAuthor: author,
channelCreation:
Expand All @@ -341,9 +350,8 @@ async function relayAuthority(fetch, relay) {
nip11.supported_extensions.includes("nip-cl"),
// NIP-AR sync: REQ with `"artifact": "current"` keeps a set current.
artifactSync: nip11.artifacts?.sync?.version === 1,
artifactSupport:
Array.isArray(nip11.supported_extensions) &&
nip11.supported_extensions.includes("nip-ar"),
artifactSupport,
...(artifactCommunity ? { artifactCommunity } : {}),
// Bridge search accepts `search_sort: "newest"`.
searchSort:
Array.isArray(nip11.supported_extensions) &&
Expand Down Expand Up @@ -2459,6 +2467,9 @@ export function relayBrokerPlugin({
"/api/relay/channel-lifecycle-publish",
"/api/relay/identity-archive-sign",
"/api/relay/identity-archive-publish",
"/api/relay/artifact-type-policy",
"/api/relay/artifact-type-policy-sign",
"/api/relay/artifact-type-policy-publish",
"/api/relay/publish",
"/api/relay/read-state-sign",
"/api/relay/channel-kit-prepare",
Expand Down Expand Up @@ -2768,6 +2779,21 @@ export function relayBrokerPlugin({
const channelActivity = route === "/api/relay/channel-activity";
if (channelActivity && !validChannelActivityFilters(filters))
return json(res, 400, { error: "Activity filter rejected" });
const typePolicyRead = route === "/api/relay/artifact-type-policy";
if (typePolicyRead) {
try {
if (
typeof filters?.type !== "string" ||
Object.keys(filters).length !== 1
)
throw new Error("Invalid artifact type policy read");
filters = [typePolicyFilter(filters.type)];
} catch {
return json(res, 400, {
error: "Invalid artifact type policy read",
});
}
}
const profile = route === "/api/relay/profile";
const directMessage = route === "/api/relay/direct-message";
if (directMessage) {
Expand Down Expand Up @@ -2961,18 +2987,23 @@ export function relayBrokerPlugin({
const archive =
route === "/api/relay/identity-archive-sign" ||
route === "/api/relay/identity-archive-publish";
const typePolicyCommand =
route === "/api/relay/artifact-type-policy-sign" ||
route === "/api/relay/artifact-type-policy-publish";
const signing =
route === "/api/relay/sign" ||
route === "/api/relay/channel-details-sign" ||
route === "/api/relay/member-administration-sign" ||
route === "/api/relay/channel-lifecycle-sign" ||
route === "/api/relay/identity-archive-sign";
route === "/api/relay/identity-archive-sign" ||
route === "/api/relay/artifact-type-policy-sign";
const publishing =
route === "/api/relay/publish" ||
route === "/api/relay/channel-details-publish" ||
route === "/api/relay/member-administration-publish" ||
route === "/api/relay/channel-lifecycle-publish" ||
route === "/api/relay/identity-archive-publish";
route === "/api/relay/identity-archive-publish" ||
route === "/api/relay/artifact-type-policy-publish";
if (signing || publishing) {
if (administration) {
try {
Expand All @@ -2995,6 +3026,18 @@ export function relayBrokerPlugin({
sent: false,
});
}
} else if (typePolicyCommand) {
try {
validTypePolicy(
filters,
(await getAuthority(relay)).artifactCommunity,
);
} catch {
return json(res, 400, {
error: "Invalid artifact type policy command",
sent: false,
});
}
} else if (details) {
try {
validateDetailsTemplate(filters);
Expand Down Expand Up @@ -3165,6 +3208,7 @@ export function relayBrokerPlugin({
!readPublishing &&
!snapshot &&
!channelActivity &&
!typePolicyRead &&
!validFilters(filters)
)
return json(res, 400, { error: "Read filter rejected" });
Expand Down Expand Up @@ -3216,6 +3260,12 @@ export function relayBrokerPlugin({
)
)
return json(res, 400, { error: failure.reason });
if (
Comment thread
LordMelkor marked this conversation as resolved.
Resolved
typePolicyCommand &&
failure?.sent === false &&
/^(restricted|blocked):/.test(failure.reason ?? "")
)
return json(res, 403, { error: failure.reason });
return json(res, conflict ? 409 : 503, {
error:
failure?.sent === false &&
Expand Down
Loading
Loading