Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(x-webhook): real-time mentions via the Account Activity API webhook
nirholas4cbab4a0fb31
diff --git a/api/_lib/x-webhook-events.js b/api/_lib/x-webhook-events.jsnew file mode 100644index 000000000..16b42374c--- /dev/null+++ b/api/_lib/x-webhook-events.js@@ -0,0 +1,128 @@+// @ts-check+// Normalize one Account Activity API webhook event into the same+// platform-neutral mention shape api/_lib/x-mentions.js's normalizeMentions+// produces, so api/_lib/x-mention-intents.js and api/_lib/x-mention-store.js+// read a webhook delivery exactly as they read a polled timeline page. PURE:+// no network, no DB.+//+// The webhook payload carries the classic v1.1 Tweet object (tweet_create_events),+// not the v2 shape fetchMentions reads, so this is a second normalizer rather+// than a variant of normalizeMentions: field names differ (id_str vs id,+// user.screen_name vs username, entities.user_mentions vs entities.mentions,+// created_at as an RFC 2822 string vs ISO 8601) and v1.1 has no+// conversation_id, so a reply's conversation is approximated as the mention's+// own id, same as normalizeMentions does for a non-reply.++import { decodeXText } from './x-search.js';++function permalink(id, username) {+ return username ? `https://x.com/${username}/status/${id}` : `https://x.com/i/status/${id}`;+}++function isoCreatedAt(value) {+ const t = value ? Date.parse(value) : NaN;+ return Number.isFinite(t) ? new Date(t).toISOString() : null;+}++function fullText(t) {+ return decodeXText(t?.extended_tweet?.full_text || t?.full_text || t?.text || '');+}++function authorOf(user) {+ if (!user?.id_str) return null;+ return {+ id: String(user.id_str),+ username: user.screen_name ? String(user.screen_name) : null,+ name: user.name ? decodeXText(user.name) : null,+ profileImageUrl: user.profile_image_url_https || user.profile_image_url || null,+ verified: user.verified === true,+ };+}++function mediaOf(t) {+ const entities = t?.extended_entities?.media || t?.entities?.media || [];+ const out = [];+ for (const m of Array.isArray(entities) ? entities : []) {+ if (!m) continue;+ out.push({+ key: m.id_str ? String(m.id_str) : null,+ type: m.type || null,+ url: m.type === 'photo' ? m.media_url_https || null : null,+ previewUrl: m.media_url_https || null,+ width: Number.isFinite(Number(m.sizes?.large?.w)) ? Number(m.sizes.large.w) : null,+ height: Number.isFinite(Number(m.sizes?.large?.h)) ? Number(m.sizes.large.h) : null,+ altText: m.ext_alt_text ? decodeXText(m.ext_alt_text) : null,+ });+ }+ return out;+}++/** An unresolved parent reference: the webhook payload never inlines the parent tweet. */+function unavailableRef(id, username = null) {+ if (!id) return null;+ return { id: String(id), available: false, text: null, author: null, media: [], url: permalink(id, username), conversationId: null };+}++function quotedOf(t) {+ if (t?.quoted_status?.id_str) {+ const q = t.quoted_status;+ const author = authorOf(q.user);+ return {+ id: String(q.id_str),+ available: true,+ text: fullText(q),+ author,+ media: mediaOf(q),+ url: permalink(q.id_str, author?.username),+ conversationId: null,+ };+ }+ if (t?.is_quote_status && t?.quoted_status_id_str) return unavailableRef(t.quoted_status_id_str);+ return null;+}++/**+ * @param {any} tweet one entry of payload.tweet_create_events (v1.1 Tweet object)+ * @param {{ kind: 'company'|'agent', ref: string, userId: string, handle?: string|null }} account+ * @returns {object|null} a mention in normalizeMentions' shape, or null when the tweet has no id+ */+export function normalizeActivityEvent(tweet, account) {+ const id = tweet?.id_str || tweet?.id;+ if (!id) return null;+ const author = authorOf(tweet.user);+ const conversationId = String(id);+ const entities = tweet?.extended_tweet?.entities || tweet?.entities || {};+ return {+ platform: 'x',+ id: String(id),+ url: permalink(id, author?.username),+ text: fullText(tweet),+ lang: tweet.lang || null,+ createdAt: isoCreatedAt(tweet.created_at),+ chatId: conversationId,+ chatType: 'public',+ conversationId,+ userId: tweet.user?.id_str ? String(tweet.user.id_str) : null,+ username: author?.username || null,+ author,+ inReplyToUserId: tweet.in_reply_to_user_id_str ? String(tweet.in_reply_to_user_id_str) : null,+ repliedTo: unavailableRef(tweet.in_reply_to_status_id_str),+ quoted: quotedOf(tweet),+ isRetweet: !!tweet.retweeted_status,+ media: mediaOf(tweet),+ mentions: (entities.user_mentions || []).map((m) => ({+ username: m?.screen_name ? String(m.screen_name) : null,+ id: m?.id_str ? String(m.id_str) : null,+ start: Number.isFinite(m?.indices?.[0]) ? m.indices[0] : null,+ end: Number.isFinite(m?.indices?.[1]) ? m.indices[1] : null,+ })),+ urls: (entities.urls || []).map((u) => ({+ url: u?.url || null,+ expandedUrl: u?.expanded_url || null,+ start: Number.isFinite(u?.indices?.[0]) ? u.indices[0] : null,+ end: Number.isFinite(u?.indices?.[1]) ? u.indices[1] : null,+ })),+ account: { kind: account.kind, ref: account.ref, userId: account.userId, handle: account.handle || null },+ fromSelf: !!(tweet.user?.id_str && String(tweet.user.id_str) === String(account.userId)),+ };+}diff --git a/api/x/webhook.js b/api/x/webhook.jsnew file mode 100644index 000000000..06fec0abf--- /dev/null+++ b/api/x/webhook.js@@ -0,0 +1,131 @@+// @ts-check+// GET/POST /api/x/webhook: the Account Activity API webhook (x-grok 41).+//+// GET answers the Challenge-Response Check (CRC) X sends when the webhook is+// registered and periodically afterward to re-verify it is still live: X+// sends ?crc_token=... and expects { response_token: "sha256=" + base64(+// HMAC-SHA256(crc_token, consumer_secret)) } back. This has no gate: X must+// get a valid CRC response before it will ever deliver a POST, and the CRC+// reveals nothing an attacker could use (it only proves we hold the same+// consumer secret X already gave us).+//+// POST delivers real-time events once a subscription exists. Every delivery+// is signed over the raw body with the app's OAuth 1.0a consumer secret+// (X_API_SECRET, the same credential api/_lib/x-mentions.js's oauth1Transport+// already uses to read mentions): header x-twitter-webhooks-signature,+// "sha256=" + base64(HMAC-SHA256(rawBody, consumer_secret)). Gated behind+// X_WEBHOOK_ENABLED since the Account Activity API needs Enterprise or+// Pay-Per-Use access (order 926's owner message); until that is on, POST+// acks 200 without reading the body, which is also the correct response to+// X's own delivery retries while registration is incomplete.+//+// This order scopes event handling to the company account only: X's own+// tier gate caps Pay-Per-Use at 3 subscriptions, and reverse-resolving an+// arbitrary for_user_id to one of our agents' connected X accounts has no+// lookup on this branch (resolveXConnection needs the agentId already known,+// not just the X user id). An event for any other for_user_id is acknowledged+// and dropped; extending to agent accounts needs that reverse lookup first.+//+// Recording is the one step this handler takes: parseMentionIntent (pure)+// then recordMention, the exact same dedupe-safe insert the polling cron+// uses (x-mention-store.js, tweet_id primary key), so whichever path sees a+// tweet first wins and the other is a silent no-op. An intent of 'ignore'+// (not addressed to us, our own post, a retweet) is immediately marked+// 'skip', mirroring the cron's own early exit in api/_lib/x-mention-poll.js+// (main-branch only as of this order). Every other intent is left with+// decision = null, exactly as x-mention-store.js's recordMention already+// documents ("decision is null until decided"): deciding and replying is the+// cron's job, which keeps running as backfill regardless of this webhook.++import { createHash, createHmac, timingSafeEqual } from 'node:crypto';+import { cors, error, json, method, readBody, wrap } from '../_lib/http.js';+import { companyMentionsConfigured, companyUserId, COMPANY_HANDLE_DEFAULT } from '../_lib/x-mentions.js';+import { normalizeActivityEvent } from '../_lib/x-webhook-events.js';+import { parseMentionIntent } from '../_lib/x-mention-intents.js';+import { recordMention, updateDecision } from '../_lib/x-mention-store.js';++const BODY_LIMIT = 2_000_000;++function enabled(env = process.env) {+ return env.X_WEBHOOK_ENABLED === '1';+}++function sign(value, secret) {+ return createHmac('sha256', secret).update(value).digest('base64');+}++/** Constant-time string compare: hash both sides first so unequal lengths never short-circuit the comparison. */+function safeEqualStrings(a, b) {+ const ha = createHash('sha256').update(String(a)).digest();+ const hb = createHash('sha256').update(String(b)).digest();+ return timingSafeEqual(ha, hb);+}++function companyAccount(env) {+ const handle = env.X_COMPANY_HANDLE || COMPANY_HANDLE_DEFAULT;+ return { kind: 'company', ref: handle, userId: companyUserId(env), handle };+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const secret = process.env.X_API_SECRET;++ if (req.method === 'GET') {+ const crcToken = req.query?.crc_token;+ if (typeof crcToken !== 'string' || !crcToken) return error(res, 400, 'bad_request', 'crc_token required');+ if (!secret) return error(res, 503, 'not_configured', 'X_API_SECRET not set');+ return json(res, 200, { response_token: `sha256=${sign(crcToken, secret)}` });+ }++ // POST. Ack quietly rather than 404/401 while disabled or unconfigured: a+ // 4xx on every retry is how X eventually suspends a webhook as unhealthy,+ // and "we chose not to read this yet" is not the same failure as "this URL+ // is broken".+ if (!enabled() || !secret || !companyMentionsConfigured(process.env)) {+ return json(res, 200, { ok: true, disabled: true });+ }++ const sigHeader = req.headers['x-twitter-webhooks-signature'];+ if (typeof sigHeader !== 'string' || !sigHeader.startsWith('sha256=')) {+ return error(res, 401, 'unauthorized', 'missing signature');+ }+ const raw = await readBody(req, BODY_LIMIT).catch((e) => {+ throw Object.assign(new Error(e?.message || 'invalid body'), { status: e?.status || 400 });+ });+ const expected = `sha256=${sign(raw, secret)}`;+ if (!safeEqualStrings(sigHeader, expected)) {+ return error(res, 401, 'unauthorized', 'bad signature');+ }++ let payload;+ try {+ payload = JSON.parse(raw.toString('utf8'));+ } catch {+ return error(res, 400, 'bad_request', 'invalid JSON');+ }++ const account = companyAccount(process.env);+ const forUserId = payload?.for_user_id ? String(payload.for_user_id) : null;+ const events = Array.isArray(payload?.tweet_create_events) ? payload.tweet_create_events : [];++ let inserted = 0;+ let skipped = 0;+ if (forUserId && account.userId && forUserId === String(account.userId)) {+ for (const tweet of events) {+ const mention = normalizeActivityEvent(tweet, account);+ if (!mention) continue;+ const parsed = parseMentionIntent(mention, account);+ const { inserted: wasInserted } = await recordMention({ mention, parsed, dryRun: true });+ if (!wasInserted) continue;+ inserted += 1;+ if (parsed.intent === 'ignore') {+ await updateDecision(mention.id, { decision: 'skip', reason: parsed.reason });+ skipped += 1;+ }+ }+ }++ return json(res, 200, { ok: true, received: events.length, inserted, skipped });+});diff --git a/scripts/x-webhook-register.mjs b/scripts/x-webhook-register.mjsnew file mode 100644index 000000000..dc054d180--- /dev/null+++ b/scripts/x-webhook-register.mjs@@ -0,0 +1,156 @@+#!/usr/bin/env node+// Register the Account Activity API webhook (api/x/webhook.js) and subscribe+// the company account to it, per docs.x.com's current Webhooks API:+//+// POST /2/webhooks -> register, OAuth2 app-only bearer+// GET /2/webhooks -> list, OAuth2 app-only bearer+// POST /2/account_activity/webhooks/:webhook_id/subscriptions/all -> subscribe, OAuth 1.0a user context+// DELETE /2/webhooks/:webhook_id -> remove, OAuth2 app-only bearer+//+// The webhook URL must answer the CRC before X will register it, so this+// only makes sense against a deployed, publicly reachable three.ws.+// Credentials come from this process's env, falling back to the three-ws-api+// Cloud Run service (same pattern as scripts/x-mentions-probe.mjs).+//+// USAGE+// node scripts/x-webhook-register.mjs --dry-run # print the calls, make none+// node scripts/x-webhook-register.mjs # register + subscribe for real+// node scripts/x-webhook-register.mjs --list # GET /2/webhooks+// node scripts/x-webhook-register.mjs --delete <id> # DELETE /2/webhooks/:id+// node scripts/x-webhook-register.mjs --url <https://...> # override the webhook URL++import { serviceEnvValue } from './lib/service-env.mjs';+import { appOrigin } from '../api/_lib/gateway/format.js';++const API_BASE = 'https://api.twitter.com/2';+const TOKEN_URL = 'https://api.twitter.com/oauth2/token';+const KEYS = ['X_API_KEY', 'X_API_SECRET', 'X_ACCESS_TOKEN', 'X_ACCESS_SECRET'];++function parseArgs(argv) {+ const out = { dryRun: false, list: false, deleteId: null, url: null };+ for (let i = 0; i < argv.length; i++) {+ const a = argv[i];+ if (a === '--dry-run') out.dryRun = true;+ else if (a === '--list') out.list = true;+ else if (a === '--delete') out.deleteId = argv[++i];+ else if (a === '--url') out.url = argv[++i];+ }+ return out;+}++function loadCreds() {+ const env = {};+ const source = {};+ for (const k of KEYS) {+ if (process.env[k]) {+ env[k] = process.env[k];+ source[k] = 'process.env';+ continue;+ }+ const v = serviceEnvValue(k);+ if (v) {+ env[k] = v;+ source[k] = 'cloud-run:three-ws-api';+ }+ }+ return { env, source };+}++async function appBearerToken(env, { dryRun }) {+ if (env.X_BEARER_TOKEN) return env.X_BEARER_TOKEN;+ if (dryRun) return '<app-only bearer, minted via POST /oauth2/token client_credentials grant>';+ if (!env.X_API_KEY || !env.X_API_SECRET) throw new Error('X_API_KEY and X_API_SECRET are required to mint an app-only bearer token');+ const basic = Buffer.from(`${encodeURIComponent(env.X_API_KEY)}:${encodeURIComponent(env.X_API_SECRET)}`).toString('base64');+ const res = await fetch(TOKEN_URL, {+ method: 'POST',+ headers: { authorization: `Basic ${basic}`, 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8' },+ body: 'grant_type=client_credentials',+ });+ const body = await res.json().catch(() => null);+ if (!res.ok || !body?.access_token) throw new Error(`X token exchange failed: HTTP ${res.status} ${JSON.stringify(body)}`);+ return body.access_token;+}++function logCall(method, path, { auth, body } = {}) {+ console.log(`${method} ${API_BASE}${path}`);+ console.log(` auth: ${auth}`);+ if (body !== undefined) console.log(` body: ${JSON.stringify(body)}`);+}++async function bearerCall(method, path, token, { dryRun, body } = {}) {+ logCall(method, path, { auth: 'OAuth2 app-only bearer', body });+ if (dryRun) return null;+ const res = await fetch(`${API_BASE}${path}`, {+ method,+ headers: {+ authorization: `Bearer ${token}`,+ ...(body !== undefined ? { 'content-type': 'application/json' } : {}),+ },+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),+ });+ const json = await res.json().catch(() => null);+ if (!res.ok) throw new Error(`${method} ${path} failed: HTTP ${res.status} ${JSON.stringify(json)}`);+ return json;+}++async function oauth1Call(method, path, env, { dryRun } = {}) {+ logCall(method, path, { auth: 'OAuth 1.0a user context (the company account being subscribed)' });+ if (dryRun) return null;+ const { TwitterApi } = await import('twitter-api-v2');+ const client = new TwitterApi({+ appKey: env.X_API_KEY,+ appSecret: env.X_API_SECRET,+ accessToken: env.X_ACCESS_TOKEN,+ accessSecret: env.X_ACCESS_SECRET,+ });+ return method === 'POST' ? client.v2.post(path.replace(/^\//, '')) : client.v2.get(path.replace(/^\//, ''));+}++async function main() {+ const args = parseArgs(process.argv.slice(2));+ const { env, source } = loadCreds();+ const url = args.url || `${appOrigin()}/api/x/webhook`;++ if (!args.dryRun) {+ const missing = KEYS.filter((k) => !env[k]);+ if (missing.length) throw new Error(`missing X credentials (checked process.env and the three-ws-api Cloud Run service): ${missing.join(', ')}`);+ }+ console.log(`webhook URL: ${url}`);+ if (!args.dryRun) console.log(`credential source: ${JSON.stringify(source)}`);+ console.log('');++ if (args.list) {+ const token = await appBearerToken(env, args);+ const result = await bearerCall('GET', '/webhooks', token, args);+ if (result) console.log(JSON.stringify(result, null, 2));+ return;+ }++ if (args.deleteId) {+ const token = await appBearerToken(env, args);+ const result = await bearerCall('DELETE', `/webhooks/${args.deleteId}`, token, args);+ if (result) console.log(JSON.stringify(result, null, 2));+ return;+ }++ const token = await appBearerToken(env, args);+ const registered = await bearerCall('POST', '/webhooks', token, { ...args, body: { url } });+ const webhookId = args.dryRun ? '<webhook_id from the POST /2/webhooks response above>' : registered?.data?.id;+ if (!args.dryRun && !webhookId) throw new Error(`POST /2/webhooks did not return an id: ${JSON.stringify(registered)}`);+ console.log('');++ const subscribed = await oauth1Call('POST', `/account_activity/webhooks/${webhookId}/subscriptions/all`, env, args);+ console.log('');++ if (args.dryRun) {+ console.log('Dry run: no network calls were made.');+ return;+ }+ console.log('Registered webhook:', JSON.stringify(registered, null, 2));+ console.log('Subscribed:', JSON.stringify(subscribed, null, 2));+}++main().catch((err) => {+ console.error(`x-webhook-register failed: ${err?.message || err}`);+ process.exitCode = 1;+});diff --git a/tests/api/x-webhook.test.js b/tests/api/x-webhook.test.jsnew file mode 100644index 000000000..a54b1cd06--- /dev/null+++ b/tests/api/x-webhook.test.js@@ -0,0 +1,195 @@+// Tests for /api/x/webhook: CRC challenge-response, signature verification,+// and dedupe with the mention-polling cron's own insert path. Against the+// REAL x_mention_events migration in an in-process Postgres (PGlite), the+// same pattern tests/x-mention-store.test.js uses, so a column or CHECK this+// handler relies on cannot drift from what production gets.++import { readFileSync } from 'node:fs';+import { createHmac } from 'node:crypto';+import { Readable } from 'node:stream';+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { PGlite } from '@electric-sql/pglite';++vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));++const dbState = { pg: null };++vi.mock('../../api/_lib/db.js', () => {+ const sql = async (strings, ...values) => {+ const text = strings.reduce((acc, part, i) => acc + part + (i < values.length ? `$${i + 1}` : ''), '');+ const out = await dbState.pg.query(text, values);+ return out.rows;+ };+ return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false };+});++const MIG = new URL('../../api/_lib/migrations/', import.meta.url);+const MIGRATION = readFileSync(new URL('20261008170000_x_mention_events.sql', MIG), 'utf8');+const APP_SETTINGS = (() => {+ const src = readFileSync(new URL('20260922210000_free_tier_models.sql', MIG), 'utf8');+ const start = src.indexOf('CREATE TABLE IF NOT EXISTS app_settings');+ return src.slice(start, src.indexOf(');', start) + 2);+})();++beforeEach(async () => {+ dbState.pg = new PGlite();+ await dbState.pg.exec(APP_SETTINGS);+ await dbState.pg.exec(MIGRATION);+});++const SECRET = 'fixture-consumer-secret';+const ORIGINAL_ENV = { ...process.env };++beforeEach(() => {+ process.env = { ...ORIGINAL_ENV };+ process.env.X_WEBHOOK_ENABLED = '1';+ process.env.X_API_SECRET = SECRET;+ process.env.X_API_KEY = 'fixture-app-key';+ process.env.X_ACCESS_TOKEN = '1700000000000000001-fixtureaccesstoken';+ process.env.X_ACCESS_SECRET = 'fixture-access-secret';+ delete process.env.X_COMPANY_HANDLE;+ delete process.env.X_COMPANY_USER_ID;+});++const FIXTURE_PATH = new URL('../fixtures/x-webhook/tweet-create-events.fixture.json', import.meta.url);+const rawFixture = () => readFileSync(FIXTURE_PATH, 'utf8');++function sign(raw, secret = SECRET) {+ return `sha256=${createHmac('sha256', secret).update(raw).digest('base64')}`;+}++function makeReq({ method = 'POST', body = '', headers = {}, query = {} } = {}) {+ const buf = Buffer.from(body, 'utf8');+ const stream = Readable.from(body ? [buf] : []);+ stream.method = method;+ stream.url = '/api/x/webhook';+ stream.query = query;+ stream.headers = {+ 'content-type': 'application/json',+ 'content-length': String(buf.length),+ ...headers,+ };+ return stream;+}++function makeRes() {+ return {+ statusCode: 200,+ _h: {},+ writableEnded: false,+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },+ getHeader(k) { return this._h[k.toLowerCase()]; },+ end(body) { this._body = body; this.writableEnded = true; },+ };+}++async function callWebhook(req, res) {+ const handler = (await import('../../api/x/webhook.js')).default;+ await handler(req, res);+ return { res, body: res._body ? JSON.parse(res._body) : null };+}++async function mentionRow(tweetId) {+ const { getMentionEvent } = await import('../../api/_lib/x-mention-store.js');+ return getMentionEvent(tweetId);+}++describe('GET /api/x/webhook (CRC)', () => {+ it('answers the challenge with HMAC-SHA256(crc_token, consumer secret), base64, sha256= prefixed', async () => {+ const { res, body } = await callWebhook(makeReq({ method: 'GET', query: { crc_token: 'challenge-abc' } }), makeRes());+ expect(res.statusCode).toBe(200);+ expect(body.response_token).toBe(sign('challenge-abc'));+ });++ it('rejects a GET with no crc_token', async () => {+ const { res, body } = await callWebhook(makeReq({ method: 'GET', query: {} }), makeRes());+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('bad_request');+ });+});++describe('POST /api/x/webhook (signature)', () => {+ it('rejects a POST with no signature header', async () => {+ const body = rawFixture();+ const { res, body: out } = await callWebhook(makeReq({ body }), makeRes());+ expect(res.statusCode).toBe(401);+ expect(out.error).toBe('unauthorized');+ expect(await mentionRow('1800000000000000901')).toBeNull();+ });++ it('rejects a tampered body even with a signature present', async () => {+ const real = rawFixture();+ const headers = { 'x-twitter-webhooks-signature': sign(real) };+ const tampered = real.replace('fixture_webhook_author', 'someone_else');+ const { res, body: out } = await callWebhook(makeReq({ body: tampered, headers }), makeRes());+ expect(res.statusCode).toBe(401);+ expect(out.error).toBe('unauthorized');+ });++ it('rejects a signature computed with the wrong secret', async () => {+ const real = rawFixture();+ const headers = { 'x-twitter-webhooks-signature': sign(real, 'wrong-secret') };+ const { res, body: out } = await callWebhook(makeReq({ body: real, headers }), makeRes());+ expect(res.statusCode).toBe(401);+ expect(out.error).toBe('unauthorized');+ });++ it('accepts a correctly signed delivery, records the addressed mention with decision left null, and skips the unaddressed one', async () => {+ const real = rawFixture();+ const headers = { 'x-twitter-webhooks-signature': sign(real) };+ const { res, body: out } = await callWebhook(makeReq({ body: real, headers }), makeRes());+ expect(res.statusCode).toBe(200);+ expect(out).toMatchObject({ ok: true, received: 2, inserted: 2, skipped: 1 });++ const addressed = await mentionRow('1800000000000000901');+ expect(addressed).toMatchObject({+ account_kind: 'company',+ account_ref: 'trythreews',+ author_id: '1700000000000000900',+ author_username: 'fixture_webhook_author',+ dry_run: true,+ decision: null,+ });++ const unaddressed = await mentionRow('1800000000000000902');+ expect(unaddressed).toMatchObject({ intent: 'ignore', decision: 'skip', reason: 'not_addressed' });+ });++ it('acks without reading the body while X_WEBHOOK_ENABLED is unset', async () => {+ delete process.env.X_WEBHOOK_ENABLED;+ const real = rawFixture();+ const headers = { 'x-twitter-webhooks-signature': sign(real) };+ const { res, body: out } = await callWebhook(makeReq({ body: real, headers }), makeRes());+ expect(res.statusCode).toBe(200);+ expect(out).toEqual({ ok: true, disabled: true });+ expect(await mentionRow('1800000000000000901')).toBeNull();+ });+});++describe('dedupe with the mention-polling cron', () => {+ it('a tweet the cron already recorded is a silent no-op for the webhook, and vice versa', async () => {+ const { recordMention } = await import('../../api/_lib/x-mention-store.js');+ const { parseMentionIntent } = await import('../../api/_lib/x-mention-intents.js');+ const { normalizeActivityEvent } = await import('../../api/_lib/x-webhook-events.js');++ const payload = JSON.parse(rawFixture());+ const account = { kind: 'company', ref: 'trythreews', userId: '1700000000000000001', handle: 'trythreews' };+ const mention = normalizeActivityEvent(payload.tweet_create_events[0], account);++ // The cron sees it first (same recordMention() every path shares).+ const parsed = parseMentionIntent(mention, account);+ const first = await recordMention({ mention, parsed, dryRun: true });+ expect(first.inserted).toBe(true);++ // The webhook delivers the same tweet: inserted count for THIS tweet is 0.+ const headers = { 'x-twitter-webhooks-signature': sign(rawFixture()) };+ const { body: out } = await callWebhook(makeReq({ body: rawFixture(), headers }), makeRes());+ // Only the second (unaddressed) event in the fixture is new; the first was already recorded.+ expect(out.inserted).toBe(1);+ expect(out.skipped).toBe(1);++ const row = await mentionRow('1800000000000000901');+ expect(row.decision).toBeNull(); // untouched by the webhook's second, no-op delivery+ });+});diff --git a/tests/fixtures/x-webhook/tweet-create-events.fixture.json b/tests/fixtures/x-webhook/tweet-create-events.fixture.jsonnew file mode 100644index 000000000..e5d43c0bc--- /dev/null+++ b/tests/fixtures/x-webhook/tweet-create-events.fixture.json@@ -0,0 +1,46 @@+{+ "for_user_id": "1700000000000000001",+ "tweet_create_events": [+ {+ "id_str": "1800000000000000901",+ "created_at": "Sun Oct 11 18:30:00 +0000 2026",+ "text": "@trythreews make a red vintage scooter",+ "lang": "en",+ "in_reply_to_status_id_str": null,+ "in_reply_to_user_id_str": null,+ "user": {+ "id_str": "1700000000000000900",+ "screen_name": "fixture_webhook_author",+ "name": "Fixture Webhook Author",+ "profile_image_url_https": "https://pbs.twimg.com/profile_images/fixture.jpg",+ "verified": false+ },+ "entities": {+ "user_mentions": [+ { "id_str": "1700000000000000001", "screen_name": "trythreews", "indices": [0, 11] }+ ],+ "urls": []+ },+ "extended_entities": { "media": [] },+ "is_quote_status": false+ },+ {+ "id_str": "1800000000000000902",+ "created_at": "Sun Oct 11 18:31:00 +0000 2026",+ "text": "anyway, back to my day",+ "lang": "en",+ "in_reply_to_status_id_str": "1800000000000000800",+ "in_reply_to_user_id_str": "1700000000000000800",+ "user": {+ "id_str": "1700000000000000901",+ "screen_name": "fixture_unaddressed_author",+ "name": "Fixture Unaddressed Author",+ "profile_image_url_https": "https://pbs.twimg.com/profile_images/fixture2.jpg",+ "verified": false+ },+ "entities": { "user_mentions": [], "urls": [] },+ "extended_entities": { "media": [] },+ "is_quote_status": false+ }+ ]+}