@johnhenry/browsermesh-apps 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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
+ }