feat: rename to BitGate and close the drop-in gap

Renames the project and makes it as easy to adopt as BitLogin, which was the
stated bar and which it did not previously meet.

Rename (ADR 0005): @nostr-governance/* -> @bitgate/*, governance-* elements ->
bitgate-*, createGovernanceRuntime -> createBitGate. "Governance" reads as DAO
voting to this audience and named a category rather than a product; BitGate
names the benefit and joins the bit- family that BitVid and BitRoad compose
with. Domain types keep their names — the product is BitGate, the subject
matter is still governance. The migration plan is left as written; this ADR
records the change rather than rewriting history.

Drop-in distribution (ADR 0006): adopting BitGate meant supplying a transport,
authoring a policy, and wiring every element in JavaScript. Now:

- createRelayTransport(urls) — WebSocket transport with reconnection, backoff,
  subscription replay, and cross-relay dedupe
- policy presets (social, commerce, admin-only) addressable by name; the engine
  still carries no thresholds of its own
- <bitgate-provider> — configuration in markup, with descendants finding the
  runtime through a bubbling context event rather than DOM walking, which
  breaks across shadow boundaries
- npm run build:widget — a self-contained dist/bitgate.js

That last one came from running it in a browser rather than from a test. Bare
specifiers resolve in Node and vitest but not in a browser, so the widget
source worked everywhere except a plain static page — the one place it exists
to serve. The bundle is not committed: consumers build from reviewed source.

Also found by running it: the provider's ready event fires during element
upgrade, before a page that defines elements after parsing can attach a
listener, so it now exposes `ready` as a promise too.

Four bugs fixed along the way, three found by new tests and one by the browser:
admin state stayed silent when a roster change altered capabilities but no
denials; the relay transport sent every subscription twice on connect; the
commerce preset computed a meaningless visibility verdict at checkout and could
hide a listing from its own seller; <bitgate-status> threw on an unusable
decision.

759 tests; lint, typecheck, and both builds clean.
This commit is contained in:
thePR0M3TH3AN committed 2026-08-09 19:58:45 -04:00
1 parent 7f70a64d61
commit adeba151b8
63 files changed
+2774 -401

No files matched your search

+6 -6
View File
@@ -1,10 +1,10 @@
import { describe, expect, it, vi } from "vitest";
import { createPolicyDefinition } from "@nostr-governance/core";
import { REPORT_KIND, encodeRoles } from "@nostr-governance/nostr";
import { createPolicyDefinition } from "@bitgate/core";
import { REPORT_KIND, encodeRoles } from "@bitgate/nostr";
import { ERROR_CODES, createCommands } from "../src/commands.js";
import { createGovernanceRuntime } from "../src/runtime.js";
import { createBitGate } from "../src/runtime.js";
import { createMemoryTransport } from "../src/interfaces.js";
const ROOT = "a1".repeat(32);
@@ -45,7 +45,7 @@ function signerFor(pubkey) {
*/
function setup({ actor = MODERATOR, signer, transport } = {}) {
const memory = transport ?? createMemoryTransport();
const runtime = createGovernanceRuntime({
const runtime = createBitGate({
applicationId: "test",
namespace: "app",
transport: memory,
@@ -177,7 +177,7 @@ describe("argument validation", () => {
describe("signer failures", () => {
it("reports a missing signer", async () => {
const runtime = createGovernanceRuntime({
const runtime = createBitGate({
applicationId: "test",
namespace: "app",
transport: createMemoryTransport(),
@@ -244,7 +244,7 @@ describe("contribution round-trip", () => {
const { runtime, commands, transport } = setup();
await commands.denyUser(CREATOR);
const fresh = createGovernanceRuntime({
const fresh = createBitGate({
applicationId: "test",
namespace: "app",
transport: createMemoryTransport(),
+11 -11
View File
@@ -3,15 +3,15 @@
import { describe, expect, it, vi } from "vitest";
import { createPolicyDefinition } from "@nostr-governance/core";
import { createPolicyDefinition } from "@bitgate/core";
import {
CANONICAL_KIND,
MUTE_LIST_KIND,
encodeContribution,
encodeRoles,
} from "@nostr-governance/nostr";
} from "@bitgate/nostr";
import { createGovernanceRuntime } from "../src/runtime.js";
import { createBitGate } from "../src/runtime.js";
import { createMemoryStorage, createMemoryTransport } from "../src/interfaces.js";
const ROOT = "a1".repeat(32);
@@ -66,11 +66,11 @@ const denyEvent = () =>
* @param {Object} [options]
* @param {import('../src/interfaces.js').GovernanceStorage} [options.storage]
* @param {any} [options.transport]
* @param {import('@nostr-governance/nostr').SignatureVerifier} [options.verifySignature]
* @param {import('@bitgate/nostr').SignatureVerifier} [options.verifySignature]
* @param {string} [options.root]
*/
function makeRuntime({ storage, transport, verifySignature, root = ROOT } = {}) {
return createGovernanceRuntime({
return createBitGate({
applicationId: "test",
namespace: "app",
transport: transport ?? createMemoryTransport([rolesEvent(), denyEvent()]),
@@ -92,7 +92,7 @@ describe("persistence", () => {
expect(writes).toHaveBeenCalled();
const [key] = writes.mock.calls[0];
expect(key).toMatch(/^nostr-governance:test:app:[0-9a-f]{16}:v1:admin$/);
expect(key).toMatch(/^bitgate:test:app:[0-9a-f]{16}:v1:admin$/);
});
it("restores administrative state without touching a relay", async () => {
@@ -257,7 +257,7 @@ describe("trusted mute list subscriptions", () => {
it("subscribes by author, chunked", () => {
const transport = createMemoryTransport();
const subscribe = vi.spyOn(transport, "subscribe");
const runtime = createGovernanceRuntime({
const runtime = createBitGate({
applicationId: "t",
namespace: "app",
transport,
@@ -275,7 +275,7 @@ describe("trusted mute list subscriptions", () => {
it("ingests a delivered mute list into evaluation", () => {
const transport = createMemoryTransport();
const runtime = createGovernanceRuntime({
const runtime = createBitGate({
applicationId: "t",
namespace: "app",
transport,
@@ -331,13 +331,13 @@ describe("community sources", () => {
});
const merged = await runtime.loadCommunitySources([
{ curator: CURATOR, identifier: "app:governance:user-deny:v1", kind: CANONICAL_KIND },
{ curator: CURATOR, identifier: "app:bitgate:user-deny:v1", kind: CANONICAL_KIND },
]);
expect(merged).toBe(1);
expect(runtime.admin.state.userDeny.has(`user:${CREATOR}`)).toBe(true);
expect(runtime.admin.state.communitySources.get(`user:${CREATOR}`)).toEqual([
`${CURATOR}:app:governance:user-deny:v1`,
`${CURATOR}:app:bitgate:user-deny:v1`,
]);
});
@@ -357,7 +357,7 @@ describe("community sources", () => {
runtime.admin.setRoles({ root: ROOT, actors: { [CURATOR]: ["curator"] } });
await runtime.loadCommunitySources([
{ curator: CURATOR, identifier: "app:governance:event-deny:v1", kind: CANONICAL_KIND },
{ curator: CURATOR, identifier: "app:bitgate:event-deny:v1", kind: CANONICAL_KIND },
]);
expect(runtime.admin.state.eventDeny.size).toBe(0);
@@ -0,0 +1,391 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { createRelayTransport } from "../src/relayTransport.js";
const NOW = 1_750_000_000;
/** Every socket built during a test, so assertions can drive them. */
let sockets = [];
/** A scriptable WebSocket stand-in. */
class FakeSocket {
constructor(url) {
this.url = url;
this.sent = [];
this.closed = false;
this.onopen = null;
this.onmessage = null;
this.onerror = null;
this.onclose = null;
sockets.push(this);
}
send(payload) {
this.sent.push(JSON.parse(payload));
}
close() {
this.closed = true;
}
/** Simulate the relay accepting the connection. */
open() {
this.onopen?.();
}
/** Simulate a frame arriving from the relay. */
deliver(frame) {
this.onmessage?.({ data: JSON.stringify(frame) });
}
/** Simulate the connection dropping. */
drop() {
this.onclose?.();
}
/** Frames of a given verb that this socket was asked to send. */
sentOf(verb) {
return this.sent.filter((frame) => frame[0] === verb);
}
}
const event = (id) => ({
id,
pubkey: "a1".repeat(32),
kind: 1,
created_at: NOW,
tags: [],
content: "",
});
function makeTransport(urls = ["wss://one.example"], options = {}) {
return createRelayTransport(urls, { WebSocketImpl: /** @type {any} */ (FakeSocket), ...options });
}
afterEach(() => {
sockets = [];
vi.useRealTimers();
});
describe("construction", () => {
it("requires at least one relay", () => {
expect(() => makeTransport([])).toThrow(/at least one relay/);
expect(() => makeTransport([" ", ""])).toThrow(/at least one relay/);
});
it("requires a usable WebSocket implementation", () => {
// Node 22 has a global WebSocket, so passing null correctly falls back to
// it. The guard is for environments that have neither.
expect(() =>
createRelayTransport(["wss://one.example"], { WebSocketImpl: /** @type {any} */ (42) }),
).toThrow(/WebSocket implementation/);
});
it("falls back to the global WebSocket when none is injected", () => {
expect(() => createRelayTransport(["wss://one.example"])).not.toThrow();
});
it("opens one socket per relay", () => {
makeTransport(["wss://one.example", "wss://two.example"]);
expect(sockets.map((socket) => socket.url)).toEqual([
"wss://one.example",
"wss://two.example",
]);
});
it("trims and drops blank relay URLs", () => {
const transport = makeTransport([" wss://one.example ", ""]);
expect(transport.relays).toEqual(["wss://one.example"]);
});
});
describe("connection lifecycle", () => {
it("issues a subscription exactly once when it opens", () => {
const transport = makeTransport();
transport.subscribe([{ kinds: [1] }], {});
// Nothing can be sent yet — the socket has not opened.
expect(sockets[0].sent).toHaveLength(0);
sockets[0].open();
// Re-issued from the subscription map, not also flushed from the queue.
expect(sockets[0].sentOf("REQ")).toHaveLength(1);
});
it("queues a publish made before the socket opens", async () => {
const transport = makeTransport();
const published = event("bb".repeat(32));
const pending = transport.publish(published);
expect(sockets[0].sentOf("EVENT")).toHaveLength(0);
sockets[0].open();
expect(sockets[0].sentOf("EVENT")).toHaveLength(1);
sockets[0].deliver(["OK", published.id, true, ""]);
expect((await pending).ok).toBe(true);
});
it("re-opens live subscriptions after a reconnect", () => {
vi.useFakeTimers();
const transport = makeTransport(["wss://one.example"], { reconnectDelay: 10 });
sockets[0].open();
transport.subscribe([{ kinds: [1] }], {});
expect(sockets[0].sentOf("REQ")).toHaveLength(1);
sockets[0].drop();
vi.advanceTimersByTime(20);
// A fresh socket was created and the subscription re-issued on open.
expect(sockets).toHaveLength(2);
sockets[1].open();
expect(sockets[1].sentOf("REQ")).toHaveLength(1);
});
it("backs off between reconnect attempts", () => {
vi.useFakeTimers();
makeTransport(["wss://one.example"], { reconnectDelay: 100 });
sockets[0].drop();
vi.advanceTimersByTime(100);
expect(sockets).toHaveLength(2);
// Second failure waits longer than the first.
sockets[1].drop();
vi.advanceTimersByTime(100);
expect(sockets).toHaveLength(2);
vi.advanceTimersByTime(100);
expect(sockets).toHaveLength(3);
});
it("stops reconnecting once closed", () => {
vi.useFakeTimers();
const transport = makeTransport(["wss://one.example"], { reconnectDelay: 10 });
transport.close();
sockets[0].drop();
vi.advanceTimersByTime(500);
expect(sockets).toHaveLength(1);
});
it("closes every socket on close", () => {
const transport = makeTransport(["wss://one.example", "wss://two.example"]);
transport.close();
expect(sockets.every((socket) => socket.closed)).toBe(true);
});
});
describe("list", () => {
it("resolves with stored events once every relay sends EOSE", async () => {
const transport = makeTransport(["wss://one.example", "wss://two.example"]);
sockets.forEach((socket) => socket.open());
const pending = transport.list([{ kinds: [1] }]);
const id = sockets[0].sentOf("REQ")[0][1];
sockets[0].deliver(["EVENT", id, event("aa".repeat(32))]);
sockets[0].deliver(["EOSE", id]);
sockets[1].deliver(["EOSE", id]);
expect(await pending).toHaveLength(1);
});
it("deduplicates events served by more than one relay", async () => {
const transport = makeTransport(["wss://one.example", "wss://two.example"]);
sockets.forEach((socket) => socket.open());
const pending = transport.list([{ kinds: [1] }]);
const id = sockets[0].sentOf("REQ")[0][1];
const duplicate = event("aa".repeat(32));
sockets[0].deliver(["EVENT", id, duplicate]);
sockets[1].deliver(["EVENT", id, duplicate]);
sockets[0].deliver(["EOSE", id]);
sockets[1].deliver(["EOSE", id]);
expect(await pending).toHaveLength(1);
});
it("returns what it has when a relay never answers", async () => {
vi.useFakeTimers();
const transport = makeTransport(["wss://one.example", "wss://slow.example"], {
listTimeout: 1_000,
});
sockets.forEach((socket) => socket.open());
const pending = transport.list([{ kinds: [1] }]);
const id = sockets[0].sentOf("REQ")[0][1];
sockets[0].deliver(["EVENT", id, event("aa".repeat(32))]);
sockets[0].deliver(["EOSE", id]);
// The second relay stays silent; the timeout must not discard what arrived.
await vi.advanceTimersByTimeAsync(1_000);
expect(await pending).toHaveLength(1);
});
it("closes the subscription when it resolves", async () => {
const transport = makeTransport();
sockets[0].open();
const pending = transport.list([{ kinds: [1] }]);
const id = sockets[0].sentOf("REQ")[0][1];
sockets[0].deliver(["EOSE", id]);
await pending;
expect(sockets[0].sentOf("CLOSE")[0][1]).toBe(id);
});
it("ignores malformed frames", async () => {
const transport = makeTransport();
sockets[0].open();
const pending = transport.list([{ kinds: [1] }]);
const id = sockets[0].sentOf("REQ")[0][1];
sockets[0].onmessage?.({ data: "not json" });
sockets[0].onmessage?.({ data: JSON.stringify({ not: "an array" }) });
sockets[0].deliver(["EOSE", id]);
expect(await pending).toEqual([]);
});
});
describe("subscribe", () => {
it("delivers events to the handler", () => {
const transport = makeTransport();
sockets[0].open();
const onEvent = vi.fn();
transport.subscribe([{ kinds: [1] }], { onEvent });
const id = sockets[0].sentOf("REQ")[0][1];
sockets[0].deliver(["EVENT", id, event("aa".repeat(32))]);
expect(onEvent).toHaveBeenCalledTimes(1);
});
it("deduplicates across relays", () => {
const transport = makeTransport(["wss://one.example", "wss://two.example"]);
sockets.forEach((socket) => socket.open());
const onEvent = vi.fn();
transport.subscribe([{ kinds: [1] }], { onEvent });
const id = sockets[0].sentOf("REQ")[0][1];
const duplicate = event("aa".repeat(32));
sockets[0].deliver(["EVENT", id, duplicate]);
sockets[1].deliver(["EVENT", id, duplicate]);
expect(onEvent).toHaveBeenCalledTimes(1);
});
it("reports EOSE", () => {
const transport = makeTransport();
sockets[0].open();
const onEose = vi.fn();
transport.subscribe([{ kinds: [1] }], { onEose });
sockets[0].deliver(["EOSE", sockets[0].sentOf("REQ")[0][1]]);
expect(onEose).toHaveBeenCalled();
});
it("stops delivering after close", () => {
const transport = makeTransport();
sockets[0].open();
const onEvent = vi.fn();
const handle = transport.subscribe([{ kinds: [1] }], { onEvent });
const id = sockets[0].sentOf("REQ")[0][1];
handle.close();
sockets[0].deliver(["EVENT", id, event("aa".repeat(32))]);
expect(onEvent).not.toHaveBeenCalled();
expect(sockets[0].sentOf("CLOSE")).toHaveLength(1);
});
});
describe("publish", () => {
it("succeeds when a relay accepts", async () => {
const transport = makeTransport();
sockets[0].open();
const published = event("bb".repeat(32));
const pending = transport.publish(published);
sockets[0].deliver(["OK", published.id, true, ""]);
const result = await pending;
expect(result.ok).toBe(true);
expect(result.accepted).toEqual(["wss://one.example"]);
});
it("treats partial acceptance as success and keeps failures visible", async () => {
const transport = makeTransport(["wss://one.example", "wss://two.example"]);
sockets.forEach((socket) => socket.open());
const published = event("bb".repeat(32));
const pending = transport.publish(published);
sockets[0].deliver(["OK", published.id, true, ""]);
sockets[1].deliver(["OK", published.id, false, "blocked: spam"]);
const result = await pending;
expect(result.ok).toBe(true);
expect(result.accepted).toEqual(["wss://one.example"]);
expect(result.failed).toEqual([{ relay: "wss://two.example", error: "blocked: spam" }]);
});
it("fails when every relay rejects", async () => {
const transport = makeTransport();
sockets[0].open();
const published = event("bb".repeat(32));
const pending = transport.publish(published);
sockets[0].deliver(["OK", published.id, false, "rejected"]);
const result = await pending;
expect(result.ok).toBe(false);
expect(result.failed).toHaveLength(1);
});
it("reports silent relays as timed out rather than omitting them", async () => {
vi.useFakeTimers();
const transport = makeTransport(["wss://one.example", "wss://quiet.example"], {
listTimeout: 500,
});
sockets.forEach((socket) => socket.open());
const published = event("bb".repeat(32));
const pending = transport.publish(published);
sockets[0].deliver(["OK", published.id, true, ""]);
await vi.advanceTimersByTimeAsync(500);
const result = await pending;
expect(result.ok).toBe(true);
expect(result.failed).toEqual([{ relay: "wss://quiet.example", error: "timeout" }]);
});
it("ignores OK frames for a different event", async () => {
vi.useFakeTimers();
const transport = makeTransport(["wss://one.example"], { listTimeout: 200 });
sockets[0].open();
const published = event("bb".repeat(32));
const pending = transport.publish(published);
sockets[0].deliver(["OK", "cc".repeat(32), true, ""]);
await vi.advanceTimersByTimeAsync(200);
const result = await pending;
expect(result.ok).toBe(false);
});
it("does not stack handlers across repeated publishes", async () => {
const transport = makeTransport();
sockets[0].open();
for (const id of ["aa", "bb", "cc"]) {
const published = event(id.repeat(32));
const pending = transport.publish(published);
sockets[0].deliver(["OK", published.id, true, ""]);
expect((await pending).ok).toBe(true);
}
expect(sockets[0].sentOf("EVENT")).toHaveLength(3);
});
});
+12 -12
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { createPolicyDefinition } from "@nostr-governance/core";
import { createPolicyDefinition } from "@bitgate/core";
import {
CANONICAL_KIND,
MUTE_LIST_KIND,
@@ -8,9 +8,9 @@ import {
canonicalIdentifier,
encodeContribution,
encodeRoles,
} from "@nostr-governance/nostr";
} from "@bitgate/nostr";
import { GovernanceRuntime, chunk, createGovernanceRuntime } from "../src/runtime.js";
import { GovernanceRuntime, chunk, createBitGate } from "../src/runtime.js";
import { createMemoryTransport, storageKey } from "../src/interfaces.js";
const ROOT = "a1".repeat(32);
@@ -37,8 +37,8 @@ const POLICY = createPolicyDefinition({
});
/**
* @param {Partial<import('@nostr-governance/nostr').NostrEvent>} parts
* @returns {import('@nostr-governance/nostr').NostrEvent}
* @param {Partial<import('@bitgate/nostr').NostrEvent>} parts
* @returns {import('@bitgate/nostr').NostrEvent}
*/
const event = (parts) => ({
id: "00".repeat(32),
@@ -57,7 +57,7 @@ const rolesEvent = () =>
...encodeRoles({ actors: { [MODERATOR]: ["moderator"] }, protectedActors: [] }, "app"),
});
/** @param {import('@nostr-governance/core').GovernanceTarget} [target] */
/** @param {import('@bitgate/core').GovernanceTarget} [target] */
const denyEvent = (target = { type: "user", pubkey: CREATOR }) =>
event({
id: "bb".repeat(32),
@@ -66,7 +66,7 @@ const denyEvent = (target = { type: "user", pubkey: CREATOR }) =>
function makeRuntime(events = []) {
const transport = createMemoryTransport(events);
const runtime = createGovernanceRuntime({
const runtime = createBitGate({
applicationId: "test-app",
namespace: "app",
transport,
@@ -100,7 +100,7 @@ describe("storageKey", () => {
schemaVersion: "v1",
scope: "admin",
}),
).toBe("nostr-governance:bitroad:bitroad:abcd:v1:admin");
).toBe("bitgate:bitroad:bitroad:abcd:v1:admin");
});
it("appends the viewer for viewer-scoped state", () => {
@@ -260,7 +260,7 @@ describe("loadAdministrativeState", () => {
it("can restrict the query to known authors", async () => {
const transport = createMemoryTransport([rolesEvent(), denyEvent()]);
const listSpy = vi.spyOn(transport, "list");
const runtime = createGovernanceRuntime({
const runtime = createBitGate({
applicationId: "a",
namespace: "app",
transport,
@@ -277,7 +277,7 @@ describe("active targets and subscriptions", () => {
it("chunks report subscriptions rather than opening one per target", () => {
const transport = createMemoryTransport();
const subscribeSpy = vi.spyOn(transport, "subscribe");
const runtime = createGovernanceRuntime({
const runtime = createBitGate({
applicationId: "a",
namespace: "app",
transport,
@@ -299,7 +299,7 @@ describe("active targets and subscriptions", () => {
it("separates event and user filters", () => {
const transport = createMemoryTransport();
const subscribeSpy = vi.spyOn(transport, "subscribe");
const runtime = createGovernanceRuntime({
const runtime = createBitGate({
applicationId: "a",
namespace: "app",
transport,
@@ -411,7 +411,7 @@ describe("evaluation", () => {
runtime.ingestEvent(rolesEvent());
runtime.ingestEvent(denyEvent());
/** @type {import('@nostr-governance/core').GovernanceTarget} */
/** @type {import('@bitgate/core').GovernanceTarget} */
const target = { type: "user", pubkey: CREATOR };
const many = runtime.evaluateMany([target], { profile: "feed" });
expect(many.get(`user:${CREATOR}`)).toEqual(runtime.evaluate(target, { profile: "feed" }));
+2 -2
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { createPolicyDefinition } from "@nostr-governance/core";
import { createPolicyDefinition } from "@bitgate/core";
import { Emitter } from "../src/emitter.js";
import {
@@ -18,7 +18,7 @@ const CREATOR = "d4".repeat(32);
const OTHER = "e5".repeat(32);
const DAY = 86_400;
/** @param {string} pubkey @returns {import("@nostr-governance/core").UserTarget} */
/** @param {string} pubkey @returns {import("@bitgate/core").UserTarget} */
const user = (pubkey) => ({ type: "user", pubkey });
const roster = {