@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
package/src/peer-files.mjs
CHANGED
|
@@ -1,17 +1,88 @@
|
|
|
1
1
|
/**
|
|
2
|
-
|
|
3
|
-
* clawser-peer-files.js -- Remote file access over peer sessions.
|
|
2
|
+
* peer-files.mjs -- Remote file access over the mesh.
|
|
4
3
|
*
|
|
5
4
|
* Provides browsing, reading, writing, and deleting files on a remote
|
|
6
|
-
* peer's OPFS through FileHost (serves local filesystem) and FileClient
|
|
7
|
-
* (sends requests and awaits results). Built
|
|
8
|
-
* service
|
|
5
|
+
* peer's OPFS through `FileHost` (serves local filesystem) and `FileClient`
|
|
6
|
+
* (sends requests and awaits results). Built as a `MeshService`
|
|
7
|
+
* (`mesh-service.mjs`, the same `attach(peerNode, ctx) -> {teardown, api}`
|
|
8
|
+
* convention `mesh-rpc.mjs`/`chunk-replication.mjs`/`grant-log.mjs` etc.
|
|
9
|
+
* already use), NOT on top of `peer-session.mjs`'s `PeerSession`/
|
|
10
|
+
* `SessionManager` -- see "Migration history" below.
|
|
9
11
|
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
+
* Kept deliberately, NOT retired despite overlapping with `cloud-storage.mjs`
|
|
13
|
+
* (`CloudStorage`): this is a lighter-weight, unencrypted, non-replicated
|
|
14
|
+
* direct-access option (one `sendTo()` round trip to one specific peer's raw
|
|
15
|
+
* `fs`), not a replacement for CloudStorage's encrypted, manifest-tracked,
|
|
16
|
+
* multi-replica object store. See issue #84/#117-124's triage table for the
|
|
17
|
+
* full per-module decision record.
|
|
18
|
+
*
|
|
19
|
+
* ---------------------------------------------------------------------------
|
|
20
|
+
* Migration history (issue #84, Phase 8 of the app-layer migration plan):
|
|
21
|
+
*
|
|
22
|
+
* This file used to depend on `peer-session.mjs`'s `PeerSession` --
|
|
23
|
+
* `FileHost`/`FileClient` each called `session.registerHandler('files', ...)`
|
|
24
|
+
* in their constructor and `session.send()`/`session.requireCapability()`/
|
|
25
|
+
* `session.remotePodId` from inside their request/response handling. Nothing
|
|
26
|
+
* in this repo ever constructed a live `PeerSession` (`SessionManager` is
|
|
27
|
+
* never instantiated outside its own tests) -- `PeerSession`'s two
|
|
28
|
+
* cross-cutting value-adds (heartbeat, audit logging) are also independently
|
|
29
|
+
* covered by `mesh-keepalive.mjs` (issue #110) and `PeerNode`'s own
|
|
30
|
+
* `#audit()` (issue #85) -- so this migration removes the `PeerSession`
|
|
31
|
+
* dependency entirely rather than bridging it.
|
|
32
|
+
*
|
|
33
|
+
* `FileHost#handleRequest()`/`FileClient`'s `switch(action)`
|
|
34
|
+
* dispatch/`#fs` calls are UNCHANGED from the `PeerSession`-era version --
|
|
35
|
+
* only the transport/correlation plumbing changed:
|
|
36
|
+
* - `FileHost` no longer owns "who do I reply to" (a `PeerSession` bound
|
|
37
|
+
* to exactly one remote peer) -- `handleRequest(fromPubKey, payload)` is
|
|
38
|
+
* now a pure function that COMPUTES and RETURNS a response; the caller
|
|
39
|
+
* (`createFileShareService()`'s `attach()`, below) sends it via
|
|
40
|
+
* `ctx.sendTo()`. This is a real, necessary shape change (a `MeshService`
|
|
41
|
+
* is attached once per NODE and can be asked for files by any connected
|
|
42
|
+
* peer, not once per peer-pair the way a `PeerSession` was), not a
|
|
43
|
+
* rewrite of the request-handling logic itself.
|
|
44
|
+
* - `FileHost`'s capability check (`session.requireCapability(scope)`,
|
|
45
|
+
* which threw against a static per-session capability list) is now
|
|
46
|
+
* `ctx.registry.checkAccess(fromPubKey, 'files', action)` -- live,
|
|
47
|
+
* per-request, per-sender ACL/capability-token checking via
|
|
48
|
+
* `PeerRegistry` (`peer-registry.mjs`), the same mechanism every other
|
|
49
|
+
* `MeshService` in this family already uses (see e.g.
|
|
50
|
+
* `chunk-replication.mjs`, `manifest-sync.mjs`, `mesh-kv.mjs`).
|
|
51
|
+
* `FILE_CAPABILITIES` moved from `fs:read`/`fs:write`/`fs:delete` to
|
|
52
|
+
* `files:read`/`files:write`/`files:delete` to align with
|
|
53
|
+
* `@johnhenry/browsermesh-core`'s `acl.mjs` `DEFAULT_TEMPLATES` (`guest`/
|
|
54
|
+
* `collaborator` already grant `files:read`/`files:write` -- this was
|
|
55
|
+
* the family's own established scope vocabulary for this resource, the
|
|
56
|
+
* module just wasn't using it yet).
|
|
57
|
+
* - `FileClient` no longer wraps one `PeerSession` bound to one remote
|
|
58
|
+
* peer -- its public methods (`listFiles`/`readFile`/`writeFile`/
|
|
59
|
+
* `deleteFile`/`stat`) now take a leading `pubKey` argument, since one
|
|
60
|
+
* `FileClient` (like `mesh-rpc.mjs`'s `request()`) can request files
|
|
61
|
+
* from ANY connected peer, not just one fixed session. Internally it
|
|
62
|
+
* still does exactly what it did before: generate a `requestId`, track
|
|
63
|
+
* a `{resolve, reject, timer}` in a pending-requests map, and correlate
|
|
64
|
+
* the eventual response by that id -- this was ALREADY a self-contained
|
|
65
|
+
* `requestId`-based correlation mechanism (not something `PeerSession`
|
|
66
|
+
* provided), so no new correlation primitive had to be invented; it's
|
|
67
|
+
* the exact same shape `mesh-rpc.mjs`'s `request()`/`pendingRequests`
|
|
68
|
+
* uses, applied here too. The one addition: each pending entry also
|
|
69
|
+
* records the `pubKey` the request targeted, and `handleResponse()`
|
|
70
|
+
* ignores a reply from any OTHER peer even if it happens to guess/replay
|
|
71
|
+
* a `requestId` -- a property the old design got "for free" (a
|
|
72
|
+
* `PeerSession`'s transport only ever delivered messages from the one
|
|
73
|
+
* peer it was bound to) that a shared, node-wide `onIncomingData()`
|
|
74
|
+
* subscription does not.
|
|
75
|
+
*
|
|
76
|
+
* `createFileShareService()` is ONE `MeshService` covering both directions
|
|
77
|
+
* (hosting files to others, and requesting files from others), not two --
|
|
78
|
+
* both share the same `files-request`/`files-response` envelope-type pair
|
|
79
|
+
* and the same `ctx.onIncomingData()` subscription, so splitting them would
|
|
80
|
+
* only duplicate that wiring for no isolation benefit (a node that only
|
|
81
|
+
* wants to be a client passes no `fs`, and `FileHost` is simply never
|
|
82
|
+
* constructed -- see `attach()` below).
|
|
12
83
|
*
|
|
13
84
|
* Run tests:
|
|
14
|
-
* node --import ./
|
|
85
|
+
* node --import ./test/_setup-globals.mjs --test test/peer-files.test.mjs
|
|
15
86
|
*/
|
|
16
87
|
|
|
17
88
|
// ---------------------------------------------------------------------------
|
|
@@ -31,22 +102,40 @@ export const FILE_ACTIONS = Object.freeze({
|
|
|
31
102
|
STAT: 'stat',
|
|
32
103
|
})
|
|
33
104
|
|
|
105
|
+
/** `ctx.registry.checkAccess()` resource name used for every file operation (see module doc comment's "Migration history"). */
|
|
106
|
+
export const FILE_RESOURCE = 'files'
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Capability scope strings, `files:read`/`files:write`/`files:delete` --
|
|
110
|
+
* matches `@johnhenry/browsermesh-core`'s `acl.mjs` `DEFAULT_TEMPLATES`
|
|
111
|
+
* vocabulary (`guest`/`collaborator` already grant `files:read`/
|
|
112
|
+
* `files:write`). Kept for documentation/back-compat; the actual check is
|
|
113
|
+
* `ctx.registry.checkAccess(fromPubKey, FILE_RESOURCE, action)` (see
|
|
114
|
+
* `ACTION_CAP_ACTION` below), not a direct comparison against these strings.
|
|
115
|
+
*/
|
|
34
116
|
export const FILE_CAPABILITIES = Object.freeze({
|
|
35
|
-
READ: '
|
|
36
|
-
WRITE: '
|
|
37
|
-
DELETE: '
|
|
117
|
+
READ: 'files:read',
|
|
118
|
+
WRITE: 'files:write',
|
|
119
|
+
DELETE: 'files:delete',
|
|
38
120
|
})
|
|
39
121
|
|
|
122
|
+
/** Default `envelope.type` for a file-operation request, on the shared `ctx.onIncomingData()` bus. */
|
|
123
|
+
const DEFAULT_REQUEST_ENVELOPE_TYPE = 'files-request'
|
|
124
|
+
/** Default `envelope.type` for a file-operation response. */
|
|
125
|
+
const DEFAULT_RESPONSE_ENVELOPE_TYPE = 'files-response'
|
|
126
|
+
|
|
40
127
|
// ---------------------------------------------------------------------------
|
|
41
|
-
// Internal
|
|
128
|
+
// Internal -- map a file action to the capability ACTION (not the full
|
|
129
|
+
// scope) `ctx.registry.checkAccess(fromPubKey, FILE_RESOURCE, action)`
|
|
130
|
+
// expects as its third argument.
|
|
42
131
|
// ---------------------------------------------------------------------------
|
|
43
132
|
|
|
44
|
-
const
|
|
45
|
-
[FILE_ACTIONS.LIST]:
|
|
46
|
-
[FILE_ACTIONS.READ]:
|
|
47
|
-
[FILE_ACTIONS.STAT]:
|
|
48
|
-
[FILE_ACTIONS.WRITE]:
|
|
49
|
-
[FILE_ACTIONS.DELETE]:
|
|
133
|
+
const ACTION_CAP_ACTION = Object.freeze({
|
|
134
|
+
[FILE_ACTIONS.LIST]: 'read',
|
|
135
|
+
[FILE_ACTIONS.READ]: 'read',
|
|
136
|
+
[FILE_ACTIONS.STAT]: 'read',
|
|
137
|
+
[FILE_ACTIONS.WRITE]: 'write',
|
|
138
|
+
[FILE_ACTIONS.DELETE]: 'delete',
|
|
50
139
|
})
|
|
51
140
|
|
|
52
141
|
// ---------------------------------------------------------------------------
|
|
@@ -56,15 +145,12 @@ const ACTION_CAPABILITY = Object.freeze({
|
|
|
56
145
|
/**
|
|
57
146
|
* Serves file operations from the local filesystem to remote peers.
|
|
58
147
|
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
*
|
|
148
|
+
* Framework-agnostic: `handleRequest()` is a pure function that computes and
|
|
149
|
+
* RETURNS a response, it does not send anything itself -- see module doc
|
|
150
|
+
* comment's "Migration history". `createFileShareService()` (below) is what
|
|
151
|
+
* actually wires this to `ctx.onIncomingData()`/`ctx.sendTo()`.
|
|
63
152
|
*/
|
|
64
153
|
export class FileHost {
|
|
65
|
-
/** @type {object} PeerSession */
|
|
66
|
-
#session
|
|
67
|
-
|
|
68
154
|
/**
|
|
69
155
|
* @type {object} File system interface (duck-typed)
|
|
70
156
|
* async list(path) -> { name, type, size }[]
|
|
@@ -81,91 +167,97 @@ export class FileHost {
|
|
|
81
167
|
/** @type {Function} */
|
|
82
168
|
#onLog
|
|
83
169
|
|
|
170
|
+
/** @type {(fromPubKey: string, action: string) => ({allowed: boolean, reason?: string})} */
|
|
171
|
+
#checkAccess
|
|
172
|
+
|
|
84
173
|
/**
|
|
85
174
|
* @param {object} opts
|
|
86
|
-
* @param {object} opts.session - PeerSession instance
|
|
87
175
|
* @param {object} opts.fs - File system interface with list/read/write/delete/stat
|
|
88
176
|
* @param {number} [opts.maxFileSize=10485760] - Maximum file size for writes (bytes)
|
|
89
177
|
* @param {Function} [opts.onLog] - Logging callback
|
|
178
|
+
* @param {(fromPubKey: string, action: string) => ({allowed: boolean, reason?: string})} [opts.checkAccess]
|
|
179
|
+
* Capability check for a given requester + capability action
|
|
180
|
+
* (`'read'`/`'write'`/`'delete'`, i.e. `ACTION_CAP_ACTION`'s values, NOT
|
|
181
|
+
* a full `resource:action` scope string). `createFileShareService()`
|
|
182
|
+
* supplies `(fromPubKey, action) => ctx.registry.checkAccess(fromPubKey, FILE_RESOURCE, action)`.
|
|
183
|
+
* Defaults to permissive (`{ allowed: true }` for everyone) when
|
|
184
|
+
* constructed directly without one -- a `FileHost` built by hand (e.g. in
|
|
185
|
+
* a unit test) has no registry of its own to consult; supplying real
|
|
186
|
+
* gating is the caller's responsibility, exactly like
|
|
187
|
+
* `cloud-storage.mjs`/`chunk-replication.mjs` require a real `registry`
|
|
188
|
+
* at their own composition root.
|
|
90
189
|
*/
|
|
91
|
-
constructor({
|
|
92
|
-
if (!session) {
|
|
93
|
-
throw new Error('session is required')
|
|
94
|
-
}
|
|
190
|
+
constructor({ fs, maxFileSize, onLog, checkAccess }) {
|
|
95
191
|
if (!fs || typeof fs.list !== 'function' || typeof fs.read !== 'function') {
|
|
96
192
|
throw new Error('fs with list() and read() methods is required')
|
|
97
193
|
}
|
|
98
194
|
|
|
99
|
-
this.#session = session
|
|
100
195
|
this.#fs = fs
|
|
101
196
|
this.#maxFileSize = maxFileSize ?? FILE_DEFAULTS.maxFileSize
|
|
102
197
|
this.#onLog = onLog || (() => {})
|
|
103
|
-
|
|
104
|
-
// Register handler on session for 'files' service type
|
|
105
|
-
this.#session.registerHandler('files', (envelope) => this.#handleRequest(envelope))
|
|
198
|
+
this.#checkAccess = typeof checkAccess === 'function' ? checkAccess : () => ({ allowed: true })
|
|
106
199
|
}
|
|
107
200
|
|
|
108
|
-
// -- Request handling
|
|
201
|
+
// -- Request handling -------------------------------------------------------
|
|
109
202
|
|
|
110
203
|
/**
|
|
111
|
-
* Handle an incoming file operation request
|
|
204
|
+
* Handle an incoming file operation request from `fromPubKey`.
|
|
112
205
|
*
|
|
113
206
|
* 1. Validates the action and path
|
|
114
|
-
* 2. Checks the required capability
|
|
207
|
+
* 2. Checks the required capability via the injected `checkAccess`
|
|
115
208
|
* 3. Dispatches to the appropriate fs method
|
|
116
209
|
* 4. Enforces maxFileSize on writes
|
|
117
|
-
* 5.
|
|
210
|
+
* 5. Returns the response (does NOT send it -- see class doc comment)
|
|
118
211
|
*
|
|
119
|
-
* @param {
|
|
212
|
+
* @param {string} fromPubKey - Requesting peer's public key
|
|
213
|
+
* @param {object} payload - `{ action, path, data?, requestId }`
|
|
214
|
+
* @returns {Promise<{requestId: string|null, action: string|null, success: boolean, result?: *, error?: string}>}
|
|
120
215
|
*/
|
|
121
|
-
async
|
|
122
|
-
const
|
|
123
|
-
const { action, path, data, requestId } = payload
|
|
216
|
+
async handleRequest(fromPubKey, payload) {
|
|
217
|
+
const { action, path, data, requestId } = payload || {}
|
|
124
218
|
|
|
125
|
-
// Build base response
|
|
126
219
|
const response = {
|
|
127
220
|
requestId: requestId || null,
|
|
128
221
|
action: action || null,
|
|
129
222
|
success: false,
|
|
130
223
|
}
|
|
131
224
|
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
return
|
|
138
|
-
}
|
|
225
|
+
// 1. Validate action
|
|
226
|
+
if (!action || !Object.values(FILE_ACTIONS).includes(action)) {
|
|
227
|
+
response.error = `Unknown action: ${action}`
|
|
228
|
+
return response
|
|
229
|
+
}
|
|
139
230
|
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
}
|
|
231
|
+
// 2. Validate path
|
|
232
|
+
if (!path || typeof path !== 'string') {
|
|
233
|
+
response.error = 'path must be a non-empty string'
|
|
234
|
+
return response
|
|
235
|
+
}
|
|
146
236
|
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
237
|
+
// 3. Check capability
|
|
238
|
+
const capAction = ACTION_CAP_ACTION[action]
|
|
239
|
+
if (capAction) {
|
|
240
|
+
const { allowed, reason } = this.#checkAccess(fromPubKey, capAction) || {}
|
|
241
|
+
if (!allowed) {
|
|
242
|
+
response.error = `Capability "${FILE_RESOURCE}:${capAction}" not granted for ${fromPubKey}${reason ? ` (${reason})` : ''}`
|
|
243
|
+
return response
|
|
151
244
|
}
|
|
245
|
+
}
|
|
152
246
|
|
|
247
|
+
try {
|
|
153
248
|
// 4. Dispatch to the appropriate fs method
|
|
154
|
-
let result
|
|
155
249
|
switch (action) {
|
|
156
250
|
case FILE_ACTIONS.LIST: {
|
|
157
|
-
this.#onLog(2, `File list request from ${
|
|
158
|
-
result = await this.#fs.list(path)
|
|
251
|
+
this.#onLog(2, `File list request from ${fromPubKey}: ${path}`)
|
|
252
|
+
response.result = await this.#fs.list(path)
|
|
159
253
|
response.success = true
|
|
160
|
-
response.result = result
|
|
161
254
|
break
|
|
162
255
|
}
|
|
163
256
|
|
|
164
257
|
case FILE_ACTIONS.READ: {
|
|
165
|
-
this.#onLog(2, `File read request from ${
|
|
166
|
-
result = await this.#fs.read(path)
|
|
258
|
+
this.#onLog(2, `File read request from ${fromPubKey}: ${path}`)
|
|
259
|
+
response.result = await this.#fs.read(path)
|
|
167
260
|
response.success = true
|
|
168
|
-
response.result = result
|
|
169
261
|
break
|
|
170
262
|
}
|
|
171
263
|
|
|
@@ -173,8 +265,7 @@ export class FileHost {
|
|
|
173
265
|
// Reject null/undefined data
|
|
174
266
|
if (data == null) {
|
|
175
267
|
response.error = 'Write data is required'
|
|
176
|
-
|
|
177
|
-
return
|
|
268
|
+
return response
|
|
178
269
|
}
|
|
179
270
|
|
|
180
271
|
// Enforce maxFileSize
|
|
@@ -183,30 +274,28 @@ export class FileHost {
|
|
|
183
274
|
: (data.byteLength ?? data.length ?? 0)
|
|
184
275
|
if (size > this.#maxFileSize) {
|
|
185
276
|
response.error = `File size ${size} exceeds maximum ${this.#maxFileSize} bytes`
|
|
186
|
-
|
|
187
|
-
return
|
|
277
|
+
return response
|
|
188
278
|
}
|
|
189
279
|
|
|
190
|
-
this.#onLog(2, `File write request from ${
|
|
191
|
-
result = await this.#fs.write(path, data)
|
|
192
|
-
response.success = result.success !== false
|
|
280
|
+
this.#onLog(2, `File write request from ${fromPubKey}: ${path}`)
|
|
281
|
+
const result = await this.#fs.write(path, data)
|
|
193
282
|
response.result = result
|
|
283
|
+
response.success = result.success !== false
|
|
194
284
|
break
|
|
195
285
|
}
|
|
196
286
|
|
|
197
287
|
case FILE_ACTIONS.DELETE: {
|
|
198
|
-
this.#onLog(2, `File delete request from ${
|
|
199
|
-
result = await this.#fs.delete(path)
|
|
200
|
-
response.success = result.success !== false
|
|
288
|
+
this.#onLog(2, `File delete request from ${fromPubKey}: ${path}`)
|
|
289
|
+
const result = await this.#fs.delete(path)
|
|
201
290
|
response.result = result
|
|
291
|
+
response.success = result.success !== false
|
|
202
292
|
break
|
|
203
293
|
}
|
|
204
294
|
|
|
205
295
|
case FILE_ACTIONS.STAT: {
|
|
206
|
-
this.#onLog(2, `File stat request from ${
|
|
207
|
-
result = await this.#fs.stat(path)
|
|
296
|
+
this.#onLog(2, `File stat request from ${fromPubKey}: ${path}`)
|
|
297
|
+
response.result = await this.#fs.stat(path)
|
|
208
298
|
response.success = true
|
|
209
|
-
response.result = result
|
|
210
299
|
break
|
|
211
300
|
}
|
|
212
301
|
}
|
|
@@ -215,31 +304,14 @@ export class FileHost {
|
|
|
215
304
|
this.#onLog(0, `File operation error (${action}): ${err.message}`)
|
|
216
305
|
}
|
|
217
306
|
|
|
218
|
-
|
|
219
|
-
this.#session.send('files', response)
|
|
307
|
+
return response
|
|
220
308
|
}
|
|
221
309
|
|
|
222
|
-
// --
|
|
223
|
-
|
|
224
|
-
/**
|
|
225
|
-
* Close the file host. Removes the handler from the session.
|
|
226
|
-
*/
|
|
227
|
-
close() {
|
|
228
|
-
this.#session.removeHandler('files')
|
|
229
|
-
}
|
|
310
|
+
// -- Serialization ------------------------------------------------------
|
|
230
311
|
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
/**
|
|
234
|
-
* Serialize to a JSON-safe object.
|
|
235
|
-
*
|
|
236
|
-
* @returns {object}
|
|
237
|
-
*/
|
|
312
|
+
/** @returns {object} */
|
|
238
313
|
toJSON() {
|
|
239
314
|
return {
|
|
240
|
-
sessionId: this.#session.sessionId,
|
|
241
|
-
localPodId: this.#session.localPodId,
|
|
242
|
-
remotePodId: this.#session.remotePodId,
|
|
243
315
|
maxFileSize: this.#maxFileSize,
|
|
244
316
|
}
|
|
245
317
|
}
|
|
@@ -250,17 +322,24 @@ export class FileHost {
|
|
|
250
322
|
// ---------------------------------------------------------------------------
|
|
251
323
|
|
|
252
324
|
/**
|
|
253
|
-
* Client-side interface for accessing
|
|
325
|
+
* Client-side interface for accessing remote peers' files.
|
|
254
326
|
*
|
|
255
|
-
*
|
|
256
|
-
*
|
|
257
|
-
*
|
|
327
|
+
* One `FileClient` can request files from ANY connected peer (not bound to
|
|
328
|
+
* a single remote peer the way the `PeerSession`-era version was) -- every
|
|
329
|
+
* public method takes a leading `pubKey` argument. Requests are correlated
|
|
330
|
+
* to their responses by a generated `requestId`, exactly like the
|
|
331
|
+
* `PeerSession`-era version already did (see module doc comment's
|
|
332
|
+
* "Migration history"); the only addition is also recording which `pubKey`
|
|
333
|
+
* a request targeted, so a response claiming a stale/guessed `requestId`
|
|
334
|
+
* from the WRONG peer is ignored rather than resolving/rejecting the wrong
|
|
335
|
+
* promise -- a property a per-peer `PeerSession` transport provided for
|
|
336
|
+
* free that a shared, node-wide subscription does not.
|
|
258
337
|
*/
|
|
259
338
|
export class FileClient {
|
|
260
|
-
/** @type {object}
|
|
261
|
-
#
|
|
339
|
+
/** @type {(pubKey: string, payload: object) => Promise<void>} */
|
|
340
|
+
#sendRequest
|
|
262
341
|
|
|
263
|
-
/** @type {Map<string, { resolve: Function, reject: Function, timer:
|
|
342
|
+
/** @type {Map<string, { resolve: Function, reject: Function, timer: *, pubKey: string }>} */
|
|
264
343
|
#pendingRequests = new Map()
|
|
265
344
|
|
|
266
345
|
/** @type {number} default timeout in ms */
|
|
@@ -271,96 +350,100 @@ export class FileClient {
|
|
|
271
350
|
|
|
272
351
|
/**
|
|
273
352
|
* @param {object} opts
|
|
274
|
-
* @param {object} opts.
|
|
353
|
+
* @param {(pubKey: string, payload: object) => Promise<void>} opts.sendRequest
|
|
354
|
+
* Sends a `files-request`-shaped payload to `pubKey`. `createFileShareService()`
|
|
355
|
+
* supplies `(pubKey, payload) => ctx.sendTo(pubKey, 'files-request', payload)`.
|
|
275
356
|
* @param {number} [opts.timeout=30000] - Default timeout for requests in ms
|
|
276
357
|
* @param {Function} [opts.onLog] - Logging callback
|
|
277
358
|
*/
|
|
278
|
-
constructor({
|
|
279
|
-
if (
|
|
280
|
-
throw new Error('
|
|
359
|
+
constructor({ sendRequest, timeout, onLog }) {
|
|
360
|
+
if (typeof sendRequest !== 'function') {
|
|
361
|
+
throw new Error('sendRequest function is required')
|
|
281
362
|
}
|
|
282
363
|
|
|
283
|
-
this.#
|
|
364
|
+
this.#sendRequest = sendRequest
|
|
284
365
|
this.#timeout = timeout ?? FILE_DEFAULTS.timeout
|
|
285
366
|
this.#onLog = onLog || (() => {})
|
|
286
|
-
|
|
287
|
-
// Register handler on session for 'files' response messages
|
|
288
|
-
this.#session.registerHandler('files', (envelope) => this.#handleResponse(envelope))
|
|
289
367
|
}
|
|
290
368
|
|
|
291
369
|
// -- File operations ------------------------------------------------------
|
|
292
370
|
|
|
293
371
|
/**
|
|
294
|
-
* List files at a path on
|
|
372
|
+
* List files at a path on a remote peer.
|
|
295
373
|
*
|
|
374
|
+
* @param {string} pubKey - Remote peer to query
|
|
296
375
|
* @param {string} path - Directory path to list
|
|
297
376
|
* @returns {Promise<{ name: string, type: string, size: number }[]>}
|
|
298
377
|
*/
|
|
299
|
-
async listFiles(path) {
|
|
300
|
-
const response = await this.#request(FILE_ACTIONS.LIST, path)
|
|
378
|
+
async listFiles(pubKey, path) {
|
|
379
|
+
const response = await this.#request(pubKey, FILE_ACTIONS.LIST, path)
|
|
301
380
|
return response.result
|
|
302
381
|
}
|
|
303
382
|
|
|
304
383
|
/**
|
|
305
|
-
* Read a file from
|
|
384
|
+
* Read a file from a remote peer.
|
|
306
385
|
*
|
|
386
|
+
* @param {string} pubKey - Remote peer to query
|
|
307
387
|
* @param {string} path - File path to read
|
|
308
388
|
* @returns {Promise<{ data: string|Uint8Array, size: number }>}
|
|
309
389
|
*/
|
|
310
|
-
async readFile(path) {
|
|
311
|
-
const response = await this.#request(FILE_ACTIONS.READ, path)
|
|
390
|
+
async readFile(pubKey, path) {
|
|
391
|
+
const response = await this.#request(pubKey, FILE_ACTIONS.READ, path)
|
|
312
392
|
return response.result
|
|
313
393
|
}
|
|
314
394
|
|
|
315
395
|
/**
|
|
316
|
-
* Write data to a file on
|
|
396
|
+
* Write data to a file on a remote peer.
|
|
317
397
|
*
|
|
398
|
+
* @param {string} pubKey - Remote peer to write to
|
|
318
399
|
* @param {string} path - File path to write
|
|
319
400
|
* @param {string|Uint8Array} data - File content to write
|
|
320
401
|
* @returns {Promise<{ success: boolean, size: number }>}
|
|
321
402
|
*/
|
|
322
|
-
async writeFile(path, data) {
|
|
323
|
-
const response = await this.#request(FILE_ACTIONS.WRITE, path, data)
|
|
403
|
+
async writeFile(pubKey, path, data) {
|
|
404
|
+
const response = await this.#request(pubKey, FILE_ACTIONS.WRITE, path, data)
|
|
324
405
|
return response.result
|
|
325
406
|
}
|
|
326
407
|
|
|
327
408
|
/**
|
|
328
|
-
* Delete a file on
|
|
409
|
+
* Delete a file on a remote peer.
|
|
329
410
|
*
|
|
411
|
+
* @param {string} pubKey - Remote peer to delete on
|
|
330
412
|
* @param {string} path - File path to delete
|
|
331
413
|
* @returns {Promise<{ success: boolean }>}
|
|
332
414
|
*/
|
|
333
|
-
async deleteFile(path) {
|
|
334
|
-
const response = await this.#request(FILE_ACTIONS.DELETE, path)
|
|
415
|
+
async deleteFile(pubKey, path) {
|
|
416
|
+
const response = await this.#request(pubKey, FILE_ACTIONS.DELETE, path)
|
|
335
417
|
return response.result
|
|
336
418
|
}
|
|
337
419
|
|
|
338
420
|
/**
|
|
339
|
-
* Get file metadata from
|
|
421
|
+
* Get file metadata from a remote peer.
|
|
340
422
|
*
|
|
423
|
+
* @param {string} pubKey - Remote peer to query
|
|
341
424
|
* @param {string} path - File path to stat
|
|
342
425
|
* @returns {Promise<{ name: string, type: string, size: number, modified: number }|null>}
|
|
343
426
|
*/
|
|
344
|
-
async stat(path) {
|
|
345
|
-
const response = await this.#request(FILE_ACTIONS.STAT, path)
|
|
427
|
+
async stat(pubKey, path) {
|
|
428
|
+
const response = await this.#request(pubKey, FILE_ACTIONS.STAT, path)
|
|
346
429
|
return response.result
|
|
347
430
|
}
|
|
348
431
|
|
|
349
432
|
// -- Internal request handling --------------------------------------------
|
|
350
433
|
|
|
351
434
|
/**
|
|
352
|
-
* Send a file operation request and wait for the matching response.
|
|
353
|
-
*
|
|
354
|
-
* Creates a unique requestId, sends the request via the session,
|
|
355
|
-
* and returns a promise that resolves when the response arrives
|
|
356
|
-
* or rejects on timeout.
|
|
435
|
+
* Send a file operation request to `pubKey` and wait for the matching response.
|
|
357
436
|
*
|
|
437
|
+
* @param {string} pubKey - Target peer
|
|
358
438
|
* @param {string} action - File action (list, read, write, delete, stat)
|
|
359
439
|
* @param {string} path - File path
|
|
360
440
|
* @param {*} [data] - Optional data payload (for write)
|
|
361
441
|
* @returns {Promise<{ requestId, action, success, result?, error? }>}
|
|
362
442
|
*/
|
|
363
|
-
async #request(action, path, data) {
|
|
443
|
+
async #request(pubKey, action, path, data) {
|
|
444
|
+
if (!pubKey || typeof pubKey !== 'string') {
|
|
445
|
+
throw new Error('pubKey must be a non-empty string')
|
|
446
|
+
}
|
|
364
447
|
if (!path || typeof path !== 'string') {
|
|
365
448
|
throw new Error('path must be a non-empty string')
|
|
366
449
|
}
|
|
@@ -381,7 +464,7 @@ export class FileClient {
|
|
|
381
464
|
}, timeoutMs)
|
|
382
465
|
|
|
383
466
|
// Register pending request
|
|
384
|
-
this.#pendingRequests.set(requestId, { resolve, reject, timer })
|
|
467
|
+
this.#pendingRequests.set(requestId, { resolve, reject, timer, pubKey })
|
|
385
468
|
|
|
386
469
|
// Build and send request payload
|
|
387
470
|
const payload = { action, path, requestId }
|
|
@@ -389,34 +472,40 @@ export class FileClient {
|
|
|
389
472
|
payload.data = data
|
|
390
473
|
}
|
|
391
474
|
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
475
|
+
Promise.resolve(this.#sendRequest(pubKey, payload))
|
|
476
|
+
.then(() => {
|
|
477
|
+
this.#onLog(2, `Sent file ${action} request to ${pubKey}: ${path}`)
|
|
478
|
+
})
|
|
479
|
+
.catch((err) => {
|
|
480
|
+
clearTimeout(timer)
|
|
481
|
+
this.#pendingRequests.delete(requestId)
|
|
482
|
+
reject(err)
|
|
483
|
+
})
|
|
400
484
|
})
|
|
401
485
|
}
|
|
402
486
|
|
|
403
|
-
// -- Response handling
|
|
487
|
+
// -- Response handling ------------------------------------------------------
|
|
404
488
|
|
|
405
489
|
/**
|
|
406
|
-
* Handle an incoming file response
|
|
407
|
-
*
|
|
490
|
+
* Handle an incoming file response. Matches by requestId (AND the peer it
|
|
491
|
+
* was sent to -- see class doc comment) and resolves or rejects the
|
|
492
|
+
* pending promise.
|
|
408
493
|
*
|
|
409
|
-
* @param {
|
|
494
|
+
* @param {string} fromPubKey - Peer the response actually arrived from
|
|
495
|
+
* @param {object} payload - `{ requestId, action, success, result?, error? }`
|
|
410
496
|
*/
|
|
411
|
-
|
|
412
|
-
const
|
|
413
|
-
const { requestId } = payload
|
|
414
|
-
|
|
497
|
+
handleResponse(fromPubKey, payload) {
|
|
498
|
+
const { requestId } = payload || {}
|
|
415
499
|
if (!requestId) return
|
|
416
500
|
|
|
417
501
|
const pending = this.#pendingRequests.get(requestId)
|
|
418
502
|
if (!pending) return
|
|
419
503
|
|
|
504
|
+
// A response claiming this requestId but arriving from a different peer
|
|
505
|
+
// than the one it was sent to is never valid -- ignore it rather than
|
|
506
|
+
// resolving/rejecting the wrong caller's promise (see class doc comment).
|
|
507
|
+
if (pending.pubKey !== fromPubKey) return
|
|
508
|
+
|
|
420
509
|
// Clean up
|
|
421
510
|
clearTimeout(pending.timer)
|
|
422
511
|
this.#pendingRequests.delete(requestId)
|
|
@@ -436,35 +525,140 @@ export class FileClient {
|
|
|
436
525
|
// -- Lifecycle ------------------------------------------------------------
|
|
437
526
|
|
|
438
527
|
/**
|
|
439
|
-
* Close the file client.
|
|
440
|
-
* and rejects all pending requests.
|
|
528
|
+
* Close the file client. Rejects all pending requests.
|
|
441
529
|
*/
|
|
442
530
|
close() {
|
|
443
|
-
|
|
444
|
-
for (const [requestId, pending] of this.#pendingRequests) {
|
|
531
|
+
for (const [, pending] of this.#pendingRequests) {
|
|
445
532
|
clearTimeout(pending.timer)
|
|
446
533
|
pending.reject(new Error('FileClient closed'))
|
|
447
534
|
}
|
|
448
535
|
this.#pendingRequests.clear()
|
|
449
|
-
|
|
450
|
-
// Remove handler from session
|
|
451
|
-
this.#session.removeHandler('files')
|
|
452
536
|
}
|
|
453
537
|
|
|
454
538
|
// -- Serialization --------------------------------------------------------
|
|
455
539
|
|
|
456
|
-
/**
|
|
457
|
-
* Serialize to a JSON-safe object.
|
|
458
|
-
*
|
|
459
|
-
* @returns {object}
|
|
460
|
-
*/
|
|
540
|
+
/** @returns {object} */
|
|
461
541
|
toJSON() {
|
|
462
542
|
return {
|
|
463
|
-
sessionId: this.#session.sessionId,
|
|
464
|
-
localPodId: this.#session.localPodId,
|
|
465
|
-
remotePodId: this.#session.remotePodId,
|
|
466
543
|
pendingRequests: this.#pendingRequests.size,
|
|
467
544
|
timeout: this.#timeout,
|
|
468
545
|
}
|
|
469
546
|
}
|
|
470
547
|
}
|
|
548
|
+
|
|
549
|
+
// ---------------------------------------------------------------------------
|
|
550
|
+
// createFileShareService -- the MeshService descriptor
|
|
551
|
+
// ---------------------------------------------------------------------------
|
|
552
|
+
|
|
553
|
+
/**
|
|
554
|
+
* Build a `MeshService` descriptor (`mesh-service.mjs`) wiring `FileHost`/
|
|
555
|
+
* `FileClient` onto `ctx.sendTo()`/`ctx.onIncomingData()`. One service
|
|
556
|
+
* covers both directions -- hosting files to other peers (if `fs` is
|
|
557
|
+
* supplied) and requesting files from other peers (always available via the
|
|
558
|
+
* returned `api`) -- see module doc comment for why this isn't split into
|
|
559
|
+
* two descriptors.
|
|
560
|
+
*
|
|
561
|
+
* @param {object} [opts]
|
|
562
|
+
* @param {object} [opts.fs] - File system interface for `FileHost` (list/read/
|
|
563
|
+
* write/delete/stat, list+read required, others optional per action). If
|
|
564
|
+
* omitted, this node does not host files -- inbound `files-request`
|
|
565
|
+
* envelopes still get a clean `{success: false, error: 'this peer is not
|
|
566
|
+
* hosting files'}` response rather than being silently dropped (matching
|
|
567
|
+
* `mesh-rpc.mjs`'s "no handler registered" convention) or crashing the
|
|
568
|
+
* shared dispatch loop.
|
|
569
|
+
* @param {number} [opts.maxFileSize] - See `FileHost`.
|
|
570
|
+
* @param {number} [opts.timeout] - See `FileClient`.
|
|
571
|
+
* @param {Function} [opts.onLog]
|
|
572
|
+
* @param {string} [opts.resource='files'] - `ctx.registry.checkAccess()` resource
|
|
573
|
+
* name (see `FILE_RESOURCE`). Override to scope file access under a
|
|
574
|
+
* different capability namespace than the family default.
|
|
575
|
+
* @param {string} [opts.requestEnvelopeType='files-request']
|
|
576
|
+
* @param {string} [opts.responseEnvelopeType='files-response']
|
|
577
|
+
* @returns {import('./mesh-service.mjs').MeshService}
|
|
578
|
+
*/
|
|
579
|
+
export function createFileShareService({
|
|
580
|
+
fs,
|
|
581
|
+
maxFileSize,
|
|
582
|
+
timeout,
|
|
583
|
+
onLog,
|
|
584
|
+
resource = FILE_RESOURCE,
|
|
585
|
+
requestEnvelopeType = DEFAULT_REQUEST_ENVELOPE_TYPE,
|
|
586
|
+
responseEnvelopeType = DEFAULT_RESPONSE_ENVELOPE_TYPE,
|
|
587
|
+
} = {}) {
|
|
588
|
+
const log = onLog || (() => {})
|
|
589
|
+
|
|
590
|
+
return {
|
|
591
|
+
name: 'file-share',
|
|
592
|
+
|
|
593
|
+
attach(peerNode, ctx) {
|
|
594
|
+
const fileHost = fs
|
|
595
|
+
? new FileHost({
|
|
596
|
+
fs,
|
|
597
|
+
maxFileSize,
|
|
598
|
+
onLog,
|
|
599
|
+
checkAccess: (fromPubKey, capAction) => ctx.registry.checkAccess(fromPubKey, resource, capAction),
|
|
600
|
+
})
|
|
601
|
+
: null
|
|
602
|
+
|
|
603
|
+
const fileClient = new FileClient({
|
|
604
|
+
timeout,
|
|
605
|
+
onLog,
|
|
606
|
+
sendRequest: (pubKey, payload) => ctx.sendTo(pubKey, requestEnvelopeType, payload),
|
|
607
|
+
})
|
|
608
|
+
|
|
609
|
+
const unsubscribeRequests = ctx.onIncomingData(requestEnvelopeType, async (fromPubKey, msg) => {
|
|
610
|
+
let response
|
|
611
|
+
try {
|
|
612
|
+
response = fileHost
|
|
613
|
+
? await fileHost.handleRequest(fromPubKey, msg)
|
|
614
|
+
: {
|
|
615
|
+
requestId: msg?.requestId ?? null,
|
|
616
|
+
action: msg?.action ?? null,
|
|
617
|
+
success: false,
|
|
618
|
+
error: 'this peer is not hosting files',
|
|
619
|
+
}
|
|
620
|
+
} catch (err) {
|
|
621
|
+
// FileHost#handleRequest() already catches every fs-operation
|
|
622
|
+
// error itself -- reaching here would mean something unexpected
|
|
623
|
+
// (e.g. checkAccess() throwing). Never let it become an unhandled
|
|
624
|
+
// rejection or crash the shared onIncomingData() dispatch loop.
|
|
625
|
+
log('file-share:request-handling-failed', { from: fromPubKey, requestId: msg?.requestId, error: err?.message || String(err) })
|
|
626
|
+
response = { requestId: msg?.requestId ?? null, action: msg?.action ?? null, success: false, error: err?.message || String(err) }
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
ctx.emit('file-share:request-served', { from: fromPubKey, action: response.action, success: response.success })
|
|
630
|
+
|
|
631
|
+
try {
|
|
632
|
+
await ctx.sendTo(fromPubKey, responseEnvelopeType, response)
|
|
633
|
+
} catch (err) {
|
|
634
|
+
log('file-share:response-send-failed', { to: fromPubKey, requestId: response.requestId, error: err?.message || String(err) })
|
|
635
|
+
}
|
|
636
|
+
})
|
|
637
|
+
|
|
638
|
+
const unsubscribeResponses = ctx.onIncomingData(responseEnvelopeType, (fromPubKey, msg) => {
|
|
639
|
+
fileClient.handleResponse(fromPubKey, msg)
|
|
640
|
+
})
|
|
641
|
+
|
|
642
|
+
const api = {
|
|
643
|
+
host: fileHost,
|
|
644
|
+
client: fileClient,
|
|
645
|
+
listFiles: (pubKey, path) => fileClient.listFiles(pubKey, path),
|
|
646
|
+
readFile: (pubKey, path) => fileClient.readFile(pubKey, path),
|
|
647
|
+
writeFile: (pubKey, path, data) => fileClient.writeFile(pubKey, path, data),
|
|
648
|
+
deleteFile: (pubKey, path) => fileClient.deleteFile(pubKey, path),
|
|
649
|
+
stat: (pubKey, path) => fileClient.stat(pubKey, path),
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
return {
|
|
653
|
+
api,
|
|
654
|
+
teardown() {
|
|
655
|
+
unsubscribeRequests()
|
|
656
|
+
unsubscribeResponses()
|
|
657
|
+
fileClient.close()
|
|
658
|
+
},
|
|
659
|
+
}
|
|
660
|
+
},
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
export { DEFAULT_REQUEST_ENVELOPE_TYPE, DEFAULT_RESPONSE_ENVELOPE_TYPE }
|