@johnhenry/browsermesh-primitives 0.4.1 → 0.5.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-primitives",
3
- "version": "0.4.1",
3
+ "version": "0.5.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/index.d.ts CHANGED
@@ -512,5 +512,26 @@ export declare function paddedLength(length: number, opts?: { buckets?: number[]
512
512
  export declare function padTo(bytes: Uint8Array, opts?: { buckets?: number[] }): Uint8Array;
513
513
  export declare function unpad(padded: Uint8Array): Uint8Array;
514
514
 
515
+ // Key agreement keys bound to pod ids, and sealing to them
516
+
517
+ export declare class KeyAgreementError extends Error {
518
+ code: 'malformed' | 'unsupported-version' | 'pod-id-mismatch' | 'bad-signature' | 'not-yet-valid' | 'expired' | 'invalid-lifetime' | 'lifetime-too-long' | 'wrong-identity' | 'identity-retired' | 'unknown-key' | 'open-failed' | 'too-large' | 'bad-argument' | 'unsupported';
519
+ }
520
+ export declare const KEY_STATEMENT_VERSION: 1;
521
+ export declare const MAX_STATEMENT_LIFETIME_MS: number;
522
+ export declare const DEFAULT_STATEMENT_LIFETIME_MS: number;
523
+ export declare const DEFAULT_MAX_SEALED_BYTES: number;
524
+ export interface AgreementKeyPair { privateKey: CryptoKey; publicKeyRaw: Uint8Array }
525
+ export interface KeyStatement { v: 1; podId: string; pk: string; ka: string; kid: string; notBefore: number; notAfter: number; sig: string }
526
+ export interface VerifiedKeyStatement { podId: string; pk: Uint8Array; ka: Uint8Array; kid: string; notBefore: number; notAfter: number }
527
+ export interface SealedBox { v: 1; kid: string; epk: string; iv: string; ct: string }
528
+ export declare function supportsKeyAgreement(): Promise<boolean>;
529
+ export declare function generateAgreementKeyPair(): Promise<AgreementKeyPair>;
530
+ export declare function keyIdOf(ka: Uint8Array): Promise<string>;
531
+ export declare function createKeyStatement(identity: { podId: string; sign(data: Uint8Array): Promise<Uint8Array> | Uint8Array; rawPublicKey(): Promise<Uint8Array> }, agreement: { publicKeyRaw: Uint8Array }, opts?: { now?: number; lifetimeMs?: number }): Promise<KeyStatement>;
532
+ export declare function verifyKeyStatement(statement: unknown, opts?: { now?: number; skewMs?: number; expectedPodId?: string; revocations?: { isRevoked(identityKey: Uint8Array, serial: Uint8Array | null): boolean | Promise<boolean> } }): Promise<VerifiedKeyStatement>;
533
+ export declare function sealToStatement(verified: { ka: Uint8Array; kid: string }, opts: { aad: Uint8Array; plaintext: Uint8Array; maxBytes?: number }): Promise<SealedBox>;
534
+ export declare function openSealed(sealed: unknown, opts: { privateKeys: Map<string, AgreementKeyPair> | ((kid: string) => AgreementKeyPair | undefined); aad: Uint8Array; maxBytes?: number }): Promise<Uint8Array>;
535
+
515
536
  /** Parse a case-sensitive mesh:// or *.mesh.local address. */
516
537
  export declare function parseMeshRequest(url: string): { podId: string; path: string } | null;
package/src/index.mjs CHANGED
@@ -35,6 +35,22 @@ export {
35
35
  MemoryRevocationStore,
36
36
  } from "./session.mjs";
37
37
 
38
+ // Key agreement keys bound to pod ids, and sealing to them
39
+ export {
40
+ KeyAgreementError,
41
+ KEY_STATEMENT_VERSION,
42
+ MAX_STATEMENT_LIFETIME_MS,
43
+ DEFAULT_STATEMENT_LIFETIME_MS,
44
+ DEFAULT_MAX_SEALED_BYTES,
45
+ supportsKeyAgreement,
46
+ generateAgreementKeyPair,
47
+ keyIdOf,
48
+ createKeyStatement,
49
+ verifyKeyStatement,
50
+ sealToStatement,
51
+ openSealed,
52
+ } from "./key-agreement.mjs";
53
+
38
54
  // Wire format
39
55
  export { messageTypeRegistry, encodeMeshMessage, decodeMeshMessage } from "./wire.mjs";
40
56
 
@@ -0,0 +1,246 @@
1
+ /**
2
+ * key-agreement.mjs -- key agreement keys bound to pod ids, and sealing to them.
3
+ *
4
+ * A pod id is the hash of an Ed25519 identity key. That key signs; it does not
5
+ * agree on secrets. An X25519 key is a separate key, so nothing about a pod id
6
+ * tells a sender which X25519 key to encrypt to. A **key statement** closes the
7
+ * gap: the identity key signs "this X25519 key is mine, from now until then".
8
+ * A receiver of a statement checks the signature against the pod id (the hash
9
+ * of the key inside the statement) before it uses the X25519 key for anything.
10
+ *
11
+ * signed bytes = "browsermesh/key-agreement/v1\n" +
12
+ * JSON [podId, pk, ka, notBefore, notAfter] (fixed order)
13
+ *
14
+ * statement = { v: 1, podId, pk, ka, kid, notBefore, notAfter, sig }
15
+ * pk raw Ed25519 public key (base64url), podId must be its hash
16
+ * ka raw X25519 public key (base64url)
17
+ * kid names ka: first 16 bytes of SHA-256(ka), base64url (checked, not trusted)
18
+ *
19
+ * A statement expires (at most 24 h after `notBefore`, no grace after
20
+ * `notAfter`), is refused when the identity has been retired in the revocation
21
+ * store used for session certificates, and is rotated by issuing a new one.
22
+ *
23
+ * **Sealing** is ephemeral-static: for each message the sender makes a fresh
24
+ * X25519 key pair, agrees with the statement's `ka`, derives an AES-256-GCM key
25
+ * with HKDF-SHA-256 (salt = ephemeral public key || ka), and encrypts with the
26
+ * caller's header as additional authenticated data. Because the key is fresh for
27
+ * every message, the (key, nonce) pair cannot repeat; the 12-byte nonce is
28
+ * random as well. The sender throws its ephemeral private key away, so a later
29
+ * compromise of the SENDER reveals nothing about what it sealed. A later
30
+ * compromise of the RECIPIENT's static agreement key reveals every message
31
+ * sealed to it, unless the recipient has already deleted that key: rotation
32
+ * (and deleting expired private keys) bounds the exposure to one statement
33
+ * lifetime. There is no sender authentication at this layer; the signed
34
+ * envelope around the sealed bytes provides it.
35
+ *
36
+ * Browser-safe: WebCrypto only (X25519, HKDF, AES-GCM, Ed25519).
37
+ */
38
+
39
+ import { encodeBase64url, decodeBase64url } from './identity.mjs';
40
+ import { verifyWithRawPublicKey, podIdFromRawKey } from './session.mjs';
41
+
42
+ export const KEY_STATEMENT_VERSION = 1;
43
+ export const STATEMENT_DOMAIN = 'browsermesh/key-agreement/v1\n';
44
+ export const SEAL_DOMAIN = 'browsermesh/sealed/v1';
45
+ /** A statement never lives longer than this. */
46
+ export const MAX_STATEMENT_LIFETIME_MS = 24 * 3_600_000;
47
+ export const DEFAULT_STATEMENT_LIFETIME_MS = 2 * 3_600_000;
48
+ /** Clock skew tolerated before `notBefore`. There is none after `notAfter`. */
49
+ export const DEFAULT_SKEW_MS = 30_000;
50
+ /** Largest plaintext sealed or opened unless the caller says otherwise. */
51
+ export const DEFAULT_MAX_SEALED_BYTES = 256 * 1024;
52
+
53
+ const KEY_BYTES = 32;
54
+ const IV_BYTES = 12;
55
+ const TAG_BYTES = 16;
56
+ const enc = new TextEncoder();
57
+
58
+ /** Every refusal. `code`: malformed | unsupported-version | pod-id-mismatch | bad-signature | not-yet-valid | expired | invalid-lifetime | lifetime-too-long | wrong-identity | identity-retired | unknown-key | open-failed | too-large | bad-argument | unsupported */
59
+ export class KeyAgreementError extends Error {
60
+ constructor(code, message) {
61
+ super(message);
62
+ this.name = 'KeyAgreementError';
63
+ this.code = code;
64
+ }
65
+ }
66
+
67
+ const b64len = (n) => Math.ceil((n * 4) / 3);
68
+ const isB64 = (s, bytes) => typeof s === 'string' && s.length === b64len(bytes) && /^[A-Za-z0-9_-]+$/.test(s);
69
+
70
+ /** Whether this environment's WebCrypto can do X25519 (Node 18.4+, Chromium 133+, Firefox 130+, Safari 17+ per MDN). Never throws. */
71
+ export async function supportsKeyAgreement() {
72
+ try {
73
+ await crypto.subtle.generateKey({ name: 'X25519' }, false, ['deriveBits']);
74
+ return true;
75
+ } catch {
76
+ return false;
77
+ }
78
+ }
79
+
80
+ /**
81
+ * A fresh X25519 key pair for key agreement. The private key is not extractable.
82
+ *
83
+ * @returns {Promise<{ privateKey: CryptoKey, publicKeyRaw: Uint8Array }>}
84
+ */
85
+ export async function generateAgreementKeyPair() {
86
+ let pair;
87
+ try {
88
+ pair = await crypto.subtle.generateKey({ name: 'X25519' }, true, ['deriveBits']);
89
+ } catch (err) {
90
+ throw new KeyAgreementError('unsupported', `X25519 is not available here: ${err?.message ?? err}`);
91
+ }
92
+ const publicKeyRaw = new Uint8Array(await crypto.subtle.exportKey('raw', pair.publicKey));
93
+ // Re-import the private key as non-extractable so it cannot be read back out.
94
+ const jwk = await crypto.subtle.exportKey('jwk', pair.privateKey);
95
+ const privateKey = await crypto.subtle.importKey('jwk', jwk, { name: 'X25519' }, false, ['deriveBits']);
96
+ return { privateKey, publicKeyRaw };
97
+ }
98
+
99
+ /** @param {Uint8Array} ka @returns {Promise<string>} */
100
+ export async function keyIdOf(ka) {
101
+ return encodeBase64url(new Uint8Array(await crypto.subtle.digest('SHA-256', ka)).subarray(0, 16));
102
+ }
103
+
104
+ function signingInput({ podId, pk, ka, notBefore, notAfter }) {
105
+ return enc.encode(STATEMENT_DOMAIN + JSON.stringify([podId, pk, ka, notBefore, notAfter]));
106
+ }
107
+
108
+ /**
109
+ * Sign a key statement for `agreement` with the pod's identity key.
110
+ *
111
+ * @param {{ podId: string, sign: (data: Uint8Array) => Promise<Uint8Array>|Uint8Array, rawPublicKey: () => Promise<Uint8Array> }} identity - a `PodIdentity`, or anything shaped like one
112
+ * @param {{ publicKeyRaw: Uint8Array }} agreement - from `generateAgreementKeyPair()`
113
+ * @param {{ now?: number, lifetimeMs?: number }} [opts]
114
+ * @returns {Promise<object>} the statement (plain JSON)
115
+ */
116
+ export async function createKeyStatement(identity, agreement, { now = Date.now(), lifetimeMs = DEFAULT_STATEMENT_LIFETIME_MS } = {}) {
117
+ if (!Number.isInteger(lifetimeMs) || lifetimeMs <= 0) throw new KeyAgreementError('bad-argument', 'lifetimeMs must be a positive integer');
118
+ if (lifetimeMs > MAX_STATEMENT_LIFETIME_MS) throw new KeyAgreementError('lifetime-too-long', `a statement lives at most ${MAX_STATEMENT_LIFETIME_MS} ms`);
119
+ if (!Number.isSafeInteger(now)) throw new KeyAgreementError('bad-argument', 'now must be a whole number of milliseconds');
120
+ const pk = encodeBase64url(await identity.rawPublicKey());
121
+ const ka = encodeBase64url(agreement.publicKeyRaw);
122
+ const body = { podId: identity.podId, pk, ka, notBefore: now, notAfter: now + lifetimeMs };
123
+ const sig = encodeBase64url(new Uint8Array(await identity.sign(signingInput(body))));
124
+ return { v: KEY_STATEMENT_VERSION, ...body, kid: await keyIdOf(agreement.publicKeyRaw), sig };
125
+ }
126
+
127
+ /**
128
+ * Check a statement and return what may be trusted from it. Throws a
129
+ * `KeyAgreementError` for anything wrong with it.
130
+ *
131
+ * @param {object} statement
132
+ * @param {object} [opts]
133
+ * @param {number} [opts.now=Date.now()] - ms
134
+ * @param {number} [opts.skewMs=30000]
135
+ * @param {string} [opts.expectedPodId] - refuse a statement for another pod
136
+ * @param {{ isRevoked: (identityKey: Uint8Array, serial: Uint8Array|null) => boolean|Promise<boolean> }} [opts.revocations] - the store `receiveRevocation()` feeds; a retired identity is refused. A store that throws fails closed.
137
+ * @returns {Promise<{ podId: string, pk: Uint8Array, ka: Uint8Array, kid: string, notBefore: number, notAfter: number }>}
138
+ */
139
+ export async function verifyKeyStatement(statement, { now = Date.now(), skewMs = DEFAULT_SKEW_MS, expectedPodId, revocations } = {}) {
140
+ const s = statement;
141
+ if (!s || typeof s !== 'object' || Array.isArray(s)) throw new KeyAgreementError('malformed', 'a statement is an object');
142
+ if (s.v !== KEY_STATEMENT_VERSION) throw new KeyAgreementError(s.v === undefined ? 'malformed' : 'unsupported-version', 'unsupported statement version');
143
+ if (typeof s.podId !== 'string' || s.podId.length === 0 || s.podId.length > 128
144
+ || !isB64(s.pk, KEY_BYTES) || !isB64(s.ka, KEY_BYTES) || !isB64(s.sig, 64)
145
+ || !Number.isSafeInteger(s.notBefore) || !Number.isSafeInteger(s.notAfter)) {
146
+ throw new KeyAgreementError('malformed', 'a statement has podId, pk, ka, sig, notBefore and notAfter');
147
+ }
148
+ if (s.notAfter <= s.notBefore) throw new KeyAgreementError('invalid-lifetime', 'notAfter is not after notBefore');
149
+ if (s.notAfter - s.notBefore > MAX_STATEMENT_LIFETIME_MS) throw new KeyAgreementError('lifetime-too-long', 'the statement lives too long');
150
+
151
+ const pk = decodeBase64url(s.pk);
152
+ if ((await podIdFromRawKey(pk)) !== s.podId) throw new KeyAgreementError('pod-id-mismatch', 'the signing key is not the pod id the statement names');
153
+ if (expectedPodId !== undefined && expectedPodId !== s.podId) throw new KeyAgreementError('wrong-identity', 'the statement is for a different pod');
154
+ if (!(await verifyWithRawPublicKey(pk, decodeBase64url(s.sig), signingInput(s)))) {
155
+ throw new KeyAgreementError('bad-signature', 'the statement is not signed by its identity key');
156
+ }
157
+ if (now < s.notBefore - skewMs) throw new KeyAgreementError('not-yet-valid', 'the statement is not valid yet');
158
+ if (now >= s.notAfter) throw new KeyAgreementError('expired', 'the statement has expired');
159
+ if (revocations) {
160
+ let revoked;
161
+ try { revoked = await revocations.isRevoked(pk, null); } catch { revoked = true; }
162
+ if (revoked) throw new KeyAgreementError('identity-retired', 'the identity has been retired');
163
+ }
164
+ const ka = decodeBase64url(s.ka);
165
+ return { podId: s.podId, pk, ka, kid: await keyIdOf(ka), notBefore: s.notBefore, notAfter: s.notAfter };
166
+ }
167
+
168
+ async function deriveKey(sharedBits, epk, ka, usage) {
169
+ const salt = new Uint8Array(epk.length + ka.length);
170
+ salt.set(epk, 0);
171
+ salt.set(ka, epk.length);
172
+ const hkdf = await crypto.subtle.importKey('raw', sharedBits, 'HKDF', false, ['deriveKey']);
173
+ return crypto.subtle.deriveKey(
174
+ { name: 'HKDF', hash: 'SHA-256', salt, info: enc.encode(`${SEAL_DOMAIN} key`) },
175
+ hkdf,
176
+ { name: 'AES-GCM', length: 256 },
177
+ false,
178
+ [usage],
179
+ );
180
+ }
181
+
182
+ function aadBytes(aad) {
183
+ const head = enc.encode(`${SEAL_DOMAIN}\0`);
184
+ const out = new Uint8Array(head.length + aad.length);
185
+ out.set(head, 0);
186
+ out.set(aad, head.length);
187
+ return out;
188
+ }
189
+
190
+ /**
191
+ * Seal `plaintext` so only the holder of the statement's agreement key can open it.
192
+ *
193
+ * @param {{ ka: Uint8Array, kid: string }} verified - the result of `verifyKeyStatement()`; never an unverified statement
194
+ * @param {object} opts
195
+ * @param {Uint8Array} opts.aad - the header the ciphertext belongs to; opening needs the same bytes
196
+ * @param {Uint8Array} opts.plaintext
197
+ * @param {number} [opts.maxBytes=262144]
198
+ * @returns {Promise<{ v: 1, kid: string, epk: string, iv: string, ct: string }>}
199
+ */
200
+ export async function sealToStatement(verified, { aad, plaintext, maxBytes = DEFAULT_MAX_SEALED_BYTES }) {
201
+ if (!(plaintext instanceof Uint8Array) || !(aad instanceof Uint8Array)) throw new KeyAgreementError('bad-argument', 'aad and plaintext are bytes');
202
+ if (plaintext.length > maxBytes) throw new KeyAgreementError('too-large', `the message is ${plaintext.length} bytes; the limit is ${maxBytes}`);
203
+ const ephemeral = await crypto.subtle.generateKey({ name: 'X25519' }, true, ['deriveBits']);
204
+ const epk = new Uint8Array(await crypto.subtle.exportKey('raw', ephemeral.publicKey));
205
+ const recipient = await crypto.subtle.importKey('raw', verified.ka, { name: 'X25519' }, false, []);
206
+ const shared = await crypto.subtle.deriveBits({ name: 'X25519', public: recipient }, ephemeral.privateKey, 256);
207
+ const key = await deriveKey(shared, epk, verified.ka, 'encrypt');
208
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
209
+ const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: aadBytes(aad), tagLength: TAG_BYTES * 8 }, key, plaintext));
210
+ return { v: 1, kid: verified.kid, epk: encodeBase64url(epk), iv: encodeBase64url(iv), ct: encodeBase64url(ct) };
211
+ }
212
+
213
+ /**
214
+ * Open what `sealToStatement()` made.
215
+ *
216
+ * @param {object} sealed
217
+ * @param {object} opts
218
+ * @param {Map<string, { privateKey: CryptoKey, publicKeyRaw: Uint8Array }>|((kid: string) => { privateKey: CryptoKey, publicKeyRaw: Uint8Array }|undefined)} opts.privateKeys - the recipient's agreement key pairs (`generateAgreementKeyPair()`) by key id: the current one and the not-yet-expired older ones
219
+ * @param {Uint8Array} opts.aad
220
+ * @param {number} [opts.maxBytes=262144]
221
+ * @returns {Promise<Uint8Array>}
222
+ */
223
+ export async function openSealed(sealed, { privateKeys, aad, maxBytes = DEFAULT_MAX_SEALED_BYTES }) {
224
+ if (!sealed || typeof sealed !== 'object' || sealed.v !== 1 || typeof sealed.kid !== 'string'
225
+ || !isB64(sealed.epk, KEY_BYTES) || !isB64(sealed.iv, IV_BYTES) || typeof sealed.ct !== 'string' || !/^[A-Za-z0-9_-]*$/.test(sealed.ct)) {
226
+ throw new KeyAgreementError('malformed', 'not a sealed message');
227
+ }
228
+ if (sealed.ct.length > b64len(maxBytes + TAG_BYTES) + 4) throw new KeyAgreementError('too-large', 'the sealed message is larger than the limit');
229
+ const pair = typeof privateKeys === 'function' ? privateKeys(sealed.kid) : privateKeys.get(sealed.kid);
230
+ if (!pair) throw new KeyAgreementError('unknown-key', 'sealed to a key this pod does not hold (any more)');
231
+ const epk = decodeBase64url(sealed.epk);
232
+ const ct = decodeBase64url(sealed.ct);
233
+ if (ct.length < TAG_BYTES) throw new KeyAgreementError('malformed', 'too short');
234
+ if (ct.length - TAG_BYTES > maxBytes) throw new KeyAgreementError('too-large', 'the sealed message is larger than the limit');
235
+ try {
236
+ const sender = await crypto.subtle.importKey('raw', epk, { name: 'X25519' }, false, []);
237
+ const shared = await crypto.subtle.deriveBits({ name: 'X25519', public: sender }, pair.privateKey, 256);
238
+ // The recipient's own public key is part of the key derivation, as it was when sealing.
239
+ const ka = pair.publicKeyRaw;
240
+ if ((await keyIdOf(ka)) !== sealed.kid) throw new Error('kid');
241
+ const key = await deriveKey(shared, epk, ka, 'decrypt');
242
+ return new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: decodeBase64url(sealed.iv), additionalData: aadBytes(aad), tagLength: TAG_BYTES * 8 }, key, ct));
243
+ } catch {
244
+ throw new KeyAgreementError('open-failed', 'the sealed message did not open');
245
+ }
246
+ }