@johnhenry/browsermesh-apps 0.3.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-apps",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Application layer: marketplace, chat, payments, compute, orchestration, and agent tools for BrowserMesh",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -26,7 +26,8 @@
26
26
  "@johnhenry/browsermesh-sync": ">=0.0.0 <1.0.0",
27
27
  "@johnhenry/browsermesh-discovery": ">=0.0.1 <1.0.0",
28
28
  "@johnhenry/browsermesh-kernel": ">=0.0.0 <1.0.0",
29
- "@johnhenry/browsermesh-netway": ">=0.0.0 <1.0.0"
29
+ "@johnhenry/browsermesh-netway": ">=0.0.0 <1.0.0",
30
+ "@johnhenry/andbox": ">=0.0.1 <1.0.0"
30
31
  },
31
32
  "peerDependenciesMeta": {
32
33
  "@johnhenry/browsermesh-transport": {
@@ -43,6 +44,9 @@
43
44
  },
44
45
  "@johnhenry/browsermesh-netway": {
45
46
  "optional": true
47
+ },
48
+ "@johnhenry/andbox": {
49
+ "optional": true
46
50
  }
47
51
  },
48
52
  "devDependencies": {
@@ -587,22 +587,17 @@ export class CloudStorage {
587
587
  }
588
588
 
589
589
  /**
590
- * Read `key`'s content. Falls back to a remote peer request (Phase G's
591
- * lazy pull/read-repair) for any chunk not already held locally. See
592
- * module doc comment, point 2, for exactly how "the manifest entry itself
593
- * isn't here yet" is handled.
590
+ * Wait (up to `waitMs`) for `key`'s manifest entry to be present, per the
591
+ * module doc comment's point 2 ("the manifest entry itself isn't here
592
+ * yet"). Shared by `getObject()` and `stat()` so both honor the same
593
+ * manifest-sync-wait/tombstone contract as each other.
594
594
  *
595
595
  * @param {string} key
596
- * @param {object} [opts]
597
- * @param {number} [opts.manifestWaitMs] - Overrides the constructor default for this call only.
598
- * @returns {Promise<Uint8Array>}
596
+ * @param {number} waitMs
597
+ * @returns {Promise<object>} the manifest registration entry
599
598
  * @throws {CloudStorageNotFoundError}
600
599
  */
601
- async get(key, opts = {}) {
602
- if (!key || typeof key !== 'string') {
603
- throw new Error('CloudStorage.get: key is required and must be a non-empty string')
604
- }
605
- const waitMs = opts.manifestWaitMs ?? this.#manifestWaitMs
600
+ async #awaitManifestEntry(key, waitMs) {
606
601
  const deadline = Date.now() + waitMs
607
602
 
608
603
  let reg = null
@@ -620,6 +615,29 @@ export class CloudStorage {
620
615
  if (reg.tombstone) {
621
616
  throw new CloudStorageNotFoundError(key, { reason: 'deleted' })
622
617
  }
618
+ return reg
619
+ }
620
+
621
+ /**
622
+ * Read `key`'s content plus the `contentType`/`metadata` it was `put()`
623
+ * with. The backend's `get` op already returns these fields
624
+ * (`cloud-storage-backend.mjs`'s `#opGet()`) -- `get()` below is a thin
625
+ * wrapper around this that returns only `data`, for callers that don't
626
+ * need the rest. Falls back to a remote peer request (Phase G's lazy
627
+ * pull/read-repair) for any chunk not already held locally.
628
+ *
629
+ * @param {string} key
630
+ * @param {object} [opts]
631
+ * @param {number} [opts.manifestWaitMs] - Overrides the constructor default for this call only.
632
+ * @returns {Promise<{data: Uint8Array, contentType: (string|undefined), metadata: (object|undefined)}>}
633
+ * @throws {CloudStorageNotFoundError}
634
+ */
635
+ async getObject(key, opts = {}) {
636
+ if (!key || typeof key !== 'string') {
637
+ throw new Error('CloudStorage.getObject: key is required and must be a non-empty string')
638
+ }
639
+ const waitMs = opts.manifestWaitMs ?? this.#manifestWaitMs
640
+ const reg = await this.#awaitManifestEntry(key, waitMs)
623
641
 
624
642
  // Ensure every chunk this entry references is present locally BEFORE
625
643
  // asking the backend to decrypt+assemble it -- the backend itself has
@@ -640,7 +658,49 @@ export class CloudStorage {
640
658
  throw new CloudStorageNotFoundError(key, { reason: 'deleted' })
641
659
  }
642
660
  this.#events.emit('cloud-storage:get-completed', { bucket: this.#bucket, key })
643
- return fromBase64(res.data)
661
+ return { data: fromBase64(res.data), contentType: res.contentType, metadata: res.metadata }
662
+ }
663
+
664
+ /**
665
+ * Read `key`'s content. See `getObject()` for the `contentType`/`metadata`-
666
+ * preserving variant this delegates to.
667
+ *
668
+ * @param {string} key
669
+ * @param {object} [opts]
670
+ * @param {number} [opts.manifestWaitMs] - Overrides the constructor default for this call only.
671
+ * @returns {Promise<Uint8Array>}
672
+ * @throws {CloudStorageNotFoundError}
673
+ */
674
+ async get(key, opts = {}) {
675
+ const { data } = await this.getObject(key, opts)
676
+ return data
677
+ }
678
+
679
+ /**
680
+ * Return `key`'s metadata (`size`, `contentType`, `metadata`, `updatedAt`,
681
+ * `version`) without reading or decrypting its content. Thin wrapper
682
+ * around the backend's existing `head` op (`cloud-storage-backend.mjs`'s
683
+ * `#opHead()`), which was already implemented but never called from this
684
+ * class.
685
+ *
686
+ * @param {string} key
687
+ * @param {object} [opts]
688
+ * @param {number} [opts.manifestWaitMs] - Overrides the constructor default for this call only.
689
+ * @returns {Promise<{size: number, contentType: (string|undefined), metadata: (object|undefined), updatedAt: number, version: number}>}
690
+ * @throws {CloudStorageNotFoundError}
691
+ */
692
+ async stat(key, opts = {}) {
693
+ if (!key || typeof key !== 'string') {
694
+ throw new Error('CloudStorage.stat: key is required and must be a non-empty string')
695
+ }
696
+ const waitMs = opts.manifestWaitMs ?? this.#manifestWaitMs
697
+ await this.#awaitManifestEntry(key, waitMs)
698
+
699
+ const res = await this.#sendCommand({ op: 'head', key })
700
+ if (res.error) {
701
+ throw new CloudStorageNotFoundError(key, { reason: 'deleted' })
702
+ }
703
+ return { size: res.size, contentType: res.contentType, metadata: res.metadata, updatedAt: res.updatedAt, version: res.version }
644
704
  }
645
705
 
646
706
  /**
package/src/index.mjs CHANGED
@@ -50,6 +50,15 @@ export * from './mesh-keepalive.mjs';
50
50
  export * from './mesh-fetch.mjs';
51
51
  export * from './mesh-websocket.mjs';
52
52
  export * from './cloud-storage.mjs';
53
+ export * from './serverless-wire.mjs';
54
+ export * from './serverless-static.mjs';
55
+ export * from './serverless-router.mjs';
56
+ export * from './serverless-fetch.mjs';
57
+ export * from './serverless-proxy.mjs';
58
+ export * from './serverless-functions.mjs';
59
+ export * from './serverless-executor-andbox.mjs';
60
+ export * from './serverless-peer-select.mjs';
61
+ export * from './serverless-sites.mjs';
53
62
  export * from './observability-bridge.mjs';
54
63
  export * from './mesh-kv.mjs';
55
64
  export * from './peer-payments.mjs';
@@ -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 }
@@ -0,0 +1,116 @@
1
+ /**
2
+ * serverless-sites.mjs -- Phase 5 of the BrowserMesh Serverless plan
3
+ * (`/Users/johnhenry/.claude/plans/at-some-point-within-joyful-dove.md`):
4
+ * `SiteRegistry`, tracking which connected peers can serve a given site and
5
+ * picking one per request via `serverless-peer-select.mjs`'s `selectPeer()`.
6
+ *
7
+ * ---------------------------------------------------------------------------
8
+ * ADMIN-DESIGNATED, NEVER AUTO-DISCOVERED -- a deliberate design choice, not
9
+ * a missing feature. Mirrors `CloudStorage`'s own `replicaPeers`/
10
+ * `designateReplica()` precedent (that file's own module doc comment,
11
+ * point 6): a site's operator explicitly calls `registerSitePeer(siteId,
12
+ * podId)` for each peer they've deployed the site to, the same way a
13
+ * `CloudStorage` bucket's replica set is explicit, not auto-scaled.
14
+ * Discovery-based auto-population (advertising `serves:<siteId>` as a
15
+ * `DiscoveryRecord.capabilities` tag, per the plan doc's own "Design
16
+ * decisions" section) is a real, low-effort future enhancement,
17
+ * deliberately deferred -- not required for this phase, and not silently
18
+ * assumed to already exist.
19
+ *
20
+ * `selectPeer(siteId)` only ever returns a peer that BOTH (a) was
21
+ * explicitly registered for `siteId` and (b) is CURRENTLY connected per
22
+ * `peerNode.listPeers({status: 'connected'})` -- a registered-but-
23
+ * currently-disconnected peer is never selected, without needing an
24
+ * explicit `unregisterSitePeer()` call for a transient disconnect.
25
+ *
26
+ * @module serverless-sites
27
+ */
28
+
29
+ import { selectPeer as selectPeerFromCandidates } from './serverless-peer-select.mjs'
30
+
31
+ export class SiteRegistry {
32
+ /** @type {Map<string, Set<string>>} siteId -> Set<podId> */
33
+ #sites = new Map()
34
+ /** @type {Map<string, {rrIndex?: number}>} siteId -> selectPeer()'s round-robin cursor state */
35
+ #selectState = new Map()
36
+ #peerNode
37
+ #policy
38
+ #getLoad
39
+
40
+ /**
41
+ * @param {object} opts
42
+ * @param {import('./peer-node.mjs').PeerNode} opts.peerNode - duck-typed: needs `listPeers({status}) -> PeerState[]` (`{fingerprint, status, ...}`, `@johnhenry/browsermesh-core`'s shape).
43
+ * @param {import('./serverless-peer-select.mjs').PeerSelectPolicy} [opts.policy='round-robin']
44
+ * @param {(podId: string) => number} [opts.getLoad] - only consulted under `'load-balanced'`. `PeerState` carries no built-in load metric, so this defaults to a constant `0` for every peer (degrading `'load-balanced'` to an arbitrary-but-stable first-among-equals pick) unless the caller supplies a real signal.
45
+ */
46
+ constructor({ peerNode, policy = 'round-robin', getLoad } = {}) {
47
+ if (!peerNode || typeof peerNode.listPeers !== 'function') {
48
+ throw new Error('SiteRegistry: opts.peerNode (with listPeers()) is required')
49
+ }
50
+ this.#peerNode = peerNode
51
+ this.#policy = policy
52
+ this.#getLoad = typeof getLoad === 'function' ? getLoad : () => 0
53
+ }
54
+
55
+ /**
56
+ * @param {string} siteId
57
+ * @param {string} podId
58
+ */
59
+ registerSitePeer(siteId, podId) {
60
+ let set = this.#sites.get(siteId)
61
+ if (!set) {
62
+ set = new Set()
63
+ this.#sites.set(siteId, set)
64
+ }
65
+ set.add(podId)
66
+ }
67
+
68
+ /**
69
+ * @param {string} siteId
70
+ * @param {string} podId
71
+ */
72
+ unregisterSitePeer(siteId, podId) {
73
+ const set = this.#sites.get(siteId)
74
+ if (!set) return
75
+ set.delete(podId)
76
+ if (set.size === 0) this.#sites.delete(siteId)
77
+ }
78
+
79
+ /**
80
+ * @param {string} siteId
81
+ * @returns {string[]} podIds registered for `siteId`, regardless of current connection status.
82
+ */
83
+ listSitePeers(siteId) {
84
+ return [...(this.#sites.get(siteId) || [])]
85
+ }
86
+
87
+ /**
88
+ * Pick a currently-connected peer registered for `siteId`, per the
89
+ * configured policy. Returns `null` if `siteId` has no registered peers,
90
+ * or none of them are currently connected -- callers (e.g.
91
+ * `serverless-fetch.mjs`'s `resolveSite`) should fall back to treating
92
+ * the original token as a literal podId in that case, per the plan's own
93
+ * "Design decisions" section.
94
+ *
95
+ * @param {string} siteId
96
+ * @returns {string|null}
97
+ */
98
+ selectPeer(siteId) {
99
+ const podIds = this.#sites.get(siteId)
100
+ if (!podIds || podIds.size === 0) return null
101
+
102
+ const connected = this.#peerNode.listPeers({ status: 'connected' }) || []
103
+ const candidates = connected
104
+ .filter((p) => podIds.has(p.fingerprint))
105
+ .map((p) => ({ podId: p.fingerprint, load: this.#getLoad(p.fingerprint) }))
106
+
107
+ if (candidates.length === 0) return null
108
+
109
+ let state = this.#selectState.get(siteId)
110
+ if (!state) {
111
+ state = {}
112
+ this.#selectState.set(siteId, state)
113
+ }
114
+ return selectPeerFromCandidates(candidates, this.#policy, state)
115
+ }
116
+ }
@@ -0,0 +1,202 @@
1
+ /**
2
+ * serverless-static.mjs -- Phase 1 of the BrowserMesh Serverless plan
3
+ * (`/Users/johnhenry/.claude/plans/at-some-point-within-joyful-dove.md`):
4
+ * static-site serving backed by `CloudStorage` (`cloud-storage.mjs`).
5
+ *
6
+ * Adapts `actually-serverless`'s `createFileSystemHandler.mjs` (File System
7
+ * Access API, one browser tab's local folder) to a mesh-native equivalent:
8
+ * a `CloudStorage` bucket's flat, replicated key-value store stands in for
9
+ * the local folder, so the same site can be served by any peer holding (or
10
+ * able to read-repair) the bucket's chunks, not just the machine the files
11
+ * happen to live on.
12
+ *
13
+ * `CloudStorage.list()` is a flat KV store with prefix-match only -- no
14
+ * directory-tree semantics to lean on (confirmed by reading
15
+ * `cloud-storage-backend.mjs`'s `#opList()`) -- so index.html resolution,
16
+ * implicit-directory-index lookup, and SPA fallback are all built fresh
17
+ * here, not inherited from anywhere.
18
+ *
19
+ * ---------------------------------------------------------------------------
20
+ * PUBLIC vs GATED SITES (see the plan doc's "Research findings", point 4).
21
+ *
22
+ * No wildcard-peer grant primitive exists anywhere in this repo's ACL stack
23
+ * (confirmed by reading `peer-registry.mjs`/`grant-log.mjs` directly:
24
+ * `checkAccess()`/`grant()` are both keyed by an exact pubKey string). A
25
+ * "public" static site therefore does NOT rely on `CloudStorage`'s own
26
+ * per-bucket ACL at all for reads -- `CloudStorage.getObject()` has no
27
+ * reader-identity concept in the first place; it just reads whatever this
28
+ * peer's own local store already holds. The gate implemented here is a
29
+ * SEPARATE, router-facing decision: when `opts.public` is false, the caller
30
+ * (Phase 2's `serverless-router.mjs`, which has `fromPubKey` and a real
31
+ * `registry.checkAccess`) must supply `opts.checkAccess`, and every request
32
+ * is checked against it before this handler ever touches the store. When
33
+ * `opts.public` is true, that check is skipped entirely -- literally
34
+ * "this peer already has read access to its own bucket, and will re-serve
35
+ * those bytes to anyone who reaches it over mesh-rpc." State this plainly:
36
+ * it is a router-layer policy, not a `GrantLog` feature.
37
+ *
38
+ * @module serverless-static
39
+ */
40
+
41
+ import { CloudStorageNotFoundError } from './cloud-storage.mjs'
42
+
43
+ /** @type {Record<string, string>} common static-site extensions -> MIME type, used only as a fallback when `put()` was never given an explicit `contentType`. */
44
+ const EXT_CONTENT_TYPES = {
45
+ html: 'text/html',
46
+ htm: 'text/html',
47
+ css: 'text/css',
48
+ js: 'text/javascript',
49
+ mjs: 'text/javascript',
50
+ json: 'application/json',
51
+ map: 'application/json',
52
+ svg: 'image/svg+xml',
53
+ png: 'image/png',
54
+ jpg: 'image/jpeg',
55
+ jpeg: 'image/jpeg',
56
+ gif: 'image/gif',
57
+ webp: 'image/webp',
58
+ ico: 'image/x-icon',
59
+ woff: 'font/woff',
60
+ woff2: 'font/woff2',
61
+ ttf: 'font/ttf',
62
+ txt: 'text/plain',
63
+ xml: 'application/xml',
64
+ wasm: 'application/wasm',
65
+ pdf: 'application/pdf',
66
+ }
67
+
68
+ /**
69
+ * @param {string} key
70
+ * @returns {string}
71
+ */
72
+ function guessContentType(key) {
73
+ const dot = key.lastIndexOf('.')
74
+ const ext = dot === -1 ? '' : key.slice(dot + 1).toLowerCase()
75
+ return EXT_CONTENT_TYPES[ext] || 'application/octet-stream'
76
+ }
77
+
78
+ /**
79
+ * True if any path segment is literally `..` -- rejected outright rather
80
+ * than collapsed/resolved. `CloudStorage` keys are opaque flat strings, not
81
+ * real filesystem paths, so there is no actual traversal vulnerability to
82
+ * escape a root directory with -- this is defense-in-depth/predictability
83
+ * (reject the request rather than silently mapping `/../secret` to some
84
+ * unintended key), not a fix for an exploitable bug.
85
+ *
86
+ * @param {string} path
87
+ * @returns {boolean}
88
+ */
89
+ function hasTraversal(path) {
90
+ return path.split('/').some((segment) => segment === '..')
91
+ }
92
+
93
+ /**
94
+ * Build the ordered list of `CloudStorage` keys to try for an incoming
95
+ * request path, in the same precedence `actually-serverless`'s own static
96
+ * handler uses (exact file, then implicit directory index):
97
+ * '/' -> [indexFile]
98
+ * '/foo/' -> ['foo/' + indexFile]
99
+ * '/foo' -> ['foo', 'foo/' + indexFile] (file first, then directory index)
100
+ * '/foo/bar.js' -> ['foo/bar.js']
101
+ *
102
+ * @param {string} path
103
+ * @param {string} indexFile
104
+ * @returns {string[]}
105
+ */
106
+ function buildCandidateKeys(path, indexFile) {
107
+ const normalized = path.startsWith('/') ? path.slice(1) : path
108
+ if (normalized === '') return [indexFile]
109
+ if (normalized.endsWith('/')) return [normalized + indexFile]
110
+ if (/\.[^/]+$/.test(normalized)) return [normalized] // has a file extension -- don't also try it as a directory
111
+ return [normalized, `${normalized}/${indexFile}`]
112
+ }
113
+
114
+ /**
115
+ * @typedef {object} StaticRequest
116
+ * @property {string} path - request path, e.g. `/about/index.html` or `/`.
117
+ * @property {string} [method='GET']
118
+ * @property {string} [fromPubKey] - the requesting peer's identity, required unless `opts.public`.
119
+ */
120
+
121
+ /**
122
+ * @typedef {object} StaticResponse
123
+ * @property {number} status
124
+ * @property {Record<string,string>} headers
125
+ * @property {Uint8Array|string} body
126
+ */
127
+
128
+ /**
129
+ * @param {object} opts
130
+ * @param {import('./cloud-storage.mjs').CloudStorage} opts.store - a `CloudStorage`-like object exposing `getObject(key)` and, optionally, `stat(key)`.
131
+ * @param {string} [opts.indexFile='index.html']
132
+ * @param {boolean} [opts.spaFallback=false] - serve `indexFile` for any path that doesn't resolve to a stored key, for client-side-routed SPAs.
133
+ * @param {boolean} [opts.public=false] - skip the read-access gate entirely (see module doc comment above). Mutually exclusive in effect with `opts.checkAccess`.
134
+ * @param {(pubKey: string, resource: string, action: string) => {allowed: boolean, reason?: string}} [opts.checkAccess] - required unless `opts.public` is true.
135
+ * @param {string} [opts.resource] - defaults to `store.resource` (a real `CloudStorage`'s own `s3:<bucket>` resource tag).
136
+ * @returns {(req: StaticRequest) => Promise<StaticResponse|null>} null means "not mine, try the next handler in this site's chain."
137
+ */
138
+ export function createStaticHandler({ store, indexFile = 'index.html', spaFallback = false, public: isPublic = false, checkAccess, resource } = {}) {
139
+ if (!store || typeof store.getObject !== 'function') {
140
+ throw new Error('createStaticHandler: opts.store is required and must be a CloudStorage-like object (getObject())')
141
+ }
142
+ if (!isPublic && typeof checkAccess !== 'function') {
143
+ throw new Error('createStaticHandler: opts.checkAccess is required unless opts.public is true')
144
+ }
145
+ const gateResource = resource || store.resource
146
+
147
+ return async function handleStatic({ path, method = 'GET', fromPubKey } = {}) {
148
+ if (method !== 'GET' && method !== 'HEAD') return null // not a static-file request -- let the next handler in the chain try
149
+
150
+ if (!isPublic) {
151
+ const decision = checkAccess(fromPubKey, gateResource, 'read')
152
+ if (!decision?.allowed) {
153
+ return { status: 403, headers: { 'content-type': 'text/plain' }, body: 'Forbidden' }
154
+ }
155
+ }
156
+
157
+ const safePath = path || '/'
158
+ if (hasTraversal(safePath)) {
159
+ return { status: 400, headers: { 'content-type': 'text/plain' }, body: 'Bad Request' }
160
+ }
161
+
162
+ const candidates = buildCandidateKeys(safePath, indexFile)
163
+ for (const key of candidates) {
164
+ const hit = await fetchKey(store, key, method)
165
+ if (hit) return hit
166
+ }
167
+
168
+ if (spaFallback) {
169
+ const hit = await fetchKey(store, indexFile, method)
170
+ if (hit) return hit
171
+ }
172
+
173
+ return null // not found -- let the next handler in the chain (functions/proxy) try, or the router 404s
174
+ }
175
+ }
176
+
177
+ /**
178
+ * @param {import('./cloud-storage.mjs').CloudStorage} store
179
+ * @param {string} key
180
+ * @param {string} method
181
+ * @returns {Promise<StaticResponse|null>}
182
+ */
183
+ async function fetchKey(store, key, method) {
184
+ try {
185
+ if (method === 'HEAD' && typeof store.stat === 'function') {
186
+ // Avoid pulling chunk bytes across the mesh (Phase G's lazy pull) just
187
+ // to answer a HEAD -- stat() only needs the manifest entry to have
188
+ // synced, not the content itself.
189
+ const meta = await store.stat(key)
190
+ return { status: 200, headers: { 'content-type': meta.contentType || guessContentType(key) }, body: new Uint8Array() }
191
+ }
192
+ const { data, contentType } = await store.getObject(key)
193
+ return {
194
+ status: 200,
195
+ headers: { 'content-type': contentType || guessContentType(key) },
196
+ body: method === 'HEAD' ? new Uint8Array() : data,
197
+ }
198
+ } catch (err) {
199
+ if (err instanceof CloudStorageNotFoundError) return null
200
+ throw err
201
+ }
202
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * serverless-wire.mjs -- shared binary-body encoding for the
3
+ * BrowserMesh Serverless plan's `mesh-rpc` hop
4
+ * (`/Users/johnhenry/.claude/plans/at-some-point-within-joyful-dove.md`,
5
+ * Phase 2).
6
+ *
7
+ * `mesh-rpc.mjs`'s wire protocol treats a response's `body` as a plain
8
+ * JSON-shaped envelope field (see that file's module doc comment: "typical
9
+ * callers stringify a JSON envelope first" is `peer-node.mjs`'s own
10
+ * guidance for `sendTo()`'s payload). A raw `Uint8Array`/`ArrayBuffer` body
11
+ * -- e.g. `serverless-static.mjs`'s file bytes -- is not safe to hand to
12
+ * that layer as-is, for the same reason `cloud-storage-backend.mjs` already
13
+ * base64-encodes chunk bytes before putting them in a command envelope:
14
+ * whatever the underlying transport does to serialize an envelope object,
15
+ * a raw byte array embedded in it cannot be assumed to survive intact.
16
+ *
17
+ * `encodeWireResponse()`/`decodeWireResponse()` are the matched pair used
18
+ * on either side of that hop -- `serverless-router.mjs` (server side, right
19
+ * before handing a response to `createMeshRpcService({onRequest})`) and
20
+ * `serverless-fetch.mjs` (client side, right after `meshRpcApi.request()`
21
+ * returns, before handing the result to `MeshFetchRouter`, which itself
22
+ * needs a real `Uint8Array`/`ArrayBuffer`/string body to build a correct
23
+ * `Response` -- see `sw-routing.mjs`'s `MeshFetchRouter.route()` fix in
24
+ * this same phase for the other half of this).
25
+ *
26
+ * @module serverless-wire
27
+ */
28
+
29
+ /** Internal header carrying the wire-encoding marker. Stripped before the final Response's headers reach a caller. */
30
+ const WIRE_ENCODING_HEADER = 'x-mesh-serverless-body-encoding'
31
+
32
+ /** @param {Uint8Array} bytes @returns {string} */
33
+ function toBase64(bytes) {
34
+ if (typeof Buffer !== 'undefined') return Buffer.from(bytes).toString('base64')
35
+ let bin = ''
36
+ for (const b of bytes) bin += String.fromCharCode(b)
37
+ return btoa(bin)
38
+ }
39
+
40
+ /** @param {string} str @returns {Uint8Array} */
41
+ function fromBase64(str) {
42
+ if (typeof Buffer !== 'undefined') return new Uint8Array(Buffer.from(str, 'base64'))
43
+ const bin = atob(str)
44
+ const bytes = new Uint8Array(bin.length)
45
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
46
+ return bytes
47
+ }
48
+
49
+ /**
50
+ * Server side: if `res.body` is binary, base64-encode it and mark the
51
+ * encoding via `WIRE_ENCODING_HEADER` so `decodeWireResponse()` on the
52
+ * other end knows to reverse it. String/plain-object bodies pass through
53
+ * unchanged -- `mesh-rpc.mjs` already handles those natively.
54
+ *
55
+ * @param {{status?: number, headers?: object, body?: *}} res
56
+ * @returns {{status: number, headers: object, body: *}}
57
+ */
58
+ export function encodeWireResponse(res = {}) {
59
+ const status = res.status ?? 200
60
+ const headers = res.headers || {}
61
+ const body = res.body
62
+ if (body instanceof Uint8Array || body instanceof ArrayBuffer) {
63
+ const bytes = body instanceof ArrayBuffer ? new Uint8Array(body) : body
64
+ return { status, headers: { ...headers, [WIRE_ENCODING_HEADER]: 'base64' }, body: toBase64(bytes) }
65
+ }
66
+ return { status, headers, body }
67
+ }
68
+
69
+ /**
70
+ * Client side: reverses `encodeWireResponse()`. Always strips
71
+ * `WIRE_ENCODING_HEADER` from the returned headers, whether or not this
72
+ * particular response was binary-encoded, so it never leaks into a real
73
+ * `Response`'s headers.
74
+ *
75
+ * @param {{status?: number, headers?: object, body?: *}} res
76
+ * @returns {{status: number, headers: object, body: *}}
77
+ */
78
+ export function decodeWireResponse(res = {}) {
79
+ const status = res.status ?? 200
80
+ const headers = { ...(res.headers || {}) }
81
+ const isBase64 = headers[WIRE_ENCODING_HEADER] === 'base64'
82
+ delete headers[WIRE_ENCODING_HEADER]
83
+ const body = isBase64 && typeof res.body === 'string' ? fromBase64(res.body) : res.body
84
+ return { status, headers, body }
85
+ }
86
+
87
+ export { WIRE_ENCODING_HEADER }