@johnhenry/browsermesh-primitives 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 John Henry
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,117 @@
1
+ # browsermesh-primitives
2
+
3
+ Shared primitives for browser mesh networking -- wire format, identity (Ed25519), CRDTs, capabilities, trust model, and ACL engine. Zero dependencies, pure ES modules, runs in browsers and Node.js.
4
+
5
+ ## Provenance
6
+
7
+ Previously published as `browsermesh-primitives@0.1.1`. Imported into the `@johnhenry` npm scope as part of the browsermesh monorepo consolidation; the version restarts at `0.0.0` per family convention (a new address is a new era).
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm install @johnhenry/browsermesh-primitives
13
+ ```
14
+
15
+ Or via CDN:
16
+
17
+ ```html
18
+ <script type="module">
19
+ import { PodIdentity, VectorClock, ACLEngine } from 'https://esm.sh/@johnhenry/browsermesh-primitives'
20
+ </script>
21
+ ```
22
+
23
+ ## Quick Start
24
+
25
+ ```js
26
+ import {
27
+ PodIdentity,
28
+ VectorClock,
29
+ ORSet,
30
+ CapabilityToken,
31
+ ACLEngine,
32
+ encodeMeshMessage,
33
+ decodeMeshMessage,
34
+ } from 'browsermesh-primitives'
35
+
36
+ // Generate an Ed25519 identity
37
+ const identity = await PodIdentity.generate()
38
+ console.log(identity.podId) // base64url-encoded SHA-256 of public key
39
+
40
+ // Sign and verify data
41
+ const data = new TextEncoder().encode('hello mesh')
42
+ const sig = await identity.sign(data)
43
+ const ok = await PodIdentity.verify(identity.keyPair.publicKey, data, sig)
44
+
45
+ // CRDTs -- merge state across peers
46
+ const clockA = new VectorClock()
47
+ clockA.increment('node-a')
48
+ const clockB = new VectorClock()
49
+ clockB.increment('node-b')
50
+ const merged = clockA.merge(clockB)
51
+
52
+ // Observed-Remove Set
53
+ const set = new ORSet()
54
+ set.add('item', identity.podId)
55
+ console.log(set.has('item')) // true
56
+ ```
57
+
58
+ ## API Overview
59
+
60
+ ### Constants & Errors
61
+
62
+ - `MESH_TYPE` -- message type constants
63
+ - `MESH_ERROR` -- error code constants
64
+ - `MeshError`, `MeshProtocolError`, `MeshCapabilityError` -- error classes
65
+
66
+ ### Identity
67
+
68
+ - `PodIdentity` -- Ed25519 key pair with sign/verify
69
+ - `derivePodId(publicKey)` -- SHA-256 hash to base64url pod ID
70
+ - `encodeBase64url(bytes)` / `decodeBase64url(str)` -- URL-safe base64
71
+
72
+ ### Wire Format
73
+
74
+ - `messageTypeRegistry` -- extensible registry of message types
75
+ - `encodeMeshMessage(msg)` / `decodeMeshMessage(bytes)` -- binary serialization
76
+
77
+ ### Capabilities
78
+
79
+ - `CapabilityToken` -- scoped capability with expiry
80
+ - `parseScope(str)` / `matchScope(pattern, target)` -- scope parsing and matching
81
+
82
+ ### Trust
83
+
84
+ - `TRUST_CATEGORIES` -- predefined trust category constants
85
+ - `createTrustEdge(from, to, category, score)` -- weighted trust edge
86
+ - `computeTransitiveTrust(edges, source, target)` -- transitive trust score
87
+
88
+ ### ACL
89
+
90
+ - `ACLEngine` -- evaluate access grants against resource patterns
91
+ - `Permission` -- permission level enum
92
+ - `AccessGrant` -- grant struct with resource pattern, permission, and principal
93
+ - `matchResourcePattern(pattern, resource)` -- glob-style resource matching
94
+ - `generateGrantId()` -- unique grant ID generator
95
+
96
+ ### CRDTs
97
+
98
+ - `VectorClock` -- partial-order logical clock with merge
99
+ - `LWWRegister` -- last-writer-wins register with nodeId tiebreak
100
+ - `GCounter` -- grow-only counter
101
+ - `PNCounter` -- positive-negative counter
102
+ - `ORSet` -- observed-remove set (add-wins semantics)
103
+ - `RGA` -- replicated growable array (ordered list)
104
+ - `LWWMap` -- last-writer-wins map with tombstones
105
+
106
+ All CRDTs support `merge()`, `toJSON()`, and `fromJSON()` for serialization.
107
+
108
+ ### Test Utilities
109
+
110
+ - `DeterministicRNG` -- seeded RNG for reproducible tests
111
+ - `LocalChannel` / `createLocalChannelPair()` -- in-memory transport
112
+ - `TestMesh` -- lightweight mesh harness
113
+ - `TESTMESH_LIMITS` -- default resource limits for test meshes
114
+
115
+ ## License
116
+
117
+ MIT
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@johnhenry/browsermesh-primitives",
3
+ "version": "0.0.0",
4
+ "description": "Shared primitives for browser mesh networking — wire format, identity (Ed25519), CRDTs, capabilities, trust model, and ACL engine",
5
+ "type": "module",
6
+ "main": "./src/index.mjs",
7
+ "exports": {
8
+ ".": "./src/index.mjs"
9
+ },
10
+ "files": [
11
+ "src",
12
+ "LICENSE",
13
+ "README.md"
14
+ ],
15
+ "keywords": [
16
+ "mesh",
17
+ "p2p",
18
+ "crdt",
19
+ "wire-format",
20
+ "identity",
21
+ "browser"
22
+ ],
23
+ "license": "MIT",
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "https://github.com/johnhenry/browsermesh",
27
+ "directory": "packages/browsermesh-primitives"
28
+ },
29
+ "homepage": "https://opensource.johnhenry.me/browsermesh/",
30
+ "scripts": {
31
+ "test": "node --test test/*.test.mjs"
32
+ },
33
+ "engines": {
34
+ "node": ">=24.0.0"
35
+ }
36
+ }
package/src/acl.mjs ADDED
@@ -0,0 +1,471 @@
1
+ /**
2
+ * ACL (Access Control List) module for mesh-primitives.
3
+ *
4
+ * Provides glob-style resource pattern matching, permission grants,
5
+ * and an engine for managing access control across pods.
6
+ *
7
+ * Pure module — no I/O, no browser APIs, no crypto.
8
+ */
9
+
10
+ // ─── Glob-style resource pattern matching ────────────────────────────
11
+
12
+ /**
13
+ * Match a resource string against a glob-style pattern.
14
+ *
15
+ * Supported wildcards:
16
+ * - `*` matches any characters except `/` (single segment)
17
+ * - `**` matches any characters including `/` (recursive)
18
+ * - `?` matches any single character except `/`
19
+ * - Exact strings match literally
20
+ *
21
+ * @param {string} pattern - Glob pattern (e.g. `"svc://model/*"`, `"fs:///docs/**"`)
22
+ * @param {string} resource - Resource identifier to test
23
+ * @returns {boolean} True if the resource matches the pattern
24
+ */
25
+ export function matchResourcePattern(pattern, resource) {
26
+ if (pattern === '*') return true;
27
+ if (pattern === resource) return true;
28
+
29
+ // Convert glob pattern to regex
30
+ const regexStr = pattern
31
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&') // escape regex specials (not * and ?)
32
+ .replace(/\*\*/g, '{{GLOBSTAR}}') // temp placeholder for **
33
+ .replace(/\*/g, '[^/]*') // * matches any non-slash sequence
34
+ .replace(/\?/g, '[^/]') // ? matches single non-slash char
35
+ .replace(/\{\{GLOBSTAR\}\}/g, '.*'); // ** matches everything incl. /
36
+
37
+ return new RegExp(`^${regexStr}$`).test(resource);
38
+ }
39
+
40
+ // ─── Permission ──────────────────────────────────────────────────────
41
+
42
+ /**
43
+ * A single permission entry: a resource pattern + allowed actions + optional quotas.
44
+ *
45
+ * @class
46
+ */
47
+ export class Permission {
48
+ /**
49
+ * @param {object} opts
50
+ * @param {string} opts.resource - Glob pattern for the resource
51
+ * @param {string[]} opts.actions - Allowed actions (e.g. `["read","write"]`, `["*"]`, `["admin"]`)
52
+ * @param {{ maxCalls?: number, maxBytes?: number, maxTokens?: number, maxConcurrent?: number }|null} [opts.quotas=null]
53
+ */
54
+ constructor({ resource, actions, quotas = null }) {
55
+ /** @type {string} */
56
+ this.resource = resource;
57
+ /** @type {string[]} */
58
+ this.actions = [...actions];
59
+ /** @type {{ maxCalls?: number, maxBytes?: number, maxTokens?: number, maxConcurrent?: number }|null} */
60
+ this.quotas = quotas ? { ...quotas } : null;
61
+ }
62
+
63
+ /**
64
+ * Check if this permission covers the given resource + action pair.
65
+ *
66
+ * @param {string} resource - The concrete resource identifier
67
+ * @param {string} action - The action being attempted
68
+ * @returns {boolean}
69
+ */
70
+ matches(resource, action) {
71
+ if (!matchResourcePattern(this.resource, resource)) return false;
72
+ if (this.actions.includes('*') || this.actions.includes('admin')) return true;
73
+ return this.actions.includes(action);
74
+ }
75
+
76
+ /**
77
+ * Serialize to a plain JSON-compatible object.
78
+ * @returns {object}
79
+ */
80
+ toJSON() {
81
+ return {
82
+ resource: this.resource,
83
+ actions: [...this.actions],
84
+ quotas: this.quotas ? { ...this.quotas } : null,
85
+ };
86
+ }
87
+
88
+ /**
89
+ * Reconstruct a Permission from a plain object.
90
+ * @param {object} data
91
+ * @returns {Permission}
92
+ */
93
+ static fromJSON(data) {
94
+ return new Permission({
95
+ resource: data.resource,
96
+ actions: data.actions,
97
+ quotas: data.quotas ?? null,
98
+ });
99
+ }
100
+ }
101
+
102
+ // ─── AccessGrant ─────────────────────────────────────────────────────
103
+
104
+ /**
105
+ * Represents a grant of permissions from one pod (grantor) to another (grantee).
106
+ *
107
+ * @class
108
+ */
109
+ export class AccessGrant {
110
+ /**
111
+ * @param {object} opts
112
+ * @param {string} opts.id - Unique grant identifier
113
+ * @param {string} opts.grantee - Recipient pod ID
114
+ * @param {string} opts.grantor - Issuer pod ID
115
+ * @param {Array<Permission|object>} opts.permissions - Permission entries
116
+ * @param {{ expires?: number, maxUses?: number, timeWindows?: Array<{ start: string, end: string }> }} [opts.conditions={}]
117
+ * @param {number} [opts.created=Date.now()]
118
+ * @param {number} [opts.usageCount=0]
119
+ */
120
+ constructor({
121
+ id,
122
+ grantee,
123
+ grantor,
124
+ permissions,
125
+ conditions = {},
126
+ created = Date.now(),
127
+ usageCount = 0,
128
+ }) {
129
+ /** @type {string} */
130
+ this.id = id;
131
+ /** @type {string} */
132
+ this.grantee = grantee;
133
+ /** @type {string} */
134
+ this.grantor = grantor;
135
+ /** @type {Permission[]} */
136
+ this.permissions = permissions.map(
137
+ p => (p instanceof Permission ? p : new Permission(p))
138
+ );
139
+ /** @type {{ expires?: number, maxUses?: number, timeWindows?: Array<{ start: string, end: string }> }} */
140
+ this.conditions = { ...conditions };
141
+ /** @type {number} */
142
+ this.created = created;
143
+ /** @type {number|null} */
144
+ this.revoked = null;
145
+ /** @type {number} */
146
+ this.usageCount = usageCount;
147
+ }
148
+
149
+ /**
150
+ * Check whether this grant has expired.
151
+ *
152
+ * A grant is expired if:
153
+ * - It has been revoked
154
+ * - The `expires` timestamp has passed
155
+ * - The `maxUses` limit has been reached
156
+ *
157
+ * @param {number} [now=Date.now()] - Current time in milliseconds
158
+ * @returns {boolean}
159
+ */
160
+ isExpired(now = Date.now()) {
161
+ if (this.revoked) return true;
162
+ if (this.conditions.expires && now >= this.conditions.expires) return true;
163
+ if (this.conditions.maxUses && this.usageCount >= this.conditions.maxUses) return true;
164
+ return false;
165
+ }
166
+
167
+ /**
168
+ * Check whether the current time falls within any allowed time window.
169
+ *
170
+ * Time windows use `"HH:MM"` format for start/end.
171
+ * If no time windows are configured, returns true (always allowed).
172
+ *
173
+ * @param {Date} [now=new Date()] - Current date/time
174
+ * @returns {boolean}
175
+ */
176
+ isWithinTimeWindow(now = new Date()) {
177
+ if (!this.conditions.timeWindows || this.conditions.timeWindows.length === 0) {
178
+ return true;
179
+ }
180
+ const timeStr = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
181
+ return this.conditions.timeWindows.some(w => timeStr >= w.start && timeStr <= w.end);
182
+ }
183
+
184
+ /**
185
+ * Check if this grant allows a specific resource + action.
186
+ *
187
+ * @param {string} resource - Resource identifier
188
+ * @param {string} action - Action being attempted
189
+ * @param {number} [now=Date.now()] - Current time in milliseconds
190
+ * @returns {{ allowed: boolean, grant?: AccessGrant, reason?: string }}
191
+ */
192
+ check(resource, action, now = Date.now()) {
193
+ if (this.isExpired(now)) {
194
+ return { allowed: false, reason: 'grant_expired' };
195
+ }
196
+ if (!this.isWithinTimeWindow(new Date(now))) {
197
+ return { allowed: false, reason: 'outside_time_window' };
198
+ }
199
+ for (const perm of this.permissions) {
200
+ if (perm.matches(resource, action)) {
201
+ return { allowed: true, grant: this };
202
+ }
203
+ }
204
+ return { allowed: false, reason: 'no_matching_permission' };
205
+ }
206
+
207
+ /**
208
+ * Increment the usage counter by one.
209
+ */
210
+ consumeUse() {
211
+ this.usageCount++;
212
+ }
213
+
214
+ /**
215
+ * Mark this grant as revoked.
216
+ *
217
+ * @param {number} [timestamp=Date.now()] - Revocation timestamp
218
+ */
219
+ revoke(timestamp = Date.now()) {
220
+ this.revoked = timestamp;
221
+ }
222
+
223
+ /**
224
+ * Serialize to a plain JSON-compatible object.
225
+ * @returns {object}
226
+ */
227
+ toJSON() {
228
+ return {
229
+ id: this.id,
230
+ grantee: this.grantee,
231
+ grantor: this.grantor,
232
+ permissions: this.permissions.map(p => p.toJSON()),
233
+ conditions: { ...this.conditions },
234
+ created: this.created,
235
+ revoked: this.revoked,
236
+ usageCount: this.usageCount,
237
+ };
238
+ }
239
+
240
+ /**
241
+ * Reconstruct an AccessGrant from a plain object.
242
+ *
243
+ * @param {object} data
244
+ * @returns {AccessGrant}
245
+ */
246
+ static fromJSON(data) {
247
+ const grant = new AccessGrant({
248
+ id: data.id,
249
+ grantee: data.grantee,
250
+ grantor: data.grantor,
251
+ permissions: data.permissions.map(p => Permission.fromJSON(p)),
252
+ conditions: data.conditions ?? {},
253
+ created: data.created,
254
+ usageCount: data.usageCount ?? 0,
255
+ });
256
+ grant.revoked = data.revoked ?? null;
257
+ return grant;
258
+ }
259
+ }
260
+
261
+ // ─── ACLEngine ───────────────────────────────────────────────────────
262
+
263
+ /**
264
+ * Manages multiple access grants and evaluates access control decisions.
265
+ *
266
+ * @class
267
+ */
268
+ export class ACLEngine {
269
+ /** @type {Map<string, AccessGrant>} */
270
+ #grants;
271
+
272
+ constructor() {
273
+ this.#grants = new Map();
274
+ }
275
+
276
+ /**
277
+ * Add or replace a grant.
278
+ *
279
+ * @param {AccessGrant} grant
280
+ */
281
+ addGrant(grant) {
282
+ this.#grants.set(grant.id, grant);
283
+ }
284
+
285
+ /**
286
+ * Remove a grant by ID.
287
+ *
288
+ * @param {string} grantId
289
+ * @returns {boolean} True if the grant existed and was removed
290
+ */
291
+ removeGrant(grantId) {
292
+ return this.#grants.delete(grantId);
293
+ }
294
+
295
+ /**
296
+ * Mark a grant as revoked (keeps it in the map but expired).
297
+ *
298
+ * @param {string} grantId
299
+ * @param {number} [timestamp=Date.now()]
300
+ * @returns {boolean} True if the grant existed
301
+ */
302
+ revokeGrant(grantId, timestamp = Date.now()) {
303
+ const grant = this.#grants.get(grantId);
304
+ if (!grant) return false;
305
+ grant.revoke(timestamp);
306
+ return true;
307
+ }
308
+
309
+ /**
310
+ * Revoke all grants for a specific grantee.
311
+ *
312
+ * @param {string} grantee - Pod ID of the grantee
313
+ * @param {number} [timestamp=Date.now()]
314
+ * @returns {number} Number of grants revoked
315
+ */
316
+ revokeAll(grantee, timestamp = Date.now()) {
317
+ let count = 0;
318
+ for (const grant of this.#grants.values()) {
319
+ if (grant.grantee === grantee && !grant.revoked) {
320
+ grant.revoke(timestamp);
321
+ count++;
322
+ }
323
+ }
324
+ return count;
325
+ }
326
+
327
+ /**
328
+ * Check whether a grantee is allowed to perform an action on a resource.
329
+ *
330
+ * Iterates all grants for the grantee and returns on the first match.
331
+ *
332
+ * @param {string} grantee - Pod ID of the requester
333
+ * @param {string} resource - Resource identifier
334
+ * @param {string} action - Action being attempted
335
+ * @param {number} [now=Date.now()] - Current time in milliseconds
336
+ * @returns {{ allowed: boolean, grant?: AccessGrant, reason?: string }}
337
+ */
338
+ check(grantee, resource, action, now = Date.now()) {
339
+ let lastReason = 'no_grants';
340
+ for (const grant of this.#grants.values()) {
341
+ if (grant.grantee !== grantee) continue;
342
+ const result = grant.check(resource, action, now);
343
+ if (result.allowed) {
344
+ return result;
345
+ }
346
+ lastReason = result.reason;
347
+ }
348
+ return { allowed: false, reason: lastReason };
349
+ }
350
+
351
+ /**
352
+ * List grants, optionally filtered by grantee.
353
+ *
354
+ * @param {string} [grantee] - If provided, only return grants for this grantee
355
+ * @returns {AccessGrant[]}
356
+ */
357
+ listGrants(grantee) {
358
+ const results = [];
359
+ for (const grant of this.#grants.values()) {
360
+ if (grantee === undefined || grant.grantee === grantee) {
361
+ results.push(grant);
362
+ }
363
+ }
364
+ return results;
365
+ }
366
+
367
+ /**
368
+ * List unique grantee IDs with their grant counts.
369
+ *
370
+ * @returns {Array<{ grantee: string, count: number }>}
371
+ */
372
+ listGrantees() {
373
+ const counts = new Map();
374
+ for (const grant of this.#grants.values()) {
375
+ counts.set(grant.grantee, (counts.get(grant.grantee) || 0) + 1);
376
+ }
377
+ return Array.from(counts.entries()).map(([grantee, count]) => ({ grantee, count }));
378
+ }
379
+
380
+ /**
381
+ * Merge all permissions from all active (non-expired) grants for a grantee.
382
+ *
383
+ * Deduplicates by resource+actions key so identical permissions are not repeated.
384
+ *
385
+ * @param {string} grantee - Pod ID
386
+ * @param {number} [now=Date.now()]
387
+ * @returns {Permission[]}
388
+ */
389
+ getEffectivePermissions(grantee, now = Date.now()) {
390
+ const seen = new Set();
391
+ const result = [];
392
+ for (const grant of this.#grants.values()) {
393
+ if (grant.grantee !== grantee) continue;
394
+ if (grant.isExpired(now)) continue;
395
+ for (const perm of grant.permissions) {
396
+ // Deduplicate by resource + sorted actions
397
+ const key = `${perm.resource}|${[...perm.actions].sort().join(',')}`;
398
+ if (!seen.has(key)) {
399
+ seen.add(key);
400
+ result.push(perm);
401
+ }
402
+ }
403
+ }
404
+ return result;
405
+ }
406
+
407
+ /**
408
+ * Remove all expired grants from the engine.
409
+ *
410
+ * @param {number} [now=Date.now()]
411
+ * @returns {number} Number of grants pruned
412
+ */
413
+ pruneExpired(now = Date.now()) {
414
+ let count = 0;
415
+ for (const [id, grant] of this.#grants) {
416
+ if (grant.isExpired(now)) {
417
+ this.#grants.delete(id);
418
+ count++;
419
+ }
420
+ }
421
+ return count;
422
+ }
423
+
424
+ /**
425
+ * Serialize the engine state to a plain JSON-compatible object.
426
+ * @returns {object}
427
+ */
428
+ toJSON() {
429
+ return {
430
+ grants: Array.from(this.#grants.values()).map(g => g.toJSON()),
431
+ };
432
+ }
433
+
434
+ /**
435
+ * Reconstruct an ACLEngine from a plain object.
436
+ *
437
+ * @param {object} data
438
+ * @returns {ACLEngine}
439
+ */
440
+ static fromJSON(data) {
441
+ const engine = new ACLEngine();
442
+ for (const grantData of data.grants) {
443
+ engine.addGrant(AccessGrant.fromJSON(grantData));
444
+ }
445
+ return engine;
446
+ }
447
+
448
+ /**
449
+ * Total number of grants in the engine.
450
+ * @returns {number}
451
+ */
452
+ get size() {
453
+ return this.#grants.size;
454
+ }
455
+ }
456
+
457
+ // ─── ID generator ────────────────────────────────────────────────────
458
+
459
+ /** @type {number} */
460
+ let _grantSeq = 0;
461
+
462
+ /**
463
+ * Generate a unique grant ID.
464
+ *
465
+ * Format: `grant_<timestamp-base36>_<sequence-base36>`
466
+ *
467
+ * @returns {string}
468
+ */
469
+ export function generateGrantId() {
470
+ return `grant_${Date.now().toString(36)}_${(++_grantSeq).toString(36)}`;
471
+ }