From 1357d1422cd3894d900efc6fa8fac07ea4fd93ee Mon Sep 17 00:00:00 2001 From: tcaldwell-x Date: Wed, 2 Dec 2026 16:33:06 -0800 Subject: [PATCH] Expand X Chat migration guide with troubleshooting, FAQ, and endpoint details --- xchat/migrate-from-legacy-dms.mdx | 486 ++++++++++++++++++++++++++++-- 1 file changed, 463 insertions(+), 23 deletions(-) diff --git a/xchat/migrate-from-legacy-dms.mdx b/xchat/migrate-from-legacy-dms.mdx index 9bd1ab538..7454752ba 100644 --- a/xchat/migrate-from-legacy-dms.mdx +++ b/xchat/migrate-from-legacy-dms.mdx @@ -1,12 +1,27 @@ --- 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"] +description: "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." +keywords: ["X Chat migration", "legacy DM migration", "Direct Messages to X Chat", "dm_events", "dm_conversations", "direct_messages", "E2EE migration", "X Chat troubleshooting", "X Chat 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](/xchat/xchat-xdk)**. + +**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 old unencrypted DM events, and the X Chat API (`/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. + + +**What is being retired:** + +- **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 + +The replacements are `/2/chat/*` and the X Activity `chat.received`, `chat.sent`, and `chat.conversation.join` events. + --- ## 1. What changes architecturally @@ -14,14 +29,29 @@ Moving from Legacy Direct Messages (`v1.1 direct_messages/*`, `v2 /2/dm_events`, | 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) | +| **Credentials** | OAuth token only | User-context OAuth token **plus** P-256 identity & signing private keys (backed up via 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 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 | +### 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](/xchat/xchat-xdk)**: + +| 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`. | +| **JavaScript / TypeScript (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+, JVM (JDK 17+)** | See [Chat XDK](/xchat/xchat-xdk) | Native bindings supporting `export_keys` / `import_keys`. Go ships prebuilt libraries for macOS and Linux `amd64` only (on Linux `ARM64`, use Python or `@xdevplatform/chat-xdk-server`). Java 8 is not supported. | + +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, you can use the official XDK (`pip install xdk` / `npm install @xdevplatform/xdk`) or any HTTP client. + -**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). +**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](/xchat/handling-private-keys). --- @@ -41,8 +71,10 @@ Every `/2/chat/*` and `/2/users/*/public_keys` route requires **user-context aut | **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` | +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). + -**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`. +**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` will need to re-authorize. **Recommended full scope set:** @@ -51,7 +83,14 @@ Every `/2/chat/*` and `/2/users/*/public_keys` route requires **user-context aut 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`. +### OAuth 1.0a compatibility and retirement + +- **OAuth 1.0a works during migration:** OAuth 1.0a user tokens work on X Chat endpoints, including `GET` / `POST /2/users/{id}/public_keys` and `POST /2/activity/subscriptions` for chat events. Welcome-message endpoints currently require OAuth 2.0 (OAuth 1.0a support is being added). +- **Required app permission:** Your OAuth 1.0a app must be configured with **"Read, Write and Direct Messages"** permissions, otherwise routes return `403 oauth1-permissions`. Tokens retain the permissions they were originally created with: if your app already has **"Read, Write and Direct Messages"**, existing tokens keep working; if you change the app permission, users must re-authorize. +- **`chat-xdk` is auth-agnostic:** The Chat XDK only encrypts, decrypts, and signs locally — it never sends your OAuth token to X. Your own HTTP client makes the API calls using 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](/fundamentals/authentication/oauth-2-0/oauth-1-0a-token-exchange) to move existing users over without asking them to reconnect: + - A **"Read, Write and Direct Messages"** token exchanges to `dm.read`, `dm.write`, and `media.write` (plus `offline.access`) with no consent screen. + - A **"Read and Write"** token gets `media.write` only, and a **"Read"** token gets neither — those users must re-authorize to use X Chat. --- @@ -70,7 +109,7 @@ If you still sign X Chat calls with OAuth 1.0a during migration, configure your | `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). | +| `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](/xchat/media). | ### Legacy v1.1 Direct Messages → X Chat @@ -82,29 +121,430 @@ If you still sign X Chat calls with OAuth 1.0a during migration, configure your | `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 | +| `direct_messages/welcome_messages/*` & surveys | X Chat versions exist in v2 (welcome-message endpoints currently require OAuth 2.0; OAuth 1.0a support is being added). 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`). | +| `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}` | + +### Real-time events: Account Activity API & X Activity API + +| 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 and delivery endpoints (AAA → XAA) + +Existing DM subscriptions and Account Activity webhooks do **not** carry X Chat events. Create new X Activity API subscriptions for each monitored account; you can point them at your existing `webhook_id` or consume the stream. + +| 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) | + + +- `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. +- Subscribe to **`chat.conversation.join`** so bots learn when they are added to a group and receive the group conversation key. +- While unencrypted conversations still exist during cutover, their messages arrive as `dm.received` — subscribe to both `dm.received` and `chat.received` and deduplicate until cutover completes. +- Chat events currently include user IDs only, not names or profiles. Look up profiles with `GET /2/users?ids=...` or `GET /2/chat/conversations?expansions=participant_ids&user.fields=...` and cache by user ID (profile hydration via `includes.users` is being added to chat events). + + +### New X Chat endpoints (no legacy equivalent) + +| 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` | + +### Features with no 1:1 equivalent + +Plan explicit product replacements for these legacy features: + +- **Global cross-conversation DM feed (`GET /2/dm_events`, v1.1 `events/list.json`):** Use X Activity `chat.received` / `chat.sent` for live ingestion, and reconcile 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`):** Store events keyed by sequence `id` / `message_id` and `conversation_id` as they arrive, or page the conversation's events. +- **Custom profiles (`custom_profiles/*`):** No equivalent. +- **Server-side plaintext processing without keys:** Keyword search, moderation, analytics, archiving, and LLM summarization only work where private keys are legitimately held (see [Key custody and B2B key storage](#4-key-custody-and-b2b-key-storage)). +- **Send-side CTAs:** No documented send-side CTA API (quick replies are supported in the Chat XDK message content model). +- **Messaging accounts without X Chat keys:** A recipient without X Chat keys cannot receive encrypted messages (and nothing falls back to unencrypted). + +--- + +## 4. Key custody and B2B key storage + +Key custody is the primary architectural decision for business platforms (social media management, customer care, archiving, auto-response). OAuth access and encryption keys are **separate control planes**: an OAuth token authorizes API calls, while private keys unlock and sign message contents. + +### Check for existing keys before registering + +1. Call `GET /2/users/{id}/public_keys` (or batch `GET /2/users/public_keys?ids=...` for up to 100 accounts). +2. **If key backup details are returned:** The account already uses X Chat. **Do not register new keys.** Recover the existing keys with the owner's PIN instead so the official X app keeps working. +3. **If no keys are 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), you can generate and register a new keypair via `POST /2/users/{id}/public_keys` once. +4. **Before starting a new 1:1 chat:** Request `GET /2/users/{id}?user.fields=receives_your_chat` with the sending account's token. Values are `encrypted` (you can start an encrypted chat), `unencrypted` (pair cannot be encrypted yet), or `none` (you cannot message them). + + +**Never register new keys (`POST /2/users/{id}/public_keys`) on an account that already uses X Chat in the official X app.** Each X account has one active identity key. Registering a new keypair replaces the account's identity, breaks X Chat in the X app, and cuts the account off from existing encrypted conversations. + + +### Choose your key architecture + +| Integration type | Recommended pattern | Never | +|:-----------------|:--------------------|:------| +| **User-facing web app / agent console** | Run `@xdevplatform/chat-xdk` (WASM) in the browser. The user enters their PIN on-device; keys stay in memory for the session. | Send the 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 the `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 business account** | One-time PIN unlock + `export_keys()` into your KMS/HSM/Secrets Manager; discard the PIN. **Requires explicit customer agreement and X partner approval.** | Register new keys on an existing brand account, 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. | + +### One-time unlock and export (approved server-side custody) + +- **Unlock once at onboarding, never store the PIN:** Construct the server/native Chat XDK with `juicebox_config` from `GET /2/users/{id}/public_keys`, call `unlock(pin)` **once**, call `export_keys()`, store only the opaque blob in a managed 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 call `import_keys(blob, version)` + `set_identity(user_id, version)` with no PIN. +- **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 and ask the account owner to verify their PIN in the X app. Unlocks also carry a separate edge rate limit (~30 unlocks/min per egress IP) — unlock once and reuse the result, never per message or request. +- **Key export availability:** `export_keys` / `import_keys` are available in the server and native editions (`@xdevplatform/chat-xdk-server`, Python, Go, .NET, JVM, Rust), not in the browser edition. + +### B2B key-storage approval requirements + +Storing customers' keys on your servers requires **approval from X**. All of the following 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 the keys, who can access them, breach notification, and deleting or returning the keys when the relationship ends. + +To start the review, send your X account representative a Yes/No for each point above along with a short description of how your product uses X DMs. + +### Key lifecycle events to handle + +| Event | What happens | Required action | +|:------|:-------------|:----------------| +| **Account owner changes their PIN** | Your 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; your saved keys stop working. | Monitor `public_key_version` per tenant; on a mismatch, stop sending from that account 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 keys already shared remain cryptographically valid (there is no app-level key revocation). | 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. | + +See [Handling private keys](/xchat/handling-private-keys) for full security rules and checklists. --- -## 4. Behavioral differences and caveats to plan for +## 5. 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. +- **Conversation ID formats:** Events and Activity payloads carry canonical colon-joined 1:1 IDs (`min:max`), which are **never valid in URL paths** (though preferred in media-upload JSON bodies). Replace `:` with `-` (or pass the bare recipient user ID) in every URL path. Group IDs (`g…`) work everywhere unchanged. Self-conversations (`A-A`) can appear in listings. +- **Mandatory 1:1 key handshake before the first message:** If a 1:1 conversation has no key yet, fetch both participants' public keys, verify each record with `verify_key_binding`, build the handshake with `prepare_conversation_key_change` (rename the SDK's `encrypted_key` field to `encrypted_conversation_key` in `conversation_participant_keys`), and call `POST /2/chat/conversations/{recipient_id}/keys` before sending. Skip key setup if a key already exists — do not rotate on every send. If your bot only replies to inbound messages, reply encrypted with `chat-xdk` (no key setup needed). +- **Encrypted media upload order (v1-safe):** The file key derives from the message, so follow this exact sequence: `POST /2/chat/media/upload/initialize` (`total_bytes = encrypted_file_size(len(plaintext))`) → build the message with `encrypt_message` referencing `media_hash_key` → `encrypt_file(plaintext, payload.event_b64, media_hash_key)` → `append` (`segment_index` `0–999`) → `finalize` (`num_parts` as a numeric **string**) → `POST …/messages`. Cache media downloads (rate-limited per account). Legacy DM media IDs return `404` on X Chat media routes. +- **Retries and idempotency:** The Chat XDK generates `message_id` and binds it into the signature. On retries (such as `503`), **resend the exact same encrypted payload** — re-encrypting creates a duplicate message. +- **Decrypting history and older unencrypted messages:** Always pass `meta.conversation_key_events` alongside `data[].encoded_event` into `decrypt_events`, inspect decryption error buckets (`missing_signing_keys`, etc.), and fetch missing keys. There is no time limit on reading history — page with `pagination_token` until `has_more` is `false`. A few legacy behaviors do not carry over for older messages: edits and deletions of older messages, attachments after the first on an older message, and already-expired disappearing messages. Older unencrypted messages lack `conversation_key_version` and are rejected by default; opt in deliberately with `set_reject_unverified(false)` and label them unverified in your product. - **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. +- **Rate limits and pagination:** Limits are set per access package, per user and per app, in 15-minute (`x-rate-limit-*`) and 24-hour (`x-user-limit-24hour-*`, `x-app-limit-24hour-*`) windows; `429` responses include `retry-after`. Public-key registration has a low daily limit — never register per session. On `GET /2/chat/conversations`, use `max_results` of `25–100` (large pages up to 1,000 can time out with `503`), keep query filters identical across `pagination_token` calls (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 /2/chat/conversations/{id}/events` defaults to `max_results=10` (up to 100). +- **SDK and wire details:** Entity offsets in current Chat XDK releases are **UTF-8 byte offsets** (not UTF-16). `group_name` and `group_description` in API responses are ciphertext — decrypt them with the conversation key. JavaScript returns camelCase enum values (`"message"`), while Python and native bindings return PascalCase (`"Message"`, `"KeyChange"`). Allow outbound anonymous `GET https://api.x.com/2/chat/features` so the Chat XDK selects the v1 encryption format instead of falling back to v0. +- **Known API and OpenAPI caveats:** `POST /2/chat/conversations/{id}/read` silently ignores unsupported fields such as `seen_until_sequence_id` (send an empty body to mark up to newest, or pass `action_signatures` from `prepare_mark_conversation_read`). On `POST /2/chat/conversations/{id}/members`, the generated OpenAPI schema types the response as a Post, whereas the live response is `{"data":{"current_member_ids":[...],"conversation_key_change_sequence_id":"..."}}` — hand-parse it if using spec-generated clients. +- **Move all services for a brand account together:** While any service still has an active legacy DM connection for an account through an allowlisted app, new 1:1 chats stay unencrypted and `POST /2/chat/conversations/{id}/keys` can return a misleading `403`. Stop legacy DM calls and subscriptions for that account together when you switch. See [Enterprise legacy-DM allowlist cutover gotcha](/xchat/troubleshooting#enterprise-legacy-dm-allowlist-cutover-gotcha). --- -## 5. Pre-cutover verification checklist +## 6. Pre-cutover verification checklist + +- [ ] **Zero legacy DM calls remaining:** Audit your codebase and remove all calls to `/2/dm_events`, `/2/dm_conversations`, v1.1 `direct_messages/*`, `media_category=dm_*`, Account Activity DM webhooks, and XAA `dm.*` subscriptions. +- [ ] **Auth and scopes verified:** User-context tokens used 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 (proves `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 and security audit complete:** Key architecture chosen per [Handling private keys](/xchat/handling-private-keys) (X partner approval and customer contract/disclosures completed for B2B server-side custody); no code path registers new keys on an account that already has keys; the brand'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. +- [ ] **Core round-trips tested:** Conversation ID `:` → `-` conversion covered; new 1:1 key handshake → encrypted send (retry reuses identical payload and produces one message) → `chat.received` / `chat.sent` / `chat.conversation.join` delivery, deduplication, and decrypt → encrypted media upload/download round-trip → message request list/open/accept → group create → mark read. +- [ ] **Spec caveats and error handling verified:** `POST …/read` does not send `seen_until_sequence_id`; `POST …/members` hand-parsed; permanent `403`s (`recipient-not-messageable`, `message-request-not-supported`, key-init `403`) are not retried in a loop; rate-limit headers and `retry-after` respected. +- [ ] **Allowlist cutover (Enterprise):** After cutover, coordinate with your X account representative to remove your app from the enterprise legacy-DM allowlist so new 1:1s encrypt cleanly. + +--- + +## 7. Troubleshooting and FAQ + +### Common migration errors + +| HTTP / Error | Cause | Fix | +|:-------------|:------|:----| +| `400` `encryption-required` | You attempted to send plaintext into a chat that can be encrypted (or is 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` | The sending account has no X Chat keys yet. | Complete key setup for the sending account before sending. | +| `400` `recipient-xchat-setup-required` | The recipient has no X Chat keys. Nothing is sent unencrypted as a 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 key setup (`POST …/keys`), a participant's `public_key_version` changed. | Re-fetch public keys (`GET /2/users/{id}/public_keys`), rebuild with `prepare_conversation_key_change`, and retry once. | +| `400` `ContentsTooLarge` | Encrypted message payloads are capped at **20 KB** (about 11,000 bytes of plaintext). | 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 after changing filters. | Fix the 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 `/2/chat/*` or `/2/users/*/public_keys` route. | Switch to an OAuth 2.0 (or OAuth 1.0a) user-context token. | +| `403` `missing-scopes` | OAuth 2.0 token lacks one or more required scopes (commonly `media.write` on media download). | Prompt the user to re-authorize with the full scope set. | +| `403` `oauth1-permissions` | OAuth 1.0a app lacks the **"Read, Write and Direct Messages"** permission. | Update app permissions 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, so you cannot start a chat with them. | Do not retry in a loop. | +| `403` `recipient-not-messageable` | Permanent refusal: recipient's privacy settings, closed inbox, system account, or a block prevent messaging. | Treat as permanent; stop retrying. | +| `403` on `POST /2/chat/conversations/{id}/keys` | Recipient cannot receive encrypted 1:1 chats from you (must have X Chat keys and follow you / prior chat / accepted request), **or** either account still has an active legacy DM connection through 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 ID is a legacy DM media ID; conversation missing or you are 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 the `retry-after` header (or `x-rate-limit-reset`). Use X Activity webhooks/stream plus `?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](/xchat/troubleshooting). + +### Testing before cutover + +#### Testing the encrypted path before December 9, 2026 + +Send your testing or staging **app ID** to your X account representative to enable the encrypted path before cutover. + +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: + +- New 1:1 chats involving that account stay unencrypted (this applies if **either** side of the chat is connected). +- Key setup (`POST /2/chat/conversations/{id}/keys`) can fail with a `403` that mentions follows even when follows are not the issue. + +To test cleanly before cutover: + +1. Use X accounts on **both sides** that have never been connected to your production legacy DM integration. +2. Check the pair first with `GET /2/users/{id}?user.fields=receives_your_chat` to confirm the value is `encrypted`. +3. Do not retry that `403` in a loop and do not register new keys to work around it. + +#### Testing with OAuth 1.0a instead of PKCE + +You can test X Chat endpoints with OAuth 1.0a user tokens using the official **XDK** (`pip install xdk` for Python, `npm install @xdevplatform/xdk` for TypeScript) 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 +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 + +# Or with requests_oauthlib: +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") +``` + +--- + +### FAQ for API partners + +#### What's changing and when + + + + X is replacing legacy Direct Messages with X Chat. Legacy DMs were unencrypted; X Chat messages are end-to-end encrypted so that only participants in the conversation can read them. Apps using legacy DM endpoints need to move to the X Chat API (`/2/chat/*`). + + + + **December 9, 2026** is the last day to move. After that, the X Chat API is the only API for Direct Messages. X will confirm the exact switch-over time ahead of the date. + + + + After December 9, X stops accepting new unencrypted DMs — every new DM must be sent encrypted through X Chat. Legacy webhooks also stop sending unencrypted DM events, and new messages arrive as encrypted X Chat events instead. + + The following are retired: + - v1.1 `direct_messages/*` (events, typing indicator, mark read, welcome messages, DM media) and `custom_profiles/*` + - v2 `/2/dm_events` and `/2/dm_conversations/*` (including DM media) + - DM media upload with `media_category=dm_*` + - Account Activity DM events (`direct_message_events`, typing, read) + - X Activity `dm.*` events + + The replacements are `/2/chat/*` and X Activity `chat.received`, `chat.sent`, and `chat.conversation.join` events. Your message history is not lost. + + + + No. Existing conversations are upgraded on X's side, so there is nothing for you to move or archive. Older unencrypted messages stay in their conversations and remain readable through the X Chat API alongside new encrypted messages. `chat-xdk` handles both kinds, and older unencrypted messages do not require keys. + + There is no time limit on how far back you can read — page back through each conversation's events with `pagination_token` until `has_more` is `false`. A few legacy details do not carry over: edits and deletions of older messages, attachments after the first on an older message, and disappearing messages that already expired. Because `chat-xdk` rejects older unencrypted (unverified) messages by default, opt in with `set_reject_unverified(false)` and label them as unverified in your product. + + + + For most customers this is a small change. At most, a customer may need to enter their X Chat PIN once. Accounts that have never set up X Chat do not need an existing PIN, because you can create encryption keys for them through the API (only do this for accounts with no X Chat keys; storing customer keys on your servers requires X's approval). + + + + Use the X Chat docs starting at [docs.x.com/xchat/introduction](/xchat/introduction). They are kept current — do not rely on older PDF guides. + + + +#### Sign-in and permissions + + + + No. OAuth 1.0a user tokens work with the X Chat endpoints, including the endpoints that look up and register a user's public keys. Welcome-message endpoints currently require OAuth 2.0 (OAuth 1.0a support is being added). App-Only Bearer tokens do not work on X Chat endpoints, so use user-context tokens. + + OAuth 1.0a itself retires on **January 31, 2027**, so plan your move to OAuth 2.0 before then. The [OAuth 1.0a to OAuth 2.0 token exchange](/fundamentals/authentication/oauth-2-0/oauth-1-0a-token-exchange) moves existing users with DM permission over without asking them to reconnect. + + + + - **OAuth 1.0a:** Your app needs the **"Read, Write and Direct Messages"** permission (the legacy DM endpoints already required it). + - **OAuth 2.0:** The token needs `dm.read` and `dm.write`, plus `tweet.read` and `users.read`. Add `media.write` to download or upload chat media, and `offline.access` for refresh tokens. There are no separate X Chat scopes. If you only read and archive messages, `dm.write` is not needed. + + + + Yes. A token keeps the permission it was created with. If you change the app's permission, customers must authorize your app again to get new tokens. If your app already has **"Read, Write and Direct Messages"**, you do not need to change anything and existing tokens keep working. + + The same applies when you exchange OAuth 1.0a tokens for OAuth 2.0: scopes come from the permission the token was originally authorized with. A **"Read, Write and Direct Messages"** token exchanges to `dm.read`, `dm.write`, and `media.write` (plus `offline.access`) with no consent screen. A **"Read and Write"** token gets `media.write` only, and a **"Read"** token gets neither, so those users must re-authorize to use X Chat. + + + + No. `chat-xdk` encrypts, decrypts, and signs messages locally and never calls the X API with your token. Your own code makes the HTTP calls, so you can sign them with OAuth 1.0a or OAuth 2.0. + + + + No. The move to X Chat only affects DM access. To read or send X Chat for a user, the token needs DM access; if the tokens you obtain at sign-in already have it, nothing changes — otherwise users go through consent once. X Chat also needs the account's encryption keys, which are separate from sign-in. + + + +#### Keys, PINs, and key storage + + + + Each X Chat account has a set of private encryption keys that unlock and sign the account's messages. Anyone who holds them can read that account's messages and send as that account, so treat them like a master password. The PIN is a short code the account owner sets in the X app to recover those keys from X's secure key backup. + + + + Yes, with approved server-side key storage. Your backend can hold the account's encryption keys, decrypt messages as they come in, and display them to the customer's staff in your web app — staff never need the PIN. + + The PIN is used only once, when the admin connects the company's X account. Unlock and export the keys once, save them securely in your KMS/secret manager, and never save the PIN. If the admin later changes their PIN in the X app, the saved keys keep working. They stop working only if the account owner runs **Reset Chat** in the X app or resets a forgotten PIN — watch for a change in `public_key_version`, and if it changes, stop sending from that account and ask the admin to reconnect. Key export works in the server and native editions of `chat-xdk`, not in the browser edition. + + + + It depends on whether the account already uses X Chat: + - **Never set up X Chat (`GET /2/users/{id}/public_keys` returns no keys):** You can create a new keypair for the account through the API and save it. Have the admin choose the account's PIN in your connect flow rather than picking one for them, so the business can still use X Chat in the X app later. + - **Already uses X Chat, but the admin doesn't know the PIN:** Do **not** create new keys — a new keypair replaces the account's identity and breaks X Chat in the X app. The admin must find the PIN or reset it in the X app (resetting makes messages encrypted under the old keys unreadable). + + Older unencrypted DMs do not need keys at all. + + + + Call `GET /2/users/{id}/public_keys` (or batch `GET /2/users/public_keys?ids=...`). If key backup details are returned, the account already uses X Chat — recover the existing keys with the PIN instead of creating new ones. + + To check whether you can start an encrypted chat with someone, request the `receives_your_chat` user field with the sending account's token (`GET /2/users/{id}?user.fields=receives_your_chat`): `encrypted` means you can, `unencrypted` means the pair cannot be encrypted yet, and `none` means you cannot message them. + + + + Yes. Secure key backup allows only a small number of wrong guesses, and that budget cannot be reset. If it runs out, the backup is deleted and older encrypted messages become unreadable. Ask the account owner to confirm their PIN in the X app first, and stop after one wrong attempt. + + Unlock once per account and reuse the result — do not unlock per message or per request. Unlocks have a separate rate limit (about 30 per minute per IP address), independent of X API rate limits. + + + + Yes. Storing customers' keys on your servers requires approval from X. All of the following must be true: + - Your customers are businesses or organizations, not individual consumers. + - You run a business messaging or automation tool on their behalf. + - Your customers knowingly give you their key material. + - Each customer's keys are used only for that customer's own X Chat account. + - You tell customers, in your product or contract, that keys are separate from sign-in access and that revoking your app's access does not revoke keys they already shared. + - Your contract with each customer covers how you store and protect keys, who can access them, breach notice, 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. + + + + No. Revoking access only stops your app's API tokens; keys a customer already shared keep working. When a customer leaves, delete every copy and backup of their keys and instruct them to revoke your app's access and run **Reset Chat** in the X app. Reset Chat is the only way to invalidate previously shared keys — there is no app-level key revocation today. + + + + Yes, as long as you still have the keys needed to decrypt them and the account has not run Reset Chat or reset a forgotten PIN in the meantime. You can fetch history later while the account is still in the conversation. If you cannot stay subscribed, store the encrypted events (including the conversation key-change events on each page) and decrypt them later. + + + + The browser edition of `chat-xdk` cannot export keys. Export works in the server and native editions: Node (`@xdevplatform/chat-xdk-server`), Python, Go, .NET, JVM, and Rust. If the PIN must not touch your servers, the business can run a small local tool that unlocks and exports the keys on its own machine and uploads only the exported keys. Without approved key storage, decryption works only in the account owner's own session, so background or scheduled processing is not possible. There is no way to export keys without the PIN. + + + + Yes, as long as the account keeps the same X Chat keys. Store the encrypted events now, including the conversation key-change events on each page, and decrypt them once the customer provides key access. If the owner runs Reset Chat or resets a forgotten PIN before then, messages encrypted under the old keys cannot be decrypted. Capturing alone does not let you reply; replies must be sent encrypted. + + + +#### Webhooks, events, endpoints, rate limits, and SDKs + + + + Subscribe to `chat.received` for inbound messages, `chat.sent` for outbound messages, and `chat.conversation.join` for when an account joins a conversation (plus group membership/admin/settings events as needed). Message text arrives encrypted and is decrypted with `chat-xdk`. + + Existing DM subscriptions and Account Activity webhooks do not carry chat events, so create new subscriptions via `POST /2/activity/subscriptions` for each account (you can point them at your existing `webhook_id`). While unencrypted conversations still exist, their messages arrive as `dm.received`, so subscribe to both during cutover and deduplicate. + + + + Yes. `POST /2/activity/subscriptions` accepts OAuth 1.0a user tokens for chat events if the app has the **"Read, Write and Direct Messages"** permission. With OAuth 2.0, the token needs the `dm.read` scope. + + + + Chat events currently include user IDs only, not names or profiles — each event has the sender's user ID and the conversation ID. Look up profile details with `GET /2/users?ids=...`, or use `GET /2/chat/conversations` / `GET /2/chat/conversations/{id}` with `expansions=participant_ids` and `user.fields`, and cache profiles by user ID. Profile details for the sender and subscribed user are being added to chat events in an `includes.users` block, matching other X Activity API events. + + + + If you only reply to messages people send you, send your replies encrypted with `chat-xdk` — nothing else is required. To start a new 1:1 conversation yourself, set up the conversation key first with `POST /2/chat/conversations/{recipient_id}/keys`, then send. + + + + Yes — see [Endpoint mapping](#3-endpoint-mapping) above. + + + + No, X Chat has none of these. Use `chat.received` and `chat.sent` as your live feed. To catch up, list conversations changed since your last sync (`GET /2/chat/conversations?start_time=...`) and read events only for those conversations — polling every conversation on a timer exhausts per-user event limits quickly. To look up a single event later, persist events as they arrive. + + + + X Chat has its own encrypted media upload and download endpoints (see [Media](/xchat/media)). Chat media downloads are encrypted and must be decrypted with `chat-xdk`; with OAuth 2.0, downloads require the `media.write` scope. Legacy DM media IDs do not work on X Chat media endpoints and return `404`. + + Welcome messages and surveys also have X Chat versions in the API. Welcome-message endpoints currently require OAuth 2.0 (OAuth 1.0a support is being added). + + + + Limits are set per access package, per user and per app, in 15-minute and 24-hour windows. `GET /2/chat/message_requests` is limited to 75 requests per 15 minutes, and registering public keys has a low daily limit. Responses include `x-rate-limit-*` headers, and `429` responses include `retry-after`. Contact your X account representative for your package's specific numbers. + + + + Python, JavaScript/TypeScript (browser, plus `@xdevplatform/chat-xdk-server` for Node), Go, Rust, .NET 8+, and JVM (JDK 17 or later; Java 8 is not supported). There is no Ruby or PHP binding — run encryption in a small service in a supported language and call it from your app. Go ships prebuilt libraries for macOS and Linux `amd64` only; on Linux `ARM64`, use the Python or Node server package. Do not write your own encryption. + + + +#### Troubleshooting common issues + + + + No. Send all messages encrypted with `chat-xdk`. Plaintext messages are refused with HTTP `403 unencrypted-send-not-allowed`. HTTP `400 encryption-required` means the chat can be encrypted: set up conversation keys if none exist, then send encrypted. + + + + HTTP `400 xchat-setup-required` means the sending account has no X Chat keys yet. HTTP `400 recipient-xchat-setup-required` means the recipient has no X Chat keys, so nothing can be sent to them (and nothing is sent unencrypted instead). Check recipients first with `GET /2/users/public_keys?ids=...` and try again after they set up X Chat. + + + + You can start an encrypted 1:1 only when both accounts have X Chat keys **and** the recipient follows you, you have messaged each other before, or they accepted a message request from you. Being verified, or the recipient allowing messages from everyone, does not change this. + + The same `403` also appears while either account still has an active legacy DM connection through an app on the legacy DM allowlist (see [Testing before cutover](#testing-before-cutover)). Treat this `403` as permanent for that pair and do not retry it in a loop. + + + + HTTP `403 message-request-not-supported` means the recipient does not follow you and has not accepted your messages, so you cannot start a chat with them. HTTP `403 recipient-not-messageable` is permanent: their settings or a block prevent messaging. HTTP `503 chat-permissions-unavailable` is temporary, so retry with backoff. + + Message requests you receive are listed at `GET /2/chat/message_requests`. Replying does not accept a request — call `POST /2/chat/message_requests/{id}/accept`. + + + + Move them together. While any of your services still uses legacy DMs for an account, new 1:1 chats for that account stay unencrypted and key setup can fail with `403`. Stop all legacy DM calls and subscriptions for that account when you switch. + + + + Once a conversation is encrypted, its new messages are only available through the X Chat API and `chat.*` events. Legacy DM endpoints and webhooks only carry unencrypted messages. + -- [ ] **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. + + - `400 INVALID_IDENTITY_KEY_PAIR` on key setup: A participant's key version changed. Fetch their public keys again, rebuild, and retry once. + - `400 ContentsTooLarge` on send: Encrypted messages are capped at 20 KB (about 11,000 bytes of text), so split long messages. + - `404` on chat media: The attachment is gone or the ID is a legacy DM media ID — do not retry. + - `429` on conversation events: You are polling every conversation. Use webhooks/stream and read only the conversations that changed. + - `429` responses include `retry-after`: Wait that long before retrying. + +