@johnhenry/browsermesh-apps 0.3.0 → 0.4.1
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 +7 -2
- package/src/cloud-storage.mjs +73 -13
- package/src/index.mjs +9 -0
- package/src/marketplace.mjs +290 -26
- package/src/peer-escrow.mjs +12 -8
- package/src/quotas.mjs +311 -12
- package/src/serverless-executor-andbox.mjs +141 -0
- package/src/serverless-fetch.mjs +70 -0
- package/src/serverless-functions.mjs +67 -0
- package/src/serverless-peer-select.mjs +69 -0
- package/src/serverless-proxy.mjs +127 -0
- package/src/serverless-router.mjs +115 -0
- package/src/serverless-sites.mjs +116 -0
- package/src/serverless-static.mjs +202 -0
- package/src/serverless-wire.mjs +87 -0
package/src/quotas.mjs
CHANGED
|
@@ -1,18 +1,84 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* quotas.mjs -- Per-identity resource quotas with enforcement.
|
|
3
3
|
*
|
|
4
4
|
* Provides QuotaRule definitions, usage tracking (UsageRecord), a
|
|
5
5
|
* QuotaManager for CRUD on per-pod quota rules, and a QuotaEnforcer
|
|
6
6
|
* for recording usage, checking limits, and tracking violations.
|
|
7
7
|
*
|
|
8
|
-
*
|
|
8
|
+
* ---------------------------------------------------------------------------
|
|
9
|
+
* `QuotaEnforcer` predated this package's `MeshService` convention
|
|
10
|
+
* (`mesh-service.mjs`) and, until now, stayed purely local: no
|
|
11
|
+
* `sendTo`/`onIncomingData`/`attachService()` anywhere, used by nothing
|
|
12
|
+
* else in this package. Its observability surface was a single
|
|
13
|
+
* constructor-injected `opts.onViolation` callback (one listener only,
|
|
14
|
+
* manually wrapped in `try/catch` + `silentCatch()` to swallow a throwing
|
|
15
|
+
* listener). Modernized to use `mesh-service.mjs`'s `createEventBus()`
|
|
16
|
+
* instead: `on(event, cb)`/`onEvent(cb)` support real multi-listener
|
|
17
|
+
* fan-out and get the bus's own swallow-on-throw guarantee for free,
|
|
18
|
+
* making the old manual `silentCatch()` call dead code (removed).
|
|
19
|
+
* `opts.onViolation` is kept as constructor sugar -- it subscribes the
|
|
20
|
+
* given function to the bus as listener #1, unchanged in payload shape --
|
|
21
|
+
* since existing callers already construct enforcers this way and it's
|
|
22
|
+
* genuinely additive, not a compatibility shim for anything removed.
|
|
23
|
+
*
|
|
24
|
+
* The `QUOTA_*`/`USAGE_REPORT` constants below are `browsermesh-primitives`
|
|
25
|
+
* wire-registry codes, re-exported but never used as an `envelope.type` --
|
|
26
|
+
* `MeshService`'s `ctx.onIncomingData()` filters on a plain string, which
|
|
27
|
+
* this numeric registry is structurally incompatible with.
|
|
28
|
+
* `createQuotaReportingService()` mints its own string envelope type
|
|
29
|
+
* (`'quota-reporting'`) instead of repurposing them, matching
|
|
30
|
+
* `mesh-swarm.mjs`'s identical precedent for the same situation. They stay
|
|
31
|
+
* exactly as they are: unused as routing.
|
|
32
|
+
*
|
|
33
|
+
* ---------------------------------------------------------------------------
|
|
34
|
+
* `createQuotaReportingService()` establishes a host/authority model: any
|
|
35
|
+
* peer running it accepts `USAGE_REPORT`s from other peers and enforces
|
|
36
|
+
* quotas on their behalf, replying `QUOTA_VIOLATION` when a report trips
|
|
37
|
+
* one. Built directly on `ctx.sendTo()`/`ctx.onIncomingData()`, NOT
|
|
38
|
+
* wrapped around `mesh-rpc.mjs` -- unlike `marketplace.mjs`'s network
|
|
39
|
+
* search (genuinely request/response-shaped), a usage report has no
|
|
40
|
+
* synchronous reply worth awaiting (a violation reply is async-maybe-
|
|
41
|
+
* never), so this is a push, matching `mesh-kv.mjs`'s broadcast shape,
|
|
42
|
+
* not `mesh-rpc.mjs`'s request/response shape.
|
|
43
|
+
*
|
|
44
|
+
* **Security-relevant, non-negotiable**: the wire shape for a usage report
|
|
45
|
+
* carries no `podId` field. The authority attributes usage to the
|
|
46
|
+
* connection-authenticated `fromPubKey` unconditionally, never to a self-
|
|
47
|
+
* declared identity in a payload -- without this, a peer could frame
|
|
48
|
+
* another peer (drive its usage over quota) or evade its own quota
|
|
49
|
+
* (attribute its usage to someone else). Same class of gap `mesh-kv.mjs`'s
|
|
50
|
+
* `attribution-mismatch` check and `chunk-replication.mjs`'s write-access
|
|
51
|
+
* gate already close elsewhere in this family; treated as baseline
|
|
52
|
+
* hygiene here too, not optional ACL.
|
|
53
|
+
*
|
|
54
|
+
* **No ACL on who may act as, or report to, a quota authority.** A peer
|
|
55
|
+
* decides who to trust as its authority (whose `QUOTA_VIOLATION`/
|
|
56
|
+
* `QUOTA_UPDATE` it listens to) entirely by its own wiring choices outside
|
|
57
|
+
* this service, mirroring `mesh-rpc.mjs`/`mesh-websocket.mjs`'s own
|
|
58
|
+
* explicit "authorization is the handler's job, not the transport's"
|
|
59
|
+
* stance. An authority accepts `USAGE_REPORT`s from any peer that can
|
|
60
|
+
* reach it; unknown senders fall back to `QuotaManager`'s existing
|
|
61
|
+
* `DEFAULT_LIMITS`, not to unlimited enforcement.
|
|
9
62
|
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
63
|
+
* **`quota-update` never self-applies to a receiving peer's own local
|
|
64
|
+
* `QuotaManager`.** Delivered as a notification event only
|
|
65
|
+
* (`quota:rule-update-received`); a caller that wants to actually trust a
|
|
66
|
+
* given authority's pushed rule changes must opt in explicitly at the
|
|
67
|
+
* call site (e.g. `meshQuotaEnforcer.on('quota:rule-update-received', rule
|
|
68
|
+
* => { if (trusted(rule)) manager.setQuota(...) })`). This is the one
|
|
69
|
+
* place a remote peer could otherwise silently mutate local enforcement
|
|
70
|
+
* state, and it stays closed by design, not by a forgettable check.
|
|
71
|
+
*
|
|
72
|
+
* `MeshQuotaEnforcer` is the ergonomic wrapper -- the same two-layer split
|
|
73
|
+
* `mesh-kv.mjs`/`marketplace.mjs`'s `MeshMarketplace` already established.
|
|
74
|
+
* `QuotaEnforcer`/`QuotaManager` never gain a `PeerNode` reference; only
|
|
75
|
+
* `MeshQuotaEnforcer` does.
|
|
76
|
+
*
|
|
77
|
+
* No browser-only imports at module level.
|
|
12
78
|
*/
|
|
13
79
|
|
|
14
80
|
import { MESH_TYPE } from '@johnhenry/browsermesh-primitives';
|
|
15
|
-
import {
|
|
81
|
+
import { createEventBus, attachService } from './mesh-service.mjs';
|
|
16
82
|
|
|
17
83
|
// ---------------------------------------------------------------------------
|
|
18
84
|
// Wire constants — imported from canonical registry
|
|
@@ -383,17 +449,19 @@ export class QuotaEnforcer {
|
|
|
383
449
|
/** @type {Array<{podId: string, resource: string, limit: number, actual: number, policy: string, timestamp: number}>} */
|
|
384
450
|
#violations = [];
|
|
385
451
|
|
|
386
|
-
/** @type {
|
|
387
|
-
#
|
|
452
|
+
/** @type {import('./mesh-service.mjs').EventBus} */
|
|
453
|
+
#events = createEventBus();
|
|
388
454
|
|
|
389
455
|
/**
|
|
390
456
|
* @param {QuotaManager} quotaManager
|
|
391
457
|
* @param {object} [opts]
|
|
392
|
-
* @param {Function} [opts.onViolation] -
|
|
458
|
+
* @param {Function} [opts.onViolation] - Sugar for `on('quota:violation-detected', onViolation)`; called with violation info on limit breach.
|
|
393
459
|
*/
|
|
394
460
|
constructor(quotaManager, opts = {}) {
|
|
395
461
|
this.#manager = quotaManager;
|
|
396
|
-
|
|
462
|
+
if (typeof opts.onViolation === 'function') {
|
|
463
|
+
this.#events.on('quota:violation-detected', opts.onViolation);
|
|
464
|
+
}
|
|
397
465
|
}
|
|
398
466
|
|
|
399
467
|
// -- Usage key helpers ----------------------------------------------------
|
|
@@ -455,9 +523,7 @@ export class QuotaEnforcer {
|
|
|
455
523
|
timestamp: Date.now(),
|
|
456
524
|
};
|
|
457
525
|
this.#violations.push(violation);
|
|
458
|
-
|
|
459
|
-
try { this.#onViolation(violation); } catch (e) { silentCatch('clawser-mesh-quotas', 'swallow-listener-errors', e) }
|
|
460
|
-
}
|
|
526
|
+
this.#events.emit('quota:violation-detected', violation);
|
|
461
527
|
}
|
|
462
528
|
}
|
|
463
529
|
|
|
@@ -541,6 +607,30 @@ export class QuotaEnforcer {
|
|
|
541
607
|
this.#usage.delete(key);
|
|
542
608
|
}
|
|
543
609
|
|
|
610
|
+
// -- Observability ----------------------------------------------------------
|
|
611
|
+
|
|
612
|
+
/**
|
|
613
|
+
* Subscribe to exactly one event name -- currently only
|
|
614
|
+
* `'quota:violation-detected'` (data: `{podId, resource, limit, actual,
|
|
615
|
+
* policy, timestamp}`, the same shape the old constructor-only
|
|
616
|
+
* `onViolation` callback received).
|
|
617
|
+
* @param {string} event
|
|
618
|
+
* @param {(data: object, event: string) => void} cb
|
|
619
|
+
* @returns {() => void} unsubscribe
|
|
620
|
+
*/
|
|
621
|
+
on(event, cb) {
|
|
622
|
+
return this.#events.on(event, cb);
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/**
|
|
626
|
+
* Subscribe to every `quota:*` event this enforcer emits, regardless of name.
|
|
627
|
+
* @param {(event: string, data: object) => void} cb
|
|
628
|
+
* @returns {() => void} unsubscribe
|
|
629
|
+
*/
|
|
630
|
+
onEvent(cb) {
|
|
631
|
+
return this.#events.onEvent(cb);
|
|
632
|
+
}
|
|
633
|
+
|
|
544
634
|
// -- Violations -----------------------------------------------------------
|
|
545
635
|
|
|
546
636
|
/**
|
|
@@ -619,3 +709,212 @@ export class QuotaEnforcer {
|
|
|
619
709
|
return enforcer;
|
|
620
710
|
}
|
|
621
711
|
}
|
|
712
|
+
|
|
713
|
+
// ---------------------------------------------------------------------------
|
|
714
|
+
// Quota network reporting
|
|
715
|
+
// ---------------------------------------------------------------------------
|
|
716
|
+
|
|
717
|
+
/** Default `envelope.type` for a quota authority's mesh attach -- see module doc comment. */
|
|
718
|
+
export const DEFAULT_QUOTA_ENVELOPE_TYPE = 'quota-reporting';
|
|
719
|
+
|
|
720
|
+
/**
|
|
721
|
+
* Build a `MeshService` descriptor (`mesh-service.mjs`) implementing the
|
|
722
|
+
* host/authority side of cross-peer usage reporting -- see module doc
|
|
723
|
+
* comment for the full wire-protocol/security writeup (attribution via
|
|
724
|
+
* `fromPubKey`, no ACL on who may report, `quota-update` never self-
|
|
725
|
+
* applying).
|
|
726
|
+
*
|
|
727
|
+
* @param {object} opts
|
|
728
|
+
* @param {QuotaEnforcer} opts.enforcer
|
|
729
|
+
* @param {string} [opts.envelopeType='quota-reporting']
|
|
730
|
+
* @param {Function} [opts.onLog]
|
|
731
|
+
* @returns {import('./mesh-service.mjs').MeshService}
|
|
732
|
+
*/
|
|
733
|
+
export function createQuotaReportingService({ enforcer, envelopeType = DEFAULT_QUOTA_ENVELOPE_TYPE, onLog } = {}) {
|
|
734
|
+
if (!enforcer || typeof enforcer.recordUsage !== 'function') {
|
|
735
|
+
throw new Error('createQuotaReportingService: opts.enforcer (a QuotaEnforcer instance) is required');
|
|
736
|
+
}
|
|
737
|
+
const log = onLog || (() => {});
|
|
738
|
+
|
|
739
|
+
return {
|
|
740
|
+
name: 'quota-reporting',
|
|
741
|
+
|
|
742
|
+
attach(peerNode, ctx) {
|
|
743
|
+
/** @param {string} fromPubKey @param {{resource: string, amount: number}} msg */
|
|
744
|
+
async function handleUsageReport(fromPubKey, msg) {
|
|
745
|
+
const { resource, amount } = msg;
|
|
746
|
+
|
|
747
|
+
// recordUsage() emits 'quota:violation-detected' synchronously
|
|
748
|
+
// (before returning) if -- and only if -- THIS call trips a
|
|
749
|
+
// violation, so a temporary listener scoped tightly around the
|
|
750
|
+
// call captures exactly that outcome, deterministically, with no
|
|
751
|
+
// timestamp heuristics or races against concurrent reports.
|
|
752
|
+
let triggeredViolation = null;
|
|
753
|
+
const unsubscribeOnce = enforcer.on('quota:violation-detected', (v) => {
|
|
754
|
+
triggeredViolation = v;
|
|
755
|
+
});
|
|
756
|
+
try {
|
|
757
|
+
// Attribution: always the connection-authenticated sender, never
|
|
758
|
+
// a self-declared identity in the payload -- see module doc
|
|
759
|
+
// comment's "Security-relevant, non-negotiable" section.
|
|
760
|
+
enforcer.recordUsage(fromPubKey, resource, amount);
|
|
761
|
+
} finally {
|
|
762
|
+
unsubscribeOnce();
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
ctx.emit('quota:usage-report-received', { from: fromPubKey, resource, amount });
|
|
766
|
+
|
|
767
|
+
if (triggeredViolation) {
|
|
768
|
+
try {
|
|
769
|
+
await ctx.sendTo(fromPubKey, envelopeType, { kind: 'quota-violation', violation: triggeredViolation });
|
|
770
|
+
} catch (err) {
|
|
771
|
+
log('quota-reporting:violation-send-failed', { to: fromPubKey, error: err?.message || String(err) });
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
const unsubscribe = ctx.onIncomingData(envelopeType, (fromPubKey, msg) => {
|
|
777
|
+
if (!msg || typeof msg.kind !== 'string') return;
|
|
778
|
+
if (msg.kind === 'usage-report') {
|
|
779
|
+
handleUsageReport(fromPubKey, msg).catch((err) => {
|
|
780
|
+
log('quota-reporting:usage-report-handling-failed', { from: fromPubKey, error: err?.message || String(err) });
|
|
781
|
+
});
|
|
782
|
+
} else if (msg.kind === 'quota-violation') {
|
|
783
|
+
ctx.emit('quota:violation-notified', { from: fromPubKey, violation: msg.violation });
|
|
784
|
+
} else if (msg.kind === 'quota-update') {
|
|
785
|
+
// Informational only -- never self-applies to this peer's own
|
|
786
|
+
// QuotaManager. See module doc comment.
|
|
787
|
+
ctx.emit('quota:rule-update-received', { from: fromPubKey, rule: msg.rule });
|
|
788
|
+
}
|
|
789
|
+
});
|
|
790
|
+
|
|
791
|
+
/**
|
|
792
|
+
* Report this peer's own usage to a remote quota authority.
|
|
793
|
+
* Fire-and-forget: does not await a reply, since the only possible
|
|
794
|
+
* reply (a `quota-violation`) is async-maybe-never, not a
|
|
795
|
+
* synchronous ack -- see module doc comment.
|
|
796
|
+
* @param {string} authorityPodId
|
|
797
|
+
* @param {string} resource
|
|
798
|
+
* @param {number} amount
|
|
799
|
+
*/
|
|
800
|
+
async function reportUsage(authorityPodId, resource, amount) {
|
|
801
|
+
await ctx.sendTo(authorityPodId, envelopeType, { kind: 'usage-report', resource, amount });
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
/**
|
|
805
|
+
* Push a `QuotaRule` change to a specific peer as a notification --
|
|
806
|
+
* the receiving side never self-applies it (see module doc comment).
|
|
807
|
+
* @param {string} peerId
|
|
808
|
+
* @param {QuotaRule} rule
|
|
809
|
+
*/
|
|
810
|
+
async function pushQuotaUpdate(peerId, rule) {
|
|
811
|
+
await ctx.sendTo(peerId, envelopeType, { kind: 'quota-update', rule: rule.toJSON ? rule.toJSON() : rule });
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
return {
|
|
815
|
+
api: { reportUsage, pushQuotaUpdate },
|
|
816
|
+
teardown() {
|
|
817
|
+
unsubscribe();
|
|
818
|
+
},
|
|
819
|
+
};
|
|
820
|
+
},
|
|
821
|
+
};
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
/**
|
|
825
|
+
* Ergonomic wrapper composing a `QuotaEnforcer` with
|
|
826
|
+
* `createQuotaReportingService()` -- the same two-layer split `mesh-kv.mjs`/
|
|
827
|
+
* `marketplace.mjs`'s `MeshMarketplace` already established:
|
|
828
|
+
* `QuotaEnforcer`/`QuotaManager` never gain a `PeerNode` reference, only
|
|
829
|
+
* `MeshQuotaEnforcer` does.
|
|
830
|
+
*/
|
|
831
|
+
export class MeshQuotaEnforcer {
|
|
832
|
+
/** @type {QuotaManager} */
|
|
833
|
+
#manager;
|
|
834
|
+
/** @type {QuotaEnforcer} */
|
|
835
|
+
#enforcer;
|
|
836
|
+
/** @type {ReturnType<import('./mesh-service.mjs').attachService>} */
|
|
837
|
+
#handle;
|
|
838
|
+
/** @type {import('./mesh-service.mjs').EventBus} */
|
|
839
|
+
#events = createEventBus();
|
|
840
|
+
/** @type {() => void} */
|
|
841
|
+
#unsubscribeEnforcerEvents;
|
|
842
|
+
/** @type {() => void} */
|
|
843
|
+
#unsubscribeServiceEvents;
|
|
844
|
+
|
|
845
|
+
/**
|
|
846
|
+
* @param {object} opts
|
|
847
|
+
* @param {import('./peer-node.mjs').PeerNode} opts.node - duck-typed: needs `podId`.
|
|
848
|
+
* @param {import('@johnhenry/browsermesh-netway').VirtualNetwork} [opts.network] - unused today, accepted for forward compatibility with `attachService()`'s own signature.
|
|
849
|
+
* @param {QuotaManager} [opts.manager] - defaults to a fresh `new QuotaManager()`.
|
|
850
|
+
* @param {QuotaEnforcer} [opts.enforcer] - defaults to a fresh `new QuotaEnforcer(manager)`.
|
|
851
|
+
* @param {string} [opts.envelopeType]
|
|
852
|
+
* @param {Function} [opts.onLog]
|
|
853
|
+
*/
|
|
854
|
+
constructor({ node, network, manager, enforcer, envelopeType, onLog } = {}) {
|
|
855
|
+
if (!node || typeof node.podId !== 'string') {
|
|
856
|
+
throw new Error('MeshQuotaEnforcer: opts.node (a PeerNode-like object with a podId) is required');
|
|
857
|
+
}
|
|
858
|
+
this.#manager = manager ?? new QuotaManager();
|
|
859
|
+
this.#enforcer = enforcer ?? new QuotaEnforcer(this.#manager);
|
|
860
|
+
this.#handle = attachService(node, network, createQuotaReportingService({
|
|
861
|
+
enforcer: this.#enforcer,
|
|
862
|
+
envelopeType,
|
|
863
|
+
onLog,
|
|
864
|
+
}));
|
|
865
|
+
// Two independent sources forward onto this class's own bus: the
|
|
866
|
+
// enforcer's own local 'quota:violation-detected' (fired by
|
|
867
|
+
// recordUsage() itself, whether called locally or via an inbound
|
|
868
|
+
// usage-report), and the network service's own ctx.emit()'d events
|
|
869
|
+
// ('quota:usage-report-received'/'quota:violation-notified'/
|
|
870
|
+
// 'quota:rule-update-received') -- same forwarding convention
|
|
871
|
+
// MeshMarketplace/MeshKv use, just two emitters instead of one since
|
|
872
|
+
// this phase's own service has events the composed local class does not.
|
|
873
|
+
this.#unsubscribeEnforcerEvents = this.#enforcer.onEvent((event, data) => this.#events.emit(event, data));
|
|
874
|
+
this.#unsubscribeServiceEvents = this.#handle.onEvent((event, data) => this.#events.emit(event, data));
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
/** @returns {QuotaManager} */
|
|
878
|
+
get manager() { return this.#manager; }
|
|
879
|
+
|
|
880
|
+
/** @returns {QuotaEnforcer} */
|
|
881
|
+
get enforcer() { return this.#enforcer; }
|
|
882
|
+
|
|
883
|
+
// -- Local pass-throughs (delegate to the composed QuotaEnforcer) --------
|
|
884
|
+
|
|
885
|
+
recordUsage(podId, resource, amount) { return this.#enforcer.recordUsage(podId, resource, amount); }
|
|
886
|
+
checkQuota(podId, resource, requestedAmount) { return this.#enforcer.checkQuota(podId, resource, requestedAmount); }
|
|
887
|
+
listViolations(podId) { return this.#enforcer.listViolations(podId); }
|
|
888
|
+
|
|
889
|
+
/**
|
|
890
|
+
* @param {string} authorityPodId
|
|
891
|
+
* @param {string} resource
|
|
892
|
+
* @param {number} amount
|
|
893
|
+
*/
|
|
894
|
+
async reportUsage(authorityPodId, resource, amount) {
|
|
895
|
+
return this.#handle.api.reportUsage(authorityPodId, resource, amount);
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
/**
|
|
899
|
+
* Push a `QuotaRule` change to a specific peer as a notification -- the
|
|
900
|
+
* receiving side never self-applies it. See module doc comment.
|
|
901
|
+
* @param {string} peerId
|
|
902
|
+
* @param {QuotaRule} rule
|
|
903
|
+
*/
|
|
904
|
+
async pushQuotaUpdate(peerId, rule) {
|
|
905
|
+
return this.#handle.api.pushQuotaUpdate(peerId, rule);
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
// -- Observability (forwards the enforcer's events, plus this phase's own) --
|
|
909
|
+
|
|
910
|
+
on(event, cb) { return this.#events.on(event, cb); }
|
|
911
|
+
onEvent(cb) { return this.#events.onEvent(cb); }
|
|
912
|
+
|
|
913
|
+
/** Tears down the composed network service and stops event forwarding. */
|
|
914
|
+
async close() {
|
|
915
|
+
this.#unsubscribeEnforcerEvents();
|
|
916
|
+
this.#unsubscribeServiceEvents();
|
|
917
|
+
await this.#handle.teardown();
|
|
918
|
+
this.#events.closeAll();
|
|
919
|
+
}
|
|
920
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* serverless-executor-andbox.mjs -- Phase 3 of the BrowserMesh Serverless
|
|
3
|
+
* plan (`/Users/johnhenry/.claude/plans/at-some-point-within-joyful-dove.md`):
|
|
4
|
+
* the light/default function-execution backend, built on `@johnhenry/andbox`'s
|
|
5
|
+
* Worker-isolated JS runtime.
|
|
6
|
+
*
|
|
7
|
+
* ---------------------------------------------------------------------------
|
|
8
|
+
* ANDBOX IS NOT AN ADVERSARIAL-CODE SANDBOX -- restated here because it is
|
|
9
|
+
* the single most important fact about this file (andbox's own README
|
|
10
|
+
* "Security model" section, and this repo's own research confirms every
|
|
11
|
+
* item below is still live in the version this file depends on):
|
|
12
|
+
*
|
|
13
|
+
* - Worker-global `fetch`/`WebSocket`/`Worker`/`importScripts` are
|
|
14
|
+
* reachable by sandboxed code DIRECTLY, regardless of what
|
|
15
|
+
* `opts.capabilities` are granted -- omitting a `fetch` capability
|
|
16
|
+
* does not block network access.
|
|
17
|
+
* - `sandboxImport()` loads any bare `http(s)://` URL unchecked, with no
|
|
18
|
+
* allowlist, independent of any capability/network policy.
|
|
19
|
+
* - A capability call still in flight when a timeout fires still
|
|
20
|
+
* completes its host-side side effect even though the caller is told
|
|
21
|
+
* the invocation failed -- capabilities passed via `opts.capabilities`
|
|
22
|
+
* must be idempotent and/or cancellable, this file does no plumbing to
|
|
23
|
+
* help with that.
|
|
24
|
+
*
|
|
25
|
+
* This tier is appropriate for functions written by a site's own operator
|
|
26
|
+
* or trusted collaborators -- NEVER for running arbitrary third-party or
|
|
27
|
+
* user-submitted code. `serverless-executor-wasmsandbox.mjs` (Phase 6) adds
|
|
28
|
+
* a CPU/memory/instance BUDGET on top of this same trust boundary, not a
|
|
29
|
+
* stronger one -- see that file's own module doc comment when it exists.
|
|
30
|
+
*
|
|
31
|
+
* ---------------------------------------------------------------------------
|
|
32
|
+
* MANDATORY: ONE FRESH SANDBOX PER INVOCATION, NEVER POOLED OR REUSED
|
|
33
|
+
* ACROSS CONCURRENT CALLS.
|
|
34
|
+
*
|
|
35
|
+
* Confirmed by reading andbox's `sandbox.mjs`/`worker-source.mjs` directly:
|
|
36
|
+
* concurrent `evaluate()` calls on ONE sandbox instance share a single
|
|
37
|
+
* Worker realm (no per-call state isolation -- a global mutated by one
|
|
38
|
+
* call leaks into another), and a timeout on one call hard-kills
|
|
39
|
+
* (`worker.terminate()`) the shared worker out from under every OTHER
|
|
40
|
+
* concurrently in-flight call on that instance, which then gets
|
|
41
|
+
* misreported as *its own* timeout, not the real cause. Traced end-to-end
|
|
42
|
+
* through `mesh-service.mjs`'s dispatch loop: inbound `mesh-rpc` requests
|
|
43
|
+
* are handled concurrently, not serialized (`ctx.onIncomingData()`'s
|
|
44
|
+
* callback is fire-and-forget, never awaited before the next message is
|
|
45
|
+
* processed) -- so a shared/pooled sandbox instance would be a real,
|
|
46
|
+
* reachable failure mode, not a hypothetical one. `createAndboxExecutor()`
|
|
47
|
+
* therefore creates a brand-new `createSandbox()` instance inside every
|
|
48
|
+
* call to the returned `executor(job)`, disposed in a `finally`, and
|
|
49
|
+
* NEVER stores one across calls.
|
|
50
|
+
*
|
|
51
|
+
* ---------------------------------------------------------------------------
|
|
52
|
+
* TEST COVERAGE GAP, STATED PLAINLY (do not silently assume this is
|
|
53
|
+
* covered): andbox's own `mode: 'worker'` requires the browser `Worker`
|
|
54
|
+
* global (`new Worker(...)` + `Blob`/`URL.createObjectURL`), which does not
|
|
55
|
+
* exist in plain Node (`node:worker_threads`' `Worker` is a different,
|
|
56
|
+
* incompatible API) -- confirmed directly in this repo's own Node 24 test
|
|
57
|
+
* environment. This file's own test suite can therefore only exercise the
|
|
58
|
+
* REQUEST-SHAPING logic (job construction, preamble injection, dispose-on-
|
|
59
|
+
* error bookkeeping) using `mode: 'inline'`/mocks, not real Worker
|
|
60
|
+
* isolation or the real hard-kill-on-timeout/collateral-damage behavior
|
|
61
|
+
* described above. andbox's own upstream test suite has this exact same
|
|
62
|
+
* gap (its only timeout example runs under Node, exercising the weaker
|
|
63
|
+
* inline-mode Promise-race timeout, never a real Worker hard-kill). A real
|
|
64
|
+
* concurrency regression test (two overlapping requests, one deliberately
|
|
65
|
+
* runaway, assert the other's result is unaffected) needs an actual
|
|
66
|
+
* browser test environment and is intentionally NOT claimed as covered
|
|
67
|
+
* here.
|
|
68
|
+
*
|
|
69
|
+
* ---------------------------------------------------------------------------
|
|
70
|
+
* REQUEST DATA IS INJECTED VIA A JSON PREAMBLE, NOT A CAPABILITY.
|
|
71
|
+
*
|
|
72
|
+
* `actually-serverless`'s own `createFunctionHandler.mjs` takes a `preamble`
|
|
73
|
+
* string prepended to the function source before evaluation -- the same
|
|
74
|
+
* pattern used here: `job.request` (the inbound `{fromPubKey, method, path,
|
|
75
|
+
* headers, body}`) is JSON-serialized into a `const request = ...;`
|
|
76
|
+
* preamble prepended to `job.code` before `sandbox.evaluate()`, so function
|
|
77
|
+
* code can reference a `request` variable directly. This is plain,
|
|
78
|
+
* already-known data, not a live host capability -- no RPC round-trip
|
|
79
|
+
* needed for it, unlike genuine host capabilities (KV access, peer calls)
|
|
80
|
+
* a caller passes via `opts.capabilities`.
|
|
81
|
+
*
|
|
82
|
+
* ---------------------------------------------------------------------------
|
|
83
|
+
* `@johnhenry/andbox` IS IMPORTED LAZILY (inside the returned executor, not
|
|
84
|
+
* at module top level), unlike this package's other optional peer
|
|
85
|
+
* dependencies. Every other optional peer here (`browsermesh-core`,
|
|
86
|
+
* `browsermesh-discovery`, ...) is a SIBLING package in this same npm
|
|
87
|
+
* workspace, so it's always physically present in `node_modules` during
|
|
88
|
+
* this monorepo's own `npm install`/CI regardless of the "optional" marking
|
|
89
|
+
* -- that marking only matters for a standalone external consumer.
|
|
90
|
+
* `@johnhenry/andbox` is a genuinely separate repo/package, not a workspace
|
|
91
|
+
* sibling, and is declared as an OPTIONAL peer dependency
|
|
92
|
+
* (`peerDependenciesMeta`), so npm never attempts to install it
|
|
93
|
+
* automatically for anyone -- present only for a consumer that explicitly
|
|
94
|
+
* installs it themselves. (It's been published to npm since 0.0.1; that was
|
|
95
|
+
* never what made this lazy -- the optional-peer marking is what matters,
|
|
96
|
+
* and that hasn't changed.) A static top-level import here would make
|
|
97
|
+
* `index.mjs`'s eager `export *` chain fail for the ENTIRE package the
|
|
98
|
+
* moment `@johnhenry/andbox` is absent, breaking every consumer/test, not
|
|
99
|
+
* just ones using this specific executor. A dynamic `import()` inside the
|
|
100
|
+
* executor defers that requirement to "only if this specific executor is
|
|
101
|
+
* actually invoked."
|
|
102
|
+
*
|
|
103
|
+
* @module serverless-executor-andbox
|
|
104
|
+
*/
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* @typedef {object} AndboxJob
|
|
108
|
+
* @property {string} code - function source, evaluated as the body of an async IIFE (andbox's own `evaluate()` semantics -- top-level `return`/`await` both work).
|
|
109
|
+
* @property {object} [request] - the inbound request, JSON-injected as a `request` const in scope for `code`. See module doc comment.
|
|
110
|
+
* @property {number} [timeoutMs] - per-invocation override of `opts.defaultTimeoutMs`.
|
|
111
|
+
*/
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* @param {object} [opts]
|
|
115
|
+
* @param {Record<string, Function>} [opts.capabilities] - forwarded to andbox `createSandbox()` as-is. See module doc comment's security-model section before granting anything here.
|
|
116
|
+
* @param {object} [opts.importMap] - forwarded to andbox `createSandbox()` as-is.
|
|
117
|
+
* @param {number} [opts.defaultTimeoutMs] - forwarded to andbox `createSandbox()` as its `defaultTimeoutMs`; per-job `timeoutMs` overrides this for that one `evaluate()` call.
|
|
118
|
+
* @returns {(job: AndboxJob) => Promise<*>} the executor -- one fresh sandbox per call, always disposed. Rejects if the sandboxed code throws, times out (andbox's own `TimeoutError`), or is aborted.
|
|
119
|
+
*/
|
|
120
|
+
export function createAndboxExecutor({ capabilities, importMap, defaultTimeoutMs } = {}) {
|
|
121
|
+
return async function executeAndbox(job) {
|
|
122
|
+
if (!job || typeof job.code !== 'string') {
|
|
123
|
+
throw new Error('createAndboxExecutor: job.code is required and must be a string')
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const preamble = job.request !== undefined ? `const request = ${JSON.stringify(job.request)};\n` : ''
|
|
127
|
+
|
|
128
|
+
// Lazy import -- see module doc comment for why this isn't a top-level
|
|
129
|
+
// static import.
|
|
130
|
+
const { createSandbox } = await import('@johnhenry/andbox')
|
|
131
|
+
|
|
132
|
+
// See module doc comment: MANDATORY fresh sandbox per invocation, never
|
|
133
|
+
// shared across concurrent calls.
|
|
134
|
+
const sandbox = await createSandbox({ mode: 'worker', capabilities, importMap, defaultTimeoutMs })
|
|
135
|
+
try {
|
|
136
|
+
return await sandbox.evaluate(preamble + job.code, job.timeoutMs !== undefined ? { timeout: job.timeoutMs } : undefined)
|
|
137
|
+
} finally {
|
|
138
|
+
await sandbox.dispose()
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* serverless-fetch.mjs -- Phase 2 of the BrowserMesh Serverless plan
|
|
3
|
+
* (`/Users/johnhenry/.claude/plans/at-some-point-within-joyful-dove.md`):
|
|
4
|
+
* the Service-Worker-facing half of site routing, finally giving
|
|
5
|
+
* `@johnhenry/browsermesh-discovery`'s `sw-routing.mjs` its first real
|
|
6
|
+
* caller (its own module doc comment has said "no wired caller of its own
|
|
7
|
+
* yet" since it was written).
|
|
8
|
+
*
|
|
9
|
+
* ---------------------------------------------------------------------------
|
|
10
|
+
* SITE-NAME REINTERPRETATION OF `parseMeshRequest()`'s `podId` TOKEN (see
|
|
11
|
+
* the plan doc's "Design decisions" section, restated here because it's a
|
|
12
|
+
* real, deliberate semantic overload of shared code, not something a future
|
|
13
|
+
* reader should have to reverse-engineer from two disagreeing call sites):
|
|
14
|
+
*
|
|
15
|
+
* `parseMeshRequest(urlStr)` (`mesh://X/path`, `https://X.mesh.local/path`)
|
|
16
|
+
* extracts a token it calls `podId`. `mesh-fetch.mjs`'s `browserMeshFetch()`
|
|
17
|
+
* uses that token AS a literal podId, addressing one specific peer
|
|
18
|
+
* directly. This file instead treats the SAME token as a logical site name
|
|
19
|
+
* first -- resolved via `opts.resolveSite(siteName) -> podId|null` -- and
|
|
20
|
+
* only falls back to treating it as a literal podId if `resolveSite`
|
|
21
|
+
* returns nothing. This is backward compatible (an unregistered token still
|
|
22
|
+
* behaves exactly like `mesh-fetch.mjs`'s direct-podId addressing), but it
|
|
23
|
+
* IS a real reinterpretation: two call sites in this repo now disagree
|
|
24
|
+
* about what that token conceptually means, unified only by "falls back to
|
|
25
|
+
* a literal podId either way."
|
|
26
|
+
*
|
|
27
|
+
* `opts.resolveSite` is optional. Omitting it makes this file behave
|
|
28
|
+
* identically to a single-peer-per-site deployment addressed by literal
|
|
29
|
+
* podId, which is a completely valid, already-useful configuration on its
|
|
30
|
+
* own. For multi-peer sites, pass `siteRegistry.selectPeer.bind(siteRegistry)`
|
|
31
|
+
* (`serverless-sites.mjs`'s `SiteRegistry`, Phase 5) directly -- its
|
|
32
|
+
* `selectPeer(siteId) -> podId|null` signature already matches this
|
|
33
|
+
* option's shape exactly, no adapter needed.
|
|
34
|
+
*
|
|
35
|
+
* @module serverless-fetch
|
|
36
|
+
*/
|
|
37
|
+
|
|
38
|
+
import { MeshFetchRouter } from '@johnhenry/browsermesh-discovery'
|
|
39
|
+
import { decodeWireResponse } from './serverless-wire.mjs'
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @param {{request: (podId: string, req: {method?: string, path?: string, headers?: object, body?: *}) => Promise<{status: number, headers: object, body: *}>}} meshRpcApi
|
|
43
|
+
* The `.api` returned by attaching a `mesh-rpc.mjs`-based service bound to
|
|
44
|
+
* the SAME envelope type a site's `createSiteMeshRpcService()`
|
|
45
|
+
* (`serverless-router.mjs`) was attached with on the responding side --
|
|
46
|
+
* typically a second, dedicated `createMeshRpcService({envelopeType:
|
|
47
|
+
* 'mesh-serverless'})` attach on the requesting peer, distinct from any
|
|
48
|
+
* general-purpose `mesh-rpc` service that peer might also run.
|
|
49
|
+
* @param {object} [opts]
|
|
50
|
+
* @param {(siteOrPodId: string) => (string|null|undefined)} [opts.resolveSite]
|
|
51
|
+
* Optional. Resolves the `parseMeshRequest()`-extracted token to a target
|
|
52
|
+
* podId. Omit for direct single-peer-per-site addressing (the token is
|
|
53
|
+
* used as a literal podId). `serverless-sites.mjs`'s `SiteRegistry#selectPeer()`
|
|
54
|
+
* (Phase 5) matches this shape exactly and can be passed here directly.
|
|
55
|
+
* @returns {import('@johnhenry/browsermesh-discovery').MeshFetchRouter}
|
|
56
|
+
*/
|
|
57
|
+
export function createServerlessFetchRouter(meshRpcApi, { resolveSite } = {}) {
|
|
58
|
+
if (!meshRpcApi || typeof meshRpcApi.request !== 'function') {
|
|
59
|
+
throw new Error('createServerlessFetchRouter: meshRpcApi (a mesh-rpc.mjs service api with .request()) is required')
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return new MeshFetchRouter({
|
|
63
|
+
onRpc: async ({ podId: siteOrPodId, method, path, headers, body }) => {
|
|
64
|
+
const resolved = typeof resolveSite === 'function' ? resolveSite(siteOrPodId) : null
|
|
65
|
+
const targetPodId = resolved || siteOrPodId
|
|
66
|
+
const res = await meshRpcApi.request(targetPodId, { method, path, headers, body })
|
|
67
|
+
return decodeWireResponse(res)
|
|
68
|
+
},
|
|
69
|
+
})
|
|
70
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* serverless-functions.mjs -- Phase 3 of the BrowserMesh Serverless plan
|
|
3
|
+
* (`/Users/johnhenry/.claude/plans/at-some-point-within-joyful-dove.md`):
|
|
4
|
+
* the backend-agnostic route matcher that adapts a pluggable `executor`
|
|
5
|
+
* (`serverless-executor-andbox.mjs`'s light tier, or Phase 6's
|
|
6
|
+
* `serverless-executor-wasmsandbox.mjs` heavier tier) into
|
|
7
|
+
* `serverless-router.mjs`'s `functionsHandler` slot.
|
|
8
|
+
*
|
|
9
|
+
* Kept deliberately separate from any specific executor: swapping which
|
|
10
|
+
* backend a site uses (`'andbox'` vs `'wasmsandbox'`, per the plan's design
|
|
11
|
+
* decision) is a config choice on `createFunctionsHandler({executor})`, not
|
|
12
|
+
* a change to route matching or request/response shaping.
|
|
13
|
+
*
|
|
14
|
+
* @module serverless-functions
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @typedef {object} FunctionRoute
|
|
19
|
+
* @property {string} path - exact path to match (e.g. `'/api/hello'`). No pattern/param matching in v1 -- exact string match only, mirroring `createStaticHandler()`'s own "built fresh, no premature generality" scope.
|
|
20
|
+
* @property {string} [method='GET']
|
|
21
|
+
* @property {string} code - function source handed to the executor's `job.code`.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* If the sandboxed code's return value is already response-shaped (a plain
|
|
26
|
+
* object with a numeric `status`), use it as-is (with `body`/`headers`
|
|
27
|
+
* defaults). Otherwise, wrap the raw value as a JSON body with a 200.
|
|
28
|
+
*
|
|
29
|
+
* @param {*} result
|
|
30
|
+
* @returns {{status: number, headers: object, body: *}}
|
|
31
|
+
*/
|
|
32
|
+
function normalizeFunctionResult(result) {
|
|
33
|
+
if (result && typeof result === 'object' && typeof result.status === 'number') {
|
|
34
|
+
return { status: result.status, headers: result.headers || {}, body: result.body }
|
|
35
|
+
}
|
|
36
|
+
return { status: 200, headers: { 'content-type': 'application/json' }, body: result }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* @param {object} opts
|
|
41
|
+
* @param {FunctionRoute[]} [opts.routes]
|
|
42
|
+
* @param {(job: {code: string, request?: object, timeoutMs?: number}) => Promise<*>} opts.executor
|
|
43
|
+
* Typically `createAndboxExecutor(...)` (Phase 3) or, later,
|
|
44
|
+
* `createWasmSandboxExecutor(...)` (Phase 6) -- both share this same
|
|
45
|
+
* `executor(job) -> Promise<result>` shape, so the backend is swappable
|
|
46
|
+
* without touching this file.
|
|
47
|
+
* @param {number} [opts.timeoutMs] - passed through as each job's `timeoutMs`.
|
|
48
|
+
* @returns {(req: {fromPubKey?: string, method?: string, path?: string, headers?: object, body?: *}) => Promise<{status: number, headers: object, body: *}|null>}
|
|
49
|
+
* `null` for a request matching no route -- "not mine, try the next handler in the chain" (the proxy handler, or a 404).
|
|
50
|
+
*/
|
|
51
|
+
export function createFunctionsHandler({ routes = [], executor, timeoutMs } = {}) {
|
|
52
|
+
if (typeof executor !== 'function') {
|
|
53
|
+
throw new Error('createFunctionsHandler: opts.executor is required and must be a function')
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return async function handleFunctions({ fromPubKey, method = 'GET', path = '/', headers = {}, body } = {}) {
|
|
57
|
+
const route = routes.find((r) => r.path === path && (r.method || 'GET') === method)
|
|
58
|
+
if (!route) return null
|
|
59
|
+
|
|
60
|
+
try {
|
|
61
|
+
const result = await executor({ code: route.code, request: { fromPubKey, method, path, headers, body }, timeoutMs })
|
|
62
|
+
return normalizeFunctionResult(result)
|
|
63
|
+
} catch (err) {
|
|
64
|
+
return { status: 500, headers: { 'content-type': 'application/json' }, body: { error: err?.message || String(err) } }
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|