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-ops): admin console to review, pause, blocklist and send mention-bot replies
nirholas468589f4c721
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex df287c8c7..9e4375c40 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -330,6 +330,7 @@ bottom.| Announcement factory (internal) | Calendar [scripts/announce-plan.mjs](scripts/announce-plan.mjs) `npm run announce:plan`, factory [scripts/announce-kit.mjs](scripts/announce-kit.mjs) `npm run announce:kit`, engine [api/_lib/announce/](api/_lib/announce), ranker [scripts/announce-rank.mjs](scripts/announce-rank.mjs), gate [scripts/check-announce.mjs](scripts/check-announce.mjs), packs [docs/announcements/](docs/announcements/README.md), deferrals [data/announce-deferred.json](data/announce-deferred.json) | Internal, owner-gated · doc [docs/announcement-factory.md](docs/announcement-factory.md) | Works the backlog of shipped surfaces nobody has posted about (322 of 429) into the X content queue, a batch at a time. The calendar is derived from the publisher's own cadence and rotation rules, so it can never promise a slot the scheduler would refuse, and a surface whose frame would carry live third-party market data is flagged for owner approval instead of being quietly packed. Each pack starts as an evidence brief (the rendered live page, the changelog, the docs, the README) whose every fact is already a check the verifier can run; the model chain drafts from that brief and nothing else, and the draft is held against the voice lint, the claims ledger, the evidence list and the account's own archive, then rewritten until it passes. A surface with no route (packages, workers, services) gets a title card typeset from its real README in the site's own fonts, because a post with no image measured 0.875x. Output is a pack plus a queue item at status `draft`: approval and publishing stay exactly where they were. Tests: [tests/announce-factory.test.js](tests/announce-factory.test.js) || X content pipeline (internal) | Queue [data/x-content/queue.json](data/x-content/queue.json), engine [api/_lib/x-content/](api/_lib/x-content), cron [api/cron/x-content.js](api/cron/x-content.js), CLI [scripts/x-content.mjs](scripts/x-content.mjs), media `public/x-media/` | Internal · docs [docs/x-content-pipeline.md](docs/x-content-pipeline.md), [docs/x-story-authoring.md](docs/x-story-authoring.md) | The reviewed @trythreews publishing queue: posts and threads with native images, GIFs, and captioned video, blog or external pages imported as native posts or full X Articles (via the X Articles API), a copy lint against automated-feed tells, jittered cadence with lane rotation, and a database ledger that resumes a half-sent thread instead of reposting. A post's video is a proof reel ([reel.js](api/_lib/x-content/reel.js)): a filmed, passing end-to-end run of its own scenario against production, so a feature that does not work cannot be announced. The queue learns from its own measured results ([outcomes.js](api/_lib/x-content/outcomes.js)), releases filmed posts by policy with a veto window ([approval.js](api/_lib/x-content/approval.js)), and can ship an approved post without a deploy as a signed bundle ([overlay.js](api/_lib/x-content/overlay.js)). Previews only until `X_CONTENT_AUTO_PUBLISH=true`. Tests: [tests/x-content.test.js](tests/x-content.test.js), [x-content-reel](tests/x-content-reel.test.js), [x-content-approval](tests/x-content-approval.test.js), [x-content-outcomes](tests/x-content-outcomes.test.js), [x-content-overlay](tests/x-content-overlay.test.js) || X post archive + engagement analysis (internal) | Snapshots [data/x-archive/](data/x-archive), schema [api/_lib/migrations/20260814120000_x_account_archive.sql](api/_lib/migrations/20260814120000_x_account_archive.sql), normalization + analysis [scripts/x-archive-lib.mjs](scripts/x-archive-lib.mjs), commands [scripts/x-archive-import.mjs](scripts/x-archive-import.mjs) · [scripts/x-archive-refresh.mjs](scripts/x-archive-refresh.mjs) · [scripts/x-archive-analyze.mjs](scripts/x-archive-analyze.mjs), report [docs/x-archive/](docs/x-archive) | Internal · doc [docs/x-archive.md](docs/x-archive.md) | Every post our own X accounts published, kept as raw snapshot files and indexed into `x_account_posts` / `x_account_post_snapshots` so engagement is a measured time series rather than a memory. `npm run x:archive:analyze` regenerates a report ranking posts by engagement and by engagement *rate*, and scores every measurable signal (media, mentions, length, subject, hour) as lift against the corpus median. Two scraper defects are handled rather than inherited: a profile scrape returns reposts of other accounts with `isRetweet: false` (authorship is read from the permalink instead), and X renders like counts lazily so real posts arrive at "0 likes" (those are archived, named, and excluded from the medians until `npm run x:archive:refresh` replaces them with exact X API counters). Distinct from `x_posts`, which is what platform users publish through [api/x/post.js](api/x/post.js). Tests: [tests/x-archive.test.js](tests/x-archive.test.js) |+| X mention-reply bot + operator console | Reader [api/_lib/x-mentions.js](api/_lib/x-mentions.js), pure intent parser [api/_lib/x-mention-intents.js](api/_lib/x-mention-intents.js), ledger [api/_lib/x-mention-store.js](api/_lib/x-mention-store.js) (`x_mention_events`), per-agent decisions endpoint [api/x/mention-decisions.js](api/x/mention-decisions.js) `→ /api/x/mention-decisions`, operator controls [api/_lib/x-mention-admin.js](api/_lib/x-mention-admin.js) (kill switch, blocklist, live-send), console API [api/x/ops/[action].js](api/x/ops/%5Baction%5D.js) `→ /api/x/ops/*`, console page [pages/x-ops.html](pages/x-ops.html) + [src/x-ops.js](src/x-ops.js) + [src/x-ops.css](src/x-ops.css) `→ /x/ops` (admin-only, noindex) | Console: Live (admin-only) | Every `@`-mention of a company or agent X account is parsed into one of seven intents (never treated as an instruction to spend, transfer, launch or post on its own) and recorded once per tweet id before any reply is composed; a reply can be captured dry-run (recorded, never sent) or live. `/x/ops` is the admin review surface over that ledger: filter by account, intent, decision and dry-run status, read the full mention and would-be-reply text, pause or resume the bot (`app_settings` kill switch, also honored via `X_MENTION_BOT_PAUSED`), blocklist or unblock an author, and, for one dry-run `reply` row, send that exact already-composed reply live (company account via OAuth 1.0a, agent account via its own OAuth2 connection) behind an explicit "this posts publicly" confirmation. The enforcement side (the poll cron honoring the kill switch and blocklist before replying) is a separate piece of work; this console only ever writes the switches and ledger rows it is responsible for. Tests: [tests/x-ops-authorization.test.js](tests/x-ops-authorization.test.js) || Interactive 3D history timeline | [pages/timeline.html](pages/timeline.html) `→ /timeline`, [src/timeline.js](src/timeline.js), data [data/timeline.json](data/timeline.json) | Live | three.ws's public history (launches, partnerships, listings, press, product ships) as an explorable 3D scene: 60+ milestones as glowing markers along a curved path, 360° free-orbit or a marker-to-marker Walk mode with a guide beacon (reuses the shared `AnimationManager` + default rig from [src/walk.js](src/walk.js)'s pattern), a synced bottom scrubber, category filters, and a detail panel linking to the original source where one exists (IBM Community, NVIDIA Developer Forums, Yahoo Finance, Phemex, CoinGecko, HackerNoon). Real accessible HTML-list fallback for no-WebGL or fetch-failure. || Upstream resilience toolkit | [scripts/resilience/](scripts/resilience) + [scripts/audit-upstreams.mjs](scripts/audit-upstreams.mjs) `→ npm run audit:upstreams`, baseline [data/upstream-baseline.json](data/upstream-baseline.json), generated map [docs/resilience.md](docs/resilience.md) | Live | Answers the question a fallback alone cannot: when a third-party service is down, what is each endpoint ALLOWED to say? An AST pass grades every outbound call site on five protections (deadline, retry, failover, last-good, breaker) and ratchets against a committed baseline, so a new unbounded call fails the build while the existing tail is paid down at its own pace. On top of it, endpoints declare a degradation contract (`may-serve-stale`, `must-refuse`, `must-not-serve-stale`) that [tests/upstream-degradation.test.js](tests/upstream-degradation.test.js) proves by replacing fetch with a dead upstream and judging the real response. Built after four fallbacks that each passed review turned out to serve remembered data on paths where staleness costs money or grants access. Complements [scripts/check-fetch-timeouts.mjs](scripts/check-fetch-timeouts.mjs), which enforces the deadline floor. Docs: [scripts/resilience/README.md](scripts/resilience/README.md) |diff --git a/api/_lib/x-mention-admin.js b/api/_lib/x-mention-admin.jsnew file mode 100644index 000000000..382854251--- /dev/null+++ b/api/_lib/x-mention-admin.js@@ -0,0 +1,186 @@+// @ts-check+// Operator controls for the X mention bot, read by /x/ops (api/x/ops/[action].js).+//+// Two app_settings keys, both chosen to match the names and value shapes the+// poll cron's guard uses on main (x-mention-guard.js: PAUSE_KEY, BLOCKLIST_KEY)+// so that a future merge of that cron needs no data migration, even though the+// guard itself (the code that reads these keys before replying) does not exist+// on this branch yet. This module only writes the switches; enforcement is out+// of scope here.+//+// x_mention_bot_paused -> { paused: boolean } also honored via env X_MENTION_BOT_PAUSED+// x_mention_blocklist -> { ids: string[] } X author ids, never auto-replied to+//+// The one live-send path lives here too: turning a single captured dry-run+// reply into a real post. "Dry run" on x_mention_events means a reply was+// composed and recorded but never sent; sendDryRunReply posts exactly that+// text (and media, if any) to X, through the same account the mention+// addressed (the company account or one agent's connected account), then+// marks the row live. It never re-derives the reply from the mention text:+// the operator is sending what was already decided, not asking anything new.++import { sql } from './db.js';+import { fetchUpstreamPublic } from './upstream-fetch.js';+import { getMentionEvent, updateDecision } from './x-mention-store.js';+import { postOne, uploadMediaV2, refreshIfNeeded } from './x-post.js';+import { xClientFromEnv } from './x-content/publisher.js';++export const PAUSE_KEY = 'x_mention_bot_paused';+export const BLOCKLIST_KEY = 'x_mention_blocklist';+const MEDIA_FETCH_TIMEOUT_MS = 20_000;+const MEDIA_MAX_BYTES = 20 * 1024 * 1024;++export class MentionAdminError extends Error {+ /** @param {string} message @param {string} code @param {number} [status] */+ constructor(message, code, status = 400) {+ super(message);+ this.name = 'MentionAdminError';+ this.code = code;+ this.status = status;+ }+}++async function readSetting(key) {+ const [row] = await sql`select value from app_settings where key = ${key}`;+ return row?.value ?? null;+}++async function writeSetting(key, value) {+ await sql`+ insert into app_settings (key, value) values (${key}, ${JSON.stringify(value)}::jsonb)+ on conflict (key) do update set value = excluded.value, updated_at = now()+ `;+}++/** Whether the bot is paused right now, per app_settings. */+export async function isPaused() {+ const value = await readSetting(PAUSE_KEY);+ return !!value?.paused;+}++/** Flip the kill switch. The caller (api/x/ops) is responsible for the audit-log entry. */+export async function setPaused(paused) {+ const next = !!paused;+ await writeSetting(PAUSE_KEY, { paused: next, updated_at: new Date().toISOString() });+ return next;+}++/** The blocked X author ids. */+export async function loadBlocklist() {+ const value = await readSetting(BLOCKLIST_KEY);+ const ids = Array.isArray(value?.ids) ? value.ids.map(String).filter(Boolean) : [];+ return [...new Set(ids)];+}++export async function blockAuthor(authorId) {+ const id = String(authorId ?? '').trim();+ if (!id) throw new MentionAdminError('author id required', 'validation_error', 400);+ const ids = await loadBlocklist();+ if (!ids.includes(id)) ids.push(id);+ await writeSetting(BLOCKLIST_KEY, { ids });+ return ids;+}++export async function unblockAuthor(authorId) {+ const id = String(authorId ?? '').trim();+ const ids = (await loadBlocklist()).filter((x) => x !== id);+ await writeSetting(BLOCKLIST_KEY, { ids });+ return ids;+}++function mediaCategoryFor(mimeType) {+ if (mimeType.startsWith('video/')) return 'tweet_video';+ if (mimeType === 'image/gif') return 'tweet_gif';+ return 'tweet_image';+}++/** Fetch a recorded reply_media_url's bytes, SSRF-safe: this URL was written by our own generation pipeline, but it is still an outbound fetch to an operator-triggered address. */+async function fetchReplyMedia(url) {+ const res = await fetchUpstreamPublic(+ url,+ {},+ { name: 'x:ops:media', timeoutMs: MEDIA_FETCH_TIMEOUT_MS, attempts: 1 },+ );+ const contentType = res.headers.get('content-type') || 'image/png';+ const buffer = Buffer.from(await res.arrayBuffer());+ if (buffer.length > MEDIA_MAX_BYTES) throw new MentionAdminError('reply media is too large to send', 'media_too_large', 400);+ return { buffer, mimeType: contentType.split(';')[0].trim() || 'image/png' };+}++/**+ * The posting surface for one mention's account: company (@trythreews, OAuth+ * 1.0a via x-content/publisher.js) or one agent's own connected account+ * (OAuth2 via x-post.js). This is deliberately not publishTweet() in+ * x-post.js: that function enforces a monthly quota, a posting-cadence floor+ * and dedup rules meant for a user choosing to post, none of which apply to+ * sending a bot reply that was already decided and recorded.+ */+async function resolveSendTarget(accountKind, accountRef) {+ if (accountKind === 'company') {+ const client = await xClientFromEnv();+ if (!client) throw new MentionAdminError('the company X account is not configured on this deployment', 'not_configured', 501);+ return {+ async post({ text, replyTo, mediaIds }) {+ const payload = { text };+ if (replyTo) payload.reply = { in_reply_to_tweet_id: replyTo };+ if (mediaIds?.length) payload.media = { media_ids: mediaIds };+ const { data } = await client.tweet(payload);+ return data.id;+ },+ uploadMedia: (buffer, mimeType) => client.uploadMedia(buffer, { media_type: mimeType, media_category: mediaCategoryFor(mimeType) }),+ };+ }+ if (accountKind === 'agent') {+ const [conn] = await sql`+ select agent_id, access_token, refresh_token, expires_at+ from agent_x_connections+ where agent_id = ${accountRef} and disconnected_at is null+ limit 1+ `;+ if (!conn) throw new MentionAdminError(`agent ${accountRef} has no connected X account`, 'not_connected', 400);+ const accessToken = await refreshIfNeeded({ ...conn, source: 'agent' });+ return {+ async post({ text, replyTo, mediaIds }) {+ const data = await postOne({ accessToken, text, replyTo, mediaIds });+ return data.id;+ },+ uploadMedia: (buffer, mimeType) => uploadMediaV2({ accessToken, buffer, mimeType }),+ };+ }+ throw new MentionAdminError(`unknown account kind: ${accountKind}`, 'bad_account', 400);+}++/**+ * Post exactly one already-decided, still-dry-run reply, live. Never derives+ * new reply text: the row's own reply_text and reply_media_url, captured when+ * the bot made its decision, are what goes out.+ *+ * @param {{ tweetId: string }} input+ * @returns {Promise<object>} the updated x_mention_events row+ */+export async function sendDryRunReply({ tweetId }) {+ const row = await getMentionEvent(tweetId);+ if (!row) throw new MentionAdminError('mention not found', 'not_found', 404);+ if (row.decision !== 'reply') throw new MentionAdminError('this mention has no reply queued to send', 'not_sendable', 409);+ if (!row.dry_run || row.reply_tweet_id) throw new MentionAdminError('this reply was already sent live', 'already_sent', 409);+ const text = String(row.reply_text || '').trim();+ if (!text) throw new MentionAdminError('this mention has no reply text to send', 'not_sendable', 409);++ const target = await resolveSendTarget(row.account_kind, row.account_ref);++ let mediaIds = null;+ if (row.reply_media_url) {+ const { buffer, mimeType } = await fetchReplyMedia(row.reply_media_url);+ mediaIds = [await target.uploadMedia(buffer, mimeType)];+ }++ let replyTweetId;+ try {+ replyTweetId = await target.post({ text, replyTo: row.tweet_id, mediaIds });+ } catch (err) {+ await updateDecision(row.tweet_id, { error: `manual send failed: ${String(err?.message || err).slice(0, 2000)}` });+ throw err instanceof MentionAdminError ? err : new MentionAdminError(`send failed: ${err?.message || err}`, 'send_failed', 502);+ }++ return updateDecision(row.tweet_id, { replyTweetId, dryRun: false });+}diff --git a/api/_lib/x-mention-store.js b/api/_lib/x-mention-store.jsindex cf17040af..8d23826b2 100644--- a/api/_lib/x-mention-store.js+++ b/api/_lib/x-mention-store.js@@ -191,3 +191,65 @@ export async function recentDecisions(account, { limit = 50, decision = null, drlimit ${n}`;}++/**+ * Cross-account mention listing for the operator console (/x/ops): every+ * account the bot watches, filterable by account, intent, decision and+ * dry-run status. Unlike recentDecisions (one agent's own settings panel),+ * no account is required: an operator reviews the whole bot, not one agent.+ *+ * @param {{ accountKind?: string|null, accountRef?: string|null, intent?: string|null, decision?: string|null, dryRun?: boolean|null, authorId?: string|null, limit?: number, offset?: number }} [opts]+ */+export async function adminListMentions({+ accountKind = null,+ accountRef = null,+ intent = null,+ decision = null,+ dryRun = null,+ authorId = null,+ limit = 50,+ offset = 0,+} = {}) {+ if (accountKind != null && !ACCOUNT_KINDS.includes(accountKind)) throw new MentionStoreError(`unknown account kind: ${accountKind}`, 'bad_account');+ if (decision != null && !DECISIONS.includes(decision)) throw new MentionStoreError(`unknown decision: ${decision}`, 'bad_decision');+ const n = Math.max(1, Math.min(200, Math.round(Number(limit) || 50)));+ const off = Math.max(0, Math.round(Number(offset) || 0));+ const ref = accountRef != null ? String(accountRef) : null;+ const author = authorId != null ? String(authorId) : null;+ return sql`+ select * from x_mention_events+ where (${accountKind}::text is null or account_kind = ${accountKind})+ and (${ref}::text is null or account_ref = ${ref})+ and (${intent}::text is null or intent = ${intent})+ and (${decision}::text is null or decision = ${decision})+ and (${dryRun}::boolean is null or dry_run = ${dryRun})+ and (${author}::text is null or author_id = ${author})+ order by created_at desc, tweet_id desc+ limit ${n} offset ${off}+ `;+}++/** Count of mentions matching the same filters adminListMentions uses, for pagination. */+export async function adminCountMentions({+ accountKind = null,+ accountRef = null,+ intent = null,+ decision = null,+ dryRun = null,+ authorId = null,+} = {}) {+ if (accountKind != null && !ACCOUNT_KINDS.includes(accountKind)) throw new MentionStoreError(`unknown account kind: ${accountKind}`, 'bad_account');+ if (decision != null && !DECISIONS.includes(decision)) throw new MentionStoreError(`unknown decision: ${decision}`, 'bad_decision');+ const ref = accountRef != null ? String(accountRef) : null;+ const author = authorId != null ? String(authorId) : null;+ const [row] = await sql`+ select count(*)::int as n from x_mention_events+ where (${accountKind}::text is null or account_kind = ${accountKind})+ and (${ref}::text is null or account_ref = ${ref})+ and (${intent}::text is null or intent = ${intent})+ and (${decision}::text is null or decision = ${decision})+ and (${dryRun}::boolean is null or dry_run = ${dryRun})+ and (${author}::text is null or author_id = ${author})+ `;+ return row?.n ?? 0;+}diff --git a/api/x/ops/[action].js b/api/x/ops/[action].jsnew file mode 100644index 000000000..52ac346c7--- /dev/null+++ b/api/x/ops/[action].js@@ -0,0 +1,201 @@+// @ts-check+// X mention-bot operator console API: /api/x/ops/{list,status,pause,resume,block,unblock,send}.+//+// GET /api/x/ops/list?account_kind=&account_ref=&intent=&decision=&dry_run=&author_id=&limit=&offset=+// GET /api/x/ops/status+// POST /api/x/ops/pause+// POST /api/x/ops/resume+// POST /api/x/ops/block { author_id }+// POST /api/x/ops/unblock { author_id }+// POST /api/x/ops/send { tweet_id } (owner action: posts one dry-run reply live)+//+// Admin only, every action: this reads every account's mention text and reply+// content, and `send` can post to X, so requireAdmin runs before anything+// else, including the read-only actions. Mutations also need the double-+// submit CSRF token (requireCsrf) and are attributed in audit_log (logAudit),+// the same combination api/spotlight/[action].js uses for its one admin+// action (moderate).+//+// `send` is the one action that reaches X for real. It only ever posts a+// reply that was already composed and recorded with dry_run = true; nothing+// here re-derives a reply from a mention's text, and a mention's text is+// never treated as an instruction (x-grok design rule 1). The page this API+// serves renders a public-posting confirmation before calling it; this+// handler does not re-confirm, it trusts the admin session and CSRF token the+// same way every other admin mutation on this platform does.++import { cors, error, json, method, readJson, wrap } from '../../_lib/http.js';+import { requireAdmin } from '../../_lib/admin.js';+import { requireCsrf } from '../../_lib/csrf.js';+import { logAudit } from '../../_lib/audit.js';+import { ACCOUNT_KINDS, DECISIONS, MentionStoreError, adminCountMentions, adminListMentions } from '../../_lib/x-mention-store.js';+import { INTENTS } from '../../_lib/x-mention-intents.js';+import {+ MentionAdminError,+ blockAuthor,+ isPaused,+ loadBlocklist,+ sendDryRunReply,+ setPaused,+ unblockAuthor,+} from '../../_lib/x-mention-admin.js';++function mentionRow(r) {+ return {+ tweet_id: r.tweet_id,+ account_kind: r.account_kind,+ account_ref: r.account_ref,+ author_id: r.author_id,+ author_username: r.author_username,+ mention_text: r.mention_text,+ intent: r.intent,+ decision: r.decision,+ reason: r.reason,+ reply_text: r.reply_text,+ reply_media_url: r.reply_media_url,+ reply_link: r.reply_link,+ reply_tweet_id: r.reply_tweet_id,+ dry_run: r.dry_run,+ error: r.error,+ created_at: r.created_at,+ decided_at: r.decided_at,+ replied_at: r.replied_at,+ };+}++function parseBool(v) {+ if (v == null || v === '') return null;+ return v === '1' || v === 'true';+}++// ── reads ────────────────────────────────────────────────────────────────────++/** GET /api/x/ops/list */+async function handleList(req, res) {+ const url = new URL(req.url, 'http://x');+ const q = url.searchParams;+ const accountKind = q.get('account_kind') || null;+ if (accountKind != null && !ACCOUNT_KINDS.includes(accountKind)) {+ return error(res, 400, 'validation_error', `account_kind must be one of ${ACCOUNT_KINDS.join(', ')}`);+ }+ const intent = q.get('intent') || null;+ if (intent != null && !INTENTS.includes(intent)) {+ return error(res, 400, 'validation_error', `intent must be one of ${INTENTS.join(', ')}`);+ }+ const decision = q.get('decision') || null;+ if (decision != null && !DECISIONS.includes(decision)) {+ return error(res, 400, 'validation_error', `decision must be one of ${DECISIONS.join(', ')}`);+ }+ const filters = {+ accountKind,+ accountRef: q.get('account_ref') || null,+ intent,+ decision,+ dryRun: parseBool(q.get('dry_run')),+ authorId: q.get('author_id') || null,+ };+ const limit = Math.min(Math.max(Number(q.get('limit')) || 50, 1), 200);+ const offset = Math.max(Number(q.get('offset')) || 0, 0);++ const [rows, total] = await Promise.all([+ adminListMentions({ ...filters, limit, offset }),+ adminCountMentions(filters),+ ]);+ return json(res, 200, { mentions: rows.map(mentionRow), total, limit, offset });+}++/** GET /api/x/ops/status: the kill switch and blocklist, for the console's header. */+async function handleStatus(_req, res) {+ const [paused, blocklist] = await Promise.all([isPaused(), loadBlocklist()]);+ return json(res, 200, { paused, blocklist });+}++// ── mutations ────────────────────────────────────────────────────────────────++/** POST /api/x/ops/pause */+async function handlePause(req, res, admin) {+ if (!(await requireCsrf(req, res, admin.id))) return;+ await setPaused(true);+ logAudit({ userId: admin.id, action: 'x_mention_bot_pause', req });+ return json(res, 200, { paused: true });+}++/** POST /api/x/ops/resume */+async function handleResume(req, res, admin) {+ if (!(await requireCsrf(req, res, admin.id))) return;+ await setPaused(false);+ logAudit({ userId: admin.id, action: 'x_mention_bot_resume', req });+ return json(res, 200, { paused: false });+}++/** POST /api/x/ops/block { author_id } */+async function handleBlock(req, res, admin) {+ if (!(await requireCsrf(req, res, admin.id))) return;+ const body = await readJson(req).catch(() => null);+ const authorId = String(body?.author_id || '').trim();+ if (!authorId) return error(res, 400, 'validation_error', 'author_id is required');+ const blocklist = await blockAuthor(authorId);+ logAudit({ userId: admin.id, action: 'x_mention_block_author', resourceId: authorId, req });+ return json(res, 200, { blocklist });+}++/** POST /api/x/ops/unblock { author_id } */+async function handleUnblock(req, res, admin) {+ if (!(await requireCsrf(req, res, admin.id))) return;+ const body = await readJson(req).catch(() => null);+ const authorId = String(body?.author_id || '').trim();+ if (!authorId) return error(res, 400, 'validation_error', 'author_id is required');+ const blocklist = await unblockAuthor(authorId);+ logAudit({ userId: admin.id, action: 'x_mention_unblock_author', resourceId: authorId, req });+ return json(res, 200, { blocklist });+}++/**+ * POST /api/x/ops/send { tweet_id }+ * The owner action: posts one dry-run reply to X for real. The confirmation+ * (what this will post, and to whom) is rendered by the page before this is+ * ever called; this is the step that actually reaches X.+ */+async function handleSend(req, res, admin) {+ if (!(await requireCsrf(req, res, admin.id))) return;+ const body = await readJson(req).catch(() => null);+ const tweetId = String(body?.tweet_id || '').trim();+ if (!tweetId) return error(res, 400, 'validation_error', 'tweet_id is required');+ const row = await sendDryRunReply({ tweetId });+ logAudit({ userId: admin.id, action: 'x_mention_send_live', resourceId: tweetId, req });+ return json(res, 200, { mention: mentionRow(row) });+}++// ── dispatcher ───────────────────────────────────────────────────────────────++const DISPATCH = {+ list: { methods: ['GET'], fn: handleList },+ status: { methods: ['GET'], fn: handleStatus },+ pause: { methods: ['POST'], fn: handlePause },+ resume: { methods: ['POST'], fn: handleResume },+ block: { methods: ['POST'], fn: handleBlock },+ unblock: { methods: ['POST'], fn: handleUnblock },+ send: { methods: ['POST'], fn: handleSend },+};++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;++ const action = req.query?.action ?? new URL(req.url, 'http://x').pathname.split('/').pop();+ const route = DISPATCH[action];+ if (!route) return error(res, 404, 'not_found', `unknown x ops action: ${action}`);+ if (!method(req, res, route.methods)) return;++ // Admin before anything else, including the read-only actions: this console+ // shows every account's mention and reply text, and `send` can post to X.+ const admin = await requireAdmin(req, res);+ if (!admin) return;++ try {+ return await route.fn(req, res, admin);+ } catch (err) {+ if (err instanceof MentionAdminError) return error(res, err.status, err.code, err.message);+ if (err instanceof MentionStoreError) return error(res, 400, err.code, err.message);+ throw err;+ }+});diff --git a/pages/x-ops.html b/pages/x-ops.htmlnew file mode 100644index 000000000..5c4b848b0--- /dev/null+++ b/pages/x-ops.html@@ -0,0 +1,90 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot - no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>X mention bot console · three.ws</title>+ <meta name="description" content="Internal operator console for the X mention-reply bot: review dry-run replies, pause the bot, blocklist an author, or send one reply live." />+ <meta name="robots" content="noindex, nofollow" />+ <meta name="theme-color" content="#0a0a0a" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/x-ops.css" />+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="xo-shell" id="xo-app">+ <div class="xo-head">+ <div>+ <p class="xo-kicker"><span class="xo-dot" id="xo-status-dot" aria-hidden="true"></span> X mention bot</p>+ <h1 class="xo-title">Operator console</h1>+ </div>+ <div class="xo-head-meta">+ <span id="xo-status-text" aria-live="polite">loading…</span>+ <button type="button" class="xo-btn" id="xo-toggle-pause">Pause bot</button>+ <span id="xo-updated" aria-live="polite"></span>+ <button type="button" class="xo-btn" id="xo-refresh">Refresh</button>+ </div>+ </div>++ <div class="xo-body">+ <nav class="xo-rail" id="xo-rail" aria-label="Mention filters">+ <p class="xo-rail-head">Lanes</p>+ </nav>++ <section class="xo-panel" aria-label="Mention events">+ <div class="xo-panel-head">+ <h2 class="xo-panel-title" id="xo-lane-title">All mentions</h2>+ <div class="xo-filters">+ <select class="xo-select" id="xo-filter-account" aria-label="Account">+ <option value="">Every account</option>+ <option value="company">Company (@trythreews)</option>+ <option value="agent">Agent accounts</option>+ </select>+ <select class="xo-select" id="xo-filter-intent" aria-label="Intent">+ <option value="">Every intent</option>+ </select>+ <input class="xo-input" id="xo-filter-author" type="text" placeholder="author id" aria-label="Author id" autocomplete="off" />+ </div>+ </div>+ <div class="xo-scroll">+ <table class="xo-table">+ <thead>+ <tr>+ <th scope="col">When</th>+ <th scope="col">Account</th>+ <th scope="col">Author</th>+ <th scope="col">Intent</th>+ <th scope="col">Decision</th>+ <th scope="col">Reply</th>+ </tr>+ </thead>+ <tbody id="xo-rows"></tbody>+ </table>+ </div>+ <div class="xo-panel-foot">+ <button type="button" class="xo-btn" id="xo-load-more">Load more</button>+ </div>+ </section>+ </div>+ </main>++ <div class="xo-drawer-scrim" id="xo-scrim" data-open="false"></div>+ <aside class="xo-drawer" id="xo-drawer" data-open="false" aria-hidden="true" aria-label="Mention detail">+ <div class="xo-drawer-head">+ <h2 class="xo-drawer-title" id="xo-drawer-title">Mention</h2>+ <button type="button" class="xo-btn" id="xo-close" style="margin-left:auto">Close</button>+ </div>+ <div class="xo-drawer-body" id="xo-drawer-body"></div>+ </aside>++ <script type="module" src="/src/x-ops.js"></script>+ <script type="module" src="/i18n.js"></script>+ </body>+</html>diff --git a/src/x-ops.css b/src/x-ops.cssnew file mode 100644index 000000000..aeb807a87--- /dev/null+++ b/src/x-ops.css@@ -0,0 +1,464 @@+/* X mention bot operator console: /x/ops.+ An internal tool, modeled on /materialize/ops. An admin reviews what the+ mention-reply bot decided and can pause it, blocklist an author, or send one+ already-composed dry-run reply live. Every value comes from public/tokens.css. */++.xo-shell {+ max-width: 1400px;+ margin: 0 auto;+ padding: var(--space-6, 24px) var(--space-6, 24px) var(--space-2xl, 68px);+}++/* ── header ──────────────────────────────────────────────────────────────── */++.xo-head {+ display: flex;+ flex-wrap: wrap;+ align-items: baseline;+ gap: var(--space-3, 12px) var(--space-5, 20px);+ padding-bottom: var(--space-4, 16px);+ border-bottom: 1px solid var(--color-hairline);+}++.xo-kicker {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ margin: 0;+ font-family: var(--font-mono);+ font-size: var(--text-2xs, 11px);+ letter-spacing: 0.12em;+ text-transform: uppercase;+ color: var(--color-text-dim);+}++.xo-dot {+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: var(--color-success);+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-success) 22%, transparent);+}++.xo-dot[data-paused='true'] {+ background: var(--color-danger);+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-danger) 22%, transparent);+}++.xo-title {+ margin: 0;+ font-family: var(--font-display);+ font-size: var(--text-xl, 26px);+ font-weight: var(--weight-semibold, 600);+ color: var(--color-text-bright);+}++.xo-head-meta {+ margin-left: auto;+ display: flex;+ align-items: center;+ gap: var(--space-3, 12px);+ font-size: var(--text-sm, 12px);+ color: var(--color-text-dim);+}++/* ── layout ──────────────────────────────────────────────────────────────── */++.xo-body {+ display: grid;+ grid-template-columns: 220px minmax(0, 1fr);+ gap: var(--space-6, 24px);+ margin-top: var(--space-5, 20px);+ align-items: start;+}++@media (max-width: 900px) {+ .xo-body { grid-template-columns: minmax(0, 1fr); }+ .xo-rail { position: static; }+}++/* ── lane rail ────────────────────────────────────────────────────────────── */++.xo-rail {+ position: sticky;+ top: calc(var(--header-h, 3.5rem) + 12px);+ display: flex;+ flex-direction: column;+ gap: 2px;+}++.xo-rail-head {+ margin: 0 0 var(--space-2, 8px);+ font-family: var(--font-mono);+ font-size: var(--text-2xs, 11px);+ letter-spacing: 0.1em;+ text-transform: uppercase;+ color: var(--color-text-faint);+}++.xo-rail-btn {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-2, 8px);+ width: 100%;+ padding: 7px 10px;+ border: 1px solid transparent;+ border-radius: var(--radius-md, 10px);+ background: transparent;+ color: var(--color-text-dim);+ font: inherit;+ font-size: var(--text-md, 13px);+ text-align: left;+ cursor: pointer;+ transition: background var(--dur-fast, var(--duration-fast)) var(--ease-out, var(--ease-standard)),+ color var(--dur-fast, var(--duration-fast)) var(--ease-out, var(--ease-standard)),+ border-color var(--dur-fast, var(--duration-fast)) var(--ease-out, var(--ease-standard));+}++.xo-rail-btn:hover { background: var(--color-surface); color: var(--color-text); }+.xo-rail-btn:active { transform: translateY(1px); }+.xo-rail-btn:focus-visible {+ outline: 2px solid var(--color-accent);+ outline-offset: 2px;+}+.xo-rail-btn[aria-pressed='true'] {+ background: var(--color-surface-2);+ border-color: var(--color-border);+ color: var(--color-text-bright);+ font-weight: var(--weight-medium, 500);+}++/* ── mention table ───────────────────────────────────────────────────────── */++.xo-panel {+ border: 1px solid var(--color-border);+ border-radius: var(--radius-lg, 14px);+ background: var(--color-surface);+ overflow: hidden;+}++.xo-panel-head {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: var(--space-3, 12px);+ padding: var(--space-3, 12px) var(--space-4, 16px);+ border-bottom: 1px solid var(--color-hairline);+}++.xo-panel-title {+ margin: 0;+ font-family: var(--font-display);+ font-size: var(--text-ui, 14px);+ font-weight: var(--weight-semibold, 600);+ color: var(--color-text-bright);+}++.xo-filters {+ margin-left: auto;+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-2, 8px);+}++.xo-panel-foot {+ display: flex;+ justify-content: center;+ padding: var(--space-3, 12px);+ border-top: 1px solid var(--color-hairline);+}++.xo-scroll { overflow-x: auto; }++.xo-table {+ width: 100%;+ border-collapse: collapse;+ font-size: var(--text-md, 13px);+}++.xo-table th {+ padding: 10px var(--space-4, 16px);+ text-align: left;+ font-family: var(--font-mono);+ font-size: var(--text-2xs, 11px);+ font-weight: var(--weight-regular, 400);+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: var(--color-text-faint);+ border-bottom: 1px solid var(--color-hairline);+ white-space: nowrap;+}++.xo-table td {+ padding: 11px var(--space-4, 16px);+ border-bottom: 1px solid var(--color-hairline);+ color: var(--color-text);+ max-width: 360px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.xo-row { cursor: pointer; transition: background var(--dur-fast, var(--duration-fast)) var(--ease-out, var(--ease-standard)); }+.xo-row:hover { background: var(--color-surface-2); }+.xo-row:focus-visible { outline: 2px solid var(--color-accent); outline-offset: -2px; }+.xo-row[aria-selected='true'] { background: var(--color-surface-2); }+.xo-table tbody tr:last-child td { border-bottom: 0; }++.xo-mono {+ font-family: var(--font-mono);+ font-size: var(--text-2xs, 11px);+ color: var(--color-text-dim);+ font-variant-numeric: tabular-nums;+}++/* ── decision pill ───────────────────────────────────────────────────────── */++.xo-pill {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 3px 9px;+ border: 1px solid var(--color-border);+ border-radius: var(--radius-pill, 999px);+ font-family: var(--font-mono);+ font-size: var(--text-2xs, 11px);+ letter-spacing: 0.04em;+ color: var(--color-text-dim);+ background: var(--color-surface);+}++.xo-pill::before {+ content: '';+ width: 5px;+ height: 5px;+ border-radius: 50%;+ background: currentColor;+}++.xo-pill[data-decision='reply'] { color: var(--color-success); border-color: color-mix(in srgb, var(--color-success) 35%, transparent); }+.xo-pill[data-decision='pending'] { color: var(--wallet-accent, #c4b5fd); border-color: color-mix(in srgb, var(--wallet-accent, #c4b5fd) 35%, transparent); }+.xo-pill[data-decision='skip'],+.xo-pill[data-decision='paused'] { color: var(--color-text-faint); }+.xo-pill[data-decision='rate_limited'],+.xo-pill[data-decision='budget'],+.xo-pill[data-decision='unsafe'] { color: var(--color-warning); border-color: color-mix(in srgb, var(--color-warning) 35%, transparent); }+.xo-pill[data-decision='error'] { color: var(--color-danger); border-color: color-mix(in srgb, var(--color-danger) 35%, transparent); }++.xo-dryrun-tag {+ margin-left: 6px;+ font-family: var(--font-mono);+ font-size: var(--text-2xs, 11px);+ color: var(--color-text-faint);+}++/* ── states ──────────────────────────────────────────────────────────────── */++.xo-state {+ padding: var(--space-8, 32px) var(--space-4, 16px);+ text-align: center;+ color: var(--color-text-dim);+ font-size: var(--text-md, 13px);+ line-height: var(--leading-normal, 1.618);+}++.xo-state strong {+ display: block;+ margin-bottom: 6px;+ color: var(--color-text-bright);+ font-size: var(--text-ui, 14px);+ font-weight: var(--weight-semibold, 600);+}++.xo-skeleton {+ height: 41px;+ border-bottom: 1px solid var(--color-hairline);+ background: linear-gradient(90deg, transparent, var(--color-surface-2), transparent);+ background-size: 200% 100%;+ animation: xo-shimmer 1.4s ease-in-out infinite;+}++@keyframes xo-shimmer {+ 0% { background-position: 200% 0; }+ 100% { background-position: -200% 0; }+}++@media (prefers-reduced-motion: reduce) {+ .xo-skeleton { animation: none; background: var(--color-surface-2); }+ .xo-drawer { transition: none; }+}++/* ── detail drawer ───────────────────────────────────────────────────────── */++.xo-drawer-scrim {+ position: fixed;+ inset: 0;+ background: rgba(0, 0, 0, 0.5);+ opacity: 0;+ pointer-events: none;+ transition: opacity var(--dur-med, var(--duration-base)) var(--ease-out, var(--ease-standard));+ z-index: 300;+}++.xo-drawer-scrim[data-open='true'] { opacity: 1; pointer-events: auto; }++.xo-drawer {+ position: fixed;+ top: 0;+ right: 0;+ bottom: 0;+ width: min(560px, 100vw);+ display: flex;+ flex-direction: column;+ background: var(--bg-1, #1a1a1a);+ border-left: 1px solid var(--color-border);+ transform: translateX(100%);+ transition: transform var(--dur-med, var(--duration-base)) var(--ease-out, var(--ease-standard));+ z-index: 301;+ overflow: hidden;+}++.xo-drawer[data-open='true'] { transform: translateX(0); }++.xo-drawer-head {+ display: flex;+ align-items: center;+ gap: var(--space-3, 12px);+ padding: var(--space-4, 16px);+ border-bottom: 1px solid var(--color-hairline);+}++.xo-drawer-title {+ margin: 0;+ font-family: var(--font-display);+ font-size: var(--text-ui, 14px);+ font-weight: var(--weight-semibold, 600);+ color: var(--color-text-bright);+}++.xo-drawer-body {+ flex: 1;+ overflow-y: auto;+ padding: var(--space-4, 16px);+ display: flex;+ flex-direction: column;+ gap: var(--space-5, 20px);+}++.xo-section-title {+ margin: 0 0 var(--space-2, 8px);+ font-family: var(--font-mono);+ font-size: var(--text-2xs, 11px);+ letter-spacing: 0.1em;+ text-transform: uppercase;+ color: var(--color-text-faint);+}++.xo-kv {+ display: grid;+ grid-template-columns: 110px minmax(0, 1fr);+ gap: 6px var(--space-3, 12px);+ font-size: var(--text-md, 13px);+}++.xo-kv dt { color: var(--color-text-faint); }+.xo-kv dd { margin: 0; color: var(--color-text); overflow-wrap: anywhere; }++.xo-quote {+ margin: 0;+ padding: var(--space-3, 12px);+ border: 1px solid var(--color-hairline);+ border-radius: var(--radius-md, 10px);+ background: var(--color-bg);+ color: var(--color-text);+ font-size: var(--text-md, 13px);+ line-height: var(--leading-normal, 1.618);+ overflow-wrap: anywhere;+ white-space: pre-wrap;+}++.xo-media {+ max-width: 100%;+ border-radius: var(--radius-md, 10px);+ border: 1px solid var(--color-hairline);+}++/* ── controls ────────────────────────────────────────────────────────────── */++.xo-actions { display: flex; flex-wrap: wrap; gap: var(--space-2, 8px); }++.xo-btn {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 7px 13px;+ border: 1px solid var(--color-border);+ border-radius: var(--radius-md, 10px);+ background: var(--color-surface);+ color: var(--color-text);+ font: inherit;+ font-size: var(--text-md, 13px);+ text-decoration: none;+ cursor: pointer;+ transition: background var(--dur-fast, var(--duration-fast)) var(--ease-out, var(--ease-standard)),+ border-color var(--dur-fast, var(--duration-fast)) var(--ease-out, var(--ease-standard)),+ transform var(--dur-fast, var(--duration-fast)) var(--ease-out, var(--ease-standard));+}++.xo-btn:hover:not(:disabled) { background: var(--color-surface-2); border-color: var(--color-border-strong); }+.xo-btn:active:not(:disabled) { transform: translateY(1px); }+.xo-btn:focus-visible { outline: 2px solid var(--color-accent); outline-offset: 2px; }+.xo-btn:disabled { opacity: 0.45; cursor: not-allowed; }++.xo-btn-primary {+ background: var(--color-text-bright);+ border-color: var(--color-text-bright);+ color: var(--bg-0, #0a0a0a);+ font-weight: var(--weight-medium, 500);+}+.xo-btn-primary:hover:not(:disabled) { background: var(--color-text); border-color: var(--color-text); }++.xo-btn-danger { color: var(--color-danger); border-color: color-mix(in srgb, var(--color-danger) 40%, transparent); }+.xo-btn-danger:hover:not(:disabled) { background: color-mix(in srgb, var(--color-danger) 12%, transparent); }++.xo-select,+.xo-input {+ box-sizing: border-box;+ padding: 7px 10px;+ border: 1px solid var(--color-border);+ border-radius: var(--radius-md, 10px);+ background: var(--color-bg);+ color: var(--color-text);+ font: inherit;+ font-size: var(--text-sm, 12px);+}++.xo-select:focus,+.xo-input:focus {+ outline: 2px solid var(--color-accent);+ outline-offset: 1px;+ border-color: var(--color-border-strong);+}++.xo-note {+ margin: 0;+ min-height: 1.2em;+ font-size: var(--text-md, 13px);+ color: var(--color-text-dim);+}++.xo-note[data-tone='error'] { color: var(--color-danger); }+.xo-note[data-tone='ok'] { color: var(--color-success); }++.xo-warning {+ margin: 0;+ padding: var(--space-3, 12px);+ border: 1px solid color-mix(in srgb, var(--color-warning) 40%, transparent);+ border-radius: var(--radius-md, 10px);+ background: color-mix(in srgb, var(--color-warning) 8%, transparent);+ font-size: var(--text-md, 13px);+ color: var(--color-text);+}++.xo-warning strong { color: var(--color-text-bright); }diff --git a/src/x-ops.js b/src/x-ops.jsnew file mode 100644index 000000000..8dcea6ce8--- /dev/null+++ b/src/x-ops.js@@ -0,0 +1,426 @@+// X mention bot operator console: /x/ops.+//+// A client of /api/x/ops/*, never a gate in front of it: every action+// authorizes server-side (requireAdmin), so this file owes the real admin+// speed and accurate state, nothing more. Two rules follow:+//+// - The list reloads after every mutation, so what the admin sees is what+// the database holds. An admin deciding whether to send a reply live+// needs the current row, not a stale optimistic one.+// - `send` is the one action that posts to X for real. It gets its own+// confirm() naming the account and the exact text, on top of the+// page-level "posts publicly" warning in the drawer, because this is the+// one button on this console an admin must never click by habit.++import { apiFetch } from './api.js';++// Mirrors INTENTS in api/_lib/x-mention-intents.js. Kept as a plain list here+// rather than importing that module: it is server-only (reached through+// api/_lib), and the intent set changes rarely enough that duplicating seven+// short strings costs less than pulling a server module into this bundle.+const INTENTS = ['make', 'image3d', 'avatar', 'help', 'launch', 'chat', 'ignore'];++const shell = document.getElementById('xo-app');+const railEl = document.getElementById('xo-rail');+const tableBody = document.getElementById('xo-rows');+const laneTitle = document.getElementById('xo-lane-title');+const refreshBtn = document.getElementById('xo-refresh');+const loadMoreBtn = document.getElementById('xo-load-more');+const updatedEl = document.getElementById('xo-updated');+const statusDot = document.getElementById('xo-status-dot');+const statusText = document.getElementById('xo-status-text');+const togglePauseBtn = document.getElementById('xo-toggle-pause');+const filterAccount = document.getElementById('xo-filter-account');+const filterIntent = document.getElementById('xo-filter-intent');+const filterAuthor = document.getElementById('xo-filter-author');+const drawer = document.getElementById('xo-drawer');+const scrim = document.getElementById('xo-scrim');+const drawerBody = document.getElementById('xo-drawer-body');+const drawerTitle = document.getElementById('xo-drawer-title');+const closeBtn = document.getElementById('xo-close');++filterIntent.innerHTML += INTENTS.map((i) => `<option value="${i}">${i}</option>`).join('');++// The lanes an admin reviews, in the order they matter: a reply still in dry+// run is the thing that might need sending; a live reply and a skip are+// history. Account/intent/author filters stack on top of whichever lane is+// active.+const RAIL = [+ { key: 'all', label: 'All mentions', decision: null, dryRun: null },+ { key: 'review', label: 'Awaiting send', decision: 'reply', dryRun: true },+ { key: 'sent', label: 'Sent live', decision: 'reply', dryRun: false },+ { key: 'skip', label: 'Skipped', decision: 'skip', dryRun: null },+ { key: 'blocked', label: 'Paused / blocked', decision: 'paused', dryRun: null },+ { key: 'error', label: 'Errors', decision: 'error', dryRun: null },+];++let activeLane = RAIL[0];+let rows = [];+let total = 0;+let offset = 0;+const PAGE = 50;+let openTweetId = null;+let lastFocused = null;+let botPaused = false;+let blocklist = [];++const esc = (v) =>+ String(v ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);++function fmtDate(value) {+ if (!value) return 'not yet';+ const d = new Date(value);+ if (Number.isNaN(d.getTime())) return 'unknown';+ return d.toISOString().slice(0, 16).replace('T', ' ');+}++function shortText(v, max = 80) {+ const s = String(v || '');+ return s.length > max ? `${s.slice(0, max)}…` : s;+}++async function api(path, options = {}) {+ const res = await apiFetch(`/api/x/ops/${path}`, {+ ...options,+ headers: options.body ? { 'content-type': 'application/json', ...(options.headers || {}) } : options.headers,+ });+ let body = null;+ try {+ body = await res.json();+ } catch {+ body = null;+ }+ if (!res.ok) {+ const err = new Error(body?.error_description || body?.error || `request failed (${res.status})`);+ err.status = res.status;+ throw err;+ }+ return body;+}++// ── status + rail ────────────────────────────────────────────────────────────++function renderStatus() {+ statusDot.dataset.paused = String(botPaused);+ statusText.textContent = botPaused ? 'Bot paused' : 'Bot live';+ togglePauseBtn.textContent = botPaused ? 'Resume bot' : 'Pause bot';+}++async function loadStatus() {+ try {+ const data = await api('status');+ botPaused = !!data.paused;+ blocklist = data.blocklist || [];+ renderStatus();+ } catch {+ statusText.textContent = 'status unknown';+ }+}++function renderRail() {+ railEl.innerHTML =+ `<p class="xo-rail-head">Lanes</p>` ++ RAIL.map(+ (lane) => `<button type="button" class="xo-rail-btn" data-lane="${lane.key}" aria-pressed="${lane.key === activeLane.key}">+ <span>${esc(lane.label)}</span>+ </button>`,+ ).join('');+}++// ── the list ─────────────────────────────────────────────────────────────────++function decisionPill(r) {+ const label = r.decision === 'reply' && r.dry_run ? 'reply (dry run)' : r.decision === 'reply' ? 'replied' : r.decision || 'pending';+ return `<span class="xo-pill" data-decision="${esc(r.decision)}">${esc(label)}</span>`;+}++function skeletonRows(n = 6) {+ tableBody.innerHTML = `<tr><td colspan="6" style="padding:0">${'<div class="xo-skeleton"></div>'.repeat(n)}</td></tr>`;+}++function emptyState() {+ tableBody.innerHTML = `<tr><td colspan="6"><div class="xo-state">+ <strong>Nothing in ${esc(activeLane.label.toLowerCase())}</strong>+ Pick another lane, or widen the account/intent/author filters above the table.+ </div></td></tr>`;+}++function errorState(err) {+ const denied = err.status === 403 || err.status === 401;+ const body = denied+ ? `<strong>You are not signed in as an admin</strong>Sign in with a platform admin wallet to open this console.`+ : err.status === 503+ ? `<strong>The console needs a configured database</strong>This deployment has no <code>DATABASE_URL</code>, so there is nothing to show.`+ : `<strong>Could not load mentions</strong>${esc(err.message)}`;+ tableBody.innerHTML = `<tr><td colspan="6"><div class="xo-state">${body}</div></td></tr>`;+}++function currentFilters() {+ return {+ account_kind: filterAccount.value || '',+ intent: filterIntent.value || '',+ author_id: filterAuthor.value.trim() || '',+ decision: activeLane.decision || '',+ dry_run: activeLane.dryRun == null ? '' : activeLane.dryRun ? '1' : '0',+ };+}++function rowHtml(r) {+ return `<tr class="xo-row" tabindex="0" role="button" data-id="${esc(r.tweet_id)}"+ aria-selected="${r.tweet_id === openTweetId}" aria-label="Mention from ${esc(r.author_username || r.author_id)}, ${esc(r.decision)}">+ <td class="xo-mono">${esc(fmtDate(r.created_at))}</td>+ <td>${esc(r.account_kind)}${r.account_kind === 'agent' ? ` <span class="xo-mono">${esc(r.account_ref.slice ? r.account_ref.slice(0, 8) : r.account_ref)}</span>` : ''}</td>+ <td>@${esc(r.author_username || r.author_id)}</td>+ <td>${esc(r.intent || '-')}</td>+ <td>${decisionPill(r)}</td>+ <td>${esc(shortText(r.reply_text || r.reason || ''))}</td>+ </tr>`;+}++async function loadList({ reset = true } = {}) {+ laneTitle.textContent = activeLane.label;+ if (reset) {+ offset = 0;+ skeletonRows();+ }+ try {+ const params = new URLSearchParams();+ const filters = currentFilters();+ for (const [k, v] of Object.entries(filters)) if (v) params.set(k, v);+ params.set('limit', String(PAGE));+ params.set('offset', String(offset));+ const data = await api(`list?${params.toString()}`);+ total = data.total || 0;+ rows = reset ? data.mentions : [...rows, ...data.mentions];+ updatedEl.textContent = `updated ${new Date().toLocaleTimeString()}`;+ if (!rows.length) return emptyState();+ tableBody.innerHTML = rows.map(rowHtml).join('');+ loadMoreBtn.style.display = rows.length < total ? '' : 'none';+ } catch (err) {+ errorState(err);+ updatedEl.textContent = '';+ }+}++// ── the drawer ───────────────────────────────────────────────────────────────++function openDrawer(tweetId) {+ lastFocused = document.activeElement;+ openTweetId = tweetId;+ drawer.dataset.open = 'true';+ scrim.dataset.open = 'true';+ drawer.setAttribute('aria-hidden', 'false');+ drawerTitle.textContent = `Mention ${tweetId}`;+ closeBtn.focus();+ renderDrawer();+}++function closeDrawer() {+ openTweetId = null;+ drawer.dataset.open = 'false';+ scrim.dataset.open = 'false';+ drawer.setAttribute('aria-hidden', 'true');+ drawerBody.innerHTML = '';+ if (lastFocused && document.contains(lastFocused)) lastFocused.focus();+ for (const row of tableBody.querySelectorAll('.xo-row')) row.setAttribute('aria-selected', 'false');+}++function mediaHtml(url) {+ if (!url) return '';+ const isVideo = /\.(mp4|mov|webm)(\?|$)/i.test(url);+ return isVideo+ ? `<video class="xo-media" src="${esc(url)}" controls></video>`+ : `<img class="xo-media" src="${esc(url)}" alt="Reply media" loading="lazy" />`;+}++function drawerHtml(r) {+ const blocked = blocklist.includes(String(r.author_id));+ const canSend = r.decision === 'reply' && r.dry_run && !r.reply_tweet_id;+ return `+ <section>+ <h3 class="xo-section-title">Mention</h3>+ <dl class="xo-kv">+ <dt>Tweet</dt><dd class="xo-mono">${esc(r.tweet_id)}</dd>+ <dt>Account</dt><dd>${esc(r.account_kind)} · ${esc(r.account_ref)}</dd>+ <dt>Author</dt><dd>@${esc(r.author_username || r.author_id)} <span class="xo-mono">${esc(r.author_id)}</span>${blocked ? ' (blocked)' : ''}</dd>+ <dt>Intent</dt><dd>${esc(r.intent || '-')}</dd>+ <dt>Decision</dt><dd>${decisionPill(r)}</dd>+ <dt>Reason</dt><dd>${esc(r.reason || 'none recorded')}</dd>+ <dt>When</dt><dd>${esc(fmtDate(r.created_at))}</dd>+ </dl>+ </section>++ <section>+ <h3 class="xo-section-title">Mention text</h3>+ <p class="xo-quote">${esc(r.mention_text || '(no text)')}</p>+ </section>++ <section>+ <h3 class="xo-section-title">${r.dry_run ? 'Would reply' : 'Replied'}</h3>+ ${r.reply_text ? `<p class="xo-quote">${esc(r.reply_text)}</p>` : `<p class="xo-note">No reply text recorded.</p>`}+ ${mediaHtml(r.reply_media_url)}+ ${r.reply_tweet_id ? `<p class="xo-note">Live reply id: <span class="xo-mono">${esc(r.reply_tweet_id)}</span></p>` : ''}+ ${r.error ? `<p class="xo-note" data-tone="error">${esc(r.error)}</p>` : ''}+ </section>++ ${canSend ? `<section>+ <h3 class="xo-section-title">Send this reply</h3>+ <p class="xo-warning"><strong>This posts publicly on X.</strong> Sending replies the text above, as @${esc(r.account_kind === 'company' ? 'trythreews' : `agent ${r.account_ref}`)}, in reply to tweet ${esc(r.tweet_id)}. This cannot be undone.</p>+ <div class="xo-actions" style="margin-top:8px">+ <button type="button" class="xo-btn xo-btn-primary" data-act="send">Send this reply live</button>+ </div>+ </section>` : ''}++ <section>+ <h3 class="xo-section-title">Author</h3>+ <div class="xo-actions">+ ${blocked+ ? `<button type="button" class="xo-btn" data-act="unblock">Unblock this author</button>`+ : `<button type="button" class="xo-btn xo-btn-danger" data-act="block">Block this author</button>`}+ </div>+ </section>++ <p class="xo-note" id="xo-drawer-result" role="status" aria-live="polite"></p>`;+}++function rowFor(tweetId) {+ return rows.find((r) => r.tweet_id === tweetId) || null;+}++function renderDrawer() {+ const r = rowFor(openTweetId);+ if (!r) {+ drawerBody.innerHTML = `<div class="xo-state"><strong>Mention not loaded</strong>Refresh the list and reopen it.</div>`;+ return;+ }+ drawerBody.innerHTML = drawerHtml(r);+}++function sayDrawer(message, tone = '') {+ const el = drawerBody.querySelector('#xo-drawer-result');+ if (!el) return;+ el.textContent = message;+ if (tone) el.dataset.tone = tone;+ else delete el.dataset.tone;+}++let actionInFlight = false;++async function runDrawerAction(work) {+ if (actionInFlight) return;+ actionInFlight = true;+ for (const b of drawerBody.querySelectorAll('button[data-act]')) b.disabled = true;+ sayDrawer('Working…');+ try {+ await work();+ await loadStatus();+ await loadList({ reset: true });+ renderDrawer();+ } catch (err) {+ sayDrawer(err.message, 'error');+ for (const b of drawerBody.querySelectorAll('button[data-act]')) b.disabled = false;+ } finally {+ actionInFlight = false;+ }+}++drawerBody.addEventListener('click', (event) => {+ const button = event.target.closest('button[data-act]');+ if (!button) return;+ const r = rowFor(openTweetId);+ if (!r) return;++ if (button.dataset.act === 'block') {+ if (!window.confirm(`Block @${r.author_username || r.author_id} from ever getting an automatic reply?`)) return;+ return runDrawerAction(async () => {+ await api('block', { method: 'POST', body: JSON.stringify({ author_id: r.author_id }) });+ });+ }+ if (button.dataset.act === 'unblock') {+ return runDrawerAction(async () => {+ await api('unblock', { method: 'POST', body: JSON.stringify({ author_id: r.author_id }) });+ });+ }+ if (button.dataset.act === 'send') {+ const account = r.account_kind === 'company' ? '@trythreews' : `agent ${r.account_ref}`;+ const confirmed = window.confirm(+ `Post this reply publicly on X as ${account}, in reply to tweet ${r.tweet_id}?\n\n"${r.reply_text}"\n\nThis cannot be undone.`,+ );+ if (!confirmed) return;+ return runDrawerAction(async () => {+ await api('send', { method: 'POST', body: JSON.stringify({ tweet_id: r.tweet_id }) });+ });+ }+});++// ── events ───────────────────────────────────────────────────────────────────++railEl.addEventListener('click', (event) => {+ const button = event.target.closest('[data-lane]');+ if (!button) return;+ activeLane = RAIL.find((l) => l.key === button.dataset.lane) || RAIL[0];+ renderRail();+ loadList({ reset: true });+});++tableBody.addEventListener('click', (event) => {+ const row = event.target.closest('.xo-row');+ if (row) openDrawer(row.dataset.id);+});++tableBody.addEventListener('keydown', (event) => {+ if (event.key !== 'Enter' && event.key !== ' ') return;+ const row = event.target.closest('.xo-row');+ if (!row) return;+ event.preventDefault();+ openDrawer(row.dataset.id);+});++refreshBtn.addEventListener('click', () => {+ loadStatus();+ loadList({ reset: true });+});++loadMoreBtn.addEventListener('click', () => {+ offset += PAGE;+ loadList({ reset: false });+});++for (const el of [filterAccount, filterIntent]) el.addEventListener('change', () => loadList({ reset: true }));+let authorTimer = null;+filterAuthor.addEventListener('input', () => {+ clearTimeout(authorTimer);+ authorTimer = setTimeout(() => loadList({ reset: true }), 350);+});++togglePauseBtn.addEventListener('click', async () => {+ const next = !botPaused;+ const verb = next ? 'pause' : 'resume';+ if (!window.confirm(`${next ? 'Pause' : 'Resume'} the mention-reply bot across every account?`)) return;+ togglePauseBtn.disabled = true;+ try {+ await api(verb, { method: 'POST' });+ await loadStatus();+ } catch (err) {+ statusText.textContent = err.message;+ } finally {+ togglePauseBtn.disabled = false;+ }+});++closeBtn.addEventListener('click', closeDrawer);+scrim.addEventListener('click', closeDrawer);++document.addEventListener('keydown', (event) => {+ if (event.key === 'Escape' && openTweetId) closeDrawer();+ if (event.key === 'r' && !openTweetId && !/^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement?.tagName || '')) {+ loadStatus();+ loadList({ reset: true });+ }+});++renderRail();+loadStatus();+loadList({ reset: true });++shell.dataset.ready = 'true';diff --git a/tests/x-ops-authorization.test.js b/tests/x-ops-authorization.test.jsnew file mode 100644index 000000000..46e38bc25--- /dev/null+++ b/tests/x-ops-authorization.test.js@@ -0,0 +1,329 @@+// Authorization on the X mention-bot operator console (/api/x/ops/*).+//+// This console reads every account's mention and reply text, and one action+// (`send`) can post to X for real. So every action, including the read-only+// ones, must authorize as an admin BEFORE it touches a mention row, and every+// mutation must also pass the double-submit CSRF check. The sweep at the+// bottom enumerates the dispatch table itself, so a new action added later+// without the gate fails here instead of shipping open.+//+// `send` is exercised here only against a mocked, dry-run-forced+// sendDryRunReply: nothing in this file can reach the real X API.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const getSessionUser = vi.fn(async () => null);+const sqlMock = vi.fn(async () => []);++vi.mock('../api/_lib/auth.js', () => ({ getSessionUser }));+vi.mock('../api/_lib/db.js', () => ({+ sql: sqlMock,+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+ isStoragePressured: () => false,+}));++// Mirrors the real requireCsrf's contract: on failure it writes the 403+// itself (same shape http.js's error() writes) and returns false, it never+// throws. A mock that only returned false without writing to res would make+// these tests pass for the wrong reason.+let csrfOk = true;+const requireCsrf = vi.fn(async (_req, res) => {+ if (csrfOk) return true;+ res.statusCode = 403;+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify({ error: 'csrf_invalid', error_description: 'CSRF token invalid or expired' }));+ return false;+});+vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf }));++const logAudit = vi.fn();+vi.mock('../api/_lib/audit.js', () => ({ logAudit }));++class MentionStoreError extends Error {+ constructor(message, code) {+ super(message);+ this.name = 'MentionStoreError';+ this.code = code;+ }+}+const adminListMentions = vi.fn(async () => [MENTION]);+const adminCountMentions = vi.fn(async () => 1);+vi.mock('../api/_lib/x-mention-store.js', () => ({+ ACCOUNT_KINDS: ['company', 'agent'],+ DECISIONS: ['reply', 'skip', 'rate_limited', 'unsafe', 'budget', 'error', 'pending', 'paused'],+ MentionStoreError,+ adminListMentions,+ adminCountMentions,+}));++vi.mock('../api/_lib/x-mention-intents.js', () => ({+ INTENTS: ['make', 'image3d', 'avatar', 'help', 'launch', 'chat', 'ignore'],+}));++class MentionAdminError extends Error {+ constructor(message, code, status = 400) {+ super(message);+ this.name = 'MentionAdminError';+ this.code = code;+ this.status = status;+ }+}+const isPaused = vi.fn(async () => false);+const setPaused = vi.fn(async (p) => !!p);+const loadBlocklist = vi.fn(async () => []);+const blockAuthor = vi.fn(async () => ['author-1']);+const unblockAuthor = vi.fn(async () => []);+const sendDryRunReply = vi.fn(async () => ({ ...MENTION, dry_run: false, reply_tweet_id: '999' }));+vi.mock('../api/_lib/x-mention-admin.js', () => ({+ MentionAdminError,+ isPaused,+ setPaused,+ loadBlocklist,+ blockAuthor,+ unblockAuthor,+ sendDryRunReply,+}));++const MENTION = {+ tweet_id: '100000000000000001',+ account_kind: 'company',+ account_ref: 'trythreews',+ author_id: 'author-1',+ author_username: 'someone',+ mention_text: '@trythreews make me a dragon',+ intent: 'make',+ decision: 'reply',+ reason: 'queued a dry-run reply',+ reply_text: 'Here is your dragon.',+ reply_media_url: null,+ reply_link: null,+ reply_tweet_id: null,+ dry_run: true,+ error: null,+ created_at: '2026-10-10T00:00:00.000Z',+ decided_at: '2026-10-10T00:00:01.000Z',+ replied_at: null,+};++const handler = (await import('../api/x/ops/[action].js')).default;++function mockRes() {+ return {+ statusCode: 200,+ _headers: {},+ _body: '',+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },+ getHeader(k) { return this._headers[k.toLowerCase()]; },+ end(b) { this._body = b || ''; },+ get headersSent() { return false; },+ get writableEnded() { return false; },+ get json() { try { return JSON.parse(this._body); } catch { return null; } },+ };+}++// Every action the console exposes, with a request that succeeds when the+// caller is an authorized admin. Kept as data so the sweeps below cannot miss+// a newly added action.+const ACTIONS = [+ { action: 'list', method: 'GET' },+ { action: 'status', method: 'GET' },+ { action: 'pause', method: 'POST' },+ { action: 'resume', method: 'POST' },+ { action: 'block', method: 'POST', body: { author_id: 'author-1' } },+ { action: 'unblock', method: 'POST', body: { author_id: 'author-1' } },+ { action: 'send', method: 'POST', body: { tweet_id: MENTION.tweet_id } },+];++function mockReq({ action, method: httpMethod = 'GET', body = null, headers = {} }) {+ const req = {+ method: httpMethod,+ url: `/api/x/ops/${action}`,+ query: { action },+ headers: { host: 'three.ws', ...headers },+ };+ if (body) {+ req.headers['content-type'] = 'application/json';+ req.rawBody = Buffer.from(JSON.stringify(body));+ }+ return req;+}++async function call(spec, headers = {}) {+ const res = mockRes();+ await handler(mockReq({ ...spec, headers }), res);+ return res;+}++beforeEach(() => {+ vi.clearAllMocks();+ getSessionUser.mockResolvedValue(null);+ csrfOk = true;+ adminListMentions.mockResolvedValue([MENTION]);+ adminCountMentions.mockResolvedValue(1);+ isPaused.mockResolvedValue(false);+ setPaused.mockImplementation(async (p) => !!p);+ loadBlocklist.mockResolvedValue([]);+ blockAuthor.mockResolvedValue(['author-1']);+ unblockAuthor.mockResolvedValue([]);+ sendDryRunReply.mockResolvedValue({ ...MENTION, dry_run: false, reply_tweet_id: '999' });+ delete process.env.ADMIN_ADDRESSES;+});++describe('an anonymous caller is refused on every action', () => {+ for (const spec of ACTIONS) {+ it(`refuses anonymous ${spec.method} /api/x/ops/${spec.action}`, async () => {+ const res = await call(spec);+ expect(res.statusCode).toBe(401);+ expect(res.json.error).toBe('unauthorized');+ });+ }++ it('never reads a mention before deciding', async () => {+ await call({ action: 'list', method: 'GET' });+ expect(adminListMentions).not.toHaveBeenCalled();+ });++ it('never sends a reply before deciding', async () => {+ await call({ action: 'send', method: 'POST', body: { tweet_id: MENTION.tweet_id } });+ expect(sendDryRunReply).not.toHaveBeenCalled();+ });+});++describe('a signed-in non-admin is refused on every action', () => {+ beforeEach(() => {+ getSessionUser.mockResolvedValue({ id: 'user-9', wallet_address: 'NotAnAdmin1111111111111111111111111111111' });+ });++ for (const spec of ACTIONS) {+ it(`refuses a plain user on ${spec.action}`, async () => {+ const res = await call(spec);+ expect(res.statusCode).toBe(403);+ expect(res.json.error).toBe('forbidden');+ });+ }++ it('does not pause the bot it refused to let through', async () => {+ await call({ action: 'pause', method: 'POST' });+ expect(setPaused).not.toHaveBeenCalled();+ });++ it('does not send a reply it refused to let through', async () => {+ await call({ action: 'send', method: 'POST', body: { tweet_id: MENTION.tweet_id } });+ expect(sendDryRunReply).not.toHaveBeenCalled();+ });+});++describe('an authorized admin is admitted on every action', () => {+ beforeEach(() => {+ getSessionUser.mockResolvedValue({ id: 'admin-1', wallet_address: '9MjzHaTB6Jko4YKo9mDzJSaGnktzhbebgsnqPpYWnXC7' });+ });++ for (const spec of ACTIONS) {+ it(`admits an admin on ${spec.action}`, async () => {+ const res = await call(spec);+ expect(res.statusCode).toBe(200);+ });+ }++ it('lists mentions with the requested filters', async () => {+ const res = mockRes();+ await handler(+ mockReq({ action: 'list', method: 'GET' }, { host: 'three.ws' }),+ res,+ );+ expect(res.statusCode).toBe(200);+ expect(res.json.mentions).toHaveLength(1);+ expect(res.json.mentions[0].tweet_id).toBe(MENTION.tweet_id);+ });++ it('pauses the bot and attributes the audit entry', async () => {+ const res = await call({ action: 'pause', method: 'POST' });+ expect(res.json).toEqual({ paused: true });+ expect(setPaused).toHaveBeenCalledWith(true);+ expect(logAudit).toHaveBeenCalledWith(expect.objectContaining({ userId: 'admin-1', action: 'x_mention_bot_pause' }));+ });++ it('resumes the bot', async () => {+ const res = await call({ action: 'resume', method: 'POST' });+ expect(res.json).toEqual({ paused: false });+ expect(setPaused).toHaveBeenCalledWith(false);+ });++ it('blocks an author', async () => {+ const res = await call({ action: 'block', method: 'POST', body: { author_id: 'author-1' } });+ expect(res.json.blocklist).toEqual(['author-1']);+ expect(blockAuthor).toHaveBeenCalledWith('author-1');+ });++ it('rejects block with no author id', async () => {+ const res = await call({ action: 'block', method: 'POST', body: {} });+ expect(res.statusCode).toBe(400);+ expect(blockAuthor).not.toHaveBeenCalled();+ });++ it('unblocks an author', async () => {+ const res = await call({ action: 'unblock', method: 'POST', body: { author_id: 'author-1' } });+ expect(res.json.blocklist).toEqual([]);+ expect(unblockAuthor).toHaveBeenCalledWith('author-1');+ });++ it('sends exactly one already-composed dry-run reply, never deriving new text', async () => {+ const res = await call({ action: 'send', method: 'POST', body: { tweet_id: MENTION.tweet_id } });+ expect(res.statusCode).toBe(200);+ expect(sendDryRunReply).toHaveBeenCalledWith({ tweetId: MENTION.tweet_id });+ expect(logAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'x_mention_send_live', resourceId: MENTION.tweet_id }));+ });++ it('rejects send with no tweet id', async () => {+ const res = await call({ action: 'send', method: 'POST', body: {} });+ expect(res.statusCode).toBe(400);+ expect(sendDryRunReply).not.toHaveBeenCalled();+ });++ it('maps a send that was already sent live to 409, not a crash', async () => {+ sendDryRunReply.mockRejectedValue(new MentionAdminError('this reply was already sent live', 'already_sent', 409));+ const res = await call({ action: 'send', method: 'POST', body: { tweet_id: MENTION.tweet_id } });+ expect(res.statusCode).toBe(409);+ expect(res.json.error).toBe('already_sent');+ });++ it('maps an unknown account kind filter to 400 via the store error', async () => {+ adminListMentions.mockRejectedValue(new MentionStoreError('unknown account kind: bogus', 'bad_account'));+ const res = await call({ action: 'list', method: 'GET' });+ expect(res.statusCode).toBe(400);+ expect(res.json.error).toBe('bad_account');+ });++ it('rejects an unknown action instead of dispatching it', async () => {+ const res = mockRes();+ await handler(mockReq({ action: 'delete-everything', method: 'GET' }), res);+ expect(res.statusCode).toBe(404);+ });+});++describe('CSRF guards every mutation, even for an admin', () => {+ beforeEach(() => {+ getSessionUser.mockResolvedValue({ id: 'admin-1', wallet_address: '9MjzHaTB6Jko4YKo9mDzJSaGnktzhbebgsnqPpYWnXC7' });+ csrfOk = false;+ });++ const MUTATIONS = ACTIONS.filter((a) => a.method === 'POST');++ for (const spec of MUTATIONS) {+ it(`refuses ${spec.action} without a valid CSRF token`, async () => {+ const res = await call(spec);+ expect(res.statusCode).toBe(403);+ });+ }++ it('never sends a reply without a valid CSRF token', async () => {+ await call({ action: 'send', method: 'POST', body: { tweet_id: MENTION.tweet_id } });+ expect(sendDryRunReply).not.toHaveBeenCalled();+ });++ it('does not require CSRF for the read-only actions', async () => {+ expect((await call({ action: 'list', method: 'GET' })).statusCode).toBe(200);+ expect((await call({ action: 'status', method: 'GET' })).statusCode).toBe(200);+ });+});diff --git a/vercel.json b/vercel.jsonindex 32eabd2b6..752a3163b 100644--- a/vercel.json+++ b/vercel.json@@ -2341,6 +2341,10 @@"src": "/materialize/ops/?","dest": "/materialize-ops.html"},+ {+ "src": "/x/ops/?",+ "dest": "/x-ops.html"+ },{"src": "/materialize/insert/([0-9a-f]{24})/?","dest": "/print-insert.html"@@ -3760,6 +3764,10 @@"src": "/api/print/ops/(queue|order|adapters|transition|submit|tracking|cancel|refund)","dest": "/api/print/ops/[action]?action=$1"},+ {+ "src": "/api/x/ops/(list|status|pause|resume|block|unblock|send)",+ "dest": "/api/x/ops/[action]?action=$1"+ },{"src": "/api/print/webhook/([a-z][a-z0-9-]{1,31})","dest": "/api/print/webhook/[provider]?provider=$1"diff --git a/vite.config.js b/vite.config.jsindex f9c837543..797fd2ed5 100644--- a/vite.config.js+++ b/vite.config.js@@ -688,6 +688,7 @@ const appConfig = {'smart-home-satellite': resolve(__dirname, 'pages/smart-home-satellite.html'),'materialize-order': resolve(__dirname, 'pages/materialize-order.html'),'materialize-ops': resolve(__dirname, 'pages/materialize-ops.html'),+ 'x-ops': resolve(__dirname, 'pages/x-ops.html'),'drop-collection': resolve(__dirname, 'pages/drop-collection.html'),pocket: resolve(__dirname, 'pages/pocket.html'),spotlight: resolve(__dirname, 'pages/spotlight.html'),