You are an expert AI assistant tasked with generating the complete codebase for a single-page application (SPA) called 'Gizli Mesaj' (Secure Message). This application aims to provide a secure, end-to-end encrypted messaging experience, addressing user concerns about privacy on mainstream platforms like Instagram. The goal is to create a robust, user-friendly, and secure messaging platform from scratch using React and Tailwind CSS.
**1. PROJECT OVERVIEW:**
Gizli Mesaj is a React-based SPA designed to offer a secure alternative for private communication. It tackles the growing concern of digital privacy, particularly the erosion of end-to-end encryption (E2EE) on popular social media platforms. The core value proposition is to provide users with a reliable, platform-independent way to send messages and share files with guaranteed privacy and security through E2EE. It solves the problem of users feeling insecure about their private conversations and shared data being potentially accessed or mishandled by platform providers.
**2. TECH STACK:**
- **Frontend Framework:** React (using Create React App or Vite for setup)
- **Styling:** Tailwind CSS (for rapid UI development and utility-first styling)
- **State Management:** React Context API or Zustand (for managing global state like user authentication and chat data)
- **Routing:** React Router DOM (for navigation within the SPA)
- **Encryption:** `libsodium-wrappers` or `tweetnacl-js` (for implementing robust E2EE using modern cryptographic primitives like X25519, Poly1305, and ChaCha20-Poly1305)
- **Local Storage:** For storing user preferences, encryption keys (securely), and potentially chat history if cloud sync is not implemented in MVP.
- **WebSockets (Optional for Real-time):** For instant message delivery. For MVP, polling or a simpler approach might suffice, but consider WebSockets for future scalability.
- **Build Tool:** Vite (recommended for speed)
**3. CORE FEATURES:**
**A. User Authentication & Key Management:**
- **User Registration/Login:** Users can register with an email and password or a unique username. Password hashing will be done server-side (if a backend is introduced later) or client-side using secure methods for the frontend-only MVP.
- **Key Generation:** Upon registration, a unique public/private key pair is generated for each user using a strong asymmetric encryption algorithm (e.g., X25519). The private key MUST be stored securely in the browser's Local Storage, ideally encrypted with a key derived from the user's password (using PBKDF2 or Argon2). This ensures only the logged-in user can decrypt messages.
- **Contact Management:** Users can add contacts by username/ID. The system will manage public keys associated with usernames.
- **User Flow:** User opens app -> sees Login/Register -> Enters credentials -> If valid, generates/retrieves keys -> Navigates to chat list.
**B. End-to-End Encrypted Messaging:**
- **Message Encryption:** Before sending, a message is encrypted using the recipient's public key (via asymmetric encryption for key exchange/agreement) and then potentially using a symmetric session key (e.g., ChaCha20-Poly1305) for the actual message content. The sender's public key is included so the recipient knows who sent it.
- **Message Decryption:** Upon receiving an encrypted message, the app uses the user's stored private key (decrypted with the user's password) to decrypt the session key, and then uses the session key to decrypt the message content.
- **User Flow:** User selects a contact -> Types a message -> Clicks Send -> Message is encrypted client-side -> Sent to server (or directly peer-to-peer if applicable later) -> Arrives at recipient's client -> Decrypted client-side using recipient's private key -> Displayed in chat.
**C. Secure File Sharing:**
- **File Encryption:** Similar to messages, files are encrypted client-side before upload/transfer. A symmetric encryption key is generated for each file, used to encrypt the file content. This symmetric key is then encrypted using the recipient's public key and sent along with the encrypted file.
- **File Decryption:** The recipient uses their private key to decrypt the symmetric key, then uses that key to decrypt the file.
- **User Flow:** User selects a contact -> Clicks attachment icon -> Selects a file -> File is encrypted -> Uploaded/Transferred -> Received by recipient -> Decrypted using recipient's private key.
**D. Chat History & Persistence:**
- **Local Storage:** For the MVP, chat messages and decryption keys are stored in the browser's Local Storage. This is suitable for single-device usage. Sensitive keys should be encrypted before storing.
- **User Flow:** App loads -> Retrieves encrypted chat history from Local Storage -> Displays messages.
**4. UI/UX DESIGN:**
- **Layout:** Single-page application structure. A main layout with a sidebar for chat list/contacts and a main content area for the active conversation. Responsive design is crucial.
- **Color Palette:** A clean, modern, and trustworthy palette. Primary colors: Dark Blue/Purple (#4A148C, #1976D2) for security and trust, accent colors: Teal/Green (#00ACC1, #4CAF50) for positive actions (send, new message), neutral grays (#F5F5F5, #BDBDBD, #424242) for backgrounds and text. Dark mode support is highly desirable.
- **Typography:** Use a clear, readable sans-serif font like 'Inter' or 'Roboto'. Establish a clear type scale for headings, body text, and UI elements.
- **Components:** Clean, intuitive UI components. Clear visual distinction between sent and received messages. Loading indicators for sending/receiving actions. Error messages should be clear and actionable.
- **Responsive Design:** Mobile-first approach. Sidebar collapses into a hamburger menu on smaller screens. Ensure usability across all device sizes.
**5. DATA MODEL:**
- **User State:** `{ userId: string, username: string, publicKey: string, isAuthenticated: boolean }`
- **Chat List State:** `Array<{ chatId: string, username: string, lastMessage: string, timestamp: number, unreadCount: number }>`
- **Conversation State:** `Array<{ messageId: string, senderId: string, content: string (encrypted/decrypted), type: 'text' | 'file', timestamp: number, status: 'sending' | 'sent' | 'delivered' | 'error' }>`
- **Encryption Keys:** Stored in Local Storage, encrypted with a user-derived key. Example structure (hypothetical, actual storage needs careful encryption): `localStorage.setItem('gizliMesajKeys', JSON.stringify({ privateKeyEncrypted: '...', publicKey: '...' }))`
- **Mock Data Format:**
```json
// Example User Object
{
"userId": "user123",
"username": "Alice",
"publicKey": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...\n-----END PUBLIC KEY-----"
}
// Example Chat Object
{
"chatId": "chat_user123_user456",
"otherUserId": "user456",
"otherUsername": "Bob",
"lastMessage": {
"content": "Hey Bob, how are you?", // Plaintext for display in list, actual stored is encrypted
"timestamp": 1678886400000,
"isRead": false
},
"unreadCount": 2
}
// Example Message Object (within a conversation)
{
"messageId": "msg_abc",
"senderId": "user123", // sender's userId
"recipientId": "user456", // recipient's userId
"encryptedContent": "U2FsdGVkX1...", // Encrypted message payload
"fileInfo": {
"fileName": "document.pdf",
"fileType": "application/pdf",
"encryptedKey": "U2FsdGVkX1..." // Symmetric key encrypted with recipient's public key
},
"timestamp": 1678886450000,
"status": "sent", // 'sending', 'sent', 'delivered', 'error'
"isEncrypted": true
}
```
**6. COMPONENT BREAKDOWN:**
- **`App.js`:** Main component, sets up routing, global layout, and context providers.
- **`Layout.js`:** Contains the overall page structure (sidebar + main content). Handles responsiveness.
- **`Sidebar.js`:** Displays the list of contacts/chats. Handles navigation to selected chat.
- **`ChatListItem.js`:** Represents a single chat in the sidebar. Shows username, last message snippet, unread count.
- **`ConversationView.js`:** Displays the messages for a selected chat.
- **`MessageList.js`:** Renders the list of messages.
- **`MessageBubble.js`:** Renders a single message (sent/received), handling text and file display. Includes decryption logic.
- **`MessageInput.js`:** Text input field, send button, attachment button.
- **`AuthForm.js`:** Handles Login and Registration forms.
- **`KeyManager.js` (Internal/Utility):** Handles cryptographic key generation, encryption, decryption, and secure storage/retrieval.
- **`ContactManager.js` (Internal/Utility):** Manages adding/finding contacts and their public keys.
- **`ThemeProvider.js`:** Manages theme switching (light/dark mode).
- **`LoadingSpinner.js`:** Reusable loading indicator.
- **`ErrorMessage.js`:** Displays user-facing error messages.
**Props Examples:**
- `ChatListItem`: `chatData` (object with username, lastMessage, unreadCount), `onClick` (function)
- `MessageBubble`: `message` (object with content, senderId, timestamp, status), `isOwnMessage` (boolean), `onDecrypt` (function)
- `MessageInput`: `onSendMessage` (function), `onFileSelect` (function)
**7. ANIMATIONS & INTERACTIONS:**
- **Message Sending:** A subtle animation for messages in the 'sending' state (e.g., a spinning icon or dashed border), changing to 'sent' upon confirmation.
- **New Message Arrival:** A smooth scroll animation to the bottom when a new message arrives. Possibly a subtle highlight on the newly arrived message.
- **Hover Effects:** Slight background color change or shadow lift on interactive elements like buttons and chat list items.
- **Page Transitions:** Fade-in/fade-out transitions between different views (e.g., chat list to conversation) using React Router's built-in or libraries like `Framer Motion`.
- **Loading States:** Use spinners or skeleton screens when fetching data or decrypting messages.
- **File Upload Progress:** Visual progress indicator for file uploads/downloads.
**8. EDGE CASES:**
- **Empty States:** Display friendly messages when there are no chats or no messages in a conversation.
- **Error Handling:** Gracefully handle encryption/decryption errors, network issues, invalid user input. Provide clear, non-technical error messages to the user. Log detailed errors for debugging.
- **Key Loss:** Inform the user about the implications of losing their private key (i.e., inability to decrypt past messages).
- **Invalid Input:** Implement client-side validation for usernames, passwords, and message content (e.g., preventing excessively long messages).
- **Security:** Ensure private keys are never transmitted unencrypted. Use secure methods for key derivation and storage. Avoid logging sensitive information.
- **Accessibility (a11y):** Use semantic HTML, ARIA attributes where necessary, ensure keyboard navigability, sufficient color contrast, and focus management.
- **Large Files:** Implement chunking and progress indicators for large file transfers.
- **Contact Not Found:** Handle cases where a user tries to message or add a non-existent contact.
**9. SAMPLE DATA:**
*(See DATA MODEL section for detailed examples of User, Chat, and Message objects. Ensure mock data covers various scenarios like text messages, file messages, messages from self, messages from others, different statuses.)*
**Example Application State Snippets:**
```javascript
// Example Authentication State
{
currentUser: {
userId: 'user456',
username: 'Bob',
publicKey: '-----BEGIN PUBLIC KEY...'
},
isAuthenticating: false,
error: null
}
// Example Chat List State
[
{
chatId: 'chat_user456_user123',
otherUserId: 'user123',
otherUsername: 'Alice',
lastMessage: { content: 'See you tomorrow!', timestamp: 1678890000000, isRead: true },
unreadCount: 0
},
{
chatId: 'chat_user456_user789',
otherUserId: 'user789',
otherUsername: 'Charlie',
lastMessage: { content: 'Encrypted file: report.docx', timestamp: 1678889000000, isRead: false },
unreadCount: 1
}
]
// Example Conversation State for Alice's chat
[
{
messageId: 'msg_xyz',
senderId: 'user123', // Alice
recipientId: 'user456', // Bob
encryptedContent: 'U2FsdGVkX1...',
fileInfo: null,
timestamp: 1678886450000,
status: 'sent',
isEncrypted: true
},
{
messageId: 'msg_uvw',
senderId: 'user456', // Bob
recipientId: 'user123', // Alice
encryptedContent: 'U2FsdGVkX1...', // e.g., "Okay, sounds good!"
fileInfo: null,
timestamp: 1678886490000,
status: 'delivered',
isEncrypted: true
},
{
messageId: 'msg_rst',
senderId: 'user123', // Alice
recipientId: 'user456', // Bob
encryptedContent: 'U2FsdGVkX1...', // Encrypted file payload
fileInfo: {
fileName: "notes.txt",
fileType: "text/plain",
fileSize: 10240,
encryptedKey: "U2FsdGVkX1..."
},
timestamp: 1678886550000,
status: 'sent',
isEncrypted: true
}
]
```
**10. DEPLOYMENT NOTES:**
- **Build Configuration:** Use Vite's `build` command. Ensure environment variables are handled correctly.
- **Environment Variables:** Use `.env` files for API endpoints (if any), encryption constants, etc. Prefix variables with `VITE_` for Vite projects.
- **HTTPS:** Essential for any web application, especially one dealing with security. Deploy to platforms that support HTTPS (e.g., Netlify, Vercel, GitHub Pages).
- **Security Best Practices:** Regularly update dependencies. Implement Content Security Policy (CSP). Sanitize all user inputs to prevent XSS attacks. Be mindful of where and how encryption keys are stored and managed.
- **Performance:** Optimize React component rendering using `React.memo`, `useCallback`. Code-split routes and components if the application grows. Lazy load images and components. Optimize bundle size.
- **Key Management Security:** For production, consider more robust key storage solutions than basic Local Storage encryption, potentially leveraging browser storage APIs like IndexedDB with appropriate encryption layers or exploring Web Crypto API.
- **Scalability:** While MVP is frontend-focused, plan for backend integration for user management, message relay (if not P2P), and potentially secure cloud storage for message history sync.