diff --git a/docs.json b/docs.json
index 59f401df5..84acce61f 100644
--- a/docs.json
+++ b/docs.json
@@ -1320,7 +1320,8 @@
"xchat/introduction",
"xchat/cryptography-primer",
"xchat/getting-started",
- "xchat/xchat-xdk"
+ "xchat/xchat-xdk",
+ "xchat/migrate-from-legacy-dms"
]
},
{
diff --git a/xchat/getting-started.mdx b/xchat/getting-started.mdx
index 6dddc58cc..47f49043f 100644
--- a/xchat/getting-started.mdx
+++ b/xchat/getting-started.mdx
@@ -255,6 +255,10 @@ Server and bot samples often use a **key blob** (`export_keys` / `import_keys`).
## 3. Create and register keys (first-time setup)
+
+**Only run first-time setup on accounts that do not already have X Chat keys.** Calling `generate_keypairs` + `POST /2/users/{id}/public_keys` on an account that already uses X Chat in the official X app replaces its cryptographic identity and breaks X Chat on the official app. Check `GET /2/users/{id}/public_keys` first — if keys already exist, load them in [step 2](#2-initialize-the-chat-xdk-with-existing-keys) instead.
+
+
Skip this step if you loaded existing keys in [step 2](#2-initialize-the-chat-xdk-with-existing-keys). Otherwise, one-time setup for a new identity does **three things**:
1. **Create the keypairs**: `generate_keypairs` produces the identity and signing keypairs.
diff --git a/xchat/handling-private-keys.mdx b/xchat/handling-private-keys.mdx
index 6135bc0a9..047f14938 100644
--- a/xchat/handling-private-keys.mdx
+++ b/xchat/handling-private-keys.mdx
@@ -82,6 +82,33 @@ Client apps should prefer **secure key backup**. Servers and bots often use an e
- **Do not** ship end-user private keys to “make the backend simpler.”
- **Do not** confuse **OAuth revoke** with **key revoke**. Disconnecting an app does not erase keys a user already exported or typed into a hostile client.
- **Do not** store raw `export_keys` output in `localStorage` or unencrypted IndexedDB for production UI apps.
+- **Do not** register a fresh server keypair (`POST /2/users/{id}/public_keys`) for an account that already uses X Chat on the official X app — it replaces the account's identity and breaks X Chat on the official app.
+- **Do not** call `unlock(passcode)` per message or per request from server infrastructure. Backup realms enforce an IP-based rate limit (~30 `unlock()` calls per minute per egress IP) that is separate from `api.x.com` limits. Unlock once and reuse the `Chat` instance in memory, or persist `export_keys()` in a secret manager/HSM and load with `import_keys()` on native bindings.
+- **Do not** auto-retry a failed `unlock(passcode)` call. Secure key backup enforces a small, hardware-enforced, **non-renewable** wrong-PIN budget (`juicebox_config.max_guess_count`). Exhausting it deletes the key share and makes older encrypted messages unreadable. Fail closed after one wrong PIN and prompt the account owner.
+
+
+**No forward secrecy:** Conversation keys are wrapped to long-lived P-256 identity keys. If an account's identity private key is compromised, the holder can decrypt **past and future** conversation keys wrapped to that identity (rotating a conversation key protects only future messages). Disclose this to customers and treat leaked key material as a historical exposure.
+
+
+---
+
+## B2B / multi-tenant key custody
+
+Do **not** collect encryption PINs or private keys from consumer end users. For **business-to-business platforms** (customer care, social media management, archiving, automation) that must operate messaging on behalf of business accounts also used in the official X app, server-side key custody is supported **only with explicit X partner approval** (contact your X account representative) and all of the following:
+
+- **Business customers only:** Customers are businesses/organizations, not consumers; keys are used strictly for that business's own X Chat identity and conversations.
+- **Knowing consent & disclosure:** The business knowingly provides key material (one-time PIN unlock to export the key blob, then immediately discard the PIN) and is explicitly told that encryption keys are separate from OAuth — revoking OAuth does **not** revoke previously shared keys.
+- **Contract / DPA coverage:** Covers key custody, KMS/HSM encryption at rest, least-privilege access, audited reads, breach notification, and deletion/return on termination.
+- **One secret per tenant:** Store one key blob per account (`user_id` + `public_key_version`) in a managed KMS/HSM/Secrets Manager with isolated decrypt workers; never pool tenant keys or store the PIN.
+
+### Key lifecycle events to handle
+
+| Event | What happens | Required action |
+|:------|:-------------|:----------------|
+| **Owner changes their PIN** | Exported `export_keys()` blob keeps working (it does not depend on the PIN) | No action needed |
+| **Owner runs Reset Chat** | A new `public_key_version` is minted; the old blob no longer matches | Detect `public_key_version` mismatch, mark the tenant as needing re-onboarding, stop sending, and request a fresh one-time unlock + export |
+| **Owner resets a forgotten PIN or exhausts guess limit** | Messages encrypted under the previous keys become unreadable | Never auto-retry PINs; route to re-onboarding |
+| **Customer revokes OAuth or offboards** | API tokens stop working, but previously exported keys remain cryptographically valid | Delete all copies/backups of the key blob and instruct the business to revoke app access **and run Reset Chat** in the X app |
---
diff --git a/xchat/introduction.mdx b/xchat/introduction.mdx
index 9cea32b8a..bfdbc50dd 100644
--- a/xchat/introduction.mdx
+++ b/xchat/introduction.mdx
@@ -44,14 +44,15 @@ Grouped under **API reference** in the sidebar, including:
## Auth notes
-Use **OAuth 2.0 user context** with DM-related scopes (`dm.read`, `dm.write`, plus `users.read` / `tweet.read` as required; `media.write` for uploads). X Chat activity for a user requires that user's authorization. Secure key backup configuration is returned on **your** public-key record (`juicebox_config` field); see Getting Started.
+Use **OAuth 2.0 user context** with DM-related scopes (`dm.read`, `dm.write`, `users.read`, `tweet.read`, **`media.write` for both media uploads and downloads**, and `offline.access` for refresh tokens). X Chat activity for a user requires that user's authorization. Secure key backup configuration is returned on **your** public-key record (`juicebox_config` field); see [Getting Started](/xchat/getting-started) and the full scope matrix in [Migrate from Legacy DMs](/xchat/migrate-from-legacy-dms#2-authentication-and-oauth-20-scope-matrix).
---
## Next steps
-1. [Cryptography primer](/xchat/cryptography-primer): optional background on encryption concepts
-2. [Getting Started](/xchat/getting-started): implement keys, send, and receive
-3. [Chat XDK](/xchat/xchat-xdk): encryption SDK reference
-4. [Building UI apps with WASM](/xchat/building-ui-apps-with-wasm) and [Handling private keys](/xchat/handling-private-keys): keep keys on-device and treat PINs as root credentials
-5. [Real-time events](/xchat/real-time-events), [Media](/xchat/media), or [Troubleshooting](/xchat/troubleshooting) when you need those topics
+1. [Migrate from Legacy DMs](/xchat/migrate-from-legacy-dms): endpoint mapping, scopes, key custody, and cutover checklist for existing DM apps
+2. [Cryptography primer](/xchat/cryptography-primer): optional background on encryption concepts
+3. [Getting Started](/xchat/getting-started): implement keys, send, and receive
+4. [Chat XDK](/xchat/xchat-xdk): encryption SDK reference
+5. [Building UI apps with WASM](/xchat/building-ui-apps-with-wasm) and [Handling private keys](/xchat/handling-private-keys): keep keys on-device and treat PINs as root credentials
+6. [Real-time events](/xchat/real-time-events), [Media](/xchat/media), or [Troubleshooting](/xchat/troubleshooting) when you need those topics
diff --git a/xchat/media.mdx b/xchat/media.mdx
index c378c59a2..8fc5c9219 100644
--- a/xchat/media.mdx
+++ b/xchat/media.mdx
@@ -5,22 +5,39 @@ description: "Share images and file attachments in your encrypted chats: encrypt
keywords: ["X Chat media", "encrypted images", "file attachments", "encrypt_stream", "media upload", "media download"]
---
-Images and other files use the **same conversation key** as text. Encrypt bytes with the Chat XDK (`encrypt_stream` / `decrypt_stream`), upload via the **`/2/chat/media/upload`** routes (sidebar **API reference → Media**), then attach **`media_hash_key`** on `encrypt_message`.
+Images and other files are encrypted client-side with the Chat XDK (`encrypt_file` / `decrypt_file`), uploaded via the **`/2/chat/media/upload`** routes (sidebar **API reference → Media**), and referenced by **`media_hash_key`** inside `encrypt_message`.
-Include **`media.write`** with your DM scopes when uploading. Use hyphenated conversation ids in paths (`:` → `-`). Prefer MIME/dimensions from **decrypted** bytes.
+
+**`media.write` is required for both uploads and downloads.** All four `/2/chat/media/*` routes — including `GET /2/chat/media/{conversation_id}/{media_hash_key}` — require the `media.write` OAuth 2.0 scope, not `dm.read`.
+
+
+Use hyphenated conversation IDs in URL paths (`:` → `-`) and canonical colon IDs (`min:max` or `g…`) in upload JSON bodies. Prefer MIME and dimensions from **decrypted** bytes. Maximum encrypted file size is **100 MB**.
This path is **not** the Posts media model (`expansions=attachments.media_keys`, `media.fields=variants`, etc.). Those parameters apply to **Posts**; encrypted X Chat blobs are addressed by **`media_hash_key`** and X Chat media download.
+### Exact upload order (v1 format)
+
+In the current (v1) encrypted message format, each attachment's encryption key is derived from the message itself, so **build the message before encrypting the file** and start a fresh upload per attachment per message (never reuse a `media_hash_key` across two messages):
+
+1. **Initialize upload:** `POST /2/chat/media/upload/initialize` with `conversation_id` and `total_bytes = encrypted_file_size(len(plaintext))` → returns **`session_id`** and **`media_hash_key`**.
+2. **Build the message:** Call `encrypt_message` (or `encrypt_reply`) referencing `media_hash_key` in `attachments` → returns `payload` (including `event_b64` and `message_id`).
+3. **Encrypt and upload the file:** Encrypt the file with **`encrypt_file`** (or incremental **`file_encryptor`**) passing `payload.event_b64` and `media_hash_key`. Upload chunks via `POST /2/chat/media/upload/{session_id}/append` (`segment_index` **0–999**, e.g. 3 MiB chunks), then `POST /2/chat/media/upload/{session_id}/finalize` (`num_parts` as a **numeric string**).
+4. **Send the message:** `POST /2/chat/conversations/{id}/messages` with `payload`.
+
```mermaid
flowchart LR
- A[Plain bytes] --> B[encrypt_stream]
- B --> C[Upload 3 steps]
- C --> D[media_hash_key]
- D --> E[encrypt_message + send]
- F[GET media] --> G[decrypt_stream]
+ A[POST initialize] --> B[session_id + media_hash_key]
+ B --> C[encrypt_message -> event_b64]
+ C --> D[encrypt_file + append/finalize]
+ D --> E[POST messages]
+ F[GET media] --> G[decrypt_file]
G --> H[Plain bytes]
```
+
+**Legacy v0 / standalone files:** `encrypt_stream` / `decrypt_stream` (and `encrypt_file_with_key` / `decrypt_file_with_key`) encrypt directly under a raw 32-byte key rather than deriving a per-message file key (used for group avatars and v0 messages). For message attachments, use **`encrypt_file`** and **`decrypt_file`**, which handle both v0 and v1 messages seamlessly.
+
+
---
## Encrypt
@@ -116,7 +133,9 @@ flowchart LR
| Append | `POST` | `/2/chat/media/upload/{id}/append` |
| Finalize | `POST` | `/2/chat/media/upload/{id}/finalize` |
-Use the request bodies on the OpenAPI pages under **API reference → Media**. Prefer **encrypted** blob size where size is required. Finalize yields **`media_hash_key`** for attachments and download. Retry transient `5xx` with backoff. Python/TypeScript may use the XDK when media helpers exist; otherwise POST with a Bearer token in any language.
+Use the request bodies on the OpenAPI pages under **API reference → Media**. Pass **`total_bytes = encrypted_file_size(len(plaintext))`** to `initialize`, which returns `session_id` and **`media_hash_key`**. Build your encrypted message with that `media_hash_key` first, then encrypt the file via `encrypt_file` / `file_encryptor`, upload chunks with `append` (`segment_index` **0–999**), call `finalize` (`num_parts` as a **numeric string**), and finally POST the message. Retry transient `5xx` with backoff.
+
+On download (`GET /2/chat/media/{conversation_id}/{media_hash_key}`), use **`decrypt_file`** (passing the message's `event_b64`, `media_hash_key`, and your conversation keys) so both v0 and v1 encrypted attachments decrypt automatically, and cache downloaded media since downloads are rate-limited per account.
---
diff --git a/xchat/migrate-from-legacy-dms.mdx b/xchat/migrate-from-legacy-dms.mdx
new file mode 100644
index 000000000..9bd1ab538
--- /dev/null
+++ b/xchat/migrate-from-legacy-dms.mdx
@@ -0,0 +1,110 @@
+---
+title: "Migrate from Legacy Direct Messages to the X Chat API"
+sidebarTitle: Migrate from Legacy DMs
+description: "Complete guide to moving from v1.1 and v2 Direct Messages to the end-to-end encrypted X Chat API: auth scopes, endpoint mapping, key custody, real-time events, and cutover checklist."
+keywords: ["X Chat migration", "legacy DM migration", "Direct Messages to X Chat", "dm_events", "dm_conversations", "direct_messages", "E2EE migration"]
+---
+
+Moving from Legacy Direct Messages (`v1.1 direct_messages/*`, `v2 /2/dm_events`, `/2/dm_conversations`, and Account Activity DM webhooks) to the **X Chat API** (`/2/chat/*`) is an architectural change, not a URL swap. X routes only ciphertext; encryption, decryption, and signing run in your client using the **[Chat XDK](/xchat/xchat-xdk)**.
+
+---
+
+## 1. What changes architecturally
+
+| Aspect | Legacy DMs (v1.1 / v2) | X Chat API (`/2/chat`) |
+|:-------|:-----------------------|:-----------------------|
+| **Encryption** | Server-side plaintext (`text`) | End-to-end encrypted & signed via the [Chat XDK](/xchat/xchat-xdk); X relays ciphertext only |
+| **Credentials** | OAuth token only | OAuth 2.0 user token **plus** P-256 identity & signing private keys (backed up via Juicebox PIN or exported key blob) |
+| **Starting a 1:1** | One send call | Conversation-key handshake (`POST /2/chat/conversations/{id}/keys`) first if no key exists, then send |
+| **Reading history** | Cross-conversation `GET /2/dm_events` feed | No global feed — list `GET /2/chat/conversations` (`?start_time=`), then page `GET /2/chat/conversations/{id}/events` |
+| **Media** | Uploaded once via general media upload; server-readable | Client-encrypted (`encrypt_file`), uploaded in chunks, downloaded as ciphertext (`media.write` required for **both** upload and download) |
+| **Real-time delivery** | Account Activity `direct_message_*` webhooks / XAA `dm.*` | X Activity API `chat.*` events (stream or webhook), decrypted client-side |
+
+
+**No forward secrecy:** X Chat wraps conversation keys to long-lived P-256 identity keys. Anyone who obtains an account's identity private key can decrypt past and future conversation keys wrapped to it. Protect private keys and PINs as root credentials — see [Handling private keys](/xchat/handling-private-keys).
+
+
+---
+
+## 2. Authentication and OAuth 2.0 scope matrix
+
+Every `/2/chat/*` and `/2/users/*/public_keys` route requires **user-context authentication**. App-Only Bearer tokens are rejected with `403 unsupported-authentication` (the single exception is `GET /2/activity/stream`, which requires an App-Only Bearer token).
+
+**OAuth 2.0 User Context (PKCE)** is recommended. Missing scopes return `403 missing-scopes` listing the missing values:
+
+| Route group | Required OAuth 2.0 scopes |
+|:------------|:--------------------------|
+| `GET /2/chat/conversations` | `dm.read`, `users.read` |
+| All other chat **reads** (conversation metadata, events, pinned messages, message requests, admin requests, invites, settings) and `GET /2/users/{id}/public_keys`, `GET /2/users/public_keys` | `dm.read`, `tweet.read`, `users.read` |
+| All chat **writes** (send, conversation keys, groups, members, admins, mute, archive, delete, read/unread, typing, settings, accept message request) and `POST /2/users/{id}/public_keys` | `dm.write`, `tweet.read`, `users.read` |
+| `POST /2/chat/conversations/group/initialize` | `dm.write` |
+| **All four media routes:** `initialize`, `append`, `finalize`, **and `GET /2/chat/media/{id}/{media_hash_key}` (download)** | **`media.write`** |
+| `POST /2/activity/subscriptions` for any `chat.*` event | `dm.read` |
+
+
+**Media download requires `media.write`, not `dm.read`.** Request `media.write` even if your integration only downloads attachments. Users who previously authorized legacy DMs will need to re-authorize to grant `media.write`.
+
+
+**Recommended full scope set:**
+
+```text
+tweet.read users.read dm.read dm.write media.write offline.access
+```
+
+If you still sign X Chat calls with OAuth 1.0a during migration, configure your app with **Read, Write and Direct Messages** permissions and reissue user tokens — otherwise routes return `403 oauth1-permissions`.
+
+---
+
+## 3. Endpoint mapping
+
+### Legacy v2 Direct Messages → X Chat
+
+| Legacy v2 endpoint | X Chat replacement | Key differences |
+|:-------------------|:-------------------|:----------------|
+| `GET /2/dm_events` | `GET /2/chat/conversations` + `GET /2/chat/conversations/{id}/events` | No global feed. Use `?start_time=` on `/conversations` and fetch `/events` only for changed conversations. No `event_types` filter: decrypt and switch on type. |
+| `GET /2/dm_conversations/with/{participant_id}/dm_events` | `GET /2/chat/conversations/{participant_id}/events` | `max_results` is 1–100 with **default 10** (legacy default was 100). Always include `meta.conversation_key_events` in `decrypt_events`. |
+| `GET /2/dm_conversations/{id}/dm_events` | `GET /2/chat/conversations/{id}/events` | Use hyphenated `A-B` in URL paths (never colon `A:B`). Group IDs use `g…`. |
+| `GET /2/dm_events/{event_id}` | *No equivalent* | No lookup by event ID. Persist events from [Real-time events](/xchat/real-time-events) or page `…/events`. |
+| `POST /2/dm_conversations/with/{participant_id}/messages` | `POST /2/chat/conversations/{participant_id}/keys` *(first contact only)* → `POST /2/chat/conversations/{participant_id}/messages` | Body is an SDK-encrypted, signed payload. Returns `201` with `encoded_message_event`. Recipient must have X Chat keys. |
+| `POST /2/dm_conversations/{dm_conversation_id}/messages` | `POST /2/chat/conversations/{id}/messages` | Same as above. |
+| `POST /2/dm_conversations` (group) | `POST /2/chat/conversations/group/initialize` → `POST /2/chat/conversations/group` → `POST …/messages` | Two-step group create with per-member wrapped keys and 2 `action_signatures`. First message is a separate send. |
+| `DELETE /2/dm_events/{event_id}` | `POST /2/chat/conversations/{id}/messages/delete` | Batch `sequence_ids`, explicit `delete_for_all` / `delete_for_self`, signed `action_signatures`, requires conversation ID. |
+| `GET /2/dm_conversations/media/{dm_id}/{media_id}/{resource_id}` | `GET /2/chat/media/{conversation_id}/{media_hash_key}` | Returns ciphertext (`application/octet-stream`); decrypt client-side with `decrypt_file`. Requires **`media.write`**. |
+| General media upload (`media_id`) | `POST /2/chat/media/upload/initialize` → `/{id}/append` → `/{id}/finalize` | Upload encrypted bytes in the v1 order (`initialize` → `encrypt_message` → `encrypt_file` → `append` → `finalize` → send). See [Media](/xchat/media). |
+
+### Legacy v1.1 Direct Messages → X Chat
+
+| Legacy v1.1 endpoint | X Chat replacement |
+|:---------------------|:-------------------|
+| `GET /1.1/direct_messages/events/list.json` | `GET /2/chat/conversations` + `GET /2/chat/conversations/{id}/events` |
+| `GET /1.1/direct_messages/events/show.json` | *No equivalent* — page conversation events |
+| `POST /1.1/direct_messages/events/new.json` | `POST /2/chat/conversations/{id}/keys` (first contact) + `POST /2/chat/conversations/{id}/messages` (Chat XDK supports `quick_reply` in encrypted message content; no send-side CTA API) |
+| `DELETE /1.1/direct_messages/events/destroy.json` | `POST /2/chat/conversations/{id}/messages/delete` |
+| `POST /1.1/direct_messages/indicate_typing.json` | `POST /2/chat/conversations/{id}/typing` (empty body) |
+| `POST /1.1/direct_messages/mark_read.json` | `POST /2/chat/conversations/{id}/read` (empty body marks up to newest; pass `action_signatures` to target a specific event — fields like `seen_until_sequence_id` are ignored) |
+| `direct_messages/welcome_messages/*` | Supported in v2 — contact your X account representative for v2 partner onboarding |
+| `custom_profiles/*` | *No equivalent* |
+| `media/upload` (`media_category=dm_*`) & `ton.twitter.com` DM media | `/2/chat/media/upload/*` and `GET /2/chat/media/{conversation_id}/{media_hash_key}` |
+| Account Activity `direct_message_*` webhooks / XAA `dm.*` | X Activity API `chat.*` events ([Real-time events](/xchat/real-time-events)). Typing and read receipts arrive as encrypted conversation events (`Typing`, `ReadReceipt`, `MarkedUnread`). |
+
+---
+
+## 4. Behavioral differences and caveats to plan for
+
+- **Conversation ID formats:** Events and Activity payloads carry canonical colon-joined 1:1 IDs (`min:max`), which are **never valid in URL paths**. Replace `:` with `-` (or pass the bare recipient user ID) in every URL. Group IDs (`g…`) work everywhere unchanged.
+- **Message requests:** First messages from non-followers land in `GET /2/chat/message_requests` (fixed limit: **75 req / 15 min**), not `/2/chat/conversations`. Calling `GET /2/chat/message_requests/{id}` has a side effect — it marks messages delivered (like opening the request in the X app). **Replying does not accept a request**; call `POST /2/chat/message_requests/{id}/accept`.
+- **Pagination & inbox size:** `GET /2/chat/conversations` supports `max_results` up to 1,000, but large pages can time out (`503`) — use `25–100` and step down on `503`. The `pagination_token` is bound to your query filters (changing filters returns `400`), and pages can be short or empty while `has_more` is `true`.
+- **Older unencrypted history:** Legacy-era messages lack `conversation_key_version` and are rejected by the Chat XDK's default fail-closed verification policy. Only opt in deliberately (`set_reject_unverified(false)`) and label them unverified.
+- **Enterprise legacy-DM allowlist gotcha:** While an app remains on X's enterprise legacy-DM allowlist with a live DM token for an account, new 1:1s stay unencrypted and `POST /2/chat/conversations/{id}/keys` can return a misleading `403`. See [Troubleshooting](/xchat/troubleshooting#enterprise-legacy-dm-allowlist-cutover-gotcha).
+- **Known OpenAPI response caveat (`POST /2/chat/conversations/{id}/members`):** The generated OpenAPI schema types this response as a Post, whereas the live response is `{"data":{"current_member_ids":[...],"conversation_key_change_sequence_id":"..."}}`. Hand-parse this response if you generate clients from the spec.
+- **Outbound feature-switch read:** The Chat XDK makes an anonymous `GET https://api.x.com/2/chat/features` request to select the v1 message/media encryption format. Allowlist this URL in firewalled environments so the SDK does not fall back to v0.
+
+---
+
+## 5. Pre-cutover verification checklist
+
+- [ ] **Zero legacy DM calls remaining:** Audit and remove `/2/dm_events`, `/2/dm_conversations`, v1.1 `direct_messages/*`, `media_category=dm_*`, Account Activity DM webhooks, and XAA `dm.*` subscriptions.
+- [ ] **Auth & scopes verified:** OAuth 2.0 user context with `tweet.read users.read dm.read dm.write media.write offline.access`; App-Only Bearer used **only** on `GET /2/activity/stream`. Media download succeeds (verifies `media.write`).
+- [ ] **Key custody & safety verified:** Key architecture chosen per [Handling private keys](/xchat/handling-private-keys) (B2B partner approval obtained if holding keys for third-party business accounts); brand account's official X app still works after onboarding; no PIN persisted or logged; Juicebox `unlock()` never auto-retried on failure; `public_key_version` rotation monitored.
+- [ ] **Core round-trips tested:** New 1:1 key handshake → encrypted send (retry reuses identical payload, produces one message) → `chat.received` / `chat.sent` / `chat.conversation.join` delivery & decrypt → encrypted media upload/download round-trip → message request accept → group create.
+- [ ] **Allowlist cutover (Enterprise):** After cutover, coordinate with your X account representative to remove the app from the enterprise legacy-DM allowlist so new 1:1s encrypt cleanly.
diff --git a/xchat/real-time-events.mdx b/xchat/real-time-events.mdx
index 55f45cd32..5d9c324d5 100644
--- a/xchat/real-time-events.mdx
+++ b/xchat/real-time-events.mdx
@@ -21,15 +21,20 @@ Private X Chat event types need authorization for the user you monitor. Encrypte
| Event | When |
|:------|:-----|
-| `chat.received` | Subscribed user receives an encrypted DM |
-| `chat.sent` | Subscribed user sends an encrypted DM |
-| `chat.conversation_join` | Subscribed user joins a group (when offered) |
+| `chat.received` | Subscribed user receives an encrypted message |
+| `chat.sent` | Subscribed user sends an encrypted message |
+| `chat.conversation.join` | Subscribed user is added to a group (`chat.conversation_join` is a deprecated alias) |
+| `chat.conversation.member_added` / `member_removed` | Group membership changes |
+| `chat.conversation.admin_added` / `admin_removed` | Group admin changes |
+| `chat.update.group_name` / `chat.update.restrictions` | Group settings change |
+
+Typing indicators and read receipts no longer arrive as separate webhook types — they are delivered as encrypted events inside the conversation (decrypted event types `Typing`, `ReadReceipt`, `MarkedUnread`). Subscribe to **`chat.conversation.join`** for bots so they learn when added to a group and receive the group conversation key.
---
## 1. Choose delivery
-**Activity stream (often simplest for bots):** `GET /2/activity/stream` with an app Bearer token (optional `backfill_minutes`, `start_time`, `end_time` per OpenAPI). Filter client-side for `chat.received` / `chat.sent`.
+**Activity stream (often simplest for bots):** `GET /2/activity/stream` with an app Bearer token (optional `backfill_minutes`, `start_time`, `end_time` per OpenAPI). **Every open stream connection for an app receives every event**, so run one consumer per app and fan out internally. Filter client-side for `chat.received` / `chat.sent` / `chat.conversation.join`.
**Activity subscriptions:** manage durable subscriptions with:
@@ -38,9 +43,9 @@ Private X Chat event types need authorization for the user you monitor. Encrypte
- `PUT /2/activity/subscriptions/{subscription_id}`: update
- `DELETE /2/activity/subscriptions/{subscription_id}` or `DELETE /2/activity/subscriptions?ids=`: delete
-Request bodies and required scopes are defined in the OpenAPI operation for each route. Creating an X Activity API (XAA) subscription requires **user-context authorization** (OAuth 2.0 user context with the relevant scopes, such as `dm.read` for chat events) for the user whose activity you monitor.
+Request bodies and required scopes are defined in the OpenAPI operation for each route. Creating an X Activity API (XAA) subscription requires **user-context authorization** (OAuth 2.0 user context with `dm.read` for chat events) for the user whose activity you monitor.
-**Webhooks:** if you terminate events on your HTTPS endpoint, register a webhook with `POST /2/webhooks`, pass CRC challenges, then create your activity subscriptions with `POST /2/activity/subscriptions`, referencing your `webhook_id` (see Webhooks and Activity operations in OpenAPI). Python/TypeScript XDK may expose helpers for webhooks and activity when your SDK version includes them.
+**Webhooks:** if you terminate events on your HTTPS endpoint, register a webhook with `POST /2/webhooks`, pass CRC challenges, then create your activity subscriptions with `POST /2/activity/subscriptions`, referencing your `webhook_id` (see Webhooks and Activity operations in OpenAPI). Use `POST /2/webhooks/replay` to replay missed webhook deliveries. Note that `payload.conversation_id` arrives in canonical colon form (`min:max` for 1:1s) — replace `:` with `-` before placing it in URL paths.
@@ -200,7 +205,14 @@ JavaScript uses camelCase event types (`message`); other bindings use `"Message"
To keep the key maps in your own hands instead, `extract_conversation_keys` decrypts the keys from `conversation_key_change_event` and `decrypt_event` accepts them (and the sender's signing keys) as explicit arguments; an explicit non-empty argument always wins over the stores.
-History: [`GET /2/chat/conversations/{id}/events`](/x-api/chat/get-chat-conversation-events) + **`decrypt_events`**; see [Getting Started](/xchat/getting-started#6-receive-and-decrypt).
+### History and reconciliation (avoid polling storms)
+
+Unlike legacy `GET /2/dm_events`, X Chat has **no account-wide event feed or cursor**. Do **not** loop over every conversation in your inbox polling `GET /2/chat/conversations/{id}/events` on a timer — high-frequency polling quickly exhausts per-user event rate limits (`429`).
+
+Instead, use **XAA (`chat.received` / `chat.sent`)** as your primary real-time path, and reconcile gaps with a two-step check:
+
+1. Call [`GET /2/chat/conversations`](/x-api/chat/get-chat-conversations) with **`start_time=`** (and **omit `end_time`**, which would exclude conversations that received newer messages). Results return newest-first and `meta.has_more` turns `false` once paging passes `start_time`.
+2. Call [`GET /2/chat/conversations/{id}/events`](/x-api/chat/get-chat-conversation-events) + **`decrypt_events`** **only for the conversations returned** in step 1. See [Getting Started](/xchat/getting-started#6-receive-and-decrypt).
---
diff --git a/xchat/troubleshooting.mdx b/xchat/troubleshooting.mdx
index abaae0376..a3bfd20df 100644
--- a/xchat/troubleshooting.mdx
+++ b/xchat/troubleshooting.mdx
@@ -16,7 +16,7 @@ For webhooks, OAuth, HTTP status codes, and rate limits, use the general [X API]
### Unlock fails (invalid passcode)
- Confirm the passcode matches the one used with `setup`
-- Wait between attempts; realms rate-limit wrong guesses and can lock recovery after too many failures
+- **Never auto-retry a failed `unlock()` call.** Secure key backup enforces a small, hardware-enforced, **non-renewable** wrong-guess budget (`juicebox_config.max_guess_count`). Exhausting it locks recovery and forces a reset, making messages encrypted under the previous keys unreadable. Fail closed after one wrong PIN and prompt the account owner.
@@ -62,6 +62,18 @@ For webhooks, OAuth, HTTP status codes, and rate limits, use the general [X API]
+### Unlock fails with `RateLimitExceeded`
+
+Secure key backup (`unlock`, `setup`, `change_pin`, `delete`) sends multiple recovery requests directly to the backup realms from your caller's egress IP. Those realms enforce an **IP-based rate limit** at the edge (around 30 `unlock()` calls per minute per egress IP) that is independent of `api.x.com` rate limits — X API rate-limit elevations do not raise it.
+
+- **Never call `unlock(passcode)` per message or per request** from server infrastructure or shared NAT IPs.
+- **Unlock once and reuse the `Chat` instance in memory** for the lifetime of the worker/session, or (on native bindings: Python, Go, Rust, C#, Java) unlock once, store the `export_keys()` blob in a secret manager or HSM, and load it with `import_keys()` on startup.
+
+### Key registration fails or breaks the official X app
+
+- **Never run first-time key registration (`generate_keypairs` + `POST /2/users/{id}/public_keys`) on an account that already uses X Chat in the official X app.** Registering a new server keypair replaces the account's cryptographic identity and breaks X Chat on the official X app. Load the account's existing keys via `unlock` or `import_keys` instead.
+- Public-key registration is also rate-limited to **1 registration per hour per account** in the backend (and 5 per 24 hours at the API gateway).
+
### Encrypt or decrypt fails because keys or identity are not set
Load private keys first, then set the **session identity**: your user id plus the `public_key_version` from your record on X. The `encrypt_*` and `prepare_*` methods sign with it; calling them with no session identity (and no explicit per-call override) is an error.
@@ -263,7 +275,34 @@ These mistakes are specific to X Chat encryption (not general HTTP errors):
### API returns 400 for a state-changing call
-Every state-changing chat call (adding or rotating conversation keys, creating a group, adding members) requires **`action_signatures`** in the request body, validated at the API boundary. A missing or malformed entry (each needs `message_id`, `encoded_message_event_detail`, and a `message_event_signature` with `signature`, `public_key_version`, and `signature_version`) returns an HTTP 400 problem-details response immediately. Use the SDK prepare methods (`prepare_conversation_key_change`, `prepare_group_create`, `prepare_group_members_change`) and send **all** returned signatures; group create and member adds return two.
+Every state-changing chat call (adding or rotating conversation keys, creating a group, adding members) should include **`action_signatures`** in the request body. A malformed entry (each needs `message_id`, `encoded_message_event_detail`, and a `message_event_signature` with `signature`, `public_key_version`, and `signature_version`) returns an HTTP 400 problem-details response immediately. Use the SDK prepare methods (`prepare_conversation_key_change`, `prepare_group_create`, `prepare_group_members_change`) and send **all** returned signatures; group create and member adds return two.
+
+### Common X Chat API error responses
+
+| HTTP / Error | Cause | Fix |
+|:-------------|:------|:----|
+| `400` `INVALID_IDENTITY_KEY_PAIR` (`POST /2/chat/conversations/{id}/keys`) | One or more participant keys used an outdated `public_key_version`. | Re-fetch `GET /2/users/{id}/public_keys` (or `GET /2/users/public_keys`), rebuild with `prepare_conversation_key_change`, and retry once. Do not cache public key versions indefinitely. |
+| `403` `UNAUTHORIZED_REQUESTING_USER` (`POST /2/chat/conversations/{id}/keys`) or `403` `recipient-not-messageable` (`POST /2/chat/conversations/{id}/messages`) | Permanent refusal: the recipient has not set up X Chat keys, does not follow you / has not accepted a message request, or their settings block DMs. | Check `GET /2/users/{id}/public_keys` before initializing keys and treat `403` as permanent — do not retry in a loop. |
+| `400` `xchat-setup-required` / `recipient-xchat-setup-required` | The sender or recipient has not registered X Chat public keys yet. | Ensure the sending account completed key setup, and verify recipients have public keys before sending. |
+| `400` `ContentsTooLarge` / validation error on send | Encrypted message payloads are capped at **20 KB** (~11,000 UTF-8 plaintext bytes). | Truncate or split long messages before calling `encrypt_message`. |
+| `404` on `GET /2/chat/media/{id}/{media_hash_key}` | The attachment was deleted, expired, or the `media_hash_key` is invalid (for example, a legacy DM media ID rather than an encrypted X Chat `media_hash_key`). | Treat `404` as permanent — do not re-queue. |
+| `429` on `GET /2/chat/conversations/{id}/events` | Polling every conversation on a fixed loop instead of reading only changed conversations. | Use [Real-time events](/xchat/real-time-events) (`chat.received` / `chat.sent`) for live delivery, and use `GET /2/chat/conversations?start_time=` to reconcile only conversations with new messages. |
+
+### Enterprise legacy-DM allowlist cutover gotcha
+
+If your app is on X's **enterprise legacy-DM allowlist** and still holds a live DM-scoped token (`dm.read` / `dm.write`, OAuth 1.0a or 2.0) for an account:
+
+- New 1:1 conversations for that account stay **unencrypted**.
+- `POST /2/chat/conversations/{id}/keys` can fail with a **misleading `403`** (*"This user can't receive encrypted chats from you yet: they need to follow you, and both accounts need X Chat keys"*), even when the follow relationship is not the issue.
+
+Do **not** loop on this `403` and do **not** re-register keys. Finish migrating to the X Chat API, then ask your X account representative to remove your app from the enterprise legacy-DM allowlist.
+
+### Endpoint and spec caveats
+
+- **`POST /2/chat/conversations/{id}/read` ignores unsupported body fields** (such as `seen_until_sequence_id`). Send an empty body to mark read up to the newest event, or pass `action_signatures` from `prepare_mark_conversation_read` to target a specific event.
+- **Message requests:** `GET /2/chat/message_requests/{id}` marks messages delivered (like opening the request in the X app), and **replying does not accept** the request — call `POST /2/chat/message_requests/{id}/accept`. `GET /2/chat/message_requests` is fixed at 75 requests / 15 minutes.
+- **Pagination defaults & timeouts:** `GET /2/chat/conversations/{id}/events` defaults to `max_results=10` (up to 100). On `GET /2/chat/conversations`, use `max_results` of 25–100 (large pages can return `503`), keep filters identical when passing `pagination_token` (changing filters returns `400`), and keep paging while `has_more` is `true` even if a page is short or empty.
+- **OpenAPI response type on `POST /2/chat/conversations/{id}/members`:** The generated OpenAPI spec types the response as a Post, while the live response returns `{"data":{"current_member_ids":[...],"conversation_key_change_sequence_id":"..."}}`. Hand-parse this response when using spec-generated clients.
---
diff --git a/xchat/xchat-xdk.mdx b/xchat/xchat-xdk.mdx
index 867c7384a..249361518 100644
--- a/xchat/xchat-xdk.mdx
+++ b/xchat/xchat-xdk.mdx
@@ -23,6 +23,9 @@ App walkthrough: [Getting Started](/xchat/getting-started). Sample bots: [chat-x
```bash
npm install @xdevplatform/chat-xdk
npm install juicebox-sdk # optional peer dependency; required for setup()/unlock() secure key backup
+
+ # Node.js servers that persist exported key blobs (importKeys / exportKeys):
+ # npm install @xdevplatform/chat-xdk-server # never bundle into a browser app
```
The compiled WASM engine ships inside the package; there is no build step. Requires Node.js 18+.
@@ -355,6 +358,10 @@ The secure key backup config accepts three shapes: the X API `juicebox_config` o
Optional: signature verification is **on by default** (`reject_unverified = true`); call `set_reject_unverified(false)` to disable it (not recommended); `update_config` if backup realm config changes; `is_unlocked` / `has_identity_key` for UI state. Full field lists live in the [chat-xdk repo](https://github.com/xdevplatform/chat-xdk) stubs.
+
+**Outbound feature-switch check:** Python, JS, Go, .NET, and JVM bindings make an anonymous `GET https://api.x.com/2/chat/features` request to select the current v1 message and media encryption format. Allowlist this URL in firewalled environments — if blocked, the SDK silently falls back to v0.
+
+
---
## Conversation keys
@@ -556,7 +563,9 @@ Verification is mandatory by default: omitting signing keys never skips it. With
## Encrypt and send helpers
-**`encrypt_message(conversation_id, text)`** builds the signed ciphertext for a text message; optional `entities`, `attachments` (via `media_hash_key`), `should_notify`, and `ttl_msec`. The sender identity resolves from the session (`set_identity`) and the conversation key from the opt-in key cache (`set_cache_keys`), or pass `sender_id` / `signing_key_version` and `conversation_key` + `conversation_key_version` explicitly. The SDK generates the **`message_id`** (a UUID embedded in the signed event) and returns it on the payload. Never mint your own; reuse the same payload on retries so an id is never minted twice. Map the payload into the send-message body: `message_id` → **`message_id`**, `encrypted_content` → **`encoded_message_create_event`**, `encoded_event_signature` → **`encoded_message_event_signature`**.
+**`encrypt_message(conversation_id, text)`** builds the signed ciphertext for a text message; optional `entities`, `attachments` (via `media_hash_key`), `quick_reply`, `should_notify`, and `ttl_msec`. Encrypted message payloads are capped at **20 KB** (~11,000 UTF-8 plaintext bytes). The sender identity resolves from the session (`set_identity`) and the conversation key from the opt-in key cache (`set_cache_keys`), or pass `sender_id` / `signing_key_version` and `conversation_key` + `conversation_key_version` explicitly. The SDK generates the **`message_id`** (a UUID embedded in the signed event) and returns it on the payload. Never mint your own; reuse the same payload on retries so an id is never minted twice. Map the payload into the send-message body: `message_id` → **`message_id`**, `encrypted_content` → **`encoded_message_create_event`**, `encoded_event_signature` → **`encoded_message_event_signature`**.
+
+**Quick replies and clickable URLs.** Pass `quick_reply` on `encrypt_message` or `encrypt_reply` (supported across all bindings since v0.5.1) with either a `request` (`options: { id, options: [{ id, label, metadata, description }] }`) to present selectable choices, or a `response` (`options: { request_id, metadata, selected_option_id }`) when answering one; user selections arrive in decrypted `content.quick_reply` (`quickReply` in JS). The SDK does **not** auto-extract URLs or mentions from `text`: to make links clickable in X Chat clients, pass explicit `entities` (`"url"`, `"mention"`, etc.) with **UTF-8 byte offsets** (`start` inclusive, `end` exclusive — `EntityDescriptor` in Rust/.NET/JVM, `[start, end, type]` tuples in Python/JS/Go).
**Replies are event-based.** `encrypt_reply(conversation_id, text, reply_to_event)` takes the base64 raw event being replied to. The SDK derives the quoted preview (sequence id, sender, text, entities, attachments) from it and embeds the signed original in the outgoing message so recipients can validate the quote. Pass `reply_to_ckces` (the raw key-change events) when the original was encrypted under an older key version than the reply. When the original was **edited**, pass the raw edit event as `reply_to_edit_event`: the preview then quotes what the message says now (its text and entities come from the edit), and the edit travels alongside the original for the receiver to check. The explicit `reply_to_*` fields remain as overrides for callers that no longer hold the raw event.
@@ -573,7 +582,7 @@ The conversation id passed to `encrypt_message` / `encrypt_reply` can be any for
```python
payload = chat.encrypt_message(
conversation_id, "Hello",
- # Optional keyword args: entities, attachments, should_notify, ttl_msec
+ # Optional keyword args: entities, attachments, quick_reply, should_notify, ttl_msec
)
body = {
"message_id": payload.message_id,
@@ -599,7 +608,7 @@ The conversation id passed to `encrypt_message` / `encrypt_reply` can be any for
const payload = chat.encryptMessage({
conversationId,
text: 'Hello',
- // Optional: entities, attachments, shouldNotify, ttlMsec
+ // Optional: entities, attachments, quickReply, shouldNotify, ttlMsec
});
const body = {
message_id: payload.messageId,
@@ -727,7 +736,7 @@ The conversation id passed to `encrypt_message` / `encrypt_reply` can be any for
## Media streams
-Encrypt file bytes with the **same** conversation key used for text, upload via Chat media APIs, and attach **`media_hash_key`** on `encrypt_message`. This is not the Posts media model (`expansions=attachments.media_keys`). Full upload/download flow: [Media](/xchat/media).
+For message attachments in the current (v1) format, initialize the upload first (`total_bytes = encrypted_file_size(len(plaintext))`), build the encrypted message with the returned **`media_hash_key`**, then encrypt the file with **`encrypt_file`** / **`file_encryptor`** (passing `payload.event_b64` and `media_hash_key`) and decrypt downloads with **`decrypt_file`** / **`file_decryptor`**. `encrypt_stream` / `decrypt_stream` (and `encrypt_file_with_key` / `decrypt_file_with_key`) encrypt directly under a raw 32-byte key for standalone files (such as group avatars) or v0 messages. This is not the Posts media model (`expansions=attachments.media_keys`). Full upload/download flow: [Media](/xchat/media).