Skip to content

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.

feat(auth): let an X account sign in, not just post as itself

nirholas5149b401d560
diff --git a/api/_lib/identities.js b/api/_lib/identities.js
index 877889fcb..75f74880c 100644
--- a/api/_lib/identities.js
+++ b/api/_lib/identities.js
@@ -41,6 +41,7 @@ export const INTENTS = Object.freeze(['login', 'link', 'reauth']);
/** The identity providers an account can link. Same shape for every future one. */
export const PROVIDERS = Object.freeze([
{ id: 'google', label: 'Google', start: '/api/auth/google/start' },
+ { id: 'x', label: 'X', start: '/api/auth/x/login' },
]);
export class IdentityError extends Error {
diff --git a/api/_lib/migrations/20261011210000_user_identities_x_provider.sql b/api/_lib/migrations/20261011210000_user_identities_x_provider.sql
new file mode 100644
index 000000000..58f834595
--- /dev/null
+++ b/api/_lib/migrations/20261011210000_user_identities_x_provider.sql
@@ -0,0 +1,14 @@
+-- Migration: allow 'x' as a user_identities sign-in provider alongside google.
+-- Apply: node scripts/apply-migrations.mjs --apply --file 20261011210000_user_identities_x_provider.sql
+-- Idempotent.
+--
+-- user_identities (20260922190000_account_social_sso.sql) only allowed
+-- provider='google', so an X user had no way to sign in with X even though
+-- api/auth/x/[action].js already runs the OAuth2 client for connecting an
+-- account to post as it. Widening the check constraint lets the new `login`
+-- action in that file link and sign in through the same generic
+-- api/_lib/identities.js code google already uses.
+
+alter table user_identities drop constraint if exists user_identities_provider_check;
+alter table user_identities add constraint user_identities_provider_check
+ check (provider in ('google', 'x'));
diff --git a/api/_lib/x-identity.js b/api/_lib/x-identity.js
new file mode 100644
index 000000000..b0d1f390f
--- /dev/null
+++ b/api/_lib/x-identity.js
@@ -0,0 +1,32 @@
+// Is this X user one of ours? One answer, shared by every caller that needs
+// it: the mention-reply cron (personalized replies and per-user limits), the
+// forge-creation claim flow, and the mention-to-launch flow (order 925).
+//
+// "Ours" means an X account proven by OAuth and still connected today:
+// social_connections holds the link made when an owner (or an agent, via
+// agent_x_connections) ran api/auth/x/[action].js's connect flow. This is
+// deliberately separate from user_identities (api/_lib/identities.js), which
+// is the newer "sign in with X" sign-in method: a person can be looked up
+// here from a mention long before, or without ever, signing in with X.
+
+import { sql } from './db.js';
+
+/**
+ * @param {string} xAuthorId the X (Twitter) numeric user id from a tweet's author_id
+ * @returns {Promise<{ user_id: string, username: string } | null>}
+ */
+export async function findUserByXId(xAuthorId) {
+ if (!xAuthorId || typeof xAuthorId !== 'string') return null;
+ const [owner] = await sql`
+ select user_id, username from social_connections
+ where provider = 'x' and provider_uid = ${xAuthorId} and disconnected_at is null
+ limit 1
+ `;
+ if (owner) return { user_id: owner.user_id, username: owner.username };
+ const [agentOwner] = await sql`
+ select user_id, username from agent_x_connections
+ where provider_uid = ${xAuthorId} and disconnected_at is null
+ limit 1
+ `;
+ return agentOwner ? { user_id: agentOwner.user_id, username: agentOwner.username } : null;
+}
diff --git a/api/auth/x/[action].js b/api/auth/x/[action].js
index 6c2e2e4df..fdccfbdf0 100644
--- a/api/auth/x/[action].js
+++ b/api/auth/x/[action].js
@@ -1,12 +1,20 @@
-// X (Twitter) OAuth 2.0 PKCE flow. Dispatches on ?action=connect|callback.
+// X (Twitter) OAuth 2.0 PKCE flow. Dispatches on ?action=connect|callback|login.
// Env required: X_OAUTH_CLIENT_ID, X_OAUTH_CLIENT_SECRET
-// If unset, /connect returns 501 not_configured.
+// If unset, /connect and /login return 501 not_configured.
//
// /connect takes an optional ?scope=read|full (default full, see
// api/_lib/x-scopes.js). The memory-seeding card asks for `read` so an owner who
// only wants their agent to sound like them never has to grant permission to
// post as them; the posting surfaces ask for `full`.
//
+// /login is a separate, session-free round trip through the same client:
+// "Sign in with X" on /login (api/config.js xLoginEnabled). An X account
+// already linked (user_identities, api/_lib/identities.js) signs straight in;
+// an X account already connected for posting (social_connections, this file's
+// own connect flow) links and signs in rather than creating a duplicate; a
+// genuinely new X account gets a passwordless three.ws account, since X's
+// OAuth2 profile never carries a verified email to match against one.
+//
// PKCE state ({code_verifier, user_id, agent_id}) is carried in a short-lived,
// HMAC-signed httpOnly cookie keyed by the OAuth `state` param. No external
// store needed; the cookie is sent back on the top-level redirect from x.com
@@ -14,7 +22,7 @@
import { createCipheriv, createDecipheriv, hkdfSync, randomBytes } from 'node:crypto';
import { sql } from '../../_lib/db.js';
-import { getSessionUser } from '../../_lib/auth.js';
+import { getSessionUser, createSession, sessionCookie } from '../../_lib/auth.js';
import {
sha256Base64Url,
randomToken,
@@ -24,8 +32,13 @@ import {
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 { logAudit } from '../../_lib/audit.js';
+import { seedDefaultAgent } from '../../_lib/seed-default-agent.js';
+import { safeNext } from '../../../src/safe-next.js';
import { revokeAllSeedConsentsForUser } from '../../_lib/x-seed-consent.js';
import { resolveScopeSet } from '../../_lib/x-scopes.js';
+import { findUserByIdentity, touchIdentity, linkIdentity, IdentityError } from '../../_lib/identities.js';
+import { findUserByXId } from '../../_lib/x-identity.js';
import { fetchUpstream } from '../../_lib/upstream-fetch.js';
import { isUuid } from '../../_lib/validate.js';
@@ -41,7 +54,10 @@ function b64urlDecode(s) {
return Buffer.from(s, 'base64url').toString('utf8');
}
-async function signState({ state, codeVerifier, userId, agentId, scopeSet, returnTo, target }) {
+async function signState({
+ state, codeVerifier, userId = null, agentId = null, scopeSet, returnTo = null, target = 'owner',
+ purpose = 'connect', next = null,
+}) {
const payload = {
s: state,
v: codeVerifier,
@@ -50,6 +66,8 @@ async function signState({ state, codeVerifier, userId, agentId, scopeSet, retur
k: scopeSet,
r: returnTo || null,
t: target === 'agent' ? 'agent' : 'owner',
+ p: purpose === 'login' ? 'login' : 'connect',
+ n: typeof next === 'string' ? next : null,
e: Math.floor(Date.now() / 1000) + STATE_TTL_SEC,
};
const body = b64urlEncode(JSON.stringify(payload));
@@ -80,6 +98,8 @@ async function verifyState(token, expectedState) {
scopeSet: resolveScopeSet(payload.k).name,
returnTo: resolveReturnTo(payload.r),
target: payload.t === 'agent' ? 'agent' : 'owner',
+ purpose: payload.p === 'login' ? 'login' : 'connect',
+ next: payload.n || null,
};
}
@@ -142,6 +162,15 @@ function resolveReturnTo(value) {
return typeof value === 'string' && RETURN_SURFACES.has(value) ? value : null;
}
+// Where a failed or successful "sign in with X" lands, mirroring
+// api/auth/google/[action].js's loginUrl so /login's error-message map and
+// ?next= handling work identically for both providers.
+function loginUrl(code, next) {
+ const q = new URLSearchParams({ error: code });
+ if (next) q.set('next', next);
+ return `/login?${q.toString()}`;
+}
+
function connectReturnUrl({ scopeSet, agentId, outcome, returnTo = null, target = 'owner' }) {
// An agent-owned account is managed on /settings/connections, so a connect
// made for one agent always lands back on that agent's card there.
@@ -239,39 +268,10 @@ async function handleConnect(req, res) {
// ── GET /api/auth/x/callback ──────────────────────────────────────────────────
-async function handleCallback(req, res) {
- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['GET'])) return;
-
- if (!env.X_OAUTH_CLIENT_ID || !env.X_OAUTH_CLIENT_SECRET) {
- return error(res, 501, 'not_configured', 'X OAuth is not configured');
- }
-
- const url = new URL(req.url, env.APP_ORIGIN);
- const code = url.searchParams.get('code');
- const state = url.searchParams.get('state');
-
- if (!state) return error(res, 400, 'validation_error', 'missing state');
-
- const cookieToken = readStateCookie(req);
- const stateData = await verifyState(cookieToken, state);
- // Burn the cookie regardless of validity so a leaked/replayed token can't be reused.
- res.setHeader('set-cookie', stateCookie('', { clear: true }));
- if (!stateData) return error(res, 400, 'invalid_state', 'OAuth state expired or invalid');
-
- const { codeVerifier, userId, agentId: stateAgentId, scopeSet, returnTo, target } = stateData;
- // 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, returnTo, target });
- const successRedirect = backTo('connected');
- const errorRedirect = backTo('error');
- const deniedRedirect = backTo('denied');
-
- if (url.searchParams.get('error')) return redirect(res, deniedRedirect);
- if (!code) return error(res, 400, 'validation_error', 'missing code');
-
- // Exchange code for tokens
+// Swap an authorization code for tokens, then fetch the profile they unlock.
+// Shared by the connect callback (writes a posting connection) and the login
+// callback (signs the browser in), since both are the same X OAuth2 client.
+async function exchangeXCode({ code, codeVerifier }) {
const creds = Buffer.from(`${env.X_OAUTH_CLIENT_ID}:${env.X_OAUTH_CLIENT_SECRET}`).toString(
'base64',
);
@@ -292,7 +292,7 @@ async function handleCallback(req, res) {
if (!tokenRes.ok) {
console.error('[x-oauth] token exchange failed', await tokenRes.text());
- return redirect(res, errorRedirect);
+ return { ok: false };
}
const tokens = await tokenRes.json().catch(() => ({}));
@@ -304,28 +304,75 @@ async function handleCallback(req, res) {
const grantedScopes = typeof tokens.scope === 'string' ? tokens.scope : '';
if (!access_token) {
console.error('[x-oauth] token response carried no access_token');
- return redirect(res, errorRedirect);
+ return { ok: false };
}
const expiresAt = new Date(Date.now() + (expires_in ?? 7200) * 1000).toISOString();
- // Fetch X profile
- const profileRes = await fetchUpstream('https://api.twitter.com/2/users/me?user.fields=name,username,description,public_metrics', { headers: { authorization: `Bearer ${access_token}` } }, { name: 'x-api', timeoutMs: 15_000, attempts: 2, okWhen: () => true });
+ const profileRes = await fetchUpstream('https://api.twitter.com/2/users/me?user.fields=name,username,description,profile_image_url,public_metrics', { headers: { authorization: `Bearer ${access_token}` } }, { name: 'x-api', timeoutMs: 15_000, attempts: 2, okWhen: () => true });
if (!profileRes.ok) {
console.error('[x-oauth] profile fetch failed', await profileRes.text());
- return redirect(res, errorRedirect);
+ return { ok: false };
}
const { data: profile } = await profileRes.json().catch(() => ({}));
// X answers 200 with an `errors` array (and no `data`) for a suspended or
// otherwise unreadable account. Treat a profile without an id as a failed
- // connect and send the user back to the UI, not into a NULL provider_uid
- // insert that 500s on the not-null constraint.
+ // exchange rather than a NULL provider_uid insert that 500s on the
+ // not-null constraint.
if (!profile?.id) {
console.error('[x-oauth] profile response missing data.id');
- return redirect(res, errorRedirect);
+ return { ok: false };
}
- const encAccess = encryptToken(access_token);
- const encRefresh = refresh_token ? encryptToken(refresh_token) : null;
+ return { ok: true, profile, accessToken: access_token, refreshToken: refresh_token || null, expiresAt, grantedScopes };
+}
+
+async function handleCallback(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ if (!env.X_OAUTH_CLIENT_ID || !env.X_OAUTH_CLIENT_SECRET) {
+ return error(res, 501, 'not_configured', 'X OAuth is not configured');
+ }
+
+ const url = new URL(req.url, env.APP_ORIGIN);
+ const code = url.searchParams.get('code');
+ const state = url.searchParams.get('state');
+
+ if (!state) return error(res, 400, 'validation_error', 'missing state');
+
+ const cookieToken = readStateCookie(req);
+ const stateData = await verifyState(cookieToken, state);
+ // Burn the cookie regardless of validity so a leaked/replayed token can't be reused.
+ res.setHeader('set-cookie', stateCookie('', { clear: true }));
+ if (!stateData) return error(res, 400, 'invalid_state', 'OAuth state expired or invalid');
+
+ const { codeVerifier, userId, agentId: stateAgentId, scopeSet, returnTo, target, purpose, next } = stateData;
+
+ if (purpose === 'login') {
+ if (url.searchParams.get('error')) return redirect(res, loginUrl('x_cancelled', next));
+ if (!code) return redirect(res, loginUrl('x_failed', next));
+ const result = await exchangeXCode({ code, codeVerifier });
+ if (!result.ok) return redirect(res, loginUrl('x_failed', next));
+ return completeXLogin(req, res, { profile: result.profile, next });
+ }
+
+ // 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, returnTo, target });
+ const successRedirect = backTo('connected');
+ const errorRedirect = backTo('error');
+ const deniedRedirect = backTo('denied');
+
+ if (url.searchParams.get('error')) return redirect(res, deniedRedirect);
+ if (!code) return error(res, 400, 'validation_error', 'missing code');
+
+ const result = await exchangeXCode({ code, codeVerifier });
+ if (!result.ok) return redirect(res, errorRedirect);
+ const { profile, accessToken, refreshToken, expiresAt, grantedScopes } = result;
+
+ const encAccess = encryptToken(accessToken);
+ const encRefresh = refreshToken ? encryptToken(refreshToken) : null;
if (target === 'agent') {
// Ownership was checked at /connect; re-check here because the agent can
@@ -387,11 +434,126 @@ async function handleCallback(req, res) {
return redirect(res, successRedirect);
}
+// ── GET /api/auth/x/login (sign in with X) ────────────────────────────────────
+
+// No session required: this is how a brand-new visitor reaches an account at
+// all. Asks for the `read` scope set only, since signing in needs nothing
+// more than the profile api/_lib/identities.js's findUserByIdentity keys on.
+async function handleLoginStart(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 next = safeNext(url.searchParams.get('next'), '/dashboard');
+
+ if (!env.X_OAUTH_CLIENT_ID || !env.X_OAUTH_CLIENT_SECRET) {
+ if (wantsHtmlNavigation(req)) return redirect(res, loginUrl('x_unavailable', next));
+ return error(res, 501, 'not_configured', 'X sign-in is not configured');
+ }
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) {
+ if (wantsHtmlNavigation(req)) return redirect(res, loginUrl('rate_limited', next));
+ return rateLimited(res, rl);
+ }
+
+ const codeVerifier = randomToken(32);
+ const codeChallenge = await sha256Base64Url(codeVerifier);
+ const state = randomToken(16);
+ const scopeSet = resolveScopeSet('read');
+
+ const signed = await signState({ state, codeVerifier, scopeSet: scopeSet.name, purpose: 'login', next });
+ res.setHeader('set-cookie', stateCookie(signed));
+
+ const authUrl = new URL('https://twitter.com/i/oauth2/authorize');
+ authUrl.searchParams.set('response_type', 'code');
+ authUrl.searchParams.set('client_id', env.X_OAUTH_CLIENT_ID);
+ authUrl.searchParams.set('redirect_uri', `${env.APP_ORIGIN}/api/auth/x/callback`);
+ authUrl.searchParams.set('scope', scopeSet.value);
+ authUrl.searchParams.set('state', state);
+ authUrl.searchParams.set('code_challenge', codeChallenge);
+ authUrl.searchParams.set('code_challenge_method', 'S256');
+
+ return redirect(res, authUrl.toString());
+}
+
+function xClaims(profile) {
+ return {
+ subject: profile.id,
+ // X's OAuth2 profile never carries a verified email, so this identity
+ // can never be matched to an existing account by email the way Google's
+ // can: it is either already linked, already connected for posting
+ // (social_connections, checked in completeXLogin), or brand new.
+ email: null,
+ email_verified: false,
+ display_name: typeof profile.name === 'string' ? profile.name.slice(0, 120) : null,
+ avatar_url: typeof profile.profile_image_url === 'string' && /^https:\/\//.test(profile.profile_image_url)
+ ? profile.profile_image_url
+ : null,
+ };
+}
+
+async function signInX(req, res, userId, { isNew = false } = {}) {
+ const token = await createSession({ userId, userAgent: req.headers['user-agent'], ip: clientIp(req) });
+ res.setHeader('set-cookie', sessionCookie(token));
+ logAudit({ userId, action: isNew ? 'register:x' : 'login:x', req });
+ if (isNew) queueMicrotask(() => seedDefaultAgent(userId));
+}
+
+async function completeXLogin(req, res, { profile, next }) {
+ const safeNextPath = safeNext(next, '/dashboard');
+ const claims = xClaims(profile);
+
+ const linked = await findUserByIdentity('x', claims.subject);
+ if (linked) {
+ if (linked.deleted_at) return redirect(res, loginUrl('account_deleted'));
+ await touchIdentity(linked.identity_id);
+ await signInX(req, res, linked.id);
+ return redirect(res, safeNextPath);
+ }
+
+ // Not linked yet. An owner who already connected this X account to post as
+ // themselves (social_connections, proven by the same OAuth2 client) signs
+ // straight into that account instead of getting a second one.
+ const already = await findUserByXId(claims.subject);
+ if (already) {
+ try {
+ await linkIdentity({ userId: already.user_id, provider: 'x', claims });
+ } catch (err) {
+ if (!(err instanceof IdentityError)) throw err;
+ }
+ await signInX(req, res, already.user_id);
+ return redirect(res, safeNextPath);
+ }
+
+ // Genuinely new. X does not vouch for an email address, so there is no
+ // confirm-by-email step like Google's: the account is born passwordless,
+ // the same way a wallet-only signup is, with a synthetic, non-deliverable
+ // placeholder email (api/auth/siws/[action].js uses the same @wallet.local
+ // convention) that keeps the column's NOT NULL UNIQUE constraint happy.
+ let placeholderEmail = `x-${claims.subject}@wallet.local`;
+ const [squatted] = await sql`
+ select 1 from users where email = ${placeholderEmail} and password_hash is not null limit 1
+ `;
+ if (squatted) placeholderEmail = `x-${claims.subject}.${randomToken(8).toLowerCase()}@wallet.local`;
+
+ const [user] = await sql`
+ insert into users (email, display_name)
+ values (${placeholderEmail}, ${claims.display_name || `X user ${claims.subject}`})
+ on conflict (email) do update set email = excluded.email
+ returning id, (xmax = 0) as inserted
+ `;
+ await linkIdentity({ userId: user.id, provider: 'x', claims });
+ await signInX(req, res, user.id, { isNew: user.inserted });
+ return redirect(res, safeNextPath);
+}
+
// ── dispatch ──────────────────────────────────────────────────────────────────
export default wrap(async (req, res) => {
const action = req.query?.action ?? new URL(req.url, 'http://x').pathname.split('/').filter(Boolean).pop();
if (action === 'connect') return handleConnect(req, res);
if (action === 'callback') return handleCallback(req, res);
+ if (action === 'login') return handleLoginStart(req, res);
return error(res, 404, 'not_found', 'unknown action');
});
diff --git a/api/config.js b/api/config.js
index 22a112ad8..220f2f1c8 100644
--- a/api/config.js
+++ b/api/config.js
@@ -36,10 +36,16 @@ export default wrap(async (req, res) => {
process.env.SAML_IDP_METADATA_URL,
);
+ // "Sign in with X" (api/auth/x/[action].js login action), true once the same
+ // OAuth2 client the Connect-X flow already uses is configured. Drives the
+ // X button on /login.
+ const xLoginEnabled = Boolean(process.env.X_OAUTH_CLIENT_ID && process.env.X_OAUTH_CLIENT_SECRET);
+
return json(res, 200, {
walletConnectProjectId: process.env.VITE_WALLETCONNECT_PROJECT_ID || '',
privyAppId: process.env.VITE_PRIVY_APP_ID || process.env.PRIVY_APP_ID || '',
samlEnabled,
+ xLoginEnabled,
// Web Push: the client needs the VAPID public key to subscribe. Empty
// string when push isn't configured, which the client reads as "hide the
// enable-push affordance".
diff --git a/public/login.html b/public/login.html
index bc733a34a..0423fe5cd 100644
--- a/public/login.html
+++ b/public/login.html
@@ -620,6 +620,14 @@
<span id="sso-btn-label" data-i18n="login.single_sign_on_sso">Single sign-on (SSO)</span>
</button>
+ <!-- Sign in with X. Revealed by the script below only when the X OAuth2
+ client is configured (GET /api/config → xLoginEnabled). Same client
+ api/auth/x/[action].js already uses to connect X for posting. -->
+ <button type="button" id="x-login-btn" class="privy-chain-btn sso-btn" hidden>
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M18.9 2H22l-7.6 8.7L23.3 22H16.9l-5-6.5-5.7 6.5H3l8.1-9.3L2.1 2h6.6l4.5 6 5.7-6Zm-1.2 18.2h1.7L7.4 3.7H5.6l12.1 16.5Z"/></svg>
+ <span id="x-login-btn-label" data-i18n="login.sign_in_with_x">Sign in with X</span>
+ </button>
+
<div class="or-divider" id="privy-or-divider">or</div>
<label for="email" data-i18n="login.email_or_username">Email or username</label>
@@ -807,33 +815,53 @@
account_deleted: 'This account has been deleted.',
rate_limited: 'Too many attempts. Please try again in a moment.',
};
+ const X_MESSAGES = {
+ x_unavailable: 'Sign in with X is not available right now.',
+ x_cancelled: 'X sign-in was cancelled.',
+ x_failed: 'Something went wrong completing X sign-in. Please try again.',
+ account_deleted: 'This account has been deleted.',
+ rate_limited: 'Too many attempts. Please try again in a moment.',
+ };
const errCode = params.get('error');
if (errEl && errCode && SSO_MESSAGES[errCode]) {
errEl.textContent = SSO_MESSAGES[errCode];
errEl.style.display = 'block';
+ } else if (errEl && errCode && X_MESSAGES[errCode]) {
+ errEl.textContent = X_MESSAGES[errCode];
+ errEl.style.display = 'block';
} else if (errEl && params.get('signed_out')) {
errEl.textContent = 'You have been signed out.';
errEl.style.color = '#9fd09f';
errEl.style.display = 'block';
}
- const ssoBtn = document.getElementById('sso-btn');
- if (!ssoBtn) return;
let cfg;
try {
cfg = await (await fetch('/api/config')).json();
} catch {
- return; // config unreachable — leave SSO hidden
+ cfg = null; // config unreachable: leave SSO and X sign-in hidden
}
- if (!cfg?.samlEnabled) return;
- if (cfg.samlLabel) {
- document.getElementById('sso-btn-label').textContent = cfg.samlLabel;
+
+ const ssoBtn = document.getElementById('sso-btn');
+ if (ssoBtn && cfg?.samlEnabled) {
+ if (cfg.samlLabel) {
+ document.getElementById('sso-btn-label').textContent = cfg.samlLabel;
+ }
+ ssoBtn.hidden = false;
+ ssoBtn.addEventListener('click', () => {
+ const next = window.__loginNext || params.get('next') || '/dashboard';
+ window.location.href = '/api/auth/saml/login?next=' + encodeURIComponent(next);
+ });
+ }
+
+ const xBtn = document.getElementById('x-login-btn');
+ if (xBtn && cfg?.xLoginEnabled) {
+ xBtn.hidden = false;
+ xBtn.addEventListener('click', () => {
+ const next = window.__loginNext || params.get('next') || '/dashboard';
+ window.location.href = '/api/auth/x/login?next=' + encodeURIComponent(next);
+ });
}
- ssoBtn.hidden = false;
- ssoBtn.addEventListener('click', () => {
- const next = window.__loginNext || params.get('next') || '/dashboard';
- window.location.href = '/api/auth/saml/login?next=' + encodeURIComponent(next);
- });
})();
</script>
<script>
diff --git a/tests/user-identities-provider-constraint.test.js b/tests/user-identities-provider-constraint.test.js
new file mode 100644
index 000000000..454ba4b98
--- /dev/null
+++ b/tests/user-identities-provider-constraint.test.js
@@ -0,0 +1,60 @@
+// user_identities.provider started out google-only (20260922190000_account_social_sso.sql).
+// 20261011210000_user_identities_x_provider.sql widens the check constraint to
+// also allow 'x', the provider api/auth/x/[action].js's new login action
+// writes through api/_lib/identities.js. Run against a real database so the
+// constraint actually in the schema is what's exercised, not a guess about it:
+// DATABASE_URL=... npx vitest run tests/user-identities-provider-constraint.test.js
+
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+
+const hasDb = Boolean(process.env.DATABASE_URL);
+const liveDb = describe.skipIf(!hasDb);
+
+liveDb('user_identities provider check constraint', () => {
+ /** @type {import('@neondatabase/serverless').NeonQueryFunction} */
+ let sql;
+ let user;
+
+ beforeAll(async () => {
+ ({ sql } = await import('../api/_lib/db.js'));
+ const stamp = Date.now();
+ [user] = await sql`insert into users (email) values (${`identity-constraint-${stamp}@qa.three.ws`}) returning id`;
+ }, 60_000);
+
+ afterAll(async () => {
+ if (sql && user) {
+ await sql`delete from user_identities where user_id = ${user.id}`;
+ await sql`delete from users where id = ${user.id}`;
+ }
+ });
+
+ it('allows provider = x', async () => {
+ const [row] = await sql`
+ insert into user_identities (user_id, provider, subject)
+ values (${user.id}, 'x', 'x-subject-1')
+ returning id, provider
+ `;
+ expect(row.provider).toBe('x');
+ });
+
+ it('still allows provider = google', async () => {
+ const [row] = await sql`
+ insert into user_identities (user_id, provider, subject)
+ values (${user.id}, 'google', 'google-subject-1')
+ returning id, provider
+ `;
+ expect(row.provider).toBe('google');
+ });
+
+ it('rejects any other provider', async () => {
+ await expect(
+ sql`insert into user_identities (user_id, provider, subject) values (${user.id}, 'facebook', 'fb-subject-1')`,
+ ).rejects.toThrow();
+ });
+
+ it('still enforces one identity per provider per account', async () => {
+ await expect(
+ sql`insert into user_identities (user_id, provider, subject) values (${user.id}, 'x', 'x-subject-2')`,
+ ).rejects.toThrow();
+ });
+});
diff --git a/tests/x-identity.test.js b/tests/x-identity.test.js
new file mode 100644
index 000000000..8a41ff8cc
--- /dev/null
+++ b/tests/x-identity.test.js
@@ -0,0 +1,70 @@
+// findUserByXId answers "is this X user one of ours?" for the mention-reply
+// cron, the forge-creation claim flow, and the mention-to-launch flow (order
+// 925). It must check both ways an X account is proven ours: an owner's own
+// connected account (social_connections) and one connected to a single agent
+// (agent_x_connections), and it must never match a disconnected one.
+
+import { describe, it, expect, vi } from 'vitest';
+
+const queue = [];
+const sqlCalls = [];
+vi.mock('../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings) => {
+ sqlCalls.push(String(strings?.raw ? strings.join('?') : strings));
+ return queue.length ? queue.shift() : [];
+ }),
+}));
+
+const { findUserByXId } = await import('../api/_lib/x-identity.js');
+
+describe('findUserByXId', () => {
+ it('returns null without querying for a missing or non-string id', async () => {
+ expect(await findUserByXId(null)).toBeNull();
+ expect(await findUserByXId(undefined)).toBeNull();
+ expect(await findUserByXId(12345)).toBeNull();
+ expect(sqlCalls.length).toBe(0);
+ });
+
+ it('matches an owner X account connected through social_connections', async () => {
+ queue.length = 0;
+ queue.push([{ user_id: 'user-1', username: 'ownerhandle' }]);
+ const result = await findUserByXId('111');
+ expect(result).toEqual({ user_id: 'user-1', username: 'ownerhandle' });
+ });
+
+ it('falls back to an agent-owned X account via agent_x_connections', async () => {
+ queue.length = 0;
+ queue.push([]); // no social_connections match
+ queue.push([{ user_id: 'user-2', username: 'agenthandle' }]);
+ const result = await findUserByXId('222');
+ expect(result).toEqual({ user_id: 'user-2', username: 'agenthandle' });
+ });
+
+ it('returns null when the X id matches neither table', async () => {
+ queue.length = 0;
+ queue.push([]);
+ queue.push([]);
+ const result = await findUserByXId('333');
+ expect(result).toBeNull();
+ });
+
+ it('queries social_connections before agent_x_connections, both scoped to live links', async () => {
+ queue.length = 0;
+ queue.push([]);
+ queue.push([]);
+ sqlCalls.length = 0;
+ await findUserByXId('444');
+ expect(sqlCalls[0]).toMatch(/social_connections/);
+ expect(sqlCalls[0]).toMatch(/disconnected_at is null/);
+ expect(sqlCalls[1]).toMatch(/agent_x_connections/);
+ expect(sqlCalls[1]).toMatch(/disconnected_at is null/);
+ });
+
+ it('a different X id than the one connected never matches', async () => {
+ queue.length = 0;
+ queue.push([]);
+ queue.push([]);
+ const result = await findUserByXId('not-connected-id');
+ expect(result).toBeNull();
+ });
+});