diff --git a/x-api/posts/hide-replies/integrate/manage-replies-in-realtime.mdx b/x-api/posts/hide-replies/integrate/manage-replies-in-realtime.mdx index f3109fb64..f99a428df 100644 --- a/x-api/posts/hide-replies/integrate/manage-replies-in-realtime.mdx +++ b/x-api/posts/hide-replies/integrate/manage-replies-in-realtime.mdx @@ -64,7 +64,7 @@ An earlier version of this guide used Google Jigsaw's Perspective API for toxici -d '{"url": "https://yourdomain.com/webhook"}' ``` - X immediately sends a Challenge-Response Check (CRC) to the URL and repeats it hourly. Your endpoint must answer the CRC and should verify the `X-Twitter-Webhooks-Signature-OAuth2` header on every event. Both are implemented in the [full example](#put-it-together) below; the [Webhooks quickstart](/x-api/webhooks/quickstart) explains them in detail. + X immediately sends a Challenge-Response Check (CRC) to the URL and re-checks it periodically. Your endpoint must answer the CRC and should verify the `X-Twitter-Webhooks-Signature-OAuth2` header on every event. Both are implemented in the [full example](#put-it-together) below; the [Webhooks quickstart](/x-api/webhooks/quickstart) explains them in detail. @@ -269,6 +269,7 @@ import hashlib import hmac import json import os +import re import threading import requests @@ -279,6 +280,7 @@ app = Flask(__name__) X_CLIENT_SECRET = os.environ["X_OAUTH2_CLIENT_SECRET"] # signs CRC and event payloads XAI_API_KEY = os.environ["XAI_API_KEY"] HIDE_THRESHOLD = 0.90 +CRC_TOKEN_PATTERN = re.compile(r"[A-Za-z0-9_-]{48}") # X CRC token format # Replace these in-memory stores with a database. user_tokens: dict[str, str] = {} # user_id -> OAuth 2.0 user access token @@ -317,6 +319,11 @@ def sign(secret: str, message: bytes) -> str: return "sha256=" + base64.b64encode(digest).decode("utf-8") +def has_valid_signature(message: bytes) -> bool: + signature = request.headers.get("X-Twitter-Webhooks-Signature-OAuth2", "") + return hmac.compare_digest(sign(X_CLIENT_SECRET, message), signature) + + def classify_reply(reply_text: str, parent_text: str | None) -> dict: user_content = f"Reply: {reply_text}" if parent_text: @@ -386,13 +393,17 @@ def moderate(event: dict) -> None: @app.route("/webhook", methods=["GET", "POST"]) def webhook(): if request.method == "GET": - # Challenge-Response Check + # Challenge-Response Check. Validate the request before signing anything. crc_token = request.args.get("crc_token", "") + nonce = request.args.get("nonce", "") + if not CRC_TOKEN_PATTERN.fullmatch(crc_token): + return "Invalid crc_token", 400 + if not has_valid_signature(f"crc_token={crc_token}&nonce={nonce}".encode("utf-8")): + return "Invalid signature", 401 return jsonify({"response_token": sign(X_CLIENT_SECRET, crc_token.encode("utf-8"))}) raw_body = request.get_data() - signature = request.headers.get("X-Twitter-Webhooks-Signature-OAuth2", "") - if not hmac.compare_digest(sign(X_CLIENT_SECRET, raw_body), signature): + if not has_valid_signature(raw_body): return "Invalid signature", 401 event = json.loads(raw_body).get("data", {}) @@ -417,6 +428,7 @@ const app = express(); const X_CLIENT_SECRET = process.env.X_OAUTH2_CLIENT_SECRET; // signs CRC and event payloads const XAI_API_KEY = process.env.XAI_API_KEY; const HIDE_THRESHOLD = 0.9; +const CRC_TOKEN_PATTERN = /^[A-Za-z0-9_-]{48}$/; // X CRC token format // Replace these in-memory stores with a database. const userTokens = new Map(); // user_id -> OAuth 2.0 user access token @@ -451,6 +463,12 @@ const MODERATION_SCHEMA = { const sign = (secret, message) => "sha256=" + crypto.createHmac("sha256", secret).update(message).digest("base64"); +function hasValidSignature(req, message) { + const expected = Buffer.from(sign(X_CLIENT_SECRET, message)); + const received = Buffer.from(req.get("X-Twitter-Webhooks-Signature-OAuth2") ?? ""); + return expected.length === received.length && crypto.timingSafeEqual(expected, received); +} + async function classifyReply(replyText, parentText) { const userContent = parentText ? `Original Post: ${parentText}\n\nReply: ${replyText}` @@ -518,15 +536,20 @@ async function moderate(event) { } } -// Challenge-Response Check +// Challenge-Response Check. Validate the request before signing anything. app.get("/webhook", (req, res) => { - res.json({ response_token: sign(X_CLIENT_SECRET, String(req.query.crc_token ?? "")) }); + const { crc_token: crcToken, nonce = "" } = req.query; + if (typeof crcToken !== "string" || !CRC_TOKEN_PATTERN.test(crcToken)) { + return res.status(400).send("Invalid crc_token"); + } + if (!hasValidSignature(req, `crc_token=${crcToken}&nonce=${nonce}`)) { + return res.status(401).send("Invalid signature"); + } + res.json({ response_token: sign(X_CLIENT_SECRET, crcToken) }); }); app.post("/webhook", express.raw({ type: "application/json" }), (req, res) => { - const expected = Buffer.from(sign(X_CLIENT_SECRET, req.body)); - const received = Buffer.from(req.get("X-Twitter-Webhooks-Signature-OAuth2") ?? ""); - if (expected.length !== received.length || !crypto.timingSafeEqual(expected, received)) { + if (!hasValidSignature(req, req.body)) { return res.status(401).send("Invalid signature"); } diff --git a/x-api/webhooks/introduction.mdx b/x-api/webhooks/introduction.mdx index 241566ea7..f4cbef4f8 100644 --- a/x-api/webhooks/introduction.mdx +++ b/x-api/webhooks/introduction.mdx @@ -85,7 +85,7 @@ All endpoints require **OAuth2 App Only Bearer Token** authentication. X's webhook-based APIs provide two methods for confirming the security of your webhook server: -1. **Challenge-Response Check (CRC)** — X sends periodic GET requests to your webhook URL. You respond with an HMAC-SHA256 hash to prove you control the endpoint. CRC checks happen on initial registration, hourly, and on manual re-validation. +1. **Challenge-Response Check (CRC)** — X sends periodic GET requests to your webhook URL. You respond with an HMAC-SHA256 hash to prove you control the endpoint. CRC checks happen on initial registration, on manual re-validation, and periodically (see [Webhook validation](#webhook-validation)). Validate each CRC request before you sign the token; see [Validate the CRC request](/x-api/webhooks/quickstart#validate-the-crc-request). 2. **Signature verification** — Each POST request from X includes a signature header. You can verify this signature to confirm X is the source of incoming events. diff --git a/x-api/webhooks/quickstart.mdx b/x-api/webhooks/quickstart.mdx index 93c95e54e..d5bb4dd40 100644 --- a/x-api/webhooks/quickstart.mdx +++ b/x-api/webhooks/quickstart.mdx @@ -40,19 +40,21 @@ The Challenge-Response Check (CRC) is how X validates that the callback URL you | Trigger | Description | |:--------|:------------| | **Initial registration** | When you call `POST /2/webhooks` | -| **Hourly validation** | X automatically validates your webhook every hour | +| **Periodic validation** | X automatically re-validates your webhook about once every 24 hours | | **Manual re-validation** | When you call `PUT /2/webhooks/:webhook_id` | If your webhook fails a CRC check, it will be marked as `invalid` and will **stop receiving events** until it passes again. ### How the CRC works -When X sends a CRC, it makes a **GET request** to your webhook URL with a `crc_token` query parameter: +When X sends a CRC, it makes a **GET request** to your webhook URL with `crc_token` and `nonce` query parameters: ``` -GET https://your-webhook-url.com/webhook?crc_token=challenge_string +GET https://your-webhook-url.com/webhook?crc_token=&nonce= ``` +X signs this request with the same [signature headers](#signature-verification) it sends with events, computed over the string `crc_token=&nonce=`. + Your application must respond with a JSON body containing a `response_token`: ```json @@ -72,6 +74,9 @@ Your application must respond with a JSON body containing a `response_token`: Expressed as pseudocode: ``` +if not matches(crc_token, "^[A-Za-z0-9_-]{48}$"): + return 400 # do not sign it + response_token = "sha256=" + base64( hmac_sha256(OAUTH2_CLIENT_SECRET, crc_token) ) @@ -81,6 +86,21 @@ response_token = "sha256=" + base64( **Important:** Use the app's **OAuth 2.0 client secret** (or, for legacy integrations, the **OAuth 1.0 consumer secret**) to compute the CRC response. Do **not** use the OAuth 2.0 App Only Bearer Token you pass to `/2/webhooks`, and do not use any user access token. Client and consumer secrets must remain server-side. +### Validate the CRC request + +The CRC response is an HMAC of `crc_token` made with the same secret and algorithm X uses to sign event payloads. If your endpoint signs any `crc_token` it receives, anyone who knows your webhook URL can send an event payload as the `crc_token`, get a valid signature back, and then POST that payload to your webhook as a forged event that passes signature verification. + + +Never sign an arbitrary `crc_token` with your webhook signing secret. Validate the request first, and respond with `400` without signing anything if validation fails. + + +Before you compute the `response_token`: + +1. **Check the token format.** A `crc_token` from X is always exactly 48 characters from the URL-safe Base64 alphabet (`A-Z`, `a-z`, `0-9`, `-`, `_`), so it matches `^[A-Za-z0-9_-]{48}$`. Reject anything else. An event payload can never match this format. +2. **Verify the request signature (recommended).** Compute `"sha256=" + base64(hmac_sha256(secret, "crc_token=" + crc_token + "&nonce=" + nonce))` from the query parameter values and compare it with the `X-Twitter-Webhooks-Signature-OAuth2` header (or `X-Twitter-Webhooks-Signature` for OAuth 1.0-only apps) using a constant-time comparison. The same secret and header rules apply as for [event signatures](#signature-verification). + +Either check stops your CRC endpoint from signing attacker-chosen data. The [Flask example](#example-flask-full-endpoint) below does both. + The examples below use `WEBHOOK_SIGNING_SECRET` as a generic name for the app's **OAuth 2.0 client secret**. To keep an existing OAuth 1.0 integration working, set `WEBHOOK_SIGNING_SECRET` to your `OAUTH1_CONSUMER_SECRET` instead — the algorithm is identical. @@ -91,6 +111,9 @@ The examples below use `WEBHOOK_SIGNING_SECRET` as a generic name for the app's import hmac import hashlib import base64 +import re + +CRC_TOKEN_PATTERN = re.compile(r"[A-Za-z0-9_-]{48}") def handle_crc(crc_token, webhook_signing_secret): """ @@ -102,8 +125,12 @@ def handle_crc(crc_token, webhook_signing_secret): (or OAuth 1.0 consumer secret for legacy integrations) Returns: - dict with the response_token + dict with the response_token, or None if crc_token is not a valid + X CRC token (respond with 400 and do not sign it) """ + if not isinstance(crc_token, str) or not CRC_TOKEN_PATTERN.fullmatch(crc_token): + return None + sha256_hash = hmac.new( webhook_signing_secret.encode('utf-8'), crc_token.encode('utf-8'), @@ -120,9 +147,17 @@ def handle_crc(crc_token, webhook_signing_secret): ```javascript title="Example" lines wrap icon="square-js" const crypto = require('crypto'); +const CRC_TOKEN_PATTERN = /^[A-Za-z0-9_-]{48}$/; + // OAuth 2.0 client secret (recommended). Set to your OAuth 1.0 consumer // secret instead to keep an existing OAuth 1.0 integration working. +// Returns null if crcToken is not a valid X CRC token (respond with 400 +// and do not sign it). function handleCrc(crcToken, webhookSigningSecret) { + if (typeof crcToken !== 'string' || !CRC_TOKEN_PATTERN.test(crcToken)) { + return null; + } + const hmac = crypto .createHmac('sha256', webhookSigningSecret) .update(crcToken) @@ -136,10 +171,11 @@ function handleCrc(crcToken, webhookSigningSecret) { ### Example: Flask (full endpoint) -This example shows a complete webhook endpoint that handles both CRC validation (GET) and event delivery (POST). It uses the OAuth 2.0 client secret by default and, when both secrets are configured, verifies incoming POSTs against `X-Twitter-Webhooks-Signature-OAuth2` first, falling back to the legacy `X-Twitter-Webhooks-Signature` header. +This example shows a complete webhook endpoint that handles both CRC validation (GET) and event delivery (POST). It validates the `crc_token` format and the request signature before answering a CRC, uses the OAuth 2.0 client secret by default and, when both secrets are configured, verifies signatures against `X-Twitter-Webhooks-Signature-OAuth2` first, falling back to the legacy `X-Twitter-Webhooks-Signature` header. ```python title="Example" expandable lines wrap icon="python" import os +import re import hmac import hashlib import base64 @@ -154,38 +190,45 @@ OAUTH2_CLIENT_SECRET = os.environ["OAUTH2_CLIENT_SECRET"] # this while migrating an existing OAuth 1.0 integration. OAUTH1_CONSUMER_SECRET = os.environ.get("OAUTH1_CONSUMER_SECRET") +# X CRC tokens are always 48 URL-safe Base64 characters. +CRC_TOKEN_PATTERN = re.compile(r"[A-Za-z0-9_-]{48}") + def _sign(secret: str, message: bytes) -> str: digest = hmac.new(secret.encode("utf-8"), message, hashlib.sha256).digest() return "sha256=" + base64.b64encode(digest).decode("utf-8") +def _has_valid_x_signature(message: bytes) -> bool: + """Check X's signature header on the current request against message.""" + oauth2_signature = request.headers.get("X-Twitter-Webhooks-Signature-OAuth2") + if oauth2_signature is not None: + return hmac.compare_digest(_sign(OAUTH2_CLIENT_SECRET, message), oauth2_signature) + + # Legacy fallback for OAuth 1.0-only apps during migration. + legacy_signature = request.headers.get("X-Twitter-Webhooks-Signature") + if legacy_signature is None or OAUTH1_CONSUMER_SECRET is None: + return False + return hmac.compare_digest(_sign(OAUTH1_CONSUMER_SECRET, message), legacy_signature) + + @app.route("/webhook", methods=["GET", "POST"]) def webhook(): if request.method == "GET": - # CRC check — respond with HMAC of crc_token using the OAuth 2.0 - # client secret. - crc_token = request.args.get("crc_token") - if not crc_token: - return "Missing crc_token", 400 + # CRC check. Validate the request before signing anything so this + # endpoint can't be used to sign attacker-chosen data. + crc_token = request.args.get("crc_token", "") + nonce = request.args.get("nonce", "") + if not CRC_TOKEN_PATTERN.fullmatch(crc_token): + return "Invalid crc_token", 400 + if not _has_valid_x_signature(f"crc_token={crc_token}&nonce={nonce}".encode("utf-8")): + return "Invalid signature", 401 return jsonify({"response_token": _sign(OAUTH2_CLIENT_SECRET, crc_token.encode("utf-8"))}), 200 # POST — verify signature over the raw request body. raw_body = request.get_data() # bytes - - oauth2_signature = request.headers.get("X-Twitter-Webhooks-Signature-OAuth2") - if oauth2_signature is not None: - expected = _sign(OAUTH2_CLIENT_SECRET, raw_body) - if not hmac.compare_digest(expected, oauth2_signature): - return "Invalid signature", 401 - else: - # Legacy fallback for OAuth 1.0-only apps during migration. - legacy_signature = request.headers.get("X-Twitter-Webhooks-Signature") - if legacy_signature is None or OAUTH1_CONSUMER_SECRET is None: - return "Missing signature", 401 - expected = _sign(OAUTH1_CONSUMER_SECRET, raw_body) - if not hmac.compare_digest(expected, legacy_signature): - return "Invalid signature", 401 + if not _has_valid_x_signature(raw_body): + return "Invalid signature", 401 event = request.get_json(silent=True) print("Received event:", event) @@ -200,7 +243,7 @@ X's webhook-based APIs provide two methods for confirming the security of your w ### Challenge-Response Check (CRC) -The CRC enables X to confirm ownership of the web app receiving webhook events. See [Step 2](#2-the-crc-check) above for full implementation details. +The CRC enables X to confirm ownership of the web app receiving webhook events. Always [validate the CRC request](#validate-the-crc-request) before you sign the `crc_token`. See [Step 2](#2-the-crc-check) above for full implementation details. ### Signature verification diff --git a/xchat/real-time-events.mdx b/xchat/real-time-events.mdx index 5d9c324d5..76def3c62 100644 --- a/xchat/real-time-events.mdx +++ b/xchat/real-time-events.mdx @@ -86,7 +86,7 @@ Subscribe to `chat.sent` as well if you need outbound copies. Other languages: c ## 2. CRC (webhooks only) -If you use webhooks, respond to Challenge-Response Checks (GET `crc_token`) with HMAC-SHA256 of the token using your consumer secret, in the JSON shape your webhook product expects (typically `sha256=`). +If you use webhooks, respond to Challenge-Response Checks (GET `crc_token`) with `{"response_token": "sha256="}`, where the hash is HMAC-SHA256 of the token using your app's OAuth 2.0 client secret (or OAuth 1.0 consumer secret). Validate the request before you sign it: only sign a `crc_token` that matches `^[A-Za-z0-9_-]{48}$`, and verify the request's signature header. Never sign arbitrary input with the secret you use to verify event signatures. See [Validate the CRC request](/x-api/webhooks/quickstart#validate-the-crc-request). ---