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

173 lines
5.8 KiB
TypeScript

// Channel adapter trait, registry, error model. Mirrors Rust kez-channels.
import {
COMPACT_PROOF_PREFIX,
Identity,
type SignedClaimEnvelope,
type VerificationStatus,
extractMarkdownProof,
fromCompact,
fromJson,
parseDnsTxtValue,
verifyClaim,
} from "@kez/core";
export type ChannelErrorKind =
| "Unreachable"
| "NotFound"
| "Invalid"
| "SubjectMismatch"
| "NoChannelForSystem"
| "Other";
export class ChannelError extends Error {
readonly kind: ChannelErrorKind;
readonly expected?: Identity;
readonly found?: Identity;
readonly cause?: unknown;
constructor(
kind: ChannelErrorKind,
message: string,
opts: { cause?: unknown; expected?: Identity; found?: Identity } = {},
) {
super(message);
this.name = "ChannelError";
this.kind = kind;
this.cause = opts.cause;
this.expected = opts.expected;
this.found = opts.found;
}
static unreachable(msg: string, cause?: unknown): ChannelError {
return new ChannelError("Unreachable", `channel unreachable: ${msg}`, { cause });
}
static notFound(identity: Identity): ChannelError {
return new ChannelError("NotFound", `no KEZ proof found for ${identity}`);
}
static invalid(reason: string, cause?: unknown): ChannelError {
return new ChannelError("Invalid", `proof failed verification: ${reason}`, { cause });
}
static subjectMismatch(expected: Identity, found: Identity): ChannelError {
return new ChannelError(
"SubjectMismatch",
`proof subject ${found} did not match expected identity ${expected}`,
{ expected, found },
);
}
static noChannelForSystem(system: string): ChannelError {
return new ChannelError("NoChannelForSystem", `no channel registered for system: ${system}`);
}
static other(msg: string, cause?: unknown): ChannelError {
return new ChannelError("Other", msg, { cause });
}
}
export interface ChannelHit {
proof: SignedClaimEnvelope;
status: VerificationStatus;
}
export interface Channel {
/** The `system:` prefix this channel handles. */
readonly system: string;
fetchAndVerify(identity: Identity): Promise<ChannelHit>;
}
/** system: prefix → channel adapter, with alias support. */
export class Registry {
private channels = new Map<string, Channel>();
register(channel: Channel): void {
this.channels.set(channel.system, channel);
}
/** Register the same adapter under a different scheme (e.g. `mastodon` → `ap`). */
registerAs(system: string, channel: Channel): void {
this.channels.set(system, channel);
}
get(system: string): Channel | undefined {
return this.channels.get(system);
}
async verify(identity: Identity): Promise<ChannelHit> {
const channel = this.channels.get(identity.scheme);
if (!channel) throw ChannelError.noChannelForSystem(identity.scheme);
return channel.fetchAndVerify(identity);
}
}
/** Build a Registry with every channel shipped in this package. */
export async function defaultRegistry(): Promise<Registry> {
const r = new Registry();
const { GithubChannel } = await import("./github.js");
const { DnsChannel } = await import("./dns.js");
const { NostrChannel } = await import("./nostr.js");
const { BlueskyChannel } = await import("./bluesky.js");
const { ActivityPubChannel } = await import("./activitypub.js");
r.register(new GithubChannel());
r.register(new DnsChannel());
r.register(new NostrChannel());
r.register(new BlueskyChannel());
const ap = new ActivityPubChannel();
r.register(ap);
r.registerAs("mastodon", ap);
return r;
}
// ─────────────────────────────────────────────────────────────────────────────
// parseProof / parseAndVerifyFor — shared by every channel
// ─────────────────────────────────────────────────────────────────────────────
/** Try all four wire encodings. Compact form may be embedded in prose. */
export function parseProof(raw: string): SignedClaimEnvelope {
const trimmed = raw.trim();
if (trimmed.includes("```kez")) return extractMarkdownProof(trimmed);
if (trimmed.startsWith("{")) return fromJson(trimmed);
if (trimmed.startsWith("kez1:")) return parseDnsTxtValue(trimmed);
const token = extractCompactToken(trimmed);
if (token) return fromCompact(token);
throw new Error("unknown KEZ proof format");
}
/** Parse, verify signature, and require the subject to equal `expected`. */
export function parseAndVerifyFor(raw: string, expected: Identity): ChannelHit {
let proof: SignedClaimEnvelope;
try {
proof = parseProof(raw);
} catch (e) {
throw ChannelError.invalid((e as Error).message, e);
}
let status: VerificationStatus;
try {
status = verifyClaim(proof);
} catch (e) {
throw ChannelError.invalid((e as Error).message, e);
}
if (proof.payload.subject !== expected.toString()) {
throw ChannelError.subjectMismatch(expected, Identity.parse(proof.payload.subject));
}
return { proof, status };
}
/** Find `kez:z1:<base64url>` anywhere in `text` and return the full token. */
export function extractCompactToken(text: string): string | undefined {
const idx = text.indexOf(COMPACT_PROOF_PREFIX);
if (idx < 0) return undefined;
const after = text.slice(idx + COMPACT_PROOF_PREFIX.length);
let end = 0;
while (end < after.length) {
const c = after.charCodeAt(end);
const isAlphaNum =
(c >= 0x30 && c <= 0x39) || // 0-9
(c >= 0x41 && c <= 0x5a) || // A-Z
(c >= 0x61 && c <= 0x7a); // a-z
const isUrlSafe = c === 0x5f /* _ */ || c === 0x2d; /* - */
if (!isAlphaNum && !isUrlSafe) break;
end++;
}
if (end === 0) return undefined;
return COMPACT_PROOF_PREFIX + after.slice(0, end);
}