Specs: Protocol requirements. Load only for protocol or implementation work. # Backend API contract The gRPC contract every client depends on: what a caller sends, what it gets back, and what the backend guarantees about order, atomicity, and failure. A client publishes envelopes, reads them back by topic and position, and streams them as they arrive. Every promise here survives a reimplementation of the backend, because a client written against it has no other way to tell one backend from another. ```mermaid flowchart LR C[The client] -->|Publish| P[Admission and atomic store] P -->|EnvelopeMeta| C P --> S[(Envelopes by topic
and sequence id)] S -->|Query, QueryNewest| C S -->|Subscribe, SubscribeStatic| C C -->|GetInboxIds,
VerifySmartContractWalletSignatures| I[Identity reads] ``` ## Scope In scope: sequence ids, ordering, and visibility; the envelope wire format and the metadata the backend assigns; publish atomicity, idempotency, and admission, including what admission establishes and what it does not, and the checks of a handle claim that only the backend applies; query and paging; the subscribe frame contracts; identity lookups, by identifier and by handle; connection statistics; request bounds; the status codes; and the transport. Out of scope: credentials and which requests need one ([AUTH section 1](/specs/auth-backend-auth/#1-admission)); the values of the published limits and how a client sizes its requests to them (`CONF`); the topic layout (`TOPIC`); push registration and delivery ([PUSH](/specs/push-push-subscriptions/)); retention enforcement, readiness, and health ([OPS](/specs/ops-backend-operations/)); the association log an identity update is checked against (IDENT-004, IDENT-095); the handle grammar, how a claim changes the association state, and the client’s check of a handle lookup ([IDENT section 10](/specs/ident-identity-updates/#10-handles), IDENT-085); the MLS objects a key package and a Welcome carry (`JOIN`); the commit-log entry ([FORK section 2](/specs/fork-fork-recovery/#2-keys-and-signatures)); and what a client does with a frame once received, including its positions on a topic ([PROC](/specs/proc-message-processing/)); per-caller rate limits and their charges ([RATE](/specs/rate-backend-rate-limits/)). | Related | Relation | | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TOPIC` | Owns the kind bytes, the identifier lengths, and the rejection of a malformed topic. This spec references it wherever a request names or an envelope carries a topic. | | `CONF` | Owns every published limit, the minimum name length of a handle, and the rule that a published value is the enforced value (CONF-069). This spec owns what the backend does when a request exceeds one. | | [IDENT](/specs/ident-identity-updates/) | Owns the identity update and the validation the backend runs at admission (IDENT-095), and handles: the grammar, the claim, and how a claim changes the association state ([IDENT section 10](/specs/ident-identity-updates/#10-handles)). This spec owns the claim checks that only the backend applies and the handle lookup. | | `JOIN` | Owns the key package validation the backend runs at admission (JOIN-007, JOIN-008, JOIN-082, JOIN-090), and the sequence id promises a join relies on. | | [PROC](/specs/proc-message-processing/) | Owns durable receipt and processing positions (PROC-002, PROC-005) and stream recovery (PROC-021). | | [SEND](/specs/send-message-sending/) | Owns the client’s retry of a prepared publish (SEND-007). | ## Terms | Term | Meaning | | -------------------------- | ----------------------------------------------------------------------------------------------------------- | | Read | A `Query`, `QueryNewest`, `Subscribe`, or `SubscribeStatic` request. | | Visible | The state of a stored envelope that a read can return. | | Duplicate | An envelope whose topic and `message_hash` equal a stored envelope’s. | | Registration | One topic added to a stream, with the cursor it starts after and the catch-up target it was given. | | Catch-up target | The `CatchupTarget.through_sequence_id` a registration receives, captured under API-252. | | Frame | One message of a stream response. | | Transport ceiling | The largest encoded request or response the transport carries, stated by API-282. | | Wire length | The number of bytes of a request as the client encoded it, which the transport measures. | | Re-encoded length | The number of bytes of the backend’s own encoding of a decoded request (API-211), which admission measures. | | Closed allocation boundary | The sequence id API-203 maintains, at or below which every publish has finished. | ## 1. Sequence ids, order, and visibility The backend assigns every stored envelope a sequence id that is unique across all topics. Once an envelope is visible, each later publish receives a greater sequence id. Sequence ids on one topic need not be contiguous: other topics and failed publishes can leave gaps. Order matters only within a topic. A read of a topic returns a prefix of that topic’s order: no envelope becomes visible on a topic while a lower sequence id on the same topic is still being stored, and no later publish enters behind one already visible. Across topics the backend promises nothing: an envelope with a higher sequence id on one topic can be visible while a lower one on another topic is not yet. A deployment may answer some reads from a lagging copy of its store. `QueryNewest`, a stream’s catch-up target, and `GetInboxIds` can therefore answer from an earlier point in time than a publish response the client already holds; each still returns a prefix of every topic. Only `Query` is promised to read the client’s own writes (API-202). PROC-021 defines when a client uses `Query` to reach a target, including a target from its own publish receipt. A sequence id can be allocated to a publish that then fails, so at any moment some ids below the newest are neither visible nor ever will be, and others belong to publishes still in progress. The closed allocation boundary separates the two: at or below it, every publish has finished. The push dispatcher reads only up to the boundary under PUSH-257; a stream holds a gap open until the boundary passes it. The boundary only rises (API-291); a subscription start read from it under PUSH-216 stays final. | ID | Title | Requirement | Why | | ------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- | | API-286 | Sequence id range | The backend MUST assign every stored envelope a sequence id from 1 through 9223372036854775807 inclusive. | | | API-287 | Sequence ids are globally unique | The backend MUST NOT assign the same sequence id to two different envelopes, including envelopes on different topics. | A join anchor and an identity reference compare sequence ids across topics (JOIN-037, JOIN-050). | | API-288 | Sequence ids do not change | Once the backend assigns an envelope a sequence id, it MUST return that same sequence id for the envelope in every publish response and read. | A changed sequence id invalidates stored cursors and references. | | API-289 | Later publishes have greater ids | When a publish arrives after an envelope became visible, the backend MUST assign each new envelope in that publish a sequence id greater than the visible envelope’s sequence id, regardless of topic. | A later publish behind a stored cursor is never read by a client that resumes from that cursor. | | API-201 | A read returns a prefix | The backend MUST NOT make an envelope visible on a topic while an envelope with a higher sequence id on that topic is already visible, and MUST return the envelopes of one topic in ascending sequence id from every read, including a read answered from a lagging copy of the store. | A client advances its cursor past what it received; an envelope that appears later behind that cursor is lost to it for ever. | | API-202 | Query reads its own writes | When a `Query` request arrives after the backend sent the publish response that stored an envelope on a topic `Query` accepts (API-243), the response MUST include that envelope if its sequence id is greater than the cursor supplied for its topic and the effective limit (API-241) does not cut it under API-240. | A client that published a commit confirms it by reading the topic; a read that cannot see the client’s own publish never confirms. | | API-203 | The closed allocation boundary | The backend MUST maintain a closed allocation boundary: a sequence id at or below which every publish has committed or will never commit. Every envelope stored with a sequence id at or below the boundary MUST be visible to every read, and the backend MUST NOT later store an envelope with a sequence id at or below it. | A reader that takes the boundary as “nothing below here is still coming” skips an envelope for ever if one lands behind it. | | API-291 | The boundary never decreases | The backend MUST NOT compute a closed allocation boundary lower than one it computed before, including one it computed before a restart. | A subscription stored against a later, lower boundary under PUSH-216 is woken for envelopes its client had already read when it subscribed. | ## 2. The envelope A client publishes a `ClientEnvelope`. The backend decodes it, encodes the decoded message again with its own encoder, stores those bytes, and returns them inside a `ServerEnvelope` with the metadata it assigned. The payload byte fields, which carry MLS objects and signed structures, are returned byte for byte; only the protobuf framing around them is re-encoded, so the stored length can differ from the wire length. The message hash is computed over the stored bytes, so it is a stable identity for the same input and an opaque value to the client: a hash a client computes over its own encoding need not match. PROC-001 governs client validation and preservation of that hash. ```proto // Position on one topic. `sequence_id` 0 means "from the beginning". message Cursor { uint64 sequence_id = 1; } // One kind byte followed by an identifier; the layout is TOPIC-001. message Topic { bytes topic = 1; } // Idempotency key, unique with the topic. message MessageHash { oneof hash { bytes sha256 = 1; } } // Server-assigned metadata for one stored envelope. message EnvelopeMeta { Cursor cursor = 1; uint64 server_ns = 2; MessageHash message_hash = 3; Topic topic = 4; uint64 expiry_ns = 5; bool is_commit_or_proposal = 6; } message GroupMessage { // Serialized MlsProtocolMessage. bytes data = 1; bytes sender_hmac = 2; bool should_push = 3; // 64-byte Ed25519 signature [R(32) || S(32)] over GroupMessageTBS by the // group signing key. bytes signature = 4; } // A commit-log entry, encrypted and signed under keys derived from the // group root. message SealedCommitLogEntry { // 32-byte public key of the commit-log signing key. Derives the topic. bytes commit_log_id = 1; // 12 bytes. bytes nonce = 2; // ChaCha20-Poly1305 encryption of a serialized PlaintextCommitLogEntry. bytes ciphertext = 3; // 64-byte Ed25519 signature [R(32) || S(32)] over CommitLogEntryTBS by // the commit-log signing key. bytes signature = 4; } // What a client publishes. WelcomeMessage and KeyPackage are defined in JOIN. message ClientEnvelope { oneof payload { GroupMessage group_message = 1; WelcomeMessage welcome_message = 2; KeyPackage key_package = 3; xmtp.identity.associations.IdentityUpdate identity_update = 4; SealedCommitLogEntry sealed_commit_log_entry = 6; } // The retired CommitLogEntry payload. reserved 5; reserved "commit_log_entry"; } // A stored envelope with its server-assigned metadata. message ServerEnvelope { EnvelopeMeta meta = 1; ClientEnvelope envelope = 2; } ``` Every field of `EnvelopeMeta` is set by the backend. The table below says how, and API-212 makes it binding. `expiry_ns` is the retention bound; its value per kind, and what the backend does when it passes, are owned by OPS (OPS-001, OPS-002). | Field | Value | | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `cursor.sequence_id` | The envelope’s sequence id under API-286 through API-289. | | `server_ns` | The backend’s clock in nanoseconds since the Unix epoch, read once in the transaction that stores the request, after admission; every envelope one publish stores carries the same value. | | `message_hash.sha256` | The SHA-256 of the stored bytes under API-211. | | `topic.topic` | The topic under TOPIC-001. | | `expiry_ns` | The value OPS-001 gives for the envelope’s kind. | | `is_commit_or_proposal` | `true` when the payload is a group message whose `content_type` ([RFC 9420 §6](https://www.rfc-editor.org/rfc/rfc9420.html#section-6)) is `commit` or `proposal`; `false` for every other envelope. | | ID | Title | Requirement | Why | | ------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | API-210 | Wire format | The backend MUST accept and return every message defined in a `proto` block of this spec with the field numbers, types, and presence shown, and MUST NOT reuse a field number of any of them for another meaning. | | | API-211 | Stored bytes and hash | The backend MUST store the bytes its own encoder produces for the decoded `ClientEnvelope`, MUST return every `bytes` field of the payload exactly as received, and MUST set `message_hash.sha256` to the SHA-256 of the stored bytes, so that two `ClientEnvelope` messages that decode to the same value yield the same hash. | The payload fields carry signatures and ciphertext that a changed byte invalidates. The hash is the idempotency key, so it has to be the same on a retry. | | API-212 | Metadata is assigned by the backend | The backend MUST set every field of `EnvelopeMeta` on every envelope it returns to the value the table above gives. | A client-chosen `is_commit_or_proposal` would exempt spam from retention; a client-chosen `server_ns` would reorder a conversation on every other member’s screen. | ## 3. Publish A publish is one atomic request: every envelope in it is stored, or none is. Its idempotency key is the topic and the message hash, so a client that did not receive a response retries the same bytes and gets the stored metadata back, whether the first attempt committed or not. Storage and the response are separate steps: a publish can commit and then fail on the way back, when its response is longer than the transport carries or the connection drops, so a failed response is not proof that nothing was stored (API-224). After `OUT_OF_RANGE`, which API-284 forbids the client to retry unchanged, a `Query` of the topic is the recovery read: it settles each envelope as committed with its receipt or as not stored (API-290). SEND-007 owns retries and SEND-008 owns publish receipts; SEND-011 distinguishes publication from confirmed send success. A duplicate is accepted on its stored identity. The checks that depend on time or on state, a key package’s lifetime, an identity update’s history, or the checks of a handle claim, are not run again for it, so a retry of an envelope that was valid when stored succeeds after the moment it would have been rejected as new. What is still checked for a duplicate is what admission must do to recognise it: the envelope parses and the request is within its bounds. ```proto message PublishRequest { repeated ClientEnvelope envelopes = 1; } // Same order as the request, including duplicates. message PublishResponse { repeated EnvelopeMeta envelope_metas = 1; } // Attached as a google.rpc.Status detail on a publish INVALID_ARGUMENT. message PublishError { enum Reason { REASON_UNSPECIFIED = 0; REASON_MALFORMED_PAYLOAD = 1; REASON_INVALID_KEY_PACKAGE = 2; REASON_INVALID_IDENTITY_UPDATE = 3; REASON_INVALID_SIGNATURE = 4; REASON_TOO_LARGE = 5; REASON_HANDLE_TAKEN = 6; REASON_HANDLE_NOT_ALLOWED = 7; REASON_HANDLE_TOO_SOON = 8; REASON_INSTALLATION_TAKEN = 9; } // Index of the failing envelope in the request. Absent for request-level // errors. optional uint32 index = 1; Reason reason = 2; string message = 3; } ``` | ID | Title | Requirement | Why | | ------- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | API-220 | A publish is atomic | The backend MUST store every envelope of a publish request that is not a duplicate in one transaction that commits all of them or none of them, and MUST NOT answer with success unless that transaction committed. | A commit and the Welcomes it produces travel in one request. Storing one without the other forks the group for the members it left out. | | API-224 | A failed response proves no rollback | When a publish request has committed, the backend MUST answer a later request carrying the same envelopes under API-222 whether or not the first response reached the client. When a publish returns a status other than `INVALID_ARGUMENT` or `ABORTED`, the client MUST NOT publish a different envelope for the same message until a retry of the same bytes or a `Query` of the topic has returned that message’s outcome. | A response can be lost after the commit. A client that re-encrypts on the strength of the lost response publishes the same message twice, and every member sees both. | | API-290 | Recovery after `OUT_OF_RANGE` | When a publish has returned `OUT_OF_RANGE`, the backend MUST return each envelope of that request that committed, with the sequence id and `message_hash` the publish assigned, from a `Query` of its topic that arrives after that status, under API-202. An envelope of that request that such a `Query` does not return MUST NOT have been stored by that publish. | A client may not resend the request unchanged (API-284), so without a read that settles each envelope it can only re-encrypt, and every member then sees the message twice. | | API-221 | One entry per envelope, in order | The backend MUST answer a publish with one `EnvelopeMeta` for each envelope in the request, at the same index, including an envelope that is a duplicate of another in the same request. | | | API-222 | Publishing Is Idempotent | When an envelope is a duplicate, whether of an envelope stored by an earlier request, by a request in progress at the same time, or by an earlier index of the same request, the backend MUST NOT store it again, MUST return the stored envelope’s `EnvelopeMeta` for it as success, and MUST NOT apply to it any check of the admission table beyond parsing under API-230. The bounds table (section 7) MUST still apply to the request. | A retry after a lost response would otherwise store a second copy or fail, and a client cannot tell either from a first attempt. A key package retried after its lifetime would be rejected for a copy the backend already serves. | | API-223 | Failure names the envelope | When the backend fails a publish with `INVALID_ARGUMENT`, the status MUST carry a `PublishError` detail whose `reason` is the value the admission table names for the failure, or `REASON_TOO_LARGE` for a bound in the bounds table (section 7), and whose `index` is absent when the whole request exceeded a bound. Otherwise, when an envelope exceeds a bound of the bounds table, fails its parse under API-230, or is the later of two identity updates API-233 forbids, the backend MUST fail the request before any charge of RATE section 2 other than the `request` charge and before any other check of the admission table, with `index` the lowest request index among those envelopes. Otherwise `index` MUST be the lowest request index of an envelope that fails a check of the admission table. | A client with no index can only drop the whole batch; with one it drops the bad envelope and resends the rest. | ### 3.1 Admission The backend parses every envelope to derive its topic and metadata. It validates a key package and an identity update against what it holds. It verifies the publish signature on a group message and on a sealed commit-log entry, under the public key that is the topic’s identifier. Nothing else is checked. The backend holds no group secret, so a signed envelope is stored on the strength of its signature alone: whoever holds the private key of the topic’s identifier signed it, which for an existing group’s topics is an installation that holds the group root. What acceptance does not establish is listed so that no client reads a stored envelope as more than it is. The identity update is validated against the complete history of the inbox, read once from the store that publishes commit, so an update that depends on one the client has just had confirmed is validated against it. If that history grows between the read and the store, the validation may have passed against a state that no longer exists, so the request is aborted and the client starts over from the new history. IDENT-095 owns the association validation required at admission, including the signature rules in [IDENT section 4](/specs/ident-identity-updates/#4-signature-kinds). An identity update that claims a handle passes three more checks, which need state or policy that only the backend holds: no other inbox on the deployment has claimed the handle (API-296), the name part is allowed (API-297), and the inbox’s previous claim is at least 7 days old (API-298). The backend applies them only when it admits a claim. No validator applies them to a stored log (IDENT-084), so a change of policy never stops a stored log from applying, and a handle claimed before the change stays valid. The reserved list is a set of name parts, such as `admin` and `support`, that the backend defines and does not publish; a later release can change it. A switch back to a handle that the inbox already holds is a claim like any other and passes the same checks, so an inbox can select only a handle that is valid under the current policy; the old handle still resolves to the inbox and still shows in its handles. CONF-069 publishes the deployment’s minimum name length as `HandlesConfiguration.min_name_length` and makes the published value the value the backend applies. An identity update that adds an installation passes one more check that only the backend can make: no other inbox on the deployment has added that installation (API-305), even if that inbox has since revoked it. No validator applies it to a stored log (IDENT section 8). A key package is validated by the MLS rules, with the rule of the MLS extensions draft that JOIN-082 states and the checks of the two XMTP extensions that JOIN-090 states, and nothing more. Four properties a stricter validator might check are accepted on purpose, because the installations on the network today publish packages that have them, and a backend that started rejecting them would cut those installations off from every group (API-235). A publish signature is an Ed25519 signature ([RFC 8032 §5.1.6](https://www.rfc-editor.org/rfc/rfc8032#section-5.1.6)) over the TLS encoding ([RFC 9420 §2.1.2](https://www.rfc-editor.org/rfc/rfc9420.html#section-2.1.2)) of one of the structures below, under the key that GMOD-041 names for it. The label separates the two uses. ```tls struct { opaque label; // ASCII "xmtp group message" opaque topic; // 0x00 followed by the 32-byte group id opaque data; // GroupMessage.data opaque sender_hmac; // GroupMessage.sender_hmac uint8 should_push; // 1 when GroupMessage.should_push is true, otherwise 0 } GroupMessageTBS; struct { opaque label; // ASCII "xmtp commit log entry" opaque topic; // 0x04 followed by the 32-byte commit-log id: // commit_log_id at admission, the // conversation's own at a reader (FORK-077) opaque nonce; // SealedCommitLogEntry.nonce opaque ciphertext; // SealedCommitLogEntry.ciphertext } CommitLogEntryTBS; ``` | Kind | Parsed as | Also checked | Reason on failure | Not established | | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | Group message | `GroupMessage.data` as an `MLSMessage` whose body is a `PublicMessage` or `PrivateMessage` ([RFC 9420 §6](https://www.rfc-editor.org/rfc/rfc9420.html#section-6)); bytes after the message are accepted and stored; `signature` of 64 bytes | `signature` passes API-300 over `GroupMessageTBS` under the group id | `REASON_MALFORMED_PAYLOAD` when it does not parse or TOPIC-002 rejects it, `REASON_INVALID_SIGNATURE` when API-300 fails | That the signer is a current member, that the MLS signature verifies, that the epoch is current, or that any member can decrypt it | | Welcome | `WelcomeMessage` with `version` set | Nothing | `REASON_MALFORMED_PAYLOAD` | That `installation_key` names a registered installation, or that the recipient can decrypt it | | Key package | `KeyPackage.key_package_tls_serialized` as a `KeyPackage` ([RFC 9420 §10](https://www.rfc-editor.org/rfc/rfc9420.html#section-10)), consuming every byte | JOIN-007, JOIN-008, JOIN-082, JOIN-090, and that the credential decodes under JOIN-004 | `REASON_MALFORMED_PAYLOAD` when it does not parse or TOPIC-002 rejects it, `REASON_INVALID_KEY_PACKAGE` otherwise | That the inbox the credential names exists or associates the leaf node’s `signature_key`; the four properties API-235 names | | Identity update | `IdentityUpdate` with `inbox_id` accepted by TOPIC-002 | IDENT-095: signature verification and application to the association state built from every envelope on the inbox’s identity topic; for an update that carries a `ClaimHandle`, also API-296, API-297, and API-298; for an update that adds an installation, also API-305 | `REASON_MALFORMED_PAYLOAD` when TOPIC-002 rejects it, `REASON_INVALID_SIGNATURE` when a signature does not verify, the reason API-296, API-297, API-298, or API-305 names when that check fails, `REASON_INVALID_IDENTITY_UPDATE` otherwise | That the caller is authorized to act for the inbox | | Commit-log entry | `SealedCommitLogEntry` with `commit_log_id` of 32 bytes, `nonce` of 12 bytes, `ciphertext` of at least 16 bytes, and `signature` of 64 bytes | `signature` passes API-300 over `CommitLogEntryTBS` under `commit_log_id` | `REASON_MALFORMED_PAYLOAD` when it does not parse, `REASON_INVALID_SIGNATURE` when API-300 fails | That `ciphertext` decrypts, which conversation it belongs to, that the epoch continues the previous entry, or that the hash chain holds | | ID | Title | Requirement | Why | | ------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | API-230 | Admission by kind | The backend MUST parse each envelope as the admission table above states for its kind, apply the checks the table names, and fail the request with the reason the table names when a parse or a check fails; an envelope whose `payload` is unset, or that TOPIC-002 rejects, fails with `REASON_MALFORMED_PAYLOAD`. The backend MUST NOT apply a check the table does not name and MUST NOT reject an envelope for a property the table lists as not established. | Every client on the network parses what the backend stored. A stored envelope that no client can parse blocks a topic; a rejection for a property the backend cannot judge blocks a valid one. | | API-300 | Publish signatures | When a validator verifies a publish signature under a 32-byte public key, it MUST accept it only when the public key and the signature’s `R` are each the canonical encoding ([RFC 8032 §5.1.2](https://www.rfc-editor.org/rfc/rfc8032#section-5.1.2)) of a curve point that is not of small order, the signature’s `S` is less than the group order L, and `[S]B = R + [k mod L]A` holds. Here B is the base point, A is the public key, and k is the integer that [RFC 8032 §5.1.7](https://www.rfc-editor.org/rfc/rfc8032#section-5.1.7) computes from the SHA-512 hash of `R`, the public key, and the message. This is the §5.1.7 equation without the cofactor and with k reduced modulo L. | A backend and a reader that accept different signatures disagree about what a topic holds, a small-order key lets anyone produce a signature that verifies, and a second encoding of one key names a second topic. | | API-235 | Accepted key package shapes | The backend MUST NOT reject a key package that passes JOIN-007, JOIN-008, JOIN-082 and JOIN-090 because its credential’s `inbox_id` is not 64 hexadecimal characters, because its `cipher_suite` is a suite other than the one JOIN-072 names whose signature scheme yields a 32-byte `signature_key`, because its leaf node `Capabilities` omit an extension or proposal type, or because its `Lifetime` is longer than any bound. | Installations already on the network publish packages with each of these shapes. A backend that rejects one makes those installations unaddable everywhere at once. | | API-231 | A verifier failure is not a verdict | If a smart contract wallet signature cannot be verified because the chain RPC or the verifier fails, rather than because the signature is invalid, then the backend MUST fail the request with `UNAVAILABLE` and MUST NOT report the signature as invalid. | An `INVALID_ARGUMENT` is never retried, so a transient outage would turn a valid identity update into a permanent rejection. | | API-303 | One history, or start over | When an identity update that is not a duplicate passes the checks API-302 names, the backend MUST validate it against every envelope on the inbox’s identity topic, including every one a publish response has confirmed, read in one snapshot; if at commit the highest sequence id on that topic is not the highest in that snapshot, or 0 when the snapshot was empty, then it MUST fail the request with `ABORTED` and store nothing. | An update validated against a history that has since grown can conflict with the update that grew it, and two conflicting updates in one log make the inbox’s state undefined. | | API-233 | One update per inbox per request | When a request carries two identity updates for one inbox that are not duplicates of each other, the backend MUST fail the request with `REASON_INVALID_IDENTITY_UPDATE`. | The second cannot be validated against a history that includes the first until the first is stored. | | API-234 | The association log is bounded | When an identity update that is not a duplicate names an inbox whose identity topic already holds `max_identity_entries` (CONF-069) envelopes, the backend MUST fail the request with `REASON_INVALID_IDENTITY_UPDATE`. | Every validator replays the whole log. An unbounded log is a cost imposed on every party that ever resolves the inbox. | | API-302 | Cheap identity rejections first | When an identity update that is not a duplicate (API-222) has empty `actions`, fails IDENT-079 or IDENT-094, carries an `erc_6492` signature longer than IDENT-093 allows, or carries more ERC-6492 signatures than `max_scw_signatures`, the backend MUST fail the request without reading the inbox’s identity topic. | A rejection that first reads and replays the inbox’s log lets anyone who can publish make the backend repeat work in proportion to that log, with an update that needs no signature. | | API-296 | One inbox per handle | When an identity update carries a `ClaimHandle`, and the identity topic of another inbox holds an envelope whose update carries a `ClaimHandle` with the same `handle`, or an identity update for another inbox at a lower index of the same request carries a `ClaimHandle` with the same `handle`, the backend MUST fail the request with `REASON_HANDLE_TAKEN`. The backend MUST NOT store claims of one `handle` on the identity topics of two inboxes, including claims from two requests in progress at the same time. | A user who enters the handle reaches whichever of the two inboxes a lookup returns, and the client’s check (IDENT-085) accepts either. | | API-297 | Reserved and short names refused | When an identity update carries a `ClaimHandle` whose name part is on the backend’s reserved list or has fewer characters than `HandlesConfiguration.min_name_length` (CONF-069), the backend MUST fail the request with `REASON_HANDLE_NOT_ALLOWED`, including when the inbox’s association state already holds that handle. | An inbox that claims `admin` can pose as the operator to every user who looks the name up, and a deployment holds names shorter than its operator allows. | | API-298 | Seven days between claims | When an identity update carries a `ClaimHandle` and the inbox’s identity topic holds an envelope whose update carries a `ClaimHandle` and whose `server_ns` is greater than the backend’s clock at admission minus 604800000000000 nanoseconds (7 days), the backend MUST fail the request with `REASON_HANDLE_TOO_SOON`. | Each claim makes a membership commit in every group of the inbox (GMOD-029), and claims with no pause spend an inbox’s 64 claims (IDENT-080) in minutes. | | API-305 | One inbox per installation | When an identity update carries an `AddAssociation` whose new member is an installation, and the identity topic of another inbox holds an envelope whose update adds that installation as a member, or an identity update for another inbox at a lower index of the same request adds it, the backend MUST fail the request with `REASON_INSTALLATION_TAKEN`. The backend MUST NOT store additions of one installation on the identity topics of two inboxes, including additions from two requests in progress at the same time. | A key that two member inboxes hold has one leaf in a group, so when either inbox revokes it, the commit that removes the leaf leaves the key unaccounted for the other inbox, and no member of the group can send. | ## 4. Query `Query` accepts topics, a cursor for each topic, and a total result limit. Its response contains envelopes after those cursors, in ascending sequence-id order within each topic, and `has_more` indicates whether another page is available. It does not omit an eligible envelope below another returned envelope on the same topic. `QueryNewest` returns the envelope with the greatest sequence id, or only its metadata, for each requested topic that has an envelope. Results identify their topics; a topic with no envelope has no result. Key package topics are accepted only by `QueryNewest`. To request the next page, a client advances each topic’s cursor under PROC-002 and repeats the query while `has_more` is true. ```proto // One topic and the position to read from. message TopicQuery { Topic topic = 1; // Return envelopes with sequence_id > cursor. Absent = 0. Cursor cursor = 2; } message QueryRequest { repeated TopicQuery queries = 1; // Total across all topics. uint32 limit = 2; } message QueryResponse { repeated ServerEnvelope envelopes = 1; Continuation continuation = 2; } message Continuation { bool has_more = 1; } message QueryNewestRequest { repeated Topic topics = 1; bool include_full_envelope = 2; } message QueryNewestResponse { message Result { Topic topic = 1; EnvelopeMeta meta = 2; // Set only when `include_full_envelope` was true. ClientEnvelope envelope = 3; } repeated Result results = 1; } ``` | ID | Title | Requirement | Why | | ------- | ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | API-240 | A page above the cursors | The backend MUST answer `Query` with envelopes whose sequence id is greater than the cursor supplied for their topic, at most the effective limit (API-241) in total, each stored envelope at most once, and for every topic the page includes, the envelopes with the lowest eligible sequence ids on that topic with none omitted between them. When any envelope is eligible the page MUST contain at least one, and `has_more` MUST be whether more envelopes were eligible than the effective limit allowed, computed from the same read as the page. | A page that leaves out an envelope below one it returns loses that envelope to a client that moves its cursor forward, and a page cut short with `has_more` false is history a client never asks for again. | | API-241 | Limit default and ceiling | When `QueryRequest.limit` is 0, the backend MUST page by `default_query_limit`; when it is greater than `max_query_limit`, the backend MUST page by `max_query_limit` (CONF-069). | | | API-242 | Repeated topics read from the lowest cursor | When `QueryRequest.queries` names one topic more than once, the backend MUST read that topic from the lowest cursor supplied for it. | Reading from a higher one skips the range another entry asked for. | | API-243 | No paging on key package topics | When a `Query` names a topic whose kind is key package under TOPIC-001, the backend MUST fail the request with `INVALID_ARGUMENT`. | | | API-244 | The newest envelope per topic | The backend MUST answer `QueryNewest` with one `Result` for each distinct requested topic that has a visible envelope, carrying the `EnvelopeMeta` of the envelope with the highest sequence id on that topic, and the `envelope` only when `include_full_envelope` is true; a topic with no visible envelope MUST be absent from `results`. | A sender picks an installation’s key package by this read. A result for an older package addresses a Welcome to keys the installation may have destroyed (JOIN-074). | | API-245 | Results match by topic | When the client reads a `QueryNewestResponse`, it MUST take each `Result` for the topic its `topic` field names and MUST NOT pair results with requested topics by position. When a `KeyPackage` result’s leaf node `signature_key` is not the installation key its topic names, the client MUST treat that installation as having no key package. | A topic left out of `results` shifts every later position, so a client pairing by position reads one installation’s key package as another’s and addresses a Welcome to the wrong installation. The topic is the backend’s claim; the leaf key is signed, so only the leaf proves which installation a package belongs to. | ## 5. Subscribe A stream delivers, for each registered topic, every visible envelope above the registration’s cursor, in sequence id order, first the history and then new publications as they arrive, with no frame that distinguishes the two. A `Subscribe` stream is bidirectional: the client adds and removes topics while it runs, each update is acknowledged with the catch-up targets of the topics it added, and either side proves the other is alive with `Ping` and `Pong`. A `SubscribeStatic` stream takes its whole topic set from the request, for a client that cannot send on an open stream, and receives one-way `Keepalive` frames instead. The catch-up target is the head of the topic, read once after the topic is registered so that no publish can land between the two. It tells the client how far history runs; the client decides for itself when it has processed that far, because the backend cannot see processing. A target of 0 means the topic was empty. Catch-up is shared fairly: while several registrations still have history to deliver, none of them waits on another’s, so a client that adds many topics sees all of them advance. PROC-016 owns client catch-up completion; PROC-021 owns recovery from durable receipt positions. ```proto // Fixed catch-up boundary for one newly registered topic. message CatchupTarget { Topic topic = 1; // Observed head in the serving database. Zero means empty. uint64 through_sequence_id = 2; } message SubscribeRequest { message Update { // Nonzero and strictly increasing within this connection. uint64 id = 1; repeated TopicQuery adds = 2; repeated Topic removes = 3; } oneof request { Update update = 1; Ping ping = 2; Pong pong = 3; } } message SubscribeResponse { message Started { uint32 keepalive_interval_ms = 1; } message Applied { uint64 id = 1; // Newly registered topics only, in add order. repeated CatchupTarget added_targets = 2; } message Messages { repeated ServerEnvelope envelopes = 1; } oneof response { Started started = 1; Applied applied = 2; Messages messages = 3; Ping ping = 4; Pong pong = 5; } } message Ping { uint64 nonce = 1; } message Pong { // Echoes the Ping nonce. uint64 nonce = 1; } message SubscribeStaticRequest { repeated TopicQuery topics = 1; } message SubscribeStaticResponse { message Started { uint32 keepalive_interval_ms = 1; // One per requested topic, in request order, including empty topics. repeated CatchupTarget targets = 2; } message Messages { repeated ServerEnvelope envelopes = 1; } // One-way liveness signal. No reply is expected. message Keepalive {} oneof response { Started started = 1; Messages messages = 2; Keepalive keepalive = 3; } } ``` A frame of `Messages` can carry envelopes of more than one topic, and the order across topics inside a frame carries no meaning. A client that stops reading is closed rather than throttled: the backend holds a bounded amount of output for each stream and, when live traffic cannot be queued, fails the stream with `RESOURCE_EXHAUSTED` so that one slow client cannot hold up every other. The stream’s closing status tells the client what to do next: reconnect after `UNAVAILABLE`, `RESOURCE_EXHAUSTED`, or `DEADLINE_EXCEEDED`, no sooner than the delay a rate-limit rejection carries (RATE-041), and fix the request after `INVALID_ARGUMENT`. | ID | Title | Requirement | Why | | ------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | API-250 | Started comes first | The backend MUST send `Started` as the first frame of a `Subscribe` stream, before it reads any request frame, with `keepalive_interval_ms` set to the interval API-255 uses. | | | API-251 | An invalid update fails the stream | When an `Update` has an `id` of 0 or not greater than the previous accepted `id` on the stream, names one topic more than once across `adds` and `removes`, names a topic TOPIC-003 rejects, or carries a cursor greater than 9223372036854775807, or when a request frame’s `request` is unset, the backend MUST fail the stream with `INVALID_ARGUMENT`. | | | API-252 | Applied acknowledges every update | The backend MUST answer every accepted `Update` with one `Applied` carrying the same `id`, in the order the updates were received, whose `added_targets` lists exactly the topics the update newly registered, in add order, each with `through_sequence_id` set to the highest sequence id visible on that topic in one read made after the topic was registered, or 0 when none was visible. The backend MUST NOT send a `Messages` frame for a registration before its `Applied`, and MUST NOT change a registration’s target after it. | A client that sees `Applied` knows every later envelope on that topic is above the cursor it supplied, and a target captured before registration could miss a publish that landed between the two. | | API-253 | Adds and removes are idempotent | When an `Update` adds a topic that is already registered, the backend MUST leave that registration unchanged, whatever cursor the add supplied, and MUST NOT list it in `added_targets`; when it removes a topic that is not registered, the backend MUST do nothing for it. When an `Update` removes a registered topic, the backend MUST NOT send an envelope of that registration after that update’s `Applied`, and a later add of the same topic MUST start a new registration from the cursor that add supplies. | A client reconciles its interest set by resending it; an add that moved a live registration would rewind or skip delivery for it. | | API-254 | Deliver everything, in order, or fail | While a topic is registered, the backend MUST deliver every visible envelope on it with a sequence id greater than the registration’s cursor, in strictly increasing sequence id across frames, and MUST NOT skip one; when it cannot, it MUST fail the stream with the status the table in section 7 names. | A skipped envelope is invisible to the client until it reconnects; a skipped commit is a fork. | | API-255 | Idle keepalive | When `keepalive_interval_ms` passes with no frame sent on a stream, the backend MUST send a `Keepalive` on a `SubscribeStatic` stream, and a `Ping` on a `Subscribe` stream unless a `Ping` it sent is still unanswered. | Without it a client behind a dropped connection waits for ever on a stream that no longer exists. | | API-256 | Ping is answered | When the backend or the client receives a `Ping` on a `Subscribe` stream, it MUST send a `Pong` whose `nonce` equals the `Ping`’s. | | | API-257 | A missed Pong closes the stream | When the backend has sent a `Ping` and no `Pong` carrying its `nonce` arrives within the interval the operator configures, 90 seconds by default, the backend MUST fail the stream with `DEADLINE_EXCEEDED`. When the transport has not taken a queued `Ping` within that interval of the backend queuing it, the backend MUST fail the stream with `DEADLINE_EXCEEDED`. The backend MUST NOT send a second `Ping` while one is unanswered. | A stream nobody reads holds registrations and output for as long as it stays open, and a client that stops reading never takes the `Ping`, so a wait counted only from sending never starts. | | API-258 | Frame rate is bounded per stream | The backend MUST admit `Update` frames at `max_update_frames_per_second` with a burst of `max_update_burst`, and client `Ping` frames at `max_ping_frames_per_second` with a burst of `max_ping_burst` (CONF-069), and when a frame that API-306 does not fail exceeds its bucket MUST fail the stream with `RESOURCE_EXHAUSTED`. A `Pong` MUST NOT count against either bucket. | A client answering the backend’s own challenges must never be closed for answering them. | | API-259 | Only the client ends a healthy stream | The backend MUST NOT end a `Subscribe` stream while the client’s request stream is open and no failure in the status table has occurred, whether or not a topic is registered; when the client ends its request stream, the backend MUST end the response stream without an error status. A `SubscribeStatic` stream MUST stay open until the client cancels it or a failure closes it. | A client opens its stream before it knows its topics, and a client that half-closes to say “no more updates” and expects delivery to continue loses every envelope from then on. | | API-261 | Catch-up does not starve | While two or more registrations each have visible envelopes at or below their catch-up target not yet delivered, the backend MUST NOT send a second `Messages` frame of such envelopes to one of them before every other has received one. | A client that registers a group beside a thousand busy ones would otherwise see that group’s history only after all of theirs. | | API-260 | A static stream starts with its targets | The backend MUST fail a `SubscribeStatic` request with `INVALID_ARGUMENT` when `topics` is empty or names one topic more than once, and otherwise MUST send `Started` as the first frame, with one `CatchupTarget` per requested topic in request order, including a topic with no envelope, before any `Messages` frame. | | ## 6. Identity reads `GetInboxIds` resolves external identifiers to inbox ids from the association state the backend has admitted. An identifier can be associated with more than one inbox over its life; the lookup answers with the inbox of the most recent association that has not been revoked, and revoking that one can bring an older association back into view. Lookup keys are compared in a normalized form, so an Ethereum address matches whatever its letter case; the signed bytes of an identity update are never normalized. `VerifySmartContractWalletSignatures` verifies ERC-1271 and ERC-6492 signatures over the chains the deployment publishes (CONF-070) for a client that holds no chain access of its own. `GetInboxIds` also resolves a handle, in an entry whose `identifier_kind` is `IDENTIFIER_KIND_HANDLE`, to the inbox that claimed it. A claim is never revoked, and only one inbox can claim a handle (API-296), so an old handle of an inbox still resolves to that inbox. A handle in a lookup matches whatever its ASCII letter case. A handle entry whose identifier does not match the handle grammar fails the whole request (API-299). The answer comes from the backend alone; IDENT-085 owns the client’s check of it. ```proto message GetInboxIdsRequest { message Request { string identifier = 1; xmtp.identity.associations.IdentifierKind identifier_kind = 2; } repeated Request requests = 1; } message GetInboxIdsResponse { message Response { string identifier = 1; xmtp.identity.associations.IdentifierKind identifier_kind = 2; optional string inbox_id = 3; } repeated Response responses = 1; } message VerifySmartContractWalletSignaturesRequest { message Signature { // CAIP-10 account id. string account_id = 1; // Block to verify at. Absent = latest. optional uint64 block_number = 2; bytes hash = 3; bytes signature = 4; } repeated Signature signatures = 1; } message VerifySmartContractWalletSignaturesResponse { message Response { bool is_valid = 1; optional uint64 block_number = 2; optional string error = 3; } repeated Response responses = 1; } ``` | ID | Title | Requirement | Why | | ------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | API-270 | Resolve to the latest live association | The backend MUST answer `GetInboxIds` with one `Response` per request entry, at the same index, echoing `identifier` and `identifier_kind` as sent. For an entry whose `identifier_kind` is not `IDENTIFIER_KIND_HANDLE`, `inbox_id` MUST be the inbox whose association with that identifier and kind has the highest sequence id among those not revoked, comparing an Ethereum address without regard to letter case and a passkey by its public key bytes, or absent when there is none. | An answer that ignores revocation names an inbox the identifier has left, and a client that checks it under IDENT-096 then finds no inbox for a user who has one. | | API-299 | Resolve a handle | When a `GetInboxIds` entry’s `identifier_kind` is `IDENTIFIER_KIND_HANDLE`, the backend MUST convert the ASCII uppercase letters of its `identifier` to lowercase, and MUST set `inbox_id` to the inbox whose identity topic holds an envelope whose update carries a `ClaimHandle` of that converted handle, whether or not the inbox has claimed another handle since, or leave it absent when no identity topic holds one. When the converted `identifier` of such an entry does not match the handle grammar of IDENT-078, the backend MUST fail the request with `INVALID_ARGUMENT`. | A contact saved under an old handle stops reaching its inbox, and a handle typed with capitals reaches no one. | | API-301 | One verdict per signature | When every `account_id` and `signature` passes the checks IDENT-093 makes before chain access and every `hash` is 32 bytes, the backend MUST answer `VerifySmartContractWalletSignatures` with one `Response` per request entry, at the same index, whose `is_valid` is the verdict at `block_number`, or at the latest block when it is absent, and whose `block_number` is the block the verdict was reached at; a verdict that a signature is invalid is `is_valid` `false`, not a failed request. When an entry fails those checks or its `hash` is not 32 bytes, the backend MUST fail the request with `INVALID_ARGUMENT` before any chain access; when a verdict cannot be reached, it MUST fail under API-231. | A client verifying a signature at “latest” needs the block to record with the association, and a whole request failed for one invalid signature hides the verdicts of the others. A verdict for the zero address is valid for any signature, and an oversized signature makes the backend build verification code as long as the caller chooses. | ## 7. Bounds, errors, and transport Every request has bounds it cannot exceed. Most bounds are published, so that a client sizes its requests before it sends (CONF-073); the bounds table gives the fixed value of each bound that is not. The backend enforces each one; a client that sends past a bound gets `INVALID_ARGUMENT` and nothing stored, unless its `request` spend is denied first (RATE-014). The byte budget on a request is measured twice: the transport measures the wire length before the backend sees the request, so a request that is too long on the wire is `OUT_OF_RANGE` unless its `request` spend is denied first (RATE-014), and admission measures the re-encoded length, which can be longer than the wire length when the client used a shorter varint encoding than the backend does, so a request that is within the budget on the wire and over it re-encoded is `INVALID_ARGUMENT` with `REASON_TOO_LARGE`. The transport ceiling is fixed, and configuration keeps every published byte budget under it (CONF-096), so a request within the published limits is always carried. The one response not bounded by `max_response_bytes` is `GetConfiguration`, which CONF-009 bounds separately. The bounds table names each request’s limits and the field of `LimitsConfiguration` that publishes them (CONF-069), or the fixed value of a bound that no field publishes. A publish that exceeds one carries `REASON_TOO_LARGE`; a bound checked on the input count is checked before repeated topics are merged. | Request | Bound | | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Publish` | Re-encoded request not longer than `max_request_bytes`; each envelope’s re-encoded length not longer than `max_envelope_bytes`; distinct topics not more than `max_publish_topics`; ERC-6492 signatures in one identity update not more than `max_scw_signatures`; envelopes not more than 1000, duplicates included; identity updates not more than 5, duplicates included; `IdentityAction` entries across all identity updates not more than 500 (5 updates at the limit of IDENT-094); gRPC messages in the request body not more than 1 | | `Query` | Entries in `queries` not more than `max_query_topics`; gRPC messages in the request body not more than 1 | | `QueryNewest` | Topics not more than `max_newest_full_topics` with `include_full_envelope` true and `max_newest_metadata_topics` with it false; gRPC messages in the request body not more than 1 | | `GetInboxIds` | Entries not more than `max_lookup_identifiers`; gRPC messages in the request body not more than 1 | | `VerifySmartContractWalletSignatures` | Entries not more than `max_scw_signatures`; gRPC messages in the request body not more than 1 | | `SubscribeStatic` | Topics not more than `max_static_topics`; gRPC messages in the request body not more than 1 | | `Subscribe` `Update` | `adds` not more than `max_update_adds`; `removes` not more than `max_update_removes`; topics registered after the update not more than `max_stream_topics` | | Any request | Every `Cursor.sequence_id` not greater than 9223372036854775807 | The status table maps each failure a client can meet to the code it receives. A client classifies by code, never by message text, because the text is free to change. `INVALID_ARGUMENT` is never retried unchanged: the same request fails the same way. `ABORTED` on a publish means the identity history moved (API-303); the client re-reads the inbox’s identity topic, rebuilds the update against it, and sends that. `UNAVAILABLE` and `DEADLINE_EXCEEDED` are retried with backoff; on a publish, a retry is safe under API-222 whether or not the first attempt committed. `RESOURCE_EXHAUSTED` with a rate-limit detail is retried no sooner than its delay, and never split (RATE-041). `OUT_OF_RANGE` on a publish does not prove the publish was not stored: a response can exceed the ceiling after the request committed. A `Subscribe` frame that API-306 fails gets `INVALID_ARGUMENT` in place of the code any other row gives that frame. | Condition | Code | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | | An envelope fails admission (API-230), or a request exceeds a bound in the bounds table or is malformed in a way this spec names | `INVALID_ARGUMENT`, with a `PublishError` detail on a publish (API-223) | | The wire length of a request is longer than `max_request_bytes` or the transport ceiling; an encoded unary response, or a `Messages` frame, is longer than `max_response_bytes` or the ceiling | `OUT_OF_RANGE` | | A request arrives with a compression encoding | `UNIMPLEMENTED` | | The identity history changed during validation (API-303) | `ABORTED` | | A chain RPC or verifier failure (API-231); the store is unreachable; a stream is opened or running while the backend is recovering its stream state; the backend is shutting down | `UNAVAILABLE` | | A publish or a store operation exceeds the backend’s own time limit; a `Pong` did not arrive, or the transport did not take a queued `Ping` (API-257) | `DEADLINE_EXCEEDED` | | A stream’s frame bucket is exhausted (API-258); a stream’s output cannot be queued because the client is not reading; a stored envelope cannot fit a frame; a `Started`, `Applied`, `Ping`, or `Pong` frame would be longer than `max_response_bytes` | `RESOURCE_EXHAUSTED` | | A spend for the request’s caller is denied (RATE-010), including a stream’s rent (RATE-032) and an `Update`’s catch-up target (RATE-034), other than the `request` spend of a stream’s catch-up read, which pauses that read (RATE-033) | `RESOURCE_EXHAUSTED`, with the details RATE-040 gives | | A stored value violates an invariant the backend maintains | `INTERNAL` | | ID | Title | Requirement | Why | | ------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | API-281 | Status codes | The backend MUST fail a request or a stream with the code the status table above names for its condition, and MUST NOT fail it with `INVALID_ARGUMENT` for a condition the table maps to another code. | A client retries by code. A retryable failure reported as `INVALID_ARGUMENT` is dropped for good; a permanent one reported as `UNAVAILABLE` is retried for ever. | | API-282 | The transport ceiling | The backend MUST carry a request whose wire length, and a response whose encoded length, is not longer than 26214400 bytes (25 MiB) and is within `max_request_bytes` or `max_response_bytes`, and when a message is longer than the ceiling or the budget it MUST fail it rather than truncate it. | A client sizes its requests to the published budget (CONF-073); a ceiling below it fails every request the client was told it may send. | | API-283 | A response is complete or fails | The backend MUST NOT omit an envelope, a result, or a response entry from a successful response to keep it under a byte limit. | A page that silently drops rows and reports `has_more` false is history the client never fetches. | | API-284 | Retry by code | A client MUST NOT resend a request unchanged after `INVALID_ARGUMENT`, `OUT_OF_RANGE`, or `UNIMPLEMENTED`, and after `ABORTED` on a publish MUST read the inbox’s identity topic and rebuild the identity update before it resends. | A client that retries a permanent rejection loads the deployment with a request that can never succeed, and one that resends a stale identity update aborts again for ever. | | API-285 | One port for gRPC and gRPC-Web | The backend MUST serve every service on one port over both gRPC and gRPC-Web, and MUST expose the `grpc-status`, `grpc-message`, and `grpc-status-details-bin` headers to a cross-origin browser client. | A browser client cannot open an HTTP/2 gRPC connection, and without the exposed headers it cannot read the status or the `PublishError` detail. | | API-304 | Publish counts before decode | When a `Publish` request whose `request` spend is not denied (RATE-014) carries more than 1000 entries in `envelopes`, or more than 500 `IdentityAction` entries across all its identity updates, the backend MUST fail it with the API-223 rejection for a whole-request bound before it decodes more entries of that kind than that number. | An empty entry is two bytes on the wire and decodes to a structure many times that size, so a request within the default `max_request_bytes` can hold 13107200 entries and exhaust the backend’s memory before a count check that runs after decoding. | | API-306 | Subscribe counts before decode | When a request frame within `max_request_bytes` on a `Subscribe` stream whose `request` spend is not denied (RATE-014) carries more than `max_update_adds` entries in `adds`, or more than `max_update_removes` entries in `removes`, counted across every `update` field in the frame, the backend MUST fail the stream with `INVALID_ARGUMENT` before it decodes more entries of that kind than that number, in place of any status that frame would otherwise cause, such as an exhausted update bucket (API-258) or a denied rent spend (RATE-032). | An empty entry is two bytes on the wire and decodes to up to 40 bytes, so one frame within the default `max_request_bytes` holds 13107197 entries and peaks near 1 GiB while decoding. | ## 8. Connection statistics A backend connection has one set of counts. Every client and static call that shares that connection shares its counts. | ID | Title | Requirement | Why | | ------- | --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | | API-292 | API call statistics | An SDK MUST expose call counts for the `Publish`, `Query`, `QueryNewest`, `Subscribe`, and `SubscribeStatic` RPCs of the client’s backend connection. | An app needs to see which API operations use that connection. | | API-293 | Identity call statistics | An SDK MUST expose call counts for the `GetInboxIds` and `VerifySmartContractWalletSignatures` RPCs of the client’s backend connection. | An app needs to see identity traffic on that connection. | | API-294 | Statistics summary | An SDK MUST expose a text summary of the API-292 and API-293 counts for the client’s backend connection; the summary’s format is not a contract. | An app can display the counts without relying on a fixed text format. | | API-295 | Clear connection statistics | When an app clears statistics, the SDK MUST set every count in API-292 and API-293 to 0 for the client’s backend connection. | Later observations must start from a known count for every user of that connection. | ## Known limitations A read other than `Query` can lag a publish the client already holds a response for. An installation that has just published its key package or identity update can be absent from `QueryNewest` and `GetInboxIds` for a short time, and a catch-up target captured then is below the publish. A handle claimed a moment ago can likewise resolve to no inbox; a claim of that handle then fails under API-296. Elapsed time is not proof that an envelope is absent; only `Query` reads its own writes (API-202). API-297 refuses a reserved or short name part only when the backend admits a claim. A handle claimed before a release reserved its name part, or before the deployment raised `handles.min_name_length`, still resolves under API-299, and the backend does not hide it. An inbox that claimed a name before it was reserved can therefore show that name to every user who looks it up. This is accepted; see IDENT Known limitations. Sequence ids allocated but never stored leave gaps on a topic that look like envelopes not yet visible. A stream holds such a gap open until the closed allocation boundary (API-203) passes it; a `Query` and a `QueryNewest` do not wait and can return an envelope above the boundary. A client cannot distinguish a gap from a lagging publish by any read. Publish admission establishes only what the admission table says. The backend stores a group message on a group’s topic only when an installation that holds the group root signed it. That does not show that the signer is a current member: the root never changes, so every installation that was ever a member can publish. It is not evidence for a reader either: the operator can place any bytes on a topic, and no requirement makes a client verify a group message’s signature. A stored Welcome is not evidence that its destination exists. Storage can be consumed by anyone who can reach the backend, subject to the credential checks in [AUTH section 1](/specs/auth-backend-auth/#1-admission): anyone can generate a key pair and publish signed group messages and sealed commit-log entries to the topics its public key names, and a commit or proposal there, or a commit-log entry, never expires (OPS-001). The processing capacity of a group’s members can be consumed by any holder of the group’s root, and that of a Welcome’s recipient by anyone. Bytes after the MLS message in `GroupMessage.data` are accepted and stored. No client is known to produce them. They are not a forgery or a disclosure: the parsed message and its topic are unchanged. The publish signature covers them, so only a holder of the group root can vary them, and each variant is a new stored envelope with its own sequence id; a commit or proposal variant also keeps its zero expiry (OPS-001). The backend does not read a client’s version on a request, and it does not enforce the advisory group shapes it publishes; both are the client’s to apply (CONF-049, CONF-043). A `Subscribe` stream with no registered topic stays open and costs the deployment a connection. Concurrent streams are bounded per caller only through the rent they pay (RATE section 4), per instance. A client that cannot take the queued output (up to 16 MiB) within about 2 min of catch-up (\~1.1 Mbps) is closed and reconnects from its cursors. The backend reads and replays an inbox’s whole stored log for each identity update that passes the checks of API-302, whether it then stores the update or rejects it. With the default limits, one small update can cost a read of up to 256 envelopes of up to 1 MiB each and up to 51,200 signature checks without chain access (IDENT-095). A publish can carry one such update for each of up to 5 inboxes; RATE charges one `identity_update` unit for each, whatever the length of the log it replays. A `Subscribe` stream holds each request frame until it is complete and counted (API-306), beside the decoder’s own buffer, so one stream can retain about twice `max_request_bytes` of request bytes. On a unary RPC whose request has no repeated field, the backend decodes every further message in the body as well, so the number of messages in one such request is not limited, although each is limited by `max_request_bytes`. The number of requests in flight is limited only by each connection’s HTTP/2 stream limit. Publish admission must finish within 60 seconds, and identity-log replays share 64 slots in each backend process. Admission that runs past 60 seconds fails with `DEADLINE_EXCEEDED` and stores nothing, even when every chain call it made succeeded, so an identity update whose ERC-6492 signatures together need more chain time, such as 100 signatures at about 5 seconds per call, fails on every retry while the chain stays that slow. A caller can keep the 64 replay slots busy with identity updates aimed at inboxes with long logs; every other identity update on that process then waits for a slot and can fail the same way. Each configured chain allows 64 calls in flight in each backend process, shared by publish admission and `VerifySmartContractWalletSignatures`, and a call that has not finished within 10 seconds, its wait for a slot included, fails. A `VerifySmartContractWalletSignatures` request has no overall time limit. A caller can fill a chain’s slots with verify requests whose signatures make slow calls, and a publish that needs that chain then fails with `UNAVAILABLE` until slots free. A `SubscribeStatic` stream carries no `Ping`, so API-257 does not apply to it. A static client that stops reading while its connection stays open is closed only when the output it has not taken fills the stream’s queue (`RESOURCE_EXHAUSTED`); on topics with no traffic, that takes many keepalive intervals. # Archive format An archive preserves selected conversation history and consent for another installation or a later client version. Its container, record formats, and import rules form one compatibility contract. An archive is a file the client writes from its own database under a key the app supplies, and reads back into a database that may be empty or may already hold some of the same conversations. It carries what a user owns and can read: the groups they were in, the messages of those groups, and their consent records. It carries no installation secrets or group epoch secrets. Import makes historical content readable but grants no authority to send or decrypt subsequent group traffic. A validated Welcome can activate a restored group under the pending activation rule in section 4. ```mermaid flowchart LR D[(Client database)] -->|selection, window| E[Elements: metadata, groups, messages, consent] E -->|protobuf, AES-GCM per frame, zstd| F[Archive file] K[Archive key, 32 bytes] --> E F -->|app-chosen storage| F2[Archive file] K --> I F2 --> I[Import] I -->|new group: restored, inactive| D2[(Client database)] I -->|known group or message: unchanged| D2 I -->|consent: capped, greater record wins, published| D2 ``` ## Scope In scope: the container framing, its encryption, and its version; the element kinds and their wire form; what an export includes and excludes and the selection an app makes; the promise that an archive written under this version loads in every later client; what an app can read from an archive without importing it; and how an import merges each element with existing local state. Out of scope: what a consent record means and how two records merge (CONS-050, CONS-053); what a message’s content means (CTYPE); what group metadata means (META); how a restored group becomes active again, which requires a validated Welcome (JOIN-080); the device sync channel, which does not carry archives (SYNC); and where an app stores an archive and its key. | Related | Relation | | ------------------ | --------------------------------------------------------------------------------------------------------- | | CONS-050, CONS-053 | Own the consent wire form and merge rule. | | CTYPE | Owns the `EncodedContent` a message element carries in `decrypted_message_bytes`. | | `JOIN-080` | Owns activation of a restored group by a validated Welcome; JOIN-042 applies only after a removal commit. | | META | Owns the meaning of the metadata attributes and admin lists a group element carries. | | `SEND-002` | Owns the message id that an import uses for deduplication. | | EVENT | EVENT-001 reports a changed import once it ends; EVENT-004 excludes events for each stored element. | ## Terms | Term | Meaning | | ---------------- | ------------------------------------------------------------------------------------------------------------------------ | | Archive | One file in the container format of section 1: a header, then frames. | | Archive key | The 32-byte key the app supplies to write or read an archive. | | Header | The first 14 bytes of an archive: the version and the base nonce, in the clear. | | Frame | One encrypted `BackupElement`, prefixed by its length, inside the compressed stream. | | Element | One `BackupElement`: metadata, a group, a message, a deletion record, or a consent record. | | Metadata element | The first element of every archive: what was selected, the window, and when the archive was written. | | Selection | The `elements` list of the options an app exports with: `MESSAGES`, `CONSENT`, both, or an explicit empty list. | | Window | The `start_ns` and `end_ns` of the options, bounding the messages exported by their send time. | | Restored group | A conversation created by import whose history is readable but which this installation has not joined through a Welcome. | | Export time | The single `exported_at_ns` captured at the start of export; eligibility and exported values are measured at this time. | ## 1. The container An archive has a clear header followed by one zstd stream. The header carries a two-byte little-endian container version and a 12-byte base nonce. Each decompressed frame has a four-byte little-endian ciphertext length followed by that ciphertext, including its 16-byte authentication tag. Frame numbering starts at 0. The cipher is AEAD\_AES\_256\_GCM under [RFC 5116 §5.2](https://www.rfc-editor.org/rfc/rfc5116.html#section-5.2); zstd uses the frame format in [RFC 8878 §3.1](https://www.rfc-editor.org/rfc/rfc8878.html#section-3.1). Associated data is empty. Compression covers the framed ciphertext, not the header or plaintext. The container version is 0. The legacy nonce form uses the base nonce for every frame. The retry in ARCH-002 reads that form; it does not repair the loss of confidentiality or authentication caused by nonce reuse ([RFC 5116 §5.1.1](https://www.rfc-editor.org/rfc/rfc5116.html#section-5.1.1)). ```mermaid flowchart LR H["header: version u16 LE, base nonce 12 bytes"] --> Z["zstd stream"] Z --> F0["frame 0: len u32 LE, AES-GCM(metadata) under nonce"] Z --> F1["frame 1: len, AES-GCM(element) under nonce + 1"] Z --> Fn["frame n: len, AES-GCM(element) under nonce + n"] ``` | ID | Title | Requirement | Why | | -------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ARCH-001 | Container layout | When the client writes an archive, it MUST use the header, cipher, tag length, associated data, and zstd format stated above, with version 0 and a base nonce drawn from a cryptographically secure random source for that archive. It MUST encrypt each protobuf `BackupElement` as one frame, prefix the ciphertext with its four-byte little-endian length, and use the base nonce plus the frame number modulo 2^96 as a little-endian nonce. When a frame’s ciphertext would be longer than 75497472 bytes, it MUST fail the export instead of writing the frame. | A different frame or nonce encoding makes the archive unreadable by another client, and a frame above the ARCH-018 ceiling makes it unreadable by every client. | | ARCH-002 | Legacy nonce | If a frame fails authentication under its counter nonce, then the client MUST retry it under that nonce decremented by 1 and, when that succeeds, MUST continue the counter from the nonce that succeeded; if that also fails, it MUST fail the import. | Archives written before the counter existed used one nonce for every frame, and they are the only copy a user may have. | | ARCH-003 | Reject a later version | When the header’s version is greater than 0, the client MUST fail the import before it reads any frame, naming the version. | A later container may frame or encrypt differently, and reading it as version 0 either fails on the first frame or applies elements it misread. | | ARCH-004 | Elements never change meaning | The client MUST NOT reuse a field number of any message in section 2 for another meaning, MUST NOT change a field’s type, and MUST NOT reuse a retired enum value in section 2. | Reinterpreting a saved field changes existing archive content. | | ARCH-022 | Earlier archives remain importable | When given a valid version 0 archive in the counter-nonce form or the legacy form under ARCH-002, the client MUST import it and preserve its groups, message ids and bytes, historical metadata, and consent under sections 2 through 4, including in a later client version. | Retaining field numbers alone does not preserve the ability to restore an older backup. | | ARCH-005 | Unknown elements are skipped | When an element’s `element` is unset, or is a variant the client does not implement, including `event`, the client MUST skip it and continue with the next frame. | An archive from a later client would otherwise fail on the first element the older client has not learned. | | ARCH-018 | Reject incomplete or oversized framing | When a header is incomplete, a frame length is less than 16 or greater than 75497472, the stream ends within a length prefix or before its declared ciphertext length, a zstd frame declares a window larger than 16777216 bytes, or zstd reports an incomplete or invalid stream, the client MUST end the import with an error. It MUST reject a frame length greater than 75497472 before it reads that frame’s ciphertext. It MUST report end-of-stream success only after complete metadata and a complete zstd stream with no pending length or ciphertext bytes. | Truncated input must not hang or appear to be a complete backup. The lengths and the zstd stream are read before authentication, so without a ceiling a small file with any key can make the client buffer gigabytes. | ## 2. Elements An element is one `BackupElement`. The first is always the metadata element, so that a reader learns what the archive holds before it reads the rest and an app can show that to a user before importing. The rest are groups, deletion records, messages, and consent records, in whatever order the writer produces them, with one constraint: a message’s group comes before the message, so that a reader applying frames as it reads them holds the group before its first message. The metadata element records the selection, the window, and the export time. The container version is not in it; the header carries that. ```proto // Union type representing everything that can be serialied and saved in a backup archive. message BackupElement { oneof element { BackupMetadataSave metadata = 1; xmtp.device_sync.group_backup.GroupSave group = 2; xmtp.device_sync.message_backup.GroupMessageSave group_message = 3; xmtp.device_sync.consent_backup.ConsentSave consent = 4; xmtp.device_sync.event_backup.EventSave event = 5 [deprecated = true]; xmtp.device_sync.message_backup.MessageDeletionSave message_deletion = 6; } } // Proto representation of backup metadata // (Backup version is explicitly missing - it's stored as a header.) message BackupMetadataSave { repeated BackupElementSelection elements = 2; int64 exported_at_ns = 3; optional int64 start_ns = 4; optional int64 end_ns = 5; } // Backup Options message ArchiveOptions { repeated BackupElementSelection elements = 1; optional int64 start_ns = 2; optional int64 end_ns = 3; bool exclude_disappearing_messages = 4; } // Elements selected for backup enum BackupElementSelection { BACKUP_ELEMENT_SELECTION_UNSPECIFIED = 0; BACKUP_ELEMENT_SELECTION_MESSAGES = 1; BACKUP_ELEMENT_SELECTION_CONSENT = 2; BACKUP_ELEMENT_SELECTION_EVENT = 3 [deprecated = true]; } ``` A group element carries conversation identity, timestamps, and historical metadata. Its `welcome_id`, when present, identifies the Welcome from which the source installation joined. A message element carries message identity, sender, time, delivery status, and content bytes. The identifier inside a typed `EncodedContent` controls over the separate identifier fields and the retired `content_type_save` enum; the separate fields serve records whose content is not a typed envelope. Consent uses the wire form in CONS-050 and merges under CONS-053. ```proto // Proto representation of a stored group message GroupSave { bytes id = 1; int64 created_at_ns = 2; GroupMembershipStateSave membership_state = 3; int64 installations_last_checked = 4; string added_by_inbox_id = 5; optional int64 welcome_id = 6; int64 rotated_at_ns = 7; ConversationTypeSave conversation_type = 8; optional string dm_id = 9; optional int64 last_message_ns = 10; optional int64 message_disappear_from_ns = 11; optional int64 message_disappear_in_ns = 12; // metadata fields ImmutableMetadataSave metadata = 13; MutableMetadataSave mutable_metadata = 14; optional string paused_for_version = 15; } // Group membership state enum GroupMembershipStateSave { GROUP_MEMBERSHIP_STATE_SAVE_UNSPECIFIED = 0; GROUP_MEMBERSHIP_STATE_SAVE_ALLOWED = 1; GROUP_MEMBERSHIP_STATE_SAVE_REJECTED = 2; GROUP_MEMBERSHIP_STATE_SAVE_PENDING = 3; // A group is marked as this state when it is restored // from a backup. This is a non-functional archive state // that can be reactivated when the user is re-added to // the group. GROUP_MEMBERSHIP_STATE_SAVE_RESTORED = 4; GROUP_MEMBERSHIP_STATE_SAVE_PENDING_REMOVE = 5; } // Conversation type enum ConversationTypeSave { CONVERSATION_TYPE_SAVE_UNSPECIFIED = 0; CONVERSATION_TYPE_SAVE_GROUP = 1; CONVERSATION_TYPE_SAVE_DM = 2; CONVERSATION_TYPE_SAVE_SYNC = 3; } // A Groups's mutable metadata message MutableMetadataSave { map attributes = 1; repeated string admin_list = 2; repeated string super_admin_list = 3; } // A Group's immutable metadata message ImmutableMetadataSave { string creator_inbox_id = 1; } ``` ```proto // Proto representation of a stored group message message GroupMessageSave { bytes id = 1; bytes group_id = 2; bytes decrypted_message_bytes = 3; int64 sent_at_ns = 4; GroupMessageKindSave kind = 5; bytes sender_installation_id = 6; string sender_inbox_id = 7; DeliveryStatusSave delivery_status = 8; ContentTypeSave content_type_save = 9 [deprecated = true]; int32 version_major = 10; int32 version_minor = 11; string authority_id = 12; optional bytes reference_id = 13; optional int64 sequence_id = 14; optional int64 originator_id = 15; string content_type = 16; optional int64 expires_at_ns = 17; // absolute expiry under ARCH-019 optional bool expiry_known = 18; // true distinguishes no expiry from unknown optional string deleted_by_inbox_id = 19; } message MessageDeletionSave { bytes id = 1; bytes group_id = 2; bytes deleted_message_id = 3; string deleted_by_inbox_id = 4; bool is_super_admin_deletion = 5; int64 deleted_at_ns = 6; } // Group message kind enum GroupMessageKindSave { GROUP_MESSAGE_KIND_SAVE_UNSPECIFIED = 0; GROUP_MESSAGE_KIND_SAVE_APPLICATION = 1; GROUP_MESSAGE_KIND_SAVE_MEMBERSHIP_CHANGE = 2; } // Group message delivery status enum DeliveryStatusSave { DELIVERY_STATUS_SAVE_UNSPECIFIED = 0; DELIVERY_STATUS_SAVE_UNPUBLISHED = 1; DELIVERY_STATUS_SAVE_PUBLISHED = 2; DELIVERY_STATUS_SAVE_FAILED = 3; } // Group message content type enum ContentTypeSave { option deprecated = true; CONTENT_TYPE_SAVE_UNSPECIFIED = 0; CONTENT_TYPE_SAVE_UNKNOWN = 1; CONTENT_TYPE_SAVE_TEXT = 2; CONTENT_TYPE_SAVE_GROUP_MEMBERSHIP_CHANGE = 3; CONTENT_TYPE_SAVE_GROUP_UPDATED = 4; CONTENT_TYPE_SAVE_REACTION = 5; CONTENT_TYPE_SAVE_READ_RECEIPT = 6; CONTENT_TYPE_SAVE_REPLY = 7; CONTENT_TYPE_SAVE_ATTACHMENT = 8; CONTENT_TYPE_SAVE_REMOTE_ATTACHMENT = 9; CONTENT_TYPE_SAVE_TRANSACTION_REFERENCE = 10; } ``` | ID | Title | Requirement | Why | | -------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | | ARCH-006 | Metadata comes first | When the client writes an archive, it MUST write frame 0 as a `metadata` element containing the resolved selection and window under ARCH-017 and the export time. When frame 0 is not a `metadata` element, the client MUST fail import before it applies any element. | | | ARCH-007 | Groups precede their messages | When the client writes an archive, it MUST include a `group` element before every `group_message` whose `group_id` names it, regardless of the group’s creation time. If a required group cannot be exported, the client MUST fail export and MUST NOT report the archive complete. | An archive with a message but no group fails restoration into a destination that lacks the group. | | ARCH-008 | Message content survives | When the client exports and imports a message, it MUST preserve the message id and content bytes unchanged, including unknown types, except under ARCH-028, and MUST derive the four identifier fields from `EncodedContent.type` when present, regardless of conflicting separate fields or `content_type_save`. When the content is not a typed `EncodedContent`, it MUST preserve the separate identifier fields and MUST NOT invent a type. | Another installation may have the codec this one lacks. | ## 3. What an export includes An app selects messages, consent, or both. The selection includes complete categories measured at the export time, not a sample from each. A window bounds application messages by send time; it does not bound group creation times or consent times. Groups without messages in the window still carry conversation history and metadata. The eligibility table defines the exported set. An empty explicit selection selects nothing; omitted selection selects both categories. A failed read is not evidence that a record is ineligible. Export failure can leave a partial file, but that file is not a completed backup. | Category | Eligible records at export time | | -------------------------- | ------------------------------------------------------------------------ | | MESSAGES: groups | Every group and DM, excluding sync, one-shot, and Restored conversations | | MESSAGES: messages | Every application message in those conversations that satisfies ARCH-009 | | MESSAGES: deletion records | Every PROC-037 record of those conversations, with no window | | CONSENT | Every consent record, with no time window | Expiry is the absolute deadline assigned under META-050, not one recalculated from group settings at restore time. Settings may have changed after a message was sent. The `expires_at_ns` and `expiry_known` fields in `GroupMessageSave` distinguish a known deadline, known absence of a deadline, and missing historical information. Legacy conversion uses the same selection and required-record rules. MIG-005 permits absent optional metadata when legacy decoding fails. Ordinary SDK database export retains the strict metadata failure rule. | ID | Title | Requirement | Why | | -------- | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | | ARCH-009 | The window bounds messages | When the client writes an archive, it MUST include only messages whose `sent_at_ns` is greater than `start_ns` when set and not greater than `end_ns` when set, and whose expiry is absent or greater than the export time. When `exclude_disappearing_messages` is true, it MUST exclude every message with an expiry and every restored message whose expiry is unknown under ARCH-019. | The archive must not retain content the app excluded. | | ARCH-017 | Complete selected history | When the app omits selection, time bounds, or the disappearing-message option, the SDK MUST default them to both categories, no time bounds, and `false`, respectively; an explicit empty selection MUST remain empty. On successful export, the client MUST include every selected record and no unselected record from the eligibility table above, with its values at the export time, and MUST fail rather than silently omit a record it cannot read or encode. On successful import, it MUST preserve those records under sections 2 and 4. | A metadata-only file cannot replace selected history. | | ARCH-026 | Restored history is not exported | When the client exports an archive, it MUST exclude every conversation whose membership state is Restored and every message in that conversation. When validated activation changes that state, the client MUST apply the eligibility table above to later exports. | | | ARCH-019 | Preserve message expiry | When the client exports a message with known expiry information, it MUST set `expiry_known` to true and carry its absolute deadline in `expires_at_ns`, or omit that deadline when the message has no expiry. On import, it MUST retain that information and apply META-051, without recalculating a deadline from current group settings. When `expiry_known` is absent or false, it MUST preserve the message as history with expiry reported to the app as unknown, MUST retain that distinction on re-export, and MUST NOT infer that it never expires. | Current group settings cannot recover a historical deadline. | | ARCH-010 | Secrets and internal conversations stay | The client MUST NOT write into an archive any MLS group state or epoch secret, any private key of the installation, any key package, any HMAC or preference key, or any group whose conversation type is sync or one-shot, or a message of such a group. | Whoever holds the archive and its key holds everything in it. | ## 4. Reading and importing An app reads an archive’s metadata with the key alone, before it decides to import: the container version, the selection, the window, and the export time. The metadata element is frame 0, so that read applies nothing. An import is additive. Message ids deduplicate under ARCH-013. Existing groups retain their live state under ARCH-014. Consent is keyed under CONS-052, capped under CONS-054, and merged under CONS-053. A record the import changes is published to the user’s other installations under SYNC-027. An unusable consent record is skipped (CONS-051). The client applies an archive’s consent records after all its other elements, so a pre-8.0 DM record finds its group whatever the element order (CONS-061). A new conversation exposes the historical metadata in ARCH-020 and remains inactive under ARCH-015. An internal placeholder does not confer membership or make imported admin lists authoritative. JOIN-080 lets a validated Welcome activate a group created only by archive import, without comparing the Welcome’s epoch to an internally generated placeholder epoch. It retains all Welcome validation, preserves imported history under JOIN-044, and installs positions from the validated join anchor. JOIN-042 continues to guard replacement of a group previously joined through MLS; missing archived secrets alone do not satisfy its removal-commit condition. Successful-import idempotence is separate from failure recovery. A failed import still applies every later element it can read, and retains what it applied. Retrying after a transient read or storage failure can apply the remaining elements; repeating unchanged malformed input cannot repair it. | ID | Title | Requirement | Why | | -------- | ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ARCH-011 | Metadata without import | An SDK MUST let an app read an archive’s container version and its `metadata` element with the archive key alone, without applying any other element. | | | ARCH-012 | Key length | When an app supplies an archive key whose length is not 32 bytes, the client and SDK MUST reject it before reading or writing any archive byte. | Truncation makes keys with the same 32-byte prefix identical and discards all suffix entropy. | | ARCH-013 | Known messages are unchanged | When an imported `group_message` element’s `id` equals the id of a stored message, the client MUST leave the stored message unchanged, except under ARCH-028. | | | ARCH-014 | Known groups are unchanged | When an imported `group` element’s `id` equals the id of a stored group, the client MUST leave the stored group’s state, membership state, and metadata unchanged, and MUST set its last message time to the greater of the stored and the imported `last_message_ns`. | A live group overwritten from an archive loses its MLS state and the conversation with it. | | ARCH-015 | Restored groups are inactive | Until a validated Welcome activates a restored group under JOIN-080, the client MUST NOT use import to authorize sending to that group or decrypting its subsequent traffic. It MUST reject send and sync requests for the restored group with an inactive-group error and MUST NOT publish to its topics. | Historical access does not prove current membership to the other members. | | ARCH-016 | Import is idempotent | After a successful import, and absent other writes or expiry under META-051, the client MUST leave groups, messages, and consent unchanged when the same archive is imported again. | Repeating a restore must not duplicate history or overwrite live state. | | ARCH-020 | Historical metadata stays visible | When the client creates a conversation from a `group` element, it MUST expose the archived group id, conversation type, DM identity where present, creation time, creator and adder inbox ids, mutable attributes, admin and super-admin lists, disappearing settings, and last-message time to the app as historical metadata. It MUST NOT replace these values with values generated for an internal placeholder. | The app would show a different conversation history after restore. | | ARCH-027 | One failure does not stop the import | When an element fails to import, the client MUST still apply every later element it can read, MUST retain everything it applied, and MUST return an error when the import ends. After a transient read or storage failure has ended, it MUST allow a retry from the start using the same merge rules. A malformed recognized element, other than a consent record that CONS-051 skips, or a still-missing required group MUST fail again, rather than be skipped or reported successful. | Idempotence alone does not recover a failed import. An archive written before 8.0 often lists consent and later groups after a message whose group the export window left out, so stopping at that message loses them. | | ARCH-024 | Missing archived identity remains unknown | When import creates a Restored conversation from a `group` element, the client MUST preserve its creator as unknown exactly when `metadata` is absent or `metadata.creator_inbox_id` is empty, and its adder as unknown exactly when `added_by_inbox_id` is empty, without substituting another inbox for either unknown value. | A substitute inbox changes historical identity. | | ARCH-028 | Deletions survive archives | The client MUST export every marked message with `deleted_by_inbox_id` set and empty content. On import, it MUST mark deleted by that inbox each application message it stores whose element sets that field, without applying CTYPE-018 (the exporter or converter decided it); MUST add each `message_deletion` element, and each `Published` deletion message it stores without super-admin status, to its PROC-037 records unless a record from the topic has that id; and MUST apply PROC-037 in the same write using only records from the topic. It MUST NOT mark a message from archive data except through the field on the element that stores it, or, for a message the import stores, a `Published` deletion message in the archive whose sender is that message’s sender. | A restore must not show deleted content, and an archive must not delete history the client already holds. | After validated activation, archive export uses current validated live metadata. The ARCH-024 rule applies only when import creates a Restored conversation; ARCH-014 continues to govern existing groups. The adder is independent of immutable metadata: when metadata is absent, a nonempty adder remains known. Nonempty creator or adder text stays exact under ARCH-020; protobuf does not preserve omitted-versus-explicit-empty presence for the scalar adder. ## Known limitations An archive is authenticated by the key alone. Anyone who holds the key can write an archive with any message under any sender, and an importing client cannot tell it from one the user wrote. The key is the whole trust. Archive import trusts the decrypted archive contents. Import does not verify message provenance or sender membership, so an archive from an untrusted source can add history that did not happen. Restored conversations report an unknown creator, empty member and role lists, and false admin roles until validated activation. Legacy creator getters use empty text; the new SDK uses its optional unknown value. Restored conversations do not preserve arbitrary mutable attributes or exact archived creator and admin lists. The archived group id, kind, DM pair, creation time, adder, disappearing scalar settings, and activity remain preserved. ARCH-020 and ARCH-024 have gap waivers until exact historical metadata support returns. Restored conversations and their messages are excluded from export under ARCH-026. A restored conversation whose group id is 16 bytes can never be activated: no installation holds a group root that derives a 16-byte id, so every Welcome naming it fails JOIN-083. Its history stays read-only on the installation that imported it. An archive written before 8.0 carries consent times that are not decision times (CONS Known limitations). An archive written before 8.0 has no deletion marks. Import restores only its self-deletions, and only for messages the import itself stores; it does not apply a super admin’s deletion, and it never marks a message the client already held. A message with a future expiry can remain in the archive after its deadline. Import applies META-051 only when the archive preserves that deadline. Archives written before `expiry_known` existed lack per-message expiry information; their messages remain readable with unknown expiry under ARCH-019, and current group settings cannot recover their deadlines. A message imported by a client version that did not record unknown expiry reports no expiry, because nothing stored separates it from a message that never expires, and an export with `exclude_disappearing_messages` still includes it. A frame for a missing group fails restoration when the destination lacks that group. This does not delete source data or corrupt the destination. The other elements are still applied, and an unchanged retry reaches the same failure. Legacy repeated-nonce archives remain readable, but nonce retry cannot restore the confidentiality or authentication lost by the writer. The container has no authenticated record count or final marker, so a valid zstd stream cut at a complete frame boundary cannot prove backup completeness. The zstd stream compresses ciphertext, so it provides no useful size reduction. # Remote attachments A remote attachment is a file that a message carries by reference. The sender encrypts the file under CTYPE-015, stores the ciphertext at a URL, and sends a remote attachment content type that holds the URL, the key material, and the digest of the ciphertext. A recipient fetches the URL, checks the digest, and decrypts. This spec makes storage an optional service of the backend. A backend whose operator configures a storage target publishes a base URL, and the download URL of an object is the base URL followed by the digest of its ciphertext. A client can therefore build the complete remote attachment before any byte is uploaded, and an app can send the message optimistically while the upload runs. The backend does not carry the bytes. It signs a request that lets the client put exactly those bytes, once, into the operator’s object storage. A backend with no storage target publishes no attachments configuration and answers `UNIMPLEMENTED` to the upload method, and an app reads which case applies from the client’s configuration snapshot. The client keeps a plaintext copy of every attachment it creates or downloads in an attachments directory, at a path it derives from the remote attachment alone, and keeps a record of each one. An app finds the file for a message without a lookup, and every client version finds the same file. ```mermaid sequenceDiagram participant A as App participant C as Client participant B as Backend participant S as Storage target A->>C: create pending attachment (path or bytes) C->>C: encrypt, stage ciphertext, write plaintext copy C-->>A: remote attachment (URL = base URL / digest) A->>C: send message optimistically, then upload C->>B: CreateUpload(digest, length) B-->>C: presigned PUT C->>S: PUT ciphertext with the signed headers S-->>C: 200, or 412 when the object exists Note over A,S: A recipient downloads the URL with a plain GET, from any host ``` ## Scope In scope: what the backend publishes about attachment storage; the download URL of an object; the upload request and what its signature binds; the pending attachment and its status; the attachments directory, the attachment key, the local file name, and the records of pending and local attachments; downloads, the address and size rules they follow, and their verification; the failure causes an SDK reports. Out of scope: the remote attachment encodings and the encryption of the payload (CTYPE section 7, CTYPE-014, CTYPE-015); the event kinds and their delivery (`EVENT`); credentials (`AUTH`); the layout and presence rules of the configuration file, the defaults of its keys other than the one ATCH-003 binds, and every check of an `[attachments]` key that no row of this spec states (CONF section 1.2); the storage target’s own lifecycle, access, and cache configuration; how an SDK names its methods. | Related | Relation | | ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [CTYPE](/specs/ctype-content-types/#7-the-catalogue) | Owns the remote attachment and multiple remote attachment encodings and their parameters (CTYPE-014), and the payload encryption and digest (CTYPE-015). This spec produces and consumes them. | | [CONF](/specs/conf-backend-configuration/) | Owns the public configuration message, the snapshot (CONF-020), absent values and their defaults (CONF-025), the blocked connection (CONF-075), and the app’s view of the snapshot (CONF-061). `GetConfigurationResponse.attachments` carries the `AttachmentsConfiguration` this spec owns. It also owns the layout, presence, and defaults of the `[attachments]` keys other than the one ATCH-003 binds (section 1.2). | | [AUTH](/specs/auth-backend-auth/#1-admission) | Owns admission and client credential failures. `CreateUpload` is not a public method, so AUTH-001 applies to it. | | [API section 7](/specs/api-backend-api/#7-bounds-errors-and-transport) | Owns the status codes and the client’s retry rule (API-284). The admission table of section 3 adds the conditions of `CreateUpload`. | | [EVENT](/specs/event-client-events/#1-kinds-and-payloads) | Owns the `attachment.*` kinds, their payloads, and their delivery. This spec owns the transitions they report. | | [OPS](/specs/ops-backend-operations/#5-telemetry) | Owns the route table and the metric catalogue, including the row for `CreateUpload`. | | [STORE](/specs/store-client-storage/#1-database-location) | Owns the default location, the storage label, and the database file name in a data directory. An SDK maps the default location and a directory the app names onto the layouts of section 5 (STORE-020). | ## Terms | Term | Meaning | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Ciphertext | The bytes stored at a download URL: the CTYPE-015 encryption of an `xmtp.org/attachment:1.0` encoded content, with its tag. | | Content digest | The lowercase hexadecimal SHA-256 of a ciphertext, as CTYPE-015 defines it. On the wire of `CreateUpload`, the same 32 bytes unencoded. | | Storage target | The object storage the operator configures. It accepts the signed requests the backend issues and serves the objects at their download URLs. | | Object key | The name under which the storage target stores the ciphertext of one content digest: the operator’s configured key prefix, which may be empty, followed by the lowercase hexadecimal content digest. The operator maps the base URL to that prefix, so the download URL of ATCH-010 serves the object. | | Base URL | `AttachmentsConfiguration.base_url`. | | Download URL | The URL ATCH-010 derives from a base URL and a content digest. | | Offered | A snapshot offers attachments when it carries an `AttachmentsConfiguration` to which ATCH-008 does not apply. | | Pending attachment | The client’s database record of one ciphertext that it created for upload. It holds the status (`waiting`, `uploading`, `complete`, or `failed`), the cause of the last failed upload, and the lease of a running upload. | | Upload lease | The time until which a running upload holds a pending attachment. While the lease has not expired, no other upload of that pending attachment starts (ATCH-074). | | Upload | One run of `CreateUpload` and the signed request for a pending attachment, from the moment its status becomes `uploading` until it becomes `complete` or `failed`. | | Staged ciphertext | The copy of a pending attachment’s ciphertext that the client keeps from its creation until its upload completes. | | Attachments directory | The directory under which the client stores plaintext files and staged ciphertext (ATCH-040, ATCH-049). | | Attachment key | The value ATCH-041 derives from a remote attachment. It names the plaintext file’s directory. | | Plaintext path | The path ATCH-043 derives from a remote attachment. | | Plaintext file | The file at a plaintext path. | | Local attachment | A plaintext file the client wrote by a creation or a download that succeeded, and has not deleted. | | Download host | The host a download URL names, or a host a redirect names. It need not be a backend’s storage target. | ## 1. What the backend publishes Attachment storage is optional. The backend offers it only when the operator configures a storage target, and it then publishes where objects are served, how large one may be, and how long the operator keeps them. A client builds every download URL from this message, so a wrong base URL sends every recipient to the wrong place, and a published ceiling the backend does not enforce lets a client build an attachment it can never upload. A client that receives an unusable attachments message still works for messaging. It behaves as if the deployment offered no storage. Downloads do not depend on the offer: a client downloads from any host whether or not its own backend offers storage (ATCH-050). ```proto // Published as GetConfigurationResponse.attachments (CONF section 2.1). // Absent when the deployment offers no attachment storage. message AttachmentsConfiguration { // Absolute URL with no query, fragment, or trailing "/". string base_url = 1; // Largest ciphertext CreateUpload accepts, in bytes. uint64 max_upload_bytes = 2; // Seconds the operator keeps an object after it is stored. 0: no expiry. uint64 retention_seconds = 3; } ``` | ID | Title | Requirement | Why | | -------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ATCH-001 | Offered exactly when configured | The backend MUST set `GetConfigurationResponse.attachments` if and only if a storage target is configured. | A client that sees no message never builds an attachment; one that sees a message for a target that does not exist builds attachments nobody can upload. | | ATCH-002 | Base URL form | When the configured base URL is not an absolute URL under [RFC 3986 §4.3](https://www.rfc-editor.org/rfc/rfc3986#section-4.3) whose scheme is exactly lowercase `https`, or exactly lowercase `http` with a host that is `localhost` or a loopback address, or when its host is not a non-empty reg-name with no percent-encoded octet, an IPv4address, or an IPv6address (IPvFuture is not allowed), its port when present is 0 or greater than 65535, or it carries userinfo, a `.` or `..` path segment (including percent-encoded forms), a query, a fragment, or a trailing `/`, the backend MUST refuse to start and name the key under CONF-065. | Every recipient would derive a download URL that a content type decoder may reject under ATCH-011, that a client may not fetch under ATCH-053, that discloses a credential, or that has a doubled separator. | | ATCH-003 | Upload ceiling | When the configured upload ceiling is 0 or greater than the largest `contentLength` the CTYPE-014 parameters table admits, the backend MUST refuse to start. The backend MUST set `max_upload_bytes` to the ceiling it enforces under ATCH-021, which is the default the CONF defaults table gives for `attachments.max_upload_bytes` when the operator sets none. | A larger ceiling admits an attachment whose length no remote attachment can carry. | | ATCH-004 | Published retention | When the configured retention exceeds 9007199254740991 seconds, the backend MUST refuse to start and name the key under CONF-065. Otherwise, the backend MUST set `retention_seconds` to the configured retention, and to 0 when none is configured. | A larger value loses precision in clients that represent seconds as an IEEE 754 integer. | | ATCH-005 | Retention matches the target | An operator SHOULD configure a retention equal to the expiry rule of the storage target, and none when the target keeps objects without expiry. | An app that shows an attachment as available after its object expired shows a file no recipient can fetch. | | ATCH-006 | Storage secrets stay private | The backend MUST NOT place in any field of `GetConfigurationResponse` a storage target credential, a bucket name, or a storage endpoint URL other than the base URL. | The message is served without a credential (CONF-010). | | ATCH-007 | The target enforces the signed request | An operator SHOULD configure only a storage target that rejects a PUT whose body’s SHA-256 or length differs from the value its signature binds, and a PUT whose signature binds the create-only precondition when an object is at the key; that answers a PUT with a 2xx status only once it serves the object unchanged at the download URL of its content digest, and then keeps serving it there; that, where browser clients use the deployment, allows a cross-origin PUT with the signed headers and a cross-origin GET; and, for an S3 target, that accepts path-style requests, `{endpoint}/{bucket}/{object key}`, which is the form the backend signs. | ATCH-023 holds only on a target that enforces what the backend signs. On any other target, a member who knows a digest can store other bytes at it, and a target that answers before it serves the object lets the client delete its only staged copy under ATCH-037. | | ATCH-073 | Signing credential sources | The backend MUST obtain the credentials it signs with from the source that `attachments.target.S3.credentials.kind` names: `static`, `default_chain`, `environment`, `profile`, `sso`, `process`, `web_identity`, `container`, `instance`, or `assume_role`, as the AWS SDK credential providers define them. When the kind is not one of these, or a field that kind requires is missing or empty, the backend MUST refuse to start and name the key under CONF-065. | An operator who runs the backend in a cloud account must not have to copy a long-lived secret into the configuration file. | | ATCH-075 | Key prefix form | When the configured key prefix is not empty and contains a character other than an ASCII letter, digit, `_`, `-`, `.`, or `/`, begins with `/`, contains `//`, or has a `.` or `..` segment, the backend MUST refuse to start and name the key under CONF-065. | A prefix with other characters, or with empty or dot segments, signs an object key that differs from the one the operator maps the base URL to. | | ATCH-081 | S3 target names | When the configured S3 region is empty or contains a whitespace character, or the configured bucket is empty, contains `/`, or is `.` or `..`, the backend MUST refuse to start and name the key under CONF-065. | A request signed for an empty region, or for a bucket that is not one path segment, fails at every target, so the backend would start but every upload would fail. | | ATCH-083 | Presign lifetime setting | When `attachments.target.S3.presign_ttl_seconds` is set to a value below 300 or above 3600, the backend MUST refuse to start and name the key under CONF-065. | A lifetime outside that range cannot satisfy ATCH-028, so every upload response would be wrong. | | ATCH-008 | An unusable offer is no offer | If the snapshot carries an `AttachmentsConfiguration` whose `base_url` fails the form of ATCH-002, whose `max_upload_bytes` is greater than the largest `contentLength` the CTYPE-014 parameters table admits, or whose `retention_seconds` exceeds the bound in ATCH-004, then the client MUST apply this spec as if the snapshot carried no `AttachmentsConfiguration`. | A client that builds URLs from a malformed base URL sends every recipient to nothing; one that fails creation over it loses messaging for an attachments fault (CONF-027). | | ATCH-009 | Apps read the offer | An SDK MUST let an app read, from the client’s snapshot and without a request, whether the snapshot offers attachments. | An app that cannot tell hides no attach button, and its users meet `not_offered` after choosing a file. | ## 2. The download URL and the remote attachment The download URL is a function of the base URL and the content digest. The client builds it when it creates the pending attachment, and the backend signs a request for the object key of the same digest. The same ciphertext therefore has one URL at one deployment. Two creations of one file have two URLs, because each has a fresh secret, salt, and nonce under CTYPE-015. | ID | Title | Requirement | Why | | -------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | ATCH-010 | Download URL derivation | The client MUST set the download URL of a ciphertext to the snapshot’s `base_url`, followed by `/`, followed by its content digest. | A client that builds another URL sends recipients to an object that does not exist. | | ATCH-011 | The remote attachment the client builds | When the client creates a pending attachment, it MUST build a remote attachment whose `url` is the download URL under ATCH-010, whose `content_digest`, `secret`, `salt`, and `nonce` are those of CTYPE-015 for the ciphertext, whose `content_length` is the ciphertext length, and whose `scheme` is the download URL’s scheme followed by `://`. It MUST set `filename` to the `AttachmentSource` `filename`, or, when that is absent and the source is a path, to the final component of the path, and MUST leave it absent otherwise. | A recipient bounds its download by `content_length` (ATCH-056) and names the local file by `filename` (ATCH-042). | | ATCH-012 | The encrypted content | The client MUST encrypt, for a pending attachment, the `xmtp.org/attachment:1.0` encoded content whose content is the bytes of the `AttachmentSource`, whose `mimeType` is its `mime_type`, and whose `filename` is the remote attachment’s `filename`, absent when that is absent. | A recipient that decodes another type fails under ATCH-051, and one that reads another MIME type opens the file with the wrong app. | ## 3. The upload request The client asks the backend for permission to store one ciphertext, named by its digest and length. `CreateUpload` is the one method of `xmtp.backend.v1.AttachmentService`: a unary call that takes a `CreateUploadRequest` and answers a `CreateUploadResponse`. The backend answers with a request the client sends unchanged to the storage target. The signature binds the method, the object key, the length, the SHA-256 of the body, and a create-only precondition, so the target accepts exactly the declared bytes, and only when no object is at the key. A second upload of stored bytes is not an error. The backend does not look for the object before it signs. The target answers 412 when an object is already at the key, and the client counts that as stored. ```proto message CreateUploadRequest { bytes content_digest = 1; // 32 bytes: SHA-256 of the ciphertext uint64 content_length = 2; // ciphertext length in bytes } message CreateUploadResponse { string method = 1; // "PUT" string url = 2; // the storage target's URL for the object key repeated HttpHeader headers = 3; // sent exactly as given uint32 expires_in_seconds = 4; // from the response until the target refuses the request } message HttpHeader { string name = 1; string value = 2; } ``` The admission table adds the conditions of `CreateUpload` to the status table of API section 7. The backend checks the rows in order, after admission under AUTH-001 and the `request` charge of RATE section 2; the first row that matches decides the code. `UNAVAILABLE` reports a credential failure that a later request can outlive, such as a credential source that does not answer or a credential that has expired and is not yet renewed. `FAILED_PRECONDITION` and `INTERNAL` report a failure that stays until the operator corrects the configuration or the backend. | Condition | Code | | --------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | | No storage target is configured | `UNIMPLEMENTED` | | `content_digest` is not 32 bytes, or `content_length` is 0 or greater than the enforced `max_upload_bytes` | `INVALID_ARGUMENT` | | The caller’s `upload` spend is denied (RATE-010) | `RESOURCE_EXHAUSTED`, with the details RATE-040 gives | | The credential source that ATCH-073 names reports that its own configuration is invalid | `FAILED_PRECONDITION` | | The backend cannot obtain a credential from that source, or obtains one whose remaining lifetime is shorter than the least lifetime ATCH-028 allows | `UNAVAILABLE` | | The backend cannot build or sign the request for a reason other than its credential | `INTERNAL` | | ID | Title | Requirement | Why | | -------- | -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ATCH-020 | Attachment wire format | The backend MUST publish `AttachmentsConfiguration` and serve `xmtp.backend.v1.AttachmentService.CreateUpload` as a unary RPC that takes `CreateUploadRequest` and returns `CreateUploadResponse`, with the messages of sections 1 and 3, with the field numbers and types shown, and MUST NOT reuse a field number of any of them for another meaning. | | | ATCH-021 | Upload admission | The backend MUST fail a `CreateUpload` whose `request` spend is not denied (RATE-014) with the code the admission table names for the first row its request matches. | A retryable failure reported as `INVALID_ARGUMENT` is dropped for good under API-284. | | ATCH-023 | The signature binds the bytes | When the backend answers a `CreateUpload`, it MUST set `method` to `PUT` and MUST sign the request so that a storage target that meets ATCH-007 accepts it only as a PUT of exactly `content_length` bytes whose SHA-256 is `content_digest`, to the object key of `content_digest`, while no object is at that key. | A request that admits other bytes lets a member who has read the message replace the file every recipient downloads; one that admits an overwrite lets anyone erase it. | | ATCH-028 | Signed request lifetime | The backend MUST set `expires_in_seconds` to a value from 300 through 3600, equal to the lifetime of the signature it issues. | A client that trusts a longer lifetime starts a PUT the target refuses. | | ATCH-024 | The client sends the request as signed | When the client uploads, it MUST send a PUT request to the `url` of the `CreateUploadResponse`, with every header of `headers` and its value, and the staged ciphertext as the body. A header that the client’s HTTP transport sets from the body, such as `content-length`, MUST have the value `headers` gives. When `method` is not `PUT`, the client MUST end the upload as `failed` with the cause `target_rejected` without sending a request to the target. | The target refuses a request that differs from its signature. | | ATCH-025 | Upload outcome | The client MUST end an upload as `complete` when the target answers the signed request with a 2xx status or 412, and as `failed` with the cause ATCH-060 names on any other answer or transport failure, including a timeout under ATCH-070, and when `CreateUpload` fails or the client cannot read or write the staged ciphertext or the record. | A 412 is a stored object under ATCH-023, so reporting it as a failure makes an app retry for ever. | | ATCH-026 | Blocked clients do not upload | When an upload starts while the client has a blocked connection under CONF-075, the client MUST end it as `failed` with the cause `connection_blocked` before it sends any request. | A client with a blocked connection is bound to another deployment or refused by this one. | | ATCH-029 | Permanent rejections are not resent | When an upload has ended as `failed` because `CreateUpload` answered `INVALID_ARGUMENT`, `OUT_OF_RANGE`, or `UNIMPLEMENTED`, the client MUST record the cause `backend_rejected` in the pending attachment’s record. While the record holds that cause, every client on the same database MUST end each request to upload that pending attachment as `failed` with that cause, without changing the record, emitting an event, or sending a request. | API-284: the same request fails the same way, and a retry loop, or a restart, loads the deployment for nothing. | | ATCH-027 | No credential off the backend | The client MUST NOT send a backend credential under AUTH section 6, or any other value that identifies the inbox or the installation, on a request to a storage target or a download host. Where the client does not open its own connections, it MUST make these requests with credentials omitted and no referrer, so the browser sends no cookie, HTTP authentication, client certificate, or `Referer`. | The request goes to a host the backend does not control, and a download host is chosen by the sender of a message. A browser would otherwise attach the app origin’s cookies to a download URL on that origin. | | ATCH-071 | Secure upload URL | When the configured storage endpoint URL has neither an `https` scheme nor an `http` scheme with `localhost` or a loopback address, the backend MUST refuse to start and name the key under CONF-065. The client MUST NOT send an upload PUT to a URL that does not use `https`, except `http` to `localhost` or a loopback address, and MUST end the upload as `failed` with cause `insecure_url`. When the upload PUT receives a redirect, the client MUST NOT follow it and MUST end the upload as `failed` with cause `target_rejected`. | A network attacker could fake a 2xx response to a plaintext PUT; the client would drop the staged ciphertext under ATCH-037, and every recipient would get `not_found`. | ## 4. Pending attachments An app creates a pending attachment from a file path or from bytes. Creation reads the source once. It writes the plaintext file and the staged ciphertext, and returns the complete remote attachment. After that the source is not read again, so a source that moves or is deleted after creation does not affect the upload. When creation fails, it leaves nothing behind, and the app can create again. A client holds one pending attachment for each content digest, as a record in its database. The record carries the status, the cause of the last failed upload, and the upload lease, so every client on the same database reports the same status, also after the process ends and a client is created again. An app can list the pending attachments, or ask for one by its remote attachment, and can upload it many times: after a failure, from two places or two clients at once, or after completion. A pending attachment is dropped with its record and any staged ciphertext when it reaches a maximum age, one day unless the app sets another, unless an upload of it is running. The upload table says what each request does. The `attachment.upload_*` events report each change of status that the client makes (EVENT section 1). ```webidl enum AttachmentSourceKind { "path", "bytes" }; dictionary AttachmentSource { required AttachmentSourceKind kind; // exactly one of path and bytes is present DOMString path; sequence bytes; DOMString filename; // ATCH-011 required DOMString mime_type; // ATCH-012 }; enum PendingAttachmentStatus { "waiting", "uploading", "complete", "failed" }; ``` The upload table: what the client does when an app asks to upload a pending attachment, by its status at that moment, read under ATCH-074. | Status | What the client does | | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `waiting`, or `failed` with a cause other than `backend_rejected` | Takes the upload lease and sets the status to `uploading` in one change of the record, then starts an upload, which begins with `CreateUpload` unless ATCH-026 or ATCH-036 ends it first | | `failed` with the cause `backend_rejected` | Sends no request and does not change the record; the request ends as `failed` with the cause `backend_rejected` (ATCH-029) | | `uploading` | Sends no request; the request ends with the running upload’s outcome, whichever client on the database runs it | | `complete` | Sends no request; the request ends successfully | | ID | Title | Requirement | Why | | -------- | --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | ATCH-030 | Creation preconditions | If the snapshot does not offer attachments, or the ciphertext of the source would be longer than the snapshot’s `max_upload_bytes`, or the source’s `filename` and `mime_type` would make the encoded content’s retained fields exceed the limit of ATCH-051, then the client MUST fail creation with the cause ATCH-060 names, before it writes any file. | An app that sends the remote attachment of an object that can never be stored sends a message no recipient can open. | | ATCH-031 | The remote attachment comes first | When creation succeeds, the client MUST return the remote attachment of ATCH-011 without sending any request. | An app sends the message optimistically, before the upload. | | ATCH-032 | Creation reads the source once | When creation returns successfully, the client MUST have made the plaintext file readable at its plaintext path and written the staged ciphertext so that it survives the end of the process, and MUST NOT read the source again for that pending attachment. | An app that moves or deletes its file after creation, or whose process ends after an optimistic send, would otherwise hold a message whose object can never be uploaded. | | ATCH-033 | Failed creation leaves nothing | If creation fails, then the client MUST leave no plaintext file, no staged ciphertext, no pending attachment record, and no local attachment record for it. The client MUST write the plaintext file outside every attachment key directory and the staged ciphertext outside its final path, and put each in place only by an atomic move, so creation that the end of the process interrupts leaves no partial file at either path. | An app retries creation; a leftover partial file is a file ATCH-052 would return as complete. | | ATCH-072 | Source shape | If an `AttachmentSource` whose `kind` is `path` has no `path` or has `bytes`, or one whose `kind` is `bytes` has no `bytes` or has `path`, then the SDK MUST fail creation with the cause `malformed` before the client reads the source or writes any file. | An SDK that guesses which member to read attaches the wrong content. | | ATCH-034 | Status transitions | The client MUST keep a pending attachment’s status in its record: `waiting` at creation, then only the changes the upload table states, and the outcome of an upload under ATCH-025, ATCH-026, ATCH-029, ATCH-036, ATCH-047, or ATCH-071 when the upload ends. After `complete`, the status MUST NOT change. | Two concurrent PUTs of one object race the create-only precondition for no gain; a completed upload repeated by a retry loop must not fail. | | ATCH-074 | Upload lease | The client MUST set `uploading` only in the same atomic change of the record that takes the upload lease, and only when no other upload holds an unexpired lease; while the upload runs, it MUST extend the lease to 120 seconds after the current time at least every 30 seconds. A record whose status is `uploading` and whose lease has expired holds an interrupted upload, which has no outcome: every client MUST read its status as `waiting` and MUST NOT emit an event for it. An upload whose lease has expired or was taken by another upload MUST NOT change the record or delete the staged ciphertext, and the request it serves MUST end as the upload table states for `uploading`. | Two clients on one database would otherwise run two uploads of one object, a lease left by a process that ended would block the upload for ever, and a process that resumes after suspension would overwrite the state of the upload that replaced it. | | ATCH-035 | One pending attachment per digest | The client MUST hold at most one pending attachment record for each content digest, and every handle an SDK returns for that digest, from any client on the same database, MUST report the status of that record and share its uploads. | Two handles or two clients would run two uploads of one staged ciphertext, and the one that completes first deletes the file under the other (ATCH-037). | | ATCH-036 | Unusable staged ciphertext | If an upload starts and the staged ciphertext is absent, or its SHA-256 differs from the content digest, then the client MUST end the upload as `failed` with the cause `staged_unusable` before it sends any request. | A truncated file would be rejected by the target on every retry, and the app would loop on `target_rejected` for an object it can never store. | | ATCH-037 | Staged ciphertext is released | When a pending attachment becomes `complete`, the client MUST record `complete` and then delete its staged ciphertext. | Every sent attachment would otherwise occupy its size twice on the device. | | ATCH-038 | Resuming by remote attachment | When an app asks for the pending attachment of a remote attachment, the SDK MUST return the pending attachment the client holds for its content digest, with its current status, and otherwise a failure with the cause `staged_unusable`. | An app that sent a message optimistically and was stopped before the upload completed can upload the same object, instead of sending a new message. | | ATCH-066 | Pending attachments persist | The client MUST keep each pending attachment record, with its status and the cause of its last failed upload, across the end of the process until ATCH-047 or ATCH-068 removes it. A client created later on the same database, and any other client on it at the same time, MUST hold the pending attachment with that status, read under ATCH-074. | An app restarted after an optimistic send would hold a message whose object nothing uploads, would resend an upload the backend refused (ATCH-029), and could not tell a completed upload from one that never ran. | | ATCH-067 | Pending attachments are listed | An SDK MUST let an app list the pending attachments the client holds that are not `complete`, each with its remote attachment and its status. | An app cannot restart uploads it cannot find. | | ATCH-068 | Pending attachments expire | When a pending attachment was created more than the app’s `max_pending_age_seconds` ago, or 86400 seconds when the app sets none, and no upload of it holds an unexpired lease (ATCH-074), the client MUST NOT list or return it, and MUST delete its staged ciphertext, if any, and its record at the next client creation. While the client runs, unless the app disabled its background workers or its attachment cleanup worker, the client MUST also delete them within 3600 seconds. The client MUST NOT delete a pending attachment’s record or staged ciphertext while an upload of it holds an unexpired lease. | Staged ciphertext that nobody uploads occupies its size on the device for ever. | | ATCH-039 | Bounded memory | While the client creates a pending attachment from a path, uploads it, or downloads an attachment, the memory it has allocated for that attachment’s plaintext and ciphertext MUST NOT exceed 1048576 bytes at any moment. | Attachments are as large as 4 GiB; a client that holds one in memory ends a mobile app. | ## 5. Local files The client stores plaintext files in the attachments directory, one directory for each attachment key. The attachment key is derived from the fields of the remote attachment that determine the plaintext, so an app finds the file for any message from the remote attachment alone, and a remote attachment that reuses another message’s digest with other key material does not resolve to that message’s file. The file name is the sender’s filename, made safe for every file system the client runs on. The client keeps a record of each local attachment: its path relative to the attachments directory and when the client stored it. The record holds no attachment content; the remote attachment itself is already stored with its message. The record lets an app list what the client has stored without scanning the directory. A local attachment has no expiry: it stays until the app deletes it. An app gives the client one data directory, or, as an advanced option, a database path and an attachments directory. With a data directory, everything the client stores for an inbox on one deployment is under one directory named by the deployment and the inbox id, so an app removes an account by removing that directory, and one inbox can use two deployments from one data directory. The data directory also records which deployment answered at each backend URL, so a client created offline finds its database without a request. ```webidl enum StorageLayout { "data_dir", "explicit" }; dictionary StorageLocation { required StorageLayout layout; // "data_dir": data_dir is present; "explicit": db_path and attachments_dir are present DOMString data_dir; DOMString db_path; DOMString attachments_dir; }; dictionary LocalAttachment { required DOMString path; // relative to the attachments directory: {attachment key}/{local file name} required long long created_at_ns; // when the client made the file readable, in nanoseconds since the Unix epoch }; ``` The local file name is the result of these steps, applied in order to the remote attachment’s `filename`: | Step | Rule | | ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 1 | When `filename` is absent, the name is `attachment`, and the remaining steps are skipped. | | 2 | Keep the characters after the last `/` or `\`. | | 3 | Remove every character in U+0000 to U+001F, U+007F to U+009F, U+202A to U+202E, U+2066 to U+2069, and `<`, `>`, `:`, `"`, `\|`, `?`, `*`. | | 4 | Remove leading `.` and space characters, and trailing `.` and space characters. | | 5 | When the part before the first `.` equals, ignoring ASCII case, `CON`, `PRN`, `AUX`, `NUL`, `CONIN$`, `CONOUT$`, or `COM` or `LPT` followed by one of `1` to `9`, `¹`, `²`, `³`, prefix the name with `_`. | | 6 | While the UTF-8 encoding is longer than 255 bytes, remove the last character before the last `.`; when there is no `.`, or nothing remains before it, remove the last character. | | 7 | Apply step 4 again. | | 8 | When the name is empty, it is `attachment`. | | ID | Title | Requirement | Why | | -------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ATCH-040 | Data directory layout | When a client is created with a `data_dir` `StorageLocation`, it MUST store every file whose path it controls for the inbox under `{data_dir}/{deployment}/{inbox_id}/`, and MUST name a database that a platform store keeps elsewhere by the path it would have there and MUST use `{data_dir}/{deployment}/{inbox_id}/attachments` as the attachments directory. The `deployment` component MUST be the deployment identifier the database is bound to under CONF-030 after the file name table’s steps 2 to 8, with step 6 truncating to 190 bytes, and ASCII lowercasing, followed by `-` and the 64 lowercase hexadecimal characters of the SHA-256 of the identifier’s UTF-8 bytes; `inbox_id` MUST be the inbox id in lowercase hexadecimal. | Two deployments’ databases for one inbox would share one path, and CONF-030 would stop the second for good; an app that removes an account’s directory would leave plaintext behind. | | ATCH-069 | Deployment directory lookup | When an SDK resolves the deployment identifier for the `deployment` component of ATCH-040 for a backend URL, it MUST use the identifier the data directory records for that URL without sending a request, and only when it records none, MUST send `GetConfiguration` to that URL under CONF-062 and use its `identifier`. When the app creates the client offline under CONF-034 and the data directory records no identifier for that URL, the SDK MUST NOT send a request and MUST fail client creation with a storage-location error; an app that must start offline before its first connection uses an explicit location. After each `GetConfiguration` answer that the client stores under CONF-026, CONF-033, or CONF-040 for a data directory, the SDK MUST record its `identifier` for that backend URL. | A client created offline would not find its database, and one that fetched on every start could not start offline at all (CONF-034). | | ATCH-080 | Explicit layout | When a client is created with an `explicit` `StorageLocation`, it MUST open the database at `db_path` and use `attachments_dir` as the attachments directory, without sending a request and without requiring the inbox id; ATCH-040 and ATCH-069 do not apply to it. | An app that manages its own paths, or restores a cached identity, must not depend on the network or on a known inbox id to open its database. | | ATCH-082 | Complete storage location | When a client is created with a `StorageLocation` whose `layout` is `data_dir` and that has no `data_dir`, or whose `layout` is `explicit` and that lacks `db_path` or `attachments_dir`, client creation MUST fail with a storage-location error before the client opens or creates any path. | A client that guessed a missing path would store the database or plaintext files where the app does not expect them. | | ATCH-048 | Browser storage | Where the client runs in a browser, it MUST resolve every path of a `StorageLocation` and every path this section derives as an entry of the origin private file system. | | | ATCH-049 | Staged ciphertext location | The client MUST store every staged ciphertext under the attachments directory, outside every attachment key directory. | An app that removes the attachments directory would leave ciphertext behind; one that lists a key directory would find a second file. | | ATCH-077 | Private local files | Where the platform and the file system support POSIX file permissions, the client MUST create every directory and file it writes under the attachments directory, including staged ciphertext and partial files, and every directory it creates for a `data_dir` location (ATCH-040), including the `data_dir` directory itself when it is missing, and the record of deployment identifiers, with access for the owning user only: mode `0700` for a directory and `0600` for a file. | On a shared host, another local user would read decrypted attachments that the encrypted database does not expose. | | ATCH-041 | Attachment key | The client MUST set the attachment key of a remote attachment to the lowercase hexadecimal SHA-256 of the 108-byte string made of the raw bytes, not their text encodings, of its 32-byte content digest, its 32-byte `secret`, its 32-byte `salt`, and its 12-byte `nonce`, in that order. | A key from the URL alone lets a sender who reuses another message’s URL point the recipient at that message’s file. | | ATCH-042 | Local file name | The client MUST derive the local file name of a remote attachment by the steps of the file name table above. | A name that differs between client versions loses every file stored before the upgrade; an unsanitized name writes outside the attachments directory. | | ATCH-043 | Plaintext path and content | The client MUST store the plaintext file of a remote attachment at `{attachments directory}/{attachment key}/{local file name}`, holding exactly the `content` of the decrypted `xmtp.org/attachment:1.0` encoded content. | | | ATCH-044 | Path without I/O | An SDK MUST let an app derive the plaintext path of a remote attachment from the client and the remote attachment alone, without a request and without reading a file. | An app that renders a list of messages cannot make a call per row to find its files. | | ATCH-045 | An existing file is not an error | When creation or a download finds a file at the plaintext path, the client MUST NOT fail because of it. | | | ATCH-046 | Files are the app’s to delete | The client MUST NOT delete a plaintext file or an attachment key directory, except when an app asks it to under ATCH-047 or requests native client storage deletion under STORE-018, and except a partial file of a creation or download that did not succeed. | An app that shows a file the client removed shows a broken attachment. | | ATCH-047 | Local deletion | When an app asks the client to delete the local files of a remote attachment, the client MUST end each running upload of its content digest and each download that this client runs to a plaintext path under its attachment key directory as `failed` with the cause `deleted`, and then delete its attachment key directory, its staged ciphertext, its pending attachment record, and every local attachment record whose path is under that attachment key directory. The deletion MUST also end a download to a plaintext path under that directory that starts in this client while the deletion runs. An upload of that content digest that another client on the same database runs MUST end as `failed` with the cause `deleted` no later than its next lease extension or its outcome, when it finds the record gone. | A running download that completes after the deletion puts the file back; a record left for a file the deletion removed lists an attachment the app cannot open. | | ATCH-062 | Local attachments are listed | An SDK MUST let an app list the local attachments of a client as `LocalAttachment` values, with one entry for each local attachment and no other. | An app that cannot list what the client stored cannot apply its own storage limits without scanning the directory. | | ATCH-063 | Records follow the files | The client MUST add the local attachment record right after it makes a plaintext file readable under ATCH-032 or ATCH-051, and MUST remove the record right after it deletes the file under ATCH-047. | A record without a file lists an attachment the app cannot open; a file without a record is never cleaned up. | | ATCH-076 | Crash recovery of local files | At each client creation, before it lists local or pending attachments or answers a download, the client MUST add a local attachment record, with `created_at_ns` from the file’s modification time, for each plaintext file under an attachment key directory that has none; MUST remove each local attachment record whose file is missing; and MUST delete each staged ciphertext that has no pending attachment record and was last modified more than 3600 seconds ago, or more than the pending attachment age of ATCH-068 when that is shorter, and each staged ciphertext whose record is `complete`. It MUST NOT delete a plaintext file (ATCH-046). | A process that ends between a file operation and its record leaves a file that no listing shows, or a record for a file the app cannot open; a staged file with no record is never uploaded or released. | ## 6. Downloads A download takes a remote attachment from any sender and any host. The client downloads only when an app asks; it never downloads an attachment on its own. The URL is chosen by the sender, so it is untrusted. The client fetches only secure URLs, and by default only public addresses. Where it follows redirects itself, it checks each redirect as it checks the first URL. It stops at a size bound measured after content decoding. The plaintext file appears at its path only after the digest, the authentication tag, and the content type all pass, so a file at a plaintext path is always a complete, verified attachment. A download that returns `not_found` can succeed later. Under optimistic sending, a recipient can ask for an object before its sender’s upload completes. A private address is an address in an entry of the [IANA IPv4 Special-Purpose Address Registry](https://www.iana.org/assignments/iana-ipv4-special-registry/) or the [IANA IPv6 Special-Purpose Address Registry](https://www.iana.org/assignments/iana-ipv6-special-registry/) ([RFC 6890 §2.2](https://www.rfc-editor.org/rfc/rfc6890#section-2.2)) whose “Globally Reachable” value is `False` or `N/A`, a multicast address, or an IPv4-mapped or NAT64 IPv6 address whose embedded IPv4 address is private. A NAT64 IPv6 address is an address under `64:ff9b::/96` or `64:ff9b:1::/48`, or, where the client looks up a host or connects to an IPv6 literal itself, under a prefix that the client finds in the answer for `ipv4only.arpa` ([RFC 7050 §3](https://www.rfc-editor.org/rfc/rfc7050#section-3)) when it checks the address; its embedded IPv4 address sits where [RFC 6052 §2.2](https://www.rfc-editor.org/rfc/rfc6052#section-2.2) places it for that prefix length. ```webidl dictionary AttachmentOptions { unsigned long long max_download_bytes; // absent: ATCH-056 unsigned long long max_pending_age_seconds; // absent: ATCH-068 boolean allow_private_network; // absent means false }; ``` | ID | Title | Requirement | Why | | -------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ATCH-065 | Downloads are explicit | The client MUST NOT send a download request for a remote attachment except in a download an app asked for. | A client that fetches on receipt tells every download host, which the sender chose, the recipient’s network address and when the recipient was online. | | ATCH-050 | Any host | The client MUST download a remote attachment whose URL passes ATCH-053 whatever its host, whether or not the snapshot offers attachments, and MUST NOT require the URL to begin with the snapshot’s `base_url`. | Attachments sent by an app that stores its own files, or by another deployment, would not open. | | ATCH-051 | Verified before readable | The client MUST write a download’s plaintext outside every attachment key directory and MUST put a file at the path only by an atomic move, after the ciphertext passes the digest check and the decryption of CTYPE-015 and decodes as `xmtp.org/attachment:1.0` encoded content. A download that fails, or that the end of the process interrupts, MUST leave no file at the path. The client MUST NOT treat as `xmtp.org/attachment:1.0` encoded content an envelope whose `type` field, `mimeType` and `filename` parameter entries, and `compression` field together take more than 65536 serialized bytes. | A partial or forged file at the path is shown by every later reader as the attachment. The client holds these fields in memory while content streams to disk; no file name or MIME type approaches this size, and an unbounded one is a memory attack. | | ATCH-052 | Existing files are not fetched | When a download is asked for and a file is at the plaintext path, the client MUST return that path without sending a request. | | | ATCH-053 | Secure URLs only | The client MUST NOT send a download request to a URL whose scheme is not `https`, or, where it follows redirects itself, follow a redirect to one, except `http` to `localhost` or a loopback address while `allow_private_network` is true. | A plain-HTTP fetch shows every observer which attachment a user opens, and lets an observer replace the response. | | ATCH-054 | Private addresses | Where the client opens its own connections, it MUST NOT connect a download request, or a redirected request, to a private address while `allow_private_network` is false, and MUST check the address it connects to, not the host name. Where the client resolves the host itself and `allow_private_network` is false, it MUST end the download as `failed` with cause `blocked_address` when any address the lookup returns is private. Where the client opens its own connections, it MUST NOT send a download through a proxy. Where the client does not open its own connections, `allow_private_network` is false, and the parsed download URL host is `localhost`, `localhost.`, a name ending in `.localhost` or `.localhost.`, or an IP literal that is a private address as defined above, it MUST end the download as `failed` with cause `blocked_address` without sending a request. | A message whose URL names the cloud metadata address or an internal host makes a server-side client fetch it. A proxy could resolve the host to an address the client did not check. On a DNS64 network an internal name returns its private IPv4 address together with a synthesized IPv6 address that the client cannot recognize as private. A browser could fetch a private host that the sender put in the URL. | | ATCH-055 | Redirects are checked | Where the client follows redirects itself, it MUST follow at most 10 redirects for one download, apply ATCH-053 and ATCH-054 to each, and fail the download at the first redirect that fails either. Where the client does not follow redirects itself, it MUST NOT follow any redirect of a download and MUST end the download as `failed` with cause `too_many_redirects` on the redirect. In a browser, the client MUST set manual redirect handling on the fetch GET and MUST treat an opaque redirect as a redirect. | A redirect from a public host to a blocked one would bypass both rules. | | ATCH-056 | Download size bound | The client MUST fail a download, and stop reading, once the response body after content decoding is longer than the least of `content_length` when the remote attachment carries it, the app’s `max_download_bytes`, and the largest `contentLength` the CTYPE-014 parameters table admits. When the app sets no `max_download_bytes`, the client MUST use the snapshot’s `max_upload_bytes` under CONF-025, which is 104857600 when the snapshot does not offer attachments. | A hostile host that streams without end, or sends a small compressed body that inflates, fills the device’s storage. | | ATCH-057 | Success status | The client MUST read the ciphertext only from a final response with status 200, and MUST fail a download with `not_found` on a final 404 or 410 and with `http_status` on any other final status. | An app tells an object that is not yet stored, or no longer stored, from a failure of the host. | | ATCH-058 | One fetch per path | While a download to a plaintext path is running in a client, the client MUST end a second download to the same plaintext path with the running download’s outcome, and MUST NOT send a request for it. | Two downloads to one path race to write it and fetch the object twice. | | ATCH-059 | Malformed key material | If a remote attachment’s `content_digest` is not 64 lowercase hexadecimal characters, its `secret` or `salt` is not 32 bytes, or its `nonce` is not 12 bytes, then the client MUST fail a download of it and a derivation of its plaintext path with the cause `malformed`, without sending a request. | The attachment key and the path are undefined for such a remote attachment. | ## 7. Failures An SDK reports every attachment failure with one cause from a fixed set, so an app can tell a failure it can retry from one it cannot. The same cause appears in the `attachment.upload_failed` and `attachment.download_failed` events. ```webidl enum AttachmentFailureCause { "not_offered", // ATCH-030: the snapshot does not offer attachments "too_large", // ATCH-030, ATCH-056 "source_unreadable", // creation could not read the path "local_storage", // the client could not write or read the attachments directory or its records "staged_unusable", // ATCH-036, ATCH-038 "connection_blocked", // ATCH-026 "credential", // CreateUpload failed with a client credential failure of AUTH section 6 (ATCH-061), or with PERMISSION_DENIED (ATCH-078) "backend_rejected", // CreateUpload failed with INVALID_ARGUMENT, OUT_OF_RANGE, or UNIMPLEMENTED "backend_unavailable", // CreateUpload failed with any other code, or did not reach the backend "target_rejected", // the CreateUpload response names a method other than PUT, the upload PUT received a redirect, or the storage target answered a status other than 2xx or 412 "network", // ATCH-070, or a request to a storage target or download host failed in transport "insecure_url", // ATCH-053 for a download, or ATCH-071 for an upload PUT "blocked_address", // ATCH-054 "too_many_redirects", // ATCH-055: over 10 followed redirects or any redirect under manual handling "not_found", // ATCH-057 "http_status", // ATCH-057 "malformed", // ATCH-059, ATCH-072 "digest_mismatch", // ATCH-051: the ciphertext does not match content_digest "decryption_failed", // ATCH-051: the tag does not verify "not_an_attachment", // ATCH-051: the plaintext is not xmtp.org/attachment:1.0 encoded content "deleted" // ATCH-047 }; ``` The cause tells an app when a later attempt can succeed: | Cause | A later attempt can succeed | | -------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | | `not_offered` | After the deployment offers attachments | | `too_large`, `staged_unusable`, `backend_rejected`, `too_many_redirects`, `malformed`, `digest_mismatch`, `decryption_failed`, `not_an_attachment` | No. The same input fails again | | `source_unreadable` | After the app makes the source readable | | `local_storage` | Yes, when the device has space and the directory is writable | | `connection_blocked` | After the client is updated or bound to its deployment again (CONF-075) | | `credential` | After the app renews the credential of the kind ATCH-061 reports, or supplies one that carries the required scopes (ATCH-078) | | `backend_unavailable` | Yes, after a backoff; after `FAILED_PRECONDITION` or `INTERNAL`, only when the operator has corrected the backend | | `network` | Yes, after a backoff | | `http_status` | After a backoff when the status is 408, 429, or 5xx; otherwise no | | `target_rejected` | Yes, for a new upload request, which gets a new signed URL; a target that rejects every signed request fails again | | `blocked_address` | After the app sets `allow_private_network`; otherwise no | | `insecure_url` for a download | Only when the URL is `http` to `localhost` or a loopback address and the app sets `allow_private_network`; otherwise no | | `insecure_url` for an upload | No. The backend signed a URL that ATCH-071 forbids; it fails again until the operator fixes the storage endpoint | | `not_found` | Yes, while the sender has not completed the upload; no, after the target has deleted the object (ATCH-004) | | `deleted` | Yes. The app can download again | | ID | Title | Requirement | Why | | -------- | ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | ATCH-060 | Typed failure causes | An SDK MUST report a failed creation, upload, download, or path derivation as an error that carries exactly one `AttachmentFailureCause`, the one whose comment in the block above names the failure. | An app that cannot tell `not_found` from `network` retries an expired object for ever, or gives up on a transient one. | | ATCH-061 | Credential failures keep their kind | When an upload fails with a client credential failure of AUTH section 6, an SDK MUST report the cause `credential` together with the failure kind AUTH-026 names and whether it is retryable. | An app that sees only an upload failure cannot tell a lockout that clears from a credential it must replace. | | ATCH-078 | Missing scope | When `CreateUpload` answers `PERMISSION_DENIED`, the client MUST end the upload as `failed` with the cause `credential`, marked as a missing scope (AUTH-013) that retrying with the same credential cannot cure, and MUST NOT record it under ATCH-029. | An app that reads a scope rejection as a transient outage retries for ever; one that records it as a permanent rejection cannot upload after it obtains a credential with the scope. | | ATCH-079 | HTTP status is kept | When an upload or download fails with the cause `http_status` or `target_rejected` after the host answered, an SDK MUST report the final HTTP status code with the failure. Where the client does not follow redirects itself and the platform reports a redirect answer without its status, the SDK MUST report that failure without a status. | An app that cannot see the status cannot tell a 503 it can retry from a 403 it cannot. | | ATCH-070 | Transfer deadlines | Where the client opens its own connections, it MUST use a 30 s connect timeout for an upload PUT and a download GET, and MUST end the upload or download as `failed` with cause `network` when that timeout expires. Where the client opens its own connections and no bytes are sent or received for 60 s during an upload PUT, it MUST end the upload as `failed` with cause `network`; where the client can observe response reads and no response bytes are read for 60 s during a download GET, it MUST end the download as `failed` with cause `network`. The client MUST NOT apply a total-time cap to either request. | A stalled target or host would keep an upload `uploading` or a download joined under ATCH-058 forever. | ## Known limitations The upload contract is only as strong as the storage target. ATCH-023 depends on a target that enforces what the backend signs (ATCH-007). A target that enforces neither a signed SHA-256 nor a create-only precondition, such as Google Cloud Storage through its XML API, is not a supported target. The client sends the upload PUT to whatever `https` URL, or loopback `http` URL, the backend it is bound to (CONF-030) signs, including a private address, so an on-premises storage target works. A backend that the operator does not control could direct a client’s PUT at an internal host; the body is ciphertext and carries no credential (ATCH-027), and ATCH-071 stops redirects. The client already trusts that backend with its messages. When auth is disabled (AUTH-003), anyone who can reach the backend can store objects up to `max_upload_bytes`. When auth is enabled, any holder of a credential can. The backend cannot tell a ciphertext from any other bytes, so a deployment’s storage can be used to host arbitrary files. RATE limits how many uploads a caller may create (`upload`), not how many bytes it stores. An object is public to anyone who has its URL. Its confidentiality rests on the encryption of CTYPE-015 alone. The storage target and every download host learn the size of the object, the time of each fetch, and the network address of the downloader. The backend does not apply retention. The operator’s expiry rule on the storage target does, and ATCH-005 cannot be checked by a client. The client does not read retention: it attempts every download an app asks for, and an expired object fails with `not_found`. A remote attachment forwarded unchanged in another message shares its plaintext path, and one that carries the same key material with another `filename` shares its attachment key directory, so deleting the local files for one message deletes them for both, and the next download fetches them again. A failed upload or download starts again from the first byte. There is no multipart or ranged transfer, and the largest single upload is bounded by the target’s own limit on one PUT as well as by `max_upload_bytes`. A host that sends a byte at least every 60 s can keep a download, and every download joined to it under ATCH-058, running up to the ATCH-056 size bound. The app can end the download under ATCH-047. In a browser, the SQLite store keeps every database in one origin-private pool, so the client names the inbox’s database by its `{data_dir}/{deployment}/{inbox_id}/` path but cannot place it in that directory. An app that removes the directory also removes the attachments but not the database. In a browser, ATCH-054 rejects `localhost` names and private IP literals in a download URL while `allow_private_network` is false. The client cannot check the address to which another hostname resolves before the browser connects; the browser’s private-network rules apply to those hostnames. ATCH-055 ends the download on every redirect, including an opaque redirect. A browser client cannot set a connect timeout or observe upload progress of a fetch PUT, so its PUT has no deadline beyond the browser’s own. The client can observe response reads of a download GET and applies ATCH-070 to them. A download host that sends no CORS headers cannot serve a browser client. Each client emits the `attachment.*` events only for the changes it makes. A second client on the same database, such as an app and its notification extension, reads the recorded status of a pending attachment but receives no event for an upload that the other client runs. The upload lease depends on the device clock and on a running process: a clock that jumps forward, or a platform that suspends the process for more than 120 seconds, expires a running upload’s lease, so a second upload of the same object can start. The first upload then leaves the record to the second (ATCH-074), and when both PUTs reach the target, the create-only precondition (ATCH-023) ends one of them with 412. A deletion ends only the downloads that the deleting client runs. A download of the same remote attachment that another client on the same database runs can complete after the deletion and put the plaintext file and its local attachment record back (ATCH-051, ATCH-063); the app can delete the local files again after that download ends. The client follows symbolic links in the paths the app supplies, including a data directory, an attachments directory, and their parents, so a user who can change one of those paths can redirect the client’s files; the app supplies paths that other users cannot change. The client does not change the permissions of an attachments directory the app supplies; an app that supplies one that other local users can write gives them control of the files below it, but not of files outside it: where ATCH-077 applies, the client does not follow a symbolic link below the attachments directory, so a planted link fails the operation with `local_storage`. A managed directory below the attachments directory that already exists and that another user owns fails with `local_storage` (ATCH-077), so a file system that reports a fixed owner for every file, such as Android shared storage or some network mounts, cannot hold a client-managed attachments directory; app-private storage is not affected. A browser reports a redirect answer to a fetch with manual redirect handling as an opaque redirect without its status, so a browser upload that ends on a redirect fails with `target_rejected` and no status. On a file system without POSIX permissions, such as NTFS on Windows, ATCH-077 does not apply: the files the client writes inherit the access control list of the directory the app supplies. An app keeps attachments private to its user by placing the data directory or attachments directory under that user’s profile, such as `%LOCALAPPDATA%`, whose inherited access list grants only that user, administrators, and the system. Two processes that share a data directory can each record a deployment identifier at the same time, and one record can be lost; the next online start records it again, and until then an offline start for that backend fails with a storage-location error. Clients in separate processes, or in separate browser workers, that share one attachments directory do not coordinate creation, reconciliation, deletion, and downloads with each other. Reconciliation in one can record a plaintext file that deletion in another is removing, and deletion in one does not wait for a download that another is running. Reconciliation in one can also record the plaintext file of a creation that another then cancels. The cancelled creation removes its file, and the record stays until the next client creation removes it (ATCH-076). In a browser, a lock that all workers of the origin share stops two moves to one path from replacing each other; it does not cover reconciliation, deletion, or downloads. An app that runs clients in more than one process on one directory serializes deletion itself. A deletion ends a running upload of the content digest before it removes the pending attachment record (ATCH-047). If the deletion fails after that point, the request that the upload served has already ended with the cause `deleted`, but the record stays. The record reads as `waiting` when the upload lease expires (ATCH-074), and the app can upload or delete again. This needs a failure of the local database or file system during the deletion. When creation finds a staged ciphertext at its path whose SHA-256 is not its content digest, it replaces that file. It does this also while an upload of that digest in another client on the same database holds the upload lease (ATCH-074), and that upload then reads the new file. Each creation has a new secret, salt, and nonce (CTYPE-015), so this needs two ciphertexts with the same SHA-256, or damage to the staged file from outside the client, which makes that upload fail in any case (ATCH-036). If the deployment record file cannot be parsed, the client treats it as empty and rewrites it at the next record. Until an online start records a backend again, an offline start for that backend fails with a storage-location error. A client whose app disables background workers, or the attachment cleanup worker, removes expired pending attachments only at the next client creation (ATCH-068), so their staged ciphertext stays on the device until then. A file that an app removes from the attachments directory without asking the client leaves its record behind until the next client creation, or until the app asks the client to delete the local files of that remote attachment. The client learns a NAT64 prefix other than `64:ff9b::/96` and `64:ff9b:1::/48` only from the answer for `ipv4only.arpa`. When that lookup fails, takes longer than 5 seconds, or the network’s DNS64 does not synthesize that name, an address under the network’s own prefix that embeds a private IPv4 address is treated as public. A host whose lookup also returns the private IPv4 address still fails as `blocked_address`. In a browser the client does not look up `ipv4only.arpa`. # Backend auth Authentication is optional per deployment. While it is enabled, every request outside a small public set carries a bearer credential: a named API key the operator issued, or a JWT signed by a key the deployment trusts. The client obtains credentials from a source the app supplies, attaches one to every request, refreshes it when it expires or is rejected, and stops after repeated failures. This spec owns both sides of that exchange, the checks an enabled configuration must pass before the backend serves, and the failure vocabulary between them. Getting the terminal cases wrong strands a client in a retry loop it can never leave, or lets a broken credential source hit the backend at the client’s full request rate. ```mermaid flowchart TD R[Request] --> P{Public path or preflight} P -->|yes| S[Serve] P -->|no| E{auth.enabled} E -->|false| S E -->|true| B{Bearer token present} B -->|no| U[UNAUTHENTICATED] B -->|yes| K{Digest equals an API key} K -->|yes| S K -->|no| J{JWT source configured} J -->|no| U J -->|yes| V[Select one key, verify signature, validate claims] V -->|scope missing| D[PERMISSION_DENIED] V -->|other failure| U V -->|accepted| S ``` ## Scope In scope: which paths need a credential and which never do; the bearer form; how an API key is matched; how a JWT is verified, including the accepted algorithms, key selection, the claim types, and the time, audience, issuer, and scope claims; how the key set is loaded, refreshed, bounded, and retired; the checks of an enabled `[auth]` table that this spec’s rows state; the rejection vocabulary; how the client obtains, attaches, refreshes, and replaces a credential; when the client stops trying; and what the backend records about a credential. Out of scope: the types, presence, and standard checks of the `[auth]` keys, the presence rule for `auth.enabled`, and what is published about auth (`CONF`); the general status code table ([API section 7](/specs/api-backend-api/#7-bounds-errors-and-transport)); what an operator’s identity provider does; and the metric families themselves (`OPS`). | Related | Relation | | ---------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `CONF` | Owns whether an `[auth]` table must state `enabled` (CONF-005), that the values of a disabled table are not checked (CONF-066), the published auth summary (CONF-068), the unauthenticated configuration read (CONF-010, CONF-029), and the deployment identifier (CONF-002). This spec owns the checks of an enabled table that its rows state. CONF section 1.2 owns the types, presence, and standard checks of every `[auth]` key. | | [API section 7](/specs/api-backend-api/#7-bounds-errors-and-transport) | Owns general gRPC status codes. This spec owns the auth-specific `UNAUTHENTICATED` and `PERMISSION_DENIED` conditions under AUTH-014. | | `OPS` | Owns the metric catalogue, including `xmtp_auth_rejections_total` (OPS-017), and the drain that AUTH-019 triggers (OPS-007, OPS-008). This spec owns the reason vocabulary. | | `EVENT` | EVENT-001 reports entry to and exit from credential lockout. | ## Terms | Term | Meaning | | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Credential | The value of the `authorization` request header: the scheme `Bearer`, one space, and a token. | | Token | The part of a credential after the scheme: an API key value or a JWT. | | API key | A name and a secret value the operator configures under `auth.api_keys`. | | JWT | A JSON Web Token in compact serialization, signed as a JWS ([RFC 7519 §3](https://www.rfc-editor.org/rfc/rfc7519.html#section-3)). | | Signing key source | Where the backend gets the public keys it verifies JWTs with: keys inline under `auth.keys`, or a JWKS document at `auth.jwks_url`. | | Key set | The signing keys the backend holds at one moment. | | Public path | A request path that begins with `/grpc.health.v1.` or `/xmtp.backend.v1.ConfigurationService/`. | | Principal | What a request is admitted as: an API key’s name, or a JWT’s verified claims. | | Reason | One of the fixed labels in the rejection table of section 4. | | Leeway | The configured `auth.leeway_seconds`, default 60: the clock skew the time claims tolerate. | | Now | The verifier’s current time, in seconds since the Unix epoch. | | Credential source | The callback or fixed credential an app gives a client, as in `CONF`. A callback returns a held credential on demand; a fixed credential is set by the app and used until the app sets another. | | Held credential | The record a client keeps between requests: the header to send, its value, and when it expires. Defined in section 6. | | Attempt | One request the client sends with a held credential, or one invocation of the callback. | | Lockout | The state a client enters after 13 consecutive failed attempts, held for a 60-second cool-down. | ## 1. Admission Admission is decided by the request path before the request body is read. While auth is enabled, a request to any path outside the public set needs a credential the backend accepts, including a path no service implements. While auth is disabled, the `authorization` header is not read at all, so a deployment on a trusted network serves any caller. Health is public so that an orchestrator can probe the process, and the configuration service is public so that a client can learn what the deployment requires before it holds a credential (CONF-010). A CORS preflight is answered before admission, because a browser sends it without credentials. A stream is admitted once, when it opens. Nothing that happens to the credential later ends it. | ID | Title | Requirement | Why | | -------- | ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | AUTH-001 | Enabled admission by path | While the configured `auth.enabled` is `true`, when a request to a path that is not a public path carries no credential, or a credential the backend does not accept under section 2 or section 3, the backend MUST reject it with the status and reason the rejection table in section 4 gives, before it validates the request body, whatever the HTTP method, content type, or path. | An unknown path admitted without a credential is the one path an attacker probes, and a validation error returned first tells the caller about the payload before the caller has proven anything. | | AUTH-002 | Health and preflight are public | Whatever `auth.enabled`, the backend MUST serve a request to a public path that begins with `/grpc.health.v1.` and MUST answer a CORS preflight request without reading the `authorization` header. | An orchestrator holds no credential, and a browser sends the preflight before it can attach one. | | AUTH-003 | Disabled admission | While `auth.enabled` is `false` or the configuration has no `[auth]` table, the backend MUST serve every request without reading the `authorization` header. | | | AUTH-004 | Streams are checked at open | When the backend has admitted a `Subscribe` or `SubscribeStatic` request, it MUST NOT end that stream because the credential’s `exp` has passed, because the key set no longer holds the key that signed it, or because a later request from the same caller was rejected. | A client holds a stream open for hours on a token that lives minutes; ending it at every expiry forces a reconnect storm at the token lifetime. | | AUTH-005 | Bearer form | The backend MUST accept a credential only as an `authorization` header whose value is the scheme `Bearer`, compared without regard to case, one space, and a token that is not empty after trimming whitespace and is at most 8192 bytes; any other value MUST be rejected with reason `malformed`. | | ## 2. API keys An API key is a shared secret an operator hands to a caller it runs itself, such as a bot or a bridge. It is checked before any JWT work, so its value does not have to look like a JWT, and it carries no scopes: the required scopes apply to JWTs only. The match compares SHA-256 digests in constant time, so response timing does not depend on how much of a key a caller guessed. An enabled table must name at least one mechanism, and a key value must be a usable secret: long enough that it cannot be guessed, made of bytes a header can carry, and distinct from every other key so that the recorded principal is unambiguous. CONF section 1.2 states the name syntax, the map layout, and the number of keys a table may hold. | ID | Title | Requirement | Why | | -------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | AUTH-006 | API key admits by digest | When the SHA-256 digest of the token equals the SHA-256 digest of a configured API key value, the backend MUST admit the request with that key’s name as its principal and MUST NOT apply the scope, audience, or issuer checks of section 3. The comparison MUST take the same time over every configured key whichever key matches, and whether or not one does. | A comparison that stops at the first differing byte lets a caller recover a key from response timing, one byte at a time. | | AUTH-007 | A miss falls through | When the token matches no API key, the backend MUST verify it as a JWT under section 3 where a signing key source is configured, and MUST reject it with reason `untrusted` where none is. | | | AUTH-029 | Enabled auth names a mechanism | When `auth.enabled` is `true` and the table configures none of `api_keys`, `jwks_url`, or `keys`, or configures both `jwks_url` and `keys`, the backend MUST refuse to start and MUST name the offending key. | A deployment that enables auth with nothing to check against rejects every caller while its operator believes it is protected. | | AUTH-030 | API key values are usable secrets | When `auth.enabled` is `true` and an API key value is shorter than 32 bytes, longer than 8192 bytes, contains a byte outside `0x21` to `0x7E`, or equals another key’s value, the backend MUST refuse to start, naming the key’s name and not its value. | A short key is guessable by every caller; a value with whitespace or control bytes cannot be sent as a header; two names with one value make the recorded principal a coin toss. | ## 3. JWT verification A JWT is accepted when a key in the key set verifies its signature and its claims pass the configured checks. The backend decodes the token’s syntax first, so a token that is not a JWS with a JSON object of claims is `malformed` whatever else is wrong with it. It then selects exactly one key before it verifies anything: by `kid` when the token names one, otherwise by algorithm. It never tries a second key and never fetches keys while a request waits. No claim value affects admission until the signature has verified, because a claim trusted first is a claim the attacker wrote. The verified claims are then checked in a fixed order, so a caller fixing a token gets one stable answer. The JOSE header, the signature, and the registered claims are defined by [RFC 7515 §4](https://www.rfc-editor.org/rfc/rfc7515.html#section-4), [RFC 7515 §5.2](https://www.rfc-editor.org/rfc/rfc7515.html#section-5.2), and [RFC 7519 §4](https://www.rfc-editor.org/rfc/rfc7519.html#section-4). This spec states only what the backend adds: which algorithms it accepts, how it picks a key, which claim types it accepts, which claims it requires, and what the `scope` claim must hold. | ID | Title | Requirement | Why | | -------- | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | AUTH-008 | Supported algorithms | The backend MUST accept a JWT only when its header `alg` is `RS256`, `RS384`, `RS512`, `ES256`, `ES384` ([RFC 7518 §3.1](https://www.rfc-editor.org/rfc/rfc7518.html#section-3.1)), or `EdDSA` ([RFC 8037 §3.1](https://www.rfc-editor.org/rfc/rfc8037.html#section-3.1)), and MUST reject any other value, including `none` and every HMAC algorithm, with reason `unsupported_alg`. | An HMAC algorithm verified against a public key makes that public key the signing secret. | | AUTH-009 | One key, selected first | Before it verifies a signature, the backend MUST select exactly one key from the key set: when the header carries `kid`, the one key with that `kid`; otherwise the one key whose algorithm equals `alg`. When no key or more than one key matches, or the selected key’s algorithm differs from `alg`, the backend MUST reject the token with reason `untrusted`, and MUST NOT try another key or fetch keys during the request. | Trying every key makes each request a signature oracle over the whole set, and a fetch during a request lets a slow key server stall admission. | | AUTH-010 | Signature before trusting claims | The backend MUST verify the JWS signature under the selected key before any claim value affects admission, the principal, or the reason it reports, other than `malformed` for a claims segment that is not a JSON object, and MUST reject a token whose signature does not verify with reason `untrusted`. | | | AUTH-031 | Claim types | The backend MUST accept `exp` and `nbf` only as a NumericDate ([RFC 7519 §2](https://www.rfc-editor.org/rfc/rfc7519.html#section-2)) that is a finite JSON number not less than 0, rounding a fractional part to the nearest second; `aud` and `scope` only as a string or an array of strings; and `iss` and `sub` only as a string. A claim that is present with any other type MUST be rejected with reason `malformed`. | A claim of the wrong type reported as expired or missing sends the caller to fix its clock instead of its issuer. | | AUTH-011 | Time claims | The backend MUST reject a token with no `exp` claim, or whose `exp` is less than now minus the leeway, with reason `expired`, and a token whose `nbf` is greater than now plus the leeway with reason `not_yet_valid`. | | | AUTH-012 | Audience and issuer | Where `auth.audiences` is configured, the backend MUST reject a token whose `aud` claim contains none of the configured values with reason `audience`. Where `auth.issuers` is configured, it MUST reject a token whose `iss` claim equals none of the configured values with reason `issuer`. A token without the claim fails the check. | | | AUTH-013 | Required scopes | When any value in `auth.required_scopes` is absent from the token’s `scope` claim, read as a space-separated string or an array of strings, the backend MUST reject the request with reason `scope`, on every path that is not a public path. | | | AUTH-032 | Leeway ceiling | When the configured `auth.leeway_seconds` is greater than 300 and `auth.enabled` is `true`, the backend MUST refuse to start and MUST name the key. | Leeway extends every token’s life; an unbounded value makes `exp` meaningless. | ## 4. Rejections Every rejection carries a fixed reason. The reason selects the status and the message the caller sees and the label the backend counts under. The table is in processing order: the header, the token’s syntax, the key, the signature, then the verified claims. When more than one reason applies, the earliest stage wins. | Reason | Status | Message | Given when | | ----------------- | ------------------- | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | | `missing` | `UNAUTHENTICATED` | `missing bearer token` | The request has no `authorization` header. | | `malformed` | `UNAUTHENTICATED` | `authorization header is not a bearer token` | The header fails the scheme or empty-token part of AUTH-005. | | `malformed` | `UNAUTHENTICATED` | `token is not a supported JWT` | The token is longer than 8192 bytes, or its JOSE header does not decode as a JSON object with a string `alg`. | | `unsupported_alg` | `UNAUTHENTICATED` | `token is not a supported JWT` | AUTH-008. | | `malformed` | `UNAUTHENTICATED` | `token is not a supported JWT` | The header’s `kid` is longer than 256 bytes, or the claims segment does not decode as a JSON object. | | `untrusted` | `UNAUTHENTICATED` | `token signature is not trusted` | AUTH-007, AUTH-009, or AUTH-010. | | `expired` | `UNAUTHENTICATED` | `token has expired` | AUTH-011, `exp`. | | `not_yet_valid` | `UNAUTHENTICATED` | `token is not yet valid` | AUTH-011, `nbf`. | | `audience` | `UNAUTHENTICATED` | `token audience is not allowed` | AUTH-012, `aud`. | | `issuer` | `UNAUTHENTICATED` | `token issuer is not allowed` | AUTH-012, `iss`. | | `malformed` | `UNAUTHENTICATED` | `token is not a supported JWT` | AUTH-031, for a verified claim of the wrong type. | | `scope` | `PERMISSION_DENIED` | `token is missing a required scope` | AUTH-013. | | ID | Title | Requirement | Why | | -------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------- | | AUTH-014 | Rejection vocabulary | When the backend rejects a request under this spec, it MUST answer with the status and message the rejection table above gives for the reason, MUST count the reason as the `reason` label of `xmtp_auth_rejections_total` (OPS-017), and when more than one reason applies MUST use the one from the earliest stage in table order. | A status message that varies with the token’s contents is a channel for the token’s contents. | ## 5. The key set The backend loads its key set before it binds its listener, from inline keys or from a JWKS document ([RFC 7517 §5](https://www.rfc-editor.org/rfc/rfc7517.html#section-5)); the configuration names one source (AUTH-029). A JWKS is fetched again on a period, and a successful fetch replaces the whole set, so a key the identity provider withdraws stops verifying at the next refresh and one it adds starts. A failed fetch keeps the last successful set, so a transient outage of the key server does not log every caller out. That tolerance has a bound: after `auth.jwks_max_stale_seconds` without a successful fetch the backend stops serving rather than keep verifying against keys that may have been revoked, and the refresh timing must fit inside that window or a healthy deployment drains itself. Every fetch is bounded in time, size, and keys kept, so a slow or hostile key server cannot stall startup or exhaust the backend. The keys published in the auth summary are the ones loaded at startup (CONF-068); a refresh does not republish them (CONF-012). | ID | Title | Requirement | Why | | -------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | AUTH-015 | Key source transport | The backend MUST fetch a JWKS only over HTTPS, or over HTTP when the URL’s host is `localhost` or a loopback address, and MUST NOT follow a redirect. | A key set fetched over plain HTTP or through a redirect is a key set anyone on the path can replace. | | AUTH-016 | Usable JWKS entries | The backend MUST load from a JWKS only an entry whose `alg` is a value AUTH-008 accepts, whose `kty` and `crv` are the pair that algorithm needs (`RSA`; `EC` with `P-256` for `ES256` or `P-384` for `ES384`; `OKP` with `Ed25519`), whose `use` is absent or `sig`, and whose `kid`, when present, is a string of at most 256 bytes, and MUST skip every other entry. | An entry with no `alg` gives no way to fix the verification algorithm without letting the token choose it. | | AUTH-033 | Bounded key fetch | The backend MUST abandon a JWKS fetch that has not completed after 10 seconds, MUST NOT read more than 262144 bytes of its body, MUST keep at most the first 64 usable entries of one document, and MUST treat a fetch that exceeds the time or size bound as failed. | An unbounded fetch lets the key server hold the backend’s startup or its memory. | | AUTH-017 | Startup needs a key set | When `auth.enabled` is `true` and a JWKS URL is configured, and no usable entry has been loaded after 3 fetch attempts 1 second apart, the backend MUST refuse to start. When `auth.enabled` is `true` and an inline key is not a SubjectPublicKeyInfo of the key type its `alg` needs, or two inline keys share a `kid`, the backend MUST refuse to start. | A backend that serves with an empty key set rejects every JWT while reporting itself healthy. | | AUTH-018 | Refresh replaces the set | The backend MUST fetch the JWKS again every `auth.jwks_refresh_seconds` (default 300) plus a random delay of at most one tenth of that period, and when a fetch yields at least one usable entry MUST replace the whole key set with the fetched entries. When a fetch fails or yields no usable entry, the backend MUST keep the last successful set. | | | AUTH-034 | Refresh fits the stale window | When `auth.enabled` is `true` and the configured `auth.jwks_refresh_seconds` is less than 1, or `auth.jwks_max_stale_seconds` is less than `auth.jwks_refresh_seconds` plus one tenth of it, rounded up, plus 10, the backend MUST refuse to start and MUST name the key. | One refresh cycle, with its jitter and a fetch that runs to its timeout, must fit inside the stale window, or a deployment whose key server is healthy drains under AUTH-019. | | AUTH-019 | Stale key set stops serving | When `auth.jwks_max_stale_seconds` (default 3600) have passed since the last successful JWKS fetch, the backend MUST report `NOT_SERVING`, drain under OPS-007 and OPS-008, and exit with a failure status, and a fetch that completes after that deadline MUST NOT keep it serving. | A backend verifying against keys an hour old accepts tokens under keys the provider has revoked. | ## 6. Client credentials The app gives the client a credential source: a callback that returns a held credential with an expiry, a fixed credential the app sets through a handle, or both. The client attaches the held credential to every request except the configuration read (CONF-029), asks the callback for a new one when the held one has expired or was rejected, replays a rejected request once with the new credential, and gives up after 13 consecutive failed attempts. Only an `UNAUTHENTICATED` answer counts as a rejection of the credential; a `PERMISSION_DENIED` answer is returned to the caller, because a new token from the same source has the same scopes. The rules below apply in this order. The configuration read carries nothing and invokes nothing (CONF-029). A credential the app sets replaces whatever the client held and clears any lockout (AUTH-024). Lockout fails an attempt before any refresh or send (AUTH-023). Otherwise the client refreshes an expired or rejected credential before it sends (AUTH-021), and replays a rejected request once (AUTH-022). A replay is an attempt of its own: a request whose first send and replay are both rejected adds two failures. ```webidl dictionary HeldCredential { DOMString header_name; // absent means "authorization" required DOMString value; // the full header value, including the scheme required long long expires_at_seconds; // seconds since the Unix epoch }; ``` The failures a client reports are the four kinds below. Whether a kind is retryable depends on whether a callback exists: with a callback, a new credential may cure a rejection; without one, only the app can. | Kind | Meaning | Retryable | | ------------------- | ------------------------------------------------------------------------- | ------------------------------------------- | | Credential rejected | The backend answered `UNAUTHENTICATED` to the credential the client sent. | Only when a callback exists. | | Callback failed | The callback returned an error instead of a credential. | Yes. | | Exhausted | The client is in lockout, or this attempt put it there. | Not now; it clears when the cool-down ends. | | Missing credential | The client holds no credential and has no callback. | No. | | ID | Title | Requirement | Why | | -------- | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | AUTH-020 | Credential on every request | Where the app supplied a credential source, the client MUST send the held credential’s `value` in the header its `header_name` names, replacing any header of that name already on the request, on every request except `GetConfiguration`. | | | AUTH-021 | Refresh before use | When the client is about to send a request that carries a credential and it holds none, or the held credential’s `expires_at_seconds` is not greater than now, or the last attempt with the held credential was answered `UNAUTHENTICATED`, the client MUST obtain a new held credential from the callback before it sends, and MUST NOT run two invocations of the callback at once. When no callback exists, the client MUST send the held credential unchanged, or fail the request as `missing credential` when it holds none. | A callback invoked by every parallel request hits the identity provider once per request instead of once per expiry. | | AUTH-022 | One replay after rejection | When a unary request or a server-stream open is answered `UNAUTHENTICATED`, a callback exists, and the attempt does not enter lockout under AUTH-023, the client MUST obtain a new held credential and resend the request once, and MUST return a second `UNAUTHENTICATED` answer to the caller as `credential rejected`. An answer with any other status MUST be returned to the caller without invoking the callback. | A second rejection with a fresh credential is a deployment refusing this caller, not a stale token, and a scope rejection is not cured by a new token from the same source. | | AUTH-023 | Lockout after repeated failures | Where a callback exists, the client MUST count each attempt answered `UNAUTHENTICATED` or ended by a callback error as one failure, and reset the count when an attempt succeeds. When the count reaches 13, the client MUST fail that attempt’s request as `exhausted` and enter lockout: for 60 seconds it MUST fail every request that carries a credential as `exhausted` without invoking the callback or sending the request. When the cool-down ends, the client MUST obtain one held credential from the callback and send the waiting requests with it, and MUST re-enter lockout for a further 60 seconds when an attempt with it is rejected. | Without a bound, a broken credential source hits the backend at the client’s full request rate for ever. | | AUTH-035 | A shared handle shares its lockout | When client instances share one credential handle, the failure count and the lockout of AUTH-023 MUST belong to the handle, so a failure from any sharing client counts toward one lockout and the lockout applies to every sharing client. | Per-client counts on one credential would let the clients together send many times the limit before any lockout. | | AUTH-024 | The app can replace the credential | An SDK MUST let an app set a held credential at any time. When the app does, the client MUST leave lockout, reset its failure count, keep that credential over one a callback already running returns afterwards, and send it on every later request that carries a credential under AUTH-020 until AUTH-021 replaces it. | | | AUTH-036 | No wait behind a callback | While a callback invocation is in progress, when the client is about to send a request that carries a credential, other than the request that started that invocation, and it holds a credential that AUTH-021 does not require it to replace and is not in lockout under AUTH-023, the client MUST send the request without waiting for the invocation to end, including a request that was already waiting when the app set the credential under AUTH-024. | A credential the app sets while its callback is stuck, or that a callback sets before it sends through the same client, is otherwise unused until the callback returns, which may be never. | | AUTH-025 | Streams wait out a lockout | While the client is in lockout, a subscription stream that needs to reconnect MUST wait for the cool-down and then reconnect within the recovery episode limits in PROC-038, and MUST NOT end solely because the client entered lockout. When a reconnect fails because a credential is missing or rejected without a refresh callback, the affected stream MUST end with that failure. Other response failures follow the bounded recovery rule in PROC-038. | A temporary credential failure must permit recovery on the same stream. | | AUTH-026 | Failures are distinguishable | An SDK MUST let an app distinguish the four kinds in the client failure table above and read whether each is retryable. | | ## 7. Recording and redaction A rejection is counted and logged so an operator can see a misconfigured caller, and nothing more. The one place a secret leaves a well-run deployment is its log pipeline, so no token, key value, claim value, JWKS URL beyond its host, or JWKS body reaches a log, a status message, a metric label, or a span. An API key name is an operator-chosen label and is recorded on the request span; a JWT subject is an end user and, like every other claim, is not. | ID | Title | Requirement | Why | | -------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------- | | AUTH-027 | Nothing secret in diagnostics | The backend MUST NOT write a token, an API key value, a JWT claim value including `sub`, a JWKS URL beyond its host, or a JWKS response body to a log, a status message, a metric label, or a span field. A rejection log entry MUST carry only the request id, the deployment identifier (CONF-002), and the reason, and a log entry for a skipped JWKS entry MUST carry at most the first 32 bytes of its `kid`. | | | AUTH-028 | Principal on the request | When the backend admits a request under an API key, it MUST record the key’s name as `auth.principal` on the request span. | An operator tracing a bot’s traffic needs the name it configured. | ## Known limitations A stream keeps running after its token expires or its signing key is withdrawn (AUTH-004). Revocation takes effect at the next open, which the client controls. An operator who must cut a caller off at once restarts the backend or removes the key and waits for the client’s next reconnect. A deployment with only API keys answers a token that matches none of them with `untrusted`, while a deployment with a JWT source answers a non-JWT token with `malformed`. One probe tells the two apart. Both answers are `UNAUTHENTICATED`, and the deployment’s auth summary is public anyway (CONF-010). `auth.required_scopes` is one set for every path. A deployment cannot require one scope to publish and another to read. The lockout is per credential handle, not per deployment (AUTH-035). A client that is recreated with a new handle starts its count again. A callback that never returns holds one request at a time: the request that started it, or, in an SDK, the next request that needs a new held credential after that one is cancelled, because the SDK runs one callback at a time and a callback keeps running after the request that started it is cancelled. Every other request that needs a new held credential waits until the app sets a fresh one (AUTH-024). The client sets no deadline on a callback. A callback that sends a request through the same client before it sets a held credential waits for itself, because that request needs the refresh the callback is running. A callback that uses the client sets a credential through the SDK first. The published auth summary names the keys loaded at startup. A key added by a JWKS refresh verifies tokens but is not published until the backend restarts. The configured API key values stay in process memory in plaintext for the life of the process. Only the comparison uses digests. # Backend configuration An operator configures one deployment. The backend publishes part of that configuration to every client and keeps the rest private. This spec owns that boundary, the public configuration wire format, and how a client fetches, stores, binds to, and applies it. A client sizes its requests to the published values, not to compiled constants, and a client database is bound to exactly one deployment by the identifier the operator chooses. ```mermaid flowchart LR T[Operator's configuration] -->|validated at startup| B[The backend] B -->|GetConfigurationResponse| C[The client] B -.->|never published| P[Secrets, URLs, timing] C -->|stored with its URL| D[(Stored copy)] D -->|read at creation| S[Snapshot for the client's life] S --> A[Request sizing, group shapes,
chains, commit log] D -->|refresh| B ``` ## Scope In scope: the backend’s configuration file, which is a contract with operators: the sources the backend reads it from, every key with its type, presence, default, and checks, environment references, which values are secret, and what a later release must still accept; the configuration checks the backend makes before it serves; the boundary between what is published and what stays private; the public configuration wire format; how a client fetches, validates, stores, and binds to it; what a refresh may change; the conditions under which a client stops; what a client sizes or rejects using it; and what an SDK exposes to an app. Out of scope: what a key does once it is applied, and the checks and defaults that another spec states for a key, which the configuration field table cites by identifier. These include credentials and authorization ([AUTH](/specs/auth-backend-auth/)), the backend API’s enforcement of limits and its errors ([API section 7](/specs/api-backend-api/#7-bounds-errors-and-transport)), per-caller rate limits and their defaults ([RATE](/specs/rate-backend-rate-limits/)), operations such as retention, readiness, and telemetry ([OPS](/specs/ops-backend-operations/)), push delivery ([PUSH](/specs/push-push-subscriptions/)), and attachment storage ([ATCH](/specs/atch-remote-attachments/)). The platform a deployment runs on is also out of scope. | Related | Relation | | ------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [AUTH](/specs/auth-backend-auth/#6-client-credentials) | Owns what a credential is, when a client attaches one, which failures are terminal, and the checks of an enabled `[auth]` table that its rows state (AUTH-017, AUTH-029, AUTH-030, AUTH-032, AUTH-034). This spec owns what is published about auth, and the types, presence, and standard checks of the `[auth]` keys. | | [API section 7](/specs/api-backend-api/#7-bounds-errors-and-transport) | Owns what the backend does when a request exceeds a limit, and the fixed transport ceiling. This spec owns the published values and what a client does before it sends. | | [OPS](/specs/ops-backend-operations/) | Owns retention enforcement, health, the identifier’s use in telemetry, and the startup checks OPS-020, OPS-021, and OPS-022, which the configuration field table cites. | | [PUSH](/specs/push-push-subscriptions/) | Owns push channels, delivery, and recipient expiry, with the defaults that PUSH-217 and PUSH-226 state. This spec owns the `[push]` keys and their checks, including CONF-091 and CONF-092. | | [ATCH section 1](/specs/atch-remote-attachments/#1-what-the-backend-publishes) | Owns the checks of the `[attachments]` keys that its rows state, the upload ceiling default of ATCH-003, and what is published about storage. This spec owns the layout and presence of that table and its other defaults. | | [RATE](/specs/rate-backend-rate-limits/) | Owns what the `rate_limits` keys mean and the default limits. This spec owns their types, presence, and checks, including CONF-094. | | [IDENT](/specs/ident-identity-updates/) | Owns handles: the grammar and the rules for a claim in an identity log. This spec owns only the published minimum name length. | | `EVENT` | EVENT-016 keeps local event subscriptions open after a server rejection. EVENT-001 owns the `client.rejected_by_server` event. | ## Terms | Term | Meaning | | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Deployment | One backend an operator runs, with one configuration and one identifier. | | Deployment identifier | The value of `GetConfigurationResponse.identifier`: the name an operator gives a deployment. A client database is bound to exactly one. | | Backend URL | The address a client is configured to reach a deployment at. | | Stored copy | The `GetConfigurationResponse` a client keeps in its database, with the backend URL it was fetched from and any conflicting identifier recorded under CONF-030. | | Snapshot | The configuration a client resolves when it is created and reads for its life. | | Compiled default | The value in the defaults table of section 3 that a client uses for a field its snapshot does not carry. | | Advisory value | A published value the backend does not enforce, because only a client holds the state it is about. | | Blocked connection | A condition that, once observed, fails later network work for the life of the client. | | Refresh | A fetch of `GetConfiguration` by a client that already holds a snapshot, on its own schedule or when the app asks. | | Credential source | The callback or key an app gives a client so that it can obtain credentials. [AUTH section 6](/specs/auth-backend-auth/#6-client-credentials) defines the credential. | | Configuration file | The TOML document an operator gives the backend at startup, inline or as a file (CONF-082). | | Environment reference | A string value of the form `env:NAME` in the configuration file (CONF-084). | | Secret value | The value of a key whose Type in the configuration field table is `secret string`. | | Configuration field table | The table of section 1.2 with one row for every key of the configuration file. | | Standard check | A check that the standard checks table of section 1.2 defines. | ## 1. What an operator configures The backend validates its configuration before it serves. The rows below are the checks with a reason of their own that a client or an operator relies on: a published value a client would reject, or one the transport cannot honour. Section 1.1 states how the backend reads the configuration file. Section 1.2 lists every key with its type, presence, default, and checks. Section 1.3 is an example file. | ID | Title | Requirement | Why | | -------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | CONF-002 | Identifier is required | When the configured deployment identifier is absent, empty, longer than 256 bytes, or contains a whitespace or control character, the backend MUST refuse to start. | | | CONF-003 | Stable identifier | An operator SHOULD NOT change a deployment identifier once a client has connected. | Every client database that reached this deployment is bound to the old value, and CONF-030 stops each of them permanently. | | CONF-067 | Minimum version is a semantic version | When the configured minimum client version is set and is not a version under [Semantic Versioning 2.0.0 §2](https://semver.org/spec/v2.0.0.html#spec-item-2), the backend MUST refuse to start. | A client rejects an answer whose minimum does not parse (CONF-071), so a deployment that starts with one is unusable by every client. | | CONF-005 | Explicit credential intent | When the configuration contains an `[auth]` table without an `enabled` key, the backend MUST refuse to start. | A configuration that gained the table before the key existed would otherwise serve without credentials, on the strength of an omission. | | CONF-066 | Disabled auth values are unchecked | While the `[auth]` table has `enabled` set to `false`, the backend MUST NOT refuse to start because another key of that table fails a standard check, and MUST NOT fetch a key set. | | | CONF-096 | Byte budgets fit transport and subscription frames | When the configured `max_request_bytes` or `max_response_bytes` is greater than the transport ceiling API-282 states, the backend MUST refuse to start. It MUST also refuse when `max_request_bytes` is smaller than the largest valid `UpdateSubscriptions` request within PUSH-264, or when `max_response_bytes` is smaller than either a complete `Applied` frame for `max_update_adds` topics or a complete static `Started` frame for `max_static_topics` topics. These sizes MUST include protobuf wrappers and the largest legal topic identifiers, HMAC key windows and epoch bases, sequence ids, update id, and keepalive interval, and MUST exclude the gRPC frame header. | A budget above the transport ceiling promises bytes the transport cannot carry. A budget below a full subscription batch or its control response makes ordinary count-bounded subscriptions fail repeatedly. | | CONF-009 | Public configuration stays small | When the encoded `GetConfigurationResponse` the backend would publish is longer than 65536 bytes (64 KiB), the backend MUST refuse to start. | The message is served without a credential, so an unbounded one is an amplification source. Bounding the whole message bounds every list in it without a limit per list. | | CONF-078 | Valid application catalogue | When an operator configures an application component, the backend MUST refuse to start unless its `component_id` is in `0xC000`–`0xFEFF`, its `name` contains 1 to 100 UTF-8 bytes, its `component_type` is one of the seven types in META section 2, all three member policies are present, and at least one of `in_groups` and `in_dms` is true; it MUST refuse duplicate IDs or names and a name equal to a well-known component name in META section 2. | An unusable or ambiguous definition would be published to every client, and a duplicate name makes name lookup ambiguous. | | CONF-080 | Handle name minimum in range | When the configured `handles.min_name_length` is less than 1 or greater than 27, the backend MUST refuse to start. | A client reads a published 0 as not provided (CONF-025), so an app would check names against the compiled default instead. Above 27, every claim fails, because no name part is longer than 27 characters. | | CONF-065 | Refusal names the key | When the backend refuses to start because a key or its value fails a rule in this section, it MUST report that key, and when it refuses under CONF-009, it MUST report that the public configuration is too large. | | Application component definitions are a sending catalogue: a client copies them into the registry of a conversation it creates or refreshes, and the committed group registry, not the catalogue, governs every received change. CONF-009 applies to the response including the catalogue. Operator documentation states that a published definition’s ID, name, type, policies, and conversation selection should stay stable, because a change reaches only conversations that register the ID later; no receive-side rule depends on that advice. API-282 states the transport ceiling and the failure rule for a message above the ceiling or byte budget. API-281 owns the status codes. A handle is a public name, such as `nick` or `nick#2341`, that an inbox claims in its identity log. `handles.min_name_length` is the shortest name part the backend admits in a claim. IDENT-078 states the handle grammar, whose name part is 1 to 27 characters, and IDENT-084 forbids a validator to check a claim’s name part against this setting when it validates an identity log. API-297 makes the backend fail a publish with `REASON_HANDLE_NOT_ALLOWED` when a claim in it has a name part shorter than this setting. A change of the setting applies only to later claims. A handle claimed before the change stays valid. ### 1.1 The configuration file An operator gives the backend one TOML document at startup, inline or as a file, and the backend reads it once (CONF-082). The file is a contract with the operator for a major version. A file that one release accepts, every later release with the same major version also accepts, and reads each value in the same unit (CONF-097). A release with a higher major version may require edits to the file; it names each key to change when it refuses the file, and its release notes list the changes. The key set is closed. A key that the configuration field table does not list is refused (CONF-083), because an ignored key would leave its default in force while the operator believes the setting changed. A key the operator chooses, such as a chain id or an API key name, fills a position that the field table shows in angle brackets. A string value of the form `env:NAME` is an environment reference. The backend replaces it with the value of the environment variable `NAME` before any other check (CONF-084). Every check therefore sees the resolved value, and a reference inside a disabled `[auth]` table must still resolve. Only a string value can be a reference: a table key, an integer, a float, and a boolean cannot come from the environment. The field table gives the type `secret string` to credentials, and to the URLs of the store, the chain RPC services, the OTLP collector, and the storage endpoint, which can carry credentials. API key values and the JWKS URL have the type `string`, because AUTH-027 governs them. An environment reference keeps a secret value out of the file. CONF-011 and ATCH-006 keep secret values out of the published configuration, and CONF-085 keeps them out of the backend’s output. | ID | Title | Requirement | Why | | -------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | CONF-082 | One configuration source | The backend MUST read its configuration as one [TOML v1.1.0](https://toml.io/en/v1.1.0) document from the file `--config-file` names, or else from `--config`, or else from the `XMTP_CONFIG` environment variable. When `--config-file` is given together with `--config` or `XMTP_CONFIG`, when none of the three is given, when the named file cannot be read, or when the document is not valid TOML v1.1.0, the backend MUST refuse to start. | An instance given two sources would run on a source its operator did not choose. | | CONF-083 | Unknown keys are refused | When the configuration holds a key that the configuration field table does not list, or lists only for a credential `kind` other than the one its table sets, the backend MUST refuse to start. A key the operator chooses, in a position the table shows in angle brackets, is listed. | A misspelled key would be ignored and its default applied, so the deployment would run on a value its operator believes they changed. | | CONF-084 | Environment references resolve once | When a string value anywhere in the configuration begins with `env:`, the backend MUST replace it, after it parses the document and before any other check of this section, with the value of the environment variable that the rest of the string names, and MUST NOT read the replacement as a reference. When that name is empty, or the variable is not set or does not hold valid Unicode, the backend MUST refuse to start, and in the second case MUST name the variable. | A reference read as written would run the deployment on the text `env:NAME` as a URL, key, or audience. A value read a second time would let the content of one secret select another variable. | | CONF-085 | Secret values stay out of output | The backend MUST NOT write a secret value, or any part of one other than the host of a URL, to a log entry, a span field, a metric label, its help output, or a refusal message other than one under OPS-022, whether the file holds the value or an environment reference supplies it. | Logs, spans, metrics, help output, and refusals reach terminals, collectors, and people who never hold the secret. A database URL or a provider key in them is a credential leak. | | CONF-097 | Files stay valid within a major version | When a configuration file passes every check that section 1 states or cites under one release of the backend, every later release with the same major version, given the same host, environment variables, store, and JWKS document, MUST NOT refuse that file under a check that its own section 1 states or cites, and MUST NOT read a value in it in a unit other than the one the earlier release used. A release with a higher major version MAY refuse such a file; when it does, its startup error MUST name each key that needs a change. | An operator upgrades within a major version by replacing the binary. A release that refuses a working file takes the deployment down, and one that reads a value in another unit changes the deployment without an edit by the operator. A major release may tighten checks, and naming the key lets the operator fix the file without guessing. | ### 1.2 Keys and checks The configuration field table lists every key of the configuration file. Its columns mean: * Key: the dotted path. `a.b` is key `b` of table `a`, a word in angle brackets such as `` is a key the operator chooses, and `[]` is one entry of an array of tables. Every table on a listed path has a row of its own. * Type: the TOML type ([TOML v1.1.0](https://toml.io/en/v1.1.0)). `table` includes an inline table, and `array of tables` includes an array of inline tables. `non-negative integer` is an integer not less than 0, and `number` is a float or an integer. `secret string` is a string that holds a secret value. * Presence: `required` or `optional`, sometimes under a condition, such as the presence of the enclosing table or the credential `kind`. An identifier after a semicolon names the requirement that governs the key’s presence in place of CONF-087. An optional table may be omitted, and each of its keys is then absent. * Default: what applies when the key is absent. A value, or `section 3`, is what the backend applies under CONF-088. `section 3` is the compiled default that the defaults table of section 3 gives for the field the key is published as. An identifier, or a section or term of another spec, points at the requirement that states the default, and that requirement governs it. `absent` means the key stays unset, and the requirement that reads the key gives the effect. `none` marks a key whose absence is refused. * Checks: standard checks with their parameters, separated by commas. Every one of them must pass. After a semicolon come the identifiers of rules, in this spec or another, that also bind the key. A cell with only identifiers begins with the semicolon. `key` before a check or an identifier applies it to the key in angle brackets instead of to its value. On an array, `non-empty` applies to the array, and every other standard check applies to each element. * Notes: informative. The standard checks table defines each standard check. A rule that relates keys, needs a fact the backend learns at startup, or loads credential material has a row of its own after the tables. The backend applies the checks before it serves (OPS-005). CONF-065 says what a refusal names. When more than one check fails, which failure the refusal reports is not specified. Inside an `[auth]` table whose `enabled` is `false`, the standard checks do not apply (CONF-066), but CONF-083, CONF-084, and the Type and Presence columns do. | Check | Meaning | | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `range A..B` | The value is not less than A, not greater than B, and not NaN. On a `number` key, A, B, and the value may be floats. When B is omitted, the only upper bound is the largest TOML integer. | | `bytes A..B` | The UTF-8 encoding of the string is A to B bytes long. | | `non-empty` | The string is at least one byte long, or the array holds at least one element. | | `non-blank` | The string holds at least one character that is not Unicode `White_Space`. | | `entries ..B` | The table holds at most B keys. | | `one of: V, ...` | The string equals one of the listed values, byte for byte. When `one of` is followed by an identifier, the listed values are those that requirement accepts. | | `not: V, ...` | The string equals none of the listed values, byte for byte. | | `pattern R` | The whole string matches the regular expression R, read under [ECMA-262 §22.2](https://tc39.es/ecma262/#sec-regexp-regular-expression-objects) with no flags. | | `socket address` | The string is an IPv4 address, or an IPv6 address in square brackets. An IPv4 address is four decimal numbers from 0 to 255, each without a leading zero, joined by `.`. An IPv6 address follows [RFC 4291 §2.2](https://www.rfc-editor.org/rfc/rfc4291#section-2.2), and inside the brackets `%` and a decimal zone index may follow it. After the address come `:` and a decimal port from 0 to 65535. A host name does not pass. | | `socket address or empty` | The string is empty, or passes `socket address`. | | `ip address` | The string is an IPv4 address, written as in `socket address`, or an IPv6 address following [RFC 4291 §2.2](https://www.rfc-editor.org/rfc/rfc4291#section-2.2) without brackets or a zone index. | | `ip network` | The string passes `ip address`, followed by `/` and a decimal prefix length from 0 to 32 for IPv4 or 0 to 128 for IPv6, with every bit after the prefix 0. | | `url S` | The string begins with `S://` for one of the listed schemes S. The [WHATWG URL Standard basic URL parser](https://url.spec.whatwg.org/#concept-basic-url-parser), given no base URL, returns a URL for it. | | `secure url` | The basic URL parser, given no base URL, returns a URL for the string that has a host. Its scheme is `https`, or `http` when the host is `localhost`, an IPv4 address in `127.0.0.0/8`, or `::1`. | | `plain url` | The string is ASCII with no control character, no white space, and no `\`, and has no `%` between `://` and the next `/`. The basic URL parser, given no base URL, returns a URL for it that has a host and no username, password, query, or fragment. An IPv4 host is written in the dotted-decimal form that the parser serializes. | | `host name` | The string is an optional `*.` followed by a host of 1 to 253 bytes. The host is labels joined by `.`. Each label is 1 to 63 ASCII letters, digits, or `-`, and no label begins or ends with `-`. | | Key | Type | Presence | Default | Checks | Notes | | ------------------------------------------------------------ | -------------------- | ----------------------------------------------------------- | -------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `server` | table | required; CONF-002 | none | | CONF-002 requires `server.identifier`. | | `server.identifier` | string | required; CONF-002 | none | ; CONF-002 | The deployment identifier, published as `identifier`. CONF-003 asks the operator to keep it stable. | | `server.min_libxmtp_version` | string | optional | absent | ; CONF-067 | Published as `min_libxmtp_version`, which CONF-069 leaves empty when the key is absent. Clients apply it (CONF-049, CONF-036). | | `server.listen` | string | optional | `"0.0.0.0:5050"` | `socket address` | The listener of OPS-004 and API-285. | | `server.log_level` | string | optional | `"info"` | `one of: off, error, warn, info, debug, trace` | The `--log-level` option replaces it. The OPS-018 log needs a level that admits `info`. | | `server.log_format` | string | optional | `"text"` | `one of: text, json` | `json` writes one JSON event per line. | | `server.request_logger` | boolean | optional | OPS-018 | | Turns the completion log of OPS-018 on or off. | | `server.max_drain_duration_ms` | integer | optional | OPS Terms (Drain deadline) | `range 1..4294967295` | The drain deadline of OPS-008. | | `telemetry` | table | optional | `{}` | | | | `telemetry.metrics_listen` | string | optional | `"0.0.0.0:9464"` | `socket address or empty`; OPS-022 | The metrics listener of OPS-016. | | `telemetry.otlp_endpoint` | secret string | optional | absent | ; OPS-022 | When absent, OPS-022 reads `OTEL_EXPORTER_OTLP_ENDPOINT`. | | `telemetry.otlp_logs` | boolean | optional | `false` | | Also exports logs to the OTLP endpoint. | | `telemetry.service_name` | string | optional | OPS-013 | `non-blank` | The `service.name` of OPS-013. | | `telemetry.sample_ratio` | number | optional | `1.0` | `range 0.0..1.0` | Share of root traces recorded. | | `telemetry.resource_attributes` | table | optional | `{}` | | Extra OpenTelemetry resource attributes, exported as written. | | `telemetry.resource_attributes.` | string | optional | absent | key `not: service.name, service.version, xmtp.backend.identifier` | OPS-013 sets the three reserved names. | | `database` | table | required | none | | | | `database.url` | secret string | required | none | `url postgres, postgresql` | The primary store. | | `database.replica_url` | secret string | optional | absent | `url postgres, postgresql` | One streaming read replica. OPS section 4 says which reads may answer from a lagged copy. | | `database.max_connections` | integer | optional | `20` | `range 1..4294967295` | Connections in each request pool, with one pool for each database URL. | | `database.max_statement_timeout_ms` | integer | optional | `5000` | `range 1..2147483647`; CONF-089 | Statement timeout on every pooled connection. | | `publishing` | table | optional | `{}` | | | | `publishing.max_publish_duration_ms` | integer | optional | `10000` | `range 1..2147483647`; CONF-089 | Bound on one publish, from its first lock to its commit. | | `publishing.max_barrier_wait_ms` | integer | optional | `1000` | `range 1..2147483647` | Wait for the allocation barrier of API-203 before a retry. | | `streams` | table | optional | `{}` | | | | `streams.poll_interval_ms` | integer | optional | `100` | `range 1..4294967295` | Interval between push dispatcher polls of the read database, and the longest wait between stream tailer polls. After a poll that finds envelopes, the tailer polls again after 50 ms, or after this interval when it is shorter. | | `streams.max_gap_ranges` | integer | optional | `10000` | `range 1..` | The gap-range bound of OPS-006. | | `streams.keepalive_interval_ms` | integer | optional | `30000` | `range 1..4294967295` | The interval of API-250 and API-255. | | `streams.max_pong_wait_ms` | integer | optional | API-257 | `range 1..4294967295` | The Pong wait of API-257. | | `retention` | table | optional | `{}` | | | | `retention.group_message_seconds` | integer | optional | section 3 | `range 1..`; OPS-020 | A retention period of OPS section 1. | | `retention.welcome_seconds` | integer | optional | section 3 | `range 1..`; OPS-020 | A retention period of OPS section 1. | | `retention.key_package_seconds` | integer | optional | section 3 | `range 1..`; OPS-020 | A retention period of OPS section 1. | | `validation` | table | optional | `{}` | | | | `validation.max_scw_cache_entries` | integer | optional | `10000` | `range 1..` | Entries in the instance’s cache of smart contract wallet verdicts. | | `limits` | table | optional | `{}` | | | | `limits.max_push_topics` | integer | optional | PUSH-217 | `range 1..2147483647` | The `max_push_topics` of PUSH-217. Not published. | | `limits.max_query_topics` | integer | optional | section 3 | `range 1..4294967295` | | | `limits.default_query_limit` | integer | optional | section 3 | `range 1..4294967295`; CONF-089 | API-241. | | `limits.max_query_limit` | integer | optional | section 3 | `range 1..4294967295`; CONF-089 | API-241. | | `limits.max_newest_metadata_topics` | integer | optional | section 3 | `range 1..4294967295` | | | `limits.max_newest_full_topics` | integer | optional | section 3 | `range 1..4294967295` | | | `limits.max_publish_topics` | integer | optional | section 3 | `range 1..4294967295` | | | `limits.max_envelope_bytes` | integer | optional | section 3 | `range 1..`; OPS-021 | | | `limits.max_request_bytes` | integer | optional | section 3 | `range 1..`; CONF-096, OPS-021 | Also bounds a Subscribe update frame (section 6). | | `limits.max_response_bytes` | integer | optional | section 3 | `range 1..`; CONF-096, OPS-021 | | | `limits.max_update_adds` | integer | optional | section 3 | `range 1..4294967295`; CONF-089 | | | `limits.max_update_removes` | integer | optional | section 3 | `range 1..4294967295` | | | `limits.max_stream_topics` | integer | optional | section 3 | `range 1..4294967295`; CONF-089 | | | `limits.max_static_topics` | integer | optional | section 3 | `range 1..4294967295` | | | `limits.max_lookup_identifiers` | integer | optional | section 3 | `range 1..4294967295` | | | `limits.max_scw_signatures` | integer | optional | section 3 | `range 1..200` | Not above two for each action IDENT-094 allows, the most ERC-6492 signatures one identity update can carry. Clients size verify requests by it. | | `limits.max_identity_entries` | integer | optional | section 3 | `range 1..4294967295` | API-234. | | `limits.max_http2_streams` | integer | optional | `100` | `range 1..4294967295` | Concurrent HTTP/2 streams per connection. Open subscriptions count toward it. Not published. | | `limits.max_update_frames_per_second` | integer | optional | section 3 | `range 1..4294967295` | API-258. | | `limits.max_update_burst` | integer | optional | section 3 | `range 1..4294967295` | API-258. | | `limits.max_ping_frames_per_second` | integer | optional | section 3 | `range 1..4294967295` | API-258. | | `limits.max_ping_burst` | integer | optional | section 3 | `range 1..4294967295` | API-258. | | `rate_limits` | table | optional | `{}` | | RATE. | | `rate_limits.enabled` | boolean | optional | `true` | | When `false`: RATE-012. | | `rate_limits.max_memory_mib` | integer | optional | `100` | `range 1..65536` | The bound of RATE-050. | | `rate_limits.trusted_proxies` | array of strings | optional | `[]` | `ip network` | The trusted proxies of RATE-002. | | `rate_limits.categories` | table | optional | `{}` | | | | `rate_limits.categories.` | table | optional | absent | key `one of: request, publish, identity_update, chain_verify, push, upload, stream_rent` | The categories of RATE section 2. | | `rate_limits.categories..` | array of tables | optional | RATE-025 | key `one of: default, ip, jwt, api_key`; CONF-094 | The limits RATE-025 applies. `[]` admits every spend. | | `rate_limits.categories..[].count` | integer | required | none | `range 1..4294967295`; CONF-094 | | | `rate_limits.categories..[].window_seconds` | integer | required | none | `range 1..2592000` | | | `rate_limits.overrides` | array of tables | optional | `[]` | ; CONF-094 | One caller each. | | `rate_limits.overrides[].api_key` | string | optional; CONF-094 | absent | `pattern ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$` | An API key name (AUTH-028). | | `rate_limits.overrides[].jwt_issuer` | string | optional; CONF-094 | absent | | The `iss` of RATE-001. When absent, the override names a token with no `iss`. | | `rate_limits.overrides[].jwt_subject` | string | optional; CONF-094 | absent | `non-empty` | The `sub` of RATE-001. | | `rate_limits.overrides[].ip` | string | optional; CONF-094 | absent | `ip address` | An IPv6 address names its /64 (RATE-003). | | `rate_limits.overrides[].limits` | table | required in `rate_limits.overrides[]` | none | | | | `rate_limits.overrides[].limits.` | array of tables | optional | absent | key `one of: request, publish, identity_update, chain_verify, push, upload, stream_rent`; CONF-094 | `[]` admits every spend. | | `rate_limits.overrides[].limits.[].count` | integer | required | none | `range 1..4294967295`; CONF-094 | | | `rate_limits.overrides[].limits.[].window_seconds` | integer | required | none | `range 1..2592000` | | | `mls` | table | optional | `{}` | | | | `mls.max_group_members` | integer | optional | section 3 | `range 1..65535` | Advisory. Clients apply it (CONF-043). | | `mls.max_installations_per_inbox` | integer | optional | section 3 | `range 1..100` | Advisory. Clients apply it (CONF-044). Not above the action limit of IDENT-094, so one update can revoke every installation within the ceiling. | | `mls.commit_log_enabled` | boolean | optional | section 3 | | CONF-045. | | `handles` | table | optional | `{}` | | | | `handles.min_name_length` | integer | optional | section 3 | ; CONF-080 | API-297 applies it to claims. | | `chains` | table | optional | `{}` | | Section 3 gives a client’s reading of an empty table. | | `chains.` | secret string | optional | absent | `url http, https`; key CONF-090 | The chain’s JSON-RPC URL. The key is published (CONF-070); the URL is not (CONF-011). | | `auth` | table | optional | absent | | When absent: AUTH-003. | | `auth.enabled` | boolean | required in `[auth]`; CONF-005 | none | | When `false`: CONF-066. | | `auth.jwks_url` | string | optional | absent | `secure url`; AUTH-015, AUTH-017, AUTH-029 | AUTH-027 keeps the part after its host out of diagnostics. | | `auth.keys` | array of tables | optional | absent | `non-empty`; AUTH-029 | Inline signing keys. | | `auth.keys[].kid` | string | required while `auth.enabled` is `true` | absent | `bytes 1..256`; AUTH-017 | Published (CONF-068). | | `auth.keys[].alg` | string | required | none | `one of` AUTH-008; AUTH-017 | Published (CONF-068). | | `auth.keys[].public_key` | string | required | none | ; AUTH-017 | PEM text, not a path. Never published (CONF-011). | | `auth.api_keys` | table | optional | `{}` | `entries ..256` | An empty table configures no API key under AUTH-029. | | `auth.api_keys.` | string | optional | absent | key `pattern ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`; AUTH-030 | The name is the principal (AUTH-028). AUTH-027 keeps the value out of diagnostics. | | `auth.audiences` | array of strings | optional | absent | `non-empty` | AUTH-012. | | `auth.issuers` | array of strings | optional | absent | `non-empty` | AUTH-012. | | `auth.required_scopes` | array of strings | optional | `[]` | | AUTH-013. Published (CONF-068). | | `auth.leeway_seconds` | non-negative integer | optional | AUTH Terms (Leeway) | ; AUTH-032 | AUTH-011. | | `auth.jwks_refresh_seconds` | non-negative integer | optional | AUTH-018 | ; AUTH-034 | | | `auth.jwks_max_stale_seconds` | non-negative integer | optional | AUTH-019 | `range 0..4294967295`; AUTH-034 | | | `push` | table | optional | `{}` | | | | `push.recipient_ttl_seconds` | integer | optional | PUSH-226 | `range 86400..`; CONF-091 | | | `push.max_attempts` | integer | optional | `3` | `range 1..10` | Provider attempts for each delivery (PUSH section 7). | | `push.apns` | table | optional | absent | | When present, the APNs channel exists (PUSH-210). | | `push.apns.key` | secret string | required in `[push.apns]` | none | `non-empty`; CONF-092 | PEM text, not a path. | | `push.apns.key_id` | string | required in `[push.apns]` | none | `non-empty` | Apple’s id of the signing key (PUSH-259). | | `push.apns.team_id` | string | required in `[push.apns]` | none | `non-empty` | Issuer of the provider token (PUSH-259). | | `push.apns.bundle_id` | string | required in `[push.apns]` | none | `non-empty` | The `apns-topic` of PUSH-259. | | `push.apns.environment` | string | required in `[push.apns]` | none | `one of: production, sandbox` | Selects the host of PUSH-259. | | `push.fcm` | table | optional | absent | | When present, the FCM channel exists (PUSH-210). | | `push.fcm.service_account` | secret string | required in `[push.fcm]` | none | `non-empty`; CONF-092 | JSON text, not a path. | | `push.http` | table | optional | absent | | When present, even if empty, the HTTPS channel exists (PUSH-210). | | `push.http.allowed_domains` | array of strings | optional | absent | `host name` | PUSH-256 reads it. When it is absent or empty, every host passes the list. | | `push.http.allow_private_addresses` | boolean | optional | `false` | | PUSH-256. | | `attachments` | table | optional | absent | | ATCH-001. | | `attachments.base_url` | string | required in `[attachments]` | none | ; ATCH-002 | Published. | | `attachments.max_upload_bytes` | non-negative integer | optional | ATCH-003 | ; ATCH-003 | | | `attachments.retention_seconds` | non-negative integer | optional | absent | ; ATCH-004 | ATCH-004 publishes 0 when it is absent. ATCH-005 asks the operator to match the target’s expiry rule. | | `attachments.target` | table | required in `[attachments]` | none | | Holds the one target table. | | `attachments.target.S3` | table | required in `[attachments.target]` | none | | ATCH-007 says which targets fit. | | `attachments.target.S3.endpoint` | secret string | required in `[attachments.target.S3]` | none | `plain url`; ATCH-071 | Never published (ATCH-006). | | `attachments.target.S3.region` | string | required in `[attachments.target.S3]` | none | ; ATCH-081 | | | `attachments.target.S3.bucket` | string | required in `[attachments.target.S3]` | none | ; ATCH-081 | Never published (ATCH-006). | | `attachments.target.S3.key_prefix` | string | optional | `""` | ; ATCH-075 | Put before the object name with no separator added. | | `attachments.target.S3.presign_ttl_seconds` | integer | optional | `900` | ; ATCH-083 | ATCH-028. | | `attachments.target.S3.credentials` | table | required in `[attachments.target.S3]` | none | | | | `attachments.target.S3.credentials.kind` | string | required in `[attachments.target.S3.credentials]`; ATCH-073 | none | ; ATCH-073 | | | `attachments.target.S3.credentials.access_key_id` | secret string | required when `kind` is `static`; ATCH-073 | none | ; ATCH-073 | | | `attachments.target.S3.credentials.secret_access_key` | secret string | required when `kind` is `static`; ATCH-073 | none | ; ATCH-073 | | | `attachments.target.S3.credentials.session_token` | secret string | optional when `kind` is `static` | absent | | | | `attachments.target.S3.credentials.name` | string | required when `kind` is `profile`; ATCH-073 | none | ; ATCH-073 | | | `attachments.target.S3.credentials.account_id` | string | required when `kind` is `sso`; ATCH-073 | none | ; ATCH-073 | | | `attachments.target.S3.credentials.region` | string | required when `kind` is `sso`; ATCH-073 | none | ; ATCH-073 | | | `attachments.target.S3.credentials.role_name` | string | required when `kind` is `sso`; ATCH-073 | none | ; ATCH-073 | | | `attachments.target.S3.credentials.start_url` | string | required when `kind` is `sso`; ATCH-073 | none | ; ATCH-073 | | | `attachments.target.S3.credentials.session_name` | string | optional when `kind` is `sso` or `assume_role` | absent | | | | `attachments.target.S3.credentials.command` | string | required when `kind` is `process`; ATCH-073 | none | ; ATCH-073 | | | `attachments.target.S3.credentials.role_arn` | string | required when `kind` is `assume_role`; ATCH-073 | none | ; ATCH-073 | | | `attachments.target.S3.credentials.external_id` | string | optional when `kind` is `assume_role` | absent | | | | `application_components` | array of tables | optional | `[]` | | Published under CONF-079. Counts toward CONF-009. | | `application_components[].component_id` | integer | required; CONF-078 | none | ; CONF-078 | META section 1 gives the write-once range. | | `application_components[].name` | string | required; CONF-078 | none | ; CONF-078 | META section 2 gives the `USER_` prefix convention. | | `application_components[].component_type` | string | required; CONF-078 | none | ; CONF-078 | A type of META section 2, written in lowercase without its prefix: `bytes`, `string`, `tls_map_bytes_bytes`, `tls_map_inbox_id_bytes`, `tls_set_bytes`, `tls_set_inbox_id`, or `tls_map_inbox_id_string`. | | `application_components[].insert_policy` | string | required; CONF-078 | none | `one of: allow, deny, allow_if_admin, allow_if_super_admin, allow_if_self_or_non_member`; CONF-078 | Who may add a value. Each value is a `MetadataBasePolicy` name in lowercase. | | `application_components[].update_policy` | string | required; CONF-078 | none | `one of: allow, deny, allow_if_admin, allow_if_super_admin, allow_if_self_or_non_member`; CONF-078 | Who may change a value. META-004 refuses a change to a write-once component. | | `application_components[].delete_policy` | string | required; CONF-078 | none | `one of: allow, deny, allow_if_admin, allow_if_super_admin, allow_if_self_or_non_member`; CONF-078 | Who may remove a value. | | `application_components[].in_groups` | boolean | required; CONF-078 | none | ; CONF-078 | Register the field in new groups. | | `application_components[].in_dms` | boolean | required; CONF-078 | none | ; CONF-078 | Register the field in new DMs. | | ID | Title | Requirement | Why | | -------- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | CONF-087 | Field table is enforced | When a key whose row in the configuration field table makes it required, and whose Presence cell names no requirement, is absent, when a value does not have the type its row’s Type cell gives, or when, outside an `[auth]` table whose `enabled` is `false`, a value fails a check from the standard checks table that its row’s Checks cell names, the backend MUST refuse to start. | A value outside its range reaches code that cannot honour it: a timeout the store refuses, a count published as a number other than the one enforced (CONF-069), or a zero that clients read as not provided (CONF-025). | | CONF-088 | Absent keys take their default | When the configuration omits an optional key whose Default cell in the configuration field table holds a value or `section 3`, the backend MUST apply that value. For `section 3`, the value is the compiled default that section 3 gives for the field the key is published as. | An operator who omits a key relies on the value this table documents. Any other value changes a limit, a timeout, or a published field the operator never set. | | CONF-089 | Related keys agree | When `publishing.max_publish_duration_ms` is not greater than `database.max_statement_timeout_ms`, `limits.max_query_limit` is less than `limits.default_query_limit`, or `limits.max_update_adds` is greater than `limits.max_stream_topics`, the backend MUST refuse to start. | Each pair nests one bound inside another. When a pair is inverted, a publish ends at its own deadline before its statement timeout can act, a page for `limit` 0 is larger than the published `max_query_limit`, and an update of `max_update_adds` topics is refused. | | CONF-090 | Chain keys are EIP-155 ids | When a key of the `chains` table is not `eip155:` followed by a chain id in the decimal form IDENT-093 requires and not greater than 18446744073709551615, the backend MUST refuse to start. | A key in another form is published (CONF-070) but never equals the chain of a signature that IDENT-093 admits, so no signature on that chain is ever verified. | | CONF-091 | Push expiry fits the clock | When `push.recipient_ttl_seconds`, converted to nanoseconds and added to the primary store’s clock at startup, cannot be represented as a signed 64-bit nanosecond timestamp, the backend MUST refuse to start. | Otherwise every `Register` fails with `INTERNAL`, because the `expires_at_ns` that PUSH-255 returns cannot be computed, while the instance reports SERVING. | | CONF-092 | Push credentials load at startup | When `[push.apns]` is present and its `key` is not a PEM-encoded private key ([RFC 7468 §10](https://www.rfc-editor.org/rfc/rfc7468#section-10)) in the form of [RFC 5958 §2](https://www.rfc-editor.org/rfc/rfc5958#section-2) on the curve `secp256r1` ([RFC 5480 §2.1.1.1](https://www.rfc-editor.org/rfc/rfc5480#section-2.1.1.1)), the backend MUST refuse to start. When `[push.fcm]` is present and its `service_account` is not a JSON object ([RFC 8259 §4](https://www.rfc-editor.org/rfc/rfc8259#section-4)) whose `project_id` is a string of one or more ASCII letters, digits, or `-`, whose `client_email` is a string that is not empty, whose `private_key` is a PEM-encoded RSA private key ([RFC 8017 §3.2](https://www.rfc-editor.org/rfc/rfc8017#section-3.2)) in the same form, and whose `token_uri` is `https://oauth2.googleapis.com/token`, the backend MUST refuse to start. | Otherwise the backend reports SERVING while every delivery on that channel fails. Any other `token_uri` would send the signed token request to a host the file names. | | CONF-094 | Rate limit lists and overrides agree | When a list of limits under `rate_limits` holds more than 3 entries, two entries with equal `window_seconds`, or an entry whose `count` is greater than 1,000,000,000 × its `window_seconds`, when an entry of `rate_limits.overrides` sets none or more than one of `api_key`, `jwt_subject`, and `ip`, or sets `jwt_issuer` without `jwt_subject`, or when two entries name the same caller key under RATE-001 and RATE-003, the backend MUST refuse to start. | Two overrides for one caller make the applied limits depend on file order, a fourth limit has nowhere to be recorded, and a limit of more than one unit per nanosecond is earned back at once, so it admits every spend. | | CONF-095 | Unsafe settings are reported | Before it serves, the backend MUST log, while the configured log level admits WARN, one entry at level WARN for each of these settings, and MUST NOT refuse to start because of any of them: auth disabled while `server.listen` is not a loopback address; a `database.url` or `database.replica_url` whose host is not a loopback address, `localhost`, or a Unix socket and whose TLS mode is not `verify-full`, where the TLS mode is the URL’s `sslmode` parameter, or else the `PGSSLMODE` environment variable, or else `prefer`; and a `chains` URL whose scheme is `http` and whose host is not a loopback address or `localhost`. Each entry MUST name the key and, for a store URL, the TLS mode. | CONF-097 keeps these files valid, so a log entry is how an operator learns that any caller is admitted without a credential, or that a party on the network path can read and rewrite the store link or forge a chain’s answers. | ### 1.3 Example configuration The file below gives every key a value that passes the checks of section 1.2. Where keys exclude one another, the key is shown in a comment instead. A comment above each key says what it does. The file is informative. The commented choices are `[[auth.keys]]` in place of `auth.jwks_url`, and each storage credential `kind` other than `web_identity`, with the keys that kind takes. Secret values are environment references. ```toml # Backend configuration with every key set. Secret values are environment # references; set those variables in the backend's environment. [server] # Stable name of this deployment, in reverse DNS form. Every client database # binds to it on first connect, so never change it after clients connect. identifier = "org.example.xmtp" # Oldest libxmtp version this deployment accepts. Clients compare major, # minor, and patch, and refuse to run when they are older. Omit it to accept # every version. min_libxmtp_version = "1.10.0" # Address and port of the listener that serves gRPC, gRPC-Web, and health. listen = "0.0.0.0:5050" # Log level: off, error, warn, info, debug, or trace. Request completion logs # need info or a more detailed level. The --log-level option overrides it. log_level = "info" # Log encoding on standard output: text, or json for one JSON event per line. log_format = "json" # Write one completion log line for each gRPC request. request_logger = true # Milliseconds that shutdown gives running requests to finish. OPS-008 says # when the process exits after that; keep that below your orchestrator's kill # timeout. max_drain_duration_ms = 10000 [telemetry] # Prometheus listener. Keep it on a private network. An empty string turns # the listener off; metrics are still recorded. metrics_listen = "0.0.0.0:9464" # OTLP gRPC collector for traces. Omit it to use OTEL_EXPORTER_OTLP_ENDPOINT; # with neither, nothing is exported. otlp_endpoint = "env:XMTP_OTLP_ENDPOINT" # Also export logs to the OTLP collector. otlp_logs = true # service.name on every exported span. Give each backend its own name when # several share one collector. service_name = "xmtp-backend" # Share of new traces to record, from 0.0 to 1.0. Metrics do not depend on it. sample_ratio = 0.25 [telemetry.resource_attributes] # Extra OpenTelemetry resource attributes, exported as written on every # signal. service.name, service.version, and xmtp.backend.identifier are set by # the backend and cannot be used. Never put a secret here. "deployment.environment" = "production" [database] # Connection URL of the primary database. Publishing, queries, migrations, and # maintenance use it. Keep it in an environment variable. url = "env:XMTP_DATABASE_URL" # Connection URL of one streaming read replica. Omit it to read from the # primary. Reads from a replica can lag behind a publish. replica_url = "env:XMTP_REPLICA_URL" # Connections in each pool: one pool on the primary and one on the replica. # The stream tailer and the push dispatcher each hold one more connection. max_connections = 20 # Statement timeout, in milliseconds, on every database connection. Raise it # only together with publishing.max_publish_duration_ms. max_statement_timeout_ms = 5000 [publishing] # Upper bound, in milliseconds, on one publish, from its first lock to its # commit. It must be greater than database.max_statement_timeout_ms. max_publish_duration_ms = 10000 # Milliseconds the boundary task waits for the allocation barrier before it # tries again on a later poll. max_barrier_wait_ms = 1000 [streams] # Milliseconds between push dispatcher polls of the read database, and the # longest wait between stream tailer polls. While envelopes arrive, the tailer # polls every 50 ms, or at this interval when it is shorter. poll_interval_ms = 100 # Unresolved sequence gaps the tailer tracks before it ends open streams and # restarts recovery. max_gap_ranges = 10000 # Idle milliseconds after which the server sends a keepalive or a Ping on a # stream. Keep it below every proxy and load balancer idle timeout. keepalive_interval_ms = 30000 # Milliseconds the server waits for the Pong that answers its Ping. max_pong_wait_ms = 90000 [retention] # Expiry period, in seconds, stamped on each group message. Commits and # proposals never expire. group_message_seconds = 7776000 # Expiry period, in seconds, stamped on each Welcome. welcome_seconds = 7776000 # Expiry period, in seconds, stamped on each key package. key_package_seconds = 7776000 [validation] # Entries in this instance's cache of smart contract wallet signature # verdicts. Raise it to make fewer chain RPC calls. max_scw_cache_entries = 10000 [limits] # Most push subscriptions one push recipient may hold. max_push_topics = 100000 # Most topics in one Query request. max_query_topics = 1000 # Rows per page when a Query request sets limit 0. Not above max_query_limit. default_query_limit = 100 # Most rows in one Query page. A larger client limit is lowered to it. max_query_limit = 1000 # Most topics in one QueryNewest request without full envelopes. max_newest_metadata_topics = 1000 # Most topics in one QueryNewest request with full envelopes. max_newest_full_topics = 100 # Most distinct topics in one Publish request. max_publish_topics = 1000 # Largest client envelope, in bytes, that a publish may carry. It must leave # room for framing inside the request, response, and stream frame budgets. max_envelope_bytes = 1048576 # Largest encoded request, in bytes, including a Subscribe update frame. It # cannot exceed the transport ceiling. max_request_bytes = 26214400 # Largest encoded response or stream frame, in bytes. It cannot exceed the # transport ceiling. max_response_bytes = 26214400 # Most topics one Subscribe update may add. Not above max_stream_topics. max_update_adds = 100000 # Most topics one Subscribe update may remove. max_update_removes = 100000 # Most topics one Subscribe stream may hold. max_stream_topics = 100000 # Most topics in one SubscribeStatic request. max_static_topics = 10000 # Most identifiers in one GetInboxIds request. max_lookup_identifiers = 250 # Most smart contract wallet signatures in one verification request or one # identity update. max_scw_signatures = 100 # Most identity updates one inbox's identity log may hold. max_identity_entries = 256 # Most concurrent HTTP/2 streams on one connection. Open subscriptions count. max_http2_streams = 100 # Update frames per second one Subscribe stream may send, on average. max_update_frames_per_second = 10 # Update frames one Subscribe stream may send in a burst. max_update_burst = 100 # Ping frames per second one Subscribe stream may send, on average. max_ping_frames_per_second = 10 # Ping frames one Subscribe stream may send in a burst. max_ping_burst = 100 # Per-caller rate limits (RATE). On by default with the limits RATE section 3 # lists. Set `enabled = false` to turn them off. [rate_limits] enabled = true max_memory_mib = 100 # Networks your proxy connects from. Their X-Forwarded-For entries are # trusted. The default trusts none. trusted_proxies = ["10.0.0.0/8"] # Callers without credentials get a tighter publish limit. [rate_limits.categories.publish] ip = [{ count = 600, window_seconds = 60 }, { count = 10000, window_seconds = 3600 }] # One bot publishes without a limit. [[rate_limits.overrides]] api_key = "bridge-bot" [rate_limits.overrides.limits] publish = [] # One user of an identity provider may make more requests. [[rate_limits.overrides]] jwt_issuer = "https://auth.example.org" jwt_subject = "user-1234" [rate_limits.overrides.limits] request = [{ count = 20000, window_seconds = 60 }] # One office network shares an address and holds more streams. [[rate_limits.overrides]] ip = "203.0.113.7" [rate_limits.overrides.limits] stream_rent = [{ count = 1000, window_seconds = 60 }] [mls] # Largest group a client creates or grows. Clients apply it; the backend only # publishes it. max_group_members = 250 # Most installations a client keeps for one inbox. Clients apply it. max_installations_per_inbox = 10 # Whether clients publish and read the remote commit log for fork detection. commit_log_enabled = true [handles] # Shortest name part, the text before "#", that a new handle claim may have. # Handles claimed before a change stay valid. min_name_length = 3 [chains] # JSON-RPC URL of each EIP-155 chain that smart contract wallet signatures are # verified on. Clients see the chain ids, never the URLs. RPC URLs often carry # an API key, so keep them in environment variables. "eip155:1" = "env:XMTP_CHAIN_1_RPC_URL" "eip155:8453" = "env:XMTP_CHAIN_8453_RPC_URL" [auth] # Require a credential on every RPC except health and the configuration # service. Set it whenever [auth] is present. With false, the values of the # other keys of this table are not checked and no key set is loaded. enabled = true # URL of the identity provider's JWKS document, which holds the keys that # verify JWTs. Pick one of jwks_url and [[auth.keys]]. jwks_url = "https://auth.example.org/.well-known/jwks.json" # Audiences a JWT must name in its aud claim. Omit it to accept any audience. audiences = ["xmtp.example.org"] # Issuers a JWT's iss claim must equal. Omit it to accept any issuer. issuers = ["https://auth.example.org/"] # Scopes every JWT must carry. Clients read this list to request a token. required_scopes = ["xmtp.messaging"] # Clock skew, in seconds, allowed on a JWT's exp and nbf claims. leeway_seconds = 60 # Seconds between JWKS refreshes, before random jitter. jwks_refresh_seconds = 300 # Longest time, in seconds, the backend keeps serving after its last good JWKS # fetch. AUTH-034 sets its minimum from jwks_refresh_seconds. jwks_max_stale_seconds = 3600 # Inline signing keys, in place of jwks_url. Pick one of jwks_url and # [[auth.keys]]. A key change needs a restart. # [[auth.keys]] # # Key id that a JWT header names to select this key. Unique per key. # kid = "2026-10-signing" # # JWS algorithm of the key, one that AUTH-008 accepts. # alg = "ES256" # # PEM SubjectPublicKeyInfo text of the key, not a file path. # public_key = "env:XMTP_JWT_PUBLIC_KEY" [auth.api_keys] # Named API keys for callers you run, such as bots. The name identifies the # caller in logs; the value is the bearer token it sends, a long random string # of printable ASCII. Keep each value in an environment variable. notification-bot = "env:XMTP_API_KEY_NOTIFICATION_BOT" "support.bridge" = "env:XMTP_API_KEY_SUPPORT_BRIDGE" [push] # Seconds a push registration lives without renewal before the backend # deletes it. recipient_ttl_seconds = 2592000 # Provider attempts for each delivery, counting the first. max_attempts = 3 [push.apns] # APNs signing key: the PEM text of the .p8 file, not a path. key = "env:XMTP_APNS_KEY" # Apple's identifier for that signing key. key_id = "ABC123DEFG" # Apple developer team that owns the key. team_id = "DEF123GHIJ" # Bundle id of the app, sent as the APNs topic. bundle_id = "org.example.messenger" # APNs service: sandbox for development builds, production for App Store and # TestFlight builds. environment = "production" [push.fcm] # Firebase service account key: the JSON text, not a path. It selects the one # Firebase project this deployment sends through. service_account = "env:XMTP_FCM_SERVICE_ACCOUNT" [push.http] # Hosts that webhook URLs may use; "*." also allows every subdomain. Omit it to # allow any public host. Narrowing it also stops deliveries to earlier # registrations. allowed_domains = ["push.example.org", "*.hooks.example.net"] # Allow webhooks to private, loopback, and link-local addresses. For # development and tests only. allow_private_addresses = false [attachments] # Public URL prefix that clients download attachment ciphertext from, with no # trailing slash. Use HTTPS. base_url = "https://files.example.org/attachments" # Largest encrypted upload, in bytes. max_upload_bytes = 104857600 # Seconds the storage target keeps an object. Set it to the target's expiry # rule, or omit it when objects never expire. retention_seconds = 2592000 [attachments.target.S3] # S3-compatible API URL. The target must accept path-style requests. endpoint = "env:XMTP_S3_ENDPOINT" # Signing region of the target. region = "us-east-1" # Bucket that receives uploads. bucket = "example-xmtp-attachments" # Prefix of every object key. End it with "/" to place objects in a folder; # base_url must serve the same path. key_prefix = "attachments/" # Lifetime, in seconds, of each signed upload URL. presign_ttl_seconds = 900 [attachments.target.S3.credentials] # Where the backend gets the credentials it signs uploads with. Pick one kind; # prefer an ambient source to static keys. web_identity reads the web identity # token the platform provides. kind = "web_identity" # kind = "static" # # Static access key id. Use static keys only with a secret injector. # access_key_id = "env:XMTP_S3_ACCESS_KEY_ID" # # Static secret access key. # secret_access_key = "env:XMTP_S3_SECRET_ACCESS_KEY" # # Session token, for temporary static credentials. # session_token = "env:XMTP_S3_SESSION_TOKEN" # # The AWS SDK default provider chain. # kind = "default_chain" # # The standard AWS credential environment variables. # kind = "environment" # # The container credential endpoint. # kind = "container" # # The instance metadata service. # kind = "instance" # kind = "profile" # # Profile in the shared AWS configuration. # name = "xmtp-attachments" # kind = "sso" # # AWS account of the IAM Identity Center role. # account_id = "123456789012" # # Region of the IAM Identity Center instance. # region = "us-east-1" # # Role, or permission set, to sign in as. # role_name = "XmtpAttachments" # # IAM Identity Center start URL. # start_url = "https://example.awsapps.com/start" # # Optional session name. # session_name = "xmtp-backend" # kind = "process" # # Command that prints credentials in the credential_process format. # command = "/usr/local/bin/xmtp-s3-credentials" # kind = "assume_role" # # Role to assume, starting from credentials in the AWS default chain. # role_arn = "arn:aws:iam::123456789012:role/xmtp-attachments" # # External id that the role's trust policy requires, if any. # external_id = "xmtp-backend-prod" # # Optional session name. # session_name = "xmtp-backend" # Group metadata fields that clients add to the conversations they create. # Every key is required. Keep a published entry unchanged once conversations # use it. [[application_components]] # Field id. Never reuse an id for a different field. component_id = 0xC000 # Name apps look the field up by. Prefix a per-inbox field with USER_. name = "USER_STATUS" # Value shape: bytes, string, tls_map_bytes_bytes, tls_map_inbox_id_bytes, # tls_set_bytes, tls_set_inbox_id, or tls_map_inbox_id_string. component_type = "tls_map_inbox_id_string" # Who may add a value: allow, deny, allow_if_admin, allow_if_super_admin, or # allow_if_self_or_non_member, which is meant for an inbox-keyed map. insert_policy = "allow_if_self_or_non_member" # Who may change a value. update_policy = "allow_if_self_or_non_member" # Who may remove a value. delete_policy = "allow_if_self_or_non_member" # Add the field to new groups. in_groups = true # Add the field to new direct messages. in_dms = true [[application_components]] # An id in the write-once range: the value is set once and never changes. component_id = 0xFD00 # Name apps look the field up by. name = "TICKET_ID" # A single text value. component_type = "string" # Only admins may set the value. insert_policy = "allow_if_admin" # Write-once ids refuse every change. update_policy = "deny" # Write-once ids refuse every removal. delete_policy = "deny" # Add the field to new groups. in_groups = true # Leave it out of direct messages. in_dms = false ``` ## 2. What is published and what is not The backend publishes the values a client or an app acts on, on a request that needs no credential, and nothing else. Connection strings, key material, the JWKS URL, API key values, and credential-verification timing stay private. Of the auth configuration, a client acts on `enabled` and `required_scopes`; the key identities, audiences, and issuers are published for inspection. AUTH-001 through AUTH-003 own credential admission; [AUTH section 3](/specs/auth-backend-auth/#3-jwt-verification) defines the audience, issuer, and scope checks. The message is built once at startup from the validated configuration and the key set loaded then. A key set refreshed while the process runs is not republished. An operator changes what is published by restarting. ### 2.1 Public configuration wire format This is the public configuration wire format. An absent scalar reads as 0 or empty, which a client treats as not provided under CONF-025; `commit_log_enabled` carries explicit presence because absent and `false` mean different things. ```proto message GetConfigurationRequest {} // Admission settings a client needs before it holds a credential. Never // includes a JWKS URL, key material, leeway, or refresh timing. message AuthConfiguration { // Public identity of one accepted signing key. Never the key itself. message SigningKey { string kid = 1; string alg = 2; } bool enabled = 1; repeated SigningKey keys = 2; repeated string audiences = 3; repeated string issuers = 4; repeated string required_scopes = 5; } message RetentionConfiguration { uint64 group_message_seconds = 1; uint64 welcome_seconds = 2; uint64 key_package_seconds = 3; } // Request shapes the backend accepts. A client chunks its work to these values. message LimitsConfiguration { uint64 max_envelope_bytes = 1; uint64 max_request_bytes = 2; uint64 max_response_bytes = 3; uint32 max_publish_topics = 4; uint32 max_query_topics = 5; uint32 max_query_limit = 6; uint32 default_query_limit = 7; uint32 max_newest_metadata_topics = 8; uint32 max_newest_full_topics = 9; uint32 max_update_adds = 10; uint32 max_update_removes = 11; uint32 max_stream_topics = 12; uint32 max_static_topics = 13; uint32 max_lookup_identifiers = 14; uint32 max_scw_signatures = 15; uint32 max_identity_entries = 16; uint32 max_update_frames_per_second = 17; uint32 max_update_burst = 18; uint32 max_ping_frames_per_second = 19; uint32 max_ping_burst = 20; } // Advisory group shapes. The backend does not enforce these values. message MlsConfiguration { uint32 max_group_members = 1; uint32 max_installations_per_inbox = 2; // Absent means the client keeps its compiled default. optional bool commit_log_enabled = 3; } // Handle settings. message HandlesConfiguration { // The shortest name part, the text before "#", the backend admits in a claim. uint32 min_name_length = 1; } // One operator-defined application component. A client registers it in the // conversations the flags select; it carries no initial value. message ApplicationComponentDefinition { uint32 component_id = 1; string name = 2; xmtp.mls.message_contents.ComponentType component_type = 3; xmtp.mls.message_contents.ComponentPermissions permissions = 4; bool in_groups = 5; bool in_dms = 6; } message GetConfigurationResponse { // Stable operator-chosen name for this deployment. Never changes once // clients have connected. string identifier = 1; string server_version = 2; // Empty when the operator published no minimum. string min_libxmtp_version = 3; AuthConfiguration auth = 4; RetentionConfiguration retention = 5; LimitsConfiguration limits = 6; MlsConfiguration mls = 7; // CAIP-2 chain ids this backend verifies smart contract wallet signatures on. repeated string smart_contract_wallet_chains = 8; // Attachment storage this deployment offers; absent when it offers none. // The message and its rules are owned by ATCH section 1. xmtp.backend.v1.AttachmentsConfiguration attachments = 9; // Sorted by component_id ascending. repeated ApplicationComponentDefinition application_components = 10; // Set on every deployment. HandlesConfiguration handles = 11; } ``` | ID | Title | Requirement | Why | | -------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | CONF-017 | Public configuration wire format | The backend MUST answer `GetConfiguration` with the `GetConfigurationResponse` defined above, with the field numbers and types shown, and MUST NOT reuse a field number of any message above for another meaning. | | | CONF-010 | Published without a credential | The backend MUST answer `GetConfiguration` for a request that carries no credential, whatever the configured `auth.enabled`. | A client cannot learn that credentials are required if learning it requires one. | | CONF-079 | Publish application catalogue | When the backend answers `GetConfiguration`, it MUST set `application_components` to every configured application component under the wire block in section 2.1, sorted by `component_id` ascending. | Clients need a stable public view of the operator’s field definitions. | | CONF-011 | Nothing secret is published | The backend MUST NOT place in any field of `GetConfigurationResponse` a signing key’s key material, a JWKS URL, a database URL, a chain RPC URL, or an API key value. | The message has no access control, so the only protection a value has is not being in it. | | CONF-012 | Stable for a process | While a backend process is running, it MUST answer every `GetConfiguration` with the same `GetConfigurationResponse`. | | | CONF-069 | Published values are the applied values | The backend MUST set every field of `LimitsConfiguration`, `RetentionConfiguration`, and `HandlesConfiguration` to the value it enforces or applies for that key, every field of `MlsConfiguration` to the configured value, and `min_libxmtp_version` to the configured minimum or to the empty string when none is configured. It MUST set `retention`, `limits`, `mls`, and `handles`, and MUST NOT set a numeric field of those four messages to 0. | A client reads 0 as “not provided” (CONF-025), so a 0 for a value the backend enforces tells the client to use a different one. | | CONF-068 | Auth summary equals enforcement | The backend MUST set `AuthConfiguration.enabled` to the configured `auth.enabled`. While that is `true`, it MUST set `keys` to the `kid` and `alg` of each signing key accepted at startup and `audiences`, `issuers`, and `required_scopes` to the values it checks credentials against; while it is `false`, it MUST leave every other field of `AuthConfiguration` empty. | Leftover scopes from a disabled table would tell a client to satisfy demands nothing checks. | | CONF-070 | Published chains are the verifiable set | The backend MUST set `smart_contract_wallet_chains` to the CAIP-2 identifier of every chain it verifies smart contract wallet signatures on, and to no other. | | ## 3. The snapshot A client resolves its snapshot once, when it is created, and reads it for its life. The client configures itself from the values it receives from the server. A changed value takes effect for a client created afterwards. Two conditions block a client’s connection: a different deployment answering, and a raised minimum version. The blocked connection lasts for the life of the client. It fails operations that would reach the backend and closes streams that hold network interest with its error. Local event subscriptions stay open under EVENT-016. Which cause the client reports when both arise is the implementation’s choice. PROC-002 owns durable receipt and PROC-005 owns processed positions. Closing a stream can leave received work above the processed position; it does not erase that work. A field the snapshot does not carry, or carries as 0 or empty, takes the compiled default below. Section 1.2 gives the key each field is published from a backend default with the same meaning. | Field | Default value | | -------------------------------------- | --------------------------------------------------------------------------------------- | | `min_libxmtp_version` | No minimum: every client version is accepted | | `auth` | `enabled` `false`, every list empty | | `retention.group_message_seconds` | 7776000 | | `retention.welcome_seconds` | 7776000 | | `retention.key_package_seconds` | 7776000 | | `limits.max_envelope_bytes` | 1048576 | | `limits.max_request_bytes` | 26214400 | | `limits.max_response_bytes` | 26214400 | | `limits.max_publish_topics` | 1000 | | `limits.max_query_topics` | 1000 | | `limits.max_query_limit` | 1000 | | `limits.default_query_limit` | 100 | | `limits.max_newest_metadata_topics` | 1000 | | `limits.max_newest_full_topics` | 100 | | `limits.max_update_adds` | 100000 | | `limits.max_update_removes` | 100000 | | `limits.max_stream_topics` | 100000 | | `limits.max_static_topics` | 10000 | | `limits.max_lookup_identifiers` | 250 | | `limits.max_scw_signatures` | 100 | | `limits.max_identity_entries` | 256 | | `limits.max_update_frames_per_second` | 10 | | `limits.max_update_burst` | 100 | | `limits.max_ping_frames_per_second` | 10 | | `limits.max_ping_burst` | 100 | | `mls.max_group_members` | 250 | | `mls.max_installations_per_inbox` | 10 | | `mls.commit_log_enabled` (absent) | `true` | | `handles.min_name_length` | 3 | | `smart_contract_wallet_chains` (empty) | No chain: every app-supplied smart contract wallet signature is rejected under CONF-046 | | `attachments` (absent) | No attachment storage: creation fails under ATCH-030 | | `attachments.max_upload_bytes` | 104857600 | | `attachments.retention_seconds` | No expiry | `identifier` has no default: an empty one is rejected under CONF-071. A present `commit_log_enabled` of `false` is not a missing value; it switches the commit log off under CONF-045. | ID | Title | Requirement | Why | | -------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | CONF-020 | One snapshot per client | The client MUST NOT replace its snapshot after it is created, whatever a later fetch returns. | | | CONF-025 | Absent means the compiled default | When a field of a snapshot is 0, empty, or absent, the client MUST use the value the table above gives for that field. | | | CONF-075 | Blocked connection stops network work | While the client has a blocked connection, every operation that would publish an envelope, publish or apply an identity update, or sync a group MUST fail with the blocked connection’s error before any request is sent, and every open stream that holds network interest MUST close with that error. | The client has lost its binding or been refused by the deployment. Network work against that deployment cannot succeed. | ## 4. Fetching, storing, and binding A client fetches the public configuration once, stores it with the backend URL, and reads the stored copy on every later creation. A stored copy that does not decode reads as the compiled defaults, with its identifier kept for CONF-030. The identifier binds the database to a deployment. The URL does not, because an operator moves a deployment to a new address; a changed URL only triggers a re-check (CONF-033). A stored copy whose identifier is empty binds nothing. A client validates an answer before it stores it (CONF-071). A `uint64` above 2^53 - 1 is rejected because the JavaScript number cannot hold it exactly. A client does not require the application catalogue sorted, and accepts a `component_type` or policy value it does not know and a name equal to a well-known component name, all of which the backend refuses (CONF-078, CONF-079). A newer deployment may publish any of them, and the committed group registry, not the catalogue, governs what a conversation accepts. An app may create a client that does no network work (CONF-034). A client told to reach the deployment that cannot fails under CONF-027 and does not fall back to working offline. | ID | Title | Requirement | Why | | -------- | ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | CONF-098 | Backend requests stay at their origin | When a client is built for a backend URL, the client MUST reject it before sending any request if its parsed path is neither empty nor `/`, or if it has a query, a fragment, a non-empty username, or a password. When it sends a backend RPC, the client MUST use the configured scheme and authority with the RPC path and MUST NOT follow an HTTP redirect. | URL components and redirects can send credentials and traffic to a different route or origin on different platforms. | | CONF-026 | Fetch before other work | When a client that may reach the backend is created on a database with no stored copy, the client MUST send `GetConfiguration`, apply CONF-071 and CONF-030 to the answer, and store the answer with the backend URL, before it sends any other request. | Identity work is sized by the limits and bound by the identifier. Run first, it can register an installation on the wrong deployment. | | CONF-027 | Failed first fetch | If the fetch under CONF-026 or CONF-033 fails, or its answer cannot be stored, then the client MUST fail creation and MUST NOT use the compiled defaults in place of the answer. | Compiled defaults would bind the database to nothing and size every request to values this deployment never published. | | CONF-071 | Reject an unusable answer | If a `GetConfigurationResponse` carries an `identifier` that CONF-002 would refuse, a non-empty `min_libxmtp_version` that is not a version under [Semantic Versioning 2.0.0 §2](https://semver.org/spec/v2.0.0.html#spec-item-2), a `smart_contract_wallet_chains` entry that does not match the syntax of [CAIP-2](https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-2.md#syntax), a `uint64` or `uint32` field of `retention`, `limits`, or `mls` greater than 9007199254740991, or an `application_components` entry whose `component_id` is outside `0xC000`–`0xFEFF`, whose `name` is not 1 to 100 UTF-8 bytes, whose `component_type` is not positive, whose member policy is absent, unspecified, or an empty condition at any depth, whose `in_groups` and `in_dms` are both false, or whose `component_id` or `name` repeats an earlier entry’s, then the client MUST reject it and MUST NOT store it. | | | CONF-029 | Fetch carries no credential | When the client sends `GetConfiguration`, it MUST NOT attach a credential and MUST NOT invoke the app’s credential source. | | | CONF-030 | Identifier binds the database | When a `GetConfigurationResponse` carries an `identifier` that differs from the stored copy’s non-empty `identifier`, the client MUST record the received identifier as a conflict in the stored copy, MUST block the connection with a backend mismatch naming both identifiers whether or not the record succeeded, and MUST NOT store the answer. | Stored positions, group state, and identity state are meaningful only against the deployment that issued them. | | CONF-072 | A recorded conflict fails creation | When a client is created on a database whose stored copy records a conflict, the client MUST fail creation with a backend mismatch naming the stored and the conflicting identifier, without sending any request. | | | CONF-031 | A conflict is permanent | The client MUST NOT clear a recorded conflict, including when a later answer’s `identifier` equals the stored one. | A database that has seen two deployments cannot be shown to hold consistent state for either. Only a database created for the deployment in use can. | | CONF-033 | A moved deployment is re-checked | When a client that may reach the backend is created on a database whose stored copy carries a backend URL that differs from the client’s backend URL, the client MUST send `GetConfiguration`, apply CONF-071 and CONF-030, and store the answer with the new URL, before it sends any other request. | | | CONF-034 | Offline creation | Where an app creates a client that may not reach the backend, the client MUST use the stored copy when the database has one and the compiled defaults when it does not, and MUST NOT send `GetConfiguration`. | | | CONF-076 | Offline creation ignores a moved URL | Where an app creates a client that may not reach the backend, the client MUST NOT fail creation because the stored copy’s backend URL differs from the client’s backend URL. | An app that moved its backend URL must still open offline; CONF-077 re-checks before the first request. | | CONF-077 | Offline URL re-check before first request | When a client created under CONF-034 on a database whose stored copy carries a backend URL that differs from the client’s backend URL is about to send its first request after creation, it MUST send `GetConfiguration`, apply CONF-071 and CONF-030, and store the answer with the new URL before it sends that request, and MUST fail that request when this does not complete. | Otherwise a database for one deployment sends its identity and group traffic to another deployment before any identifier check. | ## 5. Refreshing A refresh rewrites the stored copy and never the running snapshot (CONF-020). It can stop a live client in the two cases of section 3; everything else it learns takes effect when a client is next created on that database. The client refreshes on its own schedule, spread at random. The interval, the spread, and the number of attempts in one run are the implementation’s choice. A refresh is never driven by a failed request, and a failed refresh leaves the stored copy unchanged. | ID | Title | Requirement | Why | | -------- | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --- | | CONF-040 | Refreshes are persisted | When a refresh returns an answer that passes CONF-071 and whose `identifier` equals the stored copy’s, the client MUST replace the stored copy with that answer. | | | CONF-036 | A raised minimum | When a refresh returns a `min_libxmtp_version` that is greater than the client’s version under CONF-050, the client MUST store the answer and MUST block the connection because the client is too old, naming both versions. | | | CONF-037 | A failed refresh changes nothing | If a refresh does not return an answer that passes CONF-071, then the client MUST keep the stored copy unchanged and MUST NOT fail any other operation because of it. | | ## 6. Applying the snapshot The client splits and bounds its requests to the published limits, so that a request the backend would reject is never sent. The table below names the bound for each request; one bound is fixed rather than published. The fields it does not name (`max_response_bytes`, `max_stream_topics`, `max_identity_entries`, `max_ping_frames_per_second`, and `max_ping_burst`) are published for an app to read. The client paces `Update` frames to `max_update_frames_per_second` and `max_update_burst` (CONF-093). API-281 and API-282 own response and request bounds, API-234 owns the identity-log limit, and API-258 owns the backend’s stream frame rate limits. | Request | Bound | | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Publish | Encoded request not longer than `max_request_bytes`; distinct topics not more than `max_publish_topics`; each envelope not longer than `max_envelope_bytes`; envelopes not more than the fixed envelope bound of API section 7 | | Query | Topics per request not more than `max_query_topics`; `limit` not more than `max_query_limit` | | QueryNewest | Topics per request not more than `max_newest_full_topics` with full envelopes and `max_newest_metadata_topics` without | | GetInboxIds | Identifiers per request not more than `max_lookup_identifiers` | | VerifySmartContractWalletSignatures | Signatures per request not more than `max_scw_signatures`; encoded request not longer than `max_request_bytes` | | SubscribeStatic | Topics per stream not more than `max_static_topics` | | Subscribe update | `adds` not more than `max_update_adds`; `removes` not more than `max_update_removes`; encoded frame not longer than `max_request_bytes` | Group size and installation count are advisory: the backend has no view of the state they are about, so only a client can check them (Known limitations). [GMOD section 2](/specs/gmod-modifying-groups/#2-the-membership-component) owns group membership; [IDENT section 8](/specs/ident-identity-updates/#8-installations) defines the installations in an association state. [FORK](/specs/fork-fork-recovery/) owns the commit log; this spec owns only the switch. The chain check runs on a signature an app is about to produce. It does not run on a signature read from the network, which the network already accepted, or when the app supplied its own verifier. PROC-012 owns the preservation of unresolved work. The version gate and the credential requirement fail creation, so an app gets one clear reason instead of every request failing. `handles.min_name_length` is published for an app, which may check a name a user types against it before a claim. Only the backend applies it, when it admits a claim (section 1). | ID | Title | Requirement | Why | | -------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | CONF-073 | Size every request to its bounds | The client MUST split or bound every request it sends so that it stays within each bound in the table above. When one envelope alone is longer than `max_envelope_bytes`, the client MUST reject the publish before it sends any request. | | | CONF-093 | Pace updates to the snapshot | The client MUST send `Update` frames on each `Subscribe` stream no faster than the snapshot’s `max_update_frames_per_second` with a burst of `max_update_burst`, counting the `Update` it sends when it opens the stream. | The backend fails a stream whose `Update` frames arrive faster than these values (API-258), so a client that paces to its compiled defaults loses its stream on ordinary interest changes when a deployment publishes lower values. | | CONF-043 | Advisory group size | When the number of distinct inboxes in a group’s `GROUP_MEMBERSHIP` component plus the inboxes a change would add is greater than `max_group_members`, the client MUST reject the change before it builds a commit. | | | CONF-044 | Advisory installation count | When the number of installations an inbox’s association state names is not less than `max_installations_per_inbox`, the client MUST NOT register a new installation for that inbox. | | | CONF-045 | Commit log follows the deployment | While the snapshot’s `commit_log_enabled` is `false`, the client MUST NOT publish a commit-log entry and MUST NOT read the commit log. | A deployment that keeps no commit log would be sent entries it discards, and clients would read an always-empty log as evidence about groups. | | CONF-046 | Only published chains are accepted | When an app that supplied no verifier of its own supplies a smart contract wallet signature whose CAIP-2 chain id is not in `smart_contract_wallet_chains`, the client MUST reject it before it sends any request, naming the chain and the accepted chains. | | | CONF-048 | Chains and received data | The client MUST NOT apply CONF-046 to a signature it reads from a received identity update or envelope. | A signature the network already accepted is a fact. Refusing it would hold the client on that envelope for ever. | | CONF-049 | Too old to run | When the snapshot’s `min_libxmtp_version` is greater than the client’s version under CONF-050, the client MUST fail creation, naming both versions. | | | CONF-050 | Version compare ignores prerelease | When the client compares its version with a `min_libxmtp_version`, it MUST compare the major, minor, and patch numbers in that order ([Semantic Versioning 2.0.0 §11](https://semver.org/spec/v2.0.0.html#spec-item-11)) and MUST ignore the pre-release and build metadata of both. | A prerelease build of the version the operator named would otherwise be too old, which stops every development build. | | CONF-051 | Credentials required but absent | When the snapshot’s `AuthConfiguration.enabled` is `true` and the app supplied no credential source, the client MUST fail creation and MUST report `required_scopes`. | | | CONF-081 | Client never applies name minimum | The client and an SDK MUST NOT fail an operation, and MUST NOT omit a handle from a result they return to an app, because a handle’s name part is shorter than the snapshot’s `handles.min_name_length`. | A snapshot can be older than the deployment’s setting (CONF-020), and a raised minimum leaves the shorter handles claimed before it valid. A client that applied it would refuse a claim the backend admits, and hide a handle that other clients show. | AUTH-020 owns when the client attaches a credential, including when `enabled` is `false` and the app supplied a source. ## 7. What an app can read An app needs the public configuration before a client exists, to choose credentials, scopes, and chains, so it is readable from a backend URL alone. After that it reads the snapshot the client holds, which under CONF-020 can differ from what the deployment publishes now. | ID | Title | Requirement | Why | | -------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --- | | CONF-061 | Apps read the snapshot | An SDK MUST expose to an app the snapshot the client holds, with every field of `GetConfigurationResponse`. | | | CONF-062 | Reading before building | An SDK MUST let an app fetch a deployment’s `GetConfigurationResponse` from a backend URL alone, with no database, no client, and no credential, and MUST apply CONF-071 to the answer. | | | CONF-074 | Explicit refresh | An SDK MUST let an app start a refresh, and that refresh MUST apply CONF-071, CONF-030, CONF-036, and CONF-040 and return the fetched configuration. | | | CONF-064 | Failures are distinguishable | An SDK MUST let an app distinguish, as distinct error kinds, an unreachable deployment or an unstorable answer (CONF-027), an invalid answer (CONF-071), a backend mismatch (CONF-030, CONF-072), a client that is too old (CONF-049, CONF-036), a missing credential source (CONF-051), and a chain that is not accepted (CONF-046). | | ## Known limitations An advisory value binds only a client that applies it. A modified client can exceed the published group size or installation count, and the deployment will not notice. These values are a deployment’s policy for cooperating clients, not a protection against a hostile one. The backend does not read a client’s version on a request. `min_libxmtp_version` is applied by the client alone, at creation and at refresh, so a client that never refreshes keeps working against a deployment that has raised its minimum. A deployment behind one address may be more than one process, and two of them may hold different configurations during a rolling change. A client holds whichever it fetched. A limit lowered on one of them is still enforced by that one, so the client’s request is rejected rather than silently accepted; a differing identifier across processes is an operator error and stops every client that reaches the odd one. An operator’s change reaches an existing client’s stored copy within one refresh interval and its behaviour only when a client is next created. If every refresh fails there is no upper bound on how stale a stored copy may be; the client keeps using it rather than falling back to the compiled defaults. A deployment that lowers `max_update_frames_per_second` or `max_update_burst` can fail the `Subscribe` streams of clients created before the change with `RESOURCE_EXHAUSTED` (API-258), because each client paces to the snapshot it was created with (CONF-020) until it is created again. The backend counts an `Update` frame when it arrives, and the client counts it when it sends it. The client leaves 500 ms more than the published refill interval between frames beyond the burst. When an earlier frame is held back, for example by a TCP retransmission, later frames on the same stream queue behind it and arrive together. If the earlier frame’s delay exceeds a later frame’s delay by more than 500 ms, those frames can exceed the backend’s bucket and fail the stream with `RESOURCE_EXHAUSTED`; the client then opens a new stream. An app that checks a name against the snapshot’s `handles.min_name_length` uses the value from when the client was created (CONF-020). After the operator changes the setting, such an app can refuse a name the backend admits, or pass a name the backend refuses. The backend’s answer to the claim decides. Anyone who can reach the backend API can read the public configuration, including the auth summary and the accepted chains (CONF-010). CONF-011 keeps it harmless to disclose. `GetConfiguration` is not rate limited. A string value that begins with `env:` is always an environment reference, so a literal value with that prefix cannot be written. A value that is not a secret value can come from an environment reference and still appear in output. The deployment identifier is on spans and logs under OPS-013, and OPS-022 names a metrics address that fails to bind. CONF-097 binds the keys a file holds and the units of their values. It does not bind the defaults of keys the file omits, or whether a later release still applies a key it accepts. A later release can change a default, and with it the behaviour of a deployment that relies on that default. The backend starts with auth disabled, with a store link that does not verify the server’s certificate and host, and with a chain RPC URL in plain HTTP, because CONF-097 keeps a file that an earlier release accepted valid. CONF-095 logs each one; it does not refuse it. # Consent Consent decides what a user sees. An allowed conversation is listed, streamed, and pushed. A denied one is hidden. An unknown one is listed as a request, so the user can decide on it. Every installation of the user’s inbox can decide, and installations never coordinate. They exchange records over the sync group (`SYNC`) and through archives (`ARCH`). Four rules give every installation the same answer, in any order: 1. **One record per conversation.** A group’s record is keyed by its group id. A DM’s record is the other member’s inbox record, so one decision covers every DM with that person (CONS-052). 2. **The greater record wins.** Records compare by consent time, then by state: denied over allowed over unknown (CONS-053). 3. **A received time is capped** at one day after the envelope time of the sync message that carries it, or, from an archive, one day after the current time (CONS-054). 4. **A decision comes after what this installation has seen**, so the newest decision wins even on a slow clock (CONS-055). Only the user stores allowed or denied: by deciding, by creating a conversation, or by sending in one. A join stores nothing, and that includes a join after a removal (CONS-058). ```mermaid flowchart LR D[App sets, creates, or sends] -->|decision, CONS-055| R[(One record per key)] P[Peer installation or archive] -->|capped, greater wins| R R --> L[Listing, streams, push] R -->|every change| S[Other installations, SYNC] ``` Non-goal: a backend that falsifies envelope times. CONS-054 uses them as given. ## Scope In scope: consent states, keys, the wire form, which record wins, what the client stores on its own, how consent filters listings and streams, and what an SDK exposes. Out of scope: how records travel and when they are published (`SYNC`), the dm id and the peer of a DM (`DMS`), stream delivery (`PROC`), push (`PUSH`), readd requests (FORK-053, FORK-080), and the archive container (`ARCH`). A device clock that is more than a day off is out of scope. | Related | Relation | | ------------------ | ---------------------------------------------------------------------------------------------------------- | | `SYNC` | Carries records between installations. SYNC-027 marks the changes to publish. | | `DMS` | Owns the dm id (DMS-001), the peer of a DM (DMS-017), and the group an app sees for a DM (DMS-007). | | `JOIN` | Owns the join. CONS-058 owns what a join stores: nothing. | | `PUSH` | Owns which conversations produce push notifications. It reads conversation consent. | | FORK-053, FORK-080 | Own acceptance and response to readd requests, including consent checks. | | `ARCH` | Owns the archive. An imported record is merged under CONS-053. | | `MIG` | Converts a pre-8.0 database. MIG-009 writes a peer’s DM rows as one inbox record under CONS-061. | | `EVENT` | EVENT-001 owns `consent.changed` emission. EVENT-030 and EVENT-031 own queue loss and the `lagged` report. | ## Terms | Term | Meaning | | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Consent record | A key, a state, and a consent time. | | Key | What a record is about: a group or an inbox. CONS-052 defines it. | | Conversation consent | The record CONS-052 assigns to a conversation. For a DM, it is the other member’s inbox record. | | Consent time | When the state was decided, in nanoseconds since the Unix epoch. | | Decision | A record the client stores because the user acted: CONS-055, CONS-056, or CONS-057. | | Merge | Storing a record that carries its own time, under CONS-053. | | Consent filter | The set of states an app passes when it lists or streams conversations or messages. An absent filter and an empty filter are different things. | | Listing time | The time a conversation listing orders by: a conversation’s creation time when the app orders by creation, and its last-activity time under CONS-048 otherwise. | ## 1. Records and keys A record is unknown, allowed, or denied. Unknown is both a stored state and the state of a key with no record; an app and a filter cannot tell them apart. Conversation consent gates listing and streaming (section 4), push (`PUSH`), and readd requests (FORK-053, FORK-080). An inbox record is also the consent of every DM with that inbox. Peers (`SYNC`) and archives (`ARCH`) share one wire form: ```proto message ConsentSave { ConsentTypeSave entity_type = 1; ConsentStateSave state = 2; string entity = 3; int64 consented_at_ns = 4; } enum ConsentTypeSave { CONSENT_TYPE_SAVE_UNSPECIFIED = 0; CONSENT_TYPE_SAVE_CONVERSATION_ID = 1; CONSENT_TYPE_SAVE_INBOX_ID = 2; CONSENT_TYPE_SAVE_ADDRESS = 3 [deprecated = true]; } enum ConsentStateSave { CONSENT_STATE_SAVE_UNSPECIFIED = 0; CONSENT_STATE_SAVE_UNKNOWN = 1; CONSENT_STATE_SAVE_ALLOWED = 2; CONSENT_STATE_SAVE_DENIED = 3; } ``` | ID | Title | Requirement | Why | | -------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | CONS-001 | No record is unknown | When an app reads the consent of an entity, or a consent filter is applied to a conversation, the client MUST report and filter an entity with no record as unknown. | | | CONS-050 | One wire form | When the client encodes a record for a peer installation or an archive, it MUST encode it as the `ConsentSave` above, with `entity_type` conversation for a group key and inbox for an inbox key, `entity` set to the key under CONS-052, and `state` and `consented_at_ns` set to the record’s values. | Two installations that encode one key differently hold two records and never merge them. | | CONS-051 | Skip an unusable record | When a received or imported `ConsentSave` has `entity_type` `CONSENT_TYPE_SAVE_UNSPECIFIED` or `CONSENT_TYPE_SAVE_ADDRESS`, `state` `CONSENT_STATE_SAVE_UNSPECIFIED`, or an `entity` longer than 256 bytes, the client MUST NOT store it and MUST go on with the other records. | An archive from early 2025 can hold address records, and failing on one loses every record after it. A record too large for a sync message would stop every publish behind it. | | CONS-052 | One record per conversation | The client MUST key the consent of a group by its group id in lowercase hexadecimal, of an inbox by its inbox id in lowercase, and of a DM by the inbox id of its other member under DMS-017, as an inbox record; a DM whose dm id does not name the own inbox has no key. When an app sets the consent of a conversation by group id, the client MUST use the key of the conversation it holds under that id, and MUST return an error and store nothing when it holds none. Any other record MUST be stored under the key it names, except as CONS-061 moves it. | Either inbox can start another group for a DM at any time, and a block stored per group leaves the new group unblocked. A record stored under a group id the client does not hold is never read by a DM that arrives later. Moving it then would let a former member of a group, who can build a DM with that group’s id (JOIN Known limitations), take over the user’s decision about the group. | ## 2. Which record wins Applied in any order, and any number of times, a set of records leaves the same record on every installation that has seen them all. | ID | Title | Requirement | Why | | -------- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | CONS-053 | The greater record wins | When the client merges a record, it MUST store it when the key has no record, or when its consent time is greater than the stored one, or when the times are equal and its state is greater, with denied over allowed over unknown; otherwise it MUST leave the stored record unchanged. | One order on records gives every installation the same answer whatever order records arrive in. | | CONS-054 | A received time is capped | When the client merges a record whose consent time is more than one day after the envelope time of the sync message that carries it, or, from an archive, more than one day after the client’s current time, it MUST merge it with that limit as its consent time. | A time far ahead would beat every later decision. Measured from the envelope time, the limit gives every receiver the same value whatever its clock. A record that is capped, not refused, still arrives. | | CONS-055 | A decision comes after what was seen | When an app sets the consent of a key, or the client stores allowed under CONS-056 or CONS-057, the client MUST store the state at the greater of its current time and the stored consent time plus one nanosecond, even when the state is unchanged. | A decision must beat every record its installation saw, even on a slow clock. A repeated decision must move the time forward, or it loses to one made elsewhere in between. | ## 3. What the client writes | When | The client stores | Rule | | ----------------------------------------------------------------- | ------------------------------------------------------- | ------------------ | | The app sets a state | That state, as a decision | CONS-055 | | The app creates a group or a DM | Allowed, as a decision, unless the user already decided | CONS-056 | | The app sends a message, other than a deletion or a leave request | Allowed, as a decision, unless it already reads allowed | CONS-057 | | A Welcome adds the user, for the first time or again | Nothing | CONS-058 | | A peer or an archive sends a record | The record, capped and merged | CONS-053, CONS-054 | | ID | Title | Requirement | Why | | -------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | CONS-056 | Creating allows | When the client creates a group or a DM at an app’s request and the conversation’s record is absent or unknown, it MUST store allowed for it under CONS-055. | A conversation the user started must not be a request. A DM with a person the user blocked stays blocked when the app opens it again. | | CONS-057 | Sending allows | When the client queues a message an app sent, other than a message deletion or a leave request, in a conversation that does not read allowed, it MUST store allowed for it under CONS-055, in the transaction that queues the message. When it reads allowed, the client MUST NOT store a record. | A conversation the user replied in must not stay a request. An allow stored after the send is lost if the process ends first. A record stored on every send is published on every send. Leaving is not a reply. | | CONS-058 | Joining stores nothing | When the client completes a join from a Welcome, including a join to a group it was removed from or left, it MUST NOT store a consent record. | Another inbox chooses whom to add and whom to add back, and a group can name anyone as its creator. A removed installation cannot tell a re-add from a second MLS group that a former member built under the same id (JOIN-083), so a re-add changes nothing the user decided. | ## 4. Gating listing and streaming An app can filter conversation listings and streams by consent state. The client returns or delivers only conversations in the requested states, and a conversation with no record counts as unknown (CONS-001). An empty filter names no state and so includes nothing; it is not the same as no filter. Without a filter, a listing and a message stream across conversations include allowed and unknown conversations. A conversation stream without a filter includes every consent state. PROC-047 owns default delivery progress when a message filter excludes a candidate. A message listing within one conversation is not filtered: the app named the conversation. A sync group is never listed or streamed unless the app asks for sync groups (SYNC-005). | ID | Title | Requirement | Why | | -------- | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | CONS-060 | The filter is on conversation consent | When an app lists or streams conversations, or streams messages across conversations, with a consent filter, the client MUST include only conversations whose conversation consent under CONS-052 is in the filter, so that an empty filter includes none. | A DM’s consent is its peer’s inbox record. A filter that reads only group records would list a blocked person’s DMs. | | CONS-031 | Default listing excludes denied | When an app lists conversations with no consent filter, the client MUST return the conversations whose conversation consent is allowed or unknown and MUST NOT return one whose consent is denied. | A denied conversation that appears is the block failing; an unknown one that disappears can never be decided on. | | CONS-042 | Default all-message stream | When an app streams messages across all its conversations with no consent filter, the client MUST deliver only messages from conversations whose conversation consent is allowed or unknown, as CONS-031 does for listings. | Messages from a denied conversation must not reach an app that used the default consent choice. | | CONS-043 | One conversation stream | When an app streams messages from one named conversation with no consent filter, the client MUST NOT filter that stream by the conversation’s consent state. | The app has selected that conversation explicitly. | | CONS-044 | Default conversation stream | When an app streams conversations with no consent filter, the client MUST deliver new conversations of every consent state. | An app that hides a new denied conversation cannot show it in a blocked list. | | CONS-046 | Conversation page size | When an app lists conversations, an SDK MUST return at most the `limit` the app names, or at most 100 conversations when the app names none, and MUST fail the call with an invalid-argument error when `limit` is less than 1 or greater than 1000. | The default listing includes unknown conversations (CONS-031), so without a page size one call returns every conversation that any stranger creates for the user. | | CONS-047 | Pages resume after ties | When an app lists conversations with a before time and a conversation id, an SDK MUST return only conversations whose listing time is less than that time, or equal to it with a group id lower in byte order than that conversation’s group id. | A cursor of time alone skips every conversation that shares the boundary time, and a sender can give many conversations the same last-activity time. | | CONS-049 | Pages are ordered | When an app lists conversations, an SDK MUST return the matching conversations in order of descending listing time and then descending group id in byte order, starting with the first that CONS-047 admits, up to the page size of CONS-046, where the listing time is the creation time in creation order and the CONS-048 time in activity order; when the app names a before conversation id without a before time, the SDK MUST fail the call with an invalid-argument error. | A page that may hold any matching subset, or that orders ties by ascending id, skips or repeats every conversation that shares the boundary time, even with the CONS-047 cursor. | | CONS-048 | Activity time matches the listing | When an app reads a conversation’s last-activity time without naming content types, an SDK MUST return the greatest send time among the conversation’s unexpired application messages that an activity-ordered listing counts, or its creation time when there is none. An activity-ordered listing MUST use that same time as its listing time under CONS-049. | An app pages an activity-ordered listing with this time, and a time that counts an expired message names a later boundary than the listing used and returns the same conversations again. | ## 5. What an app can read and set An app reads consent to build its inbox and its request list, sets it when the user decides, and follows changes that arrive from the user’s other installations. A `consent.changed` event tells the app to read the record again. If the event queue discards a change, EVENT-031 reports it through `lagged`. An app names conversations by group id, so a DM is also reported under the group the app lists. | ID | Title | Requirement | Why | | -------- | --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | CONS-041 | Read set and follow consent | An SDK MUST let an app read and set the consent of a conversation and of an inbox, and subscribe to `consent.changed` events under EVENT-001, subject to EVENT-030 and EVENT-031. | An app cannot update its view after a change on another installation without a change signal. | | CONS-059 | Apps see group ids | When an SDK reports a change to an inbox record in an event or a stream, it MUST also report it for the DM with that inbox, named by the group id that DMS-007 returns, when the client holds one. It MUST NOT report a change to a group record as a change to a conversation whose CONS-052 key is a different record. When it reports a DM’s consent in a read, it MUST report the conversation consent of CONS-052. | An app keys conversations by group id and redraws a DM only when its group id is reported. An event must agree with the read that follows it. | ## 6. Records written before 8.0 Before 8.0, a DM’s consent was its group’s record, and inbox records decided no DM. The time of a pre-8.0 record is when the row was first created, not when its state was last set. So the time of a DM record and the time of an inbox record cannot say which decision is newer. | ID | Title | Requirement | Why | | -------- | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | CONS-061 | Pre-8.0 DM records | When the client receives or imports a record that names a 16-byte group id held as a DM, it MUST store the record under that DM’s key under CONS-052. When an archive carries a 16-byte DM group that the client holds, whether or not its import stored it, the client MUST combine the archive’s records for every 16-byte DM it holds with that DM’s peer and the archive’s inbox record for the peer into one inbox record whose state is the strongest of theirs, denied over allowed over unknown, and whose consent time is the greatest of their times. When the client restores a 16-byte DM while it holds a record under that DM’s group id, it MUST merge the record into the DM’s key under CONS-053 and remove it. | An archive written before 8.0 names a DM by its 16-byte group id, which no Welcome can activate (JOIN-083), so moving it cannot give another inbox control of the record. Pre-8.0 times are first-insert times, so they cannot order the rows; the strongest state never weakens a block the user saw, in either the DM or the inbox read. The greatest time lets the combined record replace each of its sources, and the same archive imported twice gives the same record. | ## Known limitations Two installations that decide on one key without seeing each other’s decision are ordered by their clocks. The decision made later in real time loses when its installation’s clock is behind. A compromised own installation can store a record up to a day after its message’s envelope time before it is revoked; the user’s next decision replaces it. An archive carrying a time more than a day ahead of the import is capped at the importing clock, so importing it again later can raise that record above a decision made in between. A join stores nothing. When another inbox removes the user from a group and adds the user back, or a former member builds a second MLS group under its id (JOIN-083), the conversation keeps the user’s earlier decision, including an allow. An archive written before 8.0 stores each record at the time its row was first created, not the time of its latest state, and rows older than 2025 at time 0. Between two such group records, or two such inbox records, for one key, the later-created row wins. CONS-061 combines a peer’s DM records only within one archive; across two archives, they merge by time. The combined record keeps the strongest state, so a DM the user allowed reads denied when another DM with that person, or that person’s inbox, read denied. When such an archive leaves out a DM’s group, the DM’s record names a 16-byte group id that nothing reads until that DM is restored. Those clients also allowed a group whose creator field named the user, and the archive carries that allow as a decision. An app cannot set the consent of a conversation the client does not hold yet. It can set the consent of the other member’s inbox, which covers every DM with that person. Inbox consent decides DMs only. Denying an inbox hides its DMs but not the groups it adds the user to; only a group’s own record does. A DM restored from another inbox’s archive has a dm id that does not name the own inbox (DMS-017). It has no key, reads unknown, and cannot be set. In activity order, a conversation whose last-activity time changes between two pages, because a message arrives or expires, can be returned twice or skipped. In creation order, a group’s creation time does not change, so each conversation is returned once, with two exceptions. A DM whose listed group changes between two pages, because a message arrives in another group for the same DM identifier (DMS-007, DMS-013), is then listed with that group’s id and creation time, so it can be returned twice or skipped. A restored group whose Welcome arrives between two pages takes the Welcome’s processing time as its creation time, so it can be skipped. # Content types How a message payload declares what it is, so that a client which does not understand a type can still show something useful rather than nothing. Every application message a client publishes carries an `EncodedContent`: a content type identifier, the content bytes, the parameters a decoder needs, and optional fallback text. The identifier names an authority, a type, and a version. A codec is the pair of functions that turn a value into an `EncodedContent` and back for one identifier. This spec owns the identifier scheme, the envelope, what a client does with a type it cannot decode, and the catalogue of standard types with their encodings. ```mermaid flowchart LR A[App value] -->|codec.encode| E[EncodedContent
type, parameters, fallback, content] E -->|MLS application message| N[(The backend)] N --> R[Recipient client] R -->|codec for authority, type, major| D[Decoded value] R -->|no codec, or decode fails| F[raw EncodedContent and optional fallback text] ``` ## Scope In scope: the content type identifier and how a client matches one; the `EncodedContent` envelope and its parameters, fallback, and compression fields; the codec contract and the errors it reports; the push flag a type carries; content nested inside content; content type versions; what a client does with a type it cannot decode; and the catalogue of standard types with their schemas. Out of scope: the `PlaintextEnvelope` that carries an `EncodedContent` inside an MLS message, the message id, and publishing (SEND); receipt, ordering, and storage of messages (PROC); the group metadata a commit changes and the transcript message a client derives from it (GMOD, META); the device sync payload (SYNC); what a push server does with the push flag (PUSH-219); the archive that carries stored content between installations (ARCH); and the effect of a delete or a leave request on group state (PROC-037, GMOD). | Related | Relation | | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | | SEND section 1 | Owns the `PlaintextEnvelope` and message identity. SEND-021 owns the explicit push override and SEND-020 the default text type referenced in sections 3 and 4. | | `PROC-037` | Owns deletion authorization and application. CTYPE-018 owns type and message-kind eligibility. | | `PUSH-219` | Owns backend push eligibility. CTYPE-010 owns the default value for catalogue content; PUSH-218 needs to defer to it. | | SYNC | Owns the sync message, an `EncodedContent` of its own type whose schema it states. | | `GMOD-034`, `GMOD-054` | Own transcript derivation and the publication restriction referenced in section 7; GMOD owns group changes. | | ARCH | Carries a stored message’s `EncodedContent` bytes unchanged (ARCH-008), so a type a client does not decode survives export and import. | | EVENT | EVENT-020 filters received messages by content type. EVENT-021 tests reply and reaction references. | ## Terms | Term | Meaning | | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Content type identifier | A `ContentTypeId`: `authority_id`, `type_id`, `version_major`, and `version_minor`. | | Human-readable form | The string `authority_id/type_id:version_major.version_minor` of an identifier, for example `xmtp.org/text:1.0`. It appears on the wire only where a catalogue schema names it. | | Encoded content | An `EncodedContent` as defined in section 2. | | Codec | The encode and decode functions for one identifier, with the push value in section 4. Catalogue decoders can be supplied by the client or an SDK; an app can register additional codecs under CTYPE-017. | | Standard type | A type under authority `xmtp.org`, or one of the two `coinbase.com` types, in the catalogue in section 7. | | Custom type | A type outside the catalogue, whether or not an app has registered a codec for it. | | Unknown type | An identifier for which the client and SDK have no matching decoder under CTYPE-001. | | Unknown content | The `unknown` body for content with no matching decoder, with its raw encoded bytes kept under CTYPE-008. | | Fallback | The `fallback` string of an encoded content: text a client shows when it cannot decode the content. | | Nested content | An `EncodedContent` carried inside the `content` of another, as a reply carries the content it replies with. | | Push value | The boolean a codec supplies for a type, which the client publishes as `should_push` under PUSH-219. | ## 1. The identifier An identifier has three parts that name the type and one that does not. The authority is the party that defines the type, named by a DNS name. The type is a name unique under that authority. The major version separates encodings that do not decode one another. The minor version marks an additive change: content under a later minor version decodes under a codec for an earlier one, so a client matches a codec without it. The catalogue in section 7 reserves identifiers under `xmtp.org` and lists two types under `coinbase.com`. An unlisted identifier may be implemented by an app. It does not become a standard type by using the `xmtp.org` authority. ```proto message ContentTypeId { string authority_id = 1; // authority governing this content type string type_id = 2; // type identifier uint32 version_major = 3; // major version of the type uint32 version_minor = 4; // minor version of the type } ``` | ID | Title | Requirement | Why | | --------- | ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | | CTYPE-001 | Match on three values | When the client or an SDK selects a codec, including through the Kotlin, Swift, or TypeScript registry, it MUST match `authority_id`, `type_id`, and `version_major`, and MUST NOT require `version_minor` to match. | Ignoring authority can select another party’s codec; requiring the minor version rejects compatible content. | | CTYPE-002 | Standard authority is reserved | An app SHOULD NOT register a codec whose `authority_id` is `xmtp.org` for a `type_id` the catalogue in section 7 does not list. | | | CTYPE-016 | Published identifiers retain meaning | When the client or an SDK implements a published identifier, it MUST retain that identifier’s meaning and accept later minor versions with the earlier minor version’s decoding rules. When a sender uses an encoding that those rules cannot decode, it MUST use a new major version or a new type identifier. | Reassigning an identifier makes stored messages change meaning and separates clients by version. | ## 2. The envelope An `EncodedContent` carries the identifier, the parameters a decoder needs beyond the bytes, optional fallback text, optional compression, and the content. A recipient reads parameters under CTYPE-014. Fallback text is available without decoding the content. It is optional for every type, including types whose codecs can supply it (CTYPE-021). `compression` names an algorithm applied to `content` before encoding. `COMPRESSION_DEFLATE` is 0, so absent and deflate are told apart by presence alone. Compressed publication follows CTYPE-023, and decoding follows CTYPE-024 and CTYPE-025. Older SDK releases do not share one decompression path (Known limitations). ```proto // Recognized compression algorithms enum Compression { COMPRESSION_DEFLATE = 0; COMPRESSION_GZIP = 1; } // EncodedContent bundles the content with metadata identifying its type // and parameters required for correct decoding and presentation of the content. message EncodedContent { // content type identifier used to match the payload with // the correct decoding machinery ContentTypeId type = 1; // optional encoding parameters required to correctly decode the content map parameters = 2; // optional fallback description of the content that can be used in case // the client cannot decode or render the content optional string fallback = 3; // optional compression; the value indicates algorithm used to // compress the encoded content bytes optional Compression compression = 5; // encoded content itself bytes content = 4; } ``` | ID | Title | Requirement | Why | | --------- | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | CTYPE-003 | Every message names its type | When the client publishes an application message, it MUST require a protobuf `EncodedContent` with a present `type` containing non-empty `authority_id` and `type_id`, and MUST reject input that lacks that envelope or identifier. It MUST carry the identifier as the protobuf `ContentTypeId`, not its human-readable form; a catalogue parameter that explicitly carries that form does not replace `type`. | Recipients need the structured identifier to select a decoder. | | CTYPE-021 | Fallback is optional | The client and an SDK MUST accept otherwise valid content without `fallback` when encoding, sending, or decoding any content type. | Missing display text does not make the content invalid. | | CTYPE-005 | Custom fallback recommendation | An app SHOULD set `fallback` on every content it encodes under a custom type it registers. | | | CTYPE-023 | Compressed content formats | Where the client or an SDK compresses the `content` of an application message it publishes, it MUST set `compression` to `COMPRESSION_DEFLATE` and write `content` in the zlib format ([RFC 1950 §2.2](https://www.rfc-editor.org/rfc/rfc1950.html#section-2.2)), or set it to `COMPRESSION_GZIP` and write `content` in the gzip format ([RFC 1952 §2](https://www.rfc-editor.org/rfc/rfc1952.html#section-2)). | A recipient reads the bytes by the algorithm the envelope names, so any other form is undecodable. | | CTYPE-024 | Decompress before decoding | When the client or an SDK decodes an `EncodedContent` whose `compression` is present, including nested content, it MUST decompress `content` before it selects a codec: `COMPRESSION_GZIP` as the gzip format, and `COMPRESSION_DEFLATE` as the zlib format or, when zlib decoding fails, as raw DEFLATE ([RFC 1951 §3](https://www.rfc-editor.org/rfc/rfc1951.html#section-3)). When `compression` holds any other value, or decompression fails, it MUST report a decode failure and preserve the message under CTYPE-008. | Compressed bytes handed to a codec decode as garbage or as the wrong text, and receive paths that differ show one message differently. | | CTYPE-025 | Decompressed size limit | If decompressing `content` would produce more than 16777216 bytes, then the client or an SDK MUST stop decompressing at 16777216 bytes, MUST NOT pass the output to a codec, and MUST report a decode failure that preserves the message under CTYPE-008. | A small compressed payload can otherwise expand until the recipient runs out of memory. | | CTYPE-033 | Decoded element limit | Before the client or an SDK decodes a reply’s nested `EncodedContent` or a `MultiRemoteAttachment`, it MUST count the fields at the top level of the protobuf bytes. Before it decodes TransactionReference, WalletSendCalls, Actions, or Intent content, it MUST count the `[`, `{`, `,`, and `:` characters outside JSON strings. If the field count exceeds 4096 or the character count exceeds 16383, it MUST NOT decode the bytes and MUST report a decode failure that preserves the message under CTYPE-008. | Each decoded element costs tens of times its wire size, so content within CTYPE-025 can otherwise make the recipient allocate gigabytes on every read. | | CTYPE-034 | Reaction size limit | When the client or an SDK encodes `xmtp.org/reaction:2.0` content whose `ReactionV2` bytes exceed 4096 bytes, it MUST return an encode failure. When it decodes `xmtp.org/reaction` content of any major version, it MUST NOT decompress more than 4097 bytes of `content`, and if the decompressed `content` is longer than 4096 bytes it MUST NOT pass the bytes to a codec and MUST report a decode failure that preserves the message under CTYPE-008. | A message’s reaction summary holds 50 reactions and a reaction page up to 1000, so reactions decoded at the CTYPE-025 limit let one read allocate gigabytes. | | CTYPE-031 | Compression requires opt-in | When an app sends content without requesting compression, the client and SDK MUST publish that content without applying compression. | A default compressed send can be unreadable to an older recipient. | ## 3. Codecs and undecodable content A codec turns a value into an `EncodedContent` and back. What the encode function writes is the contract with every other client: the identifier, the content bytes in the encoding the catalogue states, the parameters, and the fallback. A codec that writes a different encoding under the same identifier splits the network at that type. A client meets content it cannot decode as a matter of course: a custom type from a different application, a standard type from a newer client, or bytes a buggy sender produced. The message is still a message: it has an id, a sender, a position in the conversation, and it may be the target of a reply, a reaction, or a deletion. The client keeps it and hands the app what it has, which is the identifier, the fallback when present, and the raw envelope. Dropping it would make the conversation differ between a client that has the codec and one that does not. An SDK reports no matching codec, decode failure, encode failure, and malformed envelope as distinct outcomes. A registry lookup that fails is not permission to call the text decoder. For CTYPE-007, equality means the same strings, byte sequences, numeric values, optional-member presence, and sequence order; map-member order is irrelevant. An action timestamp is compared after conversion to UTC and truncation below millisecond precision, as required by its encoding in section 7. SEND-020 requires an SDK that accepts string content without an explicit content type to encode it as the catalogue text type. This default applies to a send request, not to received content with a missing or unknown identifier. | ID | Title | Requirement | Why | | --------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- | | CTYPE-007 | Encode round trip | When the client or an SDK encodes an app value with a codec, it MUST return an envelope whose `type` equals that codec’s identifier and whose decoding with the same codec returns an equal value under the comparison above. | The app and the recipient must receive the value that was sent. | | CTYPE-008 | Undecodable content is kept | When a received application message has no matching codec, fails decoding, or is not a typed `EncodedContent`, the client MUST retain its original bytes and message id. The client and SDK MUST expose those bytes and that id to the app, with the actual content identifier and fallback when present, without replacing the identifier with a text or fallback type. | Dropping undecodable content gives installations different conversation histories. | | CTYPE-009 | Failures are distinguishable | When encoding, decoding, or selecting a codec, an SDK MUST let the app distinguish no matching codec, codec decode failure, codec encode failure, and a malformed or untyped envelope. On a lookup failure, the Kotlin and Swift SDK registries MUST report no matching codec and MUST NOT return a successful text decode instead. | Unknown UTF-8 content can otherwise appear to be ordinary text. | | CTYPE-017 | Apps supply custom codecs | An SDK MUST let an app register a codec for a custom type, use it for received custom content matched under CTYPE-001, and send typed envelopes that the app encodes with it. | An app-defined type must be usable without changing the client. | | CTYPE-026 | Standard codecs without a client | An SDK MUST expose, for each standard type except the legacy group membership change, group updates, and the reserved edit type, a codec that an app can call without a client and whose envelope for a value equals the client’s own encoding of that value under CTYPE-014. | Apps build and inspect standard content outside a conversation, and a second encoder in a host language drifts from the client’s. | ## 4. The push value A type supplies a default push value. The client can obtain it from a codec or from the identifier of an app-supplied envelope. PUSH-219 owns backend push eligibility. SEND-021 requires that an explicitly supplied `shouldPush` value, including false, overrides the type default. An omitted options object and an object with no `shouldPush` field both leave that default in effect. PUSH-218 needs to defer to CTYPE-010 for catalogue application messages instead of imposing a blanket true default. | ID | Title | Requirement | Why | | --------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | | CTYPE-010 | Push value from the catalogue | When the client or an SDK publishes catalogue content without an explicit app push override under SEND-021, it MUST set the push flag to the catalogue’s Push value, including for an app-supplied raw envelope and for an options object with no push field. | Incorrect defaults suppress wanted notifications or send unwanted ones to recipients. | ## 5. Nested content A reply carries the content it replies with as a complete `EncodedContent` inside its own `content`, with the nested identifier repeated in human-readable form in the `contentType` parameter. The nested content is decoded with the same rule as a top-level one, so a reply with a custom type inside it is a reply the recipient can still place in the conversation: the reply retains its reference and its outer fallback when present. The reserved `editMessage` schema also contains nested content, but CTYPE-020 gives it no mutation effect. | ID | Title | Requirement | Why | | --------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | | CTYPE-011 | Nested content is complete | When the client or an SDK encodes nested content, it MUST require a complete protobuf `EncodedContent` with a present `type` and non-empty `authority_id` and `type_id`, and MUST fail encoding when these are absent. | An outer type cannot identify the nested payload. | | CTYPE-027 | Unknown nested content | When the client or an SDK decodes a reply with a complete typed nested envelope but no matching nested codec, it MUST return the reply reference and an `unknown` body under CTYPE-008, keeping the nested `EncodedContent`, with `content` decompressed under CTYPE-024. | An app cannot tell undecoded bytes from a value its codec decoded. | | CTYPE-028 | Nested type takes precedence | When a reply’s nested envelope has a `type` that conflicts with its outer `contentType` parameter, the client or SDK MUST select the nested `type`. | The typed envelope identifies the bytes to decode. | | CTYPE-029 | Invalid nested content | When a reply’s nested bytes are malformed or untyped, or a matching nested codec fails, the client or SDK MUST report a decode failure and preserve the outer bytes and fallback under CTYPE-008. | Malformed bytes do not supply a valid nested envelope. | ## 6. Content type versions An incompatible encoding needs a different major version under CTYPE-016. A codec is not selected merely because its major version is greater than the message’s. The legacy reaction type `xmtp.org/reaction:1.0` is deprecated and is outside this spec’s catalogue. The current reaction type is `xmtp.org/reaction:2.0`. | ID | Title | Requirement | Why | | --------- | ------------------------- | ----------------------------------------------------------------------------------- | --- | | CTYPE-022 | Publish current reactions | When the client publishes a new `xmtp.org/reaction`, it MUST use `version_major` 2. | | ## 7. The catalogue The catalogue lists identifiers, encodings, parameters, push values, and deletion eligibility (CTYPE-018). Every SDK exposes a codec for each standard type except the legacy group membership change, group updates, and the reserved edit type (CTYPE-026); the client only receives or derives those types, or reserves them. Standard content may be decoded by the client before an SDK registry is reached. SYNC owns its own message identifier and schema. The reserved edit type has a protobuf schema but no active codec. JSON payloads use [RFC 8259 §§4–8](https://www.rfc-editor.org/rfc/rfc8259.html#section-4). Section 7.2 states member names, types, and presence in tables, without using WebIDL for a wire format. SPEC-043 and [SPEC section 3.1](/specs/spec-spec-format/#31-type-blocks) provide no notation for repository-defined JSON type blocks. The tables avoid claiming a WebIDL exception. | Type | Identifier | Content | Parameters | Push | Deletable | | --------------------------- | ------------------------------------------ | --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----- | --------- | | Text | `xmtp.org/text:1.0` | UTF-8 text | `encoding`: `UTF-8` | true | yes | | Markdown | `xmtp.org/markdown:1.0` | UTF-8 Markdown | `encoding`: `UTF-8` | true | yes | | Reaction | `xmtp.org/reaction:2.0` | Protobuf `ReactionV2` | none | false | no | | Reply | `xmtp.org/reply:1.0` | Protobuf `EncodedContent`: the nested content | `reference`: the replied-to message id in lowercase hexadecimal; `contentType`: the nested identifier in human-readable form; `referenceInboxId`: optional, the replied-to sender’s inbox id | true | yes | | Read receipt | `xmtp.org/readReceipt:1.0` | Empty | none | false | no | | Attachment | `xmtp.org/attachment:1.0` | The file bytes | `mimeType`; `filename`: optional | true | yes | | Remote attachment | `xmtp.org/remoteStaticAttachment:1.0` | The URL as UTF-8 text | `contentDigest`, `secret`, `salt`, `nonce`, `scheme`; `contentLength` and `filename`: optional; see the Remote attachment parameters table | true | yes | | Multiple remote attachments | `xmtp.org/multiRemoteStaticAttachment:1.0` | Protobuf `MultiRemoteAttachment` | none | true | yes | | Transaction reference | `xmtp.org/transactionReference:1.0` | JSON `TransactionReference` | none | true | yes | | Wallet send calls | `xmtp.org/walletSendCalls:1.0` | JSON `WalletSendCalls` | none | true | yes | | Actions | `coinbase.com/actions:1.0` | JSON `Actions` | none | true | no | | Intent | `coinbase.com/intent:1.0` | JSON `Intent` | none | true | no | | Group updated | `xmtp.org/group_updated:1.0` | Protobuf `GroupUpdated` | none | false | no | | Legacy membership change | `xmtp.org/group_membership_change:1.0` | Protobuf `GroupMembershipChanges` | none | false | no | | Leave request | `xmtp.org/leave_request:1.0` | Protobuf `LeaveRequest` | none | false | no | | Delete message | `xmtp.org/deleteMessage:1.0` | Protobuf `DeleteMessage` | none | false | no | | Edit message (reserved) | `xmtp.org/editMessage:1.0` | Protobuf `EditMessage` | none | false | no | Group updated and legacy membership change represent commit transcripts. GMOD-034 requires that the client derives transcript records from validated commits, and GMOD-054 that it does not publish either transcript type as an application message, at the top level or nested in a reply, except the saved bytes of an attempt already prepared. | ID | Title | Requirement | Why | | --------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | CTYPE-014 | Catalogue encodings are binding | When the client or an SDK encodes or decodes a catalogue type, it MUST use the identifier, content encoding, parameters, protobuf schemas, Remote attachment parameters table, and JSON member tables in this section, and MUST NOT publish that type under another identifier. On decode, it MUST ignore envelope parameters that the type does not name. | Different encodings under one identifier break interoperability. | | CTYPE-015 | Remote attachment payload | When the client or an SDK encodes a remote attachment, including each entry of a multiple attachment, it MUST encrypt a serialized attachment `EncodedContent` with AEAD\_AES\_256\_GCM ([RFC 5116 §5.2](https://www.rfc-editor.org/rfc/rfc5116.html#section-5.2)), a 16-byte appended tag, empty associated data, and a fresh 12-byte random nonce. It MUST derive the 32-byte key with HKDF-SHA256 ([RFC 5869 §2](https://www.rfc-editor.org/rfc/rfc5869.html#section-2)) from a fresh 32-byte random secret and 32-byte random salt with empty info, and set `contentDigest` to lowercase hexadecimal SHA-256 of ciphertext including the tag. Before decryption, it MUST reject a digest mismatch; it MUST reject an authentication failure without returning plaintext. | The digest identifies the encrypted object; GCM authenticates its contents. | | CTYPE-032 | In-memory decryption bound | When an app passes a ciphertext longer than 104857600 bytes to an SDK call that decrypts a CTYPE-015 payload from a byte buffer, the SDK MUST fail the call before it hashes or decrypts the ciphertext. | An app that fetches a hostile sender’s attachment into memory otherwise holds several full-size copies of it during decryption, which can exhaust the device’s memory. | | CTYPE-018 | Deletion eligibility | When the client accepts or applies a deletion, it MUST require the target to have application message kind and a catalogue identifier with Deletable `yes`, matched on authority, type, and major version under CTYPE-001. It MUST reject deletion of a transcript, an unknown type, a custom type, a reserved type, or any catalogue type marked `no`, regardless of sender privileges. | A privileged sender must not erase protocol records or content with undefined deletion semantics. | | CTYPE-020 | Reserved edits do not mutate | When the client receives the reserved edit type, it MUST preserve it under CTYPE-008 and MUST NOT change the referenced message. | A schema alone does not authorize replacement of message history. | ### 7.1 Schemas The Remote attachment parameters table gives the map values for a single remote attachment. Its URL is the UTF-8 content. The multiple-attachment protobuf carries the same values with its declared field types. | Parameter | Presence | Value | | --------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `contentDigest` | required | Lowercase hexadecimal SHA-256 of ciphertext and tag | | `secret` | required | Lowercase hexadecimal, 32 bytes | | `salt` | required | Lowercase hexadecimal, 32 bytes | | `nonce` | required | Lowercase hexadecimal, 12 bytes | | `scheme` | required | Encode: `https://`, or `http://` when the URL’s host is `localhost` or a loopback address. Decode: also accept legacy `https` and `http`; normalize to `https://` and `http://` before the same URL and metadata checks. Keep the stored envelope and its original parameters unchanged. | | `contentLength` | optional | Decimal unsigned integer, 0 through 4294967295; ciphertext and tag length | | `filename` | optional | String | The protobuf encodings: ```proto // Action enum to represent reaction states enum ReactionAction { REACTION_ACTION_UNSPECIFIED = 0; REACTION_ACTION_ADDED = 1; REACTION_ACTION_REMOVED = 2; } // Schema enum to represent reaction content types enum ReactionSchema { REACTION_SCHEMA_UNSPECIFIED = 0; REACTION_SCHEMA_UNICODE = 1; REACTION_SCHEMA_SHORTCODE = 2; REACTION_SCHEMA_CUSTOM = 3; } // Reaction message type message ReactionV2 { // The message ID being reacted to string reference = 1; // The inbox ID of the user who sent the message being reacted to // Optional for group messages string reference_inbox_id = 2; // The action of the reaction (added or removed) ReactionAction action = 3; // The content of the reaction string content = 4; // The schema of the reaction content ReactionSchema schema = 5; } ``` ```proto // MultiRemoteAttachment message type message MultiRemoteAttachment { // Array of attachment information repeated RemoteAttachmentInfo attachments = 1; } message RemoteAttachmentInfo { // The SHA256 hash of the remote content string content_digest = 1; // A 32 byte array for decrypting the remote content payload bytes secret = 2; // A byte array for the nonce used to encrypt the remote content payload bytes nonce = 3; // A byte array for the salt used to encrypt the remote content payload bytes salt = 4; // The scheme of the URL: "https://", or "http://" for a loopback host string scheme = 5; // The URL of the remote content string url = 6; // The size of the encrypted content in bytes (max size of 4GB) optional uint32 content_length = 7; // The filename of the remote content optional string filename = 8; } ``` Each `RemoteAttachmentInfo` is encrypted as CTYPE-015 states for a single remote attachment. ```proto // A summary of the changes in a commit. // Includes added/removed inboxes and changes to metadata message GroupUpdated { // An inbox that was added or removed in this commit message Inbox { string inbox_id = 1; } // A summary of a change to the mutable metadata message MetadataFieldChange { // The field that was changed string field_name = 1; // The previous value optional string old_value = 2; // The updated value optional string new_value = 3; } string initiated_by_inbox_id = 1; // The inboxes added in the commit repeated Inbox added_inboxes = 2; // The inboxes removed in the commit repeated Inbox removed_inboxes = 3; // The metadata changes in the commit repeated MetadataFieldChange metadata_field_changes = 4; /// The inboxes that were removed from the group in response to pending-remove/self-remove requests repeated Inbox left_inboxes = 5; // The inboxes that were added to admin list in the commit repeated Inbox added_admin_inboxes = 6; // The inboxes that were removed from admin list in the commit repeated Inbox removed_admin_inboxes = 7; // The inboxes that were added to super admin list in the commit repeated Inbox added_super_admin_inboxes = 8; // The inboxes that were removed from super admin list in the commit repeated Inbox removed_super_admin_inboxes = 9; } ``` ```proto // A group member and affected installation IDs message MembershipChange { repeated bytes installation_ids = 1; string account_address = 2; string initiated_by_account_address = 3; } // The group membership change proto message GroupMembershipChanges { // Members that have been added in the commit repeated MembershipChange members_added = 1; // Members that have been removed in the commit repeated MembershipChange members_removed = 2; // Installations that have been added in the commit, grouped by member repeated MembershipChange installations_added = 3; // Installations removed in the commit, grouped by member repeated MembershipChange installations_removed = 4; } ``` ```proto // LeaveRequest message type message LeaveRequest { // A serialized AuthenticatedNote containing the sender's signed, member-only verifiable statement optional bytes authenticated_note = 1; } // DeleteMessage message type message DeleteMessage { // ID of the message to delete string message_id = 1; } // EditMessage message type message EditMessage { // ID of the message to edit string message_id = 1; // The new content for the message xmtp.mls.message_contents.EncodedContent edited_content = 2; } ``` `DeleteMessage.message_id` is the target message id in lowercase hexadecimal. ### 7.2 JSON members and validation These JSON member tables define object shapes. All listed members are required unless marked optional. Strings and numbers are JSON strings and numbers; arrays preserve order. Optional members are omitted on encode when absent. Unknown JSON object members are ignored on decode except for the additional string members of `WalletCallMetadata`. | Object | Required members | Optional members | | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | | TransactionReference | `networkId`: string; `reference`: string | `namespace`: string; `metadata`: TransactionMetadata | | TransactionMetadata | `transactionType`, `currency`, `fromAddress`, `toAddress`: strings; `amount`: number; `decimals`: integer from 0 through 4294967295 | none | | WalletSendCalls | `version`, `chainId`, `from`: strings; `calls`: array of WalletCall | `capabilities`: object with string values | | WalletCall | none | `to`, `data`, `value`, `gas`: strings; `metadata`: WalletCallMetadata | | WalletCallMetadata | `description`, `transactionType`: strings | Additional members with string values | | Actions | `id`, `description`: strings; `actions`: array of Action | `expiresAt`: string | | Action | `id`, `label`: strings | `imageUrl`: string; `style`: string, one of `primary`, `secondary`, `danger`; `expiresAt`: string | | Intent | `id`, `actionId`: strings | `metadata`: object with arbitrary JSON values | The validation table states encode and decode behavior separately. A decode error preserves the received message under CTYPE-008. The action-count and metadata-size limits restrict encoding; they do not reject otherwise decodable historical content. CTYPE-033 sets a separate decode ceiling far above these limits. | Type or field | Encode | Decode | | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Text and markdown `encoding` | Set `UTF-8` | Use `UTF-8` when absent; reject any other value | | JSON object members | Use the JSON member tables, omit absent optional members, and fail for a missing required member or wrong value type | Require the declared member types; accept absent or null optional members and ignore unknown members, except that additional WalletCallMetadata members are retained as strings | | TransactionReference `networkId` | String | Accept string or number; return a number’s decimal text as a string | | Actions `actions` | Require 1 through 10 entries and unique `id` values | Accept an array without imposing the encode count or uniqueness limits | | Action and Actions `expiresAt` | RFC 3339 UTC timestamp with exactly three fractional digits; discard precision below milliseconds; fail for a time outside the signed 64-bit nanosecond range | Parse RFC 3339 timestamps and normalize to UTC; accept `expires_at` as an alias | | Action `imageUrl`; Intent `actionId` | Use the camel-case member name | Also accept `image_url` and `action_id`, respectively | | Intent `metadata` | Reject when its compact UTF-8 JSON encoding exceeds 10240 bytes | Accept an object without imposing the encode size limit | Timestamp syntax is defined by [RFC 3339 §5.6](https://www.rfc-editor.org/rfc/rfc3339.html#section-5.6). Transaction hashes, addresses, call data, and numeric strings are content values, not client-side authorization of a transaction. | ID | Title | Requirement | Why | | --------- | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | | CTYPE-019 | Encoding and decoding checks | When the client or an SDK encodes or decodes catalogue content, it MUST apply the matching column of the validation table above and MUST return an encode or decode failure for a violated check. | Hidden validation differences make the same content work on one SDK and fail on another. | | CTYPE-030 | Action expiry range | When the client or an SDK encodes or decodes Actions content whose Actions or Action `expiresAt` names a time that a signed 64-bit count of nanoseconds since the Unix epoch cannot represent, it MUST return an encode or decode failure for the message. | An SDK that clamps or drops an unrepresentable expiry shows a different value than another SDK, or none. | ## Known limitations SDK releases before the Rust decode path decompress no content, or decompress only one DEFLATE form, and some send LZFSE labelled `COMPRESSION_GZIP`; they cannot read content that other clients compress under CTYPE-023. SDK releases before CTYPE-034 decode reactions up to the CTYPE-025 limit. The client decodes the outer EncodedContent of a received message without the CTYPE-033 count. The envelope size limit bounds those bytes; its parameter map can cost about 20 times the envelope size. The client’s standard dispatch checks type and major version but omits authority. Kotlin, Swift, and TypeScript registries include the minor version in their keys. These are gaps in CTYPE-001, but they do not imply that every standard text message with a later minor fails: the client can decode it before the SDK registry is reached. Kotlin and Swift registry lookup failures select a text codec. Unknown UTF-8 content can therefore decode as text instead of producing the missing-codec outcome in CTYPE-009. Node raw-envelope sends use false when the options object is absent; browser raw-envelope sends use true. Neither derives that default from the catalogue. A supplied options object is forwarded unchanged; both bindings declare the push field as required, so omission is not the same path as an absent options object. These paths do not yet satisfy CTYPE-010. JSON member tables state the wire shapes without a JSON type-block notation. SPEC-043 and section 3.1 need a JSON notation before these tables can be replaced with JSON type blocks. # DMs and stitching A DM is an MLS group with an immutable pair of inboxes and fixed membership policies. Either inbox can create one before it sees a group created by the other inbox or a peer installation. A client combines these groups into one conversation and selects one group for sends. ```mermaid flowchart LR A[Inbox A creates a DM] --> GA[(Group 1)] B[Inbox B creates a DM
before it sees group 1] --> GB[(Group 2)] GA --> ID[dm id from DM_MEMBERS] GB --> ID ID --> S[One stitched DM:
messages of both groups,
one winner to send in,
one consent state] ``` ## Scope In scope: the identifier a client derives from the DM pair; what a creator writes into a DM; the fixed DM policy and the one addition it permits; what a joiner checks before it accepts a DM; how a client folds the groups that share an identifier into one conversation and which of them it acts in; deduplication of the membership-change messages they repeat; and what an SDK exposes about a DM. Out of scope: the join itself and its rejections (`JOIN`), component ids and encodings (`META`), the policy engine and role rules (`PERM`), commit validation (`GMOD`), consent, including a DM’s (`CONS`), stream ordering (`PROC`), and archives (`ARCH`). | Related | Relation | | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `META-004`, `META-010`, `META-030` | Own immutability, component encodings, and DM pair structure. This spec owns DM initialization and admission. | | `JOIN-060` | Rejects a Welcome whose group fails the checks its kind demands. DMS-021 states the checks a DM demands. | | `JOIN-025` | Names the inbox that added the joiner, which DMS-021 compares against the DM pair. | | `JOIN-080`, `JOIN-089` | Own activation of a restored placeholder by a validated Welcome, and the rule that a Welcome for a held group, a restored DM included, keeps its conversation type and dm id. | | `PERM-009`, `PERM-011`, `PERM-026`, `PERM-028` | Own hardcoded authority, the DM participant’s application registry and policy authority, and evaluation against each proposer’s operation. This spec owns fixed DM policy values and the participant-add exception. | | CONS-052, CONS-053 | Own a DM’s consent: the other member’s inbox record, and its merge. | | `PROC-025`, `PROC-026`, `PROC-034` | Own stream eligibility and delivery order. DMS-009 owns the stitched scope and query ordering; DMS-016 owns the legacy snapshot tail. | | `EVENT` | EVENT-020 selects events across the groups of one stitched DM. | ## Terms | Term | Meaning | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | DM pair | The two inboxes in a DM’s `DM_MEMBERS` component. | | Peer inbox | The inbox of the DM pair that is not the client’s own. | | Dm id | The string derived from the DM pair under DMS-001. Two groups with equal dm ids are one conversation. | | Stitched DM | The set of groups a client holds whose dm ids are equal. | | Winner | The group of a stitched DM the client lists, sends in, and resolves group ids to, chosen under DMS-013. | | Activity timestamp | The retained `last_message_ns` value used for conversation ordering, including a value imported under ARCH-014. It can outlive the messages that supplied it. | | Restored placeholder | A group imported without MLS state under ARCH-015. | | Fixed DM policy | The policy values of section 2. | | DM registry profile | A numbered list of the registry entries outside the application range that a DM holds from its creation, defined in section 2. | | Membership-change message | A message for a commit or join that carries a `GroupUpdated` payload. | ## 1. The DM pair and its identifier A DM is identified by the two inboxes it is between, not by its MLS group id. The creator records both inboxes in `DM_MEMBERS` at creation, where they are immutable (META-004), and every client derives the same string from them. The derivation is order-free, so the group each side created yields the same dm id, and it is the key under which everything in sections 3 and 4 happens. A DM is between two different inboxes. A client does not create a DM with itself, and rejects one at the join. | ID | Title | Requirement | Why | | ------- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | DMS-001 | Dm id derivation | The client MUST derive a DM’s dm id as `dm:` followed by the two inbox ids of `DM_MEMBERS` in lowercase hexadecimal, sorted ascending by byte order and joined by `:`. | Two installations that derive it differently import each other’s archives and consent records into different conversations. | | DMS-002 | What a creator writes | When a client creates a DM, it MUST set `CONVERSATION_TYPE` to `CONVERSATION_TYPE_DM`, `DM_MEMBERS` to its own inbox id and one distinct inbox id, and both `ADMIN_LIST` and `SUPER_ADMIN_LIST` to empty sets. It MUST write, at ids outside the application range, exactly the registry entries of one DM registry profile of section 2. | A joiner rejects a DM whose entries match no profile (DMS-021). | ## 2. The fixed DM policy A DM’s fixed policies deny inbox additions, inbox removals, and admin changes. DMS-004 permits the other participant’s addition. Updates to existing membership entries still support installation changes under GMOD. The registry and super-admin list require a super admin under PERM-026; a DM starts with neither role. PERM-026 lets either participant change application registry entries, and PERM-028 lets it satisfy `ALLOW_IF_SUPER_ADMIN` and `ALLOW_IF_ADMIN` on application components. Neither exception reaches membership, the role lists, or a well-known component. | Registry entry | `insert_policy` | `update_policy` | `delete_policy` | | ------------------ | --------------------------- | ---------------------------- | --------------------------- | | `GROUP_MEMBERSHIP` | `METADATA_BASE_POLICY_DENY` | `METADATA_BASE_POLICY_ALLOW` | `METADATA_BASE_POLICY_DENY` | | `ADMIN_LIST` | `METADATA_BASE_POLICY_DENY` | `METADATA_BASE_POLICY_DENY` | `METADATA_BASE_POLICY_DENY` | The settings policies below apply at creation under DMS-002. The component names and wire ids belong to META section 2. Permission evaluation belongs to PERM-011. Clearing disappearing settings writes disabled values instead of removing the components. The `USER_DISPLAY_NAME` row has the policies of PERM-029, which META-066 also requires. A DM registry has no `GROUP_IMAGE` entry. | Registry entries | `insert_policy` | `update_policy` | `delete_policy` | | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- | | `GROUP_NAME`, `GROUP_DESCRIPTION`, `GROUP_IMAGE_URL`, `APP_DATA`, `MESSAGE_DISAPPEAR_FROM_NS`, `MESSAGE_DISAPPEAR_IN_NS`, `MIN_SUPPORTED_PROTOCOL_VERSION` | `METADATA_BASE_POLICY_ALLOW` | `METADATA_BASE_POLICY_ALLOW` | `METADATA_BASE_POLICY_ALLOW_IF_SUPER_ADMIN` | | `COMMIT_LOG_SIGNER` | `METADATA_BASE_POLICY_ALLOW_IF_SUPER_ADMIN` | `METADATA_BASE_POLICY_ALLOW_IF_SUPER_ADMIN` | `METADATA_BASE_POLICY_ALLOW_IF_SUPER_ADMIN` | | `USER_DISPLAY_NAME` | `METADATA_BASE_POLICY_ALLOW_IF_SELF_OR_NON_MEMBER` | `METADATA_BASE_POLICY_ALLOW_IF_SELF_OR_NON_MEMBER` | `METADATA_BASE_POLICY_ALLOW_IF_SELF_OR_NON_MEMBER` | | `CONVERSATION_TYPE`, `CREATOR_INBOX_ID`, `DM_MEMBERS`, `GROUP_ROOT_KEY` | `METADATA_BASE_POLICY_ALLOW_IF_SUPER_ADMIN` | `METADATA_BASE_POLICY_DENY` | `METADATA_BASE_POLICY_DENY` | The two tables above are DM registry profile 1. A DM registry profile lists, for each component it names, one registry entry whose bytes are the serialized `ComponentMetadata` holding that component’s `component_type` from META section 2 and the three policies of its table row, with no other field and its fields in field-number order. A change to the entries a creator writes outside the application range, such as a new well-known component or a new `ComponentMetadata` field, is a new profile with the next number. A profile is never changed or removed, because a DM keeps the entries it was created with for its life and new installations keep joining it. A release writes a new profile only after the minimum client version (CONF-036) excludes every client that does not accept it. | ID | Title | Requirement | Why | | ------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | DMS-021 | A DM is what it claims | When a client joins a DM, it MUST verify that `DM_MEMBERS` is the distinct pair of META-030 and includes its own inbox, that the adder under JOIN-025 is either inbox of that pair, that every `GROUP_MEMBERSHIP` entry and every ratchet-tree leaf names an inbox in that pair, and that `SUPER_ADMIN_LIST` and `ADMIN_LIST` are empty. It MUST also verify, including when the adder is its own inbox, that the registry’s entries at ids outside the application range are exactly the entries of one DM registry profile of section 2, each byte-equal to that profile’s entry for its id. If any check fails, it MUST reject the Welcome under JOIN-060. | Valid credentials for a third inbox do not make it a participant. PERM-026 lets no participant change a registry entry outside the application range, so an entry that differs, such as a `GROUP_MEMBERSHIP` update policy of deny or a field a later release would read, stays for the DM’s life. A client that accepts only the newest profile rejects every older DM when a new installation joins it. | | DMS-004 | Only the pair is added | When a proposal in a DM adds exactly the other inbox of `DM_MEMBERS` relative to its proposer, the client MUST allow that inbox’s `GROUP_MEMBERSHIP` insertion and its MLS Add proposals despite the fixed deny policy, subject to all other validation. It MUST reject an inbox addition outside that exception. | Without the exception the DM cannot gain its second participant. | ## 3. Duplicate groups and the winner Two groups for one pair arise whenever the two sides, or two installations of one side, each create before they see the other’s Welcome. The client keeps every one of them: each is a valid MLS group its peer may be sending in, and a group discarded is a message lost. What the client hides is the multiplicity. Every group that shares a dm id is one conversation to the app: one entry in the list, one message thread, one identifier to send to. The winner order is deterministic for the state a client holds. Installations with different received history can select different winners. An archive import can raise a group’s retained activity timestamp under ARCH-014 without importing a message at that time. Message deletion does not cause selection to fall back to the remaining history. The client does not create a further group while it holds one that is not a restored placeholder, so an honest peer’s set grows only from races, never from repetition. A peer that ignores that rule can create any number of groups (Known limitations). A restored placeholder keeps its archived conversation type and dm id under ARCH-020, and that pair need not include the client’s own inbox. A Welcome for the same group id activates the placeholder under JOIN-080. The legacy history-to-live snapshot is a separate handoff API. DMS-016 states its selection and order; DMS-009 states the ordinary history-query and stream rules. | ID | Title | Requirement | Why | | ------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | DMS-005 | Reuse before create | When an app asks the client for the DM with an inbox and the client holds a group whose dm id is that pair’s and that is not a restored placeholder, the client MUST return that stitched DM’s winner and MUST NOT create another group. | Every group created adds a Welcome, a key package fetch, and a group the peer must hold for ever. | | DMS-020 | A DM holds its peer before use | When an SDK returns a stored DM for an app’s request to find or create the DM with an inbox (DMS-005), or sends a message in a DM, and that DM’s `GROUP_MEMBERSHIP` holds no entry for the peer inbox, the SDK MUST first publish and apply a commit that adds the peer inbox under DMS-004. If that commit fails, the SDK MUST return its failure instead of the DM or the message. | A creation interrupted between storing the DM and adding the peer otherwise leaves a conversation that reports sent messages the peer never receives. | | DMS-013 | Winner uses retained activity | Among the groups of a stitched DM, the client MUST select the winner by preferring non-restored groups, then the greatest retained `last_message_ns` with absent lowest, then the greatest group id under byte order. It MUST retain activity after message deletion and include activity imported under ARCH-014, even when no retained message has that timestamp. | Recomputing from remaining messages can move the winner after expiry or an archive import. | | DMS-007 | One conversation per dm id | When the client lists conversations, or resolves a group id that belongs to a stitched DM, it MUST return the winner and MUST NOT return another group of the set unless the app asked for duplicates. | | | DMS-008 | A second group is joined | When a client receives a Welcome for a group whose dm id equals that of a group it holds, it MUST process the Welcome under JOIN and MUST NOT reject it for the equal dm id. | The peer created it and may be sending in it. | | DMS-009 | The thread is the union | When an app queries or streams a stitched DM through any of its group ids, the client MUST use the union of the groups’ messages and apply the requested filters and limit to that union. For history queries, it MUST order by `sent_at_ns` ascending by default, or by the app’s requested supported sort field and direction. For streams, it MUST apply the eligibility and delivery order of PROC-025, PROC-026, and PROC-034. | Applying a limit separately to each group gives the app the wrong page. | | DMS-019 | One group’s failure stays local | When the app syncs a stitched DM through one of its group ids, the client MUST sync every group of the set that is not a restored placeholder, holding a paused group under GMOD-025, and MUST NOT let a failure or pause of one group stop it from syncing the others. It MUST return the outcome of the group the app named and MUST NOT return another group’s failure. | A pause or error in a group the peer created would otherwise stop the rest of the thread, including the group both sides send in. | | DMS-016 | Snapshot selects recent delivery | When the client creates a legacy history-to-live snapshot for a stitched DM through any group id, it MUST select the eligible retained messages with the greatest local delivery numbers under one limit across the union and return them in ascending local delivery-number order. | A per-group limit or sent-time selection can omit the most recent visible messages at stream handoff. | ## 4. Consent and repeated records A DM has no consent record of its own. Its consent is the record of its other member’s inbox under DMS-017 (CONS-052), so a decision covers every group of the DM: held now, joined later, or restored from an archive. Each group of a set records its own membership-change messages, and the join into a second group records the same add the first one did. The client suppresses a record that repeats what it already holds for the set, so the thread does not show the user being added twice. CONS-001 owns the unknown state when no record exists. CONS-060 and CONS-031 own consent filtering and default listing. | ID | Title | Requirement | Why | | ------- | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | | DMS-011 | Repeated adds are shown once | When membership-change messages in a stitched DM have non-empty `added_inboxes` and equal decoded `GroupUpdated` payloads, the client MUST show at most one of them in app queries and streams. It MUST compare `initiated_by_inbox_id`, every repeated field in its listed order, and both presence and value of each optional field. It MUST NOT suppress a message as a duplicate under this rule unless one complete earlier payload equals it. | Combining fields from different records can hide a change that has never been shown. | ## 5. What an app can read An app addresses a DM by the peer, not by group id, and needs to know which groups a conversation spans so that it can, for example, register push keys for each. | ID | Title | Requirement | Why | | ------- | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | DMS-017 | Peer and duplicates are readable | When an app reads a DM, an SDK MUST let it list the other groups of its stitched DM and list conversations with every group of each stitched DM included. When the app asks for the peer inbox, the SDK MUST return the other member if its own inbox belongs to the pair, and MUST report peer absence for a foreign Restored DM without choosing either archived member. | A fabricated peer mislabels imported history, and omitted physical groups prevent the app from registering for all DM traffic. | ## Known limitations The winner can change when another group’s activity timestamp becomes greater, including through an archive import. A late message with an older timestamp need not change it. An app that keeps state by group id can see the conversation’s identifier change. A Restored DM can contain history for two inboxes other than the importing inbox. It has no peer relative to that inbox under DMS-017. It stays inactive until a validated Welcome joins the exact stored pair and kind. Import preserves that pair, but current placeholder metadata can still replace other archived values such as creator and adder; ARCH-020 remains open for those values. A DM has no super admin, so its well-known registry entries cannot be changed through the fixed policies. Only application registry entries can change, under PERM-026. A DM therefore keeps the profile it was created with for its life, and a component that a later profile adds is absent from older DMs. A client rejects a DM whose profile it does not know (DMS-021), so a creator that writes a new profile before every client accepts it makes those clients reject the DM. History imported from an archive is trusted as written, because the archive key is its only authentication. Import does not check a message’s sender against the DM pair, so an archive can add history under any sender to a DM, and the stitched thread shows that history. The client does not check a stored DM against DMS-021 again after its join, because that check would load the MLS state of every stored DM at each client open. A DM that an older client accepted with an inbox outside its pair therefore stays in the stitched thread. Current add-record deduplication compares accumulated hashes of the most recent non-empty fields and ignores the initiator. It can suppress a record that does not equal any complete earlier payload, or show one that equals an older payload. This differs from DMS-011. Records without adds are outside that rule; DM history omits membership-change messages by default. A peer that does not follow DMS-005 can create any number of groups for one pair, and the client joins each under DMS-008. Syncing the DM under DMS-019, and listing its duplicates under DMS-017, then costs work linear in that number. Newcomer conversation adds under SYNC-014 cover a DM’s winner among eligible groups and at most `MAX_DM_EXTRA_GROUPS` (10) most recently active eligible duplicates. Siblings beyond that selection get no newcomer add, by design. # Client events A client event tells an app that the client made a change: a conversation joined, a message received, a consent record changed. The app uses the event as a signal to read the state it shows again. An event carries identifiers and a small set of values, not the changed objects. Events are live. A subscription receives only the events emitted after it starts, and an event is gone once the SDK hands it to the app. Nothing is replayed and nothing is acknowledged. An app that must see every message uses durable message delivery (PROC section 7), not events. Events report changes that the client makes for some other reason. A subscription causes no network activity: it does not open a stream, register a topic, or send a request. An app that subscribes to received messages and holds no message stream, runs no sync, and has no background worker running receives no `message.received` event. ```mermaid flowchart LR P[Processing, sync,
app acts, workers] -->|makes a change| DB[(Client state)] DB -->|emits after the change is readable| E[Event] E --> F{Filter} F -->|selected| Q[Per-subscription queue
at most 1024 events] Q -->|full: discard and count| L[lagged] Q --> A[App: iterator or callback] L --> A ``` ## Scope In scope: the event kinds and what each one carries, when the client emits an event, the order of events, which client instance’s subscriptions receive it, the typed filter, the queue bound and the `lagged` event, callback delivery, and ending a subscription. Out of scope: durable message delivery and acknowledgement (PROC section 7), internal catch-up state, the changes themselves and their validation (the specs in the Related table), push notifications (`PUSH`), and how an SDK names its methods. | Related | Relation | | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `PROC` | Owns durable delivery, delivery numbers (PROC-024), eligibility (PROC-025), and deletion (PROC-037). Events do not replace them. | | `CONS` | Owns consent records and their changes. CONS-041 gives an app access to consent and uses `consent.changed` for stored-state changes, subject to EVENT-030 and EVENT-031. | | `JOIN` | Owns the join from a Welcome (JOIN-045), replacing an ended group (JOIN-042), activating a restored group (JOIN-080), and the adder (JOIN-025). | | `GMOD` | Owns commits, removal, and leave (GMOD-031 to GMOD-033), and the membership refresh that reads an inbox’s newer identity state (GMOD-029). | | `META` | Owns components and their names (section 2, META-074), disappearing messages (META-050, META-051, META-063), and the protocol version floor (section 7, META-062). | | `PERM` | Owns the permission policy set and the admin lists. | | `DMS` | Owns stitched DMs (DMS-007, DMS-009). | | `SEND` | Owns message delivery status (SEND-003, SEND-009, SEND-013, SEND-016, SEND-018). | | `CTYPE` | Owns content type ids (CTYPE-001), deletion eligibility (CTYPE-018), and the reply and reaction encodings. | | `IDENT` | Owns installation keys (section 8), installation addition and revocation (section 5, IDENT-044), and handle claims and the handles of the association state (IDENT-082). | | `FORK` | Owns the fork state (FORK-082). | | `CONF` | Owns the blocked connection and the two conditions that set it (CONF-030, CONF-036). CONF-075 closes streams with network interest while EVENT-016 keeps event subscriptions open. | | `AUTH` | Owns credential lockout (AUTH-023) and replacing the credential (AUTH-024). | | `PUSH` | Owns the notification state (PUSH-267). | | `SYNC` | Owns the HMAC root key (SYNC-026, SYNC-032) and SYNC-005, which hides sync groups from an app. | | `ARCH` | Owns archive import (section 4, ARCH-027). | | `ATCH` | Owns pending attachment status (ATCH-034), downloads (section 6), local deletion (ATCH-047), attachment keys (ATCH-041), and the failure causes (ATCH-060). | ## Terms | Term | Meaning | | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Event | One report of one change, with a kind and a payload. | | Kind | The name of the change an event reports: a row of the kind table in section 1, or `lagged` (section 4). | | Emission | The client making an event available to its subscriptions. | | Subscription | An app’s request for events that match an `EventFilter`, from the moment the SDK registers it, which is before the call that creates it returns, until it ends. An iterator and a callback are two forms of one subscription. | | Handoff | The SDK giving one event to the app: an iterator returns it, or a callback starts with it. | | Queue | The events emitted for one subscription that are not yet handed off, wherever the SDK holds them, plus the event whose callback is running. | | Running | A callback is running from the moment the SDK starts it until it returns and any value it returns has completed. | | Fails | A callback fails when it throws, or when the value it returns completes with an error. | | Names a group | An event names a group when its payload carries a `group_id`, or when it is a `consent.changed` event whose `entity_kind` is `conversation`. Filters use this term; ordering does not. | | Own inbox | The inbox of the client that emits the event. | ## 1. Kinds and payloads Each row of the kind table names one change, the unit that gets one event, and the payload member that carries it. An app selects a kind through the typed `EventKind` filter. A kind is never removed and never changes meaning. One act can produce events of more than one kind. A commit that removes the own inbox produces `conversation.removed` and `conversation.membership_changed`. A commit that removes only this installation while the own inbox remains a member does not produce `conversation.membership_changed`. A deletion produces `message.received` for the deletion message and `message.deleted` for its target. Events from one transaction are emitted in the order of the kind table (EVENT-012). `handle.changed` reports a change to the display handle of the association state with the greatest sequence id that the client holds for an inbox, the own inbox included. When the client holds no association state for an inbox, the state it stores for that inbox is not a change and has no event, so loading the members of a new conversation does not emit one event for each member. | Kind | Emitted when | One event for each | Payload member | | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | ------------------------------- | | `conversation.joined` | The client stores a group or DM it did not hold, one it creates or one it joins from a Welcome under JOIN-045; replaces an ended group’s state under JOIN-042; or activates a restored group under JOIN-080 | Group | `conversation_joined` | | `conversation.removed` | The client applies a commit that removes this installation from a group | Group | `conversation_removed` | | `conversation.membership_changed` | The client applies a commit that adds or removes a member inbox | Commit | `membership_changed` | | `conversation.metadata_changed` | The client applies a commit that changes a component of META section 2, the admin or super admin list, or the permission policy set | Commit | `metadata_changed` | | `conversation.paused` | A group becomes paused for a protocol version floor (META section 7, META-062) | Group | `conversation_paused` | | `message.received` | The client assigns a delivery number under PROC-024 to an application message whose sender installation is not this installation and whose expiry under META-050, if it has one, is later than the time of emission | Message | `message_received` | | `message.status_changed` | The status of a message this installation sent changes between `Unpublished`, `Published`, and `Failed` (`SEND`) | Message | `message_status_changed` | | `message.deleted` | The client applies a deletion under PROC-037, or deletes a message locally at an app’s request | Message | `message_deleted` | | `message.expired` | The client deletes a message under META-063 | Message | `message_expired` | | `consent.changed` | The state CONS-001 reports for an inbox or a conversation changes | Inbox, or conversation as CONS-059 names it | `consent_changed` | | `hmac_keys.updated` | The client stores a new HMAC root key under SYNC-026 or SYNC-032, or an open client observes an HMAC epoch increase under EVENT-026 | Stored key or observed epoch increase | `hmac_keys_updated` | | `identity.registered` | The client reports this installation’s registration complete under IDENT-072 | Registration | `identity_registered` | | `identity.own_installation_added` | The client applies an identity update of the own inbox that adds an installation | Installation | `own_installation_added` | | `identity.own_installation_revoked` | The client applies an identity update of the own inbox that revokes an installation, including one IDENT-044 revokes with an identifier | Installation | `own_installation_revoked` | | `client.rejected_by_server` | The server rejects the client and blocks its connection: its backend does not match the stored one, or its version is below the server’s minimum (CONF-075) | Rejection | `rejected_by_server` | | `client.lockout_changed` | The client enters lockout under AUTH-023, or leaves it: when the first request after the cool-down proceeds, or under AUTH-024 | Entry or exit | `lockout_changed` | | `conversation.fork_detected` | A conversation’s fork state becomes `forked` under FORK-082 | Group | `conversation_fork_detected` | | `notifications.failed` | The notification state becomes failed under PUSH-267 | Failure | `notifications_failed` | | `archive.restored` | An archive import ends, with or without an error, after it stored at least one element (ARCH-027) | Import | `archive_restored` | | `connection.state_changed` | The client-wide state of open app streams that hold network interest changes under EVENT-027 | Transition | `connection_state_changed` | | `attachment.upload_started` | A pending attachment’s status becomes `uploading` (ATCH-034) | Transition | `attachment_upload_started` | | `attachment.upload_completed` | A pending attachment’s status becomes `complete` (ATCH-025) | Transition | `attachment_upload_completed` | | `attachment.upload_failed` | A pending attachment’s status becomes `failed` (ATCH-024, ATCH-025, ATCH-026, ATCH-036, ATCH-047, ATCH-071, ATCH-078) | Transition | `attachment_upload_failed` | | `attachment.download_started` | The client begins a download that neither ATCH-052 nor ATCH-058 ends | Download | `attachment_download_started` | | `attachment.download_completed` | A download makes a plaintext file readable at its path under ATCH-051 | Download | `attachment_download_completed` | | `attachment.download_failed` | A download that emitted `attachment.download_started` ends without a plaintext file | Download | `attachment_download_failed` | | `attachment.deleted` | An app’s request under ATCH-047 deletes at least one of the attachment key directory, the staged ciphertext, and the local attachment record | Request | `attachment_deleted` | | `handle.changed` | The client stores an association state that changes an inbox’s display handle under EVENT-058 | Stored association state | `handle_changed` | The payload of every event, including `lagged`, is the `ClientEvent` below. The client and SDK use the typed `EventKind` set in this section. ```webidl dictionary ClientEvent { required EventKind kind; // exactly one member below is present: the one the kind table names ConversationJoined conversation_joined; ConversationRemoved conversation_removed; MembershipChanged membership_changed; MetadataChanged metadata_changed; ConversationPaused conversation_paused; MessageReceived message_received; MessageStatusChanged message_status_changed; MessageDeleted message_deleted; MessageRef message_expired; ConsentChanged consent_changed; HmacKeysUpdated hmac_keys_updated; IdentityRegistered identity_registered; InstallationRef own_installation_added; InstallationRevoked own_installation_revoked; ClientRejectedByServer rejected_by_server; LockoutChanged lockout_changed; GroupRef conversation_fork_detected; NotificationsFailed notifications_failed; ArchiveRestored archive_restored; ConnectionStateChanged connection_state_changed; AttachmentRef attachment_upload_started; AttachmentRef attachment_upload_completed; AttachmentFailed attachment_upload_failed; AttachmentRef attachment_download_started; AttachmentRef attachment_download_completed; AttachmentFailed attachment_download_failed; AttachmentRef attachment_deleted; HandleChanged handle_changed; Lagged lagged; }; enum EventKind { "conversation.joined", "conversation.removed", "conversation.membership_changed", "conversation.metadata_changed", "conversation.paused", "message.received", "message.status_changed", "message.deleted", "message.expired", "consent.changed", "hmac_keys.updated", "identity.registered", "identity.own_installation_added", "identity.own_installation_revoked", "client.rejected_by_server", "client.lockout_changed", "conversation.fork_detected", "notifications.failed", "archive.restored", "connection.state_changed", "attachment.upload_started", "attachment.upload_completed", "attachment.upload_failed", "attachment.download_started", "attachment.download_completed", "attachment.download_failed", "attachment.deleted", "handle.changed", "lagged" }; enum ConversationType { "group", "dm" }; enum JoinOrigin { "created", "welcomed" }; enum RemovalCause { "removed", "left" }; enum DeletionCause { "deleted", "deleted_locally" }; enum MessageStatus { "unpublished", "published", "failed" }; enum ConsentEntityKind { "conversation", "inbox" }; enum ConsentState { "unknown", "allowed", "denied" }; enum RejectionCause { "backend_mismatch", "version_too_old" }; enum LockoutChange { "entered", "left" }; enum ConnectionState { "connecting", "connected", "reconnecting", "failed", "closed" }; dictionary GroupRef { required sequence group_id; }; dictionary MessageRef { required sequence group_id; required sequence message_id; }; dictionary ConversationJoined { required sequence group_id; required ConversationType conversation_type; required JoinOrigin origin; DOMString adder_inbox_id; // EVENT-023 }; dictionary ConversationRemoved { required sequence group_id; required RemovalCause cause; // EVENT-006 }; dictionary MembershipChanged { required sequence group_id; required sequence added_inbox_ids; required sequence removed_inbox_ids; }; dictionary MetadataChanged { required sequence group_id; required sequence changed; // EVENT-019 }; dictionary ConversationPaused { required sequence group_id; required DOMString floor; }; dictionary MessageReceived { required sequence group_id; // EVENT-018 required sequence message_id; ContentTypeId content_type; // EVENT-024 required DOMString sender_inbox_id; }; dictionary ContentTypeId { // the three values CTYPE-001 matches on required DOMString authority_id; required DOMString type_id; required unsigned long version_major; }; dictionary MessageStatusChanged { required sequence group_id; required sequence message_id; required MessageStatus previous; required MessageStatus current; }; dictionary MessageDeleted { required sequence group_id; required sequence message_id; required DeletionCause cause; // EVENT-007 }; dictionary ConsentChanged { required ConsentEntityKind entity_kind; required DOMString entity; // EVENT-059 required ConsentState state; }; dictionary HmacKeysUpdated {}; dictionary IdentityRegistered { required DOMString inbox_id; required sequence installation_key; // 32 bytes (IDENT section 8) }; dictionary InstallationRef { required sequence installation_key; }; // 32 bytes (IDENT section 8) dictionary InstallationRevoked { required sequence installation_key; // 32 bytes required boolean is_this_installation; }; dictionary ClientRejectedByServer { required RejectionCause cause; DOMString min_libxmtp_version; // EVENT-008 }; dictionary LockoutChanged { required LockoutChange change; }; dictionary NotificationsFailed { required DOMString cause; }; // the failure cause PUSH-267 records dictionary ArchiveRestored { required boolean complete; }; // EVENT-017 dictionary ConnectionStateChanged { required ConnectionState previous; required ConnectionState current; }; dictionary AttachmentRef { required DOMString attachment_key; // ATCH-041 required DOMString url; // the remote attachment's url required DOMString content_digest; // lowercase hexadecimal (ATCH terms) }; dictionary AttachmentFailed { required DOMString attachment_key; required DOMString url; required DOMString content_digest; required DOMString cause; // an AttachmentFailureCause value (ATCH-060) }; dictionary HandleChanged { required DOMString inbox_id; // EVENT-058 required DOMString handle; // the display handle (EVENT-058) }; dictionary Lagged { required unsigned long long discarded; }; ``` The member source table, which EVENT-024 makes binding. Members that other rows of this section state are not repeated here. | Member | Value | | ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | `group_id` | The id of the group the change is about | | `message_id` | The id of the message the change is about | | `conversation_type` | The group’s `CONVERSATION_TYPE` (`META`): `dm` for a DM, `group` otherwise | | `added_inbox_ids`, `removed_inbox_ids` | The inboxes the commit added to and removed from the group’s membership | | `floor` | The protocol version floor the group is paused for (META section 7) | | `content_type` | The stored message’s content type id under CTYPE-001; absent when the message has no typed content type, as for a message CTYPE-008 retains undecoded | | `sender_inbox_id` | The inbox of the message’s authenticated MLS sender | | `previous`, `current` in `MessageStatusChanged` | The message’s status before and after the change | | `inbox_id` in `IdentityRegistered` | The own inbox’s id | | `installation_key` | The installation key of the installation registered, added, or revoked (IDENT section 8) | | `is_this_installation` | Whether `installation_key` equals this installation’s key | | `cause` in `NotificationsFailed` | The failure cause PUSH-267 records | | `change` in `LockoutChanged` | `entered` or `left`, per the kind table’s trigger | | `discarded` in `Lagged` | The count EVENT-031 names | | `attachment_key`, `url`, `content_digest` in `AttachmentRef` and `AttachmentFailed` | The attachment key under ATCH-041, the `url`, and the `content_digest` of the remote attachment the transition, download, or deletion is about | | `cause` in `AttachmentFailed` | The `AttachmentFailureCause` the SDK reports for the failure under ATCH-060 | | ID | Title | Requirement | Why | | --------- | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | EVENT-001 | One event per change | When a change occurs that a row of the kind table in section 1 names, the client MUST emit exactly one event of that kind for each unit the row names, with that row’s member of the `ClientEvent` block, including after a transaction that was interrupted before it committed and was retried, except under EVENT-003 and EVENT-004 or when the process ends after the change commits but before emission. It MUST NOT emit an event of a kind in the table for any other change. | A missing event leaves the app showing stale state; a duplicate `message.received` is a duplicate notification to the user. | | EVENT-002 | Kinds survive upgrades | When a client version emits a kind, every later client version MUST emit that kind for the same trigger, with every payload member that version carried and with the same meaning. | An app that handles a typed kind reads the wrong state, or none, after the client changes under it. | | EVENT-003 | Sync groups emit nothing | The client MUST NOT emit an event that names a group SYNC-005 hides from the app. | | | EVENT-004 | Import stores emit nothing | While an archive import runs, the client MUST NOT emit `conversation.joined`, `message.received`, `message.deleted`, or `consent.changed` for what the import stores or marks. | An import of thousands of messages would fill every queue and end in `lagged`; `archive.restored` reports it once. | | EVENT-005 | Join origin | The client MUST set `origin` to `created` when this installation created the group, and to `welcomed` otherwise. | | | EVENT-006 | Removal cause | The client MUST set `RemovalCause` to `left` exactly when the own inbox had a published leave request under GMOD-031. | An app that branches on the cause takes the wrong branch. | | EVENT-007 | Deletion cause | The client MUST set `DeletionCause` to `deleted_locally` exactly for a local deletion at an app’s request. | | | EVENT-008 | Minimum version on rejection | The client MUST set `min_libxmtp_version` exactly when `RejectionCause` is `version_too_old`, to the minimum under CONF-036. | | | EVENT-059 | Consent values | The client MUST set `entity_kind` to inbox or conversation, `entity` to the lowercase inbox id or to the lowercase hexadecimal group id that CONS-059 names, and `state` to the new reported state. | An app keys conversations by group id. | | EVENT-017 | Import completion | The client MUST set `complete` to false exactly when the import ended with an error. | | | EVENT-018 | Received message group | The client MUST set a `message.received` event’s `group_id` to the group the message is stored in, including for a stitched DM. | A DM screen misattributes a message. | | EVENT-019 | Changed metadata names | The client MUST set a `conversation.metadata_changed` event’s `changed` to one entry per changed item: its `field_name` under META-074 where it has one; otherwise its component name in META section 2; otherwise `component:` followed by its component id as four lowercase hexadecimal digits, as for an application component. | An app re-reads the wrong fields, or cannot name an application component. | | EVENT-023 | Join adder | The client MUST set `adder_inbox_id` exactly when `origin` is `welcomed`, to the adder under JOIN-025. | An app that shows “you were added by” names the wrong inbox, or none. | | EVENT-024 | Other payload members | The client MUST set each payload member in the member source table to the value that table names for it. | An app that reads a member it cannot trust re-reads everything, or acts on the wrong value. | | EVENT-026 | Observed HMAC epoch increase | When the current HMAC epoch under PUSH-258 is greater than the epoch the client recorded at startup or when it last emitted `hmac_keys.updated` for an epoch increase, an open client MUST emit exactly one `hmac_keys.updated` event for the current epoch without an app call or network request. It MUST NOT emit an epoch-change event for the startup epoch or for epochs reached while it was closed. | An app that caches the current conversation HMAC keys keeps the old keys after an epoch transition. | | EVENT-027 | Client connection state | The client MUST compute one connection state over its open app streams that hold network interest, using PROC section 6’s states: `failed` if any is `failed`; else `reconnecting` if any is `reconnecting`; else `connecting` if any is `connecting`; else `connected`; and `closed` when none is open. When that state changes, the client MUST emit exactly one `connection.state_changed` event with the previous and current state. It MUST NOT emit when the state does not change. | An app cannot show that it is offline or that it recovered without a signal. | | EVENT-058 | Display handle change | When the client stores an association state for an inbox at a sequence id greater than that of every association state it already holds for that inbox, and the stored state has a display handle while the held state with the greatest sequence id has none or a different one, the client MUST emit exactly one `handle.changed` event with `inbox_id` set to that inbox’s id and `handle` set to the stored state’s display handle. The client MUST NOT emit `handle.changed` when it stores an association state for an inbox for which it holds none. | An app that shows an inbox’s handle keeps showing the old handle after the inbox claims a new one. | ## 2. Emission and order An event for a change to stored state is emitted after the change is stored, so an app that reads again on an event sees the change. A change that is not stored, because a transaction failed or was retried, has no event. Order is kept where an app depends on it: within one group, within one consent entity, and within one attachment key. Events for two groups, including two groups of one stitched DM, and a group’s events relative to its consent events, can be emitted in either order, because the client changes them independently. Emission does not depend on why the change happened: a message stream, a sync call, a push-driven fetch, a background worker, or an app act all produce the same events. An event subscription carries no network interest, so a server rejection does not close it, and `client.rejected_by_server` reaches the app (EVENT-016, CONF-075). | ID | Title | Requirement | Why | | --------- | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | | EVENT-010 | The change is readable first | When a change to stored state has an event, the client MUST emit the event only after the change is readable through the SDK, and MUST NOT emit it if the change is not stored. | An app that reads again on an event and finds the old state keeps it until the next event. | | EVENT-012 | Emission order | The client MUST emit the events whose payloads carry the same `group_id`, and the `consent.changed` events for the same entity, in the order it made the changes they report, and the events of one transaction in the order of the kind table. | Two metadata changes that arrive reversed leave the app showing the older value. | | EVENT-013 | No network interest | When an app starts, holds, or ends a subscription, the client MUST NOT send a request to the backend, open or change a subscription stream, or register a topic because of it. | An app that adds a listener would open streams, use battery, and change which messages the client fetches. | | EVENT-014 | Live only | An SDK MUST register a subscription before the call that creates it returns, and MUST NOT hand off to it an event the client emitted before it was registered. | An app that also reads current state on start would handle every earlier change twice. | | EVENT-015 | Handoff order | An SDK MUST hand off each subscription’s events in the order the client emitted them. | | | EVENT-016 | Rejection keeps subscriptions | While the server has rejected the client under CONF-075 and the app has not closed it, an SDK MUST keep every event subscription of that client open unless the app ends it. | A subscription closed by the rejection cannot hand off the `client.rejected_by_server` event that explains it. | | EVENT-055 | Shared lockout reaches every client | When client instances share one credential handle and that handle’s lockout state changes, the client MUST emit `client.lockout_changed` on the event bus of every client instance that shares the handle. | Every client that shares the handle is locked out together; an app told about only one keeps retrying with the others. | | EVENT-056 | One client’s events | An SDK MUST hand off to a subscription only the events emitted by the client instance on which the app created it, including when two client instances in one process share a database or a credential, other than the lockout event of EVENT-055. | An app with two accounts open shows one account’s messages and consent changes under the other. | | EVENT-057 | Attachment event order | The client MUST emit the `attachment.*` events whose payloads carry the same `attachment_key` in the order it made the changes they report. | An app that receives `attachment.upload_completed` before `attachment.upload_started` shows a finished upload as running. | ## 3. Filters A filter names the kinds a subscription wants and can narrow them to some conversations or some messages. The SDK applies the filter before an event enters the queue, so a subscription’s queue holds only the events it selected. An event that names no group is not narrowed by `group_ids`. ```webidl dictionary EventFilter { required sequence kinds; // an empty sequence selects no kind sequence> group_ids; // absent selects every group sequence content_types; // message.received only; absent selects every content type boolean references_own_messages; // message.received only; absent means false }; ``` A stitched DM is one conversation to an app (DMS-007, DMS-009), so a filter that names any group of the DM selects the events of every group of it. | ID | Title | Requirement | Why | | --------- | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | EVENT-020 | Filter before queueing | An SDK MUST place an event in a subscription’s queue, subject to EVENT-030, if and only if its kind is in the `kinds` of the subscription’s `EventFilter`; when `group_ids` is present and the event names a group, that group or another group of the same stitched DM under DMS-009 is in `group_ids`; and, for `message.received` when `content_types` is present, its content type is present and matches an entry of `content_types` under CTYPE-001; and it passes EVENT-021. | Events a subscription did not select would fill its queue and discard events it did select; a DM screen would miss messages stored in the DM’s other groups. | | EVENT-021 | References to own messages | Where `references_own_messages` is true, an SDK MUST pass a `message.received` event only when the message is an `xmtp.org/reply:1.0` whose `reference` parameter, or an `xmtp.org/reaction:2.0` whose `ReactionV2.reference`, names a message that the client holds at emission and whose sender inbox is the own inbox. | | | EVENT-022 | Lagged is always selected | An SDK MUST hand off a `lagged` event to its subscription whether or not the `kinds` of its `EventFilter` names `lagged`. | A subscription that did not select `lagged` loses events without any signal. | ## 4. The queue and lagged A subscription whose app is slow cannot hold events for ever. Each queue holds at most 1024 events. When the queue is full, the SDK discards new events for that subscription and counts them. Before it hands off any later event, it hands off one `lagged` event with the count, which tells the app that the events it received for that subscription are incomplete. The bound counts every event in the queue as the Terms define it: every event emitted for the subscription and not yet handed off, in every place the SDK holds it, and the event whose callback is running. A pending `lagged` event is not counted. | ID | Title | Requirement | Why | | --------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------- | | EVENT-030 | The queue bound | While a subscription’s queue holds 1024 events other than a pending `lagged` event, an SDK MUST discard each new event for that subscription and count it, and MUST NOT hold more than 1024 such events for the subscription in any place. | An app that stops reading must not make the client use memory without limit. | | EVENT-031 | Lagged before later events | When an SDK has discarded events for a subscription, it MUST hand off one `lagged` event whose `discarded` is the number discarded since the previous `lagged` handoff, before it hands off any event emitted after the first of those discards. | An app that does not know it missed events keeps state that is wrong. | | EVENT-033 | Subscriptions do not wait | An SDK MUST NOT delay a handoff to one subscription because another subscription’s queue is full or one of its callbacks is running. | One slow subscription would stall every other subscription of the client. | ## 5. Callbacks and ending a subscription A subscription is read with an iterator or with a callback. With a callback, the SDK calls the app’s code for each event. The rules below keep callbacks in order, keep one callback’s failure from affecting other work, and let an app end a subscription or close the client from inside a callback. Apps can keep several subscriptions for different kinds or conversations. They should end listeners they no longer use. An SDK may warn about duplicate listeners whose filters overlap. A callback is handed off when the SDK’s start check for its subscription admits it. | ID | Title | Requirement | Why | | --------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | | EVENT-050 | One callback at a time | An SDK MUST NOT start a subscription’s callback while an earlier callback of that subscription is running. | Two callbacks that run at the same time can finish in the wrong order and apply an older state last. | | EVENT-051 | A failed callback is contained | When an app’s callback fails, an SDK MUST continue to hand off that subscription’s later events, and MUST NOT end the subscription, any other subscription, the app’s process, or any operation of the client because of the failure. | One bad event would stop all later events, or end the client. | | EVENT-052 | Calls from a callback complete | While a callback runs, an app MAY call any operation of the same client, including ending a subscription and closing the client, and the SDK MUST complete that operation without waiting for the callback to return. | An app that reads again, or closes, inside the callback would wait for ever. | | EVENT-053 | Ending stops handoffs | After an app ends a subscription, an SDK MUST NOT hand off another event for it, and MUST complete a pending iterator read of it as ended. | A callback that runs after its screen is gone acts on state the app has released. | | EVENT-054 | Closing ends subscriptions | When an app closes the client, an SDK MUST end every subscription of that client before the close returns. | A subscription that survives its client hands off events the app can no longer act on. | ## Known limitations Events are not durable. No subscription receives an event for a change made while it did not exist, and a discarded event is reported only as a count. A process that ends after a change commits and before its event is emitted loses that event; EVENT-001 covers retries of a transaction that did not commit. An app that needs every message uses PROC section 7. Most payloads name what changed, not the new value. When the app reads again, the state can already include later changes. A client instance emits events only for changes it makes itself. Another process, or another client instance in the same process, that shares the database makes changes this instance emits no event for. `message.expired` is emitted when the cleanup pass deletes the message under META-063, which can be later than the expiry itself. META-051 hides the message from the expiry on, whether or not the event has been emitted. Filters do not read consent. A conversation whose consent is denied still produces events; an app that hides denied conversations applies CONS-060 to events itself. In a stitched DM, a reply or reaction in one group can arrive before the message it names in another group. It then does not pass `references_own_messages`, and no later event reports it. Internal receivers, such as device sync and barriers, do not count toward the client connection state. That state can be `closed` while background work uses the network. A client stores a newer association state for an inbox only when it reads that inbox’s identity updates for another reason, such as a membership refresh under GMOD-029, because a subscription causes no request (EVENT-013). Until then, a handle the inbox claimed has no `handle.changed` event on that client, and the client reports the older display handle. # Fork recovery and the commit log Members of one group can hold different MLS states for the same epoch: one applied a commit that another rejected, or two clients merged the same commit onto different trees. A member in that condition is forked. It can no longer decrypt what the others send, and nothing in MLS tells it so. The commit log is the record that does. Publishers append to a per-group log on the backend a signed entry for every commit they apply or reject, with the epoch authenticator that resulted. Every member compares its own record against that log. A member whose authenticator differs from the log’s at the same commit is forked, and asks the group’s permitted readders to remove and re-add it. The repair is a remove-and-add commit and the Welcome it produces. It restores a member that can still process the removal commit, which is the case when the member’s log diverged before its epoch secrets did, or when the readder’s commit is the first the member cannot apply. A member whose epoch secrets have already diverged cannot decrypt the removal, stays active in its own view, and refuses the Welcome under JOIN-042. This spec does not promise to repair that member; the Known limitations say why. The log is sound only while its entries are complete, ordered, and signed under one key per group. The rules here are what make that hold. ```mermaid flowchart LR C[Commit applied or rejected] --> L[(Local commit log)] L -->|publisher signs and publishes| R[(Commit-log topic on the backend)] R -->|every member reads and verifies| A[(Accepted remote entries)] L --> W{Compare at the same commit} A --> W W -->|authenticators differ| F[Forked] W -->|equal| N[Not forked] W -->|no match yet| U[Unknown] F -->|ReaddRequest in a one-shot group| P[Permitted readder] P -->|remove and add in one commit| J[Welcome replaces the state] ``` ## Scope In scope: the entries a client records for each commit outcome; the keys an entry is sealed under and how a reader opens it; who publishes entries and in what order; how a client verifies and accepts remote entries; the fork state and how it is computed; readd requests, the one-shot groups that carry them, and who may act on them; the readd commit; the recovery policy an app sets; and what an app can read. Out of scope: commit validation, the membership component, and the protocol-version hold (GMOD-021, GMOD-005, GMOD-025), ordered topic processing and terminal rejection (PROC-005, PROC-011), the publish and query contract, sequence ids, and the admission of a commit-log entry (`API`), the topic layout (`TOPIC`), retention (`OPS`), the super admin role and proposal authorization (`PERM`), consent (`CONS`), the metadata components this spec uses (`META`), when a Welcome replaces existing group state (JOIN section 7), and the deployment switch that turns the log on (CONF-045). | Related | Relation | | --------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `CONF` | Owns `commit_log_enabled` and CONF-045, the switch that turns publishing and reading off for a deployment. | | `JOIN` | Owns whether a Welcome replaces state the client already holds (JOIN-092, JOIN-042 to JOIN-044), the adder read from the ratchet tree (JOIN-025), and key-package validation (JOIN-007, JOIN-008, JOIN-082). A readd is repaired by that path. | | `API` | Owns `ClientEnvelope` and its `sealed_commit_log_entry` payload, sequence ids (API-286 through API-289), the prefix a read returns (API-201), and the admission of a commit-log entry (API-230). | | `TOPIC` | Owns the commit-log kind byte and its 32-byte commit-log identifier (TOPIC-001, TOPIC-002). | | `OPS` | Owns retention. API-212 assigns commit-log expiry; OPS-001 prevents deletion of an exempt envelope. | | PERM-001, GMOD-052 | Own the super admin role and the same-installation readd exception used by FORK-062. | | [CONS section 1](/specs/cons-consent/#1-records-and-keys) | Defines the conversation consent state tested by FORK-085, FORK-030, and FORK-053. | | [META section 2](/specs/meta-group-metadata/#2-well-known-components) | Owns the `GROUP_ROOT_KEY`, `ONESHOT_MESSAGE`, and minimum protocol version components. This spec states their use. | | GMOD-040, GMOD-041 | Own the group root and the commit-log keys derived from it. | | `ARCH` | Owns restored groups (ARCH-015). A restored group holds no group root, so it has no commit-log id, and FORK-030 does not read it. | | GMOD-021, GMOD-025 | Own commit validation and the hold below a group’s minimum protocol version. | | PROC-011, PROC-012 | Own terminal rejection, which FORK-002 records, and unresolved work, which it does not. | | `EVENT` | EVENT-001 reports when a conversation’s fork state becomes forked. | ## Terms | Term | Meaning | | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Epoch authenticator | The `epoch_authenticator` of a group’s key schedule ([RFC 9420 §8](https://www.rfc-editor.org/rfc/rfc9420.html#section-8)). It identifies the encryption state after a commit and is not secret. | | Commit sequence id | The sequence id of a commit’s envelope on the group’s message topic. | | Local entry | One `LocalCommitLogEntry` (section 1) that a client records for a commit outcome. | | Removal entry | A local entry for a commit that removed the recording installation. It carries the pre-commit epoch as its applied epoch. | | Membership | The span from one installation of a group’s state, by creation, a Welcome, or an archive restore, to the next. Local entries from an earlier membership are not compared. | | Entry | A commit-log entry: a `PlaintextCommitLogEntry` (section 2), which a publisher seals into a `SealedCommitLogEntry` (FORK-074). | | Commit-log topic | The topic of a conversation’s entries, named by its commit-log id (TOPIC-001). | | Publisher | An installation whose leaf node names an inbox in the conversation’s `DM_MEMBERS`, for a DM, or in its super admin list, for a group. | | Legacy local history | Local commit-log entries recorded by a client that did not yet support author-signed entries under FORK-076. | | Connected legacy suffix | The longest suffix of local entries that can be followed backward from the current MLS epoch and epoch authenticator through consecutive applied states, stopping at the current membership start or the first missing or inconsistent state transition. Rejected entries retain the same epoch and authenticator. A removal entry is excluded and stops the suffix. A zero-sequence membership marker identifies the current membership start only when this backward proof reaches its recorded state. | | Retained role evidence | A `GroupUpdated` record the client created when it applied an MLS commit, associated with that commit’s group and sequence id. An application message whose content claims to be `GroupUpdated` is not retained role evidence. | | Unresolved role commit | An applied commit in legacy local history whose recorded change classification permits a super-admin-list change, or is absent or unrecognized, and for which retained role evidence is absent or cannot be decoded. | | Legacy reader epoch floor | A persistent minimum `applied_epoch_number` for entry admission, initialized under FORK-088; zero is an initialized value. | | Publisher boundary | The group-message sequence position for a publisher that FORK-089 uses when testing continuity. | | Accepted entry | An entry a client read from the commit-log topic and kept under FORK-077, FORK-087, and FORK-083. | | Fork state | One of `forked`, `not forked`, or `unknown`, held for each conversation and set under section 5. | | Readd request | A `ReaddRequest` (section 6): a forked installation’s request to be removed and added back. | | One-shot group | A group whose conversation type is one-shot: it carries one `OneshotMessage` in its immutable metadata and never carries an application message. | | Permitted readder | An inbox whose installations receive a readd request and may act on it, per the table in section 6. | | Readd commit | The commit under FORK-062 that removes an installation and adds it back. | | Recovery policy | The app-supplied choice of which conversations a client sends readd requests for. | ## 1. The local commit log Every commit a client merges or rejects with a terminal outcome leaves one local entry. The entry records the commit’s sequence id, the epoch authenticator before it, the result, and the epoch and authenticator after it. A commit that removes the recording installation is a removal entry: the member merges only the public part of that commit and cannot derive the new epoch’s secrets, so the entry keeps the pre-commit epoch. A removal entry is neither published nor compared. A failure is recorded only when it is terminal. PROC-011 and PROC-012 distinguish terminal rejection from unresolved work; a held commit has no outcome yet, and recording one would publish a rejection the group never made. CONF-045 forbids publishing and reading while a deployment’s `commit_log_enabled` is `false`. This spec adds that such a client records no local entries and reports every fork state as `unknown` (FORK-004), so that a log that was never kept is not read as evidence. ```webidl dictionary LocalCommitLogEntry { required sequence group_id; // 16 or 32 bytes required unsigned long long commit_sequence_id; required sequence last_epoch_authenticator; required CommitResult commit_result; // the wire enum of section 2 required unsigned long long applied_epoch_number; // unchanged when the commit was not applied required sequence applied_epoch_authenticator; // unchanged when the commit was not applied required boolean removed_this_installation; // true for a removal entry }; ``` The result a terminal failure records is the first row below whose condition holds. | Failure | `commit_result` | | ----------------------------------------------------------------------------------- | ----------------------------- | | The commit’s `epoch` is not the group’s current epoch | `COMMIT_RESULT_WRONG_EPOCH` | | The commit’s payload cannot be decrypted or fails MLS processing for another reason | `COMMIT_RESULT_UNDECRYPTABLE` | | The commit decrypts and fails validation under GMOD-021 | `COMMIT_RESULT_INVALID` | | ID | Title | Requirement | Why | | -------- | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | FORK-001 | Record every applied commit | While `commit_log_enabled` is `true`, when the client merges a commit into a group’s MLS state and its installation is a member after the merge, the client MUST record a local entry whose `commit_sequence_id` is the commit sequence id, whose `last_epoch_authenticator` is the group’s epoch authenticator before the merge, whose `commit_result` is `COMMIT_RESULT_APPLIED`, and whose `applied_epoch_number` and `applied_epoch_authenticator` are the group’s epoch and epoch authenticator after it. | A commit without an entry can never be compared, so a fork at that commit is read as `unknown` for ever, and a publisher that skips it ends the log for every member under FORK-083. | | FORK-002 | Record only a terminal failure | While `commit_log_enabled` is `true`, when the client records a terminal rejection for a commit under PROC-011, it MUST record a local entry with the `commit_result` the table above gives and with `applied_epoch_number` and `applied_epoch_authenticator` equal to the group’s current values, and MUST NOT record an entry for a commit it holds for a later attempt. | A held failure recorded as terminal publishes a rejection the group never made, and every member that applied the commit then reads itself as forked. | | FORK-004 | No log, no evidence | While `commit_log_enabled` is `false`, the client MUST report every conversation’s fork state as `unknown`. | A `not forked` read from an empty log tells an app a broken conversation is healthy. | ## 2. Keys and signatures Entries are encrypted and signed. Three keys serve a conversation’s log, all derived from its group root under GMOD-041. The commit-log signing key signs every entry, the commit-log encryption key encrypts it, and the commit-log nonce key derives its nonce. Every installation that holds a conversation’s MLS state received the root with the creation or Welcome that installed it, so every member can read the log, whether or not it is forked. The commit-log id names the topic (TOPIC-001). It is the only key a reader verifies an entry’s outer signature under, and no entry can change it. A group whose id is 16 bytes has no commit-log id, and so no log to read. The nonce is derived from the topic and the entry, so the same entry sealed twice is the same bytes, and a retry is a duplicate under API-222. This is a deterministic use of RFC 8439, in the style of SIV ([RFC 5297](https://www.rfc-editor.org/rfc/rfc5297)). RFC 8439 §2.8 asks for a nonce that is unique for each invocation, and its §4 rejects truncated wide outputs as nonces because they can repeat. Here a repeat for identical input is intended. For distinct entries of one conversation, a repeat has probability at most q(q−1)/2^97 for q entries, about 2^-57 at a million entries. A repeat would reveal the XOR of the two entries to readers of the topic, and would allow AEAD forgeries under that nonce, which the signature checks in FORK-077 still reject. `API` owns `xmtp.backend.v1.SealedCommitLogEntry` as a payload of `ClientEnvelope`. It is shown here because FORK-074 states what its fields carry. `xmtp.mls.message_contents.CommitLogEntry`, an older message with a `sequence_id` field, is not used on this backend. xmtp.backend.v1 ```proto // A commit-log entry, encrypted and signed under keys derived from the // group root. message SealedCommitLogEntry { // 32-byte public key of the commit-log signing key. Derives the topic. bytes commit_log_id = 1; // 12 bytes. bytes nonce = 2; // ChaCha20-Poly1305 encryption of a serialized PlaintextCommitLogEntry. bytes ciphertext = 3; // 64-byte Ed25519 signature [R(32) || S(32)] over CommitLogEntryTBS by // the commit-log signing key. bytes signature = 4; } ``` xmtp.mls.message\_contents ```proto enum CommitResult { COMMIT_RESULT_UNSPECIFIED = 0; COMMIT_RESULT_APPLIED = 1; COMMIT_RESULT_WRONG_EPOCH = 2; COMMIT_RESULT_UNDECRYPTABLE = 3; COMMIT_RESULT_INVALID = 4; } // PlaintextCommitLogEntry indicates whether a commit was successful or not, // when applied on top of the indicated `last_epoch_authenticator`. message PlaintextCommitLogEntry { // The group_id of the group that the commit belongs to. bytes group_id = 1; // The sequence ID of the commit payload being validated. uint64 commit_sequence_id = 2; // The encryption state before the commit was applied. bytes last_epoch_authenticator = 3; // Indicates whether the commit was successful, or why it failed. CommitResult commit_result = 4; // The epoch number after the commit was applied, if successful. uint64 applied_epoch_number = 5; // The encryption state after the commit was applied, if successful. bytes applied_epoch_authenticator = 6; // The 32-byte installation key of the installation that published this // entry: the signature_key of its leaf node. bytes author_installation_key = 7; // 64-byte Ed25519ph signature by author_installation_key (FORK-076). bytes author_signature = 8; } ``` | ID | Title | Requirement | Why | | -------- | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | FORK-074 | Seal each entry | When the client publishes an entry, it MUST publish a `SealedCommitLogEntry` whose `commit_log_id` is the conversation’s commit-log id and whose `nonce` is the first 12 bytes of the HMAC-SHA256, under the commit-log nonce key, of the commit-log topic followed by the encoding of the `PlaintextCommitLogEntry` that writes each field whose value is not the default once, in ascending field-number order, and no other bytes. Its `ciphertext` MUST be the ChaCha20-Poly1305 ([RFC 8439](https://www.rfc-editor.org/rfc/rfc8439)) encryption of that same encoding under the commit-log encryption key, with that nonce and with the commit-log topic as associated data. Its `signature` MUST be the publish signature of `CommitLogEntryTBS` under the commit-log signing key. | A nonce taken from anything but the topic and the entry makes a retried entry a second stored copy, or puts two inputs under one nonce and key. An entry under any other key is discarded by every reader. | | FORK-076 | Sign each entry as its author | When the client publishes an entry, it MUST set its `author_installation_key` to its own installation key and its `author_signature` to the Ed25519ph signature ([RFC 8032 §5.1](https://www.rfc-editor.org/rfc/rfc8032#section-5.1)) under that key, with context `XMTP commit-log author v1`, of the commit-log topic followed by the encoding FORK-074 defines of that entry with `author_signature` empty. | Every reader discards an entry whose author signature fails (FORK-077), so a publisher that omits it leaves the conversation with no log. | ## 3. Publishing entries A publisher appends its local entries to the conversation’s commit-log topic in the order it recorded them. A reader requires an entry to continue the previous accepted entry except where FORK-083 permits a new chain. A publish that fails, or whose response does not confirm an entry, is retried from that entry before anything later is sent. Removal entries are never published: a removal entry does not attest the epoch the remaining members moved to. The backend routes an entry by its `commit_log_id` (TOPIC-001). It refuses the entry unless its signature passes API-300 (API-230), assigns it a sequence id (API-286 through API-289), and stores it. It cannot decrypt it. A read returns a prefix of the topic in sequence id order (API-201), and a commit-log entry never expires (OPS-001), so the order every member reads is the order every member reads. A client upgrading legacy local history may hold a publisher flag that predates later role changes. Publication eligibility comes from its current MLS state and its current role’s start, rather than from that old flag. The client’s retained role evidence can identify a promotion that happened after the current membership began. Administrative message clearing can remove that evidence while preserving local commit-log entries. Logging disabled during a commit or replacement Welcome can also leave a gap in the recorded states. Recovery first limits history to the connected legacy suffix; an older zero-sequence marker by itself does not establish the current membership. Where the evidence cannot distinguish a role change from another applied change, recovery keeps the suffix whose eligibility follows from the current role and the remaining evidence. It omits the uncertain earlier entries. It does not move publication progress backwards. This is a one-time rule for legacy local history; ordinary subsequent role changes keep the current-role rule. The connected-suffix state-proof table computes the connected suffix in reverse local recording order. Start `(E, A)` at the current MLS epoch number and epoch authenticator. Each row below describes the next older local record. A mismatch excludes that record and all earlier records. A state match compares the complete authenticator bytes. | Record | State proof and stopping rule | | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Removal entry | Stop before including this record, even if its retained pre-removal state matches. | | Zero-sequence membership marker | Stop without publishing this marker. It establishes the membership start only if its applied epoch number and applied authenticator equal `(E, A)`; otherwise the earlier prefix remains unproved. | | Applied entry | Require `(applied_epoch_number, applied_epoch_authenticator) = (E, A)` and `E > 0`. Include it and continue with `(E − 1, last_epoch_authenticator)`. | | Rejected entry | Require `applied_epoch_number = E` and both `last_epoch_authenticator` and `applied_epoch_authenticator` equal `A`. Include it and continue with unchanged `(E, A)`. | The legacy recovery boundary table selects the boundary within the connected legacy suffix. If that suffix is empty, no legacy entry is eligible. A position in the table refers to the corresponding local entry, and that entry is included in the suffix. The entry of a promotion is included just as it is during normal operation. | Conversation | Legacy recovery boundary | | ----------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | DM | The start of the connected legacy suffix. Both members are publishers throughout that membership. | | Group with a retained own-inbox super-admin promotion or an unresolved role commit in the connected legacy suffix | Whichever of those commits has the greatest commit sequence id. A retained promotion is identified by the client’s inbox in `GroupUpdated.added_super_admin_inboxes`. | | Group with neither such commit | The start of the connected legacy suffix. | Retained role evidence after the chosen boundary is what rules out a later loss of the current role. A publisher’s continuing role cannot be inferred from its cached flag. The last unresolved commit itself is included: the current role and the absence of a later role transition establish its post-commit role, while the uncertainty concerns the earlier prefix. A recorded classification that permits changes to group membership, permissions, or administrator lists permits a super-admin-list change for this purpose: one applied commit can combine those changes. A classification confined to a key update or to non-role metadata does not. A rejected commit does not change the role. These classifications describe the retained local evidence; the internal enum and storage layout remain outside the spec. | ID | Title | Requirement | Why | | -------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | FORK-085 | Publish from the current role | While `commit_log_enabled` is `true`, a conversation’s consent state is allowed, and the client is a publisher of that conversation, it MUST publish an entry for each local entry, other than a removal entry, that it recorded in its current membership since it last became a publisher, with `group_id`, `commit_sequence_id`, `last_epoch_authenticator`, `commit_result`, `applied_epoch_number`, and `applied_epoch_authenticator` equal to the local entry’s values of the same name, and MUST NOT publish any other local entry, except that legacy local history is subject to FORK-086. The local entry of the commit that made it a publisher counts as recorded since then. | A publisher that skips an eligible entry can leave readers without evidence, while entries from an earlier membership or role can precede a gap and duplicate permanent log history. | | FORK-086 | Recover legacy publication eligibility | When publication eligibility for legacy local history has not yet been recovered, before the first publication attempt or first subsequent applied commit, the client MUST retain for publication exactly the suffix selected by the connected-suffix state-proof table and the legacy recovery boundary table if its current MLS role permits publication, subject to existing publication progress and the other conditions of FORK-085. It MUST publish those eligible legacy entries while the enable, consent, and actual-role conditions in FORK-085 hold, and MUST NOT publish a legacy entry preceding that boundary. The client MUST preserve recorded publication progress and its resulting eligibility through restart. | An idle promoted publisher otherwise remains excluded, and treating flag repair as a promotion permanently skips pending entries, including in a DM whose authority never changed. | | FORK-021 | No gaps, in order | The client MUST publish a conversation’s entries in ascending `commit_sequence_id` order, and when a publish request fails or its response does not carry a sequence id greater than 0 for an entry, it MUST publish that entry again before it publishes any later entry of that conversation. | An entry published ahead of one the backend never stored is discarded by every reader under FORK-083, and the missing one can never be inserted behind it. | ## 4. Reading the remote log Every member reads the commit-log topic of each DM and group it holds and verifies each entry before it counts. Verification has three parts. The signatures, the decryption, and the identity of the entry tie it to the conversation’s commit-log id, its group, and the installation that wrote it. The author check ties it to a publisher in the reader’s own ratchet tree, once the reader has processed the commit the entry names. The chain rules tie it to the previous accepted entry: sequence ids increase, an applied commit starts from the authenticator the last one produced and advances the epoch by one, and a rejected commit leaves both unchanged. An entry that fails any part is discarded and never counts, however often it is read. An entry that fails FORK-077 is discarded whoever published it, and the backend refuses one whose signature fails before storing it (API-230, API-300). That stops anyone who never held the root. Every installation that was ever a member holds it, so the root alone does not make an installation a publisher: each entry names its author and is signed by that installation, and a reader keeps it only when its own ratchet tree shows the author is a publisher. A reader judges that once it has processed the commit the entry names, so an entry from a newly promoted publisher waits instead of being lost, and when the author of the last accepted entry stops being a publisher, the next publisher’s entry starts the chain again. A publisher that returns after losing the role, or after removal and readd in the same commit, has a new publisher boundary. An entry at or after that boundary can start a chain after an accepted entry from before it. A reader’s membership also sets a publisher boundary from the Welcome’s authenticated group-message anchor (JOIN-036 through JOIN-038). The anchor gives a reader that joined after earlier publisher changes a point from which it can compare the log. Publisher boundaries survive a client restart. Accepted entries and the sticky fork state remain subject to section 5. The chain conditions a reader applies once it holds an accepted entry for the conversation: | `commit_result` of the entry | Condition on the last accepted entry | | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Any | `commit_sequence_id` is greater than the last accepted entry’s `commit_sequence_id` | | `COMMIT_RESULT_APPLIED` | `last_epoch_authenticator` equals the last accepted entry’s `applied_epoch_authenticator`, when that is non-empty, and `applied_epoch_number` equals the last accepted entry’s `applied_epoch_number` plus 1 | | Not `COMMIT_RESULT_APPLIED` | `applied_epoch_number` and `applied_epoch_authenticator` equal the last accepted entry’s | A legacy reader may not retain the Welcome anchor or every publisher return it processed before upgrade. It therefore records a one-time minimum applied epoch before its first later merge or remote-entry evaluation. Entries from lower applied epochs are discarded, while the existing authority, hold, and continuity checks apply to the rest. The floor uses the current public group-context epoch even for an inactive reader: that reader cannot derive post-removal MLS secrets, but can still verify commit-log envelopes under the persistent group root. Application messages do not advance this epoch. Creation and every validated Welcome set the floor to zero. A Welcome provides an authenticated publisher boundary for its new membership. Ordinary processing and restart preserve the initialized floor until that reset. Legacy initialization preserves existing accepted entries and sticky fork state. The boundary-initialization table supplies the initial value and the later commits counted by FORK-089: | Boundary initialization | Initial boundary for each current publisher | Later role/readd commits considered | | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | | Creation | Zero. | Commits applied in that membership. | | Welcome installation | Its authenticated `message_cursor` (JOIN-036 through JOIN-038). | Commits applied after that Welcome. | | Legacy reader initialization under FORK-088 | Its previously recorded publisher boundary, or zero if none was recorded. Earlier unrecorded role/readd positions and the earlier Welcome anchor are omitted. | Commits applied after this initialization. A subsequent Welcome starts the Welcome row instead. | | ID | Title | Requirement | Why | | -------- | ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | FORK-030 | Read every conversation’s log | While `commit_log_enabled` is `true`, the client MUST read every envelope on the commit-log topic of every DM and group it holds whose consent state is allowed, other than one-shot groups, sync groups, and restored groups under ARCH-015, and MUST evaluate each under FORK-077, FORK-087, and FORK-083 exactly once, in sequence id order. | A member that does not read cannot learn it is forked, and keeps sending messages nobody can decrypt. An entry evaluated twice is a duplicate under the chain rules. | | FORK-077 | Verify and open each entry | When the client reads an envelope from a conversation’s commit-log topic, it MUST discard it unless its `commit_log_id` equals the conversation’s commit-log id, its `signature` passes API-300 under that id over the `CommitLogEntryTBS` whose topic is the conversation’s commit-log topic, its `ciphertext` decrypts under the commit-log encryption key with its `nonce` and that topic as associated data, the decrypted entry’s `group_id` equals the conversation’s group id, its `commit_sequence_id` is greater than 0 and less than the envelope’s sequence id, and its `author_signature` verifies under its 32-byte `author_installation_key` as FORK-076 defines. A failed check discards that envelope only. | The operator can place any bytes on a topic, and every installation that was ever a member can seal an entry; the author signature is what names the installation that wrote it. A publisher records an entry only after reading its commit, so an entry naming a commit at or after its own sequence id is false (API-289), and one accepted would stop every later entry from continuing the chain. | | FORK-087 | Admit current publisher evidence | When an entry passes FORK-077, the client MUST discard it if its `applied_epoch_number` is less than the legacy reader epoch floor under FORK-088. While the client’s MLS state for the group is active, it MUST NOT evaluate any remaining entry or any later envelope of that topic under FORK-083 until the last processed group-message envelope’s sequence id is not less than the entry’s `commit_sequence_id`. When it evaluates that entry, it MUST discard it unless its `author_installation_key` is the `signature_key` of a publisher’s leaf node in its ratchet tree, as that tree stands no earlier than the processed position it checked. | An old signed entry can establish a tip whose real pre-upgrade tenure boundary was never recorded, permanently blocking later entries. | | FORK-088 | Initialize legacy reader admission | For an existing conversation whose legacy reader epoch floor is absent, before its first subsequent applied commit or remote-entry evaluation, the client MUST set its legacy reader epoch floor to the current MLS public group-context epoch and preserve that floor through restart and later processing until a subsequent Welcome installation, whether the group is active or inactive. When creating a conversation or installing a validated Welcome, it MUST set the floor to zero. Admission under this floor MUST preserve prior accepted entries and sticky fork state. | The current epoch remains available when logging was disabled or role records were cleared, and application messages do not advance it. | | FORK-083 | Preserve continuity within publisher tenure | When an entry passes FORK-087 and the client holds an accepted entry for the conversation, the client MUST discard the entry unless every condition in the chain table holds, except that only the first row’s condition applies when either the last accepted entry’s author is not a publisher in the current ratchet tree, or the last accepted entry’s `commit_sequence_id` is less than that author’s publisher boundary under FORK-089 and the candidate entry’s `commit_sequence_id` is not less than that boundary. | A publisher can return after its upload cutoff skips an unpublished part of the old chain. | | FORK-089 | Track admitted publisher tenure | When evaluating an entry under FORK-083, including after a restart, the client MUST use for each current publisher installation the maximum of its initial boundary from the boundary-initialization table and the commit sequence ids of commits considered by that row that either made that installation a publisher or removed and added that installation in the same commit. | The legacy admission floor makes unknown earlier boundaries unnecessary for newly admitted entries; subsequent observed role changes still need exact boundaries. | ## 5. Fork detection A client’s fork state for a conversation is decided at the newest commit both its own log and the accepted remote log hold. Equal authenticators there mean the client is on the group’s state; different ones mean it is not, whatever newer entries say. Newer local entries with no remote counterpart yet leave the answer open when the newest shared commit agrees: the publisher may not have published them, or the client may have applied a commit the group rejected. Only entries from the current membership count, and removal entries never do. `forked` is sticky. Once a member is on a different state, later entries cannot be compared meaningfully, and only a Welcome that replaces the state (JOIN-042) gives it a log worth comparing again. The reset is what an app and a readder observe: a repaired member reports `unknown` until its new membership has been checked, not `forked` for ever and not `not forked` on trust. The table below is exhaustive and its rows are exclusive. The shared commit is the local entry, other than a removal entry, recorded in the current membership with the highest `commit_sequence_id` for which an accepted remote entry has the same `commit_sequence_id`. | Fork state | Condition | | ------------ | --------------------------------------------------------------------------------------------------------------------------------------- | | `forked` | A shared commit exists and the local `applied_epoch_authenticator` differs from the accepted remote entry’s. | | `not forked` | A shared commit exists, the authenticators are equal, and no local entry of the current membership has a higher `commit_sequence_id`. | | `unknown` | No shared commit exists, or the authenticators are equal and a local entry of the current membership has a higher `commit_sequence_id`. | | ID | Title | Requirement | Why | | -------- | ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | FORK-082 | The comparison for read logs | While `commit_log_enabled` is `true`, for each conversation whose log FORK-030 reads and whose fork state is not `forked`, the client MUST hold the fork state the table above gives for its local entries and accepted remote entries. | A state computed at an older commit than the newest shared one reports `not forked` for a member that diverged since. | | FORK-041 | Forked is sticky until replaced | While a conversation’s fork state is `forked`, the client MUST NOT set it to another value, except that when it replaces the conversation’s state from a Welcome under JOIN-042 it MUST set the fork state to `unknown`. | A state that clears itself when later entries happen to agree hides the fork the readders were asked to repair. One that survives the repair makes the repaired member ask again. | ### 5.1 Epoch mismatch diagnostic `maybe_forked` is a separate diagnostic. It is not the three-state result above. A rejected old-epoch commit can be the normal loser of a commit race. Its epoch alone does not prove that members hold different state. Keep its rejection and commit-log entry for comparison. A future-epoch or unexpected equal-epoch failure remains suspicious. A clear diagnostic is not proof of agreement, and this rule does not clear a diagnostic saved by an earlier failure. | ID | Title | Requirement | Why | | -------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | | FORK-073 | Distinguish stale epoch rejections | When the client records a terminal `WrongEpoch` rejection, it MUST NOT set `maybe_forked` solely from that rejection if the envelope epoch is strictly less than the current MLS epoch. It MUST retain the rejection and applicable commit-log entry. A future-epoch or unexpected equal-epoch mismatch MUST retain the diagnostic trigger. | A losing concurrent commit must not make a healthy group appear forked; the log must still expose real divergence. | ## 6. Readd requests A forked installation cannot send in the group, so the request travels outside it: as the `ONESHOT_MESSAGE` component in the immutable metadata of a new one-shot group whose members are the permitted readders. Their installations receive it as a Welcome and read the message from the metadata. A one-shot group is never a conversation: it is not listed, not streamed, and never carries an application message. JOIN-036 exempts it from carrying a join anchor. The requester’s other installations receive the request too, because they are added with the requester’s inbox. The request names the group and the highest commit sequence id among the requester’s accepted remote entries. A readder uses that value to tell a request made before its last readd commit from one made after it, so that one fork does not produce a second readd. The requester sends one request per fork and waits for a Welcome. A recipient checks the request before it records it. The sender is the installation the Welcome’s ratchet tree names (JOIN-025), and it has to be a member of the group it wants back into: a non-member asking to be re-added is an add request, which only the group’s permissions decide. A group the recipient has not consented to gets no work from it. | Conversation | Permitted readders | | ------------ | ----------------------------------- | | DM | Both members’ inboxes | | Group | Every inbox in the super admin list | xmtp.mls.message\_contents ```proto message OneshotMessage { oneof message_type { ReaddRequest readd_request = 1; } } // A request sent by an installation to recover from a fork. Other members // may remove and readd that installation from the group. message ReaddRequest { bytes group_id = 1; // The sequence ID of the latest commit log entry at the time the request // is sent; used to disambiguate cases where an installation forks // and is readded multiple times. uint64 latest_commit_sequence_id = 2; } ``` | ID | Title | Requirement | Why | | -------- | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | FORK-050 | Send a readd request | When a conversation’s fork state becomes `forked` and the recovery policy selects it (FORK-070), the client MUST send a `ReaddRequest` whose `group_id` is the conversation’s id and whose `latest_commit_sequence_id` is the highest `commit_sequence_id` among its accepted remote entries, as the `ONESHOT_MESSAGE` of a one-shot group whose members are the permitted readders in the table above, and MUST NOT send an application message in that group. | A request sent to anyone else reaches nobody who can act, and one that understates the sequence id is discarded as already answered. | | FORK-051 | One request per fork | While the client has sent a readd request for a conversation and has not since replaced the conversation’s state from a Welcome, the client MUST NOT send another readd request for that conversation. | Every request creates a group and a Welcome for each readder installation. Repeating it while the first is pending multiplies that for nothing. | | FORK-052 | One-shot groups are not conversations | When a client receives a Welcome for a group whose conversation type is one-shot, it MUST act on the `ONESHOT_MESSAGE` in the group’s immutable metadata, and MUST NOT list or stream that group to an app. | An app shown a one-shot group shows its user an empty conversation with a stranger’s name on it. | | FORK-053 | Check the requester | When a client receives a `ReaddRequest`, it MUST discard it unless its consent state for `group_id` is allowed and the adder installation key of the Welcome that carried it (JOIN-025) is the `signature_key` of a leaf node in its ratchet tree for that group. | A request from a non-member accepted as a readd is an add that bypasses the group’s permissions. | ## 7. Responding to a readd request A readder acts only from a state it can vouch for. It processes the group’s message topic to the end first, then checks that it still consents, that its own state is active, that it is a permitted readder, and that it is not itself forked. A readder whose fork state is `unknown` waits: readding from an unverified state can readd the requester into a fork. A readder whose fork state is `forked` never acts. A readder that meets every condition acts; a request is not a suggestion. The repair is one commit that removes the requester’s leaf node and adds the same installation back with the key package the backend serves for it, and the Welcome that commit produces. The requester processes the removal, becomes inactive, and accepts the Welcome under JOIN-042, keeping its messages under JOIN-044. Clients older than the version FORK-063 names do not accept a Welcome for a group they already hold, so the readder raises the group’s minimum protocol version first. [META section 2](/specs/meta-group-metadata/#2-well-known-components) owns that component; GMOD-025 owns the hold below the minimum, and GMOD-052 owns the readd exception for super admins and DM members. An installation the readder cannot add back is left in place: a readd that only removes puts a member out of the group with no Welcome and no notice. After a readd commit, whoever published it, the readder records the commit’s sequence id against each readded installation, so a request carrying a lower `latest_commit_sequence_id` is one already answered. A request for a group the readder no longer consents to, is no longer active in, or is no longer a permitted readder of is dropped. | ID | Title | Requirement | Why | | -------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | FORK-080 | Respond to a position the readder holds | When a client holds a readd request that passed FORK-053 and, after it has processed every envelope on the group’s message topic with a sequence id not greater than the highest the backend reported for that topic (API-244), its consent state for the group is allowed, its MLS state for the group is active, its inbox is a permitted readder, its fork state for the group is `not forked`, and the request’s `latest_commit_sequence_id` is not greater than the sequence id of the last envelope it has processed on that topic, the client MUST publish a readd commit for the requester under FORK-062. While its fork state for the group is `unknown`, or the request’s `latest_commit_sequence_id` is greater than that sequence id, it MUST keep the request for a later attempt. | A readder that is forked, or has not applied the latest commits, readds the requester into a state the group does not hold, and one that never acts leaves the requester forked with no signal. A position beyond every envelope the readder has processed is never answered under FORK-064, so answering it would publish a readd commit at every attempt, and dropping it would strand a requester that is only ahead, because FORK-051 forbids a second request. | | FORK-061 | Readd only a current member | When the client builds a readd commit, it MUST readd only an installation whose installation key is the `signature_key` of a leaf node in its ratchet tree at that moment, and MUST drop the request of any other installation. | A member removed between request and response would be added back by a commit nobody authorised. | | FORK-062 | The readd commit | When the client readds an installation, it MUST do so in one commit that removes that installation’s leaf node and adds the same installation with the key package the backend serves for it under JOIN section 1, and MUST send that installation the Welcome derived from that commit. When no key package for the installation passes JOIN-007, JOIN-008 and JOIN-082, the client MUST NOT remove it, and MUST NOT start another readd of that installation until its scheduled membership refresh interval has passed. A readd attempt restarted by a concurrent commit MAY fetch that key package once more. | Two commits leave a window in which the requester is out of the group, and a removal without an add puts a member out with no Welcome. The request stays until a readd commit answers it, so a readder that fetches at every attempt repeats a failing fetch for as long as the request stands. | | FORK-063 | Version floor for a readd | Before the client publishes a readd commit for a group whose minimum protocol version component is absent or, compared under CONF-050, less than 1.6.0, it MUST set that component to 1.6.0. | A member below that version applies the removal and then rejects the Welcome, and is left out of the group. | | FORK-064 | Answer each request once | The client MUST NOT publish a readd commit for a request whose `latest_commit_sequence_id` is less than the commit sequence id of a readd commit for the same installation in the same group that it has already applied, whichever readder published it. | A second readd for the same fork removes a member the first one repaired. | ## 8. Recovery policy and what an app can read Requests are sent only where an app has asked for them. The policy is set when the client is created and has three values: none, a list of group ids, or all conversations. The default is none. An app can also switch off responses, for the case where a readd commit is itself doing harm. Neither switch affects publishing or reading the log, which CONF-045 alone controls. An app can read each conversation’s fork state, and its local and accepted remote entries, so that it can explain a conversation that has stopped and decide whether to enable requests for it. | ID | Title | Requirement | Why | | -------- | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | | FORK-070 | The recovery policy | An SDK MUST let an app set, when it creates a client, a recovery policy of none, a list of group ids, or all, and let it disable readd responses, and MUST apply none and responses enabled when the app sets neither. | An app that cannot scope requests cannot roll recovery out, and one that cannot stop responses cannot stop a readd loop. | | FORK-071 | Responses can be disabled | While the app has disabled readd responses, the client MUST NOT publish a readd commit. | | | FORK-072 | Apps read the fork state | An SDK MUST expose for each conversation its fork state, as one of `forked`, `not forked`, and `unknown`, and expose its local entries and accepted remote entries. | | ## Known limitations The legacy reader epoch floor deliberately omits otherwise valid older signed history. It can also delay current fork detection: a reader at epoch E discards evidence from a current publisher whose divergent branch is still at E−1 until a publisher entry reaches E. An inactive legacy reader also omits locally comparable evidence from its last secret-bearing epoch. Initializing and enforcing the floor preserves prior accepted entries and sticky fork state. A subsequent validated Welcome resets the floor to zero; its effect on fork state remains governed by FORK-041. This is a loss of comparison completeness, not reconstruction of missing earlier publisher boundaries. A conservative legacy recovery boundary is not a publisher boundary under FORK-089. If publisher A has already published C1/C2, publisher B recovers at C5 and omits uncertain C3/C4, and A remains a current publisher, a reader that accepted A:C2 rejects B:C5 under FORK-083 until a current publisher supplies the missing chain or a real publisher boundary permits a restart. A member whose epoch secrets have diverged cannot decrypt the readd commit. It stays active in its own view, so JOIN-092 holds the repair Welcome and JOIN-042 never lets it replace the state. The readd path repairs a member that can still process its removal. A rule that lets a Welcome from a permitted readder replace an active group whose fork state is `forked` would repair the rest; no spec states one, and JOIN is not amended here. The commit-log topic is readable by anyone who knows its commit-log id. Its entries are encrypted, so such a reader learns how many entries the publishers write, when, and their lengths. Each entry names and is signed by its own publisher, so each publisher writes a different entry for the same commit, and such a reader can count how many publishers wrote an entry for each commit, though not which ones. Lengths show the rough size of the sequence id and the epoch number, and whether the result is unknown. Each entry follows a commit on the group’s message topic, where a commit is visible as one, so an observer who can read both topics can match them by timing; the operator can do this for every conversation. A publisher can publish a false entry, and a member that accepts it before the true one reports `forked` at that commit. A publisher already holds the authority to remove and readd members (PERM-001, FORK-062), so this spec adds no check against it. A member judges an author by its own ratchet tree when it evaluates the entry (FORK-087), so an installation whose role was removed by a commit the member has not yet processed still counts as a publisher to that member, and after a publisher loses its role the next publisher’s entry starts the chain even if that publisher disagrees with the last accepted entry. A publisher boundary also permits that disagreement when the last accepted entry is before the boundary and the candidate is at or after it. Any installation that holds the root can publish an entry whose `commit_sequence_id` is below its own sequence id but names no envelope on the group’s message topic. A member whose state is active evaluates nothing after that entry until it processes a later envelope on the group’s message topic (FORK-087), so such an entry delays fork detection until the group’s next envelope. In a DM both members publish, and a reader keeps the first entry it reads for each commit (FORK-083). After a fork, the member that reports `forked`, and so is readded onto the other member’s state, is the one whose entry the backend stored second, not necessarily the one whose state its other installations share. The requester records each readd attempt before sending and retries definite non-publication failures after any rate-limit delay. If publication succeeds or its outcome is unknown, it waits for a Welcome and does not resend; an interrupted attempt can therefore leave it waiting even when no request reached a readder. If every readder drops the request, or every readder stays `unknown`, the requester waits for a Welcome that does not come. If an earlier attempt inside a retried publish has an unknown outcome and a later attempt is rate-limited, clearing the request mark can permit one duplicate readd request. A conversation whose log FORK-030 does not read, because its consent state is not allowed, keeps the fork state last computed for it until its consent state becomes allowed; one that was never allowed reports `unknown`. Its log is unread, so there are no new remote entries to compare, and checking every such conversation on every pass is work that any sender of unsolicited conversations can multiply. Only permitted readders readd. A group whose super admins are all offline, all forked, or all below the version FORK-063 names cannot recover. # Glossary The actors and shared terms every spec uses. A spec’s own Terms section defines only terms local to that spec. Add an actor here, not in a spec (SPEC-038). This file names things; it does not constrain them. Under SPEC-072 every obligation belongs to a requirement in the spec that owns the capability, so an entry here says what a term refers to and points at the spec that states its rules. A property worth enforcing, such as how sequence ids are ordered or how a message hash is computed, is a requirement there and not a sentence here. ## Actors | Actor | Meaning | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | The backend | The self-hosted XMTP server: the gRPC services in the `xmtp.backend.v1` package and the process that serves them. | | The client | libxmtp: the Rust library that holds keys, MLS state, and the local database, on native and wasm targets. | | An SDK | A language binding on top of the client: Kotlin, Swift, or TypeScript. Specs describe SDK behaviour abstractly, not by method name. | | An app | The developer’s program that uses an SDK. | | An operator | The party that deploys and configures a backend. | | A member | An inbox that belongs to a group. “Another member” is a member other than the one whose client is acting. | | A peer installation | Another installation of the same inbox as the acting client. | | A sender | The installation that published an envelope. | | A recipient | An installation the backend delivers an envelope or a push notification to. | | The storage target | The object storage an operator configures for remote attachments. It accepts the upload requests the backend signs and serves the stored ciphertext at its download URLs (ATCH). | | A validator | Whichever party checks a payload, when the obligation is the same for the backend and the client. Use a named actor when only one of them is bound. | ## Terms | Term | Meaning | | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Inbox | The identity a user acts as, named by an inbox id. Derivation and length are stated by `IDENT`. | | Installation | One client instance with its own key pair, named by an installation key. An inbox has many. Stated by `IDENT`. | | Identifier | An external account bound to an inbox: an Ethereum address, a smart contract wallet, or a passkey. | | Envelope | One unit of client data the backend stores: a group message, a Welcome, a key package, an identity update, or a commit-log entry. | | Topic | The routing key of an envelope. Its layout is stated by `TOPIC`. | | Sequence id | The integer the backend assigns to a stored envelope. Its range, ordering, and uniqueness are stated by `API`. | | Cursor | A client’s position on one topic. Its meaning and bounds are stated by `API`. | | Message hash | The digest that identifies a stored envelope. Its algorithm and role in idempotency are stated by `API`. | | Group | An MLS group: a conversation named by a group id. A DM, a sync group, and a one-shot group are groups with a conversation type. | | Group root | The 32-byte secret a group’s creator draws, from which the group id and each key in the group key table are derived. It is not the root key of `PUSH`, from which group HMAC keys derive. Stated by the `GMOD` spec. | | DM | A group between exactly two inboxes with the fixed DM policy. Owned by the `DMS` spec. | | Epoch | The MLS epoch of a group. Every commit advances it. | | Commit | An MLS message that changes a group’s state and advances its epoch. | | Proposal | An MLS message that proposes a change for a later commit. | | Welcome | The MLS message that adds an installation to a group, inline or through a welcome pointer. | | Key package | An installation’s published MLS credential and keys that let another member add it to a group. | | Identity update | A signed change to an inbox’s association log. Owned by the `IDENT` spec. | | Handle | A public name, such as `nick` or `nick#2341`, that an inbox claims with a `ClaimHandle` action in its association log. Its grammar and the claim rules are stated by `IDENT` section 10. | | Name part | The text of a handle before its `#`, or the whole handle when it has no `#`. | | Display handle | The handle an inbox is shown by: the last of the handles in its association state (IDENT-082). An inbox that has claimed no handle has none. | | Commit-log entry | A record of a commit that a client publishes for fork detection: a `PlaintextCommitLogEntry`, which travels encrypted and signed in a `SealedCommitLogEntry`. Owned by the `FORK` spec. | | Commit-log id | The 32-byte public key of a group’s commit-log signing key, which names the group’s commit-log topic. Stated by the `GMOD` spec. | | Consent | An inbox’s or conversation’s state of allowed, denied, or unknown. Owned by the `CONS` spec. | | Content type | The typed encoding of a message payload. Owned by the `CTYPE` spec. | | Remote attachment | The description of a file a message carries by reference: the URL of an encrypted object, with the key material and digest to fetch and decrypt it. Its encoding is owned by `CTYPE`; its storage, upload, and download by `ATCH`. | # Modifying groups How a group changes after it exists: what a change is made of, who may make one, what a receiving client checks before it applies one, and what the sender does between building a commit and knowing that the group accepted it. Every member validates every commit against state it already holds and against identity state it resolves itself, so a client that accepts a commit the others reject, or rejects one they accept, forks the group. A change is an MLS commit over proposals. MLS Add, Remove, and Update proposals change the ratchet tree. XMTP group settings and membership records live in the app-data dictionary and change through `AppDataUpdate` proposals. The sender does not trust its own commit: it publishes the commit, reads it back from the group’s message topic in the order the backend fixed, and validates it as it would a commit from anyone else. Only then does it apply the commit and send Welcomes to the installations it added. ```mermaid flowchart LR A[App operation] --> B[Build proposals and a commit
on the current epoch] B --> P[Publish in one request,
proposals first] P --> R[Read back from the
group's message topic] R --> V{Validate as any
received commit} V -->|passes| M[Apply, then publish Welcomes
anchored at the commit] V -->|lost the epoch race| B V -->|rejected| F[Fail the operation] ``` ## Scope In scope: the proposal types and senders a client accepts; the membership component and the rule for writing it; how a commit’s leaf changes are checked against identity state; how a change is published, read back, and applied; the order and outcome of the checks on a received commit; commit validation against the protocol-version floor; committing another member’s proposals; keeping installations current; leaving a group; and group id generation, the group root, and the keys derived from it. Out of scope: which member may make a given change (`PERM`), component identifiers, encodings, byte limits, and update ordering (`META`), joining and what a Welcome carries (`JOIN`), the association log and exact association state (IDENT-070 and IDENT-071), fork detection, the commit log’s use of those keys, and re-add requests (`FORK`), ordered processing and positions (`PROC`), application-message publication (`SEND`), leave-request encoding (CTYPE-014), and consent, which a rejoin does not change (CONS-058). | Related | Relation | | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | | `PERM` | Owns whether a proposer may make a change. GMOD-019 says when it is asked; PERM-009 says whom it judges. | | `JOIN` | Owns Welcome validation and key-package checks. GMOD-009 supplies the sender accounting that JOIN-053 relies on. | | `META` | Owns all component identifiers and encodings, except the `GroupMembershipEntry` payload below. META-064 owns update ordering; META-010 owns byte limits. | | `PROC` | PROC-011 and PROC-012 own terminal advancement and holding. This spec supplies the commit-specific checks. | | `FORK` | Owns re-add requests. GMOD-052 is the validation exception they rely on. | | `EVENT` | EVENT-001 reports applied membership and metadata changes, removal, and a group pause. | ## Terms | Term | Meaning | | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Proposer | The member whose leaf node signed a proposal. | | Committer | The member whose leaf node signed a commit. | | Membership component | The component of the app-data dictionary that records the group’s inboxes, stated in section 2. | | Membership entry | One inbox’s value in the membership component: a `GroupMembershipEntry`. | | Referenced identity state | The association state of an inbox at the `sequence_id` its membership entry names after the commit. Owned by IDENT-070 and IDENT-071. | | Previous identity state | The association state of an inbox at the `sequence_id` its entry named before the commit, or no state when the inbox was not a member or its entry named 0. | | Expected additions | For every inbox whose entry the commit adds or changes: the installation keys the referenced identity state associates with it and the previous identity state does not. | | Expected removals | The installation keys the previous identity state associates with an inbox and the referenced identity state does not, plus every installation key the previous identity state associates with an inbox the commit removes. | | Stale leaf | A leaf node before the commit whose credential names an inbox that the commit removes from `GROUP_MEMBERSHIP`, or names an inbox whose entry the commit adds, or whose entry’s sequence id the commit raises, when that inbox’s referenced identity state does not associate the leaf’s `signature_key`. | | Failed installation | An installation key listed in a membership entry’s `failed_installations` after the commit. | | Floor | The minimum client version a group requires: the minimum protocol version component of its dictionary, a semantic version string. | | Read-back | The sender’s receipt of its own commit from the group’s message topic, at the sequence id the backend assigned. | | Terminal rejection | A refusal recorded under PROC-011. A held envelope remains pending under PROC-012. | ## 1. Proposals and commits MLS defines the proposal types a commit can carry ([RFC 9420 §12.1](https://www.rfc-editor.org/rfc/rfc9420.html#section-12.1)), and the MLS extensions draft adds `AppDataUpdate` ([draft-ietf-mls-extensions-08 §4.7](https://www.ietf.org/archive/id/draft-ietf-mls-extensions-08.html#section-4.7)), which writes one component of the dictionary. XMTP uses four of them. `GroupContextExtensions` is not one: the dictionary is the only group context extension a commit may change, and it changes through `AppDataUpdate`. Pre-shared keys, re-initialisation, external joins, and self-removal are not used. A proposal from anyone who is not a member, an external sender or a new member, is refused. | Proposal type | Use | | ----------------- | ------------------------------------------------------------------------ | | `add` | Adds an installation’s leaf node, from its key package (JOIN section 1). | | `remove` | Removes a leaf node. | | `update` | Replaces the proposer’s own leaf node. | | `app_data_update` | Writes one component of the dictionary. | A group is named by its MLS `group_id`, which never changes. TOPIC-001 derives the group’s message topic from it. A group’s id is the Ed25519 public key of its group signing key. That key is derived from a 32-byte group root, which the creator draws. The root reaches every installation a commit adds inside the Welcome’s group context (META section 4). The backend admits a publish to the group’s message topic only under a signature by that key (API-230, API-300), so only an installation that holds the root can publish there. A group whose id is 16 bytes is a legacy group, known only from imported archives: its id is random, no installation holds a key for it, and no topic carries it (TOPIC-002). Each key in the group key table below is derived from the root, one key per use. Each is HKDF-Expand(HKDF-Extract(salt, root), info, 32) under [RFC 5869](https://www.rfc-editor.org/rfc/rfc5869) with SHA-256, where salt is the UTF-8 bytes `xmtp group root`. The group key table: | Key | `info` (UTF-8) | Use | | ------------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Group signing key | `xmtp group signing key` | Ed25519 private key ([RFC 8032 §5.1.5](https://www.rfc-editor.org/rfc/rfc8032#section-5.1.5)); its public key is the group id; signs `GroupMessageTBS` (API section 3.1) | | Commit-log signing key | `xmtp commit log signing key` | Ed25519 private key; its public key is the commit-log id; signs `CommitLogEntryTBS` (API section 3.1) | | Commit-log encryption key | `xmtp commit log encryption key` | ChaCha20-Poly1305 key for commit-log entries (FORK-074) | | Commit-log nonce key | `xmtp commit log nonce key` | HMAC-SHA256 key that derives commit-log nonces (FORK-074) | The MLS validation of a proposal and a commit under [RFC 9420 §12.2](https://www.rfc-editor.org/rfc/rfc9420.html#section-12.2) and [§12.4.2](https://www.rfc-editor.org/rfc/rfc9420.html#section-12.4.2) is not restated here; the rules below are what XMTP adds. A commit references proposals that the group’s members already hold, so the sender publishes the proposals it created and the commit that references them in one publish request, proposals first: a commit that arrives without its proposals is rejected by every member. | ID | Title | Requirement | Why | | -------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | GMOD-002 | Only members propose | When a proposal’s or a commit’s sender is not a `member` sender ([RFC 9420 §6.1](https://www.rfc-editor.org/rfc/rfc9420.html#section-6.1)) whose leaf node is in the group, the client MUST record a terminal rejection for it. | | | GMOD-003 | An update keeps its identity and key | When a standalone `update` proposal’s credential names an inbox other than the proposer’s, the client MUST record a terminal rejection for it. When a commit carries an `update` proposal whose leaf’s `signature_key` differs from the `signature_key` of the leaf it replaces, the client MUST record a terminal rejection for the commit. | A member could otherwise place its leaf under another member’s inbox. GMOD-046 compares `signature_key`s, so an update that copies a sibling leaf’s key would let a commit remove one of the two leaves and keep the other after that key is revoked. | | GMOD-004 | Proposals travel with their commit | When a client publishes a commit that references proposals it created, it MUST publish those proposals and the commit in one publish request, the proposals first in the order it created them. | | | GMOD-059 | Only four proposal types | When a standalone proposal or a proposal inside a commit is not `add`, `update`, `remove`, or `app_data_update`, and the group’s committed floor does not exceed the client’s version, the client MUST record a terminal rejection for that proposal or commit. | A held proposal stops every later message and commit for every member, including the removal of its sender. | | GMOD-040 | The group id is a public key | When a client creates a group of any conversation type, other than a restored placeholder under ARCH-015, it MUST draw a 32-byte group root from a cryptographically secure random source for that group alone. It MUST set the MLS `group_id` to the 32-byte public key of the group signing key derived from that root under GMOD-041. | A root that is predictable or shared gives the publish key of a group to an installation the group never added. | | GMOD-041 | Keys derive from the root | The client MUST derive each key in the group key table from the group root with the salt and `info` the table gives, and MUST use each derived key only for the use the table names. | Installations that derive differently compute different topics and signatures, and a key used for two purposes lets a signature for one be presented as the other. | | GMOD-042 | The root stays in the group | A client MUST NOT write a group root, a private or symmetric key in the group key table, or a `GroupInfo` whose group context holds a root, to any destination other than its own client database and a Welcome or welcome pointee for an installation that a commit adds. | Whoever obtains the root can publish to the group’s topics and find its commit-log topic for as long as the group exists, because the root never changes. | GMOD-059 applies after MLS validation has accepted the message; earlier MLS failures follow PROC-011 and PROC-012. A rejected proposal is not retained, so a commit that references it fails for a missing proposal. A release that accepts another proposal type raises the floor first under PERM-023, so a client that rejects that type pauses under GMOD-025 before it sees one. ### 1.1 Proposal-list validity The proposal-list checks of [draft-ietf-mls-extensions-08 §4.7](https://www.ietf.org/archive/id/draft-ietf-mls-extensions-08.html#section-4.7) apply without a `GroupContextExtensions` proposal. After these checks, the client uses META-064 for both validation and application of app-data updates. | ID | Title | Requirement | Why | | -------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | | GMOD-030 | Reject conflicting component operations | When a commit carries `AppDataUpdate` proposals, the client MUST reject an invalid proposal list under draft-ietf-mls-extensions-08 §4.7, including an Update and a Remove, or more than one Remove, for the same component id, whether or not the commit contains a `GroupContextExtensions` proposal. | Conflicting component operations can make clients compute different state for one epoch. | ### 1.2 Selecting pending membership proposals An accepted Add can outlive the commit that first referenced it. Acceptance of that proposal does not prove that its installation or key package is still eligible for a later commit. The sender resolves the intended membership and fetches current key packages before selecting pending membership proposals. It compares complete key packages, not only installation signature keys. A fetch failure is not evidence that an accepted proposal is obsolete. The sender reuses a current eligible proposal with its original proposer. A replacement Add uses the sender’s own authority. If it cannot replace an obsolete Add, it can omit the Add and the whole signed membership update that depends on it. It then recomputes the dependent Adds and Removes. It does not edit another proposer’s signed update. An empty commit can advance the epoch when only obsolete work remains. Omitted proposals then expire under the MLS epoch rules; their authors can propose them again. The sender also selects compatible whole membership updates before applying their dictionary changes. For example, two proposals can each insert the same new inbox, but a commit cannot apply both inserts. Every commit builder uses the selected dictionary changes and retains Welcomes for the selected Adds. This includes metadata, permission, and automatic key-update commits. These are sender selection rules. Receivers continue to validate the published commit against its stated identity references. They do not fetch the latest key package to decide whether to accept a commit. | ID | Title | Requirement | Why | | -------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | | GMOD-038 | Select one consistent proposal set | When preparing a commit from pending membership proposals, the sender MUST select a set that satisfies the resolved membership, key-package validation, and proposer authority rules. It MUST compute dictionary updates and the MLS commit from that same set, MUST preserve accepted proposal references until normal commit resolution, and MUST NOT report an omitted app-requested change as successful. | An obsolete Add can block publication; inconsistent selection can make members disagree. | ### 1.3 Omitting uncommittable pending proposals A receiver checks a standalone proposal against the committed group state alone, so every member accepts or rejects it alike. Proposals accepted one at a time can still form a commit that every member rejects: two inserts of one key, an Update and a Remove of one component, two super-admin removals that leave none, or a Delete that the membership after the commit forbids. The sender of a commit of pending proposals therefore applies the receivers’ commit validation first. It walks the pending proposals in order and keeps each one that receivers would accept after the ones kept before it. It judges membership-dependent rules with the membership the kept proposals leave, and repeats the walk until that membership stops changing. It does not look ahead, so a later proposal that would make an earlier one valid may itself be omitted. Omitted proposals expire under the MLS epoch rules, as in section 1.2. No conforming client proposes a leaf `Update`, and the sender omits every pending `Update`, so its commit never carries one. Receivers check an `Update`’s credential on receipt and its `signature_key` in a commit (GMOD-003). The sender’s own requested change is not filtered. An author publishes its proposals with the commit that carries them in one request (API-220), so when another member’s commit omits them, the author’s commit goes stale and is rebuilt under GMOD-036. | ID | Title | Requirement | Why | | -------- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | GMOD-047 | Omit uncommittable pending proposals | When preparing a commit from pending proposals, the sender MUST count each proposal reference once, and with N the smaller of 1,000 and `max_envelope_bytes` divided by 136 and rounded down, MUST omit every pending `GROUP_MEMBERSHIP` `AppDataUpdate` proposal after the oldest N, not counting and never omitting the intent’s own, and every other pending `AppDataUpdate` proposal after the oldest N. It MUST omit each remaining pending proposal that receivers’ validation of the commit would reject after the proposals kept before it, judged with the membership the kept proposals leave, MUST omit a membership delta that adds an inbox with no Add of that inbox, or removes an inbox that a leaf node’s credential names before the commit with no Remove of that inbox, among the carried proposals, and MUST NOT carry a leaf `Update` proposal. When the intent’s own requested change conflicts with the kept proposals, the sender MUST fail that intent and MUST NOT omit a kept proposal because of the conflict. | One member’s accepted proposal would otherwise fail every commit of pending proposals, so no member could send or change the group. A reference costs about 34 bytes, so a flood of accepted proposals would otherwise make every commit too large to publish under the deployment’s limit, and only a published commit discards them. | | GMOD-045 | Store a repeated proposal once | When a client accepts a standalone proposal whose reference is already pending, it MUST NOT store a second copy. | A commit covers a reference once. A second copy counts an update twice, and removing one copy deletes the stored proposal both share. | ## 2. The membership component The membership component names every inbox that is a member and, for each, the identity state its installations are checked against and the installations the group could not add. It is what a joiner validates a Welcome’s ratchet tree against (JOIN section 8) and what every member validates a commit’s leaf changes against (section 3). The component is a map from inbox id to an encoded `GroupMembershipEntry`; META-010 and META-011 own the map and inbox-id encodings, and META section 2 assigns the component id. ```proto message GroupMembershipEntry { message V1 { uint64 sequence_id = 1; repeated bytes failed_installations = 2; } oneof version { V1 v1 = 1; } } ``` A `sequence_id` is a promise the sender makes: it resolved that inbox’s identity updates through that sequence id and built the commit from the state it found. It is 0 only for the creator’s own entry at creation, before any identity reference is needed. Every sequence id a commit writes is less than the sequence id the commit itself receives, because the identity update was published first and the backend assigns sequence ids in publication order, so a reference at or after the commit can never resolve. JOIN-093 owns partial success when some key packages are invalid. GMOD-009 accounts for the installations in each inbox, including an installation for which the backend returns no key package. JOIN section 8 owns validation of the membership asserted by a Welcome. A failed installation is one the group holds no leaf for. A membership change can be built when an installation’s key package cannot be fetched and published after that installation has a leaf: a later fetch succeeds and the commit adds it, or another member’s commit added it first. The installation is then not failed. A listed key never exempts a leaf from the removal check of section 3 (GMOD-046), but under GMOD-052 it lets a super admin remove that leaf without a re-add. | ID | Title | Requirement | Why | | -------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | GMOD-005 | Membership entry format | The client MUST encode each member’s value in `GROUP_MEMBERSHIP` as the `GroupMembershipEntry` defined above, with `v1` set and exactly one entry per member inbox. | | | GMOD-006 | An added inbox references resolved state | When a commit adds an inbox, the sender MUST set its entry’s `sequence_id` to the sequence id of the latest identity update it resolved for that inbox, greater than 0. | | | GMOD-007 | References precede the commit | If any entry’s `sequence_id` is not less than the commit’s own sequence id, or an entry the commit adds has a `sequence_id` of 0, then the client MUST record a terminal rejection for the commit. | A reference at or after the commit can never be resolved, and 0 asserts nothing. | | GMOD-008 | Sequence ids never decrease | If an inbox’s entry after the commit has a `sequence_id` less than before it, then the client MUST record a terminal rejection for the commit. | A lowered reference would let a revoked installation back in. | | GMOD-009 | Every installation is accounted for | When a sender publishes a commit that adds an inbox or changes its `sequence_id`, the sender MUST ensure that every installation key in that inbox’s referenced identity state is either the `signature_key` of a leaf after the commit or in that inbox’s `failed_installations`. | An omitted installation loses access, and a later joiner rejects the incomplete membership. | | GMOD-044 | A failed installation has no leaf | When a client publishes a commit for its own membership update, which adds, removes, or refreshes inboxes, it MUST NOT list in any membership entry that update writes the `signature_key` of a leaf that the ratchet tree holds after the commit. | A listed key that has a leaf lets a super admin’s commit remove that leaf under GMOD-052 without a re-add or an identity change. | | GMOD-049 | A failure belongs to its inbox | If a commit leaves an inbox’s entry listing in `failed_installations` a key that entry did not list before the commit, and that key is neither associated with the inbox by its referenced identity state nor the `signature_key` of a leaf node before the commit whose credential names the inbox, then the client MUST record a terminal rejection for the commit. | A failure filed under another inbox does not account for that inbox’s missing installation under JOIN-053, so joiners reject a Welcome for a membership that members accepted. | | GMOD-057 | A commit keeps installations accounted for | When a commit leaves an installation key unaccounted for an inbox that is a member after the commit and whose entry (`sequence_id` or `failed_installations`) or set of leaf `signature_key`s, over leaf nodes whose credential names it, the commit changes, and the key was not unaccounted for that inbox before the commit, the client MUST record a terminal rejection for the commit. A key is unaccounted for an inbox when the inbox’s referenced identity state in `GROUP_MEMBERSHIP` associates the key with the inbox, no leaf node has it as its `signature_key`, and the inbox’s entry `failed_installations` does not list it. Before the commit, an inbox that was not a member or whose entry was 0 has no unaccounted key. | GMOD-009 binds only the sender. Without a receiver check, one member’s commit can leave an installation unaccounted, and every later joiner then rejects the Welcome under JOIN-053 while existing members see nothing wrong. | ## 3. Leaf changes against identity A commit’s Add and Remove proposals are not taken at their word. The membership component says which identity state each inbox is at, and the difference between the previous and the referenced identity state says which installations may be added and which must be removed. A leaf added outside the expected additions is a leaf under an identity that never authorised it; a removal missing from the expected removals leaves a revoked installation reading the group. The expected additions are one set across all inboxes, so each new leaf must also name the inbox that owns its key. This includes the committer’s leaf in the update path, because MLS lets that leaf carry a new credential; that leaf must also keep the committer’s inbox (GMOD-043). A key that has no leaf before the commit is exempt from the removal check, because the commit has nothing to remove; a key listed as failed is not exempt when it has a leaf. The difference between two identity states misses two kinds of leaf. A leaf that an earlier commit kept past its revocation is in neither state, and an entry raised from 0 has no previous state to compare with. A commit that raises or removes an inbox therefore also removes that inbox’s stale leaves, so the inbox’s next identity update repairs a leaf left behind. The checks read identity state the client resolves itself. When it does not hold an inbox’s association state at the `sequence_id` an entry names, it fetches that inbox’s identity updates through that sequence id before it decides, so that two members with different caches reach the same answer. A reference the backend holds nothing for can never resolve and is rejected. The creator’s unchanged zero-sequence entry is a creation placeholder: only a key and inbox already paired in an authenticated committed leaf can use it, without resolving sequence 0. A new key still needs a nonzero identity reference. Two exceptions exist for recovery. A super admin, or either member of a DM, may remove and re-add an installation in one commit, replacing its leaf without an identity change. A super admin may also remove a leaf whose installation is listed as failed. `FORK` owns when that is done; this section owns that every member accepts it. An inbox may also add back its own installation that has no leaf, outside the expected additions, because no later identity change would make that key expected again (GMOD-055); GMOD-012 still binds the key to the inbox’s referenced identity state. | ID | Title | Requirement | Why | | -------- | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | GMOD-010 | Only expected leaves are added | If a commit adds a leaf node whose `signature_key` is not in the expected additions, is not the `signature_key` of a leaf node already in the group, and was not proposed by a member whose inbox is the inbox the leaf’s credential names, then the client MUST record a terminal rejection for the commit. | This is the check that stops a member placing a leaf under an identity that never authorised it. An inbox may add back its own installation that holds no leaf, because no later identity change makes that key an expected addition again; GMOD-012 still requires the key in the inbox’s referenced identity state. | | GMOD-046 | Expected leaves are removed | If, after the GMOD-052 adjustments, the set of `signature_key`s of the leaf nodes a commit removes is not equal to the set of `signature_key`s of leaf nodes before the commit that are expected removals or stale leaves, then the client MUST record a terminal rejection for the commit. | A removal the identity state does not call for evicts a member. A revoked installation’s leaf that a commit keeps, because the commit omits its Remove or an earlier commit left the leaf behind, keeps reading the group. | | GMOD-012 | Signing keys belong to their inboxes | When the client validates a commit, it MUST record a terminal rejection for the commit unless, for the committer’s leaf, the leaf in the commit’s update path, and the leaf of every `add` and `update` proposal, the leaf’s `signature_key` belongs to the credential’s inbox in its referenced identity state, or that inbox’s entry is 0 both before and after the commit and the same key and inbox pair exists in a committed leaf. | GMOD-010 compares additions with the expected additions of all inboxes together, and MLS lets an update path change the leaf’s credential. Without this check, a member could place a leaf it signs under another member’s inbox and then send messages and proposals as that member. | | GMOD-043 | An update path keeps its identity | When the leaf in a commit’s update path names an inbox other than the committer’s, the client MUST record a terminal rejection for the commit. | The update path replaces the committer’s own leaf, as an `update` proposal does under GMOD-003. A key that two inboxes both hold would otherwise let its holder move its leaf from one inbox to the other. | | GMOD-013 | Resolve before deciding | When validation needs an inbox’s association state at a nonzero `sequence_id`, the client MUST resolve that exact state under IDENT-070 and IDENT-071 before it decides on the commit. | Deciding on cached state makes members disagree about the same commit. | | GMOD-014 | Unresolvable references are terminal | When a client has fetched an inbox’s identity updates and the backend holds no update at the `sequence_id` an entry names, the client MUST record a terminal rejection for the commit. | A reference to a state never published can never become valid. | | GMOD-052 | Permitted readders may re-add | When the committer is a super admin, or the group is a DM whose `DM_MEMBERS` names the committer’s inbox, the client MUST remove keys that the commit both adds and removes from its actual addition and removal sets before the GMOD-010 and GMOD-046 comparisons. When the committer is a super admin, the client MUST then remove keys present in both the remaining actual removals and failed installations from both of those sets. | Without the DM case, every member rejects the readd commit that FORK-062 asks of a DM’s permitted readder, so a forked DM member is never repaired. The failed-key case stays with super admins: in a DM it would let one member remove the other’s installation with no Welcome. | ## 4. Publishing a change An app’s operation becomes an intent the client holds until the group accepts it. The client builds proposals and a commit on the epoch it holds, publishes them, and then waits for the read-back. The commit is not applied from the sender’s own copy: the sender processes the group’s message topic in order like every other member, meets its own commit there, and validates it under section 5. A commit that fails validation on the sender fails on every member, and the operation is reported to the app as failed. Two commits built on the same epoch race, and the backend’s order decides the winner. The loser reads its own commit back after the group’s epoch has moved past the epoch it was built on. That commit is stale: applying it would fork the sender from the members that applied the winning commit, so the sender discards it and builds the change again on the current state. SEND-014 owns when that recovery applies to an intent and when a rejection ends it instead. A commit that adds installations owes them a Welcome. The Welcome names the commit by its sequence id on the group’s message topic (JOIN section 6), so it cannot be built until the read-back, and an installation that never receives it has no way to join. Welcomes are published after the commit is applied, and the operation is not complete until the backend has accepted every one of them. A commit may reference proposals other members published. Every member keeps a received proposal only after validating it, so a proposal that one member rejects is one every member rejects, and a commit that references it fails everywhere the same way. PERM-009 judges each proposal by its proposer, so the committer needs no authority of its own over the changes it commits. A standalone proposal is judged against the committed membership, because the commit that will reference it is not yet known. A delete that is authorized only because its key leaves the membership in the same commit, such as a removed member’s profile entry under PERM-027, is therefore an inline proposal of the member-removal commit and is validated there under section 5. The sender of a member removal cleans up after the inboxes it removes, so a departed member’s name or admin role does not outlive its membership. Cleanup is a courtesy of the sender, not a condition of the commit: a remover whose policies forbid a cleanup delete still removes the member, and a receiver accepts a removal with or without it. | ID | Title | Requirement | Why | | -------- | -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | GMOD-016 | Apply only what the topic returns | A client MUST NOT apply a commit it built before it has read that commit back from the group’s message topic at the sequence id the backend assigned, and MUST NOT exempt it from any check of section 5 because it built it. | A sender that applies first and loses the race, or built a commit the others reject, is forked from the group. | | GMOD-036 | A stale commit is rebuilt | If a client reads back a commit it published and the group’s current `GroupContext.epoch` is greater than the epoch the commit was built on, then the client MUST NOT apply that commit and MUST build the change again on the current group state before it publishes again. | Applying a commit from a past epoch forks the sender from every member that applied the winning commit. | | GMOD-058 | An own commit resolves like a peer’s | When a client reads back a commit it published at the group’s current epoch and a proposal the commit includes by reference is neither pending in its proposal store nor among the proposals it durably recorded as delivered in that epoch, it MUST NOT apply its saved staged state and MUST record a terminal rejection for the commit. | A saved commit applied after the members dropped a proposal it references advances its author while every other member rejects it, and the group splits. | | GMOD-018 | Welcomes follow the commit | When a client has applied a commit it built that adds leaf nodes, it MUST publish a Welcome to every installation the commit added, with `message_cursor` equal to the commit’s sequence id, and MUST NOT publish any Welcome for that commit before the read-back. | An installation that receives no Welcome cannot join the group. | | GMOD-019 | Received proposals are validated first | When the client receives a standalone proposal, it MUST check its type and sender under section 1, the same-inbox condition for Update, the Add or Remove authority under PERM-015, and the component structure and write authority under META and PERM for `AppDataUpdate`, before retaining it as an accepted proposal. | A proposal accepted by only some members can make a later commit fork the group. | | GMOD-039 | Clean up removed inboxes | When a client builds a commit that removes an inbox from `GROUP_MEMBERSHIP`, it MUST include in that commit an inline delete of the inbox’s key from each other registered inbox-keyed map and from `ADMIN_LIST` where present, for each delete the committed policies authorize with the context of PERM-027, and MUST omit each other delete. A receiver MUST NOT reject a removal commit for omitting a cleanup delete. | A stale name or role would outlive the membership, but a forbidden cleanup must not block the removal. | | GMOD-050 | Carry identity leaf changes inline | When a client builds a commit for its own membership update, it MUST carry each Add and each Remove that update makes for a leaf whose inbox is in `GROUP_MEMBERSHIP` both before and after the commit as an inline proposal of that commit. | Receivers judge a standalone Add or Remove under PERM-003 and PERM-015 as a change to the inbox. They reject one for a super admin’s revoked installation, from a member without that policy, or in a DM, so the other members cannot stage the sender’s commit and the group forks. | | GMOD-056 | Store the first add with the group | When an app creates a group with members, the client MUST resolve every member’s identity state and key packages and check the member limit before it stores anything, and MUST store the group, its consent record under CONS-056, its `conversation.joined` event, and the intent that adds the members in one transaction. When the call’s wait for that intent ends while the intent is still pending, the client MUST return the stored group. | A failure after the group is stored and announced leaves a live group the app was told does not exist, and a repeated call creates a second group that the invitees also join. A join event delivered before the add is queued lets a message the app sends on that event publish at an epoch the members never join. | ## 5. Receiving a commit A received commit passes through the checks in this spec and in `PERM`, and is applied only when every one passes. A commit that fails leaves the group’s state and epoch unchanged. What happens next depends on why it failed. PROC-011 owns terminal rejection and advancement. PROC-012 owns holding after a storage failure or an unresolved identity dependency. The floor is different from both. A client below the group’s floor cannot be sure it can even parse what the group now carries, and a rejection it issues alone is a fork. So it pauses: it applies nothing further on that group, publishes nothing to it, and records no rejection, until its version reaches the floor and it reprocesses from where it stopped. While the committed floor is supported, a commit that raises it is validated before it can pause the client. A terminal validation failure rejects that commit; an unresolved dependency or storage failure holds it under PROC-012. A committed floor that is already unsupported pauses the client before further commit validation. Versions compare under [Semantic Versioning 2.0.0 §11](https://semver.org/spec/v2.0.0.html#spec-item-11), including its pre-release precedence, unlike the backend’s minimum under CONF-050. The floor only rises, because a lowered floor lets a paused client apply commits it cannot interpret. A new group is created with the floor of its creating release: the lowest version, including pre-releases, that implements every receive rule of that release whose acceptance differs from an earlier release (PERM-023). A commit the client applies is recorded for the app as a membership-change message whose payload is a `GroupUpdated` transcript (CTYPE-014, META-074). The transcript is derived from the validated commit: who committed it, which inboxes it added or removed, and which settings it changed. It is a record the client writes for itself, never content a member sends, so an application message that carries a transcript type is not a transcript. GMOD-054 says when such a message is not published. META-010 owns component encodings and byte limits. Standalone checks do not resolve a future commit’s identity references, compare its aggregate leaf changes, or apply its proposed floor. The client repeats authorization at commit time under PERM-009 and checks the full change here. | ID | Title | Requirement | Why | | -------- | -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | GMOD-021 | Validate, then apply | The client MUST apply a commit only after the checks in GMOD, PERM, and META have passed, with app-data validation and application in the order META-064 defines. When any check fails, it MUST leave the group state and epoch unchanged. | | | GMOD-022 | Judge before the floor pauses | When the committed floor is not greater than the client’s version and a commit would raise it above that version, the client MUST complete the other commit validation checks before pausing for that raise, and MUST terminally reject a terminal validation failure under PROC-011. | An unauthorized floor raise would otherwise pause the group. | | GMOD-025 | Pause below the floor | While the committed floor exceeds the client’s version, or a commit that passes all other validation would raise it above that version, the client MUST hold before that commit under PROC-012 and MUST NOT publish a message, proposal, or commit in the group. When its version reaches the floor, it MUST resume from the first held envelope. | Rejecting or skipping a commit that newer members accept forks the group. | | GMOD-026 | The floor only rises | If a proposal sets the floor to a version whose precedence under GMOD-027 is lower than the committed floor’s, or removes the floor while one is committed, then the client MUST record a terminal rejection for it. | Clients that order two floors differently reject different proposals, and a commit that carries one forks the group. | | GMOD-027 | Version precedence | When the client compares its version with a floor, it MUST use [Semantic Versioning 2.0.0 §11](https://semver.org/spec/v2.0.0.html#spec-item-11), including pre-release precedence; a malformed committed floor MUST NOT cause a pause. | | | GMOD-034 | Transcripts come from validated commits | When the client applies a commit, it MUST derive the membership-change message it stores for that commit from the validated commit, with the committer and the added, removed, and changed entries taken from the commit’s actor and its effect on the pre-commit state. | A transcript written from anything but the commit shows the app membership changes that did not happen. | | GMOD-054 | Transcripts are never published at any depth | When an application message’s content, or content nested in a reply at any depth, compressed or not, has type `xmtp.org/group_updated` or `xmtp.org/group_membership_change`, the client MUST NOT publish that message. When a prepared attempt for such a message is already saved under SEND-006, the client MAY publish its saved bytes under SEND-007. | A member could send a forged transcript that other apps show as a membership change, or a reply that every receiver reports as a decode failure under GMOD-053. The saved bytes of an attempt may already be on the backend, and SEND-007 does not let the client replace them. | | GMOD-053 | Application transcripts are not decoded | When the client decodes an application message whose content, or content nested in a reply at any depth, has type `xmtp.org/group_updated` or `xmtp.org/group_membership_change`, it MUST report a decode failure that preserves the message under CTYPE-008, and MUST NOT decode that content’s payload as a transcript. | A member could send a transcript that apps show as a membership change that never happened, carrying lists large enough to exhaust the recipient’s memory. | ## 6. Keeping membership current An inbox’s installations can change after it joins: a device is added or revoked through an identity update (IDENT-070), and the group’s leaf nodes no longer match. Any member repairs this. A client that syncs a group fetches the identity updates of every member on a schedule, and when an inbox’s latest sequence id is greater than its entry, publishes a commit that raises the entry and makes the expected additions and removals. The revoked installation loses the group at that commit, and the new one receives a Welcome. Which member does it first does not matter: the commits race under section 4 and the loser finds nothing left to do. A refresh is built from the membership at one moment and published later, after other commits can have landed. Its entries raise inboxes that were members when it was built. When one of those inboxes has since been removed, the refresh leaves it out, and when a later commit raised an entry past the refresh, the entry keeps the higher sequence id. Only an app’s request to add an inbox inserts one. | ID | Title | Requirement | Why | | -------- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | GMOD-029 | Members repair changed identity state | When a membership refresh for an active group that is not a sync group resolves an inbox’s identity state at a sequence id greater than its membership entry’s, the client MUST publish a membership change that raises the entry to that sequence id and makes the expected additions and removals under sections 2 and 3. SYNC-034 governs a sync group. | A new device cannot add itself, and a revoked one keeps reading until a member removes it. | | GMOD-051 | A refresh never inserts an inbox | When a client publishes a membership change that records which of its entries are refreshes under GMOD-029, it MUST NOT insert into `GROUP_MEMBERSHIP` an inbox whose entry the change records as a refresh. | A refresh built before a commit removed an inbox would undo that removal. | | GMOD-055 | An inbox retries its own missing installations | When a client’s membership refresh finds a key that its own inbox’s referenced identity state associates with that inbox and that is not the `signature_key` of any leaf node, and the group’s floor is at least the required version (PERM-023) for the own-inbox clause of GMOD-010, the client MUST fetch that key’s key package and, when the package meets the conditions JOIN-093 sets for that installation, MUST publish a commit that adds it. After a fetch for such a key fails, the client MUST NOT fetch it again for this purpose until its scheduled membership refresh interval has passed. | A key that fails once is associated in both identity states, so no later identity change makes it an expected addition. Without a retry, a member or backend that withholds one key package keeps that device out of the conversation. Only the key’s own inbox retries, so receivers can tell a retry from a forged add. | ## 7. Leaving a group A leave request is an authenticated application message in the group. CTYPE-014 owns its content type and `LeaveRequest` encoding. Its sender asks for removal of the sender’s inbox; the note carries no authority over another inbox. Sending the request does not publish a self-removal commit. The requesting inbox is pending removal until another member commits the removal. PERM-025 owns authority to act on a leave request. The removal still passes PERM-003 and PERM-015 and the membership checks here. A request can remain pending while no authorized super-admin client can publish the removal. A later rejoin leaves consent unchanged (CONS-058). | ID | Title | Requirement | Why | | -------- | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | GMOD-031 | Request a permitted leave | When an app requests leave, the client MUST reject the operation if its inbox is not a member, the group has only one member inbox, the conversation is a DM, or its inbox is a super admin. Otherwise, if its inbox has no pending leave request, it MUST send a `LeaveRequest` under CTYPE-014 without publishing a self-removal commit. | | | GMOD-032 | Authenticate the leaving inbox | When the client processes a leave request, it MUST take the inbox to remove from the authenticated MLS application-message sender and MUST NOT take it from the request payload. For a request from its own inbox, it MUST expose the group as pending removal until a commit removes that inbox. | A payload chosen by one member cannot authorize another member’s leave. | | GMOD-033 | Complete an authorized leave | When a client processes pending leave requests and has authority under PERM-025, it MUST publish a removal commit for the requesting inboxes that are still members, subject to PERM-003 and PERM-015. When it builds or rebuilds that commit, it MUST omit each inbox that a commit it applied after the inbox’s latest leave request has removed. It MUST report removal complete only after it applies a commit that removes the inbox, and MUST keep a request pending when publication or validation fails. | Publication of a request alone does not remove any installation from the ratchet tree. A removal queued before another admin removed the inbox would otherwise remove it again after a re-add. | ## Known limitations A commit accepted before a client implemented GMOD-057 can have left an installation unaccounted. GMOD-057 does not reject later commits that keep it so, and a joiner rejects the Welcome under JOIN-053 until a commit adds that installation, lists it as failed, or the inbox’s next identity change removes it. An installation key that two member inboxes hold has one leaf, whose credential names one of them. When the other inbox revokes the key, or an admin removes the other inbox, the commit removes the leaf and leaves the key unaccounted for the leaf’s inbox, so GMOD-057 rejects it. A membership refresh runs before each send, so no member can send, and a member’s pending membership delta can fail every other commit, until an admin removes the leaf’s inbox. When the leaf’s inbox revokes the key, the commit is accepted unless it also changes the other inbox’s entry. Every later joiner then rejects the Welcome under JOIN-053, until a commit adds the key or lists it as failed for the other inbox. API-305 stops a backend from admitting such a key, but a key admitted before API-305, or by a backend that does not apply it, can still do either. In a group whose floor is below the version GMOD-055 requires, a membership refresh does not retry a failed installation key that remains associated in both identity states, and its key package becoming valid does not by itself add it to the group. Only a client of the key’s own inbox retries it, so a key whose inbox has no leaf in the group stays out. Receivers do not reject a membership entry that keeps listing a key that has a leaf, and older clients wrote such entries. The listing does not exempt the leaf from removal under GMOD-046, but under GMOD-052 a super admin’s commit can remove that leaf without a re-add. A leaf that a commit accepted before GMOD-046 kept past its revocation stays until a commit raises its inbox’s entry or removes the inbox, and that commit must remove it as a stale leaf. If the inbox publishes no later identity update and stays a member, the leaf stays. GMOD-044 covers a client’s own membership updates. A commit that keeps another member’s accepted membership delta keeps it whole or omits it whole (GMOD-038), and a readd or a standalone membership proposal carries the failed lists already written, so these can keep a key with a leaf that an earlier writer listed. They do not add a leaf for a listed key: selection omits the Add of a key that a kept delta lists as failed, and a pending proposal never outlives a commit. Omitting such a delta would hold back its other changes until its author proposes again, while a revocation that a conforming client commits removes the leaf either way. A membership change stored before its refresh entries were recorded apart from its requested adds treats every entry as an add. When it publishes, it can insert an inbox that a commit removed after the change was built. A removal for leave requests stored before its leave removals were recorded removes each listed inbox, so it can remove an inbox that another admin removed and re-added after the change was built (GMOD-033). An older build that publishes a stored change after a downgrade ignores these records in the same way, as it does for the changes it builds itself. The record is not versioned to make older builds fail closed: an older build cannot decode a newer payload version, and an own change it cannot decode stops every later publication in its group. MLS discards proposals that a commit did not reference once the epoch advances. A member whose proposal was omitted from an accepted commit has to propose again if the change is still needed. A member who sends more than N accepted `AppDataUpdate` proposals of either class in every epoch, with N as in GMOD-047, makes each send of another member need its own commit. The group still makes progress. The floor pauses only the clients below it. Members at or above it continue, and the paused client’s unpublished changes are built on an epoch the group has left and are rebuilt under SEND-014 after it resumes. A membership refresh is triggered by client activity. Its interval is an implementation choice, not a deadline for removing a revoked installation or adding a new one. No bound applies while all members are offline. Clients that predate GMOD-043, the coverage of `add` and update path leaves in GMOD-012, or the `signature_key` clause of GMOD-003 apply commits that newer clients reject: a commit with an unbound leaf, or one whose `update` changes its leaf’s key. Without a version floor (PERM-023), the group forks between them. A forged commit causes either. An older client’s own refresh can also cause the first, because it adds a key package whose credential names another inbox, which JOIN-093 excludes. An older client’s commit can also cause the second: a client that predates the omission of pending `update` proposals from commits (section 1), including every `8.0.0-rc4` and earlier release, commits a member’s standalone `update` that changes its leaf’s key, which receivers accept on receipt. A group created by `8.0.0-0` or later has a floor of `8.0.0-0`, so these older clients pause in it. A group created earlier keeps its lower floor, because no client raises an existing group’s floor, and an older member of it can still fork it this way. Clients that predate GMOD-057 apply a commit that leaves an installation unaccounted, which newer clients reject. Such a commit, forged or built honestly by an older client that commits another member’s pending membership delta, forks a group whose floor is below `8.0.0-0`. Builds of `main` that report `8.0.0` but lack these checks are not paused by an `8.0.0-0` floor, and a backend minimum cannot exclude them, because CONF-050 compares major, minor and patch only, so such a build can fork a group of any floor in each of these ways. Clients that predate the own-inbox clause of GMOD-010 reject a commit in which an inbox adds back its own installation that holds no leaf, which newer clients accept. No client publishes such a commit before the group’s floor includes that clause (GMOD-055), so only a forged commit from an installation of that inbox causes this fork. Clients that predate GMOD-059 hold, with no deadline, a standalone proposal of another type and a commit that carries a `GroupContextExtensions` or `ReInit` proposal; OpenMLS rejects a member commit that carries an `ExternalInit` proposal before XMTP validation, and they already reject a commit that carries any other type. They apply nothing past a held message, so they do not fork, and after an upgrade they reject it and continue. A group with a floor of `8.0.0-0` or later pauses them under GMOD-025, except builds of `main` that report `8.0.0` but lack GMOD-059, which the floor admits. Receivers check only that a readd adds back the installation it removes, not that the added key package is the newest one that installation published. A super admin, or either member of a DM (GMOD-052), can readd an installation with a key package whose private keys it destroyed under JOIN-074; that installation processes the removal, cannot open the Welcome, and keeps a leaf it cannot use, so it is out of the conversation until it is readded again. A super admin can already remove any member; for a DM member this is a new power. A member can hold a conversation’s head for about 30 seconds per commit that names an identity sequence with no update; K such commits hold it about K x 30 seconds. These holds use the client’s 8 shared identity dependency slots, and so does a Welcome whose membership names an identity sequence with no update. Anyone who can send a Welcome can therefore occupy every slot: 8 such Welcomes every 30 seconds stop every conversation on that client whose next commit needs an identity proof the client does not hold, not only one conversation. # Identity updates An inbox is controlled by a chain of signed identity updates. Every rule here is a security boundary: a mistake lets an attacker attach their key to someone else’s inbox, or locks a user out of their own. An inbox has members: the identifiers a user is reached by, and the installation keys that sign on the user’s behalf. Membership changes only by an identity update, which every party validates for itself from the signatures it carries. The backend validates an update before it stores it and a client validates every update it reads, under the same rules, so that every party derives the same member set from the same log. One identifier, the recovery identifier, can remove members and reassign its own role; every other member can only add. An inbox can also claim handles: short public names by which other users find it. ```mermaid flowchart TD U[Identity update arrives] --> T[Build the signature text from the update's own fields] T --> V[Verify every signature against it, by kind] V --> A[Apply the actions in order to the previous state] A --> R{Every rule holds and the state's inbox id equals the update's} R -->|yes| S[New association state; record the replay keys] R -->|no| X[Reject the whole update; state unchanged] ``` ## Scope In scope: the identity update wire format and its actions, the association state and how each action changes it, the signature text and the signature kinds, which kind may sign for which member, inbox id derivation, replay protection, recovery authorization, smart contract wallet verification and chain binding, what an installation’s registration and revocation mean, how an identifier resolves to an inbox, local Ethereum signing-key export and restoration, and handles: the claim action, the handle grammar, how a claim changes the association state, and how a client checks a handle lookup answer and reports an inbox’s handles. Out of scope: how an identity update is published, stored, ordered, and read back as an envelope, the snapshot the backend validates against and what it does when that snapshot moves (API-303), duplicate publishes (API-222), the lookup RPC and its answer (API-270), the verifier RPC, the checks of a claim that only the backend applies, and the error codes (`API`); the identity topic layout (TOPIC-001); the published limits and chains, and the minimum name length of a handle (`CONF`); what a key package carries (`JOIN`); how a group’s membership follows a change of an inbox’s installations (GMOD-029); and the event that reports a change of display handle (`EVENT`). | Related | Relation | | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `CONF` | Owns the published installation ceiling a client applies (CONF-044), the chains a deployment verifies (CONF-070), the client’s chain check before it signs (CONF-046, CONF-048), and the minimum name length of a handle. | | `JOIN` | Owns the key package an installation publishes (JOIN-001) and the check of a group’s leaves against association state at a sequence id (JOIN-052, JOIN-053, JOIN-059). | | `API` | Owns the publish and query contract an identity update travels under, the sequence id it receives, the one-snapshot admission and its `ABORTED` (API-303), duplicates (API-222), the resolution RPC (API-270), the verifier RPC, the checks of a claim that only the backend applies, and the error codes. This spec owns what the validation in API-303 checks. | | `GMOD-029` | Owns how a member commits the installations an inbox gained or lost between two sequence ids. | | `EVENT` | EVENT-001 reports own installation additions, revocations, and completed registration. `EVENT` also owns the event that reports a change of display handle. | ## Terms | Term | Meaning | | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Association log | The identity updates stored for one inbox, in ascending sequence id order. | | Sequence id | The position the backend assigns to a stored identity update in its inbox’s association log, under API-286 through API-289. | | Association state | The members, the recovery identifier, the seen replay keys, the handles, and the claim count of an inbox after a prefix of its association log is applied. | | Member | An identifier or an installation key the association state holds for an inbox. | | Member kind | Ethereum, passkey, or installation. | | Recovery identifier | The identifier the association state names as permitted to revoke members and to reassign this role. Not always a member. | | Signer | The identifier or installation key a validator derives from a signature under section 4. | | Signature text | The string built from an update under section 3 that every signature in that update signs. | | Replay key | What a validator records for a signature after it is applied: the signature’s signer and the signature text it signed (IDENT-090). | | Adder | The existing member whose signature added a member. | | Chain id | The `eip155` chain of a smart contract wallet signature, as a number; absent for every other signature kind. The association state records one for each member and one for the recovery identifier. | | Handles | The handles an association state holds for its inbox, in the order IDENT-082 produces. | | Claim count | The number of `ClaimHandle` actions applied to produce an association state. | ## 1. The identity update An identity update is one or more actions signed together. It is published as an envelope on the topic derived from its `inbox_id` and receives its sequence id from the backend; `API` owns that envelope’s storage, order, and duplicates (API-222), and TOPIC-001 owns identity topic derivation. The log is validated the same way by the backend before it stores an update (API-303 names the snapshot it validates against) and by a client after it reads one. A validator is either of them. An update with no actions changes nothing, so accepting one would let anyone who can publish fill an inbox’s log with signed-by-nobody entries. `client_timestamp_ns` is set by the sender and is not checked by anyone. It is covered by the signature text, and it is the time a member records as when it was added. ```proto // The identifier for a member of an XID message MemberIdentifier { oneof kind { string ethereum_address = 1; bytes installation_public_key = 2; Passkey passkey = 3; } } // Passkey identifier message Passkey { bytes key = 1; optional string relying_party = 2; } // List of identity kinds enum IdentifierKind { IDENTIFIER_KIND_UNSPECIFIED = 0; // Ethereum on old clients IDENTIFIER_KIND_ETHEREUM = 1; IDENTIFIER_KIND_PASSKEY = 2; IDENTIFIER_KIND_HANDLE = 3; // lookups only (IDENT-077) } // The first entry of any XID log. The XID must be deterministically derivable // from the address and nonce. // The recovery address defaults to the initial associated_address unless // there is a subsequent ChangeRecoveryAddress in the log. message CreateInbox { string initial_identifier = 1; uint64 nonce = 2; Signature initial_identifier_signature = 3; // Must be an addressable member IdentifierKind initial_identifier_kind = 4; // Should be provided if identifier kind is passkey optional string relying_party = 5; } // Adds a new member for an XID - either an addressable member such as a // wallet, or an installation acting on behalf of an address. // A key-pair that has been associated with one role MUST not be permitted to be // associated with a different role. message AddAssociation { MemberIdentifier new_member_identifier = 1; Signature existing_member_signature = 2; Signature new_member_signature = 3; // Should be provided if identifier kind is passkey optional string relying_party = 4; } // Revokes a member from an XID. The recovery address must sign the revocation. message RevokeAssociation { MemberIdentifier member_to_revoke = 1; Signature recovery_identifier_signature = 2; } // Changes the recovery identifier for an XID. The new recovery identifier must be // a current member of the XID; it keeps the role if it is later revoked as a // member. In addition to being able to add members, the recovery identifier can // also revoke members. message ChangeRecoveryAddress { string new_recovery_identifier = 1; Signature existing_recovery_identifier_signature = 2; IdentifierKind new_recovery_identifier_kind = 3; // Should be provided if identifier kind is passkey optional string relying_party = 4; } // Claims a handle for the inbox. Section 10 states the rules. message ClaimHandle { string handle = 1; Signature signature = 2; } // A single identity operation message IdentityAction { oneof kind { CreateInbox create_inbox = 1; AddAssociation add = 2; RevokeAssociation revoke = 3; ChangeRecoveryAddress change_recovery_address = 4; ClaimHandle claim_handle = 5; } } // One or more identity actions that were signed together. message IdentityUpdate { repeated IdentityAction actions = 1; uint64 client_timestamp_ns = 2; string inbox_id = 3; } ``` An `IdentifierKind` of `IDENTIFIER_KIND_UNSPECIFIED` reads as Ethereum. The `relying_party` fields and `Passkey.relying_party` are carried for display and take no part in identity: two passkey members with the same `key` are the same member. A `ClaimHandle` claims a handle for the update’s inbox; section 10 states its rules. | ID | Title | Requirement | Why | | --------- | --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | IDENT-001 | Identity update wire format | A validator MUST accept an identity update only as the `IdentityUpdate` defined above, with the field numbers and types shown, and MUST reject an update whose `actions` is empty or in which any action’s `kind`, any `MemberIdentifier`’s `kind`, or any `Signature`’s `signature` is unset or a field the definition does not list. | An empty update passes every signature rule, because it carries no signature, and each one stored spends a slot of the inbox’s finite log. | | IDENT-002 | Whole update or nothing | If any action of an update fails a rule in sections 2 to 7 or section 10, then a validator MUST reject the whole update and MUST leave the association state as it was before the update. | A half-applied update gives two validators two member sets from one log. | | IDENT-003 | The update names its inbox | When the inbox id of the association state after an update’s actions are applied differs from the update’s `inbox_id`, a validator MUST reject the update. | The topic is derived from `inbox_id`, so a mismatch stores one inbox’s log under another’s topic. | | IDENT-004 | Apply in log order | A validator MUST apply an inbox’s updates in ascending sequence id order, and each update’s actions in the order listed, each starting from the state the previous one produced. | | | IDENT-094 | At most 100 actions | If an identity update’s `actions` has more than 100 elements, then a validator MUST reject the update before it verifies any signature the update carries. | Every validator replays every action of every stored update, so one update with unbounded actions multiplies the work of every party that resolves the inbox. | | IDENT-095 | Admission checks this spec | When the backend validates an identity update under API-303, it MUST apply sections 1 to 7 and section 10 of this spec to the snapshot API-303 names followed by that update, and MUST NOT store the update when they fail. For an `erc_6492` signature of an update already in that snapshot, it MUST NOT access a chain and MUST NOT reject the new update because of that signature’s result under IDENT-093. | A stored update that does not apply stops every client from resolving the inbox at any later sequence id. Verifying the stored log against a chain on every publish costs chain calls in proportion to the history, even for an update that is then rejected. | `API` owns what a caller receives for an update rejected under IDENT-095, a duplicate of an update already stored (API-222), and the limit on stored updates per inbox that CONF publishes as `max_identity_entries`. ## 2. Inbox ids and creation An inbox id is derived from its first identifier and a nonce the app chooses, so that the same identifier can open more than one inbox and any party can check that a `CreateInbox` names the id it claims. The first action ever applied to an inbox is a `CreateInbox`; it makes the initial identifier the only member and the recovery identifier. | ID | Title | Requirement | Why | | --------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | IDENT-010 | Inbox id derivation | A validator MUST derive an inbox id as the 64 lowercase hexadecimal characters of the SHA-256 digest of the UTF-8 bytes of the initial identifier’s identifier text under the table in section 3, followed with no separator by the nonce in decimal. | | | IDENT-011 | Creation opens the log | If the first action applied to an inbox with no association state is not a `CreateInbox`, or a `CreateInbox` is applied to an inbox that has association state, then a validator MUST reject the update. | | | IDENT-012 | The creator is the first member | If a `CreateInbox`’s `initial_identifier_signature` signer differs from `initial_identifier` under `initial_identifier_kind`, then a validator MUST reject the update. When a validator applies a `CreateInbox`, it MUST produce a state that holds that identifier as its only member and as its recovery identifier, with the signature’s chain id recorded for the member and for the recovery identifier. | | | IDENT-013 | Ethereum identifier form | If an action carries an Ethereum identifier, in `initial_identifier`, `new_recovery_identifier`, or a `MemberIdentifier`, that is not `0x` followed by exactly 40 lowercase hexadecimal characters, then a validator MUST reject the update. | A signer is always derived in that form, so an identifier stored in another form never matches its own later signature, and a recovery identifier stored that way can never recover. | | IDENT-077 | Only signing identifier kinds | If a `CreateInbox`’s `initial_identifier_kind` or a `ChangeRecoveryAddress`’s `new_recovery_identifier_kind` is a value other than `IDENTIFIER_KIND_UNSPECIFIED`, `IDENTIFIER_KIND_ETHEREUM`, or `IDENTIFIER_KIND_PASSKEY`, then a validator MUST reject the update. | A recovery identifier of a kind that cannot sign can never revoke a member or hand on its role. | IDENT-013 rejects, and never rewrites, because the identifier is inside the signed text. It applies to every update a validator reads, including one stored before a validator enforced it; a deployment holds no log written under the earlier rule that tolerated other forms (Known limitations). `IDENTIFIER_KIND_HANDLE` names a handle in a lookup (section 11). A handle signs nothing, so it is never an initial identifier or a recovery identifier. IDENT-077 applies to every update a validator reads, as IDENT-013 does (Known limitations). ## 3. The signature text Every signature in an update signs one string, the signature text, built from the update’s `inbox_id`, its `client_timestamp_ns`, and its actions. A wallet user sees this text; an installation key signs it without display. The text is built by the validator from the update it received, never taken from the update, so a signer authorizes exactly the actions the validator applies. The template, where `{lines}` is the two lines of each action, in action order, joined by a single newline: ```text XMTP : Authenticate to inbox Inbox ID: {inbox_id} Current time: {timestamp} {lines} For more info: https://xmtp.org/signatures ``` The text is UTF-8; every line break is a single line feed, and there is no line feed after the last line. `{timestamp}` is `client_timestamp_ns` reinterpreted as a signed 64-bit two’s complement count of nanoseconds since 1970-01-01T00:00:00Z, so a value of 2^63 or more reads as a time before the epoch, divided by 10^9 rounding toward negative infinity, in the `date-time` form of [RFC 3339 §5.6](https://www.rfc-editor.org/rfc/rfc3339#section-5.6) with no fractional seconds and the `Z` designator, such as `2024-04-10T12:00:00Z`. Each action contributes two lines. The first is a hyphen, a space, and the action’s first line below; the second is two spaces, `(`, the label, a colon, a space, the identifier text, and `)`: ```text - {first line} ({label}: {text}) ``` | Action | Member kind of the named member | First line | Label | | ----------------------- | ------------------------------- | ---------------------------------- | --------- | | `CreateInbox` | any | `Create inbox` | `Owner` | | `AddAssociation` | installation | `Grant messaging access to app` | `ID` | | `AddAssociation` | Ethereum | `Link address to inbox` | `Address` | | `AddAssociation` | passkey | `Link passkey to inbox` | `Passkey` | | `RevokeAssociation` | installation | `Revoke messaging access from app` | `ID` | | `RevokeAssociation` | Ethereum | `Unlink address from inbox` | `Address` | | `RevokeAssociation` | passkey | `Unlink passkey from inbox` | `Passkey` | | `ChangeRecoveryAddress` | any | `Change inbox recovery address` | `Address` | | `ClaimHandle` | none | `Claim handle` | `Handle` | `{text}` is the `handle` of a `ClaimHandle`, as carried. For every other action, it is the identifier text of the named member (`initial_identifier`, `new_member_identifier`, `member_to_revoke`, or `new_recovery_identifier`): | Member kind | Identifier text | | ------------ | --------------------------------------------------------------------------------- | | Ethereum | The address as carried: `0x` and 40 lowercase hexadecimal characters | | Installation | The 64 lowercase hexadecimal characters of the 32-byte public key, with no prefix | | Passkey | The lowercase hexadecimal characters of `Passkey.key`, with no prefix | A `relying_party` never appears in the text. The nonce never appears in the text; it is bound through the inbox id. | ID | Title | Requirement | Why | | --------- | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | | IDENT-020 | One text for every signature | A validator MUST build the signature text of an update from that update’s own `inbox_id`, `client_timestamp_ns`, and actions, exactly as the template and the two tables above state, and MUST verify every signature the update carries against that text. | A text built from anything the update does not carry lets a signer authorize actions it never saw. | ## 4. Signature kinds A signature both proves possession of a key and names the party it stands for. Five kinds exist. Each verifies differently, yields a signer of one member kind, and records one replay key (section 6). ```proto // RecoverableEcdsaSignature for EIP-191 and V2 signatures message RecoverableEcdsaSignature { // 65-bytes [ R || S || V ], with recovery id as the last byte bytes bytes = 1; } // EdDSA signature for 25519 message RecoverableEd25519Signature { // 64 bytes [R(32 bytes) || S(32 bytes)] bytes bytes = 1; // 32 bytes bytes public_key = 2; } // Smart Contract Wallet signature message SmartContractWalletSignature { // CAIP-10 string // https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-10.md string account_id = 1; // Specify the block number to verify the signature against uint64 block_number = 2; // The actual signature bytes bytes signature = 3; } // Passkey signature message RecoverablePasskeySignature { bytes public_key = 1; bytes signature = 2; bytes authenticator_data = 3; bytes client_data_json = 4; } // A wrapper for all possible signature types message Signature { // Field 4 was the retired legacy delegated signature. Neither its number // nor its name may be reused. reserved 4; reserved "delegated_erc_191"; oneof signature { RecoverableEcdsaSignature erc_191 = 1; SmartContractWalletSignature erc_6492 = 2; RecoverableEd25519Signature installation_key = 3; RecoverablePasskeySignature passkey = 5; } } ``` The verification of each kind and the signer it yields. A secp256k1 recovery byte is accepted as 0, 1, 27, or 28, and an ECDSA `s` is accepted in either half of the curve order. | Field | Signs for | Verification | Signer | | ------------------ | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------- | | `erc_191` | Ethereum | `bytes` is 65 bytes `r`, `s`, recovery. Recover the secp256k1 public key from the personal-message hash ([EIP 191](https://eips.ethereum.org/EIPS/eip-191), version `0x45`) of the signature text. | The recovered address, lowercase, `0x`-prefixed | | `erc_6492` | Ethereum | Section 7: the account at `account_id` validates `signature` over the personal-message hash of the signature text at block `block_number`. | The address part of `account_id`, lowercase; chain id from its `eip155` reference | | `installation_key` | Installation | Ed25519ph ([RFC 8032 §5.1](https://www.rfc-editor.org/rfc/rfc8032.html#section-5.1)) over the signature text with the context string `IDENTITY UPDATE SIGNATURE`, under `public_key`. | The 32-byte `public_key` | | `passkey` | Passkey | `client_data_json` parses as WebAuthn client data whose `challenge` equals the base64url encoding without padding of the signature text. `signature` is a DER-encoded ECDSA P-256 signature, under the SEC1 key `public_key`, over `authenticator_data` followed by the SHA-256 digest of `client_data_json` ([WebAuthn Level 2 §6.1](https://www.w3.org/TR/webauthn-2/#sctn-authenticator-data), [§7.2 step 20](https://www.w3.org/TR/webauthn-2/#sctn-verifying-assertion)). | `Passkey` with `key` equal to `public_key`; `relying_party` is the client data’s `origin` | A `Signature` whose `signature` is unset, or set to a field this definition does not list, is rejected under IDENT-001. Field 4 carried a legacy delegated signature, which this definition retires. It is now an unknown field: a `Signature` holding only field 4 has `signature` unset and is rejected, and field 4 beside a listed field is ignored like any unknown field, so it never changes which signature is verified. A `passkey` signature proves possession of the P-256 key bound to this signature text. It is not a WebAuthn assertion verification: the ceremony `type`, the relying party id hash, the flags, the counter, the minimum authenticator data length, and the `origin` are not checked (Known limitations). | ID | Title | Requirement | Why | | --------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | | IDENT-030 | Verify by kind | A validator MUST verify each signature by the verification the table above states for its field, MUST derive its signer as the table states, and MUST reject the update when the verification fails. | | | IDENT-031 | The kind matches the member | If a signature’s field is not one the table above lists for the member kind of the party it stands for, whether the initial identifier, the new member, the existing member, or the recovery identifier, then a validator MUST reject the update. | Without it an installation key stands for a wallet, and the app that holds the key adds members the user never approved. | ## 5. Adding, revoking, and recovery Every add is approved by both sides: an existing member or the recovery identifier, and the new member. Only the recovery identifier revokes, and only the recovery identifier hands the role on. A new recovery identifier does not sign, so it must already be a member, and the role takes the chain id the log recorded for that member. To hand recovery to another party, a user first adds that party as a member; one update can carry the add and the change, in that order. The new recovery identifier can then be revoked as a member and keep its role. The pairs an add permits: | Existing signer | New member | | ------------------- | ---------------------------------- | | Ethereum or passkey | Installation, Ethereum, or passkey | | Installation | Ethereum or passkey | An installation never adds an installation: a compromised app would otherwise grant itself keys that survive its own revocation. A member is added once; a second add of a current member is rejected rather than rewriting its adder, time, or chain. An Ethereum address is not one account across chains: a contract at the same address on another chain is another signer. The chain a member was added on is recorded with it, and the chain the recovery identifier was set on is recorded with the role, so that a signature from the same address on another chain stands for neither. The recovery identifier’s chain survives its revocation as a member, because the role does. | ID | Title | Requirement | Why | | --------- | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | IDENT-040 | Both parties approve an add | If an `AddAssociation`’s `new_member_signature` signer differs from `new_member_identifier`, or its `existing_member_signature` signer is neither a current member nor the recovery identifier, or the two signers are equal, or `new_member_identifier` is a current member, then a validator MUST reject the update. | | | IDENT-041 | Permitted pairs only | If an `AddAssociation`’s existing signer and new member are both installations, then a validator MUST reject the update. | | | IDENT-042 | An add records its adder | When a validator applies an `AddAssociation`, it MUST produce a state that holds the new member with the existing signer as its adder, the update’s `client_timestamp_ns` as its time, and the new member signature’s chain id recorded. | IDENT-044 removes installations by adder, so an unrecorded adder leaves a revoked wallet’s installations live. | | IDENT-043 | Only the recovery identifier revokes | If a `RevokeAssociation`’s `recovery_identifier_signature` signer differs from the association state’s recovery identifier, then a validator MUST reject the update. | | | IDENT-044 | Revocation cascades to installations | When a validator applies a `RevokeAssociation`, it MUST produce a state that no longer holds `member_to_revoke` nor any installation member whose adder is `member_to_revoke`, and that holds every other member, the recovery identifier, and its chain id unchanged. | An installation added by a compromised wallet is as compromised as the wallet. | | IDENT-091 | Recovery moves only to a member | If a `ChangeRecoveryAddress`’s `existing_recovery_identifier_signature` signer differs from the association state’s recovery identifier, or `new_recovery_identifier` under `new_recovery_identifier_kind` is not a current member, then a validator MUST reject the update. When it applies one, the validator MUST set the recovery identifier to that member, without any signature from it, with that member’s recorded chain id as the recovery identifier’s chain id, and MUST leave the members unchanged. | A new recovery identifier signs nothing, so only a member’s record can give it a chain id; a contract wallet set while not a member would hold none, IDENT-046 would reject every signature it can make, and no member could be revoked or recovery moved again. | | IDENT-046 | A signer keeps its chain | If a signature’s signer is a current member, or the signature is the `recovery_identifier_signature` of a `RevokeAssociation`, the `existing_recovery_identifier_signature` of a `ChangeRecoveryAddress`, or an `existing_member_signature` from the recovery identifier, and the signature’s chain id differs from the chain id recorded for that member or for the recovery identifier, then a validator MUST reject the update. | A recovery identifier that is not a member has no member record to check against, and the same address on another configured chain would otherwise revoke and reassign. | | IDENT-092 | Re-added recovery keeps its chain | If an `AddAssociation`’s `new_member_identifier` is the association state’s recovery identifier and the `new_member_signature`’s chain id differs from the chain id recorded for the recovery identifier, then a validator MUST reject the update. | The member would hold one chain id and the role another, IDENT-046 would then reject every signature from the recovery identifier, and no member could be revoked or recovery moved again. | A `RevokeAssociation` naming an identifier that is not a member applies: it removes every installation whose adder is that identifier, which is how installations the recovery identifier added while not a member are removed, and it consumes its replay key and a slot of the log. The recovery identifier may revoke itself as a member; it keeps its role and its chain id. ## 6. Replay protection A signer approves an update by signing its signature text. Once the update is applied, no signature by that signer over that text can be used again, so that an attacker who holds the public log cannot re-add a member the recovery identifier has since revoked. The replay key is the signer and the signature text, never the signature bytes: a re-encoded signature, an `erc_191` signature carried again inside an `erc_6492` signature, and a second encoding that a wallet contract accepts all record the same key. One signer can sign several actions of one update. Their signatures share a key, which the check allows, because the check runs against the state the update is applied to and the keys are recorded after all of its actions apply. The signature text records time in whole seconds, so two updates with the same actions built in the same second share a text, and the second is rejected. | ID | Title | Requirement | Why | | --------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | | IDENT-090 | An authorization is used once | When an update is applied, a validator MUST add to the association state’s seen keys, for every signature the update carried, the pair of that signature’s signer and the update’s signature text. If an action carries a signature whose signer and signature text are a pair among the seen keys of the state the update is applied to, then the validator MUST reject the update. | A revoked member’s original add, republished with its signatures re-encoded or carried in another signature kind, would otherwise re-add it. | ## 7. Smart contract wallets A smart contract wallet has no private key of its own; its contract decides which signatures it accepts, and that decision can change with every block. The signature therefore names the block at which it is to be judged, and every validator judges it at that block, so an identity update accepted once is accepted by every later reader whatever the wallet’s signers become. That pinning cuts the other way at admission: a signer the wallet has removed can still produce a new signature today and name a block from before its removal. The backend therefore admits a new update only when its stated block is close to the chain head, and that freshness check runs once, at admission, never when a stored log is replayed. Validation needs chain access. A deployment publishes the chains it verifies (CONF-070); a client refuses to produce a signature for any other chain (CONF-046) and never applies that check to a signature it reads (CONF-048). `API` owns the verifier RPC a client may use in place of its own chain access, and the error a caller receives when the backend cannot reach a chain. The checks in IDENT-093 that need no chain run before any chain access, so a malformed `account_id` or an oversized `signature` is rejected and never retried. | ID | Title | Requirement | Why | | --------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | IDENT-093 | Verify at the stated block | If an `erc_6492` signature’s `signature` is longer than 47232 bytes, or its `account_id` is not a [CAIP-10](https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-10.md) account id whose namespace is `eip155`, whose reference is a chain id in decimal with no sign and no leading zero, and whose account address is `0x` followed by 40 hexadecimal characters that are not all `0`, then a validator MUST reject the update before any chain access. Otherwise, except for a signature that IDENT-095 exempts from chain access, it MUST verify `signature` by [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492) universal signature validation for the account named, over the personal-message hash of the signature text as the table in section 4 states, against the chain state at `block_number`, and MUST reject the update when the result is not valid. | Judged at the current block instead, a signer rotation would invalidate the whole log behind it. Universal signature validation reports any invalid signature as valid for the zero address, and an unbounded signature makes every validator build verification code as long as the sender chooses. 47232 bytes is the longest signature whose deployless verification initcode (validator code, ABI head, and signature) fits the 49152-byte initcode limit of EIP-3860; a longer signature can never be verified this way. | | IDENT-061 | Unreachable is not invalid | If a validator cannot obtain a result under IDENT-093 for a signature that passed the checks IDENT-093 makes before chain access, because it has no route for the chain or the chain call fails, then it MUST NOT reject the update and MUST leave it eligible for a later attempt. | A rejection recorded for an outage is permanent, and the update behind it is valid. | | IDENT-062 | Fresh block at admission | When the backend validates an update it has not stored, if an `erc_6492` signature’s `block_number` is greater than the chain’s head block number, or the timestamp of that block is more than 1800 seconds before the timestamp of the head block, then the backend MUST reject the update. | A signer removed from a wallet can otherwise sign for it for ever by naming a block from before its removal. | ## 8. Installations An installation is a member representing a single device/client database instance. Its identifier is a 32-byte Ed25519 public key, and its private key signs on the inbox’s behalf. It is registered by an `AddAssociation` with the installation as the new member, in the same update as the `CreateInbox` for a new inbox or alone for an existing one, and it is revoked by a `RevokeAssociation` from the recovery identifier. What an installation may publish as a key package is JOIN-001. The number of installations an inbox may hold is a client-side ceiling: CONF-044 stops a client from registering when the installation members in the association state it has resolved, at the highest sequence id it holds, number at least `max_installations_per_inbox`. No validator rejects an update for exceeding it, so two clients that register at once can leave an inbox above the ceiling, and a client that has not fetched the latest updates counts fewer than exist. A registration is published to the inbox’s identity topic and confirmed by the publish receipt, but the reads other parties use to find the installation can lag that receipt (OPS-009). A client that reports the registration complete on the receipt alone hands the app an installation that another client’s `GetInboxIds` or `QueryNewest` does not yet show. The client therefore confirms visibility with a metadata-only `QueryNewest` on the identity topic before it reports completion; PROC-015 owns that read. Every party that decides whether an installation belongs to an inbox does so at a sequence id: a Welcome names one per inbox (JOIN-052, JOIN-053), a group’s membership component names one per inbox (GMOD-005), and GMOD-029 owns reconciliation with later identity state. The state at a sequence id is one value for every party, and the installations an inbox has at that point are the members of kind installation in it. A sequence id that no update in the log carries names no state (IDENT-070). A client caches states it has derived; a cached state is one it derived itself. Only the backend checks that no two inboxes add one installation (API-305). No validator rejects such an update, so a stored log keeps applying, and a backend that admits one installation for two inboxes is seen only by a client that derives both states. GMOD Known limitations describe what such a key does to a group. A pre-authentication handler is an app callback that the SDK calls before it asks the signer to sign a registration, for example so the app can show its wallet or passkey prompt (IDENT-076). | ID | Title | Requirement | Why | | --------- | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | | IDENT-070 | State at a sequence id | When a validator needs an inbox’s association state at a sequence id, it MUST use the state produced under IDENT-004 by every update in that inbox’s association log with a sequence id not greater than it, only when the log holds an update whose sequence id equals it, and MUST NOT substitute the state at any other sequence id. | Two members that check a leaf against different states disagree about whether the group is valid, and a reference no update carries names nothing. | | IDENT-071 | A client validates for itself | A client MUST derive every association state it uses by applying sections 2 to 7 and section 10 to the updates it read, and MUST NOT use a member set or handles it did not derive that way. | A client that trusts the backend’s acceptance adds whatever installation a compromised backend inserts. | | IDENT-072 | Registration is visible before it is complete | When a client registers an installation, it MUST NOT report the registration complete until a `QueryNewest` on the inbox’s identity topic with `include_full_envelope` false has returned a sequence id not less than the publish receipt of the identity update that added the installation. | An app that acts on the registration at once, for example by asking another client to add the installation, is answered from a read that does not show it yet. | | IDENT-073 | Pre-authentication before a registration signature | When an SDK registers an installation whose registration needs an identity-update signature and the app has set a pre-authentication handler, the SDK MUST call the handler and wait for it to return before it asks the signer to sign. | A signature request that arrives before the app’s prompt reaches the user unexplained. | | IDENT-074 | No pre-authentication without a signature | When an SDK registers an installation whose registration needs no identity-update signature, it MUST NOT call the pre-authentication handler. | The app would show a signing prompt with nothing to sign. | | IDENT-075 | Failed pre-authentication stops registration | If the pre-authentication handler fails, then the SDK MUST end the registration without asking the signer to sign and MUST report the failure to the caller as a callback failure. | Continuing asks for a signature the app has refused to prepare for. | | IDENT-076 | The app can set a pre-authentication handler | An SDK that registers installations MUST let the app supply a pre-authentication handler when it creates a client. | Without the handler, IDENT-073 to IDENT-075 never apply, and the app cannot show its prompt before a signature request. | ## 9. Resolving an identifier An app resolves an identifier to an inbox under API-270, which selects the live association with the highest sequence id. An identifier’s association with an inbox is the `CreateInbox` or `AddAssociation` update that made it a member. The association’s sequence id is that update’s, and it is live while the identifier is a member of the inbox’s association state at the head of the log. Because IDENT-040 rejects an add of a current member, an association’s sequence id is that of the update that made the identifier a member since it was last absent. One identifier can be a live member of several inboxes at once: a user creates two inboxes from one wallet with two nonces, or links one wallet to two inboxes. No validator rejects this, and the identifier resolves to the inbox of its most recent live association (API-270). Revoking that association exposes the older inbox again. | ID | Title | Requirement | Why | | --------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | IDENT-096 | An account answer is checked | When a `GetInboxIds` answer names an inbox for an entry whose `identifier_kind` is not `IDENTIFIER_KIND_HANDLE`, or names none and the client derives an inbox for that identifier under IDENT-010, a client MUST NOT return that inbox to the app, or act on it as the inbox of that identifier, unless the members of the association state at the highest sequence id the client holds for that inbox, after it reads that inbox’s identity updates for this answer and derives the state under IDENT-071, contain the entry’s identifier. A derived inbox whose log holds no update also passes this check. It MUST compare an Ethereum address without regard to letter case and a passkey by its public key bytes. | A backend could otherwise send a user’s messages to an inbox that never held the account the user entered, or to one the account has left (IDENT-044), including the inbox the account first derived. | ## 10. Handles A handle is a short public name, such as `nick` or `nick#2341`, that an inbox claims so that other users can find it. An inbox claims a handle with a `ClaimHandle` action that one of its current members signs, so any party can check from the log that the inbox itself made each claim. A handle is not a member: it signs nothing and adds no one. A handle is a name part, optionally followed by `#` and a code of exactly four digits. `nick` and `nick#2341` are two different handles. The grammar is ASCII, so a length in characters, in bytes, and in code points is the same number, and the longest handle is 32 characters. The grammar allows one spelling of each handle, in lowercase. A validator rejects any other spelling and never rewrites it, because the handle is part of the signed text. The handle grammar, in [RFC 5234](https://www.rfc-editor.org/rfc/rfc5234) ABNF: ```abnf handle = name [ "#" code ] name = %x61-7A 0*26( %x61-7A / DIGIT / "_" / "-" ) ; a-z, then a-z, 0-9, _ or - code = 4DIGIT ; The same strings as the regular expression ^[a-z][a-z0-9_-]{0,26}(#[0-9]{4})?$ ; matched against the whole string. ``` An association state holds the inbox’s handles in claim order, and a claim count. A claim adds its handle at the end. A claim of a handle that the inbox already holds moves that handle to the end, which is how a user goes back to an older handle. The last handle is the display handle. Nothing removes a handle: every other action leaves the handles as they were, so an old handle still names its inbox. IDENT-090 stops anyone from publishing an old claim again. An update that carries a claim carries no other action. So one update makes at most one claim, and an inbox exists before it claims. One log holds at most 64 claims, and a claim of a handle that the inbox already holds counts. Claims use the same log entries that membership changes need (API-234). Without the limit, an inbox that changes its handle often fills its log, and it can then no longer revoke a lost installation (Known limitations). Any current member can sign a claim: an installation, an Ethereum address, or a passkey. A claim needs no wallet signature. A claim and a revocation are ordered in one log, so an installation cannot sign a claim after its revocation. IDENT-046 binds the claim’s signature to the chain on which its signer was added, because the signer is a current member. Three checks need state or policy that only the backend holds: that no other inbox holds the handle, that the name part is not on the backend’s reserved list and is not shorter than the deployment’s minimum name length, and that enough time has passed since the inbox’s previous claim. The backend applies them only when it admits a claim, under the identity update row of the admission table in [API section 3.1](/specs/api-backend-api/#31-admission). `CONF` owns the minimum name length. No validator applies these checks to a stored log (IDENT-084), so a change of policy never makes a stored log fail to apply. Only the backend makes a handle unique on a deployment (Known limitations). | ID | Title | Requirement | Why | | --------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | IDENT-078 | Handle grammar | If a `ClaimHandle`’s `handle` is not a string that the handle grammar above matches in full, then a validator MUST reject the update. | A second spelling of one handle lets two inboxes hold what a user types as one name. | | IDENT-079 | A claim stands alone | If an update’s `actions` holds a `ClaimHandle` and has more than one element, then a validator MUST reject the update. | One update with many claims passes the backend’s interval between claims once for all of them. | | IDENT-080 | At most 64 claims | If a `ClaimHandle` is applied to an association state whose claim count is 64 or more, then a validator MUST reject the update. | Claims spend the log entries that a revocation needs (API-234), so an inbox that changes its handle often could no longer revoke a lost installation. | | IDENT-081 | A current member signs a claim | If the signer of a `ClaimHandle`’s `signature` is not a member of the association state that the claim is applied to, then a validator MUST reject the update. | Anyone could otherwise attach a handle to another user’s inbox, and a revoked installation could still change it. | | IDENT-082 | Applying a claim | When a validator applies a `ClaimHandle`, it MUST produce a state whose handles are the previous state’s handles without `handle`, followed by `handle`, whose claim count is the previous claim count plus one, and whose members, recovery identifier, and chain ids are those of the previous state. | Two validators that order the handles differently show two display handles for one inbox. | | IDENT-083 | Only a claim changes handles | When a validator applies a `CreateInbox`, it MUST produce a state with no handles and a claim count of 0. When it applies an action other than a `CreateInbox` or a `ClaimHandle`, it MUST leave the handles and the claim count as they were. | A client that drops a handle on another action rejects a lookup answer that every other client accepts (IDENT-085). | | IDENT-084 | Claim policy is admission only | When a validator applies an update read from a stored log, it MUST NOT reject a `ClaimHandle` because another inbox holds the same handle, because its name part is reserved or shorter than a minimum length, or because of the time since the inbox’s previous claim. | A policy change would make every stored log that predates it fail to apply, and no client could then resolve the inboxes those logs name. | ## 11. Resolving and showing a handle A user finds an inbox by its handle with `GetInboxIds`, in an entry whose `identifier_kind` is `IDENTIFIER_KIND_HANDLE`. The backend answers such an entry with the inbox whose log claimed the handle, an old handle of that inbox included, or with no inbox (API-299). That answer comes from the backend alone, so a client checks it against the inbox’s own log before it uses it. A state that holds the handle proves the claim at any sequence id, because nothing removes a handle (IDENT-083). A state from before the claim does not hold the handle and proves nothing. A report only that a handle has an owner gives the app no inbox, so IDENT-085 does not apply to it; a wrong report costs one candidate when a client looks for a free handle. An inbox’s handles are part of its association state, so a client reads them from the state it derived (IDENT-071). A claim raises the inbox’s identity sequence id. GMOD-029 then moves each group of the inbox to the new state, and the other members of a conversation see a new display handle when they resolve that state. `EVENT` owns the event that reports a change of display handle. | ID | Title | Requirement | Why | | --------- | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | | IDENT-085 | A handle answer is checked | When a `GetInboxIds` answer names an inbox for a handle, a client MUST NOT return that inbox to the app, or act on it as the inbox of that handle, unless the handles of an association state that the client derived for that inbox under IDENT-071 contain the entry’s `identifier` with its ASCII uppercase letters converted to lowercase, as API-299 converts it. | A backend could otherwise send a user’s messages to an inbox that never claimed the handle the user entered. | | IDENT-086 | The current handle first | When an SDK returns the handles of an inbox to an app, it MUST return the display handle of the association state with the highest sequence id that the client holds for that inbox as the inbox’s current handle, and the other handles of that state in the reverse of their order in its handles. | An app that receives an older handle as the current one names the inbox by a handle its owner has replaced. | | IDENT-087 | Apps show the current handle | When an app shows an inbox that has a display handle, the app SHOULD show that handle as the text that identifies the inbox, and SHOULD show the inbox’s other handles only as secondary information. | | ## 12. Local signing-key persistence An app can store a local Ethereum signing key outside the client database and restore it after a restart or through another SDK. The export carries the private scalar, not an installation key or a database encryption key. Changing that scalar changes the account that can authorize identity updates. | ID | Title | Requirement | Why | | --------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | | IDENT-088 | Stable local key export | When an app exports a local Ethereum signing key, an SDK MUST return its private scalar as exactly 32 bytes in big-endian order, or as `0x` followed by the 64 lowercase hexadecimal digits of those same bytes, according to the form the app requests. | An app that stores a different encoding cannot restore its account through another SDK or version. | | IDENT-089 | Restore the same account | When an app imports a valid local Ethereum private scalar as exactly 32 big-endian bytes or as `0x` followed by 64 hexadecimal digits, an SDK MUST accept either letter case for hexadecimal digits and return a signer for the same Ethereum identifier, including after a process restart or through another SDK. | Restoring a different identifier leaves the app unable to authorize updates for its original account. | ## Known limitations Several rules reject updates that an earlier validator accepted and stored: * IDENT-013 replaces a rule that stored an Ethereum identifier in whatever case it was given. * IDENT-001 rejects an update with no actions, and a `Signature` whose only signature is the retired legacy delegated signature, field 4. * IDENT-040 rejects an add of a current member. * IDENT-093 rejects an `account_id` outside the `eip155` namespace, with a chain id not in canonical decimal form, or with an account address other than `0x` followed by 40 hexadecimal characters that are not all `0`, and a `signature` longer than its limit. * IDENT-094 rejects an update with more actions than its limit. * IDENT-077 rejects a `CreateInbox` or a `ChangeRecoveryAddress` whose identifier kind is `IDENTIFIER_KIND_HANDLE` or a value that `IdentifierKind` does not list. An earlier validator read every such kind as Ethereum. * IDENT-090 rejects an update whose signatures are by the same signers over the same signature text as an update already applied, in another encoding or another signature kind. An earlier validator keyed replay protection on the signature bytes. * IDENT-046 rejects a signature from a recovery identifier that is not a member when its chain id differs from the chain id recorded for the role. An earlier validator checked chain ids only for current members. * IDENT-091 rejects a `ChangeRecoveryAddress` whose new recovery identifier is not a current member. * IDENT-092 rejects an add of the recovery identifier as a member on a chain other than the one its role records. A validator applies each of them to every update it reads, on admission and when it replays a stored log. A log holding an update any of them rejects cannot be read past that update, and no replay path accepts it. A database written by an earlier build of this backend, or imported from the earlier networks, must hold no such update before this validator reads it. A deployment is assumed to start from an empty database, which meets this condition. `client_timestamp_ns` is not checked against any clock. A sender sets any value; it orders members for display and nothing else. An identity update’s signature text binds neither its sequence id nor a previous-update hash. A client trusts the backend for the order of an association log it first reads. A malicious backend can serve a valid revocation before the valid add it originally followed. If both updates remain authorized in that order, a client without the original log accepts the revoked member as current: revoking an absent member is permitted, and each authorization is still used only once under IDENT-090. This is accepted for the current identity update format because it carries no signed proof of log order. A `passkey` signature verifies the challenge binding and the P-256 signature, and nothing else of the WebAuthn assertion: not the ceremony `type`, the relying party id hash, the user-present or user-verified flags, the signature counter, a minimum authenticator data length, or the `origin`. A forged update still needs the private key. The omitted checks protect against phishing and cloned authenticators, not against forgery, and their absence has not been shown to permit a forgery. IDENT-062 bounds the window for a removed signer to 1800 seconds at admission. It does not close it, and it does not run when a stored log is replayed, so a signature admitted in that window stays valid for ever. A contract wallet that accepts the same signature for every message can have that signature carried in an update its owner never approved. IDENT-090 keys replay protection on the signer and the signature text, so it does not reject such an update, and no key built from the signature bytes could, because ERC-6492 admits many encodings that reach the same verdict. Such a wallet authorizes whatever is presented in its name. A member or a recovery identifier added or set through an `erc_191` signature has no chain id. An `erc_6492` signature always has one, so IDENT-046 rejects every `erc_6492` signature that stands for that member or role. Suppose the address later can sign only through ERC-1271, for example an account delegated to contract code whose wallet software no longer produces `erc_191` signatures. That wallet can then authorize nothing for that member or role again. This also holds for the recovery role after the recovery identifier is revoked as a member. No action changes a recorded chain id, because a chain id that a later signature could replace would let a contract at the same address on another chain take over the inbox. The recovery identifier can revoke such a member and add it again with an `erc_6492` signature, which records the new chain id and also revokes every installation that member added (IDENT-044). The recovery role has no such path. A user who wants to keep recovery must add another wallet or a passkey as a member, and move recovery to it (IDENT-091), before the wallet stops producing `erc_191` signatures. A block number names chain state only up to a reorganization. A validator that caches a verdict for a block keeps it after that block is replaced, until the entry is evicted or the process restarts, so a signature validated against an orphaned block can stay accepted. No validator checks block identity or finality. The backend does not ask a chain again about an `erc_6492` signature of an update it has stored (IDENT-095). The verdict it reached at admission stays in force for every later update on that inbox, as a verdict cached for a reorganized block already does. A client still verifies every signature of every log it reads (IDENT-071), with its own chain access or through the backend’s verifier RPC. A client that uses the backend’s verifier RPC for smart contract wallet signatures trusts the backend for those verdicts. It can verify against a chain of its own instead. A backend that cannot reach a chain answers the same way whether the chain is unconfigured or the chain is down (IDENT-061). A client cannot tell the two apart from the answer. Once an inbox’s log reaches the deployment’s `max_identity_entries`, no further update is stored for it, and there is no compaction. The log stays readable; the inbox can no longer add, revoke, or claim anything. One update revokes at most as many members as IDENT-094 allows actions. CONF bounds the published installation ceiling by the same number, but two clients that register at once can leave an inbox above the ceiling (section 8); revoking every installation of such an inbox takes more than one update, and each update spends an entry of the log. Only the backend checks that no two inboxes hold one handle (section 10). A backend that admits one handle for two inboxes is seen only by a client that derives the states of both inboxes, and IDENT-085 accepts an answer that names either of them, because the log of each claims the handle. IDENT-096 checks the answered inbox’s log as the backend serves it. A backend that withholds the update that revoked an identifier from an inbox can still direct a lookup of that identifier to that inbox. A lagged answer (OPS-009) that names an inbox the identifier has just left is rejected, so the lookup finds no inbox until the backend’s copy catches up. When an identifier is a live member of two inboxes (section 9), the check accepts an answer that names either of them. IDENT-096 is only as strong as the signature checks behind the state it derives. A client that uses the backend’s verifier RPC trusts the backend’s smart contract wallet verdicts (the verifier limitation above), and an `erc_6492` signature can sign for any Ethereum address (section 4). A backend that answers both `GetInboxIds` and the verifier RPC falsely can therefore add any Ethereum address to an inbox it chooses and direct a lookup of that address there; a client that verifies against a chain of its own closes this. A client created offline under CONF-034 reads no identity update before it checks that its identifier belongs to the inbox it opens, so it checks the newest state its database holds and can open an inbox whose stored log predates the update that revoked the identifier. Claim policy applies only when the backend admits a claim (IDENT-084). When a later release adds a name part to the reserved list, or a deployment raises its minimum name length, a handle claimed before the change stays with the inbox that claimed it. A lookup still resolves it (API-299), and IDENT-085 accepts the answer, because the inbox’s log claims the handle. So an inbox that claimed `support` before a release reserved `support` keeps it, and every user who looks that handle up reaches that inbox. This is accepted: a change of policy must never stop a stored log from applying or a claimed handle from resolving. Only a release changes the reserved list ([API section 3.1](/specs/api-backend-api/#31-admission)), so a name is protected only if the backend already reserves it when someone first tries to claim it. A claim does not name its deployment. A copy of an inbox’s log on another deployment carries its claims there, and gives the inbox the same handles if that backend admits them. It gives no other inbox a handle. A client built before `ClaimHandle` rejects every update that carries one under IDENT-001. It cannot derive the association state of an inbox at or after that inbox’s first claim, so it cannot resolve that inbox or check its installations in a group. This is accepted. A deployment can stop such clients first by raising its minimum client version (CONF-036). # Specifications The approved specs in this folder are the promises libxmtp and the self-hosted backend keep. `SPEC-spec-format.md` defines the format, the admission test, the identifier scheme, and the backlink rules. `GLOSSARY.md` defines the actors and shared terms. Requirement identifiers are globally unique, such as `CONF-012` or `JOIN-046`. Specs supersede XIPs. The documents they replaced were deleted under one blanket disposition (SPEC-013) once the replacing specs held their obligations; their history is in git. ## Waivers A requirement without a proving test needs a waiver under SPEC-055, SPEC-094, and SPEC-095. Use `analysis` when a recorded review proves a property that no test can prove. Use `gap` when the code does not satisfy the requirement; name an owner and an issue. Use `untested` when the reason names the code that satisfies the requirement but no test proves it yet; name an owner. ## Capability map | Prefix | Spec | Owns | | ------- | ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------- | | `SPEC` | [Specification format](/specs/spec-spec-format/) | The format, admission, identifiers, backlinks, waivers, plans’ spec-change section | | `TOPIC` | [Topic format](/specs/topic-topic-format/) | The kind byte and identifier layout of every topic | | `API` | [Backend API contract](/specs/api-backend-api/) | The gRPC contract: ordering, publish, query, subscribe, identity RPCs, connection statistics, error codes, admission validation | | `CONF` | [Backend configuration](/specs/conf-backend-configuration/) | The configuration file, configuration validation, what is published, how the client applies it | | `AUTH` | [Backend auth](/specs/auth-backend-auth/) | Request authentication and authorization, client credentials, terminal auth failures | | `OPS` | [Backend operations](/specs/ops-backend-operations/) | Retention and pruning, readiness and health, shutdown as observed, the metric catalogue | | `RATE` | [Backend rate limits](/specs/rate-backend-rate-limits/) | Caller keys, request costs by category, limits and overrides, stream rent, rate-limit rejections, limiter memory | | `PUSH` | [Push subscriptions and webhooks](/specs/push-push-subscriptions/) | Recipient registration, channels, subscription sync, dispatch, HMAC suppression, webhook signing | | `IDENT` | [Identity updates](/specs/ident-identity-updates/) | Association log, signature kinds, inbox id derivation, replay protection, installation lifecycle, local signing-key persistence | | `JOIN` | [Joining groups](/specs/join-joining-groups/) | Key packages, Welcomes, welcome pointers, when a Welcome replaces local state, join validation | | `GMOD` | [Modifying groups](/specs/gmod-modifying-groups/) | Commits and proposals, commit validation, adding members, failed installations | | `PERM` | [Group permissions](/specs/perm-group-permissions/) | The policy set, evaluation, admin semantics, policy versioning | | `META` | [Group metadata and app data](/specs/meta-group-metadata/) | Immutable and mutable metadata, the app-data dictionary and registry, disappearing messages | | `DMS` | [DMs and stitching](/specs/dms-direct-messages/) | DM id, fixed DM policy, duplicate detection and stitching | | `PROC` | [Message processing](/specs/proc-message-processing/) | Streams and queries into one ordered processor, durable positions, retry and rejection | | `SEND` | [Message sending](/specs/send-message-sending/) | Intents, message ids, publish retries, per-group ordering, failed sends | | `FORK` | [Fork recovery and commit log](/specs/fork-fork-recovery/) | Commit-log entries, fork detection, readd requests, one-shot groups | | `CONS` | [Consent](/specs/cons-consent/) | Consent states and keys, which record wins, what the client stores, gating of listing and streaming | | `SYNC` | [Device sync](/specs/sync-device-sync/) | The sync group, preference updates, trust of sync invitations | | `ARCH` | [Archive format](/specs/arch-archive-format/) | The backup export and import format and its compatibility promise | | `MIG` | [Legacy database migration](/specs/mig-legacy-database-migration/) | Closed legacy source conversion, source preservation, metadata fallback, and atomic local archives | | `CTYPE` | [Content types](/specs/ctype-content-types/) | Content type ids, the encoded-content envelope, the standard catalogue | | `STORE` | [Client storage](/specs/store-client-storage/) | Client database locations, storage lifecycle, and unencrypted database support | | `ATCH` | [Remote attachments](/specs/atch-remote-attachments/) | Published attachment storage, download URLs, the upload request, pending attachments, local attachment files, downloads | | `EVENT` | [Client events](/specs/event-client-events/) | Live event kinds, payloads, filters, delivery, and subscriptions | | `LOG` | [Client logging](/specs/log-client-logging/) | Client diagnostic logs and app sinks | ## Tools Run each one as `dev/nix-shell 'just '`. ```bash just spec-check # validate docs/specs/ and the backlinks in code; part of just lint just spec-index # print every requirement with its links; --json for tooling just spec-show JOIN-012 # print one requirement with its links ``` Skills for this work live in `.agents/skills/`: `authoring-specs`, `reviewing-specs`, and `checking-spec-compliance`. # Joining groups Everything between publishing a key package and holding group state the client can send and read in. The rules on when a Welcome may replace existing state decide whether a member can still decrypt after a re-add. A join is the one operation in which an installation accepts a group’s membership and state from a single message it did not help produce. Every other group operation is checked against state the client already holds. The rules here supply the checks a Welcome gets instead: the sender is read from the ratchet tree, the membership is checked against identity state the client resolves itself, and the join is tied to a position in the group’s message topic that precedes the Welcome. ```mermaid flowchart TD P[Publish key package] --> W[Welcome arrives] W --> U{Inline or pointer} U -->|inline| D[Unwrap with the installation's private key] U -->|pointer| R[Resolve the pointee, then unwrap symmetrically] R --> D D --> A[Check the join anchor] A --> M[Validate initial membership] M --> S{Local state for this group} S -->|none| J[Install] S -->|exists| E[Apply the replacement rules] E --> J J --> V[Validate the group at join time] ``` ## Scope In scope: what a published key package carries and advertises, its lifetime and rotation, when superseded key material is destroyed, unwrapping a Welcome under either wrapper, welcome pointers and their resolution, the join anchor, when a Welcome may replace existing local group state, validation of the membership a Welcome asserts, and the group properties a joiner checks before it accepts. Out of scope: steady-state commit validation and how a membership change is proposed and committed (`GMOD`), the association log a joiner resolves membership against (`IDENT`), the DM identifier and stitching (`DMS`), consent, which no join stores (`CONS`), the sync conversation’s own trust rule (`SYNC`), the policy engine (`PERM`), the metadata model (`META`), topic layout (`TOPIC`), and the publish and query contract (`API`). | Related | Relation | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | `EVENT` | EVENT-001 reports a joined conversation after the client stores it. EVENT-005 and EVENT-023 own the join origin and adder in the event payload. | | `DMS-001` | Owns the dm id that JOIN-089 compares with a held group’s stored dm id. | ## Terms | Term | Meaning | | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Wrapper | The encryption applied to a Welcome or a welcome pointer so that only the addressed installation can read it, in addition to MLS’s own encryption of the Welcome. | | Wrapper algorithm | The `wrapper_algorithm` value a sender sets on a published Welcome or welcome pointer, which names the private key the recipient decrypts with. | | Welcome pointer | A Welcome variant that carries the topic of a pointee and a symmetric key instead of the Welcome itself. | | Pointee | The Welcome that a welcome pointer names, shared by every installation the same commit adds. | | Join anchor | The `message_cursor` a Welcome carries: the sequence id, on the group’s message topic, of the commit that added the recipient. | | Superseded key package | A published key package that a later published key package from the same installation replaces. | | Terminal rejection | The refusal a client records for an envelope under JOIN-048. | ## 1. What a key package carries A key package is a public resource that every installation on the network produces. It carries the configuration and key material another installation needs to perform a handshake with this installation: the inbox it belongs to, its installation signature key, its MLS `init_key`, the extension and proposal types it supports, and the wrapper a sender is to encrypt a Welcome under. A key package is an RFC 9420 [`KeyPackage` (§10)](https://www.rfc-editor.org/rfc/rfc9420.html#section-10) in TLS presentation language. It travels inside `KeyPackage.key_package_tls_serialized` below. A Welcome is an RFC 9420 [`MLSMessage` (§6)](https://www.rfc-editor.org/rfc/rfc9420.html#section-6) whose body is a [`Welcome` (§12.4.3.1)](https://www.rfc-editor.org/rfc/rfc9420.html#section-12.4.3.1); it travels inside `WelcomeMessage.V1.data` (section 4) under the wrapper. Neither format is redefined here. ```proto // Last-resort key package for one installation. The server validates it and // derives the topic from its installation key. Every upload is kept; the // newest per installation is served by QueryNewest. Query with a cursor on a // key-package topic is not supported. message KeyPackage { bytes key_package_tls_serialized = 1; } ``` The inbox is carried in the leaf node’s credential. The credential is an RFC 9420 [`basic` credential (§5.3)](https://www.rfc-editor.org/rfc/rfc9420.html#section-5.3) whose `identity` is a serialized `MlsCredential`: ```proto // A credential that can be used in MLS leaf nodes message MlsCredential { string inbox_id = 1; } ``` A key package carries two XMTP extensions inside the MLS object, under extension types RFC 9420 does not define. The identifiers below are the interoperability contract: an advertisement written under any other identifier is invisible to every other implementation. ```proto // The KeyPackageExtension that stores the PubKey and the WelcomeWrapperEncryption message WelcomeWrapperEncryption { bytes pub_key = 1; WelcomeWrapperAlgorithm algorithm = 2; } ``` ```proto // Extension message that indicates the types of encryption supported by a client message WelcomePointeeEncryptionAeadTypesExtension { repeated WelcomePointeeEncryptionAeadType supported_aead_types = 1; } ``` | Extension | Identifier | Carries | | -------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------- | | Wrapper encryption | `0xff03` | A `WelcomeWrapperEncryption`: the public key and the wrapper algorithm a sender encrypts a Welcome for this installation under. | | Welcome pointee encryption | `0xff04` | A `WelcomePointeeEncryptionAeadTypesExtension`: the symmetric algorithms this installation accepts for a pointee. | A validator reads `cipher_suite` from the key package and verifies its signatures under the signature scheme of that suite, as [RFC 9420 §10.1](https://www.rfc-editor.org/rfc/rfc9420.html#section-10.1) requires. XMTP fixes the suite an installation publishes under, so a package under any other suite cannot be added to a group. The lifetime check in [§7.3](https://www.rfc-editor.org/rfc/rfc9420.html#section-7.3) is RECOMMENDED for a received leaf node; XMTP requires it for a fetched key package (JOIN-008) and omits it for the leaf nodes inside a Welcome’s ratchet tree (Known limitations). XMTP also applies one rule of the MLS extensions draft: the `last_resort_key_package` component (`0x0004`) of a key package’s `app_data_dictionary` extension only marks the package, so its `data` is empty ([draft-ietf-mls-extensions-10 §6.4.2](https://datatracker.ietf.org/doc/html/draft-ietf-mls-extensions-10#section-6.4.2)), and a validator rejects a package whose component carries data (JOIN-082). A sender fetches the newest key package the backend serves for each installation; the backend serves only that one. Using an older package would not break a protocol guarantee, but its keys may already be destroyed under section 3. When an inbox has some installations with a valid package and some without, the sender adds the inbox with the valid ones (JOIN-093) and records the rest (JOIN-012), so that a joiner can distinguish an installation the sender could not add from one it left out. | ID | Title | Requirement | Why | | -------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | JOIN-001 | Key package names its inbox | An installation MUST publish only a key package whose credential names exactly one inbox and whose leaf node `signature_key` is an installation key that the named inbox’s identity state associates with that inbox. | | | JOIN-002 | Advertised capability is binding | An installation MUST be able to process every extension type and proposal type its published key package lists in its leaf node `Capabilities` ([RFC 9420 §7.2](https://www.rfc-editor.org/rfc/rfc9420.html#section-7.2)). | A sender configures the group from what the recipients advertise. An installation that lacks a capability it advertised forks the group at the first message that uses it. | | JOIN-004 | One credential encoding | An installation MUST carry its inbox in its key package as a `basic` credential whose `identity` is a serialized `MlsCredential` as defined above, and MUST NOT use any other credential type or encoding. | | | JOIN-007 | Reject an unverifiable package | When a key package fails the validation in [RFC 9420 §10.1](https://www.rfc-editor.org/rfc/rfc9420.html#section-10.1), including the leaf node validation of [§7.3](https://www.rfc-editor.org/rfc/rfc9420.html#section-7.3) it invokes, a validator MUST reject it and MUST NOT use it to address an installation. | | | JOIN-008 | Reject an expired package | When the validator’s current time is outside the `Lifetime` of the key package’s leaf node ([RFC 9420 §7.2](https://www.rfc-editor.org/rfc/rfc9420.html#section-7.2)), at or after `not_after` or before `not_before`, the validator MUST reject the key package. | | | JOIN-082 | Reject a last-resort mark with data | When a key package’s `app_data_dictionary` extension holds the `last_resort_key_package` component (`0x0004`) with non-empty `data`, a validator MUST reject the key package and MUST NOT use it to address an installation. | Validators that follow the extensions draft reject such a package, also inside an Add. A commit that adds one is applied by the members that accept the package and rejected by those that do not, and the group forks. | | JOIN-090 | Reject an unusable addressing extension | When a key package’s `0xff03` or `0xff04` extension does not decode, or its wrapper (the `0xff03` extension, or `WELCOME_WRAPPER_ALGORITHM_CURVE25519` under `init_key` when that extension is absent) is neither `WELCOME_WRAPPER_ALGORITHM_CURVE25519` with a 32-byte key nor `WELCOME_WRAPPER_ALGORITHM_XWING_MLKEM_768_DRAFT_6` with a 1,216-byte key, or an HPKE sender setup under that algorithm fails for that key, the backend at admission and a sender choosing the installations to add MUST reject the key package. Both MUST treat a `supported_aead_types` value other than `WELCOME_POINTEE_ENCRYPTION_AEAD_TYPE_CHACHA20_POLY1305` as absent and MUST NOT reject a package for it. A member processing a commit MUST NOT reject the commit because a key package it adds fails this row. | A package no sender can address is otherwise stored and served as the installation’s newest package (API-244), and every sender that fetches it fails the add, or fails the Welcomes of a commit it has already applied. Rejecting an AEAD value defined later makes every installation that advertises it unaddable by older clients, and members that disagree about a key package in a commit fork the group. | | JOIN-072 | Published ciphersuite | An installation MUST publish its key package with `cipher_suite` `MLS_128_DHKEMX25519_CHACHA20POLY1305_SHA256_Ed25519`. | A package under another suite passes signature verification and then fails at every add, because the group’s suite does not match. | | JOIN-093 | One bad installation | When an inbox has at least one installation whose key package passes JOIN-007, JOIN-008, JOIN-082 and JOIN-090, has the `cipher_suite` JOIN-072 names, has that installation’s key as its leaf node `signature_key`, and has a credential that names that inbox, a sender MUST add that inbox using those installations and MUST NOT fail the operation because another installation of the same inbox has no such package. | One broken or stale device would otherwise make its owner unaddable by anyone. A package whose credential names another inbox is unusable, because every member rejects its leaf under GMOD-012. A package under another suite fails every Add, and API-235 makes the backend serve it. A package whose leaf is another installation’s key adds the wrong installation, and joiners then reject the Welcome under JOIN-053. | | JOIN-012 | Record what was left out | When a sender adds an inbox without one of its installations, the sender MUST record that installation’s installation key in `failed_installations` of that inbox’s entry in the group’s `GROUP_MEMBERSHIP` component. | Without the record, JOIN-053 rejects the Welcome on every joiner, or a silently dropped device is indistinguishable from one the sender never saw. | ## 2. Lifetime and rotation MLS as deployed elsewhere uses each key package once: an installation uploads many, the delivery service hands each one out once and then deletes it, and a reusable “last resort” package is the fallback ([RFC 9420 §16.8](https://www.rfc-editor.org/rfc/rfc9420.html#section-16.8)). XMTP is permissionless. Anyone can fetch an installation’s key packages, so an attacker can exhaust a supply in one pass and leave the installation with nothing but its last-resort package. XMTP therefore treats the last-resort workflow as the standard one: an installation publishes one key package at a time, every sender uses that package, and the installation bounds the package’s exposure with a lifetime and with rotation. The private keys of a published package open every Welcome addressed to it, so a compromise of the device reaches back as far as the oldest package whose keys it still holds. Two things limit that. The package states a lifetime, after which every validator rejects it. RFC 9420 [§7.2](https://www.rfc-editor.org/rfc/rfc9420.html#section-7.2) asks an application to set a maximum lifetime and reject a longer one; XMTP does not. The lifetime an installation publishes is 12 weeks by default, an installation may publish a longer one at its own risk, and no validator rejects a package for its length. And an installation that is online replaces its package: before `not_after`, and after it accepts a Welcome addressed to the current package. Neither replacement is a requirement, because an installation can be offline past its own expiry or have background work disabled, and the protocol keeps working: while all of an installation’s packages are expired, it cannot be added to a group, and nothing else breaks. | ID | Title | Requirement | Why | | -------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | JOIN-003 | Reusable key packages | While a key package is the most recently published one for its installation, that installation MUST retain the private keys that open a Welcome addressed to it, however many Welcomes addressed to the same package it has processed. | Two senders adding the installation at the same time both address the same package. Keys destroyed after the first join lose the second. | | JOIN-016 | Rotation changes keys | When an installation publishes a replacement key package, that package MUST carry an `init_key`, a leaf node `encryption_key`, and a wrapper public key generated for it, and MUST NOT reuse those of any earlier package. | A rotation that republishes the same keys moves the expiry date and leaves the compromise window unbounded. | ## 3. Destroying key material Deleting a private key is the only thing that makes a Welcome already sent to it unreadable. Deleting early gives the shortest compromise window; deleting late keeps a Welcome that is still in flight openable. Publication of a replacement is confirmed when the backend’s publish response carries a sequence id greater than 0 for the new package; API-221 owns the publish response and API-286 owns the sequence id range. From that confirmation, every superseded package is destroyed after a fixed delay, unless a Welcome the client has received is still waiting to be processed. A Welcome that is being held for a later attempt (JOIN-087, JOIN-084, JOIN-057, JOIN-094) delays that destruction until it is completed or rejected. | ID | Title | Requirement | Why | | -------- | --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | JOIN-074 | Destroy superseded key material | When 1 day has passed since the backend’s publish response for a later key package carried a sequence id greater than 0, and the client holds no Welcome it has received and not yet completed or rejected, the installation MUST destroy every private key of each superseded key package. For a package whose publish returned no sequence id, the day starts when a read of the installation’s key package topic serves another package whose sequence id is at least the highest one in a publish response the installation holds. | The only value those keys still hold is to whoever takes the device. A publish whose response was lost may be the package senders use, so only that read shows it is not, and without it the keys are kept for ever. | | JOIN-018 | Retain while work is pending | While an installation holds a received Welcome it has not completed or rejected, the installation MUST NOT destroy the private keys of any key package. | Destroying them turns a retriable join into a permanent loss of the conversation, and the client cannot ask for the Welcome again. | | JOIN-019 | Destroy every part together | When an installation destroys a key package’s private key material, it MUST destroy the private key of its `init_key`, of its leaf node `encryption_key`, and of the wrapper public key its `WelcomeWrapperEncryption` extension advertised. | Leaving any one of them behind leaves the Welcome readable and defeats the deletion. | | JOIN-020 | Confirmation precedes destruction | An installation MUST NOT destroy a key package’s private key material before the backend’s publish response for a later key package has carried a sequence id greater than 0, except that it MAY destroy at once the material of a package whose own publish the backend failed with `INVALID_ARGUMENT`. | Destroying first and failing to publish leaves the installation with no package anyone can use, and no member can add it back. A refused package was never stored (API-224), so no sender can address it. | ## 4. Unwrapping a Welcome A standard MLS Welcome is generated once for the whole set of members a commit adds. It is encrypted, but it carries publicly readable metadata that identifies which installations were added at the same time. XMTP adds a second layer of encryption for each recipient, so that a server operator cannot read that metadata, and uses a post-quantum ciphersuite in that outer layer so that traffic recorded now cannot be opened by a quantum computer later. Two wrappers exist, a classical one and the post-quantum one. Which one a sender used is recorded on the message, because a recipient can hold private keys for both and cannot tell them apart from the ciphertext. The wrapper is not a security boundary against the sender; MLS decides what a Welcome may say. The wrapper decides who can read it at all. The choice belongs to the recipient, stated in its key package, and a sender may not substitute another. ```proto message WelcomeMessage { message V1 { // Derives the topic. bytes installation_key = 1; // Encrypted MLS Welcome. bytes data = 2; // Unset when this message is the pointee of a WelcomePointer. bytes hpke_public_key = 3; xmtp.mls.message_contents.WelcomeWrapperAlgorithm wrapper_algorithm = 4; bytes welcome_metadata = 5; } message WelcomePointer { // Derives the topic. bytes installation_key = 1; // Encrypted WelcomePointer. bytes welcome_pointer = 2; bytes hpke_public_key = 3; xmtp.mls.message_contents.WelcomePointerWrapperAlgorithm wrapper_algorithm = 4; } oneof version { V1 v1 = 1; WelcomePointer welcome_pointer = 2; } } ``` ```proto enum WelcomeWrapperAlgorithm { WELCOME_WRAPPER_ALGORITHM_UNSPECIFIED = 0; WELCOME_WRAPPER_ALGORITHM_CURVE25519 = 1; WELCOME_WRAPPER_ALGORITHM_XWING_MLKEM_768_DRAFT_6 = 2; // Only used for WelcomePointee's WELCOME_WRAPPER_ALGORITHM_SYMMETRIC_KEY = 3; } ``` A Welcome with an unsupported wrapper algorithm, MLS version, or ciphersuite is held rather than rejected, because an upgrade can make it readable. A group-context extension absent from the receiving key package’s advertised capabilities receives the same hold. The hold has a deadline so that an unreadable Welcome does not keep key material and queue capacity for ever. The adder is read from the ratchet tree, not from the envelope: anyone who reads a key package can wrap a Welcome for its installation, so the wrapper names the recipient and never the sender. A Welcome can also name key material the client does not hold. JOIN-084 gives that Welcome a recovery window under the same unreadable hold; JOIN-063 prevents a change of failure reason or a restart from extending its deadline. A lookup that fails because of a database or lock error has not established that a key is absent and remains eligible for retry under JOIN-085. | ID | Title | Requirement | Why | | -------- | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | JOIN-071 | Wrap under the advertised key | When a sender wraps a Welcome or a welcome pointer for an installation, it MUST encrypt it under the `algorithm` and `pub_key` of the `WelcomeWrapperEncryption` extension of that installation’s key package, or under `WELCOME_WRAPPER_ALGORITHM_CURVE25519` and the key package’s `init_key` when the extension is absent, and MUST set `wrapper_algorithm` and `hpke_public_key` on the message to the values it used. | Any other choice produces a message the recipient cannot open, and the recipient cannot tell that from a corrupt one. | | JOIN-076 | Unwrap under the advertised key only | When a client unwraps a Welcome, it MUST decrypt with the private key of the key package whose advertised public key equals the message’s `hpke_public_key`, under the message’s `wrapper_algorithm`, and MUST reject the Welcome when that algorithm is not the one that key package advertised. | Without the rejection, an attacker who can break the classical wrapper strips the post-quantum one by relabelling the message, and the recipient accepts the downgrade silently. | | JOIN-087 | Hold an unreadable Welcome | When a Welcome cannot be read because its protobuf `WelcomeMessage.version` variant, `wrapper_algorithm`, MLS `version`, or MLS ciphersuite is unsupported by the client, or a group-context extension is absent from the receiving KeyPackage leaf node’s advertised capabilities, the client MUST keep the Welcome for 1 day from the time it first encountered that unsupported value, and MUST record a terminal rejection at the first attempt after that day on which it still cannot read it. | No deadline leaves an unreadable Welcome holding key material and queue capacity for ever. | | JOIN-084 | Hold a Welcome with missing keys | When a lookup needed to read a Welcome or welcome pointer completes and finds no key-package reference for its `hpke_public_key`, no key package for that reference, or no post-quantum private key for that package, the client MUST apply JOIN-087’s retention and terminal-rejection policy, measuring the hold from the first such result unless an unreadable hold already exists. Before terminal rejection, the client MUST retry with its current keys and MUST NOT reject solely because the hold expired if it can now read the Welcome. | A sender can name keys the installation never held; retaining those Welcomes forever prevents legitimate joins and key retirement. | | JOIN-063 | A deadline is set once | When a client retries an envelope it is holding to a deadline, it MUST NOT move that deadline later. | A deadline refreshed on every attempt never arrives. | | JOIN-025 | The adder comes from the ratchet tree | When a client records the inbox and installation that added it to a group, it MUST take them from the credential and `signature_key` of the leaf node at `GroupInfo.signer` ([RFC 9420 §12.4.3.1](https://www.rfc-editor.org/rfc/rfc9420.html#section-12.4.3.1)) in the ratchet tree, and MUST NOT take them from any field outside the Welcome’s authenticated payload. | An adder read from an unauthenticated field is one the wrapper’s author chose. | | JOIN-026 | Reject a non-Welcome payload | When the plaintext behind `data` is not an `MLSMessage` whose `wire_format` is `mls_welcome` ([RFC 9420 §6](https://www.rfc-editor.org/rfc/rfc9420.html#section-6)), the client MUST record a terminal rejection for it. | | | JOIN-027 | Refuse a pre-shared key | When a Welcome’s `GroupSecrets.psks` ([RFC 9420 §12.4.3.1](https://www.rfc-editor.org/rfc/rfc9420.html#section-12.4.3.1)) is not empty, the client MUST record a terminal rejection for it. | The client establishes no pre-shared keys, so it cannot derive the group secrets. | ## 5. Welcome pointers A commit that adds many installations produces one Welcome body repeated for each of them. A welcome pointer splits that: the body is encrypted once under a fresh symmetric key and published to a randomly generated topic, and a small message carrying that topic and the key is encrypted to each recipient. A sender uses the pointer form when more than two of the installations a commit adds advertise both `WELCOME_POINTEE_ENCRYPTION_AEAD_TYPE_CHACHA20_POLY1305` and the `WELCOME_WRAPPER_ALGORITHM_XWING_MLKEM_768_DRAFT_6` wrapper; the others receive an inline Welcome in the same publish. The pointee is published as a `WelcomeMessage.V1` whose `installation_key` is the pointer’s `destination`, so it is stored on the welcome topic for that identifier. TOPIC-001 owns the topic layout and TOPIC-002 owns identifier length validation. The pointer is the only thing that carries the topic. That is what keeps the pointee unlinkable to the group and to its recipients, and it is why JOIN-029 forbids deriving `destination` from anything an observer already has. The lowest sequence id at a topic is a meaningful rule because API-201 owns ordered visibility and reads, API-288 keeps assigned sequence ids stable, and API-289 orders later publishes after visible envelopes. ```proto message WelcomePointer { message WelcomeV1Pointer { // The topic of the welcome message. For V1, this means that it will be the first message in the topic, so no other identifier is required bytes destination = 1; // The algorithm used to encrypt the welcome pointer WelcomePointeeEncryptionAeadType aead_type = 2; // The encryption key of the welcome message. Must match key size specified by the aead_type. bytes encryption_key = 3; // Nonce used to encrypt the data field. Must match nonce size specified by the aead_type. bytes data_nonce = 4; // Nonce used to encrypt the welcome_metadata field. Must match nonce size specified by the aead_type. bytes welcome_metadata_nonce = 5; } oneof version { WelcomeV1Pointer welcome_v1_pointer = 1; } } enum WelcomePointeeEncryptionAeadType { WELCOME_POINTEE_ENCRYPTION_AEAD_TYPE_UNSPECIFIED = 0; // Use same encoding as openmls::AeadType WELCOME_POINTEE_ENCRYPTION_AEAD_TYPE_CHACHA20_POLY1305 = 3; } // MUST match the WelcomeWrapperAlgorithm enum values without 25519 so that the i32 transformations are compatible enum WelcomePointerWrapperAlgorithm { WELCOME_POINTER_WRAPPER_ALGORITHM_UNSPECIFIED = 0; WELCOME_POINTER_WRAPPER_ALGORITHM_XWING_MLKEM_768_DRAFT_6 = 2; } ``` `WelcomePointerWrapperAlgorithm` admits no classical value: a welcome pointer is always wrapped under `WELCOME_WRAPPER_ALGORITHM_XWING_MLKEM_768_DRAFT_6`. The pointee advertisement and the wrapper advertisement are independent, so a sender checks both before it chooses the pointer form (JOIN-091). | ID | Title | Requirement | Why | | -------- | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | JOIN-091 | Pointers only to pointer-capable installations | When a commit adds installations, the sender MUST send a welcome pointer only to an installation whose key package advertises `WELCOME_POINTEE_ENCRYPTION_AEAD_TYPE_CHACHA20_POLY1305` in its `0xff04` extension and `WELCOME_WRAPPER_ALGORITHM_XWING_MLKEM_768_DRAFT_6` in its `0xff03` extension, and MUST send an inline Welcome to every other installation the commit adds. | A recipient sent a form it did not advertise loses the conversation while everyone else joins. `WelcomePointerWrapperAlgorithm` has no classical value, so a pointer wrapped for a classical-only installation cannot be decoded. | | JOIN-029 | Randomly generated pointee topic | A sender MUST set a pointee’s `destination` to 32 bytes drawn from a cryptographically secure random source for that pointee alone, and MUST NOT derive them from the group, the commit, or any recipient. | The topic is the pointee’s only access control. Deriving it from the group tells an observer who was added to what. | | JOIN-030 | Fresh key for each pointee | A sender MUST set `encryption_key` to 32 bytes drawn from a cryptographically secure random source for each pointee it publishes. | One key across pointees lets a recipient of either read both. | | JOIN-065 | Distinct nonce per value | A sender MUST set `data_nonce` and `welcome_metadata_nonce` to two different 12-byte values. | A nonce reused under one key with ChaCha20-Poly1305 discloses both plaintexts and forfeits the authentication. | | JOIN-078 | ChaCha20-Poly1305 pointee encryption | A sender MUST encrypt a pointee’s `data` and `welcome_metadata` with ChaCha20-Poly1305 under `encryption_key` and the matching nonce, and MUST set `aead_type` to `WELCOME_POINTEE_ENCRYPTION_AEAD_TYPE_CHACHA20_POLY1305`. | The pointee sits on a topic anyone may publish to. Without authentication a third party substitutes a Welcome of its own and the recipient cannot tell. | | JOIN-064 | Reject an unauthentic pointee | When a pointee’s `data` or `welcome_metadata` fails ChaCha20-Poly1305 authentication under the pointer’s `encryption_key` and nonce, the client MUST reject it. | | | JOIN-032 | Take only the first pointee | When a client resolves a welcome pointer, it MUST use the message with the lowest sequence id on the topic `destination` names and MUST NOT use any later one. | Anyone who learns the topic can publish after the sender. Accepting a later message lets the race decide which group the recipient joins. | | JOIN-056 | Check the pointee’s form | When a client resolves a welcome pointer, it MUST reject a pointee whose `installation_key` is not the pointer’s `destination` or whose `wrapper_algorithm` is not `WELCOME_WRAPPER_ALGORITHM_SYMMETRIC_KEY`. | Authentication alone says that someone with the key wrote the bytes. The form check stops a Welcome meant for a different recipient being replayed into this one’s pointee topic. | | JOIN-033 | No pointer chains | If the message a welcome pointer resolves to is itself a `WelcomePointer`, then the client MUST record a terminal rejection for the pointer. | Following a chain lets one message send a client round an unbounded number of fetches. | | JOIN-094 | Bounded resolution of well-formed pointers | While the pointee of a welcome pointer whose `destination` is 32 bytes, whose `aead_type` is `WELCOME_POINTEE_ENCRYPTION_AEAD_TYPE_CHACHA20_POLY1305`, whose `encryption_key` is 32 bytes, and whose `data_nonce` and `welcome_metadata_nonce` are two different 12-byte values cannot be retrieved, the client MUST keep the pointer for a later attempt until the deadline of an unreadable hold already established under JOIN-087 or JOIN-084, or until 3 days after the backend’s timestamp on the pointer when no such hold exists. At the first attempt at or after that deadline, the client MUST record a terminal rejection if that attempt has not retrieved the pointee. | A pointer to nothing costs the sender one message and the recipient unlimited fetches; a separate unreadable hold lets recovered keys or format support complete a join. A pointer of any other form names no welcome topic under TOPIC-002 or can never open a pointee under JOIN-078, so it falls under JOIN-048 and is not held. | | JOIN-035 | Unresolved is not joined | When a client records a terminal rejection for a welcome pointer under JOIN-094, it MUST NOT install any group state for it. | The client learned nothing about the group, so state installed for it is state no member can reconcile. | ## 6. The join anchor A Welcome hands over a group that already has history. Without a stated position in that history the joiner has two bad choices: read the whole topic and fail to decrypt everything before it was added, or read nothing and miss messages sent between the commit and its first poll. The sender therefore sets `message_cursor` to the sequence id, on the group’s message topic, of the commit that added the recipient. MLS requires that commit to exist before the Welcome derived from it ([RFC 9420 §12.4.3](https://www.rfc-editor.org/rfc/rfc9420.html#section-12.4.3)). GMOD-018 requires the sender to read back and apply the commit before publishing its Welcome, and API-289 orders that later publish after the visible commit. Thus the anchor is less than the Welcome’s own sequence id or the Welcome is invalid. A client that installs a group reads its message topic from the anchor; reading earlier produces only messages it holds no secrets for. The anchor is encrypted with the Welcome and opened under the same key, so it shares the Welcome’s trust assumptions: a client that reads a Welcome trusts the sender for that Welcome’s contents, and the anchor is one of them. The client bounds the anchor under JOIN-037 and JOIN-038 and does not otherwise verify it. A Welcome that waits for its group’s message topic to reach the anchor is rejected when that topic, read 3 days after the Welcome, still ends below the anchor and the client has processed it to that end (JOIN-092). It is also the load-bearing input to the replacement rules in section 7, because it is the only statement in a Welcome about where the group’s message topic stood. ```proto // Encrypted with the welcome message data. message WelcomeMetadata { uint64 message_cursor = 1; } ``` | ID | Title | Requirement | Why | | -------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | | JOIN-036 | Every join names an anchor | When a Welcome for a group whose conversation type is not one-shot carries no `WelcomeMetadata` as defined above, the client MUST record a terminal rejection for that Welcome. | An anchor supplied outside the payload is chosen by whoever relays the message. | | JOIN-037 | The anchor precedes the Welcome | If a Welcome’s `message_cursor` is not less than the Welcome’s own sequence id, then the client MUST record a terminal rejection for it. | | | JOIN-038 | New groups start empty | If a Welcome’s `message_cursor` is 0 and the group’s `GroupContext.epoch` is not 0, then the client MUST record a terminal rejection for it. | A `message_cursor` of 0 for a group with history is an instruction to re-read the whole topic. | | JOIN-066 | Pre-join messages are not missed | A client MUST NOT report a message whose sequence id is less than its join anchor as one it failed to receive or decrypt. | Counting messages the joiner holds no secrets for as failures reports a fork that does not exist. | ## 7. Replacing local group state Being added to a group a client already holds is normal: a member is removed and added back, or two devices are added by different commits. A Welcome for a group already present is therefore not an error, but installing it discards the epoch secrets the client holds, and a client that discards live secrets leaves the group in a broken state. A Welcome replaces existing state only when the client can see that the existing state has ended. Publication order proves nothing, because the backend orders Welcomes by arrival and MLS orders groups by epoch; the two orders are independent. The decision rests on the anchor and the epoch together, compared against the group’s stored cursor on its message topic and the client’s MLS state for the group. A Welcome whose anchor equals the stored cursor is decided by JOIN-042, because that is where a re-add lands. PROC-005 owns the ordered processing position `P` used here as the stored cursor. PROC-008 owns durability of that position with the effects of processing. A group restored from an archive (ARCH-015) is a placeholder: it holds messages and metadata but no MLS state from a join, and the epoch of the placeholder group is generated locally. The rules above are about live state that must not be discarded. A placeholder has none, so a Welcome for it is validated and installed as a first join, and the messages the import wrote are kept under JOIN-044. JOIN-042 keeps guarding a group that was joined through MLS; the absence of archived secrets does not satisfy its removal-commit condition. A held group’s conversation type and dm id do not change through a Welcome. A placeholder keeps those its archive declared under ARCH-020, and a live group keeps those it was created or first joined with. JOIN-089 rejects a Welcome that would change either, for a placeholder and a live group alike, before the cursor and epoch comparisons below and before JOIN-092 keeps the Welcome for a later attempt. ```mermaid flowchart TD W[Welcome for a group already held] --> K{Same conversation type
and dm id} K -->|no| R[Identity changed: reject] K -->|yes| P{Stored cursor
versus message_cursor} P -->|cursor greater| X[Already processed: reject] P -->|cursor less, group active| E{Incoming epoch
greater than the local epoch} E -->|yes| Y[Process the topic up to the anchor first] E -->|no| X P -->|cursor not greater, group inactive| Z{Incoming epoch
not less than the local epoch} Z -->|yes| I[Replace] Z -->|no| X ``` | ID | Title | Requirement | Why | | -------- | ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | JOIN-092 | Bounded wait for the removal | When a Welcome names a group the client already holds whose MLS state is active, whose stored MLS epoch is less than the Welcome’s `GroupContext.epoch`, and whose stored cursor on its message topic is less than `message_cursor`, the client MUST keep the Welcome for a later attempt and MUST NOT replace the state before it has processed that topic up to `message_cursor`. If the newest sequence id on that topic, read no earlier than 3 days after the backend’s timestamp on the Welcome, is less than `message_cursor`, then once the client has processed the topic through that sequence id it MUST record a terminal rejection for the Welcome and MUST NOT alter the group’s state. | The commit that removed this installation lies in that range, and until it is processed the client cannot tell a re-add from an attempt to displace a live group. GMOD-018 has the sender read back its commit before it publishes the Welcome, so a topic that still ends below `message_cursor` 3 days later never reaches it, and without a deadline the Welcome and the key material JOIN-018 retains for it are held for ever. | | JOIN-042 | Replace only an ended group | A client MUST replace existing group state from a Welcome only when its MLS state for the group is inactive, because it has applied a commit that removed this installation, and the Welcome’s `GroupContext.epoch` is not less than the existing state’s epoch. When the Welcome’s `message_cursor` equals the group’s stored cursor on its message topic, the client MUST also require the Welcome’s `GroupContext.epoch` and `tree_hash` to equal those of the existing state, and otherwise MUST record a terminal rejection for it. | An earlier epoch is always stale, and an inactive group has no secrets left to lose. At the stored cursor the only valid Welcome comes from the commit that removed this installation, and the client already holds that commit’s tree. The Welcome’s GroupInfo signer must be a leaf of that tree, which a former member is not. A removed installation keeps that commit’s epoch and tree hash but not its confirmed transcript hash. | | JOIN-043 | Discard a superseded Welcome | If a Welcome’s `message_cursor` is less than the group’s stored cursor on its message topic, then the client MUST record a terminal rejection for it and MUST NOT alter the group’s state. | The client holds everything such a Welcome describes and more, so installing it would move the group backwards. | | JOIN-044 | Preserve history across a rejoin | When a client replaces group state from a Welcome, it MUST preserve the messages it already holds for that group. | A user removed and added back still owns what they read. | | JOIN-045 | Join exactly once per Welcome | A client MUST apply the effects of a given Welcome to its local state at most once, whatever the order and repetition in which the Welcome is delivered. | A second application inserts the join twice and moves the stored cursor backwards. | | JOIN-046 | Install atomically | After any interruption of a join, a client MUST hold either no state for the group or state whose stored cursor on the message topic equals the `message_cursor` of the Welcome it installed. | A group whose cursor disagrees with its secrets is indistinguishable from a fork, and a retry cannot repair it. | | JOIN-085 | Retry other local failures | If a Welcome fails for a reason that is not a property of the Welcome itself, other than unsupported input under JOIN-087, missing key material under JOIN-084, or unresolved welcome-pointer retrieval under JOIN-094, then the client MUST leave it eligible for a later attempt and MUST NOT record a terminal rejection. | Rejecting a Welcome because a local operation failed loses a join that retrying that operation could complete. | | JOIN-048 | Reject invalid input finally | When a Welcome fails for a reason that a later attempt cannot change, the client MUST record a terminal rejection for it. | A Welcome queue that never drains stops every valid Welcome behind it. | | JOIN-080 | A Welcome activates a restored group | When a Welcome names a group the client holds only as a restored placeholder under ARCH-015, the client MUST validate it under sections 4, 6, 8, and 9 as a first join, MUST NOT compare its `GroupContext.epoch` with the placeholder’s epoch or reject it under JOIN-092 or JOIN-042 on account of the placeholder, and MUST install its state with the stored cursor at `message_cursor`. It MUST preserve the imported messages under JOIN-044. | The placeholder’s epoch is generated locally and says nothing about the group, so a comparison against it rejects the only Welcome that can activate the conversation. | | JOIN-089 | A Welcome keeps the conversation identity | When a Welcome names a group the client holds, including a restored placeholder under ARCH-015 and a group whose MLS state is active, the client MUST record a terminal rejection for it unless its `CONVERSATION_TYPE` equals the stored conversation type and, when that type is DM, the dm id derived from its `DM_MEMBERS` under DMS-001 equals the stored dm id. It MUST decide this before JOIN-092 applies, without processing the group’s topic. | A Welcome that reuses a held group id would otherwise put a conversation of another kind or pair under the id, history, and label the app already shows, and the user’s messages would go to that conversation’s members. No message on the topic can make a different kind or pair match, so waiting for one only holds the Welcome. | ## 8. Validating the asserted membership A Welcome tells the joiner who is in the group. That statement comes from the sender: the ratchet tree in the `GroupInfo`’s `ratchet_tree` extension ([RFC 9420 §12.4.3.3](https://www.rfc-editor.org/rfc/rfc9420.html#section-12.4.3.3)) lists every leaf node, and each leaf node’s credential names an inbox. The joiner has no prior state to check that list against. What it has is the membership component in the group context: the `GROUP_MEMBERSHIP` component whose identifier and map encoding [META section 2](/specs/meta-group-metadata/#2-well-known-components) fixes, and whose entries GMOD-005 encodes as a `GroupMembershipEntry` naming, for each inbox in the group, the identity `sequence_id` at which that inbox’s installations are to be checked and the `failed_installations` a sender could not add. In this section, `members` means that map and `failed_installations` means the entry’s list. GMOD-006 and GMOD-009 own the sender’s resolved identity reference and installation accounting. IDENT-070 and IDENT-071 own exact association state and its validation by the client. The check runs in both directions. Every leaf node’s `signature_key` must be an installation key the named identity state associates with the leaf’s inbox, or an attacker adds a leaf under a victim’s inbox id. Every installation the named identity state associates must be a leaf node or be listed in `failed_installations`, or an attacker silently excludes a victim’s other devices and the group never notices they are missing. A joiner resolves the referenced identity state itself: when it does not hold an inbox’s association state at the referenced sequence id, it fetches that inbox’s identity updates and retries the fetch for a period the implementation chooses before it treats the reference as one that does not exist. | ID | Title | Requirement | Why | | -------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | JOIN-040 | Membership travels with the Welcome | A sender MUST include the group’s ratchet tree in the Welcome’s `GroupInfo` as a `ratchet_tree` extension ([RFC 9420 §12.4.3.3](https://www.rfc-editor.org/rfc/rfc9420.html#section-12.4.3.3)). | A Welcome that leaves the joiner to fetch the tree elsewhere lets whoever answers that fetch decide who the joiner believes is in the group. | | JOIN-049 | Membership names exact identity state | When a Welcome’s `GroupContext` carries no `GROUP_MEMBERSHIP` component, or its `members` map has no entry for the inbox named by a leaf node in the ratchet tree, the client MUST record a terminal rejection for that Welcome. | Without an exact reference the joiner checks against whatever it happens to hold, so two joiners reach different answers about the same group. | | JOIN-050 | Bound the identity references | If any value in `members` is 0 or is not less than the Welcome’s own sequence id, then the client MUST record a terminal rejection for it. | A reference at or after the Welcome can never be resolved, and 0 asserts nothing. | | JOIN-051 | Resolve before deciding | When a client does not hold an inbox’s association state at the sequence id `members` names, it MUST fetch that inbox’s identity updates through that sequence id before it decides on the membership, and MUST NOT accept or reject the membership on the state it happens to hold. | Deciding on partial state makes the outcome depend on what this device had cached, so two devices of the same inbox disagree about whether the group is valid. | | JOIN-052 | Every leaf is accounted for | When any leaf node’s `signature_key` is not an installation key that the association state of the leaf’s inbox, at the sequence id `members` names for it, associates with that inbox, the client MUST record a terminal rejection for the Welcome. | This is the check that stops one member from placing a leaf under another member’s identity. | | JOIN-053 | Expected installations are present | When an installation key that an inbox’s association state, at the sequence id `members` names for it, associates with that inbox is neither the `signature_key` of a leaf node nor listed in that inbox’s entry `failed_installations`, the client MUST record a terminal rejection for the Welcome. | Without it a sender quietly leaves a member’s other devices out, and the group’s own record shows nothing missing. | | JOIN-095 | An own adder is a current installation | When the adder under JOIN-025 names the own inbox and its `signature_key` is not an installation key of the newest association state of the own inbox that the client holds, the client MUST record a terminal rejection for the Welcome. | JOIN-052 checks the adder at the state the sender names, which can predate a revocation. An own adder makes the group a sync group under SYNC-010, so a revoked device would otherwise read every consent decision and the HMAC root key. | | JOIN-054 | Decide on unchanging evidence | When a client accepts a Welcome, it MUST install the same membership it validated, and MUST NOT install one re-derived after the validation. | Validation reads identity state over the network, and the membership can be re-derived in between. | | JOIN-059 | Unresolvable references are terminal | When a client has fetched an inbox’s identity updates and the backend holds no update at the sequence id `members` names for it, the client MUST record a terminal rejection for the Welcome. | A reference that names a state never published can never become valid, and the Welcome would otherwise stay in the queue for ever. | ## 9. Validating the group at join time The last check is on the group itself. A joiner is being handed a configuration it did not choose, and some configurations are not safe to accept: a conversation that claims to be between two people but whose policies let a third be added, or a group whose rules require behaviour this client does not have. Refusing at join is the only chance to refuse at all, because after the join the client is a member and the configuration is the group’s. DMS-021 owns the checks for a two-party conversation under JOIN-060, including a Welcome from the joiner’s own inbox. [META section 2](/specs/meta-group-metadata/#2-well-known-components) owns the minimum client version component. [CONS section 3](/specs/cons-consent/#3-what-the-client-writes) owns what a join stores, which is nothing, and CONS-060 and CONS-031 own consent filtering. SYNC-010 owns the checks for a sync-group Welcome under JOIN-060. GMOD-040 owns the group root; JOIN-083 checks that the root a Welcome carries names its group. | ID | Title | Requirement | Why | | -------- | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | JOIN-060 | Reject an inconsistent group | When the group a Welcome carries does not satisfy every property its stated conversation kind requires, the client MUST record a terminal rejection for the Welcome, whatever privileges that kind carries. | The kinds carrying the most privilege are the ones an attacker names, so a kind exempted from the check is a kind anyone can claim. | | JOIN-057 | Refuse an unsupported group | When the group a Welcome carries states a minimum client version later than this client’s, the client MUST NOT join and MUST leave the Welcome eligible for a later attempt. | Joining a group whose rules the client cannot follow forks it. An upgrade makes the Welcome valid, which no other rejection reason does. | | JOIN-058 | The joiner is present | When a client joins a group from a Welcome, it MUST establish that one leaf node’s `signature_key` is its own installation key, and MUST record a terminal rejection otherwise. | A Welcome the client can open but that adds somebody else installs a group the client can never send in and whose commits it can never apply. | | JOIN-083 | The root names the group | When a Welcome’s group context has no `GROUP_ROOT_KEY` component of 32 bytes, or the public key of the group signing key derived from it under GMOD-041 is not the Welcome’s `group_id`, the client MUST record a terminal rejection for the Welcome. | A joiner without the root cannot publish to the group, and a restored conversation activated by a group whose creator lacks the root continues into a stranger’s group. | ## Known limitations A client that has read a group’s messages past a Welcome’s anchor cannot distinguish a re-add it has already applied from a re-add whose commit it read but whose Welcome arrived late. It rejects both under JOIN-043. The cost is a missed rejoin in a rare ordering; accepting instead would let a stale Welcome displace a live group, which is worse. A sender cannot tell whether an installation has destroyed a key package’s private keys under JOIN-074, only that a replacement was published. A Welcome addressed to a superseded package more than 1 day after the replacement is wrapped for keys that may be gone, and the recipient sees only an unwrap failure. A publish that lands after the settlement read, because another process sharing the database rotates at the same moment or the backend commits a request after its client gave up, can be the served package while its keys are destroyed 1 day later. Adds to the installation fail until the next rotation. The client does not validate the `Lifetime` of the leaf nodes in the ratchet tree of a group it joins. RFC 9420 §7.3 makes that check RECOMMENDED for a received tree, and XMTP omits it, so an expired leaf that a sender would reject under JOIN-008 is accepted inside a Welcome. No change is planned. The window in JOIN-094 makes a welcome pointer that never resolves indistinguishable from one whose pointee is merely slow. A recipient on a long network outage can give up on a valid join, and no later event tells it that it did. A Welcome held for a later attempt under JOIN-087, JOIN-084, or JOIN-057 delays the destruction of every superseded key package under JOIN-074 until the held Welcome is completed or rejected. A flood of held Welcomes makes PROC-020 reject the oldest held Welcome before its JOIN deadline. A valid Welcome held under JOIN-057, JOIN-084, JOIN-087, JOIN-092, or JOIN-094 can be lost this way, and the installation needs a new Welcome to join. JOIN-092 trusts the newest sequence id that a read returns 3 days after the Welcome. A lagging copy of the store can answer that read (API-201 permits one). If that copy has not replayed the re-add commit, the client rejects a valid re-add and needs a new Welcome to rejoin. The deadline in JOIN-092 does not bound a Welcome whose group topic holds `message_cursor` but whose processing stops below it. That Welcome, and the key material it retains, stays held until that processing resumes or the group ends. An upgrade after terminal rejection under JOIN-087 cannot recover that Welcome; the installation needs a new Welcome to join. Unknown protobuf fields already stripped from pending rows by an older client cannot be reconstructed locally. Upgrading preserves the existing storage format but does not refetch those rows; if the stripped fields are needed to read the Welcome, the installation needs a new Welcome to join. A Welcome pointer whose fetched pointee carries an unknown `WelcomeMessage.version` variant is rejected rather than held under JOIN-087. The client keeps unknown fields only for Welcomes it stores, and it reads a pointee during processing without storing it. The missing-key window in JOIN-084 cannot distinguish keys that will be restored later from keys the installation never held. Restoring keys after terminal rejection does not recover that Welcome; the installation needs a new Welcome to join. JOIN-083 binds a Welcome to the group root, not to one MLS group. Every installation that was ever a member holds the root and can create a second MLS group with the same group id and root. Its Welcome passes JOIN-083 at an installation that does not hold the group, and activates a restored conversation with that id when its conversation type and dm id match (JOIN-080, JOIN-089). JOIN-042 keeps it from replacing a group whose MLS state is active, and JOIN-089 keeps it from changing a held group’s conversation type or dm id. JOIN-042 also keeps it from replacing an inactive group at the stored cursor, because there it needs the epoch and tree hash of the commit that removed this installation. Nothing protects a group whose MLS state is inactive because a commit removed this installation from a Welcome whose `message_cursor` is above the stored cursor: a Welcome with the same conversation type and dm id replaces it when its epoch is not less than the local one, and the creator of the second MLS group chooses that epoch, its members, and its `message_cursor`. The conversation keeps the consent the user gave the earlier group (CONS-058). A DM built this way reads its builder’s inbox record, never the group’s (CONS-052). The re-added installation then sends to members that creator chose, and the member list can look unchanged because the creator can add any installation whose key package the backend serves. The chosen `message_cursor` becomes the stored cursor, so pending envelopes at or below it are discarded and a later Welcome whose `message_cursor` is lower is rejected under JOIN-043. The replaced state is active, so under JOIN-042 no later Welcome replaces it until the creator’s MLS group removes this installation. Closing this needs a re-add Welcome that a former member cannot produce, which is a protocol change no spec states yet. JOIN-095 reads the own identity state this device holds. A device that has not yet loaded a revocation still accepts a Welcome from the revoked installation. A Welcome that an own installation sent before its revocation is refused when this device processes it afterwards. The decision is local and does not change the group. # Client logging Client diagnostic logs go to native logging layers or to an optional app sink. The sink is process-wide on native platforms and Node.js, and worker-wide in a browser. A slow or failed sink must not stop client work. The client keeps a fixed number of records that wait for handoff and reports overflow to the app. ## Scope In scope: client diagnostic log delivery, sink lifetime, queue capacity, drop reporting, failure isolation, and client secret redaction. Out of scope: audit logging, backend telemetry, and message bodies. AUTH-027 owns redaction in backend logs and does not replace LOG-014. ## Terms | Term | Meaning | | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Sink generation | One installed app sink. Clearing or replacing it ends that generation. | | Dispatch | The point where the client selects one retained record for its next delivery attempt and captures that generation’s pending drop count. The selected record still awaits handoff. | | Handoff | The point at which the host-side generation check admits a callback for a record. | | Pending drop count | The number of overflow records not yet cleared by a successful report in that sink generation. | ## 1. Log delivery The client sends diagnostic records to its logging layers by default. When an app installs a sink, the client retains records for asynchronous handoff in admission order. Dispatch selects one record for its next delivery attempt and captures its pending drop count. The record still waits for host handoff. One callback can run at a time across sink generations. A record waiting for handoff uses one queue slot; a callback that has started does not. A replacement may discard queued records and the pending drop count. There is no final flush when a sink ends. | ID | Title | Requirement | Why | | ------- | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | | LOG-001 | Native default logging | When no app sink is installed, the client MUST send logs to its native logging layers. | Apps must get diagnostics without a callback. | | LOG-002 | Asynchronous sink order | When a sink is installed, the client MUST hand retained records to it asynchronously in admission order, with at most one active app log callback across sink generations; LOG-011 defines which records replacement discards. | Concurrent callbacks can reorder events and retain a thread per replaced sink. | | LOG-003 | Queue capacity | While app log records await handoff, the client MUST retain at most 4096 queued records across sink generations, queues, and transport, in addition to the one active callback. | A slow app must not cause unbounded retained logs. | | LOG-004 | Nonblocking log emission | When recording a log or completing a client operation, the client MUST NOT wait for an app log callback to complete. | A slow sink must not block messaging. | | LOG-005 | Overflow drops new records | When a sink generation already has 4096 queued records, the client MUST discard each new record for that sink and increment its pending drop count by one. | The app must be able to detect lost diagnostics. | | LOG-007 | Sink replacement boundary | When clearing or replacing a sink, the client MUST stop old-generation handoffs before the operation returns, without waiting for a callback already handed off. | Waiting can deadlock a sink that replaces itself. | | LOG-008 | Reentrant sink calls | When a sink callback calls an SDK operation, the client MUST let that operation complete without waiting for the calling callback. | A callback must not wait on itself or a held client lock. | | LOG-009 | Sink failure isolation | When an app sink throws or rejects a record, the client MUST keep messaging and its configured native logging layers operational. | Diagnostic code must not stop the client. | | LOG-014 | Client secret redaction | When emitting a log to an app sink or native logging layer, the client MUST omit authentication credential values, private keys, and database encryption keys. | An app log destination must not receive secrets used by the client. | | LOG-011 | Replacement discards queued logs | When clearing or replacing a sink, the client MUST discard that generation’s queued records and pending drop count without a final reporting callback. | Sink replacement cannot promise delivery after it stops handoffs. | | LOG-012 | Old callback result isolation | When a callback from a cleared or replaced generation completes, the client MUST ignore its result for the installed generation’s drop count and queue. | A late completion must not erase or add another sink’s diagnostics. | | LOG-013 | Report dispatched drops | While a sink generation remains installed, the client MUST include the pending drop count captured at dispatch in each call’s `droppedRecords` field, clear only that reported count on success, and keep it pending on failure. Drops after dispatch MUST remain pending for a later delivery attempt. LOG-011 and LOG-012 govern a cleared or replaced generation. | A failed callback must not erase overflow evidence, and a delayed handoff must not lose later drops. | # Group metadata and app data The app-data dictionary in the MLS group context carries the group’s identity, settings, role lists, membership, and component registry. This spec owns the component ids, snapshot and delta encodings, structural checks, and the metadata an app reads. The dictionary’s bytes enter the MLS key schedule. Members that compute different bytes for one epoch cannot read each other’s messages. ```mermaid flowchart LR P[AppDataUpdate proposals] --> C[Commit] C --> V[Check pre-commit authority
and successive snapshots] V -->|reject| X[Commit rejected by every member] V -->|accept| A[Apply valid Updates in commit order
for each component] A --> D[(Dictionary in the GroupContext)] D --> R[Component registry:
type and policies per component] D --> I[Immutable: conversation type,
creator, DM pair, one-shot,
group root] D --> M[Mutable: name, settings,
version floor, admin lists,
membership] D --> O[Application components] ``` ## Scope In scope: component ids; snapshot and Update payload encodings; component structure and byte limits; creation of metadata; preservation of untouched bytes; write-once components; disappearing settings and expiry; version-floor encoding; and what an SDK exposes about metadata. Out of scope: policy semantics and roles (`PERM`); proposal-list validity, commit validation, membership, and version-floor enforcement (`GMOD`); the group root’s derivation and use (`GMOD`, `FORK`) and the one-shot payload (`FORK`); DM identity and policy (`DMS`); consent (`CONS`); message content types (`CTYPE`); and archives (`ARCH`). | Related | Relation | | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | | `PERM-010`, `PERM-012`, `PERM-017`, `PERM-026` | Own hardcoded authority, pre-commit authorization, denial of unregistered writes, and action-policy validity. | | `GMOD-059`, `GMOD-005`, `GMOD-021` | Own permitted proposal types, membership content, and validation before commit application. | | `DMS` | Reads `CONVERSATION_TYPE` and `DM_MEMBERS` from this spec and owns what a DM is. | | `JOIN-057`, `GMOD-022`, `GMOD-025`, `GMOD-026`, `GMOD-027` | Own Welcome holds, commit pauses, the monotonic floor, and version comparison. | | `GMOD-040`, `FORK-050` | Own the group root and the one-shot recovery payload. | | `EVENT` | EVENT-001 reports changed metadata and a group pause; EVENT-019 names changed metadata items. | ## Terms | Term | Meaning | | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Dictionary | The `app_data_dictionary` group context extension ([draft-ietf-mls-extensions §7.2.1](https://www.ietf.org/archive/id/draft-ietf-mls-extensions-08.html#section-7.2.1)): the map from component id to value bytes every member holds in its GroupContext. | | Component | One entry of the dictionary: a component id and its value bytes. | | Component id | The 16-bit key of a component. Its ranges are stated in section 1. | | Well-known component | A component in the XMTP range whose id, type, and encoding section 2 fixes. | | Application component | A component in the application range; registration and write authority follow PERM-010 and PERM-012. | | Registry | `COMPONENT_REGISTRY`: the map from component id to a `ComponentMetadata` entry that states the component’s type and write policies. | | Hardcoded component | `COMPONENT_REGISTRY` and `SUPER_ADMIN_LIST`: components whose write authority PERM-026 fixes in place of a registry entry. | | Immutable component | A component whose id lies in an immutable sub-range: written once and never updated or removed. | | Update, Remove | The operations of an `AppDataUpdate` proposal ([draft-ietf-mls-extensions-08 §4.7](https://www.ietf.org/archive/id/draft-ietf-mls-extensions-08.html#section-4.7)), distinct from MLS leaf-node Update and Remove proposals. | | Delta | The payload of an Update for a set or map component: an ordered list of mutations applied to the prior snapshot. | | Snapshot | The full value the dictionary stores for a component. | | Pre-commit dictionary | The dictionary of the epoch before the commit being validated. | | Version floor | The value of `MIN_SUPPORTED_PROTOCOL_VERSION`: the lowest client version that may process the group. | | Paused | The state of a group whose version floor is greater than the client’s version. | | Disappearing settings | The timestamp `MESSAGE_DISAPPEAR_FROM_NS` and duration `MESSAGE_DISAPPEAR_IN_NS`, interpreted under META-050. | | Expiry | The deadline assigned under META-050; app visibility and deletion are governed separately by META-051 and META-063. | | Application message | A stored message of the application kind: one an installation sent, as opposed to the record a client stores for a commit or a join. | | Membership-change message | A message for a commit or join that carries a `GroupUpdated` payload. | ## 1. The dictionary and its key space The dictionary is the required representation for the metadata in this spec. Previously migrated groups can have this representation too. Active readers do not use legacy XMTP extensions as a fallback; legacy-only groups lack required dictionary state. A dictionary-bearing group can retain ignored legacy extensions. GMOD-059 owns rejection of `GroupContextExtensions` proposals, subject to the pre-commit floor pause in GMOD-025. The dictionary and `AppDataUpdate` use [draft-ietf-mls-extensions-08 §4.7](https://www.ietf.org/archive/id/draft-ietf-mls-extensions-08.html#section-4.7). Their identifiers are registered in [§7.2.1](https://www.ietf.org/archive/id/draft-ietf-mls-extensions-08.html#section-7.2.1) and [§7.3.1](https://www.ietf.org/archive/id/draft-ietf-mls-extensions-08.html#section-7.3.1). XMTP assigns the component ids below. | Range | Use | | ----------------- | -------------------------------- | | `0x0000`–`0x7FFF` | Outside the component space | | `0x8000`–`0xBDFF` | Well-known mutable components | | `0xBE00`–`0xBFFF` | Well-known immutable components | | `0xC000`–`0xFCFF` | Application mutable components | | `0xFD00`–`0xFEFF` | Application immutable components | | `0xFF00`–`0xFFFF` | Reserved | Registry keys use the component id encoding in META-005. Every assigned XMTP or application id takes 4 bytes in that encoding. GMOD-030 owns rejection of invalid proposal lists under the draft’s section 4.7, including mixed Update and Remove operations and repeated Removes for one component. META-064 governs successive XMTP payloads in a valid list. META-010 and META-013 own payload decoding and delta application. | ID | Title | Requirement | Why | | -------- | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | | META-002 | Required capabilities | When a client creates a group, it MUST list the extension type `app_data_dictionary` (`0x0006`) and the proposal type `app_data_update` (`0x0008`) in the group’s `RequiredCapabilities` extension ([RFC 9420 §7.2](https://www.rfc-editor.org/rfc/rfc9420.html#section-7.2)). | An installation that does not advertise them cannot read the dictionary or process a commit that updates it. Once added, it forks the group at its first update. | | META-003 | Reserved ids are never used | When an Update or Remove targets a component id in the reserved range of section 1, the client MUST reject the commit. | | | META-004 | Immutable components are written once | When an immutable component is absent, the client MUST permit one initial scalar value or insert-only collection delta that passes authorization and structural validation. It MUST reject every Remove and every Update after that first value, including a later Update in the same commit. | Changing a conversation type or DM pair invalidates the checks made at join time. | | META-005 | Component id encoding | When a client encodes a component id inside a component value, it MUST use the QUIC variable-length integer encoding of [RFC 9000 §16](https://www.rfc-editor.org/rfc/rfc9000.html#section-16), and MUST reject a value that decodes to more than `0xFFFF`. | | ## 2. Well-known components The well-known component table gives ids, type tags, snapshot encodings, and byte limits. Creation is governed by META-075. The snapshot is the value in the dictionary; it is not necessarily the Update payload. Well-known user-scoped fields use the `USER_` name prefix. Operator documentation recommends the same prefix for application field names, without making it a configuration validation rule. `GROUP_IMAGE` bytes are opaque to the client and can carry a remote attachment descriptor; the client never fetches or parses the remote object, so a failed download does not change group state. `GROUP_IMAGE_URL` and `APP_DATA` are unchanged. Collection snapshots contain sorted, unique keys (META-012). Collection Updates carry ordered mutation sequences (META-013). Applying a delta of m mutations to a component of n keys costs about (n + m) log(n + m), each policy is evaluated at most once per operation and subject class in a commit’s validation, and processing a commit decodes and encodes each component it touches a constant number of times, however its changes are split across proposals. Scalars carry the replacement value directly. | Id | Name | `component_type` suffix | Snapshot encoding | | -------- | -------------------------------- | ------------------------- | --------------------------------------------------------------------------------------------------------- | | `0x8000` | `COMPONENT_REGISTRY` | `TLS_MAP_BYTES_BYTES` | `RegistryMap`; values are serialized `ComponentMetadata`; bounded under META-068 | | `0x8001` | `SUPER_ADMIN_LIST` | `TLS_SET_INBOX_ID` | `TlsSet` | | `0x8002` | `ADMIN_LIST` | `TLS_SET_INBOX_ID` | `TlsSet` | | `0x8003` | `GROUP_MEMBERSHIP` | `TLS_MAP_INBOX_ID_BYTES` | `TlsMap`; values are serialized `GroupMembershipEntry` (GMOD-005) | | `0x8004` | `GROUP_NAME` | `STRING` | UTF-8, at most 100 bytes | | `0x8005` | `GROUP_DESCRIPTION` | `STRING` | UTF-8, at most 1000 bytes | | `0x8006` | `GROUP_IMAGE_URL` | `STRING` | UTF-8, at most 2048 bytes | | `0x8007` | `MESSAGE_DISAPPEAR_FROM_NS` | `BYTES` | 8-byte big-endian signed integer; nanoseconds since the Unix epoch | | `0x8008` | `MESSAGE_DISAPPEAR_IN_NS` | `BYTES` | 8-byte big-endian signed integer; duration in nanoseconds | | `0x8009` | `APP_DATA` | `STRING` | UTF-8, at most 8192 bytes | | `0x800A` | `MIN_SUPPORTED_PROTOCOL_VERSION` | `STRING` | UTF-8 version under [Semantic Versioning 2.0.0 §2](https://semver.org/spec/v2.0.0.html#spec-item-2) | | `0x800B` | `COMMIT_LOG_SIGNER` | `BYTES` | Raw Ed25519 signing-key bytes | | `0x800C` | `USER_DISPLAY_NAME` | `TLS_MAP_INBOX_ID_STRING` | `TlsMap`; each value is valid UTF-8; bounded under META-068 | | `0x800D` | `GROUP_IMAGE` | `BYTES` | Opaque bytes; bounded under META-068 | | `0xBFFF` | `CONVERSATION_TYPE` | `BYTES` | 4-byte big-endian value of a defined `ConversationType` other than `CONVERSATION_TYPE_UNSPECIFIED` | | `0xBFFE` | `CREATOR_INBOX_ID` | `BYTES` | One `InboxId` | | `0xBFFD` | `DM_MEMBERS` | `TLS_SET_INBOX_ID` | `TlsSet` with exactly two entries | | `0xBFFC` | `ONESHOT_MESSAGE` | `BYTES` | Serialized `OneshotMessage` of FORK section 6 | | `0xBFFB` | `GROUP_ROOT_KEY` | `BYTES` | 32 bytes: the group root of GMOD-040 | The collection wire block below uses TLS presentation language. `K` and `T` are type parameters, with the concrete substitutions in the type table below. `` is the variable-length byte-count prefix of [RFC 9420 §2.1.2](https://www.rfc-editor.org/rfc/rfc9420.html#section-2.1.2). Each `ByteString`, including a byte-string key, carries its own prefix. Scalar payloads have no extra prefix inside `ComponentData`. `TlsSet` is `TlsMap`; an empty value has no bytes or length prefix. ```tls opaque ByteString; struct {} Empty; struct { K key; T value; } TlsMapEntry; struct { TlsMapEntry entries; } TlsMap; enum { insert(0), update(1), delete(2) } TlsMapMutationType; // one byte struct { TlsMapMutationType type; K key; select (type) { case insert: T value; case update: T value; case delete: struct {}; }; } TlsMapMutation; struct { TlsMapMutation mutations; } TlsMapDelta; enum { insert(0), remove(1), remove_by_hash(2) } TlsSetMutationType; // one byte struct { TlsSetMutationType type; select (type) { case insert: K key; case remove: K key; case remove_by_hash: opaque hash[32]; // SHA-256 of the TLS encoding of the key }; } TlsSetMutation; struct { TlsSetMutation mutations; } TlsSetDelta; struct { varint version; // QUIC varint; 0, one byte opaque id[32]; } InboxId; ``` The type table uses suffixes of the `COMPONENT_TYPE_` enum values below. `RegistryMap` is the registry-specific `TlsMap` encoding. Despite its `TLS_MAP_BYTES_BYTES` tag, its keys are component ids under META-005, without a byte-string prefix. Its Update payload is `TlsMapDelta`. | Type suffix | Snapshot | Update payload | | ------------------------- | ------------------------------------------------------------- | -------------------------------------------------------------------------------------- | | `BYTES` | Raw bytes | Replacement raw bytes | | `STRING` | UTF-8 bytes | Replacement UTF-8 bytes | | `TLS_MAP_BYTES_BYTES` | `TlsMap` | `TlsMapDelta` | | `TLS_MAP_INBOX_ID_BYTES` | `TlsMap` | `TlsMapDelta` | | `TLS_MAP_INBOX_ID_STRING` | `TlsMap`; each value must be valid UTF-8 | `TlsMapDelta`; each inserted or updated value must be valid UTF-8 | | `TLS_SET_BYTES` | `TlsSet` | `TlsSetDelta` | | `TLS_SET_INBOX_ID` | `TlsSet` | `TlsSetDelta` | ```proto // The data structure type of a component's value enum ComponentType { COMPONENT_TYPE_UNSPECIFIED = 0; // Opaque bytes, replaced atomically COMPONENT_TYPE_BYTES = 1; // A utf-8 encoded string, replaced atomically COMPONENT_TYPE_STRING = 2; // A TlsMap supporting key-level insert/update/delete via deltas COMPONENT_TYPE_TLS_MAP_BYTES_BYTES = 3; // A TlsMap supporting key-level insert/update/delete via deltas COMPONENT_TYPE_TLS_MAP_INBOX_ID_BYTES = 4; // A `TlsSet` supporting insert/remove/remove-by-hash via deltas COMPONENT_TYPE_TLS_SET_BYTES = 5; // A `TlsSet` supporting insert/remove/remove-by-hash via deltas COMPONENT_TYPE_TLS_SET_INBOX_ID = 6; // A TlsMap with key-level insert/update/delete COMPONENT_TYPE_TLS_MAP_INBOX_ID_STRING = 7; } message ComponentPermissions { // Policy for inserting a new value (component does not yet exist) MetadataPolicy insert_policy = 1; // Policy for updating an existing value MetadataPolicy update_policy = 2; // Policy for deleting a value MetadataPolicy delete_policy = 3; } message ComponentMetadata { // The data structure type of the component's value ComponentType component_type = 1; // Permission policies for this component, evaluated against regular // (member-issued) commits. ComponentPermissions permissions = 2; // Permission policies for this component, evaluated against MLS External // Commits (RFC 9420 §12.4.3.2). Absent / unset is equivalent to all-Deny: // external committers cannot touch this component. ComponentPermissions external_committer_permissions = 3; } ``` `TLS_MAP_INBOX_ID_STRING` uses the same TLS snapshot and delta encoding as `TLS_MAP_INBOX_ID_BYTES`. The type tag requires UTF-8 validation of every value in an Insert or Update delta and in the resulting snapshot; an invalid value rejects the commit. `MetadataPolicy` is defined in PERM section 2. PERM-008 owns policy evaluation failure, and PERM-017 owns action-policy validity and the restricted admin policies. Structural decoding of an entry is separate from type dispatch and policy evaluation. An entry with an unknown or unspecified `component_type` can be structurally complete; it supplies no supported dispatch type. A present policy field can still contain an invalid policy tree. The registry retains raw entry bytes, including entries that cannot be decoded or used. An authorized delta can repair or delete a mutable entry. Preservation applies to entries that the commit does not change (META-016), not to every entry in every later snapshot. A backend catalogue definition is eligible for a conversation when its `in_groups` flag is true for a group, or its `in_dms` flag for a DM, and the client supports its `component_type` and every policy tag in its three member policies; no definition is eligible for a sync group. A newer backend can publish a tag an older client does not know. That client registers nothing for the ID rather than an entry it cannot write or validate, and a client that supports the tags registers it later under META-067. Registration never forces a commit of its own. A membership refresh that finds nothing to change commits nothing, so a missing field waits for the next commit, of any kind, by a client with registry authority. | ID | Title | Requirement | Why | | -------- | ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | META-010 | Encodings are binding | The client MUST encode snapshots and Update payloads under the well-known component table, collection wire block, and type table above, including the registry-specific encoding. For an Update, it MUST decode the replacement scalar or collection delta, apply a delta to the preceding snapshot or an empty collection when absent, and reject the commit if decoding, application, or validation of the resulting snapshot and its stated byte limits fails. When a component has no built-in definition and its registry entry has an unknown or unspecified type, it MUST reject writes to that component. | A payload and a snapshot have different encodings for collections. | | META-011 | Inbox id encoding | A client MUST encode an inbox id inside a component as the `InboxId` structure above, with a `version` of 0, and MUST reject a value whose `version` is not the single byte `0x00`. | | | META-012 | Sorted collection snapshots | The client MUST encode each `TlsMap` or `TlsSet` snapshot with unique keys in ascending order, and MUST reject a snapshot that is not in that form. It MUST compare component ids numerically and byte-string and inbox-id keys lexicographically by their value bytes. | Different encodings of one set produce different group contexts. | | META-013 | Deltas apply atomically | The client MUST apply delta mutations in their listed order, with each mutation using the preceding mutation’s result, and MUST NOT reject a delta merely for repeated or unsorted keys. It MUST resolve `remove_by_hash` against the snapshot before that delta, using SHA-256 of the key’s TLS encoding. If an insert names a present key, an update or deletion names an absent key, or a hash does not identify exactly one key, it MUST reject the commit without applying any of its changes. | Partial application gives members different snapshots. | | META-014 | Registry entry form | When a registry delta names an id below the component space, reserved, or hardcoded, or inserts or updates bytes that do not decode as `ComponentMetadata` with `permissions` and all three member policy fields present, the client MUST reject the commit. It MUST also apply the policy-validity checks of PERM-017 to the resulting action policies. | A missing policy cannot authorize a later write. | | META-015 | Registry and immutable entries persist | When an `AppDataUpdate` removes `COMPONENT_REGISTRY`, or a registry delta updates or deletes an immutable component’s entry, the client MUST reject the commit. | Removing the registry prevents later authorization; changing an immutable entry can change interpretation of fixed bytes. | | META-016 | Untouched registry entries are preserved | When a commit does not explicitly change a registry entry, the client MUST preserve that entry’s bytes, including unknown protobuf fields and entries it cannot interpret. | Re-encoding an untouched entry can remove bytes that other members retain. | | META-017 | Untouched components pass through | When a client applies a commit, it MUST leave the bytes of every component the commit does not target unchanged, including a component it cannot decode. | | | META-075 | What a creator writes | When a client creates a group, other than a restored placeholder under ARCH-015, it MUST populate the epoch-0 dictionary with `COMPONENT_REGISTRY`, `SUPER_ADMIN_LIST`, `ADMIN_LIST`, `GROUP_MEMBERSHIP`, `MIN_SUPPORTED_PROTOCOL_VERSION`, `CONVERSATION_TYPE`, `CREATOR_INBOX_ID`, and `GROUP_ROOT_KEY`, with the creator set to its own inbox id and the root the one GMOD-040 drew. It MUST include each supplied name, description, image URL, app-data string, and disappearing setting, and omit each unsupplied optional value and `COMMIT_LOG_SIGNER`. It MUST initialize role lists under PERM-002 or DMS-002, the DM pair under DMS-002, and the one-shot payload under FORK-050. | | | META-066 | Register fields at creation | When a client creates a group or DM, it MUST add to `COMPONENT_REGISTRY` each application definition in its configuration snapshot that is eligible for the conversation, using that definition’s `component_type` and `permissions`; it MUST add `USER_DISPLAY_NAME` and, for a group, `GROUP_IMAGE` with the core policies of PERM-029, and leave all their component values absent. A sync group MUST NOT receive those entries. | A joiner reads field types and policies from the group, even when it has another backend snapshot. | | META-067 | Register missing fields | When a client with authority under PERM-026 builds a commit, it MUST include in that commit an Insert of each application definition eligible for the conversation whose ID has no raw key in the committed registry, subject to PERM-023; it MUST NOT overwrite a present raw entry with its backend copy. | Replacing an unreadable entry from a local snapshot would make later writes depend on which client refreshed. | | META-068 | Apply global field bounds | When a client validates an application component, `USER_DISPLAY_NAME`, `GROUP_IMAGE`, or `COMPONENT_REGISTRY`, it MUST reject a scalar or collection key or value longer than 8192 bytes and a collection snapshot longer than 65536 bytes after serialization. When a client validates an Update payload for `GROUP_MEMBERSHIP`, it MUST reject an inserted or updated entry value longer than 8192 bytes; no snapshot bound applies to `GROUP_MEMBERSHIP`. A registry entry or membership entry is measured as stored, unknown protobuf fields included. | A registry type without a shared size bound lets a writer exceed the envelope budget and blocks later changes. A DM participant may write application-range registry entries, so an unbounded registry lets one participant grow every member’s group context. Any member may update any membership entry, and repeated keys and unknown fields are stored as sent, so an unbounded entry lets one member add about one envelope per member inbox. | | META-077 | Bound the dictionary total | When a client validates a commit that carries `AppDataUpdate` proposals, it MUST sum the value lengths of every component other than `GROUP_MEMBERSHIP` before and after the commit, and MUST reject the commit when the sum after is greater than 4194304 bytes and greater than the sum before. A client MUST NOT build a commit that this rule rejects. | Per-component bounds do not limit how many application components a DM participant registers, so one participant could grow a DM’s dictionary to about 200 MiB. Judging growth, not size, keeps a conversation that is already larger usable. | | META-078 | Keep the dictionary within a Welcome | When a client builds a commit that carries `AppDataUpdate` proposals, it MUST NOT build one that leaves the sum of META-077 greater than half of `max_envelope_bytes` and greater than the sum before. Receivers MUST NOT apply this rule. | A Welcome carries the whole dictionary, so a dictionary near one envelope makes every later Add unsendable. The bound depends on the deployment, so members with different limits would fork if receivers applied it. | | META-019 | A joiner needs the identity | When a Welcome’s group context has no dictionary, or its dictionary lacks `COMPONENT_REGISTRY`, `CONVERSATION_TYPE`, or `CREATOR_INBOX_ID`, or one of those does not decode under the table above, the client MUST record a terminal rejection for the Welcome (JOIN-048). | Without them the joiner cannot tell which checks JOIN-060 demands of the group. | ## 3. Applying an update META-010 owns payload decoding and snapshot validation. PERM-010 fixes authorization to the pre-commit registry. These are separate inputs: sequential Updates use the preceding snapshot for delta application, while their authority still comes from the pre-commit state. PERM-014 owns acceptance of components without built-in definitions. Their supported registry type selects the encoding in section 2. Component-specific invariants unknown to this client cannot be checked (Known limitations). PERM-012 rejects writes without a usable registry entry, PERM-008 denies malformed policies, and META-010 rejects unsupported type dispatch. These rules do not prevent an authorized change to the registry entry itself. PERM-001 and PERM-026 own role evaluation and hardcoded write authority. | ID | Title | Requirement | Why | | -------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | | META-064 | Successive Updates use successive snapshots | When a valid commit carries successive Updates for one component, the client MUST validate and apply each XMTP payload against the snapshot produced by the preceding Update, in the order defined by [draft-ietf-mls-extensions-08 §4.7](https://www.ietf.org/archive/id/draft-ietf-mls-extensions-08.html#section-4.7). | A transition check against the original snapshot can miss a change made by an earlier Update. | ## 4. Immutable metadata Five components never change: the conversation type, the creator, the DM pair, the one-shot payload, and the group root. They are immutable under META-004, so a joiner that validates them under JOIN-060 and JOIN-083 validates them for the life of the group. ```proto // Defines the type of conversation enum ConversationType { CONVERSATION_TYPE_UNSPECIFIED = 0; CONVERSATION_TYPE_GROUP = 1; CONVERSATION_TYPE_DM = 2; CONVERSATION_TYPE_SYNC = 3; CONVERSATION_TYPE_ONESHOT = 4; } ``` `CONVERSATION_TYPE` selects the checks required by JOIN-060. DMS-002 owns the DM pair at creation, PERM-002 owns non-DM role initialization, and PERM-004 owns the non-empty super-admin invariant. | ID | Title | Requirement | Why | | -------- | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | META-030 | The DM pair is exactly two | When `DM_MEMBERS` is present and does not decode to a set of exactly two `InboxId` values, or `CONVERSATION_TYPE` is not `CONVERSATION_TYPE_DM`, the client MUST reject the Welcome or commit that carries it. | A pair of one or three is not a conversation between two people, and DMS derives the conversation’s identifier from exactly two. The pair grants DM-only authority, so a conversation of another type must not carry one. | ## 5. Mutable settings and what an app reads The name, description, image URL, and app-data string are free text an app chooses; the client bounds them (META-010) and otherwise passes them through. A component that was never set is absent from the dictionary, and absent and empty are different bytes, so an app is given one answer for both: the empty string. An app can guard an `APP_DATA` write with the value it read before it computed the new one. The guard is compared with the committed `APP_DATA` string of the group state the commit is prepared on, so a value another member committed in the meantime is detected and not overwritten. SEND-017 owns what a guard miss does to the intent. A commit that changes a setting is recorded for the app as a membership-change message whose `GroupUpdated` payload lists each changed field by a stable name. The names below are what an app matches on, and an app written against them keeps working whatever the component id behind a name. | Component | `field_name` | `old_value` and `new_value` form | | -------------------------------- | ------------------------------------ | -------------------------------- | | `GROUP_NAME` | `group_name` | The string | | `GROUP_DESCRIPTION` | `description` | The string | | `GROUP_IMAGE_URL` | `group_image_url_square` | The string | | `MESSAGE_DISAPPEAR_FROM_NS` | `message_disappear_from_ns` | The integer in decimal | | `MESSAGE_DISAPPEAR_IN_NS` | `message_disappear_in_ns` | The integer in decimal | | `MIN_SUPPORTED_PROTOCOL_VERSION` | `minimum_supported_protocol_version` | The string | | `COMMIT_LOG_SIGNER` | `_commit_log_signer` | Not recorded (META-074) | | `APP_DATA` | `app_data` | The string | ```proto message GroupUpdated { // Other fields and nested messages omitted. // A summary of a change to the mutable metadata message MetadataFieldChange { // The field that was changed string field_name = 1; // The previous value optional string old_value = 2; // The updated value optional string new_value = 3; } // The metadata changes in the commit repeated MetadataFieldChange metadata_field_changes = 4; } ``` | ID | Title | Requirement | Why | | -------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | META-074 | Changes are recorded by name | When a commit changes the value of a component in the table above other than `COMMIT_LOG_SIGNER`, the client MUST record in the membership-change message it stores for that commit a `GroupUpdated.MetadataFieldChange` as defined above, whose `field_name` and value form are the table’s, with `old_value` absent when the component was absent before. The client MUST NOT record a change for `COMMIT_LOG_SIGNER`, or for a component whose value the commit left equal. | An app reads the change log by field name, and a change recorded for an unchanged value shows the user an edit nobody made. The commit-log signer’s value is a private signing key, so recording it would put the key in stored messages, app records and logs. | | META-041 | Absent reads as empty | An SDK MUST present an absent `GROUP_NAME`, `GROUP_DESCRIPTION`, `GROUP_IMAGE_URL`, or `APP_DATA` to an app as the empty string. | | | META-069 | Describe metadata fields | When an app asks an SDK for a group’s metadata fields, the SDK MUST list every application-range registry entry that decodes as `ComponentMetadata` with all three member policies, plus each present `GROUP_NAME`, `GROUP_DESCRIPTION`, `GROUP_IMAGE_URL`, `GROUP_IMAGE`, `APP_DATA`, `USER_DISPLAY_NAME`, `MESSAGE_DISAPPEAR_FROM_NS`, and `MESSAGE_DISAPPEAR_IN_NS` entry. For each it MUST expose a field ref that holds the ID and, when available, a well-known name or a matching backend snapshot `name`; the committed member policies; and a component shape of Bytes, String, Map with key and value types, Set with key type, or Unknown with the raw type tag; it MUST derive the shape under META-010 for a well-known ID and from the registry type for an application ID; and it MUST set `is_user_field` to true exactly when the effective shape is a Map with an InboxID key. When an app asks for a field by name, the SDK MUST return the listed field with that name, preferring a well-known field over an application field, or none. | Apps need type information for every developer-facing field, including one the local backend did not define, without handling raw IDs. | | META-070 | Read component values | When an app asks for a field listed under META-069, an SDK MUST support one field ref, a batch of field refs, and one key of a map component, resolving each ref by its component ID and reading the committed group dictionary. It MUST return a batch as a list of field ref and value records in request order. It MUST return `STRING` and `TLS_MAP_INBOX_ID_STRING` values as strings and byte-valued types as bytes. | An app cannot render fields without reading the current group state or decoding the declared type. | | META-071 | Write registered fields | When an SDK writes a field listed under META-069, it MUST encode its operation under the META-010 type for a well-known ID or the committed registry type for an application ID, evaluate the committed registry policies, accept strings for `STRING` and `TLS_MAP_INBOX_ID_STRING` values and bytes for byte-valued types, and report a missing entry, unsupported type, type mismatch, or denied policy without using its backend snapshot as a substitute. | A stale snapshot can describe another type or policy for the same ID. | | META-072 | Read user data | When an app asks an SDK for user data with optional `fields` and `inbox_ids` filters, the SDK MUST select every `is_user_field` entry for `fields = None` or exactly the supplied field refs for `fields = Some`, rejecting a ref whose ID is absent or not a user field. It MUST select the current `GROUP_MEMBERSHIP` inboxes for `inbox_ids = None` in a group, the two `DM_MEMBERS` inboxes in a DM, or exactly the supplied inboxes for `inbox_ids = Some`, including former members. It MUST read one committed dictionary snapshot and return, for each selected inbox, a list of field ref and value records with only present selected values typed as Bytes or String; an inbox with no values has an empty list. | An app can render a profile list without joining separate field maps or mixing group epochs. | | META-073 | Write own user data | When an app asks an SDK to update its user data with `values`, a list of field refs with optional values, the SDK MUST infer its own inbox ID and reject a ref whose ID is absent, not a user field, repeated in `values`, or given a scalar type different from its map value type. It MUST encode each `Some(value)` as an Insert or Update of that inbox key and each `None` as a Delete when that key is present, then submit the deltas in one commit subject to the committed registry policies; an empty `values` list or a request that only clears absent keys makes no commit. | Profile edits need a typed path that cannot accidentally name another inbox. | | META-065 | A guard compares the committed app data | When an app supplies an expected value with an `APP_DATA` write, the client MUST compare it as a UTF-8 string with the `APP_DATA` value in the dictionary of the group state it prepares the commit on, and MUST NOT prepare the commit unless the two are equal. An absent `APP_DATA` component MUST NOT be equal to any expected value. | A write built on a value another member has since replaced overwrites that member’s change, and neither app sees a conflict. | ## 6. Disappearing messages Disappearing settings define a start timestamp and a duration. META-050 uses the backend’s `sent_at_ns` as the start of each eligible message’s lifespan. META-051 excludes expired messages from app reads. META-063 governs later deletion from local storage. The backend retains messages under its retention policy. A recipient can keep a copy outside the client. This feature does not erase copies already handed to an app. | ID | Title | Requirement | Why | | -------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | | META-050 | Expiry from the sent time | When the client first stores a published application message, it MUST assign an expiry exactly when both disappearing settings are present and positive and `sent_at_ns` is not less than `MESSAGE_DISAPPEAR_FROM_NS`. It MUST compute that expiry as `sent_at_ns` plus `MESSAGE_DISAPPEAR_IN_NS` using checked signed 64-bit addition, with a result above `9223372036854775807` clamped to that value. It MUST retain that expiry through later setting changes and MUST NOT assign a disappearing expiry to a membership-change message. | Processing-time expiry gives an offline installation a longer retention period. | | META-051 | Expired messages are hidden | When a message’s expiry is not later than the current time, the client MUST exclude it from history queries, direct message-id lookups, and new stream deliveries to an app. | A delayed delete must not extend the message’s visible life. | | META-063 | Delete at the cleanup pass | When a local disappearing-message cleanup pass completes successfully, the client MUST have deleted every published application message whose expiry was not later than the time that pass began. | A sender relies on cooperating recipients removing expired local copies. | | META-076 | Settings change in one commit | When an app sets or clears a conversation’s disappearing settings through the SDK’s disappearing-settings call, the SDK MUST write every changed value of `MESSAGE_DISAPPEAR_FROM_NS` and `MESSAGE_DISAPPEAR_IN_NS` in one commit. An SDK MUST let an app read a conversation’s disappearing settings, set both values, and clear them, and MUST report them as enabled exactly when both values are present and greater than 0. | A message sent between two commits gets its expiry from half a setting, and META-050 keeps that expiry. | ## 7. The protocol version floor A group can require a minimum client version. Section 2 owns the component’s encoding. GMOD-026 owns monotonic changes, GMOD-027 owns version comparison and malformed-floor handling, and JOIN-057 owns the Welcome hold. GMOD-022 requires every other validation check to pass before a floor-setting commit can pause the group. Authorization alone is insufficient. GMOD-025 owns the publication stop and resumption point; its hold follows PROC-012. PERM-023 owns the prior floor bump for changed acceptance rules, including new registry-entry formats, component types, and delta mutations. | ID | Title | Requirement | Why | | -------- | ------------------ | ------------------------------------------------------------------------------------- | --- | | META-062 | Apps see the pause | An SDK MUST let an app read whether a group is paused and the floor it is paused for. | | ## Known limitations A client cannot apply a component whose type or entry format it cannot interpret. Without the preceding floor bump described in section 7, a commit using that form can be accepted by newer clients and rejected by older clients. A component without a built-in definition is applied by its supported registry type (PERM-014 and META-010). An older client cannot check a component-specific bound or transition rule introduced by a later release. Clients that predate META-077 or the `GROUP_MEMBERSHIP` clause of META-068 apply commits that newer clients reject: one that grows the dictionary total past 4194304 bytes, or one that writes a membership entry longer than 8192 bytes. Without a version floor (PERM-023), the group forks between them. A forged commit causes either; an older client’s own write causes the first only when an app fills more than about 61 application components. A client that ignores META-078 can still grow a group’s dictionary past what one Welcome holds; after that, every Add fails under SEND-027 until the dictionary shrinks, and an immutable application component in a DM never shrinks. Clients that predate the rejection of every proposal that writes `DM_MEMBERS` under META-030 apply one, standalone or inline in a member’s own commit, which newer clients reject, and keep a standalone one for a later commit of theirs to carry by reference. Without a version floor (PERM-023), the group forks between them, so a group whose floor is below `8.0.0-0` can fork this way. An older client that applies such a write outside a DM then fails every metadata read of that group. Every rejection of an `AppDataUpdate` proposal, whether for authority, for a malformed payload, or for an invariant, is reported to the sender as one error kind. An app cannot tell a permission failure from a malformed value. Cleanup depends on local execution; META-063 imposes no wall-clock deadline while the client or cleanup work is stopped. Apps can retain copies already delivered to them. A generic metadata write under META-071 can still change one disappearing setting alone. While only one of the two values is present and positive, META-050 assigns no expiry, and a later setting change does not add one. Legacy-only groups lack the dictionary identity required by META-019. This spec defines no migration procedure. Previously migrated groups and dictionary-bearing groups with ignored legacy extensions are not excluded. # Legacy database migration Legacy conversion prepares conversation history and consent for archive import. It reads closed local storage. It does not require a network connection or a client installation on the destination network. ## Scope In scope: supported legacy storage, source preservation, the app input and result, optional metadata recovery, message eligibility, and completed output. Out of scope: archive framing and import merge rules (ARCH); conversation creation and activation (JOIN, DMS); attachment file transfer (ATCH); and an archive owner inbox check. The app selects the destination inbox. | Related | Relation | | ------- | ------------------------------------------------------------------------------------------------- | | ARCH | Owns the archive format, record ordering, exclusions, and import behavior. | | META | Owns metadata meaning and disappearing-message policy. | | CONS | Owns consent meaning and conflict resolution, and CONS-061, which combines a peer’s pre-8.0 rows. | ## Terms | Term | Meaning | | --------------- | ----------------------------------------------------------------------------------- | | Converter | The process that reads legacy storage and prepares an archive. | | Source | The closed legacy database and its sidecars. | | Working copy | Temporary storage that holds the source data during conversion. | | Publication | The atomic change that makes a completed archive available through the output path. | | Supported range | The source SDK versions listed by the converter package release. | ## 1. Source access The app closes the legacy SDK before conversion. A lock check can detect conflicting access. It cannot prove that an idle client is closed. Committed write-ahead log data is part of the source. The working copy permits schema changes without changing the source. | ID | Title | Requirement | Why | | ------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------ | | MIG-001 | Independent legacy conversion | When source storage is in the package’s published compatibility range, the converter MUST prepare an archive without requiring a legacy or destination client. | An app must not need an active legacy service to read its history. | | MIG-002 | Source bytes remain unchanged | When archive preparation succeeds, fails, or is cancelled, the converter MUST leave source database, WAL, and salt bytes unchanged; if conflicting source access is detected, it MUST fail before migration. | The app needs its source after a failed conversion. | ## 2. App input and completed output The app supplies the source path, the database key when encrypted, the archive key, and an output path. Paths identify local storage. The browser uses its local storage names. The database key, when supplied, has 32 bytes. ARCH owns the archive key length and format. ```webidl dictionary PrepareMigrationArchiveArgs { required DOMString database_path; sequence? database_key; required sequence archive_key; required DOMString output_path; }; dictionary MigrationReport { required DOMString archive_path; required unsigned long long group_count; required unsigned long long message_count; required unsigned long long consent_count; }; ``` The report counts emitted records. Import can add fewer records because the destination can already contain history. The output is complete at publication. A cancellation after publication does not undo the completed operation. A retry starts a new conversion from the source. Native publication replaces the final file. Browser publication commits an IndexedDB record that names a completed private OPFS object. A per-output lock coordinates readers, publication, and removal of unused objects. A page or worker termination is a crash. On the next access, recovery removes private objects that have no published record before it returns the completed archive. | ID | Title | Requirement | Why | | ------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | | MIG-003 | Owned input and result | When an app requests archive preparation, the converter MUST accept the owned values in `PrepareMigrationArchiveArgs` and return `MigrationReport`, or a typed input, busy, schema, migration, record, or output error. It MUST reject a database key whose length is not 32 bytes. | An app needs stable error categories and record counts. | | MIG-004 | Complete atomic output | When preparation fails or is cancelled before publication, the converter MUST preserve any completed output and remove its incomplete output. On success, it MUST publish only a complete archive under ARCH-001. If page or worker termination interrupts preparation, unpublished objects MUST remain unavailable through the output path and MUST be removed on the next storage access. | A partial file cannot replace an existing archive. | ## 3. Legacy record conversion Conversion selects both standard archive categories with no time bounds. The archive eligibility and secret exclusions remain defined by ARCH. Ordinary SDK export retains its strict metadata failure behavior. Legacy conversion can recover required history even when optional metadata is unavailable. Existing protobuf absence and scalar unknown values represent unavailable metadata. Some legacy imports lost expiry information. Their null-expiry history can migrate. Conversion cannot prove that this history was always non-disappearing. A null value added by a legacy schema migration also remains eligible. A conversation can remain in the archive when no message qualifies. On 2026-10-06, the migration owner approved this null-expiry retention choice in the [migration plan](https://plan.ref.tools/1hYl5TruynqXmFkp) to keep available legacy history even when expiry information was lost. This decision is settled for implementation. The specification as a whole remains a draft. | ID | Title | Requirement | Why | | ------- | ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | | MIG-005 | Optional metadata degrades independently | When optional legacy metadata cannot be decoded, the converter MUST retain the group and eligible messages and omit only unavailable metadata; unreadable required records MUST fail preparation. | A damaged optional field must not remove readable history. | | MIG-006 | Exclude recorded message expiry | When preparing an archive, the converter MUST exclude every otherwise eligible message whose stored `expire_at_ns` value is non-null. A null value, including one added by a legacy schema migration, MUST NOT cause exclusion by itself. | Keep available history while excluding every recorded disappearing deadline. | | MIG-007 | Bounded required-record reads | Before loading the retained variable fields of each otherwise eligible message, group, or consent row, the converter MUST validate their combined byte length in SQL against a fixed 64 MiB budget, and after decoding a message’s content it MUST count the content type ID and authority ID it copies from that content toward the same budget. It MUST project only retained columns and load at most one admitted group row at a time after bounded ID pagination. A row at the limit MUST remain supported. A row over the limit MUST fail the whole preparation with a typed record error, preserve source and previous output, and leave no incomplete output. | A large stored record must not cause an unbounded allocation or silent loss of history. | | MIG-010 | Deleted legacy messages stay deleted | When a legacy tombstone in a message’s group names it, records its sender inbox or a super-admin deletion, and the message’s encoded `type_id` is `text`, `markdown`, `reply`, `attachment`, `remoteStaticAttachment`, `transactionReference`, `walletSendCalls`, or `multiRemoteStaticAttachment`, the converter MUST write the message with empty content and `deleted_by_inbox_id` set to the deleter of such a tombstone with the lowest `deleted_at_ns`, and MUST NOT leave it out. | An archive cannot otherwise carry a super-admin deletion. | The retained variable fields are: * Message row: message ID, group ID, content bytes, sender installation ID, sender inbox ID, authority ID, and optional reference ID, and the deleter inbox ID of a deleted message. * Group row: group ID, added-by inbox ID, optional DM ID, and optional paused version. * Consent row: entity, and the DM id of the group it names. Count TEXT as bytes, not characters, including embedded NULs. An absent optional field contributes zero bytes. Optional MLS context data has a separate decode budget. This is a per-row limit, not a database or archive size limit. Conversion does not skip an oversized eligible row. Before 8.0, a DM’s consent was its group’s row. 8.0 reads a DM’s consent from the record of its other member’s inbox (CONS-052), so the converter names that member. | ID | Title | Requirement | Why | | ------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | MIG-009 | A DM’s consent names its peer | When the legacy database holds an identity row, the converter MUST write the consent rows of every group whose DM id holds that row’s inbox, together with the inbox row of that DM’s other member, as one inbox record for that member, combined under CONS-061, and MUST NOT write those rows separately. Without an identity row, it MUST write every row as stored. | 8.0 keys a DM’s consent by its peer’s inbox (CONS-052). The converter’s group filter can leave the DM’s group out of the archive, so the importer cannot find the peer. Pre-8.0 times are first-insert times, so the rows must be combined, not merged by time. | ## 4. Archive byte reads The Browser SDK supplies completed archive bytes through readMigrationArchive for the existing byte-based importer. Its 100 MB archive limit is separate from the per-row budget in MIG-007. Native file import does not use this byte reader. | ID | Title | Requirement | Why | | ------- | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | | MIG-008 | Archive byte-read limit | When readMigrationArchive is called, the SDK MUST reject a completed archive larger than 100,000,000 bytes with MigrationOutput before allocating its bytes. It MUST NOT reject an archive of exactly 100,000,000 bytes because of its length. | A caller must not allocate an unbounded archive for byte-based import. | # Backend operations Behaviour an operator or a client observes that is not any single RPC’s contract: what happens to an envelope once its expiry passes, when an instance reports itself ready, what a client sees while an instance drains, which reads may answer from a lagged copy of the store and what such a read still guarantees, and the metrics, spans, and log fields an operator monitors. Each of these is relied on by someone outside the backend: a balancer routes on health, a client plans around retention and lag, and an operator’s dashboards and alerts are written against the catalogue. ```mermaid flowchart LR I[Validate configuration
apply migrations
load key set
recover streams] --> S[SERVING] S -->|signal or stale key set| N[NOT_SERVING
new requests UNAVAILABLE
streams ended UNAVAILABLE] N -->|drain deadline| D[Remaining requests ended] D -->|flush, at most 5 s| X[Exit] ``` ## Scope In scope: what the backend may and may not delete, and what a client does not do with an expiry; the startup checks on retention and envelope size that keep every stored envelope deliverable; the health protocol and when `SERVING` is reported; what a client observes during shutdown; which reads may answer from a lagged copy and what they still guarantee; the request id, trace context, deployment identity, the telemetry startup checks, the metric families with their label vocabularies, the operator-facing span names, the request completion log, and what telemetry never contains. Out of scope: platform and deployment choices such as the database engine, the process model, read routing between database instances, and instance affinity, which live in the backend’s module README; per-RPC contracts, ordering, publish atomicity, the envelope metadata including the expiry formula, and the status codes (`API`); the configuration keys that hold the retention periods, the drain deadline, and the telemetry settings, with their types and checks other than OPS-020, OPS-021, and OPS-022 (CONF section 1.2); credentials (`AUTH`); push delivery and its dispatcher ([PUSH section 5](/specs/push-push-subscriptions/#5-dispatch)); and what a client does with a received envelope ([PROC](/specs/proc-message-processing/)). | Related | Relation | | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `API` | Owns the expiry formula and every other metadata field (API-212), the per-topic prefix every read returns (API-201), and read-your-writes on `Query` (API-202). This spec owns what happens after an expiry passes and which reads may lag. | | `CONF` | Owns the retention values (CONF-069, section 3), the request and response budgets (CONF-096), and the deployment identifier (CONF-002) this spec carries into telemetry. It also owns the configuration keys, with their types and checks other than OPS-020, OPS-021, and OPS-022 (section 1.2). | | `AUTH` | Owns admission, which runs before the drain admission of section 3, and the auth rejection reasons that label `xmtp_auth_rejections_total`; triggers the drain when its key set goes stale (AUTH-019). | | [PUSH section 5](/specs/push-push-subscriptions/#5-dispatch) | Owns push dispatch and recipient expiry (PUSH-226). This spec lists the push metric families only. | | [RATE](/specs/rate-backend-rate-limits/) | Owns the categories and auth types that label the rate-limit families. | ## Terms | Term | Meaning | | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | | Instance | One running backend process of a deployment. | | Envelope kind | The topic kind of an envelope: a group message, a Welcome, a key package, an identity update, or a commit-log entry. TOPIC-001 owns the kind byte. | | Retention period | The configured seconds for a kind: `retention.group_message_seconds`, `retention.welcome_seconds`, or `retention.key_package_seconds`. | | Expiry | The `expiry_ns` of an envelope’s metadata, set under API-212. | | Exempt envelope | An envelope whose expiry is 0. | | Current store | The state of the deployment’s store that a publish response reflects: what `Query` reads under API-202. | | Lagged copy | A copy of the store that reflects the current store as it was at some earlier time. | | Drain deadline | `server.max_drain_duration_ms`, default 10000. | | Serving | The `SERVING` status of the gRPC Health Checking Protocol. | | Request id | The UUID the backend generates for one request. | | Route table | The table in section 5 that maps a request path to its service, method, and kind labels. | ## 1. Retention Retention is decided when an envelope is stored: API-212 sets its expiry from the retention period of its kind, and to 0 for the kinds that never expire. This section owns what the expiry then means. An exempt envelope is never deleted, whatever the operator configures, because an identity update, a commit-log entry, a commit, or a proposal is state every later message depends on. An envelope is never deleted before its expiry, and while it is stored its expiry does not hide it from any read. Which stored envelopes a read returns is decided by the request’s topics, cursors, and limit under `API`, not by expiry. Deletion of an envelope after its expiry is not performed today (Known limitations); push recipient expiry under PUSH-226 is a separate mechanism. An expiry is a bound on the backend’s storage, not a message deletion rule for a client. [META section 6](/specs/meta-group-metadata/#6-disappearing-messages) owns disappearing messages. | ID | Title | Requirement | Why | | ------- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | OPS-001 | Exempt envelopes are never deleted | The backend MUST NOT delete an envelope whose `expiry_ns` is 0, whatever the configured retention periods. | A member that loses a commit can never decrypt what followed it, and an inbox that loses an identity update cannot be verified by anyone. | | OPS-002 | Expiry gates deletion only | The backend MUST NOT delete an envelope while the primary store’s clock is not greater than its `expiry_ns`, and MUST NOT exclude a stored envelope from a `Query`, `QueryNewest`, or subscription result because of its `expiry_ns`. | A client that reads a stored envelope’s metadata cannot be told it is unreadable by the same store. | | OPS-003 | Expiry is not a client deletion rule | The client MUST NOT delete, or hide from an app, a message it holds because the envelope’s `expiry_ns` has passed. | A message shown to a user and then gone is data loss to that user. | | OPS-020 | Expiry arithmetic is checked | When a configured retention period, converted to nanoseconds and added to the primary store’s clock at startup, cannot be represented as a signed 64-bit nanosecond timestamp, the backend MUST refuse to start and MUST name the key. When that addition cannot be represented at publish time, the backend MUST fail the publish with `INTERNAL` and MUST store nothing from it. | A wrapped expiry is a negative timestamp that reads as already expired. | ## 2. Readiness and health The backend serves the gRPC Health Checking Protocol ([health-checking.md](https://github.com/grpc/grpc/blob/master/doc/health-checking.md)) on the gRPC port, without a credential (AUTH-002). Every named service and the empty service name report one status, so a balancer probing one name and an orchestrator probing another cannot disagree about an instance. `SERVING` means the instance can take any request: its configuration passed its checks, its migrations are applied, its key set is loaded, and stream recovery has completed once. Unary requests do not depend on stream recovery, so a later recovery keeps health at `SERVING` and refuses only streams. One configuration check belongs here rather than with the published limits: an envelope the backend would accept must fit every path that delivers it. The backend adds at most 256 bytes of metadata and framing to an envelope in a stream frame, and a frame is 2 MiB. CONF-096 bounds the request and response budgets to the transport; this check bounds the envelope to those budgets and to the frame. | ID | Title | Requirement | Why | | ------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | OPS-004 | Health protocol on the gRPC port | The backend MUST serve `grpc.health.v1.Health` (`Check`, `Watch`, and `List`) on the port that serves the `xmtp.backend.v1` services, and MUST report the same status for the empty service name and for each `xmtp.backend.v1` service name. | | | OPS-005 | Serving means initialised | The backend MUST NOT accept a connection on the gRPC port or report `SERVING` before its configuration has passed the checks of CONF section 1 and of this spec, its database migrations have been applied, its key set has been loaded under AUTH-017 where `auth.enabled` is `true`, and stream recovery has completed once. | A balancer that routes to an instance mid-migration hands clients `INTERNAL` errors and, for a publish, a lost write. | | OPS-006 | Streams need recovery | When stream recovery restarts after a loss of the read database connection or after the unresolved gap ranges exceeded `streams.max_gap_ranges`, the backend MUST end every open stream with `UNAVAILABLE`, or with `RESOURCE_EXHAUSTED` in the gap case, and while recovery runs MUST reject a `Subscribe` or `SubscribeStatic` open with `UNAVAILABLE` and MUST continue to report `SERVING`. | A stream admitted during recovery would miss rows the backend has not yet proven delivered; a unary request needs no recovery, so taking the instance out of rotation would refuse work it can do. | | OPS-021 | Envelope size fits delivery | When the configured `limits.max_envelope_bytes` plus 256 bytes is greater than `limits.max_response_bytes` or than 2097152 bytes, or `limits.max_envelope_bytes` plus its length prefix is greater than `limits.max_request_bytes`, the backend MUST refuse to start and MUST name `limits.max_envelope_bytes`. | An envelope the backend stores but cannot fit in a frame is delivered to nobody, and every stream on its topic stalls behind it. | ## 3. Shutdown Shutdown begins on the termination signal or when the key set goes stale (AUTH-019). A client sees three things: health reports `NOT_SERVING`, every new request that reaches admission is answered `UNAVAILABLE`, and every open stream ends with `UNAVAILABLE`, whether or not its catch-up had finished. Authentication (AUTH-001) and the CORS preflight answer run before drain admission, so during a drain a request with a bad credential still gets its auth rejection and a preflight is still answered. Unary requests admitted before shutdown get the drain deadline to complete. At the deadline whatever is left is stopped, telemetry is flushed within a further 5 seconds, and the process exits. A publish admitted before shutdown may commit and still get no response. That is not proof of rollback. `API` is expected to require that a publish resent with the same envelopes returns the stored sequence ids as duplicates, which is what lets a client resend without a second copy. | ID | Title | Requirement | Why | | ------- | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | | OPS-007 | Shutdown as a client sees it | When shutdown begins, the backend MUST report `NOT_SERVING`, MUST end every open stream with `UNAVAILABLE` without waiting for its catch-up to complete, and MUST answer every request that arrives afterwards and passes AUTH-001 with `UNAVAILABLE`, while still answering a CORS preflight and still rejecting a request under AUTH-001 with its auth status. | A stream that finishes its catch-up during shutdown lets a client mistake an interrupted history for a complete one. | | OPS-008 | Bounded drain | When shutdown begins, the backend MUST stop every unary request admitted before it within the drain deadline, answering `UNAVAILABLE` where a response can still be written, and MUST exit within the drain deadline plus 5 seconds. | An orchestrator kills the process at its own deadline; work still running then ends with no response at all. | ## 4. Lagged reads A deployment may answer some reads from a lagged copy of its store, so a client that just published can see an older point in time on those reads than on `Query`. The lag is safe because a lagged read is still a prefix of every topic (API-201) and because it equals what the current store would have answered earlier, never a reordering and never a gap. Only `Query` reads the client’s own writes (API-202). A client that must confirm its own write is visible on a lagged read polls a metadata-only `QueryNewest` on the exact topic; IDENT-072 requires that for installation registration. PROC-021 defines when a client uses `Query` to reach a target from its own publish receipt. | ID | Title | Requirement | Why | | ------- | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | OPS-009 | Which reads may lag | The backend MUST answer `Publish`, `Query`, `Register`, `Unregister`, and `UpdateSubscriptions` from the current store, and MUST NOT answer any RPC other than `QueryNewest`, `Subscribe`, `SubscribeStatic`, and `GetInboxIds` from a lagged copy. | A client plans its confirmation reads around which RPCs can trail its own publish. | | OPS-010 | A lagged read is an earlier view | When an RPC answers from a lagged copy, the result MUST equal what the same request would have returned from the current store at some earlier time, so that for each topic the copy omits only envelopes whose sequence ids are greater than every envelope it returns for that topic. | A read that looks like an earlier point in time is safe; one with a gap makes a client advance its cursor past an envelope it never sees. | ## 5. Telemetry Every response carries a request id the backend generated, so one value appears in the client’s error and the operator’s log. A request that carries W3C trace context becomes a child of the caller’s trace, which is how one trace shows a client call and the backend request under it. Every exported span and every completion log names the deployment, because one collector carries several. No raw request data reaches a metric label, span field, or log field: those values outlive the message they name and are read by people it was never sent to. A claimed handle is public, but a handle in a lookup records whom a caller looked for, so handles are kept out too. What telemetry does carry is counts, sizes, durations, and words from fixed vocabularies. Metrics are in-process counters, gauges, and histograms served in the Prometheus text exposition format on a separate listener, recorded whether or not any trace is sampled or any collector is reachable. The catalogue below is the operator contract: dashboards and alerts are written against these names, types, and label vocabularies, and a label value outside its vocabulary is a series nobody planned for. | Path | `grpc_service` | `grpc_method` | `grpc_type` | | ---------------------------------------------------------------------- | -------------------------------------- | ------------------------------------- | --------------- | | `/xmtp.backend.v1.QueryService/Query` | `xmtp.backend.v1.QueryService` | `Query` | `unary` | | `/xmtp.backend.v1.QueryService/QueryNewest` | `xmtp.backend.v1.QueryService` | `QueryNewest` | `unary` | | `/xmtp.backend.v1.PublishService/Publish` | `xmtp.backend.v1.PublishService` | `Publish` | `unary` | | `/xmtp.backend.v1.SubscriptionService/Subscribe` | `xmtp.backend.v1.SubscriptionService` | `Subscribe` | `bidi_stream` | | `/xmtp.backend.v1.SubscriptionService/SubscribeStatic` | `xmtp.backend.v1.SubscriptionService` | `SubscribeStatic` | `server_stream` | | `/xmtp.backend.v1.IdentityService/GetInboxIds` | `xmtp.backend.v1.IdentityService` | `GetInboxIds` | `unary` | | `/xmtp.backend.v1.IdentityService/VerifySmartContractWalletSignatures` | `xmtp.backend.v1.IdentityService` | `VerifySmartContractWalletSignatures` | `unary` | | `/xmtp.backend.v1.ConfigurationService/GetConfiguration` | `xmtp.backend.v1.ConfigurationService` | `GetConfiguration` | `unary` | | `/xmtp.backend.v1.NotificationService/Register` | `xmtp.backend.v1.NotificationService` | `Register` | `unary` | | `/xmtp.backend.v1.NotificationService/Unregister` | `xmtp.backend.v1.NotificationService` | `Unregister` | `unary` | | `/xmtp.backend.v1.NotificationService/UpdateSubscriptions` | `xmtp.backend.v1.NotificationService` | `UpdateSubscriptions` | `unary` | | `/xmtp.backend.v1.AttachmentService/CreateUpload` | `xmtp.backend.v1.AttachmentService` | `CreateUpload` | `unary` | | `/grpc.health.v1.Health/Check` | `grpc.health.v1.Health` | `Check` | `unary` | | `/grpc.health.v1.Health/Watch` | `grpc.health.v1.Health` | `Watch` | `unary` | | `/grpc.health.v1.Health/List` | `grpc.health.v1.Health` | `List` | `unary` | | Any other path | `unknown` | `unknown` | `unary` | In the catalogue, “RPC” means the three labels of the route table. `grpc_code` is the gRPC status name in upper camel case, from `OK` through `Unauthenticated`. Histograms carry the `le` label and expose `_bucket`, `_sum`, and `_count`; their buckets are 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, and 10 seconds. A family that counts only failures is absent until its first event. The request families measure at the transport: a request is counted when it reaches the backend as a gRPC request, before authentication, and completed when its response body ends, fails, or is cancelled. The publish families measure decoded input: a position is an envelope of a `PublishRequest` that decoded and reached the publish handler. | Metric | Type | Labels | Meaning | | ------------------------------------------ | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `grpc_server_started_total` | counter | RPC | Incremented once when a gRPC request other than a health request reaches the backend, before authentication. A CORS preflight is not a gRPC request. | | `grpc_server_handled_total` | counter | RPC, `grpc_code` | Incremented once when a counted request’s response body ends, fails, or is cancelled, with the status from its headers or trailers; `Cancelled` when the body was dropped unfinished with no status, `Unknown` when it ended with none. | | `grpc_server_handling_seconds` | histogram | RPC, `grpc_code` | Time from a counted request’s arrival to its response body completion. A stream measures its whole lifetime. | | `grpc_server_in_flight` | gauge | RPC | Counted requests whose response body has not completed. Decremented exactly once per request. | | `grpc_server_request_bytes_total` | counter | RPC | Request body bytes consumed, including gRPC framing, excluding HTTP headers and trailers. | | `grpc_server_response_bytes_total` | counter | RPC | Response body bytes emitted. Emission is not receipt. | | `xmtp_operation_duration_seconds` | histogram | `operation` (a span name from the span catalogue), `status` (`ok`, `error`) | Duration of each operation span from creation to close; `error` when the span recorded an error. | | `xmtp_telemetry_export_failures_total` | counter | none | Export batches that failed. Not a count of lost spans. | | `xmtp_db_released_open_transactions_total` | counter | none | Transactions found open and rolled back when a connection returned to the pool. | | `xmtp_db_errors_total` | counter | `kind` (`timeout`, `invariant`, `connection`, `other`) | Database errors that were mapped to a gRPC status. | | `xmtp_publish_envelopes_total` | counter | `outcome` (`stored`, `duplicate`, `rejected`) | Every position of a decoded publish, counted once by its response origin; `rejected` for every position when the request fails after decoding. | | `xmtp_publish_rejections_total` | counter | `reason` (`REASON_MALFORMED_PAYLOAD`, `REASON_INVALID_KEY_PACKAGE`, `REASON_INVALID_IDENTITY_UPDATE`, `REASON_INVALID_SIGNATURE`, `REASON_TOO_LARGE`, `REASON_HANDLE_TAKEN`, `REASON_HANDLE_NOT_ALLOWED`, `REASON_HANDLE_TOO_SOON`, `REASON_INSTALLATION_TAKEN`) | One per publish rejected by validation, with the `PublishError.reason` it returned. | | `xmtp_scw_verifications_total` | counter | `result` (`valid`, `invalid`, `error`) | One per smart contract wallet verification, including ones answered from the cache. | | `xmtp_stream_sessions` | gauge | `kind` (`bidi`, `static`) | Registered stream sessions. | | `xmtp_stream_topics_registered` | gauge | none | Registered topic interests across all sessions. | | `xmtp_stream_frames_sent_total` | counter | `frame` (`started`, `applied`, `messages`, `keepalive`, `ping`, `pong`, `update`) | Frames admitted to a session’s outbound queue. | | `xmtp_stream_frames_received_total` | counter | `frame` (`update`, `ping`, `pong`) | Frames received from a client on a bidirectional stream. | | `xmtp_stream_envelopes_sent_total` | counter | `phase` (`catch_up`, `live`) | Envelopes admitted to a session’s outbound queue by delivery phase. Admission is not receipt. | | `xmtp_stream_updates_total` | counter | `outcome` (`applied`, `invalid`, `rate_limited`) | Stream interest updates by result. | | `xmtp_stream_ended_total` | counter | `reason` (`client`, `backpressure`, `capacity`, `keepalive`, `tailer`, `database`, `shutdown`, `invalid`, `rate_limited`) | One per registered session, when it ends. | | `xmtp_stream_outbound_wait_seconds` | histogram | none | Time a session waited for outbound capacity. Recorded only when it waited. | | `xmtp_stream_fetch_wait_seconds` | histogram | none | Time a session waited for a fetch permit, including a wait ended by cancellation. | | `xmtp_tailer_polls_total` | counter | `result` (`ok`, `error`) | Read-database polls by result. | | `xmtp_tailer_rows_total` | counter | `source` (`forward`, `gap`) | Rows read by the forward scan and by gap probes. Not unique delivered rows. | | `xmtp_tailer_gap_ranges` | gauge | none | Unresolved sequence id ranges. A count of ranges, not of missing ids. | | `xmtp_tailer_restarts_total` | counter | none | Stream recovery generations started, including the one at startup. | | `xmtp_tailer_ready` | gauge | none | 1 exactly while the backend admits streams under OPS-006. | | `xmtp_boundary_advances_total` | counter | `result` (`ok`, `lock_timeout`, `error`) | Allocation boundary advance attempts by result. | | `xmtp_backend_ready` | gauge | none | 1 exactly while health reports `SERVING`, set in the same step. | | `xmtp_auth_rejections_total` | counter | `reason` (the reasons of the AUTH section 4 table) | One per request rejected under AUTH-014. | | `xmtp_auth_jwks_refresh_total` | counter | `result` (`ok`, `error`) | One per JWKS refresh attempt, by the fetch’s own result. | | `xmtp_auth_keys` | gauge | none | Keys in the key set. | | `xmtp_rate_limit_rejections_total` | counter | `category` (the categories of the RATE category table), `auth_type` (`api_key`, `jwt`, `ip`) | One per denied spend (RATE-010). | | `xmtp_rate_limit_evictions_total` | counter | none | Rate-limit entries forgotten while not at full allowance, because a new caller key had no room where it can be recorded (RATE-051). | | `xmtp_push_recipients_total` | counter | `action` (`registered`, `unregistered`, `expired`, `dead`) | Push recipient changes. | | `xmtp_push_deliveries_total` | counter | `channel` (`apns`, `fcm`, `http`), `outcome` (`delivered`, `failed`, `rejected`, `mismatch`, `dead`, `suppressed`) | Completed push delivery attempts. | | `xmtp_push_dispatcher` | gauge | none | 1 while this instance holds the push dispatcher lock. | | `xmtp_push_subscriptions_total` | counter | `action` (`added`, `removed`) | Push subscription topic changes. | | `xmtp_backend_info` | gauge | `version` | Always 1, with the build version as its label. | The span catalogue names the operation spans an operator measures: the request span, the handler for each RPC, and the stages of a publish, a stream, a poll, and a chain verification. The backend also exports database and internal spans under `db.` whose names follow its own structure; those are diagnostic, are not part of this contract, and are listed in the backend’s documentation. | Group | Span names | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Request | `/` from the route table; `unknown/unknown` for any other path | | RPC handler | `rpc.publish`, `rpc.query`, `rpc.query_newest`, `rpc.get_inbox_ids`, `rpc.verify_smart_contract_wallet_signatures`, `rpc.get_configuration`, `rpc.register`, `rpc.unregister`, `rpc.update_subscriptions`, `rpc.create_upload` | | Publish stages | `publish.parse_publish`, `publish.validate_publish`, `publish.locks`, `db.commit_publish` | | Streams | `tailer.bootstrap`, `tailer.poll`, `stream.fetch`, `stream.update` | | Verification | `scw.verify` | | ID | Title | Requirement | Why | | ------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | OPS-011 | Request id on every response | For every gRPC request, the backend MUST generate a request id, return it in the `x-request-id` response header, ignore any correlation header the caller sent when choosing it, and expose that header to browser callers through CORS. | A support case needs one value that appears in the client’s error and in the operator’s log, and a caller-chosen id lets one caller forge another’s. | | OPS-012 | Trace context is accepted | When a request carries `traceparent` and `tracestate` headers ([Trace Context §3](https://www.w3.org/TR/trace-context/#trace-context-http-headers-format)), the backend MUST make that context the parent of the request span, and MUST accept a CORS preflight that names those headers. | | | OPS-013 | Deployment identity in telemetry | The backend MUST carry the deployment identifier as the resource attribute `xmtp.backend.identifier` on every exported span, and as the field `identifier` on every request completion log and every auth rejection log, and MUST carry `service.name` (`telemetry.service_name`, default `xmtp-backend`) and `service.version` (the build version) on every exported span. | One collector stream carries several deployments; without the identifier a line cannot be attributed. | | OPS-014 | No request data in telemetry | The backend MUST NOT place in a metric name, a metric label, a span field, or a log field a topic, an inbox id, an installation key, a group id, a cursor, a payload, a handle that a claim or a lookup names, a request header value, a client or peer network address, or any value computed from one of those that identifies it, except the trace context under OPS-012, the request id, and an API key name under AUTH-028. A byte count, a duration, a count of items, and a value from a label vocabulary the catalogue fixes MAY be recorded, and a reader of telemetry MUST NOT rely on any other field. | A label is kept far longer than the message it names and is read by people the message was never sent to. | | OPS-015 | Export never stops serving | When the OTLP collector is unreachable or an export batch fails, the backend MUST continue to serve and record metrics, and MUST count the failed batch in `xmtp_telemetry_export_failures_total`. | | | OPS-016 | Metrics exposition | While `telemetry.metrics_listen` is not empty, the backend MUST serve the Prometheus text exposition format on that address, with every family in the metric catalogue described by the name and type shown. While it is empty, the backend MUST serve no metrics listener and MUST keep recording. | | | OPS-017 | Catalogue semantics | The backend MUST record each family in the metric catalogue as its Meaning column states, with only the label names and label values the Labels column gives, and MUST NOT emit a label value outside that vocabulary. | An unbounded label value creates a series per user and takes the metrics store down. | | OPS-018 | Request completion events | While `server.request_logger` is `true` (the default) and the configured log level admits `INFO`, the backend MUST emit one completion log per gRPC request other than a health request, when the response body ends, fails, or is cancelled, carrying `request_id`, `identifier`, `method` (the request path), `duration_ms`, `request_size_bytes`, `response_size_bytes`, `grpc_code`, and `trace_id` when a trace context exists. The byte fields MUST count body bytes consumed and emitted, not headers or trailers. | | | OPS-019 | Span names | The backend MUST name the operation spans in the span catalogue as shown, MUST export the request span under its route table name, and MUST record `xmtp_operation_duration_seconds` with `operation` equal to the operation span’s name. | Dashboards and alerts are written against these names. | | OPS-022 | Telemetry configuration checks | When the OTLP endpoint resolved from `telemetry.otlp_endpoint`, or from `OTEL_EXPORTER_OTLP_ENDPOINT` when the key is absent, is not an HTTP or HTTPS URL with a host, the backend MUST refuse to start, naming the key or the variable and not its value. When `telemetry.metrics_listen` names an address the backend cannot bind, the backend MUST refuse to start and MUST name that address. When no endpoint resolves, the backend MUST NOT export traces. | A backend that starts with a broken exporter loses every trace silently; one that starts without its metrics listener is invisible to the alerts written against it. | ## Known limitations No envelope is deleted after its expiry today. `expiry_ns` is set under API-212 and OPS-001 and OPS-002 hold, but a row past its expiry stays readable for as long as the database keeps it, and an operator bounds storage outside the backend. A deletion of expired envelopes would let anyone who saved a signed group message from a topic of kind `0x00` publish it again as a new envelope, because the signature never expires and the duplicate check needs the stored row. A design that deletes such envelopes keeps the topic and `message_hash` of each one it deletes, and refuses a publish that matches them. `SERVING` reports that the instance can take requests, not that any client can reach it or that a message it accepted was delivered. A balancer’s health check and an end-to-end probe measure different things. Shutdown reports `NOT_SERVING`, closes admission, and ends streams as one step, not in a promised order. A balancer that polls health can route one more request to a draining instance and see `UNAVAILABLE`. At the drain deadline a connection still carrying a request is aborted, and that request ends with no gRPC status at all. The backend exposes no sampled gauges: no pool size, queue depth, replica replay delay, or process resource usage. Those belong to infrastructure monitoring. In particular, a lagged copy that has stopped receiving changes is not visible in any backend metric. The backend trusts its configured chain providers for smart contract wallet verdicts and for the size of their responses. It does not check a provider’s answer against another source or bound the size of a response body, so an operator configures only providers it trusts. `xmtp_operation_duration_seconds` derives its `status` from whether the span recorded an error. A cancellation that recorded none is `ok`, so the label is not an exact success rate. Client-side trace metrics derived by a collector from exported spans scale with the configured sample ratio and with export loss. They are estimates, unlike the in-process families above. # Group permissions Every change to a group’s shared state after creation is a proposal a member signs, and a policy decides whether that member may make it. The policies live in the group itself: the component registry is one component of the group’s app-data dictionary, so the rules travel inside the group context, every member reads the same rules, and a change to the rules is a change to the group that the same engine judges. A client that evaluates a policy differently from the others accepts a commit they reject, or rejects one they accept, and the group forks. The engine has three inputs: the proposer’s roles, read from the admin and super-admin lists as they stood before the commit; the operation, which is an insert, an update, or a delete of one element of one component; and the policy the registry stores for that component and operation. Two components are not governed by the registry, because the registry depends on them: the registry itself and the super-admin list are super-admin-only, except that either DM participant may change application registry entries under PERM-026. Membership changes carried as MLS Add and Remove proposals are judged by the membership component’s policies, so one policy governs a member’s presence however the change is carried. ```mermaid flowchart TD P[Proposal from a member's leaf] --> R[Proposer's roles from the
pre-commit admin lists] P --> E[Expand into element changes:
insert, update, delete] E --> C{Component id} C -->|registry or super-admin list| H[Super admin only,
or a DM participant under PERM-026] C -->|existing immutable component| X[Reject under META-004] C -->|any other| L{Registry entry} L -->|none| X L -->|present| Q[Policy for the operation] R --> Q H --> D{Allowed} Q --> D D -->|yes| A[Apply with the commit] D -->|no| X ``` ## Scope In scope: the roles and the components that hold them; the policy language and how it is evaluated; how a write to a component is authorised, including membership changes carried as MLS proposals; what a valid registry is and how an app changes a policy; the non-DM presets and their recognition; authority to act on leave requests; and compatibility across changes to commit acceptance. Out of scope: when the engine runs and what a rejected commit does to the group (`GMOD`); component identifiers, the dictionary, registry structure, component types, and byte limits (`META`); fixed DM policies and the participant-add exception (DMS-002 and DMS-004); exact identity state (IDENT-070); and what a Welcome carries (`JOIN`). | Related | Relation | | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `GMOD` | Owns the commit validation pipeline that invokes this engine, the membership component, and the protocol-version floor. GMOD-059 states which proposal types reach the engine. | | `META` | Owns all component ids and ranges, the `ComponentMetadata` and `ComponentPermissions` messages, registry structure, and application of component deltas. | | `DMS` | DMS-002 owns the fixed policies and initial roles; DMS-004 owns the participant-add exception used in section 3. | | `EVENT` | EVENT-001 reports a changed policy set or admin list through `conversation.metadata_changed`. | ## Terms | Term | Meaning | | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Component | One entry of a group’s app-data dictionary, named by a component id. Its value is bytes whose shape the registry’s `component_type` names. Owned by META section 2. | | Component id | The identifier assigned under META section 1. Components are named symbolically here. | | Registry | `COMPONENT_REGISTRY`: maps component ids to `ComponentMetadata`. Its `permissions` field carries the policies this spec evaluates. | | Admin list | `ADMIN_LIST`: the set of inbox ids that are admins. | | Super-admin list | `SUPER_ADMIN_LIST`: the set of inbox ids that are super admins. | | Admin | An inbox that is in the admin list. A super admin is not an admin unless it is also in the admin list, but every rule that admits an admin admits a super admin. | | Super admin | An inbox that is in the super-admin list. | | Proposer | The member whose leaf node signed a proposal. | | Committer | The member whose leaf node signed a commit. | | Element change | One insert, update, or delete of one element of a component, as section 3 derives it from a proposal. | | Action policy | One of the four registry policies that govern membership and the admin list: `insert_policy` and `delete_policy` of the membership component, and `insert_policy` and `delete_policy` of the admin list. | | Preset | One of the preconfigured policy sets of section 5. | ## 1. Roles A group has three tiers: members, admins, and super admins. The two lists are components, so a change to a list is a proposal the engine judges like any other, and a receiver reads the roles from the group context it holds. The group’s creator starts as the only super admin. There is no other standing role: the creator’s inbox id is recorded in the group but grants nothing after creation. Roles are read from the committed group context, never from a proposal inside the commit being judged. A commit that adds an inbox to the super-admin list and, in the same commit, has that inbox write a super-admin-only component is rejected, because the write is evaluated against the lists as they stood before the commit. Two rules protect the top tier from the tiers below it. A super admin cannot be removed from the group, whatever the remove-member policy says, so an admin who was delegated removals cannot remove the person who delegated them. The super-admin list cannot be emptied, so a group never reaches a state in which nobody can change its rules. A super admin can remove itself from the list while another super admin remains. | ID | Title | Requirement | Why | | -------- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | | PERM-001 | Roles from the committed lists | The client MUST take a proposer’s admin status from the admin list and its super admin status from the super-admin list of the committed group context, and MUST NOT take either from a proposal in the commit being judged. | A commit that grants a role and uses it in one step would let any member escalate. | | PERM-002 | The creator is the first super admin | When a client creates a group whose conversation type is not DM, it MUST write the super-admin list containing only the creator’s inbox id and the admin list empty. | | | PERM-003 | Super admins stay members | If a commit removes from the membership component an inbox that is in the super-admin list, then the client MUST reject the commit, whatever the membership component’s `delete_policy` says. | An admin who could remove the super admins takes the group from them. | | PERM-004 | The super-admin list never empties | If a proposal would change a super-admin list that is not empty into one that is empty, then the client MUST reject it. | A group with no super admin has nobody who can change its rules, and no rule can restore one. | | PERM-026 | Protect registry and roles | When a proposal writes `COMPONENT_REGISTRY` or `SUPER_ADMIN_LIST`, the client MUST reject it unless the proposer is a super admin under PERM-001; in a DM, it MUST also allow either `DM_MEMBERS` participant to insert, update, or delete registry entries only when every changed ID is in `0xC000`–`0xFEFF`. It MUST NOT extend that DM exception to `SUPER_ADMIN_LIST` or well-known registry entries. | A DM has no listed super admin, but a registry exception must not grant control of its roles or membership. | ## 2. The policy language A policy is a `MetadataPolicy`: a base policy, or a condition over child policies. A component’s entry in the registry carries three of them, one for each operation. ```proto // A policy that governs updating metadata message MetadataPolicy { // Base policy enum MetadataBasePolicy { METADATA_BASE_POLICY_UNSPECIFIED = 0; METADATA_BASE_POLICY_ALLOW = 1; METADATA_BASE_POLICY_DENY = 2; METADATA_BASE_POLICY_ALLOW_IF_ADMIN = 3; METADATA_BASE_POLICY_ALLOW_IF_SUPER_ADMIN = 4; METADATA_BASE_POLICY_ALLOW_IF_SELF_OR_NON_MEMBER = 5; } // Combine multiple policies. All must evaluate to true message AndCondition { repeated MetadataPolicy policies = 1; } // Combine multiple policies. Any must evaluate to true message AnyCondition { repeated MetadataPolicy policies = 1; } oneof kind { MetadataBasePolicy base = 1; AndCondition and_condition = 2; AnyCondition any_condition = 3; } } ``` META section 2 defines `ComponentPermissions` and its three policy fields. The `MetadataPolicy` block above is the policy language used by those fields. A base policy reads the authenticated proposer, its roles, the element operation and key, and the membership after the commit. It never reads the value being written. | Base policy | Allowed when | | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `METADATA_BASE_POLICY_ALLOW` | Always | | `METADATA_BASE_POLICY_DENY` | Never | | `METADATA_BASE_POLICY_ALLOW_IF_ADMIN` | The proposer is an admin or a super admin | | `METADATA_BASE_POLICY_ALLOW_IF_SUPER_ADMIN` | The proposer is a super admin | | `METADATA_BASE_POLICY_ALLOW_IF_SELF_OR_NON_MEMBER` | For a `TLS_MAP_INBOX_ID_BYTES` or `TLS_MAP_INBOX_ID_STRING` element, Insert or Update: proposer inbox equals the element’s key; Delete: proposer inbox equals the key or the key is absent from the membership after the commit. When a standalone proposal is validated on receipt, the absence test uses the committed membership. Deny for whole-component Remove and all other component types. | `METADATA_BASE_POLICY_ALLOW_IF_SELF_OR_NON_MEMBER` is an ordinary registry policy. A super admin can replace it on an application mutable-range entry, and META-015 still prevents changes to immutable-range entries. A delete that needs the membership after the commit is inline in the member-removal commit and is validated there under GMOD-019; a standalone proposal is judged against the committed membership. A policy can be malformed: no `kind`, a `base` value the table does not list, or a condition with no children. A malformed policy denies. Evaluation of a condition stops at the first child that decides it, and a malformed child that is reached decides it as denied, so two clients that evaluate the same tree in the same order reach the same answer. | ID | Title | Requirement | Why | | -------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | | PERM-027 | Evaluate base policy context | When the client evaluates a `MetadataPolicy.base`, it MUST use the base-policy table in section 2 with the authenticated proposer, the element operation and key, and the membership after the commit that carries the proposal, whether inline or by reference; when it validates a standalone proposal on receipt, it MUST use the committed membership. | A self-owned policy cannot be judged from role flags or map values alone. | | PERM-007 | Condition semantics | The client MUST evaluate the children of an `and_condition` in order and stop at the first child that is denied or malformed, with that child’s result, and MUST evaluate the children of an `any_condition` in order and stop at the first child that is allowed or malformed, with that child’s result. An `and_condition` whose children are all allowed MUST be allowed, and an `any_condition` whose children are all denied MUST be denied. | Two clients that stop at different children reach different answers for the same tree. | | PERM-008 | A malformed policy denies | When the policy that governs a write has no `kind`, has a `base` value not in the table above, or is a condition with no children, the client MUST deny the write. | A policy that fails open turns a corrupt registry entry into an open door. | ## 3. Authorising a write A proposal that writes a component is an `AppDataUpdate` proposal, defined in [draft-ietf-mls-extensions-08 §4.7](https://www.ietf.org/archive/id/draft-ietf-mls-extensions-08.html#section-4.7), whose operation is `Update` with a payload or `Remove`. The client first turns the proposal into element changes, because a delta to a set or a map can insert one element and delete another in one proposal, and the two operations can have different policies. The registry entry’s `component_type` says how the payload is read; META-010 owns component types and encodings. PERM-014 owns authorization of a component with no built-in definition; META-010 owns its type-based decoding and application. | Component type | Operation on the wire | Element changes | | ---------------------------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | A scalar (`COMPONENT_TYPE_BYTES`, `COMPONENT_TYPE_STRING`) | `Update` | One update, whether or not the component already has a value | | A scalar | `Remove` | One delete | | A set or a map | `Update` carrying a delta | One change per mutation in the delta: an insert for an insert, an update for an update, a delete for a remove, a remove-by-hash, or a delete | | A set or a map | `Update` carrying a delta with no mutations | One insert of the whole component, with no key, when the component has no value; one update of the whole component, with no key, when it has one | | A set or a map | `Remove` | One delete | META section 1 owns component id ranges. META-004 rejects writes to an existing immutable component, including insertion into an existing immutable collection. META-014 and META-015 own registry structure and immutable registry entries. These checks apply before policy evaluation; an allowing policy cannot bypass them. Every other component is governed by its registry entry, and a component with no entry is denied to everyone. The entry is read from the committed registry, so registering a component and writing it are two commits; the same rule keeps a commit from changing a policy and using the changed policy in one step. A client that predates a component still has the registry entry, and evaluates the write under it rather than refusing what it does not know, because a refusal the other members do not share is a fork. MLS Add and Remove proposals use the membership component’s policies. For an inbox added or removed by a commit, every corresponding proposal retains its own proposer, including when several proposals name installations of that inbox. A change limited to installations of an inbox that remains a member is checked under GMOD and the membership entry’s update policy. An inline proposal has the committer as proposer under [RFC 9420 §12.4.2](https://www.rfc-editor.org/rfc/rfc9420.html#section-12.4.2). A DM has no listed super admin. PERM-026 lets either `DM_MEMBERS` participant change application registry entries, and PERM-028 lets it satisfy `ALLOW_IF_SUPER_ADMIN` on application components. Neither grants a role, changes DM membership, or reaches a well-known component. DMS-004 owns the participant-add exception. That exception takes precedence over denial by the membership insert policy in both the Add path and the dictionary-insert path. It uses the proposer under PERM-009 in both paths and at final membership validation. It does not bypass structural checks or authorize another mutation in the same proposal. | ID | Title | Requirement | Why | | -------- | -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | PERM-009 | Judge each authenticated proposer | When the client evaluates a proposal, it MUST use that proposal’s authenticated proposer and the roles under PERM-001, including when other proposals name the same inbox. It MUST NOT substitute another proposal’s proposer or the committer when that actor differs. | A committer or a second proposer cannot lend authority to another member’s proposal. | | PERM-010 | The committed registry decides | The client MUST read the registry entry that governs a write from the committed group context, so that a component registered or a policy changed in the same commit does not govern a write in that commit. | | | PERM-011 | Operation selects the policy | For each element change, the client MUST select `insert_policy`, `update_policy`, or `delete_policy` under the element-change table above and MUST reject the proposal if any selected policy denies, except for the membership insertion authorized by DMS-004. | | | PERM-012 | Deny by default | When a write targets a component other than `COMPONENT_REGISTRY` or `SUPER_ADMIN_LIST` and the committed registry has no entry that decodes as a `ComponentMetadata` with all three policies present, the client MUST reject the write. | | | PERM-014 | Unknown components are judged, not refused | When a proposal names a component the client has no built-in definition for, the client MUST evaluate it under the committed registry entry’s `component_type` and policies, and MUST NOT reject it because the component is unknown. | A client that refuses what it does not know forks the group at the first component a newer release adds. | | PERM-028 | DM application policy role | When a proposer whose inbox is in a DM’s `DM_MEMBERS` writes an application component, the client MUST evaluate `ALLOW_IF_SUPER_ADMIN` and `ALLOW_IF_ADMIN` as allowed for that proposer, without granting that role for well-known components or membership changes. | A DM’s empty super-admin list would otherwise make application policies that use this option impossible to satisfy. | | PERM-015 | Membership proposals use membership policies | When a commit adds or removes an inbox from `GROUP_MEMBERSHIP`, the client MUST evaluate the corresponding `insert_policy` or `delete_policy` against each proposer of an Add or Remove for that inbox under PERM-009 and reject a denial, subject to DMS-004 for adds and PERM-003 for removals. The client MUST apply the same policy checks to each standalone Add or Remove proposal. | | | PERM-030 | Leafless removal uses its delete | When a commit removes from `GROUP_MEMBERSHIP` an inbox that no leaf node’s credential names before the commit, the client MUST judge that removal under PERM-015 with the authenticated proposer of the `AppDataUpdate` that deletes the inbox’s entry in place of a Remove proposer. | An inbox whose installations all failed has no leaf and so no Remove. Without this rule no member can remove it, and it keeps counting toward `max_group_members`. | ## 4. The registry A registry entry is validated when it is written, so that a corrupt entry never enters the committed registry and every later commit can be judged. The four action policies are validated as complete trees whenever a commit writes the registry, because a commit that leaves one of them malformed would make every later membership or admin change undecidable for every member. The admin list is constrained: its policies are base policies of deny, admin, or super admin, because unrestricted admin assignment would let a member grant itself every admin permission. PERM-026 separately protects the super-admin list. The registry is written by super admins only, and in a DM by either participant for application entries (PERM-026); no stored value changes that. The permission to update permissions is the super-admin role itself. An app changes a policy through its SDK, which names the action or the metadata field and a policy option; the client writes the registry field the table below names. META section 2 assigns the metadata component ids. | App operation | Component | Registry field | Accepted options | | ----------------------- | ---------------------- | ----------------------------------- | ----------------------------------------- | | Add member | `GROUP_MEMBERSHIP` | `insert_policy` | Allow, Deny, Admin only, Super admin only | | Remove member | `GROUP_MEMBERSHIP` | `delete_policy` | Allow, Deny, Admin only, Super admin only | | Add admin | `ADMIN_LIST` | `insert_policy` | Deny, Admin only, Super admin only | | Remove admin | `ADMIN_LIST` | `delete_policy` | Deny, Admin only, Super admin only | | Update a metadata field | That field’s component | `insert_policy` and `update_policy` | Allow, Deny, Admin only, Super admin only | | Policy option | Written as | | ---------------- | ------------------------------------------- | | Allow | `METADATA_BASE_POLICY_ALLOW` | | Deny | `METADATA_BASE_POLICY_DENY` | | Admin only | `METADATA_BASE_POLICY_ALLOW_IF_ADMIN` | | Super admin only | `METADATA_BASE_POLICY_ALLOW_IF_SUPER_ADMIN` | | ID | Title | Requirement | Why | | -------- | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | PERM-017 | Action policies stay well-formed | If the registry a commit produces has no entry for the membership component or the admin list, or an action policy in it is malformed under PERM-008 or is `METADATA_BASE_POLICY_ALLOW_IF_SELF_OR_NON_MEMBER` at any node, or an admin list policy is not a `base` of `METADATA_BASE_POLICY_DENY`, `METADATA_BASE_POLICY_ALLOW_IF_ADMIN`, or `METADATA_BASE_POLICY_ALLOW_IF_SUPER_ADMIN`, then the client MUST reject the commit. | Every later membership or admin change would be undecidable, and a group whose commits cannot be judged is stuck for every member. | | PERM-018 | Changing a policy | An SDK MUST let an app set each policy in the app-operation table to an option accepted for that operation, encoded under the policy-option table in the named registry fields. It MUST reject Allow for Add admin or Remove admin. | | ## 5. Preconfigured policy sets An app creates a non-DM group with All members, Admins only, or custom policies. The creation table states all three policies for each governed component. Allow, Deny, Allow if admin, and Allow if super admin denote the base values in section 2. DMS-002 owns DM creation, including its fixed policies and empty role lists. | Governed policy | All members | Admins only | | --------------------------------------------------------------- | -------------------- | -------------------- | | Membership: insert | Allow | Allow if admin | | Membership: update | Allow | Allow | | Membership: delete | Allow if admin | Allow if admin | | Admin list: insert, update, delete | Allow if super admin | Allow if super admin | | Group name, description, image URL, app data: insert and update | Allow | Allow if admin | | Disappearing-message settings, both fields: insert and update | Allow if admin | Allow if admin | | Minimum protocol version: insert and update | Allow if super admin | Allow if super admin | | Each metadata field above: delete | Allow if super admin | Allow if super admin | | Commit-log signer: insert, update, delete | Allow if super admin | Allow if super admin | | Each immutable component: insert | Allow if super admin | Allow if super admin | | Each immutable component: update and delete | Deny | Deny | The registry and super-admin list have no registry policies; PERM-026 applies. PERM-029 sets the policies of `USER_DISPLAY_NAME` and `GROUP_IMAGE`. META section 2 owns which component values exist at creation. Preset recognition reports a policy view, not equality of the registry. The recognition table lists every comparison. Policies compare as ordered trees, including their base values and condition kinds. Metadata policies with a missing field or any malformed node are represented as Deny in this view. An `ALLOW_IF_SELF_OR_NON_MEMBER` node, which always denies on a scalar metadata field, is represented as Deny in place, and its sibling nodes keep their values. Invalid action policies fail under PERM-017. | Policy in the recognition view | Comparison | | -------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | | Membership insert and delete | Equal to the preset’s creation policies | | Admin-list insert and delete | Equal to the preset’s creation policies | | Group name, description, image URL, app data, both disappearing-message fields, and minimum protocol version: update | Equal to the preset’s creation policies | | Authority to change permissions | Super admin under PERM-026 | Membership and admin-list update policies, metadata insert and delete policies, commit-log signer policies, immutable-component policies, and application-component policies are absent from this view. A change to one of them can leave the reported preset unchanged. There is no DM preset result. | ID | Title | Requirement | Why | | -------- | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | | PERM-019 | A preset writes the table | When the client creates a non-DM group with a preset, it MUST write the registry with every policy in that preset’s creation-table column. | A preset chosen on one SDK must give every member the same rules. | | PERM-029 | Core field creation policies | When a client creates a group or DM, it MUST set `USER_DISPLAY_NAME` insert, update, and delete policies to `ALLOW_IF_SELF_OR_NON_MEMBER`; for a group it MUST set `GROUP_IMAGE` insert, update, and delete policies equal to the respective `GROUP_IMAGE_URL` policies selected at creation. | New members must evaluate writes to the new well-known fields under the same rules. | | PERM-024 | Recognise the exposed policy view | When an SDK reports a preset, it MUST report All members or Admins only exactly when the recognition view above equals that preset, and MUST report no preset when neither matches. | An app needs a stable meaning for the reported name even when the registry holds other policies. | ## 6. Authority to process leave requests GMOD section 7 owns requesting leave, authenticating the requester, and completing removal. A request does not grant permission to remove a member. The responder still uses the group’s committed roles and membership policy. | ID | Title | Requirement | Why | | -------- | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | | PERM-025 | Leave responders need authority | When the client acts on a pending leave request by publishing a removal commit, it MUST do so only if its own inbox is a super admin under PERM-001 and the removal is authorized under PERM-003 and PERM-015. | A leave request does not grant its reader a role or override a membership policy. | ## 7. Introducing a new rule A group’s policies outlive each client version. PERM-014 permits new components whose registered type and policies existing members already understand. A change that makes clients accept different commits needs a version floor before it is used. This includes a new policy value or condition kind, component type, registry encoding, delta mutation, or validation invariant. The required version is the lowest semantic client version that implements every changed rule the commit depends on. With multiple changed rules, it is the greatest of their first supported versions under GMOD-027. The preceding floor-raising commit uses only rules supported by clients at the old floor. GMOD-022 and GMOD-025 own its validation and the pause it causes. Active group creation and commit validation use the dictionary and registry. Legacy extension readers, builders, migration helpers, and fixtures do not establish acceptance of those extensions in this workflow. | ID | Title | Requirement | Why | | -------- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------- | | PERM-023 | Changed acceptance follows the floor | Before publishing a commit that depends on a change under which older and newer clients accept different commits, the client MUST ensure that an earlier commit has set the group’s floor to at least the required version defined above. The floor-raising commit MUST use only rules supported at the preceding floor. | A same-commit raise cannot protect an older client that cannot validate the new rule. | ## Known limitations A client can check a component-specific invariant only when it implements that invariant. Registry policy evaluation alone cannot prevent different acceptance decisions. PERM-023 applies to these changes as well as new encodings. Clients that predate the element-change row for a set or map `Update` whose delta has no mutations apply such a write with no policy check, while newer clients judge it under PERM-011 as one write of the whole component. A member whose policy denies that write can publish one, standalone or inline in its own commit. Older clients apply the inline commit and keep the standalone proposal, and a later commit of theirs that carries it by reference is one that older clients apply and newer clients reject. Without a version floor (PERM-023), the group forks between them, so a group whose floor is below `8.0.0-0` can fork this way. An older client’s own write causes this when its app sends an empty delta for a component its policy denies, such as an absent self-owned map. Evaluation stops at the first child that decides a condition (PERM-007), so an `any_condition` with an allowing child ahead of a malformed one allows a write. The projection an SDK reports to an app validates the whole tree and reports a malformed metadata policy as deny, so the app can read deny for a field a write to which succeeds. The action policies do not have this gap, because PERM-017 keeps them well-formed at every node. Legacy groups that carry no app-data dictionary do not satisfy this workflow. Their extension encodings are not an alternate source of authorization here. The creator’s inbox id is recorded in an immutable component but confers no role. A creator that removes itself from the super-admin list is an ordinary member. # Prefix registry Every requirement identifier begins with a prefix registered here. The checker reads this table: a prefix that is not listed is an error, and a requirement identifier whose prefix is listed but whose number does not resolve to a current requirement is a stray mention (SPEC-053). A prefix appears exactly once. A prefix whose document was deleted is removed from this file once no mention of its identifiers remains in the tree, so a stale mention is fixed rather than hidden. ## Active | Prefix | Spec | File | | ------- | ------------------------------- | ------------------------------------------ | | `SPEC` | Specification format | `docs/specs/SPEC-spec-format.md` | | `TOPIC` | Topic format | `docs/specs/TOPIC-topic-format.md` | | `API` | Backend API contract | `docs/specs/API-backend-api.md` | | `CONF` | Backend configuration | `docs/specs/CONF-backend-configuration.md` | | `AUTH` | Backend auth | `docs/specs/AUTH-backend-auth.md` | | `OPS` | Backend operations | `docs/specs/OPS-backend-operations.md` | | `PUSH` | Push subscriptions and webhooks | `docs/specs/PUSH-push-subscriptions.md` | | `IDENT` | Identity updates | `docs/specs/IDENT-identity-updates.md` | | `JOIN` | Joining groups | `docs/specs/JOIN-joining-groups.md` | | `GMOD` | Modifying groups | `docs/specs/GMOD-modifying-groups.md` | | `PERM` | Group permissions | `docs/specs/PERM-group-permissions.md` | | `META` | Group metadata and app data | `docs/specs/META-group-metadata.md` | | `DMS` | DMs and stitching | `docs/specs/DMS-direct-messages.md` | | `PROC` | Message processing | `docs/specs/PROC-message-processing.md` | | `SEND` | Message sending | `docs/specs/SEND-message-sending.md` | | `FORK` | Fork recovery and commit log | `docs/specs/FORK-fork-recovery.md` | | `CONS` | Consent | `docs/specs/CONS-consent.md` | | `SYNC` | Device sync | `docs/specs/SYNC-device-sync.md` | | `ARCH` | Archive format | `docs/specs/ARCH-archive-format.md` | | `CTYPE` | Content types | `docs/specs/CTYPE-content-types.md` | | `STORE` | Client storage | `docs/specs/STORE-client-storage.md` | | `ATCH` | Remote attachments | `docs/specs/ATCH-remote-attachments.md` | | `EVENT` | Client events | `docs/specs/EVENT-client-events.md` | | `LOG` | Client logging | `docs/specs/LOG-client-logging.md` | | `RATE` | Backend rate limits | `docs/specs/RATE-backend-rate-limits.md` | \| `MIG` | Legacy database migration | `docs/specs/MIG-legacy-database-migration.md` | ## Reused prefixes and their floors `API` and `PUSH` are reused by their replacements: the deleted documents `001_backend_api.md` and `005_push_subscriptions.md` used those prefixes, and the new specs take them over. A reused prefix keeps its historical number space. An identifier that already meant something must never come to mean something else, or every past pull request, commit message, and review comment becomes ambiguous, and no cleanup of current code can repair that history. A replacement spec therefore allocates above the floor below, and reuses a historical number only when it carries the same obligation as before. | Prefix | Highest number the deleted document used | First number a replacement may allocate | | ------ | ---------------------------------------- | --------------------------------------- | | `API` | `API-165` | `API-200` | | `PUSH` | `PUSH-105` | `PUSH-200` | The floors are round numbers above the highest number those documents used, so no replacement requirement can take a number that already meant something else. # Message processing A client receives envelopes, processes them in topic order, and delivers stored messages to an app. Receipt, processing, and app acknowledgement are separate progress measures. A connection failure or a crash must not turn one into another. The backend supplies ordered topic prefixes under API-201, API-240, and API-254. The client preserves received work until it applies or rejects it. GMOD, JOIN, and IDENT own payload validation; this spec owns progress and the effect of a validation result on pending work. ## Scope In scope: receipt validation; durable receipt and processing positions; rejection and retry; operation targets and completion; capacity; stream recovery; and stored-message delivery with app acknowledgement. Out of scope: backend wire formats and errors (API); commit and proposal validation (GMOD); Welcome validation (JOIN); identity validation (IDENT); publishing (SEND); fork recovery (FORK); consent states (CONS); and topic format (TOPIC). | Related | Relation | | ------- | ---------------------------------------------------------------------------------------------------------------- | | API | Owns ordered reads and authoritative envelope metadata. This spec owns client validation, receipt, and recovery. | | JOIN | Owns Welcome validation, retention deadlines, and the join anchor. This spec owns pending work and completion. | | GMOD | Owns commit and proposal validation. This spec owns whether a failure advances processing. | | SEND | Owns outgoing attempts. This spec owns ordered receipt of their echoes. | | AUTH | Owns credential failures and lockout. This spec owns recovery for other connection failures. | | EVENT | EVENT-001 reports stored message changes to an app; this spec owns durable receipt and stream delivery. | ## Terms | Term | Meaning | | -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Received position | `F(topic)`: the highest sequence id through which the retained topic prefix after the starting anchor is durably pending or already handled. Sequence ids can have gaps. | | Processed position | `P(topic)`: the highest sequence id through which every group or identity envelope after the starting anchor is applied or terminally rejected. Welcome topics have no `P`; their progress is `F` and the unresolved Welcome ids. | | Pending envelope | An admitted envelope not yet applied or terminally rejected. | | Head | The pending envelope with the lowest sequence id on a group or identity topic. | | Admission | Acceptance of an ordered prefix as durable received work. | | Target | `H(topic)`: the fixed sequence id through which one operation waits for processing. Absent means target capture has not succeeded; zero means a sampled topic was empty. | | Terminal rejection | A recorded refusal that completes an envelope without applying it. | | Held | Pending work that cannot advance processing, including invalid identity history and failures with no safe rejection rule. | | Scope generation | A distinct revision of one operation’s selected topics and discovery obligations. | | Delivery number | An immutable, increasing local number assigned when a message first becomes deliverable. | | Delivery position | `D(group)`: the last delivery number acknowledged or excluded by the default consumer’s filter; zero before either occurs. | | Delivery cursor | A database identity and a delivery number, meaning resume strictly after that item. | | Default consumer | The one message reader per client database that advances `D`. | | Replay reader | A reader started from an app-supplied delivery cursor, independent of `D`. | | Full stored message result | A message returned by lookup, history, refresh, or a message reader, excluding reaction and reply-parent summaries nested in enrichment. | | Acknowledgement | The app’s callback returns normally, or the app requests the next iterator item. | | Recovery episode | The interval from a stream’s initial connection or detected failure until sustained network recovery or termination. | ## 1. Durable receipt `Subscribe`, `SubscribeStatic`, and `Query` supply ordered prefixes. Overlap on reconnect is normal. A batch can start at or below `F`, but not above it: the latter leaves an unfetched part of the log. Numeric gaps do not imply missing envelopes because API-287 makes sequence ids unique across topics. A target names work to fetch. It does not establish receipt. Push metadata, a publish receipt, a registration target, and a newest-envelope result can all supply targets without supplying the prefix below them. The backend hash is authoritative under API-211; a client re-encoding is not a check of that hash. | ID | Title | Requirement | Why | | -------- | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | | PROC-001 | Validate every received prefix | When the client admits envelopes from an ordered read, it MUST validate the topic, `cursor.sequence_id` under API-286 and `server_ns` between 0 and 9223372036854775807 inclusive, the 32-byte SHA-256 hash shape of API-211, an exclusive start at or below `F`, and strictly increasing per-topic sequence ids across batches from that registration or query. If any check fails, it MUST refuse the batch without changing received work or `F`; otherwise it MUST preserve the backend hash unchanged without comparing it to a local recomputation. | A skipped prefix loses messages; a changed hash breaks envelope identity. | | PROC-002 | Receipt survives interruption | When the client advances `F`, it MUST durably retain every unhandled envelope through that position without duplicate admission effects, and MUST leave both received work and `F` unchanged if admission fails. It MUST retain each admitted serialized `ServerEnvelope` byte-for-byte as received from the backend, including unknown protobuf fields; decoding for validation or processing MUST NOT replace those retained bytes. Except for a valid join under PROC-010, it MUST NOT advance `F` from a target or past an envelope it has not durably received, and MUST NOT move `F` backwards. | A position without the received work makes a crash lose messages. | | PROC-036 | Protect retained envelopes | While the client retains pending envelopes, it MUST apply the client database’s encryption and access protection to them and MUST NOT log raw payloads, private keys, or database keys. | Receipt must not expose data that message storage protects. | ## 2. Ordered processing Group and identity processing completes a prefix. A held head blocks later envelopes on that topic. Independent topics and independent Welcomes can still progress. Processing a received envelope can produce messages, update group state, or reject input without producing either. `P` never exceeds `F`. A closed stream can leave `F` above `P`: the client has stored ciphertext that it has not processed. CONF-075 closes streams with network interest when the connection is blocked; it does not erase that work or require the two positions to be equal. JOIN section 7 compares its anchor with `P`, not with `F`. A valid Welcome starts or resumes the group at its join anchor under JOIN-046. Envelopes below that anchor do not belong to the installed membership; envelopes above it remain work for that membership. | ID | Title | Requirement | Why | | -------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | | PROC-005 | Process a topic prefix | When the client processes a group or identity topic, it MUST apply or terminally reject the head before a later envelope, and MUST advance `P` only through that handled prefix, without moving it backwards or above `F`. After a commit removes this installation, it MUST stop processing later group envelopes, retain them, and resume only after a valid rejoin under JOIN section 7. | Out-of-order state changes fork the group. | | PROC-008 | Effects survive interruption together | After an interrupted processing attempt, the client MUST expose either all of the envelope’s effects with its completed processing position or none of them, and MUST apply each envelope’s effects at most once across retries and concurrent clients sharing the database. | Partial or repeated effects lose state or duplicate messages. | | PROC-010 | Preserve the join boundary | When the client installs group state at anchor `A` under JOIN-046, it MUST establish `F` as the greater of its previous value and `A`, discard pending group envelopes at or below `A`, and retain those above `A`, with the installed state. | Discarding work above the anchor loses messages sent while the Welcome was in flight. | ## 3. Rejection and held work A terminal group rejection needs a complete preceding prefix and the state needed to validate it. An error’s retry flag alone proves neither condition. Missing local state is not proof that the input is invalid. Identity processing has a different rule: an invalid update blocks the identity prefix and every parent that requires that state. It is not skipped to produce a later association state. IDENT-070 and IDENT-071 own the exact verified state a parent can use. The group disposition table below applies only after those prerequisites hold. Commit validation is defined by [RFC 9420 §12.4.2](https://www.rfc-editor.org/rfc/rfc9420.html#section-12.4.2) and GMOD; proposal validation is defined by [RFC 9420 §12.1](https://www.rfc-editor.org/rfc/rfc9420.html#section-12.1) and GMOD-059, GMOD-002, and GMOD-003. The application-message window does not authorize an old commit. A commit requires the current epoch; SEND-014 covers rebuilding an own commit that lost its epoch. | Group input or failure | Disposition | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Supported input fails decoding, topic/group matching, sender authentication, or payload validation | Terminal rejection | | Authentication fails, generation is out of bound, wire format is wrong, or a message secret was consumed or discarded for forward secrecy | Terminal rejection; other local key, ratchet, library, and storage failures remain held | | Application message, commit, or proposal whose sender data names a leaf outside the ratchet tree or a generation beyond the forward window of PROC-061 | Terminal rejection | | Application message from another installation at the current epoch or one of the three retained preceding epochs | Apply if validation and, for a retained epoch, PROC-059 succeed; otherwise terminal rejection; reject if its epoch secrets were discarded under the retention policy | | Own application-message echo at the current epoch or one or two epochs earlier | Apply if validation succeeds; an echo three or more epochs earlier is stale | | Application message older than its applicable window, or before the installed join epoch | Terminal rejection | | Supported message names a future epoch after the complete preceding prefix | Terminal rejection, not a stale-attempt retry | | Commit or proposal has a terminal validation result under the rules above, including a commit from a past epoch or a proposal reference absent from the complete prefix | Terminal rejection; missing local state for an already handled proposal remains held | | Own envelope has no matching attempt under SEND-012, or its effects were already applied | Terminal rejection without applying effects again | | Storage failure, interruption, absent local key, unsupported MLS or required group version, unresolved validation, or any error not established as a terminal case above | Held | | Identity input or failure | Disposition | | -------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | | Update validates against the complete preceding identity history | Apply under IDENT-004 and IDENT-071 | | Invalid identity history, missing local state, unresolved verification, unsupported input, or any other validation failure | Hold the identity prefix and dependent work; do not substitute a later or partial association state | Welcome rejection and retention belong to JOIN-085, JOIN-048, JOIN-087, JOIN-084, and JOIN-094. A later Welcome can complete while an earlier one stays unresolved. A running client needs later attempts to reach the retention decision without a restart. | ID | Title | Requirement | Why | | -------- | ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | PROC-011 | Reject on complete evidence | When a group envelope reaches the head with its preceding prefix handled and its required validation state available, the client MUST apply the group disposition table and durably record the topic, sequence id, and typed reason of a terminal rejection with the advance of `P`. It MUST base rejection on the ordered prefix, installed state, and verified identity state, using an own attempt only to match and validate its echo under SEND-012, and MUST NOT use wall-clock timing or app delivery progress as rejection evidence. | Local failures must not become permanent message loss. | | PROC-061 | Reject undecryptable senders | If a group application message, commit, or proposal other than the client’s own echo under SEND-012 has sender data that names a leaf index not less than the leaf count of that epoch’s ratchet tree, or a generation more than 1000 above the current generation of that sender’s ratchet of the same type, application or handshake, in the client’s stored secret tree for that epoch ([RFC 9420 §9.1](https://www.rfc-editor.org/rfc/rfc9420.html#section-9.1)), and the group’s committed floor does not exceed the client’s version, then the client MUST terminally reject it under PROC-011. | Holding a ciphertext no receiver can decrypt stops every later message and commit in the conversation, including the removal of its sender. | | PROC-059 | A past-epoch sender still holds its leaf | When the client processes a group application message from one of the retained preceding epochs, it MUST terminally reject it under PROC-011 unless the current ratchet tree holds, at the sender’s leaf index, a leaf whose signature key equals the key of the leaf that signed the message in that epoch, and it MUST attribute an applied message to that leaf’s installation. | All installations of an inbox share one credential, so after a removed installation’s leaf is reused by another installation of its inbox, its retained-epoch messages would be applied and attributed to that installation. | | PROC-012 | Preserve unresolved work | When group or identity work has a held disposition in the tables above, the client MUST keep it pending without advancing `P` across it or applying its successors, and MUST block parents that require invalid or unresolved identity history. While a Welcome remains held under JOIN, it MUST retain the original deadline across retries and restarts and, while running, eventually make the attempt at or after that deadline without requiring a new network event. | Invalid identity state must not authorize a member; an unreadable Welcome must not retain keys forever. | | PROC-013 | A hold stays isolated | While a topic head or a Welcome is held, the client MUST continue to attempt independent ready topics and Welcomes and MUST preserve completed dependency results when another dependency fails. | One unreadable conversation must not stop all conversations. | ## 4. Targets and completion An explicit sync samples the serving backend’s heads. A send or externally supplied fetch target names a particular envelope instead. Only a backend-sampled head describes what that backend could see at capture; an external target can be ahead of it. Neither target moves with later traffic. API-244 omits empty topics from `QueryNewest`; that omission supplies target zero, not an uncaptured target. Welcome-aware catch-up and sync of Welcomes with groups include discovery. They enroll groups installed by Welcomes through the fixed Welcome target, subject to the operation’s consent selection. A generic topic operation or a send with fixed targets has no such discovery scope. Unrelated local groups and Welcomes beyond the target do not extend a run. Completion on group and identity topics uses `P`. Completion on Welcome topics uses `F` and every unresolved Welcome through `H`; the highest successful Welcome does not replace that set. An inactive group completes its obligation at the removal position without processing messages for a membership it no longer holds. | ID | Title | Requirement | Why | | -------- | ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | | PROC-015 | Fix operation targets and scope | When an operation establishes its scope, the client MUST fix each target from a fresh `QueryNewest` result, a new registration acknowledgement for that operation, a publish receipt, or an externally supplied fetch target, using zero for a successfully queried empty topic and leaving failed captures absent. For Welcome-aware catch-up or sync of Welcomes with groups, it MUST enroll discovered groups through the fixed Welcome target that pass that operation’s selection, with one fixed target each; later traffic and unrelated groups MUST NOT extend the run. For an all-groups stream, it MUST include stored groups at startup and discover newly stored groups without relying on a new network event. | Moving targets prevent completion under continuous traffic. | | PROC-016 | Complete only processed work | The client MUST report an operation complete only after all required targets and discovery are established and, for every group or identity topic, `P >= H` or a removal at or below `H` made the group inactive, and for every Welcome topic, `F >= H` with no unresolved Welcome at or below `H`. | Receipt alone leaves the app with unprocessed ciphertext. | | PROC-018 | Report incomplete work without loss | When an operation ends with unfinished work, the SDK MUST return a typed incomplete or blocked result naming each unfinished topic, its optional target, `F`, `P` for group or identity topics or unresolved Welcome ids through the target, and its typed cause, and MUST preserve committed progress and pending work. On scope replacement or cancellation it MUST identify cancelled obligations under their old scope generation, release only that operation’s interests, and MUST NOT report them complete. Before returning blocked, it MUST let independent obligations complete, block, or reach the deadline. | An app needs to distinguish missing targets, held input, and cancelled work. | ## 5. Capacity Pending work consumes storage and memory. Separate capacity for groups, Welcomes, and identity updates prevents a group backlog from blocking its own dependencies. These budgets limit pending work; they do not bound the whole database. Local delivery reads have a separate budget and are not envelope admission. | ID | Title | Requirement | Why | | -------- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | PROC-020 | Capacity never loses work | When capacity prevents receipt, the client MUST preserve pending work and `F`, return a typed capacity error if no legal admission fits, and resume ready topics without starvation as capacity is released. It MUST reserve separate pending capacity for group, Welcome, and identity work so one kind cannot consume another kind’s capacity. Within each kind it MUST charge held work, meaning every pending envelope of a topic whose head is held under PROC-012 and every Welcome kept under JOIN-057, JOIN-084, JOIN-087, JOIN-092, or JOIN-094, to a separate held allowance no larger than that kind’s capacity, so held work cannot consume the capacity of ready work. It MUST NOT discard pending input or advance `F` to make room, except that when held Welcomes exceed the held allowance it MUST record a terminal rejection for the held Welcome with the lowest sequence id, before any JOIN deadline. | Dropping a pending commit loses the state needed for later messages. Held work never drains, so charging it to shared capacity lets one sender or conversation stop receipt for every other one. Welcomes are independent, so evicting one loses only that join. | ## 6. Streams and recovery The app selects network interests, including denied conversations. Consent filters local delivery; it does not authorize subscriptions. A Restored archive placeholder (ARCH-015) is excluded by its group state, not by authorization: when an operation selects it, whatever the scope, filter, or consent, it gets no network interest until a Welcome activates it under JOIN-080. The client checks the group state when an operation selects the group. If the group has no stored row, the client checks that selected topic again until the row exists; if an import creates a Restored placeholder, the topic then has no network interest until activation. The client re-evaluates network interest periodically, so an activation takes effect after a short delay. A topic stays registered while any operation needs it. Static replacement and reconnect both resume from durable receipt, and obsolete registration results cannot update a replacement scope. The recovery rules below also cover silence and Query fallback. Silence is three advertised keepalive intervals without an inbound frame while the client is able to read, using 30 seconds for an absent or zero interval. Client backpressure is not wire silence. For a send or supplied target, a healthy receiver has a receipt wait of 1 second from the operation’s start of receipt waiting; partial receipt does not restart it. An explicit sync starts Query immediately. Once `F >= H`, only processing remains. AUTH-025 owns credential lockout and terminal credential failures. CONF-075 owns blocked connections caused by configuration. Terminal credential failures and blocked connections close a stream with network interest. A credential cool-down alone does not close it; the recovery episode limits still apply. An explicit remote cancellation ends the affected stream. A timeout or cancellation caused by the local transport uses normal recovery. Other transport errors retain pending work and use reconnect backoff. API-284 still prohibits an unchanged invalid request, so recovery cannot repeat that request unchanged. Each app stream has its own recovery budget. Initial connection starts an episode. A later episode starts when that stream detects a failure. Ten failed recovery cycles or ten minutes without sustained recovery exhaust the budget. A failed fallback Query spends one cycle only for streams that select its topic. Sustained recovery means that the stream’s selected registrations have remained active for 30 seconds under the wire-silence rules. A selected topic that is paused or blocked does not prove recovery. Application messages are not required. Opening a socket alone does not reset the budget. Time spent in credential cool-down counts toward the episode deadline. Waiting alone adds no failed recovery cycle. Exhaustion ends that app stream and preserves stored receipt, processing, and delivery positions. Internal receipt, device-sync, and barrier operations keep their own lifecycle and can continue to use a shared receiver. A new stream on the same client starts with a fresh budget even when the network remains unavailable. Old timers and cleanup cannot end the new stream. Conversation notifications have no durable app delivery cursor; message readers resume under section 7. The connection states describe transport activity: `connecting` is the first open, `connected` has a receipt source, `reconnecting` is recovery after a retryable failure, `failed` is recovery after a non-retryable source response with delayed retries, and `closed` has no future automatic attempts. `failed` does not mean pending processing failed. Registration states are `pending`, `active`, and `removed`; processing states are `pending`, `complete`, `blocked`, and `cancelled`. | ID | Title | Requirement | Why | | -------- | ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | | PROC-021 | Recover without losing progress | When a stream fails, becomes silent under the silence rule above, or needs replacement, the client MUST recover under the recovery rules in this section from current durable `F` and current interests, preserve pending work, discard obsolete registration results, and wait for a static replacement to be ready before cancelling replaced registrations. While `F < H`, it MUST use Query after `F` immediately for explicit sync or an uncovered target, and after the receipt wait above for a covered target, skipping that wait if it would reach the operation’s deadline. It MUST NOT refetch a stored prefix or turn connection failure into processing completion. | Stream failure must not strand work that Query can supply. | | PROC-038 | Bound network recovery | While an app stream is active, the client MUST apply the recovery episode limits in this section and reset its budget only after sustained recovery. When the budget is exhausted, the SDK MUST end that stream with a typed exhaustion cause through its error callback, when supplied, and reject its pending iterator read, without treating a connection open alone as recovery. | A failed network must produce an actionable error instead of an unlimited wait. | | PROC-039 | Fresh streams recover independently | When an app opens a stream after another stream ended, the client MUST give the new stream a fresh recovery budget and preserve its saved receipt, processing, and delivery positions. Ending one stream MUST NOT exhaust another stream’s budget, create a client-wide or database-wide exhaustion latch, or let its delayed work close a replacement stream. | An app must be able to recover on the same client after an extended outage. | | PROC-044 | Current connection state | When an app subscribes to a message or conversation stream’s connection-state changes, the SDK MUST deliver the state at subscription and, after each change, its latest state under the connection-state definitions above, never older than one already delivered. | An older state can leave the app showing the wrong connection status. | | PROC-051 | Restored groups have no network interest | When any operation selects a group whose stored membership state is `Restored`, the client MUST NOT select the group’s message topic for network interest. Because only an import creates a Restored group (ARCH-014), the client MAY skip checking a topic again after an operation selected it. When a Welcome activates that group under JOIN-080, the client MUST select the topic for network interest, for each open operation that selects the group, within 250 milliseconds of the activation commit, plus the time to finish receive and processing work already in progress. | Envelopes for an inert group stay pending until activation and consume the group-wide pending capacity of PROC-020, which pauses receipt for every group. | ## 7. Local delivery Message delivery reads retained local messages. The default consumer remembers app acknowledgement in `D`; a replay reader uses its supplied cursor and leaves `D` alone. Receipt, sync, and network reconnection do not acknowledge app work. Messages stored by another process or an import remain visible without a new network event. Message handoff is the SDK’s per-reader admission check that releases one message for a pending callback or iterator request. Selection and eligibility are evaluated at this check; default delivery also checks ownership under PROC-031. A candidate waiting before this check is not handed off. Binding or transport work after this check carries an already handed-off item. Handoff is not acknowledgement; PROC-052 defines acknowledgement. An app callback or iterator can sit behind a binding queue. A successful enqueue is not an acknowledgement: the app must reach the acknowledgement boundary. A crash after app handling and before durable acknowledgement can repeat the item. An app can place a queue after the SDK iterator. When that queue requests the next item, it reaches the iterator acknowledgement boundary even if later app processing is incomplete. Cancellation after final commit admission does not make that item eligible again. For an iterator acknowledgement, cancellation and final commit admission have one atomic order. Writer acquisition and tentative progress changes do not admit the commit. Cancellation that wins that order retains the prior item; a commit already admitted can finish without starting another handoff for the cancelled read. A reader’s selection can include a Restored placeholder; when the reader selects it, PROC-051 keeps its topic out of network interest until activation. Scope and filter have different effects. A group outside scope keeps its backlog. A filter excludes a candidate inside scope and consumes it for default delivery. Conversation callbacks are live notifications; message replay does not replay conversation discovery or later message edits and deletions. A database operation uses its normal retry and busy-wait policy. If a local read, acknowledgement write, or ownership operation then returns a storage error, that stream ends with the typed cause. There is no additional stream-level storage retry. The app decides when to open another stream. If the app completes an item but its acknowledgement write fails, a new stream can deliver the item again. An explicit end under PROC-042 gives the reason `closed`. It is not an error close. | ID | Title | Requirement | Why | | -------- | ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | PROC-024 | Stable delivery identity | When a message first becomes deliverable, the client MUST assign it one delivery number greater than all previously assigned numbers in that database, with the change that makes it deliverable, and MUST NOT change or reuse it, including after deletion or duplicate insertion. Every repeat delivery MUST carry the same message id and delivery cursor. | A changed identity makes app deduplication and resume unreliable. | | PROC-025 | Deliver only eligible messages | At message handoff, a message stream MUST admit only retained application or membership-change messages with `Published` status and a delivery number whose disappearing-message deadline has not passed, and MUST NOT admit `Unpublished` or `Failed` messages. | An optimistic message is not yet accepted by the group. | | PROC-026 | Resume durable app delivery | The default consumer MUST deliver eligible messages in delivery-number order above each selected group’s saved `D`, including messages stored by sync, push-driven fetch, import, or another process, without requiring a network connection or a new network event. Receipt, processing, stream close, and reconnect MUST NOT advance or reset `D`. | Network activity must not consume the app’s unread messages. | | PROC-052 | Acknowledge at final commit admission | With one item handed to the app and not yet acknowledged, the SDK MUST persist that item’s `D` only when the app callback returns normally or the app requests the next iterator item, including across binding queues, and MUST NOT hand over another item until that write succeeds. When an iterator read is cancelled before the final atomic commit admission, after the storage writer is acquired and its tentative `D` update is complete, the SDK MUST roll back that update and leave the prior item eligible on restart; after that admission it MAY finish the acknowledgement but MUST NOT make a new message handoff for the cancelled read. A callback error, enqueue, or failed acknowledgement write MUST leave the item eligible on restart, and cancellation MUST NOT undo a committed acknowledgement. | Acknowledgement before app handling loses a message on a crash. | | PROC-031 | Exclusive recoverable consumer ownership | Before each default-consumer handoff or change to `D`, the client MUST verify that the consumer still has exclusive ownership across clients sharing the database, and MUST reject a competing consumer with a typed ownership error. It MUST maintain that ownership while active or stop handoffs and writes, release ownership on clean close, and permit takeover after an owner stops without closing, without permitting the old owner to change the new owner’s `D`. | Two owners can skip each other’s messages. | | PROC-033 | Cursors name the database | An SDK MUST attach a delivery cursor to every item from either reader, supply a beginning cursor with delivery number zero, and reject a supplied cursor for a different database with a typed cursor error. Exposing a cursor MUST NOT acknowledge default delivery. | A foreign cursor resumes at an unrelated message. | | PROC-034 | Replay is independent | When an app opens a stream from a supplied cursor, the client MUST deliver every eligible message in scope strictly after that cursor in delivery-number order and then continue with new messages, without reading, changing, or acquiring ownership of `D`. | A replay must not consume the default consumer’s backlog. | | PROC-037 | Apply authorized deletions | When the client processes a `xmtp.org/deleteMessage` message from the group’s topic or its own publication, it MUST keep, for as long as it keeps the group, a deletion record of the target id, the authenticated sender inbox, and whether that inbox is then in `SUPER_ADMIN_LIST`. It MUST mark a stored message of the group that passes CTYPE-018 deleted by the inbox of its record with the lowest `deleted_at_ns` among the records stored when it marks, among those whose inbox is its sender inbox or was a super admin, and remove its content, in one write. A mark, once set, never changes. It MUST NOT mark a message otherwise, except under ARCH-028, remove a mark, or queue a marked message for sending. | A member could erase others’ messages, and an unsent or expired deletion would leave installations showing different histories. | | PROC-056 | Only marked messages block deletion | When an app asks the client to delete a message, the client MUST NOT refuse the request as already deleted unless the message is marked under PROC-037. | An unauthorized deletion must not block an authorized one. | | PROC-060 | Deleted messages read as placeholders | An SDK MUST return a marked message, also as a reply’s parent, as `xmtp.org/deletedMessage:1.0` with empty content, no fallback or reactions, zero counts, and `deleted_by` naming sender when its sender deleted it and the deleting inbox otherwise. | Leaving it out would shift page positions. | | PROC-040 | End streams on storage failure | When a local read, acknowledgement write, or ownership operation returns a storage error, the SDK MUST end that stream with the typed cause, report the error once through the error callback when supplied, and reject iterator consumption with the cause. It MUST NOT perform another handoff or add a stream-level storage retry, and MUST preserve PROC-052 and PROC-031 when the app opens another stream. | The app must control retries without losing unacknowledged work. | | PROC-041 | One close notification | When a message or conversation stream ends for any reason, the SDK MUST deliver exactly one close notification with its close reason. | An app needs one final signal to release its stream state. | | PROC-042 | Explicit end is closed | When an app ends a message or conversation reader, the SDK MUST complete the end without an error and give its stream the close reason `closed`. | An intentional stop must not appear to be a failure. | | PROC-043 | Retryable error close | When a message or conversation stream ends with an error, the SDK MUST mark it retryable for PROC-038 and PROC-040, and not retryable for AUTH-025, CONF-075, PROC-031, and PROC-033. | An app needs to decide whether to reopen without retrying a terminal error. | | PROC-045 | Codec failure keeps stream open | When a custom content codec fails while a message stream decodes an item, the SDK MUST expose that item as custom content with its error and continue the stream under CTYPE-008 and CTYPE-009. | One app codec failure must not hide later messages. | | PROC-046 | Selection at reader open | When an app opens a message reader, the SDK MUST apply the selected conversation scope and filters for that reader’s lifetime without using consent or membership as network-subscription authorization; a group that is a Restored placeholder when the reader selects it is not a subscription candidate (PROC-051). It MUST evaluate the selected filters against current conversation state at message handoff. | App selection must not prevent protocol processing. | | PROC-047 | Scope and filter progress | When default delivery examines a message, the client MUST leave out-of-scope `D` unchanged and advance `D` past an in-scope filter exclusion without handing the message to the app. | Scope exclusion preserves unread backlog; a filter exclusion consumes it. | | PROC-048 | Local delivery independence | When a locally stored message is eligible for delivery, the client MUST NOT wait for network registration acknowledgement before handing it to the app. | Network failure must not block local history. | | PROC-049 | Shared network interests | When a message reader ends, the client MUST retain each network interest that another operation still needs. | Closing one reader must not stop another operation’s traffic. | | PROC-050 | Stored message cursor | When an SDK returns a full stored message result with a committed delivery number, it MUST expose the cursor for that number and database; when the message has no committed delivery number, it MUST expose the absence of a cursor. | Apps cannot resume from an invented or uncommitted position. | | PROC-053 | Reaction summary size | When an SDK returns a message from a history read or a message lookup, its reaction summary MUST hold exactly those of the 50 unexpired reaction messages to it that sort last by send time, then sequence id, then message id (all of them when fewer exist) that decode as reactions, where an unpublished message has sequence id 0. The SDK MUST also report how many unexpired reaction messages refer to it, counting removals. | Reactions cannot be deleted (CTYPE-018), so any member can make a one-message read load an unlimited number of them. | | PROC-054 | Reaction pages | An SDK MUST let an app read the unexpired reaction messages to one message in descending order of send time, then sequence id, then message id, starting after a reaction message the app names, at most the app’s `limit` per call or 50 when the app names none. It MUST fail the call with an invalid-argument error when `limit` is less than 1 or greater than 1000, or when the named reaction message is not an unexpired stored reaction message to that message. | Reactions outside the summary are otherwise unreadable, and a cursor of send time alone skips reactions that share a send time. | | PROC-057 | Message list size | When an app lists one conversation’s messages with `messages()`, an SDK MUST return at most the `limit` the app names, or, when the app names none, at most the 100 matching messages that come last in ascending order of the requested sort field, returned in the requested order. It MUST fail the call with an invalid-argument error when `limit` is less than 1 or greater than 1000. | Any member can add messages to a conversation, so a list with no page size loads every message they send in one call, and past the database’s bound-value limit the call fails every time. | ## Known limitations Delivery is at-least-once. A crash or loss of consumer ownership after app handling but before durable acknowledgement can repeat an item. The app can deduplicate on its message id. A backend-sampled target includes replica lag. Completion through it does not claim receipt of every primary commit before the call. An externally supplied target has no such sampled-head guarantee. Push-envelope entry points accept a backend `ServerEnvelope` and use its metadata as an ordered-fetch target. These entry points do not accept the PUSH JSON body containing `topic` and `sequence_id`; automatic Welcome discovery for an unknown group named by that body is not part of their interface. A commit that names a proposal missing from local state is rejected only when the client durably recorded every proposal the prefix delivered in that epoch and still holds each one. Once a delivered proposal is lost, the client holds any commit in that epoch that fails for a missing proposal, even one whose missing reference the prefix never carried, because the failure does not name the reference. A held group or identity prefix has no retention deadline. Unsupported input can require a client upgrade; invalid identity history can require repair. Retrying a local failure does not make invalid history valid. Envelopes already pending when a topic’s head becomes held move to the held allowance without an admission check, so held work can exceed that allowance. Each held topic still stops at its topic capacity, so held storage grows with the number of conversations a sender can hold, as stored messages do. A committer whose handshake generations in one epoch run more than 1000 ahead of the other members’ stored secret trees, because it built handshakes it never published or published ones the members did not decrypt, publishes a commit that every other member rejects under PROC-061 while it applies its own echo under SEND-012. The other members record the commit as `UNDECRYPTABLE` and keep their epoch. When the committer is a publisher (FORK-085), its entry for the commit disagrees with theirs, so fork detection marks every other member `forked`, which stays set under FORK-041, while the committer, whose own entries match, stays `not forked`. When the committer is not a publisher, the publishers’ entries agree with the other members, so only the committer is marked `forked`. The readd path repairs neither side, because their epoch secrets have diverged: a readded member cannot decrypt the readd commit, so JOIN-092 holds the repair Welcome and JOIN-042 never lets it replace the state (FORK Known limitations). Clients that predate PROC-061 hold such a commit or proposal; they apply nothing past it and reject it after an upgrade. A corrupted persisted ratchet tree can also raise the index error that PROC-061 reads as a sender outside the tree. The client then terminally rejects such a message, including a commit, instead of holding it under PROC-012, and so forks from members that apply it. An application message that the ordered topic places after the commit that removes its sender is rejected under PROC-059 by every receiver, although the sender’s own copy can show it as sent. A receiver cannot tell a message sent before the removal from one sent after it, so this version does not apply it. A reaction summary holds the 50 most recent reaction messages to a message. A member who sends 50 later reaction messages therefore pushes every other member’s reactions out of the summary, and an app reads them under PROC-054. A summary can show an addition whose removal is not yet published. The count includes removals, so it is not the number of reactions a user sees. The PROC-054 cursor is a reaction message id: when that reaction message expires or is deleted between two calls, the next call fails with an invalid-argument error, and the app restarts from the newest reaction. Removed content can stay in freed database pages and the write-ahead log. A deletion marks only a message stored when the deletion is processed, or one a later archive import stores. # Push subscriptions and webhooks A client that is not connected still needs to learn that an envelope arrived. The backend delivers that fact itself: a recipient registers a random id and a bearer secret, names one channel (APNs, FCM, or an HTTPS webhook), and keeps a list of topics on the backend. The backend reads settled envelopes, drops the ones the recipient’s own inbox sent, and sends a push body that carries the topic and the sequence id and nothing else. The app fetches and decrypts the envelope itself. A webhook receiver verifies every body against the signing key it registered. ```mermaid flowchart LR A[App enables notifications] --> C[The client
desired set, diff, renewal] C -->|Register / UpdateSubscriptions
id + secret| B[The backend] B --> R[(Recipients and subscriptions)] P[Publish: should_push, sender_hmac] --> E[(Settled envelopes)] E --> D[Dispatch
settled, above the start position] R --> D D -->|HMAC sender check| S[APNs / FCM / HTTPS
topic + sequence id] S -->|dead token| R ``` ## Scope In scope: registration and the bearer secret; the three channels and the safety of a webhook destination; how a subscription is added, replaced, and removed, and where it starts; which envelopes are pushed; the delivery condition and what survives a restart; sender suppression; the push body and the provider contract; when a recipient is deleted; webhook signing; retention; the client’s desired set, its sync, and its recovery; and what an SDK exposes to an app. Out of scope: request authentication on the notification RPCs (AUTH-001, AUTH-003, AUTH-013); sequence ids and the publish contract (API-286 through API-289, API-210); the closed allocation boundary (API-203); the layout of a topic (TOPIC-001); how the root HMAC key is generated and reaches every installation of an inbox (SYNC-026, SYNC-032); consent states (`CONS` section 1); metrics, shutdown, and read routing (OPS-007, OPS-008, OPS-014, OPS-017); the push configuration keys, their checks, and the startup checks of provider credentials (CONF section 1.2); the backend’s internal bounds, which belong to operator documentation; and the platform a deployment runs on. | Related | Relation | | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `AUTH` | AUTH-001, AUTH-003, and AUTH-013 apply to the three notification RPCs as to every other path. No claim is read for ownership; the secret alone decides it. | | `API` | Owns sequence ids (API-286 through API-289), the envelope wire format including `GroupMessage` (API-210), admission (API-230), and the closed allocation boundary (API-203). | | `TOPIC` | TOPIC-001 gives the kind byte and identifier of a group-message topic and a welcome topic, the two kinds a subscription may carry. | | `SYNC` | SYNC-026 and SYNC-032 own the inbox’s 42-byte root HMAC key. This spec owns what is derived from it. | | `OPS` | OPS-014 keeps request data out of telemetry; OPS-017 owns the metric catalogue; OPS-007 and OPS-008 own shutdown as a client sees it. | | `EVENT` | EVENT-001 reports when the stored notification state becomes failed. | | `CONF` | Owns the `[push]` configuration keys, their types, presence, and checks, and the defaults that PUSH-217 and PUSH-226 do not state (CONF section 1.2, CONF-091, CONF-092). | API-203 defines the closed allocation boundary; PUSH-216 requires that a new subscription reads it in the transaction that stores the subscription. API-291 requires that the boundary never decreases. ## Terms | Term | Meaning | | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Recipient id | `recipient_id`: 32 random bytes that name a push endpoint. | | Recipient secret | `recipient_secret`: 32 random bytes that prove ownership of a recipient id. A bearer credential on the transport’s TLS. | | Channel | How the backend reaches a recipient: `CHANNEL_APNS`, `CHANNEL_FCM`, or `CHANNEL_HTTP`. | | Delivery target | The APNs device token, the FCM registration token, or the webhook URL with its signing key. | | Signing key | `HttpDelivery.signing_key`: 16 to 64 bytes a webhook recipient supplies, under which the backend signs every body sent to it. | | Subscription | One (recipient, topic) pair with its key window, its start position, and its `include_commits` flag. | | Start position | The closed allocation boundary (API-203) read in the transaction that first stored a subscription (PUSH-216). | | HMAC epoch | A 30-day period: the Unix time in seconds divided by 2592000, rounded down. | | Key window | The `hmac_keys` of a subscription: up to three 42-byte keys for consecutive HMAC epochs starting at `hmac_epoch_base`, so the key at index `n` is for epoch `hmac_epoch_base + n`. | | Root key | The inbox’s 42-byte random key from which every group HMAC key derives (SYNC-026). | | Push-eligible envelope | A stored envelope that PUSH-219 makes eligible for delivery. | | Settled envelope | An envelope whose sequence id is at or below the closed allocation boundary. | | Dispatcher | The backend process that, at a given time, loads deliveries and records dispatch progress. | | Delivery | One (envelope, subscription) send. | | Attempt | One provider request for a delivery. | | Push body | The JSON object a delivery carries, under PUSH-259. | | Renewal time | The time of the recipient’s last successful `Register` or `UpdateSubscriptions`, set under PUSH-255. | | Receiver | The HTTPS server an app operates at a webhook URL. | | Notification state | The client’s local state: disabled, enabled, or failed with a cause. | | Override | A per-conversation setting of enabled or disabled that replaces the rules for that conversation. | | Effective value | Whether a conversation is desired: its override when it has one, otherwise whether its conversation consent state is in the enabled `consent_states`. | | Uploaded set | The client’s local record of the topics it has stored on the backend and the key window and `include_commits` it sent for each. | | Desired set | The topics the client wants stored on the backend, under PUSH-238. | ## 1. Recipients and the bearer secret A recipient is a push endpoint, not an installation. It is named by 32 random bytes and proven by 32 more, both generated by the client once for its database and sent on every request. The backend stores only the SHA-256 hash of the secret, so a database read yields nothing a caller can present. There is no binding to an inbox or an installation, so nothing on the wire identifies whose device a recipient is, and a revoked installation that still holds its secret can renew until it stops (Known limitations). `Register` creates or renews a recipient and never touches its subscriptions, so a token refresh does not lose them. `Unregister` is a hard delete that takes the subscriptions with it. Every successful mutating call returns the backend’s view in a `RecipientState`, which the client compares with its own record (section 8). ```proto enum Channel { CHANNEL_UNSPECIFIED = 0; CHANNEL_APNS = 1; CHANNEL_FCM = 2; CHANNEL_HTTP = 3; } message ApnsDelivery { string token = 1; } message FcmDelivery { string token = 1; } message HttpDelivery { string url = 1; // Webhook signing key, 16 to 64 bytes. bytes signing_key = 2; } message RegisterRequest { // Random recipient identity and bearer secret, each 32 bytes. bytes recipient_id = 1; bytes recipient_secret = 2; oneof delivery { ApnsDelivery apns = 3; FcmDelivery fcm = 4; HttpDelivery http = 5; } reserved 6; reserved "metadata"; } message UnregisterRequest { bytes recipient_id = 1; bytes recipient_secret = 2; } message UnregisterResponse {} message RecipientState { uint64 topic_count = 1; Channel channel = 2; int64 expires_at_ns = 3; } ``` Admission is one ordered contract. The checks below run in order on every notification RPC, after the request authentication of AUTH-001 and the `request` charge of RATE section 2, and the first failure decides the status; a later check runs only when every earlier one passed. The client acts on the status (PUSH-267), so for every check after the recipient lookup, a malformed payload on an unknown recipient answers `NOT_FOUND` and not `INVALID_ARGUMENT`. Check 0 (PUSH-264) and check 2 (the `push` charge of RATE section 2) run before that lookup, so an `UpdateSubscriptions` request over its bounds answers `INVALID_ARGUMENT`, and one over its caller’s `push` limit answers `RESOURCE_EXHAUSTED`, even for an unknown recipient. | Order | Condition | Status | | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | | 0 | `UpdateSubscriptions`: the request exceeds a bound of PUSH-264, or its body carries more than one gRPC message | `INVALID_ARGUMENT` | | 1 | `recipient_id` or `recipient_secret` is not exactly 32 bytes | `INVALID_ARGUMENT` | | 2 | `UpdateSubscriptions`: the caller’s `push` spend of the number of entries in `adds` is denied (RATE-010) | `RESOURCE_EXHAUSTED`, with the details RATE-040 gives | | 3 | `Unregister` or `UpdateSubscriptions` names a `recipient_id` no stored recipient carries | `NOT_FOUND` | | 4 | a stored recipient’s hash differs from the SHA-256 of `recipient_secret` | `PERMISSION_DENIED` | | 5 | `Register`: the channel, delivery target, or signing key fails section 2, or the token or URL is empty, longer than 2048 characters, or contains a NUL character | the status section 2 gives, else `INVALID_ARGUMENT` | | 5 | `UpdateSubscriptions`: a subscription fails PUSH-215 or the request exceeds PUSH-217 | the status those rows give | | ID | Title | Requirement | Why | | -------- | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | PUSH-200 | Registration wire format | The backend MUST serve `Register`, `Unregister`, and `UpdateSubscriptions` with the messages defined above and in section 3, with the field numbers and types shown, and MUST NOT reuse a field number of any of them for another meaning. | | | PUSH-201 | Random recipient identity | When a client first enables notifications on a database, it MUST set `recipient_id` and `recipient_secret` to 32 bytes each drawn from a cryptographically secure random source, MUST NOT derive either from an inbox id, an installation key, or any other key, and MUST send the same pair on every later request from that database, across disable and enable. | A secret derived from something the backend can learn is no secret. A new pair on each enable leaves the old recipient registered until it expires, and its device receives every push twice. | | PUSH-253 | Ordered admission | When the `request` spend of a notification RPC is not denied (RATE-014), the backend MUST apply the admission table above in the order given, fail the request with the status of the first condition that holds, and change nothing other than the `request` spend of RATE section 2 and a `push` spend admitted at check 2 when any condition holds. A request passes this row only when its `request` spend is not denied and no condition holds. The comparison in check 4 MUST run in constant time. | The client re-registers on `NOT_FOUND` and stops on `INVALID_ARGUMENT` (PUSH-267); a status decided by a later check for a missing recipient does the wrong one. | | PUSH-254 | Secrets and private values stay private | The backend MUST store only the SHA-256 hash of a recipient secret, and MUST NOT place a recipient secret, a recipient id, a delivery token, a webhook URL, a signing key, or a topic in storage in clear other than the columns that serve delivery, in a status message, or in any telemetry field OPS-014 names. | A copy of the database must not be a set of valid credentials, and a log line must not name whose device a recipient is. | | PUSH-255 | Registration and the reported state | When `Register` or `UpdateSubscriptions` passes PUSH-253, the backend MUST, in one transaction, store the request (for `Register`, the channel and delivery target, creating the recipient with no subscriptions when the id is unknown and otherwise leaving every subscription unchanged), set the renewal time to the current time, and return a `RecipientState` whose `topic_count` is the number of stored subscriptions, whose `channel` is the stored channel, and whose `expires_at_ns` is the renewal time plus `recipient_ttl_seconds` in nanoseconds. | A token refresh that dropped subscriptions would silence a device until its next full sync; a `topic_count` that is not the stored count starts a repair that never ends (PUSH-260). | | PUSH-207 | Unregister deletes everything | When `Unregister` passes PUSH-253, the backend MUST delete the recipient and every subscription it holds. | | ## 2. Channels A recipient has exactly one channel, and a channel exists on a deployment only when the operator configured it: a table for APNs with the provider key, its key id, the team id, the bundle id, and an `environment` of `production` or `sandbox`; a table for FCM with the service account; a table for HTTPS, which may be empty. A registration for a channel that has no table fails, so an app learns at enable time that the deployment cannot reach it. A webhook is an HTTPS request from inside the deployment’s network to a URL any registrant chooses, so the destination is checked at registration and again before every attempt, because a host can resolve to a different address later. The address classes below are never connected to unless the operator sets `allow_private_addresses`, which is for development and test only (CONF section 1.2 gives its default). When `allowed_domains` is set and not empty, a host must equal an entry, or, for an entry that starts with `*.`, end with the entry’s text after the star with at least one label before it; the match is case-insensitive on the host name alone. The list binds at send time as well, so narrowing it stops deliveries to recipients registered before the change. The blocked address classes are every private address as ATCH section 6 defines it (an IANA special-purpose entry that is not globally reachable, a multicast address, or an IPv4-mapped or NAT64 IPv6 address whose embedded IPv4 address is private) and the deprecated site-local range fec0::/10. | ID | Title | Requirement | Why | | -------- | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | PUSH-210 | Channel must be configured | When `Register` names a channel whose configuration table is absent, the backend MUST fail the request with `FAILED_PRECONDITION`. | | | PUSH-256 | Webhook destination safety | When an `HttpDelivery` has a `url` whose scheme is not `https` or that carries a username or password, a `signing_key` shorter than 16 or longer than 64 bytes, or a host that matches no entry of a non-empty `allowed_domains`, whose lookup answers with no address, or, while `allow_private_addresses` is `false`, resolves to a blocked address, the backend MUST fail `Register` with `INVALID_ARGUMENT`. When the lookup of the host fails, including for a name that does not exist, or does not finish, the backend MUST fail `Register` with `UNAVAILABLE`. The backend MUST look up the host only for a request that passes every condition of this row and of admission check 5 that needs no lookup. Before each webhook attempt the backend MUST resolve the host again, MUST NOT send when the host no longer matches a non-empty `allowed_domains` or, while `allow_private_addresses` is `false`, any resolved address is blocked, MUST connect only to an address it resolved then, and MUST NOT follow a redirect. | A redirect, a rebinding host, or a widened list moves a signed request to an address that was never checked. The backend cannot tell a missing name from a resolver outage, and `INVALID_ARGUMENT` stops push for good (PUSH-267). | ## 3. Subscriptions A subscription is one topic a recipient wants pushes for. The client sends adds and removes, never a full list, so a change costs one row per changed topic and a large set is sent in batches. An add of a topic already stored replaces its key window and flag and keeps its start position, so a key rotation never re-delivers old envelopes. A new topic starts at the closed allocation boundary read in the transaction that stores it: the recipient never receives an envelope that settled before it subscribed. An envelope settled while the subscription’s transaction was open can be missed (Known limitations). A subscription may name only a group-message topic or a welcome topic (TOPIC-001). Nothing checks that the recipient is a member of the group or the installation of the welcome topic (Known limitations). `hmac_epoch_base` is read only when `hmac_keys` is not empty; the backend stores no base for a subscription without keys, whatever value the field carries. ```proto message UpdateSubscriptionsRequest { bytes recipient_id = 1; bytes recipient_secret = 2; repeated Subscription adds = 3; repeated bytes removes = 4; } message Subscription { // Group-message or welcome topic bytes. bytes topic = 1; // First epoch of the consecutive key window; zero with no keys. int64 hmac_epoch_base = 2; // At most three keys, each 42 bytes. repeated bytes hmac_keys = 3; bool include_commits = 4; } ``` | ID | Title | Requirement | Why | | -------- | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | PUSH-215 | Malformed subscription | When a `Subscription` or a `removes` entry carries a topic that is not a group-message topic or a welcome topic under TOPIC-001, when a topic appears more than once across `adds` and `removes`, or when an add has a negative `hmac_epoch_base`, more than 3 `hmac_keys`, or a key that is not 42 bytes, the backend MUST fail the request with `INVALID_ARGUMENT` and apply nothing. | | | PUSH-216 | Atomic application | When `UpdateSubscriptions` passes PUSH-253, the backend MUST apply every remove and every add in one transaction: a removed topic that is not stored changes nothing, an added topic already stored takes the new key window and `include_commits` and keeps its start position, and a new topic takes as its start position the closed allocation boundary read in that transaction. | A start position read outside the transaction, or moved on replacement, makes a subscribing client receive envelopes it had already read or miss ones it had not. | | PUSH-217 | Topic limit | When applying a request would leave the recipient with more stored subscriptions than `max_push_topics`, whose default is 100000, the backend MUST fail the request with `RESOURCE_EXHAUSTED` and apply neither its adds nor its removes. | | | PUSH-264 | Subscription batch bounds | When an `UpdateSubscriptions` request whose `request` spend is not denied (RATE-014) carries more than 1000 entries across `adds` and `removes`, or more than 3000 entries in `hmac_keys` across its adds, which is 1000 adds of the 3 keys PUSH-215 allows, the backend MUST fail it with `INVALID_ARGUMENT` before it decodes more entries of that kind than that number or reads any recipient, and MUST apply nothing. | A rejected request otherwise makes the backend decode every entry and key, and write every add, before PUSH-215 or PUSH-217 rejects it. | ## 4. What is pushed Eligibility is decided when an envelope is stored, from the `should_push` and `sender_hmac` fields of `GroupMessage` (API-210). A Welcome is always eligible: the joiner is offline by definition. A group message is eligible when the sender asked for a push, or when it is a commit or a proposal, which reaches only the subscriptions that opted in through `include_commits`. Key packages, identity updates, and commit-log entries are never pushed. | ID | Title | Requirement | Why | | -------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --- | | PUSH-218 | Sender chooses the push | When the client publishes an application message, it MUST set `should_push` to the value the app gave for that send, and to `true` when the app gave none. When it publishes a commit or a proposal, it MUST set `should_push` to `false`. | | | PUSH-219 | Eligibility at storage | The backend MUST treat as push-eligible a stored envelope that is a Welcome, or a group message whose `should_push` is `true`, or a group message that is a commit or a proposal, and MUST NOT deliver a push for any other envelope. | | ## 5. Dispatch The backend reads push-eligible envelopes above its recorded position and up to the closed allocation boundary, joins them with the subscriptions on their topics, and sends one delivery per (envelope, subscription). The boundary is a ceiling: an envelope above it may still have an earlier sequence id in flight, so reading past it could skip one for ever. Below the boundary nothing is skipped. The promise is about first attempts, not receipt. The recorded position moves past a window only when every delivery in it has had one attempt, so a crash, a lost dispatcher role, or a shutdown that runs out of drain time (OPS-008) resends the windows above the position, and a delivery whose attempt was sent but never answered may be repeated. A failed attempt is retried up to the channel’s bound while the dispatcher that loaded it runs; a replay after a restart starts the count again. Delivery is therefore at-least-once-attempted and never exactly-once; a receiver that acts on a push more than once for the same `topic` and `sequence_id` does so at its own cost (Known limitations). Which process is the dispatcher, how the role moves, and the sizes of windows, pages, and in-flight sends are the implementation’s choice. The dispatcher also runs the retention pass: a recipient that has not renewed within `recipient_ttl_seconds` is deleted with its subscriptions. The client renews on its own schedule (PUSH-260), so a running client never expires. | ID | Title | Requirement | Why | | -------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | PUSH-257 | The delivery condition | For every push-eligible envelope whose sequence id is not greater than the closed allocation boundary when the window is read, and every subscription on its topic whose start position is less than that sequence id, whose `include_commits` is `true` or whose envelope is not a commit or a proposal, and whose recipient is stored on a configured channel, the backend MUST make at least one attempt to that recipient, including after a crash, a change of dispatcher, or a restart, unless PUSH-230 suppresses the delivery. The backend MUST NOT deliver an envelope to a subscription that fails any of those conditions. | A recipient woken for a group’s history, or for every membership change, is a recipient that switches notifications off. A skipped envelope is one no device learns of until it polls. | | PUSH-226 | Expiry deletes the recipient | While it is the dispatcher, the backend MUST run a retention pass no later than 3600 seconds after the previous pass ended, and each pass MUST delete every recipient whose renewal time is older than `recipient_ttl_seconds`, whose default is 2592000, together with its subscriptions. | A device that stopped renewing is gone or has disabled notifications, and its token would otherwise be sent to for ever. | ## 6. Sender suppression A sender’s own message must not wake the sender’s devices. The backend cannot read the message to learn who sent it, so the sender attaches an HMAC and the recipient’s installations upload the keys that verify it. Every installation of an inbox derives the same key for a group from the inbox’s root key (SYNC-026, SYNC-032), so a match means “this recipient’s inbox sent it”. The key rotates every HMAC epoch and the client uploads a three-epoch window, so a key uploaded a month ago still covers the current epoch and the next. The check runs only on a delivery that already passes PUSH-257, and it fails open. A missing `sender_hmac`, no key for the envelope’s epoch, a payload that does not decode, a key window that has not reached the backend yet, or an envelope whose 16 MiB check total is spent all result in a push. The sender picks the epoch by its own clock at send time and the backend by the envelope’s server timestamp, so a message near an epoch boundary can reach its own sender (Known limitations). | ID | Title | Requirement | Why | | -------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | PUSH-258 | Sender attaches the HMAC | When the client publishes a group message, it MUST set `sender_hmac` to the 32-byte HMAC-SHA256 ([RFC 2104 §2](https://www.rfc-editor.org/rfc/rfc2104#section-2)) of `data` under the group’s key for the current HMAC epoch by its clock, where that key is the 42-byte output of HKDF-SHA256 ([RFC 5869 §2](https://www.rfc-editor.org/rfc/rfc5869#section-2)) with salt `libXMTP HKDF salt!`, input keying material the root key followed by the group id, and info the group id followed by the epoch as a signed 64-bit little-endian integer. | Two installations that derive different keys for the same group see the inbox’s own messages pushed to one of them. | | PUSH-229 | Upload the key window | When the client stores or replaces a group-message subscription, it MUST send the keys for the HMAC epochs current minus 1, current, and current plus 1 in that order with `hmac_epoch_base` equal to current minus 1, and it MUST send the subscription again when its uploaded window no longer covers the epoch after the current one or when the root key changed. | A window that lapses turns every own message into a push at the next epoch. | | PUSH-230 | Backend suppresses a match | When a delivery that passes PUSH-257 carries a `sender_hmac` of exactly 32 bytes, the subscription’s key window holds a key at index equal to the HMAC epoch of the envelope’s server timestamp minus `hmac_epoch_base`, and the `GroupMessage.data` lengths of the checks the backend already made for that envelope plus this one total at most 16 MiB, the backend MUST compute HMAC-SHA256 of the stored `GroupMessage.data` under that key, compare it with `sender_hmac` in constant time, and MUST NOT deliver when they are equal. In every other case the backend MUST NOT suppress the delivery. | Failing closed on a missing key would silence a recipient whose client is one upload behind. A caller chooses both the number of keyed subscriptions on its topic and the message size, so without a total one message sets the dispatch work that every recipient of the deployment waits behind. | ## 7. Delivery No message content leaves the backend in a push. The body carries the topic and the sequence id, and on the webhook channel the recipient id, so a receiver that serves many recipients can tell them apart. `sequence_id` is decimal text on every channel so that a JavaScript consumer never rounds it. Every push is a background push: the app fetches the envelope and renders the notification itself. Each channel maps the provider’s answer to one of five outcomes, in the order the table lists them for that channel; the first row that matches decides. A transient outcome is retried after at least the delay shown, up to `max_attempts` attempts in total for the delivery, whose default CONF section 1.2 gives, while the dispatcher that loaded it runs. A rejected outcome stops after one attempt. A mismatch outcome names a token that does not belong to this sender, which one operator mistake in `environment`, the bundle id, or the FCM project produces for every recipient at once, so it keeps the recipient. A terminal outcome names a dead token and deletes the recipient, unless the recipient re-registered in the meantime. Every attempt, including a provider credential fetch, is bounded to 10 seconds, so a receiver that never answers holds nothing for longer than that. | Channel | Request | Outcomes, first match decides | | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | APNs | HTTP/2 `POST` to the production or sandbox host for the configured `environment`, a provider token under ES256 for the configured key, `apns-topic` equal to the bundle id, `apns-push-type: background`, `apns-priority: 5`, `apns-collapse-id` equal to the base64 topic, body `{"aps":{"content-available":1},"topic":..,"sequence_id":..}` | `200`: delivered. `410` with reason `Unregistered` or `ExpiredToken`: terminal. `400` with reason `BadDeviceToken` or `DeviceTokenNotForTopic`: mismatch. `429`, `500`, `503`, timeout, connection error: transient, delay 1 second. `403 ExpiredProviderToken`: one token refresh and resend within the same attempt, then rejected. Anything else: rejected. | | FCM | HTTP v1 `messages:send` for the service account’s project with an OAuth2 token, `data` holding `topic` and `sequence_id`, `android.priority` `HIGH`, `apns.headers` `apns-priority: 5` and `apns-push-type: background`, `apns.payload.aps.content-available: 1`, no collapse key | `200`: delivered. `429`, a `google.rpc.QuotaFailure` detail, or `FcmError` `QUOTA_EXCEEDED`: transient, delay 60 seconds. `500`, `503`, timeout, connection error: transient, delay 10 seconds. `FcmError` `UNREGISTERED`: terminal. `FcmError` `SENDER_ID_MISMATCH`: mismatch. `FcmError` `UNAVAILABLE` or `INTERNAL`: transient, delay 10 seconds. Anything else, including an error with no typed `FcmError`: rejected. A `Retry-After` longer than the delay is honoured up to 300 seconds. | | HTTPS | `POST` to the URL, `content-type: application/json`, the three signature headers of PUSH-235, body adds `"recipient_id"` | `2xx`: delivered. `404` or `410`: transient, delay 1 second, and terminal when every one of `max_attempts` attempts answered `404` or `410`. `5xx`, timeout, connection error: transient, delay 1 second. Anything else, including a redirect: rejected. | | ID | Title | Requirement | Why | | -------- | ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | PUSH-259 | Channel requests and the push body | The backend MUST send each channel’s request as the Request column of the table above states, carrying a JSON object whose `topic` is the standard base64 of the topic bytes and whose `sequence_id` is the envelope’s sequence id as decimal text, with `recipient_id` as lowercase hex on the HTTPS channel and no payload bytes, message hash, inbox id, installation key, or secret; and MUST classify each answer, retry, and delay as the Outcomes column states. | An APNs push without the background type and priority 5 is refused or shown as an empty alert; an FCM push to an Apple device at high priority is refused; a body with content leaks it to the provider. | | PUSH-234 | Dead tokens delete the recipient | When an attempt’s outcome is terminal under the table above and the recipient’s stored channel, delivery target, signing key, and secret hash still equal the ones the attempt used, the backend MUST delete the recipient and its subscriptions. On a mismatch, rejected, or transient outcome, and when the stored values differ, the backend MUST NOT delete it. | A provider’s answer that arrives after a re-registration must not delete the new registration. | ### 7.1 Webhook signing A receiver has no way to tell the backend from anyone else who learned its URL, except the signing key it registered. Every body is signed in the shape of the [Standard Webhooks specification](https://github.com/standard-webhooks/standard-webhooks/blob/main/spec/standard-webhooks.md), sections “Webhook ID”, “Timestamp”, and “Signature scheme”, with the symmetric `v1` scheme, so an existing verifier library checks it. XMTP deviates in two places: `webhook-id` is new for every attempt rather than stable across the retries of one event, and the key is 16 to 64 raw bytes carried in `HttpDelivery.signing_key` rather than a `whsec_` string with the specification’s 24-byte minimum. The backend emits the timestamp but enforces no replay window. A receiver verifies before it acts: it recomputes the signature of PUSH-235 over the exact received body bytes with its signing key, compares in constant time, rejects a body whose signature does not match, rejects a `webhook-timestamp` outside a tolerance it chooses, and treats two bodies with the same `topic` and `sequence_id` as one notification. Those checks protect only the receiver, so they are guidance here and not requirements. With `signing_key` of 32 bytes each `0x07`, `webhook-id` `fixed-id`, `webhook-timestamp` `1700000000`, and the body `{"topic":"AQID","sequence_id":"9007199254740993","recipient_id":"0101"}`, the signature is `v1,IszeBLRjxb7spJ5RLi+KW0w/aK3Buioq9E6jl3MKWZw=`. | ID | Title | Requirement | Why | | -------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --- | | PUSH-235 | Every webhook body is signed | When the backend sends a webhook, it MUST set `webhook-id` to a value unique to that attempt, `webhook-timestamp` to the current Unix time in seconds as decimal text, and `webhook-signature` to `v1,` followed by the standard base64 of HMAC-SHA256 under the recipient’s signing key over the string `webhook-id`, `.`, `webhook-timestamp`, `.`, and the exact body bytes. | | ## 8. The client The client keeps notifications in step with consent, membership, overrides, and key rotation without an app call at every start. It records locally what it has uploaded, computes the difference from local tables alone, and sends it in batches of at most 1000 subscriptions. The backend’s `topic_count` on every response is the one cross-check: when it disagrees with the local record, the client re-sends every topic it holds over later runs rather than clearing its record, so a client with more topics than fit in one request still converges. The sync runs after each event that can change the desired set, at client start while enabled, and at least once an hour, so a wake lost to a crash costs at most an hour. Notification work never sits inside another operation’s transaction, and a failed or slow notification request never fails a send or a consent write. A revoked installation, an expired recipient, or a backend restored from a backup answers `NOT_FOUND`. The client treats that as “register again from nothing”, for the configuration that is enabled now. | ID | Title | Requirement | Why | | -------- | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | PUSH-238 | The desired set | While notifications are enabled, the client’s desired set MUST be the group-message topic of every group and DM in which the installation is an active member and whose effective value is enabled, plus the installation’s welcome topic while `include_welcomes` is `true`, plus the group-message topic of every sync group in which the installation is an active member while `include_sync_groups` is `true`, and no other topic, with the `include_commits` rule on each group subscription and no keys on the welcome subscription. | | | PUSH-260 | Sync, renewal, and recovery | While notifications are enabled, the client MUST send as adds every desired topic missing from its uploaded set and as removes every uploaded topic no longer desired after each of a consent write, a membership commit, an override change, a group creation, a Welcome, a root key change, and enabling, and no later than 3600 seconds after its previous sync run ended while it runs. It MUST send `Register` or `UpdateSubscriptions` before the `expires_at_ns` of the last `RecipientState` it received while it runs, or at its first sync run when it starts after that time. When a request answers `NOT_FOUND`, or a `RecipientState.topic_count` differs from the size of its uploaded set, the client MUST re-send every desired topic over later runs, after a `Register` on `NOT_FOUND`, and MUST NOT discard its uploaded set on a count mismatch. | An expired recipient is deleted with every subscription (PUSH-226); clearing the whole record on every mismatch never converges for a set larger than one request. | | PUSH-240 | No collateral failure | The client MUST bound every notification request to 30 seconds of waiting on the backend, and MUST NOT fail, roll back, or hold for longer than that bound a message send, a consent write, welcome processing, or key package maintenance because of a notification request. | | | PUSH-266 | Enable and disable | When an app enables notifications, the client MUST reject the call without storing anything when its background task runner is disabled or an HTTP signing key is shorter than 16 or longer than 64 bytes, and otherwise MUST store the channel and rules, set the state to enabled, send `Register`, preceded by an `Unregister` while PUSH-265 forbids `Register`, and return the first failure or the result of `Register`, with a failure under PUSH-267 setting the state to failed and any other failure leaving it enabled with the reset and the registration retried. When an app disables notifications, the client MUST set the state to disabled and clear the channel and the uploaded set before it sends the disable’s own `Unregister`, MUST treat `NOT_FOUND` on that call as success, MUST keep every override, and MUST NOT send any other notification request while the state is not enabled. | A request that reaches the backend after a disable re-registers a device the user switched off. | | PUSH-265 | Reset before registering again | When the client has set the state to disabled while it holds a recipient id, it MUST NOT send `Register` or `UpdateSubscriptions` for that recipient, including after a restart, until an `Unregister` it sent after its last `Register` or `UpdateSubscriptions` for that recipient has answered success or `NOT_FOUND`. This takes precedence over PUSH-260. | `Register` keeps every subscription (PUSH-255) and the disable cleared the client’s record of them, so a new delivery target would receive pushes for topics its rules exclude, and the client could never name those topics to remove them. | | PUSH-267 | Error transitions | When a notification request for the enabled configuration fails with `PERMISSION_DENIED`, `INVALID_ARGUMENT`, `OUT_OF_RANGE`, `UNIMPLEMENTED`, or `FAILED_PRECONDITION`, the client MUST set the state to failed with that cause and MUST NOT send another notification request until the app enables notifications again. When it fails with `RESOURCE_EXHAUSTED` carrying the rate-limit detail of RATE-040, the client MUST keep the state enabled and retry under PUSH-260 no sooner than RATE-041 allows; with any other `RESOURCE_EXHAUSTED`, it MUST stop sending new topics until the desired set changes or a remove succeeds, MUST keep sending removes and replacements of topics in its uploaded set without new topics, and MUST retry such a batch with backoff if it is also refused; when it fails with `NOT_FOUND`, a timeout, or any other status, the client MUST keep the state enabled and retry under PUSH-260. After an `UpdateSubscriptions` timeout or another failure with an uncertain commit outcome, the attempted adds MUST remain eligible for retry while desired and removal when no longer desired, and unconfirmed removes MUST remain eligible for retry. | Each terminal status means the same request will fail the same way; a rate-limited request succeeds after its delay, and stopping adds would leave new groups silent until the desired set changes. | ## 9. What an app can do An app supplies the delivery target, because only the app holds the platform’s push token or operates a receiver; the client never obtains one. The surface exists on the native and Node SDKs. The browser SDK has none: there is no channel a browser page can be reached on. | ID | Title | Requirement | Why | | -------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --- | | PUSH-263 | The notification surface | A native or Node SDK MUST let an app enable notifications with a channel, a delivery target, and the rules `consent_states`, `include_welcomes`, `include_sync_groups`, and `include_commits`, applying `consent_states` of allowed only, `include_welcomes` `true`, `include_sync_groups` `false`, and `include_commits` `false` for a rule the app omits; disable them; read the notification state without a backend call; and set a conversation’s override to enabled, disabled, or none and read the conversation’s effective value. | | | PUSH-251 | Failures are distinguishable | An SDK MUST let an app distinguish, as distinct kinds, a failed state caused by each status in PUSH-267, a channel the deployment has not configured (PUSH-210), a topic limit (PUSH-217), a request timeout, and a client whose background tasks are disabled. | | ## Known limitations Anyone who holds a recipient can subscribe to any group-message or welcome topic. The push body carries no content, so what such a subscriber learns is that traffic exists on a topic, and when. The backend authorizes a publisher to a group-message topic only by a signature under its group id (API-230, API-300), and does not authorize a publisher to a welcome topic. A recipient is not bound to an installation. A revoked installation that still holds its recipient secret keeps renewing and receiving pushes until it stops or its app disables notifications. An operator who needs to cut off a revoked device does so through request authentication (AUTH-001). A subscription’s start position is read inside its transaction, but dispatch does not wait for open subscription transactions. An envelope settled after that read and dispatched before the transaction commits is above the start position and never delivered to the new subscription. Delivery is at-least-once-attempted. A crash, a change of dispatcher, a drain that runs out of time, or an attempt whose answer was lost after the request was sent repeats a delivery, and two dispatcher processes can overlap briefly while the role moves. APNs collapses repeats per topic on the device; a webhook receiver sees every one and deduplicates on `topic` and `sequence_id`. The backend reads recipients and subscriptions from a read replica when the deployment has one. A deletion or a removal takes effect for dispatch when the replica shows it, and a recipient deleted while a window is in flight may still receive that window. Sender suppression misses in four cases: the sender and the backend pick different HMAC epochs for a message sent near an epoch boundary; a message is sent before the sender’s keys reach the backend; the window after a root key cycle and before the re-upload; and an envelope whose 16 MiB check total (PUSH-230) is spent before the sender’s subscriptions are checked. A large message on a topic with many keyed subscriptions reaches that total, and anyone who knows a group’s topic can force it by subscribing keyed recipients whose ids sort first. Each results in a push to the sender’s own devices. Sender suppression needs the HMAC keys at dispatch, so the backend stores each subscription’s key window in clear, in the same store as the envelopes and their `sender_hmac`. Anyone who can read that store, a replica of it, or a backup can run the PUSH-230 check offline. A match names the recipient whose inbox sent a stored group message. When that recipient also subscribes to its installation’s welcome topic, the topic and the published identity updates name the inbox. A window covers three HMAC epochs, so one copy attributes the retained messages of the past and current epochs and, read beside later envelopes, those of the next. The live backend learns the same for every message it checks. The client sends subscription changes when its sync runs. A wake lost to a crash delays a change by at most one hour plus one request. The retention pass of PUSH-226 runs on the dispatcher, which exists only while at least one channel is configured. A deployment that removes every channel table keeps its recipients until a channel returns. Removing one channel’s table keeps the registrations for it; later deliveries on that channel fail without a provider request, and the recipients expire on their own. A failed `Unregister` is not retried while notifications stay disabled. The old delivery target keeps receiving pushes until the app enables notifications, which sends `Unregister` before `Register`, or disables them again, which sends `Unregister`, or until the backend deletes the recipient at expiry. An enable that follows a disable whose `Unregister` did not succeed deletes every subscription before it registers. An envelope that settles before the next sync run stores the desired set again is not pushed, because a new subscription starts at its start position (PUSH-216). The client cannot learn which topics the backend holds, only how many. A difference in a stored key window or `include_commits` that does not change the count is invisible until the client’s own staleness rules re-send the topic. The browser SDK and the wasm binding expose no notification surface, so a browser app cannot receive pushes. The notification RPCs are rate limited per topic a request adds (RATE section 2); a remove, a `Register`, and an `Unregister` cost only a request. A webhook host that does not exist answers `UNAVAILABLE`, so the client keeps retrying `Register` with backoff (at most hourly) until the app changes the URL or disables push; `enable` still returns the failure to the app. Host lookups for webhook `Register` share one pool of 32 per backend process, and a lookup that does not finish keeps its slot after `Register` answers, until the system resolver returns. A caller that keeps sending registrations for hosts whose lookups never answer holds every slot, and every other webhook `Register` on that process answers `UNAVAILABLE` and is retried with backoff (PUSH-267). Deliveries to stored recipients resolve their hosts outside this pool and continue. The backend learns a NAT64 prefix other than `64:ff9b::/96` and `64:ff9b:1::/48` only from the answer for `ipv4only.arpa` ([RFC 7050 §3](https://www.rfc-editor.org/rfc/rfc7050#section-3)), which it looks up beside each webhook host check. When that lookup fails, takes longer than 5 seconds, finds no free slot in the `Register` lookup pool, or the network’s DNS64 does not synthesize that name, a webhook host under the network’s own prefix that embeds a private IPv4 address passes PUSH-256; the operator can set `allowed_domains`. # Backend rate limits The backend charges every request to a caller and refuses work a caller has no allowance for. Each request costs units in one or more categories of work, such as envelopes published or topics queried, and the backend spends that cost against the caller’s limits for the category before it does the work. A spend that would exceed a limit is refused with the delay after which the same spend can be admitted. Without this, one caller can make the backend publish, read, verify chain signatures, and hold stream state without bound, and every other caller pays for it. ## Scope In scope: which caller a request is charged to; the categories of work and the cost of each request in each; what a limit admits; which limits apply to a caller; how a stream pays for what it holds and reads; the rejection a caller receives and what a client does with it; the memory the limiter may use. Out of scope: credentials and admission (AUTH); the configuration keys, their types, and their checks (CONF section 1.2); the status code table (API section 7); the per-stream frame buckets (API-258); request bounds (API section 7); the metric families (OPS section 5). | Related | Relation | | ------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [AUTH](/specs/auth-backend-auth/) | Admits the request and names the API key or JWT claims this spec forms a caller key from. A request auth rejects is never charged. | | [API section 7](/specs/api-backend-api/#7-bounds-errors-and-transport) | Owns the status code of a rate-limit rejection. This spec owns its details and what a client does with them. | | [CONF section 1.2](/specs/conf-backend-configuration/#12-keys-and-checks) | Owns the `rate_limits` keys and their checks. This spec owns what the keys mean and the default limits. | | [OPS section 5](/specs/ops-backend-operations/#5-telemetry) | Owns the rate-limit metric families. OPS-014 keeps `X-Forwarded-For` values and any client address computed from them out of telemetry, and AUTH-027 keeps JWT claim values out. | | [PUSH section 8](/specs/push-push-subscriptions/#8-the-client) | PUSH-267 keeps notifications enabled after a rate-limit rejection. | ## Terms | Term | Meaning | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Caller key | The value a request’s charges are recorded under, formed under RATE-001. | | Auth type | `api_key`, `jwt`, or `ip`: the form of a caller key. | | Client address | The IP address RATE-002 selects for a request. | | Trusted proxy | An address inside a network listed in `rate_limits.trusted_proxies`, which lists none by default. | | Category | A named kind of work with its own unit and limits, listed in the category table. | | Cost | The number of units of one category a step of a request charges. | | Limit | A `count` of units and a `window_seconds`. | | Spend | One charge of one cost in one category to one caller key, admitted or denied as a whole. | | Retry delay | The time RATE-024, or RATE-032 for a rent denial and RATE-034 for a catch-up-target denial, reports with a denied spend. | | Earned back | An admitted spend of cost n at time t under a limit with `count` C and `window_seconds` W is earned back at max(t, E′) + n × W / C, rounded down to a whole nanosecond, where E′ is when the spend admitted before it under that limit for the same caller key was earned back. | | Stream rent | The `stream_rent` cost a stream prepays for each 60-second period it stays open. | | Catch-up read | A read of the store a stream makes to deliver the envelopes of its registrations above their cursors. The read of an `Update`’s catch-up target is not one. | ## 1. Callers A request is charged to the most specific identity the backend holds for it. An API key names an operator’s own caller. A JWT names a user of an identity provider by its issuer and subject; two issuers can issue the same subject, so the issuer is part of the key. A request with neither is charged to the address it came from. A backend runs behind a proxy, which terminates TLS and connects from its own address. The proxy appends the address it received the request from to `X-Forwarded-For`, and every hop before it may have done the same, or the caller may have written anything at all. Only the entries written by proxies the operator trusts are evidence, so the backend reads the list from the right, skips the trusted proxies, and stops at the first address it does not trust. An IPv6 subscriber typically holds a whole /64, so the backend treats the /64 as one caller. | ID | Title | Requirement | Why | | -------- | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | RATE-001 | Caller key by credential | When auth admits a request under an API key (AUTH-006), the backend MUST charge it to the auth type `api_key` with the key’s name; when auth admits a JWT whose claims carry `sub`, to the auth type `jwt` with the token’s `iss`, or the empty string when it has none, and its `sub`; otherwise to the auth type `ip` with the client address. Two caller keys with different auth types MUST NOT share a charge. | Keyed on `sub` alone, a user of one trusted issuer spends the allowance of a user of another; an API key named like an address would share that address’s charges. | | RATE-002 | Client address from trusted proxies | When the peer address of a request’s connection is a trusted proxy and the request carries one or more `X-Forwarded-For` headers, the backend MUST read their comma-separated entries in header order as one list and select, scanning from the right, the first entry that is an IPv4 or IPv6 address and not a trusted proxy, or the leftmost entry when every entry is a trusted proxy; when an entry it scans before it selects one is not an IPv4 or IPv6 address, or when the peer is not a trusted proxy or no such header is present, the backend MUST select the peer address. The backend MUST compare an IPv4-mapped IPv6 address with `rate_limits.trusted_proxies` as its IPv4 address. | A header from a peer the operator does not trust is whatever the caller wrote, so a caller could charge every request to a fresh address or to a victim’s; an IPv4 proxy seen on a dual-stack listener would otherwise never match its network. | | RATE-003 | IPv6 callers by /64 | When the client address is an IPv4-mapped IPv6 address, the backend MUST form the caller key from the IPv4 address, and when it is any other IPv6 address, from its first 64 bits. | One subscriber holds a whole /64, and a key per address would give that subscriber 2^64 fresh allowances. | ## 2. Categories and costs The category table is the whole list of charges. A request charges only the categories whose rows name it; a health request, a `GetConfiguration` request, and a request to a path no service implements charge nothing. A cost is counted in the request as the backend received it, before duplicates or repeated topics are merged. A step is charged before it runs, so a denied step does no work, and a step an earlier denial prevented is never charged. Every charged RPC spends 1 `request` unit, and a denial of that spend decides the request’s status over every condition of API section 7, PUSH-264, and the PUSH and ATCH admission tables (RATE-014). Every other charge is spent by the step that does the work it pays for, before that work (RATE-010). Each category’s cost for one step is spent whole, in one spend. A request refused after a spend keeps that spend and is charged nothing more. A `request` unit pays for one RPC, for one read of the store a stream makes to catch up, or for the read of the catch-up target of an `Update` that newly registers topics. Reading one topic and reading the most topics the request bounds of API section 7 allow cost the same unit, because both are one read of the store and those bounds cap the work of one read. | Category | Unit | Charged by | Cost | | ----------------- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | `request` | request or store read | every charged RPC; each read of the store a stream makes to catch up its registrations; each `Update` that newly registers a topic, for the read of its catch-up target | 1 | | `publish` | envelope | `Publish` | The number of entries in `envelopes`, or 1 when there are none | | `identity_update` | identity update | `Publish` | The number of entries in `envelopes` whose payload is an `IdentityUpdate` | | `chain_verify` | signature | `Publish`; `VerifySmartContractWalletSignatures` | For a publish, the number of ERC-6492 signatures across its identity updates; for a verify request, the number of request entries, or 1 when there are none | | `push` | topic | `UpdateSubscriptions`, at check 2 of the PUSH admission table | The number of entries in `adds` | | `upload` | upload | `CreateUpload`, at the row of the ATCH admission table that names it | 1 | | `stream_rent` | rent unit per 60 s | an open stream | 1 + ceil(registered topics / 1000) for each period, under RATE-030 and RATE-031 | | ID | Title | Requirement | Why | | -------- | ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | RATE-010 | Charge before work | When a request reaches a step the category table charges, the backend MUST spend that step’s cost for the request’s caller key before it reads the store, calls a chain, stores an envelope, registers a topic, stores a subscription, or obtains a storage credential for that step, and when the spend is denied MUST NOT perform the step. | A charge after the work lets a caller over its limit still make the backend do the work. | | RATE-011 | Only the category table charges | The backend MUST NOT charge a request a category the category table does not give it, or more units of a category than the table gives it, and MUST NOT charge a health request, a `GetConfiguration` request, a request to a path no service implements, or a request that auth rejects. | An operator sizes a limit from the table; a charge it does not list denies callers for work they did not do, and a charged `GetConfiguration` locks a client out of learning the deployment’s requirements. | | RATE-012 | Exempt while disabled | While `rate_limits.enabled` is `false`, the backend MUST NOT deny any request or stream under this spec. | | | RATE-014 | Request charge first | When the `request` spend of a charged RPC is denied, the backend MUST fail the request with the rejection RATE-040 gives, whatever condition of the API status table, a bound of API section 7 or PUSH-264, or an admission table of PUSH or ATCH the request also meets. | A rule that let a later check decide the code would make the backend decode and validate a request it refuses for its caller’s allowance. | ## 3. Limits A limit admits a sustained rate of `count` units per `window_seconds`, with a burst of up to `count` units. A caller that has spent nothing for a whole window can spend its whole count at once, and over any span of time a caller is admitted at most one count plus the units the rate earns in that span, except that one spend larger than a count is admitted whole when every earlier spend has been earned back. A spend larger than a limit’s count is admitted only when every earlier spend under that limit has been earned back, and the caller then waits until the rate has earned back the whole cost, so one large request cannot do more work than the rate allows. A category can carry up to three limits on different windows, for example a minute and an hour; a spend must fit every one of them, and a spend that does not fit one charges none of them. The limits that apply come from the most specific configuration that names the caller: an override for its caller key, else the limits for its auth type, else the category’s `default`, else the default limits table below. An empty list of limits admits every spend. | Category | Default limits | | ----------------- | -------------------------------- | | `request` | 6000 per 60 s; 200000 per 3600 s | | `publish` | 1000 per 60 s; 20000 per 3600 s | | `identity_update` | 10 per 60 s; 100 per 3600 s | | `chain_verify` | 200 per 60 s; 2000 per 3600 s | | `push` | 2000 per 60 s; 20000 per 3600 s | | `upload` | 120 per 60 s; 2000 per 3600 s | | `stream_rent` | 120 per 60 s | | ID | Title | Requirement | Why | | -------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | RATE-020 | Admission rule | On one instance, while it keeps a caller key’s state, for each limit with `count` C and `window_seconds` W that applies to the caller key in a category, let E be the time every spend the instance admitted under that limit for the caller key is earned back, or the spend’s own time t when that is later; the backend MUST admit a spend of cost n > 0 when, for every such limit, E + n × W / C − t is not greater than W, or n is greater than C and E equals t, and MUST deny it otherwise. A spend of cost 0 MUST be admitted with no charge. | A rule that admits more does not bound the work the limit was set to bound; one that admits less refuses callers within their limits, or refuses a request larger than a count for ever. | | RATE-022 | Denial charges nothing | When a spend is denied, the backend MUST NOT charge any limit of that category for it. | A denied request that still spends allowance lets a client that retries too early lock itself out for ever. | | RATE-024 | Exact retry delay | When a spend is denied, other than a `stream_rent` spend whose delay RATE-032 sets or a `request` spend whose delay RATE-034 sets, the backend MUST report as retry delay the whole number of milliseconds, rounded up, after which the same spend is admitted on that instance if the caller key spends nothing more in that category there and the instance keeps its state until then; the same spend made 1 ms before that delay MUST be denied. | A delay that is too short brings the retry back to be denied; one that is too long holds a client off longer than its limit requires. | | RATE-025 | Most specific limits apply | When `rate_limits.overrides` holds an entry for the request’s caller key that names the category, the backend MUST apply exactly that entry’s limits for the category; otherwise, when the category’s configuration names the caller key’s auth type, exactly those limits; otherwise, the category’s `default`, or the default limits table when the category sets no `default`. An empty list MUST admit every spend in that category. | An operator who raises a bot’s limits must not find a general limit still capping it. | ## 4. Streams A stream costs the backend memory for every topic it holds, for as long as it stays open, and a read of the store for every batch of history it catches up on. Delivering a live envelope costs almost nothing: the backend reads each new envelope once and hands it to every stream that holds its topic. A stream therefore pays rent for what it holds, a `request` unit for each catch-up read, and a `request` unit for the catch-up target of each `Update` that newly registers a topic, and live delivery is free. Rent is prepaid for each 60-second period, starting at open, so it also bounds how many streams a caller can open and keep open. An `Update` that raises the rent within a period pays the difference before its topics are registered; one that lowers it is not refunded. When any rent spend is denied, the backend ends the stream, because ending it is the only way to release what it holds; the client reconnects from its cursors, so nothing is skipped (API-254), and the rejection’s retry delay covers the whole rent the replacement stream pays for those topics, its open included (RATE-032). When a catch-up read is denied, the backend reads nothing for those registrations until the retry delay has passed, and keeps the stream open. When the `request` spend for an `Update`’s catch-up target is denied, the backend ends the stream, with a delay that covers the replacement stream’s `Subscribe` and that read (RATE-034). That unit is spent before any topic of the update is registered, and the target is read after registration (API-252). An `Update` whose rent or catch-up-target spend is denied is not accepted: the stream ends before its `Applied`. | ID | Title | Requirement | Why | | -------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | RATE-030 | Rent is prepaid | When a stream opens, and when each 60-second period after its open begins, the backend MUST spend `stream_rent` of 1 + ceil(t / 1000) for that period, where t is the number of topics registered on the stream at that moment, or the number in `topics` for a `SubscribeStatic` open. | A stream that pays only to open holds topics for hours at the price of a minute. | | RATE-031 | Updates pay rent before registering | When an `Update` would leave t’ topics registered on a stream and 1 + ceil(t’ / 1000) is greater than the `stream_rent` already spent for the current period, the backend MUST spend `stream_rent` equal to the difference before it registers any topic of the update or sends its `Applied`. | An update that registers topics before paying for them holds memory the caller has no allowance for. | | RATE-032 | Rent denial ends the stream | When a `stream_rent` spend under RATE-030 or RATE-031 is denied for an open stream, the backend MUST end the stream with the rejection RATE-040 gives and MUST NOT register any topic of the update whose spend was denied. The retry delay of that rejection MUST be the RATE-024 delay for one spend of 1 + ceil(t’ / 1000), where t’ is the number of topics the stream would hold had the denied spend been admitted. | Paused delivery keeps every registration in memory; only ending the stream releases it. A delay that covers only the denied spend is short by the open charge of the replacement stream, so the reopened stream is denied again on every retry. | | RATE-033 | Read denials delay, never skip | When the `request` spend for a catch-up read is denied, the backend MUST NOT read or deliver envelopes for the registrations that read covers before the retry delay has passed, MUST keep the stream open, and MUST retry the spend no earlier than the retry delay. | A caller over its read allowance would otherwise lose its stream, and reconnecting costs more reads than waiting. | | RATE-034 | Target-read denial ends the stream | When the `request` spend for the read of an `Update`’s catch-up target is denied, the backend MUST end the stream with the rejection RATE-040 gives, MUST NOT register any topic of that update or send its `Applied`, and MUST report as retry delay the RATE-024 delay for one spend of 2 `request` units. | A delay that covers only the denied spend is short by the `request` unit of the replacement stream’s `Subscribe`, so the reopened stream’s `Update` is denied again on every retry. | ## 5. Rejection A rate-limit rejection says that the request was refused for its caller’s allowance, in which category, and how long to wait. It uses the standard gRPC error details, so any gRPC client library can read the delay. API section 7 gives the status code. | Detail | Field | Value | | ------------------------------------------------------------------------------------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------- | | [`google.rpc.ErrorInfo`](https://github.com/googleapis/googleapis/blob/master/google/rpc/error_details.proto) | `reason` | `RATE_LIMITED` | | | `domain` | `xmtp.org` | | | `metadata` | one entry, `category`, whose value is the category name from the category table | | [`google.rpc.RetryInfo`](https://github.com/googleapis/googleapis/blob/master/google/rpc/error_details.proto) | `retry_delay` | the retry delay of RATE-024, or of RATE-032 for a `stream_rent` denial and of RATE-034 for a catch-up-target denial | | ID | Title | Requirement | Why | | -------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------- | | RATE-040 | Rejection details | When the backend fails a request or a stream because a spend was denied, it MUST attach to the status the `google.rpc.ErrorInfo` and `google.rpc.RetryInfo` details the rejection table gives, and MUST NOT put the caller key, the client address, or any credential value in the status message. | A client that cannot tell a rate limit from an oversized request splits the request and multiplies the load (CONF-073). | | RATE-041 | Client waits the retry delay | When a request or a stream fails with an `ErrorInfo` whose `reason` is `RATE_LIMITED` and whose `domain` is `xmtp.org`, the client MUST NOT resend that request through its own retry of the refused call, or open a stream to replace that stream, before the `RetryInfo` delay has passed, and MUST NOT split that request into smaller requests because of the rejection. When such a rejection carries no `RetryInfo`, or a negative `retry_delay`, the first sentence sets no minimum wait. | A retry or a reopened stream inside the delay is denied again and spends the caller’s allowance on nothing. | ## 6. Memory The limiter’s memory is fixed by `rate_limits.max_memory_mib` and does not grow with the number of callers. A caller back at full allowance holds no state. A caller key can be recorded in only a small part of the state. When that part has no room, the backend forgets a caller recorded there, rather than refuse a request, so a flood of new callers costs other callers some of their recorded spend, never their admission. | ID | Title | Requirement | Why | | -------- | ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | | RATE-050 | Memory bound | The backend MUST NOT hold more than `rate_limits.max_memory_mib` MiB of rate-limit state, whatever the number of caller keys. | A flood of fresh addresses would otherwise grow the state until the instance is killed. | | RATE-051 | Full state never denies | When the backend has no room to record a caller key’s state where that key can be recorded, it MUST NOT deny a spend because of that, and MUST forget instead the state, among those it could replace, whose admitted spends are all earned back soonest. | Refusing new callers when full lets a flood of fresh keys deny service to every caller it did not already know. | | RATE-052 | State is kept until earned back | The backend MUST keep a caller key’s state for a limit until every spend the instance admitted under that limit for that key is earned back, unless it forgets that state under RATE-051 or the instance restarts. | A limiter that forgets state early admits more than the limit, and no other row refuses it. | ## Known limitations Limits apply per instance. A deployment that runs N instances behind a balancer admits up to N times each limit to a caller whose requests are spread across them. An instance forgets every caller’s spend when it restarts. It also forgets a caller’s spend under RATE-051, which can start long before the whole state is full, because a caller key can be recorded in only a small part of it. The caller forgotten is the one whose spends are earned back soonest, so a heavy spender is forgotten last. A forgotten caller receives a fresh allowance. A caller that floods fresh caller keys gains more from the fresh allowances of those keys than from what its flood makes the instance forget. Callers behind one IPv4 address, such as the subscribers of a carrier-grade NAT, share one caller key and one allowance when they hold no credential. Behind a proxy that `rate_limits.trusted_proxies` does not list, every caller without a credential is charged to the proxy’s address and shares one allowance. A listed proxy that passes on a client’s `X-Forwarded-For` without appending the address it received the request from lets that client choose the address it is charged to. A request that auth rejects is not charged, so a flood of requests with bad credentials is limited only by the cost of rejecting them. A step that is denied after an earlier step of the same request was admitted keeps the earlier charge. RATE-041 holds the client’s own retries of a refused request, not a request an app’s next action sends: a sync resends a publish that failed, an upload the app retries begins with `CreateUpload` (ATCH section 4), and an enable sends `Register` (PUSH-266), any of them before the retry delay has passed. Such a request is denied again, and keeps the charge of each of its steps admitted before the denied one, its `request` unit included when that spend was not the one denied. # Message sending The path from an app call to a published envelope, and from the published envelope back to a confirmed message. An app needs to know what it can observe after a send fails, and whether retrying can duplicate a message. A queued send is durable before its message is published. Queued acceptance returns an id that the app can use to read the local message; confirmed completion waits for ordered processing of the echo and every required follow-up Welcome. An ordinary send can perform installation and proposal work before it queues the message. A returned id from a queue operation is not confirmed send completion. ```mermaid flowchart LR A[App call] -->|one transaction| S[(Message: Unpublished
Intent: to publish)] S -->|prepare once| P[(Attempt: exact bytes
Intent: published)] P -->|send| B[The backend] B -->|receipt| P B -->|echo on the group topic| O[Ordered processing
PROC] O -->|match by payload hash| C[(Message: Published
Intent: committed)] C -->|owed Welcomes sent| D[Intent: processed
send returns] ``` ## Scope In scope: what an app’s send stores before publishing its message; the message id and the idempotency key; preparing an attempt once and retrying its exact bytes; publish receipts; the order in which a group’s intents publish; confirmation through ordered processing; what an app observes for each failure; and what becomes of an intent that can never publish. Out of scope: publish atomicity and duplicate detection on the backend (API); receipt and ordered processing of the echo (PROC); what a commit contains and how it is validated (GMOD); building and wrapping Welcomes (JOIN); the guard comparison of an app-data write (META-065); the content encoding inside a message (CTYPE); consent recorded on send (CONS); and push flags (PUSH). | Related | Relation | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | PROC | Owns the receipt path, ordered processing, and delivery to app streams. This spec owns what a send stores, what it sends, and how the echo resolves it. | | API | Owns the publish RPC, the `message_hash` the backend assigns, and duplicate detection by that hash. This spec owns what the client sends and resends. | | GMOD | Owns the content and validation of commits. This spec owns how a commit intent is queued, published, and resolved. | | `META-065` | Owns the guard comparison for an app-data write. This spec owns what a guard miss does to the intent. | | EVENT | EVENT-001 reports a message status change; this spec owns when a sent message changes status. | ## Terms | Term | Meaning | | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Intent | A durable record of one change an app asked for in one group: a message to send or a state change to commit. | | Message intent | An intent whose payload is an application message. | | State-change intent | An intent whose payload is a commit or a proposal: a membership, metadata, permission, admin, key, or app-data change. | | Attempt | The exact envelope bytes prepared for an intent, together with the epoch and pending proposals they were built from. An intent has at most one current attempt. | | Receipt | The backend’s publish response for an attempt: the sequence id, timestamp, and `message_hash` of the stored envelope. | | Echo | The client’s own published envelope as ordered processing receives it on the group topic. | | Payload hash | SHA-256 over the MLS message bytes inside an envelope. The key by which an echo is matched to its attempt. | | Idempotency key | The `idempotency_key` of the `PlaintextEnvelope` a message is sent in: a string that distinguishes sends of equal content within a group. | | Message id | The 32-byte identifier of a stored message, derived under SEND-002. | | Rejected intent | An intent ordered processing or preparation refused for a reason a later attempt cannot change. | | Superseded intent | A guarded app-data intent whose guard no longer matched when it was prepared. | ## 1. The send is stored first The client stores a new message with `Unpublished` status and the work needed to publish it before sending that message. An optimistic queue operation returns after this durable acceptance. A normal send waits for SEND-011 before returning success and can do earlier network work to update installations or commit proposals. PROC-025 keeps an unpublished message off the app’s message stream. A message is sent inside a `PlaintextEnvelope`, whose `idempotency_key` distinguishes two sends of the same bytes. The message id is derived from the group id, that key, and the content bytes, and nothing else: not the epoch, not the ciphertext, and not the time. Every installation in the group derives the same id from the same envelope, so a reply or a reaction that names a message id names the same message everywhere, and a message the client stores twice, once optimistically and once from its echo, is one row. ```proto message PlaintextEnvelope { // Version 1 of the encrypted envelope message V1 { // Expected to be EncodedContent bytes content = 1; // A unique value that can be used to ensure that the same content can // produce different hashes. May be the sender timestamp. string idempotency_key = 2; } // The nested V2 definition is shown in the next excerpt. // Selector which declares which version of the EncodedContent this // PlaintextEnvelope is oneof content { V1 v1 = 1; V2 v2 = 2; } } ``` The second excerpt completes the nested `PlaintextEnvelope.V2` type. The outer selector and `V1` above are omitted from this excerpt only. ```proto message PlaintextEnvelope { // Version 2 of the encrypted envelope message V2 { reserved 3, 4; reserved "device_sync_request", "device_sync_reply"; // A unique value that can be used to ensure that the same content can // produce different hashes. May be the sender timestamp. string idempotency_key = 1; oneof message_type { // Expected to be EncodedContent bytes content = 2; // A serialized user preference update xmtp.device_sync.content.V1UserPreferenceUpdate user_preference_update = 5; } // Removed; moved to oneshot message reserved 6; reserved "readd_request"; } } ``` For V1, the message-id content bytes are the value of `V1.content`, before content decoding and without the surrounding protobuf field tags. The group id is its raw byte value and the key is UTF-8. V2 is a retained wire type for an earlier device-sync format; the current receive path consumes it without storing an application message, so it does not derive an application-message id from either V2 variant. An app that needs a retry to name the same message supplies the same key. SEND-002 defines message identity; it does not prescribe key generation when the app supplies none. Two defaults sit at the SDK boundary. A string handed to a send with no content type is text, so every SDK encodes it under the catalogue text type (CTYPE-014); the default applies to a send request, not to received content with a missing or unknown identifier (CTYPE-008). The push flag on the envelope (API-210) defaults to the catalogue value of the content type under CTYPE-010; a value the app supplies, including `false`, replaces that default, and an omitted options object or an options object with no push field leaves it in effect. | ID | Title | Requirement | Why | | -------- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | SEND-001 | Durable queued acceptance | When an app queues a new message, the client MUST durably store the message as `Unpublished` with its publish intent before publishing that message, and MUST return its message id only after that storage succeeds. A queue result MUST remain distinguishable from confirmed send completion under SEND-011. | A process crash, operating system crash, or power loss must not lose an accepted send. | | SEND-002 | Message id derivation | When the client stores a V1 application message, it MUST derive its id as SHA-256 over the raw group id, `0x09`, the UTF-8 `idempotency_key`, `0x09`, and the unmodified `V1.content` bytes of the `PlaintextEnvelope` defined above, in that order. | All installations need the same id for replies and deduplication. | | SEND-003 | Same sender, group, key, and content | When an app sends or prepares the same content and idempotency key in the same group and the stored sender inbox equals the client’s inbox, the client MUST reuse the stored message id without a second message or a second unresolved intent, including from another installation of that inbox. If the message is already `Published`, it MUST NOT publish it again; if a previous intent was rejected and a new retry intent is queued, it MUST set the existing message to `Unpublished` until that retry is confirmed or fails. When the stored sender inbox differs, the client MUST return a non-retryable sender-conflict error before changing that message or queueing its send intent, and the SDK MUST expose it as `InvalidInput` with code `MessageSenderConflict`. | A retry must preserve its sender and delivery state; another sender’s stored message must not be reported as a successful send. | | SEND-004 | Retries supply the key | When an app retries a send after a result other than success, the app SHOULD supply the idempotency key of the first send. | | | SEND-005 | No send into an inactive group | When an app sends into a group whose local state is inactive because a commit removed this installation, the client MUST refuse before it stores a message or an intent, with an error the app can distinguish. | A message stored for a group the client has left is never published and never fails. | | SEND-020 | A string sends as text | When an app sends a string with no content type, the SDK MUST encode it as `xmtp.org/text:1.0` under CTYPE-014 before it queues the message. | Two SDKs that default differently deliver the same message under different identifiers, and a recipient decodes one and not the other. | | SEND-021 | A supplied push value wins | When an app supplies a push value with a send, the client and SDK MUST set the envelope’s `should_push` to that value, including `false`, in place of the content type’s catalogue value. | An app that suppresses a notification and is overridden wakes recipients for a message it chose to send silently. | ## 2. Preparing and publishing an attempt Publishing an intent has two halves, and the boundary between them is what makes a retry safe. The first half runs under the state writer: the client builds the MLS message from the current group state, which advances its sender ratchet, and in the same transaction stores the exact envelope bytes, their payload hash, and the epoch and pending proposals they were built from. Only after that commits does the second half send the bytes. A crash between the two leaves an attempt the next round resends, and never a ratchet advanced for bytes nobody holds. An absent receipt can mean either that the backend never received the request or that it committed and its response was lost. API-211 owns the authoritative hash and API-222 owns duplicate publication. An ambiguous result preserves the attempt and its exact bytes, including required follow-up Welcome batches. A confirmed backend refusal has no echo to wait for; an ambiguous transport failure does not establish refusal. API-284 prohibits an unchanged request after `OUT_OF_RANGE`, while API section 7 permits that status after a publish committed. SEND-007 preserves the attempt without requiring a prohibited resend. API-290 is the recovery contract: a `Query` of the topic after that status returns each committed envelope with its original receipt, and an envelope it does not return was not stored. The client retains the exact envelope bytes, including required follow-up Welcome batches, while any outcome is unknown, and neither replaces, re-encrypts, nor terminally fails that work until the recovery read establishes its outcome. Preparation can also fail locally before any publish. CONF-073 owns the size bound. A definite local request-shape failure or a backend refusal that proves non-commit ends the affected attempt under SEND-009. It does not leave a state-change intent waiting for an echo that cannot arrive. | ID | Title | Requirement | Why | | -------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | | SEND-006 | Preserve prepared publication | When the client prepares an intent or a required follow-up Welcome batch, it MUST durably preserve the exact envelope bytes before publishing them, together with the payload hash and base epoch for the group attempt and any staged state needed to apply it. A failed preparation MUST leave neither advanced sender state nor a partial prepared publication. | Regenerating lost ciphertext consumes another sender generation. | | SEND-007 | Preserve bytes while outcome is unknown | While a group attempt or required follow-up Welcome batch has an unknown publish outcome, the client MUST retain its exact prepared bytes and MUST NOT replace or re-encrypt them. Any retry permitted by API-284 MUST reuse those bytes; an `OUT_OF_RANGE` result MUST use the recovery read of API-290 instead of an unchanged request. | An ambiguous response can follow a committed publish. | | SEND-008 | A receipt binds to its attempt | When a publish response arrives, the client MUST attach it only to the current attempt or follow-up Welcome batch whose bytes were sent, preserve its `message_hash` unchanged under API-211, and discard a response for an obsolete attempt. | A late reply must not confirm different bytes. | | SEND-009 | Definite refusal ends publication | When preparation proves a request unsendable under CONF-073 or its request-shape checks, or the backend definitively refuses it without committing, the client MUST reject the affected intent, set its application message to `Failed`, and permit later intents to proceed without waiting for an echo. It MUST NOT classify an ambiguous transport failure or a status that can follow commit as such a refusal. | A refused request cannot produce the echo needed to release later work. | ## 3. Order within a group One installation publishes a group’s intents in the order the app queued them. Message intents publish in that order, several in one request when they are adjacent. A state-change intent is different: it produces a commit against a specific epoch, and until its echo says whether that commit landed, the client does not know what epoch the next intent must be built against. A published state-change intent therefore holds every intent behind it, and the client prepares at most one state-change attempt per group at a time. No application message can be built while the group holds a pending proposal; a commit that consumes the proposal comes first. A message intent that meets a pending proposal therefore stays queued, and every message queued after it waits too, including one that already holds an attempt, even when another member’s commit clears the proposal meanwhile. The client goes on to the state-change intents behind it, one of which can commit the proposal. When none of them does, the client queues a commit of the pending proposals itself. That commit is queued after the messages it releases, so a send waiting on one of them waits through the receipt of whichever state change is published. The deferred messages then publish in the next epoch, in queue order. | ID | Title | Requirement | Why | | -------- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | SEND-022 | Publish in queue order | The client MUST publish a group’s intents in the order they were queued, except that a message intent it cannot build because the group holds a pending proposal MUST stay queued, without failing, while the client prepares the later state-change intents. Every later message intent, including one that holds an attempt, MUST stay queued behind it, and if no later intent commits the proposal, the client MUST queue a commit of the pending proposals. It MUST NOT prepare any intent for a group while a state-change intent of that group is published and its echo is not yet applied or rejected. | A message built before the pending commit resolves is built against an epoch that may not exist, and a message held at the head of the queue blocks the commit that would clear the proposal. A pending proposal no queued intent commits would hold every message. | ## 4. Confirmation A publish receipt says the backend stored the envelope. It does not say the group accepted it: a commit can be superseded by another member’s commit that landed first, and a message is not in the group’s history until the client has applied its own envelope in sequence. The send therefore waits for its echo through ordered processing, with the receipt’s sequence id as the target under PROC-015. Success is the intent applied, and for a membership commit, the Welcomes it owes sent. The echo is matched to its attempt by payload hash, computed over the MLS message bytes the envelope carries. The receipt is not needed for the match, so an echo that arrives before the response still resolves the attempt. A commit echo from a past epoch is resolved under the stale-commit rule GMOD-036: the client does not apply it and rebuilds the change on the current state before it publishes again. A future epoch is a rejection under PROC-011, not a lost-race retry. Application-message and proposal intents do not use the staged-commit equality check; their validation is defined in PROC section 3 and GMOD. When intent synchronization ends while a receipt exists but ordered processing has not resolved the attempt, the result is published but unconfirmed. The attempt remains current for later synchronization. The call has a retry budget and a deadline; neither ends the durable attempt. The wait starts inside intent synchronization, after earlier installation and proposal work, and can end before its deadline. This spec does not promise a fixed duration from the send call. | ID | Title | Requirement | Why | | -------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | SEND-011 | Success includes required follow-up | The client MUST report confirmed send success only after ordered processing applies the intent’s echo and the backend acknowledges every required follow-up Welcome envelope, including pointers and pointees. It MUST preserve unresolved follow-up work under SEND-006 and SEND-007 across interruption and MUST NOT report success on the group publish receipt alone. | A membership change is incomplete for recipients without their Welcomes. | | SEND-024 | Follow-up outcomes stay per intent | While an intent’s echo is applied and its required follow-up Welcome batch is not yet acknowledged, the client MUST report confirmed success for a later intent of the same group once SEND-011 holds for that later intent, without waiting for the earlier batch. | A send unrelated to a stuck membership change otherwise returns published but unconfirmed, and the app cannot tell a delivered message from one that needs a sync. | | SEND-012 | Match the echo by payload hash | When ordered processing receives an envelope whose sender is this installation, the client MUST match it to an attempt by the SHA-256 of the envelope’s MLS message bytes equal to the attempt’s payload hash, and MUST NOT require the receipt to make the match. | An own envelope processed as a stranger’s cannot be decrypted, so the message is rejected and never confirmed. | | SEND-013 | Confirmation completes the message | When the client applies a message intent’s echo, it MUST set the message’s status to `Published`, its sequence id to the envelope’s, and its sent timestamp to the backend’s timestamp on the envelope, in the transaction that applies the envelope. | A timestamp taken from the sender’s clock differs on every installation, so members disagree on the order of messages. | | SEND-014 | Rebuild a stale commit | When an own commit echo names an epoch less than the group’s current epoch, the client MUST resolve the attempt under GMOD-036 before preparing its replacement. It MUST NOT use that recovery for a future-epoch echo or apply it to every state-change intent regardless of payload kind. | A proposal and a staged commit have different validation rules. | | SEND-015 | Published but unconfirmed | When intent synchronization ends with a publish receipt but no ordered resolution of the attempt, the client MUST return a typed published-but-unconfirmed result, keep the attempt current, and MUST NOT prepare a replacement because the call ended. | Ending the wait does not undo the backend publication. | | SEND-016 | Rejection completes message status | When ordered processing terminally rejects an intent’s echo for a reason other than a stale epoch, the client MUST reject the intent with a stable reason code, set its application message to `Failed`, and return that reason to the waiting send. | A rejected message left pending misleads the app. | ## 5. Intents that cannot publish Three things end an intent without a successful echo. A rejection under SEND-009 or SEND-016. A guard miss under META-065: the committed value no longer matches the write’s guard, so the intent is superseded without publication. And removal: a commit that removes this installation makes every unpublished or unresolved intent of that group unpublishable, and the messages behind them are failed so that the app does not show them as pending for ever. An intent whose commit was applied before the removal still owes its Welcomes and completes them. | ID | Title | Requirement | Why | | -------- | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | SEND-017 | A superseded guard is terminal | When the client prepares a guarded intent whose guard no longer matches the committed value, it MUST mark the intent superseded without publishing, MUST NOT retry it, and MUST return a result the app can distinguish from a rejection. | Retrying a stale write spins until the deadline; reporting it as an error tells the app something broke when nothing did. | | SEND-018 | Removal fails pending intents | When the client applies a commit that removes this installation from a group, it MUST mark every intent of that group that is unpublished, or published with no applied echo, as rejected, and MUST set each such message intent’s message to `Failed` status, in the transaction that applies the removal. | A message left `Unpublished` in a group the client has left is shown as pending for ever. | | SEND-023 | Settle saved Welcomes before failing | When an envelope of a saved required follow-up Welcome batch has no backend acknowledgement and exceeds a bound that CONF-073 applies under the current limits, the client MUST read the topics of the batch’s unacknowledged envelopes with a `Query` made after that check before it ends the intent under SEND-025. It MUST end the intent only when an envelope that read does not return exceeds such a bound, and otherwise MUST publish the envelopes that read does not return again, unchanged. | Saved bytes may already be stored (API-224), so ending the intent before that read reports a delivered membership change as unsendable. | | SEND-025 | Unsendable follow-up ends the call | When a required follow-up Welcome batch of an intent whose echo is applied cannot be sent under CONF-073 (for a saved batch, as SEND-023 decides), or the backend refuses a request that carries one of its envelopes with `INVALID_ARGUMENT`, the client MUST end that intent in a terminal state and MUST NOT publish any envelope of that batch after it ends the intent. It MUST report to the call waiting on that intent that the membership change is applied but its Welcomes were not sent. | Without an end state the same batch fails on every sync and a refused request is sent again (API-284). A plain rejection would tell the app that the membership change failed, although the commit is applied and the members have changed. | | SEND-027 | Check Welcomes before the commit | When a client prepares a commit for an intent that adds members or installations and the commit’s echo requires a follow-up Welcome batch, it MUST NOT publish the commit if, for any commit cursor, one of that batch’s envelopes would be longer than `max_envelope_bytes` under the current limits (CONF-073). | Once the commit is applied, the batch can only end under SEND-025, which leaves the added installations without a Welcome until a member removes and re-adds them. | | SEND-019 | Outcomes are distinguishable | An SDK MUST expose the distinct send outcomes in the outcome table below and preserve a rejected intent’s stable reason code. It MUST NOT report queued acceptance or an unknown publish outcome as confirmed completion or definite refusal. | The app needs to decide whether to wait, retry, or correct its request. | | SEND-026 | Deleting an unsent message cancels it | When an app asks to delete an `Unpublished` or `Failed` message that this installation stored for sending and that passes CTYPE-018, the client MUST remove the message and every queued message intent for it in one write, without publishing a deletion. If a message intent for it holds an attempt that is not rejected, the client MUST instead change nothing and return an error that the SDK exposes as `InvalidInput` with code `MessageInFlight`. | A deleted unsent message could otherwise still be published. | The outcome names below are semantic kinds; an SDK can use its language’s typed representation. An absent receipt is not a stable rejection code. A rejection code identifies the validation class without including payload or key material. | Outcome | Meaning | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------- | | Queued | Durable local acceptance; no claim that publishing succeeded | | Confirmed | SEND-011 holds | | Inactive group | The installation was removed; no new send is accepted | | Unsendable or refused | A local request failure or backend refusal proves no publication for the affected work | | Rejected | Ordered processing refused the echo, with its stable validation reason | | Superseded | A guarded change was not published because its guard no longer matched | | Published but unconfirmed | A receipt exists but ordered resolution did not complete before the wait ended | | Outcome unknown | No receipt or definite non-commit result establishes whether publication occurred; the same prepared work remains pending | ## Known limitations A published state-change attempt whose echo never resolves blocks later intents in its group. Each synchronization call ends under its retry budget or deadline, but no durable age or attempt limit releases that blockage. An attempt with receipts is not republished; an attempt without receipts remains eligible to retry its saved bytes subject to API-284. A later sync can resolve the work, and removal rejects unresolved intents under SEND-018. Rejected echoes can leave message status `Unpublished`. A call without an app-supplied idempotency key can use a new key. Retrying without the first key can publish the same content under a second id. Confirmation also replaces the provisional sent timestamp under SEND-013, so a message ordered by that timestamp can move. Message ids exclude the sender, and received messages keep the first stored sender for an id. A member who knows the key and exact content can publish them first, including a replay to an installation that never stored the original; installations can then disagree on the sender and on deletion authority. The send-side conflict check does not reconcile received rows; the existing id derivation is retained for compatible reply, reaction, and deletion references. V2 plaintext envelopes are decoded but produce no stored application message. Their fields remain in the wire type; no V2 application-message id derivation is promised. Only `INVALID_ARGUMENT` is treated as a definite backend refusal. Every other publish failure keeps its attempt pending, except `OUT_OF_RANGE`, which the recovery read settles. After `OUT_OF_RANGE`, a Welcome envelope the recovery read did not return is published again with its saved bytes. The client assumes that a deployment carries every request within the limits it published, so the status came from a response to a larger request. A deployment that refuses a single envelope within those limits as too long receives that envelope again. An intent ended under SEND-025 leaves some installations its commit added without a stored Welcome, and the client does not report which. Under SEND-027 this happens only for a commit that carries another member’s pending Add, or when the limits shrink between preparing the commit and sending its Welcomes. They cannot join from that commit, and raising the deployment’s bounds afterwards does not resume the batch; removing and re-adding the members that change added gives each of them a new Welcome. The read of SEND-023 can miss an envelope whose publish committed but whose response the backend never sent, because API-202 covers only a sent response; such an intent ends as unsendable although that recipient has its Welcome. # Specification format This document defines how libxmtp specifications are written, admitted, numbered, linked to code, and changed. A spec is a long-lived statement of the promises the system keeps. It is not a description of the current implementation and not a plan for one change. This document is a guide with requirement identifiers, so the checker, the skills, and reviewers cite one source. Section 6 lists the rules it exempts itself from, and why. ```mermaid flowchart LR A[Author drafts
authoring-specs] --> R[Adversarial review
reviewing-specs] R --> O[Owner review
in the PR] O -->|status: approved| S[(specs/PREFIX-slug.md)] S --> C[Code and tests
implements: / verifies:] C --> K[just spec-check
in just lint] W[specs/waivers.toml] --> K ``` ## Scope In scope: every file in `docs/specs/`, the requirement identifier scheme, the admission test, backlinks from code and tests, waivers, the checker, and the “Spec changes” section that plans carry. Out of scope: the format and tooling of plans, design notes under `docs/` and in module READMEs, and the XIP process. | Related | Relation | | ------------------------ | ----------------------------------------------------------------------------------------------------------------- | | `docs/specs/GLOSSARY.md` | Names the actors and shared terms every spec uses. Definitions only; obligations live in requirements (SPEC-072). | | `docs/specs/PREFIXES.md` | The registry of requirement prefixes. Read by the checker. | | `docs/specs/README.md` | The capability map: which spec owns what. Informative. | ## Terms | Term | Meaning | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Author | The person or agent that drafts or amends a spec. | | Reviewer | The agent that reviews a draft before an owner sees it. | | Owner | A human who approves a spec by reviewing its PR. | | The checker | `just spec-check`, `just spec-index`, and `just spec-show`. | | Requirement | One row of a requirements table, in the form of SPEC-034. | | Normative text | Text that creates an obligation: a requirement row, and whatever a requirement points at (SPEC-041). | | Design note | A Markdown file under `docs/` or a module README that explains mechanisms and choices. Never normative. | | Legacy spec | A superseded document with `status: legacy`: being replaced. It stays binding for obligations whose replacement is not yet approved (SPEC-011), and is deleted under SPEC-012. | ## 1. Files One spec is one file. The file name carries the prefix so a reader who sees `JOIN-012` in code knows where to look. The frontmatter is the only machine-read metadata; everything else the checker needs, it parses from the body. | ID | Title | Requirement | Why | | -------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | SPEC-001 | One file per spec | A spec MUST be one Markdown file in `docs/specs/` named `PREFIX-slug.md`, where `PREFIX` is the spec’s prefix in uppercase and `slug` is lowercase words joined by hyphens. | | | SPEC-002 | Frontmatter keys | A spec MUST begin with YAML frontmatter with the keys `prefix` and `status`, whose value is `draft`, `approved`, or `legacy`, and MAY carry `owns` listing identifiers it holds from another prefix. | | | SPEC-003 | Section order | After the title and its summary paragraphs, a spec MUST contain `## Scope`, then `## Terms`, then numbered capability sections `## 1.` to `## N.` in ascending order, then optionally `## Known limitations` as the last section. | | | SPEC-004 | Owner sets status | An author MUST NOT set `status: approved`. Only an owner’s review of the PR changes a spec to `approved`. | | | SPEC-005 | Size ceiling | A spec other than this one MUST NOT contain more than 150 requirements. When a draft exceeds the ceiling, the author MUST split it into two specs. | | | SPEC-006 | No implementation names | A spec MUST NOT name files, modules, functions, or crates, and MUST NOT contain phase or sequencing language, status prose, review logs, or revision numbers. Transport identifiers are the exception, under SPEC-040. | | | SPEC-007 | Platform choices are not requirements | A spec MUST NOT state platform choices such as the database engine, the process model, or a storage library. Those belong in the implementing module’s README. | | | SPEC-008 | Specs supersede their sources | When an approved spec and an XIP, a legacy spec, or the code disagree, the spec MUST be followed. An XIP is a source with no authority of its own. | | | SPEC-009 | Legacy specs | A legacy spec MUST carry `status: legacy` and a banner naming the specs that replace it. | `status: legacy` means “being replaced”, not “no longer binding”. | | SPEC-010 | Prose style | Spec prose MUST be direct: it states what a mechanism is and what breaks without it, in short sentences with one term for each concept, and MUST NOT argue for the design, describe alternatives, or narrate decisions. Prose MUST name a thing in the term the protocol uses, without metaphor or a paraphrase of its effect. | A reader comes for the rules, and every sentence that defends a choice stands between the reader and them. | | SPEC-011 | Legacy authority | Until an obligation receives a disposition under SPEC-013, that obligation MUST remain binding, and a reviewer MUST treat the legacy spec as authoritative for it. | | | SPEC-013 | Legacy dispositions | Every obligation in a legacy document MUST receive an owner-approved disposition: carried into a replacement, retired, or moved out of the specs to a design note or a module README. An author MUST record the disposition in the change summary, either per obligation or as one blanket disposition that names the replacing specs and covers every obligation the document holds. | some legacy clauses cannot be carried. A platform choice is barred from a replacement by SPEC-007, so without an explicit retirement it would either bind for ever or vanish when the file is deleted. | | SPEC-012 | Deleting a legacy spec | A legacy file MUST be deleted once every obligation in it has a disposition, and the deleting PR MUST move every consumer that reads it. | a build or a test that reads a legacy spec breaks the moment the file goes. | ## 2. Admission A spec is small because every requirement earns its place. The six questions below (SPEC-020 to SPEC-023, SPEC-092, and SPEC-088) counter the pull toward writing down whatever the current task touched. A statement that fails one question goes somewhere else: a design note, a named constant, a plan, or nowhere. | ID | Title | Requirement | Why | | -------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | SPEC-020 | Someone relies on it | A requirement MUST be one that a party outside the implementing module relies on: the other side of the wire, another installation or version of the client, an operator, an app developer, or a security property another party relies on. | | | SPEC-021 | Violation is harm | A requirement MUST be one whose violation is observable as harm: data loss, wrong ordering, a security or privacy breach, an interoperability failure across versions, or a wrong user-visible result. | | | SPEC-092 | Someone else observes the violation | A requirement MUST be one whose violation a party other than the actor it binds can observe. A rule whose violation harms only the actor that breaks it MUST NOT be a requirement. | An installation that forgets a rotation it owed keeps its own key live for longer, and only that installation pays. The rule belongs in the module’s design note, not in the contract. | | SPEC-022 | It survives a different implementation | A requirement MUST hold under a materially different implementation of the same capability. | | | SPEC-023 | It is testable | A requirement MUST be one for which a scenario, a property check, or a repeatable manual analysis distinguishes compliance from violation. | | | SPEC-088 | No belief requirements | A requirement MUST bind an observable act, and MUST NOT bind what an actor treats something as, concludes, considers, or assumes. | “a client MUST NOT treat acceptance as proof of membership” reads like a security property, but nothing distinguishes a client that holds the wrong belief and still performs every check. State the check. | | SPEC-024 | It is not already stated | Before allocating an identifier, the author MUST search the index for the same obligation and reference the existing identifier instead of restating it. | | | SPEC-028 | State the general invariant | A requirement MUST state the smallest invariant that covers its case, never one example of a rule the spec already makes, and a specific value MUST appear only when that value is the promise. A rule and the exact value it applies MUST be one requirement. Two requirements that a single act would violate MUST be merged. | “The payload `hello` survives” and “the payload `goodbye` survives” are two test cases for one invariant. “Use the advertised wrapper” and “the default wrapper is X” are one rule with its value. | | SPEC-029 | Permissions bind a reader | A requirement that grants freedom with MAY MUST be paired with the obligation it creates for anyone relying on it, or MUST NOT be a requirement at all. | “the backend MAY batch publishes” cannot be violated, so it is untestable on its own. What is testable is the client obligation it implies: not to assume otherwise. | | SPEC-025 | Excluded content | A spec MUST NOT contain task sequencing, the layout of internal storage such as tables, columns, and encodings, the client database schema, obligations about what a capability’s tests must cover, or the details of a bug fix. A bug fix MAY yield the invariant it violated. | “Phase 3 tests must cover every limit” is work planning, and belongs in a plan. A stored value that a condition tests is not layout: SPEC-089 requires it to be named. This document’s own evidence rules are exempt under SPEC-085. | | SPEC-026 | Intended behaviour | When the code and the intended behaviour differ, the author MUST write the intended behaviour and record the gap as a waiver under SPEC-055. | | | SPEC-027 | Compatibility behaviour | When a current client must still accept an old form, that acceptance MUST be a requirement. When the client merely tolerates the old form, it MUST be listed under Known limitations instead. | | ## 3. Requirements A requirement is one row of a four-column table: the identifier, the title, the requirement sentence, and the reason. The sentence keeps the EARS shape, because putting the condition first is what makes a requirement testable, and uses MUST and MUST NOT, because every engineer and every agent already reads those words as binding. A row is one line, so a cell cannot hold a fenced block or a list; a type block sits above the table whose requirements point at it, and a pipe inside a cell is written `\|`. Specs are written in waves, so one will often need an obligation another has not stated yet. The author writes `?PREFIX` where the identifier will go, says in the section’s prose what the missing obligation should require, and carries on. The explanation goes in the prose rather than inside the requirement, because the Why cell states what breaks and nothing else. The marker is a visible debt: the checker reports every one, and the pull request that approves the owning spec has to pay them. | EARS pattern | Shape | Example | | ------------------ | --------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | | Ubiquitous | The actor MUST … | The backend MUST derive the topic of every envelope from its payload. | | Event-driven | When \[event], the actor MUST … | When a publish names more topics than the published limit, the backend MUST fail the request with `INVALID_ARGUMENT`. | | State-driven | While \[state], the actor MUST … | While a client’s connection is blocked by a backend mismatch, the client MUST NOT send any request. | | Optional feature | Where \[feature is present], the actor MUST … | Where the commit log is enabled, the client MUST publish an entry for every commit it applies. | | Unwanted behaviour | If \[condition], then the actor MUST … | If a Welcome names an epoch not later than the local epoch, then the client MUST discard it. | | ID | Title | Requirement | Why | | -------- | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | SPEC-030 | Identifier form | A requirement identifier MUST be `PREFIX-NNN`: three to five uppercase letters, a hyphen, and exactly three digits. | | | SPEC-031 | Prefix registry | Every prefix MUST be registered in `docs/specs/PREFIXES.md`, and a spec MUST use only its own prefix for its requirements. | | | SPEC-032 | Allocating a number | The author MUST give a new requirement the next unused number for the prefix, MUST NOT renumber an existing requirement, and MUST NOT reuse the number of a deleted requirement. | | | SPEC-033 | Amending a requirement | When an amendment keeps the same obligation, the requirement MUST keep its identifier. When the obligation changes, the author MUST allocate a new identifier and delete the old row. A spec MUST NOT contain a table of retired requirements. | | | SPEC-075 | Moving a requirement | When a split moves an unchanged obligation to another spec, it MUST keep its identifier, and the receiving spec MUST list that identifier in its `owns` frontmatter key. | changing an identifier because a file was reorganised breaks every backlink for an obligation nobody edited. Prose cannot record this, because the checker has to know. | | SPEC-077 | Inheriting an identifier | A spec that carries an obligation forward from a superseded document under its original identifier MUST list that identifier in `owns`, and MUST NOT allocate any other identifier below its prefix’s reuse floor. | | | SPEC-034 | Row form | A requirement MUST be one row of a requirements table whose header is `\| ID \| Title \| Requirement \| Why \|`, in the form `\| PREFIX-NNN \| Title \| Sentence. \| Reason. \|`, with one obligation, the condition first, then the actor, then the keyword. A cell MUST NOT contain a fenced block or a list, and a pipe inside a cell MUST be written `\|`. | A row is one line, so no obligation can hide in a continuation, and a reader scans identifier, title, rule, and reason as columns. | | SPEC-035 | Normative keywords | An obligation MUST use MUST or MUST NOT, and explicit freedom MUST use MAY. A requirement MUST use `SHOULD` only for an app or an operator, which the system cannot enforce, and MUST NOT use `SHALL`. Trigger words are lowercase. | | | SPEC-036 | Requirement title | A requirement MUST have a title of two to seven words in the Title cell, with no trailing period. | | | SPEC-037 | Length and rationale | The Requirement cell MUST be at most three sentences. The Why cell MUST state what breaks when the requirement is violated, or be empty, and MUST NOT restate the requirement. | Section prose carries the reasons by default. A Why that repeats the rule in other words costs a reader a sentence and teaches nothing. | | SPEC-089 | Concrete conditions | A condition MUST name the field, stored value, or comparison it tests, and a bound MUST state its value, or its default and the rule that selects it when the value is a tunable. A word that stands in for a measure, such as “earliest”, “confirmed”, “usable”, or “bounded”, MUST NOT replace the measure. | “The earliest message at the location” is a claim; “the message with the lowest sequence id at the location” is a test. A bound with no value cannot be violated. | | SPEC-038 | Naming the actor | A requirement MUST name its actor with a term from `docs/specs/GLOSSARY.md`, or with a process actor this document defines in its Terms. A new system actor MUST be added to the glossary, not defined in a spec. | | | SPEC-039 | Exact values once | A wire field, topic byte, published limit, error code, or persisted format MUST be stated exactly once, in the spec that owns it. Other specs MUST reference it by identifier. | | | SPEC-040 | Transport identifiers | A spec that states the contract of a transport format MAY use that format’s identifiers and error codes, such as `xmtp.backend.v1.GetConfigurationResponse` or `INVALID_ARGUMENT`. | | | SPEC-041 | Normative text | Only requirement rows, and the content a requirement points at, are normative. A table other than a requirements table, a type block, a diagram, a glossary entry, or an example MUST be treated as informative unless a requirement points at it. | | | SPEC-072 | Every obligation has an owner | A behavioural constraint MUST be stated by a requirement. A definition, table, or type block MUST NOT introduce an obligation that no requirement states. | content that binds without an identifier cannot be amended, evidenced, or reviewed as a contract. | | SPEC-073 | Pointing at a block | A requirement that makes a table or a type block binding MUST name it, and the block MUST appear in the same spec. | | | SPEC-087 | Value tables bind by ownership | A table whose cells are only the exact values a spec owns under SPEC-039, such as wire identifiers or error codes, MUST be normative without a requirement pointing at it, and MUST NOT state behaviour. | the alternative is a requirement whose whole job is to make a table binding, which adds ceremony a reader gains nothing from. A cell that says what an actor does is behaviour and still needs its own requirement. | | SPEC-042 | Reference, do not restate | A spec MUST reference another spec’s obligation by identifier, or by section when no single identifier fits, and MUST NOT restate it. | | | SPEC-078 | Unwritten references | Where the obligation a spec needs to reference is not written yet, the author MUST write `?PREFIX` naming the spec expected to own it, and the enclosing section’s prose MUST say what that obligation is expected to require. | the alternatives are worse. Inventing a number creates a reference that resolves to the wrong requirement once the number is allocated, and omitting the reference loses the dependency entirely. | | SPEC-079 | Resolving them | A spec MUST NOT be approved while it contains a `?PREFIX` marker whose owning spec is approved, and the PR that approves a spec MUST replace every marker naming it in another spec. | a marker is a debt against a spec that does not exist. Once it does, the debt is due, and nothing else will force it. | | SPEC-043 | Type block notation | A protobuf message MUST be written as protobuf, a structure that is not a wire format MUST be written as WebIDL, and a wire format defined elsewhere MUST be referenced rather than reproduced, following section 3.1. | | | SPEC-044 | Version conditions | A requirement MAY carry a version condition where behaviour differs by client or group version, whether or not the switch exists yet. It MUST name the version that divides the cases, not the release that shipped it. | a promise about older clients is a promise about a protocol version, which outlives any particular build. | | SPEC-045 | Known limitations | A known limitation MUST be plain prose that states what is accepted and why, without an identifier. | | | SPEC-046 | Diagrams are welcome | A spec MAY contain a Mermaid diagram wherever it explains faster than prose, including one per section. | | ### 3.1 Type blocks A spec describes two kinds of shape, and they take different notations. A **wire message** is bytes that one party sends and another parses. Its field numbers, types, and presence rules are the compatibility contract: change a field number and every existing client breaks. Those specs inline protobuf, the language the wire actually uses. Translating a wire message into another notation loses the field numbers and invites the spec and the proto to drift apart. An **internal structure** is a shape a spec needs in order to state a rule, but that never appears on the wire: a stored row, a snapshot a client holds, a value handed to an app. It has no field numbers and no encoding, so it is written in [WebIDL](https://webidl.spec.whatwg.org/), which is standardised and describes shape without implying an encoding. A **foreign wire format** is a payload this repository carries but does not define. An MLS key package and a Welcome are encoded in TLS presentation language under RFC 9420, and travel inside an opaque protobuf field. A spec names that format and the section that defines it, and states its own obligations about the bytes: what must be validated beyond what the standard already requires, what must be preserved, what must be rejected. It does not restate the foreign schema or the standard’s own validation, because doing so would create a second definition that can drift from the real one. | ID | Title | Requirement | Why | | -------- | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | SPEC-047 | Protobuf for protobuf messages | A message carried by the gRPC schema MUST be written as protobuf in a fenced `proto` code block, with the field numbers and types it has on the wire. | | | SPEC-074 | Foreign formats and procedures | A payload, validation, or procedure defined outside this repository, such as an MLS object or its validation under RFC 9420, MUST be referenced by naming the document and the section that defines it, with a link, and MUST NOT be reproduced as protobuf, WebIDL, or prose. A requirement about it MUST state only what this system adds to or removes from that section. | Those bytes travel inside a protobuf field, but the field is an opaque carrier. Rewriting the payload or its checks here states a second definition that nothing implements and that drifts from the first. | | SPEC-048 | Copy, do not paraphrase | A protobuf block MUST agree field for field with the schema in this repository, which is the one baseline every reader shares. A spec MUST include only the messages the surrounding requirements constrain, and MAY omit unrelated fields with a comment saying so. | | | SPEC-076 | Not yet implemented | A protobuf block for a field the schema does not carry yet MUST mark that field with a `pending` comment, and its requirements MUST be waived as `gap` under SPEC-094 until the schema carries it. | a spec may lead its implementation, so the format has to say how, rather than forbidding the workflow it recommends. | | SPEC-049 | WebIDL for internal structures | A structure that is not a wire format MUST be written as WebIDL in a fenced `webidl` code block, as a `dictionary`. A spec MUST NOT use `interface`, which carries methods and object identity that a data structure does not have. | | | SPEC-070 | Opaque bytes in WebIDL | In a WebIDL block, a field of opaque bytes MUST have the type `sequence`, and a fixed length MUST be stated in a trailing comment, because WebIDL has no length-parameterised type. | | | SPEC-071 | Variants in WebIDL | In a WebIDL block, a set of mutually exclusive variants MUST be written as one dictionary with an `enum` discriminant and a comment saying exactly one member is present. A union of dictionary types MUST NOT be used, because WebIDL requires the members of a union to be distinguishable and two dictionaries never are. | | In a protobuf block, presence and defaults are protobuf’s own: a scalar that is absent reads as its zero value, and where absent and zero mean different things the block says so in a comment. In a WebIDL block, presence is carried by `required`, and integer widths follow the wire: `unsigned long` for 32 bits, `unsigned long long` and `long long` for 64. A wire message, as it appears on the wire: ```proto message WelcomeMessage { message V1 { bytes installation_key = 1; // 32 bytes; derives the topic bytes data = 2; // encrypted MLS Welcome bytes hpke_public_key = 3; // unset when this is the pointee of a pointer xmtp.mls.message_contents.WelcomeWrapperAlgorithm wrapper_algorithm = 4; bytes welcome_metadata = 5; } message WelcomePointer { bytes installation_key = 1; // 32 bytes; derives the topic bytes welcome_pointer = 2; // encrypted pointer bytes hpke_public_key = 3; xmtp.mls.message_contents.WelcomePointerWrapperAlgorithm wrapper_algorithm = 4; } oneof version { V1 v1 = 1; WelcomePointer welcome_pointer = 2; } } ``` An internal structure, which never appears on the wire: ```webidl dictionary ConfigurationSnapshot { required DOMString backend_identifier; required DOMString backend_url; // the URL the copy was fetched from required unsigned long max_group_members; boolean commit_log_enabled; // absent means the compiled default }; ``` ## 4. Backlinks A backlink is a comment token that ties a place in the code or the tests to one requirement. The aim is navigation and evidence, not a coverage metric: a link count measures annotations, never correctness. Links stay sparse by naming the decision point rather than every line that participates, and by tagging only a test whose assertions establish the obligation. They are not capped at a fixed number, because one obligation can need evidence in several places. Two things make a test worth linking: where it runs, and what it establishes. A payload-preservation promise is proven separately in Rust, Kotlin, Swift, and TypeScript, four places, one property each. A transactional promise is proven in one place by three tests, for the normal path, the rollback, and the restart. Both are real evidence, and a rule that counted only places would discard the second. Two tests are redundant only when they establish the same property in the same place. | ID | Title | Requirement | Why | | -------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | SPEC-050 | Implements link | An implementation MAY carry `implements: PREFIX-NNN` in a comment on the line above the item that enforces the requirement. A link MUST name the decision point that enforces the obligation, not every site that participates in it. | | | SPEC-051 | Verifies link | A test MUST carry `verifies: PREFIX-NNN` or `verifies: PREFIX-NNN, PREFIX-MMM` in a comment on the line above the test item when its assertions establish the obligation. An approved requirement MUST have at least one such link, unless SPEC-054 exempts it or SPEC-055 waives it. | | | SPEC-052 | Distinct evidence only | A test MUST carry a link only when no already-linked test establishes the same property in the same place. When two tests establish the same property in the same place, only one MUST carry the link, and it MUST be the Rust test when there is one. | a rule counting only places would reject a rollback test that shares a place with the normal-path test, and those establish different properties. | | SPEC-053 | No other mentions | A comment in code MUST NOT mention a requirement identifier except in an `implements:` or `verifies:` token. The checker reports a stray mention as an error when the identifier’s spec is approved and as a warning otherwise. | | | SPEC-054 | Evidence exemptions | This document and any requirement whose keyword is `SHOULD` MUST be exempt from SPEC-051 and from SPEC-055. | | | SPEC-055 | Waiver entries | A requirement that SPEC-054 does not exempt and that carries no `verifies:` link MUST have an entry in `docs/specs/waivers.toml` with the identifier, a `kind`, and a reason. A waiver MUST be reviewed like a spec change. | | | SPEC-056 | The checker gates merges | `just lint` MUST run `just spec-check`, and a PR MUST pass it. | | | SPEC-058 | Evidence gate rollout | While backlinks are being added to the code, the checker MAY report a missing `verifies:` link as a warning rather than an error. Once the last approved spec has its links, an owner MUST turn the gate to error, and it MUST stay there. | a gate that fails every pull request on the day it lands gets switched off. Saying so here is honest; leaving SPEC-051 to read as enforced when it is not would not be. | | SPEC-094 | Waiver kinds | A waiver entry’s `kind` MUST be `analysis` when a recorded review establishes the obligation and no test can, `gap` when the implementation does not yet satisfy it, or `untested` when the reason names the code that satisfies it and no test proves it yet. | A security property proven by review, behaviour known to be wrong, and correct behaviour without a test need different follow-up; one word for all three hides which is which. | | SPEC-095 | Waiver owner and issue | A waiver entry MUST name an owner when its kind is `gap` or `untested`, and an issue when its kind is `gap`. | An open waiver with no owner is never closed. | ## 5. Plans and spec changes Plans are out of scope and tooling-agnostic; this section is the one rule they carry. A plan changes code. A spec change is a change to a promise, and it is reviewed by an owner even when it lands inside a larger plan. | ID | Title | Requirement | Why | | -------- | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --- | | SPEC-060 | Spec changes section | A plan MUST contain a section titled “Spec changes” that lists the requirement identifiers the plan implements and every identifier it adds, amends, or removes, or states “None”. | | | SPEC-061 | Owner review | A change to a file in `docs/specs/` MUST be reviewed by an owner. A plan MUST NOT treat a proposed spec change as approved before that review. | | | SPEC-062 | Spec first | A project MAY land its spec change with waivers in the first PR of a stack and remove the waivers in later PRs. | | ## 6. This document This document is a spec about specs, so a few of its own rules cannot apply to it. The exemptions are listed rather than left implicit, because an unstated exception is one a reviewer has to invent, and two reviewers will invent different ones. | ID | Title | Requirement | Why | | -------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | SPEC-080 | Admission exemption | This document’s rules MUST be exempt from SPEC-020 through SPEC-023, which test obligations about system behaviour. | “a requirement has a title” binds an author, not the system, so asking who relies on it at runtime has no answer. | | SPEC-081 | Evidence and size exemptions | This document MUST be exempt from SPEC-005, SPEC-051, and SPEC-055. | | | SPEC-082 | Process actors | This document MAY use the process actors in its Terms section, which the glossary does not define. | | | SPEC-084 | Naming its own artefacts | This document MUST be exempt from SPEC-006 for the files, recipes, and keys it defines, which it MUST be able to name. | a format that may not write `docs/specs/waivers.toml` cannot say where a waiver goes. | | SPEC-085 | Test obligations about specs | This document’s rules about evidence MUST be exempt from SPEC-025, which bars obligations about a capability’s tests. | SPEC-025 keeps work planning out of a capability spec. Requiring a spec’s own requirements to carry evidence is a rule about specs, not about a capability’s test plan. | | SPEC-086 | Permissions in this document | A MAY in this document MUST be exempt from SPEC-029, which requires a permission to name the obligation it creates for a reader. | | | SPEC-093 | Default storage locations | The STORE spec MUST be exempt from SPEC-006, SPEC-007, and SPEC-025 for the default database directories, the platforms that select them, and the database file-name pattern it defines. | An app and its operators rely on `StorageLocation.Default` naming one location they can find, back up, and delete. | | SPEC-096 | Configuration file contract | The CONF spec MUST be exempt from SPEC-007 for the store URL schemes and the storage target name that its configuration field table states, and from SPEC-043 and SPEC-049 for that table, which states the keys of a TOML document. | An operator writes the configuration file against the field table. A check that may not name the accepted URL scheme cannot be tested, and a WebIDL dictionary has no place for a key’s presence, default, or checks. | | SPEC-083 | No other exemptions | Every rule this document states that it does not list here MUST apply to it. | the format has to survive being read by a reviewer who follows it literally. | ## Known limitations The checker cannot tell whether a `verifies:` test establishes the obligation or merely runs the code path. Reviewers read the assertions; the link is a claim of relevance, not proof. The rule against reusing a deleted number is a convention. The checker sees only the current tree; an author in doubt runs `git log -S PREFIX-NNN`. The checker counts sentences approximately and reports a long requirement as a warning, not an error. SPEC-089 and SPEC-092 are judgement rules. The checker does not enforce them; the reviewing skill does. # Client storage An SDK keeps each client’s database and attachments at a location the app names or at the platform default, by the storage location layouts of ATCH section 5. ## Scope In scope: the default directories, how the default location and a directory the app names map to the storage location layouts, the database file name in a data directory, the storage label, the identity needed to build a client from a stored database, storage lifecycle, and the database encryption choice: an absent key, a supplied key, and creating and opening a database under a key. Out of scope: the storage location layouts themselves and the attachments directory (ATCH section 5), database contents, encryption algorithms, and how an app creates and stores its database encryption key. ## Terms | Term | Meaning | | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Storage label | A value the app supplies to keep separate client stores under one root directory. | | Default location | The directory the SDK selects when the app does not name a location. | | Root directory | The default location, or the directory the app names. It is the data directory of a `data_dir` storage location (ATCH-040), or holds that data directory when the app supplies a storage label. | | Salt file | A file that an SDK keeps beside a database file it created under a database encryption key. The SDK needs it, with the key, to read that database, so an app that copies or backs up the database file copies the salt file with it. | ## 1. Database location An SDK keeps each client’s database in one database file, and stores the database and the attachments by the storage location layouts of ATCH section 5. The root directory is the data directory of a `data_dir` layout (ATCH-040). When the app supplies a storage label, the data directory is the directory named by the label inside the root directory. The database and the attachments of one inbox on one deployment are then in one inbox directory, `{data_dir}/{deployment}/{inbox_id}/` (ATCH-040). An explicit location (ATCH-080) names the database file and the attachments directory itself, and the SDK adds no label, deployment, or inbox component to either path. When the app does not name a location, the SDK uses its platform’s default directory below as the root directory. Each platform’s default is chosen for that platform; it is not always storage that is private to the app (STORE-004 uses the Node.js process working directory). `StorageLocation.Default` means this location. The defaults are not tied to earlier SDK releases, which used other directories and file names. | ID | Title | Requirement | Why | | --------- | ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | STORE-020 | Locations map to storage layouts | When an app asks for the default location or names a directory, the SDK MUST create the client with a `data_dir` storage location (ATCH-040) whose `data_dir` is the root directory, or, when the app supplies a non-empty storage label, the directory named by the label inside the root directory. When an app names a database path and an attachments directory, the SDK MUST create the client with an `explicit` storage location (ATCH-080) that holds those two paths unchanged. | An SDK that derives its own paths puts the database where another SDK does not open it, and the attachments where ATCH-044 does not find them. | | STORE-019 | Database file in a data directory | When an SDK opens a database with a `data_dir` storage location, it MUST name the database file `{data_dir}/{deployment}/{inbox_id}/xmtp.db3`, with the components of ATCH-040. | Another SDK, or another version of one, that names the file otherwise opens an empty database with no identity. | | STORE-002 | Default directory on Apple platforms | Where an SDK runs on iOS or macOS and the app asks for the default location, the SDK MUST use as the root directory the `xmtp` directory inside a folder named by the app’s bundle identifier in the app’s Application Support directory. | Documents is visible to the user and can be moved or deleted from the Files app, and a non-sandboxed macOS app shares Application Support with every other app of the user; the bundle identifier is the system’s stable name for the app. | | STORE-003 | Default directory on Android | Where an SDK runs on Android and the app asks for the default location, the SDK MUST use as the root directory the `xmtp_db` directory inside the app’s internal files directory. | External or shared storage is readable by other apps. | | STORE-004 | Default directory on Node.js | Where an SDK runs on Node.js and the app asks for the default location, the SDK MUST use as the root directory the `xmtp` directory inside the process’s current working directory at client creation. | Database files written straight into the working directory mix with the app’s own files. | | STORE-005 | Default directory in a browser | Where an SDK runs in a browser and the app asks for the default location, the SDK MUST use as the root directory the `xmtp-sdk` directory of the SDK’s OPFS storage pool. | Files at the pool root collide with other files an origin keeps in OPFS. | | STORE-006 | No default elsewhere | Where an SDK runs on a platform that STORE-002 to STORE-005 do not name, or on iOS or macOS in a process with no bundle identifier, a request for the default location MUST fail with a typed error before the SDK opens a file. | A guessed directory puts databases where the app cannot find or back them up. | | STORE-007 | Build opens only an existing identity | When an app builds a client without a signer on a database that holds no stored identity, the SDK MUST fail with a typed error and MUST NOT register an installation. | A build on a new database would create a client with no identity the app signed for. | | STORE-021 | Safe storage label | If a storage label is `.` or `..`, or contains a path separator (`/` or `\`), a colon (`:`), or a NUL character, then the SDK MUST fail with a typed error before it opens or creates a path. | A label taken from outside the app could otherwise place the client’s files outside the root directory, or open another client’s database. | The SDK uses the storage label unchanged as one directory name. On a file system that ignores letter case, labels that differ only in case name the same directory. ## 2. Storage lifecycle The storage interface reports the file in use and controls its connection and removal. An in-memory client has no database file to report or remove. The browser exposes no storage reconnect or delete operation. | ID | Title | Requirement | Why | | --------- | ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | STORE-009 | Open database path | When an app reads a client’s storage path, the SDK MUST return the path of the database file that client opened, or no path for in-memory storage. | A computed path that differs from the opened file can make an app back up the wrong database. | | STORE-010 | Reconnect the same database | When an app reconnects storage of a client it has not ended, the SDK MUST reopen the database file that client opened. | Reconnecting to another file changes the client’s stored identity and history. | | STORE-011 | In-memory storage cannot be deleted | When an app asks to delete in-memory client storage, the SDK MUST fail with a typed invalid-input error. | In-memory storage has no database file to remove. | | STORE-017 | Close before file removal | When an app asks to delete file-backed client storage, the SDK MUST close the client before it removes the database file. | A live connection could otherwise write to a file after its name is removed. | | STORE-018 | Storage files gone after deletion | When deletion of file-backed client storage or a browser database completes, the SDK MUST have removed the database file and every journal, shared-memory, salt, and temporary salt file belonging to it; native client storage deletion MUST also remove the managed attachment directories directly under that client’s attachments directory (`.tmp`, `.staged`, and directories whose names are exactly 64 lowercase hexadecimal characters), including everything below each of them. If a required removal fails, the SDK MUST report a typed error, and a later retry MUST continue past files already absent. When removing attachments, the SDK MUST preserve every entry in the attachments directory outside that managed namespace. | A database-only deletion leaves plaintext and recovery data after the app reports that storage is gone. | | STORE-026 | Synced before it leaves the device | Before a client returns a queued message’s id, or sends a request that publishes a prepared envelope or a key package, it MUST have completed a sync to stable storage of the file-backed database write that recorded that work. | An operating system crash or power loss can otherwise erase the local record of work other devices already hold: the installation forks its group, loses the send, or cannot read Welcomes to the package. | ## 3. Database encryption choice An app can use a database without an encryption key. When the key is absent, the database is not encrypted by the SDK. This choice applies when the app creates a database and when it opens that database again. Creation of a database under a database encryption key lasts from the SDK’s first write for a path whose database file is absent or 0 bytes long until the call that opens the database returns. | ID | Title | Requirement | Why | | --------- | ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | STORE-022 | Optional database encryption key | When an app omits the database encryption key, the SDK MUST support creating a database and reopening a database created without a key, without requiring a key. | Requiring a key prevents an app from using or reopening its existing store. | | STORE-023 | Interrupted keyed creation stays openable | If the app’s process exits or is killed at any point while the SDK creates a file-backed database under a database encryption key, and the device keeps running, then when the app later opens the same path with the same key, the SDK MUST open a database at that path. This requirement does not cover a power loss or an operating system crash. | A stop that leaves files the key cannot read makes every later open of that path fail, so the app cannot create or restore its client there without deleting files by hand. | | STORE-024 | Failed keyed open preserves the store | If an app opens with a database encryption key a path whose database file is longer than 0 bytes and the SDK cannot read that database with the key, then the SDK MUST fail with a typed error. It MUST NOT change the data the database holds, and MUST NOT create, change, or remove its salt file. | An open that rewrites or resets a store it cannot read can destroy data that the right key, or the missing salt file restored from a copy, would still recover. | | STORE-025 | A supplied key is applied or refused | When an app supplies a database encryption key for a file-backed database, the SDK MUST either store that database encrypted under the key, so that a later open of it with a different key fails with a typed error, or fail with a typed error before it opens a database. | A key the SDK accepts and ignores leaves installation keys and decrypted messages readable from a copy of the files while the app believes they are protected. | ## Known limitations Storage reconnect fails after the app ends the client; the app builds a new client instead. Deletion under STORE-018 removes file names; it does not promise forensic erasure of deleted blocks, backups, or copied files. Empty storage directories and the deployment record of a data directory stay. Browser database administration removes the database file family from its storage pool; the separate attachments directory stays. An app closes every other client or process using the same database or attachments directory before native deletion, because the SDK stops only the client receiving the request. An app-owned lowercase 64-hex directory inside the attachments directory is treated as managed and deleted. The replacement STORE paragraph makes the surviving empty directories, deployment record, browser attachment tree and lack of forensic erasure explicit. A browser SDK does not encrypt its database. Anyone who can read the origin’s browser storage, for example from a copied browser profile, can read the stored installation keys and decrypted messages. Older SDK releases wrote some encrypted databases without a salt file. The SDK does not convert such a database, and a keyed open of it fails (STORE-024). A power loss shortly after an SDK first creates an encrypted database can lose the new salt file on a file system that cannot sync a directory, and on Windows, where the SDK does not sync the directory. A later keyed open of that path can then fail (STORE-024), and the app removes the files and creates its client again. Closing this window on those systems needs platform-specific file-system calls. # Device sync A user’s installations exchange preferences over a group only they belong to: the sync group. What travels over it is a consent record (`CONS`) or the HMAC root key that push suppression derives from (PUSH-258). Both are the user’s own state, so accepting an invitation to a sync group grants access to that state, and the rule for trusting one is a security boundary. A new installation creates a sync group and adds every other installation of its inbox. The Welcome it sends is how those installations learn that it exists: each adds the new installation to the user’s conversations and publishes every consent record and the HMAC root key it holds, so that the newcomer holds them; it generates a root key only when it holds none. Every later preference change is published to the sync group and merged on each installation under a total order, so the same updates applied in any order leave the same state. ```mermaid flowchart LR N[New installation] -->|creates, adds own installations| G[(Sync group)] G -->|Welcome| P[Peer installation] P -->|adds newcomer to conversations| C[Conversations] P -->|every record and the root key| G A[App act on any installation] -->|consent record| G G -->|total order| E[Every installation] ``` ## Scope In scope: when a sync group is created and who is in it, the trust rule for a sync-group Welcome and for a sync message, what a peer does when it learns of a new installation, the preference update wire format, what is published and when, how an update is applied, what a restart preserves, and that a sync group is hidden from an app. Out of scope: the consent record and its merge (`CONS`), the join itself (`JOIN`), the membership commit that adds an installation (GMOD-029), HMAC key derivation and its use by a push server (PUSH-258), the archive and its transport (`ARCH`), and the content type envelope (CTYPE-001). | Related | Relation | | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `CONS` | Owns the consent record, its wire form, and the merge. This spec owns carrying it. | | `JOIN` | Owns the join. SYNC-010 adds the check a sync-group Welcome gets under JOIN-060. | | `GMOD` | GMOD-029 owns the commit that reconciles a group’s installations with identity state. SYNC-014 owns when a peer runs it for a newcomer. | | `PUSH` | PUSH-258 owns the HMAC root key’s derivation into per-conversation keys; PUSH-219 owns push eligibility. This spec owns the root key’s cycling and propagation. | | `CTYPE` | Owns `EncodedContent` and `ContentTypeId`, which a sync message is wrapped in, and CTYPE-001, which selects a codec by them. | | `META` | Owns `CONVERSATION_TYPE` and `CREATOR_INBOX_ID` in immutable metadata, and META-019, which rejects a Welcome that lacks them. | | `PROC` | Owns how a stored envelope is processed and how a message reader applies its selected scope (PROC-046). | | `EVENT` | EVENT-001 reports consent and HMAC root key changes; EVENT-003 excludes sync groups from app events. | ## Terms | Term | Meaning | | ----------------- | ------------------------------------------------------------------------------------------------------------------ | | Sync group | A group whose immutable metadata `CONVERSATION_TYPE` is `CONVERSATION_TYPE_SYNC`. | | Sync message | An application message in a sync group whose content is a `DeviceSyncContent` under the content type in section 3. | | Preference update | One `PreferenceUpdate`: a consent record or an HMAC root key. | | Admissible update | A preference update in a sync message that SYNC-030 admits and SYNC-023 does not ignore. | | Owed key | A consent key, or the root key, marked under SYNC-027 and not yet cleared under SYNC-033. | | HMAC root key | The 42-byte secret every installation of an inbox shares, from which PUSH-258 derives per-conversation keys. | | Cycle time | The `cycled_at_ns` of an HMAC root key: the time SYNC-026 gave it, capped on receipt under SYNC-032. | | Local join time | The stored time at which the client created a group or completed its join from a Welcome. | | Own inbox | The inbox the acting client belongs to. | ## 1. The sync group Each installation that holds no sync group creates one and adds every other installation its inbox’s identity state associates. An installation therefore belongs to one sync group per installation registered after it, plus its own, and the newest one is the one every current installation is in. A client publishes to that one and reads all of them, so an installation that has not yet received the newest Welcome still hears from the ones it has. A sync group is the user’s own state, not a conversation. It is never listed or streamed to an app that did not ask for sync groups, and its messages produce no push notification: PUSH-219 makes a group message push-eligible only when `should_push` is true. Whether a consent record exists for a sync group has no effect; SYNC-005 hides it by conversation type. | ID | Title | Requirement | Why | | -------- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | SYNC-001 | Create when none | When a client that may reach the backend runs and holds no sync group, it MUST create a group whose immutable metadata `CONVERSATION_TYPE` is `CONVERSATION_TYPE_SYNC` and add every installation that its inbox’s identity state associates other than itself, and MUST retry that add, including after a restart, until no own installation is missing from the group, the group is no longer the selected sync group under SYNC-002, the group is no longer held, or its committed protocol floor does not admit the retry under GMOD-055. | A peer installation learns of this one from the Welcome. Without it the peer never adds this installation to a conversation. No membership refresh runs on a sync group, so an add that is not completed is never made. | | SYNC-002 | Publish to the newest | When the client publishes a preference update, it MUST publish it to the sync group with the greatest local join time, and on an equal time the greatest group id under byte order. | One destination avoids publishing every preference to every held sync group. SYNC-031 orders joins, and SYNC-034 repairs the selected group’s installation set. | | SYNC-031 | Join times only grow | When the client stores a sync group, by creating it or from a Welcome, it MUST set its local join time to the greater of its current time and the greatest local join time of a sync group it holds plus one nanosecond. | SYNC-002 publishes to the greatest join time. A join time from a clock that was later set back keeps an older group selected, and a newcomer that is not in it receives nothing. | | SYNC-003 | Read every sync group | The client MUST apply admissible updates from every sync group it belongs to, not only the one SYNC-002 selects. | An installation that has not received the newest Welcome publishes to an older group, and a reader of the newest alone misses it. | | SYNC-004 | No push for sync messages | When the client publishes a sync message, it MUST publish it with `should_push` false. | Every consent change would otherwise notify the user on every device. | | SYNC-005 | Hidden from the app | The client MUST NOT return a sync group in a listing or stream of conversations, or its messages in a stream of messages across conversations, unless the app asked for sync groups. | | ## 2. Trust A Welcome names the inbox that added the recipient (JOIN-025) and the membership it asserts (JOIN §8). JOIN §8 checks that every leaf node belongs to the inbox it claims; it does not ask which inbox that is. For every other conversation kind the joiner accepts strangers; a sync group is the one kind in which it may not. A sync group created by another inbox, or one with another inbox in it, is a group into which this client would publish its consent decisions and the key its push suppression depends on. JOIN-060 rejects a Welcome that fails the checks its kind demands; SYNC-010 states the checks for this kind. The same rule applies to what is read. A sync message is applied only when its sender was an installation of the own inbox when the message was sent, whatever group it arrived in (SYNC-030). | ID | Title | Requirement | Why | | -------- | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | SYNC-010 | Only the own inbox is a member | When a Welcome carries a group whose `CONVERSATION_TYPE` is `CONVERSATION_TYPE_SYNC`, the client MUST record a terminal rejection for it unless the adder under JOIN-025 is the own inbox and every leaf node in the ratchet tree names the own inbox. When the client validates a commit to such a group, it MUST record a terminal rejection for the commit if `GROUP_MEMBERSHIP` after the commit names an inbox other than `CREATOR_INBOX_ID`. | Anyone can create a group and name it a sync group. Accepting one makes it the group this client publishes to under SYNC-002, and its members read every consent decision and the HMAC root key. An installation of the own inbox can still commit another inbox into a group it already holds, and that inbox stays after the installation is revoked. GMOD-012 binds every new leaf to an inbox in `GROUP_MEMBERSHIP`, so the one entry keeps every leaf in the creator’s inbox. | | SYNC-030 | Senders are judged when they sent | When the client applies a sync message, it MUST first load the own inbox’s identity updates from the network, after the message was stored. It MUST apply the message’s preference updates only when the sender is an installation of the own inbox in the own identity state after the last own identity update whose server time is at or before the message’s envelope time. When the sender is not, the client MUST NOT apply the message ever when an earlier state held the sender, and MUST otherwise leave the message to be applied later. | An accepted update sets consent and replaces the HMAC root key. A message an installation sent before its revocation is then applied on every installation whose identity read is current, and one sent after it on none, whenever each one processes it. A registration that this client’s identity read has not seen yet must not drop a newcomer’s message for good. | ## 3. Preference updates A sync message is an application message whose content is an `EncodedContent` with `ContentTypeId` authority `xmtp.org`, type `application/x-protobuf`, and major version 1, and whose `content` bytes are an encoded `DeviceSyncContent`. CTYPE-001 selects the codec by those three values. ```proto // All potential device sync group messages message DeviceSyncContent { reserved 1, 3; reserved "request", "reply"; oneof content { DeviceSyncAcknowledge acknowledge = 2; PreferenceUpdates preference_updates = 4; } } // Acknowledges a request message DeviceSyncAcknowledge { string request_id = 1; } // Preference updates message PreferenceUpdates { repeated PreferenceUpdate updates = 1; } // Preference update message PreferenceUpdate { oneof update { xmtp.device_sync.consent_backup.ConsentSave consent = 1; HmacKeyUpdate hmac = 2; } } // Hmac key update message HmacKeyUpdate { bytes key = 1; int64 cycled_at_ns = 2; } ``` Fields 1 and 3 of `DeviceSyncContent` carried a history transfer that older installations still send. `acknowledge` is its reply and carries nothing to apply. A message a client cannot use is ignored and does not stop the messages behind it. The sync group carries no archive; an archive travels by a channel the app chooses (`ARCH`). Publishing is stored state, not an event. A change the client stores to a consent record or to the root key marks the key as owed in the same transaction, unless it came from the selected sync group (SYNC-027). The client publishes the current value of every owed key (SYNC-029) and clears the mark only after a sync message carrying it is published (SYNC-033). So a restart loses nothing, many changes to one key are sent once, no failure count drops a change, and sending a value again never changes it. A value received in the sync group SYNC-002 selects is not sent back, because every installation there received it from its sender. Both update kinds merge without regard to order (CONS-053, SYNC-032), so applying a message twice, or after a greater one, changes nothing. The client’s own messages are applied like a peer’s once they are published. | ID | Title | Requirement | Why | | -------- | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | SYNC-020 | Wire format | When the client publishes a preference update, it MUST publish a sync message whose `DeviceSyncContent` carries `preference_updates` with each update as a `PreferenceUpdate` defined above, with a consent record encoded under CONS-050. | | | SYNC-027 | Mark every change owed | When the client stores a change to a consent record or to its root key, it MUST mark the key as owed in the same transaction, with a mark it has not used before. The exception is a change from a sync message in the sync group SYNC-002 selects: such a change MUST leave the key’s mark as it was. | A change held in memory is lost on restart. A value from the selected group reached every installation in it from its sender, so sending it back is an echo. A value from an older group may have reached no one in the selected group, for example when its sender stopped running. A received value never clears a mark, because the mark can stand for a newcomer that has not received the key (SYNC-035). | | SYNC-029 | Publish owed keys | The client MUST publish the current value of every owed key as a preference update under SYNC-020. It MUST publish to the sync group SYNC-002 selects after it reads the values, in sync messages of at most 1,000 updates each. Each message’s encoded updates MUST fit within a quarter of the deployment’s envelope limit and within 262,144 bytes, unless the message carries a single update. | A message refused for being too large fails on every retry. A single update always goes out, or a record larger than the budget could never be sent. Reading the values first means a newcomer’s Welcome that commits in between either marks them again or is already the selected group. | | SYNC-033 | Clear a mark only after publication | Before the client queues a sync message under SYNC-029, it MUST wait until every sync message it queued earlier in that sync group is published or has failed for good, and after a failure for good it MUST queue the owed values again. It MUST clear a key’s mark only after a sync message that carries the key’s value is published, and only when the key still holds the mark it had when the client read that value. It MUST NOT stop publishing an owed key after any number of failures or across a restart. | A change dropped after failures stays on one installation. A mark cleared when a message is queued is lost when the message is refused. A queue of retries holds many copies of one change. | | SYNC-032 | The greater root key wins | When the client receives an `HmacKeyUpdate` whose `key` is 42 bytes, it MUST cap its `cycled_at_ns` at one day after the envelope time of the sync message that carries it. It MUST then store the key and that time when it holds no root key, or when the time is greater than the stored cycle time, or when the times are equal and the received `key` is greater under byte order; otherwise it MUST leave the stored key unchanged. It MUST NOT store a key that is not 42 bytes. | Two installations that keep different root keys register different per-conversation keys, and a message one of them sends notifies the other. A tie left to arrival order leaves two devices with two keys. A key timed far ahead would beat every later cycle, including the one SYNC-026 makes on revocation. | | SYNC-023 | Ignore what cannot be used | When a sync message’s `DeviceSyncContent` has no `content` set, carries `acknowledge`, or contains a `PreferenceUpdate` with no `update` set, the client MUST ignore that content or that update without failing the message and MUST apply the other admissible updates in the same message. | An older installation’s history transfer, or a newer installation’s update kind, would otherwise stop every update behind it. | ## 4. A new installation The Welcome to a sync group is the signal that a new installation exists. In the transaction that installs it, a peer gives the group a join time after every sync group it holds, so the group becomes the one SYNC-002 selects (SYNC-031). It also schedules the adds to the user’s conversations (SYNC-014) and marks every consent record and its root key as owed (SYNC-035). A newcomer that a publish adds to an existing sync group sends no Welcome; a peer that applies the commit adding its leaf does both in the transaction that applies it. So the newcomer receives everything the peer holds, and a restart at any point loses none of it. The peer sends the root key it holds; it generates one only when it holds none. The root key is cycled when another installation of the inbox is revoked, so the revoked installation’s copy stops matching (SYNC-026). The new key is timed after every key the revoked installation could have sent. SYNC-034 removes the revoked installation from the sync group before the new key is published. Which conversations the newcomer is added to is a consent decision. A denied conversation is not shared, and a conversation with no activity for 90 days is left for its next reconciliation. A conversation’s activity time is the `sent_at_ns` of its last stored message when it has one, and its local join time otherwise. The newcomer merges what arrives under CONS-053 like any other update. A DM’s record is its peer’s inbox record, so it applies to every DM with that person that the newcomer holds or joins later. Both acts survive a restart. The add is a commit the peer retries for three days, or until it lands or the group is gone; an update the client received is applied whether or not the process that received it is the one that applies it. How a stored envelope is processed is owned by `PROC`; this spec owns only the effect on stored consent and the root key. | ID | Title | Requirement | Why | | -------- | ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | SYNC-014 | Add the newcomer to conversations | When the client joins a sync group from a Welcome, or applies a commit that adds an installation key absent from that sync group’s preceding leaf set, it MUST, for every non-DM group whose conversation consent is allowed or unknown and whose activity time is greater than the current time minus 90 days, and for each DM’s winner selected under DMS-007 from groups meeting those consent and activity conditions and at most 10 other such groups sharing its dm id with the greatest activity times, publish a commit that adds each installation that its inbox’s identity state associates and the group’s membership lacks, and MUST retry that commit, including after a restart, for three days or until it lands or the group is no longer held. | A newcomer no peer adds reads nothing until each conversation’s next reconciliation, which for a quiet one is never. A newcomer added to an existing sync group sends no peer a sync Welcome. The three-day bound keeps a group whose add keeps failing from being retried forever. | | SYNC-035 | Replay after a newcomer joins | When the client joins a sync group from a Welcome, it MUST, in the transaction that completes the join, mark every consent record it stores and its root key as owed under SYNC-027. When it applies a commit that adds an installation key absent from that sync group’s preceding leaf set, it MUST make the same marks in the transaction that applies the commit. When it holds no root key, it MUST first store one under SYNC-026. | Adding a leaf gives it future messages but no earlier preferences. Every peer can hold records the adding peer lacks, and a replay marked after the membership transaction can be lost on restart. Fresh marks keep an earlier in-flight publication from clearing the replay. | | SYNC-026 | Cycle the root key | When the client learns that an installation of its own inbox other than itself was revoked, or needs a root key and holds none, it MUST store a new 42-byte root key drawn from a cryptographically secure random source, with a cycle time equal to the greatest of its current time and the stored cycle time plus one nanosecond. For a revocation, the cycle time MUST also be at least one day after the server time of the identity update that revoked the installation. | A revoked installation that keeps a valid key can still suppress the user’s notifications. A cycle that does not come after the stored key loses to a key a compromised installation timed ahead. A key the revoked installation sent before its revocation is applied (SYNC-030) with a time below the revocation’s server time plus one day (SYNC-032), so a cycle at or after that bound beats it even when the client applies that key after it cycles. | | SYNC-034 | Reconcile before publishing | Before the client publishes a sync message to the group SYNC-002 selects, when that group contains a leaf other than its own that the newest locally stored own-inbox identity state does not associate, or lacks an installation that state associates, the client MUST publish a membership commit that raises the own inbox’s entry to that state’s sequence id, removes those revoked leaves, and adds the missing own installations under JOIN-093 and GMOD-055. It MUST list associated installations still without leaves in `failed_installations` and MUST NOT publish the sync message while a revoked leaf remains. When an associated installation still has no leaf, it MUST, unless a rate limit refused the add (RATE-041), publish the sync message to the leaves the group holds and, when the group’s floor admits GMOD-055’s retry, MUST store a retry of the add that survives a restart, runs whether or not any key is owed, and runs after each GMOD-055 retry interval while that group is still the one SYNC-002 selects and the installation is still associated and has no leaf. | A revoked leaf reads the new root key and consent decisions. A missing current installation receives neither; selecting the newest join does not repair that omission. One installation without a usable key package does not hold preferences back from the installations that can read them, and the stored retry adds it once it can be added, even when nothing new is published. | | SYNC-016 | Updates survive a restart | After a restart, the stored consent and HMAC root key MUST reflect every admissible update the client received before the restart, merged under CONS-053 and SYNC-032, whether or not the process that received it applied it. | A restart mid-way otherwise leaves a device that never converges, and neither device can tell. | | SYNC-017 | One failure does not block the rest | If applying an admissible update fails, then the client MUST still apply the other admissible updates it holds. | | ## Known limitations SYNC-034 judges revocation by the publisher’s local identity state. A publisher that has not yet loaded a revocation still publishes to a group that holds the revoked leaf, and the revoked installation reads that update. A revoked leaf stays in a sync group that no current installation publishes to; nothing new reaches it there. A sync group can keep a revoked leaf that no valid commit can remove, left by a commit made before GMOD-046, until the inbox publishes another identity update; until then, every current installation’s sync publish to that group fails under SYNC-034. A sync group created by a client that predates the durable add in SYNC-001, and whose add was lost, holds only its creator until another installation of the inbox registers. A publication waits while the sync group cannot be reached, or while the own identity state cannot be read (SYNC-034). It is retried with backoff and never dropped. Until it succeeds, the other installations do not hold the change. A message the deployment refuses for good is retried for good, and the owed values behind it wait. After a network failure, the next attempt can send one message twice. SYNC-030 judges a sender against the identity updates the backend returns. A read served by a replica that has not yet stored a revocation reports the revoked installation as current. A message that installation sends in that window is applied by a device that read the lagging replica and dropped by one that read later. The device that applied the value can pass it on to other installations (SYNC-027, SYNC-035), so they can adopt it too; a later decision by the user replaces it. A root key applied this way is replaced when that device loads the revocation and cycles under SYNC-026. A new installation holds only its own decisions until a peer that has processed its Welcome, or the commit that added it, publishes under SYNC-035. A record held only by installations that never run again never arrives. A new installation that needs a root key before one arrives makes its own under SYNC-026; it is the newest, so it replaces the account’s key on every installation. A sync group is never removed. An inbox with many installations holds one sync group per installation, and each installation reads all of them. Two root-key cycles on installations that have not seen each other’s key are ordered by their clocks. SYNC-026 cycles when the client stores a revocation. A restart between storing it and the cycle skips the cycle on that installation; every other installation cycles on its own. A sync message whose sender no own identity state has held stays unapplied, and is read again on every pass. A registration absent from the publisher’s stored identity state is not added until the publisher learns it and next publishes. An associated installation that has no key package satisfying JOIN-093 receives nothing from the selected sync group until a retry adds it; the installations in that group still receive every publication. GMOD-055’s retry interval and version condition still apply; a previously skipped key in a group below that floor is not retried, so it receives nothing there. An associated installation that never again offers a usable key package, such as one that stopped running without being revoked, is retried each interval until it is revoked. An idle, unselected sync group receives no periodic membership repair. # Topic format Every envelope the backend stores is routed by a topic: one kind byte followed by an identifier the backend reads out of the payload. A client names topics when it queries, subscribes, and registers for push; the backend names them when it stores. Both sides compute the same bytes from the same table, so the table is the whole interoperability contract. It lives here so that the specs that use topics reference it instead of each restating it. ```mermaid flowchart LR P[ClientEnvelope payload] -->|read the identifier| B[The backend] B -->|kind byte + identifier| T[(Topic)] C[The client] -->|the same table| T T --> Q[Query, Subscribe, push registration] ``` ## Scope In scope: the kind byte of each topic kind, the length of its identifier and the payload field it is read from, the rule that the backend derives every stored envelope’s topic from its payload, and the rejection of a topic a request names that does not match the table. Out of scope: what the backend does with an envelope once routed, the envelope wire format, and the publish rejection an unroutable payload receives (`API`); which topics a client reads and how it keeps its position on them ([PROC](/specs/proc-message-processing/)); which topic kinds a push subscription may name (PUSH-215); inbox id derivation (IDENT-010); installation keys ([IDENT section 8](/specs/ident-identity-updates/#8-installations)); and group id generation (GMOD-040). | Related | Relation | | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `API` | Owns the envelope payloads the identifiers are read from, the publish admission that rejects a payload this spec cannot route (API-230), and the status codes (API-281). | | `JOIN` | Owns the welcome pointer whose `destination` is a welcome topic identifier the sender generates (JOIN-029), and the key package the installation key is read from (JOIN-001). | ## Terms | Term | Meaning | | ---------- | ------------------------------------------------------------------------------------------------------------ | | Kind byte | The first byte of a topic, which names the payload kind stored under it. | | Identifier | The bytes after the kind byte: the group id, commit-log id, installation key, or inbox id the payload names. | ## 1. Layout A topic is one kind byte and one identifier, with nothing before, between, or after them. The identifier has a fixed length for each kind, so a topic parses without a length prefix and two implementations cannot disagree about where it ends. The backend reads the identifier from the payload; a publish request carries no topic field, so a client cannot store an envelope anywhere but where its payload says. A group’s message topic carries its 32-byte group id. Its commit-log topic carries its commit-log id, a public key derived from the group root separately from the group id (GMOD-041), so neither id can be computed from the other without the root. The operator can still link a conversation’s two topics by timing, because each member reads both ([FORK Known limitations](/specs/fork-fork-recovery/#known-limitations)). A group whose id is 16 bytes has no topic: TOPIC-002 refuses any payload that names it. The table below is the layout. Its kind bytes and lengths are the exact values this spec owns (SPEC-039). | Kind byte | Payload | Identifier | Read from | | --------- | ---------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `0x00` | Group message | 32-byte group id | The `group_id` of the `PublicMessage` or `PrivateMessage` ([RFC 9420 §6](https://www.rfc-editor.org/rfc/rfc9420.html#section-6)) carried in `GroupMessage.data`. | | `0x01` | Welcome | 32-byte installation key | `installation_key` of `WelcomeMessage.V1` or of `WelcomeMessage.WelcomePointer`. | | `0x02` | Identity update | 32-byte inbox id | `IdentityUpdate.inbox_id`, 64 hexadecimal characters, decoded. | | `0x03` | Key package | 32-byte installation key | The `signature_key` of the leaf node of the `KeyPackage` ([RFC 9420 §10](https://www.rfc-editor.org/rfc/rfc9420.html#section-10)) carried in `KeyPackage.key_package_tls_serialized`. | | `0x04` | Commit-log entry | 32-byte commit-log id | `SealedCommitLogEntry.commit_log_id`. | API-210 owns `ClientEnvelope` and its payloads, and [JOIN section 1](/specs/join-joining-groups/#1-what-a-key-package-carries) defines `KeyPackage`, and [JOIN section 4](/specs/join-joining-groups/#4-unwrapping-a-welcome) defines `WelcomeMessage`. IDENT-001 owns the identity update; API-210 shows `SealedCommitLogEntry`, and [FORK section 2](/specs/fork-fork-recovery/#2-keys-and-signatures) defines `PlaintextCommitLogEntry`. This spec reads the identifier field of each payload. | ID | Title | Requirement | Why | | --------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | TOPIC-001 | Topic is derived from the payload | The backend MUST set the topic of every stored envelope to the kind byte the table above gives for its payload kind, followed by the identifier read from the payload field the table names, and nothing else. A kind byte in the table MUST NOT be assigned to another payload kind. | A client that computes a topic from the table and the backend that stores under it must reach the same bytes, or every query and subscription misses. | | TOPIC-002 | Unroutable payloads are not stored | If the identifier read from a payload is not the length the table gives for its kind, or `IdentityUpdate.inbox_id` is not 64 hexadecimal characters, then the backend MUST NOT store the envelope. | An envelope under a topic no client can compute is unreachable, and storing it would still consume a sequence id on nothing. | | TOPIC-003 | Reject a malformed topic | When a request names a topic whose kind byte is not in the table, or whose identifier length is not the one the table gives for that kind byte, the backend MUST fail the request with `INVALID_ARGUMENT`. | A topic that cannot be stored under can never match an envelope, so a read or a subscription that names one waits for ever without an error. | ## Known limitations A topic binds an envelope to the identifier its payload names. On kinds `0x00` and `0x04` that identifier is a public key, and admission requires a signature under it (API-230, API-300), so only an installation that holds the group root can publish to an existing group’s topics. Anyone who can reach the backend can still generate a key pair and publish signed envelopes to the topics its public key names, publish a Welcome naming any installation key, and read any topic whose identifier it knows. Such envelopes consume storage, and a Welcome its recipient’s processing capacity, without disclosing group plaintext. A welcome topic’s identifier need not be a registered installation key. A welcome pointer’s pointee is stored under 32 random bytes that name no installation (JOIN-029), and the backend cannot tell that topic from a real installation’s.