@johnhenry/browsermesh-discovery 0.2.0 → 0.3.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 +37 -3
- package/package.json +2 -2
- package/src/dht.mjs +2 -2
- package/src/discovery.mjs +3 -3
- package/src/naming.mjs +3 -3
- package/src/silent-catch.mjs +21 -9
- package/src/stealth.mjs +297 -15
- package/src/sw-routing.mjs +4 -52
- package/src/swarm.mjs +2 -2
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@ Identity (`browsermesh-primitives`/`browsermesh-core`) answers "who is this peer
|
|
|
15
15
|
|
|
16
16
|
## Provenance
|
|
17
17
|
|
|
18
|
-
Extracted from
|
|
18
|
+
Extracted from a private monorepo (previously `packages/browsermesh-discovery`), where it was manually published to npm, unscoped, as `browsermesh-discovery@0.1.0` (2026-07-17) with no CI ever automating that publish. This is its first release as part of the `@johnhenry/browsermesh` monorepo; the version restarts at `0.0.0` per family convention.
|
|
19
19
|
|
|
20
20
|
|
|
21
21
|
## Modules
|
|
@@ -53,8 +53,42 @@ const state = await agent.reconstituteEncrypted();
|
|
|
53
53
|
```
|
|
54
54
|
|
|
55
55
|
The payload is bound to the agent id and a wrong key or any tampering rejects.
|
|
56
|
-
|
|
57
|
-
|
|
56
|
+
|
|
57
|
+
For key rotation and replay bounding, give the agent a `StealthKeyring`
|
|
58
|
+
instead of a single key:
|
|
59
|
+
|
|
60
|
+
```js
|
|
61
|
+
const keyring = await StealthKeyring.fromGroupSecrets('my-group', [{ id: 'k1', secret: s1 }]);
|
|
62
|
+
const agent = new StealthAgent({ agentId, dhtNode, keyring, maxAgeMs: 86_400_000 });
|
|
63
|
+
await agent.hideEncrypted(state); // v2.<keyId>.<seq>.<issuedAt>.<AES-GCM(iv || ciphertext)>
|
|
64
|
+
await keyring.add('k2', s2, { makeCurrent: true }); // rotate: new seals use k2, k1 still opens old state
|
|
65
|
+
keyring.remove('k1'); // when nothing sealed under k1 matters any more
|
|
66
|
+
const r = await agent.tryReconstituteEncrypted(); // { ok, state } | { ok: false, reason }; counted in agent.stats
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Each message gets a fresh random 96-bit nonce; a key refuses to seal past
|
|
70
|
+
2^32 messages (`key-exhausted`: rotate). The key id, sequence number and issue
|
|
71
|
+
time are authenticated together with the sender (agent id) and message type as
|
|
72
|
+
associated data. An older state than the newest this agent wrote or accepted
|
|
73
|
+
is refused as `replayed`; `maxAgeMs` refuses `stale` state. A peer without the
|
|
74
|
+
key (or looking at plaintext state) gets `{ ok: false, reason }` and a counter
|
|
75
|
+
in `agent.stats`, not a thrown error.
|
|
76
|
+
|
|
77
|
+
**What this hides, and from whom.** The content of the state, from nodes that
|
|
78
|
+
hold the DHT shards and anyone relaying them. **Not hidden:** that an agent
|
|
79
|
+
exists (shard keys name it), the size of its state, when it is written or read,
|
|
80
|
+
and who reads it (traffic analysis). Everyone holding the group key can read
|
|
81
|
+
the state and can also forge it: the sender in the associated data is a label,
|
|
82
|
+
not a signature (signed shards are not built). Group key custody and rotation
|
|
83
|
+
when a member leaves are the application's job. Replay protection is best
|
|
84
|
+
effort: an agent that has just started and has seen nothing newer cannot tell
|
|
85
|
+
an old state from the current one unless `maxAgeMs` is set.
|
|
86
|
+
|
|
87
|
+
**Threshold key sharing is not built.** The issue asks to *decide* on it and
|
|
88
|
+
describes it as needing a design call, not a requirement, so it is written up
|
|
89
|
+
in [docs/design/stealth-threshold.md](https://github.com/johnhenry/browsermesh/blob/main/docs/design/stealth-threshold.md)
|
|
90
|
+
and left unbuilt. Also not done: signed shards, agent-anonymous DHT keys, a
|
|
91
|
+
real checksum and multi-loss parity. The plain
|
|
58
92
|
`hide()` / `reconstitute()` below are unchanged and plaintext:
|
|
59
93
|
|
|
60
94
|
`StealthAgent.hide(stateString)` / `reconstitute()` split a state string into
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@johnhenry/browsermesh-discovery",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "DHT, peer discovery, naming, swarm coordination, and stealth networking for BrowserMesh",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.mjs",
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
"directory": "packages/browsermesh-discovery"
|
|
20
20
|
},
|
|
21
21
|
"peerDependencies": {
|
|
22
|
-
"@johnhenry/browsermesh-primitives": ">=0.
|
|
22
|
+
"@johnhenry/browsermesh-primitives": ">=0.3.1 <1.0.0"
|
|
23
23
|
},
|
|
24
24
|
"scripts": {
|
|
25
25
|
"test": "node --import ./test/_setup-globals.mjs --test test/*.test.mjs"
|
package/src/dht.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* dht.mjs -- DHT/Gossip protocol for BrowserMesh.
|
|
3
3
|
*
|
|
4
4
|
* Provides Kademlia-style distributed hash table with XOR-based routing,
|
|
5
5
|
* epidemic gossip protocol for state dissemination, and a DHT-backed
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* No browser-only imports at module level.
|
|
15
15
|
*
|
|
16
16
|
* Run tests:
|
|
17
|
-
* node --import ./
|
|
17
|
+
* cd packages/browsermesh-discovery && node --import ./test/_setup-globals.mjs --test test/dht.test.mjs
|
|
18
18
|
*/
|
|
19
19
|
|
|
20
20
|
import { DiscoveryStrategy } from './discovery.mjs'
|
package/src/discovery.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { silentCatch } from './silent-catch.mjs'
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
3
|
+
* discovery.mjs -- Peer discovery and service directory for BrowserMesh.
|
|
4
4
|
*
|
|
5
5
|
* Provides multi-strategy peer discovery (BroadcastChannel, relay, manual) and
|
|
6
6
|
* a local service directory with svc:// URI routing for the mesh network.
|
|
@@ -17,7 +17,7 @@ import { silentCatch } from './silent-catch.mjs'
|
|
|
17
17
|
* No browser-only imports at module level.
|
|
18
18
|
*
|
|
19
19
|
* Run tests:
|
|
20
|
-
* node --import ./
|
|
20
|
+
* cd packages/browsermesh-discovery && node --import ./test/_setup-globals.mjs --test test/discovery.test.mjs
|
|
21
21
|
*/
|
|
22
22
|
|
|
23
23
|
// ---------------------------------------------------------------------------
|
|
@@ -545,7 +545,7 @@ export class RelayStrategy extends DiscoveryStrategy {
|
|
|
545
545
|
try {
|
|
546
546
|
const msg = JSON.parse(event.data);
|
|
547
547
|
this.#handleMessage(msg);
|
|
548
|
-
} catch (e) { silentCatch('
|
|
548
|
+
} catch (e) { silentCatch('discovery', 'ignore-malformed', e) }
|
|
549
549
|
};
|
|
550
550
|
|
|
551
551
|
ws.onclose = () => {
|
package/src/naming.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
// STATUS: INTEGRATED — wired into
|
|
3
|
-
*
|
|
2
|
+
// STATUS: INTEGRATED — wired into Pod (@johnhenry/browsermesh-pod) lifecycle, proven via E2E testing
|
|
3
|
+
* naming.mjs -- Decentralized name resolution for BrowserMesh.
|
|
4
4
|
*
|
|
5
5
|
* Human-friendly names (@alice, mesh://alice/path) mapped to identity
|
|
6
6
|
* fingerprints. First-come-first-served registration, TTL-based expiry,
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* No browser-only imports at module level.
|
|
10
10
|
*
|
|
11
11
|
* Run tests:
|
|
12
|
-
* node --import ./
|
|
12
|
+
* cd packages/browsermesh-discovery && node --import ./test/_setup-globals.mjs --test test/naming.test.mjs
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
15
|
import { MESH_TYPE } from '@johnhenry/browsermesh-primitives';
|
package/src/silent-catch.mjs
CHANGED
|
@@ -2,31 +2,43 @@
|
|
|
2
2
|
* silent-catch.mjs — debug-gated structured logger for the
|
|
3
3
|
* `try { … } catch { /* ignore *\/ }` pattern.
|
|
4
4
|
*
|
|
5
|
-
*
|
|
6
|
-
* clawser-app imports) so this package doesn't need to reach into web/.
|
|
5
|
+
* Standalone module (no other imports) so this package is self-contained.
|
|
7
6
|
*
|
|
8
7
|
* Replaces silent catches with an opt-in inspectable record. Default
|
|
9
8
|
* behaviour is unchanged (silent), so this is a drop-in replacement.
|
|
10
9
|
* Users surface the events by enabling debug mode:
|
|
11
10
|
*
|
|
12
|
-
* localStorage.setItem('
|
|
13
|
-
* // or, in DevTools:
|
|
11
|
+
* localStorage.setItem('browsermesh_debug', 'true') // persistent
|
|
12
|
+
* // or, in DevTools: browsermeshDebug.enable()
|
|
13
|
+
*
|
|
14
|
+
* The old `clawser_debug` localStorage key and `clawserDebug` global are
|
|
15
|
+
* deprecated aliases, kept for compatibility.
|
|
14
16
|
*/
|
|
15
17
|
|
|
18
|
+
/** localStorage key that enables debug mode. */
|
|
19
|
+
const DEBUG_KEY = 'browsermesh_debug';
|
|
20
|
+
/** Deprecated alias for DEBUG_KEY, kept for compatibility. */
|
|
21
|
+
const LEGACY_DEBUG_KEY = 'clawser_debug';
|
|
22
|
+
|
|
23
|
+
function readDebugFlag() {
|
|
24
|
+
return localStorage.getItem(DEBUG_KEY) === 'true'
|
|
25
|
+
|| localStorage.getItem(LEGACY_DEBUG_KEY) === 'true';
|
|
26
|
+
}
|
|
27
|
+
|
|
16
28
|
let enabled = false;
|
|
17
29
|
try {
|
|
18
30
|
if (typeof localStorage !== 'undefined') {
|
|
19
|
-
enabled =
|
|
31
|
+
enabled = readDebugFlag();
|
|
20
32
|
}
|
|
21
33
|
} catch {
|
|
22
34
|
// localStorage may throw in privacy / sandbox contexts — treat as disabled
|
|
23
35
|
}
|
|
24
36
|
|
|
25
|
-
/** Re-check the localStorage flag; called by
|
|
37
|
+
/** Re-check the localStorage flag; called by browsermeshDebug.enable/disable. */
|
|
26
38
|
export function refreshSilentCatchState() {
|
|
27
39
|
try {
|
|
28
40
|
if (typeof localStorage !== 'undefined') {
|
|
29
|
-
enabled =
|
|
41
|
+
enabled = readDebugFlag();
|
|
30
42
|
}
|
|
31
43
|
} catch {
|
|
32
44
|
enabled = false;
|
|
@@ -36,7 +48,7 @@ export function refreshSilentCatchState() {
|
|
|
36
48
|
/**
|
|
37
49
|
* Log a silent-catch event. No-op unless debug mode is enabled.
|
|
38
50
|
*
|
|
39
|
-
* @param {string} module — file/component (e.g. '
|
|
51
|
+
* @param {string} module — file/component (e.g. 'pod')
|
|
40
52
|
* @param {string} operation — what was attempted (e.g. 'relay-disconnect')
|
|
41
53
|
* @param {*} error — the caught value
|
|
42
54
|
* @param {object} [context] — extra structured fields
|
|
@@ -51,5 +63,5 @@ export function silentCatch(module, operation, error, context) {
|
|
|
51
63
|
}
|
|
52
64
|
const entry = { module, operation, error: error?.message || String(error) };
|
|
53
65
|
if (context) Object.assign(entry, context);
|
|
54
|
-
console.warn('[
|
|
66
|
+
console.warn('[browsermesh:silent-catch]', entry);
|
|
55
67
|
}
|
package/src/stealth.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
// STATUS: INTEGRATED — wired into
|
|
3
|
-
*
|
|
2
|
+
// STATUS: INTEGRATED — wired into Pod (@johnhenry/browsermesh-pod) lifecycle, proven via E2E testing
|
|
3
|
+
* stealth.mjs -- Agent state sharding across the DHT.
|
|
4
4
|
*
|
|
5
5
|
* NOT ENCRYPTED, NOT ANONYMOUS. This module splits a state string into
|
|
6
6
|
* `threshold` plaintext data shards plus `total - threshold` XOR parity shards
|
|
@@ -24,6 +24,20 @@
|
|
|
24
24
|
* key, signed shards and agent-anonymous DHT keys are NOT done (see the issue).
|
|
25
25
|
* The plain synchronous `hide()` / `reconstitute()` are unchanged and plaintext.
|
|
26
26
|
*
|
|
27
|
+
* With a `StealthKeyring` (`keyring` option) the sealed state uses the v2
|
|
28
|
+
* envelope: key id (so keys rotate), sequence number and issue time (so an
|
|
29
|
+
* older state is refused as replayed), all authenticated with the sender and
|
|
30
|
+
* type as AES-GCM associated data. Peers without the key get a quiet,
|
|
31
|
+
* counted failure from `tryReconstituteEncrypted()`.
|
|
32
|
+
*
|
|
33
|
+
* What it hides, and from whom: the CONTENT of the state from whoever holds
|
|
34
|
+
* the DHT shards (shard-holding nodes and relays). It does NOT hide that an
|
|
35
|
+
* agent exists (keys are `stealth:<agentId>:shard:<i>`), how large its state
|
|
36
|
+
* is, when it is written or read, or who reads it (traffic analysis). Every
|
|
37
|
+
* holder of the group key can read and forge state: the sender in the
|
|
38
|
+
* associated data is a label, not a signature. Threshold sharing of the key is
|
|
39
|
+
* a design only (docs/design/stealth-threshold.md), not built.
|
|
40
|
+
*
|
|
27
41
|
* StateShard represents one fragment.
|
|
28
42
|
* ShardDistributor scatters shards across DHT nodes.
|
|
29
43
|
* ShardCollector retrieves and reconstructs state from DHT.
|
|
@@ -37,7 +51,7 @@
|
|
|
37
51
|
* No browser-only imports at module level.
|
|
38
52
|
*
|
|
39
53
|
* Run tests:
|
|
40
|
-
* node --import ./
|
|
54
|
+
* cd packages/browsermesh-discovery && node --import ./test/_setup-globals.mjs --test test/dht.test.mjs
|
|
41
55
|
*/
|
|
42
56
|
|
|
43
57
|
// ---------------------------------------------------------------------------
|
|
@@ -127,6 +141,199 @@ export async function decryptStealthState(payload, key, agentId) {
|
|
|
127
141
|
return new TextDecoder().decode(pt)
|
|
128
142
|
}
|
|
129
143
|
|
|
144
|
+
// ---------------------------------------------------------------------------
|
|
145
|
+
// Keyed, versioned, replay-bounded sealing (v2 envelope)
|
|
146
|
+
// ---------------------------------------------------------------------------
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Error for every sealing/opening refusal; `code` says why:
|
|
150
|
+
* `not-encrypted | malformed | unknown-key | tampered | replayed | stale |
|
|
151
|
+
* key-exhausted | no-key | bad-argument`.
|
|
152
|
+
*/
|
|
153
|
+
export class StealthError extends Error {
|
|
154
|
+
constructor(code, message) {
|
|
155
|
+
super(message)
|
|
156
|
+
this.name = 'StealthError'
|
|
157
|
+
this.code = code
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const V2_PREFIX = 'v2.'
|
|
162
|
+
const V2_DOMAIN = 'browsermesh-stealth/v2'
|
|
163
|
+
const KEY_ID_RE = /^[A-Za-z0-9_-]{1,64}$/
|
|
164
|
+
const DEFAULT_MAX_SEALS_PER_KEY = 2 ** 32 // NIST SP 800-38D bound for random 96-bit IVs
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* A set of AES-256-GCM keys identified by id, one of them current. Sealing
|
|
168
|
+
* uses the current key and writes its id into the envelope; opening picks the
|
|
169
|
+
* key by that id, so keys can rotate: add the new key, make it current, keep
|
|
170
|
+
* the old one until nothing sealed under it matters, then `remove` it.
|
|
171
|
+
* Each key counts its seals and refuses past `maxSealsPerKey` (random 96-bit
|
|
172
|
+
* IVs are only safe for a bounded number of messages per key).
|
|
173
|
+
*/
|
|
174
|
+
export class StealthKeyring {
|
|
175
|
+
#keys = new Map()
|
|
176
|
+
#current = null
|
|
177
|
+
#groupId = null
|
|
178
|
+
#max
|
|
179
|
+
|
|
180
|
+
/** @param {{ maxSealsPerKey?: number, groupId?: string }} [opts] */
|
|
181
|
+
constructor({ maxSealsPerKey = DEFAULT_MAX_SEALS_PER_KEY, groupId = null } = {}) {
|
|
182
|
+
if (!Number.isInteger(maxSealsPerKey) || maxSealsPerKey < 1) throw new StealthError('bad-argument', 'maxSealsPerKey must be a positive integer')
|
|
183
|
+
this.#max = maxSealsPerKey
|
|
184
|
+
this.#groupId = groupId
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Build a keyring from group secrets (HKDF per `deriveStealthKey`).
|
|
189
|
+
*
|
|
190
|
+
* @param {string} groupId
|
|
191
|
+
* @param {{ id: string, secret: Uint8Array|string }[]} entries
|
|
192
|
+
* @param {string} [currentId] - Defaults to the last entry
|
|
193
|
+
* @param {{ maxSealsPerKey?: number }} [opts]
|
|
194
|
+
* @returns {Promise<StealthKeyring>}
|
|
195
|
+
*/
|
|
196
|
+
static async fromGroupSecrets(groupId, entries, currentId, opts = {}) {
|
|
197
|
+
if (!Array.isArray(entries) || entries.length === 0) throw new StealthError('bad-argument', 'at least one key is required')
|
|
198
|
+
const kr = new StealthKeyring({ ...opts, groupId })
|
|
199
|
+
for (const e of entries) await kr.add(e.id, e.secret, { makeCurrent: false })
|
|
200
|
+
kr.setCurrent(currentId ?? entries[entries.length - 1].id)
|
|
201
|
+
return kr
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Derive and add a key from a group secret. */
|
|
205
|
+
async add(id, secret, { groupId = this.#groupId, makeCurrent = false } = {}) {
|
|
206
|
+
if (!groupId) throw new StealthError('bad-argument', 'groupId is required to derive a key')
|
|
207
|
+
return this.addKey(id, await deriveStealthKey(secret, groupId), { makeCurrent })
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Add an existing AES-GCM `CryptoKey` under `id`. */
|
|
211
|
+
addKey(id, key, { makeCurrent = false } = {}) {
|
|
212
|
+
if (typeof id !== 'string' || !KEY_ID_RE.test(id)) throw new StealthError('bad-argument', 'key id must be 1-64 characters of A-Z a-z 0-9 _ -')
|
|
213
|
+
this.#keys.set(id, { key, seals: 0 })
|
|
214
|
+
if (makeCurrent || this.#current === null) this.#current = id
|
|
215
|
+
return this
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
setCurrent(id) {
|
|
219
|
+
if (!this.#keys.has(id)) throw new StealthError('unknown-key', `no key ${id}`)
|
|
220
|
+
this.#current = id
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Drop a key. The current key cannot be removed: make another current first. */
|
|
224
|
+
remove(id) {
|
|
225
|
+
if (id === this.#current) throw new StealthError('bad-argument', 'cannot remove the current key')
|
|
226
|
+
return this.#keys.delete(id)
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
has(id) { return this.#keys.has(id) }
|
|
230
|
+
get currentId() { return this.#current }
|
|
231
|
+
get ids() { return [...this.#keys.keys()] }
|
|
232
|
+
|
|
233
|
+
/** @private used by sealStealthMessage */
|
|
234
|
+
_useCurrent() {
|
|
235
|
+
const e = this.#keys.get(this.#current)
|
|
236
|
+
if (!e) throw new StealthError('no-key', 'the keyring has no key')
|
|
237
|
+
if (e.seals >= this.#max) throw new StealthError('key-exhausted', `key ${this.#current} reached its message budget; rotate it`)
|
|
238
|
+
e.seals++
|
|
239
|
+
return { id: this.#current, key: e.key }
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** @private used by openStealthMessage */
|
|
243
|
+
_get(id) { return this.#keys.get(id)?.key ?? null }
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function u32(n) { return new Uint8Array([(n >>> 24) & 255, (n >>> 16) & 255, (n >>> 8) & 255, n & 255]) }
|
|
247
|
+
function u64(n) { const b = new Uint8Array(8); new DataView(b.buffer).setBigUint64(0, BigInt(n)); return b }
|
|
248
|
+
|
|
249
|
+
/** Associated data: length-prefixed domain, type, sender, key id, then seq and issuedAt. */
|
|
250
|
+
function v2Aad(type, sender, keyId, seq, issuedAt) {
|
|
251
|
+
const te = new TextEncoder()
|
|
252
|
+
const parts = [V2_DOMAIN, type, sender, keyId].map((s) => te.encode(s))
|
|
253
|
+
const out = []
|
|
254
|
+
for (const p of parts) out.push(u32(p.length), p)
|
|
255
|
+
out.push(u64(seq), u64(issuedAt))
|
|
256
|
+
const n = out.reduce((a, p) => a + p.length, 0)
|
|
257
|
+
const buf = new Uint8Array(n)
|
|
258
|
+
let o = 0
|
|
259
|
+
for (const p of out) { buf.set(p, o); o += p.length }
|
|
260
|
+
return buf
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Seal a message for a group that shares a keyring: AES-256-GCM, a fresh
|
|
265
|
+
* random 96-bit nonce per message, the key id, sequence number and issue time
|
|
266
|
+
* carried in the envelope and authenticated together with the sender and
|
|
267
|
+
* message type as associated data. Envelope:
|
|
268
|
+
* `v2.<keyId>.<seq>.<issuedAt>.<base64url(iv || ciphertext+tag)>`.
|
|
269
|
+
*
|
|
270
|
+
* The associated data binds the sender and type as LABELS: every group member
|
|
271
|
+
* holds the key and can seal under any sender name. It is not a signature.
|
|
272
|
+
*
|
|
273
|
+
* @param {string} plaintext
|
|
274
|
+
* @param {{ keyring: StealthKeyring, sender: string, type: string, seq?: number, issuedAt?: number }} opts
|
|
275
|
+
* @returns {Promise<string>}
|
|
276
|
+
*/
|
|
277
|
+
export async function sealStealthMessage(plaintext, { keyring, sender, type, seq, issuedAt }) {
|
|
278
|
+
if (!keyring || typeof keyring._useCurrent !== 'function') throw new StealthError('no-key', 'a keyring is required')
|
|
279
|
+
if (!sender || typeof sender !== 'string' || !type || typeof type !== 'string') throw new StealthError('bad-argument', 'sender and type are required strings')
|
|
280
|
+
const now = Date.now()
|
|
281
|
+
seq = seq ?? now
|
|
282
|
+
issuedAt = issuedAt ?? now
|
|
283
|
+
if (!Number.isSafeInteger(seq) || seq < 0 || !Number.isSafeInteger(issuedAt) || issuedAt < 0) throw new StealthError('bad-argument', 'seq and issuedAt must be non-negative integers')
|
|
284
|
+
const { id, key } = keyring._useCurrent()
|
|
285
|
+
const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES))
|
|
286
|
+
const ct = new Uint8Array(await crypto.subtle.encrypt(
|
|
287
|
+
{ name: 'AES-GCM', iv, additionalData: v2Aad(type, sender, id, seq, issuedAt) },
|
|
288
|
+
key,
|
|
289
|
+
new TextEncoder().encode(plaintext),
|
|
290
|
+
))
|
|
291
|
+
const body = new Uint8Array(IV_BYTES + ct.length)
|
|
292
|
+
body.set(iv, 0)
|
|
293
|
+
body.set(ct, IV_BYTES)
|
|
294
|
+
return `${V2_PREFIX}${id}.${seq}.${issuedAt}.${toBase64Url(body)}`
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Open a v2 envelope. Refusals throw `StealthError`: `not-encrypted` (not a v2
|
|
299
|
+
* envelope), `malformed`, `unknown-key` (key id not in the keyring),
|
|
300
|
+
* `tampered` (wrong key, or any change to the ciphertext, sender, type, key id,
|
|
301
|
+
* seq or issue time), then, after authentication, `replayed` (`seq <
|
|
302
|
+
* minSeq`) and `stale` (`now - issuedAt > maxAgeMs`).
|
|
303
|
+
*
|
|
304
|
+
* @param {string} payload
|
|
305
|
+
* @param {{ keyring: StealthKeyring, sender: string, type: string, minSeq?: number, maxAgeMs?: number, now?: number }} opts
|
|
306
|
+
* @returns {Promise<{ plaintext: string, keyId: string, seq: number, issuedAt: number }>}
|
|
307
|
+
*/
|
|
308
|
+
export async function openStealthMessage(payload, { keyring, sender, type, minSeq, maxAgeMs, now }) {
|
|
309
|
+
if (typeof payload !== 'string' || !payload.startsWith(V2_PREFIX)) throw new StealthError('not-encrypted', 'not a v2 stealth envelope')
|
|
310
|
+
const parts = payload.split('.')
|
|
311
|
+
if (parts.length !== 5 || !KEY_ID_RE.test(parts[1]) || !/^\d{1,16}$/.test(parts[2]) || !/^\d{1,16}$/.test(parts[3])) {
|
|
312
|
+
throw new StealthError('malformed', 'malformed stealth envelope')
|
|
313
|
+
}
|
|
314
|
+
const [, keyId, seqS, issuedS, bodyS] = parts
|
|
315
|
+
const seq = Number(seqS)
|
|
316
|
+
const issuedAt = Number(issuedS)
|
|
317
|
+
const key = keyring?._get?.(keyId)
|
|
318
|
+
if (!key) throw new StealthError('unknown-key', `no key ${keyId}`)
|
|
319
|
+
let bytes
|
|
320
|
+
try { bytes = fromBase64Url(bodyS) } catch { throw new StealthError('malformed', 'malformed stealth envelope') }
|
|
321
|
+
if (bytes.length <= IV_BYTES) throw new StealthError('malformed', 'truncated stealth envelope')
|
|
322
|
+
let pt
|
|
323
|
+
try {
|
|
324
|
+
pt = await crypto.subtle.decrypt(
|
|
325
|
+
{ name: 'AES-GCM', iv: bytes.slice(0, IV_BYTES), additionalData: v2Aad(type, sender, keyId, seq, issuedAt) },
|
|
326
|
+
key,
|
|
327
|
+
bytes.slice(IV_BYTES),
|
|
328
|
+
)
|
|
329
|
+
} catch {
|
|
330
|
+
throw new StealthError('tampered', 'authentication failed')
|
|
331
|
+
}
|
|
332
|
+
if (minSeq !== undefined && seq < minSeq) throw new StealthError('replayed', 'older than the newest state already seen')
|
|
333
|
+
if (maxAgeMs !== undefined && (now ?? Date.now()) - issuedAt > maxAgeMs) throw new StealthError('stale', 'older than the allowed age')
|
|
334
|
+
return { plaintext: new TextDecoder().decode(pt), keyId, seq, issuedAt }
|
|
335
|
+
}
|
|
336
|
+
|
|
130
337
|
// ---------------------------------------------------------------------------
|
|
131
338
|
// Checksum Helper
|
|
132
339
|
// ---------------------------------------------------------------------------
|
|
@@ -248,7 +455,7 @@ export class StateShard {
|
|
|
248
455
|
* Distributes agent state as shards across the DHT.
|
|
249
456
|
*/
|
|
250
457
|
export class ShardDistributor {
|
|
251
|
-
/** @type {import('./
|
|
458
|
+
/** @type {import('./dht.mjs').DhtNode} */
|
|
252
459
|
#dhtNode
|
|
253
460
|
|
|
254
461
|
/** @type {number} */
|
|
@@ -259,7 +466,7 @@ export class ShardDistributor {
|
|
|
259
466
|
|
|
260
467
|
/**
|
|
261
468
|
* @param {object} opts
|
|
262
|
-
* @param {import('./
|
|
469
|
+
* @param {import('./dht.mjs').DhtNode} opts.dhtNode - DHT node for storage
|
|
263
470
|
* @param {number} [opts.threshold=3] - Minimum shards for recovery
|
|
264
471
|
* @param {number} [opts.totalShards=5] - Total shards to create
|
|
265
472
|
*/
|
|
@@ -376,7 +583,7 @@ export class ShardDistributor {
|
|
|
376
583
|
* Collects and reconstructs agent state from DHT shards.
|
|
377
584
|
*/
|
|
378
585
|
export class ShardCollector {
|
|
379
|
-
/** @type {import('./
|
|
586
|
+
/** @type {import('./dht.mjs').DhtNode} */
|
|
380
587
|
#dhtNode
|
|
381
588
|
|
|
382
589
|
/** @type {number} */
|
|
@@ -384,7 +591,7 @@ export class ShardCollector {
|
|
|
384
591
|
|
|
385
592
|
/**
|
|
386
593
|
* @param {object} opts
|
|
387
|
-
* @param {import('./
|
|
594
|
+
* @param {import('./dht.mjs').DhtNode} opts.dhtNode - DHT node for retrieval
|
|
388
595
|
* @param {number} [opts.threshold=3] - Minimum shards needed
|
|
389
596
|
*/
|
|
390
597
|
constructor({ dhtNode, threshold = 3 }) {
|
|
@@ -509,7 +716,7 @@ export class StealthAgent {
|
|
|
509
716
|
/** @type {string} */
|
|
510
717
|
#agentId
|
|
511
718
|
|
|
512
|
-
/** @type {import('./
|
|
719
|
+
/** @type {import('./dht.mjs').DhtNode} */
|
|
513
720
|
#dhtNode
|
|
514
721
|
|
|
515
722
|
/** @type {number} */
|
|
@@ -530,19 +737,37 @@ export class StealthAgent {
|
|
|
530
737
|
/** @type {CryptoKey|null} */
|
|
531
738
|
#key = null
|
|
532
739
|
|
|
740
|
+
/** @type {StealthKeyring|null} */
|
|
741
|
+
#keyring = null
|
|
742
|
+
|
|
743
|
+
#maxAgeMs
|
|
744
|
+
|
|
745
|
+
/** Newest sequence number this agent has written. */
|
|
746
|
+
#seq = 0
|
|
747
|
+
|
|
748
|
+
/** Newest sequence number this agent has accepted from the DHT. */
|
|
749
|
+
#highestSeen = 0
|
|
750
|
+
|
|
751
|
+
#stats = {
|
|
752
|
+
opened: 0, notEncrypted: 0, noKey: 0, unknownKey: 0, tampered: 0,
|
|
753
|
+
replayed: 0, stale: 0, malformed: 0, unavailable: 0,
|
|
754
|
+
}
|
|
755
|
+
|
|
533
756
|
/**
|
|
534
757
|
* @param {object} opts
|
|
535
758
|
* @param {string} opts.agentId - Agent identifier
|
|
536
|
-
* @param {import('./
|
|
759
|
+
* @param {import('./dht.mjs').DhtNode} opts.dhtNode - DHT node
|
|
537
760
|
* @param {number} [opts.threshold=3] - Minimum shards for recovery
|
|
538
761
|
* @param {number} [opts.totalShards=5] - Total shards to create
|
|
539
762
|
* @param {CryptoKey} [opts.key] - AES-GCM key (see `deriveStealthKey`); enables `hideEncrypted()` / `reconstituteEncrypted()`
|
|
540
763
|
*/
|
|
541
|
-
constructor({ agentId, dhtNode, threshold = 3, totalShards = 5, key = null }) {
|
|
764
|
+
constructor({ agentId, dhtNode, threshold = 3, totalShards = 5, key = null, keyring = null, maxAgeMs }) {
|
|
542
765
|
if (!agentId || typeof agentId !== 'string') {
|
|
543
766
|
throw new Error('agentId is required and must be a non-empty string')
|
|
544
767
|
}
|
|
545
768
|
this.#key = key
|
|
769
|
+
this.#keyring = keyring
|
|
770
|
+
this.#maxAgeMs = maxAgeMs
|
|
546
771
|
this.#agentId = agentId
|
|
547
772
|
this.#dhtNode = dhtNode
|
|
548
773
|
this.#threshold = threshold
|
|
@@ -578,7 +803,16 @@ export class StealthAgent {
|
|
|
578
803
|
* @returns {Promise<object>} Manifest (`encrypted: true`)
|
|
579
804
|
*/
|
|
580
805
|
async hideEncrypted(stateBlob) {
|
|
581
|
-
if (
|
|
806
|
+
if (this.#keyring) {
|
|
807
|
+
// v2 envelope: key id, sequence number and issue time, authenticated with sender and type
|
|
808
|
+
const seq = Math.max(this.#seq + 1, Date.now())
|
|
809
|
+
const sealed = await sealStealthMessage(stateBlob, { keyring: this.#keyring, sender: this.#agentId, type: 'state', seq })
|
|
810
|
+
this.#seq = seq
|
|
811
|
+
this.hide(sealed)
|
|
812
|
+
this.#manifest = { ...this.#manifest, encrypted: true, keyId: sealed.split('.')[1], seq }
|
|
813
|
+
return this.#manifest
|
|
814
|
+
}
|
|
815
|
+
if (!this.#key) throw new StealthError('no-key', 'hideEncrypted requires a key or keyring (see deriveStealthKey / StealthKeyring)')
|
|
582
816
|
const sealed = await encryptStealthState(stateBlob, this.#key, this.#agentId)
|
|
583
817
|
this.hide(sealed)
|
|
584
818
|
this.#manifest = { ...this.#manifest, encrypted: true }
|
|
@@ -586,15 +820,63 @@ export class StealthAgent {
|
|
|
586
820
|
}
|
|
587
821
|
|
|
588
822
|
/**
|
|
589
|
-
* Reconstitute and decrypt state stored by `hideEncrypted()`. Rejects
|
|
590
|
-
*
|
|
823
|
+
* Reconstitute and decrypt state stored by `hideEncrypted()`. Rejects with
|
|
824
|
+
* a `StealthError` (`code`: no-key, not-encrypted, unknown-key, tampered,
|
|
825
|
+
* replayed, stale, malformed) when the state cannot be trusted. With a
|
|
826
|
+
* keyring, state older than the newest this agent wrote or accepted is
|
|
827
|
+
* refused as `replayed`. Use `tryReconstituteEncrypted()` where failures are
|
|
828
|
+
* routine.
|
|
591
829
|
* @returns {Promise<string>}
|
|
592
830
|
*/
|
|
593
831
|
async reconstituteEncrypted() {
|
|
594
|
-
if (!this.#key) throw new
|
|
595
|
-
return
|
|
832
|
+
if (!this.#key && !this.#keyring) throw new StealthError('no-key', 'reconstituteEncrypted requires a key or keyring (see deriveStealthKey / StealthKeyring)')
|
|
833
|
+
return this.#open(this.reconstitute())
|
|
596
834
|
}
|
|
597
835
|
|
|
836
|
+
async #open(raw) {
|
|
837
|
+
if (raw.startsWith(V2_PREFIX)) {
|
|
838
|
+
if (!this.#keyring) throw new StealthError('no-key', 'state is sealed under a keyring; this agent has none')
|
|
839
|
+
const r = await openStealthMessage(raw, {
|
|
840
|
+
keyring: this.#keyring, sender: this.#agentId, type: 'state',
|
|
841
|
+
minSeq: Math.max(this.#highestSeen, this.#seq), maxAgeMs: this.#maxAgeMs,
|
|
842
|
+
})
|
|
843
|
+
this.#highestSeen = Math.max(this.#highestSeen, r.seq)
|
|
844
|
+
return r.plaintext
|
|
845
|
+
}
|
|
846
|
+
if (raw.startsWith(ENC_PREFIX)) {
|
|
847
|
+
if (!this.#key) throw new StealthError('no-key', 'state is sealed under a single key; this agent has none')
|
|
848
|
+
try { return await decryptStealthState(raw, this.#key, this.#agentId) } catch { throw new StealthError('tampered', 'authentication failed') }
|
|
849
|
+
}
|
|
850
|
+
throw new StealthError('not-encrypted', 'the stored state is not encrypted')
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
/**
|
|
854
|
+
* Like `reconstituteEncrypted()` but never throws for an untrusted or
|
|
855
|
+
* unreadable state: it resolves `{ ok: true, state }` or
|
|
856
|
+
* `{ ok: false, reason }` and counts the outcome in `stats`. A peer without
|
|
857
|
+
* the key, or looking at plaintext or foreign state, gets a quiet `false`.
|
|
858
|
+
* Reasons: unavailable (too few shards), no-key, not-encrypted, unknown-key,
|
|
859
|
+
* tampered, replayed, stale, malformed.
|
|
860
|
+
* @returns {Promise<{ ok: true, state: string } | { ok: false, reason: string }>}
|
|
861
|
+
*/
|
|
862
|
+
async tryReconstituteEncrypted() {
|
|
863
|
+
let raw
|
|
864
|
+
try { raw = this.reconstitute() } catch { this.#stats.unavailable++; return { ok: false, reason: 'unavailable' } }
|
|
865
|
+
try {
|
|
866
|
+
const state = await this.#open(raw)
|
|
867
|
+
this.#stats.opened++
|
|
868
|
+
return { ok: true, state }
|
|
869
|
+
} catch (err) {
|
|
870
|
+
const code = err instanceof StealthError ? err.code : 'malformed'
|
|
871
|
+
const slot = { 'no-key': 'noKey', 'not-encrypted': 'notEncrypted', 'unknown-key': 'unknownKey' }[code] ?? code
|
|
872
|
+
this.#stats[slot in this.#stats ? slot : 'malformed']++
|
|
873
|
+
return { ok: false, reason: slot in this.#stats ? code : 'malformed' }
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
/** Counters for `tryReconstituteEncrypted()` outcomes (the throwing variant does not count). @returns {object} */
|
|
878
|
+
get stats() { return { ...this.#stats } }
|
|
879
|
+
|
|
598
880
|
/**
|
|
599
881
|
* Reconstitute the agent's state from DHT shards.
|
|
600
882
|
* @returns {string} Reconstructed state blob
|
package/src/sw-routing.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* sw-routing.mjs -- ServiceWorker mesh:// fetch routing.
|
|
3
3
|
*
|
|
4
4
|
* Intercepts mesh:// protocol requests and *.mesh.local hostnames
|
|
5
5
|
* in the Service Worker fetch handler, delegating to mesh RPC.
|
|
@@ -25,59 +25,11 @@
|
|
|
25
25
|
* No browser-only imports at module level.
|
|
26
26
|
*
|
|
27
27
|
* Run tests:
|
|
28
|
-
* node --import ./
|
|
28
|
+
* cd packages/browsermesh-discovery && node --import ./test/_setup-globals.mjs --test test/sw-routing.test.mjs
|
|
29
29
|
*/
|
|
30
30
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
/**
|
|
35
|
-
* Parse a mesh URL into { podId, path } or null.
|
|
36
|
-
* Supports:
|
|
37
|
-
* - mesh://podId/path
|
|
38
|
-
* - https://podId.mesh.local/path
|
|
39
|
-
* - http://podId.mesh.local/path
|
|
40
|
-
*
|
|
41
|
-
* @param {string} urlStr
|
|
42
|
-
* @returns {{ podId: string, path: string } | null}
|
|
43
|
-
*/
|
|
44
|
-
export function parseMeshRequest(urlStr) {
|
|
45
|
-
if (!urlStr || typeof urlStr !== 'string') return null
|
|
46
|
-
|
|
47
|
-
// --- mesh:// protocol ---
|
|
48
|
-
if (urlStr.startsWith(MESH_PROTOCOL)) {
|
|
49
|
-
const rest = urlStr.slice(MESH_PROTOCOL.length)
|
|
50
|
-
if (!rest) return null
|
|
51
|
-
|
|
52
|
-
const slashIdx = rest.indexOf('/')
|
|
53
|
-
let podId, path
|
|
54
|
-
if (slashIdx === -1) {
|
|
55
|
-
podId = rest
|
|
56
|
-
path = '/'
|
|
57
|
-
} else {
|
|
58
|
-
podId = rest.slice(0, slashIdx)
|
|
59
|
-
path = rest.slice(slashIdx) || '/'
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
if (!podId) return null
|
|
63
|
-
return { podId, path }
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
// --- https://podId.mesh.local/path or http://podId.mesh.local/path ---
|
|
67
|
-
// Extract hostname from the raw string to preserve case (URL() lowercases hostnames).
|
|
68
|
-
const httpMatch = urlStr.match(/^https?:\/\/([^/?#]+)(\/[^?#]*)?/)
|
|
69
|
-
if (!httpMatch) return null
|
|
70
|
-
|
|
71
|
-
const rawHost = httpMatch[1] // preserves original case
|
|
72
|
-
const lowerHost = rawHost.toLowerCase()
|
|
73
|
-
if (!lowerHost.endsWith(MESH_LOCAL_SUFFIX)) return null
|
|
74
|
-
|
|
75
|
-
const podId = rawHost.slice(0, -MESH_LOCAL_SUFFIX.length)
|
|
76
|
-
if (!podId) return null
|
|
77
|
-
|
|
78
|
-
const path = httpMatch[2] || '/'
|
|
79
|
-
return { podId, path }
|
|
80
|
-
}
|
|
31
|
+
import { parseMeshRequest } from '@johnhenry/browsermesh-primitives'
|
|
32
|
+
export { parseMeshRequest }
|
|
81
33
|
|
|
82
34
|
/**
|
|
83
35
|
* Routes mesh:// and *.mesh.local fetch requests to a mesh RPC handler.
|
package/src/swarm.mjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* swarm.mjs -- Swarm Coordination for BrowserMesh.
|
|
3
3
|
*
|
|
4
4
|
* Leader election, task distribution, and swarm lifecycle management.
|
|
5
5
|
* Peers form a swarm where one node acts as leader, distributing tasks
|
|
6
6
|
* across followers using pluggable strategies.
|
|
7
7
|
*
|
|
8
8
|
* Run tests:
|
|
9
|
-
* node --import ./
|
|
9
|
+
* cd packages/browsermesh-discovery && node --import ./test/_setup-globals.mjs --test test/swarm.test.mjs
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
12
|
// ---------------------------------------------------------------------------
|