@johnhenry/browsermesh-apps 0.1.1 → 0.3.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 +443 -1
- package/package.json +18 -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 +799 -0
- package/src/compat.mjs +98 -0
- package/src/gpu-kernel.mjs +242 -0
- package/src/gpu.mjs +101 -7
- package/src/grant-log.mjs +840 -0
- package/src/index.mjs +32 -2
- package/src/kernel-mesh.mjs +56 -0
- 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 +1481 -0
- 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-relay-backend.mjs +289 -0
- package/src/mesh-relay-host.mjs +362 -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-sync.mjs +253 -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 +127 -19
- package/src/peer-registry.mjs +242 -18
- package/src/peer-routing.mjs +369 -5
- package/src/peer-terminal.mjs +400 -130
- package/src/signaling.mjs +231 -0
- package/src/webrtc-negotiator.mjs +209 -0
- package/src/peer-session.mjs +0 -937
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mesh-sync.mjs -- wires a `MeshSyncEngine` (`@johnhenry/browsermesh-sync`)
|
|
3
|
+
* to a `PeerNode`'s (this package) existing message-dispatch bus, so CRDT
|
|
4
|
+
* sync deltas travel over the real connection `PeerNode` already manages
|
|
5
|
+
* instead of a parallel message-passing path.
|
|
6
|
+
*
|
|
7
|
+
* Reuses `PeerNode`'s own envelope-routing convention rather than inventing
|
|
8
|
+
* a new one: outbound via `sendTo()` (accepts plain objects -- the
|
|
9
|
+
* underlying transport JSON-serializes them, see `WebRTCPeerConnection.send`),
|
|
10
|
+
* inbound via `onIncomingData()`, filtering by `envelope.type` (default
|
|
11
|
+
* `'mesh-sync'`) exactly the way `peer-node.mjs`'s own doc comments describe
|
|
12
|
+
* `ClawserPod.onMessage` routing "by `envelope.type`" -- multiple independent
|
|
13
|
+
* consumers of `onIncomingData()` can coexist on the same bus this way, each
|
|
14
|
+
* ignoring envelopes that aren't theirs.
|
|
15
|
+
*
|
|
16
|
+
* Persistence: `createMeshSync()` defaults to a real, durable
|
|
17
|
+
* `IndexedDBSyncStorage` (from `@johnhenry/browsermesh-sync`, Phase 1) --
|
|
18
|
+
* not the in-memory adapter -- because the whole point of that adapter
|
|
19
|
+
* existing is for a workspace's CRDT state to survive a reload. Pass
|
|
20
|
+
* `storage` explicitly to override (e.g. `InMemorySyncStorage` for a test
|
|
21
|
+
* that doesn't care about persistence).
|
|
22
|
+
*
|
|
23
|
+
* No browser-only imports at module level. (`IndexedDBSyncStorage` itself
|
|
24
|
+
* only touches the global `indexedDB` lazily, inside `open()`/`save()`/
|
|
25
|
+
* `load()`, not at construction time -- see storage-indexeddb.mjs.)
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
import { MeshSyncEngine, IndexedDBSyncStorage } from '@johnhenry/browsermesh-sync'
|
|
29
|
+
|
|
30
|
+
/** Default `envelope.type` used to route sync payloads on the shared `onIncomingData()` bus. */
|
|
31
|
+
const DEFAULT_ENVELOPE_TYPE = 'mesh-sync'
|
|
32
|
+
|
|
33
|
+
// ---------------------------------------------------------------------------
|
|
34
|
+
// MeshSyncBinding
|
|
35
|
+
// ---------------------------------------------------------------------------
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Binds a `MeshSyncEngine` to a `PeerNode`'s dispatch bus.
|
|
39
|
+
*
|
|
40
|
+
* Construction wires an `onIncomingData()` subscriber immediately (matching
|
|
41
|
+
* `MeshSignalingChannel`'s "subscribe in the constructor" convention).
|
|
42
|
+
* Outbound sends are explicit (`syncDocWithPeer()`) or driven by `watch()`.
|
|
43
|
+
*/
|
|
44
|
+
export class MeshSyncBinding {
|
|
45
|
+
/** @type {import('./peer-node.mjs').PeerNode} */
|
|
46
|
+
#node
|
|
47
|
+
|
|
48
|
+
/** @type {import('@johnhenry/browsermesh-sync').MeshSyncEngine} */
|
|
49
|
+
#engine
|
|
50
|
+
|
|
51
|
+
/** @type {string} */
|
|
52
|
+
#envelopeType
|
|
53
|
+
|
|
54
|
+
/** @type {Function} */
|
|
55
|
+
#onLog
|
|
56
|
+
|
|
57
|
+
/** @type {(() => void)|null} */
|
|
58
|
+
#unsubscribeIncoming = null
|
|
59
|
+
|
|
60
|
+
/** @type {Map<string, () => void>} docId -> unsubscribe from engine.subscribe() */
|
|
61
|
+
#watchers = new Map()
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* @param {object} opts
|
|
65
|
+
* @param {import('./peer-node.mjs').PeerNode} opts.node
|
|
66
|
+
* @param {import('@johnhenry/browsermesh-sync').MeshSyncEngine} opts.engine
|
|
67
|
+
* @param {string} [opts.envelopeType='mesh-sync']
|
|
68
|
+
* @param {Function} [opts.onLog]
|
|
69
|
+
*/
|
|
70
|
+
constructor({ node, engine, envelopeType, onLog } = {}) {
|
|
71
|
+
if (!node) throw new Error('node is required')
|
|
72
|
+
if (!engine) throw new Error('engine is required')
|
|
73
|
+
|
|
74
|
+
this.#node = node
|
|
75
|
+
this.#engine = engine
|
|
76
|
+
this.#envelopeType = envelopeType || DEFAULT_ENVELOPE_TYPE
|
|
77
|
+
this.#onLog = onLog || (() => {})
|
|
78
|
+
|
|
79
|
+
this.#unsubscribeIncoming = this.#node.onIncomingData((pubKey, data) => {
|
|
80
|
+
this.#handleIncoming(pubKey, data)
|
|
81
|
+
})
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The underlying `MeshSyncEngine`. */
|
|
85
|
+
get engine() {
|
|
86
|
+
return this.#engine
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The `envelope.type` this binding sends/routes on the shared dispatch bus. */
|
|
90
|
+
get envelopeType() {
|
|
91
|
+
return this.#envelopeType
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// -----------------------------------------------------------------------
|
|
95
|
+
// Outbound
|
|
96
|
+
// -----------------------------------------------------------------------
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Send a document's current full CRDT state to one peer. The remote side
|
|
100
|
+
* merges it in (creating the document locally first if it doesn't have it
|
|
101
|
+
* yet) -- safe to call repeatedly; CRDT merge is idempotent/commutative.
|
|
102
|
+
*
|
|
103
|
+
* @param {string} pubKey - Remote peer's fingerprint / public key hash
|
|
104
|
+
* @param {string} docId
|
|
105
|
+
* @returns {Promise<void>} Resolves once `node.sendTo()` accepts the send.
|
|
106
|
+
*/
|
|
107
|
+
async syncDocWithPeer(pubKey, docId) {
|
|
108
|
+
const doc = this.#engine.get(docId)
|
|
109
|
+
if (!doc) {
|
|
110
|
+
throw new Error(`MeshSyncBinding.syncDocWithPeer: unknown document '${docId}'`)
|
|
111
|
+
}
|
|
112
|
+
const payload = this.#engine.prepareSyncPayload(docId)
|
|
113
|
+
await this.#node.sendTo(pubKey, {
|
|
114
|
+
type: this.#envelopeType,
|
|
115
|
+
docId,
|
|
116
|
+
docType: doc.type,
|
|
117
|
+
payload,
|
|
118
|
+
})
|
|
119
|
+
this.#onLog('mesh-sync:sent', { to: pubKey, docId })
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Start auto-broadcasting a document's state to one or more peers
|
|
124
|
+
* whenever it changes locally (`engine.update()` or `engine.merge()`
|
|
125
|
+
* both notify subscribers). Overwrites any existing watch for the same
|
|
126
|
+
* `docId`.
|
|
127
|
+
*
|
|
128
|
+
* @param {string} docId
|
|
129
|
+
* @param {string|string[]} pubKeys - One peer, or several.
|
|
130
|
+
* @returns {() => void} Stops watching this document.
|
|
131
|
+
*/
|
|
132
|
+
watch(docId, pubKeys) {
|
|
133
|
+
this.unwatch(docId)
|
|
134
|
+
const targets = Array.isArray(pubKeys) ? pubKeys : [pubKeys]
|
|
135
|
+
|
|
136
|
+
const unsubscribe = this.#engine.subscribe(docId, () => {
|
|
137
|
+
for (const pubKey of targets) {
|
|
138
|
+
this.syncDocWithPeer(pubKey, docId).catch((err) => {
|
|
139
|
+
this.#onLog('mesh-sync:broadcast-failed', {
|
|
140
|
+
to: pubKey,
|
|
141
|
+
docId,
|
|
142
|
+
error: err?.message || String(err),
|
|
143
|
+
})
|
|
144
|
+
})
|
|
145
|
+
}
|
|
146
|
+
})
|
|
147
|
+
this.#watchers.set(docId, unsubscribe)
|
|
148
|
+
return () => this.unwatch(docId)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Stop auto-broadcasting a document previously passed to `watch()`.
|
|
153
|
+
* @param {string} docId
|
|
154
|
+
*/
|
|
155
|
+
unwatch(docId) {
|
|
156
|
+
const unsubscribe = this.#watchers.get(docId)
|
|
157
|
+
if (unsubscribe) {
|
|
158
|
+
unsubscribe()
|
|
159
|
+
this.#watchers.delete(docId)
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// -----------------------------------------------------------------------
|
|
164
|
+
// Inbound
|
|
165
|
+
// -----------------------------------------------------------------------
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* @param {string} pubKey
|
|
169
|
+
* @param {*} data
|
|
170
|
+
*/
|
|
171
|
+
#handleIncoming(pubKey, data) {
|
|
172
|
+
if (!data || typeof data !== 'object' || data.type !== this.#envelopeType) return
|
|
173
|
+
const { docId, docType, payload } = data
|
|
174
|
+
if (!docId || !payload) return
|
|
175
|
+
|
|
176
|
+
try {
|
|
177
|
+
if (!this.#engine.get(docId)) {
|
|
178
|
+
this.#engine.create(docId, docType, { owner: pubKey })
|
|
179
|
+
}
|
|
180
|
+
this.#engine.merge(docId, payload)
|
|
181
|
+
this.#onLog('mesh-sync:merged', { from: pubKey, docId })
|
|
182
|
+
} catch (err) {
|
|
183
|
+
this.#onLog('mesh-sync:merge-failed', { from: pubKey, docId, error: err?.message || String(err) })
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// -----------------------------------------------------------------------
|
|
188
|
+
// Persistence passthrough
|
|
189
|
+
// -----------------------------------------------------------------------
|
|
190
|
+
|
|
191
|
+
/** Persist all documents through the engine's configured storage adapter. */
|
|
192
|
+
async save() {
|
|
193
|
+
await this.#engine.save()
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Restore documents from the engine's configured storage adapter. */
|
|
197
|
+
async load() {
|
|
198
|
+
await this.#engine.load()
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// -----------------------------------------------------------------------
|
|
202
|
+
// Teardown
|
|
203
|
+
// -----------------------------------------------------------------------
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Detach from the `PeerNode` dispatch bus and stop all `watch()`es. Does
|
|
207
|
+
* not destroy the engine or its persisted data -- call `engine.destroy()`
|
|
208
|
+
* separately if desired.
|
|
209
|
+
*/
|
|
210
|
+
detach() {
|
|
211
|
+
for (const docId of [...this.#watchers.keys()]) this.unwatch(docId)
|
|
212
|
+
if (this.#unsubscribeIncoming) {
|
|
213
|
+
this.#unsubscribeIncoming()
|
|
214
|
+
this.#unsubscribeIncoming = null
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// ---------------------------------------------------------------------------
|
|
220
|
+
// createMeshSync
|
|
221
|
+
// ---------------------------------------------------------------------------
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Convenience factory: build a `MeshSyncEngine` -- defaulting to durable
|
|
225
|
+
* `IndexedDBSyncStorage`, not the in-memory adapter -- and wire it to
|
|
226
|
+
* `node` via `MeshSyncBinding`.
|
|
227
|
+
*
|
|
228
|
+
* @param {object} opts
|
|
229
|
+
* @param {import('./peer-node.mjs').PeerNode} opts.node
|
|
230
|
+
* @param {object} [opts.storage] - Storage adapter (`save`/`load`/`clear`).
|
|
231
|
+
* Defaults to `new IndexedDBSyncStorage({ dbName })`.
|
|
232
|
+
* @param {string} [opts.nodeId] - CRDT node identity for vector clocks.
|
|
233
|
+
* Defaults to `node.podId`.
|
|
234
|
+
* @param {string} [opts.dbName] - Passed to the default `IndexedDBSyncStorage`.
|
|
235
|
+
* Defaults to `mesh-sync-${node.podId}` so multiple mesh nodes in one
|
|
236
|
+
* process/browser don't collide. Ignored if `storage` is supplied.
|
|
237
|
+
* @param {string} [opts.envelopeType='mesh-sync']
|
|
238
|
+
* @param {Function} [opts.onLog]
|
|
239
|
+
* @returns {MeshSyncBinding}
|
|
240
|
+
*/
|
|
241
|
+
export function createMeshSync({ node, storage, nodeId, dbName, envelopeType, onLog } = {}) {
|
|
242
|
+
if (!node) throw new Error('node is required')
|
|
243
|
+
|
|
244
|
+
const engine = new MeshSyncEngine({
|
|
245
|
+
nodeId: nodeId || node.podId,
|
|
246
|
+
storage: storage || new IndexedDBSyncStorage({ dbName: dbName || `mesh-sync-${node.podId}` }),
|
|
247
|
+
onLog,
|
|
248
|
+
})
|
|
249
|
+
|
|
250
|
+
return new MeshSyncBinding({ node, engine, envelopeType, onLog })
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export { DEFAULT_ENVELOPE_TYPE }
|
|
@@ -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 }
|