Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(platform): require a verified email before the first session, and provision the platform User at sign-up (#15135)

Bently81cb5d7e49c7
diff --git a/.secrets.baseline b/.secrets.baseline
index 3720c681e0..f9bd797951 100644
--- a/.secrets.baseline
+++ b/.secrets.baseline
@@ -547,6 +547,29 @@
"line_number": 117
}
],
+ "autogpt_platform/frontend/src/lib/auth/__tests__/auth-config.test.ts": [
+ {
+ "type": "Secret Keyword",
+ "filename": "autogpt_platform/frontend/src/lib/auth/__tests__/auth-config.test.ts",
+ "hashed_secret": "abf7aad6438836dbe526aa231abde2d0eef74d42",
+ "is_verified": false,
+ "line_number": 138
+ },
+ {
+ "type": "Secret Keyword",
+ "filename": "autogpt_platform/frontend/src/lib/auth/__tests__/auth-config.test.ts",
+ "hashed_secret": "d8c64feb1ce4fab46b6e0983217f3d4bcdea6257",
+ "is_verified": false,
+ "line_number": 140
+ },
+ {
+ "type": "Secret Keyword",
+ "filename": "autogpt_platform/frontend/src/lib/auth/__tests__/auth-config.test.ts",
+ "hashed_secret": "c26d1fbb65fd5c8648bf0c087209ae3ad16388ba",
+ "is_verified": false,
+ "line_number": 214
+ }
+ ],
"autogpt_platform/frontend/src/lib/autogpt-server-api/utils.ts": [
{
"type": "Base64 High Entropy String",
diff --git a/autogpt_platform/autogpt_libs/autogpt_libs/auth/dependencies.py b/autogpt_platform/autogpt_libs/autogpt_libs/auth/dependencies.py
index 6f7c788608..3d45a5fbd1 100644
--- a/autogpt_platform/autogpt_libs/autogpt_libs/auth/dependencies.py
+++ b/autogpt_platform/autogpt_libs/autogpt_libs/auth/dependencies.py
@@ -4,7 +4,10 @@ FastAPI dependency functions for JWT-based authentication and authorization.
These are the high-level dependency functions used in route definitions.
"""
+import asyncio
import logging
+import time
+from collections import OrderedDict
import fastapi
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
@@ -25,6 +28,81 @@ IMPERSONATION_HEADER_NAME = "X-Act-As-User-Id"
logger = logging.getLogger(__name__)
+# Recently settled self-heals, id -> monotonic expiry: a confirmed row for the
+# TTL, a failed heal (e.g. an email owned by another User) only for the
+# backoff, so it can't storm.
+_PROVISIONED_USER_IDS: "OrderedDict[str, float]" = OrderedDict()
+_PROVISIONED_USER_IDS_MAX = 10_000
+_PROVISIONED_USER_TTL_SECS = 15 * 60
+_FAILED_HEAL_BACKOFF_SECS = 60
+# Heals still running, id -> task: concurrent first requests for one user wait
+# on the same probe instead of each running their own.
+_HEALS_IN_FLIGHT: "dict[str, asyncio.Task[None]]" = {}
+
+
+def _is_heal_settled(user_id: str) -> bool:
+ """True while a recent heal outcome for *user_id* is still fresh."""
+ expires_at = _PROVISIONED_USER_IDS.get(user_id)
+ if expires_at is None:
+ return False
+ if expires_at <= time.monotonic():
+ del _PROVISIONED_USER_IDS[user_id]
+ return False
+ return True
+
+
+def _remember_heal(user_id: str, ttl: float) -> None:
+ _PROVISIONED_USER_IDS[user_id] = time.monotonic() + ttl
+ _PROVISIONED_USER_IDS.move_to_end(user_id)
+ while len(_PROVISIONED_USER_IDS) > _PROVISIONED_USER_IDS_MAX:
+ _PROVISIONED_USER_IDS.popitem(last=False)
+
+
+async def _heal_platform_user(jwt_payload: dict) -> None:
+ """Best-effort ``_ensure_platform_user`` for routes that authenticate
+ through ``get_user_id`` alone, which ``get_request_context`` doesn't heal.
+
+ Never raises, and is a no-op without the backend package or a connected DB.
+ """
+ user_id = jwt_payload.get("sub")
+ if not user_id or _is_heal_settled(user_id):
+ return
+
+ heal = _HEALS_IN_FLIGHT.get(user_id)
+ # A heal left behind by another event loop can't be awaited from this one.
+ if heal is None or heal.get_loop() is not asyncio.get_running_loop():
+ try:
+ from backend.data.db import prisma # deferred -- only needed at runtime
+ except ImportError:
+ return
+ if not prisma.is_connected():
+ return
+
+ heal = asyncio.ensure_future(_settle_heal(user_id, jwt_payload))
+ _HEALS_IN_FLIGHT[user_id] = heal
+ heal.add_done_callback(lambda done: _forget_heal(user_id, done))
+ # Shielded: a request that is cancelled must not cancel the heal that the
+ # other requests for this user are waiting on.
+ await asyncio.shield(heal)
+
+
+def _forget_heal(user_id: str, heal: "asyncio.Future[None]") -> None:
+ if _HEALS_IN_FLIGHT.get(user_id) is heal:
+ del _HEALS_IN_FLIGHT[user_id]
+
+
+async def _settle_heal(user_id: str, jwt_payload: dict) -> None:
+ try:
+ provisioned = await _ensure_platform_user(user_id, jwt_payload)
+ except Exception:
+ # A heal must never turn a request that would have worked into a 500.
+ logger.warning(f"Platform user self-heal failed for {user_id}", exc_info=True)
+ provisioned = False
+ _remember_heal(
+ user_id,
+ _PROVISIONED_USER_TTL_SECS if provisioned else _FAILED_HEAL_BACKOFF_SECS,
+ )
+
def get_optional_user_id(
credentials: HTTPAuthorizationCredentials | None = fastapi.Security(
@@ -102,6 +180,11 @@ async def get_user_id(
status_code=401, detail="User ID not found in token"
)
+ # Self-heal a missing platform User row for the token's own subject. Under
+ # impersonation that is the admin, never the target: the claims describe
+ # the admin, and provisioning the target from them would be wrong.
+ await _heal_platform_user(jwt_payload)
+
# Check for admin impersonation header
impersonate_header = request.headers.get(IMPERSONATION_HEADER_NAME, "").strip()
if impersonate_header:
@@ -131,9 +214,13 @@ ORG_HEADER_NAME = "X-Org-Id"
TEAM_HEADER_NAME = "X-Team-Id"
-async def _ensure_platform_user(user_id: str, jwt_payload: dict) -> None:
+async def _ensure_platform_user(user_id: str, jwt_payload: dict) -> bool:
"""Provision the platform ``User`` row for a valid token that has none.
+ Returns ``True`` when the row is known to exist afterwards (found, created,
+ or created by a concurrent request), ``False`` when it declined to try or
+ the attempt failed.
+
The auth provider and the platform keep separate user tables, bridged only
by the client calling ``POST /api/v1/auth/user`` after sign-in. Better Auth
issues a session the moment the auth identity is created, so a request can
@@ -159,16 +246,16 @@ async def _ensure_platform_user(user_id: str, jwt_payload: dict) -> None:
# under the admin's email.
if user_id != jwt_payload.get("sub"):
logger.debug("Not provisioning %s from an impersonator's claims", user_id)
- return
+ return False
if not jwt_payload.get("email"):
# Nothing to provision with, so this account stays broken. Say so —
# a silent return here is the exact failure mode this function exists
# to end: bricked and invisible.
logger.warning(f"Cannot provision user {user_id}: token carries no email claim")
- return
+ return False
if await prisma.user.find_unique(where={"id": user_id}) is not None:
- return
+ return True
from backend.data.user import get_or_create_user_with_status # deferred
@@ -195,16 +282,16 @@ async def _ensure_platform_user(user_id: str, jwt_payload: dict) -> None:
"exists; the caller's org bootstrap will finish or report",
exc_info=True,
)
- return
+ return True
logger.error(f"On-demand provisioning failed for user {user_id}", exc_info=True)
- return
+ return False
if not result.was_created:
# Returning without raising is not proof we created anything: a
# concurrent request can land its row between our probe and the
# get-or-create's own lookup, which then simply reads it back. That
# request reports the breach; this one would only double-count it.
- return
+ return True
# ERROR, not WARNING: LoggingIntegration reports this to Sentry, and a
# token with no platform user is an invariant breach worth seeing. Gated
@@ -213,6 +300,29 @@ async def _ensure_platform_user(user_id: str, jwt_payload: dict) -> None:
logger.error(
f"Provisioned a missing platform User row for {user_id} on first touch"
)
+ return True
+
+
+async def _finish_account_bootstrap(jwt_payload: dict) -> None:
+ """Run ``POST /auth/user``'s bootstrap for a row that never got one.
+
+ The auth hook inserts a bare ``User`` row when the identity is created. If
+ that session never reaches ``POST /auth/user`` (the OAuth flow lost its
+ redirect), the org bootstrap below would leave the account without its
+ marketplace Profile, and without the PostHog lifecycle sync.
+ Only reached once ``_ensure_platform_user`` has confirmed the row for the
+ token's own subject, and best-effort: the org bootstrap still runs after it.
+ """
+ from backend.data.user import get_or_create_user_with_status # deferred
+
+ try:
+ await get_or_create_user_with_status(jwt_payload)
+ except Exception:
+ logger.warning(
+ f"Account bootstrap failed for {jwt_payload.get('sub')}; "
+ "falling back to the org bootstrap",
+ exc_info=True,
+ )
async def get_request_context(
@@ -281,7 +391,8 @@ async def get_request_context(
# recoverable: the personal org, or the platform User row the org
# would hang off. Provision the user first so the bootstrap below
# has something to work with.
- await _ensure_platform_user(user_id, jwt_payload)
+ if await _ensure_platform_user(user_id, jwt_payload):
+ await _finish_account_bootstrap(jwt_payload)
org_id, _ = await get_user_default_team(user_id)
if org_id is None:
diff --git a/autogpt_platform/autogpt_libs/autogpt_libs/auth/dependencies_test.py b/autogpt_platform/autogpt_libs/autogpt_libs/auth/dependencies_test.py
index fe0455bcd4..5a8731f834 100644
--- a/autogpt_platform/autogpt_libs/autogpt_libs/auth/dependencies_test.py
+++ b/autogpt_platform/autogpt_libs/autogpt_libs/auth/dependencies_test.py
@@ -3,6 +3,7 @@ Comprehensive integration tests for authentication dependencies.
Tests the full authentication flow from HTTP requests to user validation.
"""
+import asyncio
import os
from unittest.mock import AsyncMock, Mock
@@ -774,6 +775,80 @@ class TestRequestContextProvisioning:
ensure.assert_not_awaited()
+ @pytest.fixture
+ def bootstrap(self, mocker: MockerFixture, wiring):
+ """The row exists (the auth hook wrote it bare); stub the full
+ get-or-create that ``POST /auth/user`` would have run."""
+ import sys
+ import types
+
+ ensure, calls = wiring
+
+ async def _ensure(user_id, payload):
+ calls.append("ensure_platform_user")
+ return True
+
+ ensure.side_effect = _ensure
+
+ async def _get_or_create(payload):
+ calls.append("get_or_create_user_with_status")
+
+ provisioner = AsyncMock(side_effect=_get_or_create)
+ user_mod = types.ModuleType("backend.data.user")
+ mocker.patch.object(
+ user_mod, "get_or_create_user_with_status", provisioner, create=True
+ )
+ mocker.patch.dict(sys.modules, {"backend.data.user": user_mod})
+ return ensure, provisioner, calls
+
+ @pytest.mark.asyncio
+ async def test_finishes_the_account_bootstrap_for_a_bare_row(self, bootstrap):
+ """A session that never reached ``POST /auth/user`` still gets the
+ Profile and sign-up sync that call would have run, not the org alone."""
+ from autogpt_libs.auth.dependencies import get_request_context
+
+ _, provisioner, calls = bootstrap
+ payload = {"sub": "user-1", "email": "[email protected]"}
+
+ await get_request_context(self._request(), payload)
+
+ provisioner.assert_awaited_once_with(payload)
+ assert calls == [
+ "ensure_platform_user",
+ "get_or_create_user_with_status",
+ "get_user_default_team",
+ ]
+
+ @pytest.mark.asyncio
+ async def test_a_failed_account_bootstrap_still_runs_the_org_bootstrap(
+ self, bootstrap
+ ):
+ from autogpt_libs.auth.dependencies import get_request_context
+
+ _, provisioner, calls = bootstrap
+ provisioner.side_effect = RuntimeError("profile insert failed")
+
+ ctx = await get_request_context(
+ self._request(), {"sub": "user-1", "email": "[email protected]"}
+ )
+
+ assert calls[-1] == "get_user_default_team"
+ assert ctx.org_id == "org-1"
+
+ @pytest.mark.asyncio
+ async def test_no_account_bootstrap_when_the_row_is_not_confirmed(self, bootstrap):
+ """Impersonation, a token without an email, or a failed provision:
+ ``_ensure_platform_user`` says no, and the claims must not be used."""
+ from autogpt_libs.auth.dependencies import get_request_context
+
+ ensure, provisioner, _ = bootstrap
+ ensure.side_effect = None
+ ensure.return_value = False
+
+ await get_request_context(self._request(), {"sub": "user-1", "email": "[email protected]"})
+
+ provisioner.assert_not_awaited()
+
class TestEnsurePlatformUserRaceLogging:
"""A losing create race must not be reported as a failure.
@@ -852,3 +927,359 @@ class TestEnsurePlatformUserRaceLogging:
await _ensure_platform_user("user-1", {"sub": "user-1", "email": "[email protected]"})
logger.error.assert_not_called()
+
+
+class TestGetUserIdSelfHeal:
+ """`get_user_id` must heal a missing platform User row on every request.
+
+ `get_request_context` only heals in its no-personal-org branch, and 150+
+ routes authenticate through `get_user_id` alone -- including the onboarding
+ read on every page load, push subscriptions and experiment assignments,
+ all of which write rows with a foreign key to `User`. Without the heal
+ here those routes 500 for a session whose row does not exist yet.
+ """
+
+ @staticmethod
+ def _request(headers: dict | None = None):
+ request = Mock(spec=Request)
+ request.headers = headers or {}
+ request.method = "GET"
+ request.url = "http://test/api/onboarding/completed"
+ return request
+
+ @pytest.fixture(autouse=True)
+ def _fresh_cache(self):
+ from autogpt_libs.auth import dependencies
+
+ dependencies._PROVISIONED_USER_IDS.clear()
+ dependencies._HEALS_IN_FLIGHT.clear()
+ yield
+ dependencies._PROVISIONED_USER_IDS.clear()
+ dependencies._HEALS_IN_FLIGHT.clear()
+
+ @staticmethod
+ def _stub_backend(mocker: MockerFixture, *, connected: bool = True):
+ import sys
+ import types
+
+ db_mod = types.ModuleType("backend.data.db")
+ mocker.patch.object(db_mod, "prisma", Mock(), create=True)
+ db_mod.prisma.is_connected = Mock(return_value=connected)
+ mocker.patch.dict(
+ sys.modules,
+ {
+ "backend": types.ModuleType("backend"),
+ "backend.data": types.ModuleType("backend.data"),
+ "backend.data.db": db_mod,
+ },
+ )
+ return db_mod
+
+ @pytest.mark.asyncio
+ async def test_heals_on_a_plain_authenticated_request(self, mocker: MockerFixture):
+ self._stub_backend(mocker)
+ ensure = mocker.patch(
+ "autogpt_libs.auth.dependencies._ensure_platform_user",
+ new_callable=AsyncMock,
+ return_value=True,
+ )
+ payload = {"sub": "user-1", "role": "user", "email": "[email protected]"}
+
+ assert await get_user_id(self._request(), payload) == "user-1"
+
+ ensure.assert_awaited_once_with("user-1", payload)
+
+ @pytest.mark.asyncio
+ async def test_probe_runs_once_per_process_per_user(self, mocker: MockerFixture):
+ """A first page load fans out ~20 requests; after the first confirms
+ the row, the rest must not each pay for an indexed read."""
+ self._stub_backend(mocker)
+ ensure = mocker.patch(
+ "autogpt_libs.auth.dependencies._ensure_platform_user",
+ new_callable=AsyncMock,
+ return_value=True,
+ )
+ payload = {"sub": "user-1", "role": "user", "email": "[email protected]"}
+
+ await get_user_id(self._request(), payload)
+ await get_user_id(self._request(), payload)
+ await get_user_id(self._request(), {**payload, "sub": "user-2"})
+
+ assert ensure.await_count == 2
+ assert [c.args[0] for c in ensure.await_args_list] == ["user-1", "user-2"]
+
+ @pytest.mark.asyncio
+ async def test_concurrent_first_requests_share_one_probe(
+ self, mocker: MockerFixture
+ ):
+ """A first page load's requests arrive together, before any heal has
+ settled: they wait on the one probe in flight instead of each running
+ their own, and none goes ahead before it confirms the row."""
+ self._stub_backend(mocker)
+ release = asyncio.Event()
+
+ async def slow_probe(user_id: str, payload: dict) -> bool:
+ await release.wait()
+ return True
+
+ ensure = mocker.patch(
+ "autogpt_libs.auth.dependencies._ensure_platform_user",
+ new_callable=AsyncMock,
+ side_effect=slow_probe,
+ )
+ payload = {"sub": "user-1", "role": "user", "email": "[email protected]"}
+
+ requests = [
+ asyncio.create_task(get_user_id(self._request(), payload)) for _ in range(5)
+ ]
+ for _ in range(5):
+ await asyncio.sleep(0)
+ assert not any(r.done() for r in requests)
+
+ release.set()
+ assert await asyncio.gather(*requests) == ["user-1"] * 5
+ assert ensure.await_count == 1
+
+ @pytest.mark.asyncio
+ async def test_a_cancelled_request_does_not_cancel_the_shared_heal(
+ self, mocker: MockerFixture
+ ):
+ """A client that drops its request mid-heal must not take the heal the
+ other requests for that user are waiting on down with it."""
+ self._stub_backend(mocker)
+ release = asyncio.Event()
+
+ async def slow_probe(user_id: str, payload: dict) -> bool:
+ await release.wait()
+ return True
+
+ ensure = mocker.patch(
+ "autogpt_libs.auth.dependencies._ensure_platform_user",
+ new_callable=AsyncMock,
+ side_effect=slow_probe,
+ )
+ payload = {"sub": "user-1", "role": "user", "email": "[email protected]"}
+
+ first = asyncio.create_task(get_user_id(self._request(), payload))
+ second = asyncio.create_task(get_user_id(self._request(), payload))
+ for _ in range(5):
+ await asyncio.sleep(0)
+ first.cancel()
+ for _ in range(5):
+ await asyncio.sleep(0)
+
+ release.set()
+ assert await second == "user-1"
+ assert ensure.await_count == 1
+ assert first.cancelled()
+
+ @pytest.mark.asyncio
+ async def test_cached_confirmation_expires(self, mocker: MockerFixture):
+ """Nothing deletes a User row today, but the cache must not turn that
+ into a permanent assumption: after the TTL the row is probed again."""
+ from autogpt_libs.auth import dependencies
+
+ self._stub_backend(mocker)
+ ensure = mocker.patch(
+ "autogpt_libs.auth.dependencies._ensure_platform_user",
+ new_callable=AsyncMock,
+ return_value=True,
+ )
+ clock = mocker.patch("autogpt_libs.auth.dependencies.time.monotonic")
+ payload = {"sub": "user-1", "role": "user", "email": "[email protected]"}
+
+ clock.return_value = 1_000.0
+ await get_user_id(self._request(), payload)
+ clock.return_value = 1_000.0 + dependencies._PROVISIONED_USER_TTL_SECS - 1
+ await get_user_id(self._request(), payload)
+ assert ensure.await_count == 1
+
+ clock.return_value = 1_000.0 + dependencies._PROVISIONED_USER_TTL_SECS
+ await get_user_id(self._request(), payload)
+ assert ensure.await_count == 2
+
+ @pytest.mark.asyncio
+ async def test_retries_a_failed_heal_after_the_backoff(self, mocker: MockerFixture):
+ """A declined or failed heal is retried, so the account does not stay
+ broken for the life of the process -- but only after a short backoff.
+ Retrying on every request would re-run the heal, and re-emit its
+ Sentry error, ~20 times per page load for an account nothing can
+ provision."""
+ from autogpt_libs.auth import dependencies
+
+ self._stub_backend(mocker)
+ ensure = mocker.patch(
+ "autogpt_libs.auth.dependencies._ensure_platform_user",
+ new_callable=AsyncMock,
+ side_effect=[False, True, True],
+ )
+ clock = mocker.patch("autogpt_libs.auth.dependencies.time.monotonic")
+ payload = {"sub": "user-1", "role": "user", "email": "[email protected]"}
+
+ clock.return_value = 1_000.0
+ await get_user_id(self._request(), payload) # fails -> backoff
+ await get_user_id(self._request(), payload) # within backoff: no retry
+ assert ensure.await_count == 1
+
+ clock.return_value = 1_000.0 + dependencies._FAILED_HEAL_BACKOFF_SECS
+ await get_user_id(self._request(), payload) # backoff over: retry, succeeds
+ await get_user_id(self._request(), payload) # now cached as confirmed
+ assert ensure.await_count == 2
+
+ @pytest.mark.asyncio
+ async def test_a_failed_heal_is_backed_off_much_shorter_than_a_confirmed_one(
+ self, mocker: MockerFixture
+ ):
+ """The backoff must not be the confirmation TTL: an account that could
+ not be healed has to be tried again well before 15 minutes pass."""
+ from autogpt_libs.auth import dependencies
+
+ assert (
+ dependencies._FAILED_HEAL_BACKOFF_SECS
+ < dependencies._PROVISIONED_USER_TTL_SECS
+ )
+ assert dependencies._FAILED_HEAL_BACKOFF_SECS <= 60
+
+ @pytest.mark.asyncio
+ async def test_skips_without_a_database_connection(self, mocker: MockerFixture):
+ """Route unit tests and tooling resolve this dependency with no
+ database at all; the heal must be a no-op there, not an error."""
+ self._stub_backend(mocker, connected=False)
+ ensure = mocker.patch(
+ "autogpt_libs.auth.dependencies._ensure_platform_user",
+ new_callable=AsyncMock,
+ )
+
+ assert (
+ await get_user_id(self._request(), {"sub": "user-1", "email": "[email protected]"})
+ == "user-1"
+ )
+
+ ensure.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_skips_when_the_backend_package_is_absent(
+ self, mocker: MockerFixture
+ ):
+ import sys
+
+ # `None` in sys.modules makes the import raise ImportError, which is
+ # what autogpt_libs sees when used outside the backend.
+ mocker.patch.dict(
+ sys.modules,
+ {"backend": None, "backend.data": None, "backend.data.db": None},
+ )
+ ensure = mocker.patch(
+ "autogpt_libs.auth.dependencies._ensure_platform_user",
+ new_callable=AsyncMock,
+ )
+
+ assert (
+ await get_user_id(self._request(), {"sub": "user-1", "email": "[email protected]"})
+ == "user-1"
+ )
+
+ ensure.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_a_failing_heal_never_fails_the_request(self, mocker: MockerFixture):
+ self._stub_backend(mocker)
+ logger = mocker.patch("autogpt_libs.auth.dependencies.logger")
+ mocker.patch(
+ "autogpt_libs.auth.dependencies._ensure_platform_user",
+ new_callable=AsyncMock,
+ side_effect=RuntimeError("db down"),
+ )
+
+ assert (
+ await get_user_id(self._request(), {"sub": "user-1", "email": "[email protected]"})
+ == "user-1"
+ )
+
+ logger.warning.assert_called_once()
+
+ @pytest.mark.asyncio
+ async def test_a_raising_heal_is_also_backed_off(self, mocker: MockerFixture):
+ self._stub_backend(mocker)
+ mocker.patch("autogpt_libs.auth.dependencies.logger")
+ ensure = mocker.patch(
+ "autogpt_libs.auth.dependencies._ensure_platform_user",
+ new_callable=AsyncMock,
+ side_effect=RuntimeError("db down"),
+ )
+ payload = {"sub": "user-1", "email": "[email protected]"}
+
+ await get_user_id(self._request(), payload)
+ await get_user_id(self._request(), payload)
+
+ ensure.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_impersonation_heals_the_admin_not_the_target(
+ self, mocker: MockerFixture
+ ):
+ self._stub_backend(mocker)
+ ensure = mocker.patch(
+ "autogpt_libs.auth.dependencies._ensure_platform_user",
+ new_callable=AsyncMock,
+ return_value=True,
+ )
+ payload = {"sub": "admin-1", "role": "admin", "email": "[email protected]"}
+ request = self._request({"X-Act-As-User-Id": "target-user"})
+
+ assert await get_user_id(request, payload) == "target-user"
+
+ # The claims describe the admin; provisioning the target from them
+ # would create the target's account under the admin's email.
+ ensure.assert_awaited_once_with("admin-1", payload)
+
+
+class TestEnsurePlatformUserOutcome:
+ """The return value drives the per-process cache in `get_user_id`, so
+ it must only be True when the row is actually known to exist."""
+
+ @pytest.mark.asyncio
+ async def test_true_when_the_row_already_exists(self, mocker: MockerFixture):
+ TestEnsurePlatformUser._stub_backend(
+ mocker, existing_user=Mock(), provisioner=AsyncMock()
+ )
+
+ assert (
+ await _ensure_platform_user("user-1", {"sub": "user-1", "email": "[email protected]"})
+ is True
+ )
+
+ @pytest.mark.asyncio
+ async def test_true_when_it_created_the_row(self, mocker: MockerFixture):
+ TestEnsurePlatformUser._stub_backend(
+ mocker,
+ existing_user=None,
+ provisioner=AsyncMock(return_value=Mock(was_created=True)),
+ )
+
+ assert (
+ await _ensure_platform_user("user-1", {"sub": "user-1", "email": "[email protected]"})
+ is True
+ )
+
+ @pytest.mark.asyncio
+ async def test_false_when_it_declined_or_failed(self, mocker: MockerFixture):
+ TestEnsurePlatformUser._stub_backend(
+ mocker,
+ existing_user=[None, None],
+ provisioner=AsyncMock(side_effect=RuntimeError("db down")),
+ )
+
+ assert (
+ await _ensure_platform_user("user-1", {"sub": "user-1", "email": "[email protected]"})
+ is False
+ )
+ # No email claim: nothing to provision with.
+ assert await _ensure_platform_user("user-1", {"sub": "user-1"}) is False
+ # Impersonation: the claims describe someone else.
+ assert (
+ await _ensure_platform_user(
+ "target", {"sub": "admin-1", "email": "[email protected]"}
+ )
+ is False
+ )
diff --git a/autogpt_platform/backend/backend/api/features/auth_email/routes_test.py b/autogpt_platform/backend/backend/api/features/auth_email/routes_test.py
index 71866bd2f1..78e04fa99d 100644
--- a/autogpt_platform/backend/backend/api/features/auth_email/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/auth_email/routes_test.py
@@ -66,6 +66,46 @@ def test_valid_request_sends_and_returns_204(send_mock):
assert VALID_BODY["url"] in text
+def test_set_password_email_says_why_it_came_and_when_it_expires(send_mock):
+ res = _post({**VALID_BODY, "type": "set_password"})
+
+ assert res.status_code == 204
+ _, subject, body, text = send_mock.call_args.args
+ assert subject == "Set your AutoGPT Platform password"
+ for part in (body, text):
+ assert "asked to sign up for, or verify" in part
+ assert "set a password and finish signing up" in part
+ assert "expires in 1 hour" in part
+
+
+def test_set_password_email_warns_an_earlier_password_no_longer_works(send_mock):
+ # Someone who resubmits the sign-up form gets this email, and the password
+ # they signed up with stops working, even if they finish through the
+ # first link.
+ _post({**VALID_BODY, "type": "set_password"})
+
+ _, _, body, text = send_mock.call_args.args
+ assert "the password you chose then no longer works" in body
+ assert "&#34;Forgot password&#34;" in body
+ assert '"Forgot password"' in text
+
+
+def test_reset_email_carries_no_set_password_note(send_mock):
+ _post(VALID_BODY)
+
+ _, _, body, text = send_mock.call_args.args
+ assert "no longer works" not in body
+ assert "no longer works" not in text
+
+
+def test_verify_email_states_its_24_hour_expiry(send_mock):
+ _post({**VALID_BODY, "type": "verify_email"})
+
+ _, _, body, text = send_mock.call_args.args
+ assert "expires in 24 hours" in body
+ assert "expires in 24 hours" in text
+
+
def test_rejects_link_on_untrusted_host(send_mock):
res = _post({**VALID_BODY, "url": "https://evil.example.com/reset"})
assert res.status_code == 400
@@ -219,6 +259,7 @@ def test_rejects_malformed_trusted_origin_regex_at_startup():
("reset_password", "Reset your AutoGPT Platform password", "Reset password"),
("verify_email", "Verify your AutoGPT Platform email", "Verify email"),
("change_email", "Confirm your new AutoGPT Platform email", "Confirm email"),
+ ("set_password", "Set your AutoGPT Platform password", "Set password"),
],
)
def test_auth_email_design_and_plain_text(send_mock, email_type, subject, button):
diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.py
index b54ca87eb3..fa9e6e2b8d 100644
--- a/autogpt_platform/backend/backend/data/db_manager.py
+++ b/autogpt_platform/backend/backend/data/db_manager.py
@@ -186,6 +186,7 @@ from backend.data.user import (
get_user_integrations,
get_user_notification_preference,
get_user_subscription_tier,
+ heal_orphaned_auth_identities,
release_welcome_email,
set_last_briefing_at,
set_user_credentials,
@@ -387,6 +388,8 @@ class DatabaseManager(AppService):
# Exposed so Prisma-less workers (scheduler, copilot-executor) can build a
# full LaunchDarkly context — see backend/util/feature_flag.py.
get_auth_user_flag_fields = _(get_auth_user_flag_fields)
+ # Exposed for the scheduler's auth-identity invariant monitor.
+ heal_orphaned_auth_identities = _(heal_orphaned_auth_identities)
get_user_integrations = _(get_user_integrations)
update_user_integrations = _(update_user_integrations)
get_user_credentials = _(get_user_credentials)
@@ -736,6 +739,8 @@ class DatabaseManagerClient(AppServiceClient):
get_block_error_stats = _(d.get_block_error_stats)
# Execution accuracy monitoring
get_accuracy_trends_and_alerts = _(d.get_accuracy_trends_and_alerts)
+ # Auth identity invariant monitoring
+ heal_orphaned_auth_identities = _(d.heal_orphaned_auth_identities)
get_frequently_executed_graphs = _(d.get_frequently_executed_graphs)
get_marketplace_graphs_for_monitoring = _(d.get_marketplace_graphs_for_monitoring)
@@ -827,6 +832,7 @@ class DatabaseManagerAsyncClient(AppServiceClient):
sync_subscription_from_stripe = d.sync_subscription_from_stripe
record_subscription_trial_cost = d.record_subscription_trial_cost
get_auth_user_flag_fields = d.get_auth_user_flag_fields
+ heal_orphaned_auth_identities = d.heal_orphaned_auth_identities
get_user_integrations = d.get_user_integrations
update_user_integrations = d.update_user_integrations
get_user_credentials = d.get_user_credentials
diff --git a/autogpt_platform/backend/backend/data/onboarding.py b/autogpt_platform/backend/backend/data/onboarding.py
index 1deb5b08c6..2fa1e3c248 100644
--- a/autogpt_platform/backend/backend/data/onboarding.py
+++ b/autogpt_platform/backend/backend/data/onboarding.py
@@ -57,7 +57,24 @@ class UserOnboardingUpdate(pydantic.BaseModel):
onboardingAgentExecutionId: Optional[str] = None
-async def get_user_onboarding(user_id: str):
+async def get_user_onboarding(user_id: str) -> UserOnboarding:
+ """Read a user's onboarding state, creating nothing.
+
+ A user with no row yet gets an unsaved all-defaults one, so this works
+ before the ``User`` row exists. Write paths use ``ensure_user_onboarding``.
+ """
+ onboarding = await UserOnboarding.prisma().find_unique(where={"userId": user_id})
+ return onboarding or _default_user_onboarding(user_id)
+
+
+async def ensure_user_onboarding(user_id: str) -> UserOnboarding:
+ """Read a user's onboarding state, creating the row if it is missing.
+
+ For write paths, which follow up with an ``update`` that has nothing to
+ target otherwise. Unlike the read above this does require a provisioned
+ ``User``, which is correct: there is no onboarding progress to record for
+ an account the platform does not have.
+ """
return await UserOnboarding.prisma().upsert(
where={"userId": user_id},
data={
@@ -67,6 +84,26 @@ async def get_user_onboarding(user_id: str):
)
+def _default_user_onboarding(user_id: str) -> UserOnboarding:
+ """An unsaved row mirroring the column defaults in ``schema.prisma``.
+
+ ``id``/``createdAt`` are placeholders: the API model this is serialized
+ through exposes neither, so they never reach a client.
+ """
+ return UserOnboarding(
+ id="",
+ createdAt=datetime.now(timezone.utc),
+ completedSteps=[],
+ walletShown=False,
+ notified=[],
+ rewardedFor=[],
+ integrations=[],
+ agentRuns=0,
+ consecutiveRunDays=0,
+ userId=user_id,
+ )
+
+
async def reset_user_onboarding(user_id: str):
return await UserOnboarding.prisma().upsert(
where={"userId": user_id},
@@ -176,7 +213,7 @@ async def complete_onboarding_step(user_id: str, step: OnboardingStep):
"""
Completes the specified onboarding step for the user if not already completed.
"""
- onboarding = await get_user_onboarding(user_id)
+ onboarding = await ensure_user_onboarding(user_id)
if step not in onboarding.completedSteps:
await UserOnboarding.prisma().update(
where={"userId": user_id},
@@ -332,7 +369,7 @@ async def increment_onboarding_runs(user_id: str):
Increment a user's run counters and trigger any onboarding milestones.
"""
user_timezone = await _get_user_timezone(user_id)
- onboarding = await get_user_onboarding(user_id)
+ onboarding = await ensure_user_onboarding(user_id)
new_run_count = onboarding.agentRuns + 1
last_run_at, consecutive_run_days = _calculate_consecutive_run_days(
onboarding.lastRunAt, onboarding.consecutiveRunDays, user_timezone
diff --git a/autogpt_platform/backend/backend/data/onboarding_test.py b/autogpt_platform/backend/backend/data/onboarding_test.py
index 2807ea8eb2..d60c1dbd00 100644
--- a/autogpt_platform/backend/backend/data/onboarding_test.py
+++ b/autogpt_platform/backend/backend/data/onboarding_test.py
@@ -8,7 +8,9 @@ from backend.data.onboarding import (
OnboardingStep,
_reward_user,
complete_onboarding_step,
+ ensure_user_onboarding,
format_onboarding_for_extraction,
+ get_user_onboarding,
)
@@ -165,6 +167,56 @@ def test_onboarding_step_values_are_plain_strings():
assert "VISIT_COPILOT" not in {step.value for step in OnboardingStep}
[email protected](loop_scope="function")
+async def test_get_user_onboarding_does_not_write_for_unprovisioned_user(
+ mocker: pytest_mock.MockerFixture,
+):
+ # A valid session can outrun the platform User row it hangs off. This read
+ # runs on every page load, so it has to answer from what is already there:
+ # creating a row for a user that does not exist yet trips the FK to User
+ # and 500s the request instead.
+ mock_prisma = mocker.patch("backend.data.onboarding.UserOnboarding.prisma")
+ mock_prisma.return_value.find_unique = AsyncMock(return_value=None)
+ mock_prisma.return_value.upsert = AsyncMock()
+
+ onboarding = await get_user_onboarding("user-1")
+
+ mock_prisma.return_value.upsert.assert_not_called()
+ assert onboarding.userId == "user-1"
+ assert onboarding.completedSteps == []
+ assert onboarding.agentRuns == 0
+ assert OnboardingStep.ONBOARDING_COMPLETE not in onboarding.completedSteps
+
+
[email protected](loop_scope="function")
+async def test_get_user_onboarding_returns_the_stored_row(
+ mocker: pytest_mock.MockerFixture,
+):
+ stored = Mock(userId="user-1", completedSteps=["ONBOARDING_COMPLETE"])
+ mock_prisma = mocker.patch("backend.data.onboarding.UserOnboarding.prisma")
+ mock_prisma.return_value.find_unique = AsyncMock(return_value=stored)
+ mock_prisma.return_value.upsert = AsyncMock()
+
+ assert await get_user_onboarding("user-1") is stored
+ mock_prisma.return_value.upsert.assert_not_called()
+
+
[email protected](loop_scope="function")
+async def test_ensure_user_onboarding_creates_the_row(
+ mocker: pytest_mock.MockerFixture,
+):
+ # Write paths still need the row to exist: each one follows up with an
+ # `update`, which has nothing to target if the row was never created.
+ mock_prisma = mocker.patch("backend.data.onboarding.UserOnboarding.prisma")
+ mock_prisma.return_value.upsert = AsyncMock(return_value=Mock())
+
+ await ensure_user_onboarding("user-1")
+
+ assert mock_prisma.return_value.upsert.call_args.kwargs["where"] == {
+ "userId": "user-1"
+ }
+
+
@pytest.fixture
def onboarding_writes(mocker: pytest_mock.MockFixture) -> Mock:
mocker.patch("backend.data.onboarding._reward_user", AsyncMock())
@@ -185,7 +237,7 @@ async def test_completing_onboarding_sends_onboarding_completed(
mocker: pytest_mock.MockFixture, onboarding_writes: Mock
):
mocker.patch(
- "backend.data.onboarding.get_user_onboarding",
+ "backend.data.onboarding.ensure_user_onboarding",
AsyncMock(return_value=_onboarding([])),
)
@@ -199,7 +251,7 @@ async def test_onboarding_completed_is_sent_once_per_user(
mocker: pytest_mock.MockFixture, onboarding_writes: Mock
):
mocker.patch(
- "backend.data.onboarding.get_user_onboarding",
+ "backend.data.onboarding.ensure_user_onboarding",
AsyncMock(return_value=_onboarding([OnboardingStep.ONBOARDING_COMPLETE])),
)
@@ -213,7 +265,7 @@ async def test_other_onboarding_steps_send_no_onboarding_completed(
mocker: pytest_mock.MockFixture, onboarding_writes: Mock
):
mocker.patch(
- "backend.data.onboarding.get_user_onboarding",
+ "backend.data.onboarding.ensure_user_onboarding",
AsyncMock(return_value=_onboarding([])),
)
diff --git a/autogpt_platform/backend/backend/data/org_migration.py b/autogpt_platform/backend/backend/data/org_migration.py
index 88de4d9081..f89f0f7dc4 100644
--- a/autogpt_platform/backend/backend/data/org_migration.py
+++ b/autogpt_platform/backend/backend/data/org_migration.py
@@ -259,12 +259,15 @@ async def _find_owned_personal_org(user_id: str):
)
-async def ensure_personal_org(user_id: str) -> None:
+async def ensure_personal_org(user_id: str) -> bool:
"""Ensure *user_id* owns a personal Organization; create one if missing.
Idempotent and race-safe. If the user already owns a personal org this is a
no-op. Otherwise it bootstraps one via ``create_personal_org``.
+ Returns ``True`` only when this call created the org, so exactly one of any
+ number of concurrent callers sees ``True`` for a given user.
+
On ``UniqueViolationError`` there are two possibilities, distinguished by a
re-check (same pattern as ``data.user._ensure_user_profile``): a concurrent
first-request already bootstrapped this user (done), or the resolved slug
@@ -276,20 +279,20 @@ async def ensure_personal_org(user_id: str) -> None:
propagates and fails the request loudly rather than bricking the account.
"""
if await _find_owned_personal_org(user_id) is not None:
- return
+ return False
slug_base, display_name = await _derive_personal_org_identity(user_id)
for _ in range(3):
try:
await create_personal_org(user_id, slug_base, display_name)
- return
+ return True
except UniqueViolationError:
existing = await _find_owned_personal_org(user_id)
if existing is not None:
# A concurrent request bootstrapped this user first.
logger.debug("Personal org for user %s created concurrently", user_id)
- return
+ return False
# A legacy orphan holding this user's index slot blocks every
# retry — clear it so the next attempt can succeed. Otherwise
# the slug collided with a *different* user; retry either way.
diff --git a/autogpt_platform/backend/backend/data/org_migration_test.py b/autogpt_platform/backend/backend/data/org_migration_test.py
index 14af27313c..06d8231bc8 100644
--- a/autogpt_platform/backend/backend/data/org_migration_test.py
+++ b/autogpt_platform/backend/backend/data/org_migration_test.py
@@ -790,7 +790,7 @@ class TestEnsurePersonalOrg:
org_migration, "create_personal_org", new_callable=AsyncMock
)
- await org_migration.ensure_personal_org("user-new")
+ assert await org_migration.ensure_personal_org("user-new") is True
create.assert_awaited_once()
assert create.await_args.args[0] == "user-new"
@@ -807,7 +807,7 @@ class TestEnsurePersonalOrg:
org_migration, "create_personal_org", new_callable=AsyncMock
)
- await org_migration.ensure_personal_org("user-has-org")
+ assert await org_migration.ensure_personal_org("user-has-org") is False
create.assert_not_called()
@@ -835,7 +835,8 @@ class TestEnsurePersonalOrg:
side_effect=UniqueViolationError({}),
)
- await org_migration.ensure_personal_org("user-racer")
+ # Only the winner reports the creation (it drives the sign-up signal).
+ assert await org_migration.ensure_personal_org("user-racer") is False
# Only one create attempt — the loser did not retry into a 2nd org.
create.assert_awaited_once()
@@ -860,7 +861,7 @@ class TestEnsurePersonalOrg:
side_effect=[UniqueViolationError({}), None],
)
- await org_migration.ensure_personal_org("user-dup")
+ assert await org_migration.ensure_personal_org("user-dup") is True
assert create.await_count == 2
diff --git a/autogpt_platform/backend/backend/data/posthog_lifecycle_hooks_test.py b/autogpt_platform/backend/backend/data/posthog_lifecycle_hooks_test.py
index b67b7e223f..41ac7c12b3 100644
--- a/autogpt_platform/backend/backend/data/posthog_lifecycle_hooks_test.py
+++ b/autogpt_platform/backend/backend/data/posthog_lifecycle_hooks_test.py
@@ -209,7 +209,12 @@ async def test_signup_schedules_only_a_new_user(existing: bool):
with (
patch.object(user_module, "prisma") as prisma,
patch.object(user_module, "_ensure_user_profile", new_callable=AsyncMock),
- patch.object(user_module, "ensure_personal_org", new_callable=AsyncMock),
+ patch.object(
+ user_module,
+ "ensure_personal_org",
+ new_callable=AsyncMock,
+ return_value=False,
+ ),
patch.object(user_module.User, "from_db", return_value=app_user),
patch.object(user_module, "UserCreationResult") as result,
patch.object(user_module, "schedule_posthog_lifecycle_sync") as schedule,
diff --git a/autogpt_platform/backend/backend/data/user.py b/autogpt_platform/backend/backend/data/user.py
index dd02979b3d..b1d00f1c47 100644
--- a/autogpt_platform/backend/backend/data/user.py
+++ b/autogpt_platform/backend/backend/data/user.py
@@ -24,7 +24,7 @@ from prisma.types import (
)
from pydantic import BaseModel, ConfigDict
-from backend.data.db import prisma
+from backend.data.db import prisma, query_raw_with_schema
from backend.data.model import (
CREDENTIALS_ADAPTER,
Credentials,
@@ -57,6 +57,10 @@ class UserCreationResult(BaseModel):
model_config = ConfigDict(frozen=True)
user: User
+ # True for the one call that set the account up: it created the ``User``
+ # row, or bootstrapped the personal org for a row the auth hook inserted
+ # bare at sign-up. Drives the sign-up conversion (via the route's
+ # ``X-AutoGPT-User-Created`` header) and the PostHog lifecycle sync.
was_created: bool
@@ -80,20 +84,24 @@ async def _get_or_create_user(user_data: dict) -> UserCreationResult:
raise HTTPException(status_code=401, detail="Email not found in token")
user = await prisma.user.find_unique(where={"id": user_id})
+ row_created = False
if not user:
- user = await prisma.user.create(
- data=UserCreateInput(
- id=user_id,
- email=user_email,
- name=user_data.get("user_metadata", {}).get("name"),
+ try:
+ user = await prisma.user.create(
+ data=UserCreateInput(
+ id=user_id,
+ email=user_email,
+ name=user_data.get("user_metadata", {}).get("name"),
+ )
)
- )
- was_created = True
- track_signup_completed(
- user_id=user.id, signup_method=await _signup_method(user.id, user_data)
- )
- else:
- was_created = False
+ row_created = True
+ except UniqueViolationError:
+ # A concurrent first request (the verify link opened in two
+ # browsers at once) created it since the lookup. If it is the
+ # email that clashes instead, there is still no row: re-raise.
+ user = await prisma.user.find_unique(where={"id": user_id})
+ if user is None:
+ raise
# Ensure every user has a marketplace Profile (required to publish
# agents). Best-effort: a failure must not block user resolution — the
@@ -113,9 +121,16 @@ async def _get_or_create_user(user_data: dict) -> UserCreationResult:
# organization context available", so a failure here must fail the
# request loudly instead of returning a bricked account. Idempotent and
# race-safe (see ensure_personal_org).
- await ensure_personal_org(user.id)
+ org_created = await ensure_personal_org(user.id)
+ # The auth hook inserts a bare row the moment the identity is created
+ # (see provision-platform-user.ts), so the row alone does not mark a
+ # new account: the personal org this call bootstraps does.
+ was_created = row_created or org_created
if was_created:
+ track_signup_completed(
+ user_id=user.id, signup_method=await _signup_method(user.id, user_data)
+ )
schedule_posthog_lifecycle_sync(user.id)
return UserCreationResult(user=User.from_db(user), was_created=was_created)
@@ -313,6 +328,110 @@ async def get_auth_user_flag_fields(user_id: str) -> Optional[AuthUserFlagFields
)
+class OrphanedAuthIdentity(BaseModel):
+ """An auth identity (Better Auth user) with no platform ``User`` row."""
+
+ id: str
+ email: str
+ name: Optional[str] = None
+ createdAt: datetime
+ # Set when a *different* platform User already owns this email, which the
+ # unique index on ``User.email`` turns into an unprovisionable account.
+ email_owner_id: Optional[str] = None
+
+ @property
+ def has_email_collision(self) -> bool:
+ return self.email_owner_id is not None and self.email_owner_id != self.id
+
+
+class OrphanedAuthIdentityReport(BaseModel):
+ healed: list[str] = []
+ collided: list[OrphanedAuthIdentity] = []
+ failed: list[str] = []
+
+ @property
+ def is_clean(self) -> bool:
+ return not (self.healed or self.collided or self.failed)
+
+
+async def find_orphaned_auth_identities(
+ older_than: datetime, limit: int = 100
+) -> list[OrphanedAuthIdentity]:
+ """Auth identities created before *older_than* that have no ``User`` row.
+
+ Only verified identities, or ones with a session: an unverified sign-up
+ gets its row when its link is opened. Identities whose email another
+ platform User owns sort last, so they can't fill every batch.
+ """
+ rows = await query_raw_with_schema(
+ # The owner lookup is case-insensitive on purpose: the auth migration
+ # copied emails as stored, so a migrated identity can differ from its
+ # platform row only by case, and missing that owner would heal a
+ # duplicate account. It is a scalar subquery rather than a join so an
+ # identity yields exactly one row even when several platform rows
+ # carry case-variants of its email -- a join would return the identity
+ # once per variant and let duplicates eat into the batch limit.
+ 'SELECT a.id, a.email, a.name, a."createdAt", '
+ '(SELECT owner.id FROM {schema_prefix}"User" owner '
+ "WHERE LOWER(owner.email) = LOWER(a.email) "
+ 'ORDER BY owner."createdAt" ASC LIMIT 1) AS email_owner_id '
+ 'FROM {schema_prefix}"UserAuthIdentity" a '
+ 'LEFT JOIN {schema_prefix}"User" u ON u.id = a.id '
+ 'WHERE u.id IS NULL AND a."createdAt" < $1::timestamptz '
+ 'AND (a."emailVerified" OR EXISTS (SELECT 1 FROM '
+ '{schema_prefix}"UserAuthSession" s WHERE s."userId" = a.id)) '
+ 'ORDER BY EXISTS (SELECT 1 FROM {schema_prefix}"User" o '
+ "WHERE LOWER(o.email) = LOWER(a.email)), "
+ 'a."createdAt" ASC '
+ "LIMIT $2::int",
+ older_than.isoformat(),
+ limit,
+ )
+ return [OrphanedAuthIdentity(**row) for row in rows]
+
+
+async def heal_orphaned_auth_identities(
+ grace_secs: int = 300, limit: int = 100
+) -> OrphanedAuthIdentityReport:
+ """Provision a platform ``User`` for every orphaned auth identity.
+
+ Runs the same provisioning as ``POST /auth/user`` (User + marketplace
+ Profile + personal org) from the identity's own email, so a healed account
+ is indistinguishable from one that signed up cleanly. Identities younger
+ than *grace_secs* are left alone: their sign-up is still in flight.
+
+ An identity whose email is already owned by a different platform User
+ (compared case-insensitively) is reported, not healed -- the unique index
+ makes it unprovisionable, and guessing which account the person meant is
+ not this function's call.
+ """
+ older_than = datetime.now(timezone.utc) - timedelta(seconds=grace_secs)
+ report = OrphanedAuthIdentityReport()
+ for identity in await find_orphaned_auth_identities(older_than, limit):
+ if identity.has_email_collision:
+ report.collided.append(identity)
+ continue
+ try:
+ result = await get_or_create_user_with_status(
+ {
+ "sub": identity.id,
+ "email": identity.email,
+ "user_metadata": {"name": identity.name},
+ }
+ )
+ except Exception:
+ logger.error(
+ f"Failed to heal orphaned auth identity {identity.id}", exc_info=True
+ )
+ report.failed.append(identity.id)
+ continue
+ # A sign-in that landed between the query and here provisioned it
+ # already: nothing was broken, so nothing to page about.
+ if result.was_created:
+ report.healed.append(identity.id)
+ return report
+
+
@cache_user_lookup
async def get_user_by_email(email: str) -> Optional[User]:
try:
diff --git a/autogpt_platform/backend/backend/data/user_provisioning_test.py b/autogpt_platform/backend/backend/data/user_provisioning_test.py
new file mode 100644
index 0000000000..36b7cdd726
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/user_provisioning_test.py
@@ -0,0 +1,121 @@
+"""Platform User provisioning against the real database.
+
+The unit tests in ``user_test.py`` patch the queries out, so a flipped
+comparison or a dropped filter in the SQL would leave them green.
+"""
+
+from datetime import datetime, timedelta, timezone
+from uuid import uuid4
+
+import pytest
+from prisma.models import AuthSession, AuthUser, Organization, User
+
+from backend.data.db import execute_raw_with_schema
+from backend.data.user import (
+ find_orphaned_auth_identities,
+ get_or_create_user_with_status,
+)
+from backend.util.test import SpinTestServer
+
+
+async def _identity(
+ created_at: datetime, *, verified: bool = True, email: str | None = None
+) -> str:
+ user_id = str(uuid4())
+ await AuthUser.prisma().create(
+ data={
+ "id": user_id,
+ "name": "Sweep test",
+ "email": email or f"{user_id}@example.com",
+ "emailVerified": verified,
+ "createdAt": created_at,
+ }
+ )
+ return user_id
+
+
[email protected](loop_scope="session")
+async def test_finds_only_identities_that_can_sign_in_without_a_user_row(
+ server: SpinTestServer,
+):
+ now = datetime.now(timezone.utc)
+ old = now - timedelta(hours=1)
+ cutoff = now - timedelta(minutes=5)
+ owner_id = str(uuid4())
+ ids: dict[str, str] = {}
+ try:
+ # Oldest of all, so ordering by age alone would put it first.
+ ids["collided"] = await _identity(
+ old - timedelta(minutes=1), email=f"Taken-{owner_id}@Example.com"
+ )
+ await User.prisma().create(
+ data={"id": owner_id, "email": f"taken-{owner_id}@example.com"}
+ )
+ ids["orphan"] = await _identity(old)
+ ids["provisioned"] = await _identity(old)
+ await User.prisma().create(
+ data={"id": ids["provisioned"], "email": f"{ids['provisioned']}@x.com"}
+ )
+ ids["in_grace"] = await _identity(now)
+ # AUTH_REQUIRE_EMAIL_VERIFICATION on: no session until the link.
+ ids["awaiting_verification"] = await _identity(old, verified=False)
+ # Flag off: an unverified password user is signed in at once.
+ ids["unverified_signed_in"] = await _identity(old, verified=False)
+ await AuthSession.prisma().create(
+ data={
+ "id": str(uuid4()),
+ "token": str(uuid4()),
+ "userId": ids["unverified_signed_in"],
+ "expiresAt": now + timedelta(days=1),
+ }
+ )
+
+ found = await find_orphaned_auth_identities(cutoff, limit=1000)
+
+ mine = [i for i in found if i.id in ids.values()]
+ by_id = {i.id: i for i in mine}
+ assert set(by_id) == {
+ ids["orphan"],
+ ids["unverified_signed_in"],
+ ids["collided"],
+ }
+ assert by_id[ids["collided"]].email_owner_id == owner_id
+ assert by_id[ids["collided"]].has_email_collision
+ # Never healed, so it must not take a batch slot ahead of one that is.
+ assert mine[-1].id == ids["collided"]
+ finally:
+ await AuthUser.prisma().delete_many(where={"id": {"in": list(ids.values())}})
+ await User.prisma().delete_many(
+ where={"id": {"in": [owner_id, ids.get("provisioned", owner_id)]}}
+ )
+
+
[email protected](loop_scope="session")
+async def test_first_bootstrap_after_the_auth_hook_reports_the_account_created(
+ server: SpinTestServer,
+):
+ """The auth hook inserts the bare row before the client's
+ ``POST /auth/user``. That call must still answer "created" (the sign-up
+ conversion header) exactly once, and only that call."""
+ user_id = str(uuid4())
+ payload = {"sub": user_id, "email": f"{user_id}@example.com"}
+ try:
+ # The exact statement in frontend/src/lib/auth/provision-platform-user.ts.
+ await execute_raw_with_schema(
+ 'INSERT INTO {schema_prefix}"User" (id, email, name, "updatedAt") '
+ "VALUES ($1, $2, $3, NOW()) ON CONFLICT (id) DO NOTHING",
+ user_id,
+ payload["email"],
+ None,
+ )
+
+ first = await get_or_create_user_with_status(payload)
+ second = await get_or_create_user_with_status(payload)
+
+ assert first.was_created is True
+ assert second.was_created is False
+ finally:
+ # The personal org has no FK to its User, so it would outlive the
+ # User's cascade; deleting it takes its members, team and balance.
+ await Organization.prisma().delete_many(where={"bootstrapUserId": user_id})
+ await User.prisma().delete_many(where={"id": user_id})
diff --git a/autogpt_platform/backend/backend/data/user_test.py b/autogpt_platform/backend/backend/data/user_test.py
index 6c1b995b00..1dffa896ce 100644
--- a/autogpt_platform/backend/backend/data/user_test.py
+++ b/autogpt_platform/backend/backend/data/user_test.py
@@ -352,9 +352,20 @@ class TestGetOrCreateUserStatus:
def stub_user_provisioning(self):
with (
patch.object(user_module, "_ensure_user_profile", new_callable=AsyncMock),
- patch.object(user_module, "ensure_personal_org", new_callable=AsyncMock),
+ patch.object(
+ user_module,
+ "ensure_personal_org",
+ new_callable=AsyncMock,
+ return_value=False,
+ ) as ensure_org,
+ patch.object(
+ user_module, "schedule_posthog_lifecycle_sync"
+ ) as posthog_sync,
+ patch.object(user_module, "AuthAccount") as auth_account,
+ patch.object(user_module, "track_signup_completed"),
):
- yield
+ auth_account.prisma.return_value.find_first = AsyncMock(return_value=None)
+ yield ensure_org, posthog_sync
@pytest.mark.asyncio
async def test_reports_newly_created_user(self):
@@ -398,6 +409,81 @@ class TestGetOrCreateUserStatus:
assert result.was_created is False
mock_prisma.user.create.assert_not_called()
+ @pytest.mark.asyncio
+ async def test_reports_created_for_a_row_the_auth_hook_inserted_bare(
+ self, stub_user_provisioning
+ ):
+ """The auth hook writes the User row before the client's
+ ``POST /auth/user``, which then finds it. The first call to bootstrap
+ that row's personal org is still the account's creation: it drives the
+ sign-up conversion header and PostHog, exactly once."""
+ ensure_org, posthog_sync = stub_user_provisioning
+ ensure_org.return_value = True
+ db_user = MagicMock(id="user-hooked", email="[email protected]", name=None)
+
+ with (
+ patch.object(user_module, "prisma") as mock_prisma,
+ patch.object(
+ user_module.User,
+ "from_db",
+ return_value=_application_user("user-hooked", "[email protected]"),
+ ),
+ patch.object(user_module, "AuthAccount") as auth_account,
+ patch.object(user_module, "track_signup_completed") as track,
+ ):
+ mock_prisma.user.find_unique = AsyncMock(return_value=db_user)
+ auth_account.prisma.return_value.find_first = AsyncMock(
+ return_value=MagicMock(providerId="credential")
+ )
+
+ result = await user_module.get_or_create_user_with_status(
+ {"sub": "user-hooked", "email": "[email protected]"}
+ )
+
+ assert result.was_created is True
+ mock_prisma.user.create.assert_not_called()
+ posthog_sync.assert_called_once_with("user-hooked")
+ track.assert_called_once_with(user_id="user-hooked", signup_method="email")
+
+ @pytest.mark.asyncio
+ async def test_a_row_created_concurrently_is_read_back_not_an_error(self):
+ """Two first requests for one account (the verify link opened in two
+ browsers at once) both miss the row and both create it. The loser's
+ unique violation on the id means the row exists: read it back."""
+ db_user = MagicMock(id="user-raced", email="[email protected]", name=None)
+
+ with (
+ patch.object(user_module, "prisma") as mock_prisma,
+ patch.object(
+ user_module.User,
+ "from_db",
+ return_value=_application_user("user-raced", "[email protected]"),
+ ),
+ ):
+ mock_prisma.user.find_unique = AsyncMock(side_effect=[None, db_user])
+ mock_prisma.user.create = AsyncMock(
+ side_effect=prisma.errors.UniqueViolationError({})
+ )
+
+ result = await user_module.get_or_create_user_with_status(
+ {"sub": "user-raced", "email": "[email protected]"}
+ )
+
+ assert result.was_created is False
+
+ @pytest.mark.asyncio
+ async def test_an_email_owned_by_another_user_still_fails(self):
+ with patch.object(user_module, "prisma") as mock_prisma:
+ mock_prisma.user.find_unique = AsyncMock(return_value=None)
+ mock_prisma.user.create = AsyncMock(
+ side_effect=prisma.errors.UniqueViolationError({})
+ )
+
+ with pytest.raises(DatabaseError):
+ await user_module.get_or_create_user_with_status(
+ {"sub": "user-new", "email": "[email protected]"}
+ )
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
"provider_id,expected", [("google", "google"), ("credential", "email")]
@@ -470,7 +556,8 @@ class TestGetOrCreateUserStatus:
track.assert_called_once_with(user_id="user-new", signup_method="google")
@pytest.mark.asyncio
- async def test_existing_user_sends_no_signup_completed(self):
+ async def test_existing_account_syncs_nothing(self, stub_user_provisioning):
+ _, posthog_sync = stub_user_provisioning
db_user = MagicMock(id="user-existing", email="[email protected]", name=None)
with (
@@ -488,6 +575,7 @@ class TestGetOrCreateUserStatus:
{"sub": "user-existing", "email": "[email protected]"}
)
+ posthog_sync.assert_not_called()
track.assert_not_called()
@@ -516,7 +604,10 @@ class TestGetOrCreateUserProfile:
branch. Tests that assert on the bootstrap use the yielded mock.
"""
with patch.object(
- user_module, "ensure_personal_org", new_callable=AsyncMock
+ user_module,
+ "ensure_personal_org",
+ new_callable=AsyncMock,
+ return_value=False,
) as m:
yield m
@@ -651,7 +742,10 @@ class TestGetOrCreateUserPersonalOrg:
),
patch.object(user_module, "_ensure_user_profile", new_callable=AsyncMock),
patch.object(
- user_module, "ensure_personal_org", new_callable=AsyncMock
+ user_module,
+ "ensure_personal_org",
+ new_callable=AsyncMock,
+ return_value=False,
) as ensure_org,
):
mock_prisma.user.find_unique = AsyncMock(return_value=db_user)
@@ -805,3 +899,184 @@ class TestSetUserDefaultChatRoute:
by_id_del.assert_called_once_with("user-1")
by_email_del.assert_called_once_with("[email protected]")
goc_clear.assert_called_once_with()
+
+
+class TestHealOrphanedAuthIdentities:
+ """Auth identity -> platform User is an invariant; the healer restores it
+ and reports what it could not restore."""
+
+ @staticmethod
+ def _identity(user_id: str, email: str, email_owner_id: str | None = None):
+ return user_module.OrphanedAuthIdentity(
+ id=user_id,
+ email=email,
+ name="Someone",
+ createdAt=datetime.now(timezone.utc),
+ email_owner_id=email_owner_id,
+ )
+
+ @pytest.mark.asyncio
+ async def test_provisions_each_orphan_from_its_own_email(self):
+ orphans = [
+ self._identity("auth-1", "[email protected]"),
+ self._identity("auth-2", "[email protected]"),
+ ]
+ provision = AsyncMock()
+ with (
+ patch.object(
+ user_module,
+ "find_orphaned_auth_identities",
+ AsyncMock(return_value=orphans),
+ ) as find,
+ patch.object(user_module, "get_or_create_user_with_status", provision),
+ ):
+ report = await user_module.heal_orphaned_auth_identities(
+ grace_secs=300, limit=50
+ )
+
+ assert report.healed == ["auth-1", "auth-2"]
+ assert report.collided == []
+ assert report.failed == []
+ # The same provisioning as POST /auth/user, keyed by the identity id
+ # and its (already lowercased) auth email.
+ assert provision.await_args_list[0].args[0] == {
+ "sub": "auth-1",
+ "email": "[email protected]",
+ "user_metadata": {"name": "Someone"},
+ }
+ # Grace window: identities younger than this are still signing up.
+ older_than = find.await_args.args[0]
+ assert older_than < datetime.now(timezone.utc)
+ assert find.await_args.args[1] == 50
+
+ @pytest.mark.asyncio
+ async def test_reports_an_email_collision_instead_of_guessing(self):
+ # A different platform User already owns this email, so the unique
+ # index makes the identity unprovisionable. That needs a human.
+ collided = self._identity("auth-new", "[email protected]", "user-old")
+ provision = AsyncMock()
+ with (
+ patch.object(
+ user_module,
+ "find_orphaned_auth_identities",
+ AsyncMock(return_value=[collided]),
+ ),
+ patch.object(user_module, "get_or_create_user_with_status", provision),
+ ):
+ report = await user_module.heal_orphaned_auth_identities()
+
+ assert report.collided == [collided]
+ assert report.healed == []
+ provision.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_one_failure_does_not_stop_the_sweep(self):
+ orphans = [
+ self._identity("auth-1", "[email protected]"),
+ self._identity("auth-2", "[email protected]"),
+ ]
+ provision = AsyncMock(side_effect=[DatabaseError("boom"), MagicMock()])
+ with (
+ patch.object(
+ user_module,
+ "find_orphaned_auth_identities",
+ AsyncMock(return_value=orphans),
+ ),
+ patch.object(user_module, "get_or_create_user_with_status", provision),
+ ):
+ report = await user_module.heal_orphaned_auth_identities()
+
+ assert report.failed == ["auth-1"]
+ assert report.healed == ["auth-2"]
+ assert not report.is_clean
+
+ @pytest.mark.asyncio
+ async def test_does_not_page_for_an_identity_provisioned_meanwhile(self):
+ # A sign-in between the query and the heal already set the account
+ # up, so nothing was broken.
+ provision = AsyncMock(return_value=MagicMock(was_created=False))
+ with (
+ patch.object(
+ user_module,
+ "find_orphaned_auth_identities",
+ AsyncMock(return_value=[self._identity("auth-1", "[email protected]")]),
+ ),
+ patch.object(user_module, "get_or_create_user_with_status", provision),
+ ):
+ report = await user_module.heal_orphaned_auth_identities()
+
+ provision.assert_awaited_once()
+ assert report.is_clean
+
+ @pytest.mark.asyncio
+ async def test_clean_when_nothing_is_orphaned(self):
+ with patch.object(
+ user_module, "find_orphaned_auth_identities", AsyncMock(return_value=[])
+ ):
+ report = await user_module.heal_orphaned_auth_identities()
+
+ assert report.is_clean
+
+
+class TestFindOrphanedAuthIdentities:
+ @pytest.mark.asyncio
+ async def test_queries_identities_without_a_user_row(self):
+ cutoff = datetime(2026, 9, 14, 12, 0, tzinfo=timezone.utc)
+ rows = [
+ {
+ "id": "auth-1",
+ "email": "[email protected]",
+ "name": None,
+ "createdAt": cutoff,
+ "email_owner_id": None,
+ }
+ ]
+ with patch.object(
+ user_module, "query_raw_with_schema", AsyncMock(return_value=rows)
+ ) as query:
+ found = await user_module.find_orphaned_auth_identities(cutoff, limit=7)
+
+ assert [i.id for i in found] == ["auth-1"]
+ assert found[0].has_email_collision is False
+ sql, older_than, limit = query.await_args.args
+ assert '"UserAuthIdentity" a' in sql
+ assert "u.id IS NULL" in sql
+ # A migrated identity may differ from its platform row only by case;
+ # a case-sensitive owner match would heal a duplicate account.
+ assert "LOWER(owner.email) = LOWER(a.email)" in sql
+ # ... and the owner must be a scalar subquery, not a join: several
+ # case-variant platform rows would otherwise return the identity once
+ # per variant and let duplicates consume the batch limit.
+ assert "LIMIT 1) AS email_owner_id" in sql
+ assert "JOIN" not in sql.split("AS email_owner_id")[0]
+ # An unverified identity that never held a session is waiting on its
+ # verification link, not orphaned.
+ assert 'a."emailVerified" OR EXISTS' in sql
+ assert '"UserAuthSession" s WHERE s."userId" = a.id' in sql
+ # Collisions are never healed, so they sort behind healable rows.
+ order_by = sql.split("ORDER BY EXISTS")[1]
+ assert "LOWER(o.email) = LOWER(a.email)" in order_by
+ assert older_than == cutoff.isoformat()
+ assert limit == 7
+
+ @pytest.mark.asyncio
+ async def test_maps_a_foreign_email_owner_to_a_collision(self):
+ # The SQL aliases the owning platform User's id as email_owner_id; the
+ # model must read that back as a collision when it is someone else.
+ cutoff = datetime(2026, 9, 14, 12, 0, tzinfo=timezone.utc)
+ rows = [
+ {
+ "id": "auth-new",
+ "email": "[email protected]",
+ "name": "Someone",
+ "createdAt": cutoff,
+ "email_owner_id": "user-old",
+ }
+ ]
+ with patch.object(
+ user_module, "query_raw_with_schema", AsyncMock(return_value=rows)
+ ):
+ found = await user_module.find_orphaned_auth_identities(cutoff)
+
+ assert found[0].email_owner_id == "user-old"
+ assert found[0].has_email_collision is True
diff --git a/autogpt_platform/backend/backend/executor/scheduler.py b/autogpt_platform/backend/backend/executor/scheduler.py
index 69b6d25767..c4662cee2a 100644
--- a/autogpt_platform/backend/backend/executor/scheduler.py
+++ b/autogpt_platform/backend/backend/executor/scheduler.py
@@ -53,6 +53,7 @@ from backend.monitoring import (
report_block_error_rates,
report_execution_accuracy_alerts,
report_late_executions,
+ report_orphaned_auth_identities,
send_due_briefings,
)
from backend.monitoring.instrumentation import SCHEDULER_JOBS
@@ -2089,6 +2090,19 @@ class Scheduler(AppService):
jobstore=Jobstores.EXECUTION.value,
)
+ # Auth identity <-> platform User invariant. Heals any auth
+ # identity that has no platform User row and pages when it had to.
+ if config.auth_identity_orphan_sweep_enabled:
+ self.scheduler.add_job(
+ report_orphaned_auth_identities,
+ id="report_orphaned_auth_identities",
+ trigger="interval",
+ replace_existing=True,
+ max_instances=1,
+ seconds=config.auth_identity_orphan_check_interval_secs,
+ jobstore=Jobstores.EXECUTION.value,
+ )
+
# Cloud Storage Cleanup - configurable interval
self.scheduler.add_job(
cleanup_expired_files,
@@ -2735,6 +2749,11 @@ class Scheduler(AppService):
def execute_report_block_error_rates(self):
return report_block_error_rates()
+ @expose
+ def execute_report_orphaned_auth_identities(self):
+ """Manually trigger the auth-identity invariant check and heal."""
+ return report_orphaned_auth_identities()
+
@expose
def execute_cleanup_expired_files(self):
"""Manually trigger cleanup of expired cloud storage files."""
diff --git a/autogpt_platform/backend/backend/executor/scheduler_unit_test.py b/autogpt_platform/backend/backend/executor/scheduler_unit_test.py
index 6276e56ccb..5b8e62f20f 100644
--- a/autogpt_platform/backend/backend/executor/scheduler_unit_test.py
+++ b/autogpt_platform/backend/backend/executor/scheduler_unit_test.py
@@ -1672,6 +1672,17 @@ def test_reconcile_stripe_tiers_interval_follows_config_setting(monkeypatch):
assert match.kwargs["seconds"] == 12 * 3600
[email protected]("enabled", [False, True])
+def test_orphan_sweep_registered_only_when_switched_on(monkeypatch, enabled):
+ monkeypatch.setattr(
+ f"{_SCHEDULER_PATH}.config.auth_identity_orphan_sweep_enabled", enabled
+ )
+ calls = _registered_jobs(monkeypatch, interval_hours=6).add_job_calls
+
+ ids = [c.kwargs.get("id") for c in calls]
+ assert ids.count("report_orphaned_auth_identities") == int(enabled)
+
+
def test_startup_embedding_backfill_defaults_on():
assert Config.model_fields["scheduler_startup_embedding_backfill"].default is True
diff --git a/autogpt_platform/backend/backend/monitoring/__init__.py b/autogpt_platform/backend/backend/monitoring/__init__.py
index d7cb576b28..ea11517b2c 100644
--- a/autogpt_platform/backend/backend/monitoring/__init__.py
+++ b/autogpt_platform/backend/backend/monitoring/__init__.py
@@ -1,6 +1,11 @@
"""Monitoring module for platform health and alerting."""
from .accuracy_monitor import AccuracyMonitor, report_execution_accuracy_alerts
+from .auth_identity_monitor import (
+ AuthIdentityMonitor,
+ OrphanedAuthIdentityException,
+ report_orphaned_auth_identities,
+)
from .block_error_monitor import BlockErrorMonitor, report_block_error_rates
from .late_execution_monitor import (
LateExecutionException,
@@ -11,12 +16,15 @@ from .notification_monitor import flush_matured_alerts, send_due_briefings
__all__ = [
"AccuracyMonitor",
+ "AuthIdentityMonitor",
"BlockErrorMonitor",
"LateExecutionException",
"LateExecutionMonitor",
+ "OrphanedAuthIdentityException",
"flush_matured_alerts",
"report_block_error_rates",
"report_execution_accuracy_alerts",
"report_late_executions",
+ "report_orphaned_auth_identities",
"send_due_briefings",
]
diff --git a/autogpt_platform/backend/backend/monitoring/auth_identity_monitor.py b/autogpt_platform/backend/backend/monitoring/auth_identity_monitor.py
new file mode 100644
index 0000000000..71924fc19f
--- /dev/null
+++ b/autogpt_platform/backend/backend/monitoring/auth_identity_monitor.py
@@ -0,0 +1,111 @@
+"""Auth identity <-> platform User invariant monitor.
+
+Every auth identity (Better Auth user) must have a platform ``User`` row with
+the same id. Three things maintain that: the auth hook writes the row at
+sign-up, the client's ``POST /auth/user`` writes it after sign-in, and every
+authenticated backend request self-heals it. This monitor is the backstop for
+all three: it heals any identity that slipped through anyway and pages, so a
+regression in the invariant is seen the first time it happens rather than
+when a user reports a broken account.
+"""
+
+import logging
+import time
+
+from backend.util.clients import (
+ get_database_manager_client,
+ get_notification_manager_client,
+)
+from backend.util.metrics import sentry_capture_error
+from backend.util.settings import Config
+
+logger = logging.getLogger(__name__)
+config = Config()
+
+# A collision comes back unchanged on every sweep until a human reconciles it.
+# Page for each one at most this often (per scheduler process), and log the
+# repeats at WARNING, so the alert channel is not trained into noise.
+_COLLISION_REPAGE_SECS = 24 * 60 * 60
+_collisions_paged_at: dict[str, float] = {}
+
+
+def _has_unpaged_collision(collided_ids: list[str]) -> bool:
+ now = time.monotonic()
+ for stale in [
+ identity_id
+ for identity_id, paged_at in _collisions_paged_at.items()
+ if now - paged_at >= _COLLISION_REPAGE_SECS
+ ]:
+ del _collisions_paged_at[stale]
+ fresh = [i for i in collided_ids if i not in _collisions_paged_at]
+ for identity_id in fresh:
+ _collisions_paged_at[identity_id] = now
+ return bool(fresh)
+
+
+class OrphanedAuthIdentityException(Exception):
+ """Raised (to Sentry) when auth identities without a platform User exist."""
+
+
+class AuthIdentityMonitor:
+ """Heal orphaned auth identities and alert when there were any."""
+
+ def __init__(self):
+ self.config = config
+ self.notification_client = get_notification_manager_client()
+
+ def check_orphaned_auth_identities(self) -> str:
+ # Also stops a job persisted while the sweep was on.
+ if not self.config.auth_identity_orphan_sweep_enabled:
+ return "Orphaned auth identity sweep is disabled."
+
+ report = get_database_manager_client().heal_orphaned_auth_identities(
+ grace_secs=self.config.auth_identity_orphan_grace_secs,
+ limit=self.config.auth_identity_orphan_check_limit,
+ )
+
+ if report.is_clean:
+ return "No orphaned auth identities detected."
+
+ # Ids only: the alert goes to Discord and Sentry, neither of which
+ # should carry the emails behind these accounts.
+ message_parts = [
+ "Auth identities without a platform User row were found. "
+ "Sign-up should have created these rows; investigate why it did not.",
+ ]
+ if report.healed:
+ message_parts.append(
+ f"* Healed {len(report.healed)} (User + Profile + personal org "
+ f"provisioned): {', '.join(report.healed)}"
+ )
+ if report.collided:
+ message_parts.append(
+ f"* {len(report.collided)} could NOT be healed: their email is "
+ "already owned by a different platform User, so these accounts "
+ "need manual reconciliation: "
+ + ", ".join(
+ f"{identity.id} (email owned by {identity.email_owner_id})"
+ for identity in report.collided
+ )
+ )
+ if report.failed:
+ message_parts.append(
+ f"* {len(report.failed)} failed to provision (see logs): "
+ f"{', '.join(report.failed)}"
+ )
+
+ msg = "\n".join(message_parts)
+ # Recorded before the check so a collision paged alongside a heal is
+ # not paged again on the next sweep.
+ new_collision = _has_unpaged_collision([i.id for i in report.collided])
+ if report.healed or report.failed or new_collision:
+ sentry_capture_error(OrphanedAuthIdentityException(msg))
+ self.notification_client.discord_system_alert(msg)
+ else:
+ logger.warning(msg)
+ return msg
+
+
+def report_orphaned_auth_identities() -> str:
+ """Heal orphaned auth identities and send alerts if there were any."""
+ return AuthIdentityMonitor().check_orphaned_auth_identities()
diff --git a/autogpt_platform/backend/backend/monitoring/auth_identity_monitor_test.py b/autogpt_platform/backend/backend/monitoring/auth_identity_monitor_test.py
new file mode 100644
index 0000000000..1b0d89f872
--- /dev/null
+++ b/autogpt_platform/backend/backend/monitoring/auth_identity_monitor_test.py
@@ -0,0 +1,150 @@
+from datetime import datetime, timezone
+from unittest.mock import MagicMock
+
+import pytest
+
+from backend.data.user import OrphanedAuthIdentity, OrphanedAuthIdentityReport
+from backend.monitoring import auth_identity_monitor as monitor_module
+from backend.monitoring.auth_identity_monitor import (
+ OrphanedAuthIdentityException,
+ report_orphaned_auth_identities,
+)
+
+
+def wiring(mocker):
+ db = MagicMock()
+ notifications = MagicMock()
+ mocker.patch.object(monitor_module, "get_database_manager_client", return_value=db)
+ mocker.patch.object(
+ monitor_module, "get_notification_manager_client", return_value=notifications
+ )
+ sentry = mocker.patch.object(monitor_module, "sentry_capture_error")
+ mocker.patch.dict(monitor_module._collisions_paged_at, clear=True)
+ mocker.patch.object(
+ monitor_module.config, "auth_identity_orphan_sweep_enabled", True
+ )
+ return db, notifications, sentry
+
+
+def _collision(identity_id: str = "auth-new") -> OrphanedAuthIdentity:
+ return OrphanedAuthIdentity(
+ id=identity_id,
+ createdAt=datetime.now(timezone.utc),
+ email_owner_id="user-old",
+ )
+
+
+def test_quiet_when_the_invariant_holds(wiring):
+ db, notifications, sentry = wiring
+ db.heal_orphaned_auth_identities.return_value = OrphanedAuthIdentityReport()
+
+ result = report_orphaned_auth_identities()
+
+ assert "No orphaned" in result
+ notifications.discord_system_alert.assert_not_called()
+ sentry.assert_not_called()
+ # Grace window and batch size come from config, not hardcoded.
+ kwargs = db.heal_orphaned_auth_identities.call_args.kwargs
+ assert kwargs == {
+ "grace_secs": monitor_module.config.auth_identity_orphan_grace_secs,
+ "limit": monitor_module.config.auth_identity_orphan_check_limit,
+ }
+
+
+def test_the_sweep_is_off_by_default():
+ assert monitor_module.Config().auth_identity_orphan_sweep_enabled is False
+
+
+def test_heals_and_pages_nothing_while_switched_off(wiring, mocker):
+ db, notifications, sentry = wiring
+ mocker.patch.object(
+ monitor_module.config, "auth_identity_orphan_sweep_enabled", False
+ )
+
+ result = report_orphaned_auth_identities()
+
+ assert "disabled" in result
+ db.heal_orphaned_auth_identities.assert_not_called()
+ notifications.discord_system_alert.assert_not_called()
+ sentry.assert_not_called()
+
+
+def test_pages_when_it_had_to_heal_or_could_not(wiring):
+ db, notifications, sentry = wiring
+ collided = OrphanedAuthIdentity(
+ id="auth-new",
+ createdAt=datetime.now(timezone.utc),
+ email_owner_id="user-old",
+ )
+ db.heal_orphaned_auth_identities.return_value = OrphanedAuthIdentityReport(
+ healed=["auth-1"], collided=[collided], failed=["auth-2"]
+ )
+
+ result = report_orphaned_auth_identities()
+
+ # A heal is still an invariant breach: something upstream failed to
+ # provision, and that has to be visible even though the user is fine now.
+ sentry.assert_called_once()
+ assert isinstance(sentry.call_args.args[0], OrphanedAuthIdentityException)
+ notifications.discord_system_alert.assert_called_once_with(result)
+ assert "Healed 1" in result and "auth-1" in result
+ assert "auth-new (email owned by user-old)" in result
+ assert "auth-2" in result
+ # Ids only: no email addresses in an alert that goes to Discord/Sentry.
+ assert "[email protected]" not in result
+
+
+def test_a_repeat_collision_pages_once_a_day(wiring, mocker):
+ """A collision needs a human but comes back on every 15-minute sweep;
+ paging each time would be ~96 alerts a day per account."""
+ db, notifications, sentry = wiring
+ clock = mocker.patch.object(monitor_module.time, "monotonic", return_value=1000.0)
+ db.heal_orphaned_auth_identities.return_value = OrphanedAuthIdentityReport(
+ collided=[_collision()]
+ )
+ warning = mocker.patch.object(monitor_module.logger, "warning")
+
+ report_orphaned_auth_identities()
+ report_orphaned_auth_identities()
+
+ assert sentry.call_count == 1
+ assert notifications.discord_system_alert.call_count == 1
+ warning.assert_called_once()
+
+ clock.return_value = 1000.0 + monitor_module._COLLISION_REPAGE_SECS
+ report_orphaned_auth_identities()
+
+ assert sentry.call_count == 2
+
+
+def test_a_new_collision_still_pages_next_to_a_known_one(wiring):
+ db, notifications, sentry = wiring
+ db.heal_orphaned_auth_identities.return_value = OrphanedAuthIdentityReport(
+ collided=[_collision("auth-a")]
+ )
+ report_orphaned_auth_identities()
+ db.heal_orphaned_auth_identities.return_value = OrphanedAuthIdentityReport(
+ collided=[_collision("auth-a"), _collision("auth-b")]
+ )
+
+ report_orphaned_auth_identities()
+
+ assert sentry.call_count == 2
+
+
+def test_a_heal_always_pages_even_beside_a_known_collision(wiring):
+ db, notifications, sentry = wiring
+ db.heal_orphaned_auth_identities.return_value = OrphanedAuthIdentityReport(
+ collided=[_collision()]
+ )
+ report_orphaned_auth_identities()
+ db.heal_orphaned_auth_identities.return_value = OrphanedAuthIdentityReport(
+ healed=["auth-1"], collided=[_collision()]
+ )
+
+ report_orphaned_auth_identities()
+
+ assert sentry.call_count == 2
diff --git a/autogpt_platform/backend/backend/notifications/auth.py b/autogpt_platform/backend/backend/notifications/auth.py
index 80f20f39eb..2996d64ce4 100644
--- a/autogpt_platform/backend/backend/notifications/auth.py
+++ b/autogpt_platform/backend/backend/notifications/auth.py
@@ -8,7 +8,9 @@ from backend.notifications.renderer import RenderedEmail, build_urls
from backend.notifications.template_env import create_body_environment
from backend.util.settings import Settings
-AuthEmailType = Literal["reset_password", "verify_email", "change_email"]
+AuthEmailType = Literal[
+ "reset_password", "verify_email", "change_email", "set_password"
+]
settings = Settings()
_html_env = create_body_environment(autoescape=True)
_text_env = create_body_environment(autoescape=False)
@@ -22,6 +24,10 @@ class AuthEmailContent(BaseModel):
preheader: str
action: str
reason: str
+ # Must match the links the frontend issues.
+ expiry: str | None = None
+ # What the recipient may not expect from following the link.
+ note: str | None = None
def render_auth_email(email_type: AuthEmailType, action_url: str) -> RenderedEmail:
@@ -49,6 +55,7 @@ _CONTENT: dict[AuthEmailType, AuthEmailContent] = {
preheader="Use the button below to choose a new password.",
action="Reset password",
reason="This link was requested from the AutoGPT password-reset form.",
+ expiry="1 hour",
),
"verify_email": AuthEmailContent(
subject="Verify your AutoGPT Platform email",
@@ -58,6 +65,7 @@ _CONTENT: dict[AuthEmailType, AuthEmailContent] = {
preheader="Use the button below to verify your email.",
action="Verify email",
reason="This link was requested from the AutoGPT sign-up form.",
+ expiry="24 hours",
),
"change_email": AuthEmailContent(
subject="Confirm your new AutoGPT Platform email",
@@ -68,4 +76,24 @@ _CONTENT: dict[AuthEmailType, AuthEmailContent] = {
action="Confirm email",
reason="This link was requested from your AutoGPT account settings.",
),
+ # Sent for an unverified account when a sign-up or resend can't safely send
+ # a verification link, so the email has to say why it came.
+ "set_password": AuthEmailContent(
+ subject="Set your AutoGPT Platform password",
+ eyebrow="ACCOUNT · SET PASSWORD",
+ headline="Set your password",
+ intro=(
+ "Someone asked to sign up for, or verify, an AutoGPT Platform "
+ "account with this email address."
+ ),
+ preheader="Use the button below to set a password and finish signing up.",
+ action="Set password",
+ reason="This link was requested from the AutoGPT sign-up form.",
+ expiry="1 hour",
+ note=(
+ "If you already finished signing up with an earlier link, the "
+ "password you chose then no longer works: set a new one with this "
+ 'link, or use "Forgot password" on the login page.'
+ ),
+ ),
}
diff --git a/autogpt_platform/backend/backend/notifications/subscriber_fields_test.py b/autogpt_platform/backend/backend/notifications/subscriber_fields_test.py
index 5d350ddb12..f815fc70ac 100644
--- a/autogpt_platform/backend/backend/notifications/subscriber_fields_test.py
+++ b/autogpt_platform/backend/backend/notifications/subscriber_fields_test.py
@@ -129,7 +129,7 @@ async def _get_or_create(existing):
with (
patch.object(user_data, "prisma", prisma),
patch.object(user_data, "_ensure_user_profile", AsyncMock()),
- patch.object(user_data, "ensure_personal_org", AsyncMock()),
+ patch.object(user_data, "ensure_personal_org", AsyncMock(return_value=False)),
patch.object(user_data, "schedule_posthog_lifecycle_sync", MagicMock()),
patch.object(user_data.User, "from_db", MagicMock()),
patch.object(user_data, "UserCreationResult", MagicMock()),
diff --git a/autogpt_platform/backend/backend/notifications/templates/auth.html.j2 b/autogpt_platform/backend/backend/notifications/templates/auth.html.j2
index c4f4f7f842..9ab74f6acd 100644
--- a/autogpt_platform/backend/backend/notifications/templates/auth.html.j2
+++ b/autogpt_platform/backend/backend/notifications/templates/auth.html.j2
@@ -14,6 +14,8 @@
{% call ui.para(top=6, size=12, lh=18) %}
<a href="{{ action_url }}" style="color:#4D36AD; text-decoration:underline; font-family:{{ ui.MONO }}; font-size:12px; overflow-wrap:anywhere; word-break:break-word;">{{ action_url }}</a>
{% endcall %}
+{% if content.expiry %}{% call ui.para() %}The link expires in {{ content.expiry }}.{% endcall %}{% endif %}
+{% if content.note %}{% call ui.para() %}{{ content.note }}{% endcall %}{% endif %}
{{ ui.close_row(content.reason, 'Something wrong? Ask in Discord', urls.discord) }}
{{ ui.sheet_close() }}
{{ ui.page_close() }}
diff --git a/autogpt_platform/backend/backend/notifications/templates/auth.txt.j2 b/autogpt_platform/backend/backend/notifications/templates/auth.txt.j2
index 4549ec1c89..b79a58fac5 100644
--- a/autogpt_platform/backend/backend/notifications/templates/auth.txt.j2
+++ b/autogpt_platform/backend/backend/notifications/templates/auth.txt.j2
@@ -4,7 +4,11 @@
{{ content.action }}:
{{ action_url }}
-
+{% if content.expiry %}
+The link expires in {{ content.expiry }}.
+{% endif %}{% if content.note %}
+{{ content.note }}
+{% endif %}
{{ content.reason }}
Something wrong? Ask in Discord: {{ urls.discord }}
diff --git a/autogpt_platform/backend/backend/util/settings.py b/autogpt_platform/backend/backend/util/settings.py
index f8e2aab723..dbdae9eff5 100644
--- a/autogpt_platform/backend/backend/util/settings.py
+++ b/autogpt_platform/backend/backend/util/settings.py
@@ -355,6 +355,38 @@ class Config(UpdateTrackingModel["Config"], BaseSettings):
description="Number of top blocks with most errors to show when no blocks exceed threshold (0 to disable).",
)
+ # Auth identity <-> platform User invariant monitoring
+ auth_identity_orphan_sweep_enabled: bool = Field(
+ default=False,
+ description=(
+ "Run the sweep that heals auth identities with no platform User row. "
+ "Off by default: its first run backfills every such identity, and "
+ "each heal counts as a sign-up in PostHog."
+ ),
+ )
+ auth_identity_orphan_check_interval_secs: int = Field(
+ default=15 * 60,
+ ge=60,
+ description=(
+ "Interval in seconds between sweeps for auth identities that have no "
+ "platform User row. Each sweep heals what it finds and alerts."
+ ),
+ )
+ auth_identity_orphan_grace_secs: int = Field(
+ default=5 * 60,
+ ge=0,
+ description=(
+ "Age in seconds an auth identity must reach before it counts as "
+ "orphaned, so a sign-up still in flight is not flagged or healed early."
+ ),
+ )
+ auth_identity_orphan_check_limit: int = Field(
+ default=100,
+ ge=1,
+ le=1000,
+ description="Maximum orphaned auth identities healed per sweep.",
+ )
+
# Execution Accuracy Monitoring
execution_accuracy_check_interval_hours: int = Field(
default=24,
diff --git a/autogpt_platform/frontend/package.json b/autogpt_platform/frontend/package.json
index f4cb467532..42b0264c4c 100644
--- a/autogpt_platform/frontend/package.json
+++ b/autogpt_platform/frontend/package.json
@@ -36,6 +36,7 @@
],
"dependencies": {
"@ai-sdk/react": "3.0.61",
+ "@better-auth/core": "1.6.22",
"@faker-js/faker": "10.0.0",
"@ferrucc-io/emoji-picker": "0.0.48",
"@hookform/resolvers": "5.2.2",
diff --git a/autogpt_platform/frontend/pnpm-lock.yaml b/autogpt_platform/frontend/pnpm-lock.yaml
index a2628bb72e..61e7138c98 100644
--- a/autogpt_platform/frontend/pnpm-lock.yaml
+++ b/autogpt_platform/frontend/pnpm-lock.yaml
@@ -19,6 +19,9 @@ importers:
'@ai-sdk/react':
specifier: 3.0.61
+ '@better-auth/core':
+ specifier: 1.6.22
'@faker-js/faker':
specifier: 10.0.0
version: 10.0.0
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/login/__tests__/actions.test.ts b/autogpt_platform/frontend/src/app/(no-navbar)/login/__tests__/actions.test.ts
index 70b7809e6e..b42ed541b3 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/login/__tests__/actions.test.ts
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/login/__tests__/actions.test.ts
@@ -6,6 +6,8 @@ const rollbackSessionMock = vi.fn();
const createUserMock = vi.fn();
const getOnboardingStatusMock = vi.fn();
const captureExceptionMock = vi.fn();
+const scheduleAccountCreatedGoalMock = vi.fn();
+const markAccountCreatedMock = vi.fn();
vi.mock("@/lib/auth/auth", () => ({
auth: {
@@ -19,12 +21,20 @@ vi.mock("@/lib/auth/server/rollbackSession", () => ({
rollbackSession: (...args: unknown[]) => rollbackSessionMock(...args),
}));
-vi.mock("@/lib/autogpt-server-api", () => ({
- default: class BackendAPIMock {
- createUser(...args: unknown[]) {
- return createUserMock(...args);
- }
- },
+vi.mock("@/app/api/__generated__/endpoints/auth/auth", () => ({
+ postV1GetOrCreateUser: (...args: unknown[]) => createUserMock(...args),
+}));
+
+vi.mock("@/services/analytics/datafast-server", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("@/services/analytics/datafast-server")
+ >()),
+ scheduleAccountCreatedGoal: (...args: unknown[]) =>
+ scheduleAccountCreatedGoalMock(...args),
+}));
+
+vi.mock("@/services/analytics/account-created-server", () => ({
+ markAccountCreated: (...args: unknown[]) => markAccountCreatedMock(...args),
}));
vi.mock("@/app/api/helpers", () => ({
@@ -41,12 +51,24 @@ vi.mock("@sentry/nextjs", () => ({
import { login } from "../actions";
+// What the backend's get-or-create answers: X-AutoGPT-User-Created is true
+// only on the call that created the User.
+function userResponse(created: boolean, status = 200) {
+ return {
+ status,
+ data: { id: "user-1" },
+ headers: new Headers({ "X-AutoGPT-User-Created": String(created) }),
+ };
+}
+
beforeEach(() => {
signInEmailMock.mockReset();
rollbackSessionMock.mockReset();
createUserMock.mockReset();
getOnboardingStatusMock.mockReset();
captureExceptionMock.mockReset();
+ scheduleAccountCreatedGoalMock.mockReset();
+ markAccountCreatedMock.mockReset();
vi.spyOn(console, "error").mockImplementation(() => undefined);
});
@@ -57,13 +79,17 @@ afterEach(() => {
describe("login", () => {
it("signs in, provisions the backend user, and points new users at onboarding", async () => {
signInEmailMock.mockResolvedValue({ user: { id: "user-1" } });
- createUserMock.mockResolvedValue({ id: "user-1" });
+ createUserMock.mockResolvedValue(userResponse(false));
getOnboardingStatusMock.mockResolvedValue({ shouldShowOnboarding: true });
const result = await login("[email protected]", "hunter2-password");
expect(signInEmailMock).toHaveBeenCalledWith({
- body: { email: "[email protected]", password: "hunter2-password" },
+ body: {
+ email: "[email protected]",
+ password: "hunter2-password",
+ callbackURL: "/auth/callback?method=email",
+ },
headers: expect.any(Headers),
});
expect(createUserMock).toHaveBeenCalledTimes(1);
@@ -73,7 +99,7 @@ describe("login", () => {
it("sends returning users to copilot when onboarding is already complete", async () => {
signInEmailMock.mockResolvedValue({ user: { id: "user-1" } });
- createUserMock.mockResolvedValue({ id: "user-1" });
+ createUserMock.mockResolvedValue(userResponse(false));
getOnboardingStatusMock.mockResolvedValue({ shouldShowOnboarding: false });
const result = await login("[email protected]", "hunter2-password");
@@ -95,6 +121,34 @@ describe("login", () => {
expect(createUserMock).not.toHaveBeenCalled();
});
+ it("reports email_not_verified so the page can show check-your-inbox", async () => {
+ // Right password, unverified address: with sendOnSignIn Better Auth has
+ // already emailed a fresh link by the time it throws this.
+ signInEmailMock.mockRejectedValue(
+ new APIError("FORBIDDEN", {
+ message: "Email not verified",
+ code: "EMAIL_NOT_VERIFIED",
+ }),
+ );
+
+ const result = await login(
+ "hunter2-password",
+ "/marketplace",
+ );
+
+ expect(result).toEqual({
+ success: false,
+ error: "email_not_verified",
+ email: "[email protected]",
+ });
+ expect(signInEmailMock.mock.calls[0][0].body.callbackURL).toBe(
+ "/auth/callback?method=email&next=%2Fmarketplace",
+ );
+ expect(createUserMock).not.toHaveBeenCalled();
+ expect(rollbackSessionMock).not.toHaveBeenCalled();
+ });
+
it("falls back to a generic message when the APIError carries no body message", async () => {
signInEmailMock.mockRejectedValue(new APIError("UNAUTHORIZED"));
@@ -132,7 +186,7 @@ describe("login", () => {
it("does not roll back the session when login succeeds end to end", async () => {
signInEmailMock.mockResolvedValue({ user: { id: "user-1" } });
- createUserMock.mockResolvedValue({});
+ createUserMock.mockResolvedValue(userResponse(false));
getOnboardingStatusMock.mockResolvedValue({ shouldShowOnboarding: false });
const result = await login("[email protected]", "hunter2-password");
@@ -140,4 +194,44 @@ describe("login", () => {
expect(rollbackSessionMock).not.toHaveBeenCalled();
expect(result).toEqual({ success: true, next: "/copilot" });
});
+
+ it("counts the sign-up when this login is the call that created the account", async () => {
+ signInEmailMock.mockResolvedValue({ user: { id: "user-1" } });
+ createUserMock.mockResolvedValue(userResponse(true));
+ getOnboardingStatusMock.mockResolvedValue({ shouldShowOnboarding: true });
+
+ const result = await login("[email protected]", "hunter2-password");
+
+ expect(scheduleAccountCreatedGoalMock).toHaveBeenCalledTimes(1);
+ expect(scheduleAccountCreatedGoalMock).toHaveBeenCalledWith("email");
+ expect(markAccountCreatedMock).toHaveBeenCalledTimes(1);
+ expect(markAccountCreatedMock).toHaveBeenCalledWith("email");
+ expect(result).toEqual({ success: true, next: "/onboarding" });
+ });
+
+ it("does not count a login into an account that already existed", async () => {
+ signInEmailMock.mockResolvedValue({ user: { id: "user-1" } });
+ createUserMock.mockResolvedValue(userResponse(false));
+ getOnboardingStatusMock.mockResolvedValue({ shouldShowOnboarding: false });
+
+ await login("[email protected]", "hunter2-password");
+
+ expect(scheduleAccountCreatedGoalMock).not.toHaveBeenCalled();
+ expect(markAccountCreatedMock).not.toHaveBeenCalled();
+ });
+
+ it("rolls back and counts nothing when provisioning answers an error status", async () => {
+ signInEmailMock.mockResolvedValue({ user: { id: "user-1" } });
+ createUserMock.mockResolvedValue(userResponse(true, 500));
+
+ const result = await login("[email protected]", "hunter2-password");
+
+ expect(rollbackSessionMock).toHaveBeenCalledTimes(1);
+ expect(scheduleAccountCreatedGoalMock).not.toHaveBeenCalled();
+ expect(markAccountCreatedMock).not.toHaveBeenCalled();
+ expect(result).toEqual({
+ success: false,
+ error: "Failed to login. Please try again.",
+ });
+ });
});
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/login/__tests__/email-verification.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/login/__tests__/email-verification.test.tsx
new file mode 100644
index 0000000000..d77fdce183
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/login/__tests__/email-verification.test.tsx
@@ -0,0 +1,101 @@
+import type { ReactNode } from "react";
+import { fireEvent, render, screen } from "@/tests/integrations/test-utils";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import LoginPage from "../page";
+
+const mockLoginAction = vi.hoisted(() => vi.fn());
+let mockSearchParams = new URLSearchParams();
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ replace: vi.fn(), push: vi.fn() }),
+ useSearchParams: () => mockSearchParams,
+ usePathname: () => "/login",
+}));
+
+vi.mock("@/providers/onboarding/onboarding-provider", () => ({
+ default: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+vi.mock("@/lib/auth/hooks/useAuth", () => ({
+ useAuth: () => ({ user: null, isUserLoading: false, isLoggedIn: false }),
+}));
+
+vi.mock("../actions", () => ({
+ login: mockLoginAction,
+}));
+
+const email = "[email protected]";
+
+function submitLoginForm() {
+ fireEvent.change(screen.getByLabelText("Email"), {
+ target: { value: email },
+ });
+ fireEvent.change(screen.getByLabelText("Password", { selector: "input" }), {
+ target: { value: "hunter2-password" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Log in" }));
+}
+
+describe("LoginPage for an unverified email", () => {
+ beforeEach(() => {
+ mockLoginAction.mockReset();
+ mockSearchParams = new URLSearchParams();
+ });
+
+ test("shows check-your-inbox instead of a dead-end error", async () => {
+ mockLoginAction.mockResolvedValue({
+ success: false,
+ error: "email_not_verified",
+ email,
+ });
+ render(<LoginPage />);
+
+ submitLoginForm();
+
+ expect(
+ await screen.findByRole("heading", {
+ name: "Verify your email to log in",
+ }),
+ ).toBeDefined();
+ expect(screen.getByText(email)).toBeDefined();
+ expect(mockLoginAction).toHaveBeenCalledWith(
+ email,
+ "hunter2-password",
+ null,
+ );
+ });
+
+ test("back to log in returns to the form", async () => {
+ mockLoginAction.mockResolvedValue({
+ success: false,
+ error: "email_not_verified",
+ email,
+ });
+ render(<LoginPage />);
+
+ submitLoginForm();
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Back to log in" }),
+ );
+
+ expect(await screen.findByRole("button", { name: "Log in" })).toBeDefined();
+ });
+
+ test("explains an expired or used verification link", () => {
+ mockSearchParams = new URLSearchParams({ email_verification: "expired" });
+ render(<LoginPage />);
+
+ expect(
+ screen.getByText(
+ "That verification link has expired or was already used. Log in and we'll email you a new one.",
+ ),
+ ).toBeDefined();
+ });
+
+ test("ignores an unknown notice value", () => {
+ mockSearchParams = new URLSearchParams({ email_verification: "<b>x</b>" });
+ render(<LoginPage />);
+
+ expect(screen.queryByRole("alert")).toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/login/actions.ts b/autogpt_platform/frontend/src/app/(no-navbar)/login/actions.ts
index 4038367d1a..31984cfb76 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/login/actions.ts
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/login/actions.ts
@@ -1,15 +1,28 @@
"use server";
+import { postV1GetOrCreateUser } from "@/app/api/__generated__/endpoints/auth/auth";
import { auth } from "@/lib/auth/auth";
+import {
+ EMAIL_NOT_VERIFIED_CODE,
+ getEmailVerificationCallbackURL,
+} from "@/lib/auth/email-verification";
import { rollbackSession } from "@/lib/auth/server/rollbackSession";
-import BackendAPI from "@/lib/autogpt-server-api";
+import { markAccountCreated } from "@/services/analytics/account-created-server";
+import {
+ scheduleAccountCreatedGoal,
+ wasAccountCreated,
+} from "@/services/analytics/datafast-server";
import { loginFormSchema } from "@/types/auth";
import * as Sentry from "@sentry/nextjs";
import { APIError } from "better-auth/api";
import { headers } from "next/headers";
import { getOnboardingStatus } from "../../api/helpers";
-export async function login(email: string, password: string) {
+export async function login(
+ email: string,
+ password: string,
+ next?: string | null,
+) {
try {
const parsed = loginFormSchema.safeParse({ email, password });
@@ -25,11 +38,22 @@ export async function login(email: string, password: string) {
body: {
email: parsed.data.email,
password: parsed.data.password,
+ // Only used for the link Better Auth emails to an unverified user.
+ callbackURL: getEmailVerificationCallbackURL(next),
},
headers: await headers(),
});
} catch (error) {
if (error instanceof APIError) {
+ // Right password, unverified address: Better Auth has just emailed a
+ // fresh verification link (sendOnSignIn).
+ if (error.body?.code === EMAIL_NOT_VERIFIED_CODE) {
+ return {
+ success: false,
+ error: "email_not_verified",
+ email: parsed.data.email,
+ };
+ }
return {
success: false,
error: error.body?.message || "Invalid email or password",
@@ -38,15 +62,23 @@ export async function login(email: string, password: string) {
throw error;
}
+ // With verification required, this can be the call that creates the
+ // account: a mail scanner may have opened the verify link first, so the
+ // owner's own click lands here instead of on /auth/callback. The backend
+ // reports a creation once, so the conversion can't count twice.
+ let accountCreated = false;
try {
- const api = new BackendAPI();
- await api.createUser();
+ accountCreated = wasAccountCreated(await postV1GetOrCreateUser());
} catch (createUserError) {
// The session cookie is already set; revoke it so the browser's auth
// state matches the failure the UI is about to show.
await rollbackSession();
throw createUserError;
}
+ if (accountCreated) {
+ await scheduleAccountCreatedGoal("email");
+ await markAccountCreated("email");
+ }
const { shouldShowOnboarding } = await getOnboardingStatus();
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/login/helpers.ts b/autogpt_platform/frontend/src/app/(no-navbar)/login/helpers.ts
index e69de29bb2..6acd32f970 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/login/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/login/helpers.ts
@@ -0,0 +1,10 @@
+import type { EmailVerificationNotice } from "@/lib/auth/email-verification";
+
+export const EMAIL_VERIFICATION_NOTICE_COPY: Record<
+ EmailVerificationNotice,
+ string
+> = {
+ expired:
+ "That verification link has expired or was already used. Log in and we'll email you a new one.",
+ verified: "Your email is verified. Log in to continue.",
+};
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/login/page.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/login/page.tsx
index 4492b79c3d..6fceef6f66 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/login/page.tsx
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/login/page.tsx
@@ -5,15 +5,18 @@ import { Input } from "@/components/atoms/Input/Input";
import { Link } from "@/components/atoms/Link/Link";
import { Text } from "@/components/atoms/Text/Text";
import AuthFeedback from "@/components/auth/AuthFeedback";
+import { CheckYourInbox } from "@/components/auth/CheckYourInbox/CheckYourInbox";
import { EmailNotAllowedModal } from "@/components/auth/EmailNotAllowedModal";
import { GoogleOAuthButton } from "@/components/auth/GoogleOAuthButton";
import { AuthDivider } from "@/components/auth/AuthSplitLayout/AuthDivider";
import { AuthSplitLayout } from "@/components/auth/AuthSplitLayout/AuthSplitLayout";
import { MobileWarningBanner } from "@/components/auth/MobileWarningBanner";
+import { Alert, AlertDescription } from "@/components/molecules/Alert/Alert";
import { environment } from "@/services/environment";
import { useSearchParams } from "next/navigation";
import { LoadingLogin } from "./components/LoadingLogin";
import { LoginMarketingPanel } from "./components/LoginMarketingPanel";
+import { EMAIL_VERIFICATION_NOTICE_COPY } from "./helpers";
import { useLoginPage } from "./useLoginPage";
export const dynamic = "force-dynamic";
@@ -29,6 +32,9 @@ export default function LoginPage() {
user,
form,
feedback,
+ nextUrl: safeNextUrl,
+ verificationEmail,
+ verificationNotice,
isLoading,
isGoogleLoading,
isCloudEnv,
@@ -37,12 +43,26 @@ export default function LoginPage() {
handleSubmit,
handleProviderLogin,
handleCloseNotAllowedModal,
+ handleBackToLogin,
} = useLoginPage();
if (isUserLoading || user) {
return <LoadingLogin />;
}
+ if (verificationEmail) {
+ return (
+ <AuthSplitLayout marketing={<LoginMarketingPanel />}>
+ <CheckYourInbox
+ email={verificationEmail}
+ reason="login"
+ next={safeNextUrl}
+ onBack={handleBackToLogin}
+ />
+ </AuthSplitLayout>
+ );
+ }
+
return (
<AuthSplitLayout marketing={<LoginMarketingPanel />}>
<div className="mb-8">
@@ -51,6 +71,14 @@ export default function LoginPage() {
</Text>
</div>
+ {verificationNotice ? (
+ <Alert className="mb-6">
+ <AlertDescription>
+ {EMAIL_VERIFICATION_NOTICE_COPY[verificationNotice]}
+ </AlertDescription>
+ </Alert>
+ ) : null}
+
<Form {...form}>
<form onSubmit={handleSubmit} className="flex w-full flex-col gap-1">
<FormField
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/login/useLoginPage.ts b/autogpt_platform/frontend/src/app/(no-navbar)/login/useLoginPage.ts
index 700e9808ea..013dccb644 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/login/useLoginPage.ts
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/login/useLoginPage.ts
@@ -1,6 +1,10 @@
import { useToast } from "@/components/molecules/Toast/use-toast";
import { useCaptureMarketingPrompt } from "@/hooks/useCaptureMarketingPrompt";
import { sanitizeAuthNext } from "@/lib/auth-redirect";
+import {
+ EMAIL_VERIFICATION_NOTICE_PARAM,
+ getEmailVerificationNotice,
+} from "@/lib/auth/email-verification";
import { useAuth } from "@/lib/auth/hooks/useAuth";
import { environment } from "@/services/environment";
import { loginFormSchema, LoginProvider } from "@/types/auth";
@@ -23,11 +27,17 @@ export function useLoginPage() {
const [isLoggingIn, setIsLoggingIn] = useState(false);
const [isGoogleLoading, setIsGoogleLoading] = useState(false);
const [showNotAllowedModal, setShowNotAllowedModal] = useState(false);
+ const [verificationEmail, setVerificationEmail] = useState<string | null>(
+ null,
+ );
const isCloudEnv = environment.isCloud();
// Same-origin redirect target; off-site values are dropped so a crafted
// `/login?next=https://phishing.site` cannot redirect users elsewhere.
const nextUrl = sanitizeAuthNext(searchParams.get("next"));
+ const verificationNotice = getEmailVerificationNotice(
+ searchParams.get(EMAIL_VERIFICATION_NOTICE_PARAM),
+ );
// Only honour explicit `?next=` deep links here. Generic "already logged in
// on /login, get me out" is handled by OnboardingProvider so the user lands
@@ -97,7 +107,14 @@ export function useLoginPage() {
}
try {
- const result = await loginAction(data.email, data.password);
+ const result = await loginAction(data.email, data.password, nextUrl);
+
+ if (result.error === "email_not_verified" && result.email) {
+ setVerificationEmail(result.email);
+ setIsLoading(false);
+ setIsLoggingIn(false);
+ return;
+ }
if (!result.success) {
throw new Error(result.error || "Login failed");
@@ -125,6 +142,9 @@ export function useLoginPage() {
return {
form,
feedback,
+ nextUrl,
+ verificationEmail,
+ verificationNotice,
user,
isLoading,
isGoogleLoading,
@@ -134,5 +154,6 @@ export function useLoginPage() {
handleSubmit: form.handleSubmit(handleLogin),
handleProviderLogin,
handleCloseNotAllowedModal: () => setShowNotAllowedModal(false),
+ handleBackToLogin: () => setVerificationEmail(null),
};
}
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/actions.test.ts b/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/actions.test.ts
index 3523bc8084..3e1b0a9c8e 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/actions.test.ts
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/actions.test.ts
@@ -44,9 +44,9 @@ vi.mock("@sentry/nextjs", () => ({
describe("email signup account creation tracking", () => {
beforeEach(() => {
vi.clearAllMocks();
- // Better Auth's signUpEmail sets the session cookie; a resolved call is
- // the success case.
- mocks.signUpEmail.mockResolvedValue({});
+ // Better Auth's signUpEmail sets the session cookie and returns its
+ // token when no email verification is required.
+ mocks.signUpEmail.mockResolvedValue({ token: "session-token" });
mocks.getOnboardingStatus.mockResolvedValue({
shouldShowOnboarding: true,
});
@@ -97,6 +97,29 @@ describe("email signup account creation tracking", () => {
expect(mocks.cookieSet).not.toHaveBeenCalled();
});
+ it("does not track an unverified sign-up; the verification link does", async () => {
+ // With AUTH_REQUIRE_EMAIL_VERIFICATION=true there is no session yet, so
+ // the account is not provisioned or counted here. /auth/callback?method=email
+ // does both once the link is clicked.
+ mocks.signUpEmail.mockResolvedValue({ token: null });
+
+ const result = await signup(
+ "ValidPassword123!",
+ "ValidPassword123!",
+ true,
+ );
+
+ expect(result).toEqual({
+ success: true,
+ verificationRequired: true,
+ email: "[email protected]",
+ });
+ expect(mocks.postV1GetOrCreateUser).not.toHaveBeenCalled();
+ expect(mocks.scheduleAccountCreatedGoal).not.toHaveBeenCalled();
+ expect(mocks.cookieSet).not.toHaveBeenCalled();
+ });
+
it("reports a thrown backend error instead of completing signup", async () => {
// The generated client throws ApiError on non-2xx (custom-mutator), which
// the action catches to roll back the session and surface the failure.
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/email-verification.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/email-verification.test.tsx
new file mode 100644
index 0000000000..beba842d96
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/email-verification.test.tsx
@@ -0,0 +1,211 @@
+import type { ReactNode } from "react";
+import { http, HttpResponse } from "msw";
+import { server } from "@/mocks/mock-server";
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@/tests/integrations/test-utils";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { Toaster } from "@/components/molecules/Toast/toaster";
+import SignupPage from "../page";
+
+const mockSignupAction = vi.hoisted(() => vi.fn());
+const routerReplace = vi.hoisted(() => vi.fn());
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ replace: routerReplace, push: vi.fn() }),
+ useSearchParams: () => new URLSearchParams(),
+ usePathname: () => "/signup",
+}));
+
+vi.mock("@/providers/onboarding/onboarding-provider", () => ({
+ default: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+vi.mock("@/lib/auth/hooks/useAuth", () => ({
+ useAuth: () => ({ user: null, isUserLoading: false, isLoggedIn: false }),
+}));
+
+vi.mock("../actions", () => ({
+ signup: mockSignupAction,
+}));
+
+const email = "[email protected]";
+const password = "validpassword123";
+
+function submitSignupForm() {
+ fireEvent.change(screen.getByLabelText("Email"), {
+ target: { value: email },
+ });
+ fireEvent.change(screen.getByLabelText("Password", { selector: "input" }), {
+ target: { value: password },
+ });
+ fireEvent.change(
+ screen.getByLabelText("Confirm Password", { selector: "input" }),
+ { target: { value: password } },
+ );
+ fireEvent.click(screen.getByRole("checkbox"));
+ fireEvent.click(screen.getByRole("button", { name: "Sign up" }));
+}
+
+function verificationRequired() {
+ mockSignupAction.mockResolvedValue({
+ success: true,
+ verificationRequired: true,
+ email,
+ });
+}
+
+async function waitOutCooldown() {
+ for (let second = 0; second < 60; second++) {
+ await act(async () => {
+ vi.advanceTimersByTime(1000);
+ });
+ }
+}
+
+describe("SignupPage with email verification required", () => {
+ beforeEach(() => {
+ mockSignupAction.mockReset();
+ routerReplace.mockReset();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ test("shows check-your-inbox with the address instead of leaving the page", async () => {
+ verificationRequired();
+ render(<SignupPage />);
+
+ submitSignupForm();
+
+ const heading = await screen.findByRole("heading", {
+ name: "Check your inbox",
+ });
+ await waitFor(() => expect(document.activeElement).toBe(heading));
+ expect(screen.getByText(email)).toBeDefined();
+ expect(
+ screen.getByRole("button", { name: "Resend email in 60s" }),
+ ).toHaveProperty("disabled", true);
+ expect(routerReplace).not.toHaveBeenCalled();
+ });
+
+ test("resends the link through Better Auth once the cooldown is over", async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ const resendBodies: unknown[] = [];
+ server.use(
+ http.post("*/api/auth/send-verification-email", async ({ request }) => {
+ resendBodies.push(await request.json());
+ return HttpResponse.json({ status: true });
+ }),
+ );
+ verificationRequired();
+ render(<SignupPage />);
+
+ submitSignupForm();
+ await screen.findByRole("heading", { name: "Check your inbox" });
+ await waitOutCooldown();
+ fireEvent.click(screen.getByRole("button", { name: "Resend email" }));
+
+ await waitFor(() => {
+ expect(resendBodies).toEqual([
+ { email, callbackURL: "/auth/callback?method=email" },
+ ]);
+ });
+ expect(
+ await screen.findByRole("button", { name: "Resend email in 60s" }),
+ ).toHaveProperty("disabled", true);
+ });
+
+ test("keeps the button available when the resend fails", async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ server.use(
+ http.post("*/api/auth/send-verification-email", () =>
+ HttpResponse.json({ message: "Too many requests" }, { status: 429 }),
+ ),
+ );
+ verificationRequired();
+ render(<SignupPage />);
+
+ submitSignupForm();
+ await screen.findByRole("heading", { name: "Check your inbox" });
+ await waitOutCooldown();
+ fireEvent.click(screen.getByRole("button", { name: "Resend email" }));
+
+ await waitFor(() => {
+ expect(
+ screen.getByRole("button", { name: "Resend email" }),
+ ).toHaveProperty("disabled", false);
+ });
+ });
+
+ test("shows an error and frees the button when the resend can't reach the server", async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ let networkUp = false;
+ server.use(
+ http.post("*/api/auth/send-verification-email", () =>
+ networkUp ? HttpResponse.json({ status: true }) : HttpResponse.error(),
+ ),
+ );
+ verificationRequired();
+ render(
+ <>
+ <SignupPage />
+ <Toaster />
+ </>,
+ );
+
+ submitSignupForm();
+ await screen.findByRole("heading", { name: "Check your inbox" });
+ await waitOutCooldown();
+ fireEvent.click(screen.getByRole("button", { name: "Resend email" }));
+
+ expect(await screen.findByText("We couldn't send the email")).toBeDefined();
+ await waitFor(() => {
+ expect(
+ screen.getByRole("button", { name: "Resend email" }),
+ ).toHaveProperty("disabled", false);
+ });
+
+ networkUp = true;
+ fireEvent.click(screen.getByRole("button", { name: "Resend email" }));
+
+ expect(
+ await screen.findByRole("button", { name: "Resend email in 60s" }),
+ ).toHaveProperty("disabled", true);
+ expect(await screen.findByText(`Email sent to ${email}`)).toBeDefined();
+ });
+
+ test("start again returns to the form with the address cleared", async () => {
+ verificationRequired();
+ render(<SignupPage />);
+
+ submitSignupForm();
+ await screen.findByRole("heading", { name: "Check your inbox" });
+ fireEvent.click(screen.getByRole("button", { name: "Start again" }));
+
+ const emailInput = (await screen.findByLabelText(
+ "Email",
+ )) as HTMLInputElement;
+ expect(emailInput.value).toBe("");
+ expect(screen.getByRole("button", { name: "Sign up" })).toBeDefined();
+ });
+
+ test("with verification off, a sign-up with a session still goes straight in", async () => {
+ mockSignupAction.mockResolvedValue({ success: true, next: "/onboarding" });
+ render(<SignupPage />);
+
+ submitSignupForm();
+
+ await waitFor(() => {
+ expect(routerReplace).toHaveBeenCalledWith("/onboarding");
+ });
+ expect(
+ screen.queryByRole("heading", { name: "Check your inbox" }),
+ ).toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/page.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/page.test.tsx
index 28e9dbc2bc..440cda9bfa 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/page.test.tsx
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/page.test.tsx
@@ -63,6 +63,7 @@ describe("SignupPage", () => {
"validpassword123",
"validpassword123",
true,
+ null,
);
});
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/signup-action.test.ts b/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/signup-action.test.ts
index be51e5d523..59442a36bb 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/signup-action.test.ts
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/signup-action.test.ts
@@ -80,7 +80,10 @@ afterEach(() => {
describe("signup", () => {
it("creates the account, provisions the backend user, and routes to onboarding", async () => {
- signUpEmailMock.mockResolvedValue({ user: { id: "user-1" } });
+ signUpEmailMock.mockResolvedValue({
+ token: "session-token",
+ user: { id: "user-1" },
+ });
postV1GetOrCreateUserMock.mockResolvedValue({
status: 200,
data: { id: "user-1" },
@@ -90,7 +93,12 @@ describe("signup", () => {
const result = await signupWithValidPayload();
expect(signUpEmailMock).toHaveBeenCalledWith({
- body: { email, password: validPassword, name: "new.user" },
+ body: {
+ email,
+ password: validPassword,
+ name: "new.user",
+ callbackURL: "/auth/callback?method=email",
+ },
headers: expect.any(Headers),
});
expect(postV1GetOrCreateUserMock).toHaveBeenCalledTimes(1);
@@ -98,7 +106,10 @@ describe("signup", () => {
});
it("routes straight to copilot when onboarding is already complete", async () => {
- signUpEmailMock.mockResolvedValue({ user: { id: "user-1" } });
+ signUpEmailMock.mockResolvedValue({
+ token: "session-token",
+ user: { id: "user-1" },
+ });
postV1GetOrCreateUserMock.mockResolvedValue({
status: 200,
data: { id: "user-1" },
@@ -157,7 +168,10 @@ describe("signup", () => {
});
it("asks the user to retry when backend user provisioning fails after sign-up", async () => {
- signUpEmailMock.mockResolvedValue({ user: { id: "user-1" } });
+ signUpEmailMock.mockResolvedValue({
+ token: "session-token",
+ user: { id: "user-1" },
+ });
postV1GetOrCreateUserMock.mockRejectedValue(new Error("backend down"));
const result = await signupWithValidPayload();
@@ -170,6 +184,38 @@ describe("signup", () => {
});
});
+ it("shows check-your-inbox instead of provisioning when verification is required", async () => {
+ // AUTH_REQUIRE_EMAIL_VERIFICATION=true: Better Auth creates no session and
+ // emails a link. Provisioning without a session is what used to fail with
+ // 401 "Failed to complete account setup".
+ signUpEmailMock.mockResolvedValue({ token: null, user: { id: "user-1" } });
+
+ const result = await signupWithValidPayload();
+
+ expect(result).toEqual({
+ success: true,
+ verificationRequired: true,
+ email,
+ });
+ expect(postV1GetOrCreateUserMock).not.toHaveBeenCalled();
+ expect(rollbackSessionMock).not.toHaveBeenCalled();
+ expect(getOnboardingStatusMock).not.toHaveBeenCalled();
+ });
+
+ it("carries a safe next path through the verification link", async () => {
+ signUpEmailMock.mockResolvedValue({ token: null, user: { id: "user-1" } });
+
+ await signup(email, validPassword, validPassword, true, "/marketplace");
+ await signup(email, validPassword, validPassword, true, "https://evil.com");
+
+ expect(signUpEmailMock.mock.calls[0][0].body.callbackURL).toBe(
+ "/auth/callback?method=email&next=%2Fmarketplace",
+ );
+ expect(signUpEmailMock.mock.calls[1][0].body.callbackURL).toBe(
+ "/auth/callback?method=email",
+ );
+ });
+
it("rejects a password shorter than 12 characters without calling Better Auth", async () => {
const result = await signup(email, "short-pass", "short-pass", true);
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/signup/actions.ts b/autogpt_platform/frontend/src/app/(no-navbar)/signup/actions.ts
index 9d041ad35a..c6f1eb51e4 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/signup/actions.ts
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/signup/actions.ts
@@ -3,6 +3,7 @@
import { postV1GetOrCreateUser } from "@/app/api/__generated__/endpoints/auth/auth";
import { getOnboardingStatus } from "@/app/api/helpers";
import { auth } from "@/lib/auth/auth";
+import { getEmailVerificationCallbackURL } from "@/lib/auth/email-verification";
import { rollbackSession } from "@/lib/auth/server/rollbackSession";
import { markAccountCreated } from "@/services/analytics/account-created-server";
import {
@@ -20,6 +21,7 @@ export async function signup(
password: string,
confirmPassword: string,
agreeToTerms: boolean,
+ next?: string | null,
) {
try {
const parsed = signupFormSchema.safeParse({
@@ -36,13 +38,15 @@ export async function signup(
};
}
+ let signUpResult;
try {
// The session cookie is set automatically by the nextCookies plugin.
- await auth.api.signUpEmail({
+ signUpResult = await auth.api.signUpEmail({
body: {
email: parsed.data.email,
password: parsed.data.password,
name: parsed.data.email.split("@")[0],
+ callbackURL: getEmailVerificationCallbackURL(next),
},
headers: await headers(),
});
@@ -74,6 +78,18 @@ export async function signup(
throw error;
}
+ // With email verification required there is no session yet: Better Auth
+ // has emailed a link instead (and answers an address that already has an
+ // account the same way). The platform user and the sign-up conversion
+ // wait for that link, which lands on /auth/callback.
+ if (!signUpResult.token) {
+ return {
+ success: true,
+ verificationRequired: true,
+ email: parsed.data.email,
+ };
+ }
+
try {
const createUserResponse = await postV1GetOrCreateUser();
if (wasAccountCreated(createUserResponse)) {
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/signup/page.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/signup/page.tsx
index 91ca7bf8d9..45a291cf71 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/signup/page.tsx
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/signup/page.tsx
@@ -13,6 +13,7 @@ import { Input } from "@/components/atoms/Input/Input";
import { Link } from "@/components/atoms/Link/Link";
import { Text } from "@/components/atoms/Text/Text";
import AuthFeedback from "@/components/auth/AuthFeedback";
+import { CheckYourInbox } from "@/components/auth/CheckYourInbox/CheckYourInbox";
import { EmailNotAllowedModal } from "@/components/auth/EmailNotAllowedModal";
import { GoogleOAuthButton } from "@/components/auth/GoogleOAuthButton";
import { AuthDivider } from "@/components/auth/AuthSplitLayout/AuthDivider";
@@ -38,6 +39,8 @@ export default function SignupPage() {
const {
form,
feedback,
+ nextUrl: safeNextUrl,
+ verificationEmail,
isLoggedIn,
hasInitializedAuth,
isLoading,
@@ -47,12 +50,26 @@ export default function SignupPage() {
handleSubmit,
handleProviderSignup,
handleCloseNotAllowedModal,
+ handleStartAgain,
} = useSignupPage();
if (!hasInitializedAuth || isLoggedIn) {
return <LoadingSignup />;
}
+ if (verificationEmail) {
+ return (
+ <AuthSplitLayout marketing={<SignupMarketingPanel />}>
+ <CheckYourInbox
+ email={verificationEmail}
+ reason="signup"
+ next={safeNextUrl}
+ onBack={handleStartAgain}
+ />
+ </AuthSplitLayout>
+ );
+ }
+
const confirmPasswordError = form.formState.errors.confirmPassword?.message;
const termsError = form.formState.errors.agreeToTerms?.message;
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/signup/useSignupPage.ts b/autogpt_platform/frontend/src/app/(no-navbar)/signup/useSignupPage.ts
index a1553b20f2..813ee2443c 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/signup/useSignupPage.ts
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/signup/useSignupPage.ts
@@ -24,6 +24,9 @@ export function useSignupPage() {
const [isSigningUp, setIsSigningUp] = useState(false);
const [isGoogleLoading, setIsGoogleLoading] = useState(false);
const [showNotAllowedModal, setShowNotAllowedModal] = useState(false);
+ const [verificationEmail, setVerificationEmail] = useState<string | null>(
+ null,
+ );
const isCloudEnv = environment.isCloud();
// Same-origin redirect target; off-site values are dropped so a crafted
@@ -121,6 +124,7 @@ export function useSignupPage() {
data.password,
data.confirmPassword,
data.agreeToTerms,
+ nextUrl,
);
if (!result.success) {
@@ -143,6 +147,13 @@ export function useSignupPage() {
return;
}
+ if (result.verificationRequired) {
+ setVerificationEmail(result.email);
+ setIsLoading(false);
+ setIsSigningUp(false);
+ return;
+ }
+
// Prefer the URL's next parameter, then result.next (for onboarding), then default
const redirectTo = nextUrl || result.next || "/";
router.replace(redirectTo);
@@ -163,9 +174,16 @@ export function useSignupPage() {
}
}
+ function handleStartAgain() {
+ setVerificationEmail(null);
+ form.resetField("email");
+ }
+
return {
form,
feedback,
+ nextUrl,
+ verificationEmail,
isLoggedIn: !!user,
hasInitializedAuth,
isLoading,
@@ -176,5 +194,6 @@ export function useSignupPage() {
handleSubmit: form.handleSubmit(handleSignup),
handleCloseNotAllowedModal: () => setShowNotAllowedModal(false),
handleProviderSignup,
+ handleStartAgain,
};
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/auth/callback/__tests__/email-verification-conversion.test.ts b/autogpt_platform/frontend/src/app/(platform)/auth/callback/__tests__/email-verification-conversion.test.ts
new file mode 100644
index 0000000000..24d62dbe04
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/auth/callback/__tests__/email-verification-conversion.test.ts
@@ -0,0 +1,112 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// The sign_up conversion across the email verification round trip: the
+// sign-up action (no session yet) must not count the account, the verify link
+// landing on /auth/callback?method=email must count it, and only once.
+
+const mocks = vi.hoisted(() => ({
+ signUpEmail: vi.fn(),
+ getServerSession: vi.fn(),
+ scheduleAccountCreatedGoal: vi.fn(),
+ cookieSet: vi.fn(),
+ provisionedUserIDs: new Set<string>(),
+}));
+
+vi.mock("@/lib/auth/auth", () => ({
+ auth: { api: { signUpEmail: mocks.signUpEmail } },
+}));
+vi.mock("@/lib/auth/server/getServerSession", () => ({
+ getServerSession: mocks.getServerSession,
+}));
+vi.mock("@/lib/auth/server/rollbackSession", () => ({
+ rollbackSession: vi.fn(),
+}));
+
+// The backend's POST /auth/user: creates the platform user on the first call
+// with a session and says so in X-AutoGPT-User-Created.
+vi.mock("@/app/api/__generated__/endpoints/auth/auth", () => ({
+ postV1GetOrCreateUser: vi.fn(async () => {
+ const session = await mocks.getServerSession();
+ if (!session)
+ throw Object.assign(new Error("Unauthorized"), { status: 401 });
+ const created = !mocks.provisionedUserIDs.has(session.user.id);
+ mocks.provisionedUserIDs.add(session.user.id);
+ return {
+ status: 200,
+ data: {},
+ headers: new Headers({ "X-AutoGPT-User-Created": String(created) }),
+ };
+ }),
+}));
+
+vi.mock("@/app/api/helpers", () => ({
+ getOnboardingStatus: vi.fn(async () => ({ shouldShowOnboarding: true })),
+}));
+vi.mock("@/services/analytics/datafast-server", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("@/services/analytics/datafast-server")
+ >()),
+ scheduleAccountCreatedGoal: mocks.scheduleAccountCreatedGoal,
+}));
+vi.mock("next/headers", () => ({
+ headers: vi.fn(async () => new Headers()),
+ cookies: vi.fn(async () => ({ set: mocks.cookieSet })),
+}));
+vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));
+vi.mock("@sentry/nextjs", () => ({ captureException: vi.fn() }));
+
+import { signup } from "@/app/(no-navbar)/signup/actions";
+import { GET } from "../route";
+
+const origin = "http://localhost:3000";
+const password = "ValidPassword123!";
+
+function clickVerificationLink(callbackURL: string) {
+ return GET(new Request(`${origin}${callbackURL}`));
+}
+
+describe("sign_up conversion across email verification", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.provisionedUserIDs.clear();
+ });
+
+ it("fires once, when the verification link signs the new user in", async () => {
+ mocks.signUpEmail.mockResolvedValue({ token: null, user: { id: "u-1" } });
+ mocks.getServerSession.mockResolvedValue(null);
+
+ const signupResult = await signup(
+ password,
+ password,
+ true,
+ );
+
+ expect(signupResult).toMatchObject({ verificationRequired: true });
+ expect(mocks.scheduleAccountCreatedGoal).not.toHaveBeenCalled();
+ expect(mocks.cookieSet).not.toHaveBeenCalled();
+
+ // Better Auth's /verify-email signs the user in, then redirects to the
+ // callbackURL the sign-up action gave it.
+ const callbackURL = mocks.signUpEmail.mock.calls[0][0].body.callbackURL;
+ mocks.getServerSession.mockResolvedValue({ user: { id: "u-1" } });
+
+ const landing = await clickVerificationLink(callbackURL);
+
+ expect(landing.headers.get("location")).toBe(`${origin}/onboarding`);
+ expect(mocks.scheduleAccountCreatedGoal).toHaveBeenCalledOnce();
+ expect(mocks.scheduleAccountCreatedGoal).toHaveBeenCalledWith("email");
+ expect(mocks.cookieSet).toHaveBeenCalledOnce();
+ expect(mocks.cookieSet).toHaveBeenCalledWith(
+ "agpt_account_created",
+ "email",
+ expect.anything(),
+ );
+
+ // A second click (or a reload of the landing) finds the user provisioned.
+ await clickVerificationLink(callbackURL);
+
+ expect(mocks.scheduleAccountCreatedGoal).toHaveBeenCalledOnce();
+ expect(mocks.cookieSet).toHaveBeenCalledOnce();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/auth/callback/__tests__/route.test.ts b/autogpt_platform/frontend/src/app/(platform)/auth/callback/__tests__/route.test.ts
index 98b17b4cde..b23ab1e832 100644
--- a/autogpt_platform/frontend/src/app/(platform)/auth/callback/__tests__/route.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/auth/callback/__tests__/route.test.ts
@@ -163,6 +163,74 @@ describe("auth callback GET — account creation tracking", () => {
});
});
+describe("auth callback GET — email verification link", () => {
+ beforeEach(() => {
+ vi.stubEnv("NODE_ENV", "development");
+ });
+
+ it("provisions and tracks a new email account once the link signs it in", async () => {
+ getServerSessionMock.mockResolvedValue({ user: { id: "user-1" } });
+ postV1GetOrCreateUserMock.mockResolvedValue(provisioningResponse(true));
+ getOnboardingStatusMock.mockResolvedValue({ shouldShowOnboarding: true });
+
+ const response = await GET(
+ makeCallbackRequest("/auth/callback?method=email"),
+ );
+
+ expect(response.headers.get("location")).toBe(`${origin}/onboarding`);
+ expect(postV1GetOrCreateUserMock).toHaveBeenCalledOnce();
+ expect(scheduleAccountCreatedGoalMock).toHaveBeenCalledOnce();
+ expect(scheduleAccountCreatedGoalMock).toHaveBeenCalledWith("email");
+ expect(cookieSetMock).toHaveBeenCalledOnce();
+ expect(cookieSetMock).toHaveBeenCalledWith(
+ "agpt_account_created",
+ "email",
+ expect.objectContaining({ maxAge: 600, path: "/" }),
+ );
+ });
+
+ it("does not track an existing account that verifies at its next sign-in", async () => {
+ getServerSessionMock.mockResolvedValue({ user: { id: "user-1" } });
+ postV1GetOrCreateUserMock.mockResolvedValue(provisioningResponse(false));
+ getOnboardingStatusMock.mockResolvedValue({ shouldShowOnboarding: false });
+
+ const response = await GET(
+ makeCallbackRequest("/auth/callback?method=email&next=/marketplace"),
+ );
+
+ expect(response.headers.get("location")).toBe(`${origin}/marketplace`);
+ expect(scheduleAccountCreatedGoalMock).not.toHaveBeenCalled();
+ expect(cookieSetMock).not.toHaveBeenCalled();
+ });
+
+ it("sends an expired or used link to log in, keeping next", async () => {
+ getServerSessionMock.mockResolvedValue(null);
+
+ const response = await GET(
+ makeCallbackRequest(
+ "/auth/callback?method=email&next=%2Fmarketplace&error=TOKEN_EXPIRED",
+ ),
+ );
+
+ expect(response.headers.get("location")).toBe(
+ `${origin}/login?email_verification=expired&next=%2Fmarketplace`,
+ );
+ expect(postV1GetOrCreateUserMock).not.toHaveBeenCalled();
+ });
+
+ it("sends a click on an already verified link to log in", async () => {
+ getServerSessionMock.mockResolvedValue(null);
+
+ const response = await GET(
+ makeCallbackRequest("/auth/callback?method=email&next=https://evil.com"),
+ );
+
+ expect(response.headers.get("location")).toBe(
+ `${origin}/login?email_verification=verified`,
+ );
+ });
+});
+
describe("auth callback GET — redirect target resolution", () => {
it("uses the canonical HTTPS origin and ignores a malicious forwarded host", async () => {
vi.stubEnv("NODE_ENV", "development");
diff --git a/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.ts b/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.ts
index 87629be919..0ec6b80499 100644
--- a/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.ts
@@ -1,8 +1,13 @@
import { postV1GetOrCreateUser } from "@/app/api/__generated__/endpoints/auth/auth";
import { getOnboardingStatus } from "@/app/api/helpers";
import { sanitizeAuthNext } from "@/lib/auth-redirect";
+import {
+ EMAIL_VERIFICATION_NOTICE_PARAM,
+ type EmailVerificationNotice,
+} from "@/lib/auth/email-verification";
import { getServerSession } from "@/lib/auth/server/getServerSession";
import { rollbackSession } from "@/lib/auth/server/rollbackSession";
+import { type SignupMethod } from "@/services/analytics/account-created-cookie";
import { markAccountCreated } from "@/services/analytics/account-created-server";
import {
scheduleAccountCreatedGoal,
@@ -16,6 +21,10 @@ import { NextResponse } from "next/server";
// cookie, then redirects here because this is the `callbackURL` we hand it in
// /api/auth/login/with-provider. So by the time we run, the session already
// exists and we only provision the backend user and decide where to send them.
+//
+// An email verification link lands here too (`?method=email`, see
+// lib/auth/email-verification.ts) after /api/auth/verify-email has signed the
+// user in, so a verified email sign-up is provisioned and counted here, once.
function getPublicOrigin(requestOrigin: string) {
const configuredURL =
process.env.BETTER_AUTH_URL || process.env.NEXT_PUBLIC_FRONTEND_BASE_URL;
@@ -31,9 +40,30 @@ function getPublicOrigin(requestOrigin: string) {
}
}
+function getSignupMethod(searchParams: URLSearchParams): SignupMethod {
+ return searchParams.get("method") === "email" ? "email" : "google";
+}
+
+// Better Auth redirects here without a session when the link is expired,
+// invalid or already used (`?error=`), and when the address was already
+// verified. Either way the user can log in: an unverified account is sent a
+// fresh link from the login form.
+function getEmailVerificationLoginPath(searchParams: URLSearchParams) {
+ const notice: EmailVerificationNotice = searchParams.get("error")
+ ? "expired"
+ : "verified";
+ const params = new URLSearchParams({
+ [EMAIL_VERIFICATION_NOTICE_PARAM]: notice,
+ });
+ const next = sanitizeAuthNext(searchParams.get("next"));
+ if (next) params.set("next", next);
+ return `/login?${params.toString()}`;
+}
+
export async function GET(request: Request) {
const { searchParams, origin: requestOrigin } = new URL(request.url);
const publicOrigin = getPublicOrigin(requestOrigin);
+ const signupMethod = getSignupMethod(searchParams);
let next = "/copilot";
@@ -43,8 +73,8 @@ export async function GET(request: Request) {
try {
const createUserResponse = await postV1GetOrCreateUser();
if (wasAccountCreated(createUserResponse)) {
- await scheduleAccountCreatedGoal("google");
- await markAccountCreated("google");
+ await scheduleAccountCreatedGoal(signupMethod);
+ await markAccountCreated(signupMethod);
}
const { shouldShowOnboarding } = await getOnboardingStatus();
@@ -111,6 +141,12 @@ export async function GET(request: Request) {
return NextResponse.redirect(`${publicOrigin}${next}`);
}
+ if (signupMethod === "email") {
+ return NextResponse.redirect(
+ `${publicOrigin}${getEmailVerificationLoginPath(searchParams)}`,
+ );
+ }
+
// return the user to an error page with instructions
return NextResponse.redirect(`${publicOrigin}/auth/auth-code-error`);
}
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 01ed36ebd4..eae1aaf2f8 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -17887,7 +17887,12 @@
"properties": {
"type": {
"type": "string",
- "enum": ["reset_password", "verify_email", "change_email"],
+ "enum": [
+ "reset_password",
+ "verify_email",
+ "change_email",
+ "set_password"
+ ],
"title": "Type"
},
"to": { "type": "string", "format": "email", "title": "To" },
diff --git a/autogpt_platform/frontend/src/components/auth/CheckYourInbox/CheckYourInbox.tsx b/autogpt_platform/frontend/src/components/auth/CheckYourInbox/CheckYourInbox.tsx
new file mode 100644
index 0000000000..d847f3d017
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/auth/CheckYourInbox/CheckYourInbox.tsx
@@ -0,0 +1,80 @@
+"use client";
+
+import { Button } from "@/components/atoms/Button/Button";
+import { Icon } from "@/components/atoms/Icon/Icon";
+import { Text } from "@/components/atoms/Text/Text";
+import { Mail01Icon } from "@hugeicons/core-free-icons";
+import {
+ CHECK_YOUR_INBOX_COPY,
+ CHECK_YOUR_INBOX_HEADING_ID,
+ type CheckYourInboxReason,
+} from "./helpers";
+import { useCheckYourInbox } from "./useCheckYourInbox";
+
+interface Props {
+ email: string;
+ reason: CheckYourInboxReason;
+ next?: string | null;
+ onBack: () => void;
+}
+
+export function CheckYourInbox({ email, reason, next, onBack }: Props) {
+ const copy = CHECK_YOUR_INBOX_COPY[reason];
+ const { cooldown, isResending, canResend, handleResend } = useCheckYourInbox({
+ email,
+ next,
+ });
+
+ return (
+ <div className="flex w-full flex-col items-center text-center">
+ <div className="mb-6 flex size-14 items-center justify-center rounded-full bg-violet-50">
+ <Icon icon={Mail01Icon} className="size-7 text-violet-600" />
+ </div>
+
+ <Text
+ id={CHECK_YOUR_INBOX_HEADING_ID}
+ tabIndex={-1}
+ variant="h3"
+ as="h1"
+ className="!text-slate-950 outline-none"
+ >
+ {copy.title}
+ </Text>
+
+ <Text variant="body" tone="secondary" unmask={false} className="mt-3">
+ We sent an email to{" "}
+ <span className="break-all font-medium text-slate-950">{email}</span>.
+ Open the link in it to {copy.action}.
+ </Text>
+
+ <Text variant="small" tone="muted" className="mt-2">
+ Can&apos;t find it? Check your spam folder.
+ </Text>
+
+ <Button
+ variant="secondary"
+ loading={isResending}
+ type="button"
+ disabled={!canResend}
+ onClick={handleResend}
+ className="mt-8 w-full"
+ >
+ {cooldown > 0 ? `Resend email in ${cooldown}s` : "Resend email"}
+ </Button>
+
+ <div className="mt-6 inline-flex items-center justify-center gap-1">
+ <Text variant="body-medium" className="!text-slate-500">
+ {copy.backPrompt}
+ </Text>
+ <Button
+ type="button"
+ variant="link"
+ className="h-auto min-w-0 p-0"
+ onClick={onBack}
+ >
+ {copy.backLabel}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/components/auth/CheckYourInbox/helpers.ts b/autogpt_platform/frontend/src/components/auth/CheckYourInbox/helpers.ts
new file mode 100644
index 0000000000..fbe13ea2d1
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/auth/CheckYourInbox/helpers.ts
@@ -0,0 +1,23 @@
+// Better Auth allows 3 verification emails per IP a minute, and one went out
+// the moment this screen appeared.
+export const RESEND_COOLDOWN_SECONDS = 60;
+
+// Focused when the screen replaces the form, so screen readers announce it.
+export const CHECK_YOUR_INBOX_HEADING_ID = "check-your-inbox-heading";
+
+export const CHECK_YOUR_INBOX_COPY = {
+ signup: {
+ title: "Check your inbox",
+ action: "continue",
+ backPrompt: "Wrong address?",
+ backLabel: "Start again",
+ },
+ login: {
+ title: "Verify your email to log in",
+ action: "log in",
+ backPrompt: "Wrong account?",
+ backLabel: "Back to log in",
+ },
+} as const;
+
+export type CheckYourInboxReason = keyof typeof CHECK_YOUR_INBOX_COPY;
diff --git a/autogpt_platform/frontend/src/components/auth/CheckYourInbox/useCheckYourInbox.ts b/autogpt_platform/frontend/src/components/auth/CheckYourInbox/useCheckYourInbox.ts
new file mode 100644
index 0000000000..4a510b7ea9
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/auth/CheckYourInbox/useCheckYourInbox.ts
@@ -0,0 +1,71 @@
+import { useToast } from "@/components/molecules/Toast/use-toast";
+import { authClient } from "@/lib/auth/client";
+import { getEmailVerificationCallbackURL } from "@/lib/auth/email-verification";
+import { useEffect, useState } from "react";
+import {
+ CHECK_YOUR_INBOX_HEADING_ID,
+ RESEND_COOLDOWN_SECONDS,
+} from "./helpers";
+
+interface Args {
+ email: string;
+ next?: string | null;
+}
+
+export function useCheckYourInbox({ email, next }: Args) {
+ const { toast } = useToast();
+ const [cooldown, setCooldown] = useState(RESEND_COOLDOWN_SECONDS);
+ const [isResending, setIsResending] = useState(false);
+
+ useEffect(() => {
+ document.getElementById(CHECK_YOUR_INBOX_HEADING_ID)?.focus();
+ }, []);
+
+ useEffect(() => {
+ if (cooldown <= 0) return;
+ const timer = setTimeout(() => setCooldown((value) => value - 1), 1000);
+ return () => clearTimeout(timer);
+ }, [cooldown]);
+
+ async function handleResend() {
+ setIsResending(true);
+ try {
+ // Through the HTTP route rather than a server action so Better Auth's
+ // per-IP rate limit applies.
+ const { error } = await authClient.sendVerificationEmail({
+ email,
+ callbackURL: getEmailVerificationCallbackURL(next),
+ });
+ if (error) {
+ showResendFailed(error.status === 429);
+ return;
+ }
+ } catch {
+ // A network failure throws instead of answering with an error.
+ showResendFailed(false);
+ return;
+ } finally {
+ setIsResending(false);
+ }
+
+ setCooldown(RESEND_COOLDOWN_SECONDS);
+ toast({ title: `Email sent to ${email}`, variant: "success" });
+ }
+
+ function showResendFailed(rateLimited: boolean) {
+ toast({
+ title: "We couldn't send the email",
+ description: rateLimited
+ ? "Too many attempts. Please try again in a few minutes."
+ : "Please try again in a moment.",
+ variant: "destructive",
+ });
+ }
+
+ return {
+ cooldown,
+ isResending,
+ canResend: cooldown <= 0 && !isResending,
+ handleResend,
+ };
+}
diff --git a/autogpt_platform/frontend/src/lib/auth/__tests__/auth-config.test.ts b/autogpt_platform/frontend/src/lib/auth/__tests__/auth-config.test.ts
index 9de91578f1..6da6ba8c77 100644
--- a/autogpt_platform/frontend/src/lib/auth/__tests__/auth-config.test.ts
+++ b/autogpt_platform/frontend/src/lib/auth/__tests__/auth-config.test.ts
@@ -18,6 +18,11 @@ const sendAuthEmailMock = vi.fn();
vi.mock("../email", () => ({
sendAuthEmail: (...args: unknown[]) => sendAuthEmailMock(...args),
}));
+const provisionPlatformUserMock = vi.fn();
+vi.mock("../provision-platform-user", () => ({
+ provisionPlatformUser: (...args: unknown[]) =>
+ provisionPlatformUserMock(...args),
+}));
interface JwtPluginOptions {
jwt: {
@@ -39,6 +44,18 @@ interface AuthEmailArgs {
}
interface CapturedAuthOptions {
+ databaseHooks: {
+ user: {
+ create: {
+ after: (user: {
+ id: string;
+ email: string;
+ name: string;
+ emailVerified?: boolean;
+ }) => Promise<void>;
+ };
+ };
+ };
emailAndPassword: {
minPasswordLength: number;
revokeSessionsOnPasswordReset: boolean;
@@ -90,6 +107,7 @@ const PROVIDER_ENV_KEYS = [
beforeEach(() => {
sendAuthEmailMock.mockReset();
+ provisionPlatformUserMock.mockReset();
for (const key of PROVIDER_ENV_KEYS) {
vi.stubEnv(key, "");
}
@@ -242,6 +260,91 @@ describe("auth config", () => {
});
});
+describe("email verification", () => {
+ it("is off unless AUTH_REQUIRE_EMAIL_VERIFICATION is exactly true", async () => {
+ vi.stubEnv("AUTH_REQUIRE_EMAIL_VERIFICATION", "");
+ const off = (await loadAuthOptions()) as unknown as {
+ emailAndPassword: { requireEmailVerification: boolean };
+ };
+ vi.stubEnv("AUTH_REQUIRE_EMAIL_VERIFICATION", "true");
+ const on = (await loadAuthOptions()) as unknown as {
+ emailAndPassword: { requireEmailVerification: boolean };
+ };
+
+ expect(off.emailAndPassword.requireEmailVerification).toBe(false);
+ expect(on.emailAndPassword.requireEmailVerification).toBe(true);
+ });
+
+ it("re-sends the link to an unverified sign-in and signs the user in from it", async () => {
+ vi.stubEnv("AUTH_REQUIRE_EMAIL_VERIFICATION", "true");
+ const options = (await loadAuthOptions()) as unknown as {
+ emailVerification: Record<string, unknown>;
+ };
+
+ // Without sendOnSignIn, accounts created before the flag was flipped
+ // would hit a 403 with no way to get a link.
+ expect(options.emailVerification.sendOnSignIn).toBe(true);
+ expect(options.emailVerification.autoSignInAfterVerification).toBe(true);
+ expect(options.emailVerification.expiresIn).toBe(60 * 60 * 24);
+ // Sign-up sends the link only when verification is required (Better
+ // Auth's default), so leaving the flag off changes nothing.
+ expect(options.emailVerification.sendOnSignUp).toBeUndefined();
+ });
+
+ it("does not sign in from a verify link with the flag off", async () => {
+ vi.stubEnv("AUTH_REQUIRE_EMAIL_VERIFICATION", "false");
+ const options = (await loadAuthOptions()) as unknown as {
+ emailVerification: Record<string, unknown>;
+ };
+
+ expect(options.emailVerification.autoSignInAfterVerification).toBe(false);
+ });
+});
+
+describe("team email sign-up", () => {
+ type CreateUserHook = (
+ user: { email: string },
+ ctx: { path?: string } | null,
+ ) => Promise<void>;
+
+ async function loadCreateUserHook() {
+ const options = (await loadAuthOptions()) as unknown as {
+ databaseHooks: { user: { create: { before: CreateUserHook } } };
+ };
+ return options.databaseHooks.user.create.before;
+ }
+
+ it("refuses a password sign-up as an @agpt.co address", async () => {
+ const createUser = await loadCreateUserHook();
+
+ await expect(
+ createUser({ email: "[email protected]" }, { path: "/sign-up/email" }),
+ ).rejects.toMatchObject({
+ statusCode: 403,
+ body: { code: "TEAM_EMAIL_REQUIRES_GOOGLE" },
+ });
+ });
+
+ it("lets Google create an @agpt.co account", async () => {
+ const createUser = await loadCreateUserHook();
+
+ await expect(
+ createUser({ email: "[email protected]" }, { path: "/callback/google" }),
+ ).resolves.toBeUndefined();
+ });
+
+ it("leaves other password sign-ups to the signup gate", async () => {
+ const createUser = await loadCreateUserHook();
+
+ await expect(
+ createUser({ email: "[email protected]" }, { path: "/sign-up/email" }),
+ ).resolves.toBeUndefined();
+ await expect(
+ createUser({ email: "[email protected]" }, { path: "/sign-up/email" }),
+ ).resolves.toBeUndefined();
+ });
+});
+
describe("change email", () => {
it("enables email change and routes the approval mail to the current address", async () => {
const options = await loadAuthOptions();
@@ -307,4 +410,61 @@ describe("auth table names", () => {
const jwtPlugin = options.plugins.find((plugin) => plugin.id === "jwt");
expect(jwtPlugin?.opts?.schema?.jwks?.modelName).toBe("UserAuthJwks");
});
+
+ it("provisions the platform User row from the user.create.after hook", async () => {
+ const options = await loadAuthOptions();
+ const user = { id: "user-1", email: "[email protected]", name: "new" };
+
+ await options.databaseHooks.user.create.after(user);
+
+ expect(provisionPlatformUserMock).toHaveBeenCalledTimes(1);
+ const [pool, provisionedUser] = provisionPlatformUserMock.mock.calls[0];
+ // Reuses the shared auth pool rather than opening a second connection.
+ expect(pool).toBeDefined();
+ expect(provisionedUser).toEqual(user);
+ });
+
+ it("defers an unverified password sign-up's User row to the verification link when verification is required", async () => {
+ vi.stubEnv("AUTH_REQUIRE_EMAIL_VERIFICATION", "true");
+ const options = await loadAuthOptions();
+
+ await options.databaseHooks.user.create.after({
+ id: "user-1",
+ email: "[email protected]",
+ name: "new",
+ emailVerified: false,
+ });
+
+ expect(provisionPlatformUserMock).not.toHaveBeenCalled();
+ });
+
+ it("still provisions a Google identity at creation when verification is required", async () => {
+ vi.stubEnv("AUTH_REQUIRE_EMAIL_VERIFICATION", "true");
+ const options = await loadAuthOptions();
+ const user = {
+ id: "user-1",
+ email: "[email protected]",
+ name: "new",
+ emailVerified: true,
+ };
+
+ await options.databaseHooks.user.create.after(user);
+
+ expect(provisionPlatformUserMock).toHaveBeenCalledTimes(1);
+ expect(provisionPlatformUserMock.mock.calls[0][1]).toEqual(user);
+ });
+
+ it("provisions an unverified password sign-up at creation when verification is off", async () => {
+ vi.stubEnv("AUTH_REQUIRE_EMAIL_VERIFICATION", "false");
+ const options = await loadAuthOptions();
+
+ await options.databaseHooks.user.create.after({
+ id: "user-1",
+ email: "[email protected]",
+ name: "new",
+ emailVerified: false,
+ });
+
+ expect(provisionPlatformUserMock).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/autogpt_platform/frontend/src/lib/auth/__tests__/auth-email-cooldown.test.ts b/autogpt_platform/frontend/src/lib/auth/__tests__/auth-email-cooldown.test.ts
new file mode 100644
index 0000000000..f0d0f0f8b1
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/auth/__tests__/auth-email-cooldown.test.ts
@@ -0,0 +1,194 @@
+import { describe, expect, it, vi } from "vitest";
+import {
+ AUTH_EMAILS_PER_IP,
+ type AuthEmailContext,
+ claimEmailSlot,
+ claimIPEmailSlot,
+} from "../auth-email-cooldown";
+import { sendAuthEmail } from "../email";
+import { capAuthEmailsPerIP } from "../ip-email-cap";
+import { sendVerificationLink } from "../verification-link";
+
+vi.mock("../email", () => ({ sendAuthEmail: vi.fn() }));
+
+interface Row {
+ id: string;
+ identifier: string;
+ expiresAt: Date;
+}
+
+// The verification table as Postgres keeps it: the id is the primary key. Every
+// check for a live row waits until all of the burst has made one, which is the
+// worst interleaving of sends that arrive together.
+function verificationTable(burst: number) {
+ const rows: Row[] = [];
+ let checked = 0;
+ let releaseChecks = () => {};
+ const allChecked = new Promise<void>((resolve) => {
+ releaseChecks = resolve;
+ });
+ let n = 0;
+ const context: AuthEmailContext = {
+ baseURL: "http://localhost:3000/api/auth",
+ password: { hash: async (password) => password },
+ adapter: {
+ findMany: async ({ where }) => {
+ const [match] = where;
+ const found = rows.filter((row) =>
+ match.field === "id"
+ ? row.id === match.value
+ : row.identifier === match.value && row.expiresAt > new Date(),
+ );
+ if (++checked === burst) releaseChecks();
+ if (checked <= burst) await allChecked;
+ return found;
+ },
+ create: async ({ data, forceAllowId }) => {
+ const id = forceAllowId ? String(data.id) : `random-${++n}`;
+ if (rows.some((row) => row.id === id)) {
+ throw new Error(`duplicate key value violates unique constraint`);
+ }
+ rows.push({
+ id,
+ identifier: String(data.identifier),
+ expiresAt: data.expiresAt as Date,
+ });
+ return data;
+ },
+ updateMany: async () => 0,
+ deleteMany: async () => 0,
+ },
+ };
+ return { context, rows };
+}
+
+describe("claimEmailSlot", () => {
+ it("lets one of a burst of simultaneous sends to an address through", async () => {
+ const { context } = verificationTable(10);
+
+ const claims = await Promise.all(
+ Array.from({ length: 10 }, () =>
+ claimEmailSlot(context, "verify-email", "[email protected]"),
+ ),
+ );
+
+ expect(claims.filter(Boolean)).toHaveLength(1);
+ });
+
+ it("keeps separate slots per address and per kind of email", async () => {
+ const { context } = verificationTable(0);
+
+ expect(await claimEmailSlot(context, "verify-email", "[email protected]")).toBe(
+ true,
+ );
+ expect(await claimEmailSlot(context, "verify-email", "[email protected]")).toBe(
+ false,
+ );
+ expect(await claimEmailSlot(context, "verify-email", "[email protected]")).toBe(
+ true,
+ );
+ expect(
+ await claimEmailSlot(context, "repeat-sign-up", "[email protected]"),
+ ).toBe(true);
+ });
+
+ it("passes on a failure that is not a lost race", async () => {
+ const { context } = verificationTable(0);
+ context.adapter.create = async () => {
+ throw new Error("database is down");
+ };
+
+ await expect(
+ claimEmailSlot(context, "verify-email", "[email protected]"),
+ ).rejects.toThrow("database is down");
+ });
+});
+
+describe("claimIPEmailSlot", () => {
+ it("lets a burst from one IP take only its share of slots", async () => {
+ const { context } = verificationTable(0);
+
+ const claims = await Promise.all(
+ Array.from({ length: 20 }, () =>
+ claimIPEmailSlot(context, "203.0.113.7"),
+ ),
+ );
+
+ expect(claims.filter(Boolean)).toHaveLength(AUTH_EMAILS_PER_IP);
+ expect(await claimIPEmailSlot(context, "198.51.100.9")).toBe(true);
+ });
+
+ it.each([
+ ["at the start of a window", 0],
+ ["midway", 300_000],
+ ["just before it ends", 599_999],
+ ])(
+ "keeps a slot until its window ends, claimed %s",
+ async (_, intoWindow) => {
+ const windowStart = Date.UTC(2026, 9, 6, 17, 10);
+ const windowEnd = windowStart + 10 * 60 * 1000;
+ vi.useFakeTimers({ now: windowStart + intoWindow });
+ try {
+ const { context, rows } = verificationTable(0);
+
+ await claimIPEmailSlot(context, "203.0.113.7");
+
+ const expiresAt = rows[0].expiresAt.getTime();
+ expect(expiresAt).toBeGreaterThan(Date.now());
+ expect(Math.abs(expiresAt - windowEnd)).toBeLessThan(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ },
+ );
+
+ it("passes on a failure that is not a taken slot", async () => {
+ const { context } = verificationTable(0);
+ context.adapter.create = async () => {
+ throw new Error("database is down");
+ };
+
+ await expect(claimIPEmailSlot(context, "203.0.113.7")).rejects.toThrow(
+ "database is down",
+ );
+ });
+});
+
+describe("when a cap can't be checked", () => {
+ function brokenContext() {
+ const { context } = verificationTable(0);
+ const down = async () => {
+ throw new Error("database is down");
+ };
+ context.adapter.findMany = down;
+ context.adapter.create = down;
+ return context;
+ }
+
+ it("still sends the verification email", async () => {
+ vi.mocked(sendAuthEmail).mockClear();
+
+ await sendVerificationLink({
+ user: { id: "user-1", email: "[email protected]" },
+ url: "http://localhost:3000/api/auth/verify-email?token=t",
+ getAuthContext: async () => brokenContext(),
+ hasPlatformUser: async () => false,
+ requireEmailVerification: true,
+ resetRedirectTo: "http://localhost:3000/reset-password",
+ });
+
+ expect(sendAuthEmail).toHaveBeenCalledWith(
+ expect.objectContaining({ to: "[email protected]", type: "verify_email" }),
+ );
+ });
+
+ it("lets the sign-up through", async () => {
+ await expect(
+ capAuthEmailsPerIP({
+ path: "/sign-up/email",
+ headers: new Headers({ "x-forwarded-for": "203.0.113.7" }),
+ context: { ...brokenContext(), options: {} },
+ }),
+ ).resolves.toBeUndefined();
+ });
+});
diff --git a/autogpt_platform/frontend/src/lib/auth/__tests__/background-tasks.test.ts b/autogpt_platform/frontend/src/lib/auth/__tests__/background-tasks.test.ts
new file mode 100644
index 0000000000..f1a421d621
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/auth/__tests__/background-tasks.test.ts
@@ -0,0 +1,57 @@
+import { after } from "next/server";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { runAfterResponse } from "../background-tasks";
+
+vi.mock("next/server", () => ({ after: vi.fn() }));
+
+afterEach(() => {
+ vi.mocked(after).mockReset();
+ vi.restoreAllMocks();
+});
+
+describe("runAfterResponse", () => {
+ it("hands the task to after without waiting for it", async () => {
+ let finish = () => {};
+ const task = new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+
+ runAfterResponse(task);
+
+ expect(after).toHaveBeenCalledOnce();
+ const kept = vi.mocked(after).mock.calls[0][0] as Promise<unknown>;
+ finish();
+ await expect(kept).resolves.toBeUndefined();
+ });
+
+ it("logs a failed task instead of letting it reject", async () => {
+ const consoleError = vi
+ .spyOn(console, "error")
+ .mockImplementation(() => {});
+
+ runAfterResponse(Promise.reject(new Error("mailer down")));
+
+ const kept = vi.mocked(after).mock.calls[0][0] as Promise<unknown>;
+ await expect(kept).resolves.toBeUndefined();
+ expect(consoleError).toHaveBeenCalledWith("Auth background task failed", {
+ error: "mailer down",
+ });
+ });
+
+ it("lets the task run on its own outside a request scope", async () => {
+ vi.mocked(after).mockImplementation(() => {
+ throw new Error("`after` was called outside a request scope");
+ });
+ let ran = false;
+
+ expect(() =>
+ runAfterResponse(
+ Promise.resolve().then(() => {
+ ran = true;
+ }),
+ ),
+ ).not.toThrow();
+
+ await vi.waitFor(() => expect(ran).toBe(true));
+ });
+});
diff --git a/autogpt_platform/frontend/src/lib/auth/__tests__/email-verification-flow.test.ts b/autogpt_platform/frontend/src/lib/auth/__tests__/email-verification-flow.test.ts
new file mode 100644
index 0000000000..2afb52bddf
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/auth/__tests__/email-verification-flow.test.ts
@@ -0,0 +1,1275 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { AUTH_EMAILS_PER_IP } from "../auth-email-cooldown";
+
+// Runs the real Better Auth handler with this app's auth options (from
+// ../auth) on an in-memory database, so the HTTP behaviour of sign-up, sign-in
+// and the verify link is checked end to end rather than assumed.
+
+vi.mock("pg", () => ({ Pool: vi.fn() }));
+// ../auth builds the real Better Auth instance, on the in-memory database of
+// the test that imported it, so the hooks that reach back into it work too.
+const testDB = vi.hoisted(() => ({ current: {} as Record<string, unknown[]> }));
+vi.mock("better-auth", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("better-auth")>();
+ const { memoryAdapter } = await import("better-auth/adapters/memory");
+ return {
+ ...actual,
+ betterAuth: (options: Parameters<typeof actual.betterAuth>[0]) =>
+ actual.betterAuth({
+ ...options,
+ database: memoryAdapter(testDB.current),
+ plugins: [],
+ }),
+ };
+});
+// Better Auth hands each email it sends to `after` (see background-tasks.ts);
+// these are the sends still pending once a response is back.
+const pendingAfterResponse = vi.hoisted(() => [] as Promise<unknown>[]);
+vi.mock("next/server", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("next/server")>()),
+ after: vi.fn((task: Promise<unknown>) => {
+ pendingAfterResponse.push(task);
+ }),
+}));
+vi.mock("better-auth/next-js", () => ({
+ nextCookies: vi.fn(() => ({ id: "next-cookies" })),
+}));
+vi.mock("better-auth/plugins", () => ({
+ admin: vi.fn(() => ({ id: "admin" })),
+ jwt: vi.fn(() => ({ id: "jwt" })),
+}));
+vi.mock("../supabase-bridge", () => ({
+ supabaseBridge: vi.fn(() => ({ id: "supabase-bridge" })),
+}));
+vi.mock("../email-mirror", () => ({
+ mirrorVerifiedEmailToPlatformUser: vi.fn(),
+}));
+
+// The platform `User` rows the auth hook has written, as the real
+// provisionPlatformUser and platformUserExists would see them.
+const platformUsers = vi.hoisted(() => new Set<string>());
+const userLookupFails = vi.hoisted(() => ({ current: false }));
+const provisionPlatformUser = vi.hoisted(() =>
+ vi.fn(async (_pool: unknown, user: { id: string }) => {
+ platformUsers.add(user.id);
+ return "created";
+ }),
+);
+vi.mock("../provision-platform-user", () => ({
+ provisionPlatformUser,
+ platformUserExists: async (_pool: unknown, userId: string) => {
+ if (userLookupFails.current) throw new Error("database is down");
+ return platformUsers.has(userId);
+ },
+}));
+
+const sentEmails = vi.hoisted(
+ () => [] as Array<{ to: string; type: string; url: string }>,
+);
+vi.mock("../email", () => ({
+ sendAuthEmail: vi.fn(async (email: (typeof sentEmails)[number]) => {
+ sentEmails.push(email);
+ }),
+}));
+
+const baseURL = "http://localhost:3000";
+const password = "a-long-enough-password";
+const callbackURL = "/auth/callback?method=email";
+
+type Handler = (request: Request) => Promise<Response>;
+
+function emptyDB() {
+ return {
+ UserAuthIdentity: [] as Array<Record<string, unknown>>,
+ UserAuthSession: [] as Array<Record<string, unknown>>,
+ UserAuthAccount: [] as Array<Record<string, unknown>>,
+ UserAuthVerification: [] as Array<Record<string, unknown>>,
+ };
+}
+
+// Pass the db of an earlier handler to flip the flag on the same accounts.
+async function createAuthHandler(requireVerification: boolean, db = emptyDB()) {
+ vi.stubEnv(
+ "AUTH_REQUIRE_EMAIL_VERIFICATION",
+ requireVerification ? "true" : "false",
+ );
+ vi.stubEnv("BETTER_AUTH_URL", baseURL);
+ vi.stubEnv("BETTER_AUTH_SECRET", "test-secret-that-is-at-least-32-chars");
+ vi.doUnmock("../auth");
+ vi.resetModules();
+
+ testDB.current = db;
+ const { auth } = await import("../auth");
+ return { handler: auth.handler as Handler, api: auth.api, db };
+}
+
+type TestDB = Awaited<ReturnType<typeof createAuthHandler>>["db"];
+
+// Lets the per-address email cooldowns lapse, as ten minutes would.
+function expireCooldowns(db: TestDB) {
+ for (const row of db.UserAuthVerification) {
+ if (/^(repeat-sign-up|verify-email):/.test(String(row.identifier))) {
+ row.expiresAt = new Date(Date.now() - 1000);
+ }
+ }
+}
+
+// A send can queue another (the repeat sign-up's reset email), so drain until
+// nothing is left.
+async function emailsSent() {
+ while (pendingAfterResponse.length) {
+ await Promise.all(pendingAfterResponse.splice(0));
+ }
+}
+
+function never() {
+ return new Promise<void>(() => {});
+}
+
+async function answeredWithin<T>(response: Promise<T>, ms = 2000) {
+ const timedOut = Symbol("timed out");
+ const result = await Promise.race([
+ response,
+ new Promise<typeof timedOut>((resolve) =>
+ setTimeout(() => resolve(timedOut), ms),
+ ),
+ ]);
+ if (result === timedOut) throw new Error(`No response within ${ms}ms`);
+ return result as T;
+}
+
+function post(handler: Handler, path: string, body: object) {
+ return handler(
+ new Request(`${baseURL}/api/auth${path}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json", Origin: baseURL },
+ body: JSON.stringify(body),
+ }),
+ );
+}
+
+function signUp(handler: Handler, email: string) {
+ return post(handler, "/sign-up/email", {
+ email,
+ password,
+ name: email.split("@")[0],
+ callbackURL,
+ });
+}
+
+function signIn(handler: Handler, email: string, as = password) {
+ return post(handler, "/sign-in/email", {
+ email,
+ password: as,
+ callbackURL,
+ });
+}
+
+function signUpAs(handler: Handler, email: string, as: string) {
+ return post(handler, "/sign-up/email", {
+ email,
+ password: as,
+ name: email.split("@")[0],
+ callbackURL,
+ });
+}
+
+type API = Awaited<ReturnType<typeof createAuthHandler>>["api"];
+
+// A real sign-out, which deletes the session row.
+async function signUpAndSignOut(api: API, email: string, as: string) {
+ const { headers } = await api.signUpEmail({
+ body: { email, password: as, name: email.split("@")[0], callbackURL },
+ returnHeaders: true,
+ });
+ const cookie = headers.get("set-cookie")?.split(";")[0] ?? "";
+ await api.signOut({ headers: new Headers({ cookie }) });
+}
+
+function fromIP(ip: string) {
+ return new Headers({ "x-forwarded-for": ip });
+}
+
+function lastResetToken(to: string, type = "set_password") {
+ const email = sentEmails.filter(
+ (sent) => sent.to === to && sent.type === type,
+ );
+ const url = email.at(-1)?.url;
+ return url ? new URL(url).pathname.split("/").at(-1) : undefined;
+}
+
+function lastVerifyLink(to: string) {
+ const email = sentEmails.filter(
+ (sent) => sent.to === to && sent.type === "verify_email",
+ );
+ return email.at(-1)?.url;
+}
+
+beforeEach(() => {
+ sentEmails.length = 0;
+ pendingAfterResponse.length = 0;
+ provisionPlatformUser.mockClear();
+ platformUsers.clear();
+ userLookupFails.current = false;
+});
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
+
+describe("with AUTH_REQUIRE_EMAIL_VERIFICATION=true", () => {
+ it("signs up with no session and emails a link back to /auth/callback", async () => {
+ const { handler, db } = await createAuthHandler(true);
+
+ const response = await signUp(handler, "[email protected]");
+
+ expect(response.status).toBe(200);
+ expect((await response.json()).token).toBeNull();
+ expect(db.UserAuthSession).toEqual([]);
+ await emailsSent();
+ const link = new URL(lastVerifyLink("[email protected]") ?? "");
+ expect(link.pathname).toBe("/api/auth/verify-email");
+ expect(link.searchParams.get("callbackURL")).toBe(callbackURL);
+ });
+
+ it("re-sends the link when an unverified user signs in, instead of a dead end", async () => {
+ const { handler, db } = await createAuthHandler(true);
+ await signUp(handler, "[email protected]");
+ await emailsSent();
+ sentEmails.length = 0;
+ // The sign-up's own email holds the address's cooldown for a while.
+ expireCooldowns(db);
+
+ const response = await signIn(handler, "[email protected]");
+
+ expect(response.status).toBe(403);
+ expect((await response.json()).code).toBe("EMAIL_NOT_VERIFIED");
+ await emailsSent();
+ expect(lastVerifyLink("[email protected]")).toContain(
+ "/api/auth/verify-email",
+ );
+ });
+
+ it("does not send a link for a wrong password", async () => {
+ const { handler } = await createAuthHandler(true);
+ await signUp(handler, "[email protected]");
+ sentEmails.length = 0;
+
+ const response = await post(handler, "/sign-in/email", {
+ email: "[email protected]",
+ password: "not-the-password",
+ });
+
+ expect(response.status).toBe(401);
+ await emailsSent();
+ expect(sentEmails).toEqual([]);
+ });
+
+ it("verify link signs the user in and lands on /auth/callback", async () => {
+ const { handler, db } = await createAuthHandler(true);
+ await signUp(handler, "[email protected]");
+ await emailsSent();
+
+ const response = await handler(
+ new Request(lastVerifyLink("[email protected]") ?? ""),
+ );
+
+ expect(response.status).toBe(302);
+ expect(response.headers.get("location")).toBe(callbackURL);
+ // happy-dom strips Set-Cookie from responses, so check the session row.
+ expect(db.UserAuthSession).toHaveLength(1);
+ expect(db.UserAuthIdentity).toEqual([
+ expect.objectContaining({
+ email: "[email protected]",
+ emailVerified: true,
+ }),
+ ]);
+ // ...and a normal sign-in works from then on.
+ expect((await signIn(handler, "[email protected]")).status).toBe(200);
+ });
+
+ it("creates no platform User row until the link is opened", async () => {
+ const { handler } = await createAuthHandler(true);
+
+ await signUp(handler, "[email protected]");
+ await emailsSent();
+ await handler(new Request(lastVerifyLink("[email protected]") ?? ""));
+
+ // Neither the sign-up nor the verify link provisions: /auth/callback
+ // does, through POST /auth/user, which also answers "created" for the
+ // sign-up conversion.
+ expect(provisionPlatformUser).not.toHaveBeenCalled();
+ });
+
+ it("sends an expired or tampered link back to the callback with an error", async () => {
+ const { handler } = await createAuthHandler(true);
+
+ const response = await handler(
+ new Request(
+ `${baseURL}/api/auth/verify-email?token=not-a-token&callbackURL=${encodeURIComponent(callbackURL)}`,
+ ),
+ );
+
+ expect(response.status).toBe(302);
+ expect(response.headers.get("location")).toBe(
+ `${callbackURL}&error=INVALID_TOKEN`,
+ );
+ });
+
+ it("emails a set-password link, not a verify link, when an unverified address signs up again", async () => {
+ const { handler, db } = await createAuthHandler(true);
+ await signUp(handler, "[email protected]");
+ await emailsSent();
+ sentEmails.length = 0;
+
+ // Better Auth answers a repeat sign-up like a new one, and the page then
+ // says to check the inbox, so something has to arrive.
+ const response = await signUp(handler, "[email protected]");
+
+ expect(response.status).toBe(200);
+ expect((await response.json()).token).toBeNull();
+ expect(db.UserAuthIdentity).toHaveLength(1);
+ await emailsSent();
+ expect(sentEmails.map((sent) => sent.type)).toEqual(["set_password"]);
+ expect(lastResetToken("[email protected]")).toEqual(expect.any(String));
+ });
+
+ it("leaves whoever signed up first no password once the owner verifies", async () => {
+ // Someone signs up with an address they do not own...
+ const { handler, db } = await createAuthHandler(true);
+ await signUpAs(
+ handler,
+ "the-first-sign-ups-password",
+ );
+ await emailsSent();
+ const firstLink = lastVerifyLink("[email protected]") ?? "";
+ // ...then the owner signs up too, with their own password.
+ await signUpAs(handler, "[email protected]", "the-owners-own-password");
+ await emailsSent();
+
+ // Even if the owner opens the first sign-up's link, which signs them in,
+ // the first password must no longer work.
+ await handler(new Request(firstLink));
+ expect(db.UserAuthIdentity).toEqual([
+ expect.objectContaining({ emailVerified: true }),
+ ]);
+ const response = await signIn(
+ handler,
+ "the-first-sign-ups-password",
+ );
+ expect(response.status).toBe(401);
+ });
+
+ it("lets the owner set a password through the reset link, which verifies the address", async () => {
+ const { handler, db } = await createAuthHandler(true);
+ await signUpAs(handler, "[email protected]", "the-first-sign-ups-password");
+ await signUp(handler, "[email protected]");
+ await emailsSent();
+
+ const reset = await post(handler, "/reset-password", {
+ token: lastResetToken("[email protected]"),
+ newPassword: "the-owners-new-password",
+ });
+
+ expect(reset.status).toBe(200);
+ expect(db.UserAuthIdentity).toEqual([
+ expect.objectContaining({ emailVerified: true }),
+ ]);
+ const asOwner = await signIn(
+ handler,
+ "the-owners-new-password",
+ );
+ expect(asOwner.status).toBe(200);
+ const asFirst = await signIn(
+ handler,
+ "the-first-sign-ups-password",
+ );
+ expect(asFirst.status).toBe(401);
+ });
+
+ it("still resets the password when marking the address verified fails", async () => {
+ const { handler, db } = await createAuthHandler(true);
+ await signUp(handler, "[email protected]");
+ await post(handler, "/request-password-reset", {
+ email: "[email protected]",
+ redirectTo: `${baseURL}/reset-password`,
+ });
+ await emailsSent();
+ const { auth } = await import("../auth");
+ const { internalAdapter } = await auth.$context;
+ const updateUser = vi
+ .spyOn(internalAdapter, "updateUser")
+ .mockRejectedValueOnce(new Error("database is down"));
+ const consoleError = vi
+ .spyOn(console, "error")
+ .mockImplementation(() => {});
+
+ const reset = await post(handler, "/reset-password", {
+ token: lastResetToken("[email protected]", "reset_password"),
+ newPassword: "a-new-long-enough-password",
+ });
+
+ expect(updateUser).toHaveBeenCalled();
+ expect(reset.status).toBe(200);
+ expect(JSON.stringify(consoleError.mock.calls)).not.toContain(
+ );
+ expect(db.UserAuthIdentity).toEqual([
+ expect.objectContaining({ emailVerified: false }),
+ ]);
+ // The address stays unverified, so signing in with the new password
+ // sends a fresh verify link rather than a dead end.
+ sentEmails.length = 0;
+ expireCooldowns(db);
+ const signedIn = await signIn(
+ handler,
+ "a-new-long-enough-password",
+ );
+ expect(signedIn.status).toBe(403);
+ expect((await signedIn.json()).code).toBe("EMAIL_NOT_VERIFIED");
+ await emailsSent();
+ expect(lastVerifyLink("[email protected]")).toContain(
+ "/api/auth/verify-email",
+ );
+ consoleError.mockRestore();
+ });
+
+ it("emails a repeatedly signed-up address once per cooldown", async () => {
+ const { handler, db } = await createAuthHandler(true);
+ await signUp(handler, "[email protected]");
+ await emailsSent();
+ sentEmails.length = 0;
+
+ for (let i = 0; i < 3; i++) {
+ const response = await signUp(handler, "[email protected]");
+ expect(response.status).toBe(200);
+ await emailsSent();
+ }
+ expect(sentEmails.map((sent) => sent.type)).toEqual(["set_password"]);
+
+ // Once the window has passed, the next repeat sign-up emails again.
+ expireCooldowns(db);
+ await signUp(handler, "[email protected]");
+ await emailsSent();
+ expect(sentEmails.map((sent) => sent.type)).toEqual([
+ "set_password",
+ "set_password",
+ ]);
+ });
+
+ it("answers a repeat sign-up like a new one even when its email fails", async () => {
+ const { handler, db } = await createAuthHandler(true);
+ await signUp(handler, "[email protected]");
+ await emailsSent();
+ const { sendAuthEmail } = await import("../email");
+ vi.mocked(sendAuthEmail).mockRejectedValueOnce(new Error("mailer down"));
+
+ const response = await signUp(handler, "[email protected]");
+ await emailsSent();
+
+ expect(response.status).toBe(200);
+ expect((await response.json()).token).toBeNull();
+ expect(db.UserAuthIdentity).toHaveLength(1);
+ expect(sendAuthEmail).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ type: "set_password",
+ }),
+ );
+ });
+
+ it("sends nothing when a verified address signs up again", async () => {
+ const { handler } = await createAuthHandler(true);
+ await signUp(handler, "[email protected]");
+ await emailsSent();
+ await handler(new Request(lastVerifyLink("[email protected]") ?? ""));
+ sentEmails.length = 0;
+
+ const response = await signUp(handler, "[email protected]");
+
+ expect(response.status).toBe(200);
+ expect((await response.json()).token).toBeNull();
+ await emailsSent();
+ expect(sentEmails).toEqual([]);
+ });
+
+ it.each([
+ ["a new address", false],
+ ["an address still waiting on its link", true],
+ ])(
+ "answers a sign-up for %s without waiting on the email",
+ async (_, alreadySignedUp) => {
+ const { handler } = await createAuthHandler(true);
+ if (alreadySignedUp) {
+ await signUp(handler, "[email protected]");
+ await emailsSent();
+ }
+ const { sendAuthEmail } = await import("../email");
+ vi.mocked(sendAuthEmail).mockImplementationOnce(never);
+ const callsBefore = vi.mocked(sendAuthEmail).mock.calls.length;
+
+ // A mail call that never finishes must not hold the response, or its
+ // timing tells an unverified address from a verified one.
+ const response = await answeredWithin(
+ signUp(handler, "[email protected]"),
+ );
+
+ expect(response.status).toBe(200);
+ expect((await response.json()).token).toBeNull();
+ await vi.waitFor(() =>
+ expect(vi.mocked(sendAuthEmail).mock.calls.length).toBeGreaterThan(
+ callsBefore,
+ ),
+ );
+ expect(pendingAfterResponse).not.toHaveLength(0);
+ },
+ );
+
+ it("keeps the password of an account that has signed in before", async () => {
+ // An unverified account from before the flag was turned on: its owner set
+ // the password and has used it, so a stranger signing up with the address
+ // must not lock them out.
+ const { handler, db } = await createAuthHandler(true);
+ await signUpAs(handler, "[email protected]", "the-owners-own-password");
+ await emailsSent();
+ const [identity] = db.UserAuthIdentity;
+ db.UserAuthSession.push({
+ id: "legacy-session",
+ userId: identity.id,
+ token: "legacy-session-token",
+ expiresAt: new Date(Date.now() + 60_000),
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ });
+ sentEmails.length = 0;
+
+ await signUpAs(handler, "[email protected]", "a-strangers-password");
+ await emailsSent();
+
+ expect(sentEmails.map((sent) => sent.type)).toEqual(["set_password"]);
+ expireCooldowns(db);
+ const asOwner = await signIn(
+ handler,
+ "the-owners-own-password",
+ );
+ expect(asOwner.status).toBe(403);
+ expect((await asOwner.json()).code).toBe("EMAIL_NOT_VERIFIED");
+ });
+
+ it("keeps the password of an owner from before the flag who has signed out", async () => {
+ const before = await createAuthHandler(false);
+ await signUpAndSignOut(
+ before.api,
+ "the-owners-own-password",
+ );
+ expect(before.db.UserAuthSession).toHaveLength(0);
+ const { handler, db } = await createAuthHandler(true, before.db);
+
+ await signUpAs(handler, "[email protected]", "a-strangers-password");
+ await emailsSent();
+
+ expireCooldowns(db);
+ const asOwner = await signIn(
+ handler,
+ "the-owners-own-password",
+ );
+ expect(asOwner.status).toBe(403);
+ });
+
+ it("answers a used account's resend with a set-password link, not one that signs in", async () => {
+ // Someone registers the owner's address while the flag is off, and so
+ // gets a session; then the flag goes on and the owner signs up too.
+ const before = await createAuthHandler(false);
+ await signUpAs(
+ before.handler,
+ "the-first-sign-ups-password",
+ );
+ const { handler } = await createAuthHandler(true, before.db);
+ await signUpAs(handler, "[email protected]", "the-owners-own-password");
+ await emailsSent();
+ sentEmails.length = 0;
+
+ const resend = await post(handler, "/send-verification-email", {
+ email: "[email protected]",
+ callbackURL,
+ });
+ await emailsSent();
+
+ expect(resend.status).toBe(200);
+ expect(sentEmails.map((sent) => sent.type)).toEqual(["set_password"]);
+ const reset = await post(handler, "/reset-password", {
+ token: lastResetToken("[email protected]"),
+ newPassword: "the-owners-new-password",
+ });
+ expect(reset.status).toBe(200);
+ const asFirst = await signIn(
+ handler,
+ "the-first-sign-ups-password",
+ );
+ expect(asFirst.status).toBe(401);
+ const asOwner = await signIn(
+ handler,
+ "the-owners-new-password",
+ );
+ expect(asOwner.status).toBe(200);
+ });
+
+ it("leaves the first password dead when the owner signs up, then verifies through Resend", async () => {
+ // The owner can only reach Resend through their own sign-up: logging in
+ // with their password fails on an account someone else created.
+ const { handler } = await createAuthHandler(true);
+ await signUpAs(handler, "[email protected]", "the-first-sign-ups-password");
+ await emailsSent();
+ const ownersLogin = await signIn(
+ handler,
+ "the-owners-own-password",
+ );
+ expect(ownersLogin.status).toBe(401);
+ await signUpAs(handler, "[email protected]", "the-owners-own-password");
+ await emailsSent();
+
+ await post(handler, "/send-verification-email", {
+ email: "[email protected]",
+ callbackURL,
+ });
+ const verified = await handler(
+ new Request(lastVerifyLink("[email protected]") ?? ""),
+ );
+
+ expect(verified.status).toBe(302);
+ const asFirst = await signIn(
+ handler,
+ "the-first-sign-ups-password",
+ );
+ expect(asFirst.status).toBe(401);
+ });
+
+ it("still replaces the first password when the User row can't be read", async () => {
+ const { handler } = await createAuthHandler(true);
+ await signUpAs(
+ handler,
+ "the-first-sign-ups-password",
+ );
+ await emailsSent();
+ const firstLink = lastVerifyLink("[email protected]") ?? "";
+ userLookupFails.current = true;
+
+ await signUpAs(handler, "[email protected]", "the-owners-own-password");
+ await emailsSent();
+ await handler(new Request(firstLink));
+
+ expect(sentEmails.at(-1)?.type).toBe("set_password");
+ const asFirst = await signIn(
+ handler,
+ "the-first-sign-ups-password",
+ );
+ expect(asFirst.status).toBe(401);
+ });
+
+ it("answers Resend with the set-password link when the User row can't be read", async () => {
+ const { handler } = await createAuthHandler(true);
+ await signUp(handler, "[email protected]");
+ await emailsSent();
+ sentEmails.length = 0;
+ userLookupFails.current = true;
+
+ const resend = await post(handler, "/send-verification-email", {
+ email: "[email protected]",
+ callbackURL,
+ });
+
+ expect(resend.status).toBe(200);
+ expect(sentEmails.map((sent) => sent.type)).toEqual(["set_password"]);
+ });
+
+ it("answers Resend with the set-password link when the session lookup fails", async () => {
+ const { handler } = await createAuthHandler(true);
+ await signUp(handler, "[email protected]");
+ await emailsSent();
+ sentEmails.length = 0;
+ const { auth } = await import("../auth");
+ const { adapter } = await auth.$context;
+ const findMany = adapter.findMany.bind(adapter);
+ let failed = false;
+ vi.spyOn(adapter, "findMany").mockImplementation(async (args) => {
+ if (args.model === "session" && !failed) {
+ failed = true;
+ throw new Error("database is down");
+ }
+ return findMany(args);
+ });
+
+ const resend = await post(handler, "/send-verification-email", {
+ email: "[email protected]",
+ callbackURL,
+ });
+
+ expect(failed).toBe(true);
+ expect(resend.status).toBe(200);
+ expect(sentEmails.map((sent) => sent.type)).toEqual(["set_password"]);
+ });
+
+ it("lets one IP have only a few addresses emailed through the sign-up page", async () => {
+ const { api } = await createAuthHandler(true);
+
+ // The page's server action calls auth.api, which Better Auth's own per-IP
+ // limiter never sees. +aliases all reach one mailbox.
+ const outcomes = [];
+ for (let i = 0; i < 20; i++) {
+ outcomes.push(
+ await api
+ .signUpEmail({
+ body: {
+ email: `mailbox+${i}@example.com`,
+ password,
+ name: "mailbox",
+ callbackURL,
+ },
+ headers: fromIP("203.0.113.7"),
+ })
+ .then(
+ () => "sent",
+ (error: { statusCode?: number }) => error.statusCode,
+ ),
+ );
+ }
+ await emailsSent();
+
+ expect(sentEmails).toHaveLength(AUTH_EMAILS_PER_IP);
+ expect(outcomes.filter((outcome) => outcome === 429)).toHaveLength(
+ 20 - AUTH_EMAILS_PER_IP,
+ );
+ await api.signUpEmail({
+ body: { email: "[email protected]", password, name: "x", callbackURL },
+ headers: fromIP("198.51.100.9"),
+ });
+ await emailsSent();
+ expect(lastVerifyLink("[email protected]")).toBeDefined();
+ });
+
+ it("counts the resend button against the same per-IP cap", async () => {
+ const { handler } = await createAuthHandler(true);
+ await signUp(handler, "[email protected]");
+
+ const statuses = [];
+ for (let i = 0; i < AUTH_EMAILS_PER_IP; i++) {
+ const response = await post(handler, "/send-verification-email", {
+ email: "[email protected]",
+ callbackURL,
+ });
+ statuses.push(response.status);
+ }
+
+ expect(statuses.filter((status) => status === 200)).toHaveLength(
+ AUTH_EMAILS_PER_IP - 1,
+ );
+ expect(statuses.at(-1)).toBe(429);
+ });
+
+ it("emails an unverified address once per cooldown however often it signs in", async () => {
+ const { handler, db } = await createAuthHandler(true);
+ await signUp(handler, "[email protected]");
+ await emailsSent();
+ expireCooldowns(db);
+ sentEmails.length = 0;
+
+ for (let i = 0; i < 3; i++) {
+ expect((await signIn(handler, "[email protected]")).status).toBe(403);
+ await emailsSent();
+ }
+ expect(sentEmails.map((sent) => sent.type)).toEqual(["verify_email"]);
+
+ expireCooldowns(db);
+ await signIn(handler, "[email protected]");
+ await emailsSent();
+ expect(sentEmails.map((sent) => sent.type)).toEqual([
+ "verify_email",
+ "verify_email",
+ ]);
+ });
+
+ it("does not hold back the resend button's emails", async () => {
+ const { handler } = await createAuthHandler(true);
+ await signUp(handler, "[email protected]");
+ await emailsSent();
+ sentEmails.length = 0;
+
+ for (let i = 0; i < 2; i++) {
+ const response = await post(handler, "/send-verification-email", {
+ email: "[email protected]",
+ callbackURL,
+ });
+ expect(response.status).toBe(200);
+ }
+
+ expect(sentEmails.map((sent) => sent.type)).toEqual([
+ "verify_email",
+ "verify_email",
+ ]);
+ });
+
+ it("leaves a verified account verified after a password reset", async () => {
+ const { handler, db } = await createAuthHandler(true);
+ await signUp(handler, "[email protected]");
+ await emailsSent();
+ await handler(new Request(lastVerifyLink("[email protected]") ?? ""));
+ await post(handler, "/request-password-reset", {
+ email: "[email protected]",
+ redirectTo: `${baseURL}/reset-password`,
+ });
+ await emailsSent();
+ const [identity] = db.UserAuthIdentity;
+ const untouchedSince = new Date("2020-01-01T00:00:00Z");
+ identity.updatedAt = untouchedSince;
+
+ const reset = await post(handler, "/reset-password", {
+ token: lastResetToken("[email protected]", "reset_password"),
+ newPassword: "a-new-long-enough-password",
+ });
+
+ expect(reset.status).toBe(200);
+ // The reset writes the password, not the identity: a verified address
+ // has nothing to update.
+ expect(db.UserAuthIdentity).toEqual([
+ expect.objectContaining({
+ emailVerified: true,
+ updatedAt: untouchedSince,
+ }),
+ ]);
+ const signedIn = await signIn(
+ handler,
+ "a-new-long-enough-password",
+ );
+ expect(signedIn.status).toBe(200);
+ });
+
+ it("re-sends the link through the resend endpoint", async () => {
+ const { handler } = await createAuthHandler(true);
+ await signUp(handler, "[email protected]");
+ sentEmails.length = 0;
+
+ const response = await post(handler, "/send-verification-email", {
+ email: "[email protected]",
+ callbackURL,
+ });
+
+ expect(response.status).toBe(200);
+ expect(lastVerifyLink("[email protected]")).toContain(
+ encodeURIComponent(callbackURL),
+ );
+ });
+});
+
+describe("with AUTH_REQUIRE_EMAIL_VERIFICATION off", () => {
+ it("signs up straight into a session and sends no email", async () => {
+ const { handler, db } = await createAuthHandler(false);
+
+ const response = await signUp(handler, "[email protected]");
+
+ expect(response.status).toBe(200);
+ expect((await response.json()).token).toEqual(expect.any(String));
+ expect(db.UserAuthSession).toHaveLength(1);
+ expect(sentEmails).toEqual([]);
+ });
+
+ it("creates the platform User row with the identity, before the session is used", async () => {
+ const { handler } = await createAuthHandler(false);
+
+ await signUp(handler, "[email protected]");
+
+ expect(provisionPlatformUser).toHaveBeenCalledTimes(1);
+ expect(provisionPlatformUser.mock.calls[0][1]).toEqual(
+ expect.objectContaining({
+ email: "[email protected]",
+ emailVerified: false,
+ }),
+ );
+ });
+
+ it("does not cap sign-ups per IP", async () => {
+ const { handler } = await createAuthHandler(false);
+
+ for (let i = 0; i <= AUTH_EMAILS_PER_IP; i++) {
+ expect((await signUp(handler, `user${i}@example.com`)).status).toBe(200);
+ }
+ });
+
+ it("verifies the address from a resent link without signing its opener in", async () => {
+ const { handler, db } = await createAuthHandler(false);
+ await signUp(handler, "[email protected]");
+ db.UserAuthSession.length = 0;
+ await post(handler, "/send-verification-email", {
+ email: "[email protected]",
+ callbackURL,
+ });
+
+ const response = await handler(
+ new Request(lastVerifyLink("[email protected]") ?? ""),
+ );
+
+ expect(response.status).toBe(302);
+ expect(db.UserAuthSession).toHaveLength(0);
+ expect(db.UserAuthIdentity).toEqual([
+ expect.objectContaining({ emailVerified: true }),
+ ]);
+ });
+
+ it("does not hold back a change of email's verification email", async () => {
+ // The per-address cap is for sign-up and sign-in, which send nothing with
+ // verification off; a retried change of email still gets its link.
+ const { api } = await createAuthHandler(false);
+ const { headers } = await api.signUpEmail({
+ body: { email: "[email protected]", password, name: "a", callbackURL },
+ returnHeaders: true,
+ });
+ const session = new Headers({
+ cookie: headers.get("set-cookie")?.split(";")[0] ?? "",
+ });
+
+ for (const newEmail of [
+ ]) {
+ await api.changeEmail({ body: { newEmail }, headers: session });
+ }
+ await emailsSent();
+
+ const toB = sentEmails.filter(
+ (sent) => sent.to === "[email protected]" && sent.type === "verify_email",
+ );
+ expect(toB).toHaveLength(2);
+ });
+
+ it("does not verify an address a reset link was never mailed to", async () => {
+ // A reset token names the account, not the address it went to, and an
+ // unverified account changes address at once. A verified address would
+ // let Better Auth link that address's OAuth sign-in into this account.
+ const { api, handler, db } = await createAuthHandler(false);
+ const { headers } = await api.signUpEmail({
+ body: { email: "[email protected]", password, name: "a", callbackURL },
+ returnHeaders: true,
+ });
+ const cookie = headers.get("set-cookie")?.split(";")[0] ?? "";
+ await api.requestPasswordReset({
+ body: { email: "[email protected]", redirectTo: "/reset-password" },
+ });
+ await emailsSent();
+ const token = lastResetToken("[email protected]", "reset_password");
+ await api.changeEmail({
+ body: { newEmail: "[email protected]" },
+ headers: new Headers({ cookie }),
+ });
+
+ const response = await post(handler, "/reset-password", {
+ newPassword: "a-new-long-enough-password",
+ token,
+ });
+
+ expect(response.status).toBe(400);
+ expect(db.UserAuthIdentity).toEqual([
+ expect.objectContaining({
+ email: "[email protected]",
+ emailVerified: false,
+ }),
+ ]);
+ });
+});
+
+describe("team addresses", () => {
+ it.each([true, false])(
+ "refuses a password sign-up as @agpt.co (verification %s)",
+ async (requireVerification) => {
+ const { handler, db } = await createAuthHandler(requireVerification);
+
+ const response = await signUp(handler, "[email protected]");
+
+ expect(response.status).toBe(403);
+ expect((await response.json()).code).toBe("TEAM_EMAIL_REQUIRES_GOOGLE");
+ expect(db.UserAuthIdentity).toEqual([]);
+ },
+ );
+});
+
+// Signed up with verification off, so the account has a session.
+async function signUpSignedIn(api: API, email: string) {
+ const { headers } = await api.signUpEmail({
+ body: { email, password, name: email.split("@")[0], callbackURL },
+ returnHeaders: true,
+ });
+ return new Headers({
+ cookie: headers.get("set-cookie")?.split(";")[0] ?? "",
+ });
+}
+
+function requestReset(handler: Handler, email: string) {
+ return post(handler, "/request-password-reset", {
+ email,
+ redirectTo: `${baseURL}/reset-password`,
+ });
+}
+
+// What Better Auth decides when someone signs in with Google as `email`.
+async function linkGoogle(email: string) {
+ const { auth } = await import("../auth");
+ const { handleOAuthUserInfo } = await import("better-auth/oauth2");
+ const context = await auth.$context;
+ return handleOAuthUserInfo(
+ { context } as never,
+ {
+ userInfo: {
+ id: "google-account-id",
+ email,
+ emailVerified: true,
+ name: "Google user",
+ },
+ account: { providerId: "google", accountId: "google-account-id" },
+ callbackURL: "/",
+ } as never,
+ );
+}
+
+describe("password reset links", () => {
+ // kcze's attack: the reset link goes to an address the attacker holds,
+ // then the account takes the victim's address before the link is opened.
+ it.each([false, true])(
+ "do not verify an address the link was not mailed to (verification %s)",
+ async (requireVerification) => {
+ const { api: signUpAPI, db } = await createAuthHandler(false);
+ const session = await signUpSignedIn(signUpAPI, "[email protected]");
+ const { handler, api } = await createAuthHandler(requireVerification, db);
+ await requestReset(handler, "[email protected]");
+ await emailsSent();
+ const token = lastResetToken("[email protected]", "reset_password");
+
+ // Applied on the spot: the account is unverified.
+ await api.changeEmail({
+ body: { newEmail: "[email protected]" },
+ headers: session,
+ });
+ await post(handler, "/reset-password", {
+ token,
+ newPassword: "the-attackers-new-password",
+ });
+
+ expect(db.UserAuthIdentity).toEqual([
+ expect.objectContaining({
+ email: "[email protected]",
+ emailVerified: false,
+ }),
+ ]);
+ expect(await linkGoogle("[email protected]")).toEqual(
+ expect.objectContaining({ error: "account not linked" }),
+ );
+ },
+ );
+
+ it("stop working once the account's address changes", async () => {
+ const { handler, api, db } = await createAuthHandler(false);
+ const session = await signUpSignedIn(api, "[email protected]");
+ await requestReset(handler, "[email protected]");
+ await emailsSent();
+ const token = lastResetToken("[email protected]", "reset_password");
+
+ await api.changeEmail({
+ body: { newEmail: "[email protected]" },
+ headers: session,
+ });
+ const reset = await post(handler, "/reset-password", {
+ token,
+ newPassword: "a-new-long-enough-password",
+ });
+
+ expect(reset.status).toBe(400);
+ expect(
+ db.UserAuthVerification.filter((row) =>
+ String(row.identifier).startsWith("reset-password"),
+ ),
+ ).toEqual([]);
+ });
+
+ it("stop working once a verified account's change of address is confirmed", async () => {
+ const { api: signUpAPI, db } = await createAuthHandler(false);
+ const session = await signUpSignedIn(signUpAPI, "[email protected]");
+ db.UserAuthIdentity[0].emailVerified = true;
+ const { handler, api } = await createAuthHandler(false, db);
+ await requestReset(handler, "[email protected]");
+ await emailsSent();
+ const token = lastResetToken("[email protected]", "reset_password");
+
+ // The address changes on /verify-email, when the new address's link is
+ // opened, not on /change-email.
+ await api.changeEmail({
+ body: { newEmail: "[email protected]", callbackURL: "/" },
+ headers: session,
+ });
+ await emailsSent();
+ const confirm = sentEmails.find((sent) => sent.type === "change_email");
+ await handler(new Request(confirm?.url ?? "", { headers: session }));
+ await emailsSent();
+ await handler(
+ new Request(lastVerifyLink("[email protected]") ?? "", {
+ headers: session,
+ }),
+ );
+ expect(db.UserAuthIdentity).toEqual([
+ expect.objectContaining({ email: "[email protected]" }),
+ ]);
+
+ const reset = await post(handler, "/reset-password", {
+ token,
+ newPassword: "a-new-long-enough-password",
+ });
+
+ expect(reset.status).toBe(400);
+ expect(
+ db.UserAuthVerification.filter((row) =>
+ String(row.identifier).startsWith("reset-password"),
+ ),
+ ).toEqual([]);
+ });
+
+ it("verify only the address they were mailed to, even if the link survives a change", async () => {
+ const { handler, db } = await createAuthHandler(false);
+ await signUp(handler, "[email protected]");
+ await requestReset(handler, "[email protected]");
+ await emailsSent();
+ // An address change that skipped Better Auth's hooks, e.g. by hand.
+ db.UserAuthIdentity[0].email = "[email protected]";
+
+ const reset = await post(handler, "/reset-password", {
+ token: lastResetToken("[email protected]", "reset_password"),
+ newPassword: "a-new-long-enough-password",
+ });
+
+ expect(reset.status).toBe(200);
+ expect(db.UserAuthIdentity).toEqual([
+ expect.objectContaining({ emailVerified: false }),
+ ]);
+ });
+
+ it.each([false, true])(
+ "verify the address they were mailed to (verification %s)",
+ async (requireVerification) => {
+ const { handler: signUpHandler, db } = await createAuthHandler(false);
+ await signUp(signUpHandler, "[email protected]");
+ const { handler } = await createAuthHandler(requireVerification, db);
+ await requestReset(handler, "[email protected]");
+ await emailsSent();
+
+ const reset = await post(handler, "/reset-password", {
+ token: lastResetToken("[email protected]", "reset_password"),
+ newPassword: "a-new-long-enough-password",
+ });
+
+ expect(reset.status).toBe(200);
+ expect(db.UserAuthIdentity).toEqual([
+ expect.objectContaining({ emailVerified: true }),
+ ]);
+ expect(
+ db.UserAuthVerification.filter((row) =>
+ String(row.identifier).startsWith("reset-password"),
+ ),
+ ).toEqual([]);
+ },
+ );
+
+ it("keep a link whose address wasn't recorded, which then verifies nothing", async () => {
+ const { handler, api, db } = await createAuthHandler(false);
+ const session = await signUpSignedIn(api, "[email protected]");
+ await requestReset(handler, "[email protected]");
+ await emailsSent();
+ // Recording the address is best-effort.
+ const record = db.UserAuthVerification.findIndex((row) =>
+ String(row.identifier).startsWith("reset-password-mailed-to:"),
+ );
+ db.UserAuthVerification.splice(record, 1);
+
+ await api.updateUser({ body: { name: "New name" }, headers: session });
+ const reset = await post(handler, "/reset-password", {
+ token: lastResetToken("[email protected]", "reset_password"),
+ newPassword: "a-new-long-enough-password",
+ });
+
+ expect(reset.status).toBe(200);
+ expect(db.UserAuthIdentity).toEqual([
+ expect.objectContaining({ emailVerified: false }),
+ ]);
+ });
+
+ it("survive changes to the account that keep its address", async () => {
+ const { handler, api, db } = await createAuthHandler(false);
+ const session = await signUpSignedIn(api, "[email protected]");
+ await requestReset(handler, "[email protected]");
+ await emailsSent();
+
+ await api.updateUser({ body: { name: "New name" }, headers: session });
+ expect(db.UserAuthIdentity).toEqual([
+ expect.objectContaining({ name: "New name" }),
+ ]);
+ const reset = await post(handler, "/reset-password", {
+ token: lastResetToken("[email protected]", "reset_password"),
+ newPassword: "a-new-long-enough-password",
+ });
+
+ expect(reset.status).toBe(200);
+ expect(db.UserAuthIdentity).toEqual([
+ expect.objectContaining({ emailVerified: true }),
+ ]);
+ });
+});
+
+describe("change-email verification emails", () => {
+ it.each([false, true])(
+ "are not held back by the sign-in cooldown when retried (verification %s)",
+ async (requireVerification) => {
+ const { api: signUpAPI, db } = await createAuthHandler(false);
+ const session = await signUpSignedIn(signUpAPI, "[email protected]");
+ db.UserAuthIdentity[0].emailVerified = true;
+ const { handler, api } = await createAuthHandler(requireVerification, db);
+
+ // The confirmation goes to the current address; opening it sends the
+ // link to the new one. The user doesn't see that one and tries again.
+ for (let attempt = 0; attempt < 2; attempt++) {
+ sentEmails.length = 0;
+ await api.changeEmail({
+ body: { newEmail: "[email protected]", callbackURL: "/" },
+ headers: session,
+ });
+ await emailsSent();
+ const confirm = sentEmails.find((sent) => sent.type === "change_email");
+ await handler(new Request(confirm?.url ?? ""));
+ await emailsSent();
+ expect(lastVerifyLink("[email protected]")).toContain("/verify-email");
+ }
+ },
+ );
+
+ it("still caps sign-in's own sends", async () => {
+ const { handler } = await createAuthHandler(true);
+ await signUp(handler, "[email protected]");
+ await emailsSent();
+ sentEmails.length = 0;
+
+ await signIn(handler, "[email protected]");
+ await emailsSent();
+
+ expect(sentEmails).toEqual([]);
+ });
+});
diff --git a/autogpt_platform/frontend/src/lib/auth/__tests__/provision-platform-user.test.ts b/autogpt_platform/frontend/src/lib/auth/__tests__/provision-platform-user.test.ts
new file mode 100644
index 0000000000..8b9ad4aab3
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/auth/__tests__/provision-platform-user.test.ts
@@ -0,0 +1,140 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+const captureExceptionMock = vi.fn();
+vi.mock("@sentry/nextjs", () => ({
+ captureException: (...args: unknown[]) => captureExceptionMock(...args),
+}));
+
+import {
+ platformUserExists,
+ provisionPlatformUser,
+} from "../provision-platform-user";
+
+describe("provisionPlatformUser", () => {
+ beforeEach(() => {
+ captureExceptionMock.mockReset();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ test("inserts the platform User row keyed by the auth identity id", async () => {
+ const query = vi.fn().mockResolvedValue({ rowCount: 1 });
+
+ await expect(
+ provisionPlatformUser(
+ { query },
+ { id: "user-1", email: "[email protected]", name: "New User" },
+ ),
+ ).resolves.toBe("created");
+
+ expect(query).toHaveBeenCalledTimes(1);
+ const [sql, params] = query.mock.calls[0];
+ expect(sql).toContain('INSERT INTO "User"');
+ // `updatedAt` is Prisma-managed and has no database default, so the raw
+ // insert has to supply it or the statement fails on every sign-up.
+ expect(sql).toContain('"updatedAt"');
+ // Idempotent against the client's own `POST /auth/user` and the backend's
+ // self-heal, both of which may race this hook.
+ expect(sql).toContain("ON CONFLICT (id) DO NOTHING");
+ expect(params).toEqual(["user-1", "[email protected]", "New User"]);
+ expect(captureExceptionMock).not.toHaveBeenCalled();
+ });
+
+ test("treats an already-provisioned row as success", async () => {
+ const query = vi.fn().mockResolvedValue({ rowCount: 0 });
+
+ await expect(
+ provisionPlatformUser({ query }, { id: "user-1", email: "[email protected]" }),
+ ).resolves.toBe("exists");
+
+ expect(query.mock.calls[0][1]).toEqual(["user-1", "[email protected]", null]);
+ expect(captureExceptionMock).not.toHaveBeenCalled();
+ });
+
+ test("never throws: a failed insert is reported and the sign-up continues", async () => {
+ // Better Auth awaits create.after hooks post-commit, so a throw here would
+ // fail the sign-up after the auth identity is already durable and strand
+ // it. Report loudly instead and let the existing provisioning paths run.
+ const error = Object.assign(
+ new Error(
+ 'duplicate key value violates unique constraint "User_email_key"',
+ ),
+ {
+ code: "23505",
+ constraint: "User_email_key",
+ detail: "Key (email)=([email protected]) already exists.",
+ },
+ );
+ const query = vi.fn().mockRejectedValue(error);
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+
+ await expect(
+ provisionPlatformUser({ query }, { id: "user-1", email: "[email protected]" }),
+ ).resolves.toBe("failed");
+
+ expect(errorSpy).toHaveBeenCalledTimes(1);
+ expect(captureExceptionMock).toHaveBeenCalledTimes(1);
+ const [reported, context] = captureExceptionMock.mock.calls[0];
+ // The SQLSTATE and constraint are enough to act on ...
+ expect(reported).toBeInstanceOf(Error);
+ expect(reported.message).toContain("23505");
+ expect(reported.message).toContain("User_email_key");
+ expect(context).toEqual(
+ expect.objectContaining({
+ tags: expect.objectContaining({ pg_code: "23505" }),
+ extra: { userId: "user-1", constraint: "User_email_key" },
+ }),
+ );
+ // ... and the raw pg error, whose `detail` carries the email, must reach
+ // neither Sentry nor the server log.
+ expect(reported).not.toBe(error);
+ expect(JSON.stringify([reported.message, context])).not.toContain(
+ );
+ expect(JSON.stringify(errorSpy.mock.calls)).not.toContain("[email protected]");
+ });
+
+ test("reports an unrecognised failure without inventing pg fields", async () => {
+ const query = vi.fn().mockRejectedValue("connection reset");
+ vi.spyOn(console, "error").mockImplementation(() => {});
+
+ await expect(
+ provisionPlatformUser({ query }, { id: "user-1", email: "[email protected]" }),
+ ).resolves.toBe("failed");
+
+ const [reported, context] = captureExceptionMock.mock.calls[0];
+ expect(reported.message).toContain("pg unknown, unknown");
+ expect(context.tags.pg_code).toBe("unknown");
+ });
+});
+
+describe("platformUserExists", () => {
+ test("reads the User row by id", async () => {
+ const query = vi.fn().mockResolvedValue({ rowCount: 1 });
+
+ await expect(platformUserExists({ query }, "user-1")).resolves.toBe(true);
+ expect(query.mock.calls[0][1]).toEqual(["user-1"]);
+ });
+
+ test("says no when there is no row", async () => {
+ const query = vi.fn().mockResolvedValue({ rowCount: 0 });
+
+ await expect(platformUserExists({ query }, "user-1")).resolves.toBe(false);
+ });
+
+ test("throws when the row can't be read, without the pg error's detail", async () => {
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ const query = vi.fn().mockRejectedValue(
+ Object.assign(new Error("boom"), {
+ code: "57P01",
+ detail: "Key (email)=([email protected])",
+ }),
+ );
+
+ await expect(platformUserExists({ query }, "user-1")).rejects.toThrow(
+ "Failed to look up the platform User (pg 57P01)",
+ );
+ });
+});
diff --git a/autogpt_platform/frontend/src/lib/auth/__tests__/team-email-policy.test.ts b/autogpt_platform/frontend/src/lib/auth/__tests__/team-email-policy.test.ts
new file mode 100644
index 0000000000..ea01b66c2a
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/auth/__tests__/team-email-policy.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from "vitest";
+import { assertTeamEmailUsesGoogle, isTeamEmail } from "../team-email-policy";
+
+describe("isTeamEmail", () => {
+ it.each([
+ ["[email protected]", true],
+ ["[email protected]", true],
+ ["[email protected]", false],
+ ["[email protected]", false],
+ ["[email protected]", false],
+ ["[email protected]", false],
+ ["no-at-sign", false],
+ ])("%s → %s", (email, expected) => {
+ expect(isTeamEmail(email)).toBe(expected);
+ });
+});
+
+describe("assertTeamEmailUsesGoogle", () => {
+ it("throws only for a team address on the password sign-up path", () => {
+ expect(() =>
+ assertTeamEmailUsesGoogle("[email protected]", { path: "/sign-up/email" }),
+ ).toThrow("Please use Google sign-in");
+ expect(() =>
+ assertTeamEmailUsesGoogle("[email protected]", { path: "/callback/google" }),
+ ).not.toThrow();
+ expect(() => assertTeamEmailUsesGoogle("[email protected]", null)).not.toThrow();
+ expect(() =>
+ assertTeamEmailUsesGoogle("[email protected]", { path: "/sign-up/email" }),
+ ).not.toThrow();
+ });
+});
diff --git a/autogpt_platform/frontend/src/lib/auth/auth-email-cooldown.ts b/autogpt_platform/frontend/src/lib/auth/auth-email-cooldown.ts
new file mode 100644
index 0000000000..aa54f26124
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/auth/auth-email-cooldown.ts
@@ -0,0 +1,151 @@
+import { createHash } from "node:crypto";
+
+// At most one email of a kind per address per window, however often whatever
+// sends it is repeated.
+const AUTH_EMAIL_COOLDOWN_SECONDS = 10 * 60;
+// And at most this many sign-ups and resends per IP per window, so fresh
+// addresses (or +aliases of one mailbox) can't each be mailed.
+export const AUTH_EMAILS_PER_IP = 5;
+
+interface Where {
+ field: string;
+ value: string | Date;
+ operator?: "eq" | "gt" | "starts_with" | "ends_with";
+}
+
+/**
+ * The parts of Better Auth's context these emails use. They run alongside the
+ * response (see background-tasks.ts), after a sign-up's database transaction
+ * has committed, and Better Auth's internal adapter (and any auth.api call)
+ * would still go through that transaction. So they use the base adapter.
+ */
+export interface AuthEmailContext {
+ baseURL: string;
+ adapter: {
+ findMany: (args: {
+ model: string;
+ where: Where[];
+ limit: number;
+ }) => Promise<unknown[]>;
+ create: (args: {
+ model: string;
+ data: Record<string, unknown>;
+ forceAllowId?: boolean;
+ }) => Promise<unknown>;
+ updateMany: (args: {
+ model: string;
+ where: Where[];
+ update: Record<string, unknown>;
+ }) => Promise<unknown>;
+ deleteMany: (args: { model: string; where: Where[] }) => Promise<unknown>;
+ };
+ password: { hash: (password: string) => Promise<string> };
+}
+
+// Kept in Better Auth's verification table, which every server shares and
+// which Better Auth clears of expired rows itself. The row's id is fixed per
+// address and window, so when several sends pass the check below at the same
+// moment, the primary key lets one insert win and the rest fail.
+export async function claimEmailSlot(
+ context: AuthEmailContext,
+ kind: "repeat-sign-up" | "verify-email",
+ email: string,
+) {
+ const identifier = `${kind}:${email.toLowerCase()}`;
+ if (await hasLiveSlot(context, identifier)) return false;
+ try {
+ await createVerification(context, {
+ id: slotID(identifier),
+ identifier,
+ value: "sent",
+ expiresInSeconds: AUTH_EMAIL_COOLDOWN_SECONDS,
+ });
+ } catch (error) {
+ // Lost the race to a concurrent send, or a real failure.
+ if (await hasLiveSlot(context, identifier)) return false;
+ throw error;
+ }
+ return true;
+}
+
+async function hasLiveSlot(context: AuthEmailContext, identifier: string) {
+ const live = await context.adapter.findMany({
+ model: "verification",
+ where: [
+ { field: "identifier", value: identifier },
+ { field: "expiresAt", value: new Date(), operator: "gt" },
+ ],
+ limit: 1,
+ });
+ return live.length > 0;
+}
+
+function slotID(identifier: string, index?: number) {
+ const window = currentWindow();
+ const key =
+ index === undefined
+ ? `${identifier}#${window}`
+ : `${identifier}#${window}#${index}`;
+ return createHash("sha256").update(key).digest("hex");
+}
+
+function currentWindow() {
+ return Math.floor(Date.now() / (AUTH_EMAIL_COOLDOWN_SECONDS * 1000));
+}
+
+// One of AUTH_EMAILS_PER_IP fixed rows per IP and window; each id can only be
+// inserted once, so a burst from one IP can't take more than that many. A
+// failed insert whose row now exists lost the race and tries the next slot.
+export async function claimIPEmailSlot(context: AuthEmailContext, ip: string) {
+ const identifier = `auth-email-ip:${ip}`;
+ const windowEndsAt = (currentWindow() + 1) * AUTH_EMAIL_COOLDOWN_SECONDS;
+ for (let index = 0; index < AUTH_EMAILS_PER_IP; index++) {
+ const id = slotID(identifier, index);
+ if (await rowExists(context, id)) continue;
+ try {
+ await createVerification(context, {
+ id,
+ identifier,
+ value: "sent",
+ expiresInSeconds: windowEndsAt - Date.now() / 1000,
+ });
+ return true;
+ } catch (error) {
+ if (!(await rowExists(context, id))) throw error;
+ }
+ }
+ return false;
+}
+
+async function rowExists(context: AuthEmailContext, id: string) {
+ const rows = await context.adapter.findMany({
+ model: "verification",
+ where: [{ field: "id", value: id }],
+ limit: 1,
+ });
+ return rows.length > 0;
+}
+
+export function createVerification(
+ context: AuthEmailContext,
+ args: {
+ id?: string;
+ identifier: string;
+ value: string;
+ expiresInSeconds: number;
+ },
+) {
+ const now = new Date();
+ return context.adapter.create({
+ model: "verification",
+ forceAllowId: args.id !== undefined,
+ data: {
+ ...(args.id === undefined ? {} : { id: args.id }),
+ identifier: args.identifier,
+ value: args.value,
+ expiresAt: new Date(now.getTime() + args.expiresInSeconds * 1000),
+ createdAt: now,
+ updatedAt: now,
+ },
+ });
+}
diff --git a/autogpt_platform/frontend/src/lib/auth/auth-endpoint.ts b/autogpt_platform/frontend/src/lib/auth/auth-endpoint.ts
new file mode 100644
index 0000000000..1efbedb9af
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/auth/auth-endpoint.ts
@@ -0,0 +1,20 @@
+import { getCurrentAuthContext } from "@better-auth/core/context";
+
+/**
+ * The Better Auth endpoint the current callback runs under, such as
+ * "/sign-in/email" or "/change-email". Better Auth runs every endpoint inside
+ * an async context, server-side auth.api calls included (they carry no
+ * request), and the email callbacks it fires run inside it too. Outside one,
+ * both are undefined.
+ */
+export async function currentAuthEndpoint(): Promise<{
+ path?: string;
+ body?: unknown;
+}> {
+ try {
+ const { path, body } = await getCurrentAuthContext();
+ return { path, body };
+ } catch {
+ return {};
+ }
+}
diff --git a/autogpt_platform/frontend/src/lib/auth/auth.ts b/autogpt_platform/frontend/src/lib/auth/auth.ts
index 51a410bc8b..0c47aac1cf 100644
--- a/autogpt_platform/frontend/src/lib/auth/auth.ts
+++ b/autogpt_platform/frontend/src/lib/auth/auth.ts
@@ -1,18 +1,35 @@
import { betterAuth } from "better-auth";
-import { APIError } from "better-auth/api";
+import { APIError, createAuthMiddleware, isAPIError } from "better-auth/api";
import { nextCookies } from "better-auth/next-js";
import { admin, jwt } from "better-auth/plugins";
import { compare, hash } from "bcryptjs";
import { Pool } from "pg";
+import { runAfterResponse } from "./background-tasks";
import { mirrorVerifiedEmailToPlatformUser } from "./email-mirror";
import { sendAuthEmail } from "./email";
+import { isAwaitingEmailVerification } from "./email-verification";
+import { emailRepeatSignUp } from "./existing-user-sign-up";
+import { capAuthEmailsPerIP } from "./ip-email-cap";
import {
AUTH_PASSWORD_BCRYPT_COST,
AUTH_PASSWORD_MIN_LENGTH,
} from "./password-policy";
+import {
+ platformUserExists,
+ provisionPlatformUser,
+} from "./provision-platform-user";
+import {
+ recordResetLinkAddress,
+ type ResetLinkContext,
+ verifyAddressTheResetLinkWasMailedTo,
+} from "./reset-link-address";
+import { revokeResetLinksMailedElsewhere } from "./reset-links";
+import { RESET_LINK_EXPIRES_IN_SECONDS } from "./set-password-link";
import { JWKS_ALG } from "./service-token";
import { isSignupAllowed, readSignupGateConfig } from "./signup-gate";
import { supabaseBridge } from "./supabase-bridge";
+import { assertTeamEmailUsesGoogle } from "./team-email-policy";
+import { sendVerificationLink } from "./verification-link";
const baseURL =
process.env.BETTER_AUTH_URL ||
@@ -62,11 +79,60 @@ if (process.env.NODE_ENV !== "production") {
globalForAuthDb.__authDbPool = authDbPool;
}
+const requireEmailVerification =
+ process.env.AUTH_REQUIRE_EMAIL_VERIFICATION === "true";
+// 24h, as GoTrue's confirmation links were; Better Auth's default is 1h.
+const emailVerificationExpiresIn = 60 * 60 * 24;
+
+const authSecret = process.env.BETTER_AUTH_SECRET;
+
+const resetRedirectTo = new URL("/reset-password", baseURL).toString();
+
+function hasPlatformUser(userId: string) {
+ return platformUserExists(authDbPool, userId);
+}
+
export const auth = betterAuth({
baseURL,
- secret: process.env.BETTER_AUTH_SECRET,
+ secret: authSecret,
database: authDbPool,
telemetry: { enabled: false },
+ hooks: {
+ // With verification required, sign-up and resend email an address with
+ // no session yet: at most a few per IP per window (ip-email-cap.ts).
+ before: createAuthMiddleware(async (ctx) => {
+ if (!requireEmailVerification) return;
+ await capAuthEmailsPerIP({
+ path: ctx.path,
+ headers: ctx.headers,
+ context: ctx.context,
+ });
+ }),
+ // A reset link only reaches whoever holds the address it was mailed to,
+ // so opening one verifies that address, if it is still the account's: an
+ // unverified account (a repeat sign-up's, or one from before the flag)
+ // then logs in with the password just set. See reset-link-address.ts.
+ // Better Auth has already saved the password and used up the token by
+ // now, and a throw here would fail a reset that happened. So a failure is
+ // logged and the address left unverified: the next sign-in sends a fresh
+ // verify link (sendOnSignIn).
+ after: createAuthMiddleware(async (ctx) => {
+ if (ctx.path !== "/reset-password") return;
+ if (isAPIError(ctx.context.returned)) return;
+ const token = ctx.body?.token ?? ctx.query?.token;
+ if (typeof token !== "string") return;
+ try {
+ await verifyAddressTheResetLinkWasMailedTo(
+ await getAuthContext(),
+ token,
+ );
+ } catch (error) {
+ console.error("Failed to verify the address on password reset", {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }),
+ },
databaseHooks: {
user: {
create: {
@@ -75,7 +141,11 @@ export const auth = betterAuth({
// a user row. Existing users and the SQL data-migration bypass it.
// The thrown message is phrased so the frontend `isWaitlistError()`
// maps it to the existing "not allowed" modal.
- before: async (user: { email: string }) => {
+ before: async (
+ user: { email: string },
+ ctx: { path?: string } | null,
+ ) => {
+ assertTeamEmailUsesGoogle(user.email, ctx);
const decision = isSignupAllowed(user.email, readSignupGateConfig());
if (!decision.allowed) {
throw new APIError("FORBIDDEN", {
@@ -83,13 +153,35 @@ export const auth = betterAuth({
});
}
},
+ // Writes the platform `User` row (see provision-platform-user.ts). An
+ // unverified identity gets it from /auth/callback?method=email instead.
+ after: async (user: {
+ id: string;
+ email: string;
+ name: string;
+ emailVerified?: boolean | null;
+ }) => {
+ if (isAwaitingEmailVerification(user, requireEmailVerification)) {
+ return;
+ }
+ await provisionPlatformUser(authDbPool, user);
+ },
},
update: {
// updateUserByEmail (fired when a change-email link is confirmed)
// runs this hook post-commit; mirror the now-verified email onto the
// platform User row so notifications/Stripe track the confirmed
// identity. See email-mirror.ts for the why.
+ // Also: reset links mailed to an address the account no longer has
+ // stop working, whatever changed it (reset-links.ts).
after: async (user: { id: string; email: string }) => {
+ await getAuthContext()
+ .then((context) => revokeResetLinksMailedElsewhere(context, user))
+ .catch((error: unknown) => {
+ console.error("Failed to revoke reset links after an update", {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
await mirrorVerifiedEmailToPlatformUser(authDbPool, user);
},
},
@@ -101,6 +193,10 @@ export const auth = betterAuth({
// pre-migration ids are Supabase UUIDs.
generateId: () => crypto.randomUUID(),
},
+ // Auth emails go out alongside the response instead of before it, so a
+ // sign-up takes as long whether or not the address already has an
+ // account: see background-tasks.ts.
+ backgroundTasks: { handler: runAfterResponse },
},
session: {
modelName: "UserAuthSession",
@@ -133,15 +229,40 @@ export const auth = betterAuth({
// flow's signOut({ scope: "global" }) — the standard defense when a
// user resets their password to evict a stolen session.
revokeSessionsOnPasswordReset: true,
- requireEmailVerification:
- process.env.AUTH_REQUIRE_EMAIL_VERIFICATION === "true",
+ requireEmailVerification,
+ // Only called with requireEmailVerification on, for a sign-up whose
+ // address already has an account: see existing-user-sign-up.ts.
+ onExistingUserSignUp: async ({ user }) => {
+ await emailRepeatSignUp({
+ user,
+ getAuthContext,
+ hasPlatformUser,
+ resetRedirectTo,
+ });
+ },
password: {
// bcrypt instead of Better Auth's default scrypt so password hashes
// migrated from Supabase GoTrue keep verifying without a reset.
hash: (password) => hash(password, AUTH_PASSWORD_BCRYPT_COST),
verify: ({ hash: hashValue, password }) => compare(password, hashValue),
},
- sendResetPassword: async ({ user, url }) => {
+ // Without the record the link still resets the password, it just doesn't
+ // verify the address (reset-link-address.ts).
+ sendResetPassword: async ({ user, url, token }) => {
+ await getAuthContext()
+ .then((context) =>
+ recordResetLinkAddress(context, {
+ token,
+ userId: user.id,
+ email: user.email,
+ expiresInSeconds: RESET_LINK_EXPIRES_IN_SECONDS,
+ }),
+ )
+ .catch((error: unknown) => {
+ console.error("Failed to record where a reset link was sent", {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
await sendAuthEmail({
to: user.email,
type: "reset_password",
@@ -150,11 +271,25 @@ export const auth = betterAuth({
},
},
emailVerification: {
- sendVerificationEmail: async ({ user, url }) => {
- await sendAuthEmail({
- to: user.email,
- type: "verify_email",
+ // Better Auth gates sendOnSignIn on requireEmailVerification itself. An
+ // unverified password user who signs in is sent a fresh link rather than a
+ // dead-end 403, so accounts created before the flag was flipped get in.
+ sendOnSignIn: true,
+ // Not gated by Better Auth: with the flag off, a link from
+ // /send-verification-email would sign in whoever opens it.
+ autoSignInAfterVerification: requireEmailVerification,
+ expiresIn: emailVerificationExpiresIn,
+ // Throttled per address, except for the resend button's own route: see
+ // verification-link.ts.
+ sendVerificationEmail: async ({ user, url }, request) => {
+ await sendVerificationLink({
+ user,
url,
+ request,
+ getAuthContext,
+ hasPlatformUser,
+ requireEmailVerification,
+ resetRedirectTo,
});
},
},
@@ -229,3 +364,9 @@ export const auth = betterAuth({
nextCookies(),
],
});
+
+// Better Auth hands the hooks above the user alone; this reaches back into the
+// instance they belong to, once it exists.
+async function getAuthContext(): Promise<ResetLinkContext> {
+ return auth.$context;
+}
diff --git a/autogpt_platform/frontend/src/lib/auth/background-tasks.ts b/autogpt_platform/frontend/src/lib/auth/background-tasks.ts
new file mode 100644
index 0000000000..197ad959c4
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/auth/background-tasks.ts
@@ -0,0 +1,31 @@
+import { after } from "next/server";
+
+/**
+ * Better Auth's `advanced.backgroundTasks.handler`. Without one, Better Auth
+ * awaits the emails it sends from sign-up, sign-in, password reset and email
+ * change before it answers, so the response time gives away whether an email
+ * went out: a sign-up for an address still waiting on its link waits on the
+ * mail call, one for a verified address does not, though both get the same
+ * body. With a handler the send runs alongside and the response does not wait.
+ *
+ * Better Auth already catches and logs a failed send at those call sites, so
+ * nothing the response says depends on the email either way. The resend
+ * endpoint does not come through here: it still awaits the send, so its
+ * button can report a failure.
+ *
+ * `after` keeps the server alive until the send settles. Outside a Next
+ * request scope (tests, scripts) it throws, and the send, already running,
+ * finishes on its own.
+ */
+export function runAfterResponse(task: Promise<unknown>) {
+ const settled = task.catch((error: unknown) => {
+ console.error("Auth background task failed", {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+ try {
+ after(settled);
+ } catch {
+ // No request scope: nothing to keep alive.
+ }
+}
diff --git a/autogpt_platform/frontend/src/lib/auth/email-verification.ts b/autogpt_platform/frontend/src/lib/auth/email-verification.ts
new file mode 100644
index 0000000000..89d77e9f07
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/auth/email-verification.ts
@@ -0,0 +1,43 @@
+import { sanitizeAuthNext } from "@/lib/auth-redirect";
+
+/**
+ * Email verification (AUTH_REQUIRE_EMAIL_VERIFICATION=true).
+ *
+ * Better Auth then creates no session at email/password sign-up and answers a
+ * sign-in by an unverified account with 403 EMAIL_NOT_VERIFIED; both email a
+ * link to `/api/auth/verify-email`, which marks the address verified, signs
+ * the user in and redirects to the callbackURL built here. `/auth/callback`
+ * then provisions the platform user and fires the sign-up conversion, exactly
+ * as it does after Google sign-in, so neither happens for an address nobody
+ * has proven they own.
+ */
+
+export const EMAIL_NOT_VERIFIED_CODE = "EMAIL_NOT_VERIFIED";
+
+// Shown on /login when the callback has no session to work with: an expired or
+// already-used link, or a second click once the address is verified.
+export const EMAIL_VERIFICATION_NOTICE_PARAM = "email_verification";
+export type EmailVerificationNotice = "expired" | "verified";
+
+export function getEmailVerificationCallbackURL(next?: string | null) {
+ const params = new URLSearchParams({ method: "email" });
+ const safeNext = sanitizeAuthNext(next);
+ if (safeNext) params.set("next", safeNext);
+ return `/auth/callback?${params.toString()}`;
+}
+
+// The user.create.after hook skips these. Provisioning the platform User (and
+// the personal org behind it) waits for the verification link, so an address
+// nobody has proven they own never gets an account.
+export function isAwaitingEmailVerification(
+ user: { emailVerified?: boolean | null },
+ requireEmailVerification: boolean,
+) {
+ return requireEmailVerification && !user.emailVerified;
+}
+
+export function getEmailVerificationNotice(
+ value: string | null,
+): EmailVerificationNotice | null {
+ return value === "expired" || value === "verified" ? value : null;
+}
diff --git a/autogpt_platform/frontend/src/lib/auth/email.ts b/autogpt_platform/frontend/src/lib/auth/email.ts
index 3a9797d7d4..5662c90230 100644
--- a/autogpt_platform/frontend/src/lib/auth/email.ts
+++ b/autogpt_platform/frontend/src/lib/auth/email.ts
@@ -1,7 +1,11 @@
import { environment } from "@/services/environment";
import { mintServiceToken } from "./service-token";
-export type AuthEmailType = "reset_password" | "verify_email" | "change_email";
+export type AuthEmailType =
+ | "reset_password"
+ | "verify_email"
+ | "change_email"
+ | "set_password";
interface SendAuthEmailArgs {
to: string;
diff --git a/autogpt_platform/frontend/src/lib/auth/existing-user-sign-up.ts b/autogpt_platform/frontend/src/lib/auth/existing-user-sign-up.ts
new file mode 100644
index 0000000000..a6d533ada4
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/auth/existing-user-sign-up.ts
@@ -0,0 +1,64 @@
+import { type AuthEmailContext, claimEmailSlot } from "./auth-email-cooldown";
+import {
+ hasAccountBeenUsed,
+ randomToken,
+ sendSetPasswordLink,
+} from "./set-password-link";
+
+interface Args {
+ user: { id: string; email: string; emailVerified?: boolean | null };
+ getAuthContext: () => Promise<AuthEmailContext>;
+ hasPlatformUser: (userId: string) => Promise<boolean>;
+ resetRedirectTo: string;
+}
+
+/**
+ * With email verification required, Better Auth answers a sign-up for an
+ * address that already has an account exactly like a new one (no session, no
+ * error), so as not to reveal that the account exists, and the sign-up page
+ * then says to check the inbox. A verified account gets nothing here.
+ *
+ * An unverified one gets a set-password link, not a verification link, at
+ * most once per address per window (auth-email-cooldown.ts). A verification
+ * link would sign the owner in to an account whose password whoever signed up
+ * first still holds. If the account has never been used, that password is
+ * replaced with a random one first. A used one (from before the flag) keeps
+ * it: its owner may have set it, and a stranger signing up with their address
+ * must not lock them out. Either way, setting a password through the link
+ * replaces the old one and verifies the address.
+ *
+ * The cooldown is claimed before any of the work, so repeats can't make us
+ * hash or mail more than once a window. Better Auth runs this alongside the
+ * response (see background-tasks.ts), so none of it shows in the response's
+ * timing. Never throws: a failure must not turn this response into an error
+ * that a brand-new address would not get.
+ */
+export async function emailRepeatSignUp({
+ user,
+ getAuthContext,
+ hasPlatformUser,
+ resetRedirectTo,
+}: Args) {
+ if (user.emailVerified) return;
+ try {
+ const context = await getAuthContext();
+ if (!(await claimEmailSlot(context, "repeat-sign-up", user.email))) return;
+ // Unknown counts as never used: the scramble costs a real owner nothing
+ // the set-password link below doesn't give back.
+ if (!(await hasAccountBeenUsed(context, user.id, hasPlatformUser, false))) {
+ await context.adapter.updateMany({
+ model: "account",
+ where: [
+ { field: "userId", value: user.id },
+ { field: "providerId", value: "credential" },
+ ],
+ update: { password: await context.password.hash(randomToken(32)) },
+ });
+ }
+ await sendSetPasswordLink(context, user, resetRedirectTo);
+ } catch (error) {
+ console.error("Failed to handle a repeat sign-up", {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+}
diff --git a/autogpt_platform/frontend/src/lib/auth/ip-email-cap.ts b/autogpt_platform/frontend/src/lib/auth/ip-email-cap.ts
new file mode 100644
index 0000000000..9eb7f9871d
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/auth/ip-email-cap.ts
@@ -0,0 +1,38 @@
+import { APIError, getIp } from "better-auth/api";
+import type { BetterAuthOptions } from "better-auth";
+import { type AuthEmailContext, claimIPEmailSlot } from "./auth-email-cooldown";
+
+// Each of these can email an address that has no session yet.
+const IP_CAPPED_PATHS = new Set(["/sign-up/email", "/send-verification-email"]);
+
+interface Args {
+ path: string | undefined;
+ headers: Headers | undefined;
+ context: AuthEmailContext & { options: BetterAuthOptions };
+}
+
+/**
+ * A Better Auth before-hook, so it covers the sign-up page's server action
+ * (auth.api, which Better Auth's own per-IP limiter never sees) as well as the
+ * HTTP routes. The count lives in the verification table, which every server
+ * shares. With no IP Better Auth trusts, or if the count can't be read, the
+ * request goes through: the per-address cap still holds.
+ */
+export async function capAuthEmailsPerIP({ path, headers, context }: Args) {
+ if (!path || !IP_CAPPED_PATHS.has(path) || !headers) return;
+ const ip = getIp(headers, context.options);
+ if (!ip) return;
+ const claimed = await claimIPEmailSlot(context, ip).catch(
+ (error: unknown) => {
+ console.error("Failed to check the per-IP auth email cap", {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return true;
+ },
+ );
+ if (!claimed) {
+ throw new APIError("TOO_MANY_REQUESTS", {
+ message: "Too many attempts. Please try again in a few minutes.",
+ });
+ }
+}
diff --git a/autogpt_platform/frontend/src/lib/auth/provision-platform-user.ts b/autogpt_platform/frontend/src/lib/auth/provision-platform-user.ts
new file mode 100644
index 0000000000..520e365c41
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/auth/provision-platform-user.ts
@@ -0,0 +1,79 @@
+import * as Sentry from "@sentry/nextjs";
+import type { Pool } from "pg";
+
+export type AuthIdentity = {
+ id: string;
+ email: string;
+ name?: string | null;
+};
+
+export type ProvisionOutcome = "created" | "exists" | "failed";
+
+// From the `user.create.after` hook, so a session never exists before its `User` row. `updatedAt` has
+// no DB default. Never throws: a throw after commit strands an identity that rejects every retry.
+export async function provisionPlatformUser(
+ pool: Pick<Pool, "query">,
+ user: AuthIdentity,
+): Promise<ProvisionOutcome> {
+ try {
+ const result = await pool.query(
+ 'INSERT INTO "User" (id, email, name, "updatedAt") VALUES ($1, $2, $3, NOW()) ON CONFLICT (id) DO NOTHING',
+ [user.id, user.email, user.name ?? null],
+ );
+ return (result.rowCount ?? 0) > 0 ? "created" : "exists";
+ } catch (error) {
+ // The likely cause is `User_email_key`: a platform row already carries
+ // this email under a different id (an auth identity removed through the
+ // admin plugin and re-created, say). `ON CONFLICT (id)` cannot absorb
+ // that, and neither can the backend's own provisioning, so it has to be
+ // visible rather than retried quietly.
+ //
+ // Report only the SQLSTATE and constraint, never the raw `pg` error: its
+ // `detail` field spells out the conflicting value ("Key (email)=(…)
+ // already exists"), which would put the user's email into server logs
+ // and, via Sentry's extra-error-data capture, into the event body.
+ const { code, constraint } = describePgError(error);
+ const sanitized = new Error(
+ `Failed to provision platform User (pg ${code}, ${constraint})`,
+ );
+ console.error(sanitized.message, { userId: user.id });
+ Sentry.captureException(sanitized, {
+ tags: { auth_hook: "user.create.after", pg_code: code },
+ extra: { userId: user.id, constraint },
+ });
+ return "failed";
+ }
+}
+
+function describePgError(error: unknown): {
+ code: string;
+ constraint: string;
+} {
+ const fields =
+ typeof error === "object" && error !== null
+ ? (error as { code?: unknown; constraint?: unknown })
+ : {};
+ return {
+ code: typeof fields.code === "string" ? fields.code : "unknown",
+ constraint:
+ typeof fields.constraint === "string" ? fields.constraint : "unknown",
+ };
+}
+
+// Whether the platform `User` row exists. Throws if it can't be read: the
+// callers want opposite answers then (see hasAccountBeenUsed).
+export async function platformUserExists(
+ pool: Pick<Pool, "query">,
+ userId: string,
+) {
+ try {
+ const result = await pool.query('SELECT 1 FROM "User" WHERE id = $1', [
+ userId,
+ ]);
+ return (result.rowCount ?? 0) > 0;
+ } catch (error) {
+ const { code } = describePgError(error);
+ console.error("Failed to look up the platform User", { userId, code });
+ throw new Error(`Failed to look up the platform User (pg ${code})`);
+ }
+}
diff --git a/autogpt_platform/frontend/src/lib/auth/reset-link-address.ts b/autogpt_platform/frontend/src/lib/auth/reset-link-address.ts
new file mode 100644
index 0000000000..6cd98430f3
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/auth/reset-link-address.ts
@@ -0,0 +1,104 @@
+import {
+ type AuthEmailContext,
+ createVerification,
+} from "./auth-email-cooldown";
+
+// `reset-password-mailed-to:<userId>:<token>` holds the address the link went
+// to. The user id comes first so an account's records can be read by prefix
+// (reset-links.ts); the token is used up before the reset's hook runs, so the
+// record is found by its suffix.
+const MAILED_TO = "reset-password-mailed-to:";
+
+interface ResetUser {
+ id: string;
+ email: string;
+ emailVerified?: boolean | null;
+}
+
+export interface ResetLinkContext extends AuthEmailContext {
+ internalAdapter: {
+ findUserById: (userId: string) => Promise<ResetUser | null>;
+ updateUser: (
+ userId: string,
+ data: { emailVerified: boolean },
+ ) => Promise<unknown>;
+ };
+}
+
+/**
+ * Better Auth binds a reset token to the account (`reset-password:<token>`
+ * holds the user id), not to the address the link was mailed to, and an
+ * unverified account can change its address on the spot. So each link
+ * records where it was mailed, and a reset verifies the account's address
+ * only while the two still match. Links are also dropped once the address
+ * changes (reset-links.ts), but one issued while a change is landing can
+ * outlive that.
+ */
+export function recordResetLinkAddress(
+ context: AuthEmailContext,
+ link: {
+ token: string;
+ userId: string;
+ email: string;
+ expiresInSeconds: number;
+ },
+) {
+ return createVerification(context, {
+ identifier: resetLinkAddressIdentifier(link.userId, link.token),
+ value: link.email.toLowerCase(),
+ expiresInSeconds: link.expiresInSeconds,
+ });
+}
+
+// Runs after /reset-password has used up the token and saved the password.
+export async function verifyAddressTheResetLinkWasMailedTo(
+ context: ResetLinkContext,
+ token: string,
+) {
+ // The adapter's LIKE leaves `_` (in base64url tokens) a wildcard, so the
+ // suffix is matched exactly here.
+ const records = (await context.adapter.findMany({
+ model: "verification",
+ where: [
+ { field: "identifier", value: `:${token}`, operator: "ends_with" },
+ { field: "identifier", value: MAILED_TO, operator: "starts_with" },
+ ],
+ limit: 10,
+ })) as Array<{ identifier: string; value: string }>;
+ const record = records.find(
+ ({ identifier }) =>
+ identifier.startsWith(MAILED_TO) && identifier.endsWith(`:${token}`),
+ );
+ if (!record) return;
+ await context.adapter.deleteMany({
+ model: "verification",
+ where: [{ field: "identifier", value: record.identifier }],
+ });
+ const userId = record.identifier.slice(MAILED_TO.length, -(token.length + 1));
+ const user = await context.internalAdapter.findUserById(userId);
+ if (!user || user.emailVerified) return;
+ if (user.email.toLowerCase() !== record.value) return;
+ await context.internalAdapter.updateUser(user.id, { emailVerified: true });
+}
+
+export function resetLinkAddressIdentifier(userId: string, token: string) {
+ return `${MAILED_TO}${userId}:${token}`;
+}
+
+// The addresses the account's outstanding links were mailed to, by token.
+export async function resetLinkAddresses(
+ context: AuthEmailContext,
+ userId: string,
+) {
+ const prefix = `${MAILED_TO}${userId}:`;
+ const records = (await context.adapter.findMany({
+ model: "verification",
+ where: [{ field: "identifier", value: prefix, operator: "starts_with" }],
+ limit: 100,
+ })) as Array<{ identifier: string; value: string }>;
+ return new Map(
+ records
+ .filter(({ identifier }) => identifier.startsWith(prefix))
+ .map((record) => [record.identifier.slice(prefix.length), record.value]),
+ );
+}
diff --git a/autogpt_platform/frontend/src/lib/auth/reset-links.ts b/autogpt_platform/frontend/src/lib/auth/reset-links.ts
new file mode 100644
index 0000000000..671a57792e
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/auth/reset-links.ts
@@ -0,0 +1,57 @@
+import type { AuthEmailContext } from "./auth-email-cooldown";
+import {
+ resetLinkAddresses,
+ resetLinkAddressIdentifier,
+} from "./reset-link-address";
+
+const RESET_LINK = "reset-password:";
+
+/**
+ * A reset or set-password link is a token naming the account, not the address
+ * it was mailed to. An unverified account changes its address at once, so a
+ * link mailed to its old address could verify the new one, and a verified
+ * address lets Better Auth link that address's OAuth sign-in into the account.
+ * And after any change of address, the old address should no longer reset the
+ * account's password.
+ *
+ * So after every update to the account, whatever path made it (/change-email,
+ * a confirmed change on /verify-email, an admin update), its links mailed to
+ * another address are dropped. A link with no address recorded (recording is
+ * best-effort) is kept: the reset checks the address itself
+ * (reset-link-address.ts), so such a link resets the password but verifies
+ * nothing.
+ */
+export async function revokeResetLinksMailedElsewhere(
+ context: AuthEmailContext,
+ user: { id: string; email: string },
+) {
+ const links = (await context.adapter.findMany({
+ model: "verification",
+ where: [
+ { field: "identifier", value: RESET_LINK, operator: "starts_with" },
+ { field: "value", value: user.id },
+ ],
+ limit: 100,
+ })) as Array<{ identifier: string }>;
+ const mailedTo = await resetLinkAddresses(context, user.id);
+ const email = user.email.toLowerCase();
+ for (const { identifier } of links) {
+ const address = mailedTo.get(identifier.slice(RESET_LINK.length));
+ if (address === undefined || address === email) continue;
+ await deleteVerification(context, identifier);
+ }
+ for (const [token, address] of mailedTo) {
+ if (address === email) continue;
+ await deleteVerification(
+ context,
+ resetLinkAddressIdentifier(user.id, token),
+ );
+ }
+}
+
+function deleteVerification(context: AuthEmailContext, identifier: string) {
+ return context.adapter.deleteMany({
+ model: "verification",
+ where: [{ field: "identifier", value: identifier }],
+ });
+}
diff --git a/autogpt_platform/frontend/src/lib/auth/set-password-link.ts b/autogpt_platform/frontend/src/lib/auth/set-password-link.ts
new file mode 100644
index 0000000000..33c72ebd5c
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/auth/set-password-link.ts
@@ -0,0 +1,70 @@
+import { randomBytes } from "node:crypto";
+import {
+ type AuthEmailContext,
+ createVerification,
+} from "./auth-email-cooldown";
+import { sendAuthEmail } from "./email";
+import { recordResetLinkAddress } from "./reset-link-address";
+
+// Better Auth's own default for a reset link.
+export const RESET_LINK_EXPIRES_IN_SECONDS = 60 * 60;
+
+/**
+ * Whether the account has been used, i.e. its password was set by someone who
+ * then got in. A sign-up while verification was off got a session, and the
+ * platform `User` row with it; with verification on, the row waits for the
+ * link. Sign-out deletes the session but never the row, so the row is the
+ * lasting evidence, and a session still counts in case provisioning failed.
+ *
+ * If the row or the sessions can't be read, the answer is `ifUnknown`: each
+ * caller picks the one that keeps a first registrant's password from
+ * surviving.
+ */
+export async function hasAccountBeenUsed(
+ context: AuthEmailContext,
+ userId: string,
+ hasPlatformUser: (userId: string) => Promise<boolean>,
+ ifUnknown: boolean,
+) {
+ const hasUser = await hasPlatformUser(userId).catch(() => ifUnknown);
+ if (hasUser) return true;
+ return context.adapter
+ .findMany({
+ model: "session",
+ where: [{ field: "userId", value: userId }],
+ limit: 1,
+ })
+ .then((sessions) => sessions.length > 0)
+ .catch(() => ifUnknown);
+}
+
+// The same token and link Better Auth's request-password-reset issues, so its
+// /reset-password endpoint redeems it, and opening it verifies the address it
+// was mailed to (reset-link-address.ts).
+export async function sendSetPasswordLink(
+ context: AuthEmailContext,
+ user: { id: string; email: string },
+ redirectTo: string,
+) {
+ const token = randomToken(18);
+ await createVerification(context, {
+ identifier: `reset-password:${token}`,
+ value: user.id,
+ expiresInSeconds: RESET_LINK_EXPIRES_IN_SECONDS,
+ });
+ await recordResetLinkAddress(context, {
+ token,
+ userId: user.id,
+ email: user.email,
+ expiresInSeconds: RESET_LINK_EXPIRES_IN_SECONDS,
+ });
+ await sendAuthEmail({
+ to: user.email,
+ type: "set_password",
+ url: `${context.baseURL}/reset-password/${token}?callbackURL=${encodeURIComponent(redirectTo)}`,
+ });
+}
+
+export function randomToken(bytes: number) {
+ return randomBytes(bytes).toString("base64url");
+}
diff --git a/autogpt_platform/frontend/src/lib/auth/team-email-policy.ts b/autogpt_platform/frontend/src/lib/auth/team-email-policy.ts
new file mode 100644
index 0000000000..820ee00267
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/auth/team-email-policy.ts
@@ -0,0 +1,39 @@
+import { APIError } from "better-auth/api";
+
+/**
+ * AutoGPT team addresses must sign up through Google, which only vouches for
+ * an address its owner controls. With email verification off, a password
+ * sign-up as `[email protected]` would otherwise get a session straight away and
+ * pass any `@agpt.co` allowlist entry (AUTH_SIGNUP_ALLOWLIST on dev/previews).
+ *
+ * The sign-up page refuses these addresses in the browser; this is the server
+ * half, so a direct POST to /api/auth/sign-up/email is refused too. Only the
+ * exact domain counts: `@previews.agpt.co` QA accounts keep password sign-up.
+ */
+
+const TEAM_EMAIL_DOMAIN = "agpt.co";
+const PASSWORD_SIGN_UP_PATH = "/sign-up/email";
+
+export const TEAM_EMAIL_REQUIRES_GOOGLE_CODE = "TEAM_EMAIL_REQUIRES_GOOGLE";
+export const TEAM_EMAIL_REQUIRES_GOOGLE_MESSAGE =
+ "Please use Google sign-in to create an account with an AutoGPT email.";
+
+export function isTeamEmail(email: string) {
+ const at = email.lastIndexOf("@");
+ if (at === -1) return false;
+ return email.slice(at + 1).toLowerCase() === TEAM_EMAIL_DOMAIN;
+}
+
+// Called from the user.create.before hook. `ctx` is the endpoint context that
+// is creating the user: null for internal callers, `/callback/:id` for OAuth.
+export function assertTeamEmailUsesGoogle(
+ email: string,
+ ctx: { path?: string } | null | undefined,
+) {
+ if (ctx?.path !== PASSWORD_SIGN_UP_PATH || !isTeamEmail(email)) return;
+
+ throw new APIError("FORBIDDEN", {
+ code: TEAM_EMAIL_REQUIRES_GOOGLE_CODE,
+ message: TEAM_EMAIL_REQUIRES_GOOGLE_MESSAGE,
+ });
+}
diff --git a/autogpt_platform/frontend/src/lib/auth/verification-link.ts b/autogpt_platform/frontend/src/lib/auth/verification-link.ts
new file mode 100644
index 0000000000..4de289f0ed
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/auth/verification-link.ts
@@ -0,0 +1,78 @@
+import { type AuthEmailContext, claimEmailSlot } from "./auth-email-cooldown";
+import { currentAuthEndpoint } from "./auth-endpoint";
+import { sendAuthEmail } from "./email";
+import { hasAccountBeenUsed, sendSetPasswordLink } from "./set-password-link";
+
+interface Args {
+ user: { id: string; email: string };
+ url: string;
+ request?: Request;
+ getAuthContext: () => Promise<AuthEmailContext>;
+ hasPlatformUser: (userId: string) => Promise<boolean>;
+ requireEmailVerification: boolean;
+ resetRedirectTo: string;
+}
+
+/**
+ * Better Auth's sendVerificationEmail. Sign-in sends one every time an
+ * unverified account signs in, and the login page calls auth.api directly,
+ * which Better Auth's rate limiter never sees, so whoever set the password
+ * could have us mail the address without limit. Sign-in and sign-up therefore
+ * share one email per address per window. If the cooldown can't be checked,
+ * the email still goes: a verification link matters more than the cap. With
+ * verification off, neither sends one. Nothing else is capped, flag or no
+ * flag: a change of email sends to the new address, and a retry must not be
+ * dropped while the page reports success.
+ *
+ * The resend button's own route skips that cap (it is capped per IP instead,
+ * see ip-email-cap.ts) because its answer has to say whether the email went.
+ * With verification required, its link would sign in whoever opens it, so for
+ * a used account, whose password someone other than the address owner may
+ * hold, it sends the set-password link a repeat sign-up gets instead.
+ */
+export async function sendVerificationLink(args: Args) {
+ const { user, url, request, getAuthContext } = args;
+ if (isResendRequest(request)) {
+ if (args.requireEmailVerification && (await sendsSetPasswordLink(args)))
+ return;
+ } else if (args.requireEmailVerification && (await isSignUpOrSignIn())) {
+ const claimed = await getAuthContext()
+ .then((context) => claimEmailSlot(context, "verify-email", user.email))
+ .catch((error: unknown) => {
+ console.error("Failed to check the verification email cooldown", {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return true;
+ });
+ if (!claimed) return;
+ }
+ await sendAuthEmail({ to: user.email, type: "verify_email", url });
+}
+
+async function sendsSetPasswordLink(args: Args) {
+ // No context means no set-password link either, and falling back to the
+ // verification link would sign in whoever opens it, so this one errors.
+ const context = await args.getAuthContext();
+ // Unknown counts as used: the set-password link is the safe one to send.
+ const used = await hasAccountBeenUsed(
+ context,
+ args.user.id,
+ args.hasPlatformUser,
+ true,
+ );
+ if (!used) return false;
+ await sendSetPasswordLink(context, args.user, args.resetRedirectTo);
+ return true;
+}
+
+// Read from Better Auth's endpoint context: the login page calls auth.api
+// directly, with no request.
+async function isSignUpOrSignIn() {
+ const { path } = await currentAuthEndpoint();
+ return path === "/sign-up/email" || path === "/sign-in/email";
+}
+
+function isResendRequest(request: Request | undefined) {
+ if (!request) return false;
+ return new URL(request.url).pathname.endsWith("/send-verification-email");
+}