@johnhenry/browsermesh-apps 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +298 -17
  2. package/package.json +13 -9
  3. package/src/apps.mjs +4 -4
  4. package/src/audit.mjs +2 -2
  5. package/src/chat.mjs +3 -3
  6. package/src/cloud-storage-backend.mjs +5 -7
  7. package/src/cloud-storage.mjs +5 -4
  8. package/src/compat.mjs +2 -2
  9. package/src/consensus.mjs +7 -7
  10. package/src/devtools.mjs +3 -3
  11. package/src/gpu.mjs +2 -2
  12. package/src/index.mjs +12 -0
  13. package/src/internal/channel-codec.mjs +179 -0
  14. package/src/internal/json-message.mjs +49 -0
  15. package/src/internal/relay-flow.mjs +178 -0
  16. package/src/internal/request-target.mjs +280 -0
  17. package/src/internal/rpc-body.mjs +33 -0
  18. package/src/marketplace-ui.mjs +1 -1
  19. package/src/mesh-agent-swarm.mjs +1 -1
  20. package/src/mesh-bootstrap.mjs +47 -1
  21. package/src/mesh-channel.mjs +716 -0
  22. package/src/mesh-fetch.mjs +77 -263
  23. package/src/mesh-hardening.mjs +8 -1
  24. package/src/mesh-relay-backend.mjs +116 -22
  25. package/src/mesh-relay-host.mjs +296 -55
  26. package/src/mesh-rpc.mjs +126 -265
  27. package/src/mesh-sync.mjs +1 -1
  28. package/src/orchestrator.mjs +54 -29
  29. package/src/payments.mjs +56 -14
  30. package/src/peer-agent-swarm.mjs +2 -2
  31. package/src/peer-agent.mjs +7 -7
  32. package/src/peer-compute.mjs +2 -2
  33. package/src/peer-encrypted-store.mjs +3 -3
  34. package/src/peer-escrow.mjs +2 -2
  35. package/src/peer-health.mjs +3 -3
  36. package/src/peer-node.mjs +8 -5
  37. package/src/peer-payments.mjs +2 -2
  38. package/src/peer-registry.mjs +45 -3
  39. package/src/peer-routing.mjs +158 -21
  40. package/src/peer-services.mjs +3 -3
  41. package/src/peer-timestamp.mjs +3 -3
  42. package/src/peer-torrent.mjs +112 -47
  43. package/src/peer-verification.mjs +3 -3
  44. package/src/pod-host-service.mjs +48 -7
  45. package/src/pod-placement.mjs +582 -0
  46. package/src/pod-supervisor.mjs +9 -30
  47. package/src/protocol-channel.mjs +327 -0
  48. package/src/resources.mjs +2 -2
  49. package/src/restart-policy.mjs +67 -0
  50. package/src/scheduler.mjs +3 -3
  51. package/src/serverless-proxy.mjs +58 -7
  52. package/src/silent-catch.mjs +22 -9
  53. package/src/tools.mjs +3 -3
  54. package/src/visualizations.mjs +2 -2
  55. package/src/wsh-negotiator.mjs +97 -0
@@ -0,0 +1,327 @@
1
+ /**
2
+ * protocol-channel.mjs -- the seam for layered protocols.
3
+ *
4
+ * A layered protocol (a remote-object layer, a file protocol, ...) is written
5
+ * against ONE small interface, the "protocol channel", and neither knows nor
6
+ * cares what carries it:
7
+ *
8
+ * channel.peer verified identity of the other end (a public key,
9
+ * never a field of a message)
10
+ * channel.maxMessageBytes payload budget for one message (conservative: the
11
+ * link maximum less framing)
12
+ * channel.send(obj, { signal }) structured message, bytes (Uint8Array) included
13
+ * channel.onMessage(cb) cb(obj, { peer }); returning a promise slows the sender
14
+ * channel.request(method, params, { signal, onProgress, timeoutMs }) -> Promise<result>
15
+ * channel.notify(method, params)
16
+ * channel.onRequest(method, handler) handler(params, { peer, signal, progress })
17
+ * channel.onNotification(method, handler) handler(params, { peer })
18
+ * channel.onClose(cb) cb(error)
19
+ * channel.close()
20
+ *
21
+ * `assertProtocolChannel(x)` checks an object has that shape. The mesh channel
22
+ * link (`mesh-channel.mjs`), the named protocol channels built here, and any
23
+ * hand-written in-memory duplex can all satisfy it.
24
+ *
25
+ * Named protocols. Many protocols share one link. A server registers
26
+ * `serveProtocol(name, handler)`; a client calls `openProtocol(peer, name)`.
27
+ * Opening is a request on the link (`mesh.protocol.open`) that is
28
+ * authorised per protocol: scope `protocol:<name>:open` through
29
+ * `PeerRegistry.checkAccess(peer, 'protocol:<name>', 'open')`, default deny,
30
+ * with the registry's own wildcards (`protocol:*:open`, `protocol:counter:*`).
31
+ * Authorisation is re-checked on every incoming request, notification and
32
+ * message of a served channel, so revoking a scope closes the channel on its
33
+ * next use. `listProtocols(peer)` returns only the protocols (and versions)
34
+ * the caller would be allowed to open.
35
+ *
36
+ * Wire (all on top of a mesh-channel link; nothing new on the envelope):
37
+ * request mesh.protocol.open { name, versions? } -> { name, version }
38
+ * request mesh.protocol.list {} -> [{ name, versions }]
39
+ * notify mesh.protocol.close { name }
40
+ * protocol methods travel as `<name>/<method>`; raw messages as { $p: name, b }.
41
+ * A peer without protocol support answers `mesh.protocol.*` with -32601 (or
42
+ * does not run the channel at all); nothing here changes the link.
43
+ *
44
+ * Handlers on the opening side: register them with `setup(channel)` (called
45
+ * before the open request is sent) if the server may speak first.
46
+ */
47
+ import { ChannelErrorCode, MeshChannelError, createMeshChannelService } from './mesh-channel.mjs'
48
+
49
+ export const PROTOCOL_OPEN_METHOD = 'mesh.protocol.open'
50
+ export const PROTOCOL_LIST_METHOD = 'mesh.protocol.list'
51
+ export const PROTOCOL_CLOSE_METHOD = 'mesh.protocol.close'
52
+ export const PROTOCOL_FRAMING_RESERVE_BYTES = 512
53
+ const NAME_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/
54
+
55
+ /** The scope a peer needs to open protocol `name`: `protocol:<name>:open`. */
56
+ export function protocolScope(name, action = 'open') {
57
+ validateName(name)
58
+ return `protocol:${name}:${action}`
59
+ }
60
+
61
+ function validateName(name) {
62
+ // No ':' and no '*': a name can never carry a wildcard or another scope part.
63
+ if (typeof name !== 'string' || !NAME_RE.test(name)) throw new TypeError('protocol name must match /^[a-z0-9][a-z0-9._-]{0,63}$/')
64
+ }
65
+
66
+ export const PROTOCOL_CHANNEL_METHODS = Object.freeze(['send', 'onMessage', 'request', 'notify', 'onRequest', 'onNotification', 'onClose', 'close'])
67
+
68
+ /** @throws {TypeError} when `channel` does not have the protocol-channel shape. */
69
+ export function assertProtocolChannel(channel) {
70
+ if (!channel || typeof channel !== 'object') throw new TypeError('protocol channel must be an object')
71
+ for (const m of PROTOCOL_CHANNEL_METHODS) {
72
+ if (typeof channel[m] !== 'function') throw new TypeError(`protocol channel is missing ${m}()`)
73
+ }
74
+ if (typeof channel.peer !== 'string' || !channel.peer) throw new TypeError('protocol channel needs a peer identity')
75
+ if (!Number.isSafeInteger(channel.maxMessageBytes) || channel.maxMessageBytes <= 0) throw new TypeError('protocol channel needs maxMessageBytes')
76
+ return channel
77
+ }
78
+
79
+ const err = (code, reason, message) => new MeshChannelError(code, reason, message)
80
+
81
+ /**
82
+ * Transport-neutral protocol host: works with any link from
83
+ * `createChannelCore` / `createMeshChannelService`.
84
+ *
85
+ * @param {object} [opts]
86
+ * @param {(peer: string, name: string, action: string) => (boolean|{allowed: boolean})} [opts.authorize]
87
+ * Default deny when absent.
88
+ * @param {Function} [opts.onLog]
89
+ */
90
+ export function createProtocolHost({ authorize, onLog } = {}) {
91
+ const log = onLog || (() => {})
92
+ const served = new Map() // name -> { handler, versions }
93
+ const states = new Map() // link -> state
94
+ const allowed = (peer, name, action = 'open') => {
95
+ if (!authorize) return false
96
+ try {
97
+ const r = authorize(peer, name, action)
98
+ return r === true || r?.allowed === true
99
+ } catch { return false }
100
+ }
101
+
102
+ function stateOf(link) {
103
+ const st = states.get(link)
104
+ if (!st) throw new Error('createProtocolHost: link is not attached')
105
+ return st
106
+ }
107
+
108
+ function makeChannel(st, name, { serving, version }) {
109
+ const link = st.link
110
+ const unsubs = []
111
+ const closeListeners = new Set()
112
+ let closed = false
113
+ const prefix = `${name}/`
114
+ const gate = () => {
115
+ if (closed) throw err(ChannelErrorCode.CANCELLED, 'channel-closed', 'protocol channel closed')
116
+ if (serving && !allowed(link.peer, name)) {
117
+ channel.close('authorization revoked')
118
+ throw err(ChannelErrorCode.UNAUTHORIZED, 'not-authorized', `not authorised for protocol ${name}`)
119
+ }
120
+ }
121
+ const channel = {
122
+ name,
123
+ version,
124
+ serving,
125
+ peer: link.peer,
126
+ get maxMessageBytes() { return Math.max(1, link.maxMessageBytes - PROTOCOL_FRAMING_RESERVE_BYTES) },
127
+ get closed() { return closed },
128
+ send(obj, opts) { try { gate() } catch (e) { return Promise.reject(e) } return link.send({ $p: name, b: obj }, opts) },
129
+ onMessage(cb) {
130
+ if (typeof cb !== 'function') throw new TypeError('onMessage needs a function')
131
+ st.messageListeners.get(name).add(cb)
132
+ const off = () => st.messageListeners.get(name)?.delete(cb)
133
+ unsubs.push(off)
134
+ return off
135
+ },
136
+ request(method, params, opts) {
137
+ try { gate() } catch (e) { return Promise.reject(e) }
138
+ if (typeof method !== 'string' || !method) return Promise.reject(new TypeError('method must be a non-empty string'))
139
+ return link.request(prefix + method, params, opts)
140
+ },
141
+ notify(method, params) {
142
+ try { gate() } catch (e) { return Promise.reject(e) }
143
+ if (typeof method !== 'string' || !method) return Promise.reject(new TypeError('method must be a non-empty string'))
144
+ return link.notify(prefix + method, params)
145
+ },
146
+ onRequest(method, handler) {
147
+ if (typeof method !== 'string' || !method || typeof handler !== 'function') throw new TypeError('onRequest(method, handler)')
148
+ const off = link.onRequest(prefix + method, (params, ctx) => {
149
+ gate()
150
+ return handler(params, { ...ctx, method })
151
+ })
152
+ unsubs.push(off)
153
+ return off
154
+ },
155
+ onNotification(method, handler) {
156
+ if (typeof method !== 'string' || !method || typeof handler !== 'function') throw new TypeError('onNotification(method, handler)')
157
+ const off = link.onNotification(prefix + method, (params, ctx) => {
158
+ try { gate() } catch { return }
159
+ return handler(params, { ...ctx, method })
160
+ })
161
+ unsubs.push(off)
162
+ return off
163
+ },
164
+ onClose(cb) {
165
+ if (typeof cb !== 'function') throw new TypeError('onClose needs a function')
166
+ if (closed) { queueMicrotask(() => cb(null)); return () => {} }
167
+ closeListeners.add(cb)
168
+ return () => closeListeners.delete(cb)
169
+ },
170
+ close(reason, { notifyRemote = true } = {}) {
171
+ if (closed) return
172
+ closed = true
173
+ for (const off of unsubs.splice(0)) { try { off() } catch { /* already gone */ } }
174
+ st.channels.delete(name)
175
+ st.messageListeners.delete(name)
176
+ if (notifyRemote && !link.closed) link.notify(PROTOCOL_CLOSE_METHOD, { name }).catch(() => {})
177
+ const why = reason instanceof Error ? reason : null
178
+ for (const cb of [...closeListeners]) { try { cb(why) } catch (e) { log('protocol:close-listener-threw', { name, error: e?.message }) } }
179
+ closeListeners.clear()
180
+ },
181
+ }
182
+ st.channels.set(name, channel)
183
+ st.messageListeners.set(name, new Set())
184
+ return channel
185
+ }
186
+
187
+ /** Attach to a ready link: installs the protocol methods and the raw-message demultiplexer. */
188
+ function attach(link) {
189
+ if (states.has(link)) return () => {}
190
+ const st = { link, channels: new Map(), messageListeners: new Map(), offs: [] }
191
+ states.set(link, st)
192
+ st.offs.push(link.onRequest(PROTOCOL_OPEN_METHOD, (params, ctx) => {
193
+ const name = params?.name
194
+ try { validateName(name) } catch { throw err(ChannelErrorCode.INVALID, 'bad-protocol-name', 'invalid protocol name') }
195
+ // Authorisation first, so an unauthorised caller learns nothing about what is served.
196
+ if (!allowed(ctx.peer, name)) throw err(ChannelErrorCode.UNAUTHORIZED, 'not-authorized', `not authorised for protocol ${name}`)
197
+ const entry = served.get(name)
198
+ if (!entry) throw err(ChannelErrorCode.METHOD_NOT_FOUND, 'unknown-protocol', `protocol ${name} is not served here`)
199
+ const wanted = Array.isArray(params.versions) && params.versions.length ? params.versions : [1]
200
+ const version = entry.versions.filter(v => wanted.includes(v)).sort((a, b) => b - a)[0]
201
+ if (version === undefined) throw err(ChannelErrorCode.UNSUPPORTED, 'unsupported-version', `no common version of ${name}`)
202
+ if (st.channels.has(name)) throw err(ChannelErrorCode.INVALID, 'already-open', `${name} is already open on this link`)
203
+ const channel = makeChannel(st, name, { serving: true, version })
204
+ // The accept handler runs before the response leaves, so it can register handlers first.
205
+ Promise.resolve().then(() => entry.handler(channel, { peer: ctx.peer, version })).catch(e => {
206
+ log('protocol:serve-handler-threw', { name, error: e?.message })
207
+ channel.close(e)
208
+ })
209
+ return { name, version }
210
+ }))
211
+ st.offs.push(link.onRequest(PROTOCOL_LIST_METHOD, (_params, ctx) => {
212
+ const out = []
213
+ for (const [name, entry] of served) if (allowed(ctx.peer, name)) out.push({ name, versions: [...entry.versions] })
214
+ return out
215
+ }))
216
+ st.offs.push(link.onNotification(PROTOCOL_CLOSE_METHOD, params => {
217
+ const ch = typeof params?.name === 'string' ? st.channels.get(params.name) : undefined
218
+ ch?.close(null, { notifyRemote: false })
219
+ }))
220
+ st.offs.push(link.onMessage(async (msg, ctx) => {
221
+ if (!msg || typeof msg.$p !== 'string') return
222
+ const ch = st.channels.get(msg.$p)
223
+ if (!ch) return
224
+ if (ch.serving !== false) {
225
+ // served side: re-check authorisation for this message
226
+ if (!allowed(link.peer, msg.$p)) { ch.close('authorization revoked'); return }
227
+ }
228
+ const listeners = st.messageListeners.get(msg.$p)
229
+ if (!listeners) return
230
+ await Promise.all([...listeners].map(cb => cb(msg.b, { peer: ctx.peer })))
231
+ }))
232
+ st.offs.push(link.onClose(err2 => {
233
+ for (const ch of [...st.channels.values()]) ch.close(err2, { notifyRemote: false })
234
+ states.delete(link)
235
+ }))
236
+ return () => { for (const off of st.offs.splice(0)) off(); states.delete(link) }
237
+ }
238
+
239
+ return {
240
+ /** Register a served protocol. `handler(channel, { peer, version })` runs for each accepted open. */
241
+ serveProtocol(name, handler, { versions = [1] } = {}) {
242
+ validateName(name)
243
+ if (typeof handler !== 'function') throw new TypeError('serveProtocol needs a handler')
244
+ if (!Array.isArray(versions) || !versions.length || !versions.every(v => Number.isSafeInteger(v) && v > 0)) throw new TypeError('versions must be positive integers')
245
+ if (served.has(name)) throw new Error(`protocol ${name} is already served`)
246
+ served.set(name, { handler, versions: [...versions] })
247
+ return () => { served.delete(name) }
248
+ },
249
+ attach,
250
+ /**
251
+ * Open protocol `name` on an attached `link`. `setup(channel)` runs before the open request is sent.
252
+ * Rejects with -32003 when not authorised, -32601 when not served, -32000 on no common version.
253
+ */
254
+ async openProtocol(link, name, { versions = [1], setup, signal, timeoutMs } = {}) {
255
+ validateName(name)
256
+ const st = stateOf(link)
257
+ if (st.channels.has(name)) throw err(ChannelErrorCode.INVALID, 'already-open', `protocol ${name} is already open on this link`)
258
+ const channel = makeChannel(st, name, { serving: false, version: undefined })
259
+ try {
260
+ setup?.(channel)
261
+ const res = await link.request(PROTOCOL_OPEN_METHOD, { name, versions }, { signal, timeoutMs })
262
+ channel.version = res?.version
263
+ return channel
264
+ } catch (e) {
265
+ channel.close(e, { notifyRemote: false })
266
+ throw e
267
+ }
268
+ },
269
+ /** Protocols (and versions) `link`'s peer would let this side open. */
270
+ async listProtocols(link, opts) {
271
+ stateOf(link)
272
+ return link.request(PROTOCOL_LIST_METHOD, {}, opts)
273
+ },
274
+ /** Protocols currently open on a link. */
275
+ openProtocols(link) { return [...stateOf(link).channels.keys()] },
276
+ /** Close every open channel of `peer` (or one `name`), e.g. after a revocation. */
277
+ closeProtocols(peer, name) {
278
+ for (const st of states.values()) {
279
+ if (st.link.peer !== peer) continue
280
+ for (const [n, ch] of [...st.channels]) if (name === undefined || n === name) ch.close('closed by the host')
281
+ }
282
+ },
283
+ }
284
+ }
285
+
286
+ /**
287
+ * MeshService descriptor: the channel service plus a protocol host, authorised
288
+ * through the node's `PeerRegistry`. Use it INSTEAD of attaching
289
+ * `createMeshChannelService` as well (both would answer the same envelope type).
290
+ *
291
+ * api: { serveProtocol, openProtocol(peer, name, opts), listProtocols(peer), openProtocols(peer),
292
+ * closeProtocols(peer, name), channel } where `channel` is the underlying channel service api.
293
+ *
294
+ * Nothing is served and nothing is authorised by default.
295
+ */
296
+ export function createMeshProtocolService({ authorize, ...channelOptions } = {}) {
297
+ return {
298
+ name: 'mesh-protocols',
299
+ attach(peerNode, ctx) {
300
+ const registry = ctx.registry
301
+ const host = createProtocolHost({
302
+ authorize: authorize || ((peer, name, action) => registry && typeof registry.checkAccess === 'function'
303
+ ? registry.checkAccess(peer, `protocol:${name}`, action)
304
+ : false),
305
+ onLog: channelOptions.onLog,
306
+ })
307
+ const inner = createMeshChannelService({ ...channelOptions, onLink: link => { host.attach(link); channelOptions.onLink?.(link) } }).attach(peerNode, ctx)
308
+ return {
309
+ api: {
310
+ serveProtocol: host.serveProtocol,
311
+ async openProtocol(peer, name, opts) {
312
+ const link = await inner.api.open(peer, opts?.timeoutMs === undefined ? undefined : { timeoutMs: opts.timeoutMs })
313
+ return host.openProtocol(link, name, opts)
314
+ },
315
+ async listProtocols(peer, opts) {
316
+ const link = await inner.api.open(peer)
317
+ return host.listProtocols(link, opts)
318
+ },
319
+ openProtocols: peer => { const l = inner.api.link(peer); return l ? host.openProtocols(l) : [] },
320
+ closeProtocols: host.closeProtocols,
321
+ channel: inner.api,
322
+ },
323
+ teardown: inner.teardown,
324
+ }
325
+ },
326
+ }
327
+ }
package/src/resources.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * clawser-mesh-resources.js -- Resource advertisement, discovery, and job
2
+ * resources.mjs --Resource advertisement, discovery, and job
3
3
  * scheduling for BrowserMesh.
4
4
  *
5
5
  * Peers advertise hardware/software resources, discover matching nodes, score
@@ -8,7 +8,7 @@
8
8
  * No browser-only imports at module level.
9
9
  *
10
10
  * Run tests:
11
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-resources.test.mjs
11
+ * cd packages/browsermesh-apps && node --import ./test/_setup-globals.mjs --test test/resources.test.mjs
12
12
  */
13
13
 
14
14
  import { MESH_TYPE } from '@johnhenry/browsermesh-primitives';
@@ -0,0 +1,67 @@
1
+ /**
2
+ * restart-policy.mjs -- the pure half of hosted-pod supervision: whether a
3
+ * podspec's `restart` policy wants an exited pod started again, and how long
4
+ * to wait first. `pod-supervisor.mjs` (timers, audit, re-placement) and
5
+ * `pod-placement.mjs` (`createHostPool().handleExit()`) both decide through
6
+ * these functions, so the two cannot drift.
7
+ *
8
+ * No clock, no timers, no I/O: callers pass the numbers in and schedule the
9
+ * delay themselves.
10
+ */
11
+
12
+ /** Default `restart.maxRestarts` when a podspec did not say. */
13
+ export const DEFAULT_MAX_RESTARTS = 3
14
+ /** Default `restart.backoffMs` base. */
15
+ export const DEFAULT_BACKOFF_MS = 1000
16
+ /** Backoff never waits longer than this, regardless of restart count. */
17
+ export const MAX_BACKOFF_MS = 60_000
18
+
19
+ /**
20
+ * Whether `policy` says to restart a pod that exited with `{code, reason}`.
21
+ * An intentional drain (`reason === 'drained'`) is never a restart
22
+ * candidate under any policy: callers check that before consulting this.
23
+ *
24
+ * @param {'never'|'on-failure'|'always'} policy
25
+ * @param {{code?: number, reason?: string}} exit
26
+ * @returns {boolean}
27
+ */
28
+ export function policyWantsRestart(policy, { code, reason } = {}) {
29
+ switch (policy) {
30
+ case 'always':
31
+ return true
32
+ case 'on-failure':
33
+ return code !== 0 || reason === 'crashed' || reason === 'host-lost'
34
+ case 'never':
35
+ default:
36
+ return false
37
+ }
38
+ }
39
+
40
+ /**
41
+ * The wait before restart number `restartsSoFar + 1`: the base doubled per
42
+ * restart already made, capped at {@link MAX_BACKOFF_MS}.
43
+ *
44
+ * @param {number} restartsSoFar - Restarts already performed (0 for the first).
45
+ * @param {number} [baseMs]
46
+ * @returns {number}
47
+ */
48
+ export function restartDelayMs(restartsSoFar, baseMs = DEFAULT_BACKOFF_MS) {
49
+ return Math.min(baseMs * (2 ** restartsSoFar), MAX_BACKOFF_MS)
50
+ }
51
+
52
+ /**
53
+ * The full decision for one exit.
54
+ *
55
+ * @param {object} input
56
+ * @param {{policy?: string, maxRestarts?: number, backoffMs?: number}} [input.restart] - A podspec's `restart`.
57
+ * @param {{code?: number, reason?: string}} input.exit
58
+ * @param {number} input.restartsSoFar
59
+ * @returns {{restart: boolean, delayMs?: number, why: 'drained'|'policy'|'gave-up'|'restart'}}
60
+ */
61
+ export function decideRestart({ restart = {}, exit = {}, restartsSoFar = 0 } = {}) {
62
+ if (exit.reason === 'drained') return { restart: false, why: 'drained' }
63
+ if (!policyWantsRestart(restart.policy ?? 'never', exit)) return { restart: false, why: 'policy' }
64
+ const maxRestarts = restart.maxRestarts ?? DEFAULT_MAX_RESTARTS
65
+ if (restartsSoFar >= maxRestarts) return { restart: false, why: 'gave-up' }
66
+ return { restart: true, delayMs: restartDelayMs(restartsSoFar, restart.backoffMs ?? DEFAULT_BACKOFF_MS), why: 'restart' }
67
+ }
package/src/scheduler.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
- * clawser-mesh-scheduler.js -- Mesh-aware task scheduling for BrowserMesh.
2
+ // STATUS: INTEGRATED — wired into the Pod lifecycle (@johnhenry/browsermesh-pod), proven via E2E testing
3
+ * scheduler.mjs --Mesh-aware task scheduling for BrowserMesh.
4
4
  *
5
5
  * Distributes tasks across mesh peers using configurable scheduling policies
6
6
  * (best-fit, first-fit, round-robin, load-balanced). Includes a priority queue,
@@ -9,7 +9,7 @@
9
9
  * No browser-only imports at module level.
10
10
  *
11
11
  * Run tests:
12
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-scheduler.test.mjs
12
+ * cd packages/browsermesh-apps && node --import ./test/_setup-globals.mjs --test test/scheduler.test.mjs
13
13
  */
14
14
 
15
15
  // ---------------------------------------------------------------------------
@@ -26,6 +26,8 @@
26
26
  * @module serverless-proxy
27
27
  */
28
28
 
29
+ import { PROXY_LIMITS_DEFAULTS, resolveTarget } from './internal/request-target.mjs'
30
+
29
31
  /** Request headers unsafe/meaningless to forward to the proxy target as-is -- `fetch()` recomputes these itself. */
30
32
  const HOP_BY_HOP_REQUEST_HEADERS = new Set([
31
33
  'host', 'connection', 'content-length', 'keep-alive', 'transfer-encoding',
@@ -88,21 +90,60 @@ function bodyForFetch(body, method) {
88
90
  * @returns {(req: {path: string, method?: string, headers?: object, body?: *}) => Promise<{status: number, headers: object, body: Uint8Array|string}>}
89
91
  * Never returns `null` -- see module doc comment.
90
92
  */
91
- export function createProxyHandler({ targetOrigin, spaFallback = false } = {}) {
93
+ export function createProxyHandler({ targetOrigin, spaFallback = false, maxResponseBytes = PROXY_LIMITS_DEFAULTS.maxResponseBytes, requestTimeoutMs = PROXY_LIMITS_DEFAULTS.requestTimeoutMs } = {}) {
92
94
  if (!targetOrigin || typeof targetOrigin !== 'string') {
93
95
  throw new Error('createProxyHandler: opts.targetOrigin is required and must be a string')
94
96
  }
95
97
  const origin = new URL(targetOrigin) // throws synchronously on an invalid URL -- fail at construction, not on first request
96
98
 
99
+ /**
100
+ * Read a response body as bytes, never holding more than `maxResponseBytes`.
101
+ * @param {Response} res
102
+ * @returns {Promise<Uint8Array|null>} null when the body exceeds the bound
103
+ */
104
+ async function readBytes(res) {
105
+ const declared = Number(res.headers.get('content-length'))
106
+ if (Number.isFinite(declared) && declared > maxResponseBytes) {
107
+ try { await res.body?.cancel() } catch { /* already closed */ }
108
+ return null
109
+ }
110
+ if (!res.body) return new Uint8Array(await res.arrayBuffer())
111
+ const reader = res.body.getReader()
112
+ const chunks = []
113
+ let total = 0
114
+ for (;;) {
115
+ const { done, value } = await reader.read()
116
+ if (done) break
117
+ total += value.byteLength
118
+ if (total > maxResponseBytes) {
119
+ try { await reader.cancel() } catch { /* already closed */ }
120
+ return null
121
+ }
122
+ chunks.push(value)
123
+ }
124
+ const out = new Uint8Array(total)
125
+ let offset = 0
126
+ for (const chunk of chunks) { out.set(chunk, offset); offset += chunk.byteLength }
127
+ return out
128
+ }
129
+
130
+ // A redirect is returned to the caller as it is and never followed, so a
131
+ // request cannot leave the target origin.
132
+ const fetchOptions = (init) => ({ ...init, redirect: 'manual', signal: AbortSignal.timeout(requestTimeoutMs) })
133
+
97
134
  return async function handleProxy({ path = '/', method = 'GET', headers = {}, body } = {}) {
98
- const target = new URL(path, origin)
135
+ const resolved = resolveTarget(origin.origin, path)
136
+ if (!resolved.ok) {
137
+ return { status: 400, headers: { 'content-type': 'text/plain' }, body: `Bad Request: ${resolved.reason}` }
138
+ }
139
+ const target = resolved.url
99
140
  const init = { method, headers: filterHeaders(headers, HOP_BY_HOP_REQUEST_HEADERS) }
100
141
  const fetchBody = bodyForFetch(body, method)
101
142
  if (fetchBody !== undefined) init.body = fetchBody
102
143
 
103
144
  let res
104
145
  try {
105
- res = await fetch(target, init)
146
+ res = await fetch(target, fetchOptions(init))
106
147
  } catch (err) {
107
148
  return { status: 502, headers: { 'content-type': 'text/plain' }, body: `Bad Gateway: ${err?.message || String(err)}` }
108
149
  }
@@ -111,17 +152,27 @@ export function createProxyHandler({ targetOrigin, spaFallback = false } = {}) {
111
152
  const fallbackTarget = new URL('/index.html', origin)
112
153
  let fallbackRes
113
154
  try {
114
- fallbackRes = await fetch(fallbackTarget)
155
+ fallbackRes = await fetch(fallbackTarget, fetchOptions({}))
115
156
  } catch {
116
157
  fallbackRes = null
117
158
  }
118
159
  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 }
160
+ const fallbackBytes = await readBytes(fallbackRes)
161
+ if (fallbackBytes) {
162
+ return { status: 200, headers: { 'content-type': fallbackRes.headers.get('content-type') || 'text/html' }, body: fallbackBytes }
163
+ }
121
164
  }
122
165
  }
123
166
 
124
- const bytes = new Uint8Array(await res.arrayBuffer())
167
+ let bytes
168
+ try {
169
+ bytes = await readBytes(res)
170
+ } catch (err) {
171
+ return { status: 502, headers: { 'content-type': 'text/plain' }, body: `Bad Gateway: ${err?.message || String(err)}` }
172
+ }
173
+ if (bytes === null) {
174
+ return { status: 502, headers: { 'content-type': 'text/plain' }, body: 'Bad Gateway: response too large' }
175
+ }
125
176
  return { status: res.status, headers: responseHeadersToObject(res.headers), body: bytes }
126
177
  }
127
178
  }
@@ -2,31 +2,44 @@
2
2
  * silent-catch.mjs — debug-gated structured logger for the
3
3
  * `try { … } catch { /* ignore *\/ }` pattern.
4
4
  *
5
- * Vendored from clawser-silent-catch.mjs (fully standalone, no other
6
- * clawser-app imports) so this package doesn't need to reach into web/.
5
+ * Vendored from a standalone module of the host application (no other
6
+ * host-application imports) so this package doesn't need to reach into it.
7
7
  *
8
8
  * Replaces silent catches with an opt-in inspectable record. Default
9
9
  * behaviour is unchanged (silent), so this is a drop-in replacement.
10
10
  * Users surface the events by enabling debug mode:
11
11
  *
12
- * localStorage.setItem('clawser_debug', 'true') // persistent
13
- * // or, in DevTools: clawserDebug.enable()
12
+ * localStorage.setItem('browsermesh_debug', 'true') // persistent
13
+ * // or, in DevTools: browsermeshDebug.enable()
14
+ *
15
+ * The old `clawser_debug` localStorage key (and `clawserDebug` global) are
16
+ * deprecated aliases, kept for compatibility.
14
17
  */
15
18
 
19
+ /** Primary localStorage key for the debug switch. */
20
+ const DEBUG_KEY = 'browsermesh_debug';
21
+ /** Deprecated alias, kept for compatibility. */
22
+ const LEGACY_DEBUG_KEY = 'clawser_debug';
23
+
24
+ function readDebugFlag() {
25
+ return localStorage.getItem(DEBUG_KEY) === 'true'
26
+ || localStorage.getItem(LEGACY_DEBUG_KEY) === 'true';
27
+ }
28
+
16
29
  let enabled = false;
17
30
  try {
18
31
  if (typeof localStorage !== 'undefined') {
19
- enabled = localStorage.getItem('clawser_debug') === 'true';
32
+ enabled = readDebugFlag();
20
33
  }
21
34
  } catch {
22
35
  // localStorage may throw in privacy / sandbox contexts — treat as disabled
23
36
  }
24
37
 
25
- /** Re-check the localStorage flag; called by clawserDebug.enable/disable. */
38
+ /** Re-check the localStorage flag; called by browsermeshDebug.enable/disable. */
26
39
  export function refreshSilentCatchState() {
27
40
  try {
28
41
  if (typeof localStorage !== 'undefined') {
29
- enabled = localStorage.getItem('clawser_debug') === 'true';
42
+ enabled = readDebugFlag();
30
43
  }
31
44
  } catch {
32
45
  enabled = false;
@@ -36,7 +49,7 @@ export function refreshSilentCatchState() {
36
49
  /**
37
50
  * Log a silent-catch event. No-op unless debug mode is enabled.
38
51
  *
39
- * @param {string} module — file/component (e.g. 'clawser-pod')
52
+ * @param {string} module — file/component (e.g. 'pod')
40
53
  * @param {string} operation — what was attempted (e.g. 'relay-disconnect')
41
54
  * @param {*} error — the caught value
42
55
  * @param {object} [context] — extra structured fields
@@ -51,5 +64,5 @@ export function silentCatch(module, operation, error, context) {
51
64
  }
52
65
  const entry = { module, operation, error: error?.message || String(error) };
53
66
  if (context) Object.assign(entry, context);
54
- console.warn('[clawser:silent-catch]', entry);
67
+ console.warn('[browsermesh:silent-catch]', entry);
55
68
  }
package/src/tools.mjs CHANGED
@@ -1,10 +1,10 @@
1
1
  /**
2
- * Clawser Mesh Tools
2
+ * BrowserMesh Mesh Tools
3
3
  *
4
4
  * BrowserTool subclasses exposing mesh stream and file transfer operations
5
- * to the AI agent. Follows the pattern in clawser-wsh-tools.js.
5
+ * to the AI agent.
6
6
  *
7
- * @module clawser-mesh-tools
7
+ * @module tools
8
8
  */
9
9
 
10
10
  import { BrowserTool } from './compat.mjs';
@@ -1,5 +1,5 @@
1
1
  /**
2
- * clawser-mesh-visualizations.js -- Trust & Topology Visualization Data.
2
+ * visualizations.mjs --Trust & Topology Visualization Data.
3
3
  *
4
4
  * Produces structured data for rendering trust graphs and mesh topology.
5
5
  * UI-agnostic — outputs JSON-friendly objects suitable for any renderer
@@ -15,7 +15,7 @@
15
15
  * No browser-only imports at module level.
16
16
  *
17
17
  * Run tests:
18
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-visualizations.test.mjs
18
+ * cd packages/browsermesh-apps && node --import ./test/_setup-globals.mjs --test test/visualizations.test.mjs
19
19
  */
20
20
 
21
21
  // ---------------------------------------------------------------------------