@johnhenry/browsermesh-pod 0.1.1 → 0.2.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 +116 -1
- package/package.json +6 -2
- package/src/discovery.mjs +35 -12
- package/src/index.d.ts +78 -3
- package/src/index.mjs +7 -0
- package/src/node-runtime-entry.mjs +51 -0
- package/src/node-runtimes.d.ts +18 -0
- package/src/node-runtimes.mjs +306 -0
- package/src/pod-runtime.mjs +374 -0
- package/src/pod.mjs +95 -11
- package/src/signed-message.mjs +292 -0
- package/src/transport.mjs +12 -0
- package/src/ws-transport.mjs +56 -10
package/README.md
CHANGED
|
@@ -27,6 +27,7 @@ Pods automatically generate an Ed25519 cryptographic identity, detect their exec
|
|
|
27
27
|
- [Pod Kinds](#pod-kinds)
|
|
28
28
|
- [Capabilities](#capabilities)
|
|
29
29
|
- [Wire Protocol](#wire-protocol)
|
|
30
|
+
- [Who sent this message?](#who-sent-this-message)
|
|
30
31
|
- [WebSocketTransport (relay-backed)](#websockettransport-relay-backed)
|
|
31
32
|
- [Running a Pod outside the browser](#running-a-pod-outside-the-browser)
|
|
32
33
|
- [Pod host protocol](#pod-host-protocol)
|
|
@@ -105,6 +106,9 @@ await pod.boot({
|
|
|
105
106
|
handshakeTimeout, // number — ms to wait for parent ACK (default: 1000)
|
|
106
107
|
discoveryTimeout, // number — ms to wait for peer responses (default: 2000)
|
|
107
108
|
globalThis, // object — override globalThis (for testing)
|
|
109
|
+
sign, // boolean — sign outgoing messages with the pod key (default: true)
|
|
110
|
+
allowUnsigned, // boolean — accept unsigned pod:message / pod:rpc-response (default: per transport, see "Who sent this message?")
|
|
111
|
+
trust, // 'same-origin' | 'untrusted' — overrides the transport's own `trust`
|
|
108
112
|
})
|
|
109
113
|
```
|
|
110
114
|
|
|
@@ -210,6 +214,60 @@ const server = await createServer({ discoveryTimeout: 5000 })
|
|
|
210
214
|
|
|
211
215
|
Message factories: `createHello()`, `createHelloAck()`, `createGoodbye()`, `createMessage()`, `createRpcRequest()`, `createRpcResponse()`.
|
|
212
216
|
|
|
217
|
+
## Who sent this message?
|
|
218
|
+
|
|
219
|
+
A receiver never takes the sender's identity from a field the sender or a relay
|
|
220
|
+
wrote (`from`, a relay's `source`). For `pod:message`, `pod:rpc-request` and
|
|
221
|
+
`pod:rpc-response` addressed to this pod (or `'*'`):
|
|
222
|
+
|
|
223
|
+
- **Signed messages** (what a pod sends by default): the message carries the
|
|
224
|
+
sender's public key `pk`, a session id `sid`, a counter `seq` and a signature
|
|
225
|
+
`sig` over `"browsermesh/pod-message/v1\n"` + the canonical JSON (sorted keys)
|
|
226
|
+
of sender, recipient, type, body, `ts`, `pk`, `sid` and `seq`. The receiver
|
|
227
|
+
checks that `from` equals the pod id of `pk` (SHA-256 of the raw key,
|
|
228
|
+
base64url), that the signature verifies, and that `(sid, seq)` has not been
|
|
229
|
+
accepted before. A relay that rewrites, re-addresses or adds to the message
|
|
230
|
+
invalidates it; only the signed fields are delivered. The delivered message
|
|
231
|
+
has `authenticated: true`.
|
|
232
|
+
- **Replay**: a sliding window of the last 64 sequence numbers per sender
|
|
233
|
+
session (4 sessions per sender, 1024 senders, in memory) refuses a copy of a
|
|
234
|
+
message already accepted and tolerates mild reordering. Clocks are not used
|
|
235
|
+
(`ts` is signed but not checked). A copy of a message from a session the
|
|
236
|
+
receiver has forgotten, or sent to a receiver that restarted, is not
|
|
237
|
+
recognised.
|
|
238
|
+
- **Links that authenticate the peer**: a transport may call its handler with
|
|
239
|
+
`(msg, { peerId })` where `peerId` is the identity the link itself verified.
|
|
240
|
+
The sender is then `peerId`, and a message whose `from` differs is dropped.
|
|
241
|
+
- **Unsigned messages** (older peers): accepted only where `allowUnsigned`
|
|
242
|
+
allows, and delivered with `authenticated: false`. Default: accepted from a
|
|
243
|
+
transport whose `trust` is `'same-origin'` (`BroadcastChannelTransport`,
|
|
244
|
+
`EventEmitterTransport`, `NullTransport`) and from messages posted to the
|
|
245
|
+
window; **refused** from every other transport, including
|
|
246
|
+
`WebSocketTransport` (`trust` is `'untrusted'`) and custom adapters that do
|
|
247
|
+
not declare `trust`. An unsigned `pod:rpc-request` is never accepted. A
|
|
248
|
+
message that carries a signature must verify whatever `allowUnsigned` is.
|
|
249
|
+
Set `allowUnsigned: true` to take unsigned messages from older peers across a
|
|
250
|
+
relay (their sender is then only a claim); `false` to refuse them everywhere.
|
|
251
|
+
- Refused messages are counted by reason in `pod.dropped` (`unsigned`,
|
|
252
|
+
`unsigned-rpc`, `malformed`, `sender-mismatch`, `bad-signature`, `replay`) and
|
|
253
|
+
announced as a `message:dropped` event `{ reason, type }`.
|
|
254
|
+
|
|
255
|
+
Same-origin delivery over `BroadcastChannel` keeps working, signed or not. The
|
|
256
|
+
trust there is the origin: any script of the origin can post to the channel
|
|
257
|
+
under any pod id, and signatures do not separate scripts that share an origin.
|
|
258
|
+
|
|
259
|
+
`send()` and `broadcast()` return a promise (signing is asynchronous): await it
|
|
260
|
+
before relying on the message having reached the transport. Payloads must be
|
|
261
|
+
JSON-compatible. A pod booted with an identity that cannot sign (`{ podId }`)
|
|
262
|
+
sends unsigned.
|
|
263
|
+
|
|
264
|
+
What this does and does not protect, end to end across several hops: a signed
|
|
265
|
+
message gives integrity and origin authenticity that the forwarding peers
|
|
266
|
+
cannot forge. It gives no confidentiality; a peer that forwards a message can
|
|
267
|
+
read it. Encrypted transport is tracked in issue #273 and is not part of this
|
|
268
|
+
change. `pod:hello`, `pod:hello-ack` and `pod:goodbye` announcements are not
|
|
269
|
+
signed: they only affect the peer list and never the attribution of messages.
|
|
270
|
+
|
|
213
271
|
## WebSocketTransport (relay-backed)
|
|
214
272
|
|
|
215
273
|
`BroadcastChannelTransport` only reaches same-origin tabs. `WebSocketTransport` is the adapter that lets a `Pod` run anywhere a WebSocket client exists — a Node process, a browser, or a V8 isolate (workerd / Cloudflare Workers) — and still join the mesh, by speaking the `browsermesh-servers` relay/signaling wire protocol (`register`/`registered`, `relay`/`relayed`, `peers`/`peer-joined`/`peer-left`, `ping`/`pong`, `error`). This is what unlocks "hosted pods" (see [issue #185](https://github.com/johnhenry/browsermesh/issues/185)): a pod running on a machine someone else operates, reachable over the same relay a browser tab would use.
|
|
@@ -290,6 +348,19 @@ None of this requires `window`, `document`, `navigator`, `indexedDB`,
|
|
|
290
348
|
`fetch`, `WebAssembly`, `RTCPeerConnection`, or `SharedArrayBuffer` — those
|
|
291
349
|
are only probed, never required, by `detectCapabilities()`.
|
|
292
350
|
|
|
351
|
+
### A sealed, key-authenticated adapter
|
|
352
|
+
|
|
353
|
+
`WshPodTransport` in `@johnhenry/browsermesh-transport` implements this
|
|
354
|
+
contract over wsh (a mesh link that is key-authenticated in both directions and
|
|
355
|
+
sealed end to end, off by default). It stamps every inbound message's `from`
|
|
356
|
+
with the key the session authenticated and drops a message that names another
|
|
357
|
+
sender, so the shared conformance suite is told to name that id (`senderId`).
|
|
358
|
+
It also calls the pod's message handler as `handler(msg, { peerId })` with that
|
|
359
|
+
key, which a pod treats as a link-authenticated sender (see "Who sent this
|
|
360
|
+
message?"): a message over a wsh link is accepted without a per-message
|
|
361
|
+
signature as that peer, and pods that sign by default interoperate with it too.
|
|
362
|
+
See [`docs/security.md`](../../docs/security.md).
|
|
363
|
+
|
|
293
364
|
### The `TransportAdapter` and `DiscoveryAdapter` contracts
|
|
294
365
|
|
|
295
366
|
Pass `opts.transport` and `opts.discovery` to `boot()` to run `Pod` anywhere
|
|
@@ -301,7 +372,8 @@ interface TransportAdapter {
|
|
|
301
372
|
open(): Promise<void>
|
|
302
373
|
close(): Promise<void>
|
|
303
374
|
send(msg: object): void // no-op before open(), never throws
|
|
304
|
-
onMessage(handler: (msg: object) => void): void
|
|
375
|
+
onMessage(handler: (msg: object, meta?: { peerId?: string }) => void): void
|
|
376
|
+
readonly trust?: 'same-origin' | 'untrusted' // absent means 'untrusted'; see "Who sent this message?"
|
|
305
377
|
}
|
|
306
378
|
|
|
307
379
|
interface DiscoveryAdapter {
|
|
@@ -587,6 +659,49 @@ hosts. For a hosted pod whose code you do not trust, use the CDP driver
|
|
|
587
659
|
inside a Lane B microVM, not the in-page driver — see §8b's "Trust
|
|
588
660
|
caveat".
|
|
589
661
|
|
|
662
|
+
### Runtime lane driver: `PodRuntime` and `createRuntimeLaneDriver()`
|
|
663
|
+
|
|
664
|
+
`createRuntimeLaneDriver({ runtime, modules })` builds a `PodHostDriver`
|
|
665
|
+
(`spawn`/`status`/`send`/`drain`/`list`) over any `PodRuntime`: the narrow
|
|
666
|
+
adapter that actually runs a module. The driver owns what must not depend on
|
|
667
|
+
the runtime: podspec validation; which modules may run (a host-side catalog
|
|
668
|
+
of names to absolute paths, never a path from the requester); which
|
|
669
|
+
environment variables a pod may be given (`NODE_*`, `LD_*`, `DYLD_*`, `UV_*`
|
|
670
|
+
and `OPENSSL_*` are refused, because they change how code is loaded or how
|
|
671
|
+
limits apply); admission limits (`maxPods`, `maxMemMib`); the lifecycle
|
|
672
|
+
state machine and its events. A runtime declares a `boundary`
|
|
673
|
+
(`none`/`process`/`language`/`hardware`), and one that claims `lane:
|
|
674
|
+
'isolate'` is refused unless the boundary is `language` or `hardware`.
|
|
675
|
+
|
|
676
|
+
Two runtimes ship, from `@johnhenry/browsermesh-pod/node-runtimes` (the
|
|
677
|
+
package root stays free of `node:` imports):
|
|
678
|
+
|
|
679
|
+
| Runtime | Boundary | What it limits | What it does NOT stop |
|
|
680
|
+
| --- | --- | --- | --- |
|
|
681
|
+
| `createWorkerThreadsRuntime()` | `none` | heap (`resourceLimits`), environment (only what the podspec names), termination | everything else: the module can read and write any file, open any connection, start processes, and share the host's memory. `worker_threads` is not a security boundary |
|
|
682
|
+
| `createPermissionProcessRuntime()` | `process` | the above, plus the Node permission model: read access to only the entry file and the hosted module, no write, no network, no child processes or workers | a determined hostile module: Node's own documentation calls the permission model a safeguard, not a sandbox. Same user and kernel as the host |
|
|
683
|
+
|
|
684
|
+
Neither is the isolate lane: both are advertised as the `node` lane, and the
|
|
685
|
+
placement planner in `@johnhenry/browsermesh-apps` only gives them work from
|
|
686
|
+
requesters the operator trusts. A real isolate (`isolated-vm`, or `workerd`
|
|
687
|
+
as in `spikes/isolate-pod-host`) implements the same `PodRuntime` interface;
|
|
688
|
+
`pod-runtime.mjs` specifies it, and it is not in this repository because
|
|
689
|
+
`isolated-vm` is a native dependency.
|
|
690
|
+
|
|
691
|
+
```js
|
|
692
|
+
import { createRuntimeLaneDriver } from '@johnhenry/browsermesh-pod'
|
|
693
|
+
import { createPermissionProcessRuntime } from '@johnhenry/browsermesh-pod/node-runtimes'
|
|
694
|
+
|
|
695
|
+
const driver = createRuntimeLaneDriver({
|
|
696
|
+
runtime: createPermissionProcessRuntime(),
|
|
697
|
+
modules: { greeter: '/srv/pods/greeter.mjs' }, // export async function handle(payload, ctx)
|
|
698
|
+
maxPods: 20,
|
|
699
|
+
maxMemMib: 256,
|
|
700
|
+
})
|
|
701
|
+
await driver.spawn({ name: 'g1', lane: 'node', run: { kind: 'module', ref: 'greeter' }, limits: { memMib: 64 } })
|
|
702
|
+
await driver.send('g1', { payload: { hello: 'world' } }) // { delivered: true, reply }
|
|
703
|
+
```
|
|
704
|
+
|
|
590
705
|
## InjectedPod
|
|
591
706
|
|
|
592
707
|
Lightweight subclass for Chrome extension injection or bookmarklet use. Adds page text extraction, structured data extraction, and a visual overlay indicator.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@johnhenry/browsermesh-pod",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Pod base class for browser execution contexts with Ed25519 identity, BroadcastChannel discovery, and peer messaging",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.mjs",
|
|
@@ -9,6 +9,10 @@
|
|
|
9
9
|
".": {
|
|
10
10
|
"types": "./src/index.d.ts",
|
|
11
11
|
"import": "./src/index.mjs"
|
|
12
|
+
},
|
|
13
|
+
"./node-runtimes": {
|
|
14
|
+
"types": "./src/node-runtimes.d.ts",
|
|
15
|
+
"import": "./src/node-runtimes.mjs"
|
|
12
16
|
}
|
|
13
17
|
},
|
|
14
18
|
"files": [
|
|
@@ -38,7 +42,7 @@
|
|
|
38
42
|
"@johnhenry/browsermesh-primitives": ">=0.2.0 <1.0.0"
|
|
39
43
|
},
|
|
40
44
|
"devDependencies": {
|
|
41
|
-
"@johnhenry/browsermesh-primitives": "^0.
|
|
45
|
+
"@johnhenry/browsermesh-primitives": "^0.4.0"
|
|
42
46
|
},
|
|
43
47
|
"engines": {
|
|
44
48
|
"node": ">=26.0.0"
|
package/src/discovery.mjs
CHANGED
|
@@ -36,6 +36,7 @@ export class TransportDiscovery {
|
|
|
36
36
|
#onPeerFound = null
|
|
37
37
|
#onPeerLost = null
|
|
38
38
|
#onNonDiscoveryMessage = null
|
|
39
|
+
#unsubscribePeers = null
|
|
39
40
|
|
|
40
41
|
/**
|
|
41
42
|
* @param {object} opts
|
|
@@ -69,7 +70,8 @@ export class TransportDiscovery {
|
|
|
69
70
|
|
|
70
71
|
/**
|
|
71
72
|
* Register handler for non-discovery messages that come through the transport.
|
|
72
|
-
* @param {(msg: object) => void} handler
|
|
73
|
+
* @param {(msg: object, meta?: { peerId?: string }) => void} handler - `meta.peerId` is set by a
|
|
74
|
+
* transport whose link authenticates the peer (see `Pod`'s `allowUnsigned` notes).
|
|
73
75
|
*/
|
|
74
76
|
onMessage(handler) {
|
|
75
77
|
this.#onNonDiscoveryMessage = handler
|
|
@@ -81,24 +83,25 @@ export class TransportDiscovery {
|
|
|
81
83
|
*/
|
|
82
84
|
async start() {
|
|
83
85
|
// Wire message routing
|
|
84
|
-
this.#transport.onMessage((msg) => {
|
|
86
|
+
this.#transport.onMessage((msg, meta) => {
|
|
85
87
|
if (!msg || !msg.type) return
|
|
86
|
-
this.#handleMessage(msg)
|
|
88
|
+
this.#handleMessage(msg, meta)
|
|
87
89
|
})
|
|
88
90
|
|
|
91
|
+
// A transport that learns its peers from a server (WebSocketTransport)
|
|
92
|
+
// can learn them after open() resolves, or any time later. Greet each
|
|
93
|
+
// peer it announces that the broadcast hello below did not reach.
|
|
94
|
+
if (typeof this.#transport.onPeerJoined === 'function') {
|
|
95
|
+
this.#unsubscribePeers = this.#transport.onPeerJoined((podId) => this.#greet(podId))
|
|
96
|
+
}
|
|
97
|
+
|
|
89
98
|
// Open transport if not already open
|
|
90
99
|
if (!this.#transport.ready) {
|
|
91
100
|
await this.#transport.open()
|
|
92
101
|
}
|
|
93
102
|
|
|
94
103
|
// Announce ourselves
|
|
95
|
-
this.#transport.send(
|
|
96
|
-
createHello({
|
|
97
|
-
podId: this.#localPodId,
|
|
98
|
-
kind: this.#localKind,
|
|
99
|
-
capabilities: this.#capabilities,
|
|
100
|
-
})
|
|
101
|
-
)
|
|
104
|
+
this.#transport.send(this.#hello())
|
|
102
105
|
|
|
103
106
|
// Wait for discovery period
|
|
104
107
|
return new Promise((resolve) => {
|
|
@@ -111,7 +114,27 @@ export class TransportDiscovery {
|
|
|
111
114
|
* @param {object} [opts]
|
|
112
115
|
* @param {boolean} [opts.silent] - Skip sending goodbye
|
|
113
116
|
*/
|
|
117
|
+
#hello() {
|
|
118
|
+
return createHello({
|
|
119
|
+
podId: this.#localPodId,
|
|
120
|
+
kind: this.#localKind,
|
|
121
|
+
capabilities: this.#capabilities,
|
|
122
|
+
})
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Send our hello to one newly announced peer (the transport reports each
|
|
127
|
+
* peer once, again only after it left). Skipped until the transport is
|
|
128
|
+
* ready: the broadcast hello in start() reaches every peer known by then.
|
|
129
|
+
*/
|
|
130
|
+
#greet(podId) {
|
|
131
|
+
if (!this.#transport.ready) return
|
|
132
|
+
this.#transport.send({ ...this.#hello(), to: podId })
|
|
133
|
+
}
|
|
134
|
+
|
|
114
135
|
async stop(opts = {}) {
|
|
136
|
+
this.#unsubscribePeers?.()
|
|
137
|
+
this.#unsubscribePeers = null
|
|
115
138
|
if (!opts.silent) {
|
|
116
139
|
try {
|
|
117
140
|
this.#transport.send(createGoodbye({ podId: this.#localPodId }))
|
|
@@ -120,7 +143,7 @@ export class TransportDiscovery {
|
|
|
120
143
|
await this.#transport.close()
|
|
121
144
|
}
|
|
122
145
|
|
|
123
|
-
#handleMessage(msg) {
|
|
146
|
+
#handleMessage(msg, meta) {
|
|
124
147
|
switch (msg.type) {
|
|
125
148
|
case POD_HELLO: {
|
|
126
149
|
if (msg.podId === this.#localPodId) return
|
|
@@ -153,7 +176,7 @@ export class TransportDiscovery {
|
|
|
153
176
|
default: {
|
|
154
177
|
// Non-discovery message — pass through
|
|
155
178
|
if (this.#onNonDiscoveryMessage) {
|
|
156
|
-
this.#onNonDiscoveryMessage(msg)
|
|
179
|
+
this.#onNonDiscoveryMessage(msg, meta)
|
|
157
180
|
}
|
|
158
181
|
break
|
|
159
182
|
}
|
package/src/index.d.ts
CHANGED
|
@@ -143,7 +143,14 @@ export declare function createRpcResponse(opts: {
|
|
|
143
143
|
|
|
144
144
|
export interface TransportAdapter {
|
|
145
145
|
readonly ready: boolean;
|
|
146
|
-
|
|
146
|
+
/**
|
|
147
|
+
* 'same-origin' when only scripts of this origin/process can put messages on the transport
|
|
148
|
+
* (unsigned messages are accepted by default); anything else, or absent, means signatures
|
|
149
|
+
* are required by default.
|
|
150
|
+
*/
|
|
151
|
+
readonly trust?: 'same-origin' | 'untrusted';
|
|
152
|
+
/** `meta.peerId`: set by a transport whose link authenticated the peer's identity. */
|
|
153
|
+
onMessage(handler: (msg: any, meta?: { peerId?: string }) => void): void;
|
|
147
154
|
open(): Promise<void>;
|
|
148
155
|
send(msg: any): void;
|
|
149
156
|
close(): Promise<void>;
|
|
@@ -266,6 +273,17 @@ export interface PodBootOptions {
|
|
|
266
273
|
handshakeTimeout?: number;
|
|
267
274
|
discoveryTimeout?: number;
|
|
268
275
|
globalThis?: typeof globalThis;
|
|
276
|
+
/** Sign outgoing messages with the pod key (default true). `send()` then settles after signing. */
|
|
277
|
+
sign?: boolean;
|
|
278
|
+
/**
|
|
279
|
+
* Accept unsigned pod:message / pod:rpc-response from older peers. Default: true for a
|
|
280
|
+
* transport whose `trust` is 'same-origin' and for window messages, false otherwise.
|
|
281
|
+
* Unsigned pod:rpc-request is never accepted.
|
|
282
|
+
*/
|
|
283
|
+
allowUnsigned?: boolean;
|
|
284
|
+
/** Overrides the transport's `trust`. */
|
|
285
|
+
trust?: 'same-origin' | 'untrusted';
|
|
286
|
+
replay?: { maxSenders?: number; maxSessionsPerSender?: number };
|
|
269
287
|
}
|
|
270
288
|
|
|
271
289
|
export interface PodShutdownOptions {
|
|
@@ -296,8 +314,10 @@ export declare class Pod {
|
|
|
296
314
|
|
|
297
315
|
boot(opts?: PodBootOptions): Promise<void>;
|
|
298
316
|
shutdown(opts?: PodShutdownOptions): Promise<void>;
|
|
299
|
-
|
|
300
|
-
|
|
317
|
+
/** Messages refused so far, by reason. */
|
|
318
|
+
get dropped(): Record<'unsigned' | 'unsigned-rpc' | 'malformed' | 'sender-mismatch' | 'bad-signature' | 'replay', number>;
|
|
319
|
+
send(targetPodId: string, payload: unknown): Promise<void>;
|
|
320
|
+
broadcast(payload: unknown): Promise<void>;
|
|
301
321
|
on(event: string, cb: (data: any) => void): void;
|
|
302
322
|
off(event: string, cb: (data: any) => void): void;
|
|
303
323
|
toJSON(): PodJSON;
|
|
@@ -597,3 +617,58 @@ export declare function createInPageDriver(opts: {
|
|
|
597
617
|
BCConstructor?: new (name: string) => unknown;
|
|
598
618
|
driverId?: string;
|
|
599
619
|
}): PodHostDriver & { close(): void };
|
|
620
|
+
|
|
621
|
+
// ── Pod runtimes (the adapter between a lane driver and what runs a module) ──
|
|
622
|
+
|
|
623
|
+
export type RuntimeBoundary = "none" | "process" | "language" | "hardware";
|
|
624
|
+
|
|
625
|
+
export declare const RUNTIME_BOUNDARY: Readonly<{
|
|
626
|
+
NONE: "none";
|
|
627
|
+
PROCESS: "process";
|
|
628
|
+
LANGUAGE: "language";
|
|
629
|
+
HARDWARE: "hardware";
|
|
630
|
+
}>;
|
|
631
|
+
|
|
632
|
+
/** Environment variable names a requester may not set (they change how code is loaded or limited). */
|
|
633
|
+
export declare const FORBIDDEN_ENV_NAME: RegExp;
|
|
634
|
+
|
|
635
|
+
export interface PodRuntimeStartOptions {
|
|
636
|
+
name: string;
|
|
637
|
+
/** Absolute path on the host, from the host's own catalog. */
|
|
638
|
+
modulePath: string;
|
|
639
|
+
readPaths: string[];
|
|
640
|
+
env: Record<string, string>;
|
|
641
|
+
input: unknown;
|
|
642
|
+
limits: { memMib?: number };
|
|
643
|
+
onLog(line: string): void;
|
|
644
|
+
/** Fires once if the pod stops on its own; not for a `terminate()`. */
|
|
645
|
+
onExit(info: { code: number | null; reason: "oom" | "crashed" | "exited" }): void;
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
export interface PodRuntimeHandle {
|
|
649
|
+
request(payload: unknown, opts?: { timeoutMs?: number }): Promise<unknown>;
|
|
650
|
+
terminate(): Promise<void>;
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/**
|
|
654
|
+
* What a lane driver needs from whatever runs a module. `worker_threads`
|
|
655
|
+
* (`boundary: "none"`) and a permission-model child process
|
|
656
|
+
* (`boundary: "process"`) are in `@johnhenry/browsermesh-pod/node-runtimes`;
|
|
657
|
+
* a runtime claiming `lane: "isolate"` must have boundary "language" or "hardware".
|
|
658
|
+
*/
|
|
659
|
+
export interface PodRuntime {
|
|
660
|
+
kind: string;
|
|
661
|
+
lane: PodLane;
|
|
662
|
+
boundary: RuntimeBoundary;
|
|
663
|
+
start(opts: PodRuntimeStartOptions): Promise<PodRuntimeHandle>;
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
export declare function createRuntimeLaneDriver(opts: {
|
|
667
|
+
runtime: PodRuntime;
|
|
668
|
+
/** Module names a podspec's `run.ref` may name, to absolute paths on this host. */
|
|
669
|
+
modules?: Record<string, string | { path: string; readPaths?: string[] }>;
|
|
670
|
+
maxPods?: number;
|
|
671
|
+
maxMemMib?: number;
|
|
672
|
+
defaultMemMib?: number;
|
|
673
|
+
sendTimeoutMs?: number;
|
|
674
|
+
}): PodHostDriver & { runtime: PodRuntime };
|
package/src/index.mjs
CHANGED
|
@@ -10,6 +10,10 @@ export {
|
|
|
10
10
|
createHello, createHelloAck, createGoodbye, createMessage,
|
|
11
11
|
createRpcRequest, createRpcResponse,
|
|
12
12
|
} from './messages.mjs'
|
|
13
|
+
export {
|
|
14
|
+
MessageSigner, ReplayGuard, ReplayWindow, verifyMessage, signedBytes,
|
|
15
|
+
SIGNED_FIELDS, SIGNATURE_DOMAIN, REPLAY_WINDOW, DROP_REASONS,
|
|
16
|
+
} from './signed-message.mjs'
|
|
13
17
|
export { InjectedPod } from './injected-pod.mjs'
|
|
14
18
|
export { installPodRuntime, createRuntime, createClient, createServer } from './runtime.mjs'
|
|
15
19
|
export { BroadcastChannelTransport, EventEmitterTransport, NullTransport } from './transport.mjs'
|
|
@@ -24,6 +28,9 @@ export {
|
|
|
24
28
|
createHostRequest, createHostResponse, createHostEvent,
|
|
25
29
|
InMemoryPodHostDriver,
|
|
26
30
|
} from './host-protocol.mjs'
|
|
31
|
+
export {
|
|
32
|
+
RUNTIME_BOUNDARY, FORBIDDEN_ENV_NAME, createRuntimeLaneDriver,
|
|
33
|
+
} from './pod-runtime.mjs'
|
|
27
34
|
export {
|
|
28
35
|
bootHostedPod, readPodName,
|
|
29
36
|
DEFAULT_DISCOVERY_CHANNEL, BROWSER_HOST_READY,
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* node-runtime-entry.mjs -- the code that runs INSIDE a `worker_threads`
|
|
3
|
+
* worker or a Node child process started by `node-runtimes.mjs`. It loads
|
|
4
|
+
* the hosted module (a path the host chose, never one the requester sent)
|
|
5
|
+
* and answers requests from the host over the channel it was started with.
|
|
6
|
+
*
|
|
7
|
+
* Not part of the package's public surface: `node-runtimes.mjs` points
|
|
8
|
+
* `Worker`/`fork` at this file. See `pod-runtime.mjs` for the module
|
|
9
|
+
* contract (`start(ctx)`, `handle(payload, ctx)`).
|
|
10
|
+
*
|
|
11
|
+
* Messages to the host: `{type: 'ready'}`, `{type: 'start-error', message}`,
|
|
12
|
+
* `{type: 'log', line}`, `{type: 'reply', id, ok, reply|message}`.
|
|
13
|
+
* Messages from the host: `{type: 'request', id, payload}`.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { parentPort, workerData } from 'node:worker_threads'
|
|
17
|
+
|
|
18
|
+
const inWorker = parentPort !== null
|
|
19
|
+
const config = inWorker ? workerData : JSON.parse(process.argv[2])
|
|
20
|
+
const post = (message) => (inWorker ? parentPort.postMessage(message) : process.send(message))
|
|
21
|
+
const listen = (fn) => (inWorker ? parentPort.on('message', fn) : process.on('message', fn))
|
|
22
|
+
|
|
23
|
+
const ctx = {
|
|
24
|
+
name: config.name,
|
|
25
|
+
env: config.env,
|
|
26
|
+
input: config.input,
|
|
27
|
+
log: (line) => post({ type: 'log', line: String(line) }),
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
let hosted
|
|
31
|
+
try {
|
|
32
|
+
hosted = await import(config.moduleUrl)
|
|
33
|
+
if (typeof hosted.handle !== 'function') throw new Error('the module must export handle(payload, ctx)')
|
|
34
|
+
if (typeof hosted.start === 'function') await hosted.start(ctx)
|
|
35
|
+
} catch (err) {
|
|
36
|
+
post({ type: 'start-error', message: String(err?.message ?? err) })
|
|
37
|
+
// Give the message a chance to flush before this context ends.
|
|
38
|
+
setTimeout(() => process.exit(1), 50)
|
|
39
|
+
await new Promise(() => {})
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
listen(async (message) => {
|
|
43
|
+
if (message?.type !== 'request') return
|
|
44
|
+
try {
|
|
45
|
+
const reply = await hosted.handle(message.payload, ctx)
|
|
46
|
+
post({ type: 'reply', id: message.id, ok: true, reply: reply ?? null })
|
|
47
|
+
} catch (err) {
|
|
48
|
+
post({ type: 'reply', id: message.id, ok: false, message: String(err?.message ?? err) })
|
|
49
|
+
}
|
|
50
|
+
})
|
|
51
|
+
post({ type: 'ready' })
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { PodRuntime } from './index.js';
|
|
2
|
+
|
|
3
|
+
export interface NodeRuntimeOptions {
|
|
4
|
+
/** How long `start()` waits for the module to load. Default 10000. */
|
|
5
|
+
startTimeoutMs?: number;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/** `worker_threads` in the host process. Boundary `none`; advertised as the `node` lane. Not a security boundary. */
|
|
9
|
+
export declare function createWorkerThreadsRuntime(opts?: NodeRuntimeOptions): PodRuntime;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* A child Node process under the permission model (no fs write, no network,
|
|
13
|
+
* no child processes, read access to only the entry and the hosted module).
|
|
14
|
+
* Boundary `process`; advertised as the `node` lane. Not a sandbox against hostile code.
|
|
15
|
+
*/
|
|
16
|
+
export declare function createPermissionProcessRuntime(
|
|
17
|
+
opts?: NodeRuntimeOptions & { nodePath?: string },
|
|
18
|
+
): PodRuntime;
|