@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.
- package/README.md +232 -1
- package/package.json +7 -3
- package/src/agent-runtime.mjs +342 -0
- package/src/chunk-replication.mjs +751 -0
- package/src/cloud-storage-backend.mjs +932 -0
- package/src/cloud-storage.mjs +859 -0
- package/src/compat.mjs +98 -0
- package/src/grant-log.mjs +840 -0
- package/src/index.mjs +34 -2
- package/src/key-distribution.mjs +525 -0
- package/src/manifest-sync.mjs +363 -0
- package/src/mesh-agent-swarm.mjs +376 -0
- package/src/mesh-bootstrap.mjs +1131 -12
- package/src/mesh-compute.mjs +397 -0
- package/src/mesh-dht.mjs +182 -0
- package/src/mesh-fetch.mjs +246 -0
- package/src/mesh-hardening.mjs +226 -0
- package/src/mesh-health.mjs +282 -0
- package/src/mesh-keepalive.mjs +353 -0
- package/src/mesh-kv.mjs +673 -0
- package/src/mesh-orchestrator-tools.mjs +251 -0
- package/src/mesh-orchestrator.mjs +343 -0
- package/src/mesh-rpc.mjs +300 -0
- package/src/mesh-service.mjs +403 -0
- package/src/mesh-swarm.mjs +677 -0
- package/src/mesh-timestamp.mjs +265 -0
- package/src/mesh-torrent.mjs +683 -0
- package/src/mesh-verification.mjs +367 -0
- package/src/mesh-websocket.mjs +722 -0
- package/src/observability-bridge.mjs +453 -0
- package/src/orchestrator.mjs +18 -5
- package/src/peer-agent-swarm.mjs +12 -1
- package/src/peer-chat.mjs +230 -61
- package/src/peer-compute.mjs +66 -3
- package/src/peer-escrow.mjs +350 -1
- package/src/peer-files.mjs +362 -168
- package/src/peer-ipfs.mjs +205 -10
- package/src/peer-node.mjs +33 -2
- package/src/peer-routing.mjs +369 -5
- package/src/peer-terminal.mjs +400 -130
- package/src/serverless-executor-andbox.mjs +136 -0
- package/src/serverless-fetch.mjs +70 -0
- package/src/serverless-functions.mjs +67 -0
- package/src/serverless-peer-select.mjs +69 -0
- package/src/serverless-proxy.mjs +127 -0
- package/src/serverless-router.mjs +115 -0
- package/src/serverless-sites.mjs +116 -0
- package/src/serverless-static.mjs +202 -0
- package/src/serverless-wire.mjs +87 -0
- package/src/peer-session.mjs +0 -937
|
@@ -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 }
|