@johnhenry/browsermesh-realm 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.mjs ADDED
@@ -0,0 +1,19 @@
1
+ export { RealmError } from "./errors.mjs";
2
+ export {
3
+ DOMAINS, DEFAULT_TTL, MIN_TTL, MAX_TTL, DEFAULT_SKEW, MAX_SKEW, MAX_DESCRIPTOR_BYTES, MAX_CREDENTIAL_BYTES, MAX_CHAIN,
4
+ MAX_ISSUERS, MAX_REVOKED,
5
+ } from "./limits.mjs";
6
+ export { keyId, publicKeyOf } from "./keys.mjs";
7
+ export { validateScope, validateRoles, defaultRole, isPrivilegedScope, GUEST_ROLE } from "./roles.mjs";
8
+ export {
9
+ createDescriptor, signDescriptor, verifyDescriptor, createAuthorityless, verifyAuthorityless, checkRendezvous, isStale,
10
+ } from "./descriptor.mjs";
11
+ export { createRotation, signRotation, countersignRotation, verifyRotation, verifyChain } from "./rotation.mjs";
12
+ export { adoptDescriptor } from "./adopt.mjs";
13
+ export { issueCredential, verifyCredential, checkSubject } from "./credential.mjs";
14
+ export { createCredentialTracker } from "./tracker.mjs";
15
+ export { createLedger, importLedger } from "./ledger.mjs";
16
+ export { FRAME_TYPES, MAX_FRAME_BYTES, MIN_SEAM_FRAME_BYTES, parseFrame } from "./frames.mjs";
17
+ export { createDescriptorStore } from "./store.mjs";
18
+ export { createRealmVerifier } from "./verifier.mjs";
19
+ export { createRealmProver } from "./prover.mjs";
package/src/keys.mjs ADDED
@@ -0,0 +1,78 @@
1
+ import { encodeBase64url, decodeBase64url, canonicalJson, domainSigningBytes } from "@johnhenry/browsermesh-primitives";
2
+ import { fail } from "./errors.mjs";
3
+
4
+ /** A raw Ed25519 key or signature as strict base64url (no padding, no stray bits). */
5
+ function decodeExact(str, bytes) {
6
+ const chars = Math.ceil((bytes * 8) / 6);
7
+ if (typeof str !== "string" || str.length !== chars || !/^[A-Za-z0-9_-]+$/.test(str)) return null;
8
+ const out = decodeBase64url(str);
9
+ if (out.length !== bytes || encodeBase64url(out) !== str) return null;
10
+ return out;
11
+ }
12
+
13
+ export const isKey = (s) => decodeExact(s, 32) !== null;
14
+ export const isSig = (s) => decodeExact(s, 64) !== null;
15
+
16
+ /** Raw 32 bytes of a base64url key; throws `malformed`. */
17
+ export function keyBytes(key) {
18
+ const b = decodeExact(key, 32);
19
+ if (!b) fail("malformed", "not a base64url Ed25519 public key");
20
+ return b;
21
+ }
22
+
23
+ /**
24
+ * Realm id / pod id of a key: base64url SHA-256 of the raw public key (the primitives `derivePodId` derivation).
25
+ * @param {string} key base64url public key
26
+ * @returns {Promise<string>}
27
+ */
28
+ export async function keyId(key) {
29
+ const hash = await crypto.subtle.digest("SHA-256", keyBytes(key));
30
+ return encodeBase64url(new Uint8Array(hash));
31
+ }
32
+
33
+ /**
34
+ * The base64url public key of a `PodIdentity`.
35
+ * @param {{ rawPublicKey(): Promise<Uint8Array> }} identity
36
+ * @returns {Promise<string>}
37
+ */
38
+ export async function publicKeyOf(identity) {
39
+ return encodeBase64url(await identity.rawPublicKey());
40
+ }
41
+
42
+ /** Sign `UTF-8(domain) || 0x00 || canonical(body)`; returns base64url. */
43
+ export async function signBody(identity, domain, body) {
44
+ const sig = await identity.sign(domainSigningBytes(domain, canonicalJson(body)));
45
+ return encodeBase64url(new Uint8Array(sig));
46
+ }
47
+
48
+ /** Verify a base64url signature over the domain-prefixed canonical body; false on anything wrong. */
49
+ export async function verifyBody(keyB64, domain, body, sigB64) {
50
+ const key = decodeExact(keyB64, 32);
51
+ const sig = decodeExact(sigB64, 64);
52
+ if (!key || !sig) return false;
53
+ try {
54
+ const pub = await crypto.subtle.importKey("raw", key, { name: "Ed25519" }, false, ["verify"]);
55
+ return await crypto.subtle.verify("Ed25519", pub, sig, domainSigningBytes(domain, canonicalJson(body)));
56
+ } catch {
57
+ return false;
58
+ }
59
+ }
60
+
61
+ /** Make sure `identity` holds `expectedKey` before signing for it. */
62
+ export async function requireSigner(identity, expectedKey) {
63
+ let key;
64
+ try {
65
+ key = await publicKeyOf(identity);
66
+ } catch {
67
+ fail("wrong-signer", "not a usable identity");
68
+ }
69
+ if (key !== expectedKey) fail("wrong-signer", "the identity does not hold the key that must sign");
70
+ return key;
71
+ }
72
+
73
+ /** `now` in whole seconds: a number, a function returning one, or the real clock when absent. */
74
+ export function resolveNow(now) {
75
+ const v = typeof now === "function" ? now() : now === undefined ? Math.floor(Date.now() / 1000) : now;
76
+ if (!Number.isSafeInteger(v) || v < 0) fail("malformed", "now must be whole seconds");
77
+ return v;
78
+ }
package/src/ledger.mjs ADDED
@@ -0,0 +1,164 @@
1
+ // The issuer ledger (docs/design/realms.md 5.8): an in-memory, append-only record of every credential an issuer has
2
+ // allocated a serial for. The serials are what `descriptor.revoked` refers to. No file I/O: `export()` returns text
3
+ // and `importLedger(text)` reads it back, so the caller decides where it lives.
4
+ //
5
+ // Serials are per ledger. `descriptor.revoked` is a flat list of serials with no issuer, so a realm with several
6
+ // issuers must give each ledger a disjoint range (`serialStart`) or share one ledger.
7
+ import { canonicalJson, parseCanonical } from "@johnhenry/browsermesh-primitives";
8
+ import { fail, toRealmError } from "./errors.mjs";
9
+ import { MAX_LEDGER_ENTRIES, MAX_LEDGER_BYTES, MAX_REVOKED, MAX_SKEW } from "./limits.mjs";
10
+ import { isKey } from "./keys.mjs";
11
+ import { isRoleName } from "./roles.mjs";
12
+ import { exactKeys, isInt, isPlainObject, isTime, need, utf8Length } from "./validate.mjs";
13
+
14
+ const STATES = new Set(["issued", "revoked"]);
15
+
16
+ function checkEntryFields(e) {
17
+ need(isPlainObject(e), "entry must be an object");
18
+ need(isKey(e.subject), "entry.subject must be a key");
19
+ need(isRoleName(e.role), "entry.role is not a role name");
20
+ need(isTime(e.notAfter), "entry.notAfter must be whole seconds");
21
+ }
22
+
23
+ function wrap(fn) {
24
+ try {
25
+ return fn();
26
+ } catch (err) {
27
+ throw toRealmError(err);
28
+ }
29
+ }
30
+
31
+ function build({ maxEntries, nextSerial, entries }) {
32
+ /** @type {Map<number, Readonly<{ serial: number, subject: string, role: string, notAfter: number, state: string }>>} */
33
+ const map = new Map(entries.map((e) => [e.serial, Object.freeze({ ...e })]));
34
+ let next = nextSerial;
35
+
36
+ return {
37
+ /**
38
+ * Allocate the next serial and record the credential about to be issued.
39
+ * @param {{ subject: string, role: string, notAfter: number }} fields
40
+ */
41
+ allocate(fields) {
42
+ return wrap(() => {
43
+ checkEntryFields(fields);
44
+ if (map.size >= maxEntries) fail("ledger-full", `ledger holds ${maxEntries} entries; compact() or start a new one`);
45
+ if (next > Number.MAX_SAFE_INTEGER) fail("ledger-full", "serial space exhausted");
46
+ const entry = Object.freeze({ serial: next, subject: fields.subject, role: fields.role, notAfter: fields.notAfter, state: "issued" });
47
+ map.set(entry.serial, entry);
48
+ next += 1;
49
+ return entry;
50
+ });
51
+ },
52
+
53
+ /** The entry for a serial, or null. */
54
+ get(serial) {
55
+ return map.get(serial) ?? null;
56
+ },
57
+
58
+ /**
59
+ * Mark a credential revoked (the only state change an entry ever has). Idempotent.
60
+ * @returns {boolean} false when the serial is unknown
61
+ */
62
+ markRevoked(serial) {
63
+ const e = map.get(serial);
64
+ if (!e) return false;
65
+ if (e.state !== "revoked") map.set(serial, Object.freeze({ ...e, state: "revoked" }));
66
+ return true;
67
+ },
68
+
69
+ /** Entries in serial order, optionally only those in `state`. */
70
+ list(opts) {
71
+ const all = [...map.values()];
72
+ return opts?.state ? all.filter((e) => e.state === opts.state) : all;
73
+ },
74
+
75
+ /**
76
+ * The serials to put in `descriptor.revoked`: revoked credentials that could still be presented (a credential past
77
+ * `notAfter` plus skew is refused anyway). Ascending. Throws `too-many-revoked` rather than drop one silently; the
78
+ * answer then is to bump the epoch.
79
+ */
80
+ revokedSerials({ now, max = MAX_REVOKED, skew = MAX_SKEW }) {
81
+ return wrap(() => {
82
+ need(isInt(now, 0), "now must be whole seconds");
83
+ const out = [...map.values()].filter((e) => e.state === "revoked" && e.notAfter + skew >= now).map((e) => e.serial);
84
+ if (out.length > max) fail("too-many-revoked", `${out.length} live revocations exceed ${max}; bump the epoch instead`);
85
+ return out;
86
+ });
87
+ },
88
+
89
+ /**
90
+ * Drop entries that can no longer matter (expired past skew). Serials are never reused. Returns how many went.
91
+ */
92
+ compact({ now, skew = MAX_SKEW }) {
93
+ return wrap(() => {
94
+ need(isInt(now, 0), "now must be whole seconds");
95
+ let n = 0;
96
+ for (const [serial, e] of map) {
97
+ if (e.notAfter + skew < now) {
98
+ map.delete(serial);
99
+ n += 1;
100
+ }
101
+ }
102
+ return n;
103
+ });
104
+ },
105
+
106
+ get size() {
107
+ return map.size;
108
+ },
109
+
110
+ get nextSerial() {
111
+ return next;
112
+ },
113
+
114
+ /**
115
+ * Canonical JSON text of the whole ledger.
116
+ * @param {{ maxBytes?: number }} [opts]
117
+ */
118
+ export(opts) {
119
+ return wrap(() => {
120
+ const text = canonicalJson({ v: 1, next, entries: [...map.values()] });
121
+ if (utf8Length(text) > (opts?.maxBytes ?? MAX_LEDGER_BYTES)) fail("too-large", "ledger export exceeds the size cap");
122
+ return text;
123
+ });
124
+ },
125
+ };
126
+ }
127
+
128
+ /**
129
+ * @param {{ maxEntries?: number, serialStart?: number }} [opts] `serialStart` gives this ledger its own serial range
130
+ */
131
+ export function createLedger(opts) {
132
+ return wrap(() => {
133
+ const { maxEntries = MAX_LEDGER_ENTRIES, serialStart = 1 } = opts ?? {};
134
+ need(isInt(maxEntries, 1) && isInt(serialStart, 1), "bad ledger options");
135
+ return build({ maxEntries, nextSerial: serialStart, entries: [] });
136
+ });
137
+ }
138
+
139
+ /**
140
+ * Read a ledger back from `export()` text. Refuses non-canonical, oversized, or inconsistent input.
141
+ * @param {string} text
142
+ * @param {{ maxBytes?: number, maxEntries?: number }} [opts]
143
+ */
144
+ export function importLedger(text, opts) {
145
+ return wrap(() => {
146
+ const { maxBytes = MAX_LEDGER_BYTES, maxEntries = MAX_LEDGER_ENTRIES } = opts ?? {};
147
+ if (typeof text !== "string") fail("malformed", "ledger must be text");
148
+ if (utf8Length(text) > maxBytes) fail("too-large", "ledger text exceeds the size cap");
149
+ const doc = parseCanonical(text);
150
+ exactKeys(doc, ["v", "next", "entries"], [], "ledger");
151
+ if (doc.v !== 1) fail("unsupported-version", "ledger version must be 1");
152
+ need(isInt(doc.next, 1) && Array.isArray(doc.entries), "bad ledger header");
153
+ if (doc.entries.length > maxEntries) fail("ledger-full", `ledger holds more than ${maxEntries} entries`);
154
+ let prev = 0;
155
+ for (const e of doc.entries) {
156
+ exactKeys(e, ["serial", "subject", "role", "notAfter", "state"], [], "entry");
157
+ checkEntryFields(e);
158
+ need(isInt(e.serial, 1) && e.serial > prev && e.serial < doc.next, "serials must ascend and stay below next");
159
+ need(STATES.has(e.state), "bad entry state");
160
+ prev = e.serial;
161
+ }
162
+ return build({ maxEntries, nextSerial: doc.next, entries: doc.entries });
163
+ });
164
+ }
package/src/limits.mjs ADDED
@@ -0,0 +1,31 @@
1
+ /** Caps and defaults. Everything a hostile peer can make a verifier chew on is bounded here. */
2
+ export const DAY = 86400;
3
+ export const DEFAULT_TTL = 7 * DAY;
4
+ export const MIN_TTL = 60;
5
+ export const MAX_TTL = 30 * DAY;
6
+ export const DEFAULT_SKEW = 300;
7
+ export const MAX_SKEW = 300;
8
+ export const MAX_DESCRIPTOR_BYTES = 16 * 1024;
9
+ export const MAX_CREDENTIAL_BYTES = 2 * 1024;
10
+ export const MAX_CHAIN = 8;
11
+ export const MAX_ISSUERS = 16;
12
+ export const MAX_ADMITTERS = 8;
13
+ export const MAX_REVOKED = 512;
14
+ export const MAX_ROLES = 32;
15
+ export const MAX_SCOPES_PER_ROLE = 64;
16
+ export const MAX_SCOPE_LENGTH = 256;
17
+ export const MAX_RENDEZVOUS_ENTRIES = 8;
18
+ export const MAX_LEDGER_ENTRIES = 10000;
19
+ export const MAX_LEDGER_BYTES = 2 * 1024 * 1024;
20
+ export const MAX_TRACKER_ENTRIES = 10000;
21
+ /** Largest time in whole seconds (year 9999); catches milliseconds passed by mistake. */
22
+ export const MAX_TIME = 253402300799;
23
+
24
+ export const DOMAINS = Object.freeze({
25
+ descriptor: "browsermesh-realm/descriptor/1",
26
+ authorityless: "browsermesh-realm/authorityless-id/1",
27
+ rotation: "browsermesh-realm/rotation/1",
28
+ rotationAccept: "browsermesh-realm/rotation-accept/1",
29
+ credential: "browsermesh-realm/credential/1",
30
+ ticket: "browsermesh-realm/ticket/1",
31
+ });
package/src/prover.mjs ADDED
@@ -0,0 +1,137 @@
1
+ // The prover's half of the realm exchange (docs/design/realms.md 5.5): the dialler presents its credential to a host that
2
+ // holds the link restricted. It is written against the same duck-typed channel the verifier's seam gives a handler:
3
+ //
4
+ // channel = { send(frame), onFrame(cb), onClose(cb), close(reason) }
5
+ //
6
+ // Frames may be objects or JSON text. A peer that does not speak realms ignores the unknown frame types, so the prover
7
+ // treats "no `realm:*` frame at all before `timeoutMs`" as `peer-does-not-speak-realms`; a peer that began the exchange
8
+ // and then stalled is `timeout`. Frames that are not `realm:` frames are ignored (an older peer's ordinary traffic); a
9
+ // malformed `realm:` frame ends the exchange with `bad-frame`.
10
+ //
11
+ // A hello can be lost when a peer sends before the other side of the link has a session (a fresh WebRTC data channel): the
12
+ // verifier therefore says hello again in answer to ours, and the prover says hello again when it sees the verifier's; each
13
+ // side ignores an identical repeat.
14
+ //
15
+ // Order, so the verifier never sees a credential it is not ready for: the prover sends `hello`; on the verifier's hello,
16
+ // if the verifier is ahead it asks for the descriptor (and adopts it, verified), if the prover is ahead it waits to be
17
+ // asked and answers, and only then does it send the credential.
18
+ //
19
+ // Resolves `{ ok: true, role, notAfter }` (whole seconds) or `{ ok: false, reason }`. Reasons beyond the verifier's own
20
+ // (see verifier.mjs): peer-does-not-speak-realms, timeout, peer-closed, and the prover's own bad-frame, wrong-realm,
21
+ // unexpected-frame, descriptor-rejected. After it settles it ignores the channel: the caller owns the link.
22
+ import { parseFrame } from "./frames.mjs";
23
+ import { need } from "./validate.mjs";
24
+
25
+ let proverCount = 0;
26
+
27
+ /**
28
+ * @param {object} opts
29
+ * @param {string} opts.pinnedId
30
+ * @param {ReturnType<import("./store.mjs").createDescriptorStore>} opts.store the prover's own descriptor store
31
+ * @param {string | null} [opts.credential] the credential text; null asks for the open-mode default role
32
+ * @param {{ send: Function, onFrame: Function, onClose: Function, close: Function }} opts.channel
33
+ * @param {number | (() => number)} [opts.now]
34
+ * @param {number} [opts.timeoutMs=5000]
35
+ * @returns {Promise<{ ok: true, role?: string, notAfter?: number } | { ok: false, reason: string }>}
36
+ */
37
+ export function createRealmProver({ pinnedId, store, credential = null, channel, now, timeoutMs = 5000 } = {}) {
38
+ need(typeof pinnedId === "string" && pinnedId !== "", "createRealmProver needs a pinnedId");
39
+ need(store && typeof store.offer === "function" && typeof store.current === "function", "createRealmProver needs a descriptor store");
40
+ need(channel && ["send", "onFrame", "onClose", "close"].every((m) => typeof channel[m] === "function"), "createRealmProver needs a channel");
41
+ need(credential === null || typeof credential === "string", "credential is text or null");
42
+ need(Number.isFinite(timeoutMs) && timeoutMs > 0, "timeoutMs is a positive number");
43
+ void now; // the store carries the clock; accepted so callers can pass one set of options
44
+
45
+ const linkId = `prover:${++proverCount}`;
46
+ return new Promise((resolve) => {
47
+ const st = { done: false, sawRealm: false, hello: null, asked: false, expectAsk: false, credentialSent: false };
48
+ const timer = setTimeout(() => finish({ ok: false, reason: st.sawRealm ? "timeout" : "peer-does-not-speak-realms" }), timeoutMs);
49
+
50
+ function finish(result) {
51
+ if (st.done) return;
52
+ st.done = true;
53
+ clearTimeout(timer);
54
+ store.forget?.(linkId);
55
+ resolve(result);
56
+ if (!result.ok && result.reason !== "peer-closed") {
57
+ try { channel.close(result.reason); } catch { /* already gone */ }
58
+ }
59
+ }
60
+
61
+ const put = async (frame) => {
62
+ try { await channel.send(frame); } catch { /* a closed link ends through onClose or the result */ }
63
+ };
64
+ const sendCredential = async () => {
65
+ if (st.credentialSent) return;
66
+ st.credentialSent = true;
67
+ await put({ t: "realm:credential", text: credential });
68
+ };
69
+
70
+ async function onFrame(raw) {
71
+ await store.ready; // a baked descriptor is still being verified: do not read "none held" too early
72
+ if (st.done) return;
73
+ const parsed = parseFrame(raw);
74
+ if (!parsed.ok) {
75
+ if (parsed.realm) { st.sawRealm = true; finish({ ok: false, reason: "bad-frame" }); }
76
+ return; // foreign traffic
77
+ }
78
+ st.sawRealm = true;
79
+ const f = parsed.frame;
80
+ const cur = store.current();
81
+ const mine = cur?.serial ?? 0;
82
+ switch (f.t) {
83
+ case "realm:hello":
84
+ if (f.id !== pinnedId) return finish({ ok: false, reason: "wrong-realm" });
85
+ // The verifier says hello again in answer to ours (its first may have been lost): a repeat is ignored.
86
+ if (st.hello) return;
87
+ st.hello = f;
88
+ // Said again, so the verifier has seen a hello before the credential even if ours was lost on the way.
89
+ await put({ t: "realm:hello", id: pinnedId, serial: mine, epoch: cur?.epoch ?? 0 });
90
+ if (f.serial > mine) {
91
+ st.asked = true;
92
+ await put({ t: "realm:need-descriptor", have: mine });
93
+ } else if (mine > f.serial) {
94
+ st.expectAsk = true;
95
+ } else {
96
+ await sendCredential();
97
+ }
98
+ return;
99
+ case "realm:need-descriptor": {
100
+ const text = store.export?.();
101
+ if (!cur || !text || f.have >= cur.serial) return;
102
+ await put({ t: "realm:descriptor", text });
103
+ if (st.expectAsk) await sendCredential();
104
+ return;
105
+ }
106
+ case "realm:descriptor": {
107
+ if (!st.asked) return finish({ ok: false, reason: "unexpected-frame" });
108
+ st.asked = false;
109
+ const v = await store.offer(f.text, { linkId });
110
+ if (st.done) return;
111
+ const caughtUp = !v.ok && v.reason === "stale-serial" && (store.current()?.serial ?? 0) >= st.hello.serial;
112
+ if (!v.ok && !caughtUp) return finish({ ok: false, reason: v.reason === "rate-limited" ? "rate-limited" : "descriptor-rejected" });
113
+ await sendCredential();
114
+ return;
115
+ }
116
+ case "realm:result":
117
+ if (!f.ok) return finish({ ok: false, reason: f.reason ?? "refused" });
118
+ return finish({ ok: true, ...(f.role !== undefined ? { role: f.role } : {}), ...(f.notAfter !== undefined ? { notAfter: f.notAfter } : {}) });
119
+ default:
120
+ return finish({ ok: false, reason: "unexpected-frame" }); // a credential flows the other way
121
+ }
122
+ }
123
+
124
+ let chain = Promise.resolve();
125
+ channel.onFrame((raw) => {
126
+ chain = chain.then(() => onFrame(raw)).catch(() => finish({ ok: false, reason: "internal-error" }));
127
+ return chain;
128
+ });
129
+ channel.onClose(() => finish({ ok: false, reason: "peer-closed" }));
130
+
131
+ (async () => {
132
+ await store.ready;
133
+ const cur = store.current();
134
+ await put({ t: "realm:hello", id: pinnedId, serial: cur?.serial ?? 0, epoch: cur?.epoch ?? 0 });
135
+ })().catch(() => finish({ ok: false, reason: "internal-error" }));
136
+ });
137
+ }
package/src/roles.mjs ADDED
@@ -0,0 +1,80 @@
1
+ // Roles (docs/design/realms.md 5.3): a role is a named list of scope patterns, an UPPER BOUND that each host narrows.
2
+ //
3
+ // A scope here is in the `<namespace>:<resource>:<action>` notation of docs/capability-notation.md, written out in
4
+ // full. Under `matchScope` a missing or empty segment counts as `*`, so a 2-segment form such as `mcp:tool` is a
5
+ // wildcard: roles therefore write `mcp:tool:call`. A role scope with a `*`, fewer than 3 segments or an empty segment
6
+ // is rejected.
7
+ import { MAX_ROLES, MAX_SCOPES_PER_ROLE, MAX_SCOPE_LENGTH } from "./limits.mjs";
8
+ import { isPlainObject } from "./validate.mjs";
9
+
10
+ export const GUEST_ROLE = "guest";
11
+
12
+ const ROLE_NAME = /^[a-z][a-z0-9-]{0,31}$/;
13
+ const SEGMENT = /^[A-Za-z0-9._~-]+$/;
14
+ const PRIVILEGED_NAMESPACES = new Set(["egress", "ingress", "pod-host"]);
15
+
16
+ export const isRoleName = (s) => typeof s === "string" && ROLE_NAME.test(s);
17
+
18
+ const bad = (reason, detail) => ({ ok: false, reason, detail });
19
+
20
+ /**
21
+ * @param {unknown} scope
22
+ * @returns {{ ok: true } | { ok: false, reason: "bad-scope", detail: string }}
23
+ */
24
+ export function validateScope(scope) {
25
+ if (typeof scope !== "string") return bad("bad-scope", "a scope must be a string");
26
+ if (scope.length === 0 || scope.length > MAX_SCOPE_LENGTH) return bad("bad-scope", "scope is empty or too long");
27
+ const segments = scope.split(":");
28
+ if (segments.length < 3) return bad("bad-scope", `scope ${JSON.stringify(scope)} has fewer than 3 segments (under matchScope that is a wildcard)`);
29
+ for (const seg of segments) {
30
+ if (seg === "") return bad("bad-scope", `scope ${JSON.stringify(scope)} has an empty segment`);
31
+ if (!SEGMENT.test(seg)) return bad("bad-scope", `scope ${JSON.stringify(scope)} has a segment with a wildcard or unusual character`);
32
+ }
33
+ return { ok: true };
34
+ }
35
+
36
+ /**
37
+ * Scopes a host must never grant from a realm unless its own policy lists them: `egress:`, `ingress:`, `pod-host`
38
+ * and anything `wsh-`.
39
+ * @param {string} scope
40
+ */
41
+ export function isPrivilegedScope(scope) {
42
+ const segments = String(scope).split(":");
43
+ return PRIVILEGED_NAMESPACES.has(segments[0]) || segments.some((s) => s.startsWith("wsh-"));
44
+ }
45
+
46
+ /**
47
+ * @param {unknown} roles `{ roleName: [scope, ...] }`
48
+ * @returns {{ ok: true } | { ok: false, reason: "bad-role" | "bad-scope", detail: string }}
49
+ */
50
+ export function validateRoles(roles) {
51
+ if (!isPlainObject(roles)) return bad("bad-role", "roles must be an object");
52
+ const names = Object.keys(roles);
53
+ if (names.length > MAX_ROLES) return bad("bad-role", `more than ${MAX_ROLES} roles`);
54
+ for (const name of names) {
55
+ if (!isRoleName(name)) return bad("bad-role", `bad role name ${JSON.stringify(name)}`);
56
+ const scopes = roles[name];
57
+ if (!Array.isArray(scopes) || scopes.length === 0 || scopes.length > MAX_SCOPES_PER_ROLE) {
58
+ return bad("bad-role", `role ${name} needs 1 to ${MAX_SCOPES_PER_ROLE} scopes`);
59
+ }
60
+ const seen = new Set();
61
+ for (const scope of scopes) {
62
+ const v = validateScope(scope);
63
+ if (!v.ok) return bad("bad-scope", `role ${name}: ${v.detail}`);
64
+ if (seen.has(scope)) return bad("bad-scope", `role ${name}: duplicate scope ${JSON.stringify(scope)}`);
65
+ seen.add(scope);
66
+ }
67
+ }
68
+ return { ok: true };
69
+ }
70
+
71
+ /**
72
+ * The role a peer with no credential gets: `guest` (or the descriptor's `defaultRole`) in open mode, else null.
73
+ * @param {{ mode?: string, roles?: Record<string, string[]>, defaultRole?: string }} descriptor
74
+ * @returns {string | null}
75
+ */
76
+ export function defaultRole(descriptor) {
77
+ if (!descriptor || descriptor.mode !== "open" || !isPlainObject(descriptor.roles)) return null;
78
+ const name = descriptor.defaultRole ?? GUEST_ROLE;
79
+ return Object.hasOwn(descriptor.roles, name) ? name : null;
80
+ }
@@ -0,0 +1,135 @@
1
+ // Root rotation (docs/design/realms.md 5.1).
2
+ //
3
+ // A statement is signed by the outgoing root (domain `rotation`) and countersigned by the successor (domain
4
+ // `rotation-accept`, over the statement including the first signature), so the successor provably holds its key.
5
+ // The realm id is the hash of the GENESIS key, so a chain is checked from the genesis key forward.
6
+ //
7
+ // First-seen fork rule: a verifier that holds chain positions never accepts a different statement for one of them
8
+ // (`held`). KNOWN LIMIT: a leaked retired key can sign a competing successor; a verifier that has seen nothing cannot
9
+ // tell the two apart. Rotation limits key aging and planned changes, not compromise.
10
+ import { canonicalJson } from "@johnhenry/browsermesh-primitives";
11
+ import { fail, guard, building } from "./errors.mjs";
12
+ import { DOMAINS, MAX_CHAIN } from "./limits.mjs";
13
+ import { isKey, isSig, keyId, signBody, verifyBody, requireSigner } from "./keys.mjs";
14
+ import { exactKeys, isInt, isTime, need } from "./validate.mjs";
15
+
16
+ const BODY_KEYS = ["v", "realm", "pos", "from", "to", "effective"];
17
+
18
+ function checkBody(body) {
19
+ exactKeys(body, BODY_KEYS, ["sig", "countersig"], "rotation");
20
+ need(body.v === 1, "rotation: unsupported version");
21
+ need(isKey(body.realm), "rotation: bad realm id");
22
+ need(isInt(body.pos, 1, 1000), "rotation: bad position");
23
+ need(isKey(body.from) && isKey(body.to) && body.from !== body.to, "rotation: bad keys");
24
+ need(isTime(body.effective), "rotation: bad effective time");
25
+ }
26
+
27
+ const bodyOf = (s) => ({ v: s.v, realm: s.realm, pos: s.pos, from: s.from, to: s.to, effective: s.effective });
28
+
29
+ /**
30
+ * Sign a rotation body as the outgoing root. Returns the base64url signature.
31
+ * @param {{ v?: 1, realm: string, pos: number, from: string, to: string, effective: number }} body
32
+ * @param {import("@johnhenry/browsermesh-primitives").PodIdentity} outgoing
33
+ */
34
+ export function signRotation(body, outgoing) {
35
+ return building(async () => {
36
+ const b = { ...bodyOf({ v: 1, ...body }) };
37
+ checkBody(b);
38
+ await requireSigner(outgoing, b.from);
39
+ return signBody(outgoing, DOMAINS.rotation, b);
40
+ });
41
+ }
42
+
43
+ /**
44
+ * Countersign a statement (`body` plus `sig`) as the successor. Returns the full statement.
45
+ */
46
+ export function countersignRotation(statement, successor) {
47
+ return building(async () => {
48
+ checkBody(statement);
49
+ need(isSig(statement.sig), "rotation: missing signature");
50
+ await requireSigner(successor, statement.to);
51
+ const base = { ...bodyOf(statement), sig: statement.sig };
52
+ return { ...base, countersig: await signBody(successor, DOMAINS.rotationAccept, base) };
53
+ });
54
+ }
55
+
56
+ /** Both steps at once. */
57
+ export async function createRotation(fields, outgoing, successor) {
58
+ const body = bodyOf({ v: 1, ...fields });
59
+ const sig = await signRotation(body, outgoing);
60
+ return countersignRotation({ ...body, sig }, successor);
61
+ }
62
+
63
+ /**
64
+ * Check one statement's shape and both signatures. `opts.realm`, when given, must match the statement's realm.
65
+ * @returns {Promise<{ ok: true } | { ok: false, reason: string, detail?: string }>}
66
+ */
67
+ export function verifyRotation(statement, opts = {}) {
68
+ return guard(async () => {
69
+ exactKeys(statement, [...BODY_KEYS, "sig", "countersig"], [], "rotation");
70
+ checkBody(statement);
71
+ need(isSig(statement.sig) && isSig(statement.countersig), "rotation: bad signature encoding");
72
+ if (opts?.realm !== undefined && statement.realm !== opts.realm) fail("wrong-realm", "rotation is for another realm");
73
+ if (!(await verifyBody(statement.from, DOMAINS.rotation, bodyOf(statement), statement.sig))) {
74
+ fail("bad-signature", "outgoing root's signature does not verify");
75
+ }
76
+ const base = { ...bodyOf(statement), sig: statement.sig };
77
+ if (!(await verifyBody(statement.to, DOMAINS.rotationAccept, base, statement.countersig))) {
78
+ fail("bad-countersignature", "successor's countersignature does not verify");
79
+ }
80
+ return { ok: true };
81
+ });
82
+ }
83
+
84
+ const sameStatement = (a, b) => {
85
+ try {
86
+ return canonicalJson(a) === canonicalJson(b);
87
+ } catch {
88
+ return false;
89
+ }
90
+ };
91
+
92
+ /**
93
+ * Verify a chain from the genesis key to `key` (the descriptor's current root key).
94
+ * @param {unknown[]} chain
95
+ * @param {{ id: string, key: string, maxChain?: number, held?: unknown[] }} opts `held` is the chain the verifier
96
+ * already holds (first seen wins)
97
+ * @returns {Promise<{ ok: true, rootKey: string, length: number } | { ok: false, reason: string, detail?: string }>}
98
+ */
99
+ export function verifyChain(chain, opts = {}) {
100
+ return guard(async () => {
101
+ const { id, key, maxChain = MAX_CHAIN } = opts ?? {};
102
+ const held = Array.isArray(opts?.held) ? opts.held : [];
103
+ need(typeof id === "string" && typeof key === "string", "verifyChain needs id and key");
104
+ if (!Array.isArray(chain)) fail("bad-chain", "chain must be an array");
105
+ if (chain.length > maxChain) fail("chain-too-long", `chain longer than ${maxChain}`);
106
+
107
+ for (let i = 0; i < Math.min(chain.length, held.length); i++) {
108
+ if (!sameStatement(chain[i], held[i])) fail("chain-fork", `a different statement for position ${i + 1} is already held`);
109
+ }
110
+ if (chain.length < held.length) fail("chain-regressed", "chain is shorter than the one held");
111
+
112
+ let expectedFrom = null;
113
+ let lastEffective = 0;
114
+ for (let i = 0; i < chain.length; i++) {
115
+ const s = chain[i];
116
+ const shape = await verifyRotation(s, { realm: id });
117
+ if (!shape.ok) fail("bad-chain", `statement ${i + 1}: ${shape.reason}`);
118
+ if (s.pos !== i + 1) fail("bad-chain", `statement ${i + 1} has position ${s.pos}`);
119
+ if (i === 0) {
120
+ if ((await keyId(s.from)) !== id) fail("bad-id", "the first statement's outgoing key is not the genesis key");
121
+ } else if (s.from !== expectedFrom) {
122
+ fail("bad-chain", `statement ${i + 1} does not continue from the previous successor`);
123
+ }
124
+ if (s.effective < lastEffective) fail("bad-chain", "effective times go backwards");
125
+ lastEffective = s.effective;
126
+ expectedFrom = s.to;
127
+ }
128
+ if (chain.length === 0) {
129
+ if ((await keyId(key)) !== id) fail("bad-id", "the root key does not hash to the realm id");
130
+ } else if (expectedFrom !== key) {
131
+ fail("bad-chain", "the chain does not end at the current root key");
132
+ }
133
+ return { ok: true, rootKey: key, length: chain.length };
134
+ });
135
+ }