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
114 changes: 114 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,116 @@ 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 });
// The harness signs as this fixed viewer key.
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);
// Bound to this relay's community; the shape matrix lives in
// artifact-community.test.ts.
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
34 changes: 33 additions & 1 deletion browser-host/relay-broker-live.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -1058,7 +1058,13 @@ test("production interest controls preserve socket/global routes and pending wri
});

test.each([
["restricted: not a member", true, "Relay request failed (503)"],
["restricted: not a member", true, "Not a member"],
[
"blocked: you are banned from this community",
true,
"You are banned from this community",
],
["auth-required: sign in first", true, "auth-required: sign in first"],
[
'invalid: an open channel named "Launch" already exists',
true,
Expand Down Expand Up @@ -2380,6 +2386,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
66 changes: 61 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,22 @@ export function relayBrokerPlugin({
const channelActivity = route === "/api/relay/channel-activity";
if (channelActivity && !validChannelActivityFilters(filters))
return json(res, 400, { error: "Activity filter rejected" });
// NIP-AR policy read: exactly `{type}`, sent as the relay's own filter.
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 +2988,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 +3027,20 @@ export function relayBrokerPlugin({
sent: false,
});
}
} else if (typePolicyCommand) {
try {
// Bound to the community this relay advertises; a relay
// without one gets no policy command.
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 +3211,7 @@ export function relayBrokerPlugin({
!readPublishing &&
!snapshot &&
!channelActivity &&
!typePolicyRead &&
!validFilters(filters)
)
return json(res, 400, { error: "Read filter rejected" });
Expand Down Expand Up @@ -3216,6 +3263,15 @@ export function relayBrokerPlugin({
)
)
return json(res, 400, { error: failure.reason });
// A proven authorization refusal is 403, as over HTTP, so the
// writer sees a refusal rather than an unsent publication.
if (
failure?.sent === false &&
/^(restricted|blocked|auth-required):/.test(
failure.reason ?? "",
)
)
return json(res, 403, { error: failure.reason });
return json(res, conflict ? 409 : 503, {
error:
failure?.sent === false &&
Expand Down
10 changes: 10 additions & 0 deletions docs/artifact-sync.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,13 @@ A policy change or an expired checkpoint requires a fresh query plus bounded rev
Refresh generations, schema checks, and owner cancellation fence each commit. Failed reads keep saved progress and data. Transient failures get three short retries, then a delay of 60–90 seconds. Invalid replies and capacity failures use that delay directly. Each long retry adds a fresh random delay of less than 30 seconds to the 60-second minimum. A persistent failure exposes `refreshError()`. Successful delta completion clears it. A 60-second repair runs independently of live traffic and respects a pending retry delay. A bounded set holds up to 1,000 live IDs; overflow requests another delta.

The 120-second overlap assumes bounded database delay. It does not prove recovery from every delayed commit. TTL retirement is outside this contract. Native end-to-end verification needs the compatible relay and client together.

## Community-scoped artifacts

When the relay advertises NIP-11 `artifacts.community_scope` version 1 and lists `nip-ar` in `supported_extensions`, `session.artifacts.communityId` is the community's id and `session.artifacts.typePolicy` is present. Otherwise both are absent, so a plugin can check `communityId` synchronously before it shows anything that needs community artifacts.

`session.artifacts.sync({ artifact: "current", scope: "community", "#type": [type] })` keeps one type's current community artifacts. It needs exactly one `#type` and no `#h`, and it has the same statuses as a channel sync; `restricted` also means the viewer lost access to the community. Community records are kind-45010 revisions with a `community` tag and no `h`. Plugins write them with `configArtifactWriter` and read a head with `snapshotRead`.

`typePolicy.read(type, signal)` returns `{ policy, revision }`, where `policy` is `everyone` or `admins` and `revision` is the id of the type's current kind-9034 command, or `null` when the type was never set. `typePolicy.set({ type, policy, prev }, signal)` signs one kind-9034 command for this community as the viewer and publishes it once. `prev` is `"0"` or the current revision. It resolves `{ id, ok, message }`: `message` is the relay's answer when the host keeps it, and empty after a transport failure. It rejects only when the change is malformed, signing fails or the signal aborts. It never retries; read the policy after every outcome to learn what the relay holds. The relay accepts the command only from a direct owner or admin.

The type policy acts with the viewer's authority, like the session's other administrative writers (`memberAdministration`, `channelLifecycle`): any plugin in an admin's session can change any type's write policy. Kind 9034 is signed only through this typed route, never through the artifact writer.
5 changes: 4 additions & 1 deletion src-tauri/src/relay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -941,7 +941,10 @@ pub(crate) async fn relay_http(
return Err("Agent enrollment or channel operation unavailable or invalid".into());
}
}
if matches!(kind, Some(9002 | 9008 | 9021 | 9022 | 41012 | 9035 | 9036)) {
if matches!(
kind,
Some(9002 | 9008 | 9021 | 9022 | 41012 | 9034 | 9035 | 9036)
) {
return Err("Invalid outgoing signature".into());
}
}
Expand Down
Loading
Loading