Tudisco d0db6f00f1 Initial implementation of KEZ — protocol, two impls, and storage server
KEZ is a portable, decentralized identity graph: a person signs claims
linking their many accounts, publishes those claims in places only the
claimed account can publish to, and anyone can verify the connections
without trusting a central server.

Layout
------
- SPEC.md            Language-agnostic protocol spec (v0.2)
- rust/              Rust implementation: kez-core, kez-channels, kez-cli
- nodejs/            TypeScript port at full parity
- rust-sig-server/   Optional axum + SQLite storage server for sigchains
- crosstest.sh       Cross-implementation interop harness

Capabilities (both implementations, byte-compatible)
----------------------------------------------------
- Two primary-key algorithms: nostr/secp256k1 Schnorr (BIP-340) and
  Ed25519 (RFC 8032). Identifiers: nostr:npub1... and ed25519:<hex>.
- JCS (RFC 8785) canonicalization for everything signed.
- Four proof encodings: JSON envelope, compact (kez:z1:<base64url(zstd(json))>),
  Markdown fence, DNS TXT.
- Five channel plugins (no API keys, no auth needed for any of them):
    dns:        system resolver, _kez.<domain> TXT records
    github:     public gist scan + <user>/<user> profile README fallback
    nostr:      kind-30078 events from default relays
    bluesky:    public AppView author feed
    ap:         WebFinger + actor JSON (alias mastodon:)
- Identical CLI surface:
    kez identity new [--key-type nostr|ed25519]
    kez claim create <subject> (--nsec | --ed25519-seed) [--format ...] [--out ...]
    kez claim dns <domain>     (--nsec | --ed25519-seed)
    kez verify file <path>
    kez verify id <identifier>
    kez sigchain add|revoke|show|export|publish
- Sigchains: append-only signed log per primary, hash-chained per spec §6,
  stored locally at ~/.kez/sigchains/, exportable as JSONL or kez:zc1: bundle.
- Sigchain publish destinations: chain server, web (file dump), DNS (zone
  record print), nostr (kind-30078 wrapping event).

kez-sig-server
--------------
Optional storage tier. Axum + SQLite, single binary, no external deps.

- No auth — the cryptography is the access control. The server validates
  every signature, every seq, every prev hash before storing.
- REST API: POST /v1/sigchains/{scheme}/{id}/events (append signed event,
  201 with new head hash or 4xx); GET /{scheme}/{id} (full chain as JSONL);
  GET /head; GET /healthz.
- Designed for one central instance for now; the design doesn't preclude
  running more later (clients gain a configurable list, verifiers
  reconcile per spec §6.2).
- Channel-based publishing remains the always-available fallback if the
  server is unavailable.

Tests
-----
- rust/                 99 tests
- rust-sig-server/      10 integration tests (real HTTP, real SQLite)
- nodejs/               91 tests (vitest)
- crosstest.sh          19 cross-impl scenarios — proves JCS bytes,
                        Schnorr + Ed25519 sigs, all four claim encodings,
                        and the sigchain JSONL bundle are byte-compatible
                        between Rust and Node in both directions.

What's not done yet
-------------------
- verify id consulting the sigchain for revocations (data path exists,
  just not wired into the verifier output).
- rotate and add_device sigchain ops (types reserved).
- expires_at enforcement during claim verification.
- Typed VerificationStatus.status reflecting the five failure modes.
- Auth-required publishers (GitHub gist, Bluesky, ActivityPub).
2026-05-24 14:41:00 -06:00

274 lines
7.7 KiB
TypeScript

// Nostr channel: queries relays for kind-30078 events authored by the
// requested npub, then runs each event's content through parseAndVerifyFor.
// Fetcher is abstracted so tests use canned events.
import { type Identity, NostrSecret, nostrPubkeyHex } from "@kez/core";
import { sha256 } from "@noble/hashes/sha2";
import { bytesToHex } from "@noble/hashes/utils";
import { ChannelError, type Channel, type ChannelHit, parseAndVerifyFor } from "./index.js";
export const KEZ_NOSTR_KIND = 30078;
const DEFAULT_RELAYS = ["wss://relay.damus.io", "wss://nos.lol", "wss://relay.primal.net"];
const FETCH_TIMEOUT_MS = 8_000;
export interface NostrFilter {
authors: string[]; // lowercase hex pubkeys
kinds: number[];
limit?: number;
}
export interface NostrEvent {
id: string;
pubkey: string;
created_at: number;
kind: number;
tags: string[][];
content: string;
sig: string;
}
export interface NostrFetcher {
fetchEvents(filter: NostrFilter): Promise<NostrEvent[]>;
}
export class RelayPoolFetcher implements NostrFetcher {
constructor(private relays: string[] = DEFAULT_RELAYS) {}
async fetchEvents(filter: NostrFilter): Promise<NostrEvent[]> {
let lastError: Error | undefined;
const events: NostrEvent[] = [];
for (const relay of this.relays) {
try {
events.push(...(await queryRelay(relay, filter)));
} catch (e) {
lastError = e as Error;
}
if (events.length > 0) break;
}
if (events.length === 0 && lastError) {
throw ChannelError.unreachable(lastError.message, lastError);
}
return events;
}
}
async function queryRelay(url: string, filter: NostrFilter): Promise<NostrEvent[]> {
// Node 22+ ships a global WebSocket; we use it directly.
// eslint-disable-next-line no-undef
const ws = new WebSocket(url);
const subId = "kez-1";
const events: NostrEvent[] = [];
await new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => {
try {
ws.close();
} catch {
/* noop */
}
reject(new Error(`relay ${url} timed out after ${FETCH_TIMEOUT_MS}ms`));
}, FETCH_TIMEOUT_MS);
ws.addEventListener("open", () => {
ws.send(buildReqMessage(subId, filter));
});
ws.addEventListener("message", (ev: MessageEvent) => {
const parsed = parseRelayMessage(typeof ev.data === "string" ? ev.data : String(ev.data));
if (parsed.kind === "event") events.push(parsed.event);
else if (parsed.kind === "eose") {
clearTimeout(timer);
try {
ws.send(JSON.stringify(["CLOSE", subId]));
} catch {
/* noop */
}
try {
ws.close();
} catch {
/* noop */
}
resolve();
}
});
ws.addEventListener("error", () => {
clearTimeout(timer);
reject(new Error(`relay ${url} websocket error`));
});
ws.addEventListener("close", () => {
clearTimeout(timer);
resolve();
});
});
return events;
}
export class NostrChannel implements Channel {
readonly system = "nostr";
private readonly fetcher: NostrFetcher;
constructor(fetcher: NostrFetcher = new RelayPoolFetcher()) {
this.fetcher = fetcher;
}
async fetchAndVerify(identity: Identity): Promise<ChannelHit> {
const pubkeyHex = nostrPubkeyHex(identity);
const filter: NostrFilter = {
authors: [pubkeyHex],
kinds: [KEZ_NOSTR_KIND],
limit: 20,
};
let events: NostrEvent[];
try {
events = await this.fetcher.fetchEvents(filter);
} catch (e) {
if (e instanceof ChannelError) throw e;
throw ChannelError.unreachable((e as Error).message, e);
}
let lastError: ChannelError | undefined;
for (const ev of events) {
if (!eventMatchesAuthor(ev, pubkeyHex)) continue;
try {
return parseAndVerifyFor(ev.content, identity);
} catch (e) {
lastError = e instanceof ChannelError ? e : ChannelError.invalid((e as Error).message, e);
}
}
throw lastError ?? ChannelError.notFound(identity);
}
}
/**
* Build and sign a NIP-01 event. Event id = sha256 of the canonical array
* [0, pubkey, created_at, kind, tags, content]; signature = Schnorr over
* that id. Matches Rust's `build_signed_event` byte-for-byte.
*/
export function buildSignedEvent(
signer: NostrSecret,
createdAt: number,
kind: number,
tags: string[][],
content: string,
): NostrEvent {
const pubkey = signer.pubkeyHex();
const canonical = JSON.stringify([0, pubkey, createdAt, kind, tags, content]);
const digest = sha256(new TextEncoder().encode(canonical));
const id = bytesToHex(digest);
const sig = bytesToHex(signer.signDigest(digest));
return { id, pubkey, created_at: createdAt, kind, tags, content, sig };
}
/**
* Publish a single event to one relay. Waits up to 5s for `["OK", id, true]`;
* silently accepts timeouts (many relays accept without replying).
*/
export async function publishEventToRelay(
relayUrl: string,
event: NostrEvent,
): Promise<void> {
// eslint-disable-next-line no-undef
const ws = new WebSocket(relayUrl);
const deadline = 5_000;
await new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => {
try {
ws.close();
} catch {
/* noop */
}
// Timeout = treat as accepted; client can re-fetch to confirm.
resolve();
}, deadline);
ws.addEventListener("open", () => {
try {
ws.send(JSON.stringify(["EVENT", event]));
} catch (e) {
clearTimeout(timer);
reject(ChannelError.unreachable(`send EVENT ${relayUrl}: ${(e as Error).message}`));
}
});
ws.addEventListener("message", (ev: MessageEvent) => {
const text = typeof ev.data === "string" ? ev.data : String(ev.data);
let arr: unknown;
try {
arr = JSON.parse(text);
} catch {
return;
}
if (!Array.isArray(arr)) return;
if (arr[0] === "OK") {
clearTimeout(timer);
try {
ws.close();
} catch {
/* noop */
}
if (arr[2] === false) {
const reason = typeof arr[3] === "string" ? arr[3] : "";
reject(
ChannelError.other(`relay ${relayUrl} rejected event: ${reason}`),
);
} else {
resolve();
}
}
// NOTICE messages are informational; keep waiting.
});
ws.addEventListener("error", () => {
clearTimeout(timer);
reject(ChannelError.unreachable(`relay ${relayUrl} websocket error`));
});
});
}
export function buildReqMessage(subId: string, filter: NostrFilter): string {
const spec: Record<string, unknown> = {
authors: filter.authors,
kinds: filter.kinds,
};
if (filter.limit !== undefined) spec.limit = filter.limit;
return JSON.stringify(["REQ", subId, spec]);
}
export function eventMatchesAuthor(event: NostrEvent, expectedHex: string): boolean {
return event.pubkey.toLowerCase() === expectedHex.toLowerCase();
}
export type RelayMessage =
| { kind: "event"; event: NostrEvent }
| { kind: "eose" }
| { kind: "other" };
export function parseRelayMessage(text: string): RelayMessage {
try {
const arr = JSON.parse(text);
if (!Array.isArray(arr)) return { kind: "other" };
if (arr[0] === "EVENT" && typeof arr[2] === "object" && arr[2] !== null) {
const ev = arr[2] as NostrEvent;
if (
typeof ev.id === "string" &&
typeof ev.pubkey === "string" &&
typeof ev.kind === "number" &&
typeof ev.content === "string" &&
typeof ev.sig === "string"
) {
return { kind: "event", event: ev };
}
}
if (arr[0] === "EOSE") return { kind: "eose" };
return { kind: "other" };
} catch {
return { kind: "other" };
}
}