From c2bbb1cb9b45b1debf4607c5a94386705cb72c0f Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Wed, 18 Nov 2026 06:22:54 +0000 Subject: [PATCH 1/9] feat(relay): add NIP-AR community scope wire helpers and browser client Add the dependency-free NIP-AR community-scope helpers that the desktop host, the browser broker and the session share: NIP-11 `artifacts.community_scope` discovery, the exact kind-9034 type policy command and its validator, the policy read filter and response parser, and the relay's artifact type grammar. Artifact sync now accepts a community filter (`"scope": "community"` with exactly one `#type` and no `#h`); channel filters are unchanged. A socket `conflict:` refusal of a 9034 command counts as proven non-delivery, like other compare-and-set refusals. The browser transport exposes `artifactCommunity` and `artifactTypePolicy` when the broker reports a canonical community id: the read posts `{type}` to `artifact-type-policy`, and the writer uses the `artifact-type-policy-sign` and `-publish` routes. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- src/features/relay/artifact-community.test.ts | 163 ++++++++++++++++++ src/features/relay/artifact-community.ts | 130 ++++++++++++++ src/features/relay/artifact-sync-filter.ts | 37 +++- src/features/relay/artifact-sync.test.ts | 24 +++ src/features/relay/artifact-sync.ts | 3 +- src/features/relay/socket-requests.test.ts | 28 +++ src/features/relay/socket-requests.ts | 7 +- src/features/relay/transport.test.ts | 72 ++++++++ src/features/relay/transport.ts | 35 ++++ 9 files changed, 486 insertions(+), 13 deletions(-) create mode 100644 src/features/relay/artifact-community.test.ts create mode 100644 src/features/relay/artifact-community.ts create mode 100644 src/features/relay/socket-requests.test.ts 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..540410d337 --- /dev/null +++ b/src/features/relay/artifact-community.ts @@ -0,0 +1,130 @@ +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; +}>; + +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}$/; + +/** A canonical lowercase, non-nil community UUID. */ +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..96ea45b056 100644 --- a/src/features/relay/artifact-sync-filter.ts +++ b/src/features/relay/artifact-sync-filter.ts @@ -2,13 +2,25 @@ import type { VerifiedEvent } from "nostr-tools"; // Wire contract only: no imports beyond types, 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 +67,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 +91,12 @@ 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"); + } 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.test.ts b/src/features/relay/artifact-sync.test.ts index c1bc0fe452..74eca48ffe 100644 --- a/src/features/relay/artifact-sync.test.ts +++ b/src/features/relay/artifact-sync.test.ts @@ -55,6 +55,30 @@ 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"], + [{ ...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/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..57312ecb3b 100644 --- a/src/features/relay/transport.test.ts +++ b/src/features/relay/transport.test.ts @@ -417,6 +417,78 @@ 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 { created_at, kind, content, tags } = command; + await policy.writer.publish( + await policy.writer.sign({ kind, content, tags, created_at }, signal), + signal, + ); + 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 }, + ], + [ + "/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..a05dcaeae0 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, + parseTypePolicy, + type ArtifactTypePolicyState, +} from "./artifact-community"; import type { EventTemplate, VerifiedEvent } from "nostr-tools"; import { directMessageRefusal } from "./direct-message-policy"; import { @@ -169,6 +174,16 @@ 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`: the community's per-type write + * policy read, and a writer that signs and publishes only the kind-9034 + * command for this community. Never supplied to the outbox. */ + readonly artifactTypePolicy?: Readonly<{ + read(type: string, signal: AbortSignal): Promise; + writer: RelayWriter; + }>; /** Strictly validated atomic writer snapshot; never an ordinary event-array query. */ readStateSnapshot?( signal: AbortSignal, @@ -569,6 +584,7 @@ export async function connectBrokerTransport( agentActivity?: boolean; readState?: boolean; readStateCommunity?: string; + artifactCommunity?: string; }; if ( typeof session.viewer !== "string" || @@ -918,6 +934,25 @@ 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: { + async read(type: string, signal: AbortSignal) { + 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 parseTypePolicy(await response.json()); + }, + writer: routeWriter("artifact-type-policy"), + }, + } + : {}), ...(session.channelKit ? { channelKit: { From 48460e5d9e5fdafbfc30a2a391f541f28b4df805 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Wed, 18 Nov 2026 01:45:12 -0500 Subject: [PATCH 2/9] feat(relay): sign NIP-AR type policy commands through the desktop host The desktop transport reads NIP-11 `artifacts.community_scope` (only when the relay lists `nip-ar`) and, for such a relay, offers `artifactCommunity` with `artifactTypePolicy`: a signed `/query` read of the community's per-type write policy, and a writer for the kind-9034 command bound to this community. Kind 9034 goes only through the purpose-bound `relay_channel_sign` and `relay_channel_publish` route `artifact-type-policy`, which accepts exactly the four tags in order (a canonical non-nil community, the relay's namespaced type grammar, `everyone` or `admins`, and `prev` of "0" or a lowercase event id) with empty content. The generic `relay_sign` keeps refusing 9034, so the artifact signer cannot set a policy, and raw `/events` posts now refuse it like the other typed-route kinds. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- src-tauri/src/relay.rs | 5 +- src-tauri/src/relay/channel_writes.rs | 88 +++++++++++++++++++++++++++ src-tauri/src/relay/tests.rs | 67 ++++++++++++++++++++ src/features/relay/native.test.ts | 76 +++++++++++++++++++++++ src/features/relay/native.ts | 31 ++++++++++ 5 files changed, 266 insertions(+), 1 deletion(-) 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..66bbecfbc8 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,68 @@ 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))); + + 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"), + (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/native.test.ts b/src/features/relay/native.test.ts index cf35df6a04..b99239b808 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,81 @@ 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 signs 9034 only for 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); + expect(await policy.writer.sign(template, signal)).toEqual(event); + expect(vi.mocked(invoke).mock.lastCall).toEqual([ + "relay_channel_sign", + { community, route: "artifact-type-policy", event: template }, + ]); + const elsewhere = typePolicyTemplate( + "11111111-1111-4111-8111-111111111111", + type, + "admins", + revision, + 1700000010, + ); + const calls = vi.mocked(invoke).mock.calls.length; + await expect(policy.writer.sign(elsewhere, signal)).rejects.toThrow(); + await expect( + policy.writer.publish(signed(viewer, elsewhere), signal), + ).rejects.toThrow(); + expect(vi.mocked(invoke).mock.calls).toHaveLength(calls); +}); + it.each([ "incremental_limit", "incremental_reset", diff --git a/src/features/relay/native.ts b/src/features/relay/native.ts index dc49283ef1..b57a8240b3 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, + parseTypePolicy, + typePolicyFilter, + validTypePolicy, +} from "./artifact-community"; 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,29 @@ export async function connectNativeTransport( ...(channelIdentity ? { channelIdentity: true as const } : {}), ...(searchSort ? { searchSort: true as const } : {}), ...(artifactSync ? { artifactSync: true as const } : {}), + ...(artifactCommunity + ? { + artifactCommunity, + artifactTypePolicy: { + async read(type: string, signal: AbortSignal) { + 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 parseTypePolicy(await response.json()); + }, + writer: commandWriter("artifact-type-policy", (event) => + validTypePolicy(event, artifactCommunity), + ), + }, + } + : {}), verifiedProfiles: verifiedProfileAuthority(info), async readVerifiedProfileAuthority(signal) { return verifiedProfileDiscovery(await nativeRelayInfo(origin, signal)); From 419a97c5103ec94b506cfb77829c8d96fd22ddd8 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Wed, 18 Nov 2026 06:47:59 +0000 Subject: [PATCH 3/9] feat(relay): serve NIP-AR community scope and type policy in the broker The browser host's relay broker now reads NIP-11 `artifacts.community_scope` (only with `nip-ar` listed) and reports the community as `artifactCommunity` in the session, so the browser transport can offer community-scoped artifacts. Kind-9034 type policy commands get their own `artifact-type-policy-sign` and `-publish` routes, like identity archive requests: each accepts only the exact command for the relay's advertised community, and the generic sign and publish routes still refuse it. The `artifact-type-policy` read accepts exactly `{type}` and sends the relay its own policy filter. A socket publication refused with `restricted:`, `blocked:` or `auth-required:` is now answered 403 with the relay's text, as the relay's HTTP API does, instead of 503 unsent, so writers show it as a refusal. Community artifact sync passes through the broker unchanged. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- browser-host/relay-authority.test.mjs | 12 ++- browser-host/relay-broker-api.test.mjs | 117 ++++++++++++++++++++++++ browser-host/relay-broker-live.test.mjs | 33 ++++++- browser-host/relay-broker.mjs | 67 +++++++++++++- 4 files changed, 221 insertions(+), 8 deletions(-) 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..00ca0108ca 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,119 @@ 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); + const [scope, ...rest] = template.tags; + const invalid = [ + { + ...template, + tags: [["community", "11111111-1111-4111-8111-111111111111"], ...rest], + }, + { ...template, tags: [...rest, scope] }, + { ...template, tags: [...template.tags, ["h", community]] }, + ]; + for (const event of invalid) { + expect((await h.post("artifact-type-policy-sign", event)).status).toBe( + 400, + ); + expect( + ( + await h.post( + "artifact-type-policy-publish", + finalizeEvent(event, viewerKey), + ) + ).status, + ).toBe(400); + } + const signal = new AbortController().signal; + expect((await h.post("sign", template)).status).toBe(400); + const signed = await transport.artifactTypePolicy.writer.sign( + template, + signal, + ); + expect(verifyEvent(signed)).toBe(true); + expect(signed).toMatchObject(template); + expect((await h.post("publish", signed)).status).toBe(400); + live = await openBrokerSocket(transport); + await transport.artifactTypePolicy.writer.publish(signed, signal); + expect(h.publications.map((event) => event.id)).toEqual([signed.id]); + 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..1e756319bc 100644 --- a/browser-host/relay-broker-live.test.mjs +++ b/browser-host/relay-broker-live.test.mjs @@ -1058,7 +1058,12 @@ 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", + ], [ 'invalid: an open channel named "Launch" already exists', true, @@ -2380,6 +2385,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..16b5eca19c 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,11 @@ 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"); + // NIP-AR community scope: the relay keeps this community's artifacts. + const artifactCommunity = communityScope(nip11.artifacts, artifactSupport); return { relayAuthor: author, channelCreation: @@ -341,9 +351,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 +2468,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 +2780,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 +2989,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 +3028,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 +3212,7 @@ export function relayBrokerPlugin({ !readPublishing && !snapshot && !channelActivity && + !typePolicyRead && !validFilters(filters) ) return json(res, 400, { error: "Read filter rejected" }); @@ -3216,6 +3264,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 && From 789cf0d7a643bab42e88617691768284e718e5a4 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Wed, 18 Nov 2026 06:44:34 +0000 Subject: [PATCH 4/9] feat(relay): expose community artifact scope and type policy on the session `session.artifacts.communityId` is the community id the relay advertises in NIP-11 `artifacts.community_scope`, and `session.artifacts.typePolicy` reads and sets a type's write policy (NIP-AR kind 9034). Both are present only when the transport provides the community and its policy route, so a plugin can detect community artifacts synchronously. `typePolicy.set` builds the exact 9034 command for the session's own community, signs it once as the viewer and publishes it once. It resolves with the command id and the relay's answer: the relay's refusal text when the host keeps it, or an empty message after a transport failure. It rejects only on a malformed change, a signing failure or an aborted signal. The artifact sync guide describes the community sync filter, both fields and their boundary: the policy capability acts with the viewer's authority, like the session's other administrative writers. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- docs/artifact-sync.md | 10 ++ .../relay/artifact-sync.session.test.ts | 147 +++++++++++++++++- src/features/relay/session.ts | 61 +++++++- 3 files changed, 216 insertions(+), 2 deletions(-) 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/features/relay/artifact-sync.session.test.ts b/src/features/relay/artifact-sync.session.test.ts index 38bc8a5d59..0df6ede9c8 100644 --- a/src/features/relay/artifact-sync.session.test.ts +++ b/src/features/relay/artifact-sync.session.test.ts @@ -1,8 +1,11 @@ import { afterEach, expect, it, vi } from "vitest"; +import type { EventTemplate } from "nostr-tools"; import { createRelaySession } from "./session"; import type { RelayEvent } from "./events"; import { keypair, roster, scriptedTransport, signed } from "./testing"; import type { ArtifactSyncSink } from "./artifact-sync"; +import { PublishNotSent, PublishRejected } from "./outbox"; +import type { ReadTransport } from "./transport"; const viewer = keypair(), relay = keypair(); @@ -14,7 +17,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 +30,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 +232,147 @@ it("cancels the pending retry when a listener restarts the view", async () => { expect(h.closes).toHaveBeenCalledOnce(); }); +const COMMUNITY = "9b353519-f4fe-4757-aef4-bec6cc0ae54c"; +const TYPE = "example.settings"; +const change = { type: TYPE, policy: "admins", prev: "0" } as const; + +/** A host with community-scoped artifacts; `publish` scripts the relay. */ +function policyHost( + publish: (signal: AbortSignal) => Promise = async () => "", +) { + const read = vi.fn(async () => ({ + policy: "admins" as const, + revision: null, + })); + const writer = { + sign: vi.fn(async (template: EventTemplate) => signed(viewer, template)), + publish: vi.fn((_event: RelayEvent, signal: AbortSignal) => + publish(signal), + ), + }; + const { owner } = harness(false, { + artifactCommunity: COMMUNITY, + artifactTypePolicy: { read, writer }, + }); + const { communityId, typePolicy } = owner.session.artifacts; + if (!typePolicy) throw new Error("missing typePolicy"); + return { communityId, typePolicy, read, writer }; +} + +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 community id and reads a type's policy through the host", async () => { + const h = policyHost(); + expect(h.communityId).toBe(COMMUNITY); + const { signal } = new AbortController(); + await expect(h.typePolicy.read(TYPE, signal)).resolves.toEqual({ + policy: "admins", + revision: null, + }); + expect(h.read).toHaveBeenCalledWith(TYPE, signal); +}); + +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 = policyHost(publish); + const result = await h.typePolicy.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 = policyHost(); + await expect( + h.typePolicy.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 = policyHost( + (signal) => + new Promise((_, reject) => + signal.addEventListener("abort", () => reject(signal.reason)), + ), + ); + h.writer.sign.mockRejectedValueOnce(new Error("Signer unavailable")); + await expect( + h.typePolicy.set(change, new AbortController().signal), + ).rejects.toThrow("Signer unavailable"); + expect(h.writer.publish).not.toHaveBeenCalled(); + + const controller = new AbortController(); + const pending = h.typePolicy.set(change, controller.signal); + await vi.waitFor(() => expect(h.writer.publish).toHaveBeenCalledOnce()); + controller.abort(); + await expect(pending).rejects.toMatchObject({ name: "AbortError" }); +}); + 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/session.ts b/src/features/relay/session.ts index e8878448a2..5ca31d7699 100644 --- a/src/features/relay/session.ts +++ b/src/features/relay/session.ts @@ -119,6 +119,7 @@ import { import { accessOnce, eventVisibility } from "./event-access"; import { isTransientFailure, ReadError, readErrorKind } from "./errors"; import { + PublishNotSent, PublishRejected, browserOutboxStorage, createOutbox, @@ -148,6 +149,10 @@ import { type ArtifactSyncView, createArtifactSyncView, } from "./artifact-sync"; +import { + typePolicyTemplate, + type ArtifactTypePolicyValue, +} from "./artifact-community"; import { retainEvents, matchesEvent, @@ -2481,6 +2486,8 @@ export function createRelaySession( if (connected && !liveWasConnected) recovery?.retryNow(liveRecovery); liveWasConnected = connected; }); + const artifactCommunity = transport?.artifactCommunity; + const artifactTypePolicy = transport?.artifactTypePolicy; const session = Object.freeze({ artifactIncremental: transport?.artifactIncremental, memberAdditions, @@ -3085,10 +3092,62 @@ 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: { + ...(artifactCommunity && artifactTypePolicy + ? { + /** The community's id, when the relay keeps community-scoped + * artifacts; always with `typePolicy`. */ + communityId: artifactCommunity, + /** Each type's write policy (kind 9034), set as the viewer. */ + typePolicy: { + read: (type: string, signal: AbortSignal) => + artifactTypePolicy.read(type, signal), + /** 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. */ + async set( + change: Readonly<{ + type: string; + policy: ArtifactTypePolicyValue; + prev: string; + }>, + signal: AbortSignal, + ) { + const { writer } = artifactTypePolicy; + const event = await writer.sign( + typePolicyTemplate( + artifactCommunity, + 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) : "", + }; + } + }, + }, + } + : {}), sync(filter: unknown): ArtifactSyncView { if (closed || artifactSyncs.size >= ARTIFACT_SYNC_MAX_VIEWS) throw new Error("Artifact sync capacity unavailable"); From 18a97b6f151c6a5ce81fae55693d54f6c0b96449 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Wed, 18 Nov 2026 02:44:22 -0500 Subject: [PATCH 5/9] fix(relay): refuse a malformed type in a community artifact sync A community sync filter with one `#type` outside the NIP-AR type grammar passed `artifactSyncFilter` and reached the relay, which closes the REQ as `invalid:`. The view then ended in status `error` instead of the call throwing, while the policy helpers refused the same type at the call site. The community branch now checks the value with `artifactTypeName`, the grammar the policy helpers already share, so every host refuses it before the REQ. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- src/features/relay/artifact-sync-filter.ts | 6 +++++- src/features/relay/artifact-sync.test.ts | 2 ++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/features/relay/artifact-sync-filter.ts b/src/features/relay/artifact-sync-filter.ts index 96ea45b056..de4d4dedad 100644 --- a/src/features/relay/artifact-sync-filter.ts +++ b/src/features/relay/artifact-sync-filter.ts @@ -1,6 +1,8 @@ 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. A channel sync needs `#h`; a community sync * (`"scope": "community"`) needs exactly one `#type` and no `#h`. Paging keys @@ -94,6 +96,8 @@ export function artifactSyncFilter(input: unknown): ArtifactSyncFilter { 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"); else if (channels.length > ARTIFACT_SYNC_MAX_CHANNELS) diff --git a/src/features/relay/artifact-sync.test.ts b/src/features/relay/artifact-sync.test.ts index 74eca48ffe..3d8767928a 100644 --- a/src/features/relay/artifact-sync.test.ts +++ b/src/features/relay/artifact-sync.test.ts @@ -71,6 +71,8 @@ describe("artifactSyncFilter", () => { [{ ...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"'], From 305d6ce2b7662019531bc6d07e37a80341ba6431 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Wed, 18 Nov 2026 02:44:43 -0500 Subject: [PATCH 6/9] test(relay): cover every byte class of the type policy type grammar The desktop type policy route was tested with types made only of lowercase letters, and its refusals all failed on a segment's first character. Dropping the digit, `_` or `-` arm of the per-byte check, or widening it to accept uppercase inside a segment, still passed. The test now accepts types with digits, `_` and `-` (including a hyphenated middle segment) and refuses uppercase or punctuation inside a segment and a leading or trailing dot, matching the shared TypeScript grammar's table. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- src-tauri/src/relay/channel_writes.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src-tauri/src/relay/channel_writes.rs b/src-tauri/src/relay/channel_writes.rs index 66bbecfbc8..d04e5e5778 100644 --- a/src-tauri/src/relay/channel_writes.rs +++ b/src-tauri/src/relay/channel_writes.rs @@ -304,6 +304,11 @@ mod tests { unset[2][1] = "everyone"; unset[3][1] = "0"; assert!(valid("artifact-type-policy", &command(unset))); + for value in ["a1.b_c-d", "com.example.mention-groups.group"] { + 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); @@ -316,6 +321,10 @@ mod tests { (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"), From fce1bf43ad5fdcb2a0dbd06b0052712966bf4eef Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Wed, 18 Nov 2026 02:44:59 -0500 Subject: [PATCH 7/9] test(browser-host): cover the broker's auth-required socket refusal The broker answers a proven socket refusal starting with `restricted:`, `blocked:` or `auth-required:` with 403, so the writer sees the relay's refusal instead of an unconfirmed publication. Only the first two prefixes were tested, so dropping `auth-required` from the mapping still passed. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- browser-host/relay-broker-live.test.mjs | 1 + 1 file changed, 1 insertion(+) diff --git a/browser-host/relay-broker-live.test.mjs b/browser-host/relay-broker-live.test.mjs index 1e756319bc..8aa89be1f7 100644 --- a/browser-host/relay-broker-live.test.mjs +++ b/browser-host/relay-broker-live.test.mjs @@ -1064,6 +1064,7 @@ test.each([ 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, From b2f6be14f404b3be5024629b0e4cd3277adb91a3 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Wed, 18 Nov 2026 03:02:41 -0500 Subject: [PATCH 8/9] refactor(relay): offer the type policy as one host capability Make the transport's artifactTypePolicy the plugin-facing read/set access and build it in one helper shared by the native and broker transports, so the session only passes it through. Move the set behavior tests to the helper's own test file. No behavior change. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- browser-host/relay-broker-api.test.mjs | 13 +- browser-host/relay-broker.mjs | 1 - src/features/relay/artifact-community.ts | 17 +- .../relay/artifact-sync.session.test.ts | 138 +--------------- .../relay/artifact-type-policy.test.ts | 154 ++++++++++++++++++ src/features/relay/artifact-type-policy.ts | 44 +++++ src/features/relay/native.test.ts | 43 ++--- src/features/relay/native.ts | 13 +- src/features/relay/session.ts | 55 +------ src/features/relay/transport.test.ts | 11 +- src/features/relay/transport.ts | 25 ++- 11 files changed, 279 insertions(+), 235 deletions(-) create mode 100644 src/features/relay/artifact-type-policy.test.ts create mode 100644 src/features/relay/artifact-type-policy.ts diff --git a/browser-host/relay-broker-api.test.mjs b/browser-host/relay-broker-api.test.mjs index 00ca0108ca..9e50464659 100644 --- a/browser-host/relay-broker-api.test.mjs +++ b/browser-host/relay-broker-api.test.mjs @@ -3578,16 +3578,17 @@ test("type policy commands use dedicated exact-shape routes for the relay's own } const signal = new AbortController().signal; expect((await h.post("sign", template)).status).toBe(400); - const signed = await transport.artifactTypePolicy.writer.sign( - template, + 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); - expect(signed).toMatchObject(template); + const { kind, content, tags } = template; + expect(signed).toMatchObject({ kind, content, tags }); expect((await h.post("publish", signed)).status).toBe(400); - live = await openBrokerSocket(transport); - await transport.artifactTypePolicy.writer.publish(signed, signal); - expect(h.publications.map((event) => event.id)).toEqual([signed.id]); const foreign = finalizeEvent( { ...template, tags: template.tags.map((tag) => [...tag]) }, new Uint8Array(32).fill(5), diff --git a/browser-host/relay-broker.mjs b/browser-host/relay-broker.mjs index 16b5eca19c..92401ba6b8 100644 --- a/browser-host/relay-broker.mjs +++ b/browser-host/relay-broker.mjs @@ -339,7 +339,6 @@ async function relayAuthority(fetch, relay) { const artifactSupport = Array.isArray(nip11.supported_extensions) && nip11.supported_extensions.includes("nip-ar"); - // NIP-AR community scope: the relay keeps this community's artifacts. const artifactCommunity = communityScope(nip11.artifacts, artifactSupport); return { relayAuthor: author, diff --git a/src/features/relay/artifact-community.ts b/src/features/relay/artifact-community.ts index 540410d337..590913523e 100644 --- a/src/features/relay/artifact-community.ts +++ b/src/features/relay/artifact-community.ts @@ -13,11 +13,26 @@ 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}$/; -/** A canonical lowercase, non-nil community UUID. */ export const artifactCommunityId = (value: unknown): value is string => typeof value === "string" && UUID.test(value) && diff --git a/src/features/relay/artifact-sync.session.test.ts b/src/features/relay/artifact-sync.session.test.ts index 0df6ede9c8..9c95eb21a4 100644 --- a/src/features/relay/artifact-sync.session.test.ts +++ b/src/features/relay/artifact-sync.session.test.ts @@ -1,10 +1,8 @@ import { afterEach, expect, it, vi } from "vitest"; -import type { EventTemplate } from "nostr-tools"; import { createRelaySession } from "./session"; import type { RelayEvent } from "./events"; import { keypair, roster, scriptedTransport, signed } from "./testing"; import type { ArtifactSyncSink } from "./artifact-sync"; -import { PublishNotSent, PublishRejected } from "./outbox"; import type { ReadTransport } from "./transport"; const viewer = keypair(), @@ -233,31 +231,6 @@ it("cancels the pending retry when a listener restarts the view", async () => { }); const COMMUNITY = "9b353519-f4fe-4757-aef4-bec6cc0ae54c"; -const TYPE = "example.settings"; -const change = { type: TYPE, policy: "admins", prev: "0" } as const; - -/** A host with community-scoped artifacts; `publish` scripts the relay. */ -function policyHost( - publish: (signal: AbortSignal) => Promise = async () => "", -) { - const read = vi.fn(async () => ({ - policy: "admins" as const, - revision: null, - })); - const writer = { - sign: vi.fn(async (template: EventTemplate) => signed(viewer, template)), - publish: vi.fn((_event: RelayEvent, signal: AbortSignal) => - publish(signal), - ), - }; - const { owner } = harness(false, { - artifactCommunity: COMMUNITY, - artifactTypePolicy: { read, writer }, - }); - const { communityId, typePolicy } = owner.session.artifacts; - if (!typePolicy) throw new Error("missing typePolicy"); - return { communityId, typePolicy, read, writer }; -} it.each([ ["no community scope", {}], @@ -268,109 +241,14 @@ it.each([ expect(artifacts).not.toHaveProperty("typePolicy"); }); -it("offers the community id and reads a type's policy through the host", async () => { - const h = policyHost(); - expect(h.communityId).toBe(COMMUNITY); - const { signal } = new AbortController(); - await expect(h.typePolicy.read(TYPE, signal)).resolves.toEqual({ - policy: "admins", - revision: null, - }); - expect(h.read).toHaveBeenCalledWith(TYPE, signal); -}); - -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 = policyHost(publish); - const result = await h.typePolicy.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 = policyHost(); - await expect( - h.typePolicy.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 = policyHost( - (signal) => - new Promise((_, reject) => - signal.addEventListener("abort", () => reject(signal.reason)), - ), - ); - h.writer.sign.mockRejectedValueOnce(new Error("Signer unavailable")); - await expect( - h.typePolicy.set(change, new AbortController().signal), - ).rejects.toThrow("Signer unavailable"); - expect(h.writer.publish).not.toHaveBeenCalled(); - - const controller = new AbortController(); - const pending = h.typePolicy.set(change, controller.signal); - await vi.waitFor(() => expect(h.writer.publish).toHaveBeenCalledOnce()); - controller.abort(); - await expect(pending).rejects.toMatchObject({ name: "AbortError" }); +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 { 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..3e606fa037 --- /dev/null +++ b/src/features/relay/artifact-type-policy.test.ts @@ -0,0 +1,154 @@ +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.each([ + ["a non-object body", null], + ["an unknown policy", { policy: "nobody", revision: null }], + ["a malformed revision", { policy: "admins", revision: "A".repeat(64) }], +])("rejects %s from the relay read", async (_, body) => { + const h = access(); + h.read.mockResolvedValueOnce(body); + 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 b99239b808..0a3d4095c8 100644 --- a/src/features/relay/native.test.ts +++ b/src/features/relay/native.test.ts @@ -2307,7 +2307,7 @@ it.each([ }, ); -it("reads the type policy through signed /query and signs 9034 only for this community's typed route", async () => { +it("reads the type policy through signed /query and sets it through this community's typed route", async () => { discovery = { supported_extensions: ["nip-ar"], artifacts: { @@ -2340,25 +2340,30 @@ it("reads the type policy through signed /query and signs 9034 only for this com 1700000010, ); const event = signed(viewer, template); - vi.mocked(invoke).mockResolvedValueOnce(event); - expect(await policy.writer.sign(template, signal)).toEqual(event); - expect(vi.mocked(invoke).mock.lastCall).toEqual([ - "relay_channel_sign", - { community, route: "artifact-type-policy", event: template }, - ]); - const elsewhere = typePolicyTemplate( - "11111111-1111-4111-8111-111111111111", - type, - "admins", - revision, - 1700000010, - ); - const calls = vi.mocked(invoke).mock.calls.length; - await expect(policy.writer.sign(elsewhere, signal)).rejects.toThrow(); + vi.mocked(invoke) + .mockResolvedValueOnce(event) + .mockResolvedValueOnce({ + status: 200, + headers: {}, + body: JSON.stringify({ + accepted: true, + event_id: event.id, + message: "confirmed", + }), + }); await expect( - policy.writer.publish(signed(viewer, elsewhere), signal), - ).rejects.toThrow(); - expect(vi.mocked(invoke).mock.calls).toHaveLength(calls); + 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([ diff --git a/src/features/relay/native.ts b/src/features/relay/native.ts index b57a8240b3..0682ac227f 100644 --- a/src/features/relay/native.ts +++ b/src/features/relay/native.ts @@ -69,10 +69,10 @@ import { observerFrame } from "../agents/observer"; import { ARTIFACT_KIND } from "../agents/agent-config-artifacts"; import { communityScope, - parseTypePolicy, typePolicyFilter, validTypePolicy, } from "./artifact-community"; +import { artifactTypePolicyAccess } from "./artifact-type-policy"; import { acceptPublish, acceptReadStatePublish, @@ -986,8 +986,9 @@ export async function connectNativeTransport( ...(artifactCommunity ? { artifactCommunity, - artifactTypePolicy: { - async read(type: string, signal: AbortSignal) { + artifactTypePolicy: artifactTypePolicyAccess( + artifactCommunity, + async (type, signal) => { const filters = [typePolicyFilter(type)]; const response = await admitSignedRequest( origin, @@ -998,12 +999,12 @@ export async function connectNativeTransport( signal.throwIfAborted(); if (!response.ok) throw new Error((await readApiFailure(response)).error); - return parseTypePolicy(await response.json()); + return response.json(); }, - writer: commandWriter("artifact-type-policy", (event) => + commandWriter("artifact-type-policy", (event) => validTypePolicy(event, artifactCommunity), ), - }, + ), } : {}), verifiedProfiles: verifiedProfileAuthority(info), diff --git a/src/features/relay/session.ts b/src/features/relay/session.ts index 5ca31d7699..1a0e3a0ba8 100644 --- a/src/features/relay/session.ts +++ b/src/features/relay/session.ts @@ -119,7 +119,6 @@ import { import { accessOnce, eventVisibility } from "./event-access"; import { isTransientFailure, ReadError, readErrorKind } from "./errors"; import { - PublishNotSent, PublishRejected, browserOutboxStorage, createOutbox, @@ -149,10 +148,6 @@ import { type ArtifactSyncView, createArtifactSyncView, } from "./artifact-sync"; -import { - typePolicyTemplate, - type ArtifactTypePolicyValue, -} from "./artifact-community"; import { retainEvents, matchesEvent, @@ -2486,8 +2481,6 @@ export function createRelaySession( if (connected && !liveWasConnected) recovery?.retryNow(liveRecovery); liveWasConnected = connected; }); - const artifactCommunity = transport?.artifactCommunity; - const artifactTypePolicy = transport?.artifactTypePolicy; const session = Object.freeze({ artifactIncremental: transport?.artifactIncremental, memberAdditions, @@ -3097,55 +3090,13 @@ export function createRelaySession( * this relay has no sync; use read() with `artifact: "current"` instead. * Dispose with the plugin's scope. */ artifacts: { - ...(artifactCommunity && artifactTypePolicy + ...(transport?.artifactCommunity && transport.artifactTypePolicy ? { /** The community's id, when the relay keeps community-scoped * artifacts; always with `typePolicy`. */ - communityId: artifactCommunity, + communityId: transport.artifactCommunity, /** Each type's write policy (kind 9034), set as the viewer. */ - typePolicy: { - read: (type: string, signal: AbortSignal) => - artifactTypePolicy.read(type, signal), - /** 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. */ - async set( - change: Readonly<{ - type: string; - policy: ArtifactTypePolicyValue; - prev: string; - }>, - signal: AbortSignal, - ) { - const { writer } = artifactTypePolicy; - const event = await writer.sign( - typePolicyTemplate( - artifactCommunity, - 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) : "", - }; - } - }, - }, + typePolicy: transport.artifactTypePolicy, } : {}), sync(filter: unknown): ArtifactSyncView { diff --git a/src/features/relay/transport.test.ts b/src/features/relay/transport.test.ts index 57312ecb3b..dc3e70203b 100644 --- a/src/features/relay/transport.test.ts +++ b/src/features/relay/transport.test.ts @@ -452,11 +452,10 @@ it("reads and sets community artifact type policy through the broker's typed rou policy: "admins", revision: command.id, }); - const { created_at, kind, content, tags } = command; - await policy.writer.publish( - await policy.writer.sign({ kind, content, tags, created_at }, signal), - signal, - ); + 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, @@ -467,7 +466,7 @@ it("reads and sets community artifact type policy through the broker's typed rou ["/api/relay/artifact-type-policy", { type }], [ "/api/relay/artifact-type-policy-sign", - { kind, content, tags, created_at }, + { kind, content, tags, created_at: expect.any(Number) }, ], [ "/api/relay/artifact-type-policy-publish", diff --git a/src/features/relay/transport.ts b/src/features/relay/transport.ts index a05dcaeae0..b0e57f9c9d 100644 --- a/src/features/relay/transport.ts +++ b/src/features/relay/transport.ts @@ -74,9 +74,9 @@ import { httpReadError, ReadError } from "./errors"; import { ARTIFACT_KIND } from "../agents/agent-config-artifacts"; import { artifactCommunityId, - parseTypePolicy, - type ArtifactTypePolicyState, + 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 { @@ -177,13 +177,9 @@ export interface ReadTransport { /** 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`: the community's per-type write - * policy read, and a writer that signs and publishes only the kind-9034 - * command for this community. Never supplied to the outbox. */ - readonly artifactTypePolicy?: Readonly<{ - read(type: string, signal: AbortSignal): Promise; - writer: RelayWriter; - }>; + /** 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, @@ -937,8 +933,9 @@ export async function connectBrokerTransport( ...(artifactCommunityId(session.artifactCommunity) ? { artifactCommunity: session.artifactCommunity, - artifactTypePolicy: { - async read(type: string, signal: AbortSignal) { + artifactTypePolicy: artifactTypePolicyAccess( + session.artifactCommunity, + async (type, signal) => { const response = await fetch(`${endpoint}/artifact-type-policy`, { method: "POST", credentials: "same-origin", @@ -947,10 +944,10 @@ export async function connectBrokerTransport( signal, }); if (!response.ok) throw await readResponseError(response); - return parseTypePolicy(await response.json()); + return response.json(); }, - writer: routeWriter("artifact-type-policy"), - }, + routeWriter("artifact-type-policy"), + ), } : {}), ...(session.channelKit From a20a5cd004817774f0c70c09fe5314a45aa4e1ed Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Wed, 18 Nov 2026 06:48:12 -0500 Subject: [PATCH 9/9] test(relay): use a neutral type name and drop repeated refusal cases The Rust shape test named a feature in its sample type; it now uses com.example.settings.item, as the other tests do. Two refusal cases repeated checks that have one owner elsewhere: - The broker route test sent three malformed policy commands. Wrong tag order and an extra tag are covered by artifact-community.test.ts and the Rust shape test, so it keeps only the other-community command, which proves the route binds to its relay's community. - The access test rejected three malformed relay reads. The parser's own table covers them, so one row is kept to prove read uses it. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- browser-host/relay-broker-api.test.mjs | 40 +++++++++---------- src-tauri/src/relay/channel_writes.rs | 2 +- .../relay/artifact-type-policy.test.ts | 8 +--- 3 files changed, 21 insertions(+), 29 deletions(-) diff --git a/browser-host/relay-broker-api.test.mjs b/browser-host/relay-broker-api.test.mjs index 9e50464659..e89ad5485a 100644 --- a/browser-host/relay-broker-api.test.mjs +++ b/browser-host/relay-broker-api.test.mjs @@ -3554,28 +3554,24 @@ test("type policy commands use dedicated exact-shape routes for the relay's own try { const transport = await connectBrokerTransport(h.base); expect(transport.writer.kinds).not.toContain(ARTIFACT_TYPE_POLICY_KIND); - const [scope, ...rest] = template.tags; - const invalid = [ - { - ...template, - tags: [["community", "11111111-1111-4111-8111-111111111111"], ...rest], - }, - { ...template, tags: [...rest, scope] }, - { ...template, tags: [...template.tags, ["h", community]] }, - ]; - for (const event of invalid) { - expect((await h.post("artifact-type-policy-sign", event)).status).toBe( - 400, - ); - expect( - ( - await h.post( - "artifact-type-policy-publish", - finalizeEvent(event, viewerKey), - ) - ).status, - ).toBe(400); - } + // 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); diff --git a/src-tauri/src/relay/channel_writes.rs b/src-tauri/src/relay/channel_writes.rs index d04e5e5778..f9b0927972 100644 --- a/src-tauri/src/relay/channel_writes.rs +++ b/src-tauri/src/relay/channel_writes.rs @@ -304,7 +304,7 @@ mod tests { unset[2][1] = "everyone"; unset[3][1] = "0"; assert!(valid("artifact-type-policy", &command(unset))); - for value in ["a1.b_c-d", "com.example.mention-groups.group"] { + 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}"); diff --git a/src/features/relay/artifact-type-policy.test.ts b/src/features/relay/artifact-type-policy.test.ts index 3e606fa037..27c0884c96 100644 --- a/src/features/relay/artifact-type-policy.test.ts +++ b/src/features/relay/artifact-type-policy.test.ts @@ -47,13 +47,9 @@ it("hands a plugin only the parsed policy the relay returned", async () => { ).resolves.toEqual({ policy: "everyone", revision: null }); }); -it.each([ - ["a non-object body", null], - ["an unknown policy", { policy: "nobody", revision: null }], - ["a malformed revision", { policy: "admins", revision: "A".repeat(64) }], -])("rejects %s from the relay read", async (_, body) => { +it("rejects a relay read that is not a policy", async () => { const h = access(); - h.read.mockResolvedValueOnce(body); + h.read.mockResolvedValueOnce({ policy: "nobody", revision: null }); await expect( h.access.read(TYPE, new AbortController().signal), ).rejects.toThrow("Invalid artifact type policy");