# PQMail/1 open post-quantum encrypted email standard

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

---

# PQMail/1: Post-Quantum End-to-End Encrypted Electronic Mail (Draft v0.5)

> **Status**: Working Draft (IETF Internet-Draft style, vendor-neutral core specification).
> **Schema**: [pqmail-v1.cddl](https://github.com/ldclabs/ic-panda/blob/main/docs/protocol/pqmail-v1.cddl) · **Test Vectors**: [pqmail-v1.vectors.json](https://github.com/ldclabs/ic-panda/blob/main/tests/vectors/pqmail-v1/pqmail-v1.vectors.json) · **Optional Extensions**: [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) · [Profile C](https://github.com/ldclabs/ic-panda/blob/main/docs/protocol/pqmail-profile-c-v1.md).
> **Conventions**: The key words **MUST**, **MUST NOT**, **REQUIRED**, **SHALL**, **SHALL NOT**, **SHOULD**, **SHOULD NOT**, **RECOMMENDED**, **NOT RECOMMENDED**, **MAY**, and **OPTIONAL** in this document are to be interpreted as described in BCP 14 ([RFC 2119](https://www.rfc-editor.org/rfc/rfc2119), [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174)) when, and only when, they appear in all capitals, as shown here.
> **Experimental Identifiers**: The protocol identifier `PQMail/1`, `application/pqmail*` media types, COSE private-use header parameters `-65540..-65541`, and COSE private-use algorithm identifiers `-65550..-65552` are experimental values pending formal IANA registration.

---

## 1. Scope

PQMail/1 defines a post-quantum end-to-end encrypted (E2EE) message container, key bundle format, progressive discovery mechanism, deadlock-free key rollover chain, and MIME encapsulation for Internet email.

A sender discovers each recipient's public key bundle (§4), signs a structured manifest, encrypts the padded signed manifest under a fresh random Message Encryption Key (`MEK`), and encapsulates that `MEK` individually for every intended recipient (§3). Each blind carbon-copy (`Bcc`) recipient receives an isolated single-recipient envelope with an independent `msg_id` and `MEK`. Conformant implementations **MUST** support delivering envelopes and encrypted attachment blobs over MIME (§5), readable via IMAP or JMAP.

SMTP routing addresses, delivery timestamps, and bucket-aligned message sizes remain visible to mail transport agents, and recipient key identifiers (`kid`) in envelopes may be correlated across messages. Compromise of a recipient's long-term static decryption key allows decryption of past messages encapsulated to that public key. Multi-device key synchronization, local mailbox indexing, server-side encryption-at-rest for legacy plaintext mail, and anti-spam screening are outside the scope of this specification.

---

## 2. Identity, Algorithms, and Encoding

### 2.1 Mailbox Identity

Given a single SMTP mailbox, extract the local-part `local` and DNS domain `domain`. Parse the local-part per RFC 5321 / RFC 6531, preserving original case and UTF-8 characters while rejecting all control characters; serialize `local` using minimal quoting (omit quotes whenever valid as a Dot-string; otherwise enclose in double quotes and escape only `"` and `\`). Convert the domain to lowercase ASCII A-label form per IDNA2008 and strip any trailing dot.

```text
lookup_local = ascii_lowercase(local)              ; only ASCII A-Z -> a-z
local_hash   = hex_lower(SHA-256(UTF-8(lookup_local)))
address      = "mailto:" || pct_encode(UTF-8(local)) || "@" || domain
```

`pct_encode` **MUST** apply strict RFC 3986 `unreserved` percent-encoding: preserve only ASCII letters (`A-Z`, `a-z`), digits (`0-9`), and `-._~`; encode every other octet (explicitly including `+`) as uppercase `%HH`. (**Note**: This rule is stricter than [RFC 6068 §2](https://www.rfc-editor.org/rfc/rfc6068#section-2); implementations **MUST NOT** rely on generic `mailto:` URI serializers that leave `+` or sub-delimiters unencoded.) For example, `A+b@EXAMPLE.org` canonicalizes to `mailto:A%2Bb@example.org`, and its directory hash input is `a+b`.

PQMail deliberately treats spellings within the same domain that differ only in ASCII case of the local-part as the same mailbox identity. Participating domains **MUST** ensure that each `(domain, lookup_local)` pair maps to at most one mailbox principal; if case variants belong to distinct users, none of those variants may publish a key bundle or enable in-band header bootstrapping. Directory lookups, local pin caches, and outer `From` comparisons all compare `(domain, lookup_local)`. Once matched, HPKE `info`, manifest addresses, and COSE `iss` **MUST** use the exact verbatim `bundle.address` string. SMTP transport retains the actual mailbox spelling ([RFC 5321 §2.4](https://www.rfc-editor.org/rfc/rfc5321#section-2.4)).

### 2.2 Algorithms

Conformant implementations **MUST** implement all core algorithms listed below without handshake negotiation. The HPKE suite is dictated by the recipient's encryption key `alg`, while the signature algorithm and symmetric AEAD cipher are chosen by the sender.

| Category | `alg` | Construction | Default | Sizes |
| --- | --- | --- | --- | --- |
| HPKE Public Key | `-65551` | X-Wing (`0x647a`) + HKDF-SHA256 (`0x0001`) + AES-256-GCM (`0x0002`) | Yes | Public key 1,216 B, `enc` 1,120 B |
| HPKE Public Key | `-65552` | ML-KEM-1024 (`0x0042`) + HKDF-SHA384 (`0x0002`) + AES-256-GCM (`0x0002`) | | Public key 1,568 B, `enc` 1,568 B |
| Signature | `-65550` | `MLDSA65-Ed25519-SHA512` Composite Signature (RFC 10073) | Yes | Public key 1,984 B, signature 3,373 B |
| Signature | `-49` / `-50` | ML-DSA-65 / ML-DSA-87 (RFC 9964) | | Signature 3,309 B / 4,627 B |
| Symmetric AEAD | `3` / `24` | AES-256-GCM / ChaCha20-Poly1305 (COSE algorithm IDs) | `3` | Nonce 12 B, tag 16 B |

The sender determines its signature algorithm from its signing key. Unknown algorithm identifiers **MUST** be rejected and **MUST NOT** fall back to a default. Code point `-65550` permanently identifies the composite construction below; any future IANA-assigned identifier must be introduced explicitly by a subsequent specification rather than substituted in place, because `alg` participates in `kid` computation.

### 2.3 Composite Signatures, Closed `AKP` Keys, and Mathematical Key Validation

1. **`MLDSA65-Ed25519-SHA512`** (RFC 10073 construction with empty COSE context `ctx`): the public key is `pk_mldsa65[1952] || pk_ed25519[32]` and the signature is `sig_mldsa65[3309] || sig_ed25519[64]`. For a COSE `Sig_structure` byte string `M`:
   ```text
   Prefix = "CompositeAlgorithmSignatures2025"     ; 32 B ASCII
   Label  = "COMPSIG-MLDSA65-Ed25519-SHA512"       ; 30 B ASCII
   M'     = Prefix || Label || 0x00 || SHA-512(M)  ; 0x00 is the empty ctx length byte; 127 B total
   sig_mldsa65 = ML-DSA-65.Sign(sk_mldsa65, M', ctx = Label)
   sig_ed25519 = Ed25519.Sign(sk_ed25519, M')
   ```
   Both component keypairs **MUST** be generated independently and dedicated exclusively to this composite key. Both component signatures **MUST** verify. Pure ML-DSA (`-49` / `-50`) signs `M` directly per RFC 9964 with empty context `ctx`.
2. **Closed `AKP` Public Keys** (RFC 9964, `kty = 7`): Every public key **MUST** be the exact three-entry map `{1: 7, 3: alg, -1: pub}`. Decoders **MUST** reject public keys containing any extra map entries (including `kid`, `key_ops`, or private-key parameter `-2`). The key identifier is defined as `kid = SHA-256(CanonicalCBOR(public_key))`, matching RFC 9964 §6.
3. **Mathematical Key Validation** (**MUST** be executed whenever importing a key bundle or rollover link):
   - **X-Wing and ML-KEM-1024 public keys**: The ML-KEM polynomial encoding bytes (first `1,152 B` of X-Wing, first `1,536 B` of ML-KEM-1024) **MUST** pass FIPS 203 §7.2 modulus validation (every 12-bit coefficient `< 3329`). In addition, the trailing 32-byte X25519 component (`[1184..1216]`) of an X-Wing public key **MUST NOT** be all-zero or any low-order Curve25519 point whose scalar multiplication produces an all-zero shared secret (aligned with RFC 7748 §6.1 / RFC 9180 §7.1.1; encapsulation and decapsulation **MUST** likewise reject an all-zero X25519 shared secret `ss_X`).
   - **Composite signing public keys**: The first `1,952 B` **MUST** be a valid ML-DSA-65 public key, and the final `32 B` **MUST** be a canonically encoded Ed25519 point that is not of small order.

### 2.4 Core Deterministic CBOR, Clock Skew Tolerance, and Common COSE Verification

All CBOR structures **MUST** use RFC 8949 §4.2.1 Core Deterministic Encoding: definite lengths, shortest integer and length encodings, and map keys sorted by encoded byte order. Floating-point values, `null`, duplicate map keys, and trailing bytes are forbidden; omitted optional fields **MUST** be absent rather than `null`. Decoders **MUST** reject non-conforming inputs and **SHOULD** enforce a maximum nesting depth of 32. Signature verification **MUST** hash/sign the exact received `protected` header bytes without re-encoding.

- **Notation**: Within `CanonicalCBOR([...])`, `"..."` denotes a CBOR text string (`tstr`) and `b"..."` denotes a CBOR byte string (`bstr`); `||` denotes byte concatenation, where `"..."` indicates ASCII bytes.
- **Bounded Clock Skew Tolerance**: All real-time freshness and timestamp checks share a uniform constant **`MAX_CLOCK_SKEW = 300` seconds (5 minutes)** to prevent false rejections caused by small clock drift across endpoints, TSAs, or directory servers.
- **Common `COSE_Sign1` Rules**: Both manifests and key bundles use CBOR Tag 18 `COSE_Sign1` ([RFC 9052 §3](https://www.rfc-editor.org/rfc/rfc9052#section-3)). Verifiers **MUST** check the four array elements against the CDDL schema, verify the object-specific `content type` (`3`), `typ` (`16`), `kid` (`4`), and `alg == selected_public_key.alg`. Label keys **MUST NOT** overlap between `protected` and `unprotected`. `crit` (`2`) **MUST** include `15` and `16`; every label in `crit` **MUST** be unique, present in `protected`, and understood by the verifier, or else verification **MUST** fail. Unrecognized non-critical headers and extension fields permitted by the CDDL **MAY** be ignored.

---

## 3. Message Container

### 3.1 Sign-Then-Pad-Then-Encrypt

The top-level message object is `PQMailEnvelope` (`application/pqmail+cbor; version=1`), specified in [pqmail-v1.cddl](https://github.com/ldclabs/ic-panda/blob/main/docs/protocol/pqmail-v1.cddl). Sending procedure:

1. **Manifest**: Construct `PQMailManifest` and encode per §2.4 as `manifest_bytes`.
2. **Signature**: Create a Tag 18 `COSE_Sign1` (`PQMailSignedManifest`):
   - `protected` **MUST** include `1` (`alg`), `2` (`crit`, containing at least `15` and `16`), `3` (`"application/pqmail-manifest+cbor"`), `4` (signing key `kid`), `15` (`cwt-claims`: `iss` = `Manifest.from.uri`, `iat`), and `16` (`typ`: `"application/pqmail-signed+cose;v=1"`).
   - `external_aad` is `b"pqmail/v1/signed-manifest"`:
     ```text
     Sig_structure = CanonicalCBOR(["Signature1", protected, b"pqmail/v1/signed-manifest", manifest_bytes])
     ```
   - `unprotected` **MAY** include an RFC 9921 `3161-ctt` timestamp token (header `270`, where `MessageImprint` hashes the CBOR-encoded `signature` byte string).
3. **Padding**: Let `signed_bytes = CanonicalCBOR(PQMailSignedManifest)` with length `L` **MUST** satisfy `L <= 2,097,151` (oversized bodies or resources **MUST** use `encrypted-blob-ref`). Choose a padded bucket size `B` satisfying `L + 1 <= B <= 2,097,152` (**SHOULD** be a power of two):
   ```text
   padded = signed_bytes || 0x80 || 0x00 * (B - L - 1)
   ```
   After AEAD decryption, the recipient strips all trailing `0x00` octets, **MUST** verify the final remaining octet is `0x80`, removes it, and decodes the manifest.
4. **Manifest Encryption**: Generate a fresh 32-byte random `MEK`. Independently of recipient HPKE suite, derive keys via HKDF-Expand-SHA256:
   ```text
   commitment     = HKDF-Expand-SHA256(MEK, "pqmail/v1/commitment"     || msg_id, 32)
   manifest_key   = HKDF-Expand-SHA256(MEK, "pqmail/v1/manifest-key"   || msg_id, 32)
   manifest_nonce = HKDF-Expand-SHA256(MEK, "pqmail/v1/manifest-nonce" || msg_id, 12)
   manifest_aad   = CanonicalCBOR(["pqmail/v1/manifest", aead_alg, msg_id])
   encrypted_manifest = AEAD-Seal(manifest_key, manifest_nonce, manifest_aad, padded)
   ```
   `commitment` binds all recipients in the envelope to the exact same `MEK`. Every new encryption **MUST** generate a fresh random 16-byte `msg_id` and 32-byte `MEK`; transport retries reuse the existing ciphertext.
5. **Recipient Encapsulation**: For each recipient, compute RFC 9180 Base mode `(enc, ciphertext) = SealBase(pkR, info, b"", MEK)` and place `enc` and `ciphertext` (always 48 bytes) in recipient entry fields `2` and `3`:
   ```text
   info = CanonicalCBOR(["pqmail/v1/recipient", recipient_address, msg_id, kid])
   ```

A recipient attempts decapsulation against entries matching its `kid` using its canonical `recipient_address` (aliases may share a key). Any decapsulation failing `MEK` length (32 B), `commitment`, or AEAD verification **MUST** be discarded. After unpadding, verify the signature as follows:

- **Identity and Key Selection**: The signing key **MUST** come from a sender key bundle accepted under §4, selected uniquely by `protected` header `4` (`kid`). `cwt-claims.iss`, sender `bundle.address`, and `Manifest.from.uri` **MUST** be byte-identical, and `Manifest.msg_id` **MUST** equal the envelope `msg_id`. If the signing key carries `restricted_to_extension`, any verifier not implementing that extension **MUST** reject the message.
- **Real-Time and Long-Term Archival Validation (LTV) Time Rules**:
  1. **With independent time evidence `evidence_time` (LTV archival or revoked-key re-verification)**: When trusted time evidence binds **this specific signature or message** (such as a verified RFC 9921 TSA timestamp or a trusted mailbox ingestion timestamp), evaluate validity at `evidence_time`: the sender's key bundle **MUST** have been unexpired at `evidence_time` (`evidence_time < bundle.expires_at`, supporting both contemporaneously archived bundles and rotated successor bundles), the signing key **MUST** have been active at `evidence_time` (`valid_from <= evidence_time` and either no `revoked_at` or `evidence_time < revoked_at`), and self-reported `iat` **MUST** satisfy `valid_from <= iat + MAX_CLOCK_SKEW` and `iat <= evidence_time + MAX_CLOCK_SKEW`. Consequently, archived mail remains independently verifiable years later even after the sender's key bundle expires or the domain ceases operation. A directory log timestamp proving only key existence **MUST NOT** be treated as message `evidence_time`.
  2. **Without independent time evidence (real-time receipt)**: The signing key **MUST NOT** be revoked at `now` (`revoked_at` absent or `now < revoked_at`), the key bundle **MUST** be valid at `now` (`bundle.issued_at <= now + MAX_CLOCK_SKEW` and `now < bundle.expires_at`), and `iat` **MUST** satisfy `valid_from <= iat + MAX_CLOCK_SKEW`, `iat <= now + MAX_CLOCK_SKEW`, and (if a future `revoked_at` is set) `iat < revoked_at`. If the key is already revoked at `now` and no independent `evidence_time < revoked_at` exists, verification **MUST** fail.

### 3.2 Manifest (`PQMailManifest`)

- Bodies: `15: text_plain` and `16: text_html` (UTF-8 strings).
- `17: parts[]`: inline resources use `disposition = 1`; attachments use `disposition = 2`. When referenced via HTML `cid:`, each `content_id` **MUST** be unique within the manifest. `data` is either an inline byte string or an `encrypted-blob-ref`. Clients **MUST** sanitize `text_html` against a strict allowlist before rendering and **MUST** block remote resource loading by default.
- At least one of `text_plain`, `text_html`, or `parts` **MUST** be present. `extra_headers` conveys supplemental metadata only and **MUST NOT** override core manifest fields or alter sender identity or recipient intent checks.

### 3.3 Blind Carbon Copy (`Bcc`) and Anti-Surreptitious Forwarding

- **Sending**:
  1. The primary envelope sent to `To`/`Cc` recipients **MUST** omit `Manifest.bcc`. When both `To` and `Cc` are empty, only Bcc envelopes are sent.
  2. Each Bcc recipient receives a separate message whose SMTP `RCPT TO` and envelope `recipients` array contain only that single recipient; outer `To`/`Cc` headers **MUST NOT** list Bcc addresses. Each Bcc copy **MUST** use a fresh random `msg_id`, an independent `MEK`, and a distinct outer `Message-ID`, set `Manifest.bcc` (key `7`) to that recipient's address, and retain the shared inner `rfc5322_message_id` to preserve threading.
- **Receiving** (let `self` be the local mailbox's canonical address):
  - When `Manifest.bcc` is present, the envelope **MUST** contain exactly one recipient entry and `self == Manifest.bcc.uri`. Before executing Reply-All on such a message, the client **MUST** display a secondary confirmation warning that replying to all will reveal the user's hidden Bcc status.
  - When `Manifest.bcc` is absent, inbound receipt **MUST** satisfy `self in Manifest.to U Manifest.cc` (reading one's own saved Sent copy **MAY** instead verify `self == Manifest.from.uri`).
  - If these conditions are violated, the client **MUST NOT** present the message as directly addressed to the user and **MUST** surface an explicit warning of possible re-encrypted / surreptitious forwarding.

### 3.4 Chunked Attachment Streams and Binary Ciphertext Merkle Root (`encrypted-blob-ref`)

Small resources (**SHOULD** be `<= 64 KiB`) are carried inline in `PQMailManifest.parts[]`; larger resources use `encrypted-blob-ref`:

- Generate an independent 16-byte random `stream_id` and 32-byte random `blob_key` per resource. `blob_key` **MUST NOT** appear in any URL. `chunk_size` **MUST** be a power of two in `[64 KiB, 4 MiB]` (default `1 MiB`).
- The chunk count `n = max(1, ceil(plaintext_size / chunk_size))` **MUST NOT** exceed `2^32`. Every chunk except the last has exactly `chunk_size` plaintext bytes (when `n > 1`, the final chunk has `1..chunk_size` plaintext bytes; a 0-byte empty stream is allowed only when `n == 1`). The concatenated ciphertext `ct_0 || ... || ct_{n-1}` has exact length `plaintext_size + 16 * n`, with chunk `i` at byte offset `i * (chunk_size + 16)`. Any length mismatch **MUST** be rejected.
- Per-chunk key, nonce, and AAD for 0-based `u32` chunk index `i`:
  ```text
  chunk_key          = HKDF-Expand-SHA256(blob_key, "pqmail/v1/chunk-key"   || stream_id, 32)
  chunk_nonce_prefix = HKDF-Expand-SHA256(blob_key, "pqmail/v1/chunk-nonce" || stream_id, 8)
  nonce_i = chunk_nonce_prefix || uint32_be(i)
  aad_i   = CanonicalCBOR(["pqmail/v1/chunk", aead_alg, stream_id, i, i == n - 1])
  ```
- **RFC 9162 Binary Ciphertext Merkle Root (`ciphertext_merkle_root`)**: Leaf hashes are `L_i = SHA-256(0x00 || ct_i)`. Internal nodes combine subtrees per [RFC 9162 §2.1](https://www.rfc-editor.org/rfc/rfc9162#section-2.1) by splitting at the largest power of two strictly less than the subtree leaf count: `SHA-256(0x01 || left || right)`. Because other recipients of the same message also know `blob_key`, full downloads **MUST** verify that the recomputed Merkle root equals `ciphertext_merkle_root`. Partial HTTPS `Range` fetches **MAY** verify individual chunks against `ciphertext_merkle_root` using an accompanying RFC 9162 inclusion proof without downloading the entire attachment.
- `mime_cid` identifies a unique sibling MIME part in the same message (without angle brackets; §5.2). `https_locators` **SHOULD** be used alone only when all intended recipients are known to support HTTPS retrieval; proxy fetchers **MUST** validate allowed destinations on every redirect hop and **MUST NOT** forward credentials cross-origin.

---

## 4. Public Key Discovery and Deadlock-Free Rollover

### 4.1 Key Bundle (`PQMailKeyBundle`)

Key bundles are verified under §2.4 with `external_aad = b"pqmail/v1/key-bundle"`. The self-signature **MUST** use a primary signing key listed inside the bundle that is currently valid (`valid_from <= now + MAX_CLOCK_SKEW` and not revoked), was valid at `issued_at`, and does not carry `restricted_to_extension`. `cwt-claims.iss == address` and `cwt-claims.iat == issued_at`. Every `kid` within a bundle **MUST** be unique; duplicates **MUST** be rejected.

- Real-time bundle acceptance or encryption **MUST** verify `issued_at <= now + MAX_CLOCK_SKEW` and `now < expires_at`; expired cached bundles **MUST** be refreshed before encrypting new mail.
- `encryption_keys`: lists active §2.2 HPKE public keys ordered by preference; senders encrypt to the first entry. Recipients may retain retired private keys locally to decrypt historical mail.
- `signing_keys`: one entry per device or delegated signing unit, with `valid_from` and optional `revoked_at` and `restricted_to_extension`. Revoked keys **SHOULD** be retained in the bundle for archival verification, and a signing key **MUST NOT** be repurposed for a different subject role.
- `prev_bundle_hash`: `SHA-256(previous_bundle_payload_bytes)`. Because `unprotected` headers are excluded from the payload hash, attaching or pruning directory proofs and rollover chains never invalidates `prev_bundle_hash`.

### 4.2 Progressive Discovery and DNS `_pqmail.<domain>` Policy

A domain **MAY** publish a DNS TXT record at `_pqmail.<domain>` (for example `v=pqmail1; policy=directory` or `v=pqmail1; policy=optional`) to declare its directory participation policy. Implementations **MUST** support HTTPS Directory discovery (Profile A). Profile 0 enables zero-infrastructure cold start for non-directory domains; pluggable cryptographic proofs (Profile B, Profile C, or other locally configured consensus state proofs) elevate the security tier to `pqmail_e2ee_verified`.

| Profile | Acquisition and Proof Requirements | Security Tier |
| --- | --- | --- |
| **0: In-Band Header** | Allowed only when no bundle is pinned yet AND DNS `_pqmail.<domain>` confirms **no record exists** (`NXDOMAIN`/`NODATA` — enabling cold start on webmail domains with cross-origin web redirects and MX-only enterprise domains lacking `:443`; DNS `SERVFAIL`/timeout **MUST NOT** allow Profile 0) OR explicitly declares `policy=optional` and Profile A returns same-origin `404`. If `_pqmail.<domain>` declares `policy=directory` (or mandatory proof verification is configured), in-band headers **MUST NOT** be accepted. The outer message **MUST** have a single-mailbox `From` header and a single `PQMail-Key` header (folded Base64), whose bundle address matches `From`, with DMARC pass and a passing DKIM signature whose `d=` matches the `From` domain and whose `h=` covers both `From` and `PQMail-Key` ([RFC 6376 §3.5](https://www.rfc-editor.org/rfc/rfc6376#section-3.5)). | `pqmail_e2ee_tofu` |
| **A: HTTPS Directory** | Probe `GET https://pqmail.<domain>/.well-known/pqmail/keys/<local_hash>` first (dedicated directory subdomain, enabling static apex sites and CNAME-delegated custom domains); fall back to `GET https://<domain>/.well-known/pqmail/keys/<local_hash>` **ONLY** if `pqmail.<domain>` does not resolve or cannot be reached (never fall back after an authoritative HTTP response such as `404` or `5xx`). Must return `application/pqmail-key-bundle+cose`; only same-origin redirects (within the queried host) are permitted; `404` indicates no published bundle for that address. | `pqmail_e2ee_tofu` |
| **[B: Key Transparency](https://github.com/ldclabs/ic-panda/blob/main/docs/protocol/pqmail-profile-b-v1.md)** | `pqmail-kt/1`: global 256-level bitmap-compressed sparse state tree anchored in a witness-cosigned RFC 9162 append-only epoch log. | `pqmail_e2ee_verified` |
| **[C: Certified State](https://github.com/ldclabs/ic-panda/blob/main/docs/protocol/pqmail-profile-c-v1.md) / Consensus Proof** | `pqmail-state/1` (configurable `t-of-n` validator quorum over a global sparse state tree) or another threshold/consensus state proof verified against a locally configured trust root. | `pqmail_e2ee_verified` |

Verifiers evaluate the unique matching entry in `unprotected[-65540]` according to local domain policy, binding the canonical address and `SHA-256(payload)`. `verifier_hint` never confers trust. Unrecognized or unconfigured proof types are ignored and cannot elevate the security tier. If a domain is configured to require a proof, any missing, duplicate, or invalid proof **MUST** block acceptance.

### 4.3 Deadlock-Free Rollover Chain (`rollover_chain`) and Pin Updates

To support both **single-device atomic key replacement** (where a new bundle self-signed by `K_2` retires the sole previous key `K_1` in one step) and **multi-version jumps** (where a contact caches `v1` while a static directory has advanced to `v3`), a key bundle **MAY** include up to 16 ordered `rollover-link` endorsements in `unprotected[-65541]`:

```text
rollover_msg = CanonicalCBOR([
  "pqmail/v1/bundle-rollover", address,
  prev_version, prev_payload_sha256,
  next_version, next_payload_sha256,
  next_signer_kid, endorsed_at
])
```

When a local `pin` already exists for a mailbox, validate the candidate bundle under §4.1 and apply the following rules in order:

1. **Anti-Rollback and Conflict Protection**: Reject and alert if `bundle.address` spelling changed, `bundle_version < pin.version`, the same `bundle_version` carries a different payload hash, or a pinned `stable_subject_uri` was modified or removed. Identical `(version, payload_hash)` refreshes the cache.
2. **No Downgrade of Verified Directory Pins**: If `pin` is already `pqmail_e2ee_verified`, the candidate bundle **MUST** also pass verified directory proof validation; once verified, accept the update. Directory outages, timeouts, or `404` responses **MUST NOT** clear an existing pin, downgrade trust, or trigger plaintext fallback.
3. **Chained TOFU Upgrades** (when no verified directory proof applies): Silently accept a higher-version bundle if either condition holds:
   - **Direct continuity**: `next.prev_bundle_hash == pin.hash` and the candidate's self-signing key is an unrestricted signing key in `pin` that is valid at `next.issued_at`.
   - **Single-hop or multi-hop `rollover_chain`**: `unprotected[-65541]` contains a contiguous sub-chain `L_0 .. L_{m-1}` where `L_0` matches `(pin.version, pin.hash)` and `L_0.prev_signer` is an unrestricted key in `pin` valid at `L_0.endorsed_at`; every hop satisfies `prev_version < next_version`, `endorsed_at <= now + MAX_CLOCK_SKEW`, and valid cryptographic signature over `rollover_msg`; each adjacent pair links `(next_version, next_payload_sha256, next_signer_kid)` identically to `(prev_version, prev_payload_sha256, kid(prev_signer))`; and the final hop points exactly to `(next.version, H(next.payload), next.owner.kid)`.

---

## 5. SMTP Delivery

### 5.1 Basic Structure (RFC 1847)

```text
From: Alice <alice@provider-a.example>
To: Bob <bob@provider-b.example>
Date: Fri, 04 Dec 2026 16:30:00 +0000
Message-ID: <019ae8f1-9c2a-7b4d-8f12-3c4d5e6f7a8b@provider-a.example>
MIME-Version: 1.0
Subject: ...
PQMail-Key: v=1; bundle=<standard Base64 of the key bundle, folded with continuation whitespace>
Content-Type: multipart/encrypted;
    protocol="application/pqmail-encrypted";
    boundary="pqmail-enc-7f3a"

--pqmail-enc-7f3a
Content-Type: application/pqmail-encrypted

Version: 1
--pqmail-enc-7f3a
Content-Type: application/octet-stream; name="envelope.pqm"
Content-Disposition: inline; filename="envelope.pqm"
Content-Transfer-Encoding: base64

<Base64-encoded PQMailEnvelope>
--pqmail-enc-7f3a--
```

- The outer `Subject` **MUST** be `...`, and outer headers **MUST NOT** contain `Bcc`, `In-Reply-To`, or `References`. Clients **MUST** display only decrypted and signature-verified manifest headers. If the outer `From` address differs from `Manifest.from.uri` under §2.1 comparison rules, the client **MUST** display a spoofing warning.
- When a single send includes recipients without PQMail/1 support, the client **MUST** split delivery into groups and obtain explicit sender confirmation before sending the unencrypted plaintext SMTP group.

### 5.2 Co-Located Encrypted Attachment Blobs (RFC 2387)

When `mime_cid` references are used, the top-level MIME container is `multipart/related` (RFC 2387) whose root part is the §5.1 `multipart/encrypted` structure and whose subsequent sibling parts hold the raw chunked attachment ciphertexts, enabling IMAP clients to inspect `BODYSTRUCTURE`, fetch only the root envelope first, and lazily `FETCH` attachment blobs on demand:

```text
Content-Type: multipart/related; type="multipart/encrypted"; boundary="pqmail-rel-91c2"

--pqmail-rel-91c2
Content-Type: multipart/encrypted;
    protocol="application/pqmail-encrypted";
    boundary="pqmail-enc-7f3a"

<Same two parts as Section 5.1>
--pqmail-rel-91c2
Content-Type: application/octet-stream
Content-ID: <blob-1.c84f@provider-a.example>
Content-Transfer-Encoding: base64

<Base64-encoded ct_0 || ... || ct_{n-1}>
--pqmail-rel-91c2--
```

---

## 6. Security Tiers, IANA Considerations, and Conformance Vectors

### 6.1 Security Tiers

Inbound messages first complete decryption, sender signature verification, and recipient intent checks, then inherit the verification provenance of the sender's key bundle. Outbound messages take the weakest tier across all recipient bundles actually used for encapsulation:

| Identifier | Criteria |
| --- | --- |
| `pqmail_e2ee_verified` | Every involved key bundle was verified by a locally implemented cryptographic directory proof anchored in a configured trust root (e.g., Profile B, Profile C, or threshold consensus state proof). |
| `pqmail_e2ee_tofu` | At least one key bundle was obtained via Profile 0 (in-band header) or Profile A without a verified directory proof. |
| `external_tls_pq` / `external_tls` / `external_plain` | Not end-to-end encrypted; server-side storage encryption at rest does not elevate this tier. |

### 6.2 IANA Considerations (Pending Registrations)

| Registry | Provisional Value(s) | Purpose |
| --- | --- | --- |
| Media Types | `application/pqmail-encrypted`, `application/pqmail+cbor`, `application/pqmail-manifest+cbor`, `application/pqmail-signed+cose`, `application/pqmail-key-bundle+cbor`, `application/pqmail-key-bundle+cose` | MIME control part, envelope, manifest, signed manifest, and key bundle |
| COSE Header Parameters | `-65540` (`trust_proofs`), `-65541` (`rollover_chain`) | Pluggable trust proofs and rollover chains in key bundle `unprotected` headers |
| COSE Algorithms | `-65550`; `-65551`, `-65552` | Composite signature (`MLDSA65-Ed25519-SHA512`); X-Wing and ML-KEM-1024 HPKE public keys |
| Message Headers / DNS / Well-Known | `PQMail-Key`, `_pqmail`, `pqmail.<domain>`, `/.well-known/pqmail` | Profile 0 bootstrapping, domain policy declaration, and Profile A directory |

### 6.3 Reproducible Conformance Test Vectors

[pqmail-v1.vectors.json](https://github.com/ldclabs/ic-panda/blob/main/tests/vectors/pqmail-v1/pqmail-v1.vectors.json) is deterministically generated from fixed seeds by `node scripts/gen-pqmail-vectors.mjs` (requiring OpenSSL 3.5+ CLI) and independently verified by the zero-dependency verifier `node scripts/verify-pqmail-vectors.mjs`:

| ID | Scenario | Expected |
| --- | --- | --- |
| `TV-01` | Strict RFC 3986 percent-encoding (including `+` -> `%2B`), UTF-8, quoting, and directory hashes | Byte-identical |
| `TV-02` | Misordered CBOR keys, non-minimal integers, trailing bytes; `AKP` key containing `-2` or `kid` | Reject |
| `TV-03` | Unknown non-critical headers and `ext-key >= 65536` manifest forward compatibility | Ignore & accept |
| `TV-04` | Unknown `crit` header; unimplemented `restricted_to_extension`; restricted key signing a key bundle | Reject |
| `TV-05` | ML-KEM coefficient `>= 3329`, or X-Wing trailing X25519 all-zero / small-order point | Reject |
| `TV-06` | Composite (`-65550`) and pure ML-DSA-65/87 (`-49`/`-50`) signatures on bundles and manifests | Pass |
| `TV-07` | Single-component signature tampering; cross-object `external_aad` substitution | Reject |
| `TV-08` | Heterogeneous HPKE recipients in one envelope; shared-key alias; both AEADs, `commitment`, and padding | Pass |
| `TV-09` | Recipient entry replay across address/`msg_id`; mismatched `commitment`; re-wrapped manifest; missing `0x80` pad | Reject |
| `TV-10` | Isolated Bcc envelope; surreptitious re-encrypted forwarding by `To` or `Bcc` recipient to third party | Pass / Reject |
| `TV-11` | Chunked AEAD and RFC 9162 binary ciphertext Merkle root (including odd-leaf promotion); reordering, truncation, extra empty chunk | Pass / Reject |
| `TV-12` | RFC 1847 two-part MIME; RFC 2387 sibling attachment CID matching; outer `From` spoofing detection | Pass / Reject / Warn |
| `TV-13` | DNS `_pqmail` Profile 0 admission and `policy=directory` downgrade prevention; single-device rollover and `v1 -> v3` multi-hop chain; `300s` clock skew and RFC 9921 LTV archival verification after bundle expiry | Per §3.1, §4 |

Replacing `{{envelope}}` and `{{blob}}` in `related_bcc_template` with `bcc_message.envelope_cbor_b64` and `chunk_stream.ciphertext_b64` (wrapped at 76-character CRLF lines) yields a complete RFC 2387 MIME message with a co-located encrypted attachment.
