@yrzhao/aves-core 1.0.1 → 1.2.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 +131 -75
- package/dist/core/AvesClient.d.ts +35 -8
- package/dist/core/AvesClient.js +351 -52
- package/dist/core/AvesError.d.ts +1 -1
- package/dist/core/EventEmitter.d.ts +8 -16
- package/dist/core/EventEmitter.js +41 -10
- package/dist/core/SignalingClient.d.ts +39 -44
- package/dist/core/SignalingClient.js +434 -78
- package/dist/core/WebRTCManager.d.ts +68 -99
- package/dist/core/WebRTCManager.js +611 -133
- package/dist/core/webrtc/channels.d.ts +6 -0
- package/dist/core/webrtc/channels.js +15 -0
- package/dist/core/webrtc/fileTransfer.d.ts +46 -3
- package/dist/core/webrtc/fileTransfer.js +725 -78
- package/dist/core/webrtc/mediaTracks.d.ts +38 -5
- package/dist/core/webrtc/mediaTracks.js +269 -58
- package/dist/esm/core/AvesClient.d.ts +35 -8
- package/dist/esm/core/AvesClient.js +351 -52
- package/dist/esm/core/AvesError.d.ts +1 -1
- package/dist/esm/core/EventEmitter.d.ts +8 -16
- package/dist/esm/core/EventEmitter.js +41 -10
- package/dist/esm/core/SignalingClient.d.ts +39 -44
- package/dist/esm/core/SignalingClient.js +434 -78
- package/dist/esm/core/WebRTCManager.d.ts +68 -99
- package/dist/esm/core/WebRTCManager.js +612 -134
- package/dist/esm/core/webrtc/channels.d.ts +6 -0
- package/dist/esm/core/webrtc/channels.js +14 -0
- package/dist/esm/core/webrtc/fileTransfer.d.ts +46 -3
- package/dist/esm/core/webrtc/fileTransfer.js +722 -77
- package/dist/esm/core/webrtc/mediaTracks.d.ts +38 -5
- package/dist/esm/core/webrtc/mediaTracks.js +269 -58
- package/dist/esm/index.d.ts +2 -1
- package/dist/esm/types/types.d.ts +126 -9
- package/dist/index.d.ts +2 -1
- package/dist/types/types.d.ts +126 -9
- package/package.json +22 -6
|
@@ -1,25 +1,90 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.FileTransferManager = exports.FILE_END_MARKER_PREFIX = exports.FILE_COMPLETE_TIMEOUT_MS = exports.FILE_READY_TIMEOUT_MS = exports.FILE_PROTOCOL = exports.DEFAULT_FILE_CHUNK_SIZE = void 0;
|
|
3
|
+
exports.FileTransferManager = exports.FILE_END_MARKER_PREFIX = exports.FILE_START_MARKER_PREFIX = exports.FILE_COMPLETE_TIMEOUT_MS = exports.FILE_READY_TIMEOUT_MS = exports.FILE_PROTOCOL = exports.DEFAULT_LOW_WATER_MARK = exports.DEFAULT_HIGH_WATER_MARK = exports.DEFAULT_MAX_RECEIVE_FILE_SIZE = exports.MAX_FILE_CHUNK_SIZE = exports.DEFAULT_FILE_CHUNK_SIZE = void 0;
|
|
4
|
+
exports.sanitizeFileName = sanitizeFileName;
|
|
5
|
+
exports.sanitizeMimeType = sanitizeMimeType;
|
|
4
6
|
exports.isFileControlMessage = isFileControlMessage;
|
|
5
7
|
exports.validateChunkSize = validateChunkSize;
|
|
6
8
|
const AvesError_1 = require("../AvesError");
|
|
7
9
|
exports.DEFAULT_FILE_CHUNK_SIZE = 16 * 1024;
|
|
10
|
+
exports.MAX_FILE_CHUNK_SIZE = 256 * 1024;
|
|
11
|
+
exports.DEFAULT_MAX_RECEIVE_FILE_SIZE = 100 * 1024 * 1024; // 100 MiB
|
|
12
|
+
exports.DEFAULT_HIGH_WATER_MARK = 256 * 1024; // 256 KiB
|
|
13
|
+
exports.DEFAULT_LOW_WATER_MARK = 64 * 1024; // 64 KiB
|
|
8
14
|
exports.FILE_PROTOCOL = "aves:file-control";
|
|
9
|
-
exports.FILE_READY_TIMEOUT_MS =
|
|
10
|
-
exports.FILE_COMPLETE_TIMEOUT_MS =
|
|
15
|
+
exports.FILE_READY_TIMEOUT_MS = 15000;
|
|
16
|
+
exports.FILE_COMPLETE_TIMEOUT_MS = 30000;
|
|
17
|
+
exports.FILE_START_MARKER_PREFIX = "__aves_file_start__:";
|
|
11
18
|
exports.FILE_END_MARKER_PREFIX = "__aves_file_end__:";
|
|
19
|
+
const MAX_FILENAME_LENGTH = 255;
|
|
20
|
+
const MAX_CHUNKS_PER_TRANSFER = 200000;
|
|
21
|
+
const DANGEROUS_MIME_PATTERN = /^(?:text\/html|application\/xhtml\+xml|image\/svg\+xml|(?:text|application)\/(?:x-)?javascript|application\/ecmascript)/i;
|
|
22
|
+
function sanitizeFileName(rawName) {
|
|
23
|
+
if (typeof rawName !== "string") {
|
|
24
|
+
return "shared-file";
|
|
25
|
+
}
|
|
26
|
+
// Strip path traversal, control characters, and Unicode BiDi override chars.
|
|
27
|
+
const cleaned = rawName
|
|
28
|
+
.replace(/[\x00-\x1f\x7f\u202A-\u202E\u2066-\u2069]/g, "")
|
|
29
|
+
.replace(/[\\/]+/g, "_")
|
|
30
|
+
.replace(/\.\.+/g, ".")
|
|
31
|
+
.trim();
|
|
32
|
+
if (!cleaned || cleaned === "." || cleaned === "..") {
|
|
33
|
+
return "shared-file";
|
|
34
|
+
}
|
|
35
|
+
return cleaned.slice(0, MAX_FILENAME_LENGTH);
|
|
36
|
+
}
|
|
37
|
+
function sanitizeMimeType(rawMime) {
|
|
38
|
+
if (typeof rawMime !== "string" || rawMime.trim().length === 0) {
|
|
39
|
+
return "application/octet-stream";
|
|
40
|
+
}
|
|
41
|
+
const normalized = rawMime.split(";")[0].trim().toLowerCase();
|
|
42
|
+
if (!normalized || DANGEROUS_MIME_PATTERN.test(normalized)) {
|
|
43
|
+
return "application/octet-stream";
|
|
44
|
+
}
|
|
45
|
+
return normalized;
|
|
46
|
+
}
|
|
47
|
+
function unrefTimer(timer) {
|
|
48
|
+
const maybeNodeTimer = timer;
|
|
49
|
+
maybeNodeTimer.unref?.();
|
|
50
|
+
}
|
|
12
51
|
class FileTransferManager {
|
|
13
52
|
constructor(options) {
|
|
14
53
|
this.outgoingTransfers = new Map();
|
|
15
54
|
this.incomingTransfers = new Map();
|
|
16
55
|
this.readyResolvers = new Map();
|
|
17
56
|
this.completionResolvers = new Map();
|
|
57
|
+
this.pendingOutgoingPeers = new Set();
|
|
58
|
+
this.pendingIncomingTransfers = new Map();
|
|
59
|
+
this.dirtyFileChannelPeers = new Set();
|
|
18
60
|
this.fileTransferStartedCallbacks = new Set();
|
|
19
61
|
this.fileTransferProgressCallbacks = new Set();
|
|
20
62
|
this.fileTransferCompletedCallbacks = new Set();
|
|
21
63
|
this.fileTransferFailedCallbacks = new Set();
|
|
22
64
|
this.fileChunkSize = validateChunkSize(options.fileChunkSize);
|
|
65
|
+
const cfg = options.config ?? {};
|
|
66
|
+
this.maxReceiveFileSize =
|
|
67
|
+
cfg.maxReceiveFileSize !== undefined && cfg.maxReceiveFileSize >= 0
|
|
68
|
+
? cfg.maxReceiveFileSize
|
|
69
|
+
: exports.DEFAULT_MAX_RECEIVE_FILE_SIZE;
|
|
70
|
+
this.highWaterMark =
|
|
71
|
+
cfg.highWaterMark !== undefined && cfg.highWaterMark > 0
|
|
72
|
+
? cfg.highWaterMark
|
|
73
|
+
: exports.DEFAULT_HIGH_WATER_MARK;
|
|
74
|
+
this.lowWaterMark =
|
|
75
|
+
cfg.lowWaterMark !== undefined && cfg.lowWaterMark >= 0
|
|
76
|
+
? Math.min(cfg.lowWaterMark, this.highWaterMark)
|
|
77
|
+
: Math.min(exports.DEFAULT_LOW_WATER_MARK, this.highWaterMark);
|
|
78
|
+
this.readyTimeoutMs =
|
|
79
|
+
cfg.readyTimeoutMs !== undefined && cfg.readyTimeoutMs > 0
|
|
80
|
+
? cfg.readyTimeoutMs
|
|
81
|
+
: exports.FILE_READY_TIMEOUT_MS;
|
|
82
|
+
this.completeTimeoutMs =
|
|
83
|
+
cfg.completeTimeoutMs !== undefined && cfg.completeTimeoutMs > 0
|
|
84
|
+
? cfg.completeTimeoutMs
|
|
85
|
+
: exports.FILE_COMPLETE_TIMEOUT_MS;
|
|
86
|
+
this.verifyChecksum = cfg.verifyChecksum ?? true;
|
|
87
|
+
this.onIncomingTransfer = cfg.onIncomingTransfer;
|
|
23
88
|
this.getActivePeers = options.getActivePeers;
|
|
24
89
|
this.isFileChannelReady = options.isFileChannelReady;
|
|
25
90
|
this.getMessageChannel = options.getMessageChannel;
|
|
@@ -43,6 +108,9 @@ class FileTransferManager {
|
|
|
43
108
|
this.fileTransferCompletedCallbacks.clear();
|
|
44
109
|
this.fileTransferFailedCallbacks.clear();
|
|
45
110
|
}
|
|
111
|
+
/**
|
|
112
|
+
* Send a file to one peer or broadcast in parallel to every ready peer.
|
|
113
|
+
*/
|
|
46
114
|
async sendFile(blob, options = {}) {
|
|
47
115
|
const peerIds = options.peerId
|
|
48
116
|
? [options.peerId]
|
|
@@ -55,35 +123,98 @@ class FileTransferManager {
|
|
|
55
123
|
retryable: true,
|
|
56
124
|
});
|
|
57
125
|
}
|
|
126
|
+
if (peerIds.length === 1) {
|
|
127
|
+
const info = await this.sendFileToPeer(peerIds[0], blob, options);
|
|
128
|
+
return [info];
|
|
129
|
+
}
|
|
130
|
+
const settled = await Promise.allSettled(peerIds.map((peerId) => this.sendFileToPeer(peerId, blob, options)));
|
|
58
131
|
const results = [];
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
132
|
+
let firstError = null;
|
|
133
|
+
for (const outcome of settled) {
|
|
134
|
+
if (outcome.status === "fulfilled") {
|
|
135
|
+
results.push(outcome.value);
|
|
136
|
+
}
|
|
137
|
+
else if (firstError === null) {
|
|
138
|
+
firstError = outcome.reason;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (results.length === 0 && firstError !== null) {
|
|
142
|
+
throw firstError;
|
|
62
143
|
}
|
|
63
144
|
return results;
|
|
64
145
|
}
|
|
146
|
+
/**
|
|
147
|
+
* Cancel an active outgoing or incoming transfer for a peer.
|
|
148
|
+
*/
|
|
149
|
+
cancelTransfer(peerId, transferId) {
|
|
150
|
+
const outgoing = this.outgoingTransfers.get(peerId);
|
|
151
|
+
if (outgoing && (!transferId || outgoing.transferId === transferId)) {
|
|
152
|
+
outgoing.cancelled = true;
|
|
153
|
+
const cancelError = new AvesError_1.AvesError({
|
|
154
|
+
message: `File transfer ${outgoing.transferId} cancelled`,
|
|
155
|
+
code: "FILE_TRANSFER_CANCELLED",
|
|
156
|
+
stage: "transport",
|
|
157
|
+
retryable: false,
|
|
158
|
+
peerId,
|
|
159
|
+
});
|
|
160
|
+
const ready = this.readyResolvers.get(peerId);
|
|
161
|
+
if (ready && ready.transferId === outgoing.transferId) {
|
|
162
|
+
this.clearReadyResolver(peerId);
|
|
163
|
+
ready.reject(cancelError);
|
|
164
|
+
}
|
|
165
|
+
const completion = this.completionResolvers.get(peerId);
|
|
166
|
+
if (completion && completion.transferId === outgoing.transferId) {
|
|
167
|
+
this.clearCompletionResolver(peerId);
|
|
168
|
+
completion.reject(cancelError);
|
|
169
|
+
}
|
|
170
|
+
this.trySendControl(peerId, {
|
|
171
|
+
__aves: exports.FILE_PROTOCOL,
|
|
172
|
+
kind: "file-cancel",
|
|
173
|
+
transferId: outgoing.transferId,
|
|
174
|
+
reason: "Cancelled by sender",
|
|
175
|
+
});
|
|
176
|
+
return true;
|
|
177
|
+
}
|
|
178
|
+
const incoming = this.incomingTransfers.get(peerId);
|
|
179
|
+
if (incoming && (!transferId || incoming.transferId === transferId)) {
|
|
180
|
+
this.incomingTransfers.delete(peerId);
|
|
181
|
+
// Mark file channel dirty so stale in-flight chunks from this cancelled
|
|
182
|
+
// transfer are ignored until the next transfer's start marker arrives.
|
|
183
|
+
this.dirtyFileChannelPeers.add(peerId);
|
|
184
|
+
this.trySendControl(peerId, {
|
|
185
|
+
__aves: exports.FILE_PROTOCOL,
|
|
186
|
+
kind: "file-cancel",
|
|
187
|
+
transferId: incoming.transferId,
|
|
188
|
+
reason: "Cancelled by receiver",
|
|
189
|
+
});
|
|
190
|
+
this.emitFailed(peerId, incoming, new AvesError_1.AvesError({
|
|
191
|
+
message: `File transfer ${incoming.transferId} cancelled`,
|
|
192
|
+
code: "FILE_TRANSFER_CANCELLED",
|
|
193
|
+
stage: "transport",
|
|
194
|
+
retryable: false,
|
|
195
|
+
peerId,
|
|
196
|
+
}));
|
|
197
|
+
return true;
|
|
198
|
+
}
|
|
199
|
+
const pendingIncoming = this.pendingIncomingTransfers.get(peerId);
|
|
200
|
+
if (pendingIncoming &&
|
|
201
|
+
(!transferId || pendingIncoming.transferId === transferId)) {
|
|
202
|
+
pendingIncoming.aborted = true;
|
|
203
|
+
this.pendingIncomingTransfers.delete(peerId);
|
|
204
|
+
this.trySendControl(peerId, {
|
|
205
|
+
__aves: exports.FILE_PROTOCOL,
|
|
206
|
+
kind: "file-cancel",
|
|
207
|
+
transferId: pendingIncoming.transferId,
|
|
208
|
+
reason: "Cancelled by receiver",
|
|
209
|
+
});
|
|
210
|
+
return true;
|
|
211
|
+
}
|
|
212
|
+
return false;
|
|
213
|
+
}
|
|
65
214
|
handleControlMessage(peerId, message) {
|
|
66
215
|
switch (message.kind) {
|
|
67
216
|
case "file-meta": {
|
|
68
|
-
|
|
69
|
-
transferId: message.transfer.transferId,
|
|
70
|
-
peerId,
|
|
71
|
-
direction: "receive",
|
|
72
|
-
name: message.transfer.name,
|
|
73
|
-
size: message.transfer.size,
|
|
74
|
-
mimeType: message.transfer.mimeType,
|
|
75
|
-
lastModified: message.transfer.lastModified,
|
|
76
|
-
chunks: [],
|
|
77
|
-
bytesTransferred: 0,
|
|
78
|
-
};
|
|
79
|
-
this.incomingTransfers.set(peerId, transfer);
|
|
80
|
-
this.emitStarted(peerId, transfer);
|
|
81
|
-
this.emitProgress(peerId, transfer, 0);
|
|
82
|
-
this.sendControl(peerId, {
|
|
83
|
-
__aves: exports.FILE_PROTOCOL,
|
|
84
|
-
kind: "file-ready",
|
|
85
|
-
transferId: transfer.transferId,
|
|
86
|
-
});
|
|
217
|
+
void this.handleIncomingFileMeta(peerId, message);
|
|
87
218
|
break;
|
|
88
219
|
}
|
|
89
220
|
case "file-ready": {
|
|
@@ -105,76 +236,352 @@ class FileTransferManager {
|
|
|
105
236
|
}
|
|
106
237
|
break;
|
|
107
238
|
}
|
|
239
|
+
case "file-cancel": {
|
|
240
|
+
const reason = message.reason || "Transfer cancelled by remote peer";
|
|
241
|
+
const cancelError = new AvesError_1.AvesError({
|
|
242
|
+
message: reason,
|
|
243
|
+
code: "FILE_TRANSFER_CANCELLED",
|
|
244
|
+
stage: "transport",
|
|
245
|
+
retryable: false,
|
|
246
|
+
peerId,
|
|
247
|
+
});
|
|
248
|
+
const outgoing = this.outgoingTransfers.get(peerId);
|
|
249
|
+
if (outgoing && outgoing.transferId === message.transferId) {
|
|
250
|
+
outgoing.cancelled = true;
|
|
251
|
+
outgoing.fromRemoteError = true;
|
|
252
|
+
this.rejectPendingResolvers(peerId, cancelError);
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
const pendingIncoming = this.pendingIncomingTransfers.get(peerId);
|
|
256
|
+
if (pendingIncoming && pendingIncoming.transferId === message.transferId) {
|
|
257
|
+
pendingIncoming.aborted = true;
|
|
258
|
+
this.pendingIncomingTransfers.delete(peerId);
|
|
259
|
+
}
|
|
260
|
+
const incoming = this.incomingTransfers.get(peerId);
|
|
261
|
+
if (incoming && incoming.transferId === message.transferId) {
|
|
262
|
+
this.incomingTransfers.delete(peerId);
|
|
263
|
+
this.dirtyFileChannelPeers.add(peerId);
|
|
264
|
+
this.emitFailed(peerId, incoming, cancelError);
|
|
265
|
+
}
|
|
266
|
+
break;
|
|
267
|
+
}
|
|
108
268
|
case "file-error": {
|
|
109
|
-
const
|
|
110
|
-
this.incomingTransfers.get(peerId) ??
|
|
111
|
-
null;
|
|
112
|
-
this.emitFailed(peerId, transfer, new AvesError_1.AvesError({
|
|
269
|
+
const remoteError = new AvesError_1.AvesError({
|
|
113
270
|
message: message.message,
|
|
114
271
|
code: "FILE_TRANSFER_FAILED",
|
|
115
272
|
stage: "transport",
|
|
116
273
|
retryable: false,
|
|
117
274
|
peerId,
|
|
118
|
-
})
|
|
119
|
-
this.outgoingTransfers.
|
|
120
|
-
this.incomingTransfers.
|
|
121
|
-
|
|
122
|
-
|
|
275
|
+
});
|
|
276
|
+
const outgoing = this.outgoingTransfers.get(peerId);
|
|
277
|
+
const incoming = this.incomingTransfers.get(peerId);
|
|
278
|
+
// Strictly match transferId to prevent full-duplex cross-direction kills
|
|
279
|
+
// and forged control errors from disrupting unrelated transfers.
|
|
280
|
+
if (outgoing && outgoing.transferId === message.transferId) {
|
|
281
|
+
outgoing.cancelled = true;
|
|
282
|
+
outgoing.fromRemoteError = true;
|
|
283
|
+
outgoing.failedEmitted = true;
|
|
284
|
+
this.outgoingTransfers.delete(peerId);
|
|
285
|
+
this.rejectPendingResolvers(peerId, remoteError);
|
|
286
|
+
this.emitFailed(peerId, outgoing, remoteError);
|
|
287
|
+
break;
|
|
288
|
+
}
|
|
289
|
+
if (incoming && incoming.transferId === message.transferId) {
|
|
290
|
+
this.incomingTransfers.delete(peerId);
|
|
291
|
+
this.dirtyFileChannelPeers.add(peerId);
|
|
292
|
+
this.emitFailed(peerId, incoming, remoteError);
|
|
293
|
+
break;
|
|
294
|
+
}
|
|
295
|
+
const pendingIncoming = this.pendingIncomingTransfers.get(peerId);
|
|
296
|
+
if (pendingIncoming && pendingIncoming.transferId === message.transferId) {
|
|
297
|
+
pendingIncoming.aborted = true;
|
|
298
|
+
this.pendingIncomingTransfers.delete(peerId);
|
|
299
|
+
}
|
|
123
300
|
break;
|
|
124
301
|
}
|
|
125
302
|
}
|
|
126
303
|
}
|
|
304
|
+
async handleIncomingFileMeta(peerId, message) {
|
|
305
|
+
const meta = message.transfer;
|
|
306
|
+
if (!meta ||
|
|
307
|
+
typeof meta.transferId !== "string" ||
|
|
308
|
+
meta.transferId.trim().length === 0 ||
|
|
309
|
+
!Number.isFinite(meta.size) ||
|
|
310
|
+
meta.size < 0) {
|
|
311
|
+
const invalidError = new AvesError_1.AvesError({
|
|
312
|
+
message: "Invalid incoming file metadata",
|
|
313
|
+
code: "INVALID_MESSAGE_FORMAT",
|
|
314
|
+
stage: "protocol",
|
|
315
|
+
retryable: false,
|
|
316
|
+
peerId,
|
|
317
|
+
});
|
|
318
|
+
this.trySendControl(peerId, {
|
|
319
|
+
__aves: exports.FILE_PROTOCOL,
|
|
320
|
+
kind: "file-error",
|
|
321
|
+
transferId: typeof meta?.transferId === "string" ? meta.transferId : "unknown",
|
|
322
|
+
message: invalidError.message,
|
|
323
|
+
});
|
|
324
|
+
this.emitFailed(peerId, null, invalidError);
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
// Reject concurrent incoming file transfers from the same peer to prevent silent overwrite.
|
|
328
|
+
if (this.incomingTransfers.has(peerId) ||
|
|
329
|
+
this.pendingIncomingTransfers.has(peerId)) {
|
|
330
|
+
const busyError = new AvesError_1.AvesError({
|
|
331
|
+
message: `An incoming file transfer is already active for ${peerId}`,
|
|
332
|
+
code: "FILE_TRANSFER_FAILED",
|
|
333
|
+
stage: "transport",
|
|
334
|
+
retryable: true,
|
|
335
|
+
peerId,
|
|
336
|
+
});
|
|
337
|
+
this.trySendControl(peerId, {
|
|
338
|
+
__aves: exports.FILE_PROTOCOL,
|
|
339
|
+
kind: "file-error",
|
|
340
|
+
transferId: meta.transferId,
|
|
341
|
+
message: busyError.message,
|
|
342
|
+
});
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
const transfer = {
|
|
346
|
+
transferId: meta.transferId,
|
|
347
|
+
peerId,
|
|
348
|
+
direction: "receive",
|
|
349
|
+
name: sanitizeFileName(meta.name),
|
|
350
|
+
size: meta.size,
|
|
351
|
+
mimeType: sanitizeMimeType(meta.mimeType),
|
|
352
|
+
lastModified: typeof meta.lastModified === "number" && Number.isFinite(meta.lastModified)
|
|
353
|
+
? meta.lastModified
|
|
354
|
+
: Date.now(),
|
|
355
|
+
sha256: typeof meta.sha256 === "string" ? meta.sha256 : undefined,
|
|
356
|
+
chunks: [],
|
|
357
|
+
bytesTransferred: 0,
|
|
358
|
+
awaitingStartMarker: this.dirtyFileChannelPeers.has(peerId),
|
|
359
|
+
};
|
|
360
|
+
if (meta.size > this.maxReceiveFileSize) {
|
|
361
|
+
const sizeError = new AvesError_1.AvesError({
|
|
362
|
+
message: `Incoming file "${transfer.name}" (${meta.size} bytes) exceeds maximum allowed size (${this.maxReceiveFileSize} bytes)`,
|
|
363
|
+
code: "FILE_SIZE_EXCEEDED",
|
|
364
|
+
stage: "transport",
|
|
365
|
+
retryable: false,
|
|
366
|
+
peerId,
|
|
367
|
+
});
|
|
368
|
+
this.trySendControl(peerId, {
|
|
369
|
+
__aves: exports.FILE_PROTOCOL,
|
|
370
|
+
kind: "file-error",
|
|
371
|
+
transferId: transfer.transferId,
|
|
372
|
+
message: sizeError.message,
|
|
373
|
+
});
|
|
374
|
+
this.emitFailed(peerId, transfer, sizeError);
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
if (this.onIncomingTransfer) {
|
|
378
|
+
const pendingToken = { transferId: transfer.transferId, aborted: false };
|
|
379
|
+
this.pendingIncomingTransfers.set(peerId, pendingToken);
|
|
380
|
+
let accepted = false;
|
|
381
|
+
try {
|
|
382
|
+
accepted = Boolean(await this.onIncomingTransfer(peerId, transfer));
|
|
383
|
+
}
|
|
384
|
+
catch {
|
|
385
|
+
accepted = false;
|
|
386
|
+
}
|
|
387
|
+
finally {
|
|
388
|
+
if (this.pendingIncomingTransfers.get(peerId) === pendingToken) {
|
|
389
|
+
this.pendingIncomingTransfers.delete(peerId);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
if (pendingToken.aborted) {
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
if (!accepted) {
|
|
396
|
+
const rejectedError = new AvesError_1.AvesError({
|
|
397
|
+
message: `Incoming file transfer "${transfer.name}" rejected`,
|
|
398
|
+
code: "FILE_TRANSFER_REJECTED",
|
|
399
|
+
stage: "transport",
|
|
400
|
+
retryable: false,
|
|
401
|
+
peerId,
|
|
402
|
+
});
|
|
403
|
+
this.trySendControl(peerId, {
|
|
404
|
+
__aves: exports.FILE_PROTOCOL,
|
|
405
|
+
kind: "file-error",
|
|
406
|
+
transferId: transfer.transferId,
|
|
407
|
+
message: rejectedError.message,
|
|
408
|
+
});
|
|
409
|
+
this.emitFailed(peerId, transfer, rejectedError);
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
this.incomingTransfers.set(peerId, transfer);
|
|
414
|
+
this.emitStarted(peerId, transfer);
|
|
415
|
+
this.emitProgress(peerId, transfer, 0, false);
|
|
416
|
+
this.trySendControl(peerId, {
|
|
417
|
+
__aves: exports.FILE_PROTOCOL,
|
|
418
|
+
kind: "file-ready",
|
|
419
|
+
transferId: transfer.transferId,
|
|
420
|
+
});
|
|
421
|
+
}
|
|
127
422
|
handleChunk(peerId, data) {
|
|
128
423
|
const transfer = this.incomingTransfers.get(peerId);
|
|
129
424
|
if (!transfer) {
|
|
130
425
|
return;
|
|
131
426
|
}
|
|
132
|
-
if (typeof data === "string"
|
|
133
|
-
data
|
|
134
|
-
|
|
135
|
-
|
|
427
|
+
if (typeof data === "string") {
|
|
428
|
+
if (data.startsWith(exports.FILE_START_MARKER_PREFIX)) {
|
|
429
|
+
const markerId = data.slice(exports.FILE_START_MARKER_PREFIX.length);
|
|
430
|
+
if (markerId === transfer.transferId) {
|
|
431
|
+
transfer.awaitingStartMarker = false;
|
|
432
|
+
this.dirtyFileChannelPeers.delete(peerId);
|
|
433
|
+
}
|
|
434
|
+
return;
|
|
435
|
+
}
|
|
436
|
+
if (data === `${exports.FILE_END_MARKER_PREFIX}${transfer.transferId}`) {
|
|
437
|
+
this.dirtyFileChannelPeers.delete(peerId);
|
|
438
|
+
void this.finalizeIncomingTransfer(peerId, transfer);
|
|
439
|
+
return;
|
|
440
|
+
}
|
|
441
|
+
// Ignore stale end markers from previously cancelled transfers.
|
|
442
|
+
if (data.startsWith(exports.FILE_END_MARKER_PREFIX)) {
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
// Discard residual chunks left on the file channel from a previously
|
|
447
|
+
// cancelled transfer until the new transfer's start marker arrives.
|
|
448
|
+
if (transfer.awaitingStartMarker) {
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
const chunkSize = getChunkSize(data);
|
|
452
|
+
if (chunkSize === 0 || transfer.chunks.length >= MAX_CHUNKS_PER_TRANSFER) {
|
|
453
|
+
this.incomingTransfers.delete(peerId);
|
|
454
|
+
this.dirtyFileChannelPeers.add(peerId);
|
|
455
|
+
const invalidChunkError = new AvesError_1.AvesError({
|
|
456
|
+
message: chunkSize === 0
|
|
457
|
+
? "Received empty file chunk"
|
|
458
|
+
: `Exceeded maximum allowed chunk count (${MAX_CHUNKS_PER_TRANSFER})`,
|
|
459
|
+
code: "FILE_TRANSFER_INTEGRITY_FAILED",
|
|
460
|
+
stage: "transport",
|
|
461
|
+
retryable: false,
|
|
136
462
|
peerId,
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
size: transfer.size,
|
|
140
|
-
mimeType: transfer.mimeType,
|
|
141
|
-
lastModified: transfer.lastModified,
|
|
142
|
-
blob: new Blob(transfer.chunks, { type: transfer.mimeType }),
|
|
143
|
-
};
|
|
144
|
-
this.fileTransferCompletedCallbacks.forEach((callback) => callback(peerId, result));
|
|
145
|
-
this.sendControl(peerId, {
|
|
463
|
+
});
|
|
464
|
+
this.trySendControl(peerId, {
|
|
146
465
|
__aves: exports.FILE_PROTOCOL,
|
|
147
|
-
kind: "file-
|
|
466
|
+
kind: "file-error",
|
|
148
467
|
transferId: transfer.transferId,
|
|
468
|
+
message: invalidChunkError.message,
|
|
149
469
|
});
|
|
470
|
+
this.emitFailed(peerId, transfer, invalidChunkError);
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
if (transfer.bytesTransferred + chunkSize > transfer.size) {
|
|
150
474
|
this.incomingTransfers.delete(peerId);
|
|
475
|
+
this.dirtyFileChannelPeers.add(peerId);
|
|
476
|
+
const overflowError = new AvesError_1.AvesError({
|
|
477
|
+
message: `Received bytes (${transfer.bytesTransferred + chunkSize}) exceed declared file size (${transfer.size})`,
|
|
478
|
+
code: "FILE_TRANSFER_INTEGRITY_FAILED",
|
|
479
|
+
stage: "transport",
|
|
480
|
+
retryable: false,
|
|
481
|
+
peerId,
|
|
482
|
+
});
|
|
483
|
+
this.trySendControl(peerId, {
|
|
484
|
+
__aves: exports.FILE_PROTOCOL,
|
|
485
|
+
kind: "file-error",
|
|
486
|
+
transferId: transfer.transferId,
|
|
487
|
+
message: overflowError.message,
|
|
488
|
+
});
|
|
489
|
+
this.emitFailed(peerId, transfer, overflowError);
|
|
151
490
|
return;
|
|
152
491
|
}
|
|
153
492
|
transfer.chunks.push(data);
|
|
154
|
-
transfer.bytesTransferred +=
|
|
493
|
+
transfer.bytesTransferred += chunkSize;
|
|
155
494
|
this.emitProgress(peerId, transfer, transfer.bytesTransferred);
|
|
156
495
|
}
|
|
496
|
+
async finalizeIncomingTransfer(peerId, transfer) {
|
|
497
|
+
this.incomingTransfers.delete(peerId);
|
|
498
|
+
if (transfer.bytesTransferred !== transfer.size) {
|
|
499
|
+
const sizeMismatchError = new AvesError_1.AvesError({
|
|
500
|
+
message: `Incomplete file transfer: expected ${transfer.size} bytes, received ${transfer.bytesTransferred} bytes`,
|
|
501
|
+
code: "FILE_TRANSFER_INTEGRITY_FAILED",
|
|
502
|
+
stage: "transport",
|
|
503
|
+
retryable: true,
|
|
504
|
+
peerId,
|
|
505
|
+
});
|
|
506
|
+
this.trySendControl(peerId, {
|
|
507
|
+
__aves: exports.FILE_PROTOCOL,
|
|
508
|
+
kind: "file-error",
|
|
509
|
+
transferId: transfer.transferId,
|
|
510
|
+
message: sizeMismatchError.message,
|
|
511
|
+
});
|
|
512
|
+
this.emitFailed(peerId, transfer, sizeMismatchError);
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
const assembledBlob = new Blob(transfer.chunks, {
|
|
516
|
+
type: transfer.mimeType,
|
|
517
|
+
});
|
|
518
|
+
let checksumVerified = false;
|
|
519
|
+
if (this.verifyChecksum && transfer.sha256) {
|
|
520
|
+
const actualDigest = await computeBlobSha256(assembledBlob);
|
|
521
|
+
if (actualDigest && actualDigest !== transfer.sha256) {
|
|
522
|
+
const digestError = new AvesError_1.AvesError({
|
|
523
|
+
message: `File checksum mismatch for "${transfer.name}"`,
|
|
524
|
+
code: "FILE_TRANSFER_INTEGRITY_FAILED",
|
|
525
|
+
stage: "transport",
|
|
526
|
+
retryable: true,
|
|
527
|
+
peerId,
|
|
528
|
+
});
|
|
529
|
+
this.trySendControl(peerId, {
|
|
530
|
+
__aves: exports.FILE_PROTOCOL,
|
|
531
|
+
kind: "file-error",
|
|
532
|
+
transferId: transfer.transferId,
|
|
533
|
+
message: digestError.message,
|
|
534
|
+
});
|
|
535
|
+
this.emitFailed(peerId, transfer, digestError);
|
|
536
|
+
return;
|
|
537
|
+
}
|
|
538
|
+
checksumVerified = Boolean(actualDigest && actualDigest === transfer.sha256);
|
|
539
|
+
}
|
|
540
|
+
if (transfer.size === 0) {
|
|
541
|
+
this.emitProgress(peerId, transfer, 0, true);
|
|
542
|
+
}
|
|
543
|
+
const result = {
|
|
544
|
+
transferId: transfer.transferId,
|
|
545
|
+
peerId,
|
|
546
|
+
direction: "receive",
|
|
547
|
+
name: transfer.name,
|
|
548
|
+
size: transfer.size,
|
|
549
|
+
mimeType: transfer.mimeType,
|
|
550
|
+
lastModified: transfer.lastModified,
|
|
551
|
+
sha256: transfer.sha256,
|
|
552
|
+
blob: assembledBlob,
|
|
553
|
+
checksumVerified,
|
|
554
|
+
};
|
|
555
|
+
this.fileTransferCompletedCallbacks.forEach((callback) => callback(peerId, result));
|
|
556
|
+
this.trySendControl(peerId, {
|
|
557
|
+
__aves: exports.FILE_PROTOCOL,
|
|
558
|
+
kind: "file-complete",
|
|
559
|
+
transferId: transfer.transferId,
|
|
560
|
+
});
|
|
561
|
+
}
|
|
157
562
|
failActiveTransfers(peerId, error) {
|
|
563
|
+
const pendingIncoming = this.pendingIncomingTransfers.get(peerId);
|
|
564
|
+
if (pendingIncoming) {
|
|
565
|
+
pendingIncoming.aborted = true;
|
|
566
|
+
this.pendingIncomingTransfers.delete(peerId);
|
|
567
|
+
}
|
|
158
568
|
const outgoingTransfer = this.outgoingTransfers.get(peerId) ?? null;
|
|
159
569
|
const incomingTransfer = this.incomingTransfers.get(peerId) ?? null;
|
|
160
570
|
if (outgoingTransfer) {
|
|
161
|
-
|
|
571
|
+
outgoingTransfer.cancelled = true;
|
|
572
|
+
outgoingTransfer.fromRemoteError = true;
|
|
573
|
+
if (!outgoingTransfer.failedEmitted) {
|
|
574
|
+
outgoingTransfer.failedEmitted = true;
|
|
575
|
+
this.emitFailed(peerId, outgoingTransfer, error);
|
|
576
|
+
}
|
|
162
577
|
}
|
|
163
578
|
if (incomingTransfer) {
|
|
164
579
|
this.emitFailed(peerId, incomingTransfer, error);
|
|
165
580
|
}
|
|
166
|
-
|
|
167
|
-
if (readyResolver) {
|
|
168
|
-
readyResolver.reject(error);
|
|
169
|
-
this.clearReadyResolver(peerId);
|
|
170
|
-
}
|
|
171
|
-
const completionResolver = this.completionResolvers.get(peerId);
|
|
172
|
-
if (completionResolver) {
|
|
173
|
-
completionResolver.reject(error);
|
|
174
|
-
this.clearCompletionResolver(peerId);
|
|
175
|
-
}
|
|
581
|
+
this.rejectPendingResolvers(peerId, error);
|
|
176
582
|
this.outgoingTransfers.delete(peerId);
|
|
177
583
|
this.incomingTransfers.delete(peerId);
|
|
584
|
+
this.dirtyFileChannelPeers.delete(peerId);
|
|
178
585
|
}
|
|
179
586
|
reportFailure(peerId, info, error) {
|
|
180
587
|
this.emitFailed(peerId, info, error);
|
|
@@ -195,6 +602,18 @@ class FileTransferManager {
|
|
|
195
602
|
clearTimeout(resolver.timeoutId);
|
|
196
603
|
this.completionResolvers.delete(peerId);
|
|
197
604
|
}
|
|
605
|
+
rejectPendingResolvers(peerId, error) {
|
|
606
|
+
const readyResolver = this.readyResolvers.get(peerId);
|
|
607
|
+
if (readyResolver) {
|
|
608
|
+
this.clearReadyResolver(peerId);
|
|
609
|
+
readyResolver.reject(error);
|
|
610
|
+
}
|
|
611
|
+
const completionResolver = this.completionResolvers.get(peerId);
|
|
612
|
+
if (completionResolver) {
|
|
613
|
+
this.clearCompletionResolver(peerId);
|
|
614
|
+
completionResolver.reject(error);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
198
617
|
async sendFileToPeer(peerId, blob, options) {
|
|
199
618
|
const messageChannel = this.getMessageChannel(peerId);
|
|
200
619
|
const fileChannel = this.getFileChannel(peerId);
|
|
@@ -216,7 +635,8 @@ class FileTransferManager {
|
|
|
216
635
|
peerId,
|
|
217
636
|
});
|
|
218
637
|
}
|
|
219
|
-
if (this.outgoingTransfers.has(peerId)
|
|
638
|
+
if (this.outgoingTransfers.has(peerId) ||
|
|
639
|
+
this.pendingOutgoingPeers.has(peerId)) {
|
|
220
640
|
throw new AvesError_1.AvesError({
|
|
221
641
|
message: `A file transfer is already active for ${peerId}`,
|
|
222
642
|
code: "FILE_TRANSFER_FAILED",
|
|
@@ -225,20 +645,32 @@ class FileTransferManager {
|
|
|
225
645
|
peerId,
|
|
226
646
|
});
|
|
227
647
|
}
|
|
648
|
+
const chunkSize = validateChunkSize(options.chunkSize ?? this.fileChunkSize);
|
|
649
|
+
// Synchronously reserve peer slot BEFORE async SHA-256 to eliminate TOCTOU race.
|
|
650
|
+
this.pendingOutgoingPeers.add(peerId);
|
|
651
|
+
let sha256;
|
|
652
|
+
try {
|
|
653
|
+
sha256 = this.verifyChecksum ? await computeBlobSha256(blob) : undefined;
|
|
654
|
+
}
|
|
655
|
+
catch (error) {
|
|
656
|
+
this.pendingOutgoingPeers.delete(peerId);
|
|
657
|
+
throw error;
|
|
658
|
+
}
|
|
228
659
|
const transfer = {
|
|
229
660
|
transferId: generateTransferId(),
|
|
230
661
|
peerId,
|
|
231
662
|
direction: "send",
|
|
232
|
-
name: options.fileName || getBlobName(blob),
|
|
663
|
+
name: sanitizeFileName(options.fileName || getBlobName(blob)),
|
|
233
664
|
size: blob.size,
|
|
234
665
|
mimeType: options.mimeType || blob.type || "application/octet-stream",
|
|
235
666
|
lastModified: options.lastModified ?? getBlobLastModified(blob) ?? Date.now(),
|
|
667
|
+
sha256,
|
|
236
668
|
blob,
|
|
237
|
-
chunkSize
|
|
669
|
+
chunkSize,
|
|
238
670
|
};
|
|
239
671
|
this.outgoingTransfers.set(peerId, transfer);
|
|
240
672
|
this.emitStarted(peerId, transfer);
|
|
241
|
-
this.emitProgress(peerId, transfer, 0);
|
|
673
|
+
this.emitProgress(peerId, transfer, 0, false);
|
|
242
674
|
try {
|
|
243
675
|
const readyPromise = this.awaitReady(peerId, transfer.transferId);
|
|
244
676
|
this.sendControl(peerId, {
|
|
@@ -250,22 +682,106 @@ class FileTransferManager {
|
|
|
250
682
|
size: transfer.size,
|
|
251
683
|
mimeType: transfer.mimeType,
|
|
252
684
|
lastModified: transfer.lastModified,
|
|
685
|
+
sha256: transfer.sha256,
|
|
253
686
|
},
|
|
254
687
|
});
|
|
255
688
|
await readyPromise;
|
|
689
|
+
if (transfer.cancelled) {
|
|
690
|
+
throw new AvesError_1.AvesError({
|
|
691
|
+
message: `File transfer ${transfer.transferId} cancelled`,
|
|
692
|
+
code: "FILE_TRANSFER_CANCELLED",
|
|
693
|
+
stage: "transport",
|
|
694
|
+
retryable: false,
|
|
695
|
+
peerId,
|
|
696
|
+
});
|
|
697
|
+
}
|
|
698
|
+
if (fileChannel.readyState !== "open") {
|
|
699
|
+
throw new AvesError_1.AvesError({
|
|
700
|
+
message: `File channel closed before transfer started for ${peerId}`,
|
|
701
|
+
code: "WEBRTC_DATACHANNEL_FAILED",
|
|
702
|
+
stage: "transport",
|
|
703
|
+
retryable: true,
|
|
704
|
+
peerId,
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
// Emit an in-band start marker on the ordered file channel so receivers
|
|
708
|
+
// can cleanly discard any stale chunks from previously cancelled transfers.
|
|
709
|
+
fileChannel.send(`${exports.FILE_START_MARKER_PREFIX}${transfer.transferId}`);
|
|
256
710
|
let offset = 0;
|
|
257
711
|
while (offset < transfer.size) {
|
|
712
|
+
if (transfer.cancelled) {
|
|
713
|
+
throw new AvesError_1.AvesError({
|
|
714
|
+
message: `File transfer ${transfer.transferId} cancelled`,
|
|
715
|
+
code: "FILE_TRANSFER_CANCELLED",
|
|
716
|
+
stage: "transport",
|
|
717
|
+
retryable: false,
|
|
718
|
+
peerId,
|
|
719
|
+
});
|
|
720
|
+
}
|
|
721
|
+
if (fileChannel.readyState !== "open") {
|
|
722
|
+
throw new AvesError_1.AvesError({
|
|
723
|
+
message: `File channel closed during transfer for ${peerId}`,
|
|
724
|
+
code: "WEBRTC_DATACHANNEL_FAILED",
|
|
725
|
+
stage: "transport",
|
|
726
|
+
retryable: true,
|
|
727
|
+
peerId,
|
|
728
|
+
});
|
|
729
|
+
}
|
|
730
|
+
await this.waitForBackpressure(peerId, fileChannel, transfer, this.highWaterMark);
|
|
258
731
|
const nextChunk = transfer.blob.slice(offset, offset + transfer.chunkSize);
|
|
259
732
|
const buffer = await nextChunk.arrayBuffer();
|
|
733
|
+
if (transfer.cancelled) {
|
|
734
|
+
throw new AvesError_1.AvesError({
|
|
735
|
+
message: `File transfer ${transfer.transferId} cancelled`,
|
|
736
|
+
code: "FILE_TRANSFER_CANCELLED",
|
|
737
|
+
stage: "transport",
|
|
738
|
+
retryable: false,
|
|
739
|
+
peerId,
|
|
740
|
+
});
|
|
741
|
+
}
|
|
742
|
+
if (fileChannel.readyState !== "open") {
|
|
743
|
+
throw new AvesError_1.AvesError({
|
|
744
|
+
message: `File channel closed during transfer for ${peerId}`,
|
|
745
|
+
code: "WEBRTC_DATACHANNEL_FAILED",
|
|
746
|
+
stage: "transport",
|
|
747
|
+
retryable: true,
|
|
748
|
+
peerId,
|
|
749
|
+
});
|
|
750
|
+
}
|
|
260
751
|
fileChannel.send(buffer);
|
|
261
752
|
offset += buffer.byteLength;
|
|
262
753
|
this.emitProgress(peerId, transfer, offset);
|
|
263
754
|
}
|
|
755
|
+
// Wait for SCTP send buffer to drain down to lowWaterMark before sending
|
|
756
|
+
// the end marker and starting the completion acknowledgment timeout.
|
|
757
|
+
await this.waitForBackpressure(peerId, fileChannel, transfer, this.lowWaterMark);
|
|
758
|
+
if (transfer.cancelled) {
|
|
759
|
+
throw new AvesError_1.AvesError({
|
|
760
|
+
message: `File transfer ${transfer.transferId} cancelled`,
|
|
761
|
+
code: "FILE_TRANSFER_CANCELLED",
|
|
762
|
+
stage: "transport",
|
|
763
|
+
retryable: false,
|
|
764
|
+
peerId,
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
if (fileChannel.readyState !== "open") {
|
|
768
|
+
throw new AvesError_1.AvesError({
|
|
769
|
+
message: `File channel closed before completion for ${peerId}`,
|
|
770
|
+
code: "WEBRTC_DATACHANNEL_FAILED",
|
|
771
|
+
stage: "transport",
|
|
772
|
+
retryable: true,
|
|
773
|
+
peerId,
|
|
774
|
+
});
|
|
775
|
+
}
|
|
264
776
|
const completionPromise = this.awaitCompletion(peerId, transfer.transferId);
|
|
265
777
|
fileChannel.send(`${exports.FILE_END_MARKER_PREFIX}${transfer.transferId}`);
|
|
266
778
|
await completionPromise;
|
|
779
|
+
if (transfer.size === 0) {
|
|
780
|
+
this.emitProgress(peerId, transfer, 0, true);
|
|
781
|
+
}
|
|
267
782
|
const result = {
|
|
268
783
|
...transfer,
|
|
784
|
+
checksumVerified: Boolean(this.verifyChecksum && transfer.sha256),
|
|
269
785
|
};
|
|
270
786
|
this.fileTransferCompletedCallbacks.forEach((callback) => callback(peerId, result));
|
|
271
787
|
return transfer;
|
|
@@ -279,26 +795,125 @@ class FileTransferManager {
|
|
|
279
795
|
stage: "transport",
|
|
280
796
|
retryable: false,
|
|
281
797
|
peerId,
|
|
798
|
+
cause: error,
|
|
282
799
|
});
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
800
|
+
if (!transfer.fromRemoteError &&
|
|
801
|
+
transferError.code !== "FILE_TRANSFER_CANCELLED") {
|
|
802
|
+
this.trySendControl(peerId, {
|
|
803
|
+
__aves: exports.FILE_PROTOCOL,
|
|
804
|
+
kind: "file-error",
|
|
805
|
+
transferId: transfer.transferId,
|
|
806
|
+
message: transferError.message,
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
if (!transfer.failedEmitted) {
|
|
810
|
+
transfer.failedEmitted = true;
|
|
811
|
+
this.emitFailed(peerId, transfer, transferError);
|
|
812
|
+
}
|
|
290
813
|
throw transferError;
|
|
291
814
|
}
|
|
292
815
|
finally {
|
|
293
816
|
this.clearReadyResolver(peerId);
|
|
294
817
|
this.clearCompletionResolver(peerId);
|
|
295
818
|
this.outgoingTransfers.delete(peerId);
|
|
819
|
+
this.pendingOutgoingPeers.delete(peerId);
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
/**
|
|
823
|
+
* Pause sending when RTCDataChannel bufferedAmount exceeds triggerThreshold
|
|
824
|
+
* until it drains down to lowWaterMark.
|
|
825
|
+
*/
|
|
826
|
+
waitForBackpressure(peerId, fileChannel, transfer, triggerThreshold = this.highWaterMark) {
|
|
827
|
+
if (typeof fileChannel.bufferedAmount !== "number" ||
|
|
828
|
+
fileChannel.bufferedAmount <= triggerThreshold) {
|
|
829
|
+
return Promise.resolve();
|
|
296
830
|
}
|
|
831
|
+
return new Promise((resolve, reject) => {
|
|
832
|
+
try {
|
|
833
|
+
fileChannel.bufferedAmountLowThreshold = this.lowWaterMark;
|
|
834
|
+
}
|
|
835
|
+
catch {
|
|
836
|
+
// Some mock or older implementations do not allow setting the threshold.
|
|
837
|
+
}
|
|
838
|
+
let settled = false;
|
|
839
|
+
let pollInterval = null;
|
|
840
|
+
const previousLowHandler = fileChannel.onbufferedamountlow;
|
|
841
|
+
const cleanup = () => {
|
|
842
|
+
if (pollInterval !== null) {
|
|
843
|
+
clearInterval(pollInterval);
|
|
844
|
+
pollInterval = null;
|
|
845
|
+
}
|
|
846
|
+
if (fileChannel.onbufferedamountlow === handleLow) {
|
|
847
|
+
fileChannel.onbufferedamountlow = previousLowHandler ?? null;
|
|
848
|
+
}
|
|
849
|
+
};
|
|
850
|
+
const finish = () => {
|
|
851
|
+
if (settled) {
|
|
852
|
+
return;
|
|
853
|
+
}
|
|
854
|
+
settled = true;
|
|
855
|
+
cleanup();
|
|
856
|
+
resolve();
|
|
857
|
+
};
|
|
858
|
+
const fail = (err) => {
|
|
859
|
+
if (settled) {
|
|
860
|
+
return;
|
|
861
|
+
}
|
|
862
|
+
settled = true;
|
|
863
|
+
cleanup();
|
|
864
|
+
reject(err);
|
|
865
|
+
};
|
|
866
|
+
const checkState = () => {
|
|
867
|
+
if (transfer.cancelled) {
|
|
868
|
+
fail(new AvesError_1.AvesError({
|
|
869
|
+
message: `File transfer ${transfer.transferId} cancelled`,
|
|
870
|
+
code: "FILE_TRANSFER_CANCELLED",
|
|
871
|
+
stage: "transport",
|
|
872
|
+
retryable: false,
|
|
873
|
+
peerId,
|
|
874
|
+
}));
|
|
875
|
+
return;
|
|
876
|
+
}
|
|
877
|
+
if (fileChannel.readyState !== "open") {
|
|
878
|
+
fail(new AvesError_1.AvesError({
|
|
879
|
+
message: `File channel closed while draining buffer for ${peerId}`,
|
|
880
|
+
code: "WEBRTC_DATACHANNEL_FAILED",
|
|
881
|
+
stage: "transport",
|
|
882
|
+
retryable: true,
|
|
883
|
+
peerId,
|
|
884
|
+
}));
|
|
885
|
+
return;
|
|
886
|
+
}
|
|
887
|
+
if (fileChannel.bufferedAmount <= this.lowWaterMark) {
|
|
888
|
+
finish();
|
|
889
|
+
}
|
|
890
|
+
};
|
|
891
|
+
const handleLow = () => {
|
|
892
|
+
previousLowHandler?.call(fileChannel, new Event("bufferedamountlow"));
|
|
893
|
+
checkState();
|
|
894
|
+
};
|
|
895
|
+
fileChannel.onbufferedamountlow = handleLow;
|
|
896
|
+
// Fallback poll in case a runtime does not fire onbufferedamountlow reliably.
|
|
897
|
+
pollInterval = setInterval(checkState, 25);
|
|
898
|
+
pollInterval.unref?.();
|
|
899
|
+
checkState();
|
|
900
|
+
});
|
|
297
901
|
}
|
|
298
902
|
sendControl(peerId, message) {
|
|
299
903
|
const dataChannel = this.getMessageChannel(peerId);
|
|
300
904
|
dataChannel.send(JSON.stringify(message));
|
|
301
905
|
}
|
|
906
|
+
trySendControl(peerId, message) {
|
|
907
|
+
try {
|
|
908
|
+
const dataChannel = this.getMessageChannel(peerId);
|
|
909
|
+
if (dataChannel.readyState === "open") {
|
|
910
|
+
dataChannel.send(JSON.stringify(message));
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
catch {
|
|
914
|
+
// Never mask original transfer failures if control channel is already gone.
|
|
915
|
+
}
|
|
916
|
+
}
|
|
302
917
|
awaitReady(peerId, transferId) {
|
|
303
918
|
return new Promise((resolve, reject) => {
|
|
304
919
|
const timeoutId = setTimeout(() => {
|
|
@@ -310,7 +925,8 @@ class FileTransferManager {
|
|
|
310
925
|
retryable: true,
|
|
311
926
|
peerId,
|
|
312
927
|
}));
|
|
313
|
-
},
|
|
928
|
+
}, this.readyTimeoutMs);
|
|
929
|
+
unrefTimer(timeoutId);
|
|
314
930
|
this.readyResolvers.set(peerId, {
|
|
315
931
|
transferId,
|
|
316
932
|
resolve,
|
|
@@ -330,7 +946,8 @@ class FileTransferManager {
|
|
|
330
946
|
retryable: true,
|
|
331
947
|
peerId,
|
|
332
948
|
}));
|
|
333
|
-
},
|
|
949
|
+
}, this.completeTimeoutMs);
|
|
950
|
+
unrefTimer(timeoutId);
|
|
334
951
|
this.completionResolvers.set(peerId, {
|
|
335
952
|
transferId,
|
|
336
953
|
resolve,
|
|
@@ -342,12 +959,14 @@ class FileTransferManager {
|
|
|
342
959
|
emitStarted(peerId, info) {
|
|
343
960
|
this.fileTransferStartedCallbacks.forEach((callback) => callback(peerId, info));
|
|
344
961
|
}
|
|
345
|
-
emitProgress(peerId, info, bytesTransferred) {
|
|
962
|
+
emitProgress(peerId, info, bytesTransferred, isCompleted = true) {
|
|
346
963
|
const progress = {
|
|
347
964
|
...info,
|
|
348
965
|
bytesTransferred: Math.min(bytesTransferred, info.size),
|
|
349
966
|
progress: info.size === 0
|
|
350
|
-
?
|
|
967
|
+
? isCompleted
|
|
968
|
+
? 100
|
|
969
|
+
: 0
|
|
351
970
|
: Math.min(100, (bytesTransferred / info.size) * 100),
|
|
352
971
|
};
|
|
353
972
|
this.fileTransferProgressCallbacks.forEach((callback) => callback(peerId, progress));
|
|
@@ -365,9 +984,11 @@ function isFileControlMessage(message) {
|
|
|
365
984
|
return record.__aves === exports.FILE_PROTOCOL && typeof record.kind === "string";
|
|
366
985
|
}
|
|
367
986
|
function validateChunkSize(chunkSize) {
|
|
368
|
-
if (!Number.isInteger(chunkSize) ||
|
|
987
|
+
if (!Number.isInteger(chunkSize) ||
|
|
988
|
+
chunkSize <= 0 ||
|
|
989
|
+
chunkSize > exports.MAX_FILE_CHUNK_SIZE) {
|
|
369
990
|
throw new AvesError_1.AvesError({
|
|
370
|
-
message:
|
|
991
|
+
message: `chunkSize must be a positive integer <= ${exports.MAX_FILE_CHUNK_SIZE} bytes`,
|
|
371
992
|
code: "INVALID_MESSAGE_FORMAT",
|
|
372
993
|
stage: "protocol",
|
|
373
994
|
retryable: false,
|
|
@@ -375,9 +996,26 @@ function validateChunkSize(chunkSize) {
|
|
|
375
996
|
}
|
|
376
997
|
return chunkSize;
|
|
377
998
|
}
|
|
999
|
+
async function computeBlobSha256(blob) {
|
|
1000
|
+
try {
|
|
1001
|
+
const subtle = globalThis.crypto?.subtle;
|
|
1002
|
+
if (!subtle || typeof subtle.digest !== "function") {
|
|
1003
|
+
return undefined;
|
|
1004
|
+
}
|
|
1005
|
+
const buffer = await blob.arrayBuffer();
|
|
1006
|
+
const digest = await subtle.digest("SHA-256", buffer);
|
|
1007
|
+
return Array.from(new Uint8Array(digest))
|
|
1008
|
+
.map((byte) => byte.toString(16).padStart(2, "0"))
|
|
1009
|
+
.join("");
|
|
1010
|
+
}
|
|
1011
|
+
catch {
|
|
1012
|
+
return undefined;
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
const utf8Encoder = typeof TextEncoder !== "undefined" ? new TextEncoder() : null;
|
|
378
1016
|
function getChunkSize(data) {
|
|
379
1017
|
if (typeof data === "string") {
|
|
380
|
-
return data.length;
|
|
1018
|
+
return utf8Encoder ? utf8Encoder.encode(data).byteLength : data.length;
|
|
381
1019
|
}
|
|
382
1020
|
if (data instanceof ArrayBuffer) {
|
|
383
1021
|
return data.byteLength;
|
|
@@ -395,5 +1033,14 @@ function getBlobLastModified(blob) {
|
|
|
395
1033
|
: undefined;
|
|
396
1034
|
}
|
|
397
1035
|
function generateTransferId() {
|
|
1036
|
+
if (typeof globalThis.crypto?.randomUUID === "function") {
|
|
1037
|
+
return `file-${globalThis.crypto.randomUUID()}`;
|
|
1038
|
+
}
|
|
1039
|
+
if (typeof globalThis.crypto?.getRandomValues === "function") {
|
|
1040
|
+
const bytes = new Uint8Array(8);
|
|
1041
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
1042
|
+
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
1043
|
+
return `file-${Date.now()}-${hex}`;
|
|
1044
|
+
}
|
|
398
1045
|
return `file-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
|
399
1046
|
}
|