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