@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,265 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mesh-timestamp.mjs -- Phase 1 of the browsermesh-app-layer-migration plan
|
|
3
|
+
* (issue #120): wraps `peer-timestamp.mjs`'s `TimestampAuthority`/
|
|
4
|
+
* `TimestampProof` as a `MeshService` (`mesh-service.mjs`, Phase C's
|
|
5
|
+
* `attach()`/`ctx` convention).
|
|
6
|
+
*
|
|
7
|
+
* `TimestampAuthority`'s own doc comment already confirms this is a
|
|
8
|
+
* near-trivial wire-up, not a redesign: its constructor only requires
|
|
9
|
+
* `sessions.listSessions()` to EXIST (a duck-type guard) -- nothing inside
|
|
10
|
+
* the class ever actually CALLS it. `PeerNode` (`peer-node.mjs`) already
|
|
11
|
+
* implements `listSessions()` natively, so this file passes the real
|
|
12
|
+
* `peerNode` straight through as `TimestampAuthority`'s `sessions` dependency
|
|
13
|
+
* with zero adapter code, exactly as the plan's Phase 1 section predicted.
|
|
14
|
+
*
|
|
15
|
+
* ---------------------------------------------------------------------------
|
|
16
|
+
* WHAT THIS FILE ACTUALLY ADDS: `TimestampAuthority.stamp(eventHash,
|
|
17
|
+
* peerTimestamps)` takes an already-collected `Map<podId, timestamp>` as an
|
|
18
|
+
* explicitly-optional, test-oriented parameter (see that method's own doc
|
|
19
|
+
* comment: "Optional peer timestamps for testing") -- collecting REAL
|
|
20
|
+
* timestamps from REAL connected mesh peers is deliberately left outside
|
|
21
|
+
* `peer-timestamp.mjs` entirely. That collection is the one genuine piece of
|
|
22
|
+
* new logic this wrapper contributes: a small request/response wire protocol
|
|
23
|
+
* (`'time-request'`/`'time-response'`, sharing one envelope `type`, mirroring
|
|
24
|
+
* `mesh-rpc.mjs`'s `kind`-tagged-single-type shape) that asks every currently
|
|
25
|
+
* connected peer (`peerNode.listPeers({status:'connected'})`, the same
|
|
26
|
+
* `peer.fingerprint`-is-the-pubKey convention `mesh-keepalive.mjs` already
|
|
27
|
+
* establishes) for their local clock, waits up to `witnessTimeoutMs` for
|
|
28
|
+
* replies, and hands whatever arrived (a possibly-partial map -- a slow or
|
|
29
|
+
* unresponsive peer just doesn't make it into `peerTimestamps`, exactly the
|
|
30
|
+
* same "graceful partial witness set" shape `TimestampAuthority.stamp()`
|
|
31
|
+
* itself already tolerates) to `authority.stamp()`.
|
|
32
|
+
*
|
|
33
|
+
* ---------------------------------------------------------------------------
|
|
34
|
+
* IDENTITY ADAPTER -- `TimestampAuthority` wants `identity.sign(data) ->
|
|
35
|
+
* Promise<Uint8Array>` plus `identity.podId`. The real signer,
|
|
36
|
+
* `IdentityWallet.sign(podId, data)` (`@johnhenry/browsermesh-core`), takes
|
|
37
|
+
* `podId` as an explicit first argument -- a different shape, the same gap
|
|
38
|
+
* `grant-log.mjs` documents for its own `wallet` dependency. Unless the
|
|
39
|
+
* caller supplies its own `opts.identity`, this file closes that gap the
|
|
40
|
+
* same way `grant-log.mjs`'s `attach()` derives its signer from the real
|
|
41
|
+
* node (`peerNode.podId`/`peerNode.wallet`) rather than asking the factory
|
|
42
|
+
* caller to pre-bind one:
|
|
43
|
+
*
|
|
44
|
+
* { podId: peerNode.podId, sign: (data) => peerNode.wallet.sign(peerNode.podId, new TextEncoder().encode(data)) }
|
|
45
|
+
*
|
|
46
|
+
* `identity.verify()` is deliberately left UNSET by this default adapter.
|
|
47
|
+
* `TimestampAuthority.verify()` already documents exactly what's missing to
|
|
48
|
+
* provide one for real: verifying a FOREIGN peer's witness signature needs a
|
|
49
|
+
* way to resolve `signerPodId -> raw public key bytes`, and `TimestampProof`
|
|
50
|
+
* carries no embedded pubkey material to do that with (unlike
|
|
51
|
+
* `grant-log.mjs`'s wire records, which embed the raw pubkey precisely so a
|
|
52
|
+
* receiver can verify without a directory lookup). Building that directory
|
|
53
|
+
* is a real, separate piece of design -- out of scope for "thin wrapper, not
|
|
54
|
+
* a redesign" -- so `verify()` here inherits `TimestampAuthority`'s own
|
|
55
|
+
* documented, honest degradation: full signature verification for proofs
|
|
56
|
+
* this authority issued itself (`checked: 'self'`), structural-only
|
|
57
|
+
* otherwise. A caller who builds that directory can supply its own
|
|
58
|
+
* `opts.identity` with a working `verify()` to upgrade this transparently.
|
|
59
|
+
*
|
|
60
|
+
* ---------------------------------------------------------------------------
|
|
61
|
+
* Observability events (`ctx.emit()`, see `mesh-service.mjs`'s module doc
|
|
62
|
+
* comment for the full convention):
|
|
63
|
+
*
|
|
64
|
+
* - `timestamp:stamped` `{eventHash, canonicalTimestamp, confidence,
|
|
65
|
+
* witnessCount}` -- `api.stamp()` produced a proof.
|
|
66
|
+
* - `timestamp:verified` `{eventHash, valid, checked}` -- `api.verify()`
|
|
67
|
+
* finished checking a proof.
|
|
68
|
+
* - `timestamp:witness-timeout` `{requestId, expected, received}` --
|
|
69
|
+
* `witnessTimeoutMs` elapsed with fewer witness replies than peers asked.
|
|
70
|
+
*
|
|
71
|
+
* No browser-only imports at module level.
|
|
72
|
+
*/
|
|
73
|
+
|
|
74
|
+
import { TimestampAuthority } from './peer-timestamp.mjs'
|
|
75
|
+
|
|
76
|
+
/** Shared envelope `type` for both witness-collection directions (request/response, tagged by `kind`). */
|
|
77
|
+
const DEFAULT_ENVELOPE_TYPE = 'mesh-timestamp'
|
|
78
|
+
|
|
79
|
+
/** How long `stamp()` waits for witness replies before proceeding with whatever arrived. */
|
|
80
|
+
const DEFAULT_WITNESS_TIMEOUT_MS = 3000
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Build a `MeshService` descriptor (`mesh-service.mjs`, Phase C) wrapping
|
|
84
|
+
* `TimestampAuthority`/`TimestampProof`. See this file's module doc comment
|
|
85
|
+
* for the full design writeup.
|
|
86
|
+
*
|
|
87
|
+
* @param {object} [opts]
|
|
88
|
+
* @param {{sign: (data: string) => Promise<Uint8Array>, podId: string, verify?: Function}} [opts.identity]
|
|
89
|
+
* Defaults to a thin adapter over the attached `peerNode`'s own
|
|
90
|
+
* `podId`/`wallet` (see module doc comment's "IDENTITY ADAPTER"). Supply
|
|
91
|
+
* your own to use a different signer, or to add a real `verify()` once a
|
|
92
|
+
* podId->pubkey directory exists.
|
|
93
|
+
* @param {number} [opts.clockSkewMs] - Passed straight through to
|
|
94
|
+
* `TimestampAuthority` (default 30000, see `TIMESTAMP_DEFAULTS`).
|
|
95
|
+
* @param {number} [opts.witnessTimeoutMs=3000] - How long `api.stamp()`
|
|
96
|
+
* waits for witness replies before proceeding with a partial (possibly
|
|
97
|
+
* empty) set.
|
|
98
|
+
* @param {string} [opts.envelopeType='mesh-timestamp']
|
|
99
|
+
* @param {Function} [opts.onLog]
|
|
100
|
+
* @returns {import('./mesh-service.mjs').MeshService}
|
|
101
|
+
*/
|
|
102
|
+
export function createTimestampService({
|
|
103
|
+
identity,
|
|
104
|
+
clockSkewMs,
|
|
105
|
+
witnessTimeoutMs = DEFAULT_WITNESS_TIMEOUT_MS,
|
|
106
|
+
envelopeType = DEFAULT_ENVELOPE_TYPE,
|
|
107
|
+
onLog,
|
|
108
|
+
} = {}) {
|
|
109
|
+
const log = onLog || (() => {})
|
|
110
|
+
|
|
111
|
+
return {
|
|
112
|
+
name: 'timestamp',
|
|
113
|
+
|
|
114
|
+
attach(peerNode, ctx) {
|
|
115
|
+
if (typeof peerNode?.listSessions !== 'function') {
|
|
116
|
+
throw new Error(
|
|
117
|
+
'mesh-timestamp: peerNode must be a real PeerNode providing listSessions() ' +
|
|
118
|
+
'(a duck-typed {sendTo, onIncomingData} node, as other MeshServices in this ' +
|
|
119
|
+
'family accept, is not enough here -- see module doc comment).',
|
|
120
|
+
)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const effectiveIdentity = identity || {
|
|
124
|
+
podId: peerNode.podId,
|
|
125
|
+
// TimestampAuthority signs plain strings (e.g. `${eventHash}:${ts}`);
|
|
126
|
+
// IdentityWallet.sign(podId, data) requires a BufferSource -- same
|
|
127
|
+
// string-to-bytes encoding grant-log.mjs's own wallet.sign() call
|
|
128
|
+
// sites already need (see that file's `new TextEncoder().encode(...)`).
|
|
129
|
+
sign: (data) => peerNode.wallet.sign(peerNode.podId, new TextEncoder().encode(data)),
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// TimestampAuthority's constructor only checks that sessions.listSessions
|
|
133
|
+
// exists -- it never actually calls it (see module doc comment) -- so
|
|
134
|
+
// passing the real peerNode through directly is sufficient, no adapter
|
|
135
|
+
// needed.
|
|
136
|
+
const authority = new TimestampAuthority({
|
|
137
|
+
sessions: peerNode,
|
|
138
|
+
identity: effectiveIdentity,
|
|
139
|
+
clockSkewMs,
|
|
140
|
+
onLog: (level, msg) => log('mesh-timestamp:internal', { level, msg }),
|
|
141
|
+
})
|
|
142
|
+
|
|
143
|
+
let reqSeq = 0
|
|
144
|
+
const nextRequestId = () => `${peerNode.podId}:${Date.now()}:${++reqSeq}`
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* @type {Map<string, {resolve: (responses: Map<string, number>) => void,
|
|
148
|
+
* timer: ReturnType<typeof setTimeout>, responses: Map<string, number>, expectedCount: number}>}
|
|
149
|
+
*/
|
|
150
|
+
const pendingWitnessRequests = new Map()
|
|
151
|
+
|
|
152
|
+
const unsubscribe = ctx.onIncomingData(envelopeType, (fromPubKey, msg) => {
|
|
153
|
+
if (!msg || typeof msg.kind !== 'string') return
|
|
154
|
+
if (msg.kind === 'time-request') {
|
|
155
|
+
ctx.sendTo(fromPubKey, envelopeType, { kind: 'time-response', requestId: msg.requestId, timestamp: Date.now() }).catch((err) => {
|
|
156
|
+
log('mesh-timestamp:response-send-failed', { to: fromPubKey, error: err?.message || String(err) })
|
|
157
|
+
})
|
|
158
|
+
} else if (msg.kind === 'time-response') {
|
|
159
|
+
const pending = pendingWitnessRequests.get(msg.requestId)
|
|
160
|
+
if (!pending) return // already resolved (timed out or fully collected) -- ignore
|
|
161
|
+
pending.responses.set(fromPubKey, msg.timestamp)
|
|
162
|
+
if (pending.responses.size >= pending.expectedCount) {
|
|
163
|
+
clearTimeout(pending.timer)
|
|
164
|
+
pendingWitnessRequests.delete(msg.requestId)
|
|
165
|
+
pending.resolve(pending.responses)
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
})
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Collect real peer timestamps to use as `TimestampAuthority.stamp()`'s
|
|
172
|
+
* `peerTimestamps` argument. See module doc comment.
|
|
173
|
+
* @param {string[]} [targetPubKeys] - Explicit witness set. Defaults to
|
|
174
|
+
* every currently connected peer.
|
|
175
|
+
* @returns {Promise<Map<string, number>>}
|
|
176
|
+
*/
|
|
177
|
+
async function collectWitnesses(targetPubKeys) {
|
|
178
|
+
const targets = targetPubKeys && targetPubKeys.length
|
|
179
|
+
? targetPubKeys
|
|
180
|
+
: (typeof peerNode.listPeers === 'function'
|
|
181
|
+
? peerNode.listPeers({ status: 'connected' }).map((p) => p.fingerprint).filter(Boolean)
|
|
182
|
+
: [])
|
|
183
|
+
|
|
184
|
+
if (targets.length === 0) return new Map()
|
|
185
|
+
|
|
186
|
+
const requestId = nextRequestId()
|
|
187
|
+
const responses = new Map()
|
|
188
|
+
|
|
189
|
+
const promise = new Promise((resolve) => {
|
|
190
|
+
const timer = setTimeout(() => {
|
|
191
|
+
pendingWitnessRequests.delete(requestId)
|
|
192
|
+
if (responses.size < targets.length) {
|
|
193
|
+
ctx.emit('timestamp:witness-timeout', { requestId, expected: targets.length, received: responses.size })
|
|
194
|
+
}
|
|
195
|
+
resolve(responses)
|
|
196
|
+
}, witnessTimeoutMs)
|
|
197
|
+
pendingWitnessRequests.set(requestId, { resolve, timer, responses, expectedCount: targets.length })
|
|
198
|
+
})
|
|
199
|
+
|
|
200
|
+
await Promise.all(targets.map((pubKey) =>
|
|
201
|
+
ctx.sendTo(pubKey, envelopeType, { kind: 'time-request', requestId }).catch((err) => {
|
|
202
|
+
log('mesh-timestamp:request-send-failed', { to: pubKey, error: err?.message || String(err) })
|
|
203
|
+
}),
|
|
204
|
+
))
|
|
205
|
+
|
|
206
|
+
return promise
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const api = {
|
|
210
|
+
/**
|
|
211
|
+
* Collect real witness timestamps from connected peers (or
|
|
212
|
+
* `opts.peers`, if given), then produce a signed `TimestampProof`.
|
|
213
|
+
* @param {string} eventHash
|
|
214
|
+
* @param {object} [opts]
|
|
215
|
+
* @param {string[]} [opts.peers] - Explicit witness pubKeys. Defaults
|
|
216
|
+
* to every currently connected peer.
|
|
217
|
+
* @returns {Promise<import('./peer-timestamp.mjs').TimestampProof>}
|
|
218
|
+
*/
|
|
219
|
+
async stamp(eventHash, { peers } = {}) {
|
|
220
|
+
const peerTimestamps = await collectWitnesses(peers)
|
|
221
|
+
const proof = await authority.stamp(eventHash, peerTimestamps)
|
|
222
|
+
ctx.emit('timestamp:stamped', {
|
|
223
|
+
eventHash,
|
|
224
|
+
canonicalTimestamp: proof.canonicalTimestamp,
|
|
225
|
+
confidence: proof.confidence,
|
|
226
|
+
witnessCount: proof.witnesses.length,
|
|
227
|
+
})
|
|
228
|
+
return proof
|
|
229
|
+
},
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* @param {import('./peer-timestamp.mjs').TimestampProof} proof
|
|
233
|
+
* @returns {Promise<{valid: boolean, checked?: string, reason?: string}>}
|
|
234
|
+
*/
|
|
235
|
+
async verify(proof) {
|
|
236
|
+
const result = await authority.verify(proof)
|
|
237
|
+
ctx.emit('timestamp:verified', { eventHash: proof?.eventHash, valid: result.valid, checked: result.checked })
|
|
238
|
+
return result
|
|
239
|
+
},
|
|
240
|
+
|
|
241
|
+
/** @param {Map<string,number>} [peerTimestamps] @returns {number} */
|
|
242
|
+
getNetworkTime(peerTimestamps) {
|
|
243
|
+
return authority.getNetworkTime(peerTimestamps)
|
|
244
|
+
},
|
|
245
|
+
|
|
246
|
+
/** @param {number[]} values @returns {number} */
|
|
247
|
+
computeMedian: TimestampAuthority.computeMedian,
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
return {
|
|
251
|
+
api,
|
|
252
|
+
teardown() {
|
|
253
|
+
unsubscribe()
|
|
254
|
+
for (const pending of pendingWitnessRequests.values()) {
|
|
255
|
+
clearTimeout(pending.timer)
|
|
256
|
+
pending.resolve(pending.responses)
|
|
257
|
+
}
|
|
258
|
+
pendingWitnessRequests.clear()
|
|
259
|
+
},
|
|
260
|
+
}
|
|
261
|
+
},
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
export { DEFAULT_ENVELOPE_TYPE, DEFAULT_WITNESS_TIMEOUT_MS }
|