@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/LICENSE +21 -0
- package/README.md +189 -2
- package/package.json +42 -4
- package/src/adopt.mjs +34 -0
- package/src/credential.mjs +138 -0
- package/src/descriptor.mjs +298 -0
- package/src/errors.mjs +47 -0
- package/src/frames.mjs +74 -0
- package/src/index.d.ts +257 -0
- package/src/index.mjs +19 -0
- package/src/keys.mjs +78 -0
- package/src/ledger.mjs +164 -0
- package/src/limits.mjs +31 -0
- package/src/prover.mjs +137 -0
- package/src/roles.mjs +80 -0
- package/src/rotation.mjs +135 -0
- package/src/store.mjs +137 -0
- package/src/tracker.mjs +65 -0
- package/src/validate.mjs +28 -0
- package/src/verifier.mjs +230 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 John Henry
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,190 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @johnhenry/browsermesh-realm
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@johnhenry/browsermesh-realm)
|
|
4
|
+
[](LICENSE)
|
|
5
|
+
|
|
6
|
+
The pure-logic core of **realms** (design: [docs/design/realms.md](../../docs/design/realms.md)): signed realm descriptors,
|
|
7
|
+
root rotation, roles, issuer-signed credentials, and the issuer ledger.
|
|
8
|
+
|
|
9
|
+
**Status: a preview, published to npm as 0.1.x.** The API may still change before 1.0; tickets, admitters, federation and live peer listing are not built (see "Not here"). The pure logic has no I/O, no network and no clock
|
|
10
|
+
of its own: every function takes plain objects and an injectable `now`. The realm exchange (below) talks to a duck-typed
|
|
11
|
+
channel and a duck-typed registry, so it needs no transport either. `createMeshNode({ realm })` in `browsermesh-apps` now wires
|
|
12
|
+
it in (the admission seam, the dialler, and renewal over the `realm` protocol of the protocol seam; see that README's "Realms"
|
|
13
|
+
section); `meshctl realm` (in `browsermesh-meshctl`) drives it from the command line. It depends on `@johnhenry/browsermesh-primitives` only (peer dependency, `>=0.8.0`,
|
|
14
|
+
the first release that exports `canonicalJson`), never on
|
|
15
|
+
`browsermesh-apps` or `browsermesh-core`; the integration tests that use the real `PeerRegistry`, the real admission seam
|
|
16
|
+
and a real wsh link live in `browsermesh-apps` (`test/realm-exchange-wsh.test.mjs`), which has this package as a devDependency.
|
|
17
|
+
|
|
18
|
+
Everything is signed with Ed25519 over strict canonical JSON (`canonicalJson` / `parseCanonical` /
|
|
19
|
+
`domainSigningBytes` from primitives). One domain per object type:
|
|
20
|
+
|
|
21
|
+
| Object | Domain |
|
|
22
|
+
| --- | --- |
|
|
23
|
+
| descriptor | `browsermesh-realm/descriptor/1` |
|
|
24
|
+
| authority-less id (hash, not a signature) | `browsermesh-realm/authorityless-id/1` |
|
|
25
|
+
| rotation statement | `browsermesh-realm/rotation/1` |
|
|
26
|
+
| rotation countersignature | `browsermesh-realm/rotation-accept/1` |
|
|
27
|
+
| credential | `browsermesh-realm/credential/1` |
|
|
28
|
+
| ticket (reserved, not built) | `browsermesh-realm/ticket/1` |
|
|
29
|
+
|
|
30
|
+
Keys and signatures are base64url strings (raw 32-byte key, 64-byte signature, strict: no padding, no stray bits). Times
|
|
31
|
+
are **whole seconds** (the registry takes milliseconds; the caller multiplies). `now` is seconds, or a function returning
|
|
32
|
+
them. Verifiers never throw on hostile input: they return `{ ok: false, reason, detail }`. Builders throw a typed
|
|
33
|
+
`RealmError` with a stable `code`.
|
|
34
|
+
|
|
35
|
+
## Install
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
npm install @johnhenry/browsermesh-realm @johnhenry/browsermesh-primitives
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
`@johnhenry/browsermesh-primitives` (`>=0.8.0 <1.0.0`) is a peer dependency. Node >= 26 or a current browser.
|
|
42
|
+
|
|
43
|
+
## Usage
|
|
44
|
+
|
|
45
|
+
```js
|
|
46
|
+
import { createDescriptor, signDescriptor, verifyDescriptor, adoptDescriptor,
|
|
47
|
+
issueCredential, verifyCredential, checkSubject, createCredentialTracker } from "@johnhenry/browsermesh-realm";
|
|
48
|
+
|
|
49
|
+
const d = await createDescriptor({ name: "my realm", root: { key: rootKey }, issuers: [{ key: issuerKey, notAfter }],
|
|
50
|
+
roles: { guest: ["protocol:mcp:open"], member: ["mcp:search:call"] } });
|
|
51
|
+
const { text } = await signDescriptor(d, rootIdentity); // canonical text, sig inside
|
|
52
|
+
const v = await verifyDescriptor(text, { pinnedId: d.id, now }); // { ok, descriptor, chainLength } | { ok: false, reason }
|
|
53
|
+
|
|
54
|
+
const { text: cred } = await issueCredential({ realm: d.id, subject: memberKey, role: "member", serial: 1,
|
|
55
|
+
notBefore, notAfter, epoch: 0 }, issuerIdentity);
|
|
56
|
+
const c = await verifyCredential(cred, v.descriptor, { now, tracker }); // clamps lifetime, checks epoch/revoked/issuer
|
|
57
|
+
checkSubject(c, keyTheLinkProved); // for the exchange layer
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## What is checked, in order
|
|
61
|
+
|
|
62
|
+
- **Descriptor** (`verifyDescriptor`): size, strict canonical parse (anything not byte-identical to its own canonical
|
|
63
|
+
form is refused), shape and roles, pinned id, rotation chain, root signature, `validUntil`. The realm id is the
|
|
64
|
+
base64url SHA-256 of the **genesis** root key (the pod-id derivation), so rotation never changes it.
|
|
65
|
+
- **Adoption** (`adoptDescriptor(held, offered, { pinnedId, now })`): the offered text must verify end to end AND have a
|
|
66
|
+
strictly higher `serial`; its `epoch` may not drop; its chain may not fork or shorten what is held. Size and chain
|
|
67
|
+
length are capped (16 KiB, 8).
|
|
68
|
+
- **Roles**: a scope is `ns:resource:action` written out in full. A `*`, fewer than 3 segments (a wildcard under
|
|
69
|
+
`matchScope`) or an empty segment is rejected at parse, even if correctly signed, so write `mcp:tool:call`, not
|
|
70
|
+
`mcp:tool`.
|
|
71
|
+
- **Credential** (`verifyCredential`): size, canonical parse, realm id, descriptor freshness, issuer listed (and its own
|
|
72
|
+
expiry), signature, role defined, epoch not below the descriptor's, serial not in `revoked`, then the lifetime:
|
|
73
|
+
`effective notAfter = min(notAfter, notBefore + ttl, issuer.notAfter)`, with a clock-skew tolerance of 300 s (the
|
|
74
|
+
`skew` option is capped at 300, never more). So a compromised issuer cannot mint past `ttl`, and backdating
|
|
75
|
+
`notBefore` only moves the window into the past. A credential with an epoch **above** the descriptor's is accepted and
|
|
76
|
+
flagged `descriptorBehind`. There is no keyless credential; the subject is always a key.
|
|
77
|
+
- **Monotonic checks** (`createCredentialTracker`): `PeerRegistry` replaces grants by (realm, peer, role) and does not
|
|
78
|
+
order serials, so a verifier holding a newer serial for the same (realm, issuer, subject, role), or a higher epoch
|
|
79
|
+
for the realm, refuses an older credential (`stale-serial`, `epoch-too-old`). Pass the tracker to `verifyCredential`
|
|
80
|
+
or call `admit`/`check` yourself. It is bounded (it refuses new keys when full, after evicting expired ones; it never
|
|
81
|
+
forgets a live serial).
|
|
82
|
+
- **Ledger** (`createLedger`): in-memory, append-only (the only state change is `issued` to `revoked`), serial
|
|
83
|
+
allocation, `revokedSerials` to feed `descriptor.revoked`, `compact` for dead entries, and canonical-JSON
|
|
84
|
+
`export`/`importLedger` with size caps. Serials are per ledger: a realm with several issuers must give each ledger a
|
|
85
|
+
disjoint `serialStart` or share one ledger, because `descriptor.revoked` has no issuer field.
|
|
86
|
+
- **Authority-less open form** (`createAuthorityless`, `verifyAuthorityless`): no root, no issuers, no signature; the id
|
|
87
|
+
hashes (name, roles, salt) only; the rendezvous `hints` sit outside the hash and are replaceable candidates, not
|
|
88
|
+
authority. It carries exactly one role, `guest`, and never an `egress:`, `ingress:`, `pod-host` or `wsh-` scope.
|
|
89
|
+
|
|
90
|
+
## The realm exchange
|
|
91
|
+
|
|
92
|
+
`createDescriptorStore`, `createRealmVerifier` and `createRealmProver` implement `realms.md` 5.5 on a link whose peer key is
|
|
93
|
+
proven but not yet known.
|
|
94
|
+
|
|
95
|
+
```js
|
|
96
|
+
const store = createDescriptorStore({ pinnedId, held: bakedDescriptorText, now }); // await store.ready
|
|
97
|
+
const { handler } = createRealmVerifier({ pinnedId, store, registry /* a PeerRegistry */ });
|
|
98
|
+
const admission = createLinkAdmission({ decide: () => "restrict", handler }); // browsermesh-apps; createMeshNode({ admission })
|
|
99
|
+
|
|
100
|
+
// the dialler, with a channel over its link to the host (send, onFrame, onClose, close):
|
|
101
|
+
const result = await createRealmProver({ pinnedId, store: ownStore, credential: credentialText, channel, timeoutMs: 5000 });
|
|
102
|
+
// { ok: true, role, notAfter } | { ok: false, reason }
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
**Frames** (`realm:*`, JSON objects, each field checked and size-capped; `parseFrame` takes an object or JSON text):
|
|
106
|
+
|
|
107
|
+
| `t` | fields | sent by | meaning |
|
|
108
|
+
| --- | --- | --- | --- |
|
|
109
|
+
| `realm:hello` | `id`, `serial`, `epoch` | both | the realm, and the descriptor held (`serial` 0 = none) |
|
|
110
|
+
| `realm:need-descriptor` | `have` | the side that is behind | "send yours; I hold serial `have`" |
|
|
111
|
+
| `realm:descriptor` | `text` (<= 16 KiB) | the side that is ahead | the exact canonical text; verified, never trusted |
|
|
112
|
+
| `realm:credential` | `text` (<= 2 KiB) or `null` | prover | its credential; `null` asks for the open-mode default role |
|
|
113
|
+
| `realm:result` | `ok`, `reason?`, `role?`, `notAfter?` | verifier | the verdict; `notAfter` in whole seconds |
|
|
114
|
+
|
|
115
|
+
**Order.** The verifier sends its hello at once. On the peer's hello, the side that is behind asks for the descriptor; the
|
|
116
|
+
prover sends its credential only after that is settled. The verifier then checks the credential against the CURRENT
|
|
117
|
+
descriptor (`verifyCredential`), the subject against the key the link proved (`checkSubject`), the order against a tracker,
|
|
118
|
+
computes the role's scopes from the descriptor, calls `registry.grantRealmScopes(...)` (`notAfter` in milliseconds), and only
|
|
119
|
+
then sends `realm:result` and calls `promote()`. A link restricted by the seam is not in the registry: granting first is what
|
|
120
|
+
keeps the promoted peer from being closed by the default access watcher at its next access change. **A role must therefore
|
|
121
|
+
include `mesh:link:connect` and the host's policy must admit it**, or the watcher closes the link at that re-check.
|
|
122
|
+
|
|
123
|
+
**Subject.** A credential's `subject` is the peer's POD ID (what a link calls `peerKey`: the registry and wsh key by it),
|
|
124
|
+
not the raw public key.
|
|
125
|
+
|
|
126
|
+
**Refusal reasons** (`realm:result.reason`, then `link.close(reason)`; stable):
|
|
127
|
+
- protocol: `bad-frame`, `unexpected-frame`, `too-many-frames`, `wrong-realm`, `unproven`
|
|
128
|
+
- descriptor: `descriptor-rejected` (a peer's descriptor did not verify, was a fork or regression, or was not higher),
|
|
129
|
+
`rate-limited`, `no-descriptor`, `descriptor-stale`
|
|
130
|
+
- credential: `no-credential`, `subject-mismatch`, `credential-rejected`, and the package's own `malformed`, `too-large`,
|
|
131
|
+
`not-canonical`, `unsupported-version`, `issuer-not-listed`, `bad-signature`, `unknown-role`, `epoch-too-old`, `revoked`,
|
|
132
|
+
`not-yet-valid`, `expired`, `stale-serial`, `tracker-full`
|
|
133
|
+
- grant: `no-grant` (the registry granted nothing), `grant-error` (it threw)
|
|
134
|
+
- `internal-error`. The prover adds `peer-does-not-speak-realms` (no `realm:` frame before `timeoutMs`; an older peer
|
|
135
|
+
ignores unknown types), `timeout` (it began and stalled) and `peer-closed`. A peer that goes quiet is the seam's deadline's
|
|
136
|
+
problem, not the handler's: the handler holds no timer.
|
|
137
|
+
|
|
138
|
+
**Unproven links** are refused (`unproven`), guest or not: a grant to a key the link did not prove would be a grant to
|
|
139
|
+
whoever claims it.
|
|
140
|
+
|
|
141
|
+
**Descriptor adoption** is bounded. An offer is size-capped, costs a JSON read when its serial is not higher than the held one
|
|
142
|
+
(no signature check), and is rate-limited per link and across links (`createDescriptorStore({ limits })`). Offers are
|
|
143
|
+
serialised. When the store adopts a descriptor with a higher epoch the verifier calls `registry.revokeRealmGrants({ realmId,
|
|
144
|
+
belowEpoch })`, and for each newly listed revoked serial `revokeRealmGrants({ realmId, serial })`, so open links re-check.
|
|
145
|
+
Persist `store.export()` and feed it back as `held`. A removed issuer's existing grants are not revoked (a grant does not
|
|
146
|
+
record its issuer); they end at `notAfter`.
|
|
147
|
+
|
|
148
|
+
**Ordering is this layer's job.** `PeerRegistry` replaces a grant by (realm, peer, role) and does not order serials; the
|
|
149
|
+
verifier asks the tracker first, so a second exchange from a granted peer with a NEWER serial renews, and an older serial
|
|
150
|
+
arriving later is refused (`stale-serial`). The same serial again (a reconnect) is accepted.
|
|
151
|
+
|
|
152
|
+
**Admission seam sizing.** The seam drops frames over its `maxFrameBytes` (default 16 KiB), and a descriptor's JSON escaping
|
|
153
|
+
can double it: a host that wants to receive descriptors of any allowed size sets `maxFrameBytes: MIN_SEAM_FRAME_BYTES`.
|
|
154
|
+
|
|
155
|
+
**Not here.** Renewal over an open link (a fresh credential before `notAfter` without re-linking) needs the protocol seam
|
|
156
|
+
(stage 4). Re-linking renews only when the peer reaches the handler at all: a peer the registry already allows is admitted as
|
|
157
|
+
an ordinary link and never put to the exchange. Tickets are not built.
|
|
158
|
+
|
|
159
|
+
## Rotation and its known limit
|
|
160
|
+
|
|
161
|
+
A rotation statement is signed by the outgoing root and **countersigned by the successor** (so the successor provably
|
|
162
|
+
holds the key), names a chain position and an effective time, and is checked from the genesis key. The first-seen fork
|
|
163
|
+
rule: a verifier that holds a chain position never accepts a different statement for it (`chain-fork`), and never
|
|
164
|
+
accepts a shorter chain (`chain-regressed`).
|
|
165
|
+
|
|
166
|
+
**Known limit.** A retired root key that later leaks can sign a competing successor; a verifier that has seen nothing
|
|
167
|
+
but the genesis key (a fresh page) cannot tell the fork from the real chain and will accept whichever it meets first.
|
|
168
|
+
Rotation limits the damage of key aging and planned changes, not of compromise. A compromised current root ends the
|
|
169
|
+
realm.
|
|
170
|
+
|
|
171
|
+
## Security stance and limits
|
|
172
|
+
|
|
173
|
+
- Nothing here enforces a realm by itself: a host must opt in (`createMeshNode({ realm })`) and list the realm id and, per role,
|
|
174
|
+
the scopes it will honour in its `realmPolicy`. See [docs/security.md](../../docs/security.md), "Realms".
|
|
175
|
+
- Every verifier takes hostile input and returns `{ ok: false, reason }` rather than throwing; sizes, chain length, frame counts
|
|
176
|
+
and adoption rate are capped (options: `now`, `skew` (max 300 s), `tracker`, `limits` on the descriptor store, `timeoutMs` on the prover).
|
|
177
|
+
- Grants are in memory and lost on restart; revocation is by serial in the descriptor, expiry or an epoch bump; one realm per node.
|
|
178
|
+
- Not built: tickets, admitters, federation between realms, live peer listing. The rotation limit below is inherent.
|
|
179
|
+
|
|
180
|
+
## Test vectors
|
|
181
|
+
|
|
182
|
+
`test/vectors/{descriptor,rotation,credential}.json` are language-neutral: fixed 32-byte seeds as hex, the public
|
|
183
|
+
keys, the canonical unsigned text, the signature, the exact signed bytes, and accept/reject verdicts (non-canonical,
|
|
184
|
+
wrong domain, tampered field, expired, clock-skew edge, revoked serial, removed issuer, older epoch, stale serial,
|
|
185
|
+
forked chain, ...). `npm run vectors` regenerates them from `test/make-vectors.mjs` (every verdict there is written by
|
|
186
|
+
hand); `vectors.test.mjs` fails if the committed files drift from what the generator produces.
|
|
187
|
+
|
|
188
|
+
## License
|
|
189
|
+
|
|
190
|
+
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@johnhenry/browsermesh-realm",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"description": "Realms for browsermesh: signed realm descriptors, root rotation, roles, issuer-signed credentials and the issuer ledger, as pure functions over canonical JSON and Ed25519",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.mjs",
|
|
7
|
+
"types": "./src/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./src/index.d.ts",
|
|
11
|
+
"default": "./src/index.mjs"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"sideEffects": false,
|
|
15
|
+
"files": [
|
|
16
|
+
"src",
|
|
17
|
+
"LICENSE",
|
|
18
|
+
"README.md"
|
|
19
|
+
],
|
|
20
|
+
"keywords": [
|
|
21
|
+
"mesh",
|
|
22
|
+
"p2p",
|
|
23
|
+
"realm",
|
|
24
|
+
"credentials",
|
|
25
|
+
"canonical-json",
|
|
26
|
+
"ed25519"
|
|
27
|
+
],
|
|
28
|
+
"license": "MIT",
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "https://github.com/johnhenry/browsermesh",
|
|
32
|
+
"directory": "packages/browsermesh-realm"
|
|
33
|
+
},
|
|
34
|
+
"homepage": "https://opensource.johnhenry.me/browsermesh/",
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"access": "public"
|
|
37
|
+
},
|
|
38
|
+
"peerDependencies": {
|
|
39
|
+
"@johnhenry/browsermesh-primitives": ">=0.8.0 <1.0.0"
|
|
40
|
+
},
|
|
41
|
+
"engines": {
|
|
42
|
+
"node": ">=26.0.0"
|
|
43
|
+
}
|
|
44
|
+
}
|
package/src/adopt.mjs
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// Adoption (docs/design/realms.md 5.2): a descriptor offered by any peer is adopted only after it verifies end to end
|
|
2
|
+
// against the pinned id and the rotation chain AND its serial is strictly higher than the held one. It never throws on
|
|
3
|
+
// hostile input; the verifier caps size and chain length, so a peer announcing a high serial buys bounded work.
|
|
4
|
+
import { guard, fail } from "./errors.mjs";
|
|
5
|
+
import { verifyDescriptor } from "./descriptor.mjs";
|
|
6
|
+
import { isPlainObject, need } from "./validate.mjs";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @param {object | null | undefined} held the verified descriptor object currently held (or none)
|
|
10
|
+
* @param {unknown} offered the offered descriptor text
|
|
11
|
+
* @param {{ pinnedId: string, now?: number | (() => number), maxBytes?: number, maxChain?: number }} opts
|
|
12
|
+
* @returns {Promise<{ ok: true, descriptor: object, text: string, chainLength: number } | { ok: false, reason: string, detail?: string }>}
|
|
13
|
+
*/
|
|
14
|
+
export function adoptDescriptor(held, offered, opts) {
|
|
15
|
+
return guard(async () => {
|
|
16
|
+
const { pinnedId, now, maxBytes, maxChain } = opts ?? {};
|
|
17
|
+
need(typeof pinnedId === "string", "adoptDescriptor needs a pinnedId");
|
|
18
|
+
const have = held === null || held === undefined ? null : held;
|
|
19
|
+
if (have !== null) {
|
|
20
|
+
const root = have.root;
|
|
21
|
+
if (!isPlainObject(have) || have.id !== pinnedId || !isPlainObject(root) || !Array.isArray(root.chain)
|
|
22
|
+
|| !Number.isSafeInteger(have.serial) || !Number.isSafeInteger(have.epoch)) {
|
|
23
|
+
fail("held-mismatch", "the held descriptor is not a verified descriptor for the pinned id");
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
const v = await verifyDescriptor(offered, { pinnedId, now, maxBytes, maxChain, heldChain: have?.root.chain });
|
|
27
|
+
if (!v.ok) return v;
|
|
28
|
+
if (have !== null) {
|
|
29
|
+
if (v.descriptor.serial <= have.serial) fail("stale-serial", "serial is not higher than the one held");
|
|
30
|
+
if (v.descriptor.epoch < have.epoch) fail("epoch-regressed", "epoch is lower than the one held");
|
|
31
|
+
}
|
|
32
|
+
return v;
|
|
33
|
+
});
|
|
34
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// Credentials (docs/design/realms.md 5.4).
|
|
2
|
+
//
|
|
3
|
+
// An issuer-signed statement that one KEY has a role in one realm for a time. Fields: realm id, subject key, role,
|
|
4
|
+
// serial, notBefore, notAfter (whole seconds), epoch, and the issuer's key. There is no keyless form: the subject is
|
|
5
|
+
// always a key, and the exchange layer checks it against the key the link proved (`checkSubject`).
|
|
6
|
+
//
|
|
7
|
+
// The verifier does not trust the issuer's dates: it CLAMPS the lifetime so that
|
|
8
|
+
// effective notAfter = min(notAfter, notBefore + descriptor.ttl, issuer.notAfter)
|
|
9
|
+
// which means a compromised issuer cannot mint past the realm's ttl and cannot gain anything by backdating notBefore
|
|
10
|
+
// (a backdated window simply ends in the past). Delegation is exactly one level deep: the descriptor lists issuers, and
|
|
11
|
+
// only a listed issuer's signature counts.
|
|
12
|
+
import { canonicalJson, parseCanonical, encodeBase64url } from "@johnhenry/browsermesh-primitives";
|
|
13
|
+
import { fail, guard, building } from "./errors.mjs";
|
|
14
|
+
import { DOMAINS, MAX_CREDENTIAL_BYTES, DEFAULT_SKEW, MAX_SKEW } from "./limits.mjs";
|
|
15
|
+
import { isKey, isSig, keyBytes, publicKeyOf, signBody, verifyBody, resolveNow } from "./keys.mjs";
|
|
16
|
+
import { exactKeys, isInt, isPlainObject, isTime, need, utf8Length } from "./validate.mjs";
|
|
17
|
+
import { isRoleName } from "./roles.mjs";
|
|
18
|
+
import { isStale } from "./descriptor.mjs";
|
|
19
|
+
|
|
20
|
+
const BODY = ["v", "realm", "subject", "role", "serial", "notBefore", "notAfter", "epoch", "issuer"];
|
|
21
|
+
|
|
22
|
+
function checkBody(c) {
|
|
23
|
+
exactKeys(c, BODY, ["sig"], "credential");
|
|
24
|
+
if (c.v !== 1) fail("unsupported-version", "credential version must be 1");
|
|
25
|
+
need(isKey(c.realm), "bad realm id");
|
|
26
|
+
need(isKey(c.subject), "subject must be a key (there is no keyless credential)");
|
|
27
|
+
need(isKey(c.issuer), "bad issuer key");
|
|
28
|
+
need(isRoleName(c.role), "bad role name");
|
|
29
|
+
need(isInt(c.serial, 1), "serial must be an integer >= 1");
|
|
30
|
+
need(isTime(c.notBefore) && isTime(c.notAfter) && c.notAfter > c.notBefore, "bad lifetime (whole seconds, notAfter after notBefore)");
|
|
31
|
+
need(isInt(c.epoch, 0), "epoch must be an integer >= 0");
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Sign a credential as an issuer.
|
|
36
|
+
* @param {{ realm: string, subject: string, role: string, serial: number, notBefore: number, notAfter: number, epoch: number }} fields
|
|
37
|
+
* @param {import("@johnhenry/browsermesh-primitives").PodIdentity} issuer
|
|
38
|
+
* @returns {Promise<{ credential: object, text: string }>}
|
|
39
|
+
*/
|
|
40
|
+
export function issueCredential(fields, issuer) {
|
|
41
|
+
return building(async () => {
|
|
42
|
+
need(isPlainObject(fields), "fields must be an object");
|
|
43
|
+
const body = {
|
|
44
|
+
v: 1, realm: fields.realm, subject: fields.subject, role: fields.role, serial: fields.serial,
|
|
45
|
+
notBefore: fields.notBefore, notAfter: fields.notAfter, epoch: fields.epoch, issuer: await publicKeyOf(issuer),
|
|
46
|
+
};
|
|
47
|
+
checkBody(body);
|
|
48
|
+
const text = canonicalJson({ ...body, sig: await signBody(issuer, DOMAINS.credential, body) });
|
|
49
|
+
return { credential: parseCanonical(text), text };
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function checkDescriptorShape(d) {
|
|
54
|
+
need(
|
|
55
|
+
isPlainObject(d) && isKey(d.id) && Array.isArray(d.issuers) && isPlainObject(d.roles) && Number.isSafeInteger(d.ttl) &&
|
|
56
|
+
Array.isArray(d.revoked) && Number.isSafeInteger(d.epoch),
|
|
57
|
+
"a verified descriptor is required",
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Verify a credential against a descriptor the caller has already verified.
|
|
63
|
+
*
|
|
64
|
+
* Order: size, strict canonical parse, shape, realm, descriptor freshness, issuer listed, signature, role defined,
|
|
65
|
+
* epoch, revoked serial, lifetime (clamped, with skew). Never throws.
|
|
66
|
+
*
|
|
67
|
+
* @param {unknown} text the exact received text
|
|
68
|
+
* @param {object} descriptor a descriptor returned by `verifyDescriptor` / `adoptDescriptor`
|
|
69
|
+
* @param {{ now?: number | (() => number), skew?: number, tracker?: ReturnType<import("./tracker.mjs").createCredentialTracker> }} [opts]
|
|
70
|
+
* `skew` is clamped to 0..300 seconds
|
|
71
|
+
* @returns {Promise<{ ok: true, credential: object, effective: { notBefore: number, notAfter: number }, clamped: boolean, descriptorBehind: boolean } | { ok: false, reason: string, detail?: string }>}
|
|
72
|
+
*/
|
|
73
|
+
export function verifyCredential(text, descriptor, opts) {
|
|
74
|
+
return guard(async () => {
|
|
75
|
+
const o = opts ?? {};
|
|
76
|
+
const now = resolveNow(o.now);
|
|
77
|
+
const skew = Math.max(0, Math.min(MAX_SKEW, Number.isFinite(o.skew) ? Math.floor(o.skew) : DEFAULT_SKEW));
|
|
78
|
+
if (typeof text !== "string") fail("malformed", "credential must be text");
|
|
79
|
+
if (utf8Length(text) > MAX_CREDENTIAL_BYTES) fail("too-large", "credential is too large");
|
|
80
|
+
const doc = parseCanonical(text);
|
|
81
|
+
exactKeys(doc, [...BODY, "sig"], [], "credential");
|
|
82
|
+
need(isSig(doc.sig), "bad signature encoding");
|
|
83
|
+
const { sig, ...body } = doc;
|
|
84
|
+
checkBody(body);
|
|
85
|
+
checkDescriptorShape(descriptor);
|
|
86
|
+
|
|
87
|
+
if (body.realm !== descriptor.id) fail("wrong-realm", "credential is for another realm");
|
|
88
|
+
if (isStale(descriptor, now)) fail("descriptor-stale", "the descriptor snapshot is past its validUntil");
|
|
89
|
+
const issuer = descriptor.issuers.find((i) => i?.key === body.issuer);
|
|
90
|
+
if (!issuer) fail("issuer-not-listed", "the descriptor does not list this issuer");
|
|
91
|
+
if (!(await verifyBody(body.issuer, DOMAINS.credential, body, sig))) fail("bad-signature", "issuer signature does not verify");
|
|
92
|
+
if (!Object.hasOwn(descriptor.roles, body.role)) fail("unknown-role", "the descriptor does not define this role");
|
|
93
|
+
if (body.epoch < descriptor.epoch) fail("epoch-too-old", "credential predates the realm's epoch");
|
|
94
|
+
if (descriptor.revoked.includes(body.serial)) fail("revoked", "credential serial is revoked");
|
|
95
|
+
|
|
96
|
+
const effNotAfter = Math.min(body.notAfter, body.notBefore + descriptor.ttl, issuer.notAfter);
|
|
97
|
+
if (now < body.notBefore - skew) fail("not-yet-valid", "credential is not valid yet");
|
|
98
|
+
if (now > effNotAfter + skew) fail("expired", "credential has expired");
|
|
99
|
+
|
|
100
|
+
const result = {
|
|
101
|
+
ok: true,
|
|
102
|
+
credential: doc,
|
|
103
|
+
effective: { notBefore: body.notBefore, notAfter: effNotAfter },
|
|
104
|
+
clamped: effNotAfter < body.notAfter,
|
|
105
|
+
descriptorBehind: body.epoch > descriptor.epoch,
|
|
106
|
+
};
|
|
107
|
+
if (o.tracker) {
|
|
108
|
+
o.tracker.noteEpoch(descriptor.id, descriptor.epoch);
|
|
109
|
+
const admitted = o.tracker.admit(result, { now });
|
|
110
|
+
if (!admitted.ok) return { ok: false, reason: admitted.reason };
|
|
111
|
+
}
|
|
112
|
+
return result;
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The exchange layer's check: the credential's subject must be the key the link proved.
|
|
118
|
+
* @param {{ subject?: string, credential?: { subject: string } } | null} credential a credential, or a `verifyCredential` result
|
|
119
|
+
* @param {string | Uint8Array} provenKey base64url or raw 32-byte public key from the link
|
|
120
|
+
* @returns {{ ok: true } | { ok: false, reason: "subject-mismatch" | "malformed" }}
|
|
121
|
+
*/
|
|
122
|
+
export function checkSubject(credential, provenKey) {
|
|
123
|
+
const c = credential?.credential ?? credential;
|
|
124
|
+
if (!c || typeof c.subject !== "string") return { ok: false, reason: "malformed" };
|
|
125
|
+
let key;
|
|
126
|
+
try {
|
|
127
|
+
key = typeof provenKey === "string" ? provenKey : rawToKey(provenKey);
|
|
128
|
+
keyBytes(key);
|
|
129
|
+
} catch {
|
|
130
|
+
return { ok: false, reason: "malformed" };
|
|
131
|
+
}
|
|
132
|
+
return key === c.subject ? { ok: true } : { ok: false, reason: "subject-mismatch" };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function rawToKey(bytes) {
|
|
136
|
+
if (!(bytes instanceof Uint8Array) || bytes.length !== 32) throw new TypeError("expected 32 bytes");
|
|
137
|
+
return encodeBase64url(bytes);
|
|
138
|
+
}
|