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
fix(x-connect): stop dead-ending Connect X when X sign-in is switched off
nirholas1cdd572cfc97
diff --git a/api/_lib/http.js b/api/_lib/http.jsindex bd8a6685e..ca90ce984 100644--- a/api/_lib/http.js+++ b/api/_lib/http.js@@ -134,7 +134,7 @@ export function redactUrl(rawUrl) {// fall back to an Accept that prefers HTML. Used so a human who hits a 5xx is// sent to the branded /500 page (carrying their support ref) while every API /// agent caller keeps receiving the JSON error envelope it expects.-function wantsHtmlNavigation(req) {+export function wantsHtmlNavigation(req) {const m = req?.method || 'GET';if (m !== 'GET' && m !== 'HEAD') return false;const mode = req?.headers?.['sec-fetch-mode'];diff --git a/api/auth/x/[action].js b/api/auth/x/[action].jsindex 579b6edb0..ac0cad2e3 100644--- a/api/auth/x/[action].js+++ b/api/auth/x/[action].js@@ -21,7 +21,7 @@ import {hmacSha256,constantTimeEquals,} from '../../_lib/crypto.js';-import { cors, method, wrap, error, redirect, rateLimited } from '../../_lib/http.js';+import { cors, method, wrap, error, redirect, rateLimited, wantsHtmlNavigation } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { env } from '../../_lib/env.js';import { revokeAllSeedConsentsForUser } from '../../_lib/x-seed-consent.js';@@ -120,13 +120,46 @@ export function decryptToken(ciphertext) {]).toString('utf8');}+// ── Where a finished or refused connect sends the browser back to ────────────++// A read-only connect can only have come from the memory-seeding card, so it+// goes back to Settings (with the agent it targets) rather than to the agent+// editor's posting tab, which is about the write access that grant deliberately+// does not carry. The callback and the connect endpoint both route through this+// so a refusal lands on the same surface a success would.+function connectReturnUrl({ scopeSet, agentId, outcome }) {+ if (scopeSet === 'read') {+ const q = new URLSearchParams({ tab: 'connected-accounts', x: outcome });+ if (agentId) q.set('agent_id', agentId);+ return `/settings?${q.toString()}`;+ }+ return agentId+ ? `/agents/${encodeURIComponent(agentId)}/edit?tab=social&x=${outcome}`+ : `/settings?tab=connected-accounts&x=${outcome}`;+}+// ── GET /api/auth/x/connect ───────────────────────────────────────────────────async function handleConnect(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;if (!method(req, res, ['GET'])) return;+ const url = new URL(req.url, env.APP_ORIGIN);+ const agentId = url.searchParams.get('agent_id') || null;+ const scopeSet = resolveScopeSet(url.searchParams.get('scope'));+if (!env.X_OAUTH_CLIENT_ID || !env.X_OAUTH_CLIENT_SECRET) {+ // Every Connect X button on the site is an anchor or a location assignment,+ // so an unconfigured deployment used to answer a top-level navigation with a+ // raw JSON body in the address bar. Send the browser back to the surface it+ // came from with an outcome the page explains instead; API and agent callers+ // still get the 501 envelope they parse.+ if (wantsHtmlNavigation(req)) {+ return redirect(+ res,+ connectReturnUrl({ scopeSet: scopeSet.name, agentId, outcome: 'unconfigured' }),+ );+ }return error(res, 501, 'not_configured', 'X OAuth is not configured');}@@ -136,10 +169,6 @@ async function handleConnect(req, res) {const user = await getSessionUser(req);if (!user) return error(res, 401, 'unauthorized', 'sign in required');- const url = new URL(req.url, env.APP_ORIGIN);- const agentId = url.searchParams.get('agent_id') || null;- const scopeSet = resolveScopeSet(url.searchParams.get('scope'));-const codeVerifier = randomToken(32); // 43-char base64urlconst codeChallenge = await sha256Base64Url(codeVerifier);const state = randomToken(16);@@ -192,20 +221,10 @@ async function handleCallback(req, res) {if (!stateData) return error(res, 400, 'invalid_state', 'OAuth state expired or invalid');const { codeVerifier, userId, agentId: stateAgentId, scopeSet } = stateData;- // Return to the surface that started the connect. A read-only connect can only- // have come from the memory-seeding card, so it goes back to Settings (with- // the agent it targets) rather than to the agent editor's posting tab, which- // is about the write access this grant deliberately does not carry.- const backTo = (outcome) => {- if (scopeSet === 'read') {- const q = new URLSearchParams({ tab: 'connected-accounts', x: outcome });- if (stateAgentId) q.set('agent_id', stateAgentId);- return `/settings?${q.toString()}`;- }- return stateAgentId- ? `/agents/${encodeURIComponent(stateAgentId)}/edit?tab=social&x=${outcome}`- : `/settings?tab=connected-accounts&x=${outcome}`;- };+ // Return to the surface that started the connect, the same one a refusal at+ // /connect lands on.+ const backTo = (outcome) =>+ connectReturnUrl({ scopeSet, agentId: stateAgentId, outcome });const successRedirect = backTo('connected');const errorRedirect = backTo('error');const deniedRedirect = backTo('denied');diff --git a/api/x/status.js b/api/x/status.jsindex 56d56a1cd..2c08f2d31 100644--- a/api/x/status.js+++ b/api/x/status.js@@ -6,6 +6,7 @@ import { getSessionUser } from '../_lib/auth.js';import { cors, method, wrap, error, json } from '../_lib/http.js';import { requireCsrf } from '../_lib/csrf.js';import { getUserTier } from '../_lib/x-post.js';+import { env } from '../_lib/env.js';import { revokeAllSeedConsentsForUser } from '../_lib/x-seed-consent.js';export default wrap(async (req, res) => {@@ -35,6 +36,10 @@ export default wrap(async (req, res) => {}const tier = await getUserTier(user.id);+ // Whether this deployment can start an X OAuth flow at all. Without it every+ // caller of this endpoint renders a Connect X button that dead-ends on+ // /api/auth/x/connect's not_configured refusal.+ const configured = !!(env.X_OAUTH_CLIENT_ID && env.X_OAUTH_CLIENT_SECRET);const rows = await sql`select username, posts_this_month, month_resets_at, connected_at, last_posted_at@@ -43,7 +48,8 @@ export default wrap(async (req, res) => {limit 1`;const conn = rows[0];- if (!conn) return json(res, 200, { connected: false, tier: tier.tier, quota: tier.quota });+ if (!conn)+ return json(res, 200, { connected: false, configured, tier: tier.tier, quota: tier.quota });let postsThisMonth = conn.posts_this_month;if (new Date(conn.month_resets_at) <= new Date()) {@@ -58,6 +64,7 @@ export default wrap(async (req, res) => {return json(res, 200, {connected: true,+ configured,username: conn.username,tier: tier.tier,quota: tier.quota,diff --git a/docs/x-memory-seeding.md b/docs/x-memory-seeding.mdindex fcde4870c..688f10db1 100644--- a/docs/x-memory-seeding.md+++ b/docs/x-memory-seeding.md@@ -282,6 +282,18 @@ gcloud run services update three-ws-api --region us-central1 \Until both are present, `GET /api/agents/:id/memory/seed/x` answers`configured: false` and the Settings card says X connections are not enabled onthis deployment, rather than offering a Connect button that could not complete.+`GET /api/x/status` carries the same `configured` flag, so the posting surfaces+that read it (the dashboard's X panel, the agent editor's Social tab) hide their+Connect button for the same reason instead of offering one that dead-ends.++If the connect URL is reached anyway (an old tab, a bookmark, a link someone+saved), `/api/auth/x/connect` distinguishes a top-level browser navigation from+a programmatic call. A navigation is redirected back to the surface it came from+with `?x=unconfigured`, which both pages render as an explanation; an API or+agent caller still receives the `501 not_configured` JSON envelope it parses. No+PKCE state cookie is set on that path, so nothing is left behind for a callback+that can never arrive.+Nothing else in the lane changes: the disclosure, the consent grant, andrevocation behave identically once the credentials are in place.@@ -311,3 +323,4 @@ Seeded rows in `agent_memories` are found by tag (`tags && '{x_seed}'`) and by| Transform tests | [tests/api/x-memory-seed-transform.test.js](../tests/api/x-memory-seed-transform.test.js), [tests/api/agents-memory-seed.test.js](../tests/api/agents-memory-seed.test.js) || Consent gate, scope gate and revocation tests | [tests/api/x-memory-seed-consent.test.js](../tests/api/x-memory-seed-consent.test.js), [tests/api/x-scopes.test.js](../tests/api/x-scopes.test.js) || What the connect redirect asks X for | [tests/api/x-connect-scope.test.js](../tests/api/x-connect-scope.test.js) |+| How connect refuses when no X OAuth app is configured | [tests/api/x-connect-unconfigured.test.js](../tests/api/x-connect-unconfigured.test.js) |diff --git a/public/settings/index.html b/public/settings/index.htmlindex 5f4bde6bf..ad28424cc 100644--- a/public/settings/index.html+++ b/public/settings/index.html@@ -1287,7 +1287,8 @@const xResult = _urlP.get('x');if (xResult === 'connected') showMsg(msg, 'ok', 'X account connected successfully.');else if (xResult === 'denied') showMsg(msg, 'err', 'X connection cancelled.');- else if (xResult === 'error') showMsg(msg, 'err', 'X connection failed — try again.');+ else if (xResult === 'unconfigured') showMsg(msg, 'err', 'X connections are not enabled on this deployment, so the connect could not start.');+ else if (xResult === 'error') showMsg(msg, 'err', 'X connection failed. Try again.');}function escHtml(s) {diff --git a/src/agent-edit.js b/src/agent-edit.jsindex 3603f453c..5ea7d2b5e 100644--- a/src/agent-edit.js+++ b/src/agent-edit.js@@ -2322,6 +2322,10 @@ async function ensureSocialTab() {if (xParam === 'connected') {$('x-post-status').textContent = 'X connected.';$('x-post-status').className = 'form-status ok';+ } else if (xParam === 'unconfigured') {+ $('x-post-status').textContent =+ 'X connections are not enabled on this deployment, so the connect could not start.';+ $('x-post-status').className = 'form-status err';} else if (xParam === 'error' || xParam === 'denied') {$('x-post-status').textContent = `X connect failed (${xParam}).`;$('x-post-status').className = 'form-status err';@@ -2345,6 +2349,15 @@ function renderXStatus() {const connectBtn = $('x-connect-btn');const disconnectBtn = $('x-disconnect-btn');if (!xConnection?.connected) {+ // Without X OAuth credentials the connect endpoint can only refuse, so the+ // button stays hidden and the reason is stated instead of dead-ending.+ if (xConnection?.configured === false) {+ el.textContent =+ 'X connections are not enabled on this deployment. Ask an operator to configure X OAuth.';+ connectBtn.hidden = true;+ disconnectBtn.hidden = true;+ return;+ }el.textContent = 'Not connected.';connectBtn.hidden = false;disconnectBtn.hidden = true;diff --git a/src/dashboard/dashboard.js b/src/dashboard/dashboard.jsindex 60c8002bb..dd2001da9 100644--- a/src/dashboard/dashboard.js+++ b/src/dashboard/dashboard.js@@ -995,7 +995,12 @@ async function loadXPanel({ host, meterEl, bodyEl, avatar }) {if (!status.connected) {meterEl.textContent = '';- bodyEl.innerHTML = `+ // A deployment without X OAuth credentials cannot start the flow, so say so+ // rather than offering a button whose only outcome is a refusal.+ bodyEl.innerHTML =+ status.configured === false+ ? `<p class="muted" style="font-size:13px;margin:0">X connections are not enabled on this deployment, so this agent cannot post to X yet. Ask an operator to configure X OAuth.</p>`+ : `<p class="muted" style="font-size:13px;margin:0 0 10px">Connect your X account to let this agent post tweets. Free tier: 5 posts/month per account.</p><a class="btn" href="/api/auth/x/connect?agent_id=${encodeURIComponent(avatar.agent_id || avatar.id)}">Connect X</a>`;diff --git a/tests/api-x-endpoints.test.js b/tests/api-x-endpoints.test.jsindex 0812b2eb0..2ecb0e2ad 100644--- a/tests/api-x-endpoints.test.js+++ b/tests/api-x-endpoints.test.js@@ -359,7 +359,36 @@ describe('/api/x/status', () => {it('reports a disconnected account without inventing a username', async () => {queue.push([]);const res = await call(status, { url: '/api/x/status' });- expect(res.json).toEqual({ connected: false, tier: 'free', quota: 5 });+ expect(res.json).toEqual({ connected: false, configured: false, tier: 'free', quota: 5 });+ });++ // The dashboard X panel and the agent editor's Social tab both render a+ // "Connect X" button off this payload, and /api/auth/x/connect can only refuse+ // when the OAuth app credentials are absent. Without this flag those surfaces+ // have no way to tell, so they offer a button that dead-ends.+ it('says whether this deployment can start an X OAuth flow at all', async () => {+ queue.push([]);+ expect((await call(status, { url: '/api/x/status' })).json.configured).toBe(false);++ process.env.X_OAUTH_CLIENT_ID = 'test-client-id';+ process.env.X_OAUTH_CLIENT_SECRET = 'test-client-secret';+ try {+ queue.push([]);+ expect((await call(status, { url: '/api/x/status' })).json.configured).toBe(true);++ getUserTier.mockResolvedValue({ tier: 'free', quota: 5, min_interval_min: 30 });+ queue.push([{+ username: 'threews',+ posts_this_month: 0,+ month_resets_at: new Date(Date.now() + 86_400_000).toISOString(),+ connected_at: '2026-01-01T00:00:00.000Z',+ last_posted_at: null,+ }]);+ expect((await call(status, { url: '/api/x/status' })).json.configured).toBe(true);+ } finally {+ delete process.env.X_OAUTH_CLIENT_ID;+ delete process.env.X_OAUTH_CLIENT_SECRET;+ }});it('revokes seed consents on disconnect', async () => {diff --git a/tests/api/x-connect-unconfigured.test.js b/tests/api/x-connect-unconfigured.test.jsnew file mode 100644index 000000000..8d49f8ecd--- /dev/null+++ b/tests/api/x-connect-unconfigured.test.js@@ -0,0 +1,120 @@+// What /api/auth/x/connect does on a deployment that holds no X OAuth app.+//+// Every "Connect X" control on the site is an anchor or a `location.href`+// assignment, so this endpoint is reached by a top-level browser navigation. It+// used to answer an unconfigured deployment with a JSON 501, which put+// `{"error":"not_configured"}` in the user's address bar and lost the page they+// came from. tests/api/x-connect-scope.test.js covers the configured path; this+// file pins the refusal, and pins that API callers still get the JSON envelope.++import { describe, it, expect, vi } from 'vitest';++vi.mock('../../api/_lib/db.js', () => ({+ sql: vi.fn(async () => []),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+ isStoragePressured: () => false,+}));++vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => ({ id: 'user-1' })),+ authenticateBearer: vi.fn(async () => null),+ extractBearer: vi.fn(() => null),+}));++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { authIp: vi.fn(async () => ({ success: true })) },+ clientIp: vi.fn(() => '127.0.0.1'),+}));++// The whole point of this file: no client id, no client secret.+vi.mock('../../api/_lib/env.js', () => ({+ env: {+ X_OAUTH_CLIENT_ID: '',+ X_OAUTH_CLIENT_SECRET: '',+ APP_ORIGIN: 'https://three.ws',+ JWT_SECRET: 'test-jwt-secret-value-long-enough',+ },+}));++const { default: handler } = await import('../../api/auth/x/[action].js');++function mockRes() {+ return {+ statusCode: 200,+ headers: {},+ headersSent: false,+ writableEnded: false,+ body: null,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ getHeader(k) { return this.headers[k.toLowerCase()]; },+ end(payload) { this.headersSent = true; this.writableEnded = true; this.body = payload ?? null; },+ get json() { return this.body ? JSON.parse(this.body) : null; },+ };+}++async function connect(query = '', headers = {}) {+ const req = {+ method: 'GET',+ url: `/api/auth/x/connect${query}`,+ headers,+ socket: {},+ query: { action: 'connect' },+ };+ const res = mockRes();+ await handler(req, res);+ return res;+}++const NAVIGATION = { 'sec-fetch-mode': 'navigate' };++describe('GET /api/auth/x/connect with no X OAuth app configured', () => {+ it('sends a browser back to the seeding card instead of rendering JSON', async () => {+ const res = await connect('?scope=read&agent_id=agent-9', NAVIGATION);+ expect(res.statusCode).toBe(302);+ const to = new URL(res.headers.location, 'https://three.ws');+ expect(to.pathname).toBe('/settings');+ expect(to.searchParams.get('tab')).toBe('connected-accounts');+ expect(to.searchParams.get('x')).toBe('unconfigured');+ expect(to.searchParams.get('agent_id')).toBe('agent-9');+ expect(res.body).toBeNull();+ });++ it('sends a posting connect back to the agent editor it started from', async () => {+ const res = await connect('?agent_id=agent-9', NAVIGATION);+ expect(res.statusCode).toBe(302);+ const to = new URL(res.headers.location, 'https://three.ws');+ expect(to.pathname).toBe('/agents/agent-9/edit');+ expect(to.searchParams.get('tab')).toBe('social');+ expect(to.searchParams.get('x')).toBe('unconfigured');+ });++ it('falls back to Settings when the connect names no agent', async () => {+ const res = await connect('', NAVIGATION);+ const to = new URL(res.headers.location, 'https://three.ws');+ expect(to.pathname).toBe('/settings');+ expect(to.searchParams.get('x')).toBe('unconfigured');+ });++ // An Accept that prefers HTML is the fallback signal for clients that send no+ // Sec-Fetch headers, so it has to redirect too.+ it('treats an HTML-preferring client with no Sec-Fetch headers as a navigation', async () => {+ const res = await connect('?scope=read', { accept: 'text/html,application/xhtml+xml' });+ expect(res.statusCode).toBe(302);+ });++ it('still answers a programmatic caller with the not_configured envelope', async () => {+ const res = await connect('?scope=read', { 'sec-fetch-mode': 'cors', accept: 'application/json' });+ expect(res.statusCode).toBe(501);+ expect(res.json).toMatchObject({ error: 'not_configured' });+ expect(res.headers.location).toBeUndefined();+ });++ it('never starts an authorization it cannot finish', async () => {+ const res = await connect('?scope=read', NAVIGATION);+ // No PKCE state cookie, so nothing is left behind for a callback that can+ // never arrive.+ expect(res.headers['set-cookie']).toBeUndefined();+ expect(String(res.headers.location)).not.toContain('twitter.com');+ });+});