> ## Documentation Index
> Fetch the complete documentation index at: https://docs.x.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Migrate from Legacy Direct Messages to the X Chat API

> Complete guide to moving from v1.1 and v2 Direct Messages to the end-to-end encrypted X Chat API: timeline, auth scopes, endpoint mapping, key custody, real-time events, cutover checklist, troubleshooting, and FAQ.

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](https://docs.x.com/xchat/xchat-xdk.md)**.

> [!WARNING]
>
> **Cutover deadline: December 9, 2026.** December 9, 2026 is the last day to move off legacy Direct Messages. After December 9, X stops accepting new unencrypted DMs, legacy webhooks stop sending unencrypted DM events, and `/2/chat/*` is the only API for DMs.
>
> Existing conversations are upgraded on X's side — you do **not** need to migrate or archive your existing DM history. Contact your X account representative if you have blockers or need engineering assistance with your migration timeline.

> [card] [Auth & OAuth scopes](#2-authentication-and-oauth-20-scope-matrix)
>
> User-context tokens, `media.write` for downloads, and OAuth 1.0a compatibility until Jan 31, 2027.

> [card] [Endpoint & event mapping](#3-endpoint-mapping)
>
> Full v2, v1.1, Account Activity, X Activity, and new X Chat endpoint mappings.

> [card] [Key custody & B2B storage](#4-key-custody-and-b2b-key-storage)
>
> Checking existing keys, one-time PIN unlock/export, B2B approval criteria, and key lifecycle rules.

> [card] [Troubleshooting & FAQ](#7-troubleshooting-and-faq)
>
> Error reference, pre-cutover testing (allowlist & OAuth 1.0a), and partner FAQ.

> [accordion] What is being retired on December 9, 2026?
>
> * **v1.1 Direct Messages:** `direct_messages/*` (events, typing indicator, mark read, welcome messages, DM media) and `custom_profiles/*`
> * **v2 Direct Messages:** `/2/dm_events`, `/2/dm_events/{id}`, and `/2/dm_conversations/*` (including DM media)
> * **Legacy DM media uploads:** `media/upload` with `media_category=dm_*`
> * **Legacy real-time DM events:** Account Activity DM events (`direct_message_events`, `direct_message_indicate_typing_events`, `direct_message_mark_read_events`) and X Activity `dm.*` events
>
> **Replacements:** `/2/chat/*` and X Activity `chat.received`, `chat.sent`, and `chat.conversation.join` events.

***

## 1. What changes architecturally

> [tab] Legacy DMs vs. X Chat
>
> | 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](https://docs.x.com/xchat/xchat-xdk.md); X relays ciphertext only |
> | **Credentials** | OAuth token only | User-context OAuth token **plus** P-256 identity & signing private keys (Juicebox PIN or exported key blob) |
> | **Send body** | `{"text": "...", "attachments": [{"media_id": "..."}]}` | SDK-built encrypted, signed payload (`message_id`, `encoded_message_create_event`, `encoded_message_event_signature`, `xdk_version`) |
> | **Read response** | `dm_events` objects with plaintext `text`, `sender_id`, `attachments` | `ChatMessageEvent` objects with encrypted `encoded_event`, decrypted via the Chat XDK |
> | **Starting a 1:1** | One send call | Conversation key setup (`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 |

> [tab] Official Chat XDK packages
>
> Do **not** hand-roll X Chat cryptography. The wire formats include non-standard details (such as a 16-byte AES-GCM IV inside ECIES, key binding, signature payloads, and per-message/per-attachment key derivation). Always use the official **[Chat XDK](https://docs.x.com/xchat/xchat-xdk.md)**:
>
> | Language / Package | Install | Key export (`export_keys` / `import_keys`) & notes |
> | :- | :- | :- |
> | **Python** (`chatxdk`, `import chat_xdk`) | `pip install chatxdk` | Python 3.10+. Supports Juicebox unlock and `export_keys` / `import_keys`. |
> | **JS / TS (browser)** (`@xdevplatform/chat-xdk`) | `npm install @xdevplatform/chat-xdk juicebox-sdk` | WASM for browsers and Node 18+. Keys stay in Juicebox secure key backup (**no key export**). |
> | **Node.js (server)** (`@xdevplatform/chat-xdk-server`) | `npm install @xdevplatform/chat-xdk-server` | Server-side `exportKeys` / `importKeys`. Never bundle into a browser app. |
> | **Go, Rust, .NET 8+ / .NET Framework 4.7.2+, JVM (JDK 8+)** | See [Chat XDK](https://docs.x.com/xchat/xchat-xdk.md) | Native bindings supporting `export_keys` / `import_keys`. Go ships prebuilt libraries for macOS (`arm64`, `amd64`) and Linux (`amd64` and `arm64`, both glibc and musl via `-tags musl`). |
> | **Ruby** (`chat_xdk`, `require "chat_xdk"`) | `gem install chat_xdk` | Ruby 3.0+. Bundles prebuilt native libraries for macOS (`arm64`, `x64`), Linux (`x64`, `arm64`), and Windows (`x64`). Supports Juicebox unlock and `export_keys` / `import_keys`. |
>
> There are no Ruby or PHP bindings — run encryption in a small service in a supported language and call it from your app. For REST transport, use the official XDK (`pip install xdk` / `npm install @xdevplatform/xdk`) or any HTTP client.

> [!WARNING]
>
> **No forward secrecy (or post-compromise security):** 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 (rotating a conversation key protects only future messages). Disclose this to customers and protect private keys and PINs as root credentials — see [Handling private keys](https://docs.x.com/xchat/handling-private-keys.md).

***

## 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 sole exception is `GET /2/activity/stream`, which requires an App-Only Bearer token).

> [tab] OAuth 2.0 (Recommended)
>
> Missing scopes return `403 missing-scopes` listing the missing values. There are no separate X Chat scopes — if your integration only reads and archives messages, `dm.write` is not needed (though `media.write` is still required to download chat attachments).
>
> | 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` |
>
> > [!WARNING]
> >
> > **Media download requires `media.write`, not `dm.read`.** Request `media.write` even if your integration only downloads attachments. Users who previously authorized legacy DMs without `media.write` must re-authorize.
>
> **Recommended full scope set:**
>
> ```text theme={null}
> tweet.read users.read dm.read dm.write media.write offline.access
> ```

> [tab] OAuth 1.0a (Until Jan 31, 2027)
>
> OAuth 1.0a user tokens **work with every X Chat endpoint** during migration — including welcome messages, welcome-message rules, surveys, media upload and download, `GET` / `POST /2/users/{id}/public_keys`, and `POST /2/activity/subscriptions` for chat events.
>
> * **Required app permission:** Configure **"Read, Write and Direct Messages"** permissions. Every X Chat route, including send, typing, read and unread, group creation, and media, requires it: apps with **"Read"** or **"Read and Write"** get `403 oauth1-permissions`. Tokens keep the permissions they were originally granted: if your app already has this permission, existing tokens keep working; if you change the permission, users must re-authorize.
> * **`chat-xdk` is auth-agnostic:** The Chat XDK only encrypts, decrypts, and signs locally — it never calls the X API with your token, so you can sign HTTP requests with either OAuth 1.0a or OAuth 2.0.
> * **Plan your move before January 31, 2027:** OAuth 1.0a retires on **January 31, 2027**. Use the [OAuth 1.0a to OAuth 2.0 token exchange](https://docs.x.com/fundamentals/authentication/oauth-2-0/oauth-1-0a-token-exchange.md) to move existing users without a consent screen:
>
> | Original OAuth 1.0a token permission | Scopes granted on token exchange | Needs re-authorization for X Chat? |
> | :- | :- | :- |
> | **Read, Write and Direct Messages** | `dm.read`, `dm.write`, `media.write`, `offline.access` | No (no consent screen) |
> | **Read and Write** | `media.write` only | Yes |
> | **Read** | Neither DM nor media scopes | Yes |

***

## 3. Endpoint mapping

> [tab] Legacy v2 → 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](https://docs.x.com/xchat/real-time-events.md) 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`**. |
> | `POST /2/media/upload` (DM media) | `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](https://docs.x.com/xchat/media.md). |

> [tab] Legacy v1.1 → 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` and `ctas` in encrypted message content; see [Chat XDK](https://docs.x.com/xchat/xchat-xdk.md#encrypt-and-send-helpers)) |
> | `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/*` & surveys | X Chat versions exist in v2 and accept OAuth 2.0 or OAuth 1.0a user tokens (OAuth 1.0a needs **"Read, Write and Direct Messages"**). Contact your X account representative for v2 partner onboarding. |
> | `custom_profiles/*` | *No equivalent* |
> | `POST /1.1/media/upload.json` (`media_category=dm_*`) & `GET ton.twitter.com/1.1/ton/data/dm/…` | `POST /2/chat/media/upload/initialize` → `/{id}/append` → `/{id}/finalize` and `GET /2/chat/media/{conversation_id}/{media_hash_key}` |

> [tab] Real-time events & webhooks
>
> **Event type mapping (AAA & XAA → X Chat)**
>
> | Legacy Account Activity (AAA) key | Legacy X Activity (XAA) | X Chat event (XAA) |
> | :- | :- | :- |
> | `direct_message_events` (inbound) | `dm.received` | `chat.received` |
> | `direct_message_events` (outbound) | `dm.sent` | `chat.sent` |
> | `direct_message_indicate_typing_events` | `dm.indicate_typing` | Encrypted conversation event (`Typing`) |
> | `direct_message_mark_read_events` | `dm.read` | Encrypted conversation event (`ReadReceipt` / `MarkedUnread`) |
> | — | — | `chat.conversation.join` (group join; `chat.conversation_join` is a deprecated alias) |
> | — | — | `chat.conversation.member_added`, `chat.conversation.member_removed` |
> | — | — | `chat.conversation.admin_added`, `chat.conversation.admin_removed` |
> | — | — | `chat.update.group_name`, `chat.update.restrictions` |
>
> **Subscription & delivery endpoints (AAA → XAA)**
>
> Existing DM subscriptions and Account Activity webhooks do **not** carry X Chat events. Create new X Activity subscriptions for each account (you can point them at your existing `webhook_id`).
>
> | Legacy Account Activity endpoint | X Activity API endpoint |
> | :- | :- |
> | `POST /2/account_activity/webhooks/{webhook_id}/subscriptions/all` | `POST /2/activity/subscriptions` |
> | `GET /2/account_activity/webhooks/{webhook_id}/subscriptions/all/list` | `GET /2/activity/subscriptions` |
> | `DELETE /2/account_activity/webhooks/{webhook_id}/subscriptions/{user_id}/all` | `DELETE /2/activity/subscriptions/{subscription_id}` or `DELETE /2/activity/subscriptions?ids=…` |
> | `CRUD /2/webhooks` & `POST /2/webhooks/replay` | Unchanged (set `webhook_id` on your subscription), or stream with `GET /2/activity/stream` (app Bearer token; run one consumer per app) |
>
> > [!NOTE]
> >
> > * **Auth:** `POST /2/activity/subscriptions` accepts both OAuth 2.0 user tokens (`dm.read`) and OAuth 1.0a user tokens (**"Read, Write and Direct Messages"**) for `chat.*` events. OAuth 1.0a tokens without that permission get `403 oauth1-permissions` when subscribing to `chat.*` or `dm.*` events.
> > * **Group joins:** Subscribe to `chat.conversation.join` so bots learn when added to a group and receive the group conversation key.
> > * **During cutover:** Unencrypted conversations still arrive as `dm.received` — subscribe to both `dm.received` and `chat.received` and deduplicate until cutover completes.
> > * **Sender profiles:** Chat events include profile details for the sender and subscribed user in `includes.users` (match `payload.sender_id` against `includes.users[].id`). Because `includes` is best-effort, fall back to `GET /2/users?ids=...` or `GET /2/chat/conversations?expansions=participant_ids&user.fields=...` and cache by user ID if a profile is omitted or you need extra fields.

> [tab] New X Chat endpoints
>
> | Category | X Chat API endpoints |
> | :- | :- |
> | **Encryption keys** | `GET /2/users/{id}/public_keys`, `GET /2/users/public_keys?ids=`, `POST /2/users/{id}/public_keys`, `POST /2/chat/conversations/{id}/keys` |
> | **Message requests** | `GET /2/chat/message_requests`, `GET /2/chat/message_requests/{id}`, `POST /2/chat/message_requests/{id}/accept` |
> | **Conversation state** | `GET /2/chat/conversations/{id}`, `GET /2/chat/conversations/{id}/pinned_messages`, `POST /2/chat/conversations/{id}/unread`, `POST /2/chat/conversations/{id}/mute`, `POST /2/chat/conversations/{id}/unmute`, `POST /2/chat/conversations/{id}/archive`, `POST /2/chat/conversations/{id}/unarchive`, `DELETE /2/chat/conversations/{id}` (or `POST …/delete`, deletes for you only), `PUT /2/chat/conversations/{id}/message_ttl`, `POST /2/chat/conversations/{id}/message_ttl/remove`, `PUT /2/chat/conversations/{id}/screen_capture` |
> | **Replies, reactions & edits** | Sent as encrypted event types through `POST /2/chat/conversations/{id}/messages` |
> | **Group management** | `PUT /2/chat/conversations/{id}`, `PUT /2/chat/conversations/{id}/admin_settings`, `POST /2/chat/conversations/{id}/members`, `POST /2/chat/conversations/{id}/members/remove`, `POST /2/chat/conversations/{id}/admins`, `POST /2/chat/conversations/{id}/admins/remove`, `GET` / `POST /2/chat/conversations/{id}/admin_requests`, `POST /2/chat/conversations/{id}/admin_requests/{user_id}/approve`, `POST /2/chat/conversations/{id}/admin_requests/{user_id}/reject`, `POST /2/chat/conversations/{id}/invite`, `POST /2/chat/conversations/{id}/invite/disable`, `GET /2/chat/conversations/{id}/invites/{token}`, `POST /2/chat/conversations/{id}/join_requests`, `POST /2/chat/conversations/{id}/join_requests/reject` |
> | **User settings** | `GET /2/chat/settings`, `PUT /2/chat/settings` |

> [tab] No 1:1 equivalent
>
> | Legacy feature | X Chat approach |
> | :- | :- |
> | **Global cross-conversation DM feed** (`GET /2/dm_events`, v1.1 `events/list.json`) | Use X Activity `chat.received` / `chat.sent` for live ingestion; reconcile gaps with `GET /2/chat/conversations?start_time=...` followed by `GET /2/chat/conversations/{id}/events` only for changed conversations. |
> | **Single-event lookup by ID** (`GET /2/dm_events/{id}`, v1.1 `events/show.json`) | Persist events keyed by sequence `id` / `message_id` and `conversation_id` as they arrive, or page the conversation. |
> | **Custom profiles** (`custom_profiles/*`) | No equivalent. |
> | **Server-side plaintext processing without keys** | Keyword search, moderation, analytics, archiving, and LLM processing only work where private keys are legitimately held (see [Key custody and B2B key storage](#4-key-custody-and-b2b-key-storage)). |
> | **Messaging accounts without X Chat keys** | Recipients without X Chat keys cannot receive encrypted messages (and nothing falls back to unencrypted). |

***

## 4. Key custody and B2B key storage

OAuth access and encryption keys are **separate control planes**: an OAuth token authorizes API calls, while private keys unlock and sign message contents. See [Handling private keys](https://docs.x.com/xchat/handling-private-keys.md) for full security rules.

> [!WARNING]
>
> **Never register new keys (`POST /2/users/{id}/public_keys`) silently on an account that already uses X Chat.** Each X account has one active identity key. Registering a new keypair replaces the account's previous identity and makes messages encrypted under the old keys unreadable — only create new keys on an existing X Chat account with the customer's explicit approval (and have the admin choose a new PIN for secure key backup so they can also use X Chat in the X app).

> [tab] Check keys & unlock flow
>
> **1. Check whether the account already has keys**
>
> Call `GET /2/users/{id}/public_keys` (or batch `GET /2/users/public_keys?ids=...` for up to 100 accounts).
>
> * **Key backup details returned:** The account already uses X Chat. Recover the existing keys with the owner's PIN. Only generate and register new keys if the customer explicitly authorizes replacing their existing identity (which makes messages encrypted under the old keys unreadable).
> * **No keys returned:** The account has never set up X Chat. For a dedicated bot account (or an uninitialized business account where the admin chooses the PIN in your connect flow so they can still use X Chat in the X app later), generate and register a keypair once via `POST /2/users/{id}/public_keys`.
>
> **2. Check chat eligibility before starting a new 1:1**
>
> Request `GET /2/users/{id}?user.fields=receives_your_chat` with the sending account's token:
>
> * `encrypted` — you can start an encrypted chat
> * `unencrypted` — the pair cannot be encrypted yet
> * `none` — you cannot message them
>
> **3. Unlock once and export (approved server-side custody)**
>
> Construct a server/native Chat XDK instance (`@xdevplatform/chat-xdk-server`, Python, Ruby, Go, .NET, JVM, or Rust — browser WASM cannot export keys) with `juicebox_config`, call `unlock(pin)` **once**, call `export_keys()`, store only the opaque blob in a KMS / HSM / Secrets Manager (one secret per account keyed by `user_id` + `public_key_version`, least-privilege IAM, audited reads), and **discard the PIN immediately**. Workers load the blob with `import_keys(blob, version)` and `set_identity(user_id, version)` — no PIN needed.
>
> **Never auto-retry a wrong PIN:** Juicebox enforces a small, hardware-enforced, **non-renewable** wrong-guess budget (`juicebox_config.max_guess_count`). Exhausting it deletes the backup and makes older encrypted messages unreadable. Fail closed after one wrong attempt. Unlocks also carry an independent edge rate limit (\~30 unlocks/min per egress IP) — unlock once and reuse the result.

> [tab] Architecture by app type
>
> | Integration type | Recommended pattern | Never |
> | :- | :- | :- |
> | **User-facing web app / agent console** | Run `@xdevplatform/chat-xdk` (WASM) in the browser. User enters PIN on-device; keys stay in memory for the session. | Send PIN or keys to your servers; store raw key blobs in `localStorage`. |
> | **Native mobile / desktop app** | Chat XDK on device with Juicebox secure key backup or an OS-keystore-backed blob. | Sync unencrypted key blobs to your cloud. |
> | **Dedicated bot account you fully own** | Generate and register keys once; store `export_keys` blob in a secret manager or HSM; load with `import_keys`. | Commit blobs to git, log them, or register per session. |
> | **B2B server-side automation on a brand account** | One-time PIN unlock + `export_keys()` into KMS/HSM/Secrets Manager; discard PIN. **Requires explicit customer agreement and X partner approval.** | Replace an existing brand account's keys without explicit customer approval, or store the PIN. |
> | **Ciphertext-only relay or archive** | Hold no private keys. Store and forward encrypted events (including conversation key-change events); decrypt only where keys legitimately live. | Decrypt on the server "for convenience." |
> | **Consumer (end-user) accounts** | On-device crypto only. | Collect consumer PINs or private keys on a server. |

> [tab] B2B approval requirements
>
> Storing customers' keys on your servers requires **approval from X**. All six criteria must be true:
>
> 1. Your customers are **businesses or organizations**, not individual consumers.
> 2. You run a **business messaging or automation tool** on their behalf.
> 3. Your customers **knowingly give you** their key material.
> 4. Each customer's keys are used **only for that customer's own** X Chat account.
> 5. You **disclose** to customers (in your product or contract) that keys are separate from sign-in access, and that revoking your app's OAuth access does **not** revoke keys they already shared.
> 6. Your **contract / DPA** with each customer covers how you store and protect keys, who can access them, breach notification, and deleting or returning keys when the relationship ends.
>
> To initiate the review, send your X account representative a Yes or No for each point above along with a short description of how your product uses X DMs.

> [tab] Key lifecycle events
>
> | Event | What happens | Required action |
> | :- | :- | :- |
> | **Account owner changes their PIN** | Exported key blob keeps working (it does not depend on the PIN). | No action needed. |
> | **Account owner runs Reset Chat** | A new `public_key_version` is minted; saved keys stop working. | Monitor `public_key_version` per tenant; on a mismatch, stop sending and ask an admin to re-onboard with a fresh one-time unlock. |
> | **Owner resets a forgotten PIN (or exhausts guess budget)** | Messages encrypted under the old keys become unreadable; `public_key_version` rotates. | Never auto-retry PINs; route the tenant to re-onboarding. |
> | **Customer revokes OAuth or offboards** | API tokens stop working, but previously shared keys remain cryptographically valid (no app-level key revocation exists). | Delete every copy and backup of their keys, and instruct the customer to revoke your app's access **and run Reset Chat** in the X app. |

***

## 5. Key workflows and caveats

> [tab] 1:1 key setup & sending
>
> **Conversation ID formats**
>
> | Form | Example | Where used |
> | :- | :- | :- |
> | Canonical 1:1 (`min:max`) | `1215441834412953600:1603419180975409153` | Inside events, Activity payloads, and media-upload JSON bodies. **Never valid in URL paths** — replace `:` with `-`. |
> | Hyphenated 1:1 (`A-B`) or bare user ID | `1215441834412953600-1603419180975409153` or `1603419180975409153` | Returned in listings and accepted in URL paths. Self-conversations (`A-A`) can appear in listings. |
> | Group ID (`g…`) | `g1851674867135033661` | Valid everywhere unchanged. |
>
> **Mandatory 1:1 conversation key setup (first contact only)**
>
> If your bot only replies to inbound messages, skip this step and reply encrypted with `chat-xdk`. To initiate a new 1:1 conversation with no key yet:
>
> **1. Fetch and verify both participants' keys**
>
> Fetch both public-key records and call `verify_key_binding` on each before encrypting.
>
> **2. Create and post the conversation key**
>
> Call `prepare_conversation_key_change` (rename the SDK's `encrypted_key` field to `encrypted_conversation_key` in `conversation_participant_keys`) and `POST /2/chat/conversations/{recipient_id}/keys`. Skip this step when a conversation already has a key — never rotate on every send.
>
> **3. Encrypt and send (reuse payload on retry)**
>
> Call `encrypt_message` and `POST /2/chat/conversations/{recipient_id}/messages`. Because the Chat XDK binds `message_id` into the signature, **resend the exact same encrypted payload on retry** — re-encrypting creates a duplicate message.
>
> > [!NOTE]
> >
> > **Move all services for a brand account together:** While any service still holds an active legacy DM connection for an account through an allowlisted app, new 1:1 chats stay unencrypted and key setup can fail with `403`. Stop all legacy DM calls and subscriptions for that account together when switching.

> [tab] Media upload & download
>
> In v1 encryption, the attachment key derives from the message — follow this exact sequence:
>
> **1. Initialize upload with encrypted byte length**
>
> Call `POST /2/chat/media/upload/initialize` with the canonical `conversation_id` and `total_bytes = encrypted_file_size(len(plaintext))` to get `session_id` and `media_hash_key`.
>
> **2. Build the encrypted message first**
>
> Call `encrypt_message` with an attachment referencing `media_hash_key`.
>
> **3. Encrypt and upload the file**
>
> Call `encrypt_file(plaintext, payload.event_b64, media_hash_key)`, upload chunks via `/append` (`segment_index` `0–999`), and call `/finalize` with `num_parts` as a numeric **string**.
>
> **4. Send the message**
>
> Post the message from Step 2 to `POST /2/chat/conversations/{id}/messages`.
>
> * **Downloads:** `GET /2/chat/media/{conversation_id}/{media_hash_key}` requires `media.write` and returns ciphertext — decrypt with `decrypt_file` and cache downloads (rate-limited per account). Legacy DM media IDs return `404`. See [Media](https://docs.x.com/xchat/media.md).

> [tab] History & message requests
>
> **Decrypting history and older unencrypted messages**
>
> * Always pass `meta.conversation_key_events` alongside `data[].encoded_event` into `decrypt_events`, inspect error buckets (`missing_signing_keys`, etc.), and fetch missing keys.
> * There is **no time limit** on reading history — page back with `pagination_token` until `has_more` is `false`.
> * **Legacy history caveats:** Older unencrypted messages remain readable alongside new encrypted messages without keys, but edits and deletions of older messages, attachments after the first on an older message, and already-expired disappearing messages do not carry over. Because older unencrypted messages lack `conversation_key_version`, `chat-xdk` rejects them by default — opt in deliberately with `set_reject_unverified(false)` and label them unverified in your product.
>
> **Message requests (non-followers)**
>
> * 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`.

> [tab] Rate limits, SDK & spec caveats
>
> | Topic | Detail |
> | :- | :- |
> | **Rate limits & headers** | Limits are set per access package, per user and per app, across 15-minute (`x-rate-limit-*`) and 24-hour (`x-user-limit-24hour-*`, `x-app-limit-24hour-*`) windows; `429` includes `retry-after`. Public-key registration has a low daily limit — never register per session. |
> | **Pagination** | `GET /2/chat/conversations` supports `max_results` up to 1,000, but use `25–100` to avoid `503` timeouts. Keep filters identical when passing `pagination_token` (changing filters returns `400`), keep paging while `has_more` is `true` even on short or empty pages, and stop if a `next_token` repeats. `GET …/events` defaults to `max_results=10` (max 100). |
> | **SDK & wire details** | Entity offsets use **UTF-8 byte offsets** (not UTF-16). `group_name` and `group_description` are ciphertext — decrypt with the conversation key. JavaScript returns camelCase enums (`"message"`), while Python and native bindings return PascalCase (`"Message"`, `"KeyChange"`). Allowlist outbound anonymous `GET https://api.x.com/2/chat/features` so the Chat XDK selects v1 encryption instead of falling back to v0. |
> | **`POST …/read` caveat** | Unsupported fields such as `seen_until_sequence_id` are silently ignored. Send an empty body to mark read up to newest, or pass `action_signatures` from `prepare_mark_conversation_read` to target a specific event. |
> | **`POST …/members` OpenAPI caveat** | The generated OpenAPI spec types this response as a Post, whereas the live response returns `{"data":{"current_member_ids":[...],"conversation_key_change_sequence_id":"..."}}`. Hand-parse this response in spec-generated clients. |
> | **Enterprise allowlist gotcha** | While an allowlisted app still holds a live DM token for an account, new 1:1s stay unencrypted and `POST …/keys` can return a misleading `403`. See [Enterprise legacy-DM allowlist cutover gotcha](https://docs.x.com/xchat/troubleshooting.md#enterprise-legacy-dm-allowlist-cutover-gotcha). |

***

## 6. Pre-cutover verification checklist

**Codebase & authentication**

* [ ] Zero remaining calls to `/2/dm_events`, `/2/dm_conversations`, v1.1 `direct_messages/*`, `media_category=dm_*`, Account Activity DM webhooks, or XAA `dm.*` subscriptions.
* [ ] User-context tokens on every `/2/chat/*` and `/2/users/*/public_keys` route; App-Only Bearer used **only** on `GET /2/activity/stream`.
* [ ] OAuth 2.0 apps request `tweet.read users.read dm.read dm.write media.write offline.access` and verify media download succeeds (`media.write`). OAuth 1.0a apps have **"Read, Write and Direct Messages"** and a plan to move to OAuth 2.0 before January 31, 2027.

**Key custody & security**

* [ ] Key architecture chosen per [Handling private keys](https://docs.x.com/xchat/handling-private-keys.md); X partner approval and customer contract/disclosures completed for any B2B server-side key custody.
* [ ] No code path silently registers new keys on an account that already has keys without explicit customer approval; brand account's official X app still works after onboarding.
* [ ] Zero PINs or private keys in databases, env vars, logs, or APM; Juicebox `unlock()` fails closed after one wrong attempt with no auto-retry; `public_key_version` rotation monitored; offboarding deletes all key copies and instructs Reset Chat.

**End-to-end & cutover**

* [ ] Tested: `:` → `-` URL conversion, new 1:1 conversation key setup, encrypted send & idempotent retry, `chat.received` / `chat.sent` / `chat.conversation.join` delivery & deduplication, encrypted media round-trip, message request accept, group create, and mark read.
* [ ] Spec caveats handled (`POST …/read` omits `seen_until_sequence_id`; `POST …/members` hand-parsed); permanent `403`s not retried in a loop; rate-limit headers and `retry-after` honored.
* [ ] Enterprise allowlisted apps: coordinated with your X account representative to remove the app from the legacy-DM allowlist after cutover.

***

## 7. Troubleshooting and FAQ

### Common migration errors

| HTTP / Error | Cause | Fix |
| :- | :- | :- |
| `400` `encryption-required` | Plaintext sent into a chat that can be encrypted (or a group). | Set up conversation keys if none exist (`POST /2/chat/conversations/{id}/keys`), then send encrypted with `chat-xdk`. |
| `400` `xchat-setup-required` | Sending account has no X Chat keys yet. | Complete key setup for the sending account before sending. |
| `400` `recipient-xchat-setup-required` | Recipient has no X Chat keys (no unencrypted fallback). | Check recipients first with `GET /2/users/public_keys?ids=...` (or `user.fields=receives_your_chat`) and retry only after they set up X Chat. |
| `400` `INVALID_IDENTITY_KEY_PAIR` | On `POST …/keys`, a participant's `public_key_version` changed. | Re-fetch `GET /2/users/{id}/public_keys`, rebuild with `prepare_conversation_key_change`, and retry once. |
| `400` `ContentsTooLarge` | Encrypted payload exceeds **20 KB** (\~11,000 plaintext bytes). | Split or truncate long messages before calling `encrypt_message`. |
| `400` `invalid-request` | Validation error, signature/key mismatch, missing public key on group create, or `pagination_token` reused with changed filters. | Fix request parameters; do not retry unchanged. |
| `401` Unauthorized | Missing, expired, or invalid user-context token. | Refresh the OAuth 2.0 access token and retry once. |
| `403` `unencrypted-send-not-allowed` | Plaintext message refused by X Chat. | Send all messages encrypted with `chat-xdk`. |
| `403` `unsupported-authentication` | App-Only Bearer token used on a chat or public-keys route. | Switch to an OAuth 2.0 (or OAuth 1.0a) user-context token. |
| `403` `missing-scopes` | OAuth 2.0 token missing required scopes (often `media.write` on media download). | Prompt the user to re-authorize with the full scope set. |
| `403` `oauth1-permissions` | OAuth 1.0a app lacks **"Read, Write and Direct Messages"**. | Update app permission and reissue user tokens (or migrate to OAuth 2.0). |
| `403` `message-request-not-supported` | Recipient does not follow you and has not accepted your messages. | Do not retry in a loop. |
| `403` `recipient-not-messageable` | Permanent refusal: recipient's settings, closed inbox, system account, or block. | Treat as permanent; stop retrying. |
| `403` on `POST …/keys` | Recipient cannot receive encrypted 1:1s (needs keys + follow/prior chat/accepted request), **or** either side still has an active legacy DM connection via an allowlisted app. | Treat as permanent for that pair — do **not** retry in a loop or register new keys. See [Testing before cutover](#testing-before-cutover). |
| `404` on chat media / conversation / accept | Attachment deleted or legacy DM media ID used; conversation missing or not a member; no pending message request. | Treat as permanent — do not retry. |
| `429` Too Many Requests | Rate limit hit (commonly from polling every conversation on `/events`, or re-registering public keys). | Wait for `retry-after` / `x-rate-limit-reset`. Use webhooks/stream + `?start_time=` on `/conversations` instead of polling every conversation. |
| `503` `chat-permissions-unavailable` (or timeout) | Temporary backend unavailability or large `/conversations` page timeout. | Retry with backoff, **reusing the exact same encrypted send payload**. Step down `max_results` on `/conversations`. |

For SDK-specific cryptography, backup recovery, and decryption issues, see [Fix common X Chat problems](https://docs.x.com/xchat/troubleshooting.md).

### Testing before cutover

> [tab] Encrypted path & allowlist
>
> To test the encrypted path before December 9, 2026, send your testing or staging **app ID** to your X account representative.
>
> The legacy DM allowlist is tracked **per app ID, not per project**. While an account has an active legacy DM connection through *any* allowlisted app (on **either** side of the chat), new 1:1 chats stay unencrypted and `POST /2/chat/conversations/{id}/keys` can fail with a `403` mentioning follows even when follows are not the issue.
>
> **1. Use clean test accounts on both sides**
>
> Test with X accounts on both sides that have never been connected to your production legacy DM integration.
>
> **2. Verify encryption eligibility first**
>
> Call `GET /2/users/{id}?user.fields=receives_your_chat` and confirm the pair returns `encrypted`.
>
> **3. Never loop on the 403 or re-register keys**
>
> If `POST …/keys` returns `403`, stop retrying and verify neither test account is connected to an allowlisted legacy DM app.

> [tab] Testing with OAuth 1.0a
>
> Test X Chat endpoints with OAuth 1.0a user tokens using the official **XDK** (`pip install xdk` / `npm install @xdevplatform/xdk`) or any OAuth 1.0a library (`requests_oauthlib` for Python, `oauth-1.0a` for Node), then pass the response to `chat-xdk`. Your app needs the **"Read, Write and Direct Messages"** permission.
>
> ```python XDK (Python) theme={null}
> from xdk import Client, OAuth1
>
> client = Client(
>     auth=OAuth1(
>         api_key=API_KEY,
>         api_secret=API_SECRET,
>         access_token=ACCESS_TOKEN,
>         access_token_secret=ACCESS_SECRET,
>     )
> )
> r = client.users.get_public_key(id="USER_ID")  # r.model_dump() gives a plain dict
> ```
>
> ```python requests_oauthlib (Python) theme={null}
> from requests_oauthlib import OAuth1Session
>
> s = OAuth1Session(API_KEY, API_SECRET, ACCESS_TOKEN, ACCESS_SECRET)
> r = s.get("https://api.x.com/2/users/USER_ID/public_keys")
> ```

### Partner FAQ

> [card] [Browse the Partner FAQ](https://docs.x.com/xchat/migrate-from-legacy-dms/faq.md)
>
> Searchable answers to the questions partners ask most: timeline, sign-in and permissions, keys and PINs, events and endpoints, and common errors.
