diff --git a/browser-host/relay-authority.test.mjs b/browser-host/relay-authority.test.mjs index f2a1905fd0..deebe4915c 100644 --- a/browser-host/relay-authority.test.mjs +++ b/browser-host/relay-authority.test.mjs @@ -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 = []; @@ -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( { diff --git a/browser-host/relay-broker-api.test.mjs b/browser-host/relay-broker-api.test.mjs index 2d8483ce02..e89ad5485a 100644 --- a/browser-host/relay-broker-api.test.mjs +++ b/browser-host/relay-broker-api.test.mjs @@ -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; @@ -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( diff --git a/browser-host/relay-broker-live.test.mjs b/browser-host/relay-broker-live.test.mjs index 78d478ee43..8aa89be1f7 100644 --- a/browser-host/relay-broker-live.test.mjs +++ b/browser-host/relay-broker-live.test.mjs @@ -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, @@ -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 = { diff --git a/browser-host/relay-broker.mjs b/browser-host/relay-broker.mjs index e94a0442d4..92401ba6b8 100644 --- a/browser-host/relay-broker.mjs +++ b/browser-host/relay-broker.mjs @@ -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, @@ -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: @@ -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) && @@ -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", @@ -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) { @@ -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 { @@ -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); @@ -3165,6 +3211,7 @@ export function relayBrokerPlugin({ !readPublishing && !snapshot && !channelActivity && + !typePolicyRead && !validFilters(filters) ) return json(res, 400, { error: "Read filter rejected" }); @@ -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 && diff --git a/docs/artifact-sync.md b/docs/artifact-sync.md index 8a8e0709c7..a659e1a6c7 100644 --- a/docs/artifact-sync.md +++ b/docs/artifact-sync.md @@ -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. diff --git a/src-tauri/src/relay.rs b/src-tauri/src/relay.rs index e5b0d66447..51a1b60802 100644 --- a/src-tauri/src/relay.rs +++ b/src-tauri/src/relay.rs @@ -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()); } } diff --git a/src-tauri/src/relay/channel_writes.rs b/src-tauri/src/relay/channel_writes.rs index 77ddd5c1bd..f9b0927972 100644 --- a/src-tauri/src/relay/channel_writes.rs +++ b/src-tauri/src/relay/channel_writes.rs @@ -137,6 +137,31 @@ fn member_administration(event: &EventTemplate) -> bool { && (event.kind == 9001 || matches!(tag(event, 2, "role"), Some("admin" | "member" | "guest"))))) } +/// NIP-AR SET_ARTIFACT_TYPE_POLICY: `community`, `type`, `policy` and `prev`, +/// in that order, with empty content. +fn type_policy(event: &EventTemplate) -> bool { + event.kind == 9034 + && event.content.is_empty() + && event.created_at <= 9_007_199_254_740_991 + && event.tags.len() == 4 + && tag(event, 0, "community") + .is_some_and(|id| uuid(id) && id != "00000000-0000-0000-0000-000000000000") + && tag(event, 1, "type").is_some_and(artifact_type) + && matches!(tag(event, 2, "policy"), Some("everyone" | "admins")) + && tag(event, 3, "prev").is_some_and(|prev| prev == "0" || super::hex_key(prev)) +} +/// The relay's namespaced type: at most 128 bytes, two or more dot-separated +/// segments of `[a-z][a-z0-9_-]*`. +fn artifact_type(value: &str) -> bool { + value.len() <= 128 + && value.contains('.') + && value.split('.').all(|segment| { + segment.starts_with(|c: char| c.is_ascii_lowercase()) + && segment + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'-') + }) +} /// The stepping-down owner of `[h, ["p", heir, "owner"], ["p", owner, "admin"]]`. fn ownership_transfer(event: &EventTemplate) -> Option<&str> { let [_, heir, owner] = event.tags.as_slice() else { @@ -155,6 +180,7 @@ fn member_signer_mismatch(event: &EventTemplate, viewer: &str) -> bool { } fn valid(route: &str, event: &EventTemplate) -> bool { match route { + "artifact-type-policy" => type_policy(event), "channel-details" => details(event), "channel-lifecycle" => lifecycle(event), "identity-archive" => archive(event), @@ -252,6 +278,77 @@ mod tests { event.tags[1][1] = "#C".into(); assert!(!valid("channel-details", &event)); } + + #[test] + fn type_policy_signs_only_the_exact_command() { + let command = |tags: [[&str; 2]; 4]| EventTemplate { + kind: 9034, + created_at: 9_007_199_254_740_991, + content: String::new(), + tags: tags + .iter() + .map(|t| t.iter().map(|v| v.to_string()).collect()) + .collect(), + }; + let community = "9b353519-f4fe-4757-aef4-bec6cc0ae54c"; + let longest = format!("a.{}", "b".repeat(126)); + let prev = "a".repeat(64); + let base = [ + ["community", community], + ["type", longest.as_str()], + ["policy", "admins"], + ["prev", prev.as_str()], + ]; + assert!(valid("artifact-type-policy", &command(base))); + let mut unset = base; + unset[2][1] = "everyone"; + unset[3][1] = "0"; + assert!(valid("artifact-type-policy", &command(unset))); + for value in ["a1.b_c-d", "com.example.settings.item"] { + let mut tags = base; + tags[1][1] = value; + assert!(valid("artifact-type-policy", &command(tags)), "{value}"); + } + + let too_long = format!("a.{}", "b".repeat(127)); + let upper_prev = "A".repeat(64); + let upper_community = community.to_uppercase(); + for (index, value) in [ + (0, "00000000-0000-0000-0000-000000000000"), + (0, upper_community.as_str()), + (1, too_long.as_str()), + (1, "nodot"), + (1, "Com.example"), + (1, "com.1example"), + (1, "com..example"), + (1, ".com.example"), + (1, "com.example."), + (1, "com.exAmple"), + (1, "com.ex!ample"), + (2, "owners"), + (3, upper_prev.as_str()), + (3, "1"), + ] { + let mut tags = base; + tags[index][1] = value; + assert!(!valid("artifact-type-policy", &command(tags)), "{value}"); + } + let mut swapped = base; + swapped.swap(0, 1); + let mut extra = command(base); + extra.tags.push(vec!["h".into(), community.into()]); + let mut wide = command(base); + wide.tags[3].push("relay".into()); + let mut content = command(base); + content.content = "{}".into(); + let mut late = command(base); + late.created_at += 1; + let mut kind = command(base); + kind.kind = 9035; + for event in [command(swapped), extra, wide, content, late, kind] { + assert!(!valid("artifact-type-policy", &event), "{:?}", event.tags); + } + } } #[tauri::command] diff --git a/src-tauri/src/relay/tests.rs b/src-tauri/src/relay/tests.rs index e9ab7c2daf..255ea3e115 100644 --- a/src-tauri/src/relay/tests.rs +++ b/src-tauri/src/relay/tests.rs @@ -959,6 +959,73 @@ fn managed_agent_registration_signs_as_owner_through_existing_ipc() { verify(®istered); } +#[test] +fn type_policy_commands_are_signed_and_sent_only_through_their_typed_route() { + use tauri::test::{get_ipc_response, mock_builder, INVOKE_KEY}; + let app = mock_builder() + .manage(IdentityHost::fixture()) + .manage(FederatedIdentity::new().unwrap()) + .invoke_handler(crate::commands()) + .build(crate::app_context()) + .unwrap(); + let view = tauri::WebviewWindowBuilder::new(&app, "main", tauri::WebviewUrl::default()) + .build() + .unwrap(); + let invoke = |cmd: &str, body: serde_json::Value| { + get_ipc_response( + &view, + tauri::webview::InvokeRequest { + cmd: cmd.into(), + callback: tauri::ipc::CallbackFn(0), + error: tauri::ipc::CallbackFn(1), + url: view.url().unwrap(), + body: tauri::ipc::InvokeBody::Json(body), + headers: Default::default(), + invoke_key: INVOKE_KEY.into(), + }, + ) + .map(|body| body.deserialize::().unwrap()) + }; + let command = serde_json::json!({ + "kind": 9034, "created_at": 123, "content": "", + "tags": [ + ["community", "9b353519-f4fe-4757-aef4-bec6cc0ae54c"], + ["type", "com.example.groups.group"], ["policy", "admins"], ["prev", "0"] + ] + }); + let signed = invoke( + "relay_channel_sign", + serde_json::json!({ + "community": "https://relay.test", "route": "artifact-type-policy", "event": command + }), + ) + .unwrap(); + verify(&signed); + for field in ["kind", "created_at", "tags", "content"] { + assert_eq!(signed[field], command[field]); + } + // The generic signer also backs artifact saves, which must never set a policy. + assert_eq!( + invoke( + "relay_sign", + serde_json::json!({"community": "https://relay.test", "event": command}), + ) + .unwrap_err(), + serde_json::json!("This event is not supported by the packaged relay connection") + ); + assert_eq!( + invoke( + "relay_http", + serde_json::json!({ + "community": "https://relay.test", "path": "/events", "method": "POST", + "body": signed.to_string() + }), + ) + .unwrap_err(), + serde_json::json!("Invalid outgoing signature") + ); +} + #[tokio::test] async fn signing_is_verifiable_and_does_not_export_a_key() { let event = IdentityHost::fixture() diff --git a/src/features/relay/artifact-community.test.ts b/src/features/relay/artifact-community.test.ts new file mode 100644 index 0000000000..38149e21c8 --- /dev/null +++ b/src/features/relay/artifact-community.test.ts @@ -0,0 +1,163 @@ +import { describe, expect, it } from "vitest"; +import { + artifactTypeName, + communityScope, + parseTypePolicy, + typePolicyFilter, + typePolicyTemplate, + validTypePolicy, +} from "./artifact-community"; + +const C = "9b353519-f4fe-4757-aef4-bec6cc0ae54c"; +const T = "com.example.groups.group"; +const ID = "a".repeat(64); +// NIP-AR kind 9034: empty content, exactly these four tags. +const command = { + kind: 9034, + created_at: 1_700_000_000, + content: "", + tags: [ + ["community", C], + ["type", T], + ["policy", "admins"], + ["prev", ID], + ], +}; + +describe("communityScope", () => { + const scope = (community_id: unknown, version: unknown = 1) => ({ + community_scope: { version, community_id, max_policies: 64 }, + }); + + it("accepts version 1 with a canonical community only when nip-ar is listed", () => { + expect(communityScope(scope(C), true)).toBe(C); + expect(communityScope(scope(C), false)).toBeUndefined(); + }); + + it.each([ + ["uppercase", scope(C.toUpperCase())], + ["nil", scope("00000000-0000-0000-0000-000000000000")], + ["version 2", scope(C, 2)], + ["missing id", scope(undefined)], + ["no community_scope", { sync: { version: 1 } }], + ["no artifacts", undefined], + ])("refuses %s", (_name, artifacts) => { + expect(communityScope(artifacts, true)).toBeUndefined(); + }); +}); + +describe("artifactTypeName", () => { + it.each([ + [T, true], + ["a.b", true], + ["a1.b_c-d", true], + [`a.${"b".repeat(126)}`, true], + [`a.${"b".repeat(127)}`, false], + ["nodot", false], + ["Com.example", false], + ["com.1example", false], + ["com..example", false], + [".com.example", false], + ["com.example.", false], + ])("%s is %s", (type, valid) => { + expect(artifactTypeName(type)).toBe(valid); + }); +}); + +describe("type policy command", () => { + it("builds exactly the four tags in order", () => { + expect(typePolicyTemplate(C, T, "admins", ID, 1_700_000_000)).toEqual( + command, + ); + expect(() => validTypePolicy(command, C)).not.toThrow(); + const unset = { + ...command, + tags: [...command.tags.slice(0, 3), ["prev", "0"]], + }; + expect(() => validTypePolicy(unset, C)).not.toThrow(); + }); + + it("refuses a malformed type, policy or prev before signing", () => { + expect(() => typePolicyTemplate(C, "Bad", "admins", "0", 1)).toThrow(); + expect(() => + typePolicyTemplate(C, T, "owners" as "admins", "0", 1), + ).toThrow(); + expect(() => typePolicyTemplate(C, T, "admins", "1", 1)).toThrow(); + }); + + const tags = command.tags; + it.each([ + [ + "another community", + { ...command }, + "11111111-1111-4111-8111-111111111111", + ], + ["no community at all", { ...command }, undefined], + ["an extra tag", { ...command, tags: [...tags, ["h", C]] }, C], + [ + "an h tag instead of community", + { ...command, tags: [["h", C], ...tags.slice(1)] }, + C, + ], + ["non-empty content", { ...command, content: "{}" }, C], + ["another kind", { ...command, kind: 45010 }, C], + [ + "the wrong order", + { ...command, tags: [tags[1], tags[0], tags[2], tags[3]] }, + C, + ], + [ + "uppercase prev", + { ...command, tags: [...tags.slice(0, 3), ["prev", ID.toUpperCase()]] }, + C, + ], + [ + "a three-element tag", + { ...command, tags: [...tags.slice(0, 3), ["prev", ID, "x"]] }, + C, + ], + [ + "a non-string prev", + { ...command, tags: [...tags.slice(0, 3), ["prev", [ID]]] }, + C, + ], + ["an unsafe created_at", { ...command, created_at: 2 ** 53 }, C], + ])("refuses %s", (_name, event, community) => { + expect(() => + validTypePolicy(event as typeof command, community as string), + ).toThrow("Invalid artifact type policy command"); + }); +}); + +describe("type policy read", () => { + it("is exactly the relay's policy filter", () => { + expect(typePolicyFilter(T)).toEqual({ + artifact: "policy", + scope: "community", + "#type": [T], + }); + expect(() => typePolicyFilter("nodot")).toThrow(); + }); + + it("parses the relay's answer", () => { + expect(parseTypePolicy({ policy: "everyone", revision: null })).toEqual({ + policy: "everyone", + revision: null, + }); + expect(parseTypePolicy({ policy: "admins", revision: ID })).toEqual({ + policy: "admins", + revision: ID, + }); + }); + + it.each([ + [[{ policy: "everyone", revision: null }]], + [{ policy: "owners", revision: null }], + [{ policy: "admins" }], + [{ policy: "admins", revision: "0" }], + [{ policy: "admins", revision: ID.toUpperCase() }], + [null], + ])("refuses %j", (body) => { + expect(() => parseTypePolicy(body)).toThrow("Invalid artifact type policy"); + }); +}); diff --git a/src/features/relay/artifact-community.ts b/src/features/relay/artifact-community.ts new file mode 100644 index 0000000000..590913523e --- /dev/null +++ b/src/features/relay/artifact-community.ts @@ -0,0 +1,145 @@ +import type { EventTemplate } from "nostr-tools"; + +// Wire contract only: no imports beyond types, so the browser broker can load it. +// NIP-AR community-scoped artifacts (docs/nips/NIP-AR.md "Community-scoped +// artifacts" in block/buzz). + +/** SET_ARTIFACT_TYPE_POLICY: an owner or admin sets who may write one type. */ +export const ARTIFACT_TYPE_POLICY_KIND = 9034; +export type ArtifactTypePolicyValue = "everyone" | "admins"; +/** `revision` is the id of the type's current 9034 command, or null when the + * type was never set. */ +export type ArtifactTypePolicyState = Readonly<{ + policy: ArtifactTypePolicyValue; + revision: string | null; +}>; +/** What the host offers a plugin for a community's per-type write policy. */ +export type ArtifactTypePolicyAccess = Readonly<{ + read(type: string, signal: AbortSignal): Promise; + /** Signs (filling community and created_at) and publishes once. Resolves + * with the command id and the relay's answer; a transport failure resolves + * ok:false with an empty message. Rejects only on a malformed change, a + * signing failure or an aborted signal. */ + set( + change: Readonly<{ + type: string; + policy: ArtifactTypePolicyValue; + prev: string; + }>, + signal: AbortSignal, + ): Promise>; +}>; + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; +const EVENT_ID = /^[0-9a-f]{64}$/; + +export const artifactCommunityId = (value: unknown): value is string => + typeof value === "string" && + UUID.test(value) && + value !== "00000000-0000-0000-0000-000000000000"; + +/** The relay's type grammar (buzz-core artifact.rs): at most 128 bytes, two or + * more dot-separated segments of `[a-z][a-z0-9_-]*`. */ +export const artifactTypeName = (type: string): boolean => + type.length <= 128 && /^[a-z][a-z0-9_-]*(\.[a-z][a-z0-9_-]*)+$/.test(type); + +/** The community from NIP-11 `artifacts.community_scope` version 1, only when + * `supported_extensions` lists `nip-ar`. */ +export function communityScope( + artifacts: unknown, + nipAr: boolean, +): string | undefined { + const scope = ( + artifacts as { + community_scope?: { version?: unknown; community_id?: unknown }; + } | null + )?.community_scope; + return nipAr && + scope?.version === 1 && + artifactCommunityId(scope.community_id) + ? scope.community_id + : undefined; +} + +/** The 9034 command the host signs. `now` is Unix seconds. Throws on a + * malformed community, type, policy or `prev` before anything is signed. */ +export function typePolicyTemplate( + community: string, + type: string, + policy: ArtifactTypePolicyValue, + prev: string, + now: number, +): EventTemplate { + const event = { + kind: ARTIFACT_TYPE_POLICY_KIND, + created_at: now, + content: "", + tags: [ + ["community", community], + ["type", type], + ["policy", policy], + ["prev", prev], + ], + }; + validTypePolicy(event, community); + return event; +} + +const tagValue = (tag: unknown, name: string): string | undefined => + Array.isArray(tag) && + tag.length === 2 && + tag[0] === name && + typeof tag[1] === "string" + ? tag[1] + : undefined; + +/** Hosts sign only this exact shape: empty content and the four two-element + * tags in order, for `community`. `prev` is "0" or a lowercase event id. */ +export function validTypePolicy(event: EventTemplate, community: string): void { + const [scope, type, policy, prev, ...extra] = Array.isArray(event?.tags) + ? event.tags + : []; + const name = tagValue(type, "type"); + const expected = tagValue(prev, "prev"); + if ( + !event || + event.kind !== ARTIFACT_TYPE_POLICY_KIND || + event.content !== "" || + !Number.isSafeInteger(event.created_at) || + event.created_at < 0 || + extra.length || + !artifactCommunityId(community) || + tagValue(scope, "community") !== community || + name === undefined || + !artifactTypeName(name) || + !["everyone", "admins"].includes(tagValue(policy, "policy") ?? "") || + expected === undefined || + (expected !== "0" && !EVENT_ID.test(expected)) + ) + throw new Error("Invalid artifact type policy command"); +} + +/** The policy read, sent as `[filter]` to `/query`. Throws on a malformed type. */ +export function typePolicyFilter(type: string): { + artifact: "policy"; + scope: "community"; + "#type": [string]; +} { + if (!artifactTypeName(type)) throw new Error("Invalid artifact type"); + return { artifact: "policy", scope: "community", "#type": [type] }; +} + +/** The relay's `{policy, revision}` answer to `typePolicyFilter`. Throws on + * anything else. */ +export function parseTypePolicy(body: unknown): ArtifactTypePolicyState { + const { policy, revision } = ( + body && typeof body === "object" && !Array.isArray(body) ? body : {} + ) as { policy?: unknown; revision?: unknown }; + if ( + (policy !== "everyone" && policy !== "admins") || + (revision !== null && + (typeof revision !== "string" || !EVENT_ID.test(revision))) + ) + throw new Error("Invalid artifact type policy"); + return Object.freeze({ policy, revision }); +} diff --git a/src/features/relay/artifact-sync-filter.ts b/src/features/relay/artifact-sync-filter.ts index d9a8a634cc..de4d4dedad 100644 --- a/src/features/relay/artifact-sync-filter.ts +++ b/src/features/relay/artifact-sync-filter.ts @@ -1,14 +1,28 @@ import type { VerifiedEvent } from "nostr-tools"; +import { artifactTypeName } from "./artifact-community.ts"; -// Wire contract only: no imports beyond types, so the browser broker can load it. +// Wire contract only: no imports beyond types and other wire contracts, so the +// browser broker can load it. /** NIP-AR sync (docs/nips/NIP-AR.md "Sync" in block/buzz): a REQ with one - * `"artifact": "current"` filter. `#h` is required; paging keys are refused. */ -export type ArtifactSyncFilter = Readonly<{ - artifact: "current"; - kinds?: readonly [45010]; - "#h": readonly string[]; - [tag: `#${string}`]: readonly string[] | undefined; -}>; + * `"artifact": "current"` filter. A channel sync needs `#h`; a community sync + * (`"scope": "community"`) needs exactly one `#type` and no `#h`. Paging keys + * are refused. */ +export type ArtifactSyncFilter = + | Readonly<{ + artifact: "current"; + kinds?: readonly [45010]; + scope?: never; + "#h": readonly string[]; + [tag: `#${string}`]: readonly string[] | undefined; + }> + | Readonly<{ + artifact: "current"; + kinds?: readonly [45010]; + scope: "community"; + "#type": readonly [string]; + "#h"?: never; + [tag: `#${string}`]: readonly string[] | undefined; + }>; export const ARTIFACT_REVISION_KIND = 45010; export const ARTIFACT_REMOVAL_KIND = 45011; @@ -55,6 +69,10 @@ export function artifactSyncFilter(input: unknown): ArtifactSyncFilter { ) throw new Error("Artifact sync kinds must be [45010]"); out.kinds = [ARTIFACT_REVISION_KIND]; + } else if (name === "scope") { + if (value !== "community") + throw new Error('Artifact sync accepts only "scope": "community"'); + out.scope = value; } else if (/^#[A-Za-z0-9_.:-]{1,64}$/.test(name)) { if ( !Array.isArray(value) || @@ -75,9 +93,14 @@ export function artifactSyncFilter(input: unknown): ArtifactSyncFilter { if (out.artifact !== "current") throw new Error('Artifact sync needs "artifact": "current"'); const channels = out["#h"]; - if (!Array.isArray(channels) || !channels.length) + if (out.scope) { + if (channels || (out["#type"] as string[] | undefined)?.length !== 1) + throw new Error("Community artifact sync needs one #type and no #h"); + if (!artifactTypeName((out["#type"] as [string])[0])) + throw new Error("Invalid artifact sync tag values for #type"); + } else if (!Array.isArray(channels) || !channels.length) throw new Error("Artifact sync needs #h with at least one channel"); - if (channels.length > ARTIFACT_SYNC_MAX_CHANNELS) + else if (channels.length > ARTIFACT_SYNC_MAX_CHANNELS) throw new Error( `Artifact sync accepts at most ${ARTIFACT_SYNC_MAX_CHANNELS} channels`, ); diff --git a/src/features/relay/artifact-sync.session.test.ts b/src/features/relay/artifact-sync.session.test.ts index 38bc8a5d59..9c95eb21a4 100644 --- a/src/features/relay/artifact-sync.session.test.ts +++ b/src/features/relay/artifact-sync.session.test.ts @@ -3,6 +3,7 @@ import { createRelaySession } from "./session"; import type { RelayEvent } from "./events"; import { keypair, roster, scriptedTransport, signed } from "./testing"; import type { ArtifactSyncSink } from "./artifact-sync"; +import type { ReadTransport } from "./transport"; const viewer = keypair(), relay = keypair(); @@ -14,7 +15,7 @@ afterEach(() => { const C1 = "11111111-1111-4111-8111-111111111111"; const filter = { artifact: "current", "#h": [C1] }; -function harness(artifactSync: boolean) { +function harness(artifactSync: boolean, host: Partial = {}) { const wire = scriptedTransport(viewer.pubkey, relay.pubkey); const sinks: ArtifactSyncSink[] = []; const closes = vi.fn(); @@ -27,6 +28,7 @@ function harness(artifactSync: boolean) { ...wire.transport, scope: "https://one.example", ...(artifactSync ? { artifactSync: true as const } : {}), + ...host, subscribe(callbacks) { incoming = callbacks.receive; callbacks.state({ status: "connected", routes: [] }); @@ -228,6 +230,27 @@ it("cancels the pending retry when a listener restarts the view", async () => { expect(h.closes).toHaveBeenCalledOnce(); }); +const COMMUNITY = "9b353519-f4fe-4757-aef4-bec6cc0ae54c"; + +it.each([ + ["no community scope", {}], + ["a community without a policy route", { artifactCommunity: COMMUNITY }], +])("offers no community or type policy with %s", (_, host) => { + const { artifacts } = harness(false, host).owner.session; + expect(artifacts).not.toHaveProperty("communityId"); + expect(artifacts).not.toHaveProperty("typePolicy"); +}); + +it("offers the host's community id and type policy as they are", () => { + const artifactTypePolicy = { read: vi.fn(), set: vi.fn() }; + const { artifacts } = harness(false, { + artifactCommunity: COMMUNITY, + artifactTypePolicy, + }).owner.session; + expect(artifacts.communityId).toBe(COMMUNITY); + expect(artifacts.typePolicy).toBe(artifactTypePolicy); +}); + function nth(items: readonly T[], index: number): T { const item = items[index]; if (item === undefined) throw new Error(`missing item ${index}`); diff --git a/src/features/relay/artifact-sync.test.ts b/src/features/relay/artifact-sync.test.ts index c1bc0fe452..3d8767928a 100644 --- a/src/features/relay/artifact-sync.test.ts +++ b/src/features/relay/artifact-sync.test.ts @@ -55,6 +55,32 @@ describe("artifactSyncFilter", () => { }); }); + it("accepts a community sync of one type, without #h or paging keys", () => { + const community = { + artifact: "current", + scope: "community", + "#type": ["com.example.groups.group"], + }; + expect(artifactSyncFilter(community)).toEqual(community); + expect(artifactSyncFilter({ ...community, kinds: [45010] })).toEqual({ + ...community, + kinds: [45010], + }); + for (const [bad, reason] of [ + [{ ...community, "#h": [C1] }, "one #type and no #h"], + [{ ...community, "#type": ["a.b", "c.d"] }, "one #type and no #h"], + [{ artifact: "current", scope: "community" }, "one #type and no #h"], + [{ ...community, "#type": [] }, "#type"], + // The relay refuses a type outside the NIP-AR grammar. + [{ ...community, "#type": ["Com.Example.Group"] }, "values for #type"], + [{ ...community, scope: "channel" }, '"scope"'], + [{ ...filter, scope: "channel" }, '"scope"'], + [{ ...community, limit: 10 }, '"limit"'], + [{ ...community, offset: 10 }, '"offset"'], + ] as const) + expect(() => artifactSyncFilter(bad)).toThrow(reason); + }); + it("refuses what the relay's predicate parser refuses", () => { for (const bad of [ "NOT-A-UUID", diff --git a/src/features/relay/artifact-sync.ts b/src/features/relay/artifact-sync.ts index d479773712..2a0746b5c8 100644 --- a/src/features/relay/artifact-sync.ts +++ b/src/features/relay/artifact-sync.ts @@ -25,7 +25,8 @@ export type ArtifactSyncStatus = | "live" /** The last complete set; a new sync is starting. */ | "stale" - /** The reader cannot read a channel that `#h` names. Terminal. */ + /** The reader cannot read a channel that `#h` names, or has lost access to + * the community. Terminal. */ | "restricted" /** This relay or transport has no sync. Use finite reads instead. */ | "unsupported" diff --git a/src/features/relay/artifact-type-policy.test.ts b/src/features/relay/artifact-type-policy.test.ts new file mode 100644 index 0000000000..27c0884c96 --- /dev/null +++ b/src/features/relay/artifact-type-policy.test.ts @@ -0,0 +1,150 @@ +import { afterEach, expect, it, vi } from "vitest"; +import type { EventTemplate } from "nostr-tools"; +import { artifactTypePolicyAccess } from "./artifact-type-policy"; +import type { RelayEvent } from "./events"; +import { PublishNotSent, PublishRejected } from "./outbox"; +import { keypair, signed } from "./testing"; + +const viewer = keypair(); +const COMMUNITY = "9b353519-f4fe-4757-aef4-bec6cc0ae54c"; +const TYPE = "example.settings"; +const change = { type: TYPE, policy: "admins", prev: "0" } as const; + +afterEach(() => { + vi.useRealTimers(); +}); + +/** `publish` scripts the relay. */ +function access( + publish: (signal: AbortSignal) => Promise = async () => "", +) { + const read = vi.fn<() => Promise>(async () => ({ + policy: "admins", + revision: null, + })); + const writer = { + sign: vi.fn(async (template: EventTemplate) => signed(viewer, template)), + publish: vi.fn((_event: RelayEvent, signal: AbortSignal) => + publish(signal), + ), + }; + return { + access: artifactTypePolicyAccess(COMMUNITY, read, writer), + read, + writer, + }; +} + +it("hands a plugin only the parsed policy the relay returned", async () => { + const h = access(); + h.read.mockResolvedValueOnce({ + policy: "everyone", + revision: null, + extra: "ignored", + }); + await expect( + h.access.read(TYPE, new AbortController().signal), + ).resolves.toEqual({ policy: "everyone", revision: null }); +}); + +it("rejects a relay read that is not a policy", async () => { + const h = access(); + h.read.mockResolvedValueOnce({ policy: "nobody", revision: null }); + await expect( + h.access.read(TYPE, new AbortController().signal), + ).rejects.toThrow("Invalid artifact type policy"); +}); + +it.each([ + ["accepted", async () => "", true, ""], + [ + "refused with the relay's reason", + () => + Promise.reject( + new PublishRejected( + "You don't have permission.", + "restricted: community artifact access denied", + ), + ), + false, + "restricted: community artifact access denied", + ], + [ + "refused with only a message", + () => + Promise.reject( + new PublishRejected( + "conflict: the relay state changed; reload before writing again", + ), + ), + false, + "conflict: the relay state changed; reload before writing again", + ], + [ + "not sent", + () => Promise.reject(new PublishNotSent("rate-limited: slow down")), + false, + "", + ], + [ + "unconfirmed", + () => + Promise.reject(new Error("Relay delivery could not be confirmed (502)")), + false, + "", + ], +])( + "signs this community's command once and reports %s", + async (_, publish, ok, message) => { + vi.useFakeTimers({ toFake: ["Date"], now: 1_700_000_123_456 }); + const h = access(publish); + const result = await h.access.set(change, new AbortController().signal); + expect(h.writer.sign).toHaveBeenCalledOnce(); + expect(h.writer.sign.mock.calls[0]?.[0]).toEqual({ + kind: 9034, + created_at: 1_700_000_123, + content: "", + tags: [ + ["community", COMMUNITY], + ["type", TYPE], + ["policy", "admins"], + ["prev", "0"], + ], + }); + const event = await h.writer.sign.mock.results[0]?.value; + expect(h.writer.publish).toHaveBeenCalledOnce(); + expect(h.writer.publish.mock.calls[0]?.[0]).toBe(event); + expect(result).toEqual({ id: event.id, ok, message }); + }, +); + +it("refuses a malformed change before signing", async () => { + const h = access(); + await expect( + h.access.set( + { ...change, prev: "A".repeat(64) }, + new AbortController().signal, + ), + ).rejects.toThrow(); + expect(h.writer.sign).not.toHaveBeenCalled(); +}); + +it("rejects when signing fails or the caller aborts the publish", async () => { + const h = access( + (signal) => + new Promise((_, reject) => + signal.addEventListener("abort", () => reject(signal.reason)), + ), + ); + h.writer.sign.mockRejectedValueOnce(new Error("Signer unavailable")); + await expect( + h.access.set(change, new AbortController().signal), + ).rejects.toThrow("Signer unavailable"); + expect(h.writer.publish).not.toHaveBeenCalled(); + + const controller = new AbortController(); + const pending = h.access.set(change, controller.signal); + await vi.waitFor(() => expect(h.writer.publish).toHaveBeenCalledOnce()); + controller.abort(); + await expect(pending).rejects.toMatchObject({ name: "AbortError" }); +}); diff --git a/src/features/relay/artifact-type-policy.ts b/src/features/relay/artifact-type-policy.ts new file mode 100644 index 0000000000..b736f83f0a --- /dev/null +++ b/src/features/relay/artifact-type-policy.ts @@ -0,0 +1,44 @@ +import { + parseTypePolicy, + typePolicyTemplate, + type ArtifactTypePolicyAccess, +} from "./artifact-community"; +import { PublishNotSent, PublishRejected } from "./outbox"; +import type { RelayWriter } from "./transport"; + +/** The plugin-facing type policy for `community`: `read` fetches the relay's + * answer, `set` signs and publishes only the kind-9034 command via `writer`. */ +export const artifactTypePolicyAccess = ( + community: string, + read: (type: string, signal: AbortSignal) => Promise, + writer: RelayWriter, +): ArtifactTypePolicyAccess => ({ + async read(type, signal) { + return parseTypePolicy(await read(type, signal)); + }, + async set(change, signal) { + const event = await writer.sign( + typePolicyTemplate( + community, + change.type, + change.policy, + change.prev, + Math.floor(Date.now() / 1000), + ), + signal, + ); + try { + const message = (await writer.publish(event, signal)) ?? ""; + return { id: event.id, ok: true, message }; + } catch (error) { + signal.throwIfAborted(); + const refused = + error instanceof PublishRejected && !(error instanceof PublishNotSent); + return { + id: event.id, + ok: false, + message: refused ? (error.reason ?? error.message) : "", + }; + } + }, +}); diff --git a/src/features/relay/native.test.ts b/src/features/relay/native.test.ts index cf35df6a04..0a3d4095c8 100644 --- a/src/features/relay/native.test.ts +++ b/src/features/relay/native.test.ts @@ -7,6 +7,7 @@ import { READ_STATE_TIMESTAMP_REFUSAL, } from "./read-state-host"; import memberContract from "../channel-members/administration-contract.json"; +import { typePolicyTemplate } from "./artifact-community"; import { afterEach, assert, beforeEach, expect, it, vi } from "vitest"; import { invoke } from "@tauri-apps/api/core"; import { @@ -2285,6 +2286,86 @@ it.each([ }, ); +const artifactCommunity = "9b353519-f4fe-4757-aef4-bec6cc0ae54c"; +it.each([ + { nipAr: true, offered: true }, + { nipAr: false, offered: false }, +])( + "offers the community type policy only with NIP-AR: %j", + async ({ nipAr, offered }) => { + discovery = { + ...(nipAr ? { supported_extensions: ["nip-ar"] } : {}), + artifacts: { + community_scope: { version: 1, community_id: artifactCommunity }, + }, + }; + const transport = await connectNativeTransport(community); + expect(transport.artifactCommunity).toBe( + offered ? artifactCommunity : undefined, + ); + expect(transport.artifactTypePolicy !== undefined).toBe(offered); + }, +); + +it("reads the type policy through signed /query and sets it through this community's typed route", async () => { + discovery = { + supported_extensions: ["nip-ar"], + artifacts: { + community_scope: { version: 1, community_id: artifactCommunity }, + }, + }; + const policy = (await connectNativeTransport(community)).artifactTypePolicy; + assert.exists(policy); + const signal = new AbortController().signal; + const type = "com.example.groups.group"; + const revision = "b".repeat(64); + respond = () => ({ body: { policy: "admins", revision } }); + await expect(policy.read(type, signal)).resolves.toEqual({ + policy: "admins", + revision, + }); + expect(requests.at(-1)).toMatchObject({ + community, + path: "/query", + method: "POST", + }); + expect(JSON.parse(requests.at(-1)?.body ?? "null")).toEqual([ + { artifact: "policy", scope: "community", "#type": [type] }, + ]); + const template = typePolicyTemplate( + artifactCommunity, + type, + "admins", + revision, + 1700000010, + ); + const event = signed(viewer, template); + vi.mocked(invoke) + .mockResolvedValueOnce(event) + .mockResolvedValueOnce({ + status: 200, + headers: {}, + body: JSON.stringify({ + accepted: true, + event_id: event.id, + message: "confirmed", + }), + }); + await expect( + policy.set({ type, policy: "admins", prev: revision }, signal), + ).resolves.toEqual({ id: event.id, ok: true, message: "confirmed" }); + expect(vi.mocked(invoke).mock.calls.slice(-2)).toEqual([ + [ + "relay_channel_sign", + { community, route: "artifact-type-policy", event: template }, + ], + [ + "relay_channel_publish", + { community, route: "artifact-type-policy", event }, + ], + ]); +}); + it.each([ "incremental_limit", "incremental_reset", diff --git a/src/features/relay/native.ts b/src/features/relay/native.ts index dc49283ef1..0682ac227f 100644 --- a/src/features/relay/native.ts +++ b/src/features/relay/native.ts @@ -67,6 +67,12 @@ import { import type { AgentLibrary } from "../agents/library"; import { observerFrame } from "../agents/observer"; import { ARTIFACT_KIND } from "../agents/agent-config-artifacts"; +import { + communityScope, + typePolicyFilter, + validTypePolicy, +} from "./artifact-community"; +import { artifactTypePolicyAccess } from "./artifact-type-policy"; import { acceptPublish, acceptReadStatePublish, @@ -464,6 +470,7 @@ export async function connectNativeTransport( | { sync?: { version?: unknown } } | undefined; const artifactSync = artifacts?.sync?.version === 1; + const artifactCommunity = communityScope(info.artifacts, artifactSupport); const transport = await connectSignedTransport( nativeRelaySigner(origin), origin, @@ -476,6 +483,7 @@ export async function connectNativeTransport( if (!writer) throw new Error("Native relay writer is unavailable"); const commandWriter = ( route: + | "artifact-type-policy" | "channel-details" | "channel-lifecycle" | "identity-archive" @@ -975,6 +983,30 @@ export async function connectNativeTransport( ...(channelIdentity ? { channelIdentity: true as const } : {}), ...(searchSort ? { searchSort: true as const } : {}), ...(artifactSync ? { artifactSync: true as const } : {}), + ...(artifactCommunity + ? { + artifactCommunity, + artifactTypePolicy: artifactTypePolicyAccess( + artifactCommunity, + async (type, signal) => { + const filters = [typePolicyFilter(type)]; + const response = await admitSignedRequest( + origin, + transport.viewer, + () => nativeRelayRequest(origin, "/query", filters, signal), + signal, + ); + signal.throwIfAborted(); + if (!response.ok) + throw new Error((await readApiFailure(response)).error); + return response.json(); + }, + commandWriter("artifact-type-policy", (event) => + validTypePolicy(event, artifactCommunity), + ), + ), + } + : {}), verifiedProfiles: verifiedProfileAuthority(info), async readVerifiedProfileAuthority(signal) { return verifiedProfileDiscovery(await nativeRelayInfo(origin, signal)); diff --git a/src/features/relay/session.ts b/src/features/relay/session.ts index e8878448a2..1a0e3a0ba8 100644 --- a/src/features/relay/session.ts +++ b/src/features/relay/session.ts @@ -3085,10 +3085,20 @@ export function createRelaySession( /** Whether read() search filters may ask for `search_sort: "newest"`. */ searchSort: transport?.searchSort === true, /** NIP-AR sync: an exact, kept-current set of current artifacts for a - * filter that names its channels with `#h`. Status `unsupported` means + * filter that names its channels with `#h`, or for one `#type` of this + * community with `"scope": "community"`. Status `unsupported` means * this relay has no sync; use read() with `artifact: "current"` instead. * Dispose with the plugin's scope. */ artifacts: { + ...(transport?.artifactCommunity && transport.artifactTypePolicy + ? { + /** The community's id, when the relay keeps community-scoped + * artifacts; always with `typePolicy`. */ + communityId: transport.artifactCommunity, + /** Each type's write policy (kind 9034), set as the viewer. */ + typePolicy: transport.artifactTypePolicy, + } + : {}), sync(filter: unknown): ArtifactSyncView { if (closed || artifactSyncs.size >= ARTIFACT_SYNC_MAX_VIEWS) throw new Error("Artifact sync capacity unavailable"); diff --git a/src/features/relay/socket-requests.test.ts b/src/features/relay/socket-requests.test.ts new file mode 100644 index 0000000000..2f3f56108b --- /dev/null +++ b/src/features/relay/socket-requests.test.ts @@ -0,0 +1,28 @@ +import { expect, it } from "vitest"; +import { createSocketPublications } from "./socket-requests"; +import { keypair, signed } from "./testing"; + +const key = keypair(); + +it.each([ + // A 9034 compare-and-set refusal precedes any policy change. + [9034, false, "conflict: artifact policy changed"], + // Kinds without a documented compare-and-set keep `conflict:` unconfirmed. + [9, true, undefined], +])("kind %s conflict refusal is sent=%s", async (kind, sent, reason) => { + const publications = createSocketPublications(() => {}); + const event = signed(key, { kind, content: "", tags: [] }); + const result = publications + .publish(event, new AbortController().signal) + .catch((error: unknown) => error); + const job = publications.next(); + if (!job) throw new Error("No pending publication"); + publications.dispatch(job, () => {}); + publications.receive([ + "OK", + event.id, + false, + "conflict: artifact policy changed", + ]); + expect(await result).toMatchObject({ sent, reason }); +}); diff --git a/src/features/relay/socket-requests.ts b/src/features/relay/socket-requests.ts index 8acf8bacd9..4907d67af6 100644 --- a/src/features/relay/socket-requests.ts +++ b/src/features/relay/socket-requests.ts @@ -6,6 +6,7 @@ import { MAX_EVENT_BYTES as CATALOG_EVENT_BYTES, } from "../agents/catalog-envelope.ts"; import { CANVAS_FRAME_BYTES } from "../channel-templates/canvas-limits.ts"; +import { ARTIFACT_TYPE_POLICY_KIND } from "./artifact-community.ts"; /** False means proven non-delivery, not merely a negative or missing OK. * `refusal` is the log-safe summary; `reason` is the relay's own bounded text @@ -122,11 +123,11 @@ export function createSocketPublications(wake: () => void) { /^(invalid|blocked|restricted|auth-required|rate-limited):/.test( data[3], ) || - // Buzz workflow CAS/authority and Canvas/artifact CAS refusals precede - // domain mutation. + // Buzz workflow CAS/authority and Canvas/artifact/artifact-policy CAS + // refusals precede domain mutation. ([30620, 46020].includes(job.event.kind) && /^(conflict|forbidden):/.test(data[3])) || - ([40100, 45010].includes(job.event.kind) && + ([40100, 45010, ARTIFACT_TYPE_POLICY_KIND].includes(job.event.kind) && data[3].startsWith("conflict:")); job.finish( undefined, diff --git a/src/features/relay/transport.test.ts b/src/features/relay/transport.test.ts index 5c78b85fda..dc3e70203b 100644 --- a/src/features/relay/transport.test.ts +++ b/src/features/relay/transport.test.ts @@ -417,6 +417,77 @@ it("saves the viewer's config artifacts when the broker admits kind 45010", asyn expect((await connectBrokerTransport()).configArtifacts).toBeUndefined(); }); +it("reads and sets community artifact type policy through the broker's typed routes", async () => { + const community = "9b353519-f4fe-4757-aef4-bec6cc0ae54c"; + const type = "com.example.groups.group"; + const command = signed(key, { + kind: 9034, + content: "", + tags: [ + ["community", community], + ["type", type], + ["policy", "admins"], + ["prev", "0"], + ], + }); + const fetcher = vi.fn(async (url: string, _init?: RequestInit) => { + if (url.endsWith("/session")) + return Response.json({ + viewer: key.pubkey, + relayAuthor: "relay", + artifactCommunity: community, + }); + if (url.endsWith("/artifact-type-policy")) + return Response.json({ policy: "admins", revision: command.id }); + if (url.endsWith("-sign")) return Response.json(command); + return Response.json({ accepted: true, event_id: command.id }); + }); + vi.stubGlobal("fetch", fetcher); + const transport = await connectBrokerTransport(); + expect(transport.artifactCommunity).toBe(community); + const policy = transport.artifactTypePolicy; + assert.exists(policy); + const signal = new AbortController().signal; + expect(await policy.read(type, signal)).toEqual({ + policy: "admins", + revision: command.id, + }); + const { kind, content, tags } = command; + expect( + await policy.set({ type, policy: "admins", prev: "0" }, signal), + ).toMatchObject({ id: command.id, ok: true }); + expect( + fetcher.mock.calls.map(([url, init]) => [ + url, + init?.body ? JSON.parse(init.body as string) : null, + ]), + ).toEqual([ + ["/api/relay/session", null], + ["/api/relay/artifact-type-policy", { type }], + [ + "/api/relay/artifact-type-policy-sign", + { kind, content, tags, created_at: expect.any(Number) }, + ], + [ + "/api/relay/artifact-type-policy-publish", + JSON.parse(JSON.stringify(command)), + ], + ]); + // A malformed or missing community offers neither. + for (const artifactCommunity of [community.toUpperCase(), 7, undefined]) { + vi.stubGlobal("fetch", async () => + Response.json({ + viewer: key.pubkey, + relayAuthor: "relay", + artifactCommunity, + }), + ); + const other = await connectBrokerTransport(); + expect(other.artifactCommunity).toBeUndefined(); + expect(other.artifactTypePolicy).toBeUndefined(); + } +}); + it("exposes the relay HTTP base for display, preferring the broker's explicit value", async () => { const session = (extra: Record) => async () => Response.json({ viewer: key.pubkey, relayAuthor: "relay", ...extra }); diff --git a/src/features/relay/transport.ts b/src/features/relay/transport.ts index 47fa63cd7f..b0e57f9c9d 100644 --- a/src/features/relay/transport.ts +++ b/src/features/relay/transport.ts @@ -72,6 +72,11 @@ import { subscribeBrokerTraffic } from "./broker-live"; import { PublishNotSent, PublishRejected } from "./outbox"; import { httpReadError, ReadError } from "./errors"; import { ARTIFACT_KIND } from "../agents/agent-config-artifacts"; +import { + artifactCommunityId, + type ArtifactTypePolicyAccess, +} from "./artifact-community"; +import { artifactTypePolicyAccess } from "./artifact-type-policy"; import type { EventTemplate, VerifiedEvent } from "nostr-tools"; import { directMessageRefusal } from "./direct-message-policy"; import { @@ -169,6 +174,12 @@ export interface ReadTransport { /** The relay advertises NIP-AR sync (`artifacts.sync.version` 1 in NIP-11): * a REQ with `"artifact": "current"` streams a complete set, then live heads. */ readonly artifactSync?: true; + /** This community's id from NIP-11 `artifacts.community_scope` version 1: + * the relay keeps community-scoped artifacts. */ + readonly artifactCommunity?: string; + /** Present only with `artifactCommunity`; signs and publishes only the + * kind-9034 command for this community. */ + readonly artifactTypePolicy?: ArtifactTypePolicyAccess; /** Strictly validated atomic writer snapshot; never an ordinary event-array query. */ readStateSnapshot?( signal: AbortSignal, @@ -569,6 +580,7 @@ export async function connectBrokerTransport( agentActivity?: boolean; readState?: boolean; readStateCommunity?: string; + artifactCommunity?: string; }; if ( typeof session.viewer !== "string" || @@ -918,6 +930,26 @@ export async function connectBrokerTransport( : {}), ...(session.searchSort === true ? { searchSort: true as const } : {}), ...(session.artifactSync === true ? { artifactSync: true as const } : {}), + ...(artifactCommunityId(session.artifactCommunity) + ? { + artifactCommunity: session.artifactCommunity, + artifactTypePolicy: artifactTypePolicyAccess( + session.artifactCommunity, + async (type, signal) => { + const response = await fetch(`${endpoint}/artifact-type-policy`, { + method: "POST", + credentials: "same-origin", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ type }), + signal, + }); + if (!response.ok) throw await readResponseError(response); + return response.json(); + }, + routeWriter("artifact-type-policy"), + ), + } + : {}), ...(session.channelKit ? { channelKit: {