Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs.json
Original file line number Diff line number Diff line change
Expand Up @@ -1320,7 +1320,8 @@
"xchat/introduction",
"xchat/cryptography-primer",
"xchat/getting-started",
"xchat/xchat-xdk"
"xchat/xchat-xdk",
"xchat/migrate-from-legacy-dms"
]
},
{
Expand Down
4 changes: 4 additions & 0 deletions xchat/getting-started.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,10 @@ Server and bot samples often use a **key blob** (`export_keys` / `import_keys`).

## 3. Create and register keys (first-time setup)

<Warning>
**Only run first-time setup on accounts that do not already have X Chat keys.** Calling `generate_keypairs` + `POST /2/users/{id}/public_keys` on an account that already uses X Chat in the official X app replaces its cryptographic identity and breaks X Chat on the official app. Check `GET /2/users/{id}/public_keys` first — if keys already exist, load them in [step 2](#2-initialize-the-chat-xdk-with-existing-keys) instead.
</Warning>

Skip this step if you loaded existing keys in [step 2](#2-initialize-the-chat-xdk-with-existing-keys). Otherwise, one-time setup for a new identity does **three things**:

1. **Create the keypairs**: `generate_keypairs` produces the identity and signing keypairs.
Expand Down
27 changes: 27 additions & 0 deletions xchat/handling-private-keys.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,33 @@ Client apps should prefer **secure key backup**. Servers and bots often use an e
- **Do not** ship end-user private keys to “make the backend simpler.”
- **Do not** confuse **OAuth revoke** with **key revoke**. Disconnecting an app does not erase keys a user already exported or typed into a hostile client.
- **Do not** store raw `export_keys` output in `localStorage` or unencrypted IndexedDB for production UI apps.
- **Do not** register a fresh server keypair (`POST /2/users/{id}/public_keys`) for an account that already uses X Chat on the official X app — it replaces the account's identity and breaks X Chat on the official app.
- **Do not** call `unlock(passcode)` per message or per request from server infrastructure. Backup realms enforce an IP-based rate limit (~30 `unlock()` calls per minute per egress IP) that is separate from `api.x.com` limits. Unlock once and reuse the `Chat` instance in memory, or persist `export_keys()` in a secret manager/HSM and load with `import_keys()` on native bindings.
- **Do not** auto-retry a failed `unlock(passcode)` call. Secure key backup enforces a small, hardware-enforced, **non-renewable** wrong-PIN budget (`juicebox_config.max_guess_count`). Exhausting it deletes the key share and makes older encrypted messages unreadable. Fail closed after one wrong PIN and prompt the account owner.

<Warning>
**No forward secrecy:** Conversation keys are wrapped to long-lived P-256 identity keys. If an account's identity private key is compromised, the holder can decrypt **past and future** conversation keys wrapped to that identity (rotating a conversation key protects only future messages). Disclose this to customers and treat leaked key material as a historical exposure.
</Warning>

---

## B2B / multi-tenant key custody

Do **not** collect encryption PINs or private keys from consumer end users. For **business-to-business platforms** (customer care, social media management, archiving, automation) that must operate messaging on behalf of business accounts also used in the official X app, server-side key custody is supported **only with explicit X partner approval** (contact your X account representative) and all of the following:

- **Business customers only:** Customers are businesses/organizations, not consumers; keys are used strictly for that business's own X Chat identity and conversations.
- **Knowing consent & disclosure:** The business knowingly provides key material (one-time PIN unlock to export the key blob, then immediately discard the PIN) and is explicitly told that encryption keys are separate from OAuth — revoking OAuth does **not** revoke previously shared keys.
- **Contract / DPA coverage:** Covers key custody, KMS/HSM encryption at rest, least-privilege access, audited reads, breach notification, and deletion/return on termination.
- **One secret per tenant:** Store one key blob per account (`user_id` + `public_key_version`) in a managed KMS/HSM/Secrets Manager with isolated decrypt workers; never pool tenant keys or store the PIN.

### Key lifecycle events to handle

| Event | What happens | Required action |
|:------|:-------------|:----------------|
| **Owner changes their PIN** | Exported `export_keys()` blob keeps working (it does not depend on the PIN) | No action needed |
| **Owner runs Reset Chat** | A new `public_key_version` is minted; the old blob no longer matches | Detect `public_key_version` mismatch, mark the tenant as needing re-onboarding, stop sending, and request a fresh one-time unlock + export |
| **Owner resets a forgotten PIN or exhausts guess limit** | Messages encrypted under the previous keys become unreadable | Never auto-retry PINs; route to re-onboarding |
| **Customer revokes OAuth or offboards** | API tokens stop working, but previously exported keys remain cryptographically valid | Delete all copies/backups of the key blob and instruct the business to revoke app access **and run Reset Chat** in the X app |

---

Expand Down
13 changes: 7 additions & 6 deletions xchat/introduction.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,15 @@ Grouped under **API reference** in the sidebar, including:

## Auth notes

Use **OAuth 2.0 user context** with DM-related scopes (`dm.read`, `dm.write`, plus `users.read` / `tweet.read` as required; `media.write` for uploads). X Chat activity for a user requires that user's authorization. Secure key backup configuration is returned on **your** public-key record (`juicebox_config` field); see Getting Started.
Use **OAuth 2.0 user context** with DM-related scopes (`dm.read`, `dm.write`, `users.read`, `tweet.read`, **`media.write` for both media uploads and downloads**, and `offline.access` for refresh tokens). X Chat activity for a user requires that user's authorization. Secure key backup configuration is returned on **your** public-key record (`juicebox_config` field); see [Getting Started](/xchat/getting-started) and the full scope matrix in [Migrate from Legacy DMs](/xchat/migrate-from-legacy-dms#2-authentication-and-oauth-20-scope-matrix).

---

## Next steps

1. [Cryptography primer](/xchat/cryptography-primer): optional background on encryption concepts
2. [Getting Started](/xchat/getting-started): implement keys, send, and receive
3. [Chat XDK](/xchat/xchat-xdk): encryption SDK reference
4. [Building UI apps with WASM](/xchat/building-ui-apps-with-wasm) and [Handling private keys](/xchat/handling-private-keys): keep keys on-device and treat PINs as root credentials
5. [Real-time events](/xchat/real-time-events), [Media](/xchat/media), or [Troubleshooting](/xchat/troubleshooting) when you need those topics
1. [Migrate from Legacy DMs](/xchat/migrate-from-legacy-dms): endpoint mapping, scopes, key custody, and cutover checklist for existing DM apps
2. [Cryptography primer](/xchat/cryptography-primer): optional background on encryption concepts
3. [Getting Started](/xchat/getting-started): implement keys, send, and receive
4. [Chat XDK](/xchat/xchat-xdk): encryption SDK reference
5. [Building UI apps with WASM](/xchat/building-ui-apps-with-wasm) and [Handling private keys](/xchat/handling-private-keys): keep keys on-device and treat PINs as root credentials
6. [Real-time events](/xchat/real-time-events), [Media](/xchat/media), or [Troubleshooting](/xchat/troubleshooting) when you need those topics
35 changes: 27 additions & 8 deletions xchat/media.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,39 @@ description: "Share images and file attachments in your encrypted chats: encrypt
keywords: ["X Chat media", "encrypted images", "file attachments", "encrypt_stream", "media upload", "media download"]
---

Images and other files use the **same conversation key** as text. Encrypt bytes with the Chat XDK (`encrypt_stream` / `decrypt_stream`), upload via the **`/2/chat/media/upload`** routes (sidebar **API reference → Media**), then attach **`media_hash_key`** on `encrypt_message`.
Images and other files are encrypted client-side with the Chat XDK (`encrypt_file` / `decrypt_file`), uploaded via the **`/2/chat/media/upload`** routes (sidebar **API reference → Media**), and referenced by **`media_hash_key`** inside `encrypt_message`.

Include **`media.write`** with your DM scopes when uploading. Use hyphenated conversation ids in paths (`:` → `-`). Prefer MIME/dimensions from **decrypted** bytes.
<Warning>
**`media.write` is required for both uploads and downloads.** All four `/2/chat/media/*` routes — including `GET /2/chat/media/{conversation_id}/{media_hash_key}` — require the `media.write` OAuth 2.0 scope, not `dm.read`.
</Warning>

Use hyphenated conversation IDs in URL paths (`:` → `-`) and canonical colon IDs (`min:max` or `g…`) in upload JSON bodies. Prefer MIME and dimensions from **decrypted** bytes. Maximum encrypted file size is **100 MB**.

This path is **not** the Posts media model (`expansions=attachments.media_keys`, `media.fields=variants`, etc.). Those parameters apply to **Posts**; encrypted X Chat blobs are addressed by **`media_hash_key`** and X Chat media download.

### Exact upload order (v1 format)

In the current (v1) encrypted message format, each attachment's encryption key is derived from the message itself, so **build the message before encrypting the file** and start a fresh upload per attachment per message (never reuse a `media_hash_key` across two messages):

1. **Initialize upload:** `POST /2/chat/media/upload/initialize` with `conversation_id` and `total_bytes = encrypted_file_size(len(plaintext))` → returns **`session_id`** and **`media_hash_key`**.
2. **Build the message:** Call `encrypt_message` (or `encrypt_reply`) referencing `media_hash_key` in `attachments` → returns `payload` (including `event_b64` and `message_id`).
3. **Encrypt and upload the file:** Encrypt the file with **`encrypt_file`** (or incremental **`file_encryptor`**) passing `payload.event_b64` and `media_hash_key`. Upload chunks via `POST /2/chat/media/upload/{session_id}/append` (`segment_index` **0–999**, e.g. 3 MiB chunks), then `POST /2/chat/media/upload/{session_id}/finalize` (`num_parts` as a **numeric string**).
4. **Send the message:** `POST /2/chat/conversations/{id}/messages` with `payload`.

```mermaid
flowchart LR
A[Plain bytes] --> B[encrypt_stream]
B --> C[Upload 3 steps]
C --> D[media_hash_key]
D --> E[encrypt_message + send]
F[GET media] --> G[decrypt_stream]
A[POST initialize] --> B[session_id + media_hash_key]
B --> C[encrypt_message -> event_b64]
C --> D[encrypt_file + append/finalize]
D --> E[POST messages]
F[GET media] --> G[decrypt_file]
G --> H[Plain bytes]
```

<Note>
**Legacy v0 / standalone files:** `encrypt_stream` / `decrypt_stream` (and `encrypt_file_with_key` / `decrypt_file_with_key`) encrypt directly under a raw 32-byte key rather than deriving a per-message file key (used for group avatars and v0 messages). For message attachments, use **`encrypt_file`** and **`decrypt_file`**, which handle both v0 and v1 messages seamlessly.
</Note>

---

## Encrypt
Expand Down Expand Up @@ -116,7 +133,9 @@ flowchart LR
| Append | `POST` | `/2/chat/media/upload/{id}/append` |
| Finalize | `POST` | `/2/chat/media/upload/{id}/finalize` |

Use the request bodies on the OpenAPI pages under **API reference → Media**. Prefer **encrypted** blob size where size is required. Finalize yields **`media_hash_key`** for attachments and download. Retry transient `5xx` with backoff. Python/TypeScript may use the XDK when media helpers exist; otherwise POST with a Bearer token in any language.
Use the request bodies on the OpenAPI pages under **API reference → Media**. Pass **`total_bytes = encrypted_file_size(len(plaintext))`** to `initialize`, which returns `session_id` and **`media_hash_key`**. Build your encrypted message with that `media_hash_key` first, then encrypt the file via `encrypt_file` / `file_encryptor`, upload chunks with `append` (`segment_index` **0–999**), call `finalize` (`num_parts` as a **numeric string**), and finally POST the message. Retry transient `5xx` with backoff.

On download (`GET /2/chat/media/{conversation_id}/{media_hash_key}`), use **`decrypt_file`** (passing the message's `event_b64`, `media_hash_key`, and your conversation keys) so both v0 and v1 encrypted attachments decrypt automatically, and cache downloaded media since downloads are rate-limited per account.

---

Expand Down
Loading
Loading