@johnhenry/browsermesh-apps 0.11.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.
@@ -0,0 +1,630 @@
1
+ /**
2
+ * pod-host-routes.mjs -- issue #185 control-surface item 3: an HTTP-shaped
3
+ * view of `pod-host-service.mjs` over `mesh://` URLs.
4
+ *
5
+ * `docs/hosted-pods.md` §8a calls every later control surface "a projection
6
+ * of the same eight verbs" defined in `@johnhenry/browsermesh-pod`'s
7
+ * `host-protocol.mjs`. This file is that projection for HTTP: a route table
8
+ * (`POD_HOST_ROUTES` / `matchPodHostRoute()`) mapping `METHOD /pods...` onto
9
+ * a verb, a host-side router (`createPodHostRouter()`) that answers those
10
+ * routes against a `PodHostDriver`, and a requester-side client
11
+ * (`podHostFetch()`) built on `browserMeshFetch()`.
12
+ *
13
+ * ---------------------------------------------------------------------------
14
+ * THE HOST-SIDE MOUNT POINT (read `mesh-fetch.mjs`'s module doc comment
15
+ * before this one if you haven't -- it explains why).
16
+ *
17
+ * `browserMeshFetch(url, init)` is a *caller*-side wrapper: it resolves a
18
+ * `mesh://<podId>/path` URL and round-trips it through a live `mesh-rpc`
19
+ * service's `api.request(podId, {method, path, headers, body})`
20
+ * (`mesh-rpc.mjs`, Phase 1 of the BrowserMeshFetch plan). The HOST side that
21
+ * actually *answers* an inbound request is `createMeshRpcService({
22
+ * onRequest })`'s `onRequest` callback -- `(req: {fromPubKey, method, path,
23
+ * headers, body}) => Promise<{status?, headers?, body?}>` -- exactly the
24
+ * slot `examples/08-mesh-fetch-websocket.mjs` and
25
+ * `serverless-router.mjs`'s `createSiteRequestHandler()` already plug into.
26
+ * That slot was ALREADY fully composable (any function works); no change to
27
+ * `mesh-fetch.mjs` or `mesh-rpc.mjs` was needed to mount this router there.
28
+ *
29
+ * `MeshFetchRouter` (`@johnhenry/browsermesh-discovery`'s `sw-routing.mjs`)
30
+ * is a *different*, Service-Worker-shaped thing: `Request -> Promise<Response
31
+ * |null>`, used client-side to intercept `fetch` events. `createPodHostRouter
32
+ * ().route()` below is deliberately shaped to MATCH that same `Request ->
33
+ * Promise<Response|null>` signature (so it reads the same way to anyone who
34
+ * already knows `MeshFetchRouter`, and so it can serve the Node HTTP gateway
35
+ * in `pod-host-gateway.mjs` without any reshaping) -- but it is NOT
36
+ * `MeshFetchRouter` itself and is not mounted there. It is mounted on the
37
+ * mesh side via `createPodHostMeshRpcHandler()` below, which adapts between
38
+ * `route()`'s `Request`/`Response` shape and `onRequest`'s plain-object
39
+ * `{method,path,headers,body}`/`{status,headers,body}` shape:
40
+ *
41
+ * import { attachService, createMeshRpcService } from '@johnhenry/browsermesh-apps'
42
+ * import { createPodHostRouter, createPodHostMeshRpcHandler } from '@johnhenry/browsermesh-apps'
43
+ *
44
+ * const router = createPodHostRouter({ driver, registry: peerNode.registry })
45
+ * attachService(peerNode, undefined, createMeshRpcService({
46
+ * onRequest: createPodHostMeshRpcHandler(router),
47
+ * }))
48
+ *
49
+ * ---------------------------------------------------------------------------
50
+ * ACCESS CONTROL -- NO BYPASS. `mesh-rpc.mjs` itself checks nothing (see its
51
+ * own "AUTHORIZATION IS EXPLICITLY OUT OF SCOPE" doc comment); authorization
52
+ * is this router's job, same as `pod-host-service.mjs`'s `handleRequest()`.
53
+ * `createPodHostService()`'s `attach()` returns an `api` whose `dispatch(
54
+ * pubKey, verb, payload)` is the ONE gated path (gate + validate + lane check
55
+ * + audit + events); when `api` is supplied this router calls it and nothing
56
+ * else. `api.driver` stays the raw, UNGATED driver and is never used to
57
+ * answer a request. Only a router built from a bare `driver` (no `api`) falls
58
+ * back to a standalone copy of the same steps, calling
59
+ * `registry.checkAccess(pubKey, resource, verb)` on the explicitly-supplied
60
+ * `registry` (`peerNode.registry` -- see `mesh-service.mjs`'s `ctx.registry`).
61
+ *
62
+ * The requester's pubKey travels from `createPodHostMeshRpcHandler()`'s
63
+ * `fromPubKey` into the synthetic `Request` as the `MESH_FROM_HEADER`
64
+ * header, set LAST (after copying the caller's own headers) so a malicious
65
+ * peer cannot spoof it by sending a same-named header of their own -- see
66
+ * that function's own comment.
67
+ *
68
+ * ---------------------------------------------------------------------------
69
+ * STATUS MAPPING: ok -> 200 (201 spawn, 204 drain -- no body, per HTTP's
70
+ * "204 must not carry a body" rule); EINVAL -> 400; EACCES -> 403; ENOENT ->
71
+ * 404; EEXIST -> 409; ELANE -> 405 with an `Allow` header listing the verbs
72
+ * the driver's LANE supports (not HTTP methods -- this is a deliberate,
73
+ * documented deviation from classic `Allow` semantics, matching the verb
74
+ * vocabulary this whole surface is built from); ENOTSUP -> 501; ETIMEDOUT ->
75
+ * 504; EBUSY -> 409; anything else -> 500. `statusForError()` /
76
+ * `successStatusForVerb()` are exported so `pod-host-gateway.mjs` applies
77
+ * the identical mapping.
78
+ *
79
+ * No browser-only imports, no `node:` imports -- this file must load
80
+ * unchanged in a browser, Node, or a Worker.
81
+ */
82
+
83
+ import {
84
+ POD_HOST_VERB,
85
+ POD_HOST_ERROR,
86
+ POD_LANE_VERBS,
87
+ laneSupports,
88
+ validateVerbRequest,
89
+ PodHostDriverError,
90
+ } from '@johnhenry/browsermesh-pod'
91
+ import { DEFAULT_POD_HOST_RESOURCE } from './pod-host-service.mjs'
92
+
93
+ /** Route-table sentinel for `GET /host` -- NOT one of the eight `POD_HOST_VERB`s (see module doc comment and `pod-host-service.mjs`'s own `POD_HOST_DESCRIBE` doc comment: describe is ungated, host metadata, not a verb). */
94
+ export const POD_HOST_DESCRIBE_VERB = 'describe'
95
+
96
+ /** Header `createPodHostMeshRpcHandler()` uses to carry the requester's pubKey from the mesh-rpc envelope into the synthetic `Request` the router reads. Internal wiring detail, exported only so tests can construct an equivalent `Request` directly. */
97
+ export const MESH_FROM_HEADER = 'x-mesh-from-pubkey'
98
+
99
+ /** Same grammar as `host-protocol.mjs`'s own (private) `NAME_PATTERN` -- duplicated on purpose, the same way `POD_LANE` is duplicated there, so this file has no dependency beyond the verb/error/validator exports. */
100
+ const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/
101
+
102
+ /**
103
+ * The whole HTTP projection of the eight-verb control surface, plus
104
+ * `describe`. `path` segments starting with `:` are params; `:name` is
105
+ * additionally validated against `NAME_PATTERN` by `matchPodHostRoute()`
106
+ * (an invalid name means NO match, i.e. `null`, not a route match that then
107
+ * fails validation downstream).
108
+ */
109
+ export const POD_HOST_ROUTES = Object.freeze([
110
+ Object.freeze({ method: 'GET', path: '/pods', verb: POD_HOST_VERB.LIST }),
111
+ Object.freeze({ method: 'POST', path: '/pods', verb: POD_HOST_VERB.SPAWN }),
112
+ Object.freeze({ method: 'GET', path: '/pods/:name', verb: POD_HOST_VERB.STATUS }),
113
+ Object.freeze({ method: 'POST', path: '/pods/:name/send', verb: POD_HOST_VERB.SEND }),
114
+ Object.freeze({ method: 'POST', path: '/pods/:name/exec', verb: POD_HOST_VERB.EXEC }),
115
+ Object.freeze({ method: 'POST', path: '/pods/:name/snapshot', verb: POD_HOST_VERB.SNAPSHOT }),
116
+ Object.freeze({ method: 'POST', path: '/pods/:name/restore', verb: POD_HOST_VERB.RESTORE }),
117
+ Object.freeze({ method: 'DELETE', path: '/pods/:name', verb: POD_HOST_VERB.DRAIN }),
118
+ Object.freeze({ method: 'GET', path: '/host', verb: POD_HOST_DESCRIBE_VERB }),
119
+ ])
120
+
121
+ /** @param {string} pathname @returns {string[]} */
122
+ function splitPath(pathname) {
123
+ // Linear scan rather than a regex: this runs on attacker-supplied paths.
124
+ const text = String(pathname || '')
125
+ let start = 0
126
+ let end = text.length
127
+ while (start < end && text[start] === '/') start++
128
+ while (end > start && text[end - 1] === '/') end--
129
+ const trimmed = text.slice(start, end)
130
+ return trimmed === '' ? [] : trimmed.split('/')
131
+ }
132
+
133
+ /**
134
+ * Match an HTTP method + pathname against `POD_HOST_ROUTES`.
135
+ *
136
+ * @param {string} method
137
+ * @param {string} pathname - No query string (use `new URL(url).pathname`).
138
+ * @returns {{verb: string, params: {name?: string}}|null} `null` for no
139
+ * match, including a `:name` segment that fails `NAME_PATTERN`.
140
+ */
141
+ export function matchPodHostRoute(method, pathname) {
142
+ if (typeof method !== 'string' || typeof pathname !== 'string') return null
143
+ const upperMethod = method.toUpperCase()
144
+ const segments = splitPath(pathname)
145
+
146
+ for (const route of POD_HOST_ROUTES) {
147
+ if (route.method !== upperMethod) continue
148
+ const routeSegments = splitPath(route.path)
149
+ if (routeSegments.length !== segments.length) continue
150
+
151
+ /** @type {Record<string, string>} */
152
+ const params = {}
153
+ let matched = true
154
+ for (let i = 0; i < routeSegments.length; i += 1) {
155
+ const rs = routeSegments[i]
156
+ const seg = segments[i]
157
+ if (rs.startsWith(':')) {
158
+ const key = rs.slice(1)
159
+ let value
160
+ try {
161
+ value = decodeURIComponent(seg)
162
+ } catch {
163
+ matched = false
164
+ break
165
+ }
166
+ if (key === 'name' && !NAME_PATTERN.test(value)) {
167
+ matched = false
168
+ break
169
+ }
170
+ params[key] = value
171
+ } else if (rs !== seg) {
172
+ matched = false
173
+ break
174
+ }
175
+ }
176
+ if (matched) return { verb: route.verb, params }
177
+ }
178
+ return null
179
+ }
180
+
181
+ /** @type {Readonly<Record<string, number>>} */
182
+ const ERROR_STATUS = Object.freeze({
183
+ [POD_HOST_ERROR.EINVAL]: 400,
184
+ [POD_HOST_ERROR.EACCES]: 403,
185
+ [POD_HOST_ERROR.ENOENT]: 404,
186
+ [POD_HOST_ERROR.EEXIST]: 409,
187
+ [POD_HOST_ERROR.ELANE]: 405,
188
+ [POD_HOST_ERROR.ENOTSUP]: 501,
189
+ [POD_HOST_ERROR.ETIMEDOUT]: 504,
190
+ [POD_HOST_ERROR.EBUSY]: 409,
191
+ })
192
+
193
+ /**
194
+ * Map a `POD_HOST_ERROR` code to an HTTP status. An unknown code -- which
195
+ * should not happen, since every `PodHostDriverError` carries one of the
196
+ * eight -- maps to 500 rather than throwing, so a surprising error never
197
+ * breaks response-building itself.
198
+ * @param {string} code
199
+ * @returns {number}
200
+ */
201
+ export function statusForError(code) {
202
+ return ERROR_STATUS[code] ?? 500
203
+ }
204
+
205
+ /**
206
+ * The success status for a verb: 201 for `spawn` (a new pod was created),
207
+ * 204 for `drain` (no body -- see module doc comment), 200 for everything
208
+ * else including `describe`.
209
+ * @param {string} verb
210
+ * @returns {number}
211
+ */
212
+ export function successStatusForVerb(verb) {
213
+ if (verb === POD_HOST_VERB.SPAWN) return 201
214
+ if (verb === POD_HOST_VERB.DRAIN) return 204
215
+ return 200
216
+ }
217
+
218
+ /** @param {number} status @param {object} body @returns {Response} */
219
+ function jsonResponse(status, body) {
220
+ return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })
221
+ }
222
+
223
+ /**
224
+ * Read and JSON-parse a `Request`'s body, mirroring `MeshFetchRouter.route()`
225
+ * /`mesh-fetch.mjs`'s own body handling: GET/HEAD never have a body; a
226
+ * non-JSON body is kept as the raw string rather than erroring (the verb
227
+ * payload validator downstream will reject it with a clear `EINVAL` if a
228
+ * verb actually required an object).
229
+ * @param {Request} request
230
+ * @returns {Promise<*>}
231
+ */
232
+ export async function readHttpRequestBody(request) {
233
+ const method = (request.method || 'GET').toUpperCase()
234
+ if (method === 'GET' || method === 'HEAD') return undefined
235
+ let text = ''
236
+ try {
237
+ text = await request.text()
238
+ } catch {
239
+ return undefined
240
+ }
241
+ if (!text) return undefined
242
+ try {
243
+ return JSON.parse(text)
244
+ } catch {
245
+ return text
246
+ }
247
+ }
248
+
249
+ /**
250
+ * Build the raw (pre-`validateVerbRequest()`) payload for a verb from its
251
+ * HTTP parts: the `:name` path param, the parsed JSON body, and (for
252
+ * `drain`) the `?cascade=` query param.
253
+ * @param {string} verb
254
+ * @param {{name?: string}} params
255
+ * @param {*} bodyJson
256
+ * @param {URLSearchParams} searchParams
257
+ * @returns {object}
258
+ */
259
+ function buildRawPayload(verb, params, bodyJson, searchParams) {
260
+ const body = bodyJson && typeof bodyJson === 'object' ? bodyJson : {}
261
+ switch (verb) {
262
+ case POD_HOST_VERB.SPAWN:
263
+ return body
264
+ case POD_HOST_VERB.STATUS:
265
+ case POD_HOST_VERB.SNAPSHOT:
266
+ case POD_HOST_VERB.RESTORE:
267
+ return { name: params.name }
268
+ case POD_HOST_VERB.SEND: {
269
+ const payload = { name: params.name, payload: body.payload }
270
+ if (body.to !== undefined) payload.to = body.to
271
+ return payload
272
+ }
273
+ case POD_HOST_VERB.EXEC: {
274
+ const payload = { name: params.name, command: body.command }
275
+ if (body.timeoutMs !== undefined) payload.timeoutMs = body.timeoutMs
276
+ return payload
277
+ }
278
+ case POD_HOST_VERB.DRAIN: {
279
+ const payload = { name: params.name }
280
+ const cascadeParam = searchParams.get('cascade')
281
+ if (cascadeParam !== null) payload.cascade = cascadeParam === 'true'
282
+ return payload
283
+ }
284
+ case POD_HOST_VERB.LIST:
285
+ default:
286
+ return {}
287
+ }
288
+ }
289
+
290
+ /**
291
+ * Dispatch a validated verb request to a `PodHostDriver`. Mirrors
292
+ * `pod-host-service.mjs`'s own (unexported) `dispatch()` switch exactly --
293
+ * duplicated rather than imported because that function is a closure inside
294
+ * `createPodHostService()`'s `attach()`, not a module-level export.
295
+ * @param {import('@johnhenry/browsermesh-pod').PodHostDriver} driver
296
+ * @param {string} verb
297
+ * @param {object} value - `validateVerbRequest()`'s normalized `value`.
298
+ * @returns {Promise<*>}
299
+ */
300
+ function dispatchToDriver(driver, verb, value) {
301
+ switch (verb) {
302
+ case POD_HOST_VERB.SPAWN:
303
+ return driver.spawn(value)
304
+ case POD_HOST_VERB.STATUS:
305
+ return driver.status(value.name)
306
+ case POD_HOST_VERB.SEND:
307
+ return driver.send(value.name, { to: value.to, payload: value.payload })
308
+ case POD_HOST_VERB.EXEC:
309
+ return driver.exec(value.name, value.command, { timeoutMs: value.timeoutMs })
310
+ case POD_HOST_VERB.SNAPSHOT:
311
+ return driver.snapshot(value.name)
312
+ case POD_HOST_VERB.RESTORE:
313
+ return driver.restore(value.name)
314
+ case POD_HOST_VERB.DRAIN:
315
+ return driver.drain(value.name, { cascade: value.cascade })
316
+ case POD_HOST_VERB.LIST:
317
+ default:
318
+ return driver.list()
319
+ }
320
+ }
321
+
322
+ /**
323
+ * Refuse a verb before the driver is ever called -- `ELANE` when the lane
324
+ * structurally cannot, `ENOTSUP` when this driver simply does not serve it.
325
+ * Mirrors `pod-host-service.mjs`'s own `verbRefusal()` closure.
326
+ * @param {import('@johnhenry/browsermesh-pod').PodHostDriver} driver
327
+ * @param {string} verb
328
+ * @returns {PodHostDriverError|null}
329
+ */
330
+ function verbRefusal(driver, verb) {
331
+ const caps = typeof driver.capabilities === 'function' ? driver.capabilities() : { verbs: [] }
332
+ const verbs = Array.isArray(caps.verbs) ? caps.verbs : []
333
+ // Lane first, driver second -- same order as pod-host-service.mjs.
334
+ if (!laneSupports(driver.lane, verb)) {
335
+ return new PodHostDriverError(POD_HOST_ERROR.ELANE, `lane '${driver.lane}' cannot '${verb}'`, { verb, lane: driver.lane })
336
+ }
337
+ if (verbs.includes(verb) && typeof driver[verb] === 'function') return null
338
+ return new PodHostDriverError(POD_HOST_ERROR.ENOTSUP, `host does not implement '${verb}'`, { verb, lane: driver.lane })
339
+ }
340
+
341
+ /** @param {import('@johnhenry/browsermesh-pod').PodHostDriver} driver @returns {string} */
342
+ function allowHeaderForLane(driver) {
343
+ return (POD_LANE_VERBS[driver.lane] || []).join(', ')
344
+ }
345
+
346
+ /**
347
+ * Build the host-side router: `route(request) -> Promise<Response|null>`,
348
+ * shaped like `MeshFetchRouter.route()` (see module doc comment for why
349
+ * that shape and not `MeshFetchRouter` itself).
350
+ *
351
+ * @param {object} opts
352
+ * @param {import('@johnhenry/browsermesh-pod').PodHostDriver} [opts.driver]
353
+ * The lane adapter. Required unless `opts.api` carries one.
354
+ * @param {{driver?: object, resource?: string, describe?: Function}} [opts.api]
355
+ * The `.api` an `attachService(peerNode, undefined, createPodHostService(...))`
356
+ * handle returns. Supplies `driver`/`resource`/`describe()` as fallbacks
357
+ * when not given directly -- NEVER used to bypass `checkAccess()` (see
358
+ * module doc comment: `api` has no gated-dispatch method to route through).
359
+ * @param {import('./peer-registry.mjs').PeerRegistry} opts.registry -
360
+ * REQUIRED. `peerNode.registry` -- what `checkAccess()` is called against.
361
+ * Neither `driver` nor `api` carries a registry reference, so this must be
362
+ * supplied explicitly; there is no default.
363
+ * @param {string} [opts.resource='pod-host'] - ACL resource, same grammar as
364
+ * `createPodHostService({resource})`.
365
+ * @param {Function} [opts.onLog] - `(event, data) => void` debug logging.
366
+ * @returns {{route: (request: Request) => Promise<Response|null>, describe: () => object}}
367
+ */
368
+ export function createPodHostRouter({ driver, api, registry, resource, onLog } = {}) {
369
+ const resolvedDriver = driver || api?.driver
370
+ if (!resolvedDriver || typeof resolvedDriver !== 'object' || typeof resolvedDriver.lane !== 'string') {
371
+ throw new Error('createPodHostRouter: driver (or api with a .driver) is required')
372
+ }
373
+ if (!registry || typeof registry.checkAccess !== 'function') {
374
+ throw new Error(
375
+ 'createPodHostRouter: registry (a PeerRegistry, e.g. peerNode.registry) is required -- '
376
+ + 'see this module\'s doc comment on why it cannot be defaulted or derived from api',
377
+ )
378
+ }
379
+ const resolvedResource = resource || api?.resource || DEFAULT_POD_HOST_RESOURCE
380
+ const log = onLog || (() => {})
381
+
382
+ function describe() {
383
+ if (api && typeof api.describe === 'function') return api.describe()
384
+ const caps = typeof resolvedDriver.capabilities === 'function' ? resolvedDriver.capabilities() : { verbs: [] }
385
+ const verbs = Array.isArray(caps.verbs) ? caps.verbs : []
386
+ return {
387
+ podId: null,
388
+ lane: resolvedDriver.lane,
389
+ verbs: [...verbs],
390
+ runtimeClasses: [resolvedDriver.lane],
391
+ shellBackend: null,
392
+ deploymentSupport: { canDeploy: verbs.includes(POD_HOST_VERB.SPAWN) },
393
+ capabilities: ['pod-host', ...(verbs.includes(POD_HOST_VERB.EXEC) ? ['exec'] : [])],
394
+ resource: resolvedResource,
395
+ hostLabel: null,
396
+ }
397
+ }
398
+
399
+ /**
400
+ * @param {Request} request
401
+ * @returns {Promise<Response|null>}
402
+ */
403
+ async function route(request) {
404
+ const url = new URL(request.url)
405
+ const method = (request.method || 'GET').toUpperCase()
406
+ const match = matchPodHostRoute(method, url.pathname)
407
+ if (!match) return null
408
+
409
+ if (match.verb === POD_HOST_DESCRIBE_VERB) {
410
+ // Ungated, mirrors pod-host-service.mjs's POD_HOST_DESCRIBE handling
411
+ // (see its own module doc comment) -- a peer must be able to discover
412
+ // a host before it can be granted anything on it.
413
+ return jsonResponse(200, { ok: true, result: describe() })
414
+ }
415
+
416
+ const verb = match.verb
417
+ const pubKey = request.headers.get(MESH_FROM_HEADER)
418
+ if (!pubKey) {
419
+ return jsonResponse(400, {
420
+ ok: false,
421
+ error: { code: POD_HOST_ERROR.EINVAL, message: `missing requester identity ('${MESH_FROM_HEADER}' header)` },
422
+ })
423
+ }
424
+
425
+ // Preferred path: the attached service's own gated dispatch (ONE copy
426
+ // of gate + validate + lane check + audit + events). Only when the
427
+ // router was built from a bare driver does it fall through to the
428
+ // standalone re-implementation below.
429
+ if (api && typeof api.dispatch === 'function') {
430
+ const bodyJson = await readHttpRequestBody(request)
431
+ const rawPayload = buildRawPayload(verb, match.params, bodyJson, url.searchParams)
432
+ try {
433
+ const result = await api.dispatch(pubKey, verb, rawPayload)
434
+ const status = successStatusForVerb(verb)
435
+ if (status === 204) return new Response(null, { status })
436
+ return jsonResponse(status, { ok: true, result })
437
+ } catch (err) {
438
+ const driverError = PodHostDriverError.from(err)
439
+ log('pod-host-router:verb-failed', { from: pubKey, verb, code: driverError.code, error: driverError.message })
440
+ const headers = { 'content-type': 'application/json' }
441
+ if (driverError.code === POD_HOST_ERROR.ELANE) headers.allow = allowHeaderForLane(resolvedDriver)
442
+ return new Response(JSON.stringify({ ok: false, error: driverError.toJSON() }), { status: statusForError(driverError.code), headers })
443
+ }
444
+ }
445
+
446
+ // 1. Gate -- the same checkAccess() pod-host-service.mjs itself calls.
447
+ const check = registry.checkAccess(pubKey, resolvedResource, verb)
448
+ if (!check.allowed) {
449
+ log('pod-host-router:denied', { from: pubKey, verb, reason: check.reason })
450
+ return jsonResponse(403, {
451
+ ok: false,
452
+ error: { code: POD_HOST_ERROR.EACCES, message: `not authorized for '${resolvedResource}:${verb}'` },
453
+ })
454
+ }
455
+
456
+ // 2. Validate (and normalize) before anything reaches the driver.
457
+ const bodyJson = await readHttpRequestBody(request)
458
+ const rawPayload = buildRawPayload(verb, match.params, bodyJson, url.searchParams)
459
+ const validated = validateVerbRequest(verb, rawPayload)
460
+ if (!validated.ok) {
461
+ return jsonResponse(400, { ok: false, error: { code: POD_HOST_ERROR.EINVAL, message: validated.errors.join('; ') } })
462
+ }
463
+
464
+ // 3. Lane / driver capability.
465
+ const refusal = verbRefusal(resolvedDriver, verb)
466
+ if (refusal) {
467
+ const headers = { 'content-type': 'application/json' }
468
+ if (refusal.code === POD_HOST_ERROR.ELANE) headers.allow = allowHeaderForLane(resolvedDriver)
469
+ return new Response(JSON.stringify({ ok: false, error: refusal.toJSON() }), { status: statusForError(refusal.code), headers })
470
+ }
471
+
472
+ // 4. Dispatch.
473
+ try {
474
+ const result = await dispatchToDriver(resolvedDriver, verb, validated.value)
475
+ const status = successStatusForVerb(verb)
476
+ if (status === 204) return new Response(null, { status })
477
+ return jsonResponse(status, { ok: true, result })
478
+ } catch (err) {
479
+ const driverError = PodHostDriverError.from(err)
480
+ log('pod-host-router:verb-failed', { from: pubKey, verb, code: driverError.code, error: driverError.message })
481
+ const headers = { 'content-type': 'application/json' }
482
+ if (driverError.code === POD_HOST_ERROR.ELANE) headers.allow = allowHeaderForLane(resolvedDriver)
483
+ return new Response(JSON.stringify({ ok: false, error: driverError.toJSON() }), { status: statusForError(driverError.code), headers })
484
+ }
485
+ }
486
+
487
+ return { route, describe }
488
+ }
489
+
490
+ /**
491
+ * Adapt a `createPodHostRouter()` router's `route(request)` into the
492
+ * `onRequest` shape `createMeshRpcService()` expects -- the composition hook
493
+ * that actually mounts this router under `mesh://` (see module doc
494
+ * comment). Builds a synthetic `Request` from the mesh-rpc envelope's
495
+ * `{method, path, headers, body}`, and converts the resulting `Response`
496
+ * back into `{status, headers, body}`.
497
+ *
498
+ * @param {{route: (request: Request) => Promise<Response|null>}} router
499
+ * @returns {(req: {fromPubKey: string, method?: string, path?: string, headers?: object, body?: *}) => Promise<{status: number, headers: object, body: *}>}
500
+ */
501
+ export function createPodHostMeshRpcHandler(router) {
502
+ if (!router || typeof router.route !== 'function') {
503
+ throw new Error('createPodHostMeshRpcHandler: router (from createPodHostRouter()) is required')
504
+ }
505
+
506
+ return async function onRequest({ fromPubKey, method = 'GET', path = '/', headers, body } = {}) {
507
+ const reqHeaders = new Headers()
508
+ if (headers && typeof headers === 'object') {
509
+ for (const [key, value] of Object.entries(headers)) {
510
+ if (value === undefined || value === null) continue
511
+ reqHeaders.set(key, String(value))
512
+ }
513
+ }
514
+ // Set LAST and unconditionally -- never let a client-supplied header of
515
+ // the same name spoof the identity checkAccess() will see (see module
516
+ // doc comment).
517
+ reqHeaders.set(MESH_FROM_HEADER, fromPubKey || '')
518
+
519
+ const upperMethod = String(method || 'GET').toUpperCase()
520
+ const url = `http://pod-host.internal${path.startsWith('/') ? path : `/${path}`}`
521
+ /** @type {RequestInit} */
522
+ const init = { method: upperMethod, headers: reqHeaders }
523
+ if (upperMethod !== 'GET' && upperMethod !== 'HEAD' && body !== undefined) {
524
+ init.body = typeof body === 'string' ? body : JSON.stringify(body)
525
+ if (!reqHeaders.has('content-type')) reqHeaders.set('content-type', 'application/json')
526
+ }
527
+
528
+ const response = await router.route(new Request(url, init))
529
+ if (!response) {
530
+ return { status: 404, headers: { 'content-type': 'application/json' }, body: { error: 'not found' } }
531
+ }
532
+
533
+ /** @type {Record<string, string>} */
534
+ const resHeaders = {}
535
+ response.headers.forEach((value, key) => { resHeaders[key] = value })
536
+
537
+ const text = await response.text()
538
+ let resBody
539
+ if (!text) {
540
+ resBody = undefined
541
+ } else {
542
+ try {
543
+ resBody = JSON.parse(text)
544
+ } catch {
545
+ resBody = text
546
+ }
547
+ }
548
+ return { status: response.status, headers: resHeaders, body: resBody }
549
+ }
550
+ }
551
+
552
+ // ---------------------------------------------------------------------------
553
+ // podHostFetch -- "control from within": a tiny client built on
554
+ // browserMeshFetch, for callers who already have one bound and would rather
555
+ // call fetch-shaped methods than build pod-host:* envelopes by hand.
556
+ // ---------------------------------------------------------------------------
557
+
558
+ /**
559
+ * @typedef {object} PodHostFetchClient
560
+ * @property {() => Promise<object[]>} list
561
+ * @property {(spec: object) => Promise<object>} spawn
562
+ * @property {(name: string) => Promise<object>} status
563
+ * @property {(name: string, payload: *, opts?: {to?: string}) => Promise<object>} send
564
+ * @property {(name: string, command: string[]|string, opts?: {timeoutMs?: number}) => Promise<{stdout: string, stderr: string, code: number}>} exec
565
+ * @property {(name: string) => Promise<object>} snapshot
566
+ * @property {(name: string) => Promise<object>} restore
567
+ * @property {(name: string, opts?: {cascade?: boolean}) => Promise<void>} drain
568
+ * @property {() => Promise<object>} describe
569
+ */
570
+
571
+ /**
572
+ * Build a `PodHostFetchClient` bound to one host, over `mesh://<hostPodId>/pods...`.
573
+ *
574
+ * @param {string} hostPodId
575
+ * @param {object} opts
576
+ * @param {(url: string, init?: object) => Promise<Response>} opts.fetch -
577
+ * REQUIRED. Typically `createBrowserMeshFetch(meshRpcApi)`'s return value
578
+ * (`mesh-fetch.mjs`) -- there is no sensible default: unlike real
579
+ * `fetch()`, a `mesh://` URL needs a live mesh-rpc binding to resolve.
580
+ * @returns {PodHostFetchClient}
581
+ */
582
+ export function podHostFetch(hostPodId, { fetch } = {}) {
583
+ if (!hostPodId || typeof hostPodId !== 'string') {
584
+ throw new Error('podHostFetch: hostPodId is required')
585
+ }
586
+ if (typeof fetch !== 'function') {
587
+ throw new Error('podHostFetch: fetch (e.g. createBrowserMeshFetch(meshRpcApi)) is required')
588
+ }
589
+
590
+ const base = `mesh://${hostPodId}`
591
+
592
+ /**
593
+ * @param {string} method
594
+ * @param {string} path
595
+ * @param {*} [body]
596
+ * @returns {Promise<*>}
597
+ */
598
+ async function call(method, path, body) {
599
+ const res = await fetch(`${base}${path}`, body === undefined ? { method } : { method, body })
600
+ let json = null
601
+ try {
602
+ json = await res.json()
603
+ } catch {
604
+ // No body (e.g. a 204 from drain) or a non-JSON body -- leave json null.
605
+ }
606
+ if (!res.ok) {
607
+ const error = (json && json.error) || { code: POD_HOST_ERROR.EINVAL, message: `request failed with status ${res.status}` }
608
+ throw new PodHostDriverError(error.code, error.message)
609
+ }
610
+ return json ? json.result : undefined
611
+ }
612
+
613
+ return {
614
+ list: () => call('GET', '/pods'),
615
+ spawn: (spec) => call('POST', '/pods', spec),
616
+ status: (name) => call('GET', `/pods/${encodeURIComponent(name)}`),
617
+ send: (name, payload, { to } = {}) => call(
618
+ 'POST', `/pods/${encodeURIComponent(name)}/send`, to === undefined ? { payload } : { payload, to },
619
+ ),
620
+ exec: (name, command, { timeoutMs } = {}) => call(
621
+ 'POST', `/pods/${encodeURIComponent(name)}/exec`, timeoutMs === undefined ? { command } : { command, timeoutMs },
622
+ ),
623
+ snapshot: (name) => call('POST', `/pods/${encodeURIComponent(name)}/snapshot`),
624
+ restore: (name) => call('POST', `/pods/${encodeURIComponent(name)}/restore`),
625
+ drain: (name, { cascade } = {}) => call(
626
+ 'DELETE', `/pods/${encodeURIComponent(name)}${cascade ? '?cascade=true' : ''}`,
627
+ ),
628
+ describe: () => call('GET', '/host'),
629
+ }
630
+ }