@johnhenry/browsermesh-apps 0.3.0 → 0.4.1

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,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
+ }