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.

fix(auth): never link a Privy, SAML or wallet sign-in to an account whose email was never verified

nirholas0b02d0764461
diff --git a/api/auth/privy/verify.js b/api/auth/privy/verify.js
index c1347bd87..c945fba00 100644
--- a/api/auth/privy/verify.js
+++ b/api/auth/privy/verify.js
@@ -70,6 +70,7 @@ export default wrap(async (req, res) => {
// Privy login without spawning a duplicate). Stamp privy_did on link.
let userId;
let isNew = false;
+ let emailHeld = false;
const [byDid] = await sql`
select id from users where privy_did = ${privyDid} and deleted_at is null limit 1
@@ -79,19 +80,26 @@ export default wrap(async (req, res) => {
userId = byDid.id;
} else if (realEmail) {
const [byEmail] = await sql`
- select id from users where email = ${realEmail} and deleted_at is null limit 1
+ select id, email_verified from users where email = ${realEmail} and deleted_at is null limit 1
`;
- if (byEmail) {
+ // Link only to an account whose email this platform has itself verified.
+ // Registration does not prove the inbox, so an unverified row may be
+ // someone who registered a stranger's address in advance; linking it would
+ // sign the real owner into the squatter's account (the squatter keeps the
+ // password). Such a row is left alone and this identity gets its own account.
+ if (byEmail?.email_verified) {
userId = byEmail.id;
await sql`update users set privy_did = ${privyDid} where id = ${userId}`;
+ } else if (byEmail) {
+ emailHeld = true;
}
}
if (!userId) {
- // New passwordless user. Use the real email when present, else a stable
- // synthetic scoped to the DID (matches the SIWE/SIWS @*.local convention).
+ // New passwordless user. Use the real email when present and free, else a
+ // stable synthetic scoped to the DID (matches the SIWE/SIWS @*.local convention).
const effectiveEmail =
- realEmail || `privy-${privyDid.replace('did:privy:', '')}@privy.local`;
+ (!emailHeld && realEmail) || `privy-${privyDid.replace('did:privy:', '')}@privy.local`;
// The conflict branch relinks the Privy identity but never clears
// deleted_at: the owner confirmed that deletion by hand, so a later Privy
// sign-in answers account_deleted (matching the SIWE, SIWS, and SAML
diff --git a/api/auth/saml/[action].js b/api/auth/saml/[action].js
index fbebcc0c9..90efb2bee 100644
--- a/api/auth/saml/[action].js
+++ b/api/auth/saml/[action].js
@@ -159,9 +159,16 @@ async function findOrCreateUser({ issuer, nameID, email, name }) {
return bySaml.id;
}
+ let emailHeld = false;
if (email) {
- const [byEmail] = await sql`select id, deleted_at from users where email = ${email} limit 1`;
- if (byEmail) {
+ const [byEmail] = await sql`select id, deleted_at, email_verified from users where email = ${email} limit 1`;
+ // Link only to an account whose email this platform has verified. An
+ // unverified row may be somebody who registered the address first to have
+ // the real owner's SSO sign-in land in an account they hold the password
+ // to. It is left alone, and this identity gets its own account.
+ if (byEmail && !byEmail.deleted_at && !byEmail.email_verified) {
+ emailHeld = true;
+ } else if (byEmail) {
if (byEmail.deleted_at) {
throw Object.assign(new Error('account deleted'), { code: 'account_deleted' });
}
@@ -178,14 +185,14 @@ async function findOrCreateUser({ issuer, nameID, email, name }) {
// Synthetic, non-deliverable address when the IdP releases no email — mirrors
// the wallet-login convention (…@wallet.local) so downstream code that keys
// off email still works.
- const userEmail = email || `saml-${await subjectHash(issuer, nameID)}@sso.three.ws.local`;
+ const userEmail = (!emailHeld && email) || `saml-${await subjectHash(issuer, nameID)}@sso.three.ws.local`;
const displayName = name || (email ? email.split('@')[0] : 'SSO User');
const userId = await insertSamlUser({
email: userEmail,
displayName,
issuer: issuerKey,
nameID,
- emailVerified: Boolean(email),
+ emailVerified: Boolean(email) && !emailHeld,
});
queueMicrotask(() => seedDefaultAgent(userId));
return userId;
diff --git a/tests/api/siwe-handler.test.js b/tests/api/siwe-handler.test.js
index f4c5d9dd4..6ea0bcd5d 100644
--- a/tests/api/siwe-handler.test.js
+++ b/tests/api/siwe-handler.test.js
@@ -202,6 +202,7 @@ describe('POST /api/auth/siwe/verify', () => {
sqlState.queue.push([{ nonce: TEST_NONCE, expires_at: FUTURE, consumed_at: null }]);
sqlState.queue.push([{ nonce: TEST_NONCE }]); // burn RETURNING
sqlState.queue.push([]); // no wallet
+ sqlState.queue.push([]); // placeholder address not squatted by a password account
sqlState.queue.push([]); // no existing user
sqlState.queue.push([{ id: 'user-new', inserted: true }]); // insert user
sqlState.queue.push([]); // insert wallet
@@ -223,6 +224,32 @@ describe('POST /api/auth/siwe/verify', () => {
expect(cookie).toContain('__Host-sid=siwe-session-token');
});
+ it('never hands a wallet to a password account squatting its placeholder email', async () => {
+ sqlState.queue.push([{ nonce: TEST_NONCE, expires_at: FUTURE, consumed_at: null }]);
+ sqlState.queue.push([{ nonce: TEST_NONCE }]); // burn RETURNING
+ sqlState.queue.push([]); // no wallet
+ sqlState.queue.push([{ '?column?': 1 }]); // placeholder held by a password account
+ sqlState.queue.push([]); // no passwordless account at the fresh address
+ sqlState.queue.push([{ id: 'user-fresh', inserted: true }]); // insert user
+ sqlState.queue.push([]); // insert wallet
+ sqlState.queue.push([]); // seedDefaultAgent
+
+ const { status } = await invoke({
+ action: 'verify',
+ method: 'POST',
+ body: { message: SIWE_MESSAGE, signature: `0x${'ab'.repeat(65)}` },
+ headers: withCsrf(),
+ });
+
+ expect(status).toBe(200);
+ const lookup = sqlState.calls.find((c) => /where wallet_address = .* or \(email = .* and password_hash is null\)/is.test(c.query));
+ expect(lookup, 'the existing-user lookup must skip password accounts').toBeTruthy();
+ const insert = sqlState.calls.find((c) => /insert into users/i.test(c.query));
+ expect(insert).toBeTruthy();
+ const email = insert.values.find((v) => typeof v === 'string' && v.endsWith('@wallet.local'));
+ expect(email).toMatch(/^wallet-0x[0-9a-f]{40}\.[a-z0-9_-]+@wallet\.local$/);
+ });
+
it('returns 400 with nonce_reused when nonce was already consumed', async () => {
sqlState.queue.push([{ nonce: TEST_NONCE, expires_at: FUTURE, consumed_at: '2024-01-01T00:00:00.000Z' }]);
@@ -273,6 +300,7 @@ describe('POST /api/auth/siwe/verify', () => {
sqlState.queue.push([{ nonce: TEST_NONCE, expires_at: FUTURE, consumed_at: null }]);
sqlState.queue.push([{ nonce: TEST_NONCE }]); // burn RETURNING
sqlState.queue.push([]); // no user_wallets row
+ sqlState.queue.push([]); // placeholder address not squatted by a password account
sqlState.queue.push([{ id: 'user-gone', deleted_at: '2026-01-01T00:00:00.000Z' }]);
const { status, body, res } = await invoke({
diff --git a/tests/auth-privy-verify.test.js b/tests/auth-privy-verify.test.js
index 4c5d2243c..2e310f44e 100644
--- a/tests/auth-privy-verify.test.js
+++ b/tests/auth-privy-verify.test.js
@@ -145,3 +145,45 @@ describe('POST /api/auth/privy/verify: deleted accounts', () => {
expect(statements.some((t) => /deleted_at = null/i.test(t))).toBe(false);
});
});
+
+describe('POST /api/auth/privy/verify: email linking', () => {
+ it('never links a Privy identity to an account whose email was never verified', async () => {
+ // Registration does not prove the inbox, so an unverified row holding the
+ // victim's address may be a squatter who keeps its password. The real
+ // owner's Privy sign-in must get its own account, not that one.
+ const { extractIdentity } = await import('../api/_lib/privy.js');
+ vi.mocked(extractIdentity).mockReturnValueOnce({ email: '[email protected]' });
+ const calls = [];
+ sqlMock.mockImplementation(async (strings, ...values) => {
+ const text = Array.isArray(strings) ? strings.join(' ') : String(strings);
+ calls.push({ text, values });
+ if (text.includes('select id, email_verified from users')) return [{ id: 'squatter', email_verified: false }];
+ if (text.includes('insert into users')) return [{ id: 'user-fresh', deleted_at: null, inserted: true }];
+ return [];
+ });
+
+ const res = makeRes();
+ await handler(makeReq({ origin: 'https://three.ws' }), res);
+ expect(res.statusCode).toBe(200);
+ expect(calls.some((c) => /update users set privy_did/.test(c.text))).toBe(false);
+ const insert = calls.find((c) => c.text.includes('insert into users'));
+ expect(insert.values[0]).toBe('[email protected]');
+ });
+
+ it('links to an existing account whose email is verified', async () => {
+ const { extractIdentity } = await import('../api/_lib/privy.js');
+ vi.mocked(extractIdentity).mockReturnValueOnce({ email: '[email protected]' });
+ const calls = [];
+ sqlMock.mockImplementation(async (strings, ...values) => {
+ const text = Array.isArray(strings) ? strings.join(' ') : String(strings);
+ calls.push({ text, values });
+ if (text.includes('select id, email_verified from users')) return [{ id: 'owner', email_verified: true }];
+ return [];
+ });
+
+ const res = makeRes();
+ await handler(makeReq({ origin: 'https://three.ws' }), res);
+ expect(calls.some((c) => /update users set privy_did/.test(c.text))).toBe(true);
+ expect(calls.some((c) => c.text.includes('insert into users'))).toBe(false);
+ });
+});
diff --git a/tests/auth-verify-email-binding.test.js b/tests/auth-verify-email-binding.test.js
new file mode 100644
index 000000000..f954d0a61
--- /dev/null
+++ b/tests/auth-verify-email-binding.test.js
@@ -0,0 +1,132 @@
+// POST /api/auth/verify-email and POST /api/auth/forgot-password abuse gates.
+//
+// verify-email used to match a 6-digit code against EVERY account's pending
+// codes with no session, so the code space was shared: a caller holding many
+// unverified sign-ups could verify one of them by guessing, never reading a
+// mailbox. These tests pin that the code is checked only against the signed-in
+// account, that the account has its own attempt budget, and that
+// forgot-password caps a single sender across addresses.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+process.env.APP_ORIGIN = 'https://three.ws';
+process.env.JWT_SECRET ||= 'vitest-ephemeral-jwt-secret-00000000000000';
+
+vi.mock('../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));
+vi.mock('../api/_lib/sentry.js', () => ({ captureException: () => {} }));
+
+const statements = [];
+const pending = vi.hoisted(() => ({ rows: [] }));
+const sqlMock = vi.fn(async (strings, ...values) => {
+ const text = Array.isArray(strings) ? strings.join(' ') : String(strings);
+ statements.push({ text: text.replace(/\s+/g, ' ').trim(), values });
+ if (text.includes('from email_verifications v')) {
+ const [userId, codeHash] = values;
+ return pending.rows.filter((r) => r.user_id === userId && r.code_hash === codeHash);
+ }
+ return [];
+});
+vi.mock('../api/_lib/db.js', () => ({ sql: (strings, ...values) => sqlMock(strings, ...values) }));
+
+const getSessionUser = vi.fn();
+vi.mock('../api/_lib/auth.js', async () => {
+ const actual = await vi.importActual('../api/_lib/auth.js');
+ return { ...actual, getSessionUser: (...args) => getSessionUser(...args) };
+});
+
+const verdicts = vi.hoisted(() => ({ verifyEmailUser: true, forgotPasswordIp: true }));
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: {
+ authIp: vi.fn(async () => ({ success: true })),
+ verifyEmailIp: vi.fn(async () => ({ success: true })),
+ verifyEmailUser: vi.fn(async () => ({ success: verdicts.verifyEmailUser, reset: Date.now() + 1000 })),
+ forgotPasswordIp: vi.fn(async () => ({ success: verdicts.forgotPasswordIp, reset: Date.now() + 1000 })),
+ forgotPasswordEmail: vi.fn(async () => ({ success: true })),
+ },
+ clientIp: () => '127.0.0.1',
+}));
+vi.mock('../api/_lib/email.js', () => ({
+ sendPasswordResetEmail: vi.fn(async () => {}),
+ sendVerificationEmail: vi.fn(async () => {}),
+}));
+vi.mock('../api/_lib/seed-default-agent.js', () => ({ seedDefaultAgent: vi.fn() }));
+vi.mock('../api/_lib/usage.js', () => ({ recordEvent: vi.fn() }));
+
+const { default: handler } = await import('../api/auth/[action].js');
+const { sha256 } = await import('../api/_lib/crypto.js');
+
+const VICTIM = '11111111-1111-4111-8111-111111111111';
+const ATTACKER = '22222222-2222-4222-8222-222222222222';
+
+function makeReq(action, body) {
+ return {
+ method: 'POST',
+ url: `/api/auth/${action}`,
+ query: { action },
+ headers: { 'content-type': 'application/json', origin: 'https://three.ws' },
+ socket: { remoteAddress: '127.0.0.1' },
+ body: JSON.stringify(body),
+ };
+}
+function makeRes() {
+ const r = { statusCode: 200, _h: {}, _b: null };
+ r.setHeader = (k, v) => { r._h[k.toLowerCase()] = v; };
+ r.getHeader = (k) => r._h[k.toLowerCase()];
+ r.end = (b) => { r._b = b; };
+ r.json = () => JSON.parse(r._b);
+ return r;
+}
+
+beforeEach(async () => {
+ statements.length = 0;
+ getSessionUser.mockReset();
+ verdicts.verifyEmailUser = true;
+ verdicts.forgotPasswordIp = true;
+ pending.rows = [{ id: 'v-1', user_id: VICTIM, code_hash: await sha256('123456') }];
+});
+
+describe('verify-email', () => {
+ it('refuses an anonymous caller before touching any code', async () => {
+ getSessionUser.mockResolvedValue(null);
+ const res = makeRes();
+ await handler(makeReq('verify-email', { code: '123456' }), res);
+ expect(res.statusCode).toBe(401);
+ expect(statements.some((s) => s.text.includes('email_verifications'))).toBe(false);
+ });
+
+ it("never verifies another account's pending code", async () => {
+ getSessionUser.mockResolvedValue({ id: ATTACKER });
+ const res = makeRes();
+ await handler(makeReq('verify-email', { code: '123456' }), res);
+ expect(res.statusCode).toBe(400);
+ expect(statements.some((s) => s.text.startsWith('update users set email_verified'))).toBe(false);
+ });
+
+ it("verifies the signed-in account's own code", async () => {
+ getSessionUser.mockResolvedValue({ id: VICTIM });
+ const res = makeRes();
+ await handler(makeReq('verify-email', { code: '123456' }), res);
+ expect(res.statusCode).toBe(200);
+ const update = statements.find((s) => s.text.startsWith('update users set email_verified'));
+ expect(update.values).toContain(VICTIM);
+ });
+
+ it('stops guessing once the account budget is spent', async () => {
+ getSessionUser.mockResolvedValue({ id: VICTIM });
+ verdicts.verifyEmailUser = false;
+ const res = makeRes();
+ await handler(makeReq('verify-email', { code: '123456' }), res);
+ expect(res.statusCode).toBe(429);
+ expect(statements.some((s) => s.text.includes('email_verifications'))).toBe(false);
+ });
+});
+
+describe('forgot-password', () => {
+ it('caps one sender walking a list of addresses', async () => {
+ verdicts.forgotPasswordIp = false;
+ const res = makeRes();
+ await handler(makeReq('forgot-password', { email: '[email protected]' }), res);
+ expect(res.statusCode).toBe(429);
+ expect(statements).toHaveLength(0);
+ });
+});