Skip to content

Chunky-Chat — End-to-End Encryption & Chat Restore ​

This document describes how Chunky-Chat encrypts messages between clients and how a user recovers their chats after losing a device.

The server stores ciphertext only. Messages, conversation keys, and private keys are never sent to the backend in plaintext form. All cryptographic operations run in the browser via the WebCrypto API.


1. Keys Used ​

Three keys with distinct roles:

KeyTypeLives whereJob
Device keypairECDH P-256 (asymmetric)Browser IndexedDB (private), Postgres (public only)Identity of a single browser/device. Used to wrap conversation keys.
Conversation keyAES-256 (symmetric, 32 bytes)In-memory cache on each member's deviceEncrypts every message in one conversation.
Backup keyAES-256 derived from passphrase via ScryptNot stored; re-derived from the passphrase on demandEncrypts the device private key before upload to the server.

Algorithms: ECDH-P256 + HKDF-SHA256 + AES-256-GCM for key wrapping, AES-256-GCM for message payloads, Scrypt(N=32768, r=8, p=1) for the passphrase-based backup.


2. End-to-End Encryption — Overview ​

text
┌──────────────────────────────┐                ┌──────────────────────────────┐
│           ALICE              │                │            BOB               │
│   (browser, device A)        │                │    (browser, device B)       │
│                              │                │                              │
│  privKey_A   (in IndexedDB)  │                │  privKey_B   (in IndexedDB)  │
│  pubKey_A                    │                │  pubKey_B                    │
│  conversation key K  (RAM)   │                │  conversation key K  (RAM)   │
└──────────────┬───────────────┘                └──────────────┬───────────────┘
               │                                               │
               │  encrypted message (AES-GCM)                  │
               │  wrapped K  (ECDH → HKDF → AES-GCM)           │
               ▼                                               ▲
       ┌────────────────────────────────────────────────────────────┐
       │                    CHUNKY-CHAT BACKEND                     │
       │                                                            │
       │  Postgres                          ScyllaDB                │
       │  ┌────────────────────────┐        ┌─────────────────────┐ │
       │  │ user_devices           │        │ messages            │ │
       │  │  • public_jwk only     │        │  • content = cipher │ │
       │  ├────────────────────────┤        │  • never decrypted  │ │
       │  │ participant_device_keys│        └─────────────────────┘ │
       │  │  • wrapped_key (opaque)│                                │
       │  ├────────────────────────┤                                │
       │  │ users.e2ee_..._backup  │                                │
       │  │  • passphrase-encrypted│                                │
       │  └────────────────────────┘                                │
       │                                                            │
       │  Server has no key material to decrypt any of the above    │
       └────────────────────────────────────────────────────────────┘

3. Setting Up a New Device (first login) ​

text
┌─────────────────────────────────────┐        ┌─────────────────────────────┐
│           USER (browser)            │        │           SERVER            │
└──────────────────┬──────────────────┘        └──────────────┬──────────────┘
                   │                                          │
 ┌─────────────────┴─────────────────┐                        │
 │ 1. Generate ECDH P-256 keypair    │                        │
 │    (extractable, just for backup) │                        │
 └─────────────────┬─────────────────┘                        │
                   │                                          │
 ┌─────────────────┴─────────────────┐                        │
 │ 2. Export pubKey as JWK           │                        │
 └─────────────────┬─────────────────┘                        │
                   │  POST /api/e2ee/devices  { public_jwk }  │
                   ├─────────────────────────────────────────►│
                   │                            ┌─────────────┴─────────────┐
                   │                            │ store public_jwk in       │
                   │                            │ user_devices              │
                   │                            └─────────────┬─────────────┘
                   │     201 Created  { device_id }           │
                   │◄─────────────────────────────────────────┤
                   │                                          │
 ┌─────────────────┴─────────────────┐                        │
 │ 3. Prompt user for passphrase     │                        │
 │    (≥ 12 chars)                   │                        │
 ├───────────────────────────────────┤                        │
 │ 4. salt = random(16)              │                        │
 │    iv   = random(12)              │                        │
 │    raw  = scrypt(pass, salt,      │                        │
 │            N=32768, r=8, p=1)     │                        │
 │    blob = AES-GCM(raw, iv,        │                        │
 │            JSON{ device_id,       │                        │
 │                  pub_jwk,         │                        │
 │                  priv_jwk })      │                        │
 └─────────────────┬─────────────────┘                        │
                   │  PUT /api/users/me/e2ee/backup { blob }  │
                   ├─────────────────────────────────────────►│
                   │                            ┌─────────────┴─────────────┐
                   │                            │ store opaque blob in      │
                   │                            │ users.e2ee_private_key_   │
                   │                            │ backup  (opaque to server)│
                   │                            └─────────────┬─────────────┘
                   │              200 OK                      │
                   │◄─────────────────────────────────────────┤
                   │                                          │
 ┌─────────────────┴─────────────────┐                        │
 │ 6. Re-import privKey as           │                        │
 │    non-extractable, save IndexedDB│                        │
 ├───────────────────────────────────┤                        │
 │ 7. Wipe passphrase from memory    │                        │
 └───────────────────────────────────┘                        │

After step 7 the server holds the public_jwk and an encrypted backup blob. The blob can only be decrypted with the user's passphrase, which is never sent to the server.


4. Sending a Message (Alice → Bob) ​

text
┌──────────────────────── ALICE'S BROWSER ────────────────────────┐
│                                                                 │
│  Step 1 — get conversation key K                                │
│  ─────────────────────────────────                              │
│  if K not in cache:                                             │
│     fetch GET /api/conversations/{id}                           │
│       → server returns wrapped_K + wrapper's public JWK         │
│     shared = ECDH(my_priv_A, wrapper_pub)                       │
│     aesKey = HKDF-SHA256(shared, salt, info)                    │
│     K      = AES-GCM-decrypt(aesKey, iv, wrapped_K,             │
│                              AAD="wrap:<uid>:<did>:v1")         │
│     cache K in memory                                           │
│                                                                 │
│  Step 2 — encrypt the message                                   │
│  ─────────────────────────────                                  │
│  msg_id    = uuid()                                             │
│  iv        = random(12)                                         │
│  AAD       = "msg:<convId>:<senderId>:<msg_id>:v2"              │
│  cipher    = AES-256-GCM(K, iv, AAD, plaintext)                 │
│  payload   = { v:2, msg_id, iv_b64, ct_b64 }                    │
│                                                                 │
└──────────────────────────────┬──────────────────────────────────┘
                               │  WebSocket frame
                               │  { type:"message", content: payload }
                               ▼
┌──────────────────────── SERVER ─────────────────────────────────┐
│  Stores payload as-is in ScyllaDB messages.content              │
│  Fans out to other members via Redis pub/sub                    │
│  No decryption performed; server holds no key material.         │
└──────────────────────────────┬──────────────────────────────────┘
                               │
                               ▼
┌──────────────────────── BOB'S BROWSER ──────────────────────────┐
│  Has K already (or unwraps it like Alice did in Step 1).        │
│                                                                 │
│  AAD       = "msg:<convId>:<senderId>:<msg_id>:v2"              │
│  plaintext = AES-256-GCM-decrypt(K, iv, AAD, cipher)            │
│  display(plaintext)                                             │
│                                                                 │
│  If decrypt fails → key may have rotated → drop cache,          │
│  refetch wrapped_K, retry once.                                 │
└─────────────────────────────────────────────────────────────────┘

The AAD binds each ciphertext to its conversation, sender, and message ID, so the server cannot reshuffle messages between conversations or replay them.


5. Creating a Conversation (key wrapping) ​

When Alice creates a group with Bob and Carol, she generates one fresh K and wraps it once per recipient device (someone with 2 devices = 2 wraps):

text
   K = random 32 bytes        ← the conversation key

   for each member device d:
       shared_d  = ECDH(alice_priv, d.pubKey)
       aesKey_d  = HKDF-SHA256(shared_d, salt_d, info)
       wrapped_d = AES-GCM(aesKey_d, iv_d,
                            AAD="wrap:<uid_d>:<did_d>:v1", K)

   POST /api/conversations
      { members: [...],
        e2ee_keys: [
          { user_id, device_id, wrapped_key: wrapped_d }, ...
        ] }

The server stores each wrapped_key row in participant_device_keys. Only the device whose private key matches can unwrap its corresponding row; other rows cannot be decrypted by that device.


6. Chat Restore — Overview ​

A user logs in on a new browser after losing their previous device. The goal is to recover the message history. The server does not receive any key material during this flow.

text
   ┌─────────────┐     password        ┌──────────────┐
   │  new device │ ──────────────────► │   backend    │
   │  (browser)  │  ◄── JWT ────────── │              │
   └──────┬──────┘                     └──────┬───────┘
          │                                   │
          │  GET /api/users/me/e2ee/backup    │
          │ ─────────────────────────────────►│
          │  ◄── encrypted backup blob ───────│
          │                                   │
   ┌──────▼─────────────────────────┐         │
   │  Ask user for E2EE passphrase  │         │
   │  raw = scrypt(pass, salt)      │         │
   │  json= AES-GCM-decrypt(raw,    │         │
   │            iv, blob)           │         │
   │  → device_id, pub_jwk, priv_jwk│         │
   │  Import priv_jwk as            │         │
   │   non-extractable CryptoKey    │         │
   │  Save to IndexedDB             │         │
   └──────┬─────────────────────────┘         │
          │                                   │
          │  GET /api/conversations           │
          │ ─────────────────────────────────►│
          │  ◄── list of conversations ───────│
          │                                   │
          │  for each conversation c:         │
          │    GET /api/conversations/c       │
          │      (header: X-Device-Id)        │
          │    ◄── wrapped_K, wrapper_pubJWK ─│
          │    K = unwrap(wrapped_K, my_priv, │
          │               wrapper_pub)        │
          │    cache K                        │
          │                                   │
          │  GET /api/messages?conv=c         │
          │ ─────────────────────────────────►│
          │  ◄── ciphertext history ──────────│
          │                                   │
          │  decrypt each with K → done.      │
          └───────────────────────────────────┘

Restore Flow as a Sequence Diagram ​

text
 user           new browser              backend                  storage
  │                 │                       │                       │
  │  password       │                       │                       │
  ├────────────────►│   POST /auth/login    │                       │
  │                 ├──────────────────────►│  bcrypt verify ──────►│
  │                 │◄────── JWT ───────────│                       │
  │                 │                       │                       │
  │                 │ ensureDeviceKeypair() │                       │
  │                 │  → no key in IndexedDB                        │
  │                 │ GET /e2ee/backup      │                       │
  │                 ├──────────────────────►├──────────────────────►│
  │                 │◄── { backup: blob } ──┤◄──── postgres ────────│
  │                 │                       │                       │
  │ passphrase      │                       │                       │
  ├────────────────►│ scrypt → AES-GCM dec  │                       │
  │                 │ recover priv_jwk      │                       │
  │                 │ store in IndexedDB    │                       │
  │                 │                       │                       │
  │                 │ for each conversation:│                       │
  │                 │ GET /conversations/id │                       │
  │                 ├──────────────────────►├──────────────────────►│
  │                 │◄── wrapped_K ─────────┤◄── postgres ──────────│
  │                 │ ECDH+HKDF+AES-GCM     │                       │
  │                 │   → unwrap K          │                       │
  │                 │                       │                       │
  │                 │ GET /messages?conv=id │                       │
  │                 ├──────────────────────►├──────────────────────►│
  │                 │◄── ciphertexts ───────┤◄── scylladb ──────────│
  │                 │ AES-GCM decrypt with K│                       │
  │                 │ render chat           │                       │

What Each Side Knows During Restore ​

StepNew device knowsServer knows
After loginJWT, user_iduser authenticated
After backup fetchencrypted blobserved blob (still opaque)
After passphrase entrypassphrase, priv_jwknothing new
After unwrapconversation keysstill only wrapped blobs
After message fetchplaintext historystill only ciphertext

The server only ever observes opaque blobs and ciphertexts during this flow.


7. Key Rotation (member removed) ​

When a member is removed by an admin, the conversation key is replaced so that the removed member's cached K cannot decrypt subsequent messages:

text
admin client                           server                           other members
─────────────                          ──────                           ─────────────
generate K_new
for each remaining device d:
  wrap K_new for d
POST .../members (remove + new keys) ►
                                      DELETE participant_device_keys
                                           WHERE conversation = c
                                      INSERT new wrapped rows
                                      publish "key_rotated" on Redis ──►
                                                                        clear K cache
                                                                        refetch wrapped_K_new
                                                                        next message uses K_new

Messages stored before rotation remain encrypted with K_old and stay readable for members that still have K_old cached. Per-message forward secrecy is not implemented (no ratchet).


8. Threat Model ​

  • Server compromise: the attacker obtains ciphertexts, wrapped keys, and scrypt-encrypted backup blobs. Decryption requires a user passphrase or an unlocked device.
  • Stolen device with locked browser: the IndexedDB private key is stored as a non-extractable CryptoKey. Recovery requires access to the browser profile at the OS level.
  • Forgotten passphrase combined with lost device: the chat history cannot be recovered. There is no server-side escrow.
  • Weak passphrase: scrypt(N=32768, r=8, p=1) increases the cost of an offline brute-force attack but does not prevent it. A 12-character minimum is enforced client-side; longer passphrases provide more margin.

9. File Map ​

WhatFile
All client crypto primitivesfrontend/src/crypto/e2ee.ts
IndexedDB device storagefrontend/src/crypto/deviceStore.ts
Encrypt-on-sendfrontend/src/hooks/useWebSocket.ts
Decrypt-on-receivefrontend/src/store/chatStore.ts
Conversation creation + wrappingfrontend/src/components/CreateConversationModal.tsx
Server-side key/backup endpointsbackend/internal/api/handlers.go
Postgres schema (devices, wrapped keys, backup)infra/postgres/init.sql
ScyllaDB schema (ciphertext messages)infra/scylla/init.cql