# Post-quantum end-to-end encrypted email architecture

Source: [docs/dmsg_email.md](https://github.com/ldclabs/ic-panda/blob/main/docs/dmsg_email.md). This is a public-source snapshot; review dates and deployment limits below still apply.

---

# dMsg post-quantum end-to-end encrypted email architecture

English | [简体中文](https://github.com/ldclabs/ic-panda/blob/main/docs/dmsg_email_zh.md)

This document is written for technical enthusiasts, protocol engineers, and security auditors. It follows the public implementation and explains the architecture, cryptographic protocols (`dmsg-email/1` and the vendor-neutral open standard [`PQMail/1`](https://dmsg.net/_/docs/pqmail.md) Draft v0.5), storage chunking, anti-hijacking design, and security boundaries of dMsg post-quantum end-to-end encrypted email and encrypted contacts (`dmsg-contact/1`). For account root keys, device hardware binding, and recovery boundaries, read this alongside [Encryption design and implementation boundaries](https://dmsg.net/_/docs/encryption.md) and [Architecture](https://dmsg.net/_/docs/architecture.md). Cross-implementation byte-level test vectors live in [`pqc-email-v1.json`](https://github.com/ldclabs/ic-panda/blob/main/tests/vectors/client/pqc-email-v1.json) (`dmsg-email/1`) and [`tests/vectors/pqmail-v1/`](https://github.com/ldclabs/ic-panda/blob/main/tests/vectors/pqmail-v1/) (`PQMail/1`).

## 1. Overview and communication boundaries

### 1.1 Communication modes and design principles

Email routinely carries contracts, financial statements, identity records, and long-term correspondence archived for 10–30 years, making it a prime target for Harvest Now, Decrypt Later (HNDL) attacks. Unlike real-time messaging, email requires asynchronous delivery to offline recipients, multi-recipient static archiving, and long-term multi-device decryption. Online session ratchets do not fit this model; instead, email requires hybrid post-quantum public-key encapsulation designed for static archives, independently verifiable sender signatures, and honest metadata boundaries.

Within dMsg, **personal encrypted email** evolved from the earlier private-letter inbox and maintains strict separation from **real-time channels** and **Agent Mail**:

| Communication mode | Typical use cases | Protocol and naming boundary | Encryption and access control |
| --- | --- | --- | --- |
| Channels | 1v1 live chat, group collaboration, broadcast channels | Channel protocol and dedicated archive storage | Signed control log + epoch key rotation (X-Wing hybrid PQ); invitation-only membership |
| **Personal encrypted email (this document)** | Asynchronous long-form messages, file delivery, low-friction stranger screening, custom domains (BYOD), and global SMTP / `PQMail/1` interoperability | Unified `email` namespace: `dmsg-email/1`, `PQMail/1` (`src/pqmail_core`), `EmailKey`, `EmailKeyDescriptor`, `dmsg-contact/1` | Native X-Wing hybrid encryption + Ed25519/ML-DSA-65 hybrid signing; open `PQMail/1` (RFC 1847/2387 MIME, synced account-level `PQMailKeyBundle` signing keys, Profile 0/A progressive discovery); streaming X-Wing at-rest encryption for plaintext inbound SMTP; contact allowlist + Screener + unified blocklist |
| Agent Mail | Asynchronous encrypted message relay between AI agents | `agent-mail/1.0`, `did:agent:...` (fully isolated from human accounts and SMTP) | Dedicated mailbox protocol for managed/autonomous Agent IDs; never mixed with human email |

Five core engineering principles shape the architecture:

1. **ICP smart contracts as a decentralized certified PKI**: Device authority, post-quantum key commitments, content-root generations, and handle ownership live in decentralized Internet Computer (ICP) smart contracts (`dmsg_user` and `dmsg_handle`) certified by ICP subnet threshold signatures, allowing clients to verify recipient keys directly against the ICP root key without trusting the mail relay.
2. **Hybrid post-quantum with anti-downgrade enforcement**: Encryption uses `X-Wing` (`ML-KEM-768 + X25519`) and signatures use `Ed25519 + ML-DSA-65`, with strict anti-stripping and rollback protection backed by certified commitments.
3. **Independent recipient ownership**: Native email bodies and regular attachments (≤ 25 MiB) are copied into each recipient's own storage namespace. Deleting Sent mail or closing the sender's account never breaks a recipient's copy, and reading attachments requires zero cross-account authorization or open-time side channels.
4. **Single pure-Rust core across platforms**: Wire primitives, key rings, 1 MiB chunking, MIME parsing, allowlist HTML sanitization, local search, and contact sync live in a shared OS-independent Rust core reused across Desktop, CLI/MCP, iOS, and Android.
5. **Honest security tiers and metadata boundaries**: Clients clearly separate end-to-end encryption from transport-encrypted external mail, evaluate post-quantum status by the weakest link on each message, and disclose the routing metadata servers necessarily observe.

### 1.2 Core architectural differences from conventional E2EE email

Compared with encrypted email services built around centralized key directories or browser-hosted Webmail, dMsg differs in six structural ways:

| Dimension | Conventional E2EE email services | dMsg post-quantum E2EE email |
| --- | --- | --- |
| **Public-key discovery and MITM resistance** | Global email lacks a unified, high-availability PKI; most services rely on centralized directories or provider-operated key transparency logs, creating an inherent tension between seamless key lookup and preventing the provider from silently substituting public keys (MITM) | Device authority, ML-DSA-65 commitments, content-root generations, and handle records are anchored in **ICP smart contracts**; senders seamlessly fetch `EmailKeyDescriptor` and verify it directly against the ICP root key rather than taking the relay's word |
| **Client trust boundary and key protection** | Often Webmail-first (or thin wrappers loading remote web code), where a compromised or coerced server can serve malicious JavaScript to steal passwords or keys on unlock | **Native-first clients backed by a single open-source pure-Rust core** (Desktop, CLI, iOS, Android); login credentials are separated from content keys, and local workspaces bind by default to OS hardware security modules (Secure Enclave / Android Keystore / TPM 2.0 + Windows Hello) |
| **Cryptographic isolation on device revocation** | Long-lived private decryption keys are commonly shared statically across devices; revoking a lost device typically invalidates session tokens without cryptographically preventing an extracted key from decrypting future mail | `EmailKeyRecord` tracks active `VaultUnlock` devices; **revoking any decrypting device forces an on-chain root transition and automatic `EmailKey` rotation**, blocking relay rollback so future messages are cryptographically unreadable to the revoked device |
| **Sender signatures and historical verification** | Often rely on server-asserted sender identity or long-lived account-level keys whose historical validity becomes ambiguous after rotation or compromise | Every native message carries a per-device `Ed25519 + ML-DSA-65` hybrid signature (`dmsg/email-sig/1`, domain-separated from high-privilege approvals); ICP-certified acceptance `evidence` lets recipients verify sender authorization against the ICP root key years after a device is revoked |
| **Honest post-quantum reporting** | Partial PQ upgrades are frequently presented as blanket post-quantum protection without surfacing legacy classical root history or mixed-recipient downgrades | Evaluates `pq_effective` strictly by the **weakest link per message** (key created on a strict PQ root, verified ML-DSA-65 anti-stripping, and PQ delivery for every recipient), automatically downgrading whenever any classical or external SMTP recipient is present |
| **Anti-hijacking and large-attachment closure** | Recycled or transferred usernames risk third-party password-reset hijacking; attachments above email limits typically push users onto external unencrypted file hosts | Stateless on-chain `HandleRecord.version == 1` rules isolate transferable handles from external SMTP; 25–100 MiB files automatically re-encrypt into fresh-key cloud attachments bound into the email's PQ signature, unified with encrypted contacts and cross-app blocklists |

These architectural choices prioritize decentralized MITM resistance and native hardware security boundaries; Section 3.4 covers the open cross-provider `PQMail/1` standard implemented alongside `dmsg-email/1`, and Section 8 outlines current scope alongside planned OpenPGP/WKD compatibility.

## 2. System architecture, trust boundaries, and security tiers

### 2.1 End-to-end topology

```mermaid
flowchart TB
    subgraph Client["dMsg Multi-Platform Client (Desktop / CLI / iOS / Android - Pure-Rust Core)"]
        KEYRING["EmailKey Ring (VRK_g Synced)\nEncrypted Contacts (dmsg-contact/1)\nHybrid Device Signing (Ed25519 + ML-DSA-65)"]
        ENGINE["dmsg-email/1 Engine\nX-Wing Wrapping + 1 MiB Chunking + Cloud Attachments\nPure-Rust MIME Parser / HTML Sanitizer / In-Memory Search"]
    end

    subgraph Chain["ICP Smart-Contract Trust Root (Decentralized Certified PKI: dmsg_user / dmsg_handle)"]
        USER_LEAF["dmsg_user Certified Leaves\nSecuritySnapshot + PqSnapshot\n(Device Roles, Content Root Gen, PQ Commitments)"]
        HANDLE_LEAF["dmsg_handle Certified Leaf\nHandleRecord (owner_account, version)"]
    end

    subgraph Relay["Cloud Ciphertext Relay and Object Storage"]
        MAILBOX["Mailbox Control and Routing Service\nContact Policy / Source-Tagged Blocklist / Screener Pool\nDedup Commit / Encrypted Index Streams / Acceptance Evidence"]
        OBJSTORE["Ciphertext Object and Encrypted Share Storage\nRecipient-Owned 1 MiB Chunks (<= 25 MiB)\nFresh-Key Encrypted Cloud Attachments (25-100 MiB)"]
    end

    subgraph Edge["External SMTP Edge"]
        INBOUND["Stateless Inbound SMTP Edge\nTLS 1.3 PQ + SPF/DKIM/DMARC Verification\nRCPT TO Pre-Reject + Streaming 1 MiB AES-GCM + X-Wing"]
        OUTBOUND["External SMTP Outbound Relay\nDKIM-Aligned Delivery + Privacy Alias Isolation + Bounce Controls"]
    end

    EXT["Global Internet Mail Providers (Gmail / Outlook / Proton / Enterprise SMTP)"]

    Client <-->|"dmsg-email/1 and Contact Sync"| MAILBOX
    Client <-->|"Short-Lived Signed Chunk Transfers"| OBJSTORE
    Client -.->|"Verify SecuritySnapshot / PqSnapshot / Evidence"| USER_LEAF
    Client -.->|"Verify HandleRecord and version"| HANDLE_LEAF
    MAILBOX <--> OBJSTORE

    EXT -->|"Inbound SMTP (@dmsg.net and Custom Domains)"| INBOUND
    INBOUND -.->|"RCPT TO Route/Policy Check and Key Fetch"| MAILBOX
    INBOUND -.->|"Assert HandleRecord.version == 1"| HANDLE_LEAF
    INBOUND -.->|"Verify Recipient Certified Snapshot"| USER_LEAF
    INBOUND -->|"In-Memory Streaming Ciphertext Chunks (Zero Disk Plaintext)"| OBJSTORE

    MAILBOX -->|"Outbound Delivery Request"| OUTBOUND
    OUTBOUND <--> EXT
```

### 2.2 Trust boundaries and metadata visibility

| Data or capability | Native dMsg email (`dmsg-email/1`) | External Internet email (SMTP) |
| --- | --- | --- |
| Subject, plain text, HTML, thread links (`In-Reply-To` / `thread_id`) | **End-to-end encrypted** (random `MEK` + AES-256-GCM); unreadable to the relay | Visible in flight to external mail providers and briefly at the SMTP edge; encrypted immediately under recipient's X-Wing key before storage (zero plaintext at rest) |
| Regular attachment filenames and bytes (≤ 25 MiB) | **End-to-end encrypted** inside the payload and owned independently by each recipient | Same as above |
| Encrypted cloud attachments (25–100 MiB) | Re-encrypted under a fresh random key; decryption key stays in the URL fragment (`#<key>`) inside the encrypted payload | Key stays in the URL fragment (never sent in HTTP requests), though the cleartext outbound email channel itself carries the full link |
| Blind carbon copy (`Bcc`) | Hidden from `To`/`Cc` recipients; stored privately in sender's `VRK_g`-encrypted `SentMeta`; relay sees the set of target accounts for delivery | Placed only in the delivery envelope, never in outbound MIME headers (Bcc-only mail is sent one copy per address) |
| Routing and operational metadata | Relay observes sender account, recipient account set, delivery timestamps, ciphertext byte size, and explicitly projected allow/block rules | External providers and SMTP edges observe `MAIL FROM`, `RCPT TO`, timestamps, byte size, and TLS/DMARC status |
| Contact nicknames, groups, and notes | 100% end-to-end encrypted (`VRK_g`); invisible to the relay | Only explicit allow/block rules are projected as minimal address strings |

Consistent with [Encryption design and implementation boundaries](https://dmsg.net/_/docs/encryption.md): AEAD prevents silent ciphertext tampering without the key, but cannot prevent a malicious relay from refusing delivery, delaying messages, or withholding recent items. The endpoint device, OS security hardware, and client software form the trusted execution boundary.

### 2.3 Security tiers and per-message weakest-link evaluation

Every email summary and detail view carries an explicit `EmailSecurityTier` (`src/dmsg_client/src/email/mod.rs`) so at-rest encryption is never mislabeled as end-to-end encryption:

| Wire value (`security_tier`) | Meaning | Post-quantum rule (`pq_effective`) |
| --- | --- | --- |
| `pqmail_e2ee_verified` | Open-standard `PQMail/1` post-quantum E2EE (verified directory / consensus proof) | Every involved `PQMailKeyBundle` passed a locally anchored open cryptographic directory proof (Profile B `pqmail-kt/1` or Profile C `pqmail-state/1`); inbound signatures, recipient binding, and anti-forwarding checks all passed (`pq_effective = true`; dMsg-to-dMsg traffic uses native ICP-certified `dmsg-email/1`) |
| `pqmail_e2ee_tofu` | Open-standard `PQMail/1` post-quantum E2EE (TOFU) | At least one involved `PQMailKeyBundle` was bootstrapped via Profile 0 (`PQMail-Key` header with DMARC + aligned DKIM) or Profile A HTTPS directory without a verified consensus/KT proof; explicitly distinguished from `pqmail_e2ee_verified` in all clients (`pq_effective = true`) |
| `dmsg_e2ee_pq` | Native dMsg post-quantum E2EE | **Per-message weakest-link evaluation**: requires (1) every recipient is native `dmsg-email/1` with an ML-DSA-65 hybrid-signed `EmailKeyDescriptor` whose `created_root_generation >= pq_since_generation`; (2) sender's `dmsg/email-sig/1` passes certified ML-DSA-65 verification; (3) local content root is strictly PQ (`pq_root_strict && pq_since_generation <= generation`) |
| `dmsg_e2ee_classic` | Native dMsg E2EE (non-strict PQ) | Automatic downgrade whenever any recipient key predates `pq_since_generation`, either party lacks certified PQ signing, or strict PQ root checks do not hold |
| `external_tls_pq` | External SMTP inbound (hybrid PQ TLS transport + X-Wing at-rest encryption) | Explicitly labeled non-E2EE while surfacing inbound TLS and DMARC status |
| `external_tls` | External SMTP send/receive (standard TLS transport + X-Wing at-rest encryption) | If a single message mixes E2EE and external plaintext SMTP recipients, clients split delivery and require explicit confirmation for the plaintext group (`pq_effective = false`) |
| `external_plain` | External SMTP cleartext inbound (no TLS + X-Wing at-rest encryption) | Explicitly flags unencrypted SMTP transport |
| `legacy_letter` | Read-only historical private letter projection | Preserves migrated pre-email private letters without claiming modern PQ email guarantees |
| `pgp_e2ee` | External OpenPGP E2EE (preserved M2 compatibility tier) | Reserved for on-demand OpenPGP RFC 9580/9980/9788 interoperability alongside `PQMail/1` |

## 3. Post-quantum cryptographic protocols (`dmsg-email/1` and `PQMail/1`)

### 3.1 Dedicated email key ring (`EmailKeyRecord`) and rotation pipeline

dMsg decouples email decryption keys from ephemeral device sessions and routine root refreshes by storing a dedicated synced vault object **`EmailKeyRecord`** (`kind = "email_key"`, format `"dmsg-email-key-ring/1"`):

- **Deterministic object ID**: `hex(SHA-256(CBOR(["dmsg/email-key-ring/1", account_id])))`.
- **Encrypted sync**: Sealed under the account's active content root `VRK_g` and synced across all devices holding `Capability::VaultUnlock`. Full historical key generations remain recoverable offline via the `PQ Recovery Kit` (`DMSG-PQK1-...`).
- **Per-generation entry (`EmailKeyEntry`)**:
  - `gen`: strictly monotonic email key generation (`>= 1`);
  - `xwing_seed`: 32-byte raw X-Wing seed (`draft-connolly-cfrg-xwing-kem`, HPKE KEM `0x647a`, deriving a 1,216-byte public key and 1,120-byte `enc`);
  - `created_root_generation`: account `content_root_generation` when this key was generated, proving whether the private seed was ever exposed to a legacy classical root;
  - `vault_unlock_devices[]`: sorted list of active `VaultUnlock` device IDs observed holding this generation;
  - `retired_at`: retirement timestamp after rotation; retired private keys stay in the ring for reading historical mail.
- **Read-only legacy archive**: On first initialization, existing `INBOX_KEY` (X25519) and `INBOX_PQ_KEY` (X-Wing) records are archived read-only into `legacy_inbox_keys[]` while `EmailKey` starts at `gen = 1`. Decryption also checks sync conflict copies of the same object ID so concurrent rotations never strand mail.

**Automatic rotation triggers and synced-before-publish pipeline (`src/dmsg_client/src/email/maintenance.rs`)**:

Only the following events rotate `EmailKey` to `gen + 1`:
1. A device recorded in `vault_unlock_devices[]` is revoked or loses `Capability::VaultUnlock`;
2. Account recovery or destructive content-root reset occurs (`created_root_generation < content_root_reset_generation`);
3. The account upgrades from a classical content root to a strict PQ content root (`created_root_generation < pq_since_generation <= content_root_generation`), eliminating HNDL exposure from prior classical root copies;
4. An administrator triggers manual emergency rotation (zero grace window).

> **Why adding a new device does not rotate `EmailKey`**: Authorizing a new trusted device leaves the previous `VaultUnlock` set as a subset of the new set, introducing no key compromise. The client simply appends the new device to `vault_unlock_devices[]` (so revoking it later will trigger rotation) and re-signs `EmailKeyDescriptor` with the new `bound_root_generation`.

Rotation strictly enforces **Synced-before-Publish**: `prepare()` writes the new key locally and hands off to encrypted content sync → `finish()` verifies that the `email_key` object has reached `SYNCED` on the relay (guaranteeing the private seed is durably backed up under `VRK_{g+1}` before any public key is advertised) → only then does a root administrator sign and publish the new `EmailKeyDescriptor`. Routine rotations advertise a **24-hour** `grace_prev_gen` / `grace_until_ms` window for in-flight external mail; emergency rotations use zero grace.

### 3.2 ICP-certified hybrid-signed `EmailKeyDescriptor`

Global encrypted email has long faced two foundational problems: seamlessly fetching a recipient's public key and preventing the email provider from silently substituting public keys to perform a Man-in-the-Middle (MITM) attack. Even when a mail service adopts post-quantum algorithms, if recipient public keys are distributed and vouched for solely by the provider's centralized directory, the provider can still substitute a forged key before delivery. dMsg solves both seamless key discovery and MITM resistance by anchoring an off-chain hybrid-signed `EmailKeyDescriptor` to decentralized ICP smart-contract state (`dmsg_user`), allowing senders and the inbound edge to verify keys directly against the ICP root key without trusting the relay:

```mermaid
flowchart TD
    CERT["dmsg_user ICP Smart-Contract Subnet Certificate (Verified Directly Against ICP Root Key)"]
    L1["Certified Leaf: account_id\nSecuritySnapshot (Devices, Roles, Capabilities, content_root_generation, vault_write_state)"]
    L2["Certified Leaf: pq/account_id\nPqSnapshot (pq_since_generation, content_root_reset_generation, Device sig_digest)"]
    DESC["Off-Chain Hybrid-Signed EmailKeyDescriptor (COSE_Sign Tag 98)\nemail_key_gen, created_root_generation, bound_root_generation,\nemail_xwing_pub (1,216 B), pgp_cert_digest?, grace_prev_gen?, grace_until_ms?"]

    CERT --> L1
    CERT --> L2
    L1 -.->|"Verify active Administrator + RootManage + VaultUnlock signer\nbound_root_generation == content_root_generation and Ready"| DESC
    L2 -.->|"Enforce ML-DSA-65 anti-stripping via sig_digest\nand check created_root_generation >= pq_since_generation"| DESC
```

`EmailKeyDescriptor` is a **CBOR Tag 98 `COSE_Sign`** structure (prefix `0xd8 0x62`, capped at 32 KiB) specified in `dmsg_protocol::email` and locked by deterministic vectors:

- **Outer protected headers**:
  - `2` (`crit`): `[15, 16]`
  - `3` (`content type`): `"application/cbor"`
  - `15` (`CWT Claims`): `{1: issuer}`
  - `16` (`profile`): `"application/vnd.dmsg.email-key-descriptor+cose;v=1"`
  - Unprotected header map must be empty `{}`.
- **External AAD**: `"dmsg/email-key-descriptor/1"`, completely domain-separated from every other COSE signature.
- **Signature slots (`signatures` array, 1 or 2 entries)**:
  - Slot 0 (required): `alg = -19` (Ed25519), `kid = device_id` (32 B), 64 B signature;
  - Slot 1 (required for PQ-committed devices): `alg = -49` (FIPS 204 / RFC 9964 ML-DSA-65), `kid = device_id`, 3,309 B deterministic signature.
- **Canonical CBOR payload (`EmailKeyDescriptorPayload`, unknown fields rejected)**:
  - `v = 1`, `account_id`, `email_key_gen >= 1`, `created_root_generation >= 1`, `bound_root_generation >= created_root_generation`, `email_xwing_pub` (validated 1,216 B X-Wing public key including ML-KEM-768 modulus checks), optional 32-byte `pgp_cert_digest`, paired optional `grace_prev_gen` (`< email_key_gen`) and `grace_until_ms`, and `issued_at_ms`.

**Five mandatory invariants enforced by `verify_email_key_descriptor`**:
1. `security.vault_write_state == VaultWriteState::Ready` (during a root rekey window, old descriptors are refused; external inbound returns temporary `451` so remote MTAs retry without mail loss);
2. Signer must be an unrevoked `root_administrator` (`Administrator` + `RootManage` + `VaultUnlock`);
3. **Binds `bound_root_generation == security.content_root_generation` while deliberately ignoring `security_epoch`**: binding a new login credential or editing policies bumps `security_epoch` without interrupting email delivery, whereas any `VaultUnlock` membership change forces `RekeyRequired` and advances `content_root_generation`, preventing relay rollback to stale keys;
4. **ML-DSA-65 anti-stripping**: if the certified `pq/<account>` leaf commits a `sig_digest` for the signer, `pq_sig_key_digest("ml-dsa-65", pq_sig_pub)` must match and Slot 1 must verify—classical-only stripping fails with `Error::IntegrityFailed`;
5. **PQ effectiveness**: `pq_effective` is `true` only when `created_root_generation >= pq.pq_since_generation`.

### 3.3 Payload encryption, per-recipient X-Wing wrapping, and daily hybrid signing (`dmsg/email-sig/1`)

Sending a native `dmsg-email/1` message executes four end-to-end cryptographic steps:

1. **Canonical payload construction and daily hybrid signature (`dmsg/email-sig/1`)**:
   - Build `EmailPayload` (`v = 1`, 64-hex non-zero random `email_id`, `from`, `to`, `cc`, `subject`, `text`, `html?`, `date_ms`, `in_reply_to?`, `thread_id?`, `attachments[]`, `cloud_attachments[]`).
   - Compute `payload_canonical_sha256` over canonical CBOR headers and body (and full native + cloud attachment records whenever attachments are present, authenticating filenames, bytes, and share URLs) plus `attachments_merkle_root = digest("dmsg/email-attachments/1", &attachment_sha256_list)`.
   - Encode the 7-element canonical CBOR `EmailSigClaims` array:
     ```text
     ["dmsg/email-sig/1", email_id, sender_account, sender_device_id,
      payload_canonical_sha256, attachments_merkle_root, date_ms]
     ```
   - Sign with the active device's `Capability::ContentSign` keys as **Tag 98 `COSE_Sign`** (profile `"application/vnd.dmsg.email-sig+cose;v=1"`, external AAD `"dmsg/email-sig/1"`, strictly isolated from `FormalApprove` / `dmsg-attestation/2`), and embed `email_sig` and optional `pq_sig_pub` inside `EmailPayload`.
2. **Symmetric payload encryption under random `MEK`**:
   - Generate a fresh 32-byte Message Encryption Key (`MEK`) and encrypt canonical CBOR `EmailPayload` with AES-256-GCM (untagged `COSE_Encrypt0`) using external AAD `("dmsg-email/1", email_id)`.
3. **Per-recipient X-Wing HPKE wrapping of `MEK`**:
   - After verifying every native recipient's `EmailKeyDescriptor`, derive deterministic HPKE context bytes:
     ```text
     email_envelope_info = CBOR(["dmsg/email-envelope/1", recipient_account_id, email_id, email_key_gen])
     ```
   - Wrap the 32-byte `MEK` under each recipient's `email_xwing_pub` in HPKE Base mode (using `email_envelope_info` as both HPKE `info` and AEAD AAD), producing `XWingEnvelope { enc (1,120 B), ciphertext (48 B) }` bound to that exact recipient, message ID, and key generation.
4. **Historical signature verification after device revocation**:
   - When the mailbox relay accepts an internal delivery, it records the sender's ICP-certified `evidence` snapshot and acceptance time `stored_at`.
   - When the recipient later opens the email (even after the sending device has been revoked), the client displays the sender identity attested by the relay rather than trusting the payload's claimed `from`, validates the recorded `evidence` against the IC root key at `stored_at` via `evidence::Trust::account` (confirming the device was active with `ContentSign`), and runs `verify_email_sig` (enforcing ML-DSA-65 anti-stripping and `payload_canonical_sha256` / `attachments_merkle_root` equality).
   - **Honest boundary**: this proves the sending device was authorized at relay acceptance time (trusting the relay's acceptance clock); formal documents needing on-chain consensus timestamps can additionally attach `dmsg-attestation/2`.

### 3.4 Open post-quantum email standard (`PQMail/1` Draft v0.5)

To enable end-to-end post-quantum email across independent mail providers—including zero-infrastructure bootstrapping with standard webmail and enterprise SMTP domains—dMsg implements the 100% vendor-neutral [`PQMail/1` Draft v0.5](https://dmsg.net/_/docs/pqmail.md) open specification (plus optional [`PQMail-AI/1`](https://dmsg.net/_/docs/pqmail-ai.md), [Profile B](https://github.com/ldclabs/ic-panda/blob/main/docs/protocol/pqmail-profile-b-v1.md), and [Profile C](https://github.com/ldclabs/ic-panda/blob/main/docs/protocol/pqmail-profile-c-v1.md)) alongside native ICP-certified `dmsg-email/1` for dMsg-to-dMsg mail:

- **Vendor-neutral core crate (`src/pqmail_core`)**: Implements strict RFC 8949 core deterministic CBOR, strict RFC 3986 `mailto:` normalization (`+` → `%2B`), closed `AKP` public keys (`{1: 7, 3: alg, -1: pub}` with `kid = SHA-256(CanonicalCBOR(key))`), composite `MLDSA65-Ed25519-SHA512` (`-65550`) and pure `ML-DSA-65`/`ML-DSA-87` (`-49`/`-50`) Tag 18 `COSE_Sign1`, X-Wing (`-65551`) and `ML-KEM-1024` (`-65552`) HPKE direct 32-byte `MEK` wrapping with `MEK` commitment, ISO 7816-4 bucket padding, single-mode isolated `Bcc` envelopes (fresh `msg_id`, fresh `MEK`, signed `Manifest.bcc`), chunked AEAD blobs with RFC 9162 binary ciphertext Merkle roots, RFC 1847/2387 MIME framing, DNS `_pqmail.<domain>` policy evaluation, `rollover_chain` (`unprotected[-65541]`) multi-hop rotation, RFC 9921 LTV archival verification (`300s` clock skew), and Profile B/C verifiers. Verified against all 52 reproducible test vectors in [`tests/vectors/pqmail-v1/`](https://github.com/ldclabs/ic-panda/blob/main/tests/vectors/pqmail-v1/).
- **Synced account-level signing keys & rollover**: Each `EmailKeyRecord` generation derives its composite `PQMail/1` signing key (`ML-DSA-65 + Ed25519`) from that generation's X-Wing seed, so the key syncs across all `VaultUnlock` devices via `VRK_g` and rotates with the ring without a new record field; published bundle state (`pqmail_bundle`) syncs too. This avoids public device-count leakage and multi-device bundle version conflicts. On `EMAIL-D04` key-ring rotation, the retired key signs a `RolloverLink` to the new one, and the bundle keeps listing at most two retired keys that earlier bundles listed, with `revoked_at`, for archival LTV verification. The unfolded outbound header is capped at 48 KiB. When trimming is necessary it keeps the newest contiguous rollover endorsements. The directory serves the full bundle. When neutral Profile B/C proofs are adopted externally, they bind `H(bundle_payload)` directly and are verified once at pin admission.
- **Profile 0 `PQMail-Key` outbound policy & relay-proxied discovery**: Regular addresses (`@dmsg.net` handles and verified BYOD domains) attach a folded Base64 `PQMail-Key` header by default (first-contact acceptance requires the delivery provider to sign this header together with `From`) so compatible external clients can bootstrap TOFU encryption (`pqmail_e2ee_tofu`) on first contact; privacy aliases default to omitting `PQMail-Key` unless explicitly enabled. Domains publishing `_pqmail.<domain>` (`v=pqmail1; policy=optional` or `policy=directory`) serve Profile A bundles at `GET https://pqmail.<domain>/.well-known/pqmail/keys/<local_hash>` (falling back to apex `https://<domain>/.well-known/pqmail/keys/<local_hash>` only if `pqmail.<domain>` is unreachable); `dmsg.net` publishes handles via `https://pqmail.dmsg.net/.well-known/pqmail/keys/<local_hash>` with `policy=optional` so opted-in privacy aliases can still use Profile 0 on explicit `404`, while `policy=directory` domains strictly reject Profile 0 downgrade fallbacks.

Production cross-domain delivery currently uses Profile 0/A with a TOFU pin. Native account mail uses ICP through `dmsg-email/1`. The core provides Profile B/C proof verification.

The preview returns a `delivery_plan_id` that binds consent to the recipients, delivery groups and pinned keys shown. A change requires a fresh preview. Valid pinned recipients receive encrypted copies, and mixed delivery requires confirmation of the plaintext group. Publishing the account email key also publishes directory bundles for owned version-one handles; bundles are valid for 90 days, exported bundles can sync before publication, and directory acceptance is recorded separately (aligning to the verified live directory bundle on `VERSION_CONFLICT`), and the `root_administrator` device that last published them renews them after sync once a quarter of validity remains. Another administrator device publishes them if none exist yet, or takes over once an eighth remains. External `_pqmail.<domain>` DNS and Profile A (`https://pqmail.<domain>/.well-known/pqmail/keys/<hash>` first, falling back to apex `https://<domain>/.well-known/pqmail/keys/<hash>` only if `pqmail.<domain>` is unreachable) directory lookups are proxied through the authenticated mailbox relay (with SSRF guards, same-origin redirect caps, and short caching) so clients never contact external sender origins directly. When opening an approved inbox message, clients skip directory lookups completely when the MX already attested `pqmail_dns_absent` alongside a DKIM-covered `PQMail-Key` header, and never issue external directory lookups for unapproved messages still in Screener or Trash—preventing both client IP leaks and read-receipt timing oracles. For unpinned recipients, failed discovery or addresses outside the `PQMail/1` grammar stay on plain SMTP. For pinned recipients whose cached bundle has expired and cannot be refreshed, clients never silently downgrade: sending prompts the user either to cancel (waiting for a fresh signed header from the correspondent) or to explicitly forget the expired key and send as standard email. An expired or unreadable directory bundle counts as no bundle. If a directory returns a valid bundle that rolls back or contradicts the pin, sending is hard-blocked and can only be cleared manually after out-of-band verification via **Forget encryption key** from the compose conflict warning (which clears the saved pin without sending the email) or from message security details. A privacy alias uses `PQMail/1` only when explicitly enabled; otherwise every recipient, pinned or not, receives plain SMTP. Clients decrypt chunked attachments carried as MIME siblings; attachments with only HTTPS locators currently display their name and size pending UI download integration.

The sender checks the complete MIME size, including folded headers, against the 128 KiB relay limit. Attachments that exceed it even as encrypted MIME siblings become encrypted share links. Sent mail retains the signed inner Message-ID and encrypted structured parts across devices. After a rollback, older readers can open cached ordinary mail and PQMail bodies locally. They show a conservative security tier and hide reply-all addresses on blind copies.

- **Dual-format client integration & mixed-recipient safeguards (`src/dmsg_client/src/email/pqmail.rs`)**: Clients keep local LDK-sealed `PQMail/1` pin records, seamlessly open both `PQMail/1` MIME envelopes and legacy `dmsg-email/1` messages, partition mixed compose recipients via `plan_recipient_groups` (requiring explicit confirmation before sending an unencrypted copy to plaintext-only recipients), and confirm before `Reply all` on an isolated `Bcc` copy.
- **AI payload isolation (`src/dmsg_agent/src/pqmail_ai.rs`)**: Supports `PQMail-AI/1` (`urn:pqmail:ext:ai-v1`) structured machine payloads (`structured_parts`) kept strictly separate from human body text and non-human sender attribution (`crit: [-65538]`). Agents access structured parts only under `email.structured.read` (`dmsg_pqmail_structured_parts`) and individual attachments only under non-wildcard `email.attachment.read:<email_id>:<sha256>:<part_index>` (`dmsg_pqmail_attachment_read`) without ever receiving mailbox private keys or message `MEK`s.

## 4. Storage architecture, unified 1 MiB chunking, and encrypted cloud attachments

### 4.1 Recipient-owned copies and unified 1 MiB chunking

| Parameter | Value | Purpose |
| --- | --- | --- |
| Native email ceiling (`MAX_EMAIL_NATIVE_BYTES`) | **25 MiB** | Unified across native `dmsg-email/1` and inbound SMTP so forwarding/replying never hits size cliffs |
| Inline storage threshold (`MAX_EMAIL_INLINE_BYTES`) | **4 KiB** | Tiny ciphertexts (`<= 4 KiB`) travel inline with metadata, avoiding extra object-storage round trips |
| Unified chunk size (`CHUNK`) | **1 MiB** (`1 << 20`) | Single chunk size shared by native upload/download and streaming inbound SMTP encryption |
| Maximum chunks (`EMAIL_MAX_CHUNKS`) | **25** | 25 × 1 MiB covers the full 25 MiB email budget; per-slot transport ceiling is `1 MiB + 64 B` |
| Native fan-out ceiling (`MAX_EMAIL_RECIPIENTS`) | **20** | Combined `To` + `Cc` + `Bcc` recipients per delivery |
| Deduplication window (`EMAIL_DEDUP_WINDOW_MS`) | **72 hours** | Deterministic key `digest("dmsg/email-dedup/1", (recipient, scope, sender, content_digest))` |

For native emails larger than 4 KiB, the sender slices the ciphertext into 1 MiB chunks, computes per-chunk SHA-256 digests, and uploads the encrypted chunks plus a small canonical CBOR manifest once. On delivery commit, the server copies those ciphertext chunks into each recipient's independent storage namespace while keeping the sender's Sent copy in the sender's own namespace. Because ownership is strictly per-mailbox, purging Sent/Trash or deleting an account never breaks any recipient's mail or attachments.

### 4.2 Automatic conversion of 25–100 MiB attachments to encrypted cloud links

When composing with large attachments or library files, `plan_attachment_modes` (`src/dmsg_client/src/email/mod.rs`) partitions every attachment between inline native delivery and encrypted cloud links automatically:

1. **Hard ceiling**: any single attachment exceeding **100 MiB** (`MAX_FILE`) is rejected (`QuotaExceeded`).
2. **Automatic cloud-attachment triggers**:
   - Any single file in the **25–100 MiB** range;
   - Multiple files whose cumulative encoded size (accounting for Base64url overhead and 16 KiB payload headroom) would exceed the **25 MiB** native email ceiling;
   - Cloud-only library files whose local chunks have been freed (streamed from encrypted backup into a fresh shared edition);
   - External SMTP uses a 128 KiB budget for the complete encoded MIME message. The composer includes headers, body and transfer encoding when selecting attachments for encrypted cloud links.
3. **Fresh-key re-encryption and lifecycle**:
   - The client generates a fresh random encryption key and share ID, re-encrypting the file into an independent shared edition (`dmsg-share-file/1`) that shares neither keys nor ciphertext bytes with the user's library copy.
   - Default link lifetime is **7 days** (`LINK_DEFAULT_MS`), configurable from **1 to 30 days** (`LINK_MAX_MS`).
   - Links take the form `<site>/s/<share_id>#<key>`, keeping the decryption key strictly in the URL fragment (never transmitted in HTTP requests). Native recipients receive structured `CloudAttachmentRef` metadata (filename, MIME type, byte size, plaintext SHA-256, share URL, expiry) authenticated inside `EmailPayload` and `dmsg/email-sig/1`; external SMTP messages append clickable links for in-browser decryption.

### 4.3 External SMTP inbound streaming encryption contract (`xwing-hkdfsha256-aes256gcm/1`)

To process standard Internet SMTP mail with **bounded streaming memory, zero plaintext on disk, and protection against truncation or chunk reordering**, `src/dmsg_protocol/src/email/inbound.rs` defines the public inbound encryption byte contract:

- **Suite identifier**: `"xwing-hkdfsha256-aes256gcm/1"`.
- **Fixed bounds**: `CHUNK_SIZE = 1 MiB`, `INLINE_LIMIT = 4,096 B`, `META_LIMIT = 8,192 B`, and fixed `WRAPPED_SIZE = 1,168 B` (`1,120 B X-Wing enc + 32 B secret + 16 B GCM tag`).
- **Step 1 — Wrap a random 32-byte per-recipient secret**: the inbound edge generates an independent uniformly random 32-byte secret and wraps it under the recipient's certified `email_xwing_pub` in HPKE Base mode, using the following byte string as both HPKE `info` and AEAD AAD:
  ```text
  kem_info = "dmsg/email-inbound-kem/v2" || 0x00 || suite || 0x00 || recipient || 0x00 || email_id || 0x00 || generation_be64
  ```
- **Step 2 — Derive chunk key, nonce prefix, and metadata key via HKDF-SHA-256**:
  ```text
  chunk_key          = HKDF-Expand(secret, "dmsg/email-inbound/chunk-key/v2", 32)
  chunk_nonce_prefix = HKDF-Expand(secret, "dmsg/email-inbound/chunk-nonce/v2", 8)
  meta_key           = HKDF-Expand(secret, "dmsg/email-inbound/meta-key/v2", 32)
  ```
- **Step 3 — Stream-encrypt 1 MiB chunks and seal immutable metadata**:
  - Chunk `index` (`u32`) uses deterministic 12-byte GCM nonce `chunk_nonce_prefix[8] || index_be32` and AAD:
    ```text
    chunk_aad = "dmsg/email-chunk/v2" || 0x00 || suite || 0x00 || recipient || 0x00 || email_id || 0x00 || index_be32 || last_u8
    ```
    Every non-final chunk must be exactly `1 MiB` and the final chunk sets `last = 1`. Clients enforce exact length, index ordering, and final-chunk authentication on decryption, defeating truncation, dropped chunks, reordering, or cross-email splicing.
  - Edge-verified TLS/PQ status, `dmarc_pass`, `mail_from`, `rcpt_tos`, and `Return-Path`/`Received` trace headers are serialized as JSON and sealed once under `meta_key` (fixed zero nonce) with AAD `"dmsg/email-meta/v2" || ... || generation_be64`, binding transport/DMARC evidence directly to the recipient, email ID, and key generation.

## 5. Email addressing model and anti-hijacking

Building on `dmsg_protocol::handle` (valid handles are 1–19 chars of `[a-z0-9_]` with no leading `_`) and 20-character Xid `AccountId`s, dMsg separates email identities into five orthogonal namespaces:

| Address class | Example | Naming authority | External SMTP boundary and anti-hijacking design |
| --- | --- | --- | --- |
| 1. Primary handle | `alice@dmsg.net` | On-chain `dmsg_handle` certified record | **Stateless rule `HandleRecord.version == 1`**: external SMTP is permitted only while never transferred; transferring the handle (`version >= 2`) permanently disables external inbound and outbound routing |
| 2. Plus subaddress | `alice+github@dmsg.net` | RFC 5233 `+` extension on primary handle | Inherits the primary handle's `HandleRecord.version == 1` enforcement |
| 3. Permanent privacy alias | `moss-9k4x@dmsg.net`, `p.7k2x9m4@dmsg.net` | 7–32 chars `[a-z0-9._-]`, **must contain `-` or `.`** (100% disjoint from handles) | External SMTP only; never resolved in internal directory; automatically strips sender display name on outbound to prevent primary-identity leaks; supports `create / pause / resume / destroy`, with destroyed aliases permanently tombstoned and never recycled |
| 4. Canonical Account ID | `<20-char AccountId>` | Immutable 12-byte Xid anchor | Internal dMsg addressing only; external SMTP inbound disabled by default because Xids are enumerable |
| 5. Custom domain (BYOD) | `you@yourdomain.com` | User-owned DNS (`claim / verify / update / unbind`) | Activated after DNS TXT ownership and DKIM verification; supports catch-all inbound and explicit outbound sender lists; periodic DNS re-verification revokes outbound if records lapse; unbinding releases cleanly without exposing historical encrypted mail in the prior owner's vault |

**Key anti-hijacking and anti-abuse safeguards**:

1. **Stateless post-transfer hijack prevention (`HandleRecord.version == 1`)**: On-chain registration and legacy-handle claims always write `version = 1`; only handle transfer increments `version >= 2`, and `version` is directly embedded in `dmsg_handle`'s ICP subnet-certified leaf. Checking `record.version == 1` across inbound MX routing, outbound `From` validation, and Plus subaddressing permanently blocks password-reset hijacking after any handle transfer with zero off-chain tombstone drift—while internal `@handle` routing continues following on-chain ownership and triggers a hard `pinned_handle` warning in existing contacts.
2. **Reserved system and brand handles**: `dmsg_protocol::handle` enforces `RESERVED_SYSTEM_HANDLES` (covering RFC 2142 infrastructure and high-risk impersonation names such as `postmaster`, `abuse`, `security`, `hostmaster`, `admin`, `support`, `noreply`, `dmarc`, `tlsrpt`, `wkd`, `openpgpkey`) and `RESERVED_BRAND_PREFIX = "dmsg"`.
3. **External receive policy, TLS floor, and opaque rejection**: Users configure per-account `external_policy` (`external_off` / `external_screener` / `external_open`), `inbound_tls` (`any` / `tls` / `pq_tls`), and outbound alias/domain selection during tier downgrades (preserving existing inbound delivery without silent deletion while restricting new creation or excess outbound). RCPT rejects known address, policy or quota failures. With an allowlist or open policy it reserves up to 25 MiB. DATA establishes the visible author and DMARC result before final screening. Unavailable capacity returns 452 and an oversized message returns 552.

## 6. Encrypted contacts, Screener, and anti-impersonation

### 6.1 Dual-layer architecture: encrypted address book + minimal execution projection

Contacts follow a two-layer design (`src/dmsg_client/src/contacts.rs`) separating private user data from server-enforced routing rules:

- **Layer 1: End-to-end encrypted address book (`kind = "contact"`, format `"dmsg-contact/1"`)**:
  - Each contact is stored as an individual object encrypted under `VRK_g` and synced across devices (up to `MAX_CONTACTS = 2,000`, with conflict visibility, deletion tombstones, and `PQ Recovery Kit` recoverability).
  - Holds private `nickname` (highest display priority across email, channels, and pickers to defeat public display-name spoofing), fallback display name, groups (up to 32), private notes (≤ 4 KiB), optional `dmsg` anchor (immutable `AccountId`, `pinned_handle`, `known_reset_generation`, `inbox_allow`, optional in-person QR `verified_at`), up to 16 external email entries (`trust_screener`, `auto_load_images`, reserved `ExternalPgpPin`), and up to 32 typed custom fields.
  - Supports **RFC 6350 vCard 4.0 export and vCard 3.0/4.0 import** (up to `MAX_VCARD_IMPORT_BYTES = 8 MiB`), deduplicating by `X-DMSG-ACCOUNT` first and normalized external email second while preserving existing trust and block settings.
- **Layer 2: Minimal execution projection (`dmsg/inbox/projection/v1`)**:
  - Projects only the minimal rule sets required for delivery filtering: `allow_accounts`, unified `blocked_accounts` (≤ `MAX_UNIFIED_BLOCKS = 2,000`), `blocked_external` (≤ `MAX_EXTERNAL_RULES = 1,000`), and `allowed_external` (≤ 1,000).
  - Ordinary contacts without allow/block rules, along with all nicknames, groups, and notes, are **never projected to the server**. Every update persists an LDK-sealed retry job (`contact-projection-job:<op_id>`) with monotonic `updated_at` reconciliation across devices.

### 6.2 Source-tagged unified blocklist and on-chain anti-impersonation

- **Source-tagged unified blocklist (`BlockSources`)**: Every blocked dMsg account tracks three independent source flags `{ legacy_policy, unified_contact, mobile_safety }`; any true flag blocks across email, Screener, and channels. Legacy clients can only clear `legacy_policy`, never undoing unified or mobile blocks; modern "unblock everywhere" atomically clears all source flags.
- **Zero-fatigue hard-block warnings (`ContactSafetyWarning`)**:
  - Routine device revocation and `EmailKey` rotation remain transparent to contacts so users never suffer security-banner fatigue.
  - Only two on-chain state transitions that represent genuine control changes trigger a hard block in `check_contact_safety` before sending (requiring explicit `confirm_safety_warnings` acknowledgement):
    1. **`HandleTransferred`**: a contact's `pinned_handle` now resolves on-chain to a different `AccountId`;
    2. **`ContentRootReset`**: the peer's certified `PqSnapshot.content_root_reset_generation` rose above the locally recorded `known_reset_generation` (indicating a destructive history-discarding root reset).

Deleted incoming and Sent copies are emitted as permanent tombstones in their respective cursor streams. Moving a Sent copy to Trash and emptying it, or using `email/empty_sent`, retires only the sender’s body and attachments. Restoring a Sent copy from Archive or Trash returns it to Sent. Other devices clear their copies on sync.

### 6.3 Screener isolation and DMARC-aligned bypass

- **Bounded isolation pool**: Unapproved first-contact mail from internal or external strangers lands in **Screener** with a **14-day** automatic expiration (`SCREENER_TTL_MS`), **isolated from primary mailbox storage quota until explicitly accepted**. Users act with `allow` (moves to Inbox and optionally allowlists the sender), `block` (blocks and deletes), or `delete`. Each sender may have one new, still-screened message within a rolling 24 hours. A block uses the DMARC-authenticated author when available and otherwise the envelope sender.
- **DMARC alignment hard requirement**: The inbound SMTP edge ignores untrusted upstream `Authentication-Results` headers and trusts only its own freshly verified `SPF / DKIM / DMARC` evaluation. Even if an external sender is in `allowed_external`, mail bypasses Screener **only when `dmarc_pass == true`**; failing DMARC forces the message into Screener with a `DmarcFailed` warning.
- **Per-contact remote image gate (`email_contact_allows_images`)**: Even when `auto_load_images` is enabled for a contact, clients allow automatic remote images only when the message is in `inbox` or `archive`, `dmarc_pass == true`, zero spoof warnings are present, and neither the address nor domain is blocked. Screener messages always block remote images.

## 7. Multi-device sync, client search, and safe rendering

### 7.1 Two-tier encrypted sync, recoverable Sent mail, and legacy letter projection

1. **Symmetric header index writeback (`EmailHeaderIndex`)**: The first unlocked device to decrypt an incoming message builds an `EmailHeaderIndex` (subject, snippet, sender/recipient summary, security tier) and writes it back encrypted under `VRK_g` (domain `"dmsg/email-header-index/1"`). Sibling devices incrementally sync lists symmetrically without repeating X-Wing decapsulation; bodies larger than 4 KiB (and > 256 KiB during background sync) are lazily fetched and decrypted on open.
2. **Recoverable Sent folder (`SentMeta`)**: After sending, the client encrypts `SentMeta`—holding the sender's `MEK`, private `bcc[]`, `security_tier`, `pq_effective`, optional `inline_ciphertext` (for `<= 4 KiB`) or `upload_id`, and external `Message-ID`—under `VRK_g` (domain `"dmsg/email-sent-meta/1"`), backed by LDK-sealed retry jobs (`email-sent-job:<id>`). Both sibling devices and offline `PQ Recovery Kit` recoveries restore complete Sent bodies, attachments, and private Bcc lists.
3. **Self-sent cache isolation**: Messages sent to one's own account maintain distinct local cache keys (`<email_id>` for the received copy and `sent:<email_id>` for the Sent copy) so folder moves and read flags never collide.
4. **Read-only legacy private letters**: Local historical `inbox-letter:*` and `inbox-job:outgoing:*` entries project transparently into Inbox, Archive, and Sent as `legacy_letter` items; legacy outgoing entries that did not retain plaintext bodies explicitly set `legacy_body_unrecoverable = true`.

### 7.2 Zero-plaintext-on-disk local encrypted search

All cached email summaries (`email-item:<id>`), bodies (`email-body:<id>`), and contacts are stored on disk strictly under `LocalDataKey` (LDK) encryption—no plaintext inverted index is written to disk. While unlocked, `SearchCache` (`src/dmsg_client/src/search/cache.rs`) builds weighted in-memory projections (`subject` 100, `from` 92, `rcpt_to` 85, `to` 80, `snippet` 60) with highlight spans; `SearchCache::clear()` drops all plaintext projections immediately upon lock or workspace switch.

### 7.3 Pure-Rust HTML allowlist sanitization and anti-spoofing

- **Pure-Rust RFC 5322 / MIME engine (`src/dmsg_client/src/email/mime.rs`)**: Uses `mail-parser` to parse inbound MIME messages and attachments (stripping path separators and control characters from filenames and capping at 180 chars) and `mail-builder` to emit outbound MIME while keeping `Bcc` strictly out of message headers.
- **Zero-C allowlist HTML sanitizer (`sanitize_email_html`)**:
  - Drops `<script>`, `<style>`, `<iframe>`, `<object>`, `<embed>`, `<noscript>`, `<svg>`, `<math>`, `<template>`, and `<head>` along with all inner content;
  - Permits only a strict formatting tag allowlist and minimal structural attributes (`colspan`, `rowspan`, `title`), stripping all `on*` event handlers, `style`, and `javascript:`/`vbscript:`/`data:` URIs;
  - Forces `rel="noopener noreferrer" target="_blank"` on links and `loading="lazy" referrerpolicy="no-referrer"` on allowed images;
  - Blocks all remote `http://`/`https://` images by default and reports `blocked_remote_images` so clients can offer per-message loading without leaking read receipts or IP addresses to tracking pixels.
- **Header spoof and PQMail integrity detection (`detect_spoof_warnings` & `open_pqmail_mime_message`)**: Flags internationalized Punycode domains (`PunycodeDomain`, `xn--`), display names embedding a different email address (`DisplayNameMismatch`), failed DMARC alignment (`DmarcFailed`), outer SMTP `From` mismatch against a signed `PQMailManifest.from` (`OuterFromMismatch`), and surreptitious re-encrypted forwarding (`ResealedForwardDetected`).
- **Isolated `PQMail-AI/1` rendering**: Clients display `delegated_agent` / `automated` attribution pills and render machine-readable `structured_parts` in a clearly labeled untrusted card separate from the human body, never treating body prose or `intent_hint` as executable authority.

### 7.4 Single pure-Rust core across platforms

Desktop, CLI, and MCP share the local Rust daemon (backed by `pqmail_core` + `dmsg_client`), where all email and contact network operations execute via `Hold` without ever holding a client state lock across `.await`. iOS and Android call the exact same `dmsg_client` core directly through `dmsg_mobile` (UniFFI), keeping cryptographic verification, attachment partitioning, `PQMail/1` pin/plan checks, HTML sanitization, and downgrade indicators identical across all four platforms.

## 8. Current implementation scope and future interoperability roadmap

The table below distinguishes capabilities implemented in the public codebase from external milestones and reserved compatibility layers:

| Area | Implementation status | Notes and boundaries |
| --- | --- | --- |
| Open standard `PQMail/1` (Draft v0.5), `PQMail-AI/1`, Profile B/C & reference CLI | **Implemented (`src/pqmail_core`)** | 100% vendor-neutral `wasm32`-clean core crate + optional standalone `pqmail` CLI; verified against all 52 vectors (`TV-01`–`TV-13`, Profile B 20 cases, Profile C 19 cases) and bidirectional CLI/client integration using the same core (`pqmail_cleanroom_interop`); English & Chinese specs in [`docs/protocol/`](https://github.com/ldclabs/ic-panda/blob/main/docs/protocol/) |
| Four-platform `PQMail/1` client / UI / MCP integration | **Implemented** | Synced account-level composite signing keys with `rollover_chain`, 90-day auto-renewal, relay-proxied discovery with Screener gating, Profile 0 `PQMail-Key` policy, expired/conflicted pin UX and manual key reset, isolated Bcc, chunked RFC 2387 attachments, Desktop/iOS/Android UI in 23 languages, and `dmsg_agent` MCP isolation tools |
| Native `dmsg-email/1` PQ E2EE and hybrid daily signing | **Implemented** | Includes `EmailKeyRecord`, Tag 98 `EmailKeyDescriptor`, `dmsg/email-sig/1`, historical evidence verification, and `pqc-email-v1.json` deterministic vectors |
| Unified 1 MiB chunking (≤ 25 MiB) and 25–100 MiB auto cloud attachments | **Implemented** | Shipped across Rust core, Desktop, CLI, iOS, and Android |
| Inbound SMTP streaming encryption (`xwing-hkdfsha256-aes256gcm/1`) and outbound management | **Implemented** | Includes `HandleRecord.version == 1` anti-hijacking, privacy aliases, BYOD custom domains, receive/TLS policies, and HTML sanitization |
| Encrypted contacts (`dmsg-contact/1`), vCard 3.0/4.0, and unified blocklist | **Implemented** | Includes minimal projection, source-tagged blocklist, on-chain anti-impersonation hard blocks, and app-wide pickers |
| Screener, DMARC hard enforcement, multi-device sync, and search | **Implemented** | Includes 14-day isolation pool, `EmailHeaderIndex`, `SentMeta`, in-memory `SearchCache`, and legacy letter projection |
| External OpenPGP PQC interop (RFC 9580 v6 + RFC 9980 + RFC 9788) and WKD | **Roadmap (preserved on-demand compatibility layer)** | Wire hooks preserved alongside `PQMail/1` (`EmailKeyDescriptorPayload.pgp_cert_digest`, `ExternalPgpPin`, `EmailSecurityTier::PgpE2ee`); client-side OpenPGP keygen, PGP/MIME authoring, and live interop testing remain planned on demand |
| Out-of-band password-protected confidential web portal links | **Roadmap** | Planned exclusively with out-of-band passwords (explicitly scoped to portal script integrity, with no same-inbox verification-code mode) |
| Optional on-chain consensus timestamps (`dmsg-attestation/2`) and on-disk full-body search index | **Roadmap** | Daily email signatures are already domain-separated from `dmsg-attestation/2` for clean composition |
| `PQMail/1` formal IANA registration & third-party cryptographic audit | **External milestone** | Media types, COSE parameters/algorithms, `PQMail-Key`, `_pqmail`, and `/.well-known/pqmail` remain provisional until IANA assignment and external audit completion |

**Verification boundary**: Unit tests, deterministic vectors, and shared-core CLI interop tests in this public repository verify `dmsg-email/1` and `PQMail/1` wire encodings, hybrid/composite signing and anti-stripping, key rotation pipelines, streaming inbound chunk crypto, isolated Bcc and chunked attachments, automatic cloud-attachment partitioning, contact projections/vCard, HTML sanitization, MCP agent permission isolation, and client unit/static checks. Live Electron/Android/iOS emulator visual screenshots, iOS Xcode UI test runs, production SMTP deliverability, multi-tenant sender reputation controls, live third-party MX interoperability, and formal third-party cryptographic audits are outside local repository unit tests and must be verified separately.

## 9. Source code and verification entry points

### 9.1 Public source files

| Layer | Key files |
| --- | --- |
| Vendor-neutral `PQMail/1` core & CLI | [`src/pqmail_core/src/lib.rs`](https://github.com/ldclabs/ic-panda/blob/main/src/pqmail_core/src/lib.rs) · [`src/pqmail_core/src/bin/pqmail.rs`](https://github.com/ldclabs/ic-panda/blob/main/src/pqmail_core/src/bin/pqmail.rs) · [`src/pqmail_core/tests/conformance_vectors.rs`](https://github.com/ldclabs/ic-panda/blob/main/src/pqmail_core/tests/conformance_vectors.rs) |
| `PQMail/1` open specs & 52 vectors | [`docs/protocol/pqmail-v1.md`](https://dmsg.net/_/docs/pqmail.md) · [`docs/protocol/pqmail-ai-v1.md`](https://dmsg.net/_/docs/pqmail-ai.md) · [`docs/protocol/pqmail-profile-b-v1.md`](https://github.com/ldclabs/ic-panda/blob/main/docs/protocol/pqmail-profile-b-v1.md) · [`docs/protocol/pqmail-profile-c-v1.md`](https://github.com/ldclabs/ic-panda/blob/main/docs/protocol/pqmail-profile-c-v1.md) · [`tests/vectors/pqmail-v1/`](https://github.com/ldclabs/ic-panda/blob/main/tests/vectors/pqmail-v1/) · [`scripts/verify-pqmail-vectors.mjs`](https://github.com/ldclabs/ic-panda/blob/main/scripts/verify-pqmail-vectors.mjs) |
| dMsg protocol layer | [`src/dmsg_protocol/src/email.rs`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_protocol/src/email.rs) · [`src/dmsg_protocol/src/email/inbound.rs`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_protocol/src/email/inbound.rs) · [`src/dmsg_protocol/src/handle.rs`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_protocol/src/handle.rs) · [`src/dmsg_protocol/src/pqc.rs`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_protocol/src/pqc.rs) |
| Deterministic `dmsg-email/1` vectors | [`tests/vectors/client/pqc-email-v1.json`](https://github.com/ldclabs/ic-panda/blob/main/tests/vectors/client/pqc-email-v1.json) · [`tests/vectors/client/README.md`](https://github.com/ldclabs/ic-panda/blob/main/tests/vectors/client/README.md) |
| Client email core & interop test | [`src/dmsg_client/src/email/mod.rs`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_client/src/email/mod.rs) · [`src/dmsg_client/src/email/pqmail.rs`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_client/src/email/pqmail.rs) · [`src/dmsg_client/src/email/operations.rs`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_client/src/email/operations.rs) · [`src/dmsg_client/src/email/maintenance.rs`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_client/src/email/maintenance.rs) · [`src/dmsg_client/src/email/mime.rs`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_client/src/email/mime.rs) · [`src/dmsg_client/tests/pqmail_cleanroom_interop.rs`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_client/tests/pqmail_cleanroom_interop.rs) |
| Contacts, cloud attachments, evidence, and search | [`src/dmsg_client/src/contacts.rs`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_client/src/contacts.rs) · [`src/dmsg_client/src/library/link.rs`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_client/src/library/link.rs) · [`src/dmsg_client/src/evidence.rs`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_client/src/evidence.rs) · [`src/dmsg_client/src/search/cache.rs`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_client/src/search/cache.rs) |
| Agent MCP, CLI, and mobile bindings | [`src/dmsg_agent/src/pqmail_ai.rs`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_agent/src/pqmail_ai.rs) · [`src/dmsg_cli/src/email_methods.rs`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_cli/src/email_methods.rs) · [`src/dmsg_cli/src/contacts_methods.rs`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_cli/src/contacts_methods.rs) · [`src/dmsg_mobile/src/email.rs`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_mobile/src/email.rs) · [`src/dmsg_mobile/src/contacts.rs`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_mobile/src/contacts.rs) |
| Desktop, iOS, and Android UIs | [`src/dmsg_desktop/src/renderer/views/Email.svelte`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_desktop/src/renderer/views/Email.svelte) · [`src/dmsg_desktop/src/renderer/views/email/ComposeEmail.svelte`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_desktop/src/renderer/views/email/ComposeEmail.svelte) · [`src/dmsg_desktop/src/renderer/views/Contacts.svelte`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_desktop/src/renderer/views/Contacts.svelte) · [`src/dmsg_ios/Features/EmailView.swift`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_ios/Features/EmailView.swift) · [`src/dmsg_ios/Features/ContactsView.swift`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_ios/Features/ContactsView.swift) · [`src/dmsg_android/app/src/main/java/net/dmsg/android/ui/EmailScreen.kt`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_android/app/src/main/java/net/dmsg/android/ui/EmailScreen.kt) · [`src/dmsg_android/app/src/main/java/net/dmsg/android/ui/ContactsScreen.kt`](https://github.com/ldclabs/ic-panda/blob/main/src/dmsg_android/app/src/main/java/net/dmsg/android/ui/ContactsScreen.kt) |

### 9.2 Local verification commands

With Rust and Node.js toolchains installed, run the following commands from the repository root (use `--profile mobile` instead of `--release` for optimized Rust tests to avoid workspace full-LTO memory spikes):

```bash
# Verify all 52 PQMail/1 v0.5 vectors (core 13 groups + Profile B 20 cases + Profile C 19 cases)
node scripts/verify-pqmail-vectors.mjs && \
  node scripts/verify-pqmail-vectors.mjs --profile-b && \
  node scripts/verify-pqmail-vectors.mjs --profile-c

# Verify vendor-neutral pqmail_core library + optional standalone CLI against all vectors
cargo test --profile mobile -p pqmail_core --all-features

# Verify EmailKeyDescriptor, dmsg/email-sig/1, and pqc-email-v1.json
cargo test --profile mobile -p dmsg_protocol email

# Verify client email core, PQMail/1 round-trips, shared-core CLI interop, contacts, and Agent MCP isolation
cargo test --profile mobile -p dmsg_client email
cargo test --profile mobile -p dmsg_client --features testing --test pqmail_cleanroom_interop
bash scripts/dmsg/test-pqmail-rollback.sh
cargo test --profile mobile -p dmsg_client contacts
cargo test --profile mobile -p dmsg_agent
```
