@johnhenry/browsermesh-apps 0.2.0 → 0.4.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.
Files changed (50) hide show
  1. package/README.md +232 -1
  2. package/package.json +7 -3
  3. package/src/agent-runtime.mjs +342 -0
  4. package/src/chunk-replication.mjs +751 -0
  5. package/src/cloud-storage-backend.mjs +932 -0
  6. package/src/cloud-storage.mjs +859 -0
  7. package/src/compat.mjs +98 -0
  8. package/src/grant-log.mjs +840 -0
  9. package/src/index.mjs +34 -2
  10. package/src/key-distribution.mjs +525 -0
  11. package/src/manifest-sync.mjs +363 -0
  12. package/src/mesh-agent-swarm.mjs +376 -0
  13. package/src/mesh-bootstrap.mjs +1131 -12
  14. package/src/mesh-compute.mjs +397 -0
  15. package/src/mesh-dht.mjs +182 -0
  16. package/src/mesh-fetch.mjs +246 -0
  17. package/src/mesh-hardening.mjs +226 -0
  18. package/src/mesh-health.mjs +282 -0
  19. package/src/mesh-keepalive.mjs +353 -0
  20. package/src/mesh-kv.mjs +673 -0
  21. package/src/mesh-orchestrator-tools.mjs +251 -0
  22. package/src/mesh-orchestrator.mjs +343 -0
  23. package/src/mesh-rpc.mjs +300 -0
  24. package/src/mesh-service.mjs +403 -0
  25. package/src/mesh-swarm.mjs +677 -0
  26. package/src/mesh-timestamp.mjs +265 -0
  27. package/src/mesh-torrent.mjs +683 -0
  28. package/src/mesh-verification.mjs +367 -0
  29. package/src/mesh-websocket.mjs +722 -0
  30. package/src/observability-bridge.mjs +453 -0
  31. package/src/orchestrator.mjs +18 -5
  32. package/src/peer-agent-swarm.mjs +12 -1
  33. package/src/peer-chat.mjs +230 -61
  34. package/src/peer-compute.mjs +66 -3
  35. package/src/peer-escrow.mjs +350 -1
  36. package/src/peer-files.mjs +362 -168
  37. package/src/peer-ipfs.mjs +205 -10
  38. package/src/peer-node.mjs +33 -2
  39. package/src/peer-routing.mjs +369 -5
  40. package/src/peer-terminal.mjs +400 -130
  41. package/src/serverless-executor-andbox.mjs +136 -0
  42. package/src/serverless-fetch.mjs +70 -0
  43. package/src/serverless-functions.mjs +67 -0
  44. package/src/serverless-peer-select.mjs +69 -0
  45. package/src/serverless-proxy.mjs +127 -0
  46. package/src/serverless-router.mjs +115 -0
  47. package/src/serverless-sites.mjs +116 -0
  48. package/src/serverless-static.mjs +202 -0
  49. package/src/serverless-wire.mjs +87 -0
  50. package/src/peer-session.mjs +0 -937
@@ -0,0 +1,136 @@
1
+ /**
2
+ * serverless-executor-andbox.mjs -- Phase 3 of the BrowserMesh Serverless
3
+ * plan (`/Users/johnhenry/.claude/plans/at-some-point-within-joyful-dove.md`):
4
+ * the light/default function-execution backend, built on `@johnhenry/andbox`'s
5
+ * Worker-isolated JS runtime.
6
+ *
7
+ * ---------------------------------------------------------------------------
8
+ * ANDBOX IS NOT AN ADVERSARIAL-CODE SANDBOX -- restated here because it is
9
+ * the single most important fact about this file (andbox's own README
10
+ * "Security model" section, and this repo's own research confirms every
11
+ * item below is still live in the version this file depends on):
12
+ *
13
+ * - Worker-global `fetch`/`WebSocket`/`Worker`/`importScripts` are
14
+ * reachable by sandboxed code DIRECTLY, regardless of what
15
+ * `opts.capabilities` are granted -- omitting a `fetch` capability
16
+ * does not block network access.
17
+ * - `sandboxImport()` loads any bare `http(s)://` URL unchecked, with no
18
+ * allowlist, independent of any capability/network policy.
19
+ * - A capability call still in flight when a timeout fires still
20
+ * completes its host-side side effect even though the caller is told
21
+ * the invocation failed -- capabilities passed via `opts.capabilities`
22
+ * must be idempotent and/or cancellable, this file does no plumbing to
23
+ * help with that.
24
+ *
25
+ * This tier is appropriate for functions written by a site's own operator
26
+ * or trusted collaborators -- NEVER for running arbitrary third-party or
27
+ * user-submitted code. `serverless-executor-wasmsandbox.mjs` (Phase 6) adds
28
+ * a CPU/memory/instance BUDGET on top of this same trust boundary, not a
29
+ * stronger one -- see that file's own module doc comment when it exists.
30
+ *
31
+ * ---------------------------------------------------------------------------
32
+ * MANDATORY: ONE FRESH SANDBOX PER INVOCATION, NEVER POOLED OR REUSED
33
+ * ACROSS CONCURRENT CALLS.
34
+ *
35
+ * Confirmed by reading andbox's `sandbox.mjs`/`worker-source.mjs` directly:
36
+ * concurrent `evaluate()` calls on ONE sandbox instance share a single
37
+ * Worker realm (no per-call state isolation -- a global mutated by one
38
+ * call leaks into another), and a timeout on one call hard-kills
39
+ * (`worker.terminate()`) the shared worker out from under every OTHER
40
+ * concurrently in-flight call on that instance, which then gets
41
+ * misreported as *its own* timeout, not the real cause. Traced end-to-end
42
+ * through `mesh-service.mjs`'s dispatch loop: inbound `mesh-rpc` requests
43
+ * are handled concurrently, not serialized (`ctx.onIncomingData()`'s
44
+ * callback is fire-and-forget, never awaited before the next message is
45
+ * processed) -- so a shared/pooled sandbox instance would be a real,
46
+ * reachable failure mode, not a hypothetical one. `createAndboxExecutor()`
47
+ * therefore creates a brand-new `createSandbox()` instance inside every
48
+ * call to the returned `executor(job)`, disposed in a `finally`, and
49
+ * NEVER stores one across calls.
50
+ *
51
+ * ---------------------------------------------------------------------------
52
+ * TEST COVERAGE GAP, STATED PLAINLY (do not silently assume this is
53
+ * covered): andbox's own `mode: 'worker'` requires the browser `Worker`
54
+ * global (`new Worker(...)` + `Blob`/`URL.createObjectURL`), which does not
55
+ * exist in plain Node (`node:worker_threads`' `Worker` is a different,
56
+ * incompatible API) -- confirmed directly in this repo's own Node 24 test
57
+ * environment. This file's own test suite can therefore only exercise the
58
+ * REQUEST-SHAPING logic (job construction, preamble injection, dispose-on-
59
+ * error bookkeeping) using `mode: 'inline'`/mocks, not real Worker
60
+ * isolation or the real hard-kill-on-timeout/collateral-damage behavior
61
+ * described above. andbox's own upstream test suite has this exact same
62
+ * gap (its only timeout example runs under Node, exercising the weaker
63
+ * inline-mode Promise-race timeout, never a real Worker hard-kill). A real
64
+ * concurrency regression test (two overlapping requests, one deliberately
65
+ * runaway, assert the other's result is unaffected) needs an actual
66
+ * browser test environment and is intentionally NOT claimed as covered
67
+ * here.
68
+ *
69
+ * ---------------------------------------------------------------------------
70
+ * REQUEST DATA IS INJECTED VIA A JSON PREAMBLE, NOT A CAPABILITY.
71
+ *
72
+ * `actually-serverless`'s own `createFunctionHandler.mjs` takes a `preamble`
73
+ * string prepended to the function source before evaluation -- the same
74
+ * pattern used here: `job.request` (the inbound `{fromPubKey, method, path,
75
+ * headers, body}`) is JSON-serialized into a `const request = ...;`
76
+ * preamble prepended to `job.code` before `sandbox.evaluate()`, so function
77
+ * code can reference a `request` variable directly. This is plain,
78
+ * already-known data, not a live host capability -- no RPC round-trip
79
+ * needed for it, unlike genuine host capabilities (KV access, peer calls)
80
+ * a caller passes via `opts.capabilities`.
81
+ *
82
+ * ---------------------------------------------------------------------------
83
+ * `@johnhenry/andbox` IS IMPORTED LAZILY (inside the returned executor, not
84
+ * at module top level), unlike this package's other optional peer
85
+ * dependencies. Every other optional peer here (`browsermesh-core`,
86
+ * `browsermesh-discovery`, ...) is a SIBLING package in this same npm
87
+ * workspace, so it's always physically present in `node_modules` during
88
+ * this monorepo's own `npm install`/CI regardless of the "optional" marking
89
+ * -- that marking only matters for a standalone external consumer.
90
+ * `@johnhenry/andbox` is a genuinely separate repo/package, not a workspace
91
+ * sibling, and (as of this writing) isn't published to npm yet -- a static
92
+ * top-level import here would make `index.mjs`'s eager `export *` chain
93
+ * fail for the ENTIRE package the moment `@johnhenry/andbox` is absent,
94
+ * breaking every consumer/test, not just ones using this specific executor.
95
+ * A dynamic `import()` inside the executor defers that requirement to
96
+ * "only if this specific executor is actually invoked."
97
+ *
98
+ * @module serverless-executor-andbox
99
+ */
100
+
101
+ /**
102
+ * @typedef {object} AndboxJob
103
+ * @property {string} code - function source, evaluated as the body of an async IIFE (andbox's own `evaluate()` semantics -- top-level `return`/`await` both work).
104
+ * @property {object} [request] - the inbound request, JSON-injected as a `request` const in scope for `code`. See module doc comment.
105
+ * @property {number} [timeoutMs] - per-invocation override of `opts.defaultTimeoutMs`.
106
+ */
107
+
108
+ /**
109
+ * @param {object} [opts]
110
+ * @param {Record<string, Function>} [opts.capabilities] - forwarded to andbox `createSandbox()` as-is. See module doc comment's security-model section before granting anything here.
111
+ * @param {object} [opts.importMap] - forwarded to andbox `createSandbox()` as-is.
112
+ * @param {number} [opts.defaultTimeoutMs] - forwarded to andbox `createSandbox()` as its `defaultTimeoutMs`; per-job `timeoutMs` overrides this for that one `evaluate()` call.
113
+ * @returns {(job: AndboxJob) => Promise<*>} the executor -- one fresh sandbox per call, always disposed. Rejects if the sandboxed code throws, times out (andbox's own `TimeoutError`), or is aborted.
114
+ */
115
+ export function createAndboxExecutor({ capabilities, importMap, defaultTimeoutMs } = {}) {
116
+ return async function executeAndbox(job) {
117
+ if (!job || typeof job.code !== 'string') {
118
+ throw new Error('createAndboxExecutor: job.code is required and must be a string')
119
+ }
120
+
121
+ const preamble = job.request !== undefined ? `const request = ${JSON.stringify(job.request)};\n` : ''
122
+
123
+ // Lazy import -- see module doc comment for why this isn't a top-level
124
+ // static import.
125
+ const { createSandbox } = await import('@johnhenry/andbox')
126
+
127
+ // See module doc comment: MANDATORY fresh sandbox per invocation, never
128
+ // shared across concurrent calls.
129
+ const sandbox = await createSandbox({ mode: 'worker', capabilities, importMap, defaultTimeoutMs })
130
+ try {
131
+ return await sandbox.evaluate(preamble + job.code, job.timeoutMs !== undefined ? { timeout: job.timeoutMs } : undefined)
132
+ } finally {
133
+ await sandbox.dispose()
134
+ }
135
+ }
136
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * serverless-fetch.mjs -- Phase 2 of the BrowserMesh Serverless plan
3
+ * (`/Users/johnhenry/.claude/plans/at-some-point-within-joyful-dove.md`):
4
+ * the Service-Worker-facing half of site routing, finally giving
5
+ * `@johnhenry/browsermesh-discovery`'s `sw-routing.mjs` its first real
6
+ * caller (its own module doc comment has said "no wired caller of its own
7
+ * yet" since it was written).
8
+ *
9
+ * ---------------------------------------------------------------------------
10
+ * SITE-NAME REINTERPRETATION OF `parseMeshRequest()`'s `podId` TOKEN (see
11
+ * the plan doc's "Design decisions" section, restated here because it's a
12
+ * real, deliberate semantic overload of shared code, not something a future
13
+ * reader should have to reverse-engineer from two disagreeing call sites):
14
+ *
15
+ * `parseMeshRequest(urlStr)` (`mesh://X/path`, `https://X.mesh.local/path`)
16
+ * extracts a token it calls `podId`. `mesh-fetch.mjs`'s `browserMeshFetch()`
17
+ * uses that token AS a literal podId, addressing one specific peer
18
+ * directly. This file instead treats the SAME token as a logical site name
19
+ * first -- resolved via `opts.resolveSite(siteName) -> podId|null` -- and
20
+ * only falls back to treating it as a literal podId if `resolveSite`
21
+ * returns nothing. This is backward compatible (an unregistered token still
22
+ * behaves exactly like `mesh-fetch.mjs`'s direct-podId addressing), but it
23
+ * IS a real reinterpretation: two call sites in this repo now disagree
24
+ * about what that token conceptually means, unified only by "falls back to
25
+ * a literal podId either way."
26
+ *
27
+ * `opts.resolveSite` is optional. Omitting it makes this file behave
28
+ * identically to a single-peer-per-site deployment addressed by literal
29
+ * podId, which is a completely valid, already-useful configuration on its
30
+ * own. For multi-peer sites, pass `siteRegistry.selectPeer.bind(siteRegistry)`
31
+ * (`serverless-sites.mjs`'s `SiteRegistry`, Phase 5) directly -- its
32
+ * `selectPeer(siteId) -> podId|null` signature already matches this
33
+ * option's shape exactly, no adapter needed.
34
+ *
35
+ * @module serverless-fetch
36
+ */
37
+
38
+ import { MeshFetchRouter } from '@johnhenry/browsermesh-discovery'
39
+ import { decodeWireResponse } from './serverless-wire.mjs'
40
+
41
+ /**
42
+ * @param {{request: (podId: string, req: {method?: string, path?: string, headers?: object, body?: *}) => Promise<{status: number, headers: object, body: *}>}} meshRpcApi
43
+ * The `.api` returned by attaching a `mesh-rpc.mjs`-based service bound to
44
+ * the SAME envelope type a site's `createSiteMeshRpcService()`
45
+ * (`serverless-router.mjs`) was attached with on the responding side --
46
+ * typically a second, dedicated `createMeshRpcService({envelopeType:
47
+ * 'mesh-serverless'})` attach on the requesting peer, distinct from any
48
+ * general-purpose `mesh-rpc` service that peer might also run.
49
+ * @param {object} [opts]
50
+ * @param {(siteOrPodId: string) => (string|null|undefined)} [opts.resolveSite]
51
+ * Optional. Resolves the `parseMeshRequest()`-extracted token to a target
52
+ * podId. Omit for direct single-peer-per-site addressing (the token is
53
+ * used as a literal podId). `serverless-sites.mjs`'s `SiteRegistry#selectPeer()`
54
+ * (Phase 5) matches this shape exactly and can be passed here directly.
55
+ * @returns {import('@johnhenry/browsermesh-discovery').MeshFetchRouter}
56
+ */
57
+ export function createServerlessFetchRouter(meshRpcApi, { resolveSite } = {}) {
58
+ if (!meshRpcApi || typeof meshRpcApi.request !== 'function') {
59
+ throw new Error('createServerlessFetchRouter: meshRpcApi (a mesh-rpc.mjs service api with .request()) is required')
60
+ }
61
+
62
+ return new MeshFetchRouter({
63
+ onRpc: async ({ podId: siteOrPodId, method, path, headers, body }) => {
64
+ const resolved = typeof resolveSite === 'function' ? resolveSite(siteOrPodId) : null
65
+ const targetPodId = resolved || siteOrPodId
66
+ const res = await meshRpcApi.request(targetPodId, { method, path, headers, body })
67
+ return decodeWireResponse(res)
68
+ },
69
+ })
70
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * serverless-functions.mjs -- Phase 3 of the BrowserMesh Serverless plan
3
+ * (`/Users/johnhenry/.claude/plans/at-some-point-within-joyful-dove.md`):
4
+ * the backend-agnostic route matcher that adapts a pluggable `executor`
5
+ * (`serverless-executor-andbox.mjs`'s light tier, or Phase 6's
6
+ * `serverless-executor-wasmsandbox.mjs` heavier tier) into
7
+ * `serverless-router.mjs`'s `functionsHandler` slot.
8
+ *
9
+ * Kept deliberately separate from any specific executor: swapping which
10
+ * backend a site uses (`'andbox'` vs `'wasmsandbox'`, per the plan's design
11
+ * decision) is a config choice on `createFunctionsHandler({executor})`, not
12
+ * a change to route matching or request/response shaping.
13
+ *
14
+ * @module serverless-functions
15
+ */
16
+
17
+ /**
18
+ * @typedef {object} FunctionRoute
19
+ * @property {string} path - exact path to match (e.g. `'/api/hello'`). No pattern/param matching in v1 -- exact string match only, mirroring `createStaticHandler()`'s own "built fresh, no premature generality" scope.
20
+ * @property {string} [method='GET']
21
+ * @property {string} code - function source handed to the executor's `job.code`.
22
+ */
23
+
24
+ /**
25
+ * If the sandboxed code's return value is already response-shaped (a plain
26
+ * object with a numeric `status`), use it as-is (with `body`/`headers`
27
+ * defaults). Otherwise, wrap the raw value as a JSON body with a 200.
28
+ *
29
+ * @param {*} result
30
+ * @returns {{status: number, headers: object, body: *}}
31
+ */
32
+ function normalizeFunctionResult(result) {
33
+ if (result && typeof result === 'object' && typeof result.status === 'number') {
34
+ return { status: result.status, headers: result.headers || {}, body: result.body }
35
+ }
36
+ return { status: 200, headers: { 'content-type': 'application/json' }, body: result }
37
+ }
38
+
39
+ /**
40
+ * @param {object} opts
41
+ * @param {FunctionRoute[]} [opts.routes]
42
+ * @param {(job: {code: string, request?: object, timeoutMs?: number}) => Promise<*>} opts.executor
43
+ * Typically `createAndboxExecutor(...)` (Phase 3) or, later,
44
+ * `createWasmSandboxExecutor(...)` (Phase 6) -- both share this same
45
+ * `executor(job) -> Promise<result>` shape, so the backend is swappable
46
+ * without touching this file.
47
+ * @param {number} [opts.timeoutMs] - passed through as each job's `timeoutMs`.
48
+ * @returns {(req: {fromPubKey?: string, method?: string, path?: string, headers?: object, body?: *}) => Promise<{status: number, headers: object, body: *}|null>}
49
+ * `null` for a request matching no route -- "not mine, try the next handler in the chain" (the proxy handler, or a 404).
50
+ */
51
+ export function createFunctionsHandler({ routes = [], executor, timeoutMs } = {}) {
52
+ if (typeof executor !== 'function') {
53
+ throw new Error('createFunctionsHandler: opts.executor is required and must be a function')
54
+ }
55
+
56
+ return async function handleFunctions({ fromPubKey, method = 'GET', path = '/', headers = {}, body } = {}) {
57
+ const route = routes.find((r) => r.path === path && (r.method || 'GET') === method)
58
+ if (!route) return null
59
+
60
+ try {
61
+ const result = await executor({ code: route.code, request: { fromPubKey, method, path, headers, body }, timeoutMs })
62
+ return normalizeFunctionResult(result)
63
+ } catch (err) {
64
+ return { status: 500, headers: { 'content-type': 'application/json' }, body: { error: err?.message || String(err) } }
65
+ }
66
+ }
67
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * serverless-peer-select.mjs -- Phase 5 of the BrowserMesh Serverless plan
3
+ * (`/Users/johnhenry/.claude/plans/at-some-point-within-joyful-dove.md`):
4
+ * a small, pure "pick a peer for this request" function, extracted from
5
+ * `scheduler.mjs`'s own inlined policy switch (`MeshScheduler#schedule()`,
6
+ * around the `first-fit`/`round-robin`/`load-balanced`/`best-fit` cases).
7
+ *
8
+ * `scheduler.mjs`'s scoring logic is real and correct, but it's inlined
9
+ * inside a private method tightly coupled to that class's async job/
10
+ * queue/retry lifecycle (`ScheduledTask`, `assign()`/`complete()`/
11
+ * `fail()`) -- there's no "just give me a peer for this constraint set"
12
+ * entry point without going through the whole task-submission machinery,
13
+ * which doesn't fit answering an inbound HTTP-shaped request synchronously.
14
+ * This file is that missing standalone entry point, for exactly this
15
+ * narrower need.
16
+ *
17
+ * `best-fit` is deliberately NOT reproduced here: it's about matching a
18
+ * compute job's resource requirements (memory/CPU) against candidate
19
+ * nodes, and has no equivalent concept for "which peer should answer this
20
+ * HTTP GET" -- there is no resource-constraint input to score against.
21
+ *
22
+ * @module serverless-peer-select
23
+ */
24
+
25
+ /**
26
+ * @typedef {'first-fit'|'round-robin'|'load-balanced'} PeerSelectPolicy
27
+ */
28
+
29
+ /**
30
+ * @typedef {object} SelectPeerCandidate
31
+ * @property {string} podId
32
+ * @property {number} [load] - lower is preferred under `'load-balanced'`. Treated as `0` when omitted.
33
+ */
34
+
35
+ /**
36
+ * @param {SelectPeerCandidate[]} candidates - non-empty to get a real pick; an empty array returns `null`.
37
+ * @param {PeerSelectPolicy} [policy='round-robin']
38
+ * @param {{rrIndex?: number}} [state={}] - caller-owned, mutated in place for `'round-robin'`'s cursor. Pass the SAME object back in on every call for a given site to get real round-robin behavior across calls; a fresh `{}` every call degenerates to always picking `candidates[0]`.
39
+ * @returns {string|null} the selected `podId`, or `null` if `candidates` is empty.
40
+ */
41
+ export function selectPeer(candidates, policy = 'round-robin', state = {}) {
42
+ if (!Array.isArray(candidates) || candidates.length === 0) return null
43
+
44
+ switch (policy) {
45
+ case 'first-fit':
46
+ return candidates[0].podId
47
+
48
+ case 'load-balanced': {
49
+ let minLoad = Infinity
50
+ let minPod = candidates[0].podId
51
+ for (const c of candidates) {
52
+ const load = c.load ?? 0
53
+ if (load < minLoad) {
54
+ minLoad = load
55
+ minPod = c.podId
56
+ }
57
+ }
58
+ return minPod
59
+ }
60
+
61
+ case 'round-robin':
62
+ default: {
63
+ const index = state.rrIndex ?? 0
64
+ const selected = candidates[index % candidates.length].podId
65
+ state.rrIndex = index + 1
66
+ return selected
67
+ }
68
+ }
69
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * serverless-proxy.mjs -- Phase 4 of the BrowserMesh Serverless plan
3
+ * (`/Users/johnhenry/.claude/plans/at-some-point-within-joyful-dove.md`):
4
+ * a reverse-proxy-to-external-URL handler, modeled directly on
5
+ * `actually-serverless`'s `createProxyHandler.mjs` (plain `fetch()` to the
6
+ * target, SPA index.html fallback on 404).
7
+ *
8
+ * Deliberately NOT built on `browsermesh-netway`'s `GatewayBackend` -- that
9
+ * class proxies raw TCP/UDP/DNS bytes through a wsh gateway daemon, an
10
+ * entirely different (transport, not HTTP) layer. This handler needs real
11
+ * ambient `fetch()`, exactly like `actually-serverless`'s own version did;
12
+ * it runs at the responding peer's own top-level trust level (whatever JS
13
+ * context attaches the site's `mesh-rpc` service), not inside any future
14
+ * `Kernel`-sandboxed tenant execution context -- `Kernel#networkFor()`
15
+ * exposes raw socket capability tags (`tcp:connect`, `loopback`, ...), not
16
+ * an HTTP `fetch()` primitive, so this does not compose for free if
17
+ * function execution later moves fully inside Kernel-gated tenants (a
18
+ * Phase 7/8 concern, not this one).
19
+ *
20
+ * Always the LAST handler in a site's chain (`serverless-router.mjs`'s
21
+ * static -> functions -> proxy precedence): unlike `createStaticHandler()`,
22
+ * this handler never returns `null` -- it always attempts to proxy and
23
+ * always returns a real response (success or a clean 502/504 on failure),
24
+ * matching `actually-serverless`'s own catch-all proxy semantics.
25
+ *
26
+ * @module serverless-proxy
27
+ */
28
+
29
+ /** Request headers unsafe/meaningless to forward to the proxy target as-is -- `fetch()` recomputes these itself. */
30
+ const HOP_BY_HOP_REQUEST_HEADERS = new Set([
31
+ 'host', 'connection', 'content-length', 'keep-alive', 'transfer-encoding',
32
+ 'upgrade', 'te', 'trailer', 'proxy-authenticate', 'proxy-authorization',
33
+ ])
34
+
35
+ /**
36
+ * Response headers unsafe to forward verbatim: `fetch()` already
37
+ * transparently decompresses the body before `res.arrayBuffer()` reads it,
38
+ * so forwarding a stale `content-encoding`/`content-length` would make a
39
+ * downstream consumer try to re-decode/mis-size already-decoded bytes.
40
+ * `set-cookie` is dropped too -- a Service-Worker-synthesized `Response`
41
+ * doesn't set real cookies for a fetch(), so forwarding it is misleading
42
+ * rather than unsafe, but there's no reason to carry it through either.
43
+ */
44
+ const HOP_BY_HOP_RESPONSE_HEADERS = new Set([
45
+ 'content-encoding', 'content-length', 'transfer-encoding', 'connection', 'keep-alive', 'upgrade', 'set-cookie',
46
+ ])
47
+
48
+ /**
49
+ * @param {object} headers
50
+ * @param {Set<string>} drop - lowercased header names to omit.
51
+ * @returns {object}
52
+ */
53
+ function filterHeaders(headers, drop) {
54
+ const out = {}
55
+ for (const [k, v] of Object.entries(headers || {})) {
56
+ if (!drop.has(k.toLowerCase())) out[k] = v
57
+ }
58
+ return out
59
+ }
60
+
61
+ /**
62
+ * @param {Headers} headers
63
+ * @returns {object}
64
+ */
65
+ function responseHeadersToObject(headers) {
66
+ const out = {}
67
+ for (const [k, v] of headers.entries()) {
68
+ if (!HOP_BY_HOP_RESPONSE_HEADERS.has(k.toLowerCase())) out[k] = v
69
+ }
70
+ return out
71
+ }
72
+
73
+ /**
74
+ * @param {*} body
75
+ * @param {string} method
76
+ * @returns {string|Uint8Array|undefined}
77
+ */
78
+ function bodyForFetch(body, method) {
79
+ if (method === 'GET' || method === 'HEAD' || body === undefined || body === null) return undefined
80
+ if (typeof body === 'string' || body instanceof Uint8Array) return body
81
+ return JSON.stringify(body)
82
+ }
83
+
84
+ /**
85
+ * @param {object} opts
86
+ * @param {string} opts.targetOrigin - e.g. `'https://api.example.com'`. `path` is resolved against this via `new URL(path, targetOrigin)`.
87
+ * @param {boolean} [opts.spaFallback=false] - on a 404 from the target, retry `/index.html` under `targetOrigin` and serve that instead (client-side-routed SPA convention, matching `actually-serverless`'s own proxy handler).
88
+ * @returns {(req: {path: string, method?: string, headers?: object, body?: *}) => Promise<{status: number, headers: object, body: Uint8Array|string}>}
89
+ * Never returns `null` -- see module doc comment.
90
+ */
91
+ export function createProxyHandler({ targetOrigin, spaFallback = false } = {}) {
92
+ if (!targetOrigin || typeof targetOrigin !== 'string') {
93
+ throw new Error('createProxyHandler: opts.targetOrigin is required and must be a string')
94
+ }
95
+ const origin = new URL(targetOrigin) // throws synchronously on an invalid URL -- fail at construction, not on first request
96
+
97
+ return async function handleProxy({ path = '/', method = 'GET', headers = {}, body } = {}) {
98
+ const target = new URL(path, origin)
99
+ const init = { method, headers: filterHeaders(headers, HOP_BY_HOP_REQUEST_HEADERS) }
100
+ const fetchBody = bodyForFetch(body, method)
101
+ if (fetchBody !== undefined) init.body = fetchBody
102
+
103
+ let res
104
+ try {
105
+ res = await fetch(target, init)
106
+ } catch (err) {
107
+ return { status: 502, headers: { 'content-type': 'text/plain' }, body: `Bad Gateway: ${err?.message || String(err)}` }
108
+ }
109
+
110
+ if (res.status === 404 && spaFallback) {
111
+ const fallbackTarget = new URL('/index.html', origin)
112
+ let fallbackRes
113
+ try {
114
+ fallbackRes = await fetch(fallbackTarget)
115
+ } catch {
116
+ fallbackRes = null
117
+ }
118
+ if (fallbackRes && fallbackRes.ok) {
119
+ const bytes = new Uint8Array(await fallbackRes.arrayBuffer())
120
+ return { status: 200, headers: { 'content-type': fallbackRes.headers.get('content-type') || 'text/html' }, body: bytes }
121
+ }
122
+ }
123
+
124
+ const bytes = new Uint8Array(await res.arrayBuffer())
125
+ return { status: res.status, headers: responseHeadersToObject(res.headers), body: bytes }
126
+ }
127
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * serverless-router.mjs -- Phase 2 of the BrowserMesh Serverless plan
3
+ * (`/Users/johnhenry/.claude/plans/at-some-point-within-joyful-dove.md`):
4
+ * the per-site request handler that chains static -> functions -> proxy,
5
+ * mirroring `actually-serverless`'s own handler precedence, and attaches
6
+ * it over the mesh via a dedicated-envelope `mesh-rpc.mjs` service.
7
+ *
8
+ * `functionsHandler`/`proxyHandler` are optional and not yet implemented by
9
+ * anything in this repo (Phases 3/4) -- a `siteConfig` that only sets
10
+ * `staticHandler` already works end to end today (a static-only site), the
11
+ * chain just skips whatever fields are absent.
12
+ *
13
+ * ---------------------------------------------------------------------------
14
+ * WHY A DEDICATED `'mesh-serverless'` ENVELOPE TYPE, NOT THE DEFAULT
15
+ * `'mesh-rpc'` (see the plan doc's "Design decisions" section):
16
+ *
17
+ * `createMeshRpcService()` takes exactly one `onRequest` per attached
18
+ * instance. A pod that also runs a general-purpose `mesh-rpc` service for
19
+ * something else (e.g. `agent-runtime.mjs` tool calls) would collide if
20
+ * both shared the default envelope type and default `onRequest` slot.
21
+ * `createSiteMeshRpcService()` below always passes its own `envelopeType`
22
+ * (default `'mesh-serverless'`, overridable), matching this family's
23
+ * one-`MeshService`-per-concern convention (`mesh-compute` uses
24
+ * `'mesh-compute'`, etc.) rather than fighting over a shared default.
25
+ *
26
+ * @module serverless-router
27
+ */
28
+
29
+ import { createMeshRpcService } from './mesh-rpc.mjs'
30
+ import { encodeWireResponse } from './serverless-wire.mjs'
31
+
32
+ /** Default envelope type for a site's mesh-rpc attach -- see module doc comment. */
33
+ const DEFAULT_SITE_ENVELOPE_TYPE = 'mesh-serverless'
34
+
35
+ /**
36
+ * @typedef {object} SiteHandlerRequest
37
+ * @property {string} [fromPubKey]
38
+ * @property {string} method
39
+ * @property {string} path
40
+ * @property {object} [headers]
41
+ * @property {*} [body]
42
+ */
43
+
44
+ /**
45
+ * @typedef {object} SiteHandlerResponse
46
+ * @property {number} status
47
+ * @property {object} headers
48
+ * @property {Uint8Array|ArrayBuffer|string|*} body
49
+ */
50
+
51
+ /**
52
+ * @typedef {object} SiteConfig
53
+ * @property {(req: {path: string, method?: string, fromPubKey?: string}) => Promise<SiteHandlerResponse|null>} [staticHandler]
54
+ * Typically `createStaticHandler(...)` from `serverless-static.mjs`.
55
+ * @property {(req: SiteHandlerRequest) => Promise<SiteHandlerResponse|null>} [functionsHandler]
56
+ * Not yet implemented anywhere in this repo -- Phase 3.
57
+ * @property {(req: SiteHandlerRequest) => Promise<SiteHandlerResponse|null>} [proxyHandler]
58
+ * Not yet implemented anywhere in this repo -- Phase 4.
59
+ */
60
+
61
+ /**
62
+ * Build the `onRequest` handler for one site: static -> functions -> proxy,
63
+ * first non-null response wins. A binary (`Uint8Array`/`ArrayBuffer`) body
64
+ * from any handler is base64-encoded via `encodeWireResponse()` before
65
+ * being returned, so it survives the `mesh-rpc.mjs` wire hop intact --
66
+ * `serverless-fetch.mjs`'s client side reverses this.
67
+ *
68
+ * @param {SiteConfig} siteConfig
69
+ * @returns {(req: SiteHandlerRequest) => Promise<SiteHandlerResponse>}
70
+ */
71
+ export function createSiteRequestHandler(siteConfig = {}) {
72
+ const { staticHandler, functionsHandler, proxyHandler } = siteConfig
73
+
74
+ return async function onRequest(req) {
75
+ const { fromPubKey, method = 'GET', path = '/', headers = {}, body } = req || {}
76
+
77
+ if (staticHandler) {
78
+ const res = await staticHandler({ path, method, fromPubKey })
79
+ if (res) return encodeWireResponse(res)
80
+ }
81
+ if (functionsHandler) {
82
+ const res = await functionsHandler({ fromPubKey, method, path, headers, body })
83
+ if (res) return encodeWireResponse(res)
84
+ }
85
+ if (proxyHandler) {
86
+ const res = await proxyHandler({ fromPubKey, method, path, headers, body })
87
+ if (res) return encodeWireResponse(res)
88
+ }
89
+
90
+ return { status: 404, headers: { 'content-type': 'application/json' }, body: { error: 'not found' } }
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Attach a site's request handler to `peerNode` over a dedicated
96
+ * `mesh-rpc.mjs` envelope type. Thin convenience wrapper -- equivalent to
97
+ * calling `attachService(peerNode, network, createMeshRpcService({onRequest:
98
+ * createSiteRequestHandler(siteConfig), envelopeType}))` directly.
99
+ *
100
+ * @param {SiteConfig} siteConfig
101
+ * @param {object} [opts]
102
+ * @param {string} [opts.envelopeType='mesh-serverless']
103
+ * @param {number} [opts.requestTimeoutMs]
104
+ * @returns {import('./mesh-service.mjs').MeshService}
105
+ */
106
+ export function createSiteMeshRpcService(siteConfig, { envelopeType = DEFAULT_SITE_ENVELOPE_TYPE, requestTimeoutMs, name = 'mesh-serverless' } = {}) {
107
+ const rpcService = createMeshRpcService({
108
+ onRequest: createSiteRequestHandler(siteConfig),
109
+ envelopeType,
110
+ requestTimeoutMs,
111
+ })
112
+ return { ...rpcService, name }
113
+ }
114
+
115
+ export { DEFAULT_SITE_ENVELOPE_TYPE }