-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_transfer.rs
More file actions
1667 lines (1487 loc) · 61.9 KB
/
Copy pathfile_transfer.rs
File metadata and controls
1667 lines (1487 loc) · 61.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Platform-agnostic secure file transfer — web-compatible ("SBWT") wire format.
//
// This module owns the *protocol* of sending and receiving files over an
// already-established secure channel. It is deliberately free of any I/O or
// transport: the platform layer (Tauri webview, native mobile, ...) picks,
// reads and saves files, and moves the JSON protocol messages produced here
// over the WebRTC data channel.
//
// # Wire compatibility
//
// The message shapes below are a *contract* with the SecureBit web client
// (`EnhancedSecureFileTransfer.js`) and with the desktop client, which speaks
// the same protocol from its webview. Do not rename or restructure anything
// here to suit a platform: a field that differs by one character makes this
// peer unable to exchange files with every existing client.
//
// The wrappers travel as PLAINTEXT JSON on the data channel — only the chunk
// payload is encrypted. That is what the web does, and matching it is why an
// iOS peer is indistinguishable from a browser peer on the wire.
//
// Per-file key (see [`crate::file_crypto`], which is verified against reference
// vectors produced by the browser's WebCrypto):
//
// fileKey = SHA-256( utf8(keyFingerprint) ‖ sessionSalt ‖ fileSalt(32) ‖ utf8(fileId) )
//
// Every chunk is AES-256-GCM under that key with a fresh random 12-byte nonce.
// Deriving per file — rather than using the session key directly — means a
// single leaked file key never exposes the chat or any other transfer.
//
// Protocol messages (all JSON, camelCase to match the JS side):
// file_transfer_start { fileId, fileName, fileSize, fileType, fileHash,
// totalChunks, chunkSize, salt[32], timestamp,
// version, isVoice?, voice? }
// file_transfer_response { fileId, accepted, error?, timestamp }
// file_chunk { fileId, chunkIndex, totalChunks, nonce[12],
// encryptedDataB64, chunkSize, timestamp }
// chunk_confirmation { fileId, chunkIndex, timestamp }
// file_chunk_request { fileId, missing[], timestamp } (loss recovery)
// file_transfer_complete { fileId, success, error?, timestamp }
// file_transfer_error { fileId, error, timestamp }
use crate::file_crypto::{decrypt_chunk, derive_file_key, encrypt_chunk};
use base64::{engine::general_purpose, Engine as _};
use rand::Rng;
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::time::Instant;
/// Raw bytes per chunk before encryption. 16 KB matches the web's `CHUNK_SIZE`
/// and keeps the on-the-wire (AES-GCM + Base64) message near 22 KB, well under
/// the 64 KB SCTP message-size floor some peers enforce.
pub const CHUNK_SIZE: usize = 16 * 1024;
/// Largest chunk we will *accept*. Older peers may use a bigger chunk than we
/// send, so the receive path is deliberately more permissive than the send path.
pub const MAX_RECEIVE_CHUNK: usize = 64 * 1024;
/// Hard ceiling on a single file, matching the web client.
pub const MAX_FILE_SIZE: usize = 100 * 1024 * 1024;
/// Concurrency caps, matching the web client.
pub const MAX_CONCURRENT_TRANSFERS: usize = 3;
pub const MAX_PENDING_INCOMING: usize = 3;
/// Protocol version stamped on `file_transfer_start`.
pub const PROTOCOL_VERSION: &str = "2.0";
/// Most chunks a receiver will name in one `file_chunk_request`, and most a
/// sender will honour from one. Bounds the work a peer can ask for per message.
const MAX_MISSING_PER_REQUEST: usize = 256;
const MAX_RETRANSMIT_PER_REQUEST: usize = 512;
// ---------------------------------------------------------------------------
// key material
// ---------------------------------------------------------------------------
/// The session-derived inputs every per-file key is built from.
///
/// Both values come from the completed handshake: the caller reads them off the
/// session rather than the wire, so a peer cannot steer our key derivation.
#[derive(Clone)]
pub struct TransferCrypto {
/// Colon-hex "safety number" both peers computed independently.
pub key_fingerprint: String,
/// The 64-byte session salt agreed during the handshake.
pub session_salt: Vec<u8>,
}
impl TransferCrypto {
pub fn new(key_fingerprint: String, session_salt: Vec<u8>) -> Result<Self, String> {
if key_fingerprint.is_empty() {
return Err("Session crypto not ready (no key fingerprint)".to_string());
}
if session_salt.is_empty() {
return Err("Session crypto not ready (no session salt)".to_string());
}
Ok(Self { key_fingerprint, session_salt })
}
fn file_key(&self, file_salt: &[u8], file_id: &str) -> [u8; 32] {
derive_file_key(&self.key_fingerprint, &self.session_salt, file_salt, file_id)
}
}
// ---------------------------------------------------------------------------
// file-type policy (byte-for-byte the web's FILE_TYPE_RESTRICTIONS)
// ---------------------------------------------------------------------------
/// One allow-listed category. The *extension* is the security boundary; MIME is
/// advisory, because browsers and operating systems disagree on it and it is
/// frequently absent.
struct TypeRule {
extensions: &'static [&'static str],
mime_types: &'static [&'static str],
max_size: usize,
category: &'static str,
description: &'static str,
}
const TYPE_RULES: &[TypeRule] = &[
TypeRule {
extensions: &[".pdf"],
mime_types: &["application/pdf", "application/x-pdf", "application/acrobat"],
max_size: 50 * 1024 * 1024,
category: "PDF",
description: "PDF",
},
TypeRule {
extensions: &[".txt"],
mime_types: &["text/plain", "application/txt"],
max_size: 10 * 1024 * 1024,
category: "Plain text",
description: "TXT",
},
TypeRule {
extensions: &[".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".ico"],
mime_types: &[
"image/jpeg", "image/jpg", "image/pjpeg", "image/png", "image/gif",
"image/webp", "image/bmp", "image/x-windows-bmp", "image/x-icon",
"image/vnd.microsoft.icon",
],
max_size: 25 * 1024 * 1024,
category: "Images",
description: "JPG, JPEG, PNG, GIF, WEBP, BMP, ICO",
},
TypeRule {
extensions: &[".zip"],
mime_types: &[
"application/zip", "application/x-zip", "application/x-zip-compressed",
"multipart/x-zip",
],
max_size: 100 * 1024 * 1024,
category: "Archives",
description: "ZIP",
},
TypeRule {
extensions: &[".webm", ".ogg", ".oga", ".opus", ".m4a", ".mp4", ".mp3", ".wav"],
mime_types: &[
"audio/webm", "audio/ogg", "audio/opus", "audio/mp4", "audio/mpeg",
"audio/mp3", "audio/wav", "audio/x-m4a", "audio/aac",
],
max_size: 20 * 1024 * 1024,
category: "Voice",
description: "Voice messages",
},
];
/// Extensions refused outright, regardless of category. Executable and
/// active-content formats: delivering one to a peer's disk is the payload half
/// of most social-engineering attacks.
const BLOCKED_EXTENSIONS: &[&str] = &[
".exe", ".bat", ".cmd", ".sh", ".js", ".msi", ".dmg", ".app", ".jar", ".scr",
".ps1", ".vbs", ".html", ".svg",
];
/// MIME values that carry no information, so they never count as a mismatch.
const GENERIC_MIME: &[&str] = &["application/octet-stream", "application/binary"];
const UNSUPPORTED_DESCRIPTION: &str =
"Allowed: JPG, JPEG, PNG, GIF, WEBP, BMP, ICO, PDF, TXT, ZIP";
/// The lowercase extension of `name`, including the dot ("" when there is none).
fn extension_of(name: &str) -> String {
let lower = name.to_lowercase();
match lower.rfind('.') {
Some(index) => lower[index..].to_string(),
None => String::new(),
}
}
struct ResolvedType {
max_size: usize,
category: &'static str,
description: &'static str,
allowed: bool,
extension: String,
}
/// Resolve a file to its allow-list category, mirroring the web's `getFileType`.
///
/// A blatantly foreign MIME is treated as a spoofing signal and rejected, but an
/// absent or generic one is tolerated — that is the common, honest case.
fn resolve_type(name: &str, mime: &str) -> ResolvedType {
let extension = extension_of(name);
let mime = mime.to_lowercase();
let known_mime: bool = TYPE_RULES
.iter()
.any(|rule| rule.mime_types.contains(&mime.as_str()));
for rule in TYPE_RULES {
if !rule.extensions.contains(&extension.as_str()) {
continue;
}
if mime.is_empty() || GENERIC_MIME.contains(&mime.as_str()) || known_mime {
return ResolvedType {
max_size: rule.max_size,
category: rule.category,
description: rule.description,
allowed: true,
extension,
};
}
}
ResolvedType {
max_size: MAX_FILE_SIZE,
category: "Unsupported",
description: UNSUPPORTED_DESCRIPTION,
allowed: false,
extension,
}
}
fn format_size(bytes: usize) -> String {
if bytes >= 1024 * 1024 {
format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
} else if bytes >= 1024 {
format!("{:.1} KB", bytes as f64 / 1024.0)
} else {
format!("{} B", bytes)
}
}
/// Validate a file against the allow-list. Applied to *both* directions so a
/// file we accept locally is never rejected by the peer, and vice versa.
fn validate_file(name: &str, size: usize, mime: &str) -> Result<(), String> {
let resolved = resolve_type(name, mime);
let mut errors: Vec<String> = Vec::new();
if BLOCKED_EXTENSIONS.contains(&resolved.extension.as_str()) {
errors.push(format!(
"File rejected: {} files are not allowed for security reasons.",
resolved.extension
));
}
if size > resolved.max_size {
errors.push(format!(
"File size ({}) exceeds maximum allowed for {} ({})",
format_size(size),
resolved.category,
format_size(resolved.max_size)
));
}
if !resolved.allowed && !BLOCKED_EXTENSIONS.contains(&resolved.extension.as_str()) {
errors.push(format!(
"File rejected: unsupported file type. Supported types: {}",
resolved.description
));
}
if size > MAX_FILE_SIZE {
errors.push(format!(
"File size ({}) exceeds general limit ({})",
format_size(size),
format_size(MAX_FILE_SIZE)
));
}
if errors.is_empty() {
Ok(())
} else {
Err(errors.join(". "))
}
}
/// True for C0 control characters and DEL — never legitimate in a file name and
/// the classic way to disguise one in a UI.
fn has_control_chars(text: &str) -> bool {
text.chars().any(|c| (c as u32) < 0x20 || (c as u32) == 0x7F)
}
/// Reduce a peer-supplied name to something safe to display and to write.
///
/// Note: the web additionally applies Unicode NFKC here. We deliberately do not
/// pull in a normalisation crate for it — the security-relevant cases (control
/// characters, path separators, empty and dot names) are rejected outright by
/// [`validate_incoming_name`], and NFKC beyond that is a display nicety.
fn normalise_name(name: &str) -> String {
let cleaned: String = name
.chars()
.filter(|c| (*c as u32) >= 0x20 && (*c as u32) != 0x7F)
.map(|c| if c == '\\' || c == '/' { '_' } else { c })
.collect();
cleaned.trim().chars().take(255).collect()
}
/// Reject a peer-supplied name that is dangerous rather than merely ugly, and
/// return the display form of a safe one.
fn validate_incoming_name(raw: &str) -> Result<String, String> {
let display = normalise_name(raw);
let dangerous = raw.is_empty()
|| raw != raw.trim()
|| has_control_chars(raw)
|| raw.contains('\\')
|| raw.contains('/')
|| raw == "."
|| raw == ".."
|| display.is_empty();
if dangerous {
Err("Dangerous file name".to_string())
} else {
Ok(display)
}
}
// ---------------------------------------------------------------------------
// rate limiting (web RateLimiter, same windows)
// ---------------------------------------------------------------------------
/// Sliding-window counter. Bounds how fast a peer can make us do expensive work
/// (offers that allocate state, chunks that cost a decryption each).
struct RateLimiter {
hits: Vec<Instant>,
max_requests: usize,
window_ms: u128,
}
impl RateLimiter {
fn new(max_requests: usize, window_ms: u128) -> Self {
Self { hits: Vec::new(), max_requests, window_ms }
}
fn allow(&mut self) -> bool {
let now = Instant::now();
let window = self.window_ms;
self.hits
.retain(|hit| now.duration_since(*hit).as_millis() < window);
if self.hits.len() >= self.max_requests {
return false;
}
self.hits.push(now);
true
}
}
// ---------------------------------------------------------------------------
// transfer state
// ---------------------------------------------------------------------------
/// Outgoing (sender) transfer state.
struct SendingState {
data: Vec<u8>,
file_key: [u8; 32],
total_chunks: usize,
next_chunk: usize,
accepted: bool,
confirmed_chunks: usize,
}
/// An incoming offer that has passed validation and is waiting for the local
/// user's consent. Kept apart from `receiving` so no chunk is ever stored — let
/// alone decrypted — before a human agreed to the transfer.
struct PendingOffer {
file_name: String,
file_type: String,
file_size: usize,
total_chunks: usize,
file_hash: String,
file_salt: Vec<u8>,
is_voice: bool,
voice: Option<Value>,
}
/// Incoming (receiver) transfer state.
struct ReceivingState {
file_name: String,
file_type: String,
file_size: usize,
total_chunks: usize,
file_hash: String,
file_key: [u8; 32],
chunks: HashMap<usize, Vec<u8>>,
received_count: usize,
is_voice: bool,
voice: Option<Value>,
/// Guards assembly so a received file is delivered exactly once.
assembled: bool,
/// Per-transfer chunk budget, on top of the manager-wide one.
chunk_limiter: RateLimiter,
}
/// A file that finished assembling and is waiting to be collected.
///
/// The bytes are handed over by [`FileTransferManager::take_assembled`] rather
/// than embedded in the completion event: at up to 100 MB, base64-ing a file
/// into a JSON event would cost several multiples of its size in peak memory.
pub struct AssembledFile {
pub file_name: String,
pub file_type: String,
pub is_voice: bool,
pub voice: Option<Value>,
pub data: Vec<u8>,
}
/// Owns all in-flight transfers in both directions.
pub struct FileTransferManager {
sending: HashMap<String, SendingState>,
receiving: HashMap<String, ReceivingState>,
pending: HashMap<String, PendingOffer>,
assembled: HashMap<String, AssembledFile>,
send_limiter: RateLimiter,
offer_limiter: RateLimiter,
chunk_limiter: RateLimiter,
}
impl FileTransferManager {
pub fn new() -> Self {
Self {
sending: HashMap::new(),
receiving: HashMap::new(),
pending: HashMap::new(),
assembled: HashMap::new(),
// Windows copied from the web client.
send_limiter: RateLimiter::new(10, 60_000), // outgoing files / min
offer_limiter: RateLimiter::new(5, 60_000), // incoming offers / min
chunk_limiter: RateLimiter::new(60_000, 60_000), // all chunks (~16 MB/s)
}
}
/// Drop all transfer state (e.g. on disconnect).
pub fn clear(&mut self) {
self.sending.clear();
self.receiving.clear();
self.pending.clear();
self.assembled.clear();
}
// ---- Sender ---------------------------------------------------------
/// Register an outgoing file and produce the `file_transfer_start` message
/// the platform should send to the peer. No chunk is produced until the peer
/// accepts (see [`next_chunk`]).
///
/// `voice` carries the web's `{ dur, bars }` descriptor for a voice note; it
/// is passed through untouched so the peer can draw the waveform before the
/// audio has finished arriving.
#[allow(clippy::too_many_arguments)]
pub fn prepare_outgoing(
&mut self,
file_id: String,
file_name: String,
file_type: String,
data: Vec<u8>,
is_voice: bool,
voice: Option<Value>,
crypto: &TransferCrypto,
) -> Result<Value, String> {
if data.is_empty() {
return Err("Cannot send an empty file".to_string());
}
if self.sending.len() >= MAX_CONCURRENT_TRANSFERS {
return Err("Maximum concurrent transfers reached".to_string());
}
if self.sending.contains_key(&file_id) {
return Err("A transfer with this id is already in flight".to_string());
}
if !self.send_limiter.allow() {
return Err(
"Rate limit exceeded. Please wait before sending another file.".to_string()
);
}
// Hold ourselves to the same policy we enforce on the peer, so we never
// offer a file the other side is obliged to refuse.
validate_file(&file_name, data.len(), &file_type)?;
let mut file_salt = [0u8; 32];
rand::thread_rng().fill(&mut file_salt);
let file_key = crypto.file_key(&file_salt, &file_id);
let total_chunks = data.len().div_ceil(CHUNK_SIZE).max(1);
let file_hash = hex::encode(Sha256::digest(&data));
let mut start = json!({
"type": "file_transfer_start",
"fileId": file_id,
"fileName": file_name,
"fileSize": data.len(),
"fileType": file_type,
"fileHash": file_hash,
"totalChunks": total_chunks,
"chunkSize": CHUNK_SIZE,
"salt": file_salt.to_vec(),
"timestamp": now_ms(),
"version": PROTOCOL_VERSION,
});
if is_voice {
start["isVoice"] = json!(true);
if let Some(descriptor) = voice {
start["voice"] = descriptor;
}
}
self.sending.insert(
file_id,
SendingState {
data,
file_key,
total_chunks,
next_chunk: 0,
accepted: false,
confirmed_chunks: 0,
},
);
Ok(start)
}
/// Produce the next `file_chunk` message for an accepted outgoing transfer.
/// Returns `Ok(None)` once there is nothing left to send.
///
/// A transfer that has *disappeared* also yields `Ok(None)` rather than an
/// error, because that is a normal race rather than a fault: the receiver
/// confirms the last chunk with `file_transfer_complete`, which drops the
/// send state, and that reply can land while the caller's pump loop is still
/// going. The web client bails out of its pump the same way. Callers stop
/// either way, so nothing is sent that should not be — this only decides
/// whether the user is shown a spurious failure.
pub fn next_chunk(&mut self, file_id: &str) -> Result<Option<Value>, String> {
let index = {
let Some(state) = self.sending.get(file_id) else {
return Ok(None);
};
if !state.accepted {
return Err("Transfer not accepted by peer yet".to_string());
}
if state.next_chunk >= state.total_chunks {
return Ok(None);
}
state.next_chunk
};
let message = self.build_chunk(file_id, index)?;
if let Some(state) = self.sending.get_mut(file_id) {
state.next_chunk = index + 1;
}
Ok(Some(message))
}
/// Re-encrypt and re-emit one chunk the receiver said it never got.
///
/// Each retransmission gets a *fresh* nonce: reusing a nonce with the same
/// key is the one mistake that breaks AES-GCM outright.
pub fn chunk_at(&mut self, file_id: &str, index: usize) -> Result<Option<Value>, String> {
let known = match self.sending.get(file_id) {
Some(state) => {
if !state.accepted || index >= state.total_chunks {
return Ok(None);
}
true
}
None => false,
};
if !known {
return Ok(None);
}
self.build_chunk(file_id, index).map(Some)
}
fn build_chunk(&mut self, file_id: &str, index: usize) -> Result<Value, String> {
let state = self
.sending
.get(file_id)
.ok_or_else(|| "Unknown outgoing transfer".to_string())?;
let start = index * CHUNK_SIZE;
let end = ((index + 1) * CHUNK_SIZE).min(state.data.len());
let plaintext = &state.data[start..end];
let mut nonce = [0u8; 12];
rand::thread_rng().fill(&mut nonce);
let ciphertext = encrypt_chunk(&state.file_key, &nonce, plaintext)?;
Ok(json!({
"type": "file_chunk",
"fileId": file_id,
"chunkIndex": index,
"totalChunks": state.total_chunks,
"nonce": nonce.to_vec(),
"encryptedDataB64": general_purpose::STANDARD.encode(&ciphertext),
"chunkSize": plaintext.len(),
"timestamp": now_ms(),
}))
}
/// How many chunks of an outgoing transfer have been produced so far.
pub fn send_progress(&self, file_id: &str) -> Option<(usize, usize, usize)> {
self.sending
.get(file_id)
.map(|s| (s.next_chunk, s.confirmed_chunks, s.total_chunks))
}
// ---- Receiver consent ----------------------------------------------
/// Accept an incoming offer: derive the per-file key, start receiving, and
/// return the `file_transfer_response` to send so the sender starts
/// streaming.
pub fn accept(&mut self, file_id: &str, crypto: &TransferCrypto) -> Result<Value, String> {
let offer = self
.pending
.remove(file_id)
.ok_or_else(|| "Unknown incoming transfer".to_string())?;
let file_key = crypto.file_key(&offer.file_salt, file_id);
self.receiving.insert(
file_id.to_string(),
ReceivingState {
file_name: offer.file_name,
file_type: offer.file_type,
file_size: offer.file_size,
total_chunks: offer.total_chunks,
file_hash: offer.file_hash,
file_key,
chunks: HashMap::new(),
received_count: 0,
is_voice: offer.is_voice,
voice: offer.voice,
assembled: false,
// ~8 MB/s per transfer, matching the web.
chunk_limiter: RateLimiter::new(30_000, 60_000),
},
);
Ok(json!({
"type": "file_transfer_response",
"fileId": file_id,
"accepted": true,
"timestamp": now_ms(),
}))
}
/// Reject an incoming offer. Returns the `file_transfer_response` to send
/// back, and forgets the transfer.
pub fn reject(&mut self, file_id: &str, reason: &str) -> Result<Value, String> {
self.pending.remove(file_id);
self.receiving.remove(file_id);
Ok(json!({
"type": "file_transfer_response",
"fileId": file_id,
"accepted": false,
"error": reason,
"timestamp": now_ms(),
}))
}
/// Forget any state for a transfer (cancel/cleanup), either direction.
pub fn cancel(&mut self, file_id: &str) {
self.sending.remove(file_id);
self.receiving.remove(file_id);
self.pending.remove(file_id);
self.assembled.remove(file_id);
}
/// Take the assembled bytes of a completed incoming transfer, exactly once.
pub fn take_assembled(&mut self, file_id: &str) -> Option<AssembledFile> {
self.assembled.remove(file_id)
}
// ---- Loss recovery --------------------------------------------------
/// Chunk indices an in-flight incoming transfer is still missing, capped so
/// one request never names an unbounded list.
pub fn missing_chunks(&self, file_id: &str) -> Vec<usize> {
let Some(state) = self.receiving.get(file_id) else {
return Vec::new();
};
let mut missing = Vec::new();
for index in 0..state.total_chunks {
if missing.len() >= MAX_MISSING_PER_REQUEST {
break;
}
if !state.chunks.contains_key(&index) {
missing.push(index);
}
}
missing
}
/// Build the `file_chunk_request` for whatever an incoming transfer still
/// lacks. `None` when nothing is missing (or the transfer is unknown).
///
/// This is what makes a transfer survive a connection blip: without it, a
/// single dropped chunk leaves the receiver waiting forever.
pub fn request_missing(&self, file_id: &str) -> Option<Value> {
let missing = self.missing_chunks(file_id);
if missing.is_empty() {
return None;
}
Some(json!({
"type": "file_chunk_request",
"fileId": file_id,
"missing": missing,
"timestamp": now_ms(),
}))
}
/// Build a `file_transfer_error` to tell the peer we are giving up.
pub fn error_message(file_id: &str, reason: &str) -> Value {
json!({
"type": "file_transfer_error",
"fileId": file_id,
"error": reason,
"timestamp": now_ms(),
})
}
// ---- Unified incoming message handler ------------------------------
/// Process any incoming file-protocol message (both directions).
///
/// Returns a JSON object describing what happened, with these `kind`s:
/// "request" offer awaiting consent { fileId, fileName, fileSize, fileType, isVoice, voice, autoAccept }
/// "response" peer accepted/rejected { fileId, accepted, error? }
/// "progress" a chunk was received { fileId, received, total }
/// "complete" file received+verified { fileId, fileName, fileType, fileSize, isVoice, voice }
/// "ack" peer confirmed a chunk { fileId, confirmed, total }
/// "retransmit" peer wants chunks back { fileId, missing }
/// "sent" peer finished receiving { fileId, success, error? }
/// "error" transfer failed { fileId, message }
/// "ignored" duplicate/irrelevant { fileId }
///
/// Any result may carry a `"send"` array of messages the platform must
/// transmit back to the peer, and a `"take"` flag meaning the assembled file
/// is ready to be collected with [`take_assembled`].
///
/// No session crypto is needed here: an incoming transfer's key is derived
/// once, at [`accept`], and held in the transfer's own state.
pub fn handle_incoming(&mut self, message: &Value) -> Result<Value, String> {
let msg_type = message
.get("type")
.and_then(|v| v.as_str())
.ok_or_else(|| "Message missing 'type'".to_string())?;
match msg_type {
"file_transfer_start" => self.on_start(message),
"file_transfer_response" => self.on_response(message),
"file_chunk" => self.on_chunk(message),
"chunk_confirmation" => self.on_chunk_confirmation(message),
"file_chunk_request" => self.on_chunk_request(message),
"file_transfer_complete" => self.on_transfer_complete(message),
"file_transfer_error" => self.on_transfer_error(message),
other => Err(format!("Unknown file message type: {}", other)),
}
}
fn on_start(&mut self, message: &Value) -> Result<Value, String> {
let file_id = get_str(message, "fileId")?;
// Duplicate offer for a transfer we already know about: ignore.
if self.receiving.contains_key(&file_id) || self.pending.contains_key(&file_id) {
return Ok(json!({ "kind": "ignored", "fileId": file_id }));
}
if !self.offer_limiter.allow() {
return Err("Incoming file request rate limit exceeded".to_string());
}
if self.pending.len() >= MAX_PENDING_INCOMING {
return Err("Too many pending incoming file requests".to_string());
}
// Everything below is peer-controlled, so validate before allocating.
let refuse = |reason: &str| -> Value {
json!({
"kind": "error",
"fileId": file_id,
"message": reason,
"send": [json!({
"type": "file_transfer_response",
"fileId": file_id,
"accepted": false,
"error": reason,
"timestamp": now_ms(),
})],
})
};
let file_size = get_usize(message, "fileSize")?;
let total_chunks = get_usize(message, "totalChunks")?;
let chunk_size = get_usize(message, "chunkSize")?;
let file_hash = get_str(message, "fileHash")?;
let file_type = message
.get("fileType")
.and_then(|v| v.as_str())
.unwrap_or("application/octet-stream")
.to_string();
if file_size == 0 || file_size > MAX_FILE_SIZE {
return Ok(refuse("Invalid file size"));
}
if total_chunks == 0 {
return Ok(refuse("Invalid chunk count"));
}
if chunk_size == 0 || chunk_size > MAX_RECEIVE_CHUNK {
return Ok(refuse("Invalid chunk size"));
}
let file_salt = get_byte_array(message, "salt")?;
if file_salt.len() != 32 {
return Ok(refuse("Invalid salt"));
}
let raw_name = message
.get("fileName")
.and_then(|v| v.as_str())
.unwrap_or("");
let file_name = match validate_incoming_name(raw_name) {
Ok(name) => name,
Err(reason) => return Ok(refuse(&reason)),
};
if let Err(reason) = validate_file(&file_name, file_size, &file_type) {
return Ok(refuse(&reason));
}
let is_voice = message
.get("isVoice")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let voice = message.get("voice").cloned();
// Voice notes auto-accept and play inline, exactly like the web: a
// consent card for every spoken reply would make the feature unusable.
let auto_accept = is_voice || file_type.starts_with("audio/");
self.pending.insert(
file_id.clone(),
PendingOffer {
file_name: file_name.clone(),
file_type: file_type.clone(),
file_size,
total_chunks,
file_hash,
file_salt,
is_voice,
voice: voice.clone(),
},
);
Ok(json!({
"kind": "request",
"fileId": file_id,
"fileName": file_name,
"fileSize": file_size,
"fileType": file_type,
"isVoice": is_voice,
"voice": voice,
"autoAccept": auto_accept,
}))
}
fn on_response(&mut self, message: &Value) -> Result<Value, String> {
let file_id = get_str(message, "fileId")?;
let accepted = message
.get("accepted")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let error = message.get("error").and_then(|v| v.as_str()).map(str::to_owned);
if let Some(state) = self.sending.get_mut(&file_id) {
state.accepted = accepted;
if !accepted {
self.sending.remove(&file_id);
}
}
Ok(json!({
"kind": "response",
"fileId": file_id,
"accepted": accepted,
"error": error,
}))
}
fn on_chunk(&mut self, message: &Value) -> Result<Value, String> {
let file_id = get_str(message, "fileId")?;
let chunk_index = get_usize(message, "chunkIndex")?;
let declared_size = get_usize(message, "chunkSize")?;
let nonce = get_byte_array(message, "nonce")?;
// The web sends base64; much older peers sent a raw byte array. Accept
// both so an upgrade on one side never strands the other.
let ciphertext = match message.get("encryptedDataB64").and_then(|v| v.as_str()) {
Some(b64) => general_purpose::STANDARD
.decode(b64)
.map_err(|_| "Invalid chunk data encoding".to_string())?,
None => get_byte_array(message, "encryptedData")
.map_err(|_| "Missing encrypted data".to_string())?,
};
// A missing receiving state means the transfer already completed, was
// cancelled, or has not been consented to. A late chunk is benign.
let Some(state) = self.receiving.get_mut(&file_id) else {
return Ok(json!({ "kind": "ignored", "fileId": file_id }));
};
if state.assembled {
return Ok(json!({ "kind": "ignored", "fileId": file_id }));
}
if chunk_index >= state.total_chunks {
return Err(format!("Chunk index {} out of range", chunk_index));
}
// Idempotent: a re-sent chunk is acknowledged but not re-stored.
if state.chunks.contains_key(&chunk_index) {
return Ok(json!({
"kind": "ignored",
"fileId": file_id,
"send": [confirmation(&file_id, chunk_index)],
}));
}
if nonce.len() != 12 {
return Err("Invalid nonce length".to_string());
}
if declared_size > MAX_RECEIVE_CHUNK {
return Err("Chunk exceeds maximum size".to_string());
}
if !state.chunk_limiter.allow() || !self.chunk_limiter.allow() {
self.receiving.remove(&file_id);
return Ok(json!({
"kind": "error",
"fileId": file_id,
"message": "Incoming chunk rate limit exceeded",
}));
}
let state = self
.receiving
.get_mut(&file_id)
.ok_or_else(|| "Unknown incoming transfer".to_string())?;
let mut nonce12 = [0u8; 12];
nonce12.copy_from_slice(&nonce);
let plaintext = decrypt_chunk(&state.file_key, &nonce12, &ciphertext)?;
if plaintext.len() != declared_size {
return Err(format!(
"Chunk size mismatch: expected {}, got {}",
declared_size,
plaintext.len()
));
}
state.chunks.insert(chunk_index, plaintext);
state.received_count += 1;
if state.received_count < state.total_chunks {
return Ok(json!({
"kind": "progress",
"fileId": file_id,
"received": state.received_count,
"total": state.total_chunks,
"send": [confirmation(&file_id, chunk_index)],
}));
}
// All chunks present — assemble exactly once.
state.assembled = true;
match assemble(state) {
Ok(data) => {
let file_name = state.file_name.clone();
let file_type = state.file_type.clone();
let is_voice = state.is_voice;
let voice = state.voice.clone();
let file_size = data.len();
self.receiving.remove(&file_id);
self.assembled.insert(
file_id.clone(),
AssembledFile {
file_name: file_name.clone(),
file_type: file_type.clone(),
is_voice,
voice: voice.clone(),
data,
},
);
Ok(json!({
"kind": "complete",
"fileId": file_id,
"fileName": file_name,
"fileType": file_type,
"fileSize": file_size,
"isVoice": is_voice,
"voice": voice,