@johnhenry/browsermesh-primitives 0.3.0 → 0.4.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/README.md +58 -1
- package/package.json +1 -1
- package/src/identity.mjs +228 -4
- package/src/index.d.ts +135 -2
- package/src/index.mjs +31 -0
- package/src/mesh-address.mjs +56 -0
- package/src/session.mjs +739 -0
package/README.md
CHANGED
|
@@ -89,12 +89,17 @@ console.log(set.has('item')) // true
|
|
|
89
89
|
|
|
90
90
|
### Identity
|
|
91
91
|
|
|
92
|
-
- `PodIdentity` -- Ed25519 key pair with sign/verify
|
|
92
|
+
- `PodIdentity` -- Ed25519 key pair with sign/verify; also `fromCryptoKeyPair`, `fromJwk`, `fromPkcs8`, `fromSigner`, `generate({ extractable })` (see [Vault-friendly identity](#vault-friendly-identity-session-certificates-and-revocation))
|
|
93
93
|
- `derivePodId(publicKey)` -- SHA-256 hash to base64url pod ID
|
|
94
94
|
- `encodeBase64url(bytes)` / `decodeBase64url(str)` -- URL-safe base64
|
|
95
|
+
- Session certificates and signed revocation: `createSession`, `issueSessionCertificate`, `verifyPeerCredential`, `scopeAllows`, `revokeSessionCertificate`, `retireIdentity`, `receiveRevocation`, `isRevoked`, `MemoryRevocationStore`, `CredentialError`
|
|
95
96
|
|
|
96
97
|
### Wire Format
|
|
97
98
|
|
|
99
|
+
- `parseMeshRequest(url)` — shared browser-safe parsing of `mesh://` and
|
|
100
|
+
`*.mesh.local` addresses into `{ podId, path }`, preserving ID case and
|
|
101
|
+
query strings and excluding fragments. Discovery re-exports the same helper.
|
|
102
|
+
|
|
98
103
|
- `messageTypeRegistry` -- extensible registry of message types
|
|
99
104
|
- `encodeMeshMessage(msg)` / `decodeMeshMessage(bytes)` -- binary serialization
|
|
100
105
|
|
|
@@ -190,6 +195,58 @@ acl.check(sender, 'mesh://memory/notes', 'write'); // { allowed: false, reason:
|
|
|
190
195
|
```
|
|
191
196
|
|
|
192
197
|
|
|
198
|
+
### Vault-friendly identity, session certificates and revocation
|
|
199
|
+
|
|
200
|
+
**Where the key lives.** `PodIdentity` can be built four ways, and every signature goes through one `sign()` seam:
|
|
201
|
+
|
|
202
|
+
```js
|
|
203
|
+
await PodIdentity.generate(); // as before: extractable key
|
|
204
|
+
await PodIdentity.generate({ extractable: false }); // usable, never readable by the page
|
|
205
|
+
await PodIdentity.fromJwk(jwk); // import (non-extractable unless { extractable: true })
|
|
206
|
+
await PodIdentity.fromPkcs8(bytes, { publicKey }); // PKCS#8 has no public half: pass it, or ask for extractable: true
|
|
207
|
+
await PodIdentity.fromCryptoKeyPair(storedKeyPair); // e.g. a non-extractable pair loaded from IndexedDB
|
|
208
|
+
await PodIdentity.fromSigner({ publicKey, sign }); // the private key is in a vault, token, extension...
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
Nothing in this package calls `exportKey` on a private key; `identity.exportPrivateKey()` is the only way, and it rejects unless the identity was made exportable. The signer is `{ publicKey, sign(data) }` -- `publicKey` the raw 32-byte key or a public `CryptoKey`, `sign` returning the 64-byte signature, sync or async. That is the same shape as `@johnhenry/wsh`'s "Signing with a page-held signer", so one signer object can serve both libraries.
|
|
212
|
+
|
|
213
|
+
**Session certificates.** Use the long-lived identity key rarely: once per session, to certify a short-lived, non-extractable session key.
|
|
214
|
+
|
|
215
|
+
```js
|
|
216
|
+
const { session, certificate } = await createSession(identity, {
|
|
217
|
+
scope: ['chat:*:read', 'mesh:peer:send'], // required; [] grants nothing, ['*'] is "everything"
|
|
218
|
+
ttlSeconds: 3600, // default 1 h; the issuer and every verifier cap it at 24 h by default
|
|
219
|
+
});
|
|
220
|
+
const sig = await session.sign(message); // the session key signs traffic, the identity key is not touched
|
|
221
|
+
// ...send `certificate` (bytes, or encodeBase64url(certificate)) once, with a proof of possession:
|
|
222
|
+
const proof = await createSessionProof(session, challenge);
|
|
223
|
+
|
|
224
|
+
// verifier
|
|
225
|
+
const peer = await verifyPeerCredential(certificate, {
|
|
226
|
+
now: Date.now(), skewSeconds: 30, revocations: store,
|
|
227
|
+
expectedIdentity: knownPodId, requireScope: 'chat:room1:read', proof: { challenge, signature: proof },
|
|
228
|
+
});
|
|
229
|
+
// -> { identityKey, podId, sessionKey, scope, serial, notBefore, notAfter }; throws CredentialError otherwise
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
Rules: a certificate is valid during `[notBefore - skew, notAfter + skew)` in whole seconds (`skewSeconds` defaults to 30, at most 300); a verifier enforces its own `maxLifetimeSeconds` (default 86400) whatever the issuer chose; chain length is exactly one (a session key cannot issue certificates, and a list of certificates is refused); an empty scope grants nothing (the conservative choice: "all" has to be written as `'*'`); scope entries use the `namespace:resource:action` form of `matchScope`. A certificate proves the identity authorised that session key -- it does not prove the sender holds it, so also verify message signatures against `peer.sessionKey` (`verifyWithRawPublicKey`) or pass a `proof`. Pass `expectedIdentity` when you know whom you are talking to; otherwise the certificate only says "some identity key vouches for this session".
|
|
233
|
+
|
|
234
|
+
**Encoding** (so another implementation can match; test vectors are in `test/session.test.mjs`): `"BMSC" | u8 version=1 | field identityKey | field sessionKey | field serial(16) | u64 notBefore | u64 notAfter | u16 scopeCount | field scope... | field signature`, where `field` is a big-endian u16 length plus bytes and scopes are sorted bytewise and unique. The signature covers `"browsermesh/session-certificate/v1\n" + body`.
|
|
235
|
+
|
|
236
|
+
**Revocation.** The identity key signs `revokeSessionCertificate(identity, certificate)` (one session, by serial) or `retireIdentity(identity)` (the identity is done; all its certificates, past and future, are refused). Only the key a statement names can sign it, so a key can revoke only its own sessions and itself. Feed what arrives to a store:
|
|
237
|
+
|
|
238
|
+
```js
|
|
239
|
+
const store = new MemoryRevocationStore({ maxEntries: 10000, filter: (st) => iCareAbout(st.identityKey) });
|
|
240
|
+
store.onRevocation(({ bytes }) => broadcast(bytes)); // fires once per NEW revocation: forward these
|
|
241
|
+
const { status } = await receiveRevocation(bytes, store); // 'added' | 'duplicate' | 'ignored'; throws CredentialError if malformed or mis-signed
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
Revocations are idempotent and may arrive before the certificate. A certificate revocation is dropped once the certificate's own `notAfter` plus 300 s has passed; retirements are kept. The store is bounded: expired entries go first, then the revocation nearest expiry; if it holds only retirements and is full, `add` throws `store-full`. Because anyone can mint identities and sign statements for them, give the store a `filter` that admits only identities you care about on an open network. A store is any object with `add(statement, bytes)` and `isRevoked(identityKey, serial)` (sync or async); a store that throws makes verification fail closed.
|
|
245
|
+
|
|
246
|
+
**What this does and does not protect.** It limits the damage of a stolen session key to its lifetime and scope, and keeps the identity key off the hot path (so it can sit in a vault or token that prompts the user). Revocation only reaches peers that hear of it: a peer that is offline, partitioned or not forwarding keeps accepting the certificate until it expires, so keep lifetimes short and treat revocation as a way to shorten the tail, not an instant switch. It does not protect against theft of the identity key itself (retiring it needs the identity key, so a thief can race you; there is no recovery or key-rotation chain here), against a compromised page that can ask a signer to sign anything, or against a verifier with a wrong clock beyond the skew. Message signing, replay protection and channel binding remain the transport's job.
|
|
247
|
+
|
|
248
|
+
**Adoption by other layers.** A peer layer should send the certificate (and a challenge proof) when it introduces a session key, call `verifyPeerCredential(credential, { now, revocations, expectedIdentity })` before trusting any message signed by `sessionKey`, and wire `store.onRevocation` to its broadcast and a new-connection sync (`store.list()`). The wsh transport can use `PodIdentity.fromSigner` to wrap its signer, mint a session per connection with `createSession`, and verify the remote with `verifyPeerCredential`.
|
|
249
|
+
|
|
193
250
|
### Test Utilities
|
|
194
251
|
|
|
195
252
|
- `DeterministicRNG` -- seeded RNG for reproducible tests
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@johnhenry/browsermesh-primitives",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Shared primitives for browser mesh networking — wire format, identity (Ed25519), CRDTs, capabilities, trust model, and ACL engine",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.mjs",
|
package/src/identity.mjs
CHANGED
|
@@ -101,16 +101,208 @@ export async function derivePodId(publicKey) {
|
|
|
101
101
|
* @class
|
|
102
102
|
*/
|
|
103
103
|
export class PodIdentity {
|
|
104
|
+
/** @type {((data: BufferSource) => Uint8Array|Promise<Uint8Array>)|null} */
|
|
105
|
+
#signer = null;
|
|
106
|
+
|
|
107
|
+
/** @type {Uint8Array|null} */
|
|
108
|
+
#rawPublicKey = null;
|
|
109
|
+
|
|
104
110
|
/**
|
|
105
111
|
* @param {object} opts
|
|
106
|
-
* @param {CryptoKeyPair} opts.keyPair - Ed25519 key pair
|
|
112
|
+
* @param {CryptoKeyPair} opts.keyPair - Ed25519 key pair. For an identity
|
|
113
|
+
* backed by an external signer, `privateKey` is `null`.
|
|
107
114
|
* @param {string} opts.podId - Base64url-encoded public key hash
|
|
115
|
+
* @param {(data: BufferSource) => Uint8Array|Promise<Uint8Array>} [opts.signer]
|
|
116
|
+
* - Signing function for an identity whose private key this object does
|
|
117
|
+
* not hold. Prefer `PodIdentity.fromSigner()`, which validates it.
|
|
108
118
|
*/
|
|
109
|
-
constructor({ keyPair, podId }) {
|
|
119
|
+
constructor({ keyPair, podId, signer }) {
|
|
110
120
|
/** @type {CryptoKeyPair} */
|
|
111
121
|
this.keyPair = keyPair;
|
|
112
122
|
/** @type {string} */
|
|
113
123
|
this.podId = podId;
|
|
124
|
+
if (signer !== undefined && signer !== null) {
|
|
125
|
+
if (typeof signer !== 'function') throw new TypeError('PodIdentity: signer must be a function');
|
|
126
|
+
this.#signer = signer;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* True when the private key is a `CryptoKey` this page could export
|
|
132
|
+
* (`extractable: true`). False for a non-extractable key and for a signer
|
|
133
|
+
* identity, whose key this object never holds.
|
|
134
|
+
*
|
|
135
|
+
* @returns {boolean}
|
|
136
|
+
*/
|
|
137
|
+
get extractable() {
|
|
138
|
+
return !this.#signer && !!this.keyPair?.privateKey && this.keyPair.privateKey.extractable === true;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* True when signing goes to an external signer (vault, token, extension).
|
|
143
|
+
*
|
|
144
|
+
* @returns {boolean}
|
|
145
|
+
*/
|
|
146
|
+
get isExternalSigner() {
|
|
147
|
+
return this.#signer !== null;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* The raw 32-byte Ed25519 public key. Exports the PUBLIC key only (always
|
|
152
|
+
* allowed by WebCrypto); the result is cached.
|
|
153
|
+
*
|
|
154
|
+
* @returns {Promise<Uint8Array>}
|
|
155
|
+
*/
|
|
156
|
+
async rawPublicKey() {
|
|
157
|
+
if (!this.#rawPublicKey) {
|
|
158
|
+
this.#rawPublicKey = new Uint8Array(await crypto.subtle.exportKey('raw', this.keyPair.publicKey));
|
|
159
|
+
}
|
|
160
|
+
return new Uint8Array(this.#rawPublicKey);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Export the private key. Only for an identity created as exportable: a
|
|
165
|
+
* non-extractable key or an external signer rejects. Nothing else in this
|
|
166
|
+
* package calls `exportKey` on a private key.
|
|
167
|
+
*
|
|
168
|
+
* @param {'jwk'|'pkcs8'} [format='jwk']
|
|
169
|
+
* @returns {Promise<object|Uint8Array>}
|
|
170
|
+
*/
|
|
171
|
+
async exportPrivateKey(format = 'jwk') {
|
|
172
|
+
if (format !== 'jwk' && format !== 'pkcs8') throw new TypeError("PodIdentity.exportPrivateKey: format must be 'jwk' or 'pkcs8'");
|
|
173
|
+
if (!this.extractable) {
|
|
174
|
+
throw new Error('PodIdentity.exportPrivateKey: this identity is not exportable (non-extractable key or external signer)');
|
|
175
|
+
}
|
|
176
|
+
const out = await crypto.subtle.exportKey(format, this.keyPair.privateKey);
|
|
177
|
+
return format === 'pkcs8' ? new Uint8Array(out) : out;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Wrap an existing Ed25519 `CryptoKeyPair`, including one whose private key
|
|
182
|
+
* is non-extractable (for example loaded from IndexedDB or generated with
|
|
183
|
+
* `extractable: false`).
|
|
184
|
+
*
|
|
185
|
+
* @param {CryptoKeyPair} keyPair
|
|
186
|
+
* @returns {Promise<PodIdentity>}
|
|
187
|
+
*/
|
|
188
|
+
static async fromCryptoKeyPair(keyPair) {
|
|
189
|
+
if (!keyPair || !keyPair.publicKey || !keyPair.privateKey) {
|
|
190
|
+
throw new TypeError('PodIdentity.fromCryptoKeyPair: expected { publicKey, privateKey } CryptoKeys');
|
|
191
|
+
}
|
|
192
|
+
if (keyPair.publicKey.algorithm?.name !== 'Ed25519' || keyPair.privateKey.algorithm?.name !== 'Ed25519') {
|
|
193
|
+
throw new TypeError('PodIdentity.fromCryptoKeyPair: keys must be Ed25519');
|
|
194
|
+
}
|
|
195
|
+
const podId = await derivePodId(keyPair.publicKey);
|
|
196
|
+
return new PodIdentity({ keyPair, podId });
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Import a private key as JWK (the format `MeshIdentityManager.export()`
|
|
201
|
+
* produces). The public half comes from the JWK's `x`; the private key is
|
|
202
|
+
* non-extractable unless `extractable: true` is passed.
|
|
203
|
+
*
|
|
204
|
+
* @param {object} jwk - Ed25519 private JWK (`kty: 'OKP'`, `crv: 'Ed25519'`, `x`, `d`)
|
|
205
|
+
* @param {{ extractable?: boolean }} [opts]
|
|
206
|
+
* @returns {Promise<PodIdentity>}
|
|
207
|
+
*/
|
|
208
|
+
static async fromJwk(jwk, { extractable = false } = {}) {
|
|
209
|
+
if (!jwk || jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519' || typeof jwk.d !== 'string' || typeof jwk.x !== 'string') {
|
|
210
|
+
throw new TypeError('PodIdentity.fromJwk: expected an Ed25519 private JWK with x and d');
|
|
211
|
+
}
|
|
212
|
+
const privateKey = await crypto.subtle.importKey('jwk', { ...jwk, key_ops: ['sign'], ext: true }, { name: 'Ed25519' }, !!extractable, ['sign']);
|
|
213
|
+
const publicKey = await crypto.subtle.importKey(
|
|
214
|
+
'jwk',
|
|
215
|
+
{ kty: 'OKP', crv: 'Ed25519', x: jwk.x, key_ops: ['verify'], ext: true },
|
|
216
|
+
{ name: 'Ed25519' },
|
|
217
|
+
true,
|
|
218
|
+
['verify']
|
|
219
|
+
);
|
|
220
|
+
const identity = new PodIdentity({ keyPair: { publicKey, privateKey }, podId: await derivePodId(publicKey) });
|
|
221
|
+
await identity.#checkPair();
|
|
222
|
+
return identity;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Import a private key as PKCS#8. PKCS#8 does not carry the public key and
|
|
227
|
+
* WebCrypto cannot derive it from a non-extractable key, so pass it as
|
|
228
|
+
* `publicKey` (raw 32 bytes or a public `CryptoKey`). If you ask for
|
|
229
|
+
* `extractable: true` the public key may be omitted and is derived by
|
|
230
|
+
* exporting the key you handed over. The result is checked with one
|
|
231
|
+
* sign/verify round trip so a mismatched pair is rejected.
|
|
232
|
+
*
|
|
233
|
+
* @param {BufferSource} pkcs8
|
|
234
|
+
* @param {{ extractable?: boolean, publicKey?: Uint8Array|CryptoKey }} [opts]
|
|
235
|
+
* @returns {Promise<PodIdentity>}
|
|
236
|
+
*/
|
|
237
|
+
static async fromPkcs8(pkcs8, { extractable = false, publicKey } = {}) {
|
|
238
|
+
if (!publicKey && !extractable) {
|
|
239
|
+
throw new TypeError(
|
|
240
|
+
'PodIdentity.fromPkcs8: pass the public key (raw bytes or CryptoKey) for a non-extractable import, ' +
|
|
241
|
+
'or ask for extractable: true so it can be derived'
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
const privateKey = await crypto.subtle.importKey('pkcs8', pkcs8, { name: 'Ed25519' }, !!extractable, ['sign']);
|
|
245
|
+
let pub;
|
|
246
|
+
if (publicKey) {
|
|
247
|
+
pub = await importPublicKey(publicKey);
|
|
248
|
+
} else {
|
|
249
|
+
const jwk = await crypto.subtle.exportKey('jwk', privateKey);
|
|
250
|
+
pub = await crypto.subtle.importKey(
|
|
251
|
+
'jwk',
|
|
252
|
+
{ kty: 'OKP', crv: 'Ed25519', x: jwk.x, key_ops: ['verify'], ext: true },
|
|
253
|
+
{ name: 'Ed25519' },
|
|
254
|
+
true,
|
|
255
|
+
['verify']
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
const identity = new PodIdentity({ keyPair: { publicKey: pub, privateKey }, podId: await derivePodId(pub) });
|
|
259
|
+
await identity.#checkPair();
|
|
260
|
+
return identity;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* An identity whose private key lives elsewhere: a vault, a hardware token,
|
|
265
|
+
* an extension, a WebAuthn-like holder. Everything that signs goes through
|
|
266
|
+
* `signer.sign`.
|
|
267
|
+
*
|
|
268
|
+
* The signer shape is the one `@johnhenry/wsh` takes for "signing with a
|
|
269
|
+
* page-held signer" -- `{ publicKey, sign(data) }` with `publicKey` the raw
|
|
270
|
+
* 32-byte Ed25519 key or a public `CryptoKey`, and `sign` returning the
|
|
271
|
+
* 64-byte signature, sync or async -- so one signer object can serve both
|
|
272
|
+
* libraries.
|
|
273
|
+
*
|
|
274
|
+
* @param {{ publicKey: Uint8Array|CryptoKey, sign: (data: Uint8Array) => Uint8Array|Promise<Uint8Array> }} signer
|
|
275
|
+
* @param {{ check?: boolean }} [opts] - `check: true` makes one test signature at construction (one use of the signer) to confirm it matches `publicKey`
|
|
276
|
+
* @returns {Promise<PodIdentity>}
|
|
277
|
+
*/
|
|
278
|
+
static async fromSigner(signer, { check = false } = {}) {
|
|
279
|
+
if (!signer || typeof signer.sign !== 'function' || !signer.publicKey) {
|
|
280
|
+
throw new TypeError('PodIdentity.fromSigner: expected { publicKey, sign(data) }');
|
|
281
|
+
}
|
|
282
|
+
const publicKey = await importPublicKey(signer.publicKey);
|
|
283
|
+
const sign = async (data) => {
|
|
284
|
+
const sig = await signer.sign(toBytes(data));
|
|
285
|
+
const bytes = sig instanceof ArrayBuffer ? new Uint8Array(sig) : sig;
|
|
286
|
+
if (!(bytes instanceof Uint8Array) || bytes.length !== ED25519_SIGNATURE_BYTES) {
|
|
287
|
+
throw new TypeError('PodIdentity signer.sign must return a 64-byte Ed25519 signature');
|
|
288
|
+
}
|
|
289
|
+
return new Uint8Array(bytes);
|
|
290
|
+
};
|
|
291
|
+
const identity = new PodIdentity({
|
|
292
|
+
keyPair: { publicKey, privateKey: null },
|
|
293
|
+
podId: await derivePodId(publicKey),
|
|
294
|
+
signer: sign,
|
|
295
|
+
});
|
|
296
|
+
if (check) await identity.#checkPair();
|
|
297
|
+
return identity;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
async #checkPair() {
|
|
301
|
+
const probe = crypto.getRandomValues(new Uint8Array(32));
|
|
302
|
+
const sig = await this.sign(probe);
|
|
303
|
+
if (!(await crypto.subtle.verify('Ed25519', this.keyPair.publicKey, sig, probe))) {
|
|
304
|
+
throw new Error('PodIdentity: the private key does not match the public key');
|
|
305
|
+
}
|
|
114
306
|
}
|
|
115
307
|
|
|
116
308
|
/**
|
|
@@ -121,14 +313,18 @@ export class PodIdentity {
|
|
|
121
313
|
* message naming the requirement rather than a bare NotSupportedError.
|
|
122
314
|
* Use probeEd25519Support() to check first.
|
|
123
315
|
*
|
|
316
|
+
* The private key is extractable by default (existing behaviour); pass
|
|
317
|
+
* `{ extractable: false }` for a key this page can use but never read.
|
|
318
|
+
*
|
|
319
|
+
* @param {{ extractable?: boolean }} [opts]
|
|
124
320
|
* @returns {Promise<PodIdentity>}
|
|
125
321
|
*/
|
|
126
|
-
static async generate() {
|
|
322
|
+
static async generate({ extractable = true } = {}) {
|
|
127
323
|
let keyPair;
|
|
128
324
|
try {
|
|
129
325
|
keyPair = await crypto.subtle.generateKey(
|
|
130
326
|
{ name: 'Ed25519' },
|
|
131
|
-
|
|
327
|
+
!!extractable,
|
|
132
328
|
['sign', 'verify']
|
|
133
329
|
);
|
|
134
330
|
} catch (err) {
|
|
@@ -151,6 +347,8 @@ export class PodIdentity {
|
|
|
151
347
|
* @returns {Promise<Uint8Array>} Ed25519 signature
|
|
152
348
|
*/
|
|
153
349
|
async sign(data) {
|
|
350
|
+
// The one signing seam: an external signer or the CryptoKey, nothing else.
|
|
351
|
+
if (this.#signer) return this.#signer(data);
|
|
154
352
|
return new Uint8Array(
|
|
155
353
|
await crypto.subtle.sign('Ed25519', this.keyPair.privateKey, data)
|
|
156
354
|
);
|
|
@@ -189,6 +387,32 @@ export class PodIdentity {
|
|
|
189
387
|
|
|
190
388
|
const ED25519_SIGNATURE_BYTES = 64;
|
|
191
389
|
|
|
390
|
+
/**
|
|
391
|
+
* @param {BufferSource} v
|
|
392
|
+
* @returns {Uint8Array}
|
|
393
|
+
*/
|
|
394
|
+
function toBytes(v) {
|
|
395
|
+
if (v instanceof Uint8Array) return v;
|
|
396
|
+
if (ArrayBuffer.isView(v)) return new Uint8Array(v.buffer, v.byteOffset, v.byteLength);
|
|
397
|
+
return new Uint8Array(v);
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* Import an Ed25519 public key from raw bytes or accept a public CryptoKey.
|
|
402
|
+
* Only ever touches public keys.
|
|
403
|
+
*
|
|
404
|
+
* @param {Uint8Array|CryptoKey} key
|
|
405
|
+
* @returns {Promise<CryptoKey>}
|
|
406
|
+
*/
|
|
407
|
+
async function importPublicKey(key) {
|
|
408
|
+
if (key instanceof Uint8Array) {
|
|
409
|
+
if (key.length !== 32) throw new TypeError('Ed25519 public key must be 32 raw bytes');
|
|
410
|
+
return crypto.subtle.importKey('raw', key, { name: 'Ed25519' }, true, ['verify']);
|
|
411
|
+
}
|
|
412
|
+
if (key && typeof key === 'object' && key.type === 'public' && key.algorithm?.name === 'Ed25519') return key;
|
|
413
|
+
throw new TypeError('public key must be 32 raw bytes or a public Ed25519 CryptoKey');
|
|
414
|
+
}
|
|
415
|
+
|
|
192
416
|
/**
|
|
193
417
|
* @param {BufferSource} v
|
|
194
418
|
* @returns {number}
|
package/src/index.d.ts
CHANGED
|
@@ -37,11 +37,35 @@ export declare function supportsEd25519(): boolean | null;
|
|
|
37
37
|
/** Reset the cached Ed25519 probe. Tests only. */
|
|
38
38
|
export declare function _resetEd25519Probe(): void;
|
|
39
39
|
|
|
40
|
+
/**
|
|
41
|
+
* An external signer: `@johnhenry/wsh`'s "page-held signer" shape. `publicKey`
|
|
42
|
+
* is the raw 32-byte Ed25519 key or a public `CryptoKey`; `sign` returns the
|
|
43
|
+
* 64-byte signature, sync or async.
|
|
44
|
+
*/
|
|
45
|
+
export interface Ed25519Signer {
|
|
46
|
+
publicKey: Uint8Array | CryptoKey;
|
|
47
|
+
sign(data: Uint8Array): Uint8Array | Promise<Uint8Array>;
|
|
48
|
+
}
|
|
49
|
+
|
|
40
50
|
export declare class PodIdentity {
|
|
51
|
+
/** For a signer identity `privateKey` is `null`. */
|
|
41
52
|
keyPair: CryptoKeyPair;
|
|
42
53
|
podId: string;
|
|
43
|
-
constructor(opts: { keyPair: CryptoKeyPair; podId: string });
|
|
44
|
-
|
|
54
|
+
constructor(opts: { keyPair: CryptoKeyPair; podId: string; signer?: (data: BufferSource) => Uint8Array | Promise<Uint8Array> });
|
|
55
|
+
/** Private key is extractable by default; pass `{ extractable: false }` for a key this page cannot read. */
|
|
56
|
+
static generate(opts?: { extractable?: boolean }): Promise<PodIdentity>;
|
|
57
|
+
static fromCryptoKeyPair(keyPair: CryptoKeyPair): Promise<PodIdentity>;
|
|
58
|
+
static fromJwk(jwk: object, opts?: { extractable?: boolean }): Promise<PodIdentity>;
|
|
59
|
+
static fromPkcs8(pkcs8: BufferSource, opts?: { extractable?: boolean; publicKey?: Uint8Array | CryptoKey }): Promise<PodIdentity>;
|
|
60
|
+
static fromSigner(signer: Ed25519Signer, opts?: { check?: boolean }): Promise<PodIdentity>;
|
|
61
|
+
/** True when the private key is an extractable CryptoKey this object holds. */
|
|
62
|
+
readonly extractable: boolean;
|
|
63
|
+
/** True when signing goes to an external signer. */
|
|
64
|
+
readonly isExternalSigner: boolean;
|
|
65
|
+
/** Raw 32-byte public key (public key export only). */
|
|
66
|
+
rawPublicKey(): Promise<Uint8Array>;
|
|
67
|
+
/** Rejects unless the identity is exportable. */
|
|
68
|
+
exportPrivateKey(format?: 'jwk' | 'pkcs8'): Promise<object | Uint8Array>;
|
|
45
69
|
sign(data: BufferSource): Promise<Uint8Array>;
|
|
46
70
|
/**
|
|
47
71
|
* Argument order is (publicKey, signature, data), matching WebCrypto.
|
|
@@ -51,6 +75,112 @@ export declare class PodIdentity {
|
|
|
51
75
|
static verify(publicKey: CryptoKey, signature: BufferSource, data: BufferSource): Promise<boolean>;
|
|
52
76
|
}
|
|
53
77
|
|
|
78
|
+
// ---- Session certificates and signed revocation ----
|
|
79
|
+
|
|
80
|
+
export declare const CERT_VERSION: 1;
|
|
81
|
+
export declare const DEFAULT_MAX_LIFETIME_SECONDS: number;
|
|
82
|
+
export declare const DEFAULT_SKEW_SECONDS: number;
|
|
83
|
+
export declare const MAX_SKEW_SECONDS: number;
|
|
84
|
+
export declare const MAX_SCOPE_ENTRIES: number;
|
|
85
|
+
export declare const MAX_SCOPE_ENTRY_BYTES: number;
|
|
86
|
+
export declare const DEFAULT_REVOCATION_STORE_SIZE: number;
|
|
87
|
+
export declare const REVOCATION_KIND: Readonly<{ SESSION: 1; IDENTITY: 2 }>;
|
|
88
|
+
|
|
89
|
+
export declare class CredentialError extends Error {
|
|
90
|
+
/** malformed | unsupported-version | bad-signature | not-yet-valid | expired | invalid-lifetime | lifetime-too-long | chain-too-long | revoked | identity-retired | wrong-identity | scope-denied | bad-proof | bad-argument | store-full */
|
|
91
|
+
code: string;
|
|
92
|
+
constructor(code: string, message: string);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface SessionCertificateFields {
|
|
96
|
+
identityKey: Uint8Array;
|
|
97
|
+
sessionKey: Uint8Array;
|
|
98
|
+
serial: Uint8Array;
|
|
99
|
+
notBefore: number;
|
|
100
|
+
notAfter: number;
|
|
101
|
+
scope: string[];
|
|
102
|
+
}
|
|
103
|
+
export interface DecodedSessionCertificate extends SessionCertificateFields {
|
|
104
|
+
version: number;
|
|
105
|
+
signature: Uint8Array;
|
|
106
|
+
body: Uint8Array;
|
|
107
|
+
}
|
|
108
|
+
export interface IssuedSessionCertificate {
|
|
109
|
+
certificate: Uint8Array;
|
|
110
|
+
serial: string;
|
|
111
|
+
identityKey: Uint8Array;
|
|
112
|
+
sessionKey: Uint8Array;
|
|
113
|
+
scope: string[];
|
|
114
|
+
notBefore: number;
|
|
115
|
+
notAfter: number;
|
|
116
|
+
}
|
|
117
|
+
export interface IssueOptions {
|
|
118
|
+
scope: string[];
|
|
119
|
+
ttlSeconds?: number;
|
|
120
|
+
notBefore?: number;
|
|
121
|
+
notAfter?: number;
|
|
122
|
+
serial?: Uint8Array;
|
|
123
|
+
now?: number | Date;
|
|
124
|
+
maxLifetimeSeconds?: number;
|
|
125
|
+
}
|
|
126
|
+
export interface PeerCredential {
|
|
127
|
+
identityKey: Uint8Array;
|
|
128
|
+
podId: string;
|
|
129
|
+
sessionKey: Uint8Array;
|
|
130
|
+
scope: string[];
|
|
131
|
+
serial: string;
|
|
132
|
+
notBefore: number;
|
|
133
|
+
notAfter: number;
|
|
134
|
+
}
|
|
135
|
+
export interface RevocationStatement {
|
|
136
|
+
kind: number;
|
|
137
|
+
identityKey: Uint8Array;
|
|
138
|
+
serial: Uint8Array;
|
|
139
|
+
issuedAt: number;
|
|
140
|
+
retainUntil: number;
|
|
141
|
+
bytes: Uint8Array;
|
|
142
|
+
}
|
|
143
|
+
export interface RevocationStore {
|
|
144
|
+
add(statement: RevocationStatement, bytes: Uint8Array): boolean | 'ignored' | Promise<boolean | 'ignored'>;
|
|
145
|
+
isRevoked(identityKey: Uint8Array, serial: Uint8Array | null): boolean | Promise<boolean>;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export declare function verifyWithRawPublicKey(rawPublicKey: Uint8Array, signature: Uint8Array, data: BufferSource): Promise<boolean>;
|
|
149
|
+
export declare function podIdFromRawKey(rawPublicKey: Uint8Array): Promise<string>;
|
|
150
|
+
export declare function encodeSessionCertificateBody(c: SessionCertificateFields): Uint8Array;
|
|
151
|
+
export declare function decodeSessionCertificate(credential: Uint8Array | string): DecodedSessionCertificate;
|
|
152
|
+
export declare function issueSessionCertificate(identity: PodIdentity, opts: IssueOptions & { sessionPublicKey: Uint8Array | CryptoKey }): Promise<IssuedSessionCertificate>;
|
|
153
|
+
export declare function createSession(identity: PodIdentity, opts: IssueOptions): Promise<IssuedSessionCertificate & { session: PodIdentity }>;
|
|
154
|
+
export declare function createSessionProof(session: PodIdentity, challenge: Uint8Array): Promise<Uint8Array>;
|
|
155
|
+
export declare function scopeAllows(scope: string[], required: string): boolean;
|
|
156
|
+
export declare function verifyPeerCredential(
|
|
157
|
+
credential: Uint8Array | string | Array<Uint8Array | string>,
|
|
158
|
+
opts?: {
|
|
159
|
+
now?: number | Date;
|
|
160
|
+
skewSeconds?: number;
|
|
161
|
+
maxLifetimeSeconds?: number;
|
|
162
|
+
revocations?: RevocationStore;
|
|
163
|
+
expectedIdentity?: Uint8Array | string;
|
|
164
|
+
requireScope?: string;
|
|
165
|
+
proof?: { challenge: Uint8Array; signature: Uint8Array };
|
|
166
|
+
}
|
|
167
|
+
): Promise<PeerCredential>;
|
|
168
|
+
export declare function revokeSessionCertificate(identity: PodIdentity, certificate: Uint8Array | string, opts?: { now?: number | Date }): Promise<Uint8Array>;
|
|
169
|
+
export declare function retireIdentity(identity: PodIdentity, opts?: { now?: number | Date }): Promise<Uint8Array>;
|
|
170
|
+
export declare function verifyRevocation(bytes: Uint8Array | string): Promise<RevocationStatement>;
|
|
171
|
+
export declare function receiveRevocation(bytes: Uint8Array | string, store: RevocationStore): Promise<{ status: 'added' | 'duplicate' | 'ignored'; statement: RevocationStatement; bytes: Uint8Array }>;
|
|
172
|
+
export declare function isRevoked(subject: { identityKey: Uint8Array; serial?: Uint8Array | null }, store: RevocationStore): Promise<boolean>;
|
|
173
|
+
export declare class MemoryRevocationStore implements RevocationStore {
|
|
174
|
+
constructor(opts?: { maxEntries?: number; filter?: (statement: RevocationStatement) => boolean; clock?: () => number });
|
|
175
|
+
clock: () => number;
|
|
176
|
+
readonly size: number;
|
|
177
|
+
prune(now?: number | Date): number;
|
|
178
|
+
add(statement: RevocationStatement, bytes: Uint8Array): boolean | 'ignored';
|
|
179
|
+
isRevoked(identityKey: Uint8Array, serial: Uint8Array | null): boolean;
|
|
180
|
+
list(): Uint8Array[];
|
|
181
|
+
onRevocation(fn: (ev: { statement: RevocationStatement; bytes: Uint8Array }) => void): () => void;
|
|
182
|
+
}
|
|
183
|
+
|
|
54
184
|
export declare const messageTypeRegistry: Map<number, string>;
|
|
55
185
|
export declare function encodeMeshMessage(message: {
|
|
56
186
|
type: number;
|
|
@@ -381,3 +511,6 @@ export declare const PAD_TRAILER_BYTES: 4;
|
|
|
381
511
|
export declare function paddedLength(length: number, opts?: { buckets?: number[] }): number;
|
|
382
512
|
export declare function padTo(bytes: Uint8Array, opts?: { buckets?: number[] }): Uint8Array;
|
|
383
513
|
export declare function unpad(padded: Uint8Array): Uint8Array;
|
|
514
|
+
|
|
515
|
+
/** Parse a case-sensitive mesh:// or *.mesh.local address. */
|
|
516
|
+
export declare function parseMeshRequest(url: string): { podId: string; path: string } | null;
|
package/src/index.mjs
CHANGED
|
@@ -7,6 +7,34 @@ export { MeshError, MeshProtocolError, MeshCapabilityError } from "./errors.mjs"
|
|
|
7
7
|
// Identity
|
|
8
8
|
export { PodIdentity, derivePodId, encodeBase64url, decodeBase64url, supportsEd25519, probeEd25519Support, _resetEd25519Probe } from "./identity.mjs";
|
|
9
9
|
|
|
10
|
+
// Session certificates and signed revocation
|
|
11
|
+
export {
|
|
12
|
+
CERT_VERSION,
|
|
13
|
+
DEFAULT_MAX_LIFETIME_SECONDS,
|
|
14
|
+
DEFAULT_SKEW_SECONDS,
|
|
15
|
+
MAX_SKEW_SECONDS,
|
|
16
|
+
MAX_SCOPE_ENTRIES,
|
|
17
|
+
MAX_SCOPE_ENTRY_BYTES,
|
|
18
|
+
DEFAULT_REVOCATION_STORE_SIZE,
|
|
19
|
+
REVOCATION_KIND,
|
|
20
|
+
CredentialError,
|
|
21
|
+
verifyWithRawPublicKey,
|
|
22
|
+
podIdFromRawKey,
|
|
23
|
+
encodeSessionCertificateBody,
|
|
24
|
+
decodeSessionCertificate,
|
|
25
|
+
issueSessionCertificate,
|
|
26
|
+
createSession,
|
|
27
|
+
createSessionProof,
|
|
28
|
+
scopeAllows,
|
|
29
|
+
verifyPeerCredential,
|
|
30
|
+
revokeSessionCertificate,
|
|
31
|
+
retireIdentity,
|
|
32
|
+
verifyRevocation,
|
|
33
|
+
receiveRevocation,
|
|
34
|
+
isRevoked,
|
|
35
|
+
MemoryRevocationStore,
|
|
36
|
+
} from "./session.mjs";
|
|
37
|
+
|
|
10
38
|
// Wire format
|
|
11
39
|
export { messageTypeRegistry, encodeMeshMessage, decodeMeshMessage } from "./wire.mjs";
|
|
12
40
|
|
|
@@ -33,3 +61,6 @@ export {
|
|
|
33
61
|
|
|
34
62
|
// Size-bucket padding (relay-blind envelopes)
|
|
35
63
|
export { DEFAULT_PAD_BUCKETS, PAD_TRAILER_BYTES, paddedLength, padTo, unpad } from "./padding.mjs";
|
|
64
|
+
|
|
65
|
+
// Mesh addressing
|
|
66
|
+
export { parseMeshRequest } from './mesh-address.mjs';
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// Shared browser-safe mesh address parsing. Pod IDs are case sensitive.
|
|
2
|
+
const MESH_PROTOCOL = 'mesh://'
|
|
3
|
+
const MESH_LOCAL_SUFFIX = '.mesh.local'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Parse a mesh URL into { podId, path } or null.
|
|
7
|
+
* Supports:
|
|
8
|
+
* - mesh://podId/path
|
|
9
|
+
* - https://podId.mesh.local/path
|
|
10
|
+
* - http://podId.mesh.local/path
|
|
11
|
+
*
|
|
12
|
+
* @param {string} urlStr
|
|
13
|
+
* @returns {{ podId: string, path: string } | null}
|
|
14
|
+
*/
|
|
15
|
+
export function parseMeshRequest(urlStr) {
|
|
16
|
+
if (!urlStr || typeof urlStr !== 'string') return null
|
|
17
|
+
|
|
18
|
+
// --- mesh:// protocol ---
|
|
19
|
+
if (urlStr.startsWith(MESH_PROTOCOL)) {
|
|
20
|
+
const rest = urlStr.slice(MESH_PROTOCOL.length)
|
|
21
|
+
if (!rest) return null
|
|
22
|
+
|
|
23
|
+
const fragment = rest.indexOf('#')
|
|
24
|
+
const address = fragment < 0 ? rest : rest.slice(0, fragment)
|
|
25
|
+
const slashIdx = address.search(/[/?]/)
|
|
26
|
+
let podId, path
|
|
27
|
+
if (slashIdx === -1) {
|
|
28
|
+
podId = address
|
|
29
|
+
path = '/'
|
|
30
|
+
} else {
|
|
31
|
+
podId = address.slice(0, slashIdx)
|
|
32
|
+
path = address.slice(slashIdx) || '/'
|
|
33
|
+
if (path.startsWith('?')) path = '/' + path
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (!podId) return null
|
|
37
|
+
return { podId, path }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// --- https://podId.mesh.local/path or http://podId.mesh.local/path ---
|
|
41
|
+
// Extract hostname from the raw string to preserve case (URL() lowercases hostnames).
|
|
42
|
+
const httpMatch = urlStr.match(/^https?:\/\/([^/?#]+)([^#]*)/)
|
|
43
|
+
if (!httpMatch) return null
|
|
44
|
+
|
|
45
|
+
const rawHost = httpMatch[1] // preserves original case
|
|
46
|
+
const lowerHost = rawHost.toLowerCase()
|
|
47
|
+
if (!lowerHost.endsWith(MESH_LOCAL_SUFFIX)) return null
|
|
48
|
+
|
|
49
|
+
const podId = rawHost.slice(0, -MESH_LOCAL_SUFFIX.length)
|
|
50
|
+
if (!podId) return null
|
|
51
|
+
|
|
52
|
+
const suffix = httpMatch[2] || '/'
|
|
53
|
+
const path = suffix.startsWith('?') ? '/' + suffix : suffix
|
|
54
|
+
return { podId, path }
|
|
55
|
+
}
|
|
56
|
+
|
package/src/session.mjs
ADDED
|
@@ -0,0 +1,739 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session certificates and signed revocation.
|
|
3
|
+
*
|
|
4
|
+
* A long-lived identity key signs a short-lived SESSION key (a certificate with
|
|
5
|
+
* a scope and a validity window). The identity key is then used rarely -- once
|
|
6
|
+
* per session -- while the session key signs the traffic. A stolen session key
|
|
7
|
+
* stops working when its certificate expires, or sooner if the identity signs a
|
|
8
|
+
* REVOCATION that peers hear of.
|
|
9
|
+
*
|
|
10
|
+
* Rules, in one place:
|
|
11
|
+
*
|
|
12
|
+
* - Chain length is exactly one. A session key cannot issue certificates
|
|
13
|
+
* (`issueSessionCertificate` refuses a session identity) and a credential
|
|
14
|
+
* presented as a list of more than one certificate is refused.
|
|
15
|
+
* - Scope is a list of capability strings (the `namespace:resource:action`
|
|
16
|
+
* form `matchScope` understands, `*` per part). An EMPTY scope grants
|
|
17
|
+
* nothing: issuing refuses it, and `scopeAllows` is false for every request.
|
|
18
|
+
* "Everything the identity may" must be written out as `'*'`.
|
|
19
|
+
* - Time is whole seconds. A certificate is valid during
|
|
20
|
+
* `[notBefore - skew, notAfter + skew)`; `skewSeconds` defaults to 30 and is
|
|
21
|
+
* capped at 300. A verifier also enforces its OWN maximum lifetime
|
|
22
|
+
* (`maxLifetimeSeconds`, default 24 h) whatever the issuer chose.
|
|
23
|
+
* - A revocation is only ever valid when signed by the identity key it names,
|
|
24
|
+
* so a key can revoke its own sessions and retire itself, nothing else.
|
|
25
|
+
*
|
|
26
|
+
* Wire encodings (all integers big-endian; `field` = u16 length + bytes):
|
|
27
|
+
*
|
|
28
|
+
* certificate = "BMSC" | u8 version=1 | field identityKey(32) | field sessionKey(32)
|
|
29
|
+
* | field serial(16) | u64 notBefore | u64 notAfter
|
|
30
|
+
* | u16 scopeCount | field scope... (scopes sorted bytewise, unique)
|
|
31
|
+
* | field signature(64)
|
|
32
|
+
* revocation = "BMRV" | u8 version=1 | u8 kind (1 session, 2 identity)
|
|
33
|
+
* | field identityKey(32) | field serial (16, or empty for kind 2)
|
|
34
|
+
* | u64 issuedAt | u64 retainUntil (0 = forever) | field signature(64)
|
|
35
|
+
*
|
|
36
|
+
* The signature covers `domain + body` where `body` is everything before the
|
|
37
|
+
* signature field and `domain` is the ASCII string
|
|
38
|
+
* `browsermesh/session-certificate/v1\n` or `browsermesh/revocation/v1\n`, so
|
|
39
|
+
* a signature made for one purpose never verifies as another.
|
|
40
|
+
*/
|
|
41
|
+
|
|
42
|
+
import { PodIdentity, encodeBase64url, decodeBase64url } from './identity.mjs';
|
|
43
|
+
import { matchScope } from './capability.mjs';
|
|
44
|
+
|
|
45
|
+
export const CERT_VERSION = 1;
|
|
46
|
+
export const DEFAULT_MAX_LIFETIME_SECONDS = 86400;
|
|
47
|
+
export const DEFAULT_SKEW_SECONDS = 30;
|
|
48
|
+
export const MAX_SKEW_SECONDS = 300;
|
|
49
|
+
export const MAX_SCOPE_ENTRIES = 64;
|
|
50
|
+
export const MAX_SCOPE_ENTRY_BYTES = 256;
|
|
51
|
+
export const DEFAULT_REVOCATION_STORE_SIZE = 10000;
|
|
52
|
+
|
|
53
|
+
const CERT_MAGIC = [0x42, 0x4d, 0x53, 0x43]; // BMSC
|
|
54
|
+
const REV_MAGIC = [0x42, 0x4d, 0x52, 0x56]; // BMRV
|
|
55
|
+
const CERT_DOMAIN = 'browsermesh/session-certificate/v1\n';
|
|
56
|
+
const REV_DOMAIN = 'browsermesh/revocation/v1\n';
|
|
57
|
+
const PROOF_DOMAIN = 'browsermesh/session-proof/v1\n';
|
|
58
|
+
const KEY_BYTES = 32;
|
|
59
|
+
const SERIAL_BYTES = 16;
|
|
60
|
+
const SIG_BYTES = 64;
|
|
61
|
+
const MAX_U64 = (1n << 64n) - 1n;
|
|
62
|
+
|
|
63
|
+
/** Revocation kinds. */
|
|
64
|
+
export const REVOCATION_KIND = Object.freeze({ SESSION: 1, IDENTITY: 2 });
|
|
65
|
+
|
|
66
|
+
const enc = new TextEncoder();
|
|
67
|
+
const dec = new TextDecoder('utf-8', { fatal: true });
|
|
68
|
+
|
|
69
|
+
/** Error thrown for every refusal; `code` says why. */
|
|
70
|
+
export class CredentialError extends Error {
|
|
71
|
+
/**
|
|
72
|
+
* @param {string} code - malformed | unsupported-version | bad-signature | not-yet-valid | expired |
|
|
73
|
+
* invalid-lifetime | lifetime-too-long | chain-too-long | revoked | identity-retired |
|
|
74
|
+
* wrong-identity | scope-denied | bad-proof | bad-argument | store-full
|
|
75
|
+
* @param {string} message
|
|
76
|
+
*/
|
|
77
|
+
constructor(code, message) {
|
|
78
|
+
super(message);
|
|
79
|
+
this.name = 'CredentialError';
|
|
80
|
+
this.code = code;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Session identities created by `createSession`: they may not issue certificates. */
|
|
85
|
+
const sessionIdentities = new WeakSet();
|
|
86
|
+
|
|
87
|
+
// ---------------------------------------------------------------------------
|
|
88
|
+
// byte helpers
|
|
89
|
+
// ---------------------------------------------------------------------------
|
|
90
|
+
|
|
91
|
+
function concat(...parts) {
|
|
92
|
+
let n = 0;
|
|
93
|
+
for (const p of parts) n += p.length;
|
|
94
|
+
const out = new Uint8Array(n);
|
|
95
|
+
let o = 0;
|
|
96
|
+
for (const p of parts) { out.set(p, o); o += p.length; }
|
|
97
|
+
return out;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function u16(n) {
|
|
101
|
+
return new Uint8Array([(n >>> 8) & 0xff, n & 0xff]);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function u64(n) {
|
|
105
|
+
const out = new Uint8Array(8);
|
|
106
|
+
new DataView(out.buffer).setBigUint64(0, BigInt(n));
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function field(bytes) {
|
|
111
|
+
if (bytes.length > 0xffff) throw new CredentialError('bad-argument', 'field too long');
|
|
112
|
+
return concat(u16(bytes.length), bytes);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function bytesEqual(a, b) {
|
|
116
|
+
if (a.length !== b.length) return false;
|
|
117
|
+
let d = 0;
|
|
118
|
+
for (let i = 0; i < a.length; i++) d |= a[i] ^ b[i];
|
|
119
|
+
return d === 0;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function compareBytes(a, b) {
|
|
123
|
+
const n = Math.min(a.length, b.length);
|
|
124
|
+
for (let i = 0; i < n; i++) if (a[i] !== b[i]) return a[i] - b[i];
|
|
125
|
+
return a.length - b.length;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
class Reader {
|
|
129
|
+
constructor(bytes) { this.b = bytes; this.o = 0; }
|
|
130
|
+
take(n) {
|
|
131
|
+
if (this.o + n > this.b.length) throw new CredentialError('malformed', 'truncated');
|
|
132
|
+
const out = this.b.subarray(this.o, this.o + n);
|
|
133
|
+
this.o += n;
|
|
134
|
+
return out;
|
|
135
|
+
}
|
|
136
|
+
u8() { return this.take(1)[0]; }
|
|
137
|
+
u16() { const t = this.take(2); return (t[0] << 8) | t[1]; }
|
|
138
|
+
u64() {
|
|
139
|
+
const v = new DataView(this.b.buffer, this.b.byteOffset + this.o, 8).getBigUint64(0);
|
|
140
|
+
this.take(8);
|
|
141
|
+
if (v > BigInt(Number.MAX_SAFE_INTEGER)) throw new CredentialError('malformed', 'time out of range');
|
|
142
|
+
return Number(v);
|
|
143
|
+
}
|
|
144
|
+
field() { return this.take(this.u16()); }
|
|
145
|
+
done() { if (this.o !== this.b.length) throw new CredentialError('malformed', 'trailing bytes'); }
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function toBytes(v, what) {
|
|
149
|
+
if (v instanceof Uint8Array) return v;
|
|
150
|
+
if (typeof v === 'string') {
|
|
151
|
+
try { return decodeBase64url(v); } catch { throw new CredentialError('malformed', `${what} is not valid base64url`); }
|
|
152
|
+
}
|
|
153
|
+
throw new CredentialError('bad-argument', `${what} must be bytes or a base64url string`);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async function importRawPublic(raw) {
|
|
157
|
+
return crypto.subtle.importKey('raw', raw, { name: 'Ed25519' }, true, ['verify']);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Verify an Ed25519 signature against a RAW 32-byte public key. Resolves false
|
|
162
|
+
* (never throws) for a bad key, a bad length or a bad signature.
|
|
163
|
+
*
|
|
164
|
+
* @param {Uint8Array} rawPublicKey
|
|
165
|
+
* @param {Uint8Array} signature
|
|
166
|
+
* @param {BufferSource} data
|
|
167
|
+
* @returns {Promise<boolean>}
|
|
168
|
+
*/
|
|
169
|
+
export async function verifyWithRawPublicKey(rawPublicKey, signature, data) {
|
|
170
|
+
try {
|
|
171
|
+
if (rawPublicKey.length !== KEY_BYTES || signature.length !== SIG_BYTES) return false;
|
|
172
|
+
return await crypto.subtle.verify('Ed25519', await importRawPublic(rawPublicKey), signature, data);
|
|
173
|
+
} catch {
|
|
174
|
+
return false;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Pod id (base64url SHA-256) of a raw public key; equals `derivePodId`.
|
|
180
|
+
*
|
|
181
|
+
* @param {Uint8Array} rawPublicKey
|
|
182
|
+
* @returns {Promise<string>}
|
|
183
|
+
*/
|
|
184
|
+
export async function podIdFromRawKey(rawPublicKey) {
|
|
185
|
+
return encodeBase64url(new Uint8Array(await crypto.subtle.digest('SHA-256', rawPublicKey)));
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function nowSeconds(now) {
|
|
189
|
+
const ms = now instanceof Date ? now.getTime() : now === undefined ? Date.now() : now;
|
|
190
|
+
if (typeof ms !== 'number' || !Number.isFinite(ms)) throw new CredentialError('bad-argument', 'now must be a finite number of milliseconds or a Date');
|
|
191
|
+
return Math.floor(ms / 1000);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function skewOf(opts) {
|
|
195
|
+
const s = opts.skewSeconds ?? DEFAULT_SKEW_SECONDS;
|
|
196
|
+
if (!Number.isInteger(s) || s < 0 || s > MAX_SKEW_SECONDS) {
|
|
197
|
+
throw new CredentialError('bad-argument', `skewSeconds must be an integer from 0 to ${MAX_SKEW_SECONDS}`);
|
|
198
|
+
}
|
|
199
|
+
return s;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function maxLifetimeOf(opts) {
|
|
203
|
+
const m = opts.maxLifetimeSeconds ?? DEFAULT_MAX_LIFETIME_SECONDS;
|
|
204
|
+
if (!Number.isInteger(m) || m < 1) throw new CredentialError('bad-argument', 'maxLifetimeSeconds must be a positive integer');
|
|
205
|
+
return m;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// ---------------------------------------------------------------------------
|
|
209
|
+
// certificate encoding
|
|
210
|
+
// ---------------------------------------------------------------------------
|
|
211
|
+
|
|
212
|
+
function normalizeScope(scope) {
|
|
213
|
+
if (!Array.isArray(scope)) throw new CredentialError('bad-argument', 'scope must be an array of strings');
|
|
214
|
+
const entries = scope.map((s) => {
|
|
215
|
+
if (typeof s !== 'string' || s.length === 0) throw new CredentialError('bad-argument', 'scope entries must be non-empty strings');
|
|
216
|
+
const b = enc.encode(s);
|
|
217
|
+
if (b.length > MAX_SCOPE_ENTRY_BYTES) throw new CredentialError('bad-argument', 'scope entry too long');
|
|
218
|
+
return b;
|
|
219
|
+
});
|
|
220
|
+
entries.sort(compareBytes);
|
|
221
|
+
const unique = entries.filter((e, i) => i === 0 || compareBytes(entries[i - 1], e) !== 0);
|
|
222
|
+
if (unique.length > MAX_SCOPE_ENTRIES) throw new CredentialError('bad-argument', 'too many scope entries');
|
|
223
|
+
return unique;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Canonical body of a certificate (everything the signature covers, minus the
|
|
228
|
+
* domain prefix). Exposed so another implementation can be checked against the
|
|
229
|
+
* test vectors.
|
|
230
|
+
*
|
|
231
|
+
* @param {{ identityKey: Uint8Array, sessionKey: Uint8Array, serial: Uint8Array, notBefore: number, notAfter: number, scope: string[] }} c
|
|
232
|
+
* @returns {Uint8Array}
|
|
233
|
+
*/
|
|
234
|
+
export function encodeSessionCertificateBody(c) {
|
|
235
|
+
if (c.identityKey.length !== KEY_BYTES || c.sessionKey.length !== KEY_BYTES) throw new CredentialError('bad-argument', 'keys must be 32 bytes');
|
|
236
|
+
if (c.serial.length !== SERIAL_BYTES) throw new CredentialError('bad-argument', 'serial must be 16 bytes');
|
|
237
|
+
for (const t of [c.notBefore, c.notAfter]) {
|
|
238
|
+
if (!Number.isSafeInteger(t) || t < 0) throw new CredentialError('bad-argument', 'times must be non-negative integer seconds');
|
|
239
|
+
}
|
|
240
|
+
const scope = normalizeScope(c.scope);
|
|
241
|
+
return concat(
|
|
242
|
+
new Uint8Array(CERT_MAGIC),
|
|
243
|
+
new Uint8Array([CERT_VERSION]),
|
|
244
|
+
field(c.identityKey),
|
|
245
|
+
field(c.sessionKey),
|
|
246
|
+
field(c.serial),
|
|
247
|
+
u64(c.notBefore),
|
|
248
|
+
u64(c.notAfter),
|
|
249
|
+
u16(scope.length),
|
|
250
|
+
...scope.map(field)
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function certSigningInput(body) {
|
|
255
|
+
return concat(enc.encode(CERT_DOMAIN), body);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Parse certificate bytes WITHOUT checking the signature or the time. Strict:
|
|
260
|
+
* unknown version, non-canonical scope order, wrong lengths and trailing bytes
|
|
261
|
+
* are all refused. Use `verifyPeerCredential` to decide whether to trust it.
|
|
262
|
+
*
|
|
263
|
+
* @param {Uint8Array|string} credential - bytes or base64url
|
|
264
|
+
* @returns {{ version: number, identityKey: Uint8Array, sessionKey: Uint8Array, serial: Uint8Array, notBefore: number, notAfter: number, scope: string[], signature: Uint8Array, body: Uint8Array }}
|
|
265
|
+
*/
|
|
266
|
+
export function decodeSessionCertificate(credential) {
|
|
267
|
+
const bytes = toBytes(credential, 'certificate');
|
|
268
|
+
const r = new Reader(bytes);
|
|
269
|
+
const magic = r.take(4);
|
|
270
|
+
if (!bytesEqual(magic, new Uint8Array(CERT_MAGIC))) throw new CredentialError('malformed', 'not a session certificate');
|
|
271
|
+
const version = r.u8();
|
|
272
|
+
if (version !== CERT_VERSION) throw new CredentialError('unsupported-version', `unsupported certificate version ${version}`);
|
|
273
|
+
const identityKey = r.field();
|
|
274
|
+
const sessionKey = r.field();
|
|
275
|
+
const serial = r.field();
|
|
276
|
+
if (identityKey.length !== KEY_BYTES || sessionKey.length !== KEY_BYTES || serial.length !== SERIAL_BYTES) {
|
|
277
|
+
throw new CredentialError('malformed', 'bad key or serial length');
|
|
278
|
+
}
|
|
279
|
+
const notBefore = r.u64();
|
|
280
|
+
const notAfter = r.u64();
|
|
281
|
+
const count = r.u16();
|
|
282
|
+
if (count > MAX_SCOPE_ENTRIES) throw new CredentialError('malformed', 'too many scope entries');
|
|
283
|
+
const raw = [];
|
|
284
|
+
for (let i = 0; i < count; i++) {
|
|
285
|
+
const f = r.field();
|
|
286
|
+
if (f.length === 0 || f.length > MAX_SCOPE_ENTRY_BYTES) throw new CredentialError('malformed', 'bad scope entry');
|
|
287
|
+
if (i > 0 && compareBytes(raw[i - 1], f) >= 0) throw new CredentialError('malformed', 'scope is not sorted and unique');
|
|
288
|
+
raw.push(f);
|
|
289
|
+
}
|
|
290
|
+
const body = bytes.subarray(0, r.o);
|
|
291
|
+
const signature = r.field();
|
|
292
|
+
if (signature.length !== SIG_BYTES) throw new CredentialError('malformed', 'bad signature length');
|
|
293
|
+
r.done();
|
|
294
|
+
let scope;
|
|
295
|
+
try { scope = raw.map((f) => dec.decode(f)); } catch { throw new CredentialError('malformed', 'scope is not UTF-8'); }
|
|
296
|
+
return {
|
|
297
|
+
version,
|
|
298
|
+
identityKey: new Uint8Array(identityKey),
|
|
299
|
+
sessionKey: new Uint8Array(sessionKey),
|
|
300
|
+
serial: new Uint8Array(serial),
|
|
301
|
+
notBefore,
|
|
302
|
+
notAfter,
|
|
303
|
+
scope,
|
|
304
|
+
signature: new Uint8Array(signature),
|
|
305
|
+
body: new Uint8Array(body),
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// ---------------------------------------------------------------------------
|
|
310
|
+
// issuing
|
|
311
|
+
// ---------------------------------------------------------------------------
|
|
312
|
+
|
|
313
|
+
async function publicKeyBytes(k) {
|
|
314
|
+
if (k instanceof Uint8Array) return new Uint8Array(k);
|
|
315
|
+
if (k && k.type === 'public') return new Uint8Array(await crypto.subtle.exportKey('raw', k));
|
|
316
|
+
throw new CredentialError('bad-argument', 'sessionPublicKey must be 32 raw bytes or a public CryptoKey');
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* Sign a certificate for `sessionPublicKey` with the identity key. This is the
|
|
321
|
+
* ONE use of the identity key per session.
|
|
322
|
+
*
|
|
323
|
+
* @param {PodIdentity} identity - Long-lived identity (key, non-extractable key or external signer)
|
|
324
|
+
* @param {object} opts
|
|
325
|
+
* @param {Uint8Array|CryptoKey} opts.sessionPublicKey
|
|
326
|
+
* @param {string[]} opts.scope - Non-empty list of capability strings; use `['*']` for everything
|
|
327
|
+
* @param {number} [opts.ttlSeconds=3600] - Used when `notAfter` is not given
|
|
328
|
+
* @param {number} [opts.notBefore] - Seconds; default now
|
|
329
|
+
* @param {number} [opts.notAfter] - Seconds
|
|
330
|
+
* @param {Uint8Array} [opts.serial] - 16 bytes; default random
|
|
331
|
+
* @param {number|Date} [opts.now] - Milliseconds; default `Date.now()`
|
|
332
|
+
* @param {number} [opts.maxLifetimeSeconds=86400]
|
|
333
|
+
* @returns {Promise<{ certificate: Uint8Array, serial: string, identityKey: Uint8Array, sessionKey: Uint8Array, scope: string[], notBefore: number, notAfter: number }>}
|
|
334
|
+
*/
|
|
335
|
+
export async function issueSessionCertificate(identity, opts) {
|
|
336
|
+
if (!identity || typeof identity.sign !== 'function' || typeof identity.rawPublicKey !== 'function') {
|
|
337
|
+
throw new CredentialError('bad-argument', 'identity must be a PodIdentity');
|
|
338
|
+
}
|
|
339
|
+
if (sessionIdentities.has(identity)) {
|
|
340
|
+
throw new CredentialError('chain-too-long', 'a session key cannot issue certificates (chain length is exactly one)');
|
|
341
|
+
}
|
|
342
|
+
const scope = Array.isArray(opts.scope) ? opts.scope : null;
|
|
343
|
+
if (!scope || scope.length === 0) {
|
|
344
|
+
throw new CredentialError('bad-argument', "scope must list at least one capability; an empty scope grants nothing (use ['*'] for everything)");
|
|
345
|
+
}
|
|
346
|
+
const now = nowSeconds(opts.now);
|
|
347
|
+
const notBefore = opts.notBefore ?? now;
|
|
348
|
+
const notAfter = opts.notAfter ?? notBefore + (opts.ttlSeconds ?? 3600);
|
|
349
|
+
if (!Number.isSafeInteger(notBefore) || !Number.isSafeInteger(notAfter) || notAfter <= notBefore) {
|
|
350
|
+
throw new CredentialError('invalid-lifetime', 'notAfter must be after notBefore');
|
|
351
|
+
}
|
|
352
|
+
const max = maxLifetimeOf(opts);
|
|
353
|
+
if (notAfter - notBefore > max) {
|
|
354
|
+
throw new CredentialError('lifetime-too-long', `lifetime ${notAfter - notBefore}s exceeds the maximum ${max}s`);
|
|
355
|
+
}
|
|
356
|
+
const serial = opts.serial ?? crypto.getRandomValues(new Uint8Array(SERIAL_BYTES));
|
|
357
|
+
const identityKey = await identity.rawPublicKey();
|
|
358
|
+
const sessionKey = await publicKeyBytes(opts.sessionPublicKey);
|
|
359
|
+
const body = encodeSessionCertificateBody({ identityKey, sessionKey, serial, notBefore, notAfter, scope });
|
|
360
|
+
const signature = await identity.sign(certSigningInput(body));
|
|
361
|
+
if (signature.length !== SIG_BYTES) throw new CredentialError('bad-argument', 'signer returned a bad signature');
|
|
362
|
+
const certificate = concat(body, field(signature));
|
|
363
|
+
return {
|
|
364
|
+
certificate,
|
|
365
|
+
serial: encodeBase64url(serial),
|
|
366
|
+
identityKey,
|
|
367
|
+
sessionKey,
|
|
368
|
+
scope: decodeSessionCertificate(certificate).scope,
|
|
369
|
+
notBefore,
|
|
370
|
+
notAfter,
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Create a fresh NON-EXTRACTABLE session key and have the identity certify it
|
|
376
|
+
* (one identity signature). The returned `session` is a `PodIdentity` for
|
|
377
|
+
* signing traffic; it cannot issue certificates.
|
|
378
|
+
*
|
|
379
|
+
* @param {PodIdentity} identity
|
|
380
|
+
* @param {Parameters<typeof issueSessionCertificate>[1] extends infer O ? Omit<O & object, 'sessionPublicKey'> : never} opts
|
|
381
|
+
* @returns {Promise<{ session: PodIdentity, certificate: Uint8Array, serial: string, identityKey: Uint8Array, sessionKey: Uint8Array, scope: string[], notBefore: number, notAfter: number }>}
|
|
382
|
+
*/
|
|
383
|
+
export async function createSession(identity, opts) {
|
|
384
|
+
const session = await PodIdentity.generate({ extractable: false });
|
|
385
|
+
const issued = await issueSessionCertificate(identity, { ...opts, sessionPublicKey: await session.rawPublicKey() });
|
|
386
|
+
sessionIdentities.add(session);
|
|
387
|
+
return { session, ...issued };
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Sign a challenge with the session key to show possession (a certificate
|
|
392
|
+
* alone only says the identity authorised that key; anyone can replay it).
|
|
393
|
+
*
|
|
394
|
+
* @param {PodIdentity} session
|
|
395
|
+
* @param {Uint8Array} challenge
|
|
396
|
+
* @returns {Promise<Uint8Array>}
|
|
397
|
+
*/
|
|
398
|
+
export async function createSessionProof(session, challenge) {
|
|
399
|
+
return session.sign(concat(enc.encode(PROOF_DOMAIN), await session.rawPublicKey(), challenge));
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// ---------------------------------------------------------------------------
|
|
403
|
+
// verifying
|
|
404
|
+
// ---------------------------------------------------------------------------
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* Whether `scope` (what a certificate grants) covers `required`. An empty
|
|
408
|
+
* scope covers nothing; `'*'` covers everything; otherwise `matchScope` rules
|
|
409
|
+
* apply (`namespace:resource:action`, `*` per part).
|
|
410
|
+
*
|
|
411
|
+
* @param {string[]} scope
|
|
412
|
+
* @param {string} required
|
|
413
|
+
* @returns {boolean}
|
|
414
|
+
*/
|
|
415
|
+
export function scopeAllows(scope, required) {
|
|
416
|
+
if (typeof required !== 'string' || required.length === 0) return false;
|
|
417
|
+
return scope.some((granted) => granted === '*' || granted === required || matchScope(granted, required));
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* Check a peer's credential and return who it speaks for.
|
|
422
|
+
*
|
|
423
|
+
* Refusals throw `CredentialError` with a `code`. Checks, in order: the
|
|
424
|
+
* credential is exactly one certificate; encoding; the identity's signature;
|
|
425
|
+
* lifetime sanity and the verifier's maximum; the validity window with skew;
|
|
426
|
+
* `expectedIdentity`; revocation (store errors fail closed); `requireScope`;
|
|
427
|
+
* `proof`.
|
|
428
|
+
*
|
|
429
|
+
* Verifying the certificate does NOT verify messages: the caller still checks
|
|
430
|
+
* message signatures against the returned `sessionKey` (see
|
|
431
|
+
* `verifyWithRawPublicKey`), or passes a `proof`.
|
|
432
|
+
*
|
|
433
|
+
* @param {Uint8Array|string|Uint8Array[]} credential
|
|
434
|
+
* @param {object} [opts]
|
|
435
|
+
* @param {number|Date} [opts.now] - Milliseconds; default `Date.now()`
|
|
436
|
+
* @param {number} [opts.skewSeconds=30] - 0..300
|
|
437
|
+
* @param {number} [opts.maxLifetimeSeconds=86400]
|
|
438
|
+
* @param {RevocationStore} [opts.revocations]
|
|
439
|
+
* @param {Uint8Array|string} [opts.expectedIdentity] - Raw identity key, or its pod id
|
|
440
|
+
* @param {string} [opts.requireScope] - The certificate must cover this
|
|
441
|
+
* @param {{ challenge: Uint8Array, signature: Uint8Array }} [opts.proof]
|
|
442
|
+
* @returns {Promise<{ identityKey: Uint8Array, podId: string, sessionKey: Uint8Array, scope: string[], serial: string, notBefore: number, notAfter: number }>}
|
|
443
|
+
*/
|
|
444
|
+
export async function verifyPeerCredential(credential, opts = {}) {
|
|
445
|
+
if (Array.isArray(credential)) {
|
|
446
|
+
if (credential.length !== 1) throw new CredentialError('chain-too-long', 'a credential is exactly one certificate (no delegation from a session key)');
|
|
447
|
+
credential = credential[0];
|
|
448
|
+
}
|
|
449
|
+
const skew = skewOf(opts);
|
|
450
|
+
const max = maxLifetimeOf(opts);
|
|
451
|
+
const now = nowSeconds(opts.now);
|
|
452
|
+
const cert = decodeSessionCertificate(credential);
|
|
453
|
+
|
|
454
|
+
if (!(await verifyWithRawPublicKey(cert.identityKey, cert.signature, certSigningInput(cert.body)))) {
|
|
455
|
+
throw new CredentialError('bad-signature', 'the certificate is not signed by its identity key');
|
|
456
|
+
}
|
|
457
|
+
if (cert.notAfter <= cert.notBefore) throw new CredentialError('invalid-lifetime', 'notAfter is not after notBefore');
|
|
458
|
+
if (cert.notAfter - cert.notBefore > max) {
|
|
459
|
+
throw new CredentialError('lifetime-too-long', `lifetime ${cert.notAfter - cert.notBefore}s exceeds the maximum ${max}s`);
|
|
460
|
+
}
|
|
461
|
+
if (now < cert.notBefore - skew) throw new CredentialError('not-yet-valid', 'the certificate is not valid yet');
|
|
462
|
+
if (now >= cert.notAfter + skew) throw new CredentialError('expired', 'the certificate has expired');
|
|
463
|
+
|
|
464
|
+
const podId = await podIdFromRawKey(cert.identityKey);
|
|
465
|
+
if (opts.expectedIdentity !== undefined) {
|
|
466
|
+
const e = opts.expectedIdentity;
|
|
467
|
+
const ok = typeof e === 'string' ? e === podId : e instanceof Uint8Array && bytesEqual(e, cert.identityKey);
|
|
468
|
+
if (!ok) throw new CredentialError('wrong-identity', 'the certificate speaks for a different identity');
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
if (opts.revocations) {
|
|
472
|
+
let revoked;
|
|
473
|
+
try {
|
|
474
|
+
revoked = await opts.revocations.isRevoked(cert.identityKey, cert.serial);
|
|
475
|
+
} catch (err) {
|
|
476
|
+
throw new CredentialError('revoked', `revocation store failed, refusing: ${err?.message ?? err}`);
|
|
477
|
+
}
|
|
478
|
+
if (revoked) throw new CredentialError('revoked', 'the certificate or its identity has been revoked');
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
if (opts.requireScope !== undefined && !scopeAllows(cert.scope, opts.requireScope)) {
|
|
482
|
+
throw new CredentialError('scope-denied', `the certificate does not cover ${opts.requireScope}`);
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
if (opts.proof) {
|
|
486
|
+
const ok = await verifyWithRawPublicKey(
|
|
487
|
+
cert.sessionKey,
|
|
488
|
+
opts.proof.signature,
|
|
489
|
+
concat(enc.encode(PROOF_DOMAIN), cert.sessionKey, opts.proof.challenge)
|
|
490
|
+
);
|
|
491
|
+
if (!ok) throw new CredentialError('bad-proof', 'the proof was not signed by the session key');
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
return {
|
|
495
|
+
identityKey: cert.identityKey,
|
|
496
|
+
podId,
|
|
497
|
+
sessionKey: cert.sessionKey,
|
|
498
|
+
scope: cert.scope,
|
|
499
|
+
serial: encodeBase64url(cert.serial),
|
|
500
|
+
notBefore: cert.notBefore,
|
|
501
|
+
notAfter: cert.notAfter,
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
// ---------------------------------------------------------------------------
|
|
506
|
+
// revocation
|
|
507
|
+
// ---------------------------------------------------------------------------
|
|
508
|
+
|
|
509
|
+
function encodeRevocationBody({ kind, identityKey, serial, issuedAt, retainUntil }) {
|
|
510
|
+
return concat(
|
|
511
|
+
new Uint8Array(REV_MAGIC),
|
|
512
|
+
new Uint8Array([CERT_VERSION, kind]),
|
|
513
|
+
field(identityKey),
|
|
514
|
+
field(serial),
|
|
515
|
+
u64(issuedAt),
|
|
516
|
+
u64(retainUntil)
|
|
517
|
+
);
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
function revSigningInput(body) {
|
|
521
|
+
return concat(enc.encode(REV_DOMAIN), body);
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* Sign a revocation of one session certificate. Only the identity that issued
|
|
526
|
+
* it can: pass the certificate (bytes) and the same identity.
|
|
527
|
+
*
|
|
528
|
+
* @param {PodIdentity} identity
|
|
529
|
+
* @param {Uint8Array|string} certificate
|
|
530
|
+
* @param {{ now?: number|Date }} [opts]
|
|
531
|
+
* @returns {Promise<Uint8Array>} Revocation bytes, ready to forward
|
|
532
|
+
*/
|
|
533
|
+
export async function revokeSessionCertificate(identity, certificate, opts = {}) {
|
|
534
|
+
const cert = decodeSessionCertificate(certificate);
|
|
535
|
+
const identityKey = await identity.rawPublicKey();
|
|
536
|
+
if (!bytesEqual(identityKey, cert.identityKey)) {
|
|
537
|
+
throw new CredentialError('wrong-identity', 'only the identity that issued a certificate can revoke it');
|
|
538
|
+
}
|
|
539
|
+
return signRevocation(identity, identityKey, REVOCATION_KIND.SESSION, cert.serial, nowSeconds(opts.now), cert.notAfter);
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* Sign the identity's retirement: every certificate it ever issued, and any it
|
|
544
|
+
* would issue later, is to be refused. Kept by stores until pruned by size.
|
|
545
|
+
*
|
|
546
|
+
* @param {PodIdentity} identity
|
|
547
|
+
* @param {{ now?: number|Date }} [opts]
|
|
548
|
+
* @returns {Promise<Uint8Array>}
|
|
549
|
+
*/
|
|
550
|
+
export async function retireIdentity(identity, opts = {}) {
|
|
551
|
+
const identityKey = await identity.rawPublicKey();
|
|
552
|
+
return signRevocation(identity, identityKey, REVOCATION_KIND.IDENTITY, new Uint8Array(0), nowSeconds(opts.now), 0);
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
async function signRevocation(identity, identityKey, kind, serial, issuedAt, retainUntil) {
|
|
556
|
+
const body = encodeRevocationBody({ kind, identityKey, serial, issuedAt, retainUntil });
|
|
557
|
+
const signature = await identity.sign(revSigningInput(body));
|
|
558
|
+
return concat(body, field(signature));
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/**
|
|
562
|
+
* Parse and verify a revocation. It is valid only if signed by the identity
|
|
563
|
+
* key it names. Throws `CredentialError` otherwise.
|
|
564
|
+
*
|
|
565
|
+
* @param {Uint8Array|string} bytes
|
|
566
|
+
* @returns {Promise<{ kind: number, identityKey: Uint8Array, serial: Uint8Array, issuedAt: number, retainUntil: number, bytes: Uint8Array }>}
|
|
567
|
+
*/
|
|
568
|
+
export async function verifyRevocation(bytes) {
|
|
569
|
+
const raw = toBytes(bytes, 'revocation');
|
|
570
|
+
const r = new Reader(raw);
|
|
571
|
+
if (!bytesEqual(r.take(4), new Uint8Array(REV_MAGIC))) throw new CredentialError('malformed', 'not a revocation');
|
|
572
|
+
const version = r.u8();
|
|
573
|
+
if (version !== CERT_VERSION) throw new CredentialError('unsupported-version', `unsupported revocation version ${version}`);
|
|
574
|
+
const kind = r.u8();
|
|
575
|
+
if (kind !== REVOCATION_KIND.SESSION && kind !== REVOCATION_KIND.IDENTITY) throw new CredentialError('malformed', 'unknown revocation kind');
|
|
576
|
+
const identityKey = r.field();
|
|
577
|
+
const serial = r.field();
|
|
578
|
+
if (identityKey.length !== KEY_BYTES) throw new CredentialError('malformed', 'bad key length');
|
|
579
|
+
if (kind === REVOCATION_KIND.SESSION ? serial.length !== SERIAL_BYTES : serial.length !== 0) throw new CredentialError('malformed', 'bad serial length');
|
|
580
|
+
const issuedAt = r.u64();
|
|
581
|
+
const retainUntil = r.u64();
|
|
582
|
+
const body = raw.subarray(0, r.o);
|
|
583
|
+
const signature = r.field();
|
|
584
|
+
r.done();
|
|
585
|
+
if (!(await verifyWithRawPublicKey(identityKey, signature, revSigningInput(body)))) {
|
|
586
|
+
throw new CredentialError('bad-signature', 'the revocation is not signed by the identity it names');
|
|
587
|
+
}
|
|
588
|
+
return {
|
|
589
|
+
kind,
|
|
590
|
+
identityKey: new Uint8Array(identityKey),
|
|
591
|
+
serial: new Uint8Array(serial),
|
|
592
|
+
issuedAt,
|
|
593
|
+
retainUntil,
|
|
594
|
+
bytes: new Uint8Array(raw),
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* @typedef {object} RevocationStore
|
|
600
|
+
* @property {(statement: object, bytes: Uint8Array) => boolean|Promise<boolean>} add - Record a VERIFIED revocation; resolve true if it was new
|
|
601
|
+
* @property {(identityKey: Uint8Array, serial: Uint8Array|null) => boolean|Promise<boolean>} isRevoked - True if that serial, or the whole identity, is revoked
|
|
602
|
+
*/
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* Receive a revocation from the network: verify it, then offer it to the
|
|
606
|
+
* store. Idempotent: a repeat resolves `status: 'duplicate'`. Forward the
|
|
607
|
+
* returned `bytes` onward ONLY when `status` is `'added'`, which keeps gossip
|
|
608
|
+
* from looping. Throws `CredentialError` for malformed or wrongly-signed input
|
|
609
|
+
* (count those; do not forward them).
|
|
610
|
+
*
|
|
611
|
+
* @param {Uint8Array|string} bytes
|
|
612
|
+
* @param {RevocationStore} store
|
|
613
|
+
* @returns {Promise<{ status: 'added'|'duplicate'|'ignored', statement: object, bytes: Uint8Array }>}
|
|
614
|
+
*/
|
|
615
|
+
export async function receiveRevocation(bytes, store) {
|
|
616
|
+
const statement = await verifyRevocation(bytes);
|
|
617
|
+
const added = await store.add(statement, statement.bytes);
|
|
618
|
+
return { status: added === 'ignored' ? 'ignored' : added ? 'added' : 'duplicate', statement, bytes: statement.bytes };
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/**
|
|
622
|
+
* Is this certificate (or `{ identityKey, serial }`) revoked in `store`?
|
|
623
|
+
*
|
|
624
|
+
* @param {{ identityKey: Uint8Array, serial: Uint8Array }} subject
|
|
625
|
+
* @param {RevocationStore} store
|
|
626
|
+
* @returns {Promise<boolean>}
|
|
627
|
+
*/
|
|
628
|
+
export async function isRevoked(subject, store) {
|
|
629
|
+
return !!(await store.isRevoked(subject.identityKey, subject.serial ?? null));
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
/**
|
|
633
|
+
* In-memory revocation store with a size bound.
|
|
634
|
+
*
|
|
635
|
+
* Bounding: expired certificate revocations are dropped first (a revocation of
|
|
636
|
+
* a certificate is moot once the certificate's own `notAfter`, plus the
|
|
637
|
+
* maximum skew, has passed). If the store is still full, the certificate
|
|
638
|
+
* revocation closest to expiry is evicted. Identity retirements are never
|
|
639
|
+
* evicted for a certificate revocation; if the store holds only retirements
|
|
640
|
+
* and is full, `add` throws `store-full`. Anyone can mint identities and sign
|
|
641
|
+
* revocations for them, so give the store a `filter` that admits only
|
|
642
|
+
* identities you care about on a public network.
|
|
643
|
+
*/
|
|
644
|
+
export class MemoryRevocationStore {
|
|
645
|
+
#max;
|
|
646
|
+
#filter;
|
|
647
|
+
#entries = new Map();
|
|
648
|
+
#listeners = new Set();
|
|
649
|
+
#retired = new Set();
|
|
650
|
+
|
|
651
|
+
/**
|
|
652
|
+
* @param {object} [opts]
|
|
653
|
+
* @param {number} [opts.maxEntries=10000]
|
|
654
|
+
* @param {(statement: object) => boolean} [opts.filter] - Return false to ignore a statement
|
|
655
|
+
* @param {() => number} [opts.clock] - Milliseconds; default `Date.now`
|
|
656
|
+
*/
|
|
657
|
+
constructor({ maxEntries = DEFAULT_REVOCATION_STORE_SIZE, filter, clock = Date.now } = {}) {
|
|
658
|
+
if (!Number.isInteger(maxEntries) || maxEntries < 1) throw new TypeError('maxEntries must be a positive integer');
|
|
659
|
+
this.#max = maxEntries;
|
|
660
|
+
this.#filter = filter ?? null;
|
|
661
|
+
this.clock = clock;
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
/** @returns {number} */
|
|
665
|
+
get size() { return this.#entries.size; }
|
|
666
|
+
|
|
667
|
+
#key(identityKey, serial) {
|
|
668
|
+
return `${encodeBase64url(identityKey)}|${serial && serial.length ? encodeBase64url(serial) : ''}`;
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/**
|
|
672
|
+
* Drop revocations of certificates that have expired (beyond the maximum skew).
|
|
673
|
+
*
|
|
674
|
+
* @param {number|Date} [now]
|
|
675
|
+
* @returns {number} How many were dropped
|
|
676
|
+
*/
|
|
677
|
+
prune(now) {
|
|
678
|
+
const t = nowSeconds(now ?? this.clock());
|
|
679
|
+
let dropped = 0;
|
|
680
|
+
for (const [k, e] of this.#entries) {
|
|
681
|
+
if (e.retainUntil !== 0 && t >= e.retainUntil + MAX_SKEW_SECONDS) { this.#entries.delete(k); dropped++; }
|
|
682
|
+
}
|
|
683
|
+
return dropped;
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/** @returns {boolean|'ignored'} */
|
|
687
|
+
add(statement, bytes) {
|
|
688
|
+
if (this.#filter && !this.#filter(statement)) return 'ignored';
|
|
689
|
+
const key = this.#key(statement.identityKey, statement.serial);
|
|
690
|
+
if (this.#entries.has(key)) return false;
|
|
691
|
+
const t = nowSeconds(this.clock());
|
|
692
|
+
if (statement.retainUntil !== 0 && t >= statement.retainUntil + MAX_SKEW_SECONDS) return 'ignored';
|
|
693
|
+
if (this.#entries.size >= this.#max) this.prune();
|
|
694
|
+
if (this.#entries.size >= this.#max) {
|
|
695
|
+
let victim = null;
|
|
696
|
+
for (const [k, e] of this.#entries) {
|
|
697
|
+
if (e.retainUntil !== 0 && (victim === null || e.retainUntil < this.#entries.get(victim).retainUntil)) victim = k;
|
|
698
|
+
}
|
|
699
|
+
if (victim === null) {
|
|
700
|
+
throw new CredentialError('store-full', 'the revocation store is full of identity retirements');
|
|
701
|
+
}
|
|
702
|
+
this.#entries.delete(victim);
|
|
703
|
+
}
|
|
704
|
+
this.#entries.set(key, { bytes: new Uint8Array(bytes), retainUntil: statement.retainUntil, kind: statement.kind });
|
|
705
|
+
if (statement.kind === REVOCATION_KIND.IDENTITY) this.#retired.add(encodeBase64url(statement.identityKey));
|
|
706
|
+
for (const fn of [...this.#listeners]) {
|
|
707
|
+
try { fn({ statement, bytes: new Uint8Array(bytes) }); } catch { /* a listener must not break reception */ }
|
|
708
|
+
}
|
|
709
|
+
return true;
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
/** @returns {boolean} */
|
|
713
|
+
isRevoked(identityKey, serial) {
|
|
714
|
+
if (this.#retired.has(encodeBase64url(identityKey))) return true;
|
|
715
|
+
return serial ? this.#entries.has(this.#key(identityKey, serial)) : false;
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/**
|
|
719
|
+
* Revocations to hand a newly connected peer (unexpired ones).
|
|
720
|
+
*
|
|
721
|
+
* @returns {Uint8Array[]}
|
|
722
|
+
*/
|
|
723
|
+
list() {
|
|
724
|
+
this.prune();
|
|
725
|
+
return [...this.#entries.values()].map((e) => new Uint8Array(e.bytes));
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
/**
|
|
729
|
+
* Called once for each NEW revocation (not for duplicates), with
|
|
730
|
+
* `{ statement, bytes }`; forward `bytes` to other peers.
|
|
731
|
+
*
|
|
732
|
+
* @param {(ev: { statement: object, bytes: Uint8Array }) => void} fn
|
|
733
|
+
* @returns {() => void} Unsubscribe
|
|
734
|
+
*/
|
|
735
|
+
onRevocation(fn) {
|
|
736
|
+
this.#listeners.add(fn);
|
|
737
|
+
return () => this.#listeners.delete(fn);
|
|
738
|
+
}
|
|
739
|
+
}
|