@johnhenry/browsermesh-apps 0.10.0 → 0.12.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 +604 -7
- package/package.json +3 -1
- package/src/chunk-replication.mjs +2 -2
- package/src/index.mjs +5 -0
- package/src/internal/wire-envelope.mjs +33 -0
- package/src/mesh-bootstrap.mjs +1 -1
- package/src/mesh-orchestrator-tools.mjs +77 -10
- package/src/mesh-orchestrator.mjs +1 -1
- package/src/mesh-relay-backend.mjs +2 -0
- package/src/mesh-relay-host.mjs +3 -0
- package/src/mesh-service.mjs +28 -6
- package/src/mesh-sync.mjs +2 -0
- package/src/mesh-torrent.mjs +3 -3
- package/src/mesh-websocket.mjs +3 -1
- package/src/orchestrator.mjs +895 -6
- package/src/peer-node-transport.mjs +114 -0
- package/src/peer-node.mjs +94 -2
- package/src/pod-host-gateway.mjs +372 -0
- package/src/pod-host-routes.mjs +630 -0
- package/src/pod-host-service.mjs +732 -0
- package/src/pod-supervisor.mjs +784 -0
- package/src/resources.mjs +107 -2
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* peer-node-transport.mjs -- the host half of `wireTransport(broadcastFn,
|
|
3
|
+
* subscribeFn)`.
|
|
4
|
+
*
|
|
5
|
+
* `PaymentRouter`, `ConsensusManager` (both in this package),
|
|
6
|
+
* `MigrationEngine` (`@johnhenry/browsermesh-sync`) and `GroupKeyManager`
|
|
7
|
+
* (`@johnhenry/browsermesh-core`) each expose
|
|
8
|
+
* `wireTransport(broadcastFn, subscribeFn)` and leave the host to supply the
|
|
9
|
+
* one-to-all send and the typed subscription. This builds both from a
|
|
10
|
+
* `PeerNode`, so wiring all four is one call each:
|
|
11
|
+
*
|
|
12
|
+
* const { broadcastFn, subscribeFn } = createPeerNodeTransport(peerNode)
|
|
13
|
+
* paymentRouter.wireTransport(broadcastFn, subscribeFn)
|
|
14
|
+
* consensus.wireTransport(broadcastFn, subscribeFn)
|
|
15
|
+
* migration.wireTransport(broadcastFn, subscribeFn)
|
|
16
|
+
* groupKeys.wireTransport(broadcastFn, subscribeFn)
|
|
17
|
+
*
|
|
18
|
+
* Wire shape: `peerNode.broadcast({ type: <wireType>, payload, from })`,
|
|
19
|
+
* where `<wireType>` is the module's numeric message constant
|
|
20
|
+
* (`PAYMENT_OPEN`, `CONSENSUS_VOTE`, ...). `subscribeFn(wireType, handler)`
|
|
21
|
+
* calls `handler(payload, fromPodId)` for matching inbound envelopes.
|
|
22
|
+
* `fromPodId` is the pubKey of the session the message arrived on -- the
|
|
23
|
+
* transport-authenticated sender -- never the envelope's own `from` field,
|
|
24
|
+
* which a remote peer could set to anything.
|
|
25
|
+
*
|
|
26
|
+
* Inbound envelopes are accepted as parsed objects or as JSON text, like
|
|
27
|
+
* `ctx.onIncomingData()`.
|
|
28
|
+
*
|
|
29
|
+
* Browser-safe: no imports beyond a sibling internal helper.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
import { decodeWireData } from './internal/wire-envelope.mjs'
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* @param {import('./peer-node.mjs').PeerNode} peerNode
|
|
36
|
+
* @param {object} [opts]
|
|
37
|
+
* @param {string} [opts.podId] - Value for the envelope's informational
|
|
38
|
+
* `from` field. Defaults to `peerNode.podId`.
|
|
39
|
+
* @param {'control'|'bulk'} [opts.channel] - Data channel for outbound
|
|
40
|
+
* broadcasts. Defaults to the control lane.
|
|
41
|
+
* @param {(event: string, data: object) => void} [opts.onLog]
|
|
42
|
+
* @returns {{
|
|
43
|
+
* broadcastFn: (wireType: number, payload: object) => Promise<{sent: string[], failed: {pubKey: string, error: string}[]}>,
|
|
44
|
+
* subscribeFn: (wireType: number, handler: (payload: object, fromPodId: string) => void) => (() => void),
|
|
45
|
+
* dispose: () => void,
|
|
46
|
+
* }}
|
|
47
|
+
* `broadcastFn` never rejects (a stopped node or a dead peer is reported
|
|
48
|
+
* through `onLog`, not thrown at a fire-and-forget caller). `subscribeFn`
|
|
49
|
+
* returns an unsubscribe function; `dispose()` drops every subscription.
|
|
50
|
+
*/
|
|
51
|
+
export function createPeerNodeTransport(peerNode, { podId, channel, onLog } = {}) {
|
|
52
|
+
if (!peerNode || typeof peerNode.broadcast !== 'function' || typeof peerNode.onIncomingData !== 'function') {
|
|
53
|
+
throw new Error('createPeerNodeTransport: peerNode with broadcast() and onIncomingData() is required')
|
|
54
|
+
}
|
|
55
|
+
const log = typeof onLog === 'function' ? onLog : () => {}
|
|
56
|
+
|
|
57
|
+
/** @type {Map<*, Set<Function>>} */
|
|
58
|
+
const handlers = new Map()
|
|
59
|
+
let unsubscribeIncoming = null
|
|
60
|
+
|
|
61
|
+
function ensureListening() {
|
|
62
|
+
if (unsubscribeIncoming) return
|
|
63
|
+
unsubscribeIncoming = peerNode.onIncomingData((fromPubKey, rawData) => {
|
|
64
|
+
const env = decodeWireData(rawData)
|
|
65
|
+
if (!env || typeof env !== 'object' || !('payload' in env)) return
|
|
66
|
+
const set = handlers.get(env.type)
|
|
67
|
+
if (!set) return
|
|
68
|
+
for (const handler of [...set]) {
|
|
69
|
+
try {
|
|
70
|
+
const result = handler(env.payload, fromPubKey)
|
|
71
|
+
if (result && typeof result.catch === 'function') {
|
|
72
|
+
result.catch((err) => log('peer-node-transport:handler-error', { type: env.type, error: err?.message || String(err) }))
|
|
73
|
+
}
|
|
74
|
+
} catch (err) {
|
|
75
|
+
log('peer-node-transport:handler-error', { type: env.type, error: err?.message || String(err) })
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
})
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function broadcastFn(wireType, payload) {
|
|
82
|
+
const localPodId = podId ?? peerNode.podId
|
|
83
|
+
return peerNode
|
|
84
|
+
.broadcast({ type: wireType, payload, from: localPodId }, channel === undefined ? undefined : { channel })
|
|
85
|
+
.then((result) => {
|
|
86
|
+
for (const f of result.failed) log('peer-node-transport:broadcast-send-failed', { type: wireType, to: f.pubKey, error: f.error })
|
|
87
|
+
return result
|
|
88
|
+
})
|
|
89
|
+
.catch((err) => {
|
|
90
|
+
log('peer-node-transport:broadcast-failed', { type: wireType, error: err?.message || String(err) })
|
|
91
|
+
return { sent: [], failed: [] }
|
|
92
|
+
})
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function subscribeFn(wireType, handler) {
|
|
96
|
+
if (typeof handler !== 'function') return () => {}
|
|
97
|
+
let set = handlers.get(wireType)
|
|
98
|
+
if (!set) {
|
|
99
|
+
set = new Set()
|
|
100
|
+
handlers.set(wireType, set)
|
|
101
|
+
}
|
|
102
|
+
set.add(handler)
|
|
103
|
+
ensureListening()
|
|
104
|
+
return () => { set.delete(handler) }
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function dispose() {
|
|
108
|
+
handlers.clear()
|
|
109
|
+
if (unsubscribeIncoming) unsubscribeIncoming()
|
|
110
|
+
unsubscribeIncoming = null
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
return { broadcastFn, subscribeFn, dispose }
|
|
114
|
+
}
|
package/src/peer-node.mjs
CHANGED
|
@@ -553,6 +553,14 @@ export class PeerNode {
|
|
|
553
553
|
* @param {object} [opts]
|
|
554
554
|
* @param {string} [opts.connectionId] - Target this specific connection's
|
|
555
555
|
* session (issue #116) rather than "most recently created".
|
|
556
|
+
* @param {'control'|'bulk'} [opts.channel] - Which of the transport's data
|
|
557
|
+
* channels to send on. Omit (or pass `'control'`) for the ordered control
|
|
558
|
+
* lane; `'bulk'` selects the second, unordered `mesh-bulk` channel, so
|
|
559
|
+
* large payloads (file/torrent chunks) cannot queue in front of control
|
|
560
|
+
* traffic. Passed through as `transport.send(data, { channel })` only
|
|
561
|
+
* when given; a transport with no bulk lane ignores it (the WebRTC
|
|
562
|
+
* transport falls back to its control channel when the bulk channel is
|
|
563
|
+
* not open). Any other value throws a `TypeError`.
|
|
556
564
|
* @returns {Promise<void>} Resolves when the underlying transport
|
|
557
565
|
* has accepted the send (transport-defined; some are fire-and-
|
|
558
566
|
* forget, others await an ack).
|
|
@@ -560,8 +568,11 @@ export class PeerNode {
|
|
|
560
568
|
* @example
|
|
561
569
|
* await peerNode.sendTo('podid_abc', JSON.stringify({ type: 'ping' }));
|
|
562
570
|
*/
|
|
563
|
-
async sendTo(pubKey, data, { connectionId } = {}) {
|
|
571
|
+
async sendTo(pubKey, data, { connectionId, channel } = {}) {
|
|
564
572
|
this.#ensureRunning('sendTo');
|
|
573
|
+
if (channel !== undefined && channel !== 'control' && channel !== 'bulk') {
|
|
574
|
+
throw new TypeError(`PeerNode.sendTo: unknown channel ${JSON.stringify(channel)} (expected 'control' or 'bulk')`);
|
|
575
|
+
}
|
|
565
576
|
let session = null;
|
|
566
577
|
for (const [, s] of this.#sessions) {
|
|
567
578
|
if (s.pubKey !== pubKey || s.state !== 'active') continue;
|
|
@@ -575,7 +586,86 @@ export class PeerNode {
|
|
|
575
586
|
if (!session.transportInstance || typeof session.transportInstance.send !== 'function') {
|
|
576
587
|
throw new Error(`PeerNode.sendTo: session for ${pubKey} has no transport.send`);
|
|
577
588
|
}
|
|
578
|
-
return
|
|
589
|
+
return channel === undefined
|
|
590
|
+
? session.transportInstance.send(data)
|
|
591
|
+
: session.transportInstance.send(data, { channel });
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
/**
|
|
595
|
+
* Send `data` to every connected peer (one active session per peer, the
|
|
596
|
+
* most recently created one -- the same session `sendTo(pubKey, data)`
|
|
597
|
+
* would pick), fanning out through `sendTo()` so each send gets the same
|
|
598
|
+
* session selection, `channel` handling and error behaviour as a direct
|
|
599
|
+
* one.
|
|
600
|
+
*
|
|
601
|
+
* Errors are collected, never thrown: one dead peer must not stop the
|
|
602
|
+
* message reaching the others. A peer whose send throws or rejects is
|
|
603
|
+
* reported in `failed` and the rest carry on.
|
|
604
|
+
*
|
|
605
|
+
* Emits a `'broadcast'` event (payload: the result object) after the
|
|
606
|
+
* fan-out settles.
|
|
607
|
+
*
|
|
608
|
+
* @param {*} data - Wire payload, exactly as for `sendTo()`.
|
|
609
|
+
* @param {object} [opts]
|
|
610
|
+
* @param {'control'|'bulk'} [opts.channel] - As for `sendTo()`.
|
|
611
|
+
* @param {string[]|Set<string>|((pubKey: string) => boolean)} [opts.exclude]
|
|
612
|
+
* Peers to skip: a list/Set of pubKeys, or a predicate returning true to
|
|
613
|
+
* skip. (A node never has a session with itself, so there is no need to
|
|
614
|
+
* exclude yourself.)
|
|
615
|
+
* @param {number} [opts.concurrency=8] - Max sends in flight at once.
|
|
616
|
+
* `1` sends strictly one after another.
|
|
617
|
+
* @returns {Promise<{ sent: string[], failed: { pubKey: string, error: string }[] }>}
|
|
618
|
+
* `sent` lists the pubKeys whose send resolved, `failed` those whose send
|
|
619
|
+
* threw or rejected. Both are in session order. With no connected peers
|
|
620
|
+
* both are empty (not an error).
|
|
621
|
+
*
|
|
622
|
+
* @example
|
|
623
|
+
* const { sent, failed } = await peerNode.broadcast({ type: 'hello' })
|
|
624
|
+
*/
|
|
625
|
+
async broadcast(data, { channel, exclude, concurrency = 8 } = {}) {
|
|
626
|
+
this.#ensureRunning('broadcast');
|
|
627
|
+
if (channel !== undefined && channel !== 'control' && channel !== 'bulk') {
|
|
628
|
+
throw new TypeError(`PeerNode.broadcast: unknown channel ${JSON.stringify(channel)} (expected 'control' or 'bulk')`);
|
|
629
|
+
}
|
|
630
|
+
const skip = typeof exclude === 'function'
|
|
631
|
+
? exclude
|
|
632
|
+
: (() => { const set = new Set(exclude || []); return (pk) => set.has(pk); })();
|
|
633
|
+
|
|
634
|
+
// One target per peer, in first-session order, however many sessions it has.
|
|
635
|
+
const targets = [];
|
|
636
|
+
const seen = new Set();
|
|
637
|
+
for (const s of this.#sessions.values()) {
|
|
638
|
+
if (s.state !== 'active' || seen.has(s.pubKey)) continue;
|
|
639
|
+
if (!s.transportInstance || typeof s.transportInstance.send !== 'function') continue;
|
|
640
|
+
seen.add(s.pubKey);
|
|
641
|
+
if (skip(s.pubKey)) continue;
|
|
642
|
+
targets.push(s.pubKey);
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
const outcome = new Map();
|
|
646
|
+
const limit = Math.max(1, Math.floor(Number(concurrency)) || 1);
|
|
647
|
+
let next = 0;
|
|
648
|
+
const worker = async () => {
|
|
649
|
+
while (next < targets.length) {
|
|
650
|
+
const pubKey = targets[next++];
|
|
651
|
+
try {
|
|
652
|
+
await this.sendTo(pubKey, data, channel === undefined ? undefined : { channel });
|
|
653
|
+
outcome.set(pubKey, null);
|
|
654
|
+
} catch (err) {
|
|
655
|
+
outcome.set(pubKey, err?.message || String(err));
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
};
|
|
659
|
+
await Promise.all(Array.from({ length: Math.min(limit, targets.length) }, worker));
|
|
660
|
+
|
|
661
|
+
const result = { sent: [], failed: [] };
|
|
662
|
+
for (const pubKey of targets) {
|
|
663
|
+
const error = outcome.get(pubKey);
|
|
664
|
+
if (error === null) result.sent.push(pubKey);
|
|
665
|
+
else result.failed.push({ pubKey, error });
|
|
666
|
+
}
|
|
667
|
+
this.#emit('broadcast', result);
|
|
668
|
+
return result;
|
|
579
669
|
}
|
|
580
670
|
|
|
581
671
|
/**
|
|
@@ -771,6 +861,8 @@ export class PeerNode {
|
|
|
771
861
|
* those that don't. See issue #110.
|
|
772
862
|
* - 'peer:transport-error' — same, for onError(). Payload:
|
|
773
863
|
* `{pubKey, sessionId, transport, error}`.
|
|
864
|
+
* - 'broadcast' — fired after a `broadcast()` fan-out settles.
|
|
865
|
+
* Payload: `{sent, failed}` (see `broadcast()`).
|
|
774
866
|
* - 'boot' — fired after successful boot
|
|
775
867
|
* - 'shutdown' — fired after shutdown
|
|
776
868
|
*
|
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pod-host-gateway.mjs -- issue #185 control-surface item 3's other half:
|
|
3
|
+
* a Node HTTP gateway so the pod-host verbs can be driven from OUTSIDE the
|
|
4
|
+
* mesh, over plain HTTP, using the exact same route table
|
|
5
|
+
* (`POD_HOST_ROUTES`/`matchPodHostRoute()`, `pod-host-routes.mjs`) the
|
|
6
|
+
* `mesh://` router projects.
|
|
7
|
+
*
|
|
8
|
+
* `createPodHostGatewayHandler()` is a Web-standard `(req: Request) =>
|
|
9
|
+
* Promise<Response>` handler -- no Node-specific types in its own
|
|
10
|
+
* signature, so it runs in a Worker, Deno, or (via `serveNodeGateway()`
|
|
11
|
+
* below) plain Node's `node:http`. It does NOT reuse
|
|
12
|
+
* `createPodHostRouter()` from `pod-host-routes.mjs`: that router dispatches
|
|
13
|
+
* straight to a local `PodHostDriver` for the HOST mounted on the mesh;
|
|
14
|
+
* this gateway is itself a MESH PEER (it holds a `peerNode`/`client`) and
|
|
15
|
+
* dispatches by calling `createPodHostClient()`'s per-verb methods against
|
|
16
|
+
* a remote host over the real, gated `pod-host:request` envelope protocol
|
|
17
|
+
* (`pod-host-service.mjs`) -- the exact client API
|
|
18
|
+
* `docs/hosted-pods.md` §8a calls the thing every later surface projects.
|
|
19
|
+
*
|
|
20
|
+
* ---------------------------------------------------------------------------
|
|
21
|
+
* IDENTITY CAVEAT -- read this before deploying a gateway.
|
|
22
|
+
*
|
|
23
|
+
* `checkAccess()` on the remote host is evaluated against the GATEWAY's OWN
|
|
24
|
+
* mesh identity (`client`'s/`peerNode`'s pubKey), not against whoever made
|
|
25
|
+
* the HTTP request. The gateway acts on the mesh AS ITSELF. This mirrors
|
|
26
|
+
* exactly how a real API gateway in front of a backend service that trusts
|
|
27
|
+
* mTLS client certs works: the backend sees the gateway's cert, not the
|
|
28
|
+
* original caller's. Whatever scopes the gateway's identity was granted on
|
|
29
|
+
* each host it talks to are the scopes every HTTP caller through this
|
|
30
|
+
* gateway effectively gets (modulo whatever the `auth()` callback and
|
|
31
|
+
* `resolveHost()` additionally restrict at the HTTP layer).
|
|
32
|
+
*
|
|
33
|
+
* Because of this, `auth(req) -> {ok, pubKey?} | Promise<...>` is a REQUIRED
|
|
34
|
+
* constructor argument -- there is no default-open gateway. It is entirely
|
|
35
|
+
* the OPERATOR's responsibility to decide who gets to use the gateway's
|
|
36
|
+
* mesh identity, and how (a bearer token, mTLS terminated upstream, a
|
|
37
|
+
* signed JWT, ...); this file has no opinion on the scheme, only that one
|
|
38
|
+
* must be supplied. See `test/pod-host-gateway.test.mjs` for a bearer-token
|
|
39
|
+
* example.
|
|
40
|
+
*
|
|
41
|
+
* ---------------------------------------------------------------------------
|
|
42
|
+
* PATHS: `/hosts/:hostPodId/pods...` (and `/hosts/:hostPodId/host` for
|
|
43
|
+
* describe), mapped onto `POD_HOST_ROUTES` via `matchPodHostRoute()` after
|
|
44
|
+
* stripping the `/hosts/:hostPodId` prefix -- plus `GET /hosts`, which lists
|
|
45
|
+
* the hosts this gateway knows about via `resolveHost` (see
|
|
46
|
+
* `createPodHostGatewayHandler()`'s own doc comment for the two shapes
|
|
47
|
+
* `resolveHost` may take).
|
|
48
|
+
*
|
|
49
|
+
* `serveNodeGateway({handler, port, host})` wraps a handler in a real
|
|
50
|
+
* `node:http` server, lazily `await import('node:http')`-ing so this file
|
|
51
|
+
* stays reachable from `src/index.mjs`'s `export *` graph without breaking
|
|
52
|
+
* `test/browser-safe-entry.test.mjs` (see that test's own doc comment) --
|
|
53
|
+
* the Node-only code only runs once `serveNodeGateway()` is actually
|
|
54
|
+
* called, never merely by importing this module.
|
|
55
|
+
*
|
|
56
|
+
* No `node:` imports at module top level.
|
|
57
|
+
*/
|
|
58
|
+
|
|
59
|
+
import { POD_HOST_VERB, POD_HOST_ERROR, PodHostDriverError } from '@johnhenry/browsermesh-pod'
|
|
60
|
+
import { createPodHostClient } from './pod-host-service.mjs'
|
|
61
|
+
import {
|
|
62
|
+
matchPodHostRoute,
|
|
63
|
+
statusForError,
|
|
64
|
+
successStatusForVerb,
|
|
65
|
+
readHttpRequestBody,
|
|
66
|
+
POD_HOST_DESCRIBE_VERB,
|
|
67
|
+
} from './pod-host-routes.mjs'
|
|
68
|
+
|
|
69
|
+
/** @param {number} status @param {object} body @returns {Response} */
|
|
70
|
+
function jsonResponse(status, body) {
|
|
71
|
+
return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Normalize the `resolveHost` constructor option into `{resolve, list}`.
|
|
76
|
+
* Accepts either a lookup function `(token) => pubKey|null|Promise<...>`
|
|
77
|
+
* (in which case `GET /hosts` lists nothing unless `listHosts` is also
|
|
78
|
+
* given), or a plain object / `Map` of `token -> pubKey`, in which case its
|
|
79
|
+
* keys double as the `GET /hosts` listing -- "the hosts the gateway knows"
|
|
80
|
+
* in the common static-config case.
|
|
81
|
+
* @param {Function|object|Map<string,string>|undefined} resolveHost
|
|
82
|
+
* @param {Function|undefined} listHosts
|
|
83
|
+
* @returns {{resolve: (token: string) => Promise<string|null>, list: () => Promise<string[]>}}
|
|
84
|
+
*/
|
|
85
|
+
function normalizeHostResolver(resolveHost, listHosts) {
|
|
86
|
+
const list = typeof listHosts === 'function'
|
|
87
|
+
? async () => listHosts()
|
|
88
|
+
: null
|
|
89
|
+
|
|
90
|
+
if (typeof resolveHost === 'function') {
|
|
91
|
+
return { resolve: async (token) => resolveHost(token), list: list || (async () => []) }
|
|
92
|
+
}
|
|
93
|
+
if (resolveHost instanceof Map) {
|
|
94
|
+
return {
|
|
95
|
+
resolve: async (token) => (resolveHost.has(token) ? resolveHost.get(token) : null),
|
|
96
|
+
list: list || (async () => [...resolveHost.keys()]),
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
if (resolveHost && typeof resolveHost === 'object') {
|
|
100
|
+
return {
|
|
101
|
+
resolve: async (token) => (Object.prototype.hasOwnProperty.call(resolveHost, token) ? resolveHost[token] : null),
|
|
102
|
+
list: list || (async () => Object.keys(resolveHost)),
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return { resolve: async () => null, list: list || (async () => []) }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Call the right `PodHostClient` method for a matched HTTP route. Mirrors
|
|
110
|
+
* `pod-host-routes.mjs`'s internal `buildRawPayload()`/`dispatchToDriver()`
|
|
111
|
+
* pair, but targets `createPodHostClient()`'s per-verb, host-bound-first-arg
|
|
112
|
+
* methods instead of a local driver -- the remote host performs its own
|
|
113
|
+
* `validateVerbRequest()`/`checkAccess()`, so this function only has to
|
|
114
|
+
* shape arguments, not validate them.
|
|
115
|
+
*
|
|
116
|
+
* @param {import('./pod-host-service.mjs').PodHostClient} client
|
|
117
|
+
* @param {string} hostPubKey
|
|
118
|
+
* @param {string} verb
|
|
119
|
+
* @param {{name?: string}} params
|
|
120
|
+
* @param {*} bodyJson
|
|
121
|
+
* @param {URLSearchParams} searchParams
|
|
122
|
+
* @returns {Promise<*>}
|
|
123
|
+
*/
|
|
124
|
+
async function dispatchToClient(client, hostPubKey, verb, params, bodyJson, searchParams) {
|
|
125
|
+
const body = bodyJson && typeof bodyJson === 'object' ? bodyJson : {}
|
|
126
|
+
switch (verb) {
|
|
127
|
+
case POD_HOST_DESCRIBE_VERB:
|
|
128
|
+
return client.describe(hostPubKey)
|
|
129
|
+
case POD_HOST_VERB.LIST:
|
|
130
|
+
return client.list(hostPubKey)
|
|
131
|
+
case POD_HOST_VERB.SPAWN:
|
|
132
|
+
return client.spawn(hostPubKey, body)
|
|
133
|
+
case POD_HOST_VERB.STATUS:
|
|
134
|
+
return client.status(hostPubKey, params.name)
|
|
135
|
+
case POD_HOST_VERB.SEND:
|
|
136
|
+
return client.send(hostPubKey, params.name, body.payload, body.to === undefined ? {} : { to: body.to })
|
|
137
|
+
case POD_HOST_VERB.EXEC:
|
|
138
|
+
return client.exec(hostPubKey, params.name, body.command, body.timeoutMs === undefined ? {} : { timeoutMs: body.timeoutMs })
|
|
139
|
+
case POD_HOST_VERB.SNAPSHOT:
|
|
140
|
+
return client.snapshot(hostPubKey, params.name)
|
|
141
|
+
case POD_HOST_VERB.RESTORE:
|
|
142
|
+
return client.restore(hostPubKey, params.name)
|
|
143
|
+
case POD_HOST_VERB.DRAIN: {
|
|
144
|
+
const cascadeParam = searchParams.get('cascade')
|
|
145
|
+
return client.drain(hostPubKey, params.name, cascadeParam === null ? {} : { cascade: cascadeParam === 'true' })
|
|
146
|
+
}
|
|
147
|
+
default:
|
|
148
|
+
throw new PodHostDriverError(POD_HOST_ERROR.EINVAL, `unknown verb '${verb}'`)
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Build the gateway handler.
|
|
154
|
+
*
|
|
155
|
+
* @param {object} opts
|
|
156
|
+
* @param {import('./pod-host-service.mjs').PodHostClient} [opts.client] -
|
|
157
|
+
* A client built with `createPodHostClient()`. Preferred over `peerNode`
|
|
158
|
+
* when the caller already has one (e.g. to share it across several
|
|
159
|
+
* gateways/services).
|
|
160
|
+
* @param {object} [opts.peerNode] - Used to build a client internally
|
|
161
|
+
* (`createPodHostClient({peerNode})`) when `client` is not given. One of
|
|
162
|
+
* `client`/`peerNode` is required.
|
|
163
|
+
* @param {Function|object|Map<string,string>} [opts.resolveHost] - Resolves
|
|
164
|
+
* the `:hostPodId` URL token to the actual mesh pubKey `client` methods
|
|
165
|
+
* expect. Defaults to "no hosts known" (every host path 404s) -- see
|
|
166
|
+
* `normalizeHostResolver()`'s doc comment for the function-vs-map shapes.
|
|
167
|
+
* @param {Function} [opts.listHosts] - `() => Promise<array>` for `GET
|
|
168
|
+
* /hosts`; overrides the listing `resolveHost` would otherwise provide.
|
|
169
|
+
* @param {(req: Request) => ({ok: boolean, pubKey?: string}|Promise<{ok: boolean, pubKey?: string}>)} opts.auth -
|
|
170
|
+
* REQUIRED. See module doc comment's "IDENTITY CAVEAT" -- this gateway
|
|
171
|
+
* acts on the mesh with its OWN identity; `auth()` is the operator's own
|
|
172
|
+
* gate on who may use it, not a mesh-level identity substitution.
|
|
173
|
+
* @param {Function} [opts.onLog] - `(event, data) => void` debug logging.
|
|
174
|
+
* @returns {(req: Request) => Promise<Response>}
|
|
175
|
+
*/
|
|
176
|
+
export function createPodHostGatewayHandler({
|
|
177
|
+
client,
|
|
178
|
+
peerNode,
|
|
179
|
+
resolveHost,
|
|
180
|
+
listHosts,
|
|
181
|
+
auth,
|
|
182
|
+
onLog,
|
|
183
|
+
} = {}) {
|
|
184
|
+
const resolvedClient = client || (peerNode ? createPodHostClient({ peerNode }) : null)
|
|
185
|
+
if (!resolvedClient || typeof resolvedClient.spawn !== 'function') {
|
|
186
|
+
throw new Error('createPodHostGatewayHandler: client (or peerNode) is required')
|
|
187
|
+
}
|
|
188
|
+
if (typeof auth !== 'function') {
|
|
189
|
+
throw new Error(
|
|
190
|
+
'createPodHostGatewayHandler: auth(req) is required -- there is no default-open gateway '
|
|
191
|
+
+ '(see module doc comment\'s "IDENTITY CAVEAT")',
|
|
192
|
+
)
|
|
193
|
+
}
|
|
194
|
+
const hostResolver = normalizeHostResolver(resolveHost, listHosts)
|
|
195
|
+
const log = onLog || (() => {})
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* @param {Request} req
|
|
199
|
+
* @returns {Promise<Response>}
|
|
200
|
+
*/
|
|
201
|
+
async function handler(req) {
|
|
202
|
+
const url = new URL(req.url)
|
|
203
|
+
const method = (req.method || 'GET').toUpperCase()
|
|
204
|
+
|
|
205
|
+
if (method === 'GET' && url.pathname === '/hosts') {
|
|
206
|
+
const hosts = await hostResolver.list()
|
|
207
|
+
return jsonResponse(200, { ok: true, result: hosts })
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const hostMatch = url.pathname.match(/^\/hosts\/([^/]+)((?:\/.*)?)$/)
|
|
211
|
+
if (!hostMatch) {
|
|
212
|
+
return jsonResponse(404, { ok: false, error: { code: POD_HOST_ERROR.ENOENT, message: 'not found' } })
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
let hostToken
|
|
216
|
+
try {
|
|
217
|
+
hostToken = decodeURIComponent(hostMatch[1])
|
|
218
|
+
} catch {
|
|
219
|
+
return jsonResponse(400, { ok: false, error: { code: POD_HOST_ERROR.EINVAL, message: 'malformed host token' } })
|
|
220
|
+
}
|
|
221
|
+
const subPath = hostMatch[2] || ''
|
|
222
|
+
const match = matchPodHostRoute(method, subPath)
|
|
223
|
+
if (!match) {
|
|
224
|
+
return jsonResponse(404, { ok: false, error: { code: POD_HOST_ERROR.ENOENT, message: `no such route '${method} ${subPath}'` } })
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// Auth gates USE of the gateway; it does not change whose mesh identity
|
|
228
|
+
// the downstream checkAccess() call sees (see "IDENTITY CAVEAT" above).
|
|
229
|
+
const authResult = await auth(req)
|
|
230
|
+
if (!authResult || authResult.ok !== true) {
|
|
231
|
+
return jsonResponse(401, { ok: false, error: { code: POD_HOST_ERROR.EACCES, message: 'unauthorized' } })
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const hostPubKey = await hostResolver.resolve(hostToken)
|
|
235
|
+
if (!hostPubKey) {
|
|
236
|
+
return jsonResponse(404, { ok: false, error: { code: POD_HOST_ERROR.ENOENT, message: `unknown host '${hostToken}'` } })
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const bodyJson = await readHttpRequestBody(req)
|
|
240
|
+
|
|
241
|
+
try {
|
|
242
|
+
const result = await dispatchToClient(resolvedClient, hostPubKey, match.verb, match.params, bodyJson, url.searchParams)
|
|
243
|
+
if (match.verb === POD_HOST_DESCRIBE_VERB) return jsonResponse(200, { ok: true, result })
|
|
244
|
+
const status = successStatusForVerb(match.verb)
|
|
245
|
+
if (status === 204) return new Response(null, { status })
|
|
246
|
+
return jsonResponse(status, { ok: true, result })
|
|
247
|
+
} catch (err) {
|
|
248
|
+
const driverError = PodHostDriverError.from(err)
|
|
249
|
+
log('pod-host-gateway:verb-failed', {
|
|
250
|
+
host: hostToken, verb: match.verb, code: driverError.code, error: driverError.message,
|
|
251
|
+
})
|
|
252
|
+
const headers = { 'content-type': 'application/json' }
|
|
253
|
+
if (driverError.code === POD_HOST_ERROR.ELANE) {
|
|
254
|
+
// The remote error's `details` (which would carry `lane`) does not
|
|
255
|
+
// survive the wire -- pod-host-service.mjs's createHostResponse()
|
|
256
|
+
// only round-trips {code, message} (see its own toJSON()). Best
|
|
257
|
+
// effort: ask the host what it actually serves. Never let this
|
|
258
|
+
// extra round trip turn a real error response into a different
|
|
259
|
+
// failure -- any problem with it is swallowed and Allow is omitted.
|
|
260
|
+
try {
|
|
261
|
+
const description = await resolvedClient.describe(hostPubKey)
|
|
262
|
+
if (description && Array.isArray(description.verbs)) headers.allow = description.verbs.join(', ')
|
|
263
|
+
} catch {
|
|
264
|
+
// best-effort only
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
return new Response(JSON.stringify({ ok: false, error: driverError.toJSON() }), { status: statusForError(driverError.code), headers })
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
return handler
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// ---------------------------------------------------------------------------
|
|
275
|
+
// serveNodeGateway -- node:http adapter, lazily imported (see module doc
|
|
276
|
+
// comment on why this keeps test/browser-safe-entry.test.mjs passing).
|
|
277
|
+
// ---------------------------------------------------------------------------
|
|
278
|
+
|
|
279
|
+
/** Headers that are transport-level and should not be forwarded into the synthetic `Request`. */
|
|
280
|
+
const HOP_BY_HOP_HEADERS = new Set(['host', 'connection', 'content-length', 'transfer-encoding', 'keep-alive', 'upgrade'])
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Convert one incoming `node:http` request/response pair into a Web-standard
|
|
284
|
+
* `Request`, run `handler`, and write the resulting `Response` back out.
|
|
285
|
+
* @param {(req: Request) => Promise<Response>} handler
|
|
286
|
+
* @param {import('node:http').IncomingMessage} nodeReq
|
|
287
|
+
* @param {import('node:http').ServerResponse} nodeRes
|
|
288
|
+
*/
|
|
289
|
+
async function handleNodeRequest(handler, nodeReq, nodeRes) {
|
|
290
|
+
const host = nodeReq.headers.host || 'localhost'
|
|
291
|
+
const url = `http://${host}${nodeReq.url}`
|
|
292
|
+
|
|
293
|
+
const headers = new Headers()
|
|
294
|
+
for (const [key, value] of Object.entries(nodeReq.headers)) {
|
|
295
|
+
if (value === undefined || HOP_BY_HOP_HEADERS.has(key.toLowerCase())) continue
|
|
296
|
+
if (Array.isArray(value)) {
|
|
297
|
+
for (const v of value) headers.append(key, v)
|
|
298
|
+
} else {
|
|
299
|
+
headers.set(key, value)
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const method = (nodeReq.method || 'GET').toUpperCase()
|
|
304
|
+
let body
|
|
305
|
+
if (method !== 'GET' && method !== 'HEAD') {
|
|
306
|
+
const chunks = []
|
|
307
|
+
for await (const chunk of nodeReq) chunks.push(chunk)
|
|
308
|
+
if (chunks.length > 0) body = Buffer.concat(chunks)
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
const request = new Request(url, { method, headers, body })
|
|
312
|
+
const response = await handler(request)
|
|
313
|
+
|
|
314
|
+
/** @type {Record<string, string>} */
|
|
315
|
+
const resHeaders = {}
|
|
316
|
+
response.headers.forEach((value, key) => { resHeaders[key] = value })
|
|
317
|
+
nodeRes.writeHead(response.status, resHeaders)
|
|
318
|
+
|
|
319
|
+
if (response.body) {
|
|
320
|
+
const buf = Buffer.from(await response.arrayBuffer())
|
|
321
|
+
nodeRes.end(buf)
|
|
322
|
+
} else {
|
|
323
|
+
nodeRes.end()
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* Serve a Web-standard `(req: Request) => Promise<Response>` handler (e.g.
|
|
329
|
+
* `createPodHostGatewayHandler()`'s return value) over real `node:http`.
|
|
330
|
+
*
|
|
331
|
+
* @param {object} opts
|
|
332
|
+
* @param {(req: Request) => Promise<Response>} opts.handler
|
|
333
|
+
* @param {number} [opts.port=0] - `0` picks an ephemeral free port.
|
|
334
|
+
* @param {string} [opts.host='127.0.0.1']
|
|
335
|
+
* @returns {Promise<{server: import('node:http').Server, port: number, url: string, close: () => Promise<void>}>}
|
|
336
|
+
*/
|
|
337
|
+
export async function serveNodeGateway({ handler, port = 0, host = '127.0.0.1' } = {}) {
|
|
338
|
+
if (typeof handler !== 'function') {
|
|
339
|
+
throw new Error('serveNodeGateway: handler is required')
|
|
340
|
+
}
|
|
341
|
+
// Lazy -- see module doc comment. Only reached when this function is
|
|
342
|
+
// actually called, never merely by importing this module (or the package
|
|
343
|
+
// root, which re-exports it), so a browser bundle never resolves
|
|
344
|
+
// `node:http` just for being loaded.
|
|
345
|
+
const { createServer } = await import('node:http')
|
|
346
|
+
|
|
347
|
+
const server = createServer((nodeReq, nodeRes) => {
|
|
348
|
+
handleNodeRequest(handler, nodeReq, nodeRes).catch((err) => {
|
|
349
|
+
if (!nodeRes.headersSent) nodeRes.writeHead(500, { 'content-type': 'application/json' })
|
|
350
|
+
nodeRes.end(JSON.stringify({ ok: false, error: { code: POD_HOST_ERROR.EINVAL, message: err?.message || String(err) } }))
|
|
351
|
+
})
|
|
352
|
+
})
|
|
353
|
+
|
|
354
|
+
await new Promise((resolve, reject) => {
|
|
355
|
+
server.once('error', reject)
|
|
356
|
+
server.listen(port, host, () => resolve(undefined))
|
|
357
|
+
})
|
|
358
|
+
|
|
359
|
+
const address = server.address()
|
|
360
|
+
const actualPort = address && typeof address === 'object' ? address.port : port
|
|
361
|
+
|
|
362
|
+
return {
|
|
363
|
+
server,
|
|
364
|
+
port: actualPort,
|
|
365
|
+
url: `http://${host}:${actualPort}`,
|
|
366
|
+
close() {
|
|
367
|
+
return new Promise((resolve, reject) => {
|
|
368
|
+
server.close((err) => (err ? reject(err) : resolve(undefined)))
|
|
369
|
+
})
|
|
370
|
+
},
|
|
371
|
+
}
|
|
372
|
+
}
|