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): consume password-reset tokens atomically and bind GitHub connect to the browser that started it

nirholas19c149181385
diff --git a/api/auth/[action].js b/api/auth/[action].js
index ccf9712fc..0330cac4b 100644
--- a/api/auth/[action].js
+++ b/api/auth/[action].js
@@ -454,12 +454,24 @@ async function handleResetPassword(req, res) {
if (!rl.success) return rateLimited(res, rl, 'too many attempts; try again later');
const body = parse(resetSchema, await readJson(req));
const tokenHash = await sha256(body.token);
- const rows = await sql`select r.id, r.user_id from password_resets r join users u on u.id = r.user_id where r.token_hash = ${tokenHash} and r.consumed_at is null and r.expires_at > now() and u.deleted_at is null limit 1`;
+ // Consume the token in the same statement that checks it, so two concurrent
+ // resets with one link cannot both win (a read-then-write let them).
+ const rows = await sql`
+ update password_resets r set consumed_at = now()
+ from users u
+ where u.id = r.user_id and r.token_hash = ${tokenHash} and r.consumed_at is null
+ and r.expires_at > now() and u.deleted_at is null
+ returning r.id, r.user_id
+ `;
if (!rows[0]) return error(res, 400, 'invalid_token', 'reset link is invalid or has expired');
+ const userId = rows[0].user_id;
const hash = await hashPassword(body.password);
- await sql`update users set password_hash = ${hash}, updated_at = now() where id = ${rows[0].user_id}`;
- await sql`update password_resets set consumed_at = now() where id = ${rows[0].id}`;
- await sql`update sessions set revoked_at = now() where user_id = ${rows[0].user_id} and revoked_at is null`;
+ await sql`update users set password_hash = ${hash}, updated_at = now() where id = ${userId}`;
+ // A reset is how an owner recovers a compromised account, so every credential
+ // the attacker could still hold goes: browser sessions and OAuth refresh
+ // tokens, exactly as logout-everywhere revokes them.
+ await sql`update sessions set revoked_at = now() where user_id = ${userId} and revoked_at is null`;
+ await sql`update oauth_refresh_tokens set revoked_at = now() where user_id = ${userId} and revoked_at is null`;
return json(res, 200, { success: true });
}
diff --git a/api/auth/github/[action].js b/api/auth/github/[action].js
index ff83324fe..0bd924134 100644
--- a/api/auth/github/[action].js
+++ b/api/auth/github/[action].js
@@ -119,10 +119,18 @@ async function handleCallback(req, res) {
return error(res, 400, 'state_expired', 'OAuth state has expired — please try again');
}
- // Session-bind: if a session is active it must match the state's userId so a
- // state token can't be replayed by a different user in their browser session.
+ // Session-bind, and require the session. The state is a signed token, not a
+ // browser-bound one, so without this an attacker could start a connect on
+ // their own account and hand the GitHub link to a signed-out victim who has
+ // authorized the app before: GitHub redirects silently, and the victim's
+ // token would land on the attacker's account. The flow starts from a signed-in
+ // page and returns as a top-level GET, so the SameSite=Lax cookie is present
+ // on every legitimate callback.
const callbackSession = await getSessionUser(req).catch(() => null);
- if (callbackSession && callbackSession.id !== stateData.userId) {
+ if (!callbackSession) {
+ return redirect(res, `${env.APP_ORIGIN}/settings?tab=connected-accounts&github=error`);
+ }
+ if (callbackSession.id !== stateData.userId) {
return error(res, 403, 'session_mismatch', 'OAuth state does not match the current session');
}
diff --git a/src/privy-login.js b/src/privy-login.js
index 84abf95be..51a6d79dc 100644
--- a/src/privy-login.js
+++ b/src/privy-login.js
@@ -14,12 +14,18 @@ import {
// looked for it, but nothing on this page loaded it, so the Solana button
// answered "No Solana wallet detected" inside the app.
import '../solana-mobile/src/index.js';
+import { safeNext } from './safe-next.js';
-const next =
+// Every source here is something a link can set (`?next=` straight from the
+// address bar), so it is reduced to a same-origin path before any
+// `location.href = next`; an absolute or protocol-relative value would
+// otherwise send a freshly signed-in visitor to another site.
+const next = safeNext(
window.__loginNext ||
- new URLSearchParams(location.search).get('next') ||
- sessionStorage.getItem('login_redirect') ||
- '/dashboard';
+ new URLSearchParams(location.search).get('next') ||
+ sessionStorage.getItem('login_redirect') ||
+ '/dashboard',
+);
sessionStorage.removeItem('login_redirect');
// ── Bootstrap ────────────────────────────────────────────────────────────────
diff --git a/tests/github-token-connect.test.js b/tests/github-token-connect.test.js
index a32cdb0e4..f8255ca8c 100644
--- a/tests/github-token-connect.test.js
+++ b/tests/github-token-connect.test.js
@@ -404,3 +404,41 @@ describe('POST /api/auth/github/disconnect', () => {
expect(revokeGrantMock).toHaveBeenCalledTimes(1);
});
});
+
+// ── OAuth callback: the state must come back to the browser that started it ──
+
+describe('GET /api/auth/github/callback', () => {
+ async function signedState(payload) {
+ const { hmacSha256 } = await import('../api/_lib/crypto.js');
+ const data = Buffer.from(JSON.stringify(payload)).toString('base64url');
+ return `${data}.${await hmacSha256(envMock.JWT_SECRET, data)}`;
+ }
+
+ async function callback(state) {
+ envMock.GITHUB_OAUTH_CLIENT_ID = 'client-id';
+ envMock.GITHUB_OAUTH_CLIENT_SECRET = 'client-secret';
+ const res = mkRes();
+ const req = mkReq({ method: 'GET', action: 'callback' });
+ req.url = `/api/auth/github/callback?action=callback&code=gh-code&state=${encodeURIComponent(state)}`;
+ await handler(req, res);
+ return res;
+ }
+
+ it("refuses a signed-out browser, so an attacker's state cannot bind a victim's GitHub", async () => {
+ const fetchSpy = vi.spyOn(globalThis, 'fetch');
+ getSessionUserMock.mockResolvedValue(null);
+ const res = await callback(await signedState({ userId: USER, agentId: '', ts: Date.now() }));
+ expect(res.statusCode).toBe(302);
+ expect(res.headers.location).toContain('github=error');
+ expect(fetchSpy).not.toHaveBeenCalled();
+ expect(sqlMock).not.toHaveBeenCalled();
+ fetchSpy.mockRestore();
+ });
+
+ it('refuses a different signed-in account', async () => {
+ getSessionUserMock.mockResolvedValue({ id: '66666666-6666-4666-8666-666666666666' });
+ const res = await callback(await signedState({ userId: USER, agentId: '', ts: Date.now() }));
+ expect(res.statusCode).toBe(403);
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+});