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): scope email codes to the signed-in account and stop wallet sign-in pre-claims

nirholas50b675e086a0
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index efb6be9b2..2dedbf96a 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -1644,6 +1644,14 @@ export const limits = {
// codes / spamming reset+verify emails must fail closed when Redis is down.
verifyEmailIp: (ip) =>
getLimiter('verify-email:ip', { limit: 10, window: '15 m', critical: true }).limit(ip),
+ // Per account as well as per IP: a code lives 30 minutes, so this bounds
+ // the guesses any one pending code can take to ~20 however many IPs try.
+ verifyEmailUser: (userId) =>
+ getLimiter('verify-email:user', { limit: 10, window: '15 m', critical: true }).limit(userId),
+ // Reset mail goes only to registered addresses, but the per-email bucket
+ // alone lets one client walk a list of them; this caps the sender.
+ forgotPasswordIp: (ip) =>
+ getLimiter('forgot-password:ip', { limit: 10, window: '15 m', critical: true }).limit(ip),
forgotPasswordEmail: (email) =>
getLimiter('forgot-password:email', { limit: 3, window: '15 m', critical: true }).limit(
email,
diff --git a/api/_lib/validate.js b/api/_lib/validate.js
index 5401e3a36..1e181f39a 100644
--- a/api/_lib/validate.js
+++ b/api/_lib/validate.js
@@ -113,8 +113,19 @@ export const httpUrl = z
message: 'must be an http(s) URL',
});
+// `.local` addresses are minted by the platform itself for accounts with no
+// real inbox: wallet sign-in (`@wallet.local`), Privy (`@privy.local`), SAML
+// (`@sso.three.ws.local`) and username sign-up (`@users.three.ws.local`). Those
+// flows find an existing account by that exact address, and comp access trusts
+// the local part of a `@users.three.ws.local` address as a handle, so letting a
+// person register one would let them pre-claim a stranger's wallet account or
+// someone else's comped handle. No real inbox lives under `.local` (RFC 6762).
+export const registrableEmail = email.refine((v) => !/\.local$/.test(v.slice(v.lastIndexOf('@') + 1)) && !v.endsWith('@local'), {
+ message: 'this email domain is reserved',
+});
+
export const registerBody = z.object({
- email,
+ email: registrableEmail,
password,
display_name: displayName.optional(),
referralCode: z.string().trim().min(3).max(30).optional(),
diff --git a/api/auth/[action].js b/api/auth/[action].js
index 402816ac6..ccf9712fc 100644
--- a/api/auth/[action].js
+++ b/api/auth/[action].js
@@ -427,6 +427,8 @@ const forgotSchema = z.object({ email });
async function handleForgotPassword(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
+ const ipRl = await limits.forgotPasswordIp(clientIp(req));
+ if (!ipRl.success) return rateLimited(res, ipRl, 'too many reset requests; try again later');
const body = parse(forgotSchema, await readJson(req));
const rl = await limits.forgotPasswordEmail(body.email);
if (!rl.success) return json(res, 200, { success: true });
@@ -465,14 +467,22 @@ async function handleResetPassword(req, res) {
const verifyEmailSchema = z.object({ code: z.string().trim().regex(/^\d{6}$/, '6-digit code required') });
+// The code is checked against the SIGNED-IN account's own pending codes only.
+// Matching it against every account's codes made the 6-digit space shared: an
+// anonymous caller holding k unverified sign-ups could verify one of them with
+// probability k/1e6 per guess, without ever reading a mailbox.
async function handleVerifyEmail(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
const rl = await limits.verifyEmailIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl, 'too many attempts; try again later');
+ const session = await getSessionUser(req);
+ if (!session) return error(res, 401, 'unauthorized', 'sign in to verify your email');
+ const userRl = await limits.verifyEmailUser(session.id);
+ if (!userRl.success) return rateLimited(res, userRl, 'too many attempts; request a new code and try again later');
const body = parse(verifyEmailSchema, await readJson(req));
const codeHash = await sha256(body.code);
- const rows = await sql`select v.id, v.user_id from email_verifications v join users u on u.id = v.user_id where v.code_hash = ${codeHash} and v.consumed_at is null and v.expires_at > now() and u.deleted_at is null limit 1`;
+ const rows = await sql`select v.id, v.user_id from email_verifications v join users u on u.id = v.user_id where v.user_id = ${session.id} and v.code_hash = ${codeHash} and v.consumed_at is null and v.expires_at > now() and u.deleted_at is null limit 1`;
if (!rows[0]) return error(res, 400, 'invalid_code', 'invalid or expired verification code');
await sql`update email_verifications set consumed_at = now() where id = ${rows[0].id}`;
await sql`update users set email_verified = true, updated_at = now() where id = ${rows[0].user_id}`;
diff --git a/api/auth/siwe/[action].js b/api/auth/siwe/[action].js
index f6540440f..5eb9d75d9 100644
--- a/api/auth/siwe/[action].js
+++ b/api/auth/siwe/[action].js
@@ -237,13 +237,21 @@ async function handleVerify(req, res) {
// Fall back to users.wallet_address — older rows may have been created
// before user_wallets existed, or by a different flow that only set the
// users column. Reconcile by backfilling user_wallets.
- const placeholderEmail = `wallet-${addrLower}@wallet.local`;
+ let placeholderEmail = `wallet-${addrLower}@wallet.local`;
+ // A row at the placeholder address that carries a password was not made
+ // by wallet sign-in (which never sets one): somebody registered the
+ // derivable address to pre-claim this wallet. Never hand the wallet to
+ // it, and mint any new account under a second address it cannot hold.
+ const [squatted] = await sql`
+ select 1 from users where email = ${placeholderEmail} and password_hash is not null limit 1
+ `;
+ if (squatted) placeholderEmail = `wallet-${addrLower}.${randomToken(8).toLowerCase()}@wallet.local`;
// Include soft-deleted rows: the email unique index ignores deleted_at, so
// skipping them would turn a retired account into a duplicate-key 500 on
// the insert below. A soft-deleted hit is refused, never revived.
const [existingUser] = await sql`
select id, deleted_at from users
- where wallet_address = ${addrLower} or email = ${placeholderEmail}
+ where wallet_address = ${addrLower} or (email = ${placeholderEmail} and password_hash is null)
limit 1
`;
diff --git a/api/auth/siws/[action].js b/api/auth/siws/[action].js
index a89d8e45e..8413a40dd 100644
--- a/api/auth/siws/[action].js
+++ b/api/auth/siws/[action].js
@@ -213,12 +213,21 @@ async function handleVerify(req, res) {
// addresses sharing a prefix into one account. Existing users are unaffected:
// returning wallets are matched by address in user_wallets above, never by
// this synthetic email (which is only used to create brand-new rows).
- const placeholderEmail = `sol-${(await sha256(addr)).slice(0, 16)}@wallet.local`;
- const [existingUser] = await sql`
- select id, deleted_at from users
+ const addrHash = await sha256(addr);
+ let placeholderEmail = `sol-${addrHash.slice(0, 16)}@wallet.local`;
+ let [existingUser] = await sql`
+ select id, deleted_at, password_hash from users
where email = ${placeholderEmail}
limit 1
`;
+ // A row at this address that carries a password was not made by wallet
+ // sign-in (which never sets one): it is somebody who registered the
+ // derivable placeholder to pre-claim this wallet. Never hand the wallet
+ // to it; mint the account under a fresh address it cannot hold.
+ if (existingUser?.password_hash) {
+ placeholderEmail = `sol-${addrHash.slice(0, 16)}.${randomToken(8).toLowerCase()}@wallet.local`;
+ existingUser = null;
+ }
if (existingUser) {
if (existingUser.deleted_at) {