Skip to content

feat(dm): add encrypted XChat conversation support - #856

Merged
Rishikant181 merged 26 commits into
Rishikant181:devfrom
vachmara:feat/encrypted-dms
Sep 18, 2026
Merged

Rishikant181 merged 26 commits into
Rishikant181:devfrom
vachmara:feat/encrypted-dms

Conversation

@vachmara

@vachmara vachmara commented Apr 2, 2026 •

Copy link
Copy Markdown
Contributor

Related issue

Closes #836

Type of change

  • Enhancement
  • New feature

Summary

  • Fetches XChat conversation pages through the current GraphQL endpoint.
  • Decodes plaintext TLV message events and media URLs.
  • Preserves encrypted events as message shells when they cannot be decrypted.
  • Supports caller-supplied 32-byte conversation keys.
  • Integrates X's official MIT-licensed @xdevplatform/chat-xdk for PIN-backed private-key recovery.
  • Recovers versioned conversation keys from key-change events and caches them in memory.
  • Maps verified decrypted one-to-one and group messages into DirectMessage models.

Security

  • Rettiwt never retains the user's XChat PIN.
  • PIN recovery is delegated to the official X Chat SDK and Juicebox.
  • Private and cached key material can be cleared with XChatSession.lock() or XChatSession.free().
  • Signature verification remains enabled by default.

Verification

  • npx tsc --noEmit
  • npm run format:check
  • npm run lint:check
  • Offline official SDK/WASM initialization smoke check
  • GitHub CI on Node.js 22 and 24

@Rishikant181

Copy link
Copy Markdown
Owner

@vachmara Is there any blocker on this?

If there isn't, I can test it out and get this merged.

@vachmara

Copy link
Copy Markdown
Contributor Author

Hey @Rishikant181, during my initial tests against the GraphQL endpoint, I ran into authentication issues (422 GRAPHQL_VALIDATION_FAILED).

Also, there’s still a major gap I haven’t had time to fully investigate: it should works fine for non-encrypted messages, but I haven’t managed to crack the encrypted payload yet.

@vachmara

vachmara commented Apr 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Current PR scope:

  • Fixed conversation pagination args for GetConversationPageQuery.
  • Added TLV decoding for plaintext XChat DM events.
  • Added media URL extraction from decoded message payloads.
  • Added isEncrypted on DirectMessage so consumers can distinguish plaintext vs encrypted events.
  • Encrypted payloads are now preserved as message shells with isEncrypted: true instead of being dropped.

Runtime check on a one-to-one mixed conversation:

  • 8 message events decoded
  • 6 plaintext
  • 2 encrypted
  • 0 unknown

Encryption Investigation

Inspected both XChat chunks:

Observed primitives:

  • ECDH on P-256, deriving 256 bits
  • ECDSA on P-256
  • AES-GCM 256-bit raw keys for message encryption/decryption
  • AES-CTR helpers, likely for supporting key/franking paths

XChat stores local state in OPFS SQLite:

  • sqlite3.94a37e8a.wasm
  • sqlite3-opfs-async-proxy.js
  • navigator.storage.getDirectory()

Relevant local tables found:

  • dm_my_keypairs(version, private_key_bytes, public_key_bytes)
  • dm_conversation_keys(conversation_id, key_bytes, version)
  • dm_conversation_key_versions(..., failed, blocked_by_private_key_version, raw_event, sequence_number)
  • dm_raw_message_events(sequence_number, bytes, processed, ...)
  • dm_entry(..., contents BLOB, entry_type, ...)

Conclusion: decrypting should be feasible, but it is a separate follow-up. The path is to load the same OPFS key material XChat uses, process missing_conversation_key_change_events / encoded_conversation_key_change_events to obtain the conversation key, then AES-GCM decrypt the payload.

Useful GraphQL operation IDs:

  • GetConversationPageQuery: IVlXls9JTnbgQ1gxsGAfJA
  • GetMessageEventsBySequenceIdQuery: WU1OOeTQbDQX8sc-HdCk8g
  • GetPublicKeys: GJQbOZALDO5D3Zp2IZhH6w
  • AddEncryptedConversationKeysMutation: 4V1KC8ue2tHHvRuIzeczdg
  • AddXChatPublicKeyMutation: CQsk6GRuWAVabyXqqEG1sA

Investigation needed before decryption:

  • Inspect OPFS file names and SQLite schema, without keys or message contents, to locate XChat storage.
  • Identify which SQLite DB contains the active XChat state.
  • Check whether the target conversation already has a clear conversation key in dm_conversation_keys, or whether key-change/private-key processing is required.

Todo

  • Add one-to-one non-encrypted DM.
  • Add one-to-one encrypted DM decryption.
  • Add group conversation decryption support.

@vachmara

vachmara commented May 7, 2026

Copy link
Copy Markdown
Contributor Author

I successfully decrypted encrypted XChat DM messages when the conversation secret key was already available locally.
We still need to reverse engineer how XChat creates, distributes, and rotates those conversation keys.

Findings:

  • Encrypted XChat message contents are not AES-GCM payloads.
  • The message payload format is libsodium-compatible SecretBox:
    24-byte nonce + ciphertext/MAC.
  • A locally stored 32-byte conversation key can decrypt those payloads.
  • Conversation keys are scoped per conversation.
  • DirectMessage.isEncrypted now means “this message came from an encrypted payload”, even when the text was successfully decrypted.

Key retrieval status:

  • Decryption currently requires a locally supplied conversation key.
  • The web client stores this material in OPFS SQLite, including tables such as dm_key_material, dm_conversation_key_versions, and related XChat state tables.
  • For the tested conversation, the key was found locally under a tag shaped like:
    ckey-<conversation_id>-<key_version>.

I think we should keep the library key-source agnostic for now. Re-requesting or rebuilding conversation keys on every call may create abnormal client behavior and could be easier to detect or rate-limit.

A safer follow-up may be an experimental local SQLite key store that mirrors the browser’s XChat storage model, with the library resolving keys through a provider hook and only running key-change/private-key flows when the local cache is missing data.

What do you think @Rishikant181?

Follow-up investigation:

  • Inspect missing_conversation_key_change_events and encoded_conversation_key_change_events.
  • Decode the key-change event payload format.
  • Identify which private key from local XChat state is used.
  • Reproduce the ECDH/key unwrap path that turns a key-change event into a 32-byte conversation key.
  • Cache the recovered key locally as ckey-<conversation_id>-<key_version>.

@westcorperations

Copy link
Copy Markdown

i saw one platform that uses reverse api also dey ask for the 4 digit password for x chat while connecting account i wonder how they use it in decryption @vachmara

@vachmara

Copy link
Copy Markdown
Contributor Author

i saw one platform that uses reverse api also dey ask for the 4 digit password for x chat while connecting account i wonder how they use it in decryption @vachmara

I made solid progress and have now completed the reverse-engineering part.

From what we’ve seen, the 4-digit password is used internally to derive or reconstruct the encryption keys. The next step is to integrate this into the lib and recreate the full key derivation/decryption flow cleanly.

@vachmara

Copy link
Copy Markdown
Contributor Author

sry I didn't take the time to finish this, hopefully I'll find some time soon to at least ship a first version of it

@Rishikant181

Copy link
Copy Markdown
Owner

@vachmara That's fine lol

@vachmara vachmara changed the title feat: encrypted dms feat(dm): add encrypted XChat conversation support Sep 14, 2026
@vachmara
vachmara marked this pull request as ready for review September 14, 2026 21:12
@vachmara

Copy link
Copy Markdown
Contributor Author

This PR is finally ready for review! 🎉 @Rishikant181 @westcorperations

Encrypted XChat conversations are now supported through manual conversation keys or PIN-backed key recovery, including verified event decryption, key rotation, group metadata, documentation, and safer TLV decoding.

X Developer Platform team open-sourced their Chat XDK. It made the key recovery, signature verification, and encrypted-event integration significantly faster and safer to implement!

@Rishikant181

Copy link
Copy Markdown
Owner

@vachmara Thanks! Will check this out, and hopefully, get it merged.

@vachmara

Copy link
Copy Markdown
Contributor Author

@Rishikant181 I only tested unlockXChat() followed by conversation() directly. You’re right, the inbox still excludes encrypted conversations. I’ll update it to support XChat conversations too.

@Rishikant181

Copy link
Copy Markdown
Owner

@vachmara Yeah I figured that out and deleted my earlier message lol.

Conversations work great, though. Kudos for that!

Let me know if fetching inbox is too much of a hassle. If yes, we can defer that to later, to another PR.

@vachmara

Copy link
Copy Markdown
Contributor Author

After investigating, XChat inbox support requires separate GraphQL endpoints, response models, and pagination. That's beyond the scope of this PR, so I'll address it properly in a follow-up PR instead!

@Rishikant181

Copy link
Copy Markdown
Owner

@vachmara No issues.

I'll continue with the review and get this merged.

@Rishikant181 Rishikant181 left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let me know if you can address the feedback or should I make the changes myself.

Comment thread src/helper/DMEventDecoder.ts Outdated
*
* @internal
*/
export class DMEventDecoder {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need for this to be a class. We can just make all the functions in here be standalone functions, with the private methods not having the export keyword, while the public methods will have the export keyword, making them be available for direct call.

Comment thread src/helper/XChatCrypto.ts Outdated
*
* @internal
*/
export class XChatCrypto {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need for this to be a class. We can just make all the functions in here be standalone functions, with the private methods not having the export keyword, while the public methods will have the export keyword, making them be available for direct call.

Comment thread src/models/data/DirectMessage.ts Outdated
export class DirectMessage implements IDirectMessage {
/** The raw message details. */
private readonly _raw: IRawMessage;
private readonly _raw: IRawMessage | Record<string, unknown>;

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of making this a generic Record, let's instead add the raw type to types/raw/dm, and use it here. That will gives us a type to compare against, if the data structure as received from X changes in the future.

Comment thread src/models/data/DirectMessage.ts Outdated
*/
public constructor(message: unknown) {
this._raw = message as IRawMessage;
this._raw = message as IRawMessage | Record<string, unknown>;

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same goes here

Comment thread src/models/data/DirectMessage.ts Outdated

/** The raw message details. */
public get raw(): IRawMessage {
public get raw(): IRawMessage | Record<string, unknown> {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here as well

Comment thread src/models/RettiwtConfig.ts Outdated
public readonly maxRetries: number;
public readonly responseMiddleware?: (response: AxiosResponse) => void | Promise<void>;
public readonly timeout?: number;
public readonly xChatConversationKeyProvider?: IRettiwtConfig['xChatConversationKeyProvider'];

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of using the type from IRettiwtConfig['<field_name>'], let's type out the actual type here i.e, XChatConversationKeyProvider | undefined, etc. This is purely a style preference.

Comment thread src/models/XChatSession.ts Outdated
@@ -0,0 +1,92 @@
import { IXChatDecryptResult, IXChatSigningKey } from '../types/args/DirectMessageArgs';

interface IXChatClient {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move this interface to types/XChatSession.ts

Comment thread src/models/XChatSession.ts Outdated
}

/** Options used to create a PIN-backed XChat session. */
export interface IXChatSessionOptions {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move this interface to types/XChatSession.ts

Comment thread src/types/XChatSession.ts

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we split the contents of this file between FetchArgs.ts and PostArgs.ts, as necessary, instead of having it's own DirectMessageArgs.ts file? It seems a bit out of place.

Comment thread src/commands/DirectMessage.ts Resolved
@vachmara

Copy link
Copy Markdown
Contributor Author

On it!

@Rishikant181
Rishikant181 merged commit aedff4b into Rishikant181:dev Sep 18, 2026
2 checks passed
@Rishikant181

Copy link
Copy Markdown
Owner

@vachmara Merged.

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support for encrypted DMs

3 participants