# TG Drive Official Documentation **Version:** 3.5.0 Stable Release (Build 2700) **URL:** [https://tgdriveo.pages.dev/docs](https://tgdriveo.pages.dev/docs) **Live Application:** [https://tgdriveo.pages.dev/](https://tgdriveo.pages.dev/) **Android APK:** [Download Native APK](https://github.com/Saini920/DevKit-Manager-v4.0.7/releases/download/tg-drive-2.0.0/TG_Drive_2.0.0.apk) --- ## Table of Contents 1. [About TG Drive](#1-about-tg-drive) 2. [What's New in Version 3.5.0](#2-whats-new-in-version-350) 3. [Premium Features](#3-premium-features) 4. [Android Native App](#4-android-native-app) 5. [System Policies & Limits](#5-system-policies--limits) 6. [Setup Guide](#6-setup-guide) 7. [Storage System: Smart Hybrid Architecture](#7-storage-system-smart-hybrid-architecture) 8. [How It Works: Virtual File System (VFS)](#8-how-it-works-virtual-file-system-vfs) 9. [Storage Logic & Quota Breakdown](#9-storage-logic--quota-breakdown) 10. [Transfers Manager & Concurrency Queue](#10-transfers-manager--concurrency-queue) 11. [Real-Time Cloud Synchronization](#11-real-time-cloud-synchronization) 12. [Frequently Asked Questions (FAQ)](#12-frequently-asked-questions-faq) 13. [Secure Vault & Zero-Knowledge E2EE Architecture](#13-secure-vault--zero-knowledge-e2ee-architecture) 14. [Desktop Experience & Keyboard Shortcuts](#14-desktop-experience--keyboard-shortcuts) 15. [Privacy, Stealth Shield & Security](#15-privacy-stealth-shield--security) --- ## 1. About TG Drive TG Drive is a premium cloud storage interface designed to transform your Telegram experience into a professional file management system. It utilizes your personal Cloud Storage space to host and organize files of any type. By connecting directly to the official Telegram servers, the app ensures that your data is always available across all your devices without the typical subscription costs associated with traditional cloud providers. - **Direct MTProto 2.0:** All communication occurs directly between your client (browser or native app) and Telegram's data centers via GramJS MTProto 2.0. - **Zero Third-Party Storage:** No user files, tokens, or encryption keys are ever transmitted to or stored on TG Drive servers. - **Client-Side Virtual File System:** Folder hierarchies, tags, and file metadata are stored right inside your private Telegram Saved Messages. --- ## 2. What's New in Version 3.5.0 Version 3.5.0 (Build 2700) is the latest stable release featuring major cryptographic enhancements, disaster recovery protocols, and performance upgrades: - **Zero-Knowledge End-to-End Vault (E2EE):** Military-grade client-side encryption using AES-GCM 256-bit and memory-hard Argon2id key derivation (96 MB, 4 passes for new vaults; 64 MB, 3 passes). Credentials and files are encrypted before leaving your browser. File names, MIME types and folder membership are additionally sealed with AES-GCM under a dedicated HKDF-SHA256 metadata key derived from the shared vault file key (envelope `v1.`, AAD-bound to account + item + key epoch); the real filename is not written to the message caption or the Telegram document attribute. Byte size, upload timing and folder names remain visible. - **Two-Phase Secure Device Pairing & Self-Healing Delivery:** A new device is enrolled from an already-unlocked device without the recovery phrase — the requesting device shows a locator short code / QR, the approver performs an ephemeral ECDH exchange and publishes its public key, and only then does the new device leave the QR screen for a **Verify Code** screen showing the identical 6-digit SAS; the vault key is released only after **Confirm Match / Authorize**. Delivery is self-healing (timeout-bounded RPCs, exponential backoff, active socket reconnect, and an immediate search sweep when connectivity returns, alongside the ~2.5 s Saved-Messages poll). Up to **5 devices** per vault. A **new** Master PIN is **6-8 digits** (legacy 4-8 PINs keep working). - **Dual-Channel OTP Password Recovery:** User-selectable choice between personal Telegram Saved Messages (direct MTProto, 0% bot ban risk) and Telegram Bot for 6-digit recovery codes with session-preserving PIN reset. - **Automatic Multi-Device Cloud Sync:** Zero-touch background synchronization of cryptographic salt and canary tokens via Telegram Saved Messages (`#TG_DRIVE_VAULT_CONFIG#`) with real-time active status indicators across all devices. - **Android Native Biometric Unlock:** Native fingerprint and facial recognition integrated directly with the Android Hardware Keystore for lightning-fast, secure vault access on mobile. - **Responsive Modular Profile Interface:** Streamlined preferences, modular vault controls, and stealth blur protection. - **Background Legacy File Migration:** One-tap background engine to scan and encrypt older unencrypted files into the AES-256 vault, with optional Wi-Fi only restriction to preserve mobile data. - **Hardened Multi-Salt Session Recovery:** Dual-tier encrypted session storage in IndexedDB with automated fallback resolution across legacy salt structures, preventing accidental logouts. - **Smart Pause & Resume & SW Streaming:** High-speed MTProto streaming pipeline with chunk-level persistence, enabling pause, resume, and direct streaming to the browser's native download manager. - **Zero-PII Anonymous Telemetry & Firebase Data Isolation:** Complete user identity isolation. No Telegram User IDs, usernames, phone numbers, auth keys, bot tokens, or personal storage file paths are ever transmitted to Firebase. Analytics operate purely on non-reversible daily aggregate counters (`stats/daily/YYYY-MM-DD`) with anonymous unique session hashing, login counts, and coarse platform distribution. --- ## 3. Premium Features - **Multipart Architecture:** Upload and download massive files efficiently by splitting them into safe, high-speed MTProto chunks (512 KB slices). - **Pause & Resume:** Interrupt and continue downloads seamlessly with chunk-level persistence, saving data and time on large transfers. - **Deep Nesting:** Unlimited folder depth with lightning-fast smart indexing stored directly in your Telegram cloud. - **Local Persistence:** Utilizes IndexedDB (`idb-keyval`) for high-speed local caching and instant app responsiveness. - **Zero Server Storage:** Pure peer-to-peer communication via GramJS MTProto. No middleman servers. - **Bank-Grade Privacy:** Leverages Telegram's native encryption and your personal API credentials for absolute security. --- ## 4. Android Native App TG Drive is available as a native Android application built with Capacitor: - **Direct APK Download:** `https://github.com/Saini920/DevKit-Manager-v4.0.7/releases/download/tg-drive-2.0.0/TG_Drive_2.0.0.apk` - **Native Performance:** Buttery-smooth transitions, zero browser address bar interference. - **Background Transfers:** Uploads and downloads continue reliably when minimized. - **Hardware Biometric Keystore:** Secure single-touch fingerprint and face authentication. - **Push Alerts:** Real-time native alerts for transfer completions and system events. - **Privacy Shield:** Independent stealth blur toggles for username, phone number, and thumbnails. --- ## 5. System Policies & Limits To ensure maximum stability and real-time performance across Telegram's MTProto API, TG Drive enforces clear system limits: - **Upload File Size Limit:** Strict 2.0 GB maximum file size policy per file (aligned with standard Telegram file size ceilings). - **Batch Uploading Limit:** Up to 100 files can be selected and queued at once in a single batch. - **Concurrent Download Limit:** Maximum of 3 simultaneous downloads. Additional files wait in a smart priority queue and start automatically as active transfers finish, preventing Telegram API `FLOOD_WAIT` rate limiting and browser memory exhaustion. - **Max Linked Devices:** Up to **5 devices** can be enrolled in a vault at once (shown as a `used/5` counter in **Connected Devices**). Linking a 6th device drops the **oldest** slot, so that device must be re-linked (or recovered) before it can unlock again. - **Master PIN Length:** A **new** Master PIN must be **6-8 digits**. Vaults created on older builds may still use a **4-8 digit** PIN, which keeps working for unlock and for adopting the existing vault — legacy PINs are never invalidated. - **Pairing Request Lifetime:** A device-pairing request / locator short code expires after **5 minutes**, and link messages are deleted once the handshake completes. --- ## 6. Setup Guide Connecting your Telegram account to TG Drive takes less than 2 minutes: 1. **Obtain API Credentials:** Visit [https://my.telegram.org](https://my.telegram.org), log in with your phone number, navigate to "API development tools", and create an application to obtain your `API ID` and `API Hash`. 2. **Create a Bot Token:** Message `@BotFather` on Telegram, create a new bot using `/newbot`, and copy the provided `Bot Token`. (Used for profile photos and optional OTP recovery). 3. **Authorize Account:** Open TG Drive, enter your phone number, API ID, API Hash, and Bot Token. Enter the official Telegram verification code sent to your Telegram app. 4. **Start Organizing:** Your Telegram "Saved Messages" chat is now your unlimited cloud drive! --- ## 7. Storage System: Smart Hybrid Architecture TG Drive uses a Smart Hybrid Storage engine optimizing for speed, privacy, and file size: - **MTProto Direct:** - Files up to 2.0 GB. - High E2E Encryption (Direct P2P GramJS connection). - Encrypted chunks sent straight to your Telegram Saved Messages chat. - **Bot API Gateway:** - Fast metadata indexing and profile photo caching. - Fallback channel for small files (< 20 MB). - Secondary notification channel for OTP recovery codes. --- ## 8. How It Works: Virtual File System (VFS) TG Drive creates a Virtual File System (VFS) on top of Telegram Saved Messages by embedding structured JSON metadata tags: ```json // VFS Message Tagging Structure { "prefix": "#TG_DRIVE_FILE#", "meta": { "fileName": "Project_Archive.zip", "parentId": "root_vault", "totalSize": 2147483648, "isMultipart": true, "parts": 4, "encrypted": true } } ``` When you request a file, TG Drive fetches the corresponding MTProto message chunks, verifies cryptographic integrity, and streams the decrypted bytes directly to disk via a Service Worker. --- ## 9. Storage Logic & Quota Breakdown - **9999 TB Quota:** Visual representation reflecting Telegram's virtually unlimited Saved Messages capacity. - **Categorization Donut Chart:** - **Images:** JPG, PNG, GIF, WEBP, SVG, RAW. - **Videos:** MP4, MKV, MOV, AVI, WEBM. - **Apps & Zips:** ZIP, RAR, 7Z, TAR, GZ, APK, EXE, DMG. - **Documents:** PDF, DOCX, XLSX, PPTX, TXT, CSV, EPUB. - **Others:** Audio, code files, unknown formats. - **Critical Notice:** Never manually delete `#TG_DRIVE_FILE#` or `#TG_DRIVE_VAULT_CONFIG#` messages in your official Telegram "Saved Messages" chat, as this breaks cloud indexing. --- ## 10. Transfers Manager & Concurrency Queue - **Aggregate Progress Bar:** Sleek floating progress pill at the bottom of the viewport showing aggregate percentage, total transferred bytes, and active transfer count. - **Granular Transfers View:** Tabbed panels for "Uploaded" and "Downloaded" items with real-time speed (MB/s), ETA calculation, chunk-level progress, and pause/resume/cancel controls. - **100-File Batch Upload:** Queue entire folders or up to 100 individual files at once with automated chunk scheduling. - **3 Concurrent Transfers:** Strict 3-file concurrency queue prevents browser out-of-memory errors and Telegram network throttling. --- ## 11. Real-Time Cloud Synchronization - **MTProto Update Listeners:** Instant synchronization across all devices. Adding, renaming, moving, or deleting files triggers real-time indexing. - **Auto-Recovery:** TG Drive is completely stateless. Clearing your browser cache or switching devices requires only a login—all folders, files, and tags auto-recover within seconds. - **Favorites & Trash:** Full lifecycle virtual containers for starred files and soft-deleted items with instant restore capability (`Alt + R`). --- ## 12. Frequently Asked Questions (FAQ) ### Does TG Drive leak personal info or Telegram data to Firebase? **No, absolutely not.** TG Drive enforces a strict **Zero-PII (Personally Identifiable Information)** privacy standard with 100% data isolation: - **Zero Personal Data in Firebase:** We never upload your Telegram User ID, phone number, username, session keys, bot tokens, or personal storage file paths to Firebase Realtime Database. - **Pure Non-Reversible Daily Aggregates:** Firebase is used strictly for anonymous daily platform health metrics (total daily unique sessions, login events, and coarse platform distribution: Web vs. Android APK) under `stats/daily/YYYY-MM-DD` using one-way salted hashes. - **Complete Telegram Cloud Isolation:** All your files, folders, metadata, and cryptographic vault configs reside strictly within your personal Telegram Saved Messages chat and your browser's local sandbox. ### Is TG Drive safe? Yes. TG Drive operates entirely client-side using official MTProto 2.0 protocols. Your API ID, API Hash, phone session strings, and Master PIN never touch any external server. ### What is the maximum file size? A strict limit of 2.0 GB per file is enforced for all uploads, adhering to Telegram's standard document size limit. ### Why do I need a Bot Token? The Bot Token acts as a lightweight metadata gateway for profile photos, fast thumbnail indexing, and optional OTP delivery without burdening your personal MTProto session. ### How does Master PIN / Password Recovery work? If you forget your Master PIN: 1. Tap **Forgot Password** on the lock screen. 2. Select your delivery channel: - **Saved Messages (Recommended):** Directly to your Telegram Saved Messages via MTProto with **0% risk of bot bans**. - **Telegram Bot:** Delivered via your configured Bot Token. 3. Enter the 6-digit OTP code to verify and reset your PIN while **preserving your active Telegram login session**. ### How does Multi-Device Sync work? Multi-Device Sync is 100% automated and zero-touch. When you configure the Vault, TG Drive securely anchors your cryptographic salt and verification canary into a tagged message (`#TG_DRIVE_VAULT_CONFIG#`) in your Telegram Saved Messages. Secondary devices discover this config automatically upon login—entering your Master PIN unlocks the vault without manual import/export. ### What is the concurrent download and batch upload limit? Up to **100 files per upload batch** and **3 simultaneous concurrent downloads** to prevent Telegram `FLOOD_WAIT` rate limits. ### How many devices can I link to one vault, and who can revoke devices? Up to **5 devices** per vault (the **Connected Devices** list shows a `used/5` counter). Linking a 6th device drops the **oldest** slot, so that device must be re-linked or recovered before it can unlock again. **Device Authority & Multi-Primary Revocation:** - **Primary Devices:** Any device that initialized the vault or unlocked/recovered it with the 12-Word Recovery Phrase is a **Primary Device**. Multiple primary devices can exist concurrently (e.g. your primary phone and work laptop). - **Peer Primary Revocation:** Any active Primary device holds administrative authority to revoke any other device—including another primary device slot (e.g. if an old primary phone was lost, sold, or its Telegram session terminated). - **Linked Seed Devices (Restricted):** Devices joined via QR code or push pairing without the 12-word phrase operate as **Linked Seed Devices**. Seed devices have full read/write access to encrypted files, but are strictly non-authoritative: they **cannot revoke, remove, or modify other devices**. - **Revoked Device Lockout:** When a device is revoked by a Primary device, its slot is purged and its salt is added to the `revokedSalts` denylist. On the revoked device, entering a PIN fails immediately with an explicit revocation notice, and the user is redirected to the `/login` screen to sign in again or recover via 12-word phrase. ### How long can my Master PIN be? A **new** Master PIN must be **6-8 digits**. Vaults created on older builds may use a **4-8 digit** PIN, which keeps working for unlock and for adopting the existing vault; a fresh PIN can never be shorter than 6 digits. ### Why does my new device not see the pairing request? The request is delivered over your account's own Telegram Saved Messages. In addition to a real-time push, the unlocked device actively polls every ~2.5 s, and the poll is hardened: every Telegram RPC is timeout-bounded (a half-open socket can never wedge it), failures back off exponentially, a dropped socket is actively reconnected, and returning online forces an immediate search sweep. If the unlocked device is still locked, a notice appears prompting you to unlock so the request can be approved. If it still does not appear, confirm both devices are logged into the **same Telegram account** and that the request has not expired past its 5-minute window. ### What is Privacy & Stealth Shield? Stealth Shield provides independent client-side frosted glass blur toggles for: - Telegram Username (`@username`) - Telegram Phone Number - Media Gallery & File Manager Thumbnails Hovering or tapping temporarily reveals blurred items. ### Does Privacy Shield affect file quality or download speed? No. Privacy Shield is a cosmetic CSS visual filter. Uploads, downloads, and stored files remain 100% full-resolution and uncompressed. ### How do Desktop Right-Click Menus and Drag-and-Drop work? Right-clicking any file card opens a desktop context menu (Download, Star, Rename, Info, Trash). Right-clicking blank space opens folder actions (Upload, New Folder, Select 100, Refresh). Dragging files into the window activates a frosted glass drop zone for instant batch uploading. ### How do I open the Keyboard Shortcuts Cheat Sheet? Press `?` (or `Shift + /`) anywhere in the application to open the interactive, searchable Keyboard Shortcuts modal. ### Why does TG Drive ask for my Old PIN immediately after logging out and re-logging in instead of prompting to create a New PIN? When you log out from TG Drive and subsequently log back in to the same Telegram account, the application immediately prompts for your existing (old) Master PIN rather than allowing a new PIN to be created. This happens due to TG Drive's **decentralized zero-knowledge cryptographic architecture**: 1. **Decentralized Cloud State Anchor (`#TG_DRIVE_VAULT_CONFIG#`):** TG Drive does not store your account or vault settings in an external centralized database. Instead, your vault's public KDF salt, canary verification token, and device slots are anchored directly in your personal Telegram **Saved Messages** under the tagged message `#TG_DRIVE_VAULT_CONFIG#`. 2. **Logout Purges Local Storage, NOT Your Cloud Data:** When you click Logout, TG Drive performs a local 8-tier cache wipe (IndexedDB, Dexie VFS DB, browser cache, and memory keys). It explicitly terminates that single MTProto session. However, TG Drive does **NOT** delete your Telegram account, your uploaded files, or the `#TG_DRIVE_VAULT_CONFIG#` message in your Telegram Saved Messages. 3. **Preventing Catastrophic Data Loss (Key Continuity):** All your previously uploaded files were encrypted with a 256-bit AES-GCM Master Key derived from your **Old PIN + Cloud Salt**. If TG Drive allowed an unverified "New PIN" upon re-login, the key derivation function would generate a completely different cryptographic key. With that new key, **all your previously uploaded photos, videos, and documents would become permanently unreadable and corrupted**! 4. **Instant Vault Discovery Upon Re-Login:** When you log back into the same Telegram account, TG Drive scans your Saved Messages, instantly discovers `#TG_DRIVE_VAULT_CONFIG#`, and recognizes that an existing vault already protects your files. It therefore prompts you for your **Old Master PIN** so it can derive the correct master key and unlock your existing data. 5. **What If You Forgot Your Old PIN?** If you no longer remember your Old PIN: - On the PIN Lock screen, click **"Forgot PIN / Recover Vault"**. - Enter your **12-Word BIP-39 Recovery Phrase**. - Enter a new Master PIN (6-8 digits for new PINs). - Confirm the **Confirm / Cancel** warning dialog. - Recovering verifies your phrase, then **preserves the existing vault file key** — your previously uploaded files stay fully readable. It re-enrolls **this** device under a fresh random device seed, purges the old PIN / legacy slots on this device so the old PIN can no longer unlock it, and leaves **every other device's** seed slot intact. A **Confirm / Cancel** warning precedes the step. (This is key-preserving recovery, not a key rotation.) ### What is High E2E Encryption? - **High E2E Encryption (Standard E2EE):** Client-side AES-256-GCM envelope encryption using a per-device key derived from your Master PIN via memory-hard Argon2id (96 MB, 4 passes for new vaults; 64 MB, 3 passes; PBKDF2 100,000-round fallback for legacy vaults). Offers flexible recovery options (12-word BIP-39 recovery phrase OR dual-channel 6-digit OTP via Saved Messages/Bot). Coexists seamlessly with standard features. Visualized by a **blue "Encrypted" badge with Lock icon**. ### How does Device Sharing work in High E2E Encryption across my phone and laptop? High E2E Encryption enables seamless, zero-touch device sharing across all your devices (Android phone, laptop, desktop browser, tablet): - **Decentralized Cloud Anchor:** When you enable High E2E Encryption, TG Drive stores your public salt and verification canary inside your Telegram Saved Messages under `#TG_DRIVE_VAULT_CONFIG#`. No private keys or PINs are ever saved in Telegram or sent to any central server. - **Cross-Device Unlock:** When you log into TG Drive on your second device using your Telegram account, the app automatically detects the vault config and prompts for your Master PIN. - **Instant Decryption:** Entering your Master PIN on the new device derives the identical 256-bit AES-GCM master key client-side. All files uploaded from your phone immediately unlock, preview, and download on your laptop without requiring manual key exports or config transfers. - **Two-Way Sync:** Files uploaded and encrypted on your laptop are immediately accessible and decryptable on your phone. ### What are the critical warnings when using High E2E Encryption? - **Telegram Saved Messages Warning:** Never delete `#TG_DRIVE_FILE#` or `#TG_DRIVE_VAULT_CONFIG#` messages in your Telegram Saved Messages chat. Deleting them disrupts file metadata and vault synchronization. - **Re-Login Old PIN Warning:** When you log out and log back in to the same Telegram account, TG Drive will ask for your **Old PIN** to decrypt existing files. Setting an unlinked new PIN on login is blocked because it would derive a mismatched key and corrupt all existing files. - **Recovery Phrase Security:** Keep your 12-word recovery seed written down safely offline. Never share it with anyone. ### Why is my 12-word recovery phrase not stored in Telegram Saved Messages (even encrypted with AES)? TG Drive enforces a strict **Zero-Knowledge** architecture. Storing root recovery phrases on cloud servers (even under AES encryption) weakens the threat model by exposing recovery material to cloud message compromise. The 12-word root mnemonic is maintained strictly client-side. ### If my computer shuts down suddenly (e.g., unexpected power cut / blackout), will my 12-word phrase be lost? **No.** TG Drive persists encrypted vault state and credentials using browser IndexedDB and LocalStorage, which run atop transactional SQLite engines configured with Write-Ahead Logging (WAL). Atomic transactions ensure that once stored, sudden power cuts or OS crashes will not corrupt or wipe your 12-word recovery phrase or vault keys. (As an ultimate safeguard, always keep an offline physical paper or metal backup of your 12 words). ### Does file key rotation terminate my active Telegram session? **No.** TG Drive performs atomic session re-sealing. Whenever the vault file key is rotated or refreshed, the active MTProto session string is automatically re-encrypted under the new file key before saving. You will never experience premature logouts or unexpected session drops when unlocking after key rotation. --- ## 13. Secure Vault & Zero-Knowledge E2EE Architecture ### Cryptographic Specifications | Parameter | Standard / Value | Security Benefit | | :--- | :--- | :--- | | **Cipher & Mode** | AES-256-GCM | Authenticated symmetric encryption with 128-bit authentication tags; prevents tampering and bit-flipping. | | **Key Derivation (KDF)** | Argon2id (PBKDF2 legacy fallback) | Memory-hard key derivation that starves GPU/ASIC cracking; older vaults keep PBKDF2 for byte-identical key continuity. | | **KDF Cost Parameters** | 96 MB memory / 4 passes (new vaults) | Every guess must allocate 96 MB of RAM, multiplying the cost of offline brute-force attacks. Scales down on low-RAM devices instead of weakening the algorithm. | | **Entropy Salt** | 128 bits (16 bytes CSPRNG) | Unique per vault; generated via `crypto.getRandomValues`. Prevents pre-computed rainbow tables. | | **Initialization Vector (IV)** | 96 bits (12 bytes unique/chunk) | Unique IV per encrypted chunk; absolute zero-IV-reuse guarantee. | | **Authentication Tag** | 128 bits (16 bytes) | Validates cryptographic authenticity before ciphertext is decrypted. | | **Canary Token** | `TG_DRIVE_VAULT_TEST` | Instant PIN validation without risking state corruption or partial decryption. | | **Cloud Sync Anchor** | Telegram Saved Messages | Zero external database; config stored as `#TG_DRIVE_VAULT_CONFIG#`. | | **Vault Config Integrity** | HMAC-SHA256 (HKDF from file key) | The published config is signed and verified on every unlock, so injected device slots or a swapped recovery verifier are detected as tampering. | | **Device Seed Wrap** | Argon2id (96 MB for new vaults) + attempt throttle | The never-published per-device seed is protected with memory-hard Argon2id and an exponential lockout (3 free tries); legacy PBKDF2 wraps keep loading. | | **Sealed Metadata** | AES-256-GCM under an HKDF-SHA256 key (envelope `v1.`) | File names, MIME types and folder membership are encrypted and AAD-bound to account + item + key epoch; the real filename is not written to the message caption or the Telegram document attribute. | | **Device Pairing** | Ephemeral ECDH P-256 + SAS | A new device is enrolled from an already-unlocked device over a real-time push approval or a one-time, expiring handshake; the file key is encrypted to the new device's ephemeral key and the raw key never travels. | | **Session Credentials at Rest** | AES-256-GCM (`VAULT_DATA_KEY`) | MTProto session string, API ID, API Hash, and Bot Token are stored encrypted; zero plaintext credentials in storage. | | **BIP-39 Mnemonic at Rest** | AES-256-GCM (`tg_vault_encrypted_recovery_phrase`) | 12-word phrase is encrypted at rest; decrypted strictly in volatile RAM when vault is unlocked; zero plaintext in localStorage/IDB. | | **Remote Session Revocation** | MTProto `Api.auth.LogOut` | Server-side authorization termination on Telegram core servers upon user logout prior to local cache purge. | | **Android Native Hardening** | `webContentsDebuggingEnabled: false`, Keystore Decoupled | Prevents USB/ADB DevTools memory inspection, blocks mixed-content injection, forbids ADB backup, and isolates release signing keys in CI/CD secrets. | ### The 13 Cryptographic Lifecycle Phases 1. **Phase 1: Entropy & Salt Generation:** Generates a 16-byte cryptographically secure random salt using `crypto.getRandomValues(new Uint8Array(16))`. 2. **Phase 2: Argon2id Key Derivation:** Derives a 256-bit AES-GCM `CryptoKey` from your Master PIN using memory-hard Argon2id (96 MB memory, 4 passes for new vaults; 64 MB, 3 passes for older ones). Because every guess must allocate 96 MB of RAM, GPU/ASIC brute-force farms lose their parallelism advantage. Vaults created before this hardening have no `kdf` tag and keep deriving with PBKDF2-HMAC-SHA256 (100,000 rounds), so existing PINs and files work unchanged. 3. **Phase 3: Canary Verification Token:** Encrypts `TG_DRIVE_VAULT_TEST` with a unique 12-byte IV. The ciphertext hex is stored in vault config to reliably verify PIN correctness. 4. **Phase 4: Session Credentials Hardening:** MTProto session string, API credentials, and bot tokens are encrypted with AES-256-GCM and stored in IndexedDB under `tg_vault_data`. Plain-text credentials are actively purged from storage to prevent local exfiltration. 5. **Phase 5: Automatic Cloud Sync via Saved Messages:** Dispatches `#TG_DRIVE_VAULT_CONFIG#` to Telegram Saved Messages containing the salt, canary ciphertext, and timestamp. Master keys and PINs are NEVER sent. 6. **Phase 6: Zero-Touch Multi-Device Cross-Unlock:** Secondary devices discover `#TG_DRIVE_VAULT_CONFIG#` automatically. Entering your Master PIN derives the matching key and unlocks your vault with zero manual configuration. A device without a matching PIN can be enrolled over a real-time push approval (approve on an already-unlocked device, then confirm the matching verification code before the key is released; a rejection fails the new device's login immediately) or a one-time QR / short-code handshake. 7. **Phase 7: File Encryption & Sealed Metadata:** File contents are encrypted with a fresh 12-byte IV per chunk. File names, MIME types and folder membership are sealed with AES-256-GCM under a dedicated HKDF-SHA256 metadata key (envelope `v1.`, AAD-bound to account + item + key epoch); the real filename is no longer written to the message caption or the Telegram document attribute. Byte size, upload timing and folder names remain visible. 8. **Phase 8: Streaming Chunk-Level Encryption & Decryption:** Files are split into 512 KB chunks, each encrypted with AES-GCM and its own tag. Downloads stream through the Service Worker directly to disk with RAM usage below 50 MB. 9. **Phase 9: Android Hardware Biometric Keystore & Native Container Hardening:** Interfaces with Android BiometricPrompt and Secure Hardware Keystore for fingerprint and facial authentication. The native Capacitor Android container enforces strict production hardening: Chrome DevTools remote debugging is disabled (`webContentsDebuggingEnabled: false`), mixed HTTP content is blocked (`allowMixedContent: false`, `MIXED_CONTENT_NEVER_ALLOW`), arbitrary top-level navigation is disabled (`allowNavigation: []`), ADB backups are forbidden (`android:allowBackup="false"`), and release signing keystores are decoupled from Git and secured via encrypted CI/CD secrets (`KEYSTORE_BASE64`). 10. **Phase 10: 12-Word BIP39 Root Seed & Disaster Recovery:** Standardized 12-word cryptographic seed is stored strictly encrypted at rest under `tg_vault_encrypted_recovery_phrase`. It is decrypted strictly in volatile memory (RAM) upon vault unlock, with zero plaintext stored in `localStorage` or `IndexedDB`. Allows instant derivation of the root master key and PIN reset without loss of encrypted data. 11. **Phase 11: Real-Time Session Termination Watchdog & Safe Logout Safeguard:** If a session is terminated remotely from Telegram Devices, TG Drive intercepts the event, preserves your recovery phrase in memory, and triggers the safeguard modal upon app launch. Final logout invokes `Api.auth.LogOut()` on Telegram core servers before executing local multi-tier cache wipes. 12. **Phase 12: Config-Leak-Safe Device Seed & Authenticated Config:** The shared file key is wrapped by a random 256-bit per-device seed that is **never published**; the seed is stored locally under memory-hard Argon2id (96 MB for new vaults) with an exponential attempt throttle (3 free tries, then a growing lockout; the seed is never destroyed), while legacy PBKDF2-wrapped seeds keep loading unchanged. The published `#TG_DRIVE_VAULT_CONFIG#` envelope is **HMAC-SHA256 authenticated** with an HKDF-derived key from the vault file key and verified on every unlock, so an injected device slot or a swapped recovery verifier is detected as tampering. New device slots never publish a PIN-wrapped file key. 13. **Phase 13: Secure Device Pairing (Two-Phase, ECDH P-256):** A new device is enrolled from an already-unlocked device without the recovery phrase. **Phase 1 (discovery)** exchanges a locator short code / QR (or a real-time push prompt); **Phase 2 (verification)** begins only after the unlocking device finds the request and performs an ephemeral ECDH exchange, publishing its ephemeral public key via a separate commit message. The new device then performs the same ECDH, derives the identical 6-digit **SAS**, and leaves the QR screen for a **Verify Code** screen; the vault key is released only by the mandatory **Confirm Match / Authorize** step, and a Reject fails the new device's login instantly. Delivery is self-healing: besides the real-time push, the unlocked device polls Saved Messages every ~2.5 s with timeout-bounded RPCs, exponential backoff, and a reconnect + immediate search sweep when connectivity returns. Up to **5 devices** per vault; a 6th drops the oldest slot. ### High E2E Encryption Architecture TG Drive's End-to-End Encryption (E2EE) is engineered to balance convenience, threat modeling, and absolute data sovereignty: #### 1. High E2E Encryption (Standard Zero-Knowledge E2EE) - **Architecture:** Client-side envelope encryption using AES-256-GCM. Per-device keys are derived from your Master PIN via memory-hard Argon2id (96 MB, 4 passes for new vaults; 64 MB, 3 passes for older ones) and a 16-byte random salt. Legacy vaults fall back to PBKDF2-HMAC-SHA256 (100,000 rounds) for byte-identical key continuity. - **Recovery Flexibility:** In addition to the permanent 12-word BIP-39 recovery seed, High E2EE supports dual-channel 6-digit OTP resets delivered directly to Telegram Saved Messages (MTProto) or via Telegram Bot. This enables convenient PIN resets without loss of the active Telegram session. - **Transport & Compatibility:** Coexists smoothly with standard MTProto features and metadata handling. - **Visual Identifier:** Displays a **blue "Encrypted" badge with Lock icon** on uploaded cards and transfers. - **Best Suited For:** Daily cloud storage, documents, multimedia, and users wanting strong cryptographic privacy with forgiving account recovery safety nets. #### Multi-Device Sharing Architecture (Zero-Touch Cross-Device File Access in High E2E) High E2E Encryption is purpose-built for seamless multi-device workflows (smartphones, Android native app, desktop browsers, tablets, and work laptops). 1. **Decentralized State Anchor via `#TG_DRIVE_VAULT_CONFIG#`:** - When High E2E Encryption is enabled on Device A, TG Drive publishes a lightweight JSON envelope to your personal Telegram Saved Messages under `#TG_DRIVE_VAULT_CONFIG#`. - This envelope contains ONLY public cryptographic parameters: the 16-byte KDF random salt, the encrypted verification canary (`TG_DRIVE_VAULT_TEST`), and device slot hashes. - Crucially, your private Master PIN, the 12-word recovery seed, and raw decryption keys are **NEVER** transmitted over the internet or stored in Telegram. 2. **Automated Cross-Device Discovery & Unlock:** - When you log into TG Drive on Device B (e.g., your laptop or tablet) using your Telegram phone number, TG Drive's background listener automatically scans your Saved Messages and detects `#TG_DRIVE_VAULT_CONFIG#`. - TG Drive instantly recognizes that your account has High E2E Encryption enabled and displays the Master PIN Unlock modal. - Enter your Master PIN on Device B. Using the cloud-synced salt and the slot's recorded KDF (Argon2id, or PBKDF2 for legacy vaults), Device B derives the exact same file-key wrapping key and authenticates against the canary token in volatile RAM. - Immediately, all encrypted files uploaded from Device A are decrypted and accessible on Device B. - Any new file uploaded and encrypted on Device B is instantly accessible and decryptable on Device A. 3. **Envelope Encryption & Shared File Key:** - Files are encrypted using a single 256-bit `sharedFileKey` (Vault File Key). - This key is wrapped inside each device's cryptographic envelope. - This enables seamless cross-device sharing without needing to re-encrypt your library when you switch devices. 4. **Hardware-Bound Device Slotting (Option A):** - Each device registers its own session slot in `deviceSlots` bound to local session storage (`BOUND_DEVICE_SALT_KEY`). - If you ever reset your PIN on one device using your 12-word recovery phrase, Device A updates its slot while Device B maintains continuity through the shared file key envelope. 5. **Multi-Primary Architecture & Peer Device Revocation:** - Any device initialized during vault setup or unlocked/recovered via the 12-Word Recovery Phrase is a **Primary Device**. Multiple primary devices can exist concurrently. - Any active Primary device has the administrative authority to revoke any other slot in real time—including another peer Primary slot. - Linked Seed devices (joined via QR code or push pairing without the 12-word phrase) have non-authoritative status: they cannot revoke or remove other devices. - Revoking a device purges its slot and records its salt in `revokedSalts`. Entering PIN on a revoked device rejects unlock and redirects to `/login`. ### ⚠️ Critical Security Warnings & Best Practices > [!WARNING] > **DO NOT DELETE TELEGRAM SAVED MESSAGES:** > Never manually delete messages tagged with `#TG_DRIVE_FILE#` or `#TG_DRIVE_VAULT_CONFIG#` inside your official Telegram app's "Saved Messages" chat. > - `#TG_DRIVE_FILE#` messages store the file chunk pointers and VFS metadata. > - `#TG_DRIVE_VAULT_CONFIG#` stores the cryptographic salt and canary tokens needed for multi-device sync and PIN verification. > Deleting these messages breaks the cloud index and disrupts file streaming. > [!IMPORTANT] > **RE-LOGIN PIN REQUIREMENT (KEY CONTINUITY):** > When logging out of TG Drive and logging back in with the same Telegram account, TG Drive will **always demand your existing (Old) Master PIN**, not a new PIN. > - Setting a "new" PIN on a fresh login is intentionally blocked because deriving a different key would corrupt and permanently lock all previously encrypted files. > - If you have genuinely forgotten your Master PIN, use the **"Forgot PIN / Recover Vault"** option with your 12-word recovery phrase (or OTP in High E2E). Recovering verifies ownership, then **preserves the existing vault file key** (so your files stay readable), re-enrolls this device under a fresh random device seed, and purges the old PIN/legacy slots — while leaving every other device's seed slot intact. > [!TIP] > **DEVICE SHARING BEST PRACTICE:** > When opening TG Drive on a new phone, desktop browser, or tablet, make sure you enter the **exact same Master PIN** configured on your primary device. This ensures immediate synchronization and seamless access to all your High E2E encrypted files. ### Architectural Deep Dives #### Re-Login Cryptographic State Preservation (Why Old PIN is Demanded After Logout) When you log out and log back into the same Telegram account, TG Drive immediately requests your old PIN rather than prompting you to set a new PIN. Here is the architectural and cryptographic rationale behind this security behavior: 1. **Decentralized State Anchor in Saved Messages (`#TG_DRIVE_VAULT_CONFIG#`):** TG Drive is a pure client-side application with zero external databases. Your vault state (the KDF salt, canary token, and device slots) is anchored directly in your personal Telegram **Saved Messages** under `#TG_DRIVE_VAULT_CONFIG#`. 2. **Logout Scope (Local Device vs. Cloud State):** When you log out from TG Drive: - TG Drive executes an 8-tier local cache purge: deleting IndexedDB, Dexie VFS, Cache API, in-memory keys, and local session tokens. - However, TG Drive does **NOT** delete your Telegram Saved Messages or your uploaded files. Your encrypted data and your `#TG_DRIVE_VAULT_CONFIG#` message remain untouched on Telegram core servers. 3. **Why Prompting for a "New PIN" Would Cause Fatal Data Loss:** Every encrypted file in your account was encrypted with an AES-256-GCM Master Key derived from: $$\text{Device Key} = \text{Argon2id}(\text{Old PIN}, \text{Salt}, 64\,\text{MB}, 3)$$ If TG Drive allowed an unverified "New PIN" upon re-login, the key derivation function would derive an entirely different 256-bit key: $$\text{New Key} = \text{Argon2id}(\text{New PIN}, \text{New Salt}, 64\,\text{MB}, 3) \neq \text{Device Key}$$ Because symmetric AES-GCM decryption requires the exact key used during encryption, this new key would fail authentication tags on every existing file. **All previously uploaded files would become permanently unreadable and corrupted.** 4. **Instant Vault Discovery Upon Re-Login:** When you log back in with your phone number and Telegram OTP, TG Drive automatically inspects your Saved Messages. It discovers `#TG_DRIVE_VAULT_CONFIG#` and immediately recognizes that an initialized vault exists. To protect your existing files, it prompts for your **Old PIN** to unlock the existing key envelope. 5. **PIN Reset via 12-Word Recovery Phrase (Key-Preserving):** If you have forgotten your Old PIN, recovery verifies ownership and re-enrolls this device without touching the underlying file key: - Click **"Forgot PIN / Recover Vault"**. - Input your **12-Word BIP-39 Recovery Phrase**. - Enter your desired **New PIN**. - Confirm the **Confirm / Cancel** warning dialog. - TG Drive verifies the phrase by decrypting the published recovery verifier, then **keeps the existing vault file key** so previously uploaded files stay readable. This device is re-enrolled under a fresh random device seed; the old PIN/legacy slots are purged so the old PIN can never unlock again, while every **other device's seed slot is preserved** so those devices keep working untouched. #### Multi-Device Sync Without Central Servers TG Drive uses your personal Telegram Saved Messages as a secure, decentralized state anchor. The `#TG_DRIVE_VAULT_CONFIG#` message stores only the public 16-byte salt and encrypted canary token. When you enter your PIN on a phone, laptop, or tablet, the client validates the canary and derives the master key locally. #### Strict Device-Specific Lock (Option A) & Envelope Encryption - **Hardware-Bound PIN:** Each physical device is bound to its own unique salt and device slot in `config.deviceSlots` via `BOUND_DEVICE_SALT_KEY`. - **PIN Isolation:** A PIN set on Device 1 will strictly fail on Device 2 with `"Incorrect Master Password or PIN"`, preventing unauthorized unlock across shared devices. - **Envelope Encryption Decryption:** Files are encrypted with a single master `sharedFileKey`. Each device slot holds an encrypted copy of this key, guaranteeing 100% seamless cross-device file decryption and synchronization. - **Forgot Password Behavior:** Recovery via the 12-word phrase preserves the existing vault file key, so previously uploaded files stay readable. It re-enrolls *this* device under a fresh random device seed and purges the old PIN/legacy slots (the old PIN can never unlock again), while leaving every **other device's seed slot intact** — those devices are not disturbed. #### No Account-Level Escrow Key (Zero-Knowledge Integrity) TG Drive does **not** use any account-level escrow key, and the vault file key (`sharedFileKey`) is never derived from public data such as your Telegram user ID. It cannot be reconstructed from the published `#TG_DRIVE_VAULT_CONFIG#` message alone — that message contains only public KDF salts, per-device slots whose file key is wrapped by that device's **unpublished random 256-bit device seed** (legacy migration slots may still carry a PIN-derived envelope; new slots never do), the HMAC signature over the config, and the recovery verifier wrapped by your 12-word phrase. Each slot records the KDF that produced it, so a leaked config cannot be attacked with a cheaper legacy PBKDF2 derivation. **Opening an existing vault on a new device:** 1. Log in with the **same Telegram account** (required — the vault config and ciphertext live in that account's Saved Messages). 2. Choose one of three enrollment paths: - **Link with another device (recommended):** open **Link with another device** on the new device. It sends a link request, and any already-unlocked device surfaces an **Approve / Deny** prompt in real time — tap **Approve** (no camera needed). Alternatively the new device shows a QR code and short code which the unlocked device scans or types. Either way both devices display the same 6-digit **SAS code** to compare. The file key is handed over an ephemeral ECDH channel and never appears in plaintext on Telegram. - **Same Master PIN:** if another device already uses a PIN-matched slot, enter that same PIN (the client matches it against that device's slot). - **Recovery phrase:** tap **Forgot PIN / Recover Vault** and enter your **12-word recovery phrase** (key-preserving; see the recovery section above). A new device that has none of these is blocked from creating a second, mismatched key. > Legacy vaults created before this change may still carry a deprecated escrow field; it is removed automatically the next time the config is republished. #### Device-Seed Hardening & Authenticated Vault Config - **Config-Leak-Safe Device Seed:** The random per-device seed that wraps the file key is stored only on-device and is now protected with **memory-hard Argon2id (96 MB, 4 passes for new vaults; 64 MB, 3 passes for older ones)** instead of PBKDF2, plus an **exponential attempt throttle** (3 free tries, then a growing lockout; the seed is never destroyed). A copied IndexedDB blob therefore cannot be cheaply brute-forced with the 6-8 digit PIN, and legacy PBKDF2-wrapped seeds keep loading unchanged. - **Authenticated Vault Config:** The published `#TG_DRIVE_VAULT_CONFIG#` envelope is signed with **HMAC-SHA256** using an HKDF-derived key from the vault file key. Each device verifies the signature after unlocking, so an injected device slot or a swapped recovery verifier is flagged as tampering instead of being silently trusted. Volatile fields (message ID, timestamp) are excluded from the signed view so republishing never invalidates a good signature. - **No New PIN-Wrapped Slots:** New device slots never publish a PIN-wrapped copy of the file key; only the unpublished seed scheme (and legacy migration slots) can open it. - **Non-Destructive Recovery:** Recovery preserves the shared file key and every *other* device's seed slot; only this device is re-enrolled, and old PIN/legacy slots are purged. #### Secure Device Pairing (Real-Time Push / QR / Short Code) Enrolling a new device no longer requires the recovery phrase. On the new device, choose **Link with another device** (available on the lock screen too). It posts a link request and shows both a QR code and a human-typable short code (e.g. `7K4M-2M9`); any already-unlocked device shows an **Approve / Deny** prompt in real time, so it can be approved with a single tap. If you prefer manual entry, open **Settings → (Vault) → Add a device** on the unlocked device, then scan the QR or type the code. - **One-time ephemeral ECDH:** Each side mints a fresh **P-256** keypair for the pairing and discards it afterwards. Both derive a shared secret and an **HKDF-SHA256** key; the file key is sent as an **AES-256-GCM** bundle encrypted to the new device's ephemeral key, so the raw key never appears in Telegram (nor in plaintext on the wire). - **Approval-gated (two phases):** Phase 1 is discovery — the new device shows the short code / QR and the unlocked device scans or types it (or taps the real-time prompt). Phase 2 is SAS confirmation — only after the unlocked device finds the request and performs the ECDH exchange does it publish its ephemeral public key, and **only then** does the new device leave the QR screen for a **Verify Code** screen showing the exact same 6-digit code. The two codes are compared while both are on screen, and the file key is released only by the trusted device's **Confirm Match / Authorize**; the new device's own PIN step unlocks only afterwards. - **Short Authentication String:** both screens display the same 6-digit code derived from the shared secret; if they differ, a man-in-the-middle is present and the user must cancel. The SAS is computed locally on each side and is never transmitted. - **Reliable delivery across networks:** the request also reaches the unlocked device by an active poll of Saved Messages every ~2.5 s (in addition to the real-time push), so it still appears when the MTProto socket is lost while switching networks; a dropped connection shows a clear "Reconnecting…" state instead of a silent spinner. Every pairing RPC is **timeout-bounded** (a half-open socket can never wedge the poll loop), failures **back off exponentially** instead of hammering Telegram, a dropped socket is **actively reconnected**, the network coming back triggers an **immediate deep sweep**, and a search is forced whenever no request is present in the newest window — so leftover pairing artefacts can't hide a live request. If the vault is locked when a request lands, a notice prompts the user to unlock. - **Expiring and single-use:** the short code is only a locator and expires after **5 minutes**; link messages are deleted as soon as the handshake finishes. - **Zero-knowledge preserved:** pairing moves the same file key between your own devices; the QR and short code carry only public keys and a locator, never a secret. - **Connected Devices:** Vault settings list every enrolled slot. **Up to 5 devices** can be linked at once (shown as a `used/5` counter) — linking a 6th drops the **oldest** slot, so that device must be re-linked or recovered. The list also allows **revoking** another device. Revocation is **sticky**: the removed salt is recorded in the published config (which is re-signed) and can't be re-added from a stale local cache, so the device can no longer unlock. The revoked device is **locked out in real time** as soon as it receives the updated config, and the list updates across all devices on every add / revoke / logout. Every revoke **also rotates the shared file key** (always on — it is not a user setting), so a revoked device cannot read anything uploaded from then on; files it read before the revoke stay readable on the remaining devices. - **File-Key Rotation on Revoke (Static Exchange Key):** Enrolling a device also mints a static **P-256 exchange keypair**. Only the public half (`kxPub`) is published in the device's slot; the private half is stored locally, encrypted under that device's never-published seed. **Every revoke now uses it**: a new epoch key is generated and wrapped to each remaining device via ECDH without needing any other device's seed, and the revoked device is simply not given it — so it cannot read anything uploaded from then on. Rotation is **always on and cannot be switched off from the UI**; if the revoking device holds no seed/exchange key (a legacy PIN-only device) the app says so instead of reporting a revoke whose protection was silently skipped. Because the private half is protected by the device seed, a device that loses its seed must re-enroll (link or recovery) before it can receive future epoch keys. #### Accidental Deletion of `#TG_DRIVE_VAULT_CONFIG#` (Real-Time Auto-Recovery) - Your encrypted files are NOT deleted or corrupted. The vault config message only stores public salts and canary tokens. - **Real-Time Auto-Heal Watchdog:** TG Drive's auto-recovery engine continuously monitors Telegram Saved Messages. If the `#TG_DRIVE_VAULT_CONFIG#` message is deleted, any active device with a local vault cache automatically re-publishes it back to Saved Messages within seconds (upon routine sync, MTProto deletion events, or window focus). - If all devices were logged out, entering your 12-word recovery phrase generates a fresh salt, re-derives the master key, sets a new PIN, and publishes a new config. #### Clearing Browser Cache or Reinstalling App - Wiping cookies or reinstalling the APK clears local cache, but all encrypted files and `#TG_DRIVE_VAULT_CONFIG#` remain safe in Telegram. - Log back in with your phone number and Telegram OTP. - TG Drive retrieves the config from Saved Messages, prompts for your Master PIN, and unlocks all files immediately. #### Remote Telegram Session Termination Watchdog When Telegram invalidates a session (`AUTH_KEY_UNREGISTERED` or `SESSION_REVOKED`), TG Drive intercepts the event, preserves your 12-word recovery phrase in volatile in-memory only (it is never written to disk), and displays the Session Safeguard Modal with Copy and Download as .TXT buttons. #### Concurrency Control (Device Slotting) Version 2 vault configuration supports independent device session slots (`deviceSlots`). Each client updates its own slot keyed by a unique device salt hash, while Telegram's monotonic 32-bit message IDs resolve race conditions deterministically. #### Multi-Primary Architecture & Peer Revocation Authority - **Multi-Primary Coexistence:** Multiple primary devices can exist at once (the original creator + any device authenticated with the 12-Word Recovery Phrase). - **Peer Primary Revocation:** Any active Primary device holds administrative authority to revoke any other device slot in real time—including another primary device slot (e.g. if an old primary phone was lost, sold, or its Telegram session terminated). - **Linked Seed Restrictions:** Devices linked via QR / push pairing without the 12-word phrase operate as Linked Seed Devices. They have full read/write file access, but are strictly non-authoritative: they cannot revoke or remove other devices. - **Revoked Device Lockout & Re-Login Protocol:** When a device is revoked by an active Primary, its slot is purged and its salt is added to the `revokedSalts` denylist in `#TG_DRIVE_VAULT_CONFIG#`. Entering PIN on a revoked device rejects unlock with an explicit revocation notice and redirects directly to `/login`. To rejoin, the user must authenticate via Telegram and recover using their 12-word recovery phrase or re-link via an active Primary. - **Zero-Knowledge Phrase Storage & Power Crash Durability:** The 12-word recovery phrase is never uploaded to Telegram Saved Messages (even encrypted with AES) to preserve zero-knowledge boundaries. The phrase and vault keys are stored locally in transactional SQLite/IndexedDB (WAL mode) and survive sudden PC power cuts or hard reboots intact. - **Session Re-Sealing on File Key Rotation:** When the vault file key is rotated or refreshed, the active MTProto session string is automatically re-sealed under the new key, ensuring seamless session continuity without losing login state. #### Stolen Phone Threat Modeling 1. Terminate the session immediately from any other device via Telegram: `Settings → Devices → Terminate Session`. 2. All offline session data in IndexedDB is encrypted with AES-256-GCM and requires your Master PIN. 3. On Android devices, biometric keys are isolated inside the hardware Secure Enclave. 4. **Remote Slot Revocation:** Perform a password reset using your 12-word recovery phrase on another device to revoke and overwrite the stolen device's slot in the cloud config forever. #### 12-Word BIP39 Root Seed vs Master PIN | Attribute | Master PIN (6-8 digits for new PINs) | 12-Word Recovery Phrase | | :--- | :--- | :--- | | **Purpose** | Daily quick unlocking on local device | Root master cryptographic seed | | **Entropy** | Argon2id (96 MB / 4 passes for new vaults) + 16-byte salt | 128-bit BIP39 dictionary | | **Portability** | Validated via cloud canary token | Universal: restores vault on any device | | **Resettability** | Reset anytime using 12-word phrase | Permanent root master key | | **At-Rest Security** | Non-extractable CryptoKey in RAM | AES-256-GCM encrypted in IndexedDB (`tg_vault_encrypted_recovery_phrase`) | #### Zero-Plaintext Secret Architecture - **No Plaintext Recovery Phrase:** The 12-word BIP-39 recovery mnemonic is never saved in plaintext in browser `localStorage` or unencrypted IndexedDB tables. It is encrypted at rest using AES-256-GCM and only decrypted in volatile memory when the vault is unlocked. - **No Plaintext Session Credentials:** MTProto session authorization strings, API ID, API Hash, and Bot Tokens are encrypted inside `VAULT_DATA_KEY`. Plaintext fallback records are purged from storage. - **Server-Side Session Revocation:** Logout explicitly calls Telegram's `Api.auth.LogOut()` method over MTProto to terminate the authorization key on Telegram's core servers. #### 8-Tier Cache Purging & Server-Side Revocation on Logout 0. **Tier 0 - Server-Side MTProto Revocation:** Calls `Api.auth.LogOut()` over MTProto to permanently destroy the session authorization key on Telegram's core servers. 1. **Tier 1 - IndexedDB Clearance:** `idb.clear()` wipes all cached session strings, encrypted credentials, and decrypted vault tokens. 2. **Tier 2 - Dexie VFS DB:** Purges all indexed folder structures, file metadata records, and pending offline queues. 3. **Tier 3 - Browser Cache API:** Calls `caches.delete()` for thumbnail blobs and media streaming chunks. 4. **Tier 4 - In-Memory Caches:** Revokes blob URLs and clears MTProto message caches. 5. **Tier 5 - LocalStorage Reset:** Wipes profile, transfer, and account data (preserves user preferences like Dark Mode). 6. **Tier 6 - SessionStorage Purge:** Empties temporary tab sessions and revocation buffers. 7. **Tier 7 - Android Biometric Keystore:** Destroys biometric enclave keys via Capacitor NativeBiometric API. #### Android Native Container Hardening & Keystore Protection - **Disabled Chrome DevTools Remote Debugging:** Remote debugging over USB/ADB is permanently disabled via `"webContentsDebuggingEnabled": false` in `capacitor.config.json` and explicit `WebView.setWebContentsDebuggingEnabled(false)` in `MainActivity.java`. This prevents adversaries from attaching DevTools to inspect in-memory cryptographic keys or dump local storage. - **Top-Level Navigation & Mixed-Content Blocking:** Restricts WebView navigation strictly to the local bundle (`allowNavigation: []`), forcing external links into the system browser and blocking HTTP mixed-content injections (`allowMixedContent: false` and `MIXED_CONTENT_NEVER_ALLOW`). - **ADB Backup Prevention:** Android Manifest enforces `android:allowBackup="false"` and `android:usesCleartextTraffic="false"`, preventing attackers from dumping local app databases via `adb backup`. - **Keystore Protection & CI/CD Decoupling:** Production release signing keystores (`*.keystore`, `*.jks`) are strictly excluded from Git tracking via `.gitignore`. CI/CD automated builds dynamically decode signing keystores from encrypted GitHub Secrets (`KEYSTORE_BASE64`) or synthesize a secure build-time keystore, eliminating private key leakage. --- ## 14. Desktop Experience & Keyboard Shortcuts ### Desktop Context Menus & Drag-and-Drop - **File Card Context Menu:** Right-click any file card to Download, Star/Favorite, Rename, View File Info, or Move to Trash. - **Background Context Menu:** Right-click empty workspace to Upload Files, Create New Folder, Select 100 Items, or Refresh Data. - **Drag & Drop:** Drag files directly from your desktop into the browser. A frosted glass drop zone validates 100-file batches and 2.0 GB file limits. ### Keyboard Shortcuts Reference #### File & Folder Operations - `U` - Open Upload dialog (up to 100 files) - `N` - Create New Folder - `Del` - Move selected/hovered item to Trash - `F2` - Rename selected item - `F` - Toggle Favorite / Star - `Enter` - Open Download / Preview modal - `Alt + R` - Restore selected file(s) from Trash - `Ctrl + A` - Select 100 items in batch - `Esc` - Close active modals, menus, or clear selection #### Global Navigation & Controls - `?` (or `Shift + /`) - Open Keyboard Shortcuts Cheat Sheet Modal - `Ctrl + K` - Global Quick Search - `/` - Focus Search Bar - `1` - Navigate to Dashboard (Home) - `2` - Navigate to File Manager (All Files) - `3` - Navigate to Media Gallery - `4` - Navigate to Transfers Queue - `5` - Navigate to Settings & Vault - `6` - Navigate to Storage Details (`Alt + S`) - `7` - Navigate to Favourite Files (`Alt + F`) - `8` - Navigate to Trash / Bin (`Alt + T`) - `9` - Navigate to Recent Files - `R` - Refresh Telegram Cloud Data --- ## 15. Privacy, Stealth Shield & Security - **Zero-PII Anonymous Telemetry:** Complete isolation of personal identity. No Telegram User IDs, usernames, phone numbers, session keys, bot tokens, or file metadata are ever written to Firebase or any external database. - **Daily Non-Reversible Aggregates:** Firebase Realtime Database tracks strictly anonymous aggregate metrics under `stats/daily/YYYY-MM-DD` (total unique daily sessions, total logins, new client visits, and coarse platform distribution) using non-reversible one-way cryptographic hashing. - **Zero File Logging:** TG Drive never logs, tracks, or stores your personal files, file names, or IP addresses on any external server. - **Pure Client-Side Architecture:** The application code is hosted on Cloudflare Pages as a static PWA. Direct MTProto communication ensures Telegram handles all transport encryption. - **Privacy & Stealth Shield:** - **Hide Username:** Blurs `@username` across Sidebar, Profile Drawer, Settings, and PIN lock screen. - **Blur Phone Number:** Blurs phone number with hover-to-reveal. - **Blur Media Thumbnails:** Blurs all image thumbnails across Gallery and File Manager for privacy in public spaces. - **Independent Toggles:** Each setting can be enabled or disabled independently in Profile Drawer or Settings.