|
| 1 | +# Chronicle Backend Architecture |
| 2 | + |
| 3 | +This repository contains the robust, scalable, and highly secure backend infrastructure for the **Chronicle** application. Built primarily with Node.js and Express, it serves as the central hub handling user authentication, Web3 (IPFS) integrations, data security, and user controls. |
| 4 | + |
| 5 | +--- |
| 6 | + |
| 7 | +## 🚀 Tech Stack |
| 8 | + |
| 9 | +- **Core Framework**: Node.js, Express.js |
| 10 | +- **Database**: MongoDB (Mongoose ODMs) for persistence |
| 11 | +- **In-Memory Store**: Redis (for Rate Limiting, OTP Caching, Distributed Locks) |
| 12 | +- **Cloud Storage (Avatars)**: AWS S3 + CloudFront (with `sharp` for image optimization) |
| 13 | +- **Web3 Storage**: Pinata (IPFS integration) |
| 14 | +- **Security**: |
| 15 | + - Bridge JWT (JSON Web Tokens) for session management |
| 16 | + - WebAuthn (Passkeys/Biometrics) via `@simplewebauthn` |
| 17 | + - AES Encryption (Custom encryption modules for secrets) |
| 18 | + - `speakeasy` for Two-Factor Authentication (2FA) |
| 19 | + |
| 20 | +--- |
| 21 | + |
| 22 | +## 🏗️ Core Modules & Architectural Flow |
| 23 | + |
| 24 | +The backend is modularized into distinct domains handling specialized parts of the application: |
| 25 | + |
| 26 | +### 1. Authentication & Authorization (`/api/auth`) |
| 27 | +The auth service provides a multi-layered security flow: |
| 28 | +- **Traditional Auth**: Bridge JWT-based login and registration with Bcrypt password hashing. |
| 29 | +- **OAuth Providers**: Integrations with third-party providers (Google, GitHub). |
| 30 | +- **Two-Factor Authentication (2FA)**: Time-based One Time Password (TOTP) implementation. 2FA secrets are strictly **encrypted** in the database using the internal `encryption.js` module. |
| 31 | +- **Biometric / Passkeys**: WebAuthn flow (Challenge generation and attestation) to allow users to authenticate using Touch ID, Face ID, or hardware tokens. |
| 32 | +- **Session Tracking**: Every login records a `LoginEvent` allowing the system to track user activity, IP addresses, and detect anomalies via the `security-check.js` cron job. |
| 33 | + |
| 34 | +### 2. User Controls (`/api/auth/user`) |
| 35 | +Handles all profile-related actions securely via the `requireAuth` middleware: |
| 36 | +- **Profile Management**: Aggregation pipelines to fetch rich user data including login histories. |
| 37 | +- **Email Verification**: Uses `brevo` to send verification codes. Codes are temporarily cached in **Redis** with short TTLs to ensure they expire securely. |
| 38 | +- **Avatar Uploads**: |
| 39 | + - Uploaded images are buffered in-memory (`multer`). |
| 40 | + - Optimized dynamically using `sharp` (e.g., resizing, format conversion). |
| 41 | + - Streamed directly to an **AWS S3 Bucket** and served globally via CloudFront. |
| 42 | + |
| 43 | +### 3. Encryption & Decryption (`config/encryption.js`) |
| 44 | +Security is a first-class citizen. Sensitive data such as 2FA secrets and specific user identifiers are never stored in plaintext. The system utilizes AES-based symmetric encryption algorithms: |
| 45 | +- `encrypt()`: Called before saving sensitive fields to MongoDB. |
| 46 | +- `decrypt()`: Executed dynamically during validation workflows (e.g., verifying a TOTP token). |
| 47 | + |
| 48 | +### 4. Web3 & IPFS Integration (`/api/web3`) |
| 49 | +Designed for decentralized file handling: |
| 50 | +- **Pinata Integration**: Connects with the Pinata IPFS gateway. |
| 51 | +- Files are pinned to the IPFS network ensuring immutability. |
| 52 | +- The returned Content Identifiers (CIDs) are recorded in the database under `Web3Event` models and linked to the `User` document, creating a permanent chronological ledger of user uploads. |
| 53 | + |
| 54 | +### 5. Security Middlewares & Infrastructure |
| 55 | +- **Redis Rate Limiter**: Custom sliding-window rate limiters (`rate-limiter.js`) guard against brute-force and DDoS attacks on sensitive routes (e.g., Email Sending, Login). |
| 56 | +- **Redis Blacklisting and Lock**: For blacklisting suspicious IPs and locking accounts. |
| 57 | +- **Background Cron Jobs**: `security-check.js` runs asynchronously in the background to monitor and prune stale data or flag suspicious login activities. |
| 58 | + |
| 59 | +--- |
| 60 | + |
| 61 | +## 📂 Directory Structure |
| 62 | + |
| 63 | +```text |
| 64 | +backend/ |
| 65 | +├── config/ # Cloud configurations (AWS S3, Pinata IPFS, Nodemailer, Encryption) |
| 66 | +├── controllers/ # Business logic for routes (User, Auth, OAuth, Web3) |
| 67 | +├── database/ # Connection drivers for MongoDB and Redis clients |
| 68 | +├── middlewares/ # Express middlewares (Auth guards, Multer upload, Rate Limiting, Locks) |
| 69 | +├── models/ # Mongoose schemas (User, LoginEvent, PassKey, Web3Event) |
| 70 | +├── routes/ # API routing endpoints mapping to controllers |
| 71 | +├── server.js # Express App entry point and global middleware registration |
| 72 | +├── security-check.js # Background cron processes for automated security audits |
| 73 | +└── utils/ # Helper functions and constant variables |
| 74 | +``` |
| 75 | + |
| 76 | +--- |
| 77 | + |
| 78 | +## 🔄 Request Lifecycle Example (Avatar Upload) |
| 79 | + |
| 80 | +1. **Client Request**: Frontend sends a multipart form-data request to `/api/auth/user/avatar/upload`. |
| 81 | +2. **Middleware Layer**: |
| 82 | + - `requireAuth` validates the Bridge JWT token in headers. |
| 83 | + - `upload.single('image')` captures the file into a memory buffer. |
| 84 | +3. **Controller Processing (`uploadAvatar`)**: |
| 85 | + - `sharp` processes the image buffer (compression). |
| 86 | + - `PutObjectCommand` streams the buffer directly to the **AWS S3 bucket**. |
| 87 | + - S3 Key is returned to the client. |
| 88 | +4. **Client Confirmation**: Frontend triggers `/avatar/save` with the returned key. |
| 89 | +5. **Database Update**: The CloudFront URL is constructed and patched into the MongoDB `User` document. |
| 90 | + |
| 91 | +--- |
| 92 | + |
| 93 | +## 🏃 Getting Started |
| 94 | + |
| 95 | +1. Create a `.env` file based on your environment requirements (AWS keys, Mongo URI, Redis URL, JWT Secret, Pinata Keys). |
| 96 | +2. Install dependencies: `npm install` |
| 97 | +3. Start the server: `npm start` (or `npm run dev` for local development). |
0 commit comments