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(auth): bind handoff, Telegram and SAML sign-in callbacks to the flow that started them
nirholas37d3a6d9d03f
diff --git a/api/auth/handoff.js b/api/auth/handoff.jsindex 47977fdba..7a4f1dc64 100644--- a/api/auth/handoff.js+++ b/api/auth/handoff.js@@ -107,6 +107,12 @@ async function exchange(req, res) {// land them on the page they asked for.if (!url.searchParams.has('code')) return redirect(res, `${env.APP_ORIGIN}${fallbackNext}`);+ // The app opens this URL in Safari, which sends `none` (or no header at+ // all). A link followed from another page is cross-site or same-site, and+ // honouring it would let an attacker sign a victim in as the attacker.+ const fetchSite = req.headers['sec-fetch-site'];+ if (fetchSite === 'cross-site' || fetchSite === 'same-site') return toLogin('handoff_expired');+const rl = await limits.authIp(clientIp(req));if (!rl.success) return toLogin('rate_limited');if (!/^[A-Za-z0-9_-]{32,128}$/.test(code)) return toLogin('handoff_expired');diff --git a/api/auth/saml/[action].js b/api/auth/saml/[action].jsindex 90efb2bee..7a9c3bd5e 100644--- a/api/auth/saml/[action].js+++ b/api/auth/saml/[action].js@@ -15,6 +15,7 @@ import { createSession, sessionCookie, destroySession, getSessionUser } from '..import { cors, redirect, error, wrap, readForm } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { env } from '../../_lib/env.js';+import { randomToken, constantTimeEquals } from '../../_lib/crypto.js';import { logAudit } from '../../_lib/audit.js';import { seedDefaultAgent } from '../../_lib/seed-default-agent.js';import { referralCodeCandidates } from '../../_lib/referrals.js';@@ -29,6 +30,20 @@ import {subjectHash,} from '../../_lib/saml.js';+// The IdP returns with a cross-site POST, which only a SameSite=None cookie+// rides along on. It holds the RelayState this browser was given at /login.+const FLOW_COOKIE = '__Host-samlflow';+const flowCookie = (value, maxAge = 600) =>+ `${FLOW_COOKIE}=${value}; Path=/; Max-Age=${maxAge}; HttpOnly; Secure; SameSite=None`;++function readFlowCookie(req) {+ for (const part of String(req.headers?.cookie || '').split(';')) {+ const i = part.indexOf('=');+ if (i > 0 && part.slice(0, i).trim() === FLOW_COOKIE) return part.slice(i + 1).trim();+ }+ return '';+}+const loginUrl = (params) => `${env.APP_ORIGIN}/login${params ? `?${params}` : ''}`;// ── metadata ────────────────────────────────────────────────────────────────@@ -62,8 +77,11 @@ async function handleLogin(req, res) {return redirect(res, loginUrl('error=sso_unavailable'));}- const relayState = await signRelayState({ next, ts: Date.now() });+ // A random nonce makes every RelayState unique, and the same value goes in+ // a cookie so the ACS can tell this browser started the login.+ const relayState = await signRelayState({ next, ts: Date.now(), n: randomToken(16) });const authnUrl = await saml.getAuthorizeUrlAsync(relayState, undefined, {});+ res.setHeader('set-cookie', flowCookie(relayState));return redirect(res, authnUrl);}@@ -91,6 +109,15 @@ async function handleAcs(req, res) {const RelayState = form.RelayState;if (!SAMLResponse) return redirect(res, loginUrl('error=saml_no_response'));+ // Login CSRF: the response must come back to the browser that started the+ // login. IdP-initiated sign-in has no such browser and is opt-in by config.+ if (!env.SAML_ALLOW_IDP_INITIATED) {+ const started = readFlowCookie(req);+ if (!started || !RelayState || !constantTimeEquals(started, RelayState)) {+ return redirect(res, loginUrl('error=saml_invalid'));+ }+ }+let saml;try {saml = await getSamlInstance();@@ -118,7 +145,7 @@ async function handleAcs(req, res) {const userId = await findOrCreateUser(identity);await destroySession(req);const token = await createSession({ userId, userAgent: req.headers['user-agent'], ip });- res.setHeader('set-cookie', sessionCookie(token));+ res.setHeader('set-cookie', [sessionCookie(token), flowCookie('', 0)]);logAudit({ userId, action: 'login', req, meta: { method: 'saml', issuer: identity.issuer } });return redirect(res, `${env.APP_ORIGIN}${next}`);} catch (err) {diff --git a/api/auth/telegram/[action].js b/api/auth/telegram/[action].jsindex 324fe2bb8..5d096bee9 100644--- a/api/auth/telegram/[action].js+++ b/api/auth/telegram/[action].js@@ -116,7 +116,11 @@ async function handleCallback(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;if (!method(req, res, ['GET'])) return;const url = new URL(req.url, 'http://x');- const flow = (await unsignIdentityPayload(readCookie(req, FLOW_COOKIE))) || { i: 'login', n: '/dashboard', u: null };+ // Only this browser's own /start sets the flow cookie. Without it the payload+ // could be an attacker's, replayed into a victim's browser to sign them in+ // as the attacker, so nothing past this point runs.+ const flow = await unsignIdentityPayload(readCookie(req, FLOW_COOKIE));+ if (!flow) return redirect(res, loginUrl('telegram_expired', '/dashboard'));const intent = WIDGET_INTENTS.includes(flow.i) ? flow.i : 'login';const back = (code) => {res.setHeader('set-cookie', clearCookie(FLOW_COOKIE));diff --git a/tests/auth-handoff.test.js b/tests/auth-handoff.test.jsindex ccefeae57..78cdc0180 100644--- a/tests/auth-handoff.test.js+++ b/tests/auth-handoff.test.js@@ -76,8 +76,8 @@ async function mint(body, { origin = 'https://three.ws' } = {}) {return res;}-async function open(query) {- const req = { method: 'GET', url: `/api/auth/handoff?${query}`, headers: { 'user-agent': 'Safari' } };+async function open(query, extraHeaders = {}) {+ const req = { method: 'GET', url: `/api/auth/handoff?${query}`, headers: { 'user-agent': 'Safari', ...extraHeaders } };const res = makeRes();await handler(req, res);return res;@@ -223,3 +223,20 @@ describe('GET /api/auth/handoff (exchange)', () => {expect(createSession).not.toHaveBeenCalled();});});++describe('GET /api/auth/handoff (login CSRF)', () => {+ it.each(['cross-site', 'same-site'])('does not redeem a code on a %s navigation', async (site) => {+ state.consumeRow = { user_id: USER.id, next_path: '/launch' };+ const res = await open(`code=${'a'.repeat(43)}&next=/launch`, { 'sec-fetch-site': site });+ expect(createSession).not.toHaveBeenCalled();+ expect(res.headers.location).toContain('/login?error=handoff_expired');+ expect(state.queries.some((q) => q.text.startsWith('update session_handoffs'))).toBe(false);+ });++ it.each([['none'], [undefined]])('still redeems a code opened from the app (sec-fetch-site %s)', async (site) => {+ state.consumeRow = { user_id: USER.id, next_path: '/launch' };+ const res = await open(`code=${'a'.repeat(43)}&next=/launch`, site ? { 'sec-fetch-site': site } : {});+ expect(createSession).toHaveBeenCalledTimes(1);+ expect(res.headers.location).toContain('/launch');+ });+});diff --git a/tests/auth-login-csrf.test.js b/tests/auth-login-csrf.test.jsnew file mode 100644index 000000000..7e2323b2a--- /dev/null+++ b/tests/auth-login-csrf.test.js@@ -0,0 +1,132 @@+// Login CSRF: the sign-in completion endpoints must only finish a flow that+// this browser started. Otherwise an attacker feeds the victim's browser the+// attacker's own widget payload, assertion or handoff link and the victim ends+// up signed in as the attacker.++import { beforeEach, describe, expect, it, vi } from 'vitest';++process.env.PUBLIC_APP_ORIGIN ||= 'https://three.ws';+process.env.JWT_SECRET ||= 'test-saml-secret-at-least-32-characters';++const state = { created: 0, verified: 0, samlValidated: 0, flowCookie: null };++vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => null),+ createSession: vi.fn(async () => { state.created++; return 'tok'; }),+ destroySession: vi.fn(async () => {}),+ sessionCookie: (t) => `__Host-sid=${t}`,+ isSameSiteOrigin: () => true,+}));+vi.mock('../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));+vi.mock('../api/_lib/seed-default-agent.js', () => ({ seedDefaultAgent: vi.fn() }));+vi.mock('../api/_lib/referrals.js', () => ({ referralCodeCandidates: vi.fn(() => []) }));+vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));+vi.mock('../api/_lib/gateway/bots.js', () => ({ telegramUsername: vi.fn() }));+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: new Proxy({}, { get: () => async () => ({ success: true }) }),+ clientIp: () => '203.0.113.7',+}));+vi.mock('../api/_lib/db.js', () => ({+ sql: vi.fn(async () => [{ id: 'u9', deleted_at: null }]),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));+vi.mock('../api/_lib/account-link/telegram-login.js', async (orig) => {+ const real = await orig();+ return {+ ...real,+ telegramLoginConfigured: () => true,+ verifyWidgetPayload: vi.fn(() => {+ state.verified++;+ return { payloadHash: 'h', authDate: new Date(), claims: { id: 1 } };+ }),+ recordWidgetPayload: vi.fn(async () => {}),+ claimsFrom: () => ({ subject: '1' }),+ resolveLoginUser: vi.fn(async () => ({ userId: 'u1', isNew: false })),+ };+});+vi.mock('../api/_lib/identities.js', async (orig) => {+ const real = await orig();+ return { ...real, findUserByIdentity: vi.fn(async () => ({ id: 'u1', identity_id: 'i1' })), touchIdentity: vi.fn(async () => {}) };+});++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ setHeader(k, v) { this.headers[String(k).toLowerCase()] = v; },+ getHeader(k) { return this.headers[String(k).toLowerCase()]; },+ removeHeader() {},+ writeHead(c, h) { this.statusCode = c; Object.assign(this.headers, h || {}); return this; },+ get headersSent() { return false; },+ get writableEnded() { return false; },+ end() { return this; },+ };+}++beforeEach(() => {+ state.created = 0;+ state.verified = 0;+ vi.clearAllMocks();+});++describe('telegram widget callback', () => {+ it('does not sign anyone in when the browser has no flow cookie', async () => {+ const { default: handler } = await import('../api/auth/telegram/[action].js');+ const req = {+ method: 'GET',+ url: '/api/auth/telegram/callback?id=1&hash=x&auth_date=1',+ headers: { host: 'three.ws' },+ query: { action: 'callback' },+ };+ const res = makeRes();+ await handler(req, res);+ expect(state.created).toBe(0);+ expect(String(res.headers.location || '')).toContain('/login');+ expect(String(res.headers['set-cookie'] || '')).not.toContain('__Host-sid');+ });+});++describe('saml acs', () => {+ it('does not sign anyone in when the browser did not start the login', async () => {+ vi.doMock('../api/_lib/saml.js', async (orig) => {+ const real = await orig();+ return {+ ...real,+ samlConfigured: () => true,+ getSamlInstance: async () => ({+ validatePostResponseAsync: async () => {+ state.samlValidated++;+ return { profile: { nameID: 'attacker', issuer: 'idp' } };+ },+ }),+ extractSamlIdentity: () => ({ nameID: 'attacker', issuer: 'idp', email: '[email protected]' }),+ };+ });+ vi.doMock('../api/_lib/http.js', async (orig) => ({+ ...(await orig()),+ readForm: async () => ({ SAMLResponse: 'x', RelayState: await (await import('../api/_lib/saml.js')).signRelayState({ next: '/dashboard' }) }),+ }));+ const { default: handler } = await import('../api/auth/saml/[action].js');+ const req = { method: 'POST', url: '/api/auth/saml/acs', headers: {}, query: { action: 'acs' } };+ const res = makeRes();+ await handler(req, res);+ expect(state.created).toBe(0);+ expect(String(res.headers.location || '')).toContain('error=');+ });++ it('signs in when the cookie set at /login matches the RelayState', async () => {+ const { signRelayState } = await import('../api/_lib/saml.js');+ const relay = await signRelayState({ next: '/dashboard', n: 'x' });+ vi.doMock('../api/_lib/http.js', async (orig) => ({+ ...(await orig()),+ readForm: async () => ({ SAMLResponse: 'x', RelayState: relay }),+ }));+ vi.resetModules();+ const { default: handler } = await import('../api/auth/saml/[action].js');+ const req = { method: 'POST', url: '/api/auth/saml/acs', headers: { cookie: `__Host-samlflow=${relay}` }, query: { action: 'acs' } };+ const res = makeRes();+ await handler(req, res);+ expect(state.created).toBe(1);+ });+});