@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.
@@ -0,0 +1,298 @@
1
+ // Realm descriptors (docs/design/realms.md 5.2 and 5.9).
2
+ //
3
+ // A descriptor is a canonical-JSON document signed by the realm's current root key. The signature (`sig`) is a field of
4
+ // the document and covers `UTF-8(domain) || 0x00 || canonicalJson(document without sig)`. A verifier parses with the
5
+ // strict `parseCanonical`, so anything that is not already in canonical form is refused, and it signs and checks the
6
+ // text it received, not a re-encoding.
7
+ //
8
+ // Times are whole seconds. Absent optional fields are omitted (there is no `null`).
9
+ import { canonicalJson, parseCanonical, domainSigningBytes, encodeBase64url } from "@johnhenry/browsermesh-primitives";
10
+ import { fail, guard, building } from "./errors.mjs";
11
+ import {
12
+ DOMAINS, DEFAULT_TTL, MIN_TTL, MAX_TTL, MAX_DESCRIPTOR_BYTES, MAX_CHAIN, MAX_ISSUERS, MAX_ADMITTERS, MAX_REVOKED,
13
+ MAX_RENDEZVOUS_ENTRIES,
14
+ } from "./limits.mjs";
15
+ import { isKey, isSig, keyId, signBody, verifyBody, requireSigner, resolveNow } from "./keys.mjs";
16
+ import { exactKeys, hasControl, isInt, isPlainObject, isTime, need, utf8Length } from "./validate.mjs";
17
+ import { validateRoles, defaultRole, isPrivilegedScope, GUEST_ROLE } from "./roles.mjs";
18
+ import { verifyChain } from "./rotation.mjs";
19
+
20
+ /** Room for the `sig` field when checking a body against the size limit. */
21
+ const SIG_ALLOWANCE = 100;
22
+
23
+ const REQUIRED = ["v", "id", "name", "serial", "epoch", "mode", "root", "issuers", "roles", "rendezvous", "admitters", "ttl", "revoked", "labels", "extensions", "sig"];
24
+ const OPTIONAL = ["updateUrl", "validUntil", "defaultRole"];
25
+
26
+ // ---- rendezvous ---------------------------------------------------------------------------------------------------
27
+
28
+ const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
29
+
30
+ function checkUrl(value, secure, insecure, what) {
31
+ need(typeof value === "string" && value.length > 0 && value.length <= 512, `${what}: bad URL`);
32
+ let u;
33
+ try {
34
+ u = new URL(value);
35
+ } catch {
36
+ fail("malformed", `${what}: not a URL`);
37
+ }
38
+ need(!u.username && !u.password, `${what}: no credentials in URLs`);
39
+ const ok = u.protocol === secure || (u.protocol === insecure && LOOPBACK.has(u.hostname));
40
+ need(ok, `${what}: only ${secure}// (or ${insecure}// on loopback) is browser-usable`);
41
+ }
42
+
43
+ const ICE_URL = /^(stun|stuns|turn|turns):[^\s]{1,250}$/;
44
+
45
+ /**
46
+ * Validate a rendezvous object (also used for the unsigned hints of the authority-less form).
47
+ * @param {unknown} r
48
+ */
49
+ export function checkRendezvous(r) {
50
+ exactKeys(r, ["signaling", "relays", "ice", "bootstrap"], [], "rendezvous");
51
+ for (const k of ["signaling", "relays", "ice", "bootstrap"]) {
52
+ need(Array.isArray(r[k]) && r[k].length <= MAX_RENDEZVOUS_ENTRIES, `rendezvous.${k}: at most ${MAX_RENDEZVOUS_ENTRIES} entries`);
53
+ }
54
+ r.signaling.forEach((u) => checkUrl(u, "wss:", "ws:", "rendezvous.signaling"));
55
+ r.relays.forEach((u) => checkUrl(u, "wss:", "ws:", "rendezvous.relays"));
56
+ r.bootstrap.forEach((u) => checkUrl(u, "https:", "http:", "rendezvous.bootstrap"));
57
+ for (const e of r.ice) {
58
+ exactKeys(e, ["urls"], ["username", "credential"], "rendezvous.ice entry");
59
+ need(Array.isArray(e.urls) && e.urls.length >= 1 && e.urls.length <= 4 && e.urls.every((u) => typeof u === "string" && ICE_URL.test(u)), "rendezvous.ice: bad urls");
60
+ for (const k of ["username", "credential"]) {
61
+ need(!(k in e) || (typeof e[k] === "string" && e[k].length <= 256), `rendezvous.ice: bad ${k}`);
62
+ }
63
+ }
64
+ }
65
+
66
+ // ---- body ---------------------------------------------------------------------------------------------------------
67
+
68
+ function checkName(name) {
69
+ need(typeof name === "string" && name.length >= 1 && name.length <= 64 && !hasControl(name) && name.isWellFormed(), "bad name");
70
+ }
71
+
72
+ /** Validate a descriptor document WITHOUT its signature (`body`), throwing a typed RealmError. */
73
+ function checkBody(d) {
74
+ exactKeys(d, REQUIRED.filter((k) => k !== "sig"), OPTIONAL, "descriptor");
75
+ if (d.v !== 1) fail("unsupported-version", "descriptor version must be 1");
76
+ need(isKey(d.id), "bad id");
77
+ checkName(d.name);
78
+ need(isInt(d.serial, 1), "serial must be an integer >= 1");
79
+ need(isInt(d.epoch, 0), "epoch must be an integer >= 0");
80
+ need(d.mode === "open" || d.mode === "invite", "mode must be open or invite");
81
+
82
+ exactKeys(d.root, ["key", "chain"], [], "root");
83
+ need(isKey(d.root.key) && Array.isArray(d.root.chain), "bad root");
84
+
85
+ need(Array.isArray(d.issuers) && d.issuers.length <= MAX_ISSUERS, `at most ${MAX_ISSUERS} issuers`);
86
+ const seen = new Set();
87
+ for (const i of d.issuers) {
88
+ exactKeys(i, ["key", "notAfter"], [], "issuer");
89
+ need(isKey(i.key) && isTime(i.notAfter), "bad issuer");
90
+ need(!seen.has(i.key), "duplicate issuer");
91
+ seen.add(i.key);
92
+ }
93
+
94
+ const roles = validateRoles(d.roles);
95
+ if (!roles.ok) fail(roles.reason, roles.detail);
96
+ if ("defaultRole" in d) {
97
+ need(d.mode === "open", "defaultRole only applies in open mode");
98
+ need(typeof d.defaultRole === "string" && Object.hasOwn(d.roles, d.defaultRole), "defaultRole must name a defined role");
99
+ }
100
+ if (d.mode === "open") need(defaultRole(d) !== null, "open mode needs a default role (guest)");
101
+
102
+ checkRendezvous(d.rendezvous);
103
+
104
+ need(Array.isArray(d.admitters) && d.admitters.length <= MAX_ADMITTERS && d.admitters.every(isKey), "bad admitters");
105
+ need(new Set(d.admitters).size === d.admitters.length, "duplicate admitter");
106
+ need(isInt(d.ttl, MIN_TTL, MAX_TTL), `ttl must be ${MIN_TTL} to ${MAX_TTL} seconds`);
107
+ need(
108
+ Array.isArray(d.revoked) && d.revoked.length <= MAX_REVOKED && d.revoked.every((s, i) => isInt(s, 1) && (i === 0 || s > d.revoked[i - 1])),
109
+ `revoked must be at most ${MAX_REVOKED} ascending unique serials`,
110
+ );
111
+ need(isPlainObject(d.labels) && Object.keys(d.labels).length <= 16, "bad labels");
112
+ for (const [k, v] of Object.entries(d.labels)) {
113
+ need(k.length >= 1 && k.length <= 64 && typeof v === "string" && v.length <= 128 && v.isWellFormed(), "bad label");
114
+ }
115
+ need(isPlainObject(d.extensions), "extensions must be an object");
116
+ if ("updateUrl" in d) checkUrl(d.updateUrl, "https:", "http:", "updateUrl");
117
+ if ("validUntil" in d) need(isTime(d.validUntil), "bad validUntil");
118
+ }
119
+
120
+ const withoutSig = (d) => {
121
+ const { sig, ...body } = d;
122
+ return body;
123
+ };
124
+
125
+ function sizeCheck(text, maxBytes) {
126
+ if (utf8Length(text) > maxBytes) fail("too-large", `descriptor is larger than ${maxBytes} bytes`);
127
+ }
128
+
129
+ /** True when a baked snapshot is past its `validUntil` and must be refreshed. */
130
+ export function isStale(descriptor, now) {
131
+ return descriptor?.validUntil !== undefined && resolveNow(now) > descriptor.validUntil;
132
+ }
133
+
134
+ // ---- create / sign ------------------------------------------------------------------------------------------------
135
+
136
+ /**
137
+ * Build an unsigned descriptor. `id` is the base64url SHA-256 of the GENESIS root key: `genesisKey` if given, else
138
+ * the first rotation's outgoing key, else `root.key`. Throws a typed `RealmError` on bad input.
139
+ * @param {object} fields see docs/design/realms.md 5.2
140
+ * @returns {Promise<object>}
141
+ */
142
+ export function createDescriptor(fields) {
143
+ return building(async () => {
144
+ need(isPlainObject(fields), "fields must be an object");
145
+ const f = Object.fromEntries(Object.entries(fields).filter(([, v]) => v !== undefined));
146
+ need(isPlainObject(f.root) && isKey(f.root.key), "root.key is required");
147
+ need(typeof f.name === "string" && isPlainObject(f.roles), "name and roles are required");
148
+ const chain = f.root.chain ?? [];
149
+ need(Array.isArray(chain), "root.chain must be an array");
150
+ const genesisKey = f.genesisKey ?? (chain.length > 0 ? chain[0]?.from : f.root.key);
151
+ if (f.genesisKey !== undefined && chain.length > 0) need(chain[0]?.from === f.genesisKey, "genesisKey is not the first rotation's outgoing key");
152
+ const body = {
153
+ v: 1,
154
+ id: await keyId(genesisKey),
155
+ name: f.name,
156
+ serial: f.serial ?? 1,
157
+ epoch: f.epoch ?? 0,
158
+ mode: f.mode ?? "invite",
159
+ root: { key: f.root.key, chain },
160
+ issuers: f.issuers ?? [],
161
+ roles: f.roles,
162
+ rendezvous: f.rendezvous ?? { signaling: [], relays: [], ice: [], bootstrap: [] },
163
+ admitters: f.admitters ?? [],
164
+ ttl: f.ttl ?? DEFAULT_TTL,
165
+ revoked: f.revoked ?? [],
166
+ labels: f.labels ?? {},
167
+ extensions: f.extensions ?? {},
168
+ };
169
+ for (const k of OPTIONAL) if (f[k] !== undefined) body[k] = f[k];
170
+ const text = canonicalJson(body);
171
+ sizeCheck(text, (f.maxBytes ?? MAX_DESCRIPTOR_BYTES) - SIG_ALLOWANCE);
172
+ const normal = parseCanonical(text);
173
+ checkBody(normal);
174
+ return normal;
175
+ });
176
+ }
177
+
178
+ /**
179
+ * Sign a descriptor as its current root key.
180
+ * @param {object} descriptor from `createDescriptor` (a `sig` already on it is ignored)
181
+ * @param {import("@johnhenry/browsermesh-primitives").PodIdentity} rootIdentity
182
+ * @returns {Promise<{ descriptor: object, text: string }>}
183
+ */
184
+ export function signDescriptor(descriptor, rootIdentity, opts = {}) {
185
+ return building(async () => {
186
+ need(isPlainObject(descriptor), "descriptor must be an object");
187
+ const body = withoutSig(descriptor);
188
+ checkBody(body);
189
+ await requireSigner(rootIdentity, body.root.key);
190
+ const signed = { ...body, sig: await signBody(rootIdentity, DOMAINS.descriptor, body) };
191
+ const text = canonicalJson(signed);
192
+ sizeCheck(text, opts?.maxBytes ?? MAX_DESCRIPTOR_BYTES);
193
+ return { descriptor: parseCanonical(text), text };
194
+ });
195
+ }
196
+
197
+ // ---- verify -------------------------------------------------------------------------------------------------------
198
+
199
+ /**
200
+ * Verify a signed descriptor end to end against a pinned realm id.
201
+ *
202
+ * Order: size, strict canonical parse, shape (roles and scopes included), pinned id, rotation chain (against `held`
203
+ * chain), root signature, `validUntil`. Never throws.
204
+ *
205
+ * @param {unknown} text the exact received text
206
+ * @param {{ pinnedId: string, now?: number | (() => number), maxBytes?: number, maxChain?: number, heldChain?: unknown[] }} opts
207
+ * @returns {Promise<{ ok: true, descriptor: object, text: string, chainLength: number } | { ok: false, reason: string, detail?: string }>}
208
+ */
209
+ export function verifyDescriptor(text, opts) {
210
+ return guard(async () => {
211
+ const { pinnedId, now, maxBytes = MAX_DESCRIPTOR_BYTES, maxChain = MAX_CHAIN, heldChain } = opts ?? {};
212
+ need(typeof pinnedId === "string", "verifyDescriptor needs a pinnedId");
213
+ if (typeof text !== "string") fail("malformed", "descriptor must be text");
214
+ sizeCheck(text, maxBytes);
215
+ const doc = parseCanonical(text);
216
+ if (isPlainObject(doc) && "form" in doc) fail("wrong-form", "this is not a signed descriptor");
217
+ if (isPlainObject(doc) && doc.v !== undefined && doc.v !== 1) fail("unsupported-version", "descriptor version must be 1");
218
+ exactKeys(doc, REQUIRED, OPTIONAL, "descriptor");
219
+ need(isSig(doc.sig), "bad signature encoding");
220
+ const body = withoutSig(doc);
221
+ checkBody(body);
222
+ if (body.id !== pinnedId) fail("wrong-realm", "descriptor is for another realm");
223
+
224
+ const chain = await verifyChain(body.root.chain, { id: body.id, key: body.root.key, maxChain, held: heldChain });
225
+ if (!chain.ok) return chain;
226
+
227
+ if (!(await verifyBody(body.root.key, DOMAINS.descriptor, body, doc.sig))) fail("bad-signature", "root signature does not verify");
228
+ if (isStale(body, now)) fail("expired", "descriptor is past its validUntil");
229
+ return { ok: true, descriptor: doc, text, chainLength: chain.length };
230
+ });
231
+ }
232
+
233
+ // ---- authority-less open form (5.9) -------------------------------------------------------------------------------
234
+
235
+ const AL_REQUIRED = ["v", "form", "id", "name", "mode", "roles", "salt", "hints"];
236
+ const SALT = /^[A-Za-z0-9_-]{16,64}$/;
237
+
238
+ async function authorityLessId({ name, roles, salt }) {
239
+ const bytes = domainSigningBytes(DOMAINS.authorityless, canonicalJson({ name, roles, salt }));
240
+ return encodeBase64url(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)));
241
+ }
242
+
243
+ function checkAuthorityLessShape(d) {
244
+ exactKeys(d, AL_REQUIRED, [], "authority-less descriptor");
245
+ if (d.v !== 1) fail("unsupported-version", "descriptor version must be 1");
246
+ need(d.form === "authorityless" && d.mode === "open", "authority-less descriptors are open");
247
+ need(isKey(d.id), "bad id");
248
+ checkName(d.name);
249
+ need(typeof d.salt === "string" && SALT.test(d.salt), "bad salt");
250
+ const roles = validateRoles(d.roles);
251
+ if (!roles.ok) fail(roles.reason, roles.detail);
252
+ // Never any privileged role: only `guest`, and never a machine-right scope family.
253
+ if (Object.keys(d.roles).some((r) => r !== GUEST_ROLE) || !Object.hasOwn(d.roles, GUEST_ROLE)) {
254
+ fail("bad-role", "the authority-less form carries exactly one role, guest");
255
+ }
256
+ for (const scope of d.roles.guest) {
257
+ if (isPrivilegedScope(scope)) fail("bad-scope", `guest scope ${JSON.stringify(scope)} is a privileged family`);
258
+ }
259
+ checkRendezvous(d.hints);
260
+ }
261
+
262
+ /**
263
+ * Build the authority-less open form: no root, no issuers, no signature. The id hashes (name, roles, salt) only, so the
264
+ * `hints` (signalling, relays, ICE, bootstrap) are unsigned, replaceable candidates and a dead relay cannot orphan it.
265
+ * @param {{ name: string, roles: Record<string, string[]>, salt?: string, hints?: object }} fields
266
+ */
267
+ export function createAuthorityless(fields) {
268
+ return building(async () => {
269
+ need(isPlainObject(fields), "fields must be an object");
270
+ const salt = fields.salt ?? encodeBase64url(crypto.getRandomValues(new Uint8Array(16)));
271
+ const d = {
272
+ v: 1, form: "authorityless", id: "", name: fields.name, mode: "open", roles: fields.roles, salt,
273
+ hints: fields.hints ?? { signaling: [], relays: [], ice: [], bootstrap: [] },
274
+ };
275
+ d.id = await authorityLessId(d);
276
+ checkAuthorityLessShape(d);
277
+ const text = canonicalJson(d);
278
+ sizeCheck(text, MAX_DESCRIPTOR_BYTES);
279
+ return { descriptor: parseCanonical(text), text };
280
+ });
281
+ }
282
+
283
+ /**
284
+ * Verify the authority-less form: canonical, well formed, and the id equals the hash of (name, roles, salt).
285
+ * @returns {Promise<{ ok: true, descriptor: object, text: string } | { ok: false, reason: string, detail?: string }>}
286
+ */
287
+ export function verifyAuthorityless(text, opts) {
288
+ return guard(async () => {
289
+ const { pinnedId, maxBytes = MAX_DESCRIPTOR_BYTES } = opts ?? {};
290
+ if (typeof text !== "string") fail("malformed", "descriptor must be text");
291
+ sizeCheck(text, maxBytes);
292
+ const doc = parseCanonical(text);
293
+ checkAuthorityLessShape(doc);
294
+ if ((await authorityLessId(doc)) !== doc.id) fail("bad-id", "id is not the hash of name, roles and salt");
295
+ if (pinnedId !== undefined && doc.id !== pinnedId) fail("wrong-realm", "descriptor is for another realm");
296
+ return { ok: true, descriptor: doc, text };
297
+ });
298
+ }
package/src/errors.mjs ADDED
@@ -0,0 +1,47 @@
1
+ import { CanonicalJsonError } from "@johnhenry/browsermesh-primitives";
2
+
3
+ /**
4
+ * A typed failure with a stable machine `code`. Builders (`createDescriptor`, `issueCredential`, ...) throw it on bad
5
+ * caller input; verifiers never let it escape: they turn it into `{ ok: false, reason: code, detail }`.
6
+ */
7
+ export class RealmError extends Error {
8
+ /**
9
+ * @param {string} code
10
+ * @param {string} [detail]
11
+ */
12
+ constructor(code, detail = code) {
13
+ super(detail);
14
+ this.name = "RealmError";
15
+ this.code = code;
16
+ }
17
+ }
18
+
19
+ export const fail = (code, detail) => {
20
+ throw new RealmError(code, detail);
21
+ };
22
+
23
+ /** Turn any throw into a RealmError (canonical-JSON errors become `not-canonical`; anything else `malformed`). */
24
+ export function toRealmError(err) {
25
+ if (err instanceof RealmError) return err;
26
+ if (err instanceof CanonicalJsonError) return new RealmError("not-canonical", `${err.code}: ${err.message}`);
27
+ return new RealmError("malformed", "unexpected input");
28
+ }
29
+
30
+ /** Run a verifier body; hostile input yields a verdict, never a throw. */
31
+ export async function guard(fn) {
32
+ try {
33
+ return await fn();
34
+ } catch (err) {
35
+ const e = toRealmError(err);
36
+ return { ok: false, reason: e.code, detail: e.message };
37
+ }
38
+ }
39
+
40
+ /** Run a builder body; failures surface as RealmError (with the original code) rather than raw errors. */
41
+ export async function building(fn) {
42
+ try {
43
+ return await fn();
44
+ } catch (err) {
45
+ throw toRealmError(err);
46
+ }
47
+ }
package/src/frames.mjs ADDED
@@ -0,0 +1,74 @@
1
+ // The realm exchange's frames (docs/design/realms.md 5.5). Each is a JSON object with a `t` type string and a few small
2
+ // fields. Every field is checked and every size is capped: a peer cannot make the parser, or what comes after it, do
3
+ // unbounded work.
4
+ //
5
+ // t fields who sends it meaning
6
+ // realm:hello id, serial, epoch both "this is the realm I speak, and the descriptor I hold"
7
+ // (serial 0 = none held)
8
+ // realm:need-descriptor have the side that is behind "send me yours; I hold serial `have`"
9
+ // realm:descriptor text the side that is ahead the exact canonical descriptor text (<= 16 KiB)
10
+ // realm:credential text | null the prover its credential (<= 2 KiB); null = "no credential,
11
+ // give me the open-mode default role"
12
+ // realm:result ok, reason?, role?, notAfter? the verifier the verdict; `notAfter` is whole seconds
13
+ //
14
+ // A frame may arrive as an object or as JSON text (wsh delivers text); `parseFrame` accepts both.
15
+ import { MAX_DESCRIPTOR_BYTES, MAX_CREDENTIAL_BYTES, MAX_TIME } from "./limits.mjs";
16
+ import { isPlainObject, isInt, utf8Length } from "./validate.mjs";
17
+ import { isRoleName } from "./roles.mjs";
18
+
19
+ export const FRAME_TYPES = Object.freeze([
20
+ "realm:hello", "realm:need-descriptor", "realm:descriptor", "realm:credential", "realm:result",
21
+ ]);
22
+
23
+ /** A descriptor's JSON escaping can at most double it, so a `realm:descriptor` frame is under this. */
24
+ export const MAX_FRAME_BYTES = 2 * MAX_DESCRIPTOR_BYTES + 256;
25
+ /**
26
+ * The smallest `maxFrameBytes` a host's link-admission seam may be configured with if it is to carry descriptors. The seam's
27
+ * default (16 KiB) silently drops a larger descriptor frame; small descriptors still pass.
28
+ */
29
+ export const MIN_SEAM_FRAME_BYTES = 2 * MAX_DESCRIPTOR_BYTES + 1024;
30
+
31
+ const MAX_ID = 64;
32
+ const MAX_REASON = 64;
33
+ const ID = /^[A-Za-z0-9_-]+$/;
34
+ const REASON = /^[a-z0-9:-]+$/;
35
+
36
+ const SPEC = {
37
+ "realm:hello": { required: ["t", "id", "serial", "epoch"], optional: [], check: (f) =>
38
+ typeof f.id === "string" && f.id.length >= 1 && f.id.length <= MAX_ID && ID.test(f.id) && isInt(f.serial) && isInt(f.epoch) },
39
+ "realm:need-descriptor": { required: ["t", "have"], optional: [], check: (f) => isInt(f.have) },
40
+ "realm:descriptor": { required: ["t", "text"], optional: [], check: (f) =>
41
+ typeof f.text === "string" && utf8Length(f.text) <= MAX_DESCRIPTOR_BYTES },
42
+ "realm:credential": { required: ["t", "text"], optional: [], check: (f) =>
43
+ f.text === null || (typeof f.text === "string" && utf8Length(f.text) <= MAX_CREDENTIAL_BYTES) },
44
+ "realm:result": { required: ["t", "ok"], optional: ["reason", "role", "notAfter"], check: (f) =>
45
+ typeof f.ok === "boolean"
46
+ && (f.reason === undefined || (typeof f.reason === "string" && f.reason.length <= MAX_REASON && REASON.test(f.reason)))
47
+ && (f.role === undefined || isRoleName(f.role))
48
+ && (f.notAfter === undefined || isInt(f.notAfter, 0, MAX_TIME)) },
49
+ };
50
+
51
+ const bad = (realm) => ({ ok: false, reason: "bad-frame", realm });
52
+
53
+ /**
54
+ * Parse and validate one frame. Never throws.
55
+ * @param {unknown} raw an object, or JSON text of one
56
+ * @returns {{ ok: true, frame: object } | { ok: false, reason: "bad-frame", realm: boolean }}
57
+ * `realm` is true when the input at least claims a `realm:` type (so a caller can ignore foreign traffic but refuse a
58
+ * malformed realm frame).
59
+ */
60
+ export function parseFrame(raw) {
61
+ let f = raw;
62
+ if (typeof raw === "string") {
63
+ if (raw.length > MAX_FRAME_BYTES) return bad(false);
64
+ try { f = JSON.parse(raw); } catch { return bad(false); }
65
+ }
66
+ if (!isPlainObject(f) || typeof f.t !== "string") return bad(false);
67
+ const realm = f.t.startsWith("realm:");
68
+ const spec = Object.hasOwn(SPEC, f.t) ? SPEC[f.t] : null;
69
+ if (!spec) return bad(realm);
70
+ for (const k of Object.keys(f)) if (!spec.required.includes(k) && !spec.optional.includes(k)) return bad(realm);
71
+ for (const k of spec.required) if (!(k in f)) return bad(realm);
72
+ if (!spec.check(f)) return bad(realm);
73
+ return { ok: true, frame: f };
74
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,257 @@
1
+ import type { PodIdentity } from "@johnhenry/browsermesh-primitives";
2
+
3
+ /** A verdict: `{ ok: true, ...T }` or `{ ok: false, reason, detail? }`. Verifiers never throw on hostile input. */
4
+ export type Verdict<T extends object = {}> = ({ ok: true } & T) | { ok: false; reason: string; detail?: string };
5
+
6
+ /** `now` is whole seconds since the epoch, or a function returning it; default is the real clock. */
7
+ export type Clock = number | (() => number);
8
+
9
+ export class RealmError extends Error {
10
+ readonly code: string;
11
+ constructor(code: string, detail?: string);
12
+ }
13
+
14
+ export const DOMAINS: Readonly<{
15
+ descriptor: string; authorityless: string; rotation: string; rotationAccept: string; credential: string; ticket: string;
16
+ }>;
17
+ export const DEFAULT_TTL: number;
18
+ export const MIN_TTL: number;
19
+ export const MAX_TTL: number;
20
+ export const DEFAULT_SKEW: number;
21
+ export const MAX_SKEW: number;
22
+ export const MAX_DESCRIPTOR_BYTES: number;
23
+ export const MAX_CREDENTIAL_BYTES: number;
24
+ export const MAX_CHAIN: number;
25
+ export const MAX_ISSUERS: number;
26
+ export const MAX_REVOKED: number;
27
+ export const GUEST_ROLE: "guest";
28
+
29
+ export function keyId(publicKey: string): Promise<string>;
30
+ export function publicKeyOf(identity: PodIdentity): Promise<string>;
31
+
32
+ // ---- roles
33
+ export function validateScope(scope: unknown): Verdict;
34
+ export function validateRoles(roles: unknown): Verdict;
35
+ export function isPrivilegedScope(scope: string): boolean;
36
+ export function defaultRole(descriptor: { mode?: string; roles?: Record<string, string[]>; defaultRole?: string }): string | null;
37
+
38
+ // ---- descriptor
39
+ export interface Rendezvous {
40
+ signaling: string[];
41
+ relays: string[];
42
+ ice: { urls: string[]; username?: string; credential?: string }[];
43
+ bootstrap: string[];
44
+ }
45
+ export interface RotationStatement {
46
+ v: 1; realm: string; pos: number; from: string; to: string; effective: number; sig: string; countersig: string;
47
+ }
48
+ export interface RealmDescriptor {
49
+ v: 1;
50
+ id: string;
51
+ name: string;
52
+ serial: number;
53
+ epoch: number;
54
+ mode: "open" | "invite";
55
+ root: { key: string; chain: RotationStatement[] };
56
+ issuers: { key: string; notAfter: number }[];
57
+ roles: Record<string, string[]>;
58
+ rendezvous: Rendezvous;
59
+ admitters: string[];
60
+ ttl: number;
61
+ revoked: number[];
62
+ labels: Record<string, string>;
63
+ extensions: Record<string, unknown>;
64
+ updateUrl?: string;
65
+ validUntil?: number;
66
+ defaultRole?: string;
67
+ sig?: string;
68
+ }
69
+ export interface DescriptorFields {
70
+ name: string;
71
+ roles: Record<string, string[]>;
72
+ root: { key: string; chain?: RotationStatement[] };
73
+ genesisKey?: string;
74
+ serial?: number;
75
+ epoch?: number;
76
+ mode?: "open" | "invite";
77
+ issuers?: { key: string; notAfter: number }[];
78
+ rendezvous?: Rendezvous;
79
+ admitters?: string[];
80
+ ttl?: number;
81
+ revoked?: number[];
82
+ labels?: Record<string, string>;
83
+ extensions?: Record<string, unknown>;
84
+ updateUrl?: string;
85
+ validUntil?: number;
86
+ defaultRole?: string;
87
+ maxBytes?: number;
88
+ }
89
+ export interface VerifyDescriptorOptions {
90
+ pinnedId: string;
91
+ now?: Clock;
92
+ maxBytes?: number;
93
+ maxChain?: number;
94
+ heldChain?: RotationStatement[];
95
+ }
96
+ export type DescriptorVerdict = Verdict<{ descriptor: RealmDescriptor; text: string; chainLength: number }>;
97
+
98
+ export function checkRendezvous(r: unknown): void;
99
+ export function isStale(descriptor: { validUntil?: number }, now?: Clock): boolean;
100
+ export function createDescriptor(fields: DescriptorFields): Promise<RealmDescriptor>;
101
+ export function signDescriptor(
102
+ descriptor: RealmDescriptor, rootIdentity: PodIdentity, opts?: { maxBytes?: number },
103
+ ): Promise<{ descriptor: RealmDescriptor; text: string }>;
104
+ export function verifyDescriptor(text: unknown, opts: VerifyDescriptorOptions): Promise<DescriptorVerdict>;
105
+
106
+ export interface AuthorityLessDescriptor {
107
+ v: 1; form: "authorityless"; id: string; name: string; mode: "open"; roles: { guest: string[] }; salt: string; hints: Rendezvous;
108
+ }
109
+ export function createAuthorityless(fields: {
110
+ name: string; roles: { guest: string[] }; salt?: string; hints?: Rendezvous;
111
+ }): Promise<{ descriptor: AuthorityLessDescriptor; text: string }>;
112
+ export function verifyAuthorityless(
113
+ text: unknown, opts?: { pinnedId?: string; maxBytes?: number },
114
+ ): Promise<Verdict<{ descriptor: AuthorityLessDescriptor; text: string }>>;
115
+
116
+ // ---- rotation
117
+ export interface RotationBody { v?: 1; realm: string; pos: number; from: string; to: string; effective: number }
118
+ export function signRotation(body: RotationBody, outgoing: PodIdentity): Promise<string>;
119
+ export function countersignRotation(statement: RotationBody & { sig: string }, successor: PodIdentity): Promise<RotationStatement>;
120
+ export function createRotation(body: RotationBody, outgoing: PodIdentity, successor: PodIdentity): Promise<RotationStatement>;
121
+ export function verifyRotation(statement: unknown, opts?: { realm?: string }): Promise<Verdict>;
122
+ export function verifyChain(
123
+ chain: unknown, opts: { id: string; key: string; maxChain?: number; held?: unknown[] },
124
+ ): Promise<Verdict<{ rootKey: string; length: number }>>;
125
+
126
+ // ---- adoption
127
+ export function adoptDescriptor(
128
+ held: RealmDescriptor | null | undefined,
129
+ offered: unknown,
130
+ opts: { pinnedId: string; now?: Clock; maxBytes?: number; maxChain?: number },
131
+ ): Promise<DescriptorVerdict>;
132
+
133
+ // ---- credential
134
+ export interface CredentialFields {
135
+ realm: string; subject: string; role: string; serial: number; notBefore: number; notAfter: number; epoch: number;
136
+ }
137
+ export interface Credential extends CredentialFields { v: 1; issuer: string; sig: string }
138
+ export type CredentialVerdict = Verdict<{
139
+ credential: Credential;
140
+ effective: { notBefore: number; notAfter: number };
141
+ clamped: boolean;
142
+ descriptorBehind: boolean;
143
+ }>;
144
+ export interface CredentialTracker {
145
+ noteEpoch(realm: string, epoch: number): void;
146
+ epochOf(realm: string): number | undefined;
147
+ check(verified: CredentialVerdict, opts?: { now?: Clock }): Verdict;
148
+ admit(verified: CredentialVerdict, opts?: { now?: Clock }): Verdict;
149
+ readonly size: number;
150
+ }
151
+ export function createCredentialTracker(opts?: { maxEntries?: number }): CredentialTracker;
152
+ export function issueCredential(fields: CredentialFields, issuer: PodIdentity): Promise<{ credential: Credential; text: string }>;
153
+ export function verifyCredential(
154
+ text: unknown, descriptor: RealmDescriptor, opts?: { now?: Clock; skew?: number; tracker?: CredentialTracker },
155
+ ): Promise<CredentialVerdict>;
156
+ export function checkSubject(
157
+ credential: Credential | CredentialVerdict | null | undefined, provenKey: string | Uint8Array,
158
+ ): Verdict;
159
+
160
+ // ---- ledger
161
+ export interface LedgerEntry {
162
+ readonly serial: number; readonly subject: string; readonly role: string; readonly notAfter: number; readonly state: "issued" | "revoked";
163
+ }
164
+ export interface Ledger {
165
+ allocate(fields: { subject: string; role: string; notAfter: number }): LedgerEntry;
166
+ get(serial: number): LedgerEntry | null;
167
+ markRevoked(serial: number): boolean;
168
+ list(opts?: { state?: "issued" | "revoked" }): LedgerEntry[];
169
+ revokedSerials(opts: { now: number; max?: number; skew?: number }): number[];
170
+ compact(opts: { now: number; skew?: number }): number;
171
+ export(opts?: { maxBytes?: number }): string;
172
+ readonly size: number;
173
+ readonly nextSerial: number;
174
+ }
175
+ export function createLedger(opts?: { maxEntries?: number; serialStart?: number }): Ledger;
176
+ export function importLedger(text: string, opts?: { maxBytes?: number; maxEntries?: number }): Ledger;
177
+
178
+ // ---- realm exchange (frames, descriptor store, verifier, prover)
179
+ export const FRAME_TYPES: readonly ["realm:hello", "realm:need-descriptor", "realm:descriptor", "realm:credential", "realm:result"];
180
+ export const MAX_FRAME_BYTES: number;
181
+ export const MIN_SEAM_FRAME_BYTES: number;
182
+ export type RealmFrame =
183
+ | { t: "realm:hello"; id: string; serial: number; epoch: number }
184
+ | { t: "realm:need-descriptor"; have: number }
185
+ | { t: "realm:descriptor"; text: string }
186
+ | { t: "realm:credential"; text: string | null }
187
+ | { t: "realm:result"; ok: boolean; reason?: string; role?: string; notAfter?: number };
188
+ export function parseFrame(raw: unknown): { ok: true; frame: RealmFrame } | { ok: false; reason: "bad-frame"; realm: boolean };
189
+
190
+ export interface DescriptorStoreLimits {
191
+ maxBytes: number; maxOffersPerLink: number; maxVerifiesPerLink: number; maxVerifiesPerWindow: number; windowSeconds: number; maxLinks: number;
192
+ }
193
+ export interface DescriptorStore {
194
+ readonly ready: Promise<Verdict>;
195
+ current(): RealmDescriptor | null;
196
+ /** The exact canonical text of the held descriptor (persist it; feed it back as `held`). */
197
+ export(): string | null;
198
+ offer(text: unknown, opts?: { linkId?: unknown }): Promise<Verdict<{ adopted: true; descriptor: RealmDescriptor; text: string }>>;
199
+ onAdopt(fn: (descriptor: RealmDescriptor, previous: RealmDescriptor | null) => void): () => boolean;
200
+ forget(linkId: unknown): void;
201
+ stats(): { verifies: number; adopted: number; rejected: number; links: number };
202
+ }
203
+ export function createDescriptorStore(opts: {
204
+ pinnedId: string;
205
+ held?: string;
206
+ heldChain?: RotationStatement[];
207
+ now?: Clock;
208
+ limits?: Partial<DescriptorStoreLimits>;
209
+ onAdopt?: (descriptor: RealmDescriptor, previous: RealmDescriptor | null) => void;
210
+ }): DescriptorStore;
211
+
212
+ /** The channel shape of the admission seam's `handler` link, and of the prover's side. */
213
+ export interface RealmChannel {
214
+ send(frame: RealmFrame | object): unknown;
215
+ onFrame(cb: (frame: unknown) => unknown): void;
216
+ onClose(cb: (reason?: string) => void): void;
217
+ close(reason?: string): unknown;
218
+ }
219
+ /** What `createLinkAdmission({ handler })` passes a handler. */
220
+ export interface AdmissionLink extends RealmChannel {
221
+ peerKey: string;
222
+ transport: string;
223
+ proven: boolean;
224
+ promote(): boolean;
225
+ }
226
+ /** The two `PeerRegistry` methods the verifier uses (duck-typed: this package never imports browsermesh-apps). */
227
+ export interface RealmRegistry {
228
+ grantRealmScopes(grant: {
229
+ realmId: string; serial: string | number; peerKey: string; role: string; scopes: string[]; notAfter: number; epoch: number;
230
+ }): { granted: string[]; dropped: { scope: string | null; reason: string }[] };
231
+ revokeRealmGrants(selector: { realmId: string; peerKey?: string; serial?: string | number; belowEpoch?: number }): number;
232
+ }
233
+ export interface RealmVerifierLimits { maxFrames: number; maxDescriptorReplies: number; guestTtl: number }
234
+ export type RealmEvent =
235
+ | { type: "refused"; peerKey: string; reason: string; detail?: string }
236
+ | { type: "granted"; peerKey: string; role: string; serial: number; granted: string[]; dropped: { scope: string | null; reason: string }[] }
237
+ | { type: "promoted"; peerKey: string; role: string }
238
+ | { type: "descriptor-adopted"; serial: number; epoch: number };
239
+ export function createRealmVerifier(opts: {
240
+ pinnedId: string;
241
+ store: DescriptorStore;
242
+ registry: RealmRegistry;
243
+ now?: Clock;
244
+ skew?: number;
245
+ tracker?: CredentialTracker;
246
+ limits?: Partial<RealmVerifierLimits>;
247
+ onEvent?: (event: RealmEvent) => void;
248
+ }): { handler: (link: AdmissionLink) => Promise<void>; tracker: CredentialTracker };
249
+ export type ProverResult = { ok: true; role?: string; notAfter?: number } | { ok: false; reason: string };
250
+ export function createRealmProver(opts: {
251
+ pinnedId: string;
252
+ store: DescriptorStore;
253
+ credential?: string | null;
254
+ channel: RealmChannel;
255
+ now?: Clock;
256
+ timeoutMs?: number;
257
+ }): Promise<ProverResult>;