@johnhenry/browsermesh-core 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.
@@ -0,0 +1,852 @@
1
+ /**
2
+ // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
+ * clawser-mesh-capabilities.js -- Capability Attenuation & WASM Sandbox.
4
+ *
5
+ * Implements the object-capability (ocap) model for BrowserMesh:
6
+ *
7
+ * - CapabilityToken: unforgeable, attenuable tokens granting specific access.
8
+ * - CapabilityChain: ordered list of attenuations from root to leaf.
9
+ * - CapabilityValidator: verifies token integrity and attenuation invariants.
10
+ * - WasmSandboxPolicy: security policy for WASM module execution.
11
+ * - WasmSandbox: manages WASM module lifecycle within policy constraints.
12
+ * - SandboxRegistry: tracks active sandboxes per pod.
13
+ *
14
+ * No browser-only imports at module level.
15
+ *
16
+ * Run tests:
17
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-capabilities.test.mjs
18
+ */
19
+
20
+ // ---------------------------------------------------------------------------
21
+ // Wire Constants
22
+ // ---------------------------------------------------------------------------
23
+
24
+ /** Wire type for capability grant message. */
25
+ export const CAP_GRANT = 0xDC;
26
+
27
+ /** Wire type for capability revoke message. */
28
+ export const CAP_REVOKE = 0xDD;
29
+
30
+ /** Wire type for capability delegate (attenuate) message. */
31
+ export const CAP_DELEGATE = 0xDE;
32
+
33
+ /** Wire type for WASM sandbox control message. */
34
+ export const WASM_SANDBOX_CTRL = 0xDF;
35
+
36
+ // ---------------------------------------------------------------------------
37
+ // CapabilityToken
38
+ // ---------------------------------------------------------------------------
39
+
40
+ let _tokenSeq = 0;
41
+
42
+ /**
43
+ * An unforgeable capability token granting specific access rights.
44
+ * Tokens can be attenuated (narrowed) but never amplified.
45
+ */
46
+ export class CapabilityToken {
47
+ /**
48
+ * @param {object} opts
49
+ * @param {string} [opts.id] Unique token ID
50
+ * @param {string} opts.issuer Pod ID of the issuer
51
+ * @param {string} opts.holder Pod ID of the current holder
52
+ * @param {string} opts.resource Resource identifier (e.g. 'fs:/data', 'net:*')
53
+ * @param {string[]} opts.permissions Allowed operations (e.g. ['read', 'write'])
54
+ * @param {object} [opts.constraints] Additional constraints (maxCalls, expiry, etc.)
55
+ * @param {string|null} [opts.parentId] ID of the parent token (null for root)
56
+ * @param {number} [opts.createdAt] Unix timestamp (ms)
57
+ * @param {number|null} [opts.expiresAt] Expiry timestamp (null = no expiry)
58
+ * @param {boolean} [opts.revoked] Whether token has been revoked
59
+ * @param {number} [opts.depth] Delegation depth (0 for root)
60
+ * @param {number|null} [opts.maxDepth] Maximum delegation depth (null = unlimited)
61
+ */
62
+ constructor({
63
+ id,
64
+ issuer,
65
+ holder,
66
+ resource,
67
+ permissions,
68
+ constraints = {},
69
+ parentId = null,
70
+ createdAt,
71
+ expiresAt = null,
72
+ revoked = false,
73
+ depth = 0,
74
+ maxDepth = null,
75
+ }) {
76
+ if (!issuer || typeof issuer !== 'string') {
77
+ throw new Error('issuer is required and must be a non-empty string');
78
+ }
79
+ if (!holder || typeof holder !== 'string') {
80
+ throw new Error('holder is required and must be a non-empty string');
81
+ }
82
+ if (!resource || typeof resource !== 'string') {
83
+ throw new Error('resource is required and must be a non-empty string');
84
+ }
85
+ if (!Array.isArray(permissions) || permissions.length === 0) {
86
+ throw new Error('permissions must be a non-empty array');
87
+ }
88
+
89
+ this.id = id || `cap_${Date.now()}_${++_tokenSeq}`;
90
+ this.issuer = issuer;
91
+ this.holder = holder;
92
+ this.resource = resource;
93
+ this.permissions = Object.freeze([...permissions]);
94
+ this.constraints = Object.freeze({ ...constraints });
95
+ this.parentId = parentId;
96
+ this.createdAt = createdAt || Date.now();
97
+ this.expiresAt = expiresAt;
98
+ this.revoked = revoked;
99
+ this.depth = depth;
100
+ this.maxDepth = maxDepth;
101
+ }
102
+
103
+ /** Check whether this token has expired. */
104
+ isExpired(now = Date.now()) {
105
+ return this.expiresAt !== null && now >= this.expiresAt;
106
+ }
107
+
108
+ /** Check whether this token is currently valid. */
109
+ isValid(now = Date.now()) {
110
+ return !this.revoked && !this.isExpired(now);
111
+ }
112
+
113
+ /** Check whether a specific permission is granted. */
114
+ hasPermission(perm) {
115
+ return this.permissions.includes(perm);
116
+ }
117
+
118
+ /** Check whether further delegation is allowed. */
119
+ canDelegate() {
120
+ if (this.maxDepth === null) return true;
121
+ return this.depth < this.maxDepth;
122
+ }
123
+
124
+ /**
125
+ * Create an attenuated child token with a subset of permissions.
126
+ * Attenuation can only narrow, never widen.
127
+ *
128
+ * @param {object} opts
129
+ * @param {string} opts.holder New holder pod ID
130
+ * @param {string[]} [opts.permissions] Subset of parent permissions
131
+ * @param {string} [opts.resource] Narrower resource scope
132
+ * @param {object} [opts.constraints] Additional constraints (merged)
133
+ * @param {number|null} [opts.expiresAt] Expiry (must be ≤ parent)
134
+ * @param {number|null} [opts.maxDepth] Max depth (must be ≤ parent)
135
+ * @returns {CapabilityToken}
136
+ */
137
+ attenuate({ holder, permissions, resource, constraints, expiresAt, maxDepth }) {
138
+ if (!this.canDelegate()) {
139
+ throw new Error('Delegation depth limit reached');
140
+ }
141
+ if (!this.isValid()) {
142
+ throw new Error('Cannot attenuate an invalid token');
143
+ }
144
+
145
+ // Permissions must be a subset
146
+ const childPerms = permissions || [...this.permissions];
147
+ for (const p of childPerms) {
148
+ if (!this.permissions.includes(p)) {
149
+ throw new Error(`Cannot grant permission "${p}" not held by parent`);
150
+ }
151
+ }
152
+
153
+ // Resource must be same or narrower (prefix match)
154
+ const childResource = resource || this.resource;
155
+ if (childResource !== this.resource && !childResource.startsWith(this.resource)) {
156
+ if (!this.resource.endsWith('*')) {
157
+ // Check if parent has wildcard
158
+ const parentBase = this.resource.slice(0, -1);
159
+ if (!childResource.startsWith(parentBase)) {
160
+ throw new Error('Cannot widen resource scope beyond parent');
161
+ }
162
+ } else {
163
+ const parentBase = this.resource.slice(0, -1);
164
+ if (!childResource.startsWith(parentBase)) {
165
+ throw new Error('Cannot widen resource scope beyond parent');
166
+ }
167
+ }
168
+ }
169
+
170
+ // Expiry must be ≤ parent expiry
171
+ let childExpiry = expiresAt ?? this.expiresAt;
172
+ if (this.expiresAt !== null && childExpiry !== null && childExpiry > this.expiresAt) {
173
+ throw new Error('Cannot extend expiry beyond parent');
174
+ }
175
+
176
+ // Max depth must be ≤ parent max depth
177
+ let childMaxDepth = maxDepth ?? this.maxDepth;
178
+ if (this.maxDepth !== null && childMaxDepth !== null && childMaxDepth > this.maxDepth) {
179
+ throw new Error('Cannot extend max depth beyond parent');
180
+ }
181
+
182
+ // Merge constraints (child can only add, not remove)
183
+ const mergedConstraints = { ...this.constraints, ...constraints };
184
+
185
+ return new CapabilityToken({
186
+ issuer: this.holder,
187
+ holder,
188
+ resource: childResource,
189
+ permissions: childPerms,
190
+ constraints: mergedConstraints,
191
+ parentId: this.id,
192
+ expiresAt: childExpiry,
193
+ depth: this.depth + 1,
194
+ maxDepth: childMaxDepth,
195
+ });
196
+ }
197
+
198
+ /** Revoke this token. */
199
+ revoke() {
200
+ this.revoked = true;
201
+ }
202
+
203
+ toJSON() {
204
+ return {
205
+ id: this.id,
206
+ issuer: this.issuer,
207
+ holder: this.holder,
208
+ resource: this.resource,
209
+ permissions: [...this.permissions],
210
+ constraints: { ...this.constraints },
211
+ parentId: this.parentId,
212
+ createdAt: this.createdAt,
213
+ expiresAt: this.expiresAt,
214
+ revoked: this.revoked,
215
+ depth: this.depth,
216
+ maxDepth: this.maxDepth,
217
+ };
218
+ }
219
+
220
+ static fromJSON(data) {
221
+ return new CapabilityToken(data);
222
+ }
223
+ }
224
+
225
+ // ---------------------------------------------------------------------------
226
+ // CapabilityChain
227
+ // ---------------------------------------------------------------------------
228
+
229
+ /**
230
+ * An ordered chain of capability attenuations from root to leaf.
231
+ */
232
+ export class CapabilityChain {
233
+ /** @type {CapabilityToken[]} */
234
+ #tokens = [];
235
+
236
+ /**
237
+ * @param {CapabilityToken[]} [tokens] Initial token chain
238
+ */
239
+ constructor(tokens = []) {
240
+ for (const t of tokens) {
241
+ this.#tokens.push(t);
242
+ }
243
+ }
244
+
245
+ /** Number of tokens in the chain. */
246
+ get length() {
247
+ return this.#tokens.length;
248
+ }
249
+
250
+ /** The root (first) token. */
251
+ get root() {
252
+ return this.#tokens[0] || null;
253
+ }
254
+
255
+ /** The leaf (last) token. */
256
+ get leaf() {
257
+ return this.#tokens[this.#tokens.length - 1] || null;
258
+ }
259
+
260
+ /** Get token at index. */
261
+ at(index) {
262
+ return this.#tokens[index] || null;
263
+ }
264
+
265
+ /** Add a token to the chain. Must reference the previous token as parent. */
266
+ append(token) {
267
+ if (this.#tokens.length > 0) {
268
+ const prev = this.#tokens[this.#tokens.length - 1];
269
+ if (token.parentId !== prev.id) {
270
+ throw new Error('Token parentId must match previous token id');
271
+ }
272
+ }
273
+ this.#tokens.push(token);
274
+ }
275
+
276
+ /**
277
+ * Verify chain integrity:
278
+ * 1. Each token's parentId matches the previous token's id
279
+ * 2. Permissions only narrow (never widen)
280
+ * 3. Depth increments correctly
281
+ * 4. No expired or revoked tokens (if checkValidity)
282
+ *
283
+ * @param {boolean} [checkValidity=true]
284
+ * @returns {{ valid: boolean, error?: string, brokenAt?: number }}
285
+ */
286
+ verify(checkValidity = true) {
287
+ if (this.#tokens.length === 0) {
288
+ return { valid: false, error: 'Chain is empty' };
289
+ }
290
+
291
+ // Root must have no parent
292
+ if (this.#tokens[0].parentId !== null) {
293
+ return { valid: false, error: 'Root token must have null parentId', brokenAt: 0 };
294
+ }
295
+
296
+ for (let i = 0; i < this.#tokens.length; i++) {
297
+ const token = this.#tokens[i];
298
+
299
+ if (checkValidity && !token.isValid()) {
300
+ return { valid: false, error: `Token at index ${i} is invalid`, brokenAt: i };
301
+ }
302
+
303
+ if (i > 0) {
304
+ const prev = this.#tokens[i - 1];
305
+
306
+ if (token.parentId !== prev.id) {
307
+ return { valid: false, error: `Broken parent link at index ${i}`, brokenAt: i };
308
+ }
309
+
310
+ if (token.depth !== prev.depth + 1) {
311
+ return { valid: false, error: `Depth mismatch at index ${i}`, brokenAt: i };
312
+ }
313
+
314
+ // Permissions must be subset of parent
315
+ for (const perm of token.permissions) {
316
+ if (!prev.permissions.includes(perm)) {
317
+ return { valid: false, error: `Permission amplification at index ${i}: "${perm}"`, brokenAt: i };
318
+ }
319
+ }
320
+ }
321
+ }
322
+
323
+ return { valid: true };
324
+ }
325
+
326
+ /** Get all tokens as array. */
327
+ toArray() {
328
+ return [...this.#tokens];
329
+ }
330
+
331
+ toJSON() {
332
+ return this.#tokens.map(t => t.toJSON());
333
+ }
334
+
335
+ static fromJSON(arr) {
336
+ return new CapabilityChain(arr.map(d => CapabilityToken.fromJSON(d)));
337
+ }
338
+ }
339
+
340
+ // ---------------------------------------------------------------------------
341
+ // CapabilityValidator
342
+ // ---------------------------------------------------------------------------
343
+
344
+ /**
345
+ * Validates capability tokens against requested operations.
346
+ */
347
+ export class CapabilityValidator {
348
+ /** @type {Map<string, CapabilityToken>} */
349
+ #tokens = new Map();
350
+
351
+ /** @type {Set<string>} Revoked token IDs (including transitive) */
352
+ #revokedIds = new Set();
353
+
354
+ /**
355
+ * Register a token for validation lookups.
356
+ * @param {CapabilityToken} token
357
+ */
358
+ register(token) {
359
+ this.#tokens.set(token.id, token);
360
+ if (token.revoked) {
361
+ this.#revokedIds.add(token.id);
362
+ }
363
+ }
364
+
365
+ /**
366
+ * Revoke a token and all its descendants.
367
+ * @param {string} tokenId
368
+ */
369
+ revokeTree(tokenId) {
370
+ this.#revokedIds.add(tokenId);
371
+ const token = this.#tokens.get(tokenId);
372
+ if (token) token.revoke();
373
+
374
+ // Find and revoke all descendants
375
+ for (const [id, t] of this.#tokens) {
376
+ if (t.parentId === tokenId && !this.#revokedIds.has(id)) {
377
+ this.revokeTree(id);
378
+ }
379
+ }
380
+ }
381
+
382
+ /**
383
+ * Validate whether a token grants access to a resource + permission.
384
+ *
385
+ * @param {string} tokenId
386
+ * @param {string} resource
387
+ * @param {string} permission
388
+ * @returns {{ allowed: boolean, reason?: string }}
389
+ */
390
+ validate(tokenId, resource, permission) {
391
+ const token = this.#tokens.get(tokenId);
392
+ if (!token) {
393
+ return { allowed: false, reason: 'Token not found' };
394
+ }
395
+ if (this.#revokedIds.has(tokenId)) {
396
+ return { allowed: false, reason: 'Token revoked' };
397
+ }
398
+ if (token.isExpired()) {
399
+ return { allowed: false, reason: 'Token expired' };
400
+ }
401
+ if (!token.hasPermission(permission)) {
402
+ return { allowed: false, reason: `Permission "${permission}" not granted` };
403
+ }
404
+
405
+ // Resource match: exact or prefix (with wildcard)
406
+ if (!this._resourceMatches(token.resource, resource)) {
407
+ return { allowed: false, reason: `Resource "${resource}" not covered by "${token.resource}"` };
408
+ }
409
+
410
+ // Check max calls constraint
411
+ if (token.constraints.maxCalls !== undefined) {
412
+ const used = token.constraints._callCount || 0;
413
+ if (used >= token.constraints.maxCalls) {
414
+ return { allowed: false, reason: 'Max calls exceeded' };
415
+ }
416
+ }
417
+
418
+ return { allowed: true };
419
+ }
420
+
421
+ /**
422
+ * Check if token resource pattern matches a requested resource.
423
+ * @param {string} pattern - Token's resource (may end with *)
424
+ * @param {string} target - Requested resource
425
+ * @returns {boolean}
426
+ */
427
+ _resourceMatches(pattern, target) {
428
+ if (pattern === target) return true;
429
+ if (pattern === '*') return true;
430
+ if (pattern.endsWith('*')) {
431
+ return target.startsWith(pattern.slice(0, -1));
432
+ }
433
+ return false;
434
+ }
435
+
436
+ /** List all registered tokens. */
437
+ listTokens() {
438
+ return [...this.#tokens.values()];
439
+ }
440
+
441
+ /** Get token count. */
442
+ get size() {
443
+ return this.#tokens.size;
444
+ }
445
+
446
+ toJSON() {
447
+ return {
448
+ tokens: [...this.#tokens.values()].map(t => t.toJSON()),
449
+ revokedIds: [...this.#revokedIds],
450
+ };
451
+ }
452
+
453
+ static fromJSON(data) {
454
+ const v = new CapabilityValidator();
455
+ for (const td of data.tokens) {
456
+ v.register(CapabilityToken.fromJSON(td));
457
+ }
458
+ for (const id of data.revokedIds) {
459
+ v.#revokedIds.add(id);
460
+ }
461
+ return v;
462
+ }
463
+ }
464
+
465
+ // ---------------------------------------------------------------------------
466
+ // WasmSandboxPolicy
467
+ // ---------------------------------------------------------------------------
468
+
469
+ /** @type {readonly string[]} */
470
+ const WASM_PERMISSIONS = Object.freeze([
471
+ 'memory', // allocate memory
472
+ 'fs-read', // read filesystem
473
+ 'fs-write', // write filesystem
474
+ 'net', // network access
475
+ 'ipc', // inter-process communication
476
+ 'time', // access clock
477
+ 'random', // access RNG
478
+ ]);
479
+
480
+ /**
481
+ * Security policy governing WASM module execution.
482
+ */
483
+ export class WasmSandboxPolicy {
484
+ /**
485
+ * @param {object} opts
486
+ * @param {string} opts.name Policy name
487
+ * @param {string[]} [opts.permissions] Allowed WASM permissions
488
+ * @param {number} [opts.maxMemoryMb] Maximum memory in MB (default: 64)
489
+ * @param {number} [opts.maxCpuMs] Maximum CPU time in ms (default: 5000)
490
+ * @param {number} [opts.maxStorageMb] Maximum storage in MB (default: 10)
491
+ * @param {number} [opts.maxInstances] Max concurrent instances (default: 4)
492
+ * @param {string[]} [opts.allowedImports] Allowed host import namespaces
493
+ * @param {boolean} [opts.networkAccess] Allow network (default: false)
494
+ * @param {boolean} [opts.fsAccess] Allow filesystem (default: false)
495
+ */
496
+ constructor({
497
+ name,
498
+ permissions = ['memory', 'time', 'random'],
499
+ maxMemoryMb = 64,
500
+ maxCpuMs = 5000,
501
+ maxStorageMb = 10,
502
+ maxInstances = 4,
503
+ allowedImports = [],
504
+ networkAccess = false,
505
+ fsAccess = false,
506
+ }) {
507
+ if (!name || typeof name !== 'string') {
508
+ throw new Error('name is required and must be a non-empty string');
509
+ }
510
+ this.name = name;
511
+ this.permissions = Object.freeze([...permissions]);
512
+ this.maxMemoryMb = maxMemoryMb;
513
+ this.maxCpuMs = maxCpuMs;
514
+ this.maxStorageMb = maxStorageMb;
515
+ this.maxInstances = maxInstances;
516
+ this.allowedImports = Object.freeze([...allowedImports]);
517
+ this.networkAccess = networkAccess;
518
+ this.fsAccess = fsAccess;
519
+ }
520
+
521
+ /** Check whether a permission is allowed by this policy. */
522
+ allows(permission) {
523
+ return this.permissions.includes(permission);
524
+ }
525
+
526
+ /** Check if an import namespace is allowed. */
527
+ allowsImport(namespace) {
528
+ return this.allowedImports.includes(namespace) || this.allowedImports.includes('*');
529
+ }
530
+
531
+ /** Validate that given resource usage is within policy limits. */
532
+ checkLimits({ memoryMb = 0, cpuMs = 0, storageMb = 0, instances = 0 }) {
533
+ const violations = [];
534
+ if (memoryMb > this.maxMemoryMb) violations.push(`memory: ${memoryMb}MB > ${this.maxMemoryMb}MB`);
535
+ if (cpuMs > this.maxCpuMs) violations.push(`cpu: ${cpuMs}ms > ${this.maxCpuMs}ms`);
536
+ if (storageMb > this.maxStorageMb) violations.push(`storage: ${storageMb}MB > ${this.maxStorageMb}MB`);
537
+ if (instances > this.maxInstances) violations.push(`instances: ${instances} > ${this.maxInstances}`);
538
+ return { withinLimits: violations.length === 0, violations };
539
+ }
540
+
541
+ toJSON() {
542
+ return {
543
+ name: this.name,
544
+ permissions: [...this.permissions],
545
+ maxMemoryMb: this.maxMemoryMb,
546
+ maxCpuMs: this.maxCpuMs,
547
+ maxStorageMb: this.maxStorageMb,
548
+ maxInstances: this.maxInstances,
549
+ allowedImports: [...this.allowedImports],
550
+ networkAccess: this.networkAccess,
551
+ fsAccess: this.fsAccess,
552
+ };
553
+ }
554
+
555
+ static fromJSON(data) {
556
+ return new WasmSandboxPolicy(data);
557
+ }
558
+ }
559
+
560
+ // ---------------------------------------------------------------------------
561
+ // WasmSandbox
562
+ // ---------------------------------------------------------------------------
563
+
564
+ /** @type {readonly string[]} */
565
+ const SANDBOX_STATES = Object.freeze([
566
+ 'idle',
567
+ 'loading',
568
+ 'ready',
569
+ 'running',
570
+ 'paused',
571
+ 'terminated',
572
+ 'error',
573
+ ]);
574
+
575
+ /**
576
+ * Manages a single WASM module instance within policy constraints.
577
+ */
578
+ export class WasmSandbox {
579
+ /** @type {string} */
580
+ #id;
581
+ /** @type {WasmSandboxPolicy} */
582
+ #policy;
583
+ /** @type {string} */
584
+ #state = 'idle';
585
+ /** @type {string} */
586
+ #ownerPodId;
587
+ /** @type {{ memoryMb: number, cpuMs: number, storageMb: number }} */
588
+ #usage = { memoryMb: 0, cpuMs: 0, storageMb: 0 };
589
+ /** @type {Function[]} */
590
+ #stateListeners = [];
591
+ /** @type {string|null} */
592
+ #moduleHash = null;
593
+ /** @type {number} */
594
+ #createdAt;
595
+ /** @type {string[]} */
596
+ #logs = [];
597
+
598
+ /**
599
+ * @param {object} opts
600
+ * @param {string} [opts.id]
601
+ * @param {string} opts.ownerPodId
602
+ * @param {WasmSandboxPolicy} opts.policy
603
+ */
604
+ constructor({ id, ownerPodId, policy }) {
605
+ if (!ownerPodId || typeof ownerPodId !== 'string') {
606
+ throw new Error('ownerPodId is required and must be a non-empty string');
607
+ }
608
+ if (!policy || !(policy instanceof WasmSandboxPolicy)) {
609
+ throw new Error('policy must be a WasmSandboxPolicy instance');
610
+ }
611
+ this.#id = id || `sandbox_${Date.now()}_${++_tokenSeq}`;
612
+ this.#ownerPodId = ownerPodId;
613
+ this.#policy = policy;
614
+ this.#createdAt = Date.now();
615
+ }
616
+
617
+ get id() { return this.#id; }
618
+ get ownerPodId() { return this.#ownerPodId; }
619
+ get policy() { return this.#policy; }
620
+ get state() { return this.#state; }
621
+ get usage() { return { ...this.#usage }; }
622
+ get moduleHash() { return this.#moduleHash; }
623
+ get createdAt() { return this.#createdAt; }
624
+ get logs() { return [...this.#logs]; }
625
+
626
+ /**
627
+ * Load a WASM module (simulated — stores hash).
628
+ * @param {string} moduleHash
629
+ */
630
+ async load(moduleHash) {
631
+ if (this.#state !== 'idle') {
632
+ throw new Error(`Cannot load in state "${this.#state}"`);
633
+ }
634
+ this._setState('loading');
635
+ this.#moduleHash = moduleHash;
636
+ this._log(`Module loaded: ${moduleHash}`);
637
+ this._setState('ready');
638
+ }
639
+
640
+ /**
641
+ * Execute within the sandbox.
642
+ * @param {string} functionName
643
+ * @param {*[]} [args]
644
+ * @returns {Promise<{ result: *, cpuMs: number }>}
645
+ */
646
+ async execute(functionName, args = []) {
647
+ if (this.#state !== 'ready' && this.#state !== 'running') {
648
+ throw new Error(`Cannot execute in state "${this.#state}"`);
649
+ }
650
+ this._setState('running');
651
+
652
+ // Simulate execution with usage tracking
653
+ const cpuMs = Math.random() * 10;
654
+ this.#usage.cpuMs += cpuMs;
655
+
656
+ // Check policy limits
657
+ const { withinLimits, violations } = this.#policy.checkLimits(this.#usage);
658
+ if (!withinLimits) {
659
+ this._setState('error');
660
+ throw new Error(`Policy violation: ${violations.join(', ')}`);
661
+ }
662
+
663
+ this._log(`Executed: ${functionName}(${args.length} args) in ${cpuMs.toFixed(1)}ms`);
664
+ this._setState('ready');
665
+ return { result: null, cpuMs };
666
+ }
667
+
668
+ /** Pause execution. */
669
+ pause() {
670
+ if (this.#state !== 'running' && this.#state !== 'ready') {
671
+ throw new Error(`Cannot pause in state "${this.#state}"`);
672
+ }
673
+ this._setState('paused');
674
+ }
675
+
676
+ /** Resume from paused state. */
677
+ resume() {
678
+ if (this.#state !== 'paused') {
679
+ throw new Error(`Cannot resume in state "${this.#state}"`);
680
+ }
681
+ this._setState('ready');
682
+ }
683
+
684
+ /** Terminate the sandbox. */
685
+ terminate() {
686
+ this._log('Sandbox terminated');
687
+ this._setState('terminated');
688
+ }
689
+
690
+ /** Allocate memory (tracked against policy). */
691
+ allocateMemory(mb) {
692
+ this.#usage.memoryMb += mb;
693
+ const { withinLimits, violations } = this.#policy.checkLimits(this.#usage);
694
+ if (!withinLimits) {
695
+ this.#usage.memoryMb -= mb;
696
+ throw new Error(`Memory allocation denied: ${violations.join(', ')}`);
697
+ }
698
+ this._log(`Allocated ${mb}MB memory (total: ${this.#usage.memoryMb}MB)`);
699
+ }
700
+
701
+ /** Register a state change listener. */
702
+ onStateChange(cb) {
703
+ this.#stateListeners.push(cb);
704
+ }
705
+
706
+ /** @private */
707
+ _setState(newState) {
708
+ const old = this.#state;
709
+ this.#state = newState;
710
+ for (const cb of this.#stateListeners) cb(newState, old);
711
+ }
712
+
713
+ /** @private */
714
+ _log(msg) {
715
+ this.#logs.push(`[${new Date().toISOString()}] ${msg}`);
716
+ }
717
+
718
+ toJSON() {
719
+ return {
720
+ id: this.#id,
721
+ ownerPodId: this.#ownerPodId,
722
+ policy: this.#policy.toJSON(),
723
+ state: this.#state,
724
+ usage: { ...this.#usage },
725
+ moduleHash: this.#moduleHash,
726
+ createdAt: this.#createdAt,
727
+ };
728
+ }
729
+ }
730
+
731
+ // ---------------------------------------------------------------------------
732
+ // SandboxRegistry
733
+ // ---------------------------------------------------------------------------
734
+
735
+ /**
736
+ * Tracks active WASM sandboxes per pod, enforcing per-pod instance limits.
737
+ */
738
+ export class SandboxRegistry {
739
+ /** @type {Map<string, WasmSandbox>} id → sandbox */
740
+ #sandboxes = new Map();
741
+
742
+ /** @type {Map<string, Set<string>>} podId → Set<sandbox ids> */
743
+ #byPod = new Map();
744
+
745
+ /** @type {Function[]} */
746
+ #createListeners = [];
747
+
748
+ /** @type {Function[]} */
749
+ #terminateListeners = [];
750
+
751
+ /**
752
+ * Create and register a new sandbox.
753
+ * @param {object} opts
754
+ * @param {string} opts.ownerPodId
755
+ * @param {WasmSandboxPolicy} opts.policy
756
+ * @returns {WasmSandbox}
757
+ */
758
+ create({ ownerPodId, policy }) {
759
+ // Check per-pod instance limit
760
+ const podSandboxes = this.#byPod.get(ownerPodId);
761
+ const currentCount = podSandboxes ? podSandboxes.size : 0;
762
+ if (currentCount >= policy.maxInstances) {
763
+ throw new Error(`Instance limit reached: ${currentCount}/${policy.maxInstances}`);
764
+ }
765
+
766
+ const sandbox = new WasmSandbox({ ownerPodId, policy });
767
+ this.#sandboxes.set(sandbox.id, sandbox);
768
+
769
+ if (!this.#byPod.has(ownerPodId)) {
770
+ this.#byPod.set(ownerPodId, new Set());
771
+ }
772
+ this.#byPod.get(ownerPodId).add(sandbox.id);
773
+
774
+ for (const cb of this.#createListeners) cb(sandbox);
775
+ return sandbox;
776
+ }
777
+
778
+ /**
779
+ * Terminate and remove a sandbox.
780
+ * @param {string} sandboxId
781
+ */
782
+ terminate(sandboxId) {
783
+ const sandbox = this.#sandboxes.get(sandboxId);
784
+ if (!sandbox) {
785
+ throw new Error(`Sandbox not found: ${sandboxId}`);
786
+ }
787
+ sandbox.terminate();
788
+ this.#sandboxes.delete(sandboxId);
789
+
790
+ const podSet = this.#byPod.get(sandbox.ownerPodId);
791
+ if (podSet) {
792
+ podSet.delete(sandboxId);
793
+ if (podSet.size === 0) this.#byPod.delete(sandbox.ownerPodId);
794
+ }
795
+
796
+ for (const cb of this.#terminateListeners) cb(sandbox);
797
+ }
798
+
799
+ /** Get sandbox by ID. */
800
+ get(sandboxId) {
801
+ return this.#sandboxes.get(sandboxId) || null;
802
+ }
803
+
804
+ /** List sandboxes by pod. */
805
+ listByPod(podId) {
806
+ const ids = this.#byPod.get(podId);
807
+ if (!ids) return [];
808
+ return [...ids].map(id => this.#sandboxes.get(id)).filter(Boolean);
809
+ }
810
+
811
+ /** List all sandboxes. */
812
+ listAll() {
813
+ return [...this.#sandboxes.values()];
814
+ }
815
+
816
+ /** Total number of active sandboxes. */
817
+ get size() {
818
+ return this.#sandboxes.size;
819
+ }
820
+
821
+ /** Get stats. */
822
+ getStats() {
823
+ let totalMemoryMb = 0;
824
+ let totalCpuMs = 0;
825
+ const stateCount = {};
826
+ for (const s of this.#sandboxes.values()) {
827
+ const usage = s.usage;
828
+ totalMemoryMb += usage.memoryMb;
829
+ totalCpuMs += usage.cpuMs;
830
+ stateCount[s.state] = (stateCount[s.state] || 0) + 1;
831
+ }
832
+ return {
833
+ totalSandboxes: this.#sandboxes.size,
834
+ totalMemoryMb,
835
+ totalCpuMs,
836
+ stateCount,
837
+ podCount: this.#byPod.size,
838
+ };
839
+ }
840
+
841
+ /** Register creation listener. */
842
+ onCreate(cb) { this.#createListeners.push(cb); }
843
+
844
+ /** Register termination listener. */
845
+ onTerminate(cb) { this.#terminateListeners.push(cb); }
846
+
847
+ toJSON() {
848
+ return {
849
+ sandboxes: [...this.#sandboxes.values()].map(s => s.toJSON()),
850
+ };
851
+ }
852
+ }