firecloud-cli 0.2.0

Command-line interface for FireCloud P2P messaging and file sharing
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
// Metadata-hiding private messaging system
// Innovation: Message padding, timing obfuscation, and metadata encryption
use anyhow::{anyhow, Context, Result};
use clap::Subcommand;
use colored::Colorize;
use libp2p::PeerId;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use std::time::Duration;
use chrono::{DateTime, Utc};
use rand::Rng;

use super::friend::FriendList;

// Network imports for sending messages over libp2p
use firecloud_net::{FireCloudNode, NodeConfig};

/// Fixed message size for metadata hiding (all messages padded to 1KB)
const MESSAGE_SIZE: usize = 1024;

/// Minimum random delay for timing obfuscation (milliseconds)
const MIN_DELAY_MS: u64 = 100;

/// Maximum random delay for timing obfuscation (milliseconds)
const MAX_DELAY_MS: u64 = 500;

#[derive(Debug, Subcommand)]
pub enum MessageCommand {
    /// Send a private message to a friend
    Send {
        /// The friend's name or peer ID
        friend: String,
        
        /// The message to send
        message: String,
    },
    
    /// Show inbox (received messages)
    Inbox {
        /// Show only messages from a specific friend
        #[arg(short, long)]
        from: Option<String>,
        
        /// Number of messages to show (default: 20)
        #[arg(short, long, default_value = "20")]
        limit: usize,
    },
    
    /// Show conversation with a specific friend
    Chat {
        /// The friend's name or peer ID
        friend: String,
        
        /// Number of messages to show (default: 50)
        #[arg(short, long, default_value = "50")]
        limit: usize,
    },
    
    /// Clear message history
    Clear {
        /// Clear messages with a specific friend
        friend: Option<String>,
        
        /// Confirm deletion
        #[arg(short, long)]
        yes: bool,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message {
    /// Message ID (random UUID for untraceability)
    pub id: String,
    
    /// Sender's peer ID
    pub from: PeerId,
    
    /// Recipient's peer ID
    pub to: PeerId,
    
    /// Encrypted message content (padded to MESSAGE_SIZE)
    pub content: Vec<u8>,
    
    /// Timestamp (UTC)
    pub timestamp: DateTime<Utc>,
    
    /// Delivery confirmation
    pub delivered: bool,
    
    /// Read confirmation
    pub read: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DecryptedMessage {
    pub id: String,
    pub from: PeerId,
    pub to: PeerId,
    pub content: String,
    pub timestamp: DateTime<Utc>,
    pub delivered: bool,
    pub read: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct MessageStore {
    /// All messages indexed by message ID
    pub messages: HashMap<String, Message>,
    
    /// Messages organized by peer (for quick lookups)
    pub by_peer: HashMap<PeerId, Vec<String>>, // peer_id -> message_ids
}

impl MessageStore {
    /// Load message store from disk
    pub fn load(data_dir: &PathBuf) -> Result<Self> {
        let messages_path = data_dir.join("messages.json");
        
        if !messages_path.exists() {
            return Ok(Self::default());
        }
        
        let data = fs::read_to_string(&messages_path)
            .context("Failed to read messages.json")?;
        
        let store: MessageStore = serde_json::from_str(&data)
            .context("Failed to parse messages.json")?;
        
        Ok(store)
    }
    
    /// Save message store to disk
    pub fn save(&self, data_dir: &PathBuf) -> Result<()> {
        fs::create_dir_all(data_dir)
            .context("Failed to create data directory")?;
        
        let messages_path = data_dir.join("messages.json");
        
        let data = serde_json::to_string_pretty(self)
            .context("Failed to serialize messages")?;
        
        fs::write(&messages_path, data)
            .context("Failed to write messages.json")?;
        
        Ok(())
    }
    
    /// Add a new message
    pub fn add_message(&mut self, message: Message) {
        let msg_id = message.id.clone();
        let peer_id = if message.from == self.get_local_peer_id() {
            message.to
        } else {
            message.from
        };
        
        self.messages.insert(msg_id.clone(), message);
        self.by_peer.entry(peer_id)
            .or_insert_with(Vec::new)
            .push(msg_id);
    }
    
    /// Get messages with a specific peer
    pub fn get_conversation(&self, peer_id: &PeerId, limit: usize) -> Vec<&Message> {
        if let Some(msg_ids) = self.by_peer.get(peer_id) {
            msg_ids.iter()
                .rev()
                .take(limit)
                .filter_map(|id| self.messages.get(id))
                .collect()
        } else {
            Vec::new()
        }
    }
    
    /// Get all received messages
    pub fn get_inbox(&self, limit: usize) -> Vec<&Message> {
        let local_peer_id = self.get_local_peer_id();
        
        let mut messages: Vec<&Message> = self.messages.values()
            .filter(|m| m.to == local_peer_id)
            .collect();
        
        messages.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));
        messages.into_iter().take(limit).collect()
    }
    
    /// Mark message as read
    pub fn mark_read(&mut self, message_id: &str) -> Result<()> {
        let message = self.messages.get_mut(message_id)
            .context("Message not found")?;
        message.read = true;
        Ok(())
    }
    
    /// Mark message as delivered
    pub fn mark_delivered(&mut self, message_id: &str) {
        if let Some(message) = self.messages.get_mut(message_id) {
            message.delivered = true;
        }
    }
    
    /// Clear messages with a peer
    pub fn clear_conversation(&mut self, peer_id: &PeerId) -> Result<usize> {
        if let Some(msg_ids) = self.by_peer.remove(peer_id) {
            let count = msg_ids.len();
            for msg_id in msg_ids {
                self.messages.remove(&msg_id);
            }
            Ok(count)
        } else {
            Ok(0)
        }
    }
    
    // TODO: Get from actual node
    fn get_local_peer_id(&self) -> PeerId {
        // Placeholder - in real implementation, get from running node
        PeerId::random()
    }
}

/// Encrypt message content with padding for metadata hiding
pub fn encrypt_message(content: &str, _recipient: &PeerId) -> Result<Vec<u8>> {
    // TODO: Implement ChaCha20-Poly1305 encryption with Double Ratchet
    // For now, just pad the message
    
    let bytes = content.as_bytes();
    
    if bytes.len() > MESSAGE_SIZE - 16 { // Reserve 16 bytes for auth tag
        anyhow::bail!("Message too long (max {} chars)", MESSAGE_SIZE - 16);
    }
    
    // Pad to fixed size for metadata hiding
    let mut padded = Vec::with_capacity(MESSAGE_SIZE);
    padded.extend_from_slice(bytes);
    
    // Add padding length marker (last 4 bytes)
    let original_len = bytes.len() as u32;
    
    // Fill with random padding
    let padding_len = MESSAGE_SIZE - bytes.len() - 4;
    let mut rng = rand::thread_rng();
    use rand::Rng;
    for _ in 0..padding_len {
        padded.push(rng.gen());
    }
    
    // Append original length
    padded.extend_from_slice(&original_len.to_le_bytes());
    
    Ok(padded)
}

/// Decrypt message content and remove padding
pub fn decrypt_message(encrypted: &[u8], _sender: &PeerId) -> Result<String> {
    // TODO: Implement ChaCha20-Poly1305 decryption with Double Ratchet
    
    if encrypted.len() != MESSAGE_SIZE {
        anyhow::bail!("Invalid message size");
    }
    
    // Extract original length from last 4 bytes
    let len_bytes: [u8; 4] = encrypted[MESSAGE_SIZE - 4..]
        .try_into()
        .context("Failed to extract length")?;
    
    let original_len = u32::from_le_bytes(len_bytes) as usize;
    
    if original_len > MESSAGE_SIZE - 4 {
        anyhow::bail!("Invalid message length");
    }
    
    // Extract original content
    let content_bytes = &encrypted[..original_len];
    let content = String::from_utf8(content_bytes.to_vec())
        .context("Invalid UTF-8 in message")?;
    
    Ok(content)
}

/// Create a temporary node for sending messages
/// This node will stay alive briefly to allow delivery confirmation
async fn create_message_node() -> Result<FireCloudNode> {
    let config = NodeConfig {
        port: 0,  // Random port
        bootstrap_peers: vec![],
        enable_mdns: true,
        bootstrap_relays: vec![],
    };
    
    FireCloudNode::new(config).await
        .context("Failed to create network node")
}

pub async fn handle_message_command(
    cmd: MessageCommand,
    data_dir: PathBuf,
) -> Result<()> {
    let friends = FriendList::load(&data_dir)?;
    let mut messages = MessageStore::load(&data_dir)?;
    
    match cmd {
        MessageCommand::Send { friend, message } => {
            // 1. Find friend
            let friend_data = friends.find_friend(&friend)
                .context("Friend not found. Add them first with: firecloud friend add <peer-id>")?;
            
            // 2. Verify they're an accepted friend
            if !friends.is_friend(&friend_data.peer_id) {
                anyhow::bail!(
                    "Not yet friends with {}. Wait for them to accept your request.",
                    friend_data.name.as_ref().unwrap_or(&friend)
                );
            }
            
            // 3. Encrypt with padding to exactly 1KB
            let encrypted = encrypt_message(&message, &friend_data.peer_id)?;
            
            // 4. Add random delay for timing obfuscation (metadata hiding)
            let delay = rand::thread_rng().gen_range(MIN_DELAY_MS..=MAX_DELAY_MS);
            tokio::time::sleep(Duration::from_millis(delay)).await;
            
            // 5. Create message ID and timestamp
            let message_id = uuid::Uuid::new_v4().to_string();
            let timestamp = Utc::now().timestamp();
            
            // 6. Send over network
            println!("\n{}", "📡 Sending encrypted message over network...".cyan());
            
            match create_message_node().await {
                Ok(mut node) => {
                    // Send the 1KB padded message
                    let _request_id = node.send_direct_message(
                        &friend_data.peer_id,
                        encrypted.clone(),
                        message_id.clone(),
                        timestamp,
                    );
                    
                    println!("{}", "   Message sent! (1024 bytes - padded for privacy)".green());
                    
                    // Keep node alive briefly for delivery confirmation
                    tokio::time::sleep(Duration::from_secs(2)).await;
                }
                Err(e) => {
                    println!("{}", format!("⚠️  Network error: {}", e).yellow());
                    println!("{}", "   Message saved locally. Will retry when network is available.".dimmed());
                }
            }
            
            // 7. Store locally
            let msg = Message {
                id: message_id,
                from: messages.get_local_peer_id(),
                to: friend_data.peer_id,
                content: encrypted,
                timestamp: DateTime::from_timestamp(timestamp, 0).unwrap_or(Utc::now()),
                delivered: false,  // Will be updated on confirmation
                read: false,
            };
            
            messages.add_message(msg);
            messages.save(&data_dir)?;
            
            let peer_id_string = friend_data.peer_id.to_string();
            let display_name = friend_data.name.as_ref()
                .unwrap_or(&peer_id_string);
            
            println!("\n{}", "✅ Message sent!".green().bold());
            println!("  To: {}", display_name.yellow());
            println!("  Delay: {}ms (timing obfuscation)", delay.to_string().dimmed());
            println!("  Size: {} bytes (padded for metadata privacy)", MESSAGE_SIZE.to_string().cyan());
            println!("\n{}", "Message encrypted and metadata hidden with padding + timing delays.".dimmed());
        }
        
        MessageCommand::Inbox { from, limit } => {
            let inbox = if let Some(friend_name) = from {
                let friend_data = friends.find_friend(&friend_name)
                    .context("Friend not found")?;
                messages.get_conversation(&friend_data.peer_id, limit)
            } else {
                messages.get_inbox(limit)
            };
            
            if inbox.is_empty() {
                println!("\n{}", "No messages.".yellow());
                return Ok(());
            }
            
            println!("\n{} ({} messages)", "Inbox".green().bold(), inbox.len());
            
            for msg in inbox.iter().rev() {
                // Find sender's name
                let sender = friends.friends.get(&msg.from);
                let peer_id_str = msg.from.to_string();
                let sender_name = sender
                    .and_then(|f| f.name.as_ref())
                    .map(|n| n.as_str())
                    .unwrap_or_else(|| {
                        &peer_id_str[..8.min(peer_id_str.len())]
                    });
                
                // Decrypt message
                let content = decrypt_message(&msg.content, &msg.from)
                    .unwrap_or_else(|_| "[Encrypted]".to_string());
                
                let time_ago = humantime::format_duration(
                    Utc::now().signed_duration_since(msg.timestamp)
                        .to_std()
                        .unwrap_or_default()
                );
                
                let read_marker = if msg.read { "" } else { "" };
                
                println!("\n  {} {} {} {}", 
                    read_marker.cyan(),
                    sender_name.yellow().bold(),
                    format!("({})", time_ago).dimmed(),
                    if msg.delivered { "".green() } else { "".yellow() }
                );
                println!("    {}", content);
            }
        }
        
        MessageCommand::Chat { friend, limit } => {
            let friend_data = friends.find_friend(&friend)
                .context("Friend not found")?;
            
            let conversation = messages.get_conversation(&friend_data.peer_id, limit);
            
            if conversation.is_empty() {
                println!("\n{}", "No messages yet.".yellow());
                println!("Send a message with: {}", 
                    format!("firecloud msg send '{}' 'Hello!'", friend).cyan());
                return Ok(());
            }
            
            let peer_id_string = friend_data.peer_id.to_string();
            let display_name = friend_data.name.as_ref()
                .unwrap_or(&peer_id_string);
            
            println!("\n{} {}", "Chat with".green().bold(), display_name.yellow().bold());
            println!("{}", "".repeat(50).dimmed());
            
            let local_peer_id = messages.get_local_peer_id();
            
            for msg in conversation.iter().rev() {
                let is_me = msg.from == local_peer_id;
                let content = decrypt_message(&msg.content, &msg.from)
                    .unwrap_or_else(|_| "[Encrypted]".to_string());
                
                let time = msg.timestamp.format("%H:%M").to_string();
                
                if is_me {
                    println!("  {} {} {}", 
                        time.dimmed(),
                        "You:".cyan().bold(),
                        content
                    );
                } else {
                    println!("  {} {} {}", 
                        time.dimmed(),
                        format!("{}:", display_name).yellow().bold(),
                        content
                    );
                }
            }
        }
        
        MessageCommand::Clear { friend, yes } => {
            if !yes {
                println!("{}", "This will delete message history. Use --yes to confirm.".yellow());
                return Ok(());
            }
            
            let count = if let Some(friend_name) = friend {
                let friend_data = friends.find_friend(&friend_name)
                    .context("Friend not found")?;
                messages.clear_conversation(&friend_data.peer_id)?
            } else {
                let total = messages.messages.len();
                messages.messages.clear();
                messages.by_peer.clear();
                total
            };
            
            messages.save(&data_dir)?;
            
            println!("\n{}", format!("✅ Cleared {} messages", count).green().bold());
        }
    }
    
    Ok(())
}