Skip to content

feat: keep and use connected_apps for conversation keys and app signatures - #112

Open
santiagomed wants to merge 27 commits into
mainfrom
cursor/connected-apps-conversation-keys-460c
Open

santiagomed wants to merge 27 commits into
mainfrom
cursor/connected-apps-conversation-keys-460c

Conversation

@santiagomed

@santiagomed santiagomed commented Dec 5, 2026 •

Copy link
Copy Markdown
Contributor

Support connected apps across all bindings (Rust, Python, JS/WASM, C ABI/FFI, Go, .NET, JVM, Ruby) so a connected app can participate in a business's 1:1 X Chat conversations without ever holding the business's private keys — while keeping the developer flow simple and misuse-resistant.

Developer flow

Pass GET /2/users/{id}/public_keys records straight to the SDK as usual — the SDK verifies connected apps' keys and signatures for you. Enable connected-app mode once via setIdentity({ userId, signingKeyVersion, clientAppId }), and post requestBody directly to /2/chat/conversations/${restConversationId}/... on every send and prepare result.

Full walkthrough and tradeoffs in docs/API.md#connected-apps.

import { createChat, type PublicKeyRecords } from "@xdevplatform/chat-xdk-server";

// 1. Configure the connected app's session once (app owner's own keys; no business keys shared)
const appChat = await createChat({
  resolvePublicKeys: async (userIds: string[]): Promise<PublicKeyRecords> => {
    const records: PublicKeyRecords = {};
    for (const userId of userIds) {
      const res = await xApi.get(`/2/users/${userId}/public_keys`);
      if (res.data?.length) records[userId] = res.data;
    }
    return records;
  },
});
appChat.importKeys({ keys: appOwnerKeyBytes, signingKeyVersion: appOwnerKeyVersion });
appChat.setIdentity({
  userId: appOwnerId,
  signingKeyVersion: appOwnerKeyVersion,
  clientAppId,
});

// 2. Starting or rotating a 1:1 (any client) — requestBody includes connected apps automatically
const prep = await customerChat.prepareConversationKeyChangeAsync({
  conversationId: `${customerId}:${businessId}`,
});
if (prep.skippedConnectedApps?.length) {
  console.warn("Skipped invalid connected apps:", prep.skippedConnectedApps);
}
await xApi.post(`/2/chat/conversations/${prep.restConversationId}/keys`, prep.requestBody);

// 3. Read the business's 1:1 messages in the connected app
const page = await xApiAsBusiness.get(`/2/chat/conversations/${customerId}-${businessId}/events`);
const events = [
  ...(page.meta?.conversation_key_events ?? []),
  ...(page.data ?? []).map((e) => e.encoded_event),
];
const { events: decrypted } = await appChat.decryptEventsAsync({ events });

// 4. Send a message or read receipt — the SDK infers the business participant automatically
const payload = await appChat.encryptMessageAsync({
  conversationId: `${customerId}:${businessId}`,
  text: "Your order has shipped!",
});
await xApiAsBusiness.post(
  `/2/chat/conversations/${payload.restConversationId}/messages`,
  payload.requestBody,
);

const readAction = await appChat.prepareMarkConversationReadAsync({
  conversationId: `${customerId}:${businessId}`,
  seenUntilSequenceId: lastSequenceId,
});
await xApiAsBusiness.post(
  `/2/chat/conversations/${readAction.restConversationId}/read`,
  readAction.requestBody,
);

What changed

  • Session connected-app mode & sender inference: Added optional clientAppId (client_app_id) to SetIdentityParams across all bindings and removed per-send connectedApp / ConnectedAppSender. In connected-app mode, 1:1 sends and read receipts infer the acted-for participant from stored/hook-resolved public keys (sync calls use stored keys only; JS/.NET *Async calls including prepareMarkConversationReadAsync and native bindings call resolvePublicKeys). Rejects missing keys, neither participant listing the app, both listing it (unless senderId is passed), non-participant or app-owner senderId, groups, and self-DMs, and never falls back to the app owner.
  • 1:1 participant validation on both paths: All sends and read receipts check that the resolved event sender is one of the two participants in any 1:1 conversation ID (checked against the acted-for account in connected-app mode).
  • Ready-to-POST requestBody & restConversationId: Added to SendPayload, PreparedConversationChange, PreparedGroupMetadataChange, and PreparedAction across all bindings (purely additive). Emits exact snake_case X API request JSON, includes connected_app_conversation_keys on non-self 1:1 key changes when present, and never includes the secret conversation_key.
  • Consistent invalid-app skipping (skippedConnectedApps): Broken or invalid connected-app entries are skipped identically on passed-in, stored, and hook paths instead of aborting a 1:1 key change, and reported in skippedConnectedApps ({ clientAppId, reason }).
  • Cleaner TypeScript types: Split PublicKeyRecord and ConnectedApp into one interface per casing (PublicKeyRecordSnake | PublicKeyRecordCamel, ConnectedAppSnake | ConnectedAppCamel) with plain developer-focused comments.
  • App-signed read receipts: prepare_mark_conversation_read in connected-app mode populates valid top-level signature and version fields alongside connected_app_signature so POST /2/chat/conversations/{id}/read accepts them while decryption still verifies the connected-app signature.
  • Docs & examples: Updated docs/API.md (including the connected-apps walkthrough and tradeoffs), docs/CRYPTO.md, CHANGELOG.md, all READMEs, and all examples/* projects to use the redesigned flow and requestBody.

Testing

  • Rust workspace (cargo fmt --check, cargo clippy --workspace --all-targets -- -D warnings, cargo test --workspace), Go (make test-go), Python (195 tests), and Rust/Go/Python example offline suites pass locally.
  • Parallel binding tests across Rust, FFI, JS/WASM, Python, Go, JVM, .NET, and Ruby cover every misuse case, skippedConnectedApps, requestBody / restConversationId, and app-signed read receipts.
  • Note: App-signed read receipts were verified against the X API v2 OpenAPI request schema and unit/round-trip tests; staging1 live verification was not run because staging test credentials are not present in this environment.
Open in Web Open in Cursor 

cursoragent and others added 3 commits December 5, 2026 08:37
Co-authored-by: Santiago Medina <santiagomed@users.noreply.github.com>
…tures

Co-authored-by: Santiago Medina <santiagomed@users.noreply.github.com>
…SDKs

Co-authored-by: Santiago Medina <santiagomed@users.noreply.github.com>
@CLAassistant

CLAassistant commented Dec 5, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
0 out of 2 committers have signed the CLA.

❌ cursoragent
❌ github-actions[bot]
You have signed the CLA already but the status is still pending? Let us recheck it.

github-actions Bot and others added 24 commits December 5, 2026 08:41
…p validation

Co-authored-by: Santiago Medina <santiagomed@users.noreply.github.com>
…ce & net472 test

Co-authored-by: Santiago Medina <santiagomed@users.noreply.github.com>
…nversation_keys

Co-authored-by: Santiago Medina <santiagomed@users.noreply.github.com>
Co-authored-by: Santiago Medina <santiagomed@users.noreply.github.com>
Co-authored-by: Santiago Medina <santiagomed@users.noreply.github.com>
…s all bindings

Co-authored-by: Santiago Medina <santiagomed@users.noreply.github.com>
…pp sending

Co-authored-by: Santiago Medina <santiagomed@users.noreply.github.com>
…d comments

Co-authored-by: Santiago Medina <santiagomed@users.noreply.github.com>
Co-authored-by: Santiago Medina <santiagomed@users.noreply.github.com>
…, skipped_connected_apps, and read-receipt signatures

Co-authored-by: Santiago Medina <santiagomed@users.noreply.github.com>
…_id, skipped_connected_apps, and clean types across all bindings

Co-authored-by: Santiago Medina <santiagomed@users.noreply.github.com>
…G, and all examples to use connected-app mode and request_body

Co-authored-by: Santiago Medina <santiagomed@users.noreply.github.com>
…ertion

Co-authored-by: Santiago Medina <santiagomed@users.noreply.github.com>
…ion/reply tests

Co-authored-by: Santiago Medina <santiagomed@users.noreply.github.com>
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.

3 participants