Tearleads

Security

Content is encrypted end-to-end on the client, and authorization is cryptographically verifiable: clients derive encryption targets from signed principal policies and access manifests, and verify write commitments and access paths locally before trusting synced state.

This page summarizes the implemented security architecture. The technical documentation defines the verification rules, formal models, operational limits, and residual boundaries in detail.

Threat model

The sync API and its backing storage sit outside the trusted computing base for content confidentiality and authorization integrity.

These guarantees assume an honest, uncompromised client that executes its verification gates without suppressing errors, uncompromised user signing and key-encapsulation private keys, authentic user identity bindings, and standard security assumptions on the underlying cryptographic primitives.

If the API or its storage becomes compromised, the service still holds no plaintext content, container, or principal keys, and an honest client detects and rejects forged or tampered authorization state rather than trusting server projection rows(the database's denormalized lookup tables). Under the assumptions above, client-side verification fails closed against adversarial server behavior, including:

  • Unauthorized target injection: serving forged recipient lists, altered membership projections, or substituted pinned public keys to make a client encrypt keys or content for unauthorized principals
  • Invalid access-plane mutations:honoring unsigned or forged access events, container grants, parent moves, document links, or attachment bind events, orprincipal-policyshrink transitions that reuse an earlier key epoch
  • Projection-row tampering: editing server-side group or grant lookup tables to authorize key targets without matching signed state roots and hash chains (altered roster or listing rows can still distort directory views, not verified recipient sets)
  • Ciphertext and key-envelope tampering: altering encrypted payloads, swapping context-bound content-key wraps across objects or epochs, substituting container keys that miss their signed epoch commitments, or forging content-write headers
  • Observed-state rollback and equivocation: serving older policy or manifest heads below a device's recorded checkpoints, or presenting conflicting forks of history the device has already verified

Compromised-server detection covers unauthorized mutation and tampering, not every server misbehavior: a malicious service can still withhold data or deny service, replay older valid signed state (or records signed by a since-revoked member under valid historical authority) to a device that has not observed newer state, present split views across devices without independent witnessing, or substitute identity keys on unanchored first contact. Those residual boundaries are defined under Trust boundaries.

Access plane and keying

Authorization state is derived from signed events into deterministic access manifests. Permission checks walk upward from a resource to its principals; key unwraps traverse the verified graph downward from user or group keys to content.

The authorization graph draws on Google's Zanzibar: permissions are expressed as relationships, and evaluation walks upward from the target resource. A file (blob) is reachable through active signed attachment bindings to documents, a document through its signedlink-set manifest(the signed record of which folders it belongs to) to every container (an Explorer folder) it is linked into, and a container through signed parent edges up to an organization root. Additive grants at different depths of the container hierarchy compose without per-document or per-blob recipient fanout.

Unlike server-authoritative Zanzibar, clients never accept a server check verdict or mutable database projection on trust. The API enforces authorization on reads and writes, while every client independently verifies the signed event chains, deterministic manifest hashes, and referenced principal-policy heads before decrypting or deriving encryption targets, using a fixed relationship schema rather than user-defined rewrite rules. Key encapsulation mirrors that verified graph in reverse: user and group keys unwrap container key-encryption keys (KEKs), parent KEKs derive keypairs that unwrap child container KEKs, and linked container KEKs unwrap document and blob content keys.

Tearleads access lookup and keying Relationship lookup query: can Bob read Blob B? Principals users · groups Containers manifests and grants Documents link-set manifests Updates Loro, encrypted Blobs attachments Engineering group · signed group policy Alice user Bob user includes (signed group policy) 6 C1 · org root grants · parent: none KEK C1 C2 · Projects grants · parent: C1 KEK C2 C3 · Inbox grants · parent: C1 KEK C3 parent (to root) 4 5 grant · read 5 grant · admin 5 grant · write Doc D · link-set manifest linkedContainerIds: [C2, C3] content key 3 3 linked linked Loro update u1 vv span ciphertext signed write header Loro update u2 vv span ciphertext signed write header Loro update u3 vv span ciphertext signed write header update of Blob B encrypted bytes (S3/R2) blob content key Attachment binding slotId signed bind event active = authority 1 bound by 2 binds to Keying (where it applies) User key Principals ML-KEM key pair; the private decapsulation key opens wraps opens member envelope Group epoch key Principals a member envelope wraps it to each member's user key Container KEK (one per key epoch) Containers wrapped to each direct grantee (user or group key) and to the parent KEK, so ancestor access flows down KEK C1 → Alice KEK C2 → Engineering, KEK C1 KEK C3 → Bob, KEK C1 direct grant opens KEK wrap (user or group recipient) Document content key Documents one bundle per key epoch, wrapped to the current KEK of every linked container → KEK C2, KEK C3 documentKeyTargetHash opens content-key bundle Update ciphertext Updates AEAD under the document content key; the signed header commits the manifest hash and target hash decrypts Blob content key Blobs wrapped to the union of KEK targets of every bound doc; bytes are encrypted once and rewrapping needs no restage → KEK C2, KEK C3 (via Doc D) opens blob key (not via the doc key) Lookup steps (resource → authority) 1 Blob → its active signed attachment bindings 2 Binding → document → its verified link-set manifest 3 Link-set → every linked container (C2, C3); the doc has no ACL of its own 4 Each linked container → verified manifest path to its root (C2→C1, C3→C1) 5 Collect direct grants along each path, additively: Alice·admin, Engineering·read, Bob·write 6 Expand groups via signed group policy (Engineering ∋ Bob). Read: any path grants read. Write: one write path is enough (Bob via C3), but every write encrypts to all linked containers' KEKs. Legend lookup edge (signed relationship) key unwrap (holder of upper key opens lower) KEK C1 key material held or applied at that object n lookup step, in order The server stores ciphertext, wrapped keys and manifests; clients re-verify every manifest before deciding or encrypting.
Fig. 1 Bob can read Blob B because it is bound to Doc D, which links Inbox (C3), where Bob holds a direct write grant. Solid lines are signed lookup relationships; dashed lines are key unwraps. The access plane specification defines each transition rule.

Confidentiality and metadata boundary

At-rest encryption protects local state on your device; end-to-end encryption keeps payload plaintext and content keys outside the sync service, while structural and operational metadata remain visible to the server.

Your device

Trusted client boundary

Keys are unwrapped and content is decrypted locally.

  1. Unlock the local keyring

    Each storage scope wraps a random root key under a host wrapping key, optionally outer-wrapped with a PIN-derived key.

  2. Derive domain-separated keys

    HKDF-SHA256 derives independent keys for SQLite, the local file store, and persisted identities.

  3. Encrypt local storage at rest

    Reads and writes pass through ChaCha20-encrypted SQLite and chunked AES-256-GCM file storage.

The unlocked client can read plaintext keys and content.

Encrypted sync

Sync and storage

Untrusted service boundary

The API stores and indexes ciphertext, wraps, and signed state.

Encrypted payloads
AES-256-GCM document updates, file payloads, and encrypted metadata.
Wrapped key envelopes
ML-KEM-1024 and AES-256-GCM key wraps that only authorized holders can open.
Signed authority records
ML-DSA-87 principal policies, access events (and derived manifests), and write headers.

Holds no plaintext content, container, or principal keys.

Fig. 2 Local at-rest storage and synced content use independent key hierarchies. Sync exchanges ciphertext, wrapped key envelopes, and signed access state—never the local database. Solid frame: plaintext is available after unlock. Dashed frame: the service stores and delivers encrypted and signed records without plaintext keys.

Encrypted end-to-end

  • Document updates and file (blob) payloads
  • Container metadata documents, including folder names
  • Organization names and custom group names
  • Wrapped content keys, container KEKs, historical KEK keyrings, and principal secret keys

Decrypting these artifacts requires an authorized private encapsulation key, principal secret key, or unwrapped container or content key.

Visible to the service

  • Reserved built-in group roles (Admins and Members)
  • Roster lifecycle rows and group membership projections
  • Object-graph topology: folder parent edges, signed system-folder slots (such as an organization's Trash folder), document-to-folder links, and attachment bindings
  • Object and principal identifiers, public keys, and key fingerprints
  • Signed principal-policy headers, container-grant sets, and key-epoch counts
  • Signer user IDs, signing-key fingerprints, and signed timestamps on policies, access events, and writes (plus signer device IDs on access events and writes)
  • Version-vector and sequence metadata that order document updates
  • Ciphertext lengths, part checksums, and storage consumption
  • Connection IP addresses, session and activity timestamps, and the registration IP address
  • Subscription and billing records, including the billing email for web subscriptions

Payload encryption does not conceal this structural metadata or network traffic patterns such as request timing and size.

Verified sharing

A container binds content keys to signed access rules. Clients derive recipient key targets strictly from verified access manifests and signed principal policies—mutating a server-side membership or grant lookup row cannot authorize a new recipient.

  1. Sending device

    Verify targets

    Verify signed access manifests, referenced principal policies, pinned identity bundles, and local checkpoints.

  2. Sending device

    Encrypt and wrap

    Encrypt payloads with per-record keys, wrap content keys to container KEKs, wrap KEKs to verified recipients, and sign write headers.

  3. Sync service

    Validate and persist

    Re-verify signatures, lineage, and target commitments inside transactions; store ciphertext and wrapped envelopes.

  4. Receiving device

    Verify and decrypt

    Independently verify signed policies, manifest paths, checkpoints, and write headers before unwrapping keys or decrypting.

Fig. 3 End-to-end verification flow for shared content. The API checks writes on commit, while both clients independently verify the signed records they rely on. Dashed frame: the untrusted service.
Fail-closed verification gate. Invalid required signatures, broken hash chains, mismatched commitments, identity-pin conflicts, or checkpoint rollbacks abort the affected workflow and record a typed local security incident. Server-supplied recipient lists and projection rows never authorize sharing on their own.

Signed chains, pins, and checkpoints

Signatures and hash chains bind principal policies and access manifests to their signers, predecessors, member identity commitments, and grant roots, while the organization policy commits every active group's current head. Clients persist full-bundle identity pins and monotonic checkpoints, rejecting key substitutions, forked histories, and rollbacks below observed state, and recording terminal verification failures in a local security-incident ledger.

Forward revocation and atomic rotation

Removing group members rotates the group key and every granted container's KEK in one atomic commit; removing a direct grant or moving a container rotates that container's KEK, and unlinking a document rotates its content key. Rotation leaves prior keys no forward bridge to post-rotation epochs (unless the user still holds a separate valid access path), while previously received keys, nested subtrees, and retained history follow the bounds under Trust boundaries.

Cryptography

Payload encryption, recipient key encapsulation, state authentication, commitments, and local at-rest storage use explicit, domain-separated primitives.

Asymmetric operations in the client and API keying protocol are post-quantum only: ML-KEM-1024 (NIST FIPS 203) for key encapsulation and ML-DSA-87 (NIST FIPS 204) for signatures, with no classical RSA, ECDH, X25519, or Ed25519 fallback. Transport TLS and deployment SSH keys sit outside this protocol scope.

Synced content and access plane

Cryptographic primitives for synced content and the access plane
PurposeMechanismRole
Document and file recordsAES-256-GCM + HKDF-SHA256Authenticated encryption with a domain-separated per-record key derived via HKDF, paired with a signed content-write header.
Key encapsulation and wrappingML-KEM-1024 + AES-256-GCMEncapsulates principal keys to members and container KEKs to users, groups, and parent-derived KEK keypairs. Content keys and KEK keyrings wrap under container KEKs with context-bound AES-256-GCM additional authenticated data (AAD).
Digital signaturesML-DSA-87Authenticates principal policy states, access events, content-write headers, and origin-bound sign-in challenges.
Commitments and fingerprintsSHA-256 + HKDF-SHA256Computes public-key fingerprints, canonical state and manifest hashes, Merkle roots, streamed ciphertext digests, and document content-key commitments.

Local storage and recovery

Cryptographic primitives for local at-rest storage and recovery
PurposeMechanismRole
Local key separationHKDF-SHA256Derives domain-separated keys for SQLite, the local file store, and saved identities from each scope's wrapped root key.
Local databaseChaCha20 (SQLite3MultipleCiphers)Encrypts the local SQLite database file at rest.
Local file storeAES-256-GCMEncrypts local OPFS files in authenticated chunks with namespace, storage key, and chunk index bound in AAD.
PIN lockPBKDF2-SHA256 + AES-256-GCMOuter-wraps the host-encrypted root-key envelope under a key derived from the optional local PIN.
Password-protected backupsPBKDF2-SHA256 + AES-256-GCMEncrypts exported backup archives under a key derived from the backup password.
Recovery phraseBIP39, 24 wordsEncodes 256 bits of entropy from which an identity's ML-DSA-87 signing and ML-KEM-1024 encapsulation seeds are derived via HKDF-SHA256.

Local storage and PIN protection

The client isolates local at-rest keys across three keyring scopes—SQLite, the local file store, and persisted identities—each backed by its own context-bound wrapped root key. Persistent SQLite and file chunks live in the browser's Origin Private File System (OPFS), the encrypted identity registry lives in localStorage, and the host wrapping key and keyring manifest live in IndexedDB (only the manifest store falls back tolocalStorage when IndexedDB is unavailable).

The web app persists a non-extractable Web Crypto CryptoKey in IndexedDB; the desktop and mobile shells store exported raw AES-256 key bytes in IndexedDB instead. Tearleads does not store this wrapping key in a hardware-backed OS keychain or secure enclave on any platform, so at-rest protection relies on browser, WebView, and OS profile isolation.

Configuring an optional PIN wraps the host-encrypted root-key envelope under a PBKDF2-SHA256 and AES-256-GCM key, requiring both the host wrapping key and the PIN to reopen the scope. On desktop and mobile shells (where the host key is stored as raw bytes), an attacker who obtains a copy of the app's storage—such as an unencrypted device backup—can test PINs offline, or decrypt the copy directly if no PIN was set; a copy of a browser profile's storage can permit the same. No PIN is set by default, and a local PIN does not alter remote access-plane authorization.

Unlocking the local database with and without a PIN With a PIN, the app first opens the outer layer using a key derived from the PIN. Both paths then use the host wrapping key to recover the SQLite scope’s root key. The app derives the database key from that root. Local files and saved identities use separate keyring scopes. Stored keyring · SQLite scope Without a PIN (default) Read the host-wrapped root key directly from the keyring manifest. With a PIN Derive a key with PBKDF2-SHA256. Use it to open the outer AES-GCM layer. Host-wrapped root key Unwrap with the host key SQLite scope’s root key HKDF-SHA256 Database key Encrypted SQLite database
Fig. 4 Unsealing the SQLite scope at startup with and without an optional PIN. Both paths require the host wrapping key to recover the scope's root key; the local file store and saved identities follow the same construction under separate roots.

Service infrastructure

Production runs on Cloudflare Workers, Durable Objects, PlanetScale Postgres, and Cloudflare R2. Every server component sits on the untrusted service side of the confidentiality boundary in Fig. 2.

Tearleads infrastructure Production tier staging runs the same layout on -staging hostnames Clients keys and plaintext stay on the device Cloudflare Workers and Durable Objects Storage Cloudflare R2 and PlanetScale Web app in the browser at app.tearleads.com demo.tearleads.com iOS and Android Capacitor shell, installed from the App Store and Google Play Desktop Electrobun shell, installed from downloads.tearleads.com static assets HTTPS and WebSocket presigned URLs: encrypted blob bytes Static asset Workers tearleads.com app.tearleads.com demo.tearleads.com no server runtime API Worker api.tearleads.com Hono routes and /events cron: billing every minute, blob cleanup hourly placed in us-east-1 Durable Objects KeyValueStore sessions and tickets RealtimeHub every WebSocket SQLite storage binding Hyperdrive pooled, TLS S3 API: presign, delete R2 downloads bucket downloads.tearleads.com desktop installers and update files PlanetScale Postgres us-east-1: accounts, signed records, encrypted updates, wrapped keys, billing state R2 blob bucket tearleads-blobs-prod encrypted attachment bytes S3 API, presigned URLs Notes Workers, Durable Objects, Postgres, and R2 hold ciphertext, wrapped keys, signed records, and service-visible metadata. Blob bytes move between clients and R2 directly; the API signs short-lived upload and download URLs instead of relaying them. Terraform owns the buckets, Postgres, Hyperdrive, and custom domains; Wrangler owns the Workers and their assets. Legend run in Tearleads' Cloudflare and PlanetScale accounts request direction
Fig. 5 The production tier. Clients authenticate to the API Worker with origin-bound challenge signatures, upload encrypted blob parts to R2 via short-lived size- and checksum-scoped presigned URLs, and download encrypted blobs via short-lived presigned GET URLs (with an authenticated API byte-stream fallback) before verifying length, SHA-256, and AEAD tags locally. The infrastructure guide documents each stack and deployment step.
Tearleads Durable Objects Durable Objects one SQLite-backed instance of each per tier API Worker the request isolates that call each object Durable Objects SQLite storage Stored values what the API writes into each object HTTP routes challenges, sign-in, session checks, sign-out, WebSocket ticket minting Realtime entry points GET /events upgrades are forwarded; committed writes publish hints RPC: string and set operations with TTL fetch: WebSocket RPC: publish KeyValueStore idFromName("default") every call runs one at a time, so GETDEL and SET XX KEEPTTL are atomic entries(key, value, expires_at) set_keys(key, expires_at) set_members(key, member) alarm: hourly expired-row sweep reads also skip expired rows RealtimeHub idFromName("hub") placed in eastern North America; holds every open WebSocket realtime_socket_chunks (id, part, snapshot) attachment: socket, user, session ids alarm: the next recheck deadline queues and routing stay in memory tickets, sessions KeyValueStore keys session:<bearer token> session id, user id, fingerprint, IP addresses, activity times; 24 h session-id:<session id> the session's bearer token; 24 h user-sessions:<user id> set of the user's session ids; 24 h challenge:<fingerprint> sign-in challenge; 60 s, read once ws-ticket:<ticket> user, session ids; 60 s, read once Socket snapshot proofs a container id, the container ids on its path, and the principals that authorized the interest verifiedAt, nextCheckAt proof check time and next recheck session last confirmed live, next check organization organization id and whether it is authorized, or null Notes Neither object stores content, encryption keys, or ciphertext. Session keys embed bearer tokens, so this storage is as sensitive as a sign-in. Losing KeyValueStore ends every session; losing RealtimeHub closes its sockets, and clients reconnect with a new ticket. A greenfield reset deletes both namespaces through the maintenance Worker; a normal deploy keeps their storage.
Fig. 6 Durable Object state in Fig. 5. KeyValueStore holds session tokens, short-lived sign-in challenges, and single-use WebSocket tickets; RealtimeHub retains each open socket's verified container-interest state across hibernation and emits refresh hints that carry no plaintext or authorization authority.

Trust boundaries

Residual risks, cold-start limits, and explicit non-goals of the protocol under the threat model above.

First-contact identity anchoring
Each device durably pins full user identity bundles by trust domain and user ID, rejecting any subsequent key change. Adding contacts, creating roster profiles, or enrolling new or disabled Members requires a direct anchor (this device's own keys or a verified identity link). Existing Members may receive group membership or container shares through signed Members history that commits their full identity bundle and chains back to such an anchor—an explicit transitive trust in every vouching administrator, including careless or malicious ones. First-sight signer observations never satisfy recipient admission. Deliver identity links over an authenticated channel; neither links nor chains prove global currentness.
Cold-start rollback and split views
Signatures and hash chains prove continuity, not global freshness. A device with no local checkpoint for an organization or container (a new device, a first-sight shared scope, or a reset local database) can be served older, internally valid signed history, and separate devices can be shown diverging views without cross-device witnessing or gossip. Within an observed organization, the signed organization policy commits every active group's current head, preventing isolated single-group rollback before a per-group checkpoint exists.
Availability and withholding
Denial of service sits outside the security boundary: a compromised service can withhold ciphertext, policy bundles, key wraps, or updates and refuse writes. When required verification evidence is absent, workflows fail closed rather than proceed with unverified state. An authorized writer can likewise submit undecryptable payloads or mismatched content-key wraps, causing availability failures (until repaired in a new epoch) without bypassing confidentiality or authorization.
Endpoint and recovery-key compromise
Local and end-to-end encryption do not defend against a compromised operating system, malicious code running in an unlocked client, or physical capture of displayed secrets. Anyone who obtains the 24-word recovery phrase—including its plaintext QR code—can deterministically derive that identity's signing and encapsulation private keys, and an unencrypted local backup file contains exported database rows and attachment bytes directly.
History-inclusive container access
Container access includes retained history by design: each current container KEK seals the container's predecessor keyring, allowing newly granted members to decrypt historical epochs. Compromising a current container KEK therefore exposes that container's retained history.

Revocation, nested containers, and historical authority

Revocation is forward-looking: it cannot erase keys or plaintext a former member already obtained while authorized. Rotating a parent container KEK rekeys intermediate descendants that sit above a directly shared container (within the carried-rekey cap), while unshared nested branches are not eagerly rekeyed until rotated directly or repaired along the path of a later write. Best-effort descendant re-citation (refreshing a held child folder's signed manifest citations to newer ancestor heads) narrows the stale-authorization window without rotating child KEKs or promising post-revocation confidentiality from a former member.

Without external currentness witnessing, a revoked signer colluding with a compromised server can present events or writes signed under valid historical authority to a device that has not yet observed a newer advancing event. Verifying a signature proves authority at the cited state head, not wall-clock creation time.

Documentation

Published directly from the public Tearleads repository, these guides, protocol specifications, bounded TLA+ models, operational limits, and API reference pages define the rules and residual boundaries in detail.

Backup and restore
Export a local backup, read its file format, and restore it on a device.docs/backup-and-restore.md
How re-keying works
Follow folder and document keys through sharing, revocation, and moves.docs/re-keying.md
Attribution and Loro updates
Follow encrypted Loro updates, version-vector spans, and signed headers to edit attribution and blame.docs/attribution-and-loro-updates.md
Security guarantees
What each property protects, the threat model, and the known gaps.docs/security-guarantees.md
Keying design
How content keys, container keys, and recipients fit together.docs/keying-design.md
Protocol specification
Messages, proofs, validation rules, and failure semantics.docs/protocol-specification.md
Cipher suites
The cryptographic primitives and where each one is used.docs/cipher-suites.md
Protocol models (TLA+)
Bounded models of protocol safety rules that complement, not replace, tests.formal/README.md
Hard limits
Every bound the protocol enforces, what enforces it, and what happens past it.docs/limits-hard.md
Soft limits
Bounds set by browsers, devices, and hosting services that the protocol does not enforce.docs/limits-soft.md
Glossary
Shared protocol terms used across the documentation.docs/glossary.md
API reference
Every HTTP operation, the fields it accepts and returns, and the rules the server enforces.docs/openapi.json