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): signup consent line, marketing opt-out, and MailerLite gate (#15152)

John Ababseh73cae306b4f6
diff --git a/autogpt_platform/backend/.env.default b/autogpt_platform/backend/.env.default
index a599326ba7..5b2f84b343 100644
--- a/autogpt_platform/backend/.env.default
+++ b/autogpt_platform/backend/.env.default
@@ -269,6 +269,9 @@ MAILERLITE_CHANGELOG_GROUP_ID=
MAILERLITE_TRIAL_GROUP_ID=
# Everyone who opened Stripe checkout. Blank keeps them out of MailerLite.
MAILERLITE_CHECKOUT_GROUP_ID=
+# Secret of the MailerLite webhook for subscriber.unsubscribed, which points at
+# /api/email/mailerlite/webhook. Blank refuses every call to it.
+MAILERLITE_WEBHOOK_SECRET=
# Error Tracking
SENTRY_DSN=
diff --git a/autogpt_platform/backend/backend/api/features/mailerlite/__init__.py b/autogpt_platform/backend/backend/api/features/mailerlite/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/autogpt_platform/backend/backend/api/features/mailerlite/routes.py b/autogpt_platform/backend/backend/api/features/mailerlite/routes.py
new file mode 100644
index 0000000000..898b911c2d
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/mailerlite/routes.py
@@ -0,0 +1,113 @@
+"""MailerLite's webhook: an unsubscribe there is a refusal of marketing here.
+
+Someone who clicks "unsubscribe" in a MailerLite email has refused marketing as
+surely as someone who opted out at signup, so the account is marked opted out
+(`marketingOptOutSource = "email_unsubscribe"`) and the MailerLite gate keeps
+it out from then on (`notifications/consent.py`).
+
+Authenticated by MailerLite's signature, not by a user: the `Signature` header
+is the hex HMAC-SHA256 of the raw body under the webhook's secret
+(https://developers.mailerlite.com/docs/webhooks.html). With no secret
+configured every call is refused, since an empty key would let anyone sign.
+
+MailerLite retries anything but a 2xx, so a call that changes nothing (an
+unknown address, another event, a repeat) is still a 200.
+"""
+
+import hashlib
+import hmac
+import logging
+
+from fastapi import APIRouter, HTTPException, Request, Response
+from pydantic import BaseModel, TypeAdapter, ValidationError
+
+from backend.data.user import (
+ MARKETING_OPT_OUT_SOURCE_EMAIL_UNSUBSCRIBE,
+ record_marketing_opt_out_by_email,
+)
+from backend.util.settings import Settings
+
+logger = logging.getLogger(__name__)
+settings = Settings()
+
+# No auth dependency: MailerLite has no user, and the signature is the check.
+router = APIRouter()
+
+UNSUBSCRIBED_EVENT = "subscriber.unsubscribed"
+
+
+class MailerLiteSubscriber(BaseModel):
+ email: str
+
+
+class MailerLiteEvent(BaseModel):
+ """One event. A single delivery carries the subscriber itself, named by
+ `event`; a batched one wraps it as `subscriber`, named by `type`."""
+
+ event: str | None = None
+ type: str | None = None
+ email: str | None = None
+ subscriber: MailerLiteSubscriber | None = None
+
+ @property
+ def name(self) -> str | None:
+ return self.event or self.type
+
+ @property
+ def address(self) -> str | None:
+ return self.subscriber.email if self.subscriber else self.email
+
+ def unsubscribed_addresses(self) -> list[str]:
+ if self.name != UNSUBSCRIBED_EVENT or not self.address:
+ return []
+ return [self.address]
+
+
+class MailerLiteBatch(BaseModel):
+ events: list[MailerLiteEvent]
+
+ def unsubscribed_addresses(self) -> list[str]:
+ return [a for event in self.events for a in event.unsubscribed_addresses()]
+
+
+_PAYLOAD = TypeAdapter(MailerLiteBatch | MailerLiteEvent)
+
+
[email protected]("/mailerlite/webhook", summary="Handle MailerLite webhooks")
+async def mailerlite_webhook(request: Request) -> Response:
+ secret = settings.secrets.mailerlite_webhook_secret
+ if not secret:
+ logger.error(
+ "mailerlite_webhook: MAILERLITE_WEBHOOK_SECRET is not configured; "
+ "rejecting the request"
+ )
+ raise HTTPException(status_code=503, detail="Webhook not configured")
+
+ body = await request.body()
+ if not signature_matches(body, request.headers.get("signature"), secret):
+ raise HTTPException(status_code=401, detail="Invalid signature")
+
+ try:
+ payload = _PAYLOAD.validate_json(body)
+ except ValidationError:
+ raise HTTPException(status_code=400, detail="Invalid payload")
+
+ for address in payload.unsubscribed_addresses():
+ user_id = await record_marketing_opt_out_by_email(
+ address, MARKETING_OPT_OUT_SOURCE_EMAIL_UNSUBSCRIBE
+ )
+ if user_id:
+ logger.info(
+ f"mailerlite_webhook: user {user_id} unsubscribed in MailerLite; "
+ "recorded the marketing opt-out"
+ )
+ return Response(status_code=200)
+
+
+def signature_matches(body: bytes, signature: str | None, secret: str) -> bool:
+ if not signature:
+ return False
+ expected = hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
+ # Bytes: compare_digest raises on a non-ASCII str, and headers arrive as
+ # latin-1, so a junk header would otherwise be a 500, not a refusal.
+ return hmac.compare_digest(expected.encode(), signature.strip().lower().encode())
diff --git a/autogpt_platform/backend/backend/api/features/mailerlite/routes_test.py b/autogpt_platform/backend/backend/api/features/mailerlite/routes_test.py
new file mode 100644
index 0000000000..ba0d1d4e6b
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/mailerlite/routes_test.py
@@ -0,0 +1,220 @@
+"""MailerLite's unsubscribe webhook records a refusal, and only a call signed
+with the webhook's secret can."""
+
+import hashlib
+import hmac
+import json
+from collections.abc import Iterator
+from unittest.mock import AsyncMock
+
+import fastapi
+import fastapi.testclient
+import pytest
+import pytest_mock
+from fastapi.routing import APIRoute
+
+from backend.api.rest_api import app as real_app
+
+from . import routes
+from .routes import router
+
+SECRET = "4jQ3Y4UlLI"
+PATH = "/mailerlite/webhook"
+
+app = fastapi.FastAPI()
+app.include_router(router)
+client = fastapi.testclient.TestClient(app)
+
+
[email protected](scope="session")
+def server() -> None:
+ """Pure route logic; no live stack."""
+ return None
+
+
[email protected](scope="session", autouse=True)
+def graph_cleanup() -> Iterator[None]:
+ yield
+
+
[email protected](autouse=True)
+def secret(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(routes.settings.secrets, "mailerlite_webhook_secret", SECRET)
+
+
+def record(mocker: pytest_mock.MockFixture) -> AsyncMock:
+ return mocker.patch.object(
+ routes,
+ "record_marketing_opt_out_by_email",
+ new=AsyncMock(return_value="user-1"),
+ )
+
+
+def _unsubscribed(email: str = EMAIL) -> dict:
+ """Shaped like MailerLite's documented single-event payload."""
+ return {
+ "id": "100000000000000000",
+ "email": email,
+ "status": "unsubscribed",
+ "unsubscribed_at": "2026-10-07T08:26:04.000000Z",
+ "fields": {"name": ""},
+ "event": "subscriber.unsubscribed",
+ "account_id": 0,
+ }
+
+
+def _post(payload: object, secret: str = SECRET, signature: str | None = None):
+ body = json.dumps(payload).encode()
+ if signature is None:
+ signature = hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
+ return client.post(
+ PATH,
+ content=body,
+ headers={"Content-Type": "application/json", "Signature": signature},
+ )
+
+
+def test_an_unsubscribe_records_the_opt_out(record: AsyncMock) -> None:
+ response = _post(_unsubscribed())
+
+ assert response.status_code == 200
+ record.assert_awaited_once_with(EMAIL, "email_unsubscribe")
+
+
+def test_a_batched_unsubscribe_records_each_one(record: AsyncMock) -> None:
+ payload = {
+ "events": [
+ {"type": "subscriber.unsubscribed", "subscriber": {"email": EMAIL}},
+ {"type": "campaign.open", "subscriber": {"email": "[email protected]"}},
+ {
+ "type": "subscriber.unsubscribed",
+ "subscriber": {"email": "[email protected]"},
+ },
+ ],
+ "total": 3,
+ }
+
+ assert _post(payload).status_code == 200
+
+ assert [c.args[0] for c in record.await_args_list] == [
+ EMAIL,
+ ]
+
+
+ "payload",
+ [
+ pytest.param({**_unsubscribed(), "event": "subscriber.created"}, id="other"),
+ pytest.param({**_unsubscribed(), "email": None}, id="no-email"),
+ pytest.param({}, id="empty"),
+ ],
+)
+def test_anything_else_is_acknowledged_and_ignored(
+ record: AsyncMock, payload: dict
+) -> None:
+ assert _post(payload).status_code == 200
+ record.assert_not_awaited()
+
+
+def test_an_unknown_or_repeated_address_is_still_acknowledged(
+ record: AsyncMock,
+) -> None:
+ """MailerLite retries anything but a 2xx, and a retry changes nothing."""
+ record.return_value = None
+
+ assert _post(_unsubscribed()).status_code == 200
+ assert _post(_unsubscribed()).status_code == 200
+
+
+ "signature",
+ [
+ pytest.param("", id="missing"),
+ pytest.param("0" * 64, id="wrong"),
+ pytest.param(
+ hmac.new(b"other-secret", b"{}", hashlib.sha256).hexdigest(),
+ id="other-secret",
+ ),
+ ],
+)
+def test_a_badly_signed_call_is_refused(record: AsyncMock, signature: str) -> None:
+ response = _post(_unsubscribed(), signature=signature)
+
+ assert response.status_code == 401
+ record.assert_not_awaited()
+
+
+def test_a_non_ascii_signature_is_refused_not_a_crash(record: AsyncMock) -> None:
+ response = client.post(
+ PATH,
+ content=json.dumps(_unsubscribed()).encode(),
+ headers={"Content-Type": "application/json", "Signature": b"\xe9"},
+ )
+
+ assert response.status_code == 401
+ record.assert_not_awaited()
+
+
+def test_the_signature_covers_the_exact_body(record: AsyncMock) -> None:
+ """Signed over one body and sent with another: refused."""
+ signed = json.dumps(_unsubscribed()).encode()
+ signature = hmac.new(SECRET.encode(), signed, hashlib.sha256).hexdigest()
+
+ response = client.post(
+ PATH,
+ content=json.dumps(_unsubscribed("[email protected]")).encode(),
+ headers={"Signature": signature},
+ )
+
+ assert response.status_code == 401
+ record.assert_not_awaited()
+
+
+def test_without_a_secret_every_call_is_refused(
+ record: AsyncMock, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """An empty key would let anyone sign, so unconfigured means closed."""
+ monkeypatch.setattr(routes.settings.secrets, "mailerlite_webhook_secret", "")
+
+ response = _post(_unsubscribed(), secret="")
+
+ assert response.status_code == 503
+ record.assert_not_awaited()
+
+
+def test_a_signed_body_that_is_not_an_event_is_rejected(record: AsyncMock) -> None:
+ body = b"not json"
+ signature = hmac.new(SECRET.encode(), body, hashlib.sha256).hexdigest()
+
+ response = client.post(PATH, content=body, headers={"Signature": signature})
+
+ assert response.status_code == 400
+ record.assert_not_awaited()
+
+
+def test_a_failed_write_is_not_acknowledged(record: AsyncMock) -> None:
+ """A 5xx makes MailerLite retry, and the write is idempotent."""
+ record.side_effect = RuntimeError("database down")
+ failing = fastapi.testclient.TestClient(app, raise_server_exceptions=False)
+ body = json.dumps(_unsubscribed()).encode()
+ signature = hmac.new(SECRET.encode(), body, hashlib.sha256).hexdigest()
+
+ response = failing.post(PATH, content=body, headers={"Signature": signature})
+
+ assert response.status_code == 500
+
+
+def test_the_webhook_is_mounted_without_user_auth() -> None:
+ """MailerLite carries no user credential; a dependency here would refuse
+ every delivery. The signature is the only check."""
+ route = next(
+ r
+ for r in real_app.routes
+ if isinstance(r, APIRoute) and r.path == "/api/email/mailerlite/webhook"
+ )
+ assert route.methods == {"POST"}
+ assert route.dependant.dependencies == []
+ assert "security" not in real_app.openapi()["paths"][route.path]["post"]
diff --git a/autogpt_platform/backend/backend/api/features/orgs/regression_test.py b/autogpt_platform/backend/backend/api/features/orgs/regression_test.py
index 81ba0e5434..752e69eca7 100644
--- a/autogpt_platform/backend/backend/api/features/orgs/regression_test.py
+++ b/autogpt_platform/backend/backend/api/features/orgs/regression_test.py
@@ -1587,6 +1587,10 @@ class TestRegressionUserSettings:
mock_user.subscriptionTier = "NO_TIER"
mock_user.defaultChatAuthProvider = None
mock_user.defaultChatCredentialId = None
+ mock_user.termsAcceptedAt = None
+ mock_user.termsVersion = None
+ mock_user.marketingOptOutAt = None
+ mock_user.marketingOptOutSource = None
self.mock_user_actions.update = AsyncMock(return_value=mock_user)
from backend.data.user import update_user_timezone
diff --git a/autogpt_platform/backend/backend/api/features/user/routes.py b/autogpt_platform/backend/backend/api/features/user/routes.py
index 2cf4879902..c12771c868 100644
--- a/autogpt_platform/backend/backend/api/features/user/routes.py
+++ b/autogpt_platform/backend/backend/api/features/user/routes.py
@@ -8,12 +8,18 @@ from autogpt_libs.auth.jwt_utils import get_jwt_payload
from fastapi import APIRouter, Body, HTTPException, Query, Response, Security
from prisma.enums import BriefingFrequency
-from backend.api.model import TimezoneResponse, UpdateTimezoneRequest
+from backend.api.model import (
+ RecordUserConsentRequest,
+ TimezoneResponse,
+ UpdateTimezoneRequest,
+ UserConsentResponse,
+)
from backend.data.notifications import NotificationPreference, NotificationPreferenceDTO
from backend.data.user import (
get_or_create_user,
get_or_create_user_with_status,
get_user_notification_preference,
+ record_signup_consent,
update_user_email,
update_user_notification_preference,
update_user_timezone,
@@ -24,7 +30,7 @@ from backend.util.settings import Settings
settings = Settings()
logger = logging.getLogger(__name__)
-# Nothing is hoisted onto this router, tags included. Six of the seven routes
+# Nothing is hoisted onto this router, tags included. Seven of the eight routes
# take Security(requires_user); POST /auth/user/preferences/from-email takes
# none — it is reached from an email link and verifies its own signed token —
# so a router-level dependency would silently authenticate it.
@@ -118,6 +124,28 @@ async def update_user_timezone_route(
return TimezoneResponse(timezone=user.timezone)
+ "/auth/user/consent",
+ summary="Record user consent",
+ tags=["auth"],
+ dependencies=[Security(requires_user)],
+)
+async def record_user_consent_route(
+ user_id: Annotated[str, Security(get_user_id)], request: RecordUserConsentRequest
+) -> UserConsentResponse:
+ """Record the terms version accepted at signup and, if the user refused
+ marketing email, the opt-out. Idempotent; never clears an opt-out."""
+ user = await record_signup_consent(
+ user_id, request.terms_version, request.marketing_opt_out
+ )
+ return UserConsentResponse(
+ terms_accepted_at=user.terms_accepted_at,
+ terms_version=user.terms_version,
+ marketing_opt_out_at=user.marketing_opt_out_at,
+ marketing_opt_out_source=user.marketing_opt_out_source,
+ )
+
+
@router.get(
"/auth/user/preferences",
summary="Get notification preferences",
diff --git a/autogpt_platform/backend/backend/api/features/user/routes_test.py b/autogpt_platform/backend/backend/api/features/user/routes_test.py
index 5ac2387f1d..0c17b4b5d6 100644
--- a/autogpt_platform/backend/backend/api/features/user/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/user/routes_test.py
@@ -1,15 +1,34 @@
import json
+import re
+import uuid
+from collections.abc import AsyncIterator
from datetime import datetime, timezone
-from unittest.mock import Mock
+from pathlib import Path
+from unittest.mock import AsyncMock, Mock
import fastapi
import fastapi.testclient
+import httpx
import pytest
import pytest_mock
+from autogpt_libs.auth.jwt_utils import get_jwt_payload
from fastapi.routing import APIRoute
+from prisma.actions import UserActions
+from prisma.models import User as PrismaUser
from pytest_snapshot.plugin import Snapshot
+from backend.api.model import RECOGNIZED_TERMS_VERSIONS, UserConsentResponse
from backend.api.rest_api import app as real_app
+from backend.data.model import User
+from backend.data.notifications import AudienceAction, NotificationResult
+from backend.data.user import (
+ get_or_create_user,
+ get_user_by_email,
+ get_user_by_id,
+ record_marketing_opt_out_by_email,
+ record_signup_consent,
+)
+from backend.util.exceptions import DatabaseError, NotFoundError
from .routes import router
@@ -139,6 +158,325 @@ def test_update_user_email_route(
)
+def _consented_user(user_id: str, opted_out_at: datetime | None) -> User:
+ accepted_at = datetime(2026, 10, 2, 12, 0, tzinfo=timezone.utc)
+ return User(
+ id=user_id,
+ created_at=accepted_at,
+ updated_at=accepted_at,
+ timezone="Europe/London",
+ terms_accepted_at=accepted_at,
+ terms_version="2026-10",
+ marketing_opt_out_at=opted_out_at,
+ marketing_opt_out_source="signup" if opted_out_at else None,
+ )
+
+
+def test_record_user_consent_route(
+ mocker: pytest_mock.MockFixture,
+ test_user_id: str,
+) -> None:
+ """Records for the caller's own account, whatever the body claims, and
+ answers with the four consent fields only."""
+ opted_out_at = datetime(2026, 10, 2, 12, 1, tzinfo=timezone.utc)
+ record = mocker.patch(
+ "backend.api.features.user.routes.record_signup_consent",
+ return_value=_consented_user(test_user_id, opted_out_at),
+ )
+
+ response = client.post(
+ "/auth/user/consent",
+ json={
+ "terms_version": "2026-10",
+ "marketing_opt_out": True,
+ "user_id": "someone-else",
+ },
+ )
+
+ assert response.status_code == 200
+ record.assert_awaited_once_with(test_user_id, "2026-10", True)
+ assert response.json() == {
+ "terms_accepted_at": "2026-10-02T12:00:00Z",
+ "terms_version": "2026-10",
+ "marketing_opt_out_at": "2026-10-02T12:01:00Z",
+ "marketing_opt_out_source": "signup",
+ }
+
+
+def test_record_user_consent_route_answers_404_for_a_deleted_account(
+ mocker: pytest_mock.MockFixture, mock_jwt_user
+) -> None:
+ """Through the real application, whose handlers turn NotFoundError into a
+ 404 rather than a 500."""
+ mocker.patch(
+ "backend.api.features.user.routes.record_signup_consent",
+ new=AsyncMock(side_effect=NotFoundError("User not found with ID: x")),
+ )
+ real_app.dependency_overrides[get_jwt_payload] = mock_jwt_user["get_jwt_payload"]
+ try:
+ response = fastapi.testclient.TestClient(real_app).post(
+ "/api/auth/user/consent",
+ json={"terms_version": "2026-10", "marketing_opt_out": True},
+ )
+ finally:
+ real_app.dependency_overrides.pop(get_jwt_payload, None)
+
+ assert response.status_code == 404
+
+
[email protected]("terms_version", sorted(RECOGNIZED_TERMS_VERSIONS))
+def test_record_user_consent_route_accepts_a_recognized_version(
+ mocker: pytest_mock.MockFixture,
+ test_user_id: str,
+ terms_version: str,
+) -> None:
+ record = mocker.patch(
+ "backend.api.features.user.routes.record_signup_consent",
+ return_value=_consented_user(test_user_id, None),
+ )
+
+ response = client.post(
+ "/auth/user/consent",
+ json={"terms_version": terms_version, "marketing_opt_out": False},
+ )
+
+ assert response.status_code == 200
+ record.assert_awaited_once_with(test_user_id, terms_version, False)
+
+
+ "body",
+ [
+ pytest.param(None, id="no-body"),
+ pytest.param({"marketing_opt_out": False}, id="no-terms-version"),
+ pytest.param({"terms_version": "2026-10"}, id="no-marketing-opt-out"),
+ pytest.param(
+ {"terms_version": "", "marketing_opt_out": False},
+ id="empty-terms-version",
+ ),
+ pytest.param(
+ {"terms_version": " ", "marketing_opt_out": False},
+ id="blank-terms-version",
+ ),
+ pytest.param(
+ {"terms_version": "latest", "marketing_opt_out": False},
+ id="undated-terms-version",
+ ),
+ pytest.param(
+ {"terms_version": "2026-10; x", "marketing_opt_out": False},
+ id="terms-version-with-a-suffix",
+ ),
+ pytest.param(
+ {
+ "terms_version": "\u0662\u0660\u0662\u0666-\u0661\u0660",
+ "marketing_opt_out": False,
+ },
+ id="terms-version-in-non-ascii-digits",
+ ),
+ pytest.param(
+ {"terms_version": "v" * 33, "marketing_opt_out": False},
+ id="terms-version-over-32-characters",
+ ),
+ pytest.param(
+ {"terms_version": "2026-10-15", "marketing_opt_out": False},
+ id="well-formed-but-never-shown",
+ ),
+ pytest.param(
+ {"terms_version": "9999-99", "marketing_opt_out": False},
+ id="impossible-date",
+ ),
+ pytest.param(
+ {"terms_version": "2020-01", "marketing_opt_out": False},
+ id="older-terms-than-the-page-shows",
+ ),
+ ],
+)
+def test_record_user_consent_route_rejects_an_invalid_body(
+ mocker: pytest_mock.MockFixture,
+ body: dict[str, str | bool] | None,
+) -> None:
+ record = mocker.patch("backend.api.features.user.routes.record_signup_consent")
+
+ response = client.post("/auth/user/consent", json=body)
+
+ assert response.status_code == 422
+ record.assert_not_called()
+
+
+async def _reset_consent(user_id: str) -> None:
+ row = await PrismaUser.prisma().update(
+ where={"id": user_id},
+ data={
+ "termsAcceptedAt": None,
+ "termsVersion": None,
+ "marketingOptOutAt": None,
+ "marketingOptOutSource": None,
+ },
+ )
+ assert row is not None
+ get_user_by_id.cache_delete(user_id)
+ get_user_by_email.cache_delete(row.email)
+ get_or_create_user.cache_clear()
+
+
+async def _email_of(user_id: str) -> str:
+ """The shared test user's stored address. Not necessarily
+ [email protected]: the default user may have created the row first."""
+ row = await PrismaUser.prisma().find_unique_or_raise(where={"id": user_id})
+ return row.email
+
+
+async def consent_reset(setup_test_user: str) -> AsyncIterator[str]:
+ """The test user is shared by the whole session, so the consent this
+ module writes onto it is wiped before and after."""
+ await _reset_consent(setup_test_user)
+ yield setup_test_user
+ await _reset_consent(setup_test_user)
+
+
+def _stored_consent(row: PrismaUser) -> UserConsentResponse:
+ return UserConsentResponse(
+ terms_accepted_at=row.termsAcceptedAt,
+ terms_version=row.termsVersion,
+ marketing_opt_out_at=row.marketingOptOutAt,
+ marketing_opt_out_source=row.marketingOptOutSource,
+ )
+
+
+async def test_record_user_consent_route_is_idempotent_in_the_database(
+ consent_reset: str, mocker: pytest_mock.MockFixture
+) -> None:
+ """A retried signup write keeps the first stamps, and a later call without
+ the opt-out never takes it back. Only the first call, which recorded the
+ refusal, unsubscribes the account in MailerLite."""
+ queued = mocker.patch(
+ "backend.data.user.queue_audience_change",
+ new=AsyncMock(return_value=NotificationResult(success=True, message="")),
+ )
+ consent = {"terms_version": "2026-10", "marketing_opt_out": True}
+ where = {"id": consent_reset}
+
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as http:
+ first = await http.post("/auth/user/consent", json=consent)
+ stored = _stored_consent(
+ await PrismaUser.prisma().find_unique_or_raise(where=where)
+ )
+ retried = await http.post("/auth/user/consent", json=consent)
+ after_retry = await PrismaUser.prisma().find_unique_or_raise(where=where)
+ declined = await http.post(
+ "/auth/user/consent", json={**consent, "marketing_opt_out": False}
+ )
+ after_decline = await PrismaUser.prisma().find_unique_or_raise(where=where)
+
+ assert [first.status_code, retried.status_code, declined.status_code] == [200] * 3
+ assert stored.terms_accepted_at is not None
+ assert stored.terms_version == "2026-10"
+ assert stored.marketing_opt_out_at is not None
+ assert stored.marketing_opt_out_source == "signup"
+ assert UserConsentResponse.model_validate(first.json()) == stored
+ assert _stored_consent(after_retry) == stored
+ assert retried.json() == first.json()
+ assert _stored_consent(after_decline) == stored
+ assert declined.json() == first.json()
+ queued.assert_awaited_once()
+ assert queued.await_args.args[0].action is AudienceAction.UNSUBSCRIBE
+ assert queued.await_args.args[0].user_id == consent_reset
+
+
+async def test_a_failed_opt_out_write_leaves_neither_half(
+ consent_reset: str, mocker: pytest_mock.MockFixture
+) -> None:
+ """The terms and the opt-out land together or not at all: when the opt-out
+ write fails, the terms stamp made before it in the same transaction is
+ rolled back, so a retry starts from a clean row."""
+ mocker.patch.object(
+ UserActions,
+ "update_many",
+ new=AsyncMock(side_effect=RuntimeError("opt-out write failed")),
+ )
+
+ with pytest.raises(DatabaseError):
+ await record_signup_consent(consent_reset, "2026-10", True)
+
+ row = await PrismaUser.prisma().find_unique_or_raise(where={"id": consent_reset})
+ assert _stored_consent(row) == UserConsentResponse()
+
+
+async def test_a_mailerlite_unsubscribe_is_recorded_in_the_database(
+ consent_reset: str,
+) -> None:
+ """Matched whatever the address's case, and the first refusal wins: a
+ redelivered unsubscribe keeps the first date."""
+ where = {"id": consent_reset}
+ email = await _email_of(consent_reset)
+
+ first = await record_marketing_opt_out_by_email(email.upper(), "email_unsubscribe")
+ stored = await PrismaUser.prisma().find_unique_or_raise(where=where)
+ repeated = await record_marketing_opt_out_by_email(email, "email_unsubscribe")
+ after = await PrismaUser.prisma().find_unique_or_raise(where=where)
+ cached = await get_user_by_id(consent_reset)
+
+ assert first == consent_reset
+ assert repeated is None
+ assert stored.marketingOptOutAt is not None
+ assert stored.marketingOptOutSource == "email_unsubscribe"
+ assert _stored_consent(after) == _stored_consent(stored)
+ assert cached.marketing_opt_out_at == stored.marketingOptOutAt
+
+
+async def test_an_unsubscribe_never_matches_another_account_by_wildcard() -> None:
+ """`_` is an ILIKE wildcard: an unsubscribe for `john_smith-…` must not
+ opt out the account `john.smith-…`."""
+ user_id = str(uuid.uuid4())
+ await PrismaUser.prisma().create(
+ data={"id": user_id, "email": f"john.smith-{user_id}@example.com"}
+ )
+ try:
+ recorded = await record_marketing_opt_out_by_email(
+ f"JOHN_SMITH-{user_id}@example.com", "email_unsubscribe"
+ )
+ row = await PrismaUser.prisma().find_unique_or_raise(where={"id": user_id})
+ finally:
+ await PrismaUser.prisma().delete_many(where={"id": user_id})
+
+ assert recorded is None
+ assert row.marketingOptOutAt is None
+
+
+async def test_an_unsubscribe_keeps_a_signup_refusal(
+ consent_reset: str, mocker: pytest_mock.MockFixture
+) -> None:
+ mocker.patch(
+ "backend.data.user.queue_audience_change",
+ new=AsyncMock(return_value=NotificationResult(success=True, message="")),
+ )
+ await record_signup_consent(consent_reset, "2026-10", True)
+ signed_up = await PrismaUser.prisma().find_unique_or_raise(
+ where={"id": consent_reset}
+ )
+
+ email = await _email_of(consent_reset)
+
+ assert await record_marketing_opt_out_by_email(email, "email_unsubscribe") is None
+ after = await PrismaUser.prisma().find_unique_or_raise(where={"id": consent_reset})
+ assert after.marketingOptOutSource == "signup"
+ assert after.marketingOptOutAt == signed_up.marketingOptOutAt
+
+
+def test_the_frontend_terms_version_is_recognized() -> None:
+ """The signup page sends lib/legal.ts's TERMS_VERSION. A bump there that
+ the backend does not recognize would fail every consent write."""
+ legal = Path(__file__).parents[5] / "frontend/src/lib/legal.ts"
+ shown = re.search(r'TERMS_VERSION = "([^"]+)"', legal.read_text())
+
+ assert shown is not None
+ assert shown.group(1) in RECOGNIZED_TERMS_VERSIONS
+
+
# Invalid request tests
def test_invalid_json_request() -> None:
"""Test endpoint with invalid JSON"""
@@ -150,7 +488,7 @@ def test_invalid_json_request() -> None:
assert response.status_code == 422
-# The login surface: six routes authenticate, one deliberately does not.
+# The login surface: seven routes authenticate, one deliberately does not.
# Nothing is hoisted onto this router — a router-level dependency would
# silently authenticate the email-link route.
AUTHENTICATED = {
@@ -158,6 +496,7 @@ AUTHENTICATED = {
("post", "/api/auth/user/email"),
("get", "/api/auth/user/timezone"),
("post", "/api/auth/user/timezone"),
+ ("post", "/api/auth/user/consent"),
("get", "/api/auth/user/preferences"),
("post", "/api/auth/user/preferences"),
}
diff --git a/autogpt_platform/backend/backend/api/model.py b/autogpt_platform/backend/backend/api/model.py
index 094bc7412e..068c57fdbe 100644
--- a/autogpt_platform/backend/backend/api/model.py
+++ b/autogpt_platform/backend/backend/api/model.py
@@ -1,4 +1,5 @@
import enum
+from datetime import datetime
from typing import Any, Literal, Optional
import pydantic
@@ -72,6 +73,38 @@ class UpdateTimezoneRequest(pydantic.BaseModel):
timezone: TimeZoneName
+# Every terms and privacy policy version the signup page can show. Add a new
+# one here, and deploy it, before the frontend's TERMS_VERSION (lib/legal.ts)
+# moves to it; routes_test fails if the frontend's version is missing here.
+RECOGNIZED_TERMS_VERSIONS = frozenset({"2026-10"})
+
+
+class RecordUserConsentRequest(pydantic.BaseModel):
+ # The frontend's TERMS_VERSION, e.g. "2026-10", or "2026-10-15" for a
+ # second change in one month. ASCII digits only: `\d` would also take
+ # other scripts' digits.
+ terms_version: str = pydantic.Field(
+ min_length=1, max_length=32, pattern=r"^[0-9]{4}-[0-9]{2}(-[0-9]{2})?$"
+ )
+ marketing_opt_out: bool
+
+ @pydantic.field_validator("terms_version")
+ @classmethod
+ def _recognized(cls, terms_version: str) -> str:
+ """Only a version the signup page has shown can be recorded, so a
+ caller cannot claim acceptance of terms that were never offered."""
+ if terms_version not in RECOGNIZED_TERMS_VERSIONS:
+ raise ValueError("Unrecognized terms version")
+ return terms_version
+
+
+class UserConsentResponse(pydantic.BaseModel):
+ terms_accepted_at: Optional[datetime] = None
+ terms_version: Optional[str] = None
+ marketing_opt_out_at: Optional[datetime] = None
+ marketing_opt_out_source: Optional[str] = None
+
+
class NotificationPayload(pydantic.BaseModel):
type: str
event: str
diff --git a/autogpt_platform/backend/backend/api/rest_api.py b/autogpt_platform/backend/backend/api/rest_api.py
index 78ece733f1..4f41fdcb3f 100644
--- a/autogpt_platform/backend/backend/api/rest_api.py
+++ b/autogpt_platform/backend/backend/api/rest_api.py
@@ -50,6 +50,7 @@ import backend.api.features.home.routes as home_routes
import backend.api.features.library.db
import backend.api.features.library.model
import backend.api.features.library.routes
+import backend.api.features.mailerlite.routes as mailerlite_routes
import backend.api.features.mcp.routes as mcp_routes
import backend.api.features.memory.routes as memory_routes
import backend.api.features.oauth
@@ -568,6 +569,11 @@ app.include_router(
tags=["v1", "email"],
prefix="/api/email",
)
+app.include_router(
+ mailerlite_routes.router,
+ tags=["v1", "email"],
+ prefix="/api/email",
+)
app.include_router(
chat_routes.router,
tags=["v2", "chat"],
diff --git a/autogpt_platform/backend/backend/cli/mailerlite_backfill.py b/autogpt_platform/backend/backend/cli/mailerlite_backfill.py
index 14cc7054a1..ae61a25a25 100644
--- a/autogpt_platform/backend/backend/cli/mailerlite_backfill.py
+++ b/autogpt_platform/backend/backend/cli/mailerlite_backfill.py
@@ -43,7 +43,8 @@ def mailerlite_backfill_command(
gets its subscription_status and dates. Nobody is created here: a Stripe
customer alone does not mean they opened checkout (the billing portal
makes one too), so new people come only from mailerlite-checkout-backfill.
- Accounts without a Stripe customer are never read.
+ Accounts without a Stripe customer are never read. Accounts that opted out
+ of marketing are never written, removals included.
Dry run by default: prints counts and one pseudonymised line per customer,
and writes nothing. Idempotent, so a partial or repeated --apply is safe,
@@ -69,6 +70,7 @@ def mailerlite_checkout_backfill_command(apply: bool, yes: bool):
checkout_opened_date (their first session), email_type, signin_method,
country and country_code (the Stripe billing address, else the browser's
timezone), country_source and exclude_de_at, plus their status and dates.
+ Openers who opted out of marketing are counted and never written.
Visits one person every two seconds, re-reading each just before the
write so nothing the live checkout event wrote meanwhile is overwritten.
@@ -273,6 +275,7 @@ async def _people(subscriptions: "dict[str, list[Subscription]]") -> "list[Perso
],
stripe_customer_id=user.stripeCustomerId,
timezone=user.timezone,
+ marketing_opt_out_at=user.marketingOptOutAt,
)
)
if len(page) < _ACCOUNT_PAGE:
@@ -287,17 +290,18 @@ def _customer(person: "Person") -> "Customer":
user_id=person.user_id,
email=person.email,
subscriptions=person.subscriptions,
+ marketing_opt_out_at=person.marketing_opt_out_at,
)
def _report(changes: "list[PlannedChange]", unmatched: int) -> None:
from collections import Counter
- from backend.notifications.mailerlite import _pseudonym
+ from backend.notifications.mailerlite import pseudonym
for change in changes:
click.echo(
- f"{_pseudonym(change.customer.email)} {change.standing.value:<16} "
+ f"{pseudonym(change.customer.email)} {change.standing.value:<16} "
+ ", ".join(d.value for d in change.decisions)
)
counts = Counter(d.value for c in changes for d in c.decisions)
@@ -317,6 +321,7 @@ def _report_fields(plan: "FieldPlan", accounts: int) -> None:
for status, count in plan.statuses.items():
click.echo(f" {status.value}: {count}")
click.echo(f" invalid email (skipped): {plan.invalid}")
+ click.echo(f" opted out of marketing (skipped): {plan.opted_out}")
click.echo(
f"{len(plan.changes)} existing MailerLite subscribers to update "
"(nobody is created here; see mailerlite-checkout-backfill)"
@@ -463,6 +468,7 @@ def _report_checkout(
)
click.echo(" Accounts without a Stripe customer: never read or written")
click.echo(f" invalid email (skipped): {plan.invalid}")
+ click.echo(f" opted out of marketing (skipped): {plan.opted_out}")
click.echo(f"\nCountry source: {counts(plan.country_sources)}")
click.echo(f"Countries: {counts(plan.countries)}")
click.echo(f"exclude_de_at=yes: {plan.exclude_de_at}")
diff --git a/autogpt_platform/backend/backend/cli/mailerlite_backfill_test.py b/autogpt_platform/backend/backend/cli/mailerlite_backfill_test.py
index a7d5647613..0b19561888 100644
--- a/autogpt_platform/backend/backend/cli/mailerlite_backfill_test.py
+++ b/autogpt_platform/backend/backend/cli/mailerlite_backfill_test.py
@@ -1,11 +1,24 @@
"""A checkout backfill that could not write everyone fails as a whole, after
-reporting, so a Job or script never reads a partial run as done."""
+reporting, so a Job or script never reads a partial run as done. An account
+that opted out of marketing reaches every backfill's plan as such, and every
+report counts it."""
+
+from datetime import UTC, datetime
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
import click
import pytest
from click.testing import CliRunner
from backend.cli import mailerlite_backfill as cli
+from backend.notifications import checkout_backfill, mailerlite_backfill
+from backend.notifications import mailerlite_field_backfill as field_backfill
+from backend.notifications.mailerlite_backfill import Audience, Subscription
+from backend.notifications.mailerlite_field_backfill import Person
+
+CREATED = datetime(2026, 7, 14, tzinfo=UTC)
+OPTED_OUT = datetime(2026, 10, 2, tzinfo=UTC)
# The root conftest spins a full test server for every test via an autouse
@@ -45,3 +58,69 @@ def test_the_command_exits_non_zero_when_anyone_failed(monkeypatch):
assert result.exit_code == 1
assert "4 ok, 1 failed" in result.output
assert "1 checkout openers were not written" in result.output
+
+
+def _account(user_id: str, opted_out_at: datetime | None) -> SimpleNamespace:
+ """A `User` row as `_people` reads it."""
+ return SimpleNamespace(
+ id=user_id,
+ email=f"{user_id}@example.com",
+ createdAt=CREATED,
+ stripeCustomerId=f"cus_{user_id}",
+ timezone=None,
+ marketingOptOutAt=opted_out_at,
+ )
+
+
+async def test_each_account_carries_its_opt_out_into_the_backfills():
+ users = MagicMock(
+ find_many=AsyncMock(
+ return_value=[_account("out", OPTED_OUT), _account("in", None)]
+ )
+ )
+ trials = MagicMock(find_many=AsyncMock(return_value=[]))
+ with (
+ patch("prisma.models.User.prisma", return_value=users),
+ patch("prisma.models.SubscriptionTrial.prisma", return_value=trials),
+ ):
+ out, kept = await cli._people(
+ {"cus_out": [Subscription(status="active")], "cus_in": []}
+ )
+ assert out.marketing_opt_out_at == OPTED_OUT
+ assert kept.marketing_opt_out_at is None
+ assert cli._customer(out).marketing_opt_out_at == OPTED_OUT
+ assert cli._customer(kept).marketing_opt_out_at is None
+
+
+def test_every_report_counts_the_opted_out(capsys):
+ person = Person(
+ user_id="out",
+ created_at=CREATED,
+ subscriptions=[Subscription(status="active")],
+ stripe_customer_id="cus_out",
+ marketing_opt_out_at=OPTED_OUT,
+ )
+ cli._report(
+ [
+ mailerlite_backfill.decide(
+ cli._customer(person),
+ Audience(tour={}, changelog={}, trial={}),
+ trial_enabled=True,
+ )
+ ],
+ unmatched=0,
+ )
+ cli._report_fields(field_backfill.plan([person], {}, create=False), 1)
+ cli._report_checkout(
+ checkout_backfill.plan(
+ [checkout_backfill.Opener(person=person, opened_at=1788305400)], {}, {}
+ ),
+ sessions_unlinked=0,
+ customers_without_session=0,
+ )
+ out = capsys.readouterr().out
+ assert "skip_opted_out: 1" in out
+ assert out.count("opted out of marketing (skipped): 1") == 2
+ assert "[email protected]" not in out
diff --git a/autogpt_platform/backend/backend/data/checkout_audience.py b/autogpt_platform/backend/backend/data/checkout_audience.py
index 36f99e7335..4dcd5380de 100644
--- a/autogpt_platform/backend/backend/data/checkout_audience.py
+++ b/autogpt_platform/backend/backend/data/checkout_audience.py
@@ -8,6 +8,9 @@ strongest country it has seen (`audience_enrichment.merge_with_held`).
It runs in the background and never raises. A checkout must not wait on, or
fail because of, MailerLite bookkeeping; the backfill catches anyone missed.
+
+Nothing is queued for an account that opted out of marketing: it never enters
+MailerLite (`notifications/consent.py`).
"""
import asyncio
@@ -20,6 +23,7 @@ from backend.data.db import query_raw_with_schema
from backend.data.notifications import AudienceAction
from backend.data.user import get_user_by_id
from backend.notifications.audience_enrichment import checkout_fields
+from backend.notifications.consent import audience_change_allowed
from backend.notifications.subscriber_fields import queue_fields
logger = logging.getLogger(__name__)
@@ -61,6 +65,8 @@ async def queue_checkout_opened(
) -> None:
try:
user = await get_user_by_id(user_id)
+ if not audience_change_allowed(user, AudienceAction.CHECKOUT_OPENED):
+ return
fields = checkout_fields(
email=user.email,
created_at=user.created_at,
diff --git a/autogpt_platform/backend/backend/data/checkout_audience_test.py b/autogpt_platform/backend/backend/data/checkout_audience_test.py
index 999abab51d..39c6a81748 100644
--- a/autogpt_platform/backend/backend/data/checkout_audience_test.py
+++ b/autogpt_platform/backend/backend/data/checkout_audience_test.py
@@ -3,6 +3,7 @@ each of the three checkout routes and the completed-checkout webhook, and none
of it can cost the checkout or fail the webhook."""
import inspect
+import logging
import re
from datetime import UTC, datetime
from types import SimpleNamespace
@@ -22,7 +23,9 @@ from backend.data.notifications import (
SubscriberField,
)
from backend.data.subscription_trial_checkout import TrialUnavailable
-from backend.notifications import subscriber_fields
+from backend.notifications import consent, subscriber_fields
+from backend.notifications.consent_test import _cached_before_consent
+from backend.notifications.mailerlite import pseudonym
CREATED = datetime(2026, 7, 14, 9, 0, tzinfo=UTC)
@@ -53,7 +56,10 @@ def queued(monkeypatch):
"get_user_by_id",
AsyncMock(
return_value=SimpleNamespace(
- email=EMAIL, created_at=CREATED, timezone="Europe/Vienna"
+ email=EMAIL,
+ created_at=CREATED,
+ timezone="Europe/Vienna",
+ marketing_opt_out_at=None,
)
),
)
@@ -86,6 +92,73 @@ async def test_a_failure_never_reaches_the_checkout(queued, monkeypatch):
queued.assert_not_awaited()
+def _opt_out(monkeypatch) -> tuple[AsyncMock, AsyncMock]:
+ """The account refused marketing at signup."""
+ lookup = AsyncMock(
+ return_value=SimpleNamespace(
+ email=EMAIL,
+ created_at=CREATED,
+ timezone="Europe/Vienna",
+ marketing_opt_out_at=CREATED,
+ )
+ )
+ providers = AsyncMock(return_value=["credential"])
+ monkeypatch.setattr(checkout_audience, "get_user_by_id", lookup)
+ monkeypatch.setattr(checkout_audience, "signin_providers", providers)
+ return lookup, providers
+
+
+async def test_an_opted_out_opener_is_never_queued(queued, monkeypatch, caplog):
+ _, providers = _opt_out(monkeypatch)
+ with caplog.at_level(logging.DEBUG, logger=consent.__name__):
+ await checkout_audience.queue_checkout_opened("user-1", ip_country="US")
+ queued.assert_not_awaited()
+ providers.assert_not_awaited()
+ assert pseudonym(EMAIL) in caplog.text
+ assert EMAIL not in caplog.text
+
+
+async def test_an_opener_cached_before_the_consent_fields_queues_nothing(
+ queued, monkeypatch, caplog
+):
+ """During a rolling deploy the shared cache can hand back a user pickled by
+ the previous release, with no opt-out to read. It is skipped, not reported
+ as a failed checkout."""
+ monkeypatch.setattr(
+ checkout_audience,
+ "get_user_by_id",
+ AsyncMock(return_value=_cached_before_consent()),
+ )
+ with caplog.at_level(logging.DEBUG, logger=checkout_audience.__name__):
+ await checkout_audience.queue_checkout_opened("user-1", ip_country="US")
+ queued.assert_not_awaited()
+ assert [r for r in caplog.records if r.levelno >= logging.ERROR] == []
+
+
+async def test_an_opted_out_customers_completed_checkout_queues_nothing(
+ queued, monkeypatch
+):
+ lookup, _ = _opt_out(monkeypatch)
+ with patch(
+ "prisma.models.User.prisma",
+ return_value=_user_prisma(SimpleNamespace(id="user-1")),
+ ):
+ await checkout_audience.record_checkout_completed(
+ {
+ "customer": "cus_1",
+ "created": 1788305400,
+ "customer_details": {"address": {"country": "DE"}},
+ }
+ )
+ for task in list(checkout_audience._tasks):
+ await task
+ lookup.assert_awaited_once_with("user-1")
+ queued.assert_not_awaited()
+
+
def _user_prisma(user):
return MagicMock(find_first=AsyncMock(return_value=user))
diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.py
index fa9e6e2b8d..2168a0448d 100644
--- a/autogpt_platform/backend/backend/data/db_manager.py
+++ b/autogpt_platform/backend/backend/data/db_manager.py
@@ -187,6 +187,7 @@ from backend.data.user import (
get_user_notification_preference,
get_user_subscription_tier,
heal_orphaned_auth_identities,
+ is_marketing_opted_out,
release_welcome_email,
set_last_briefing_at,
set_user_credentials,
@@ -703,6 +704,8 @@ class DatabaseManager(AppService):
# second process has no Prisma connection, so these cross the RPC.
get_billing_email_recipient = _(get_billing_email_recipient)
claim_welcome_email = _(claim_welcome_email)
+ # Read by the audience consumer right before each MailerLite write.
+ is_marketing_opted_out = _(is_marketing_opted_out)
release_welcome_email = _(release_welcome_email)
update_briefing_content = _(update_briefing_content)
@@ -881,6 +884,7 @@ class DatabaseManagerAsyncClient(AppServiceClient):
set_last_briefing_at = d.set_last_briefing_at
get_billing_email_recipient = d.get_billing_email_recipient
claim_welcome_email = d.claim_welcome_email
+ is_marketing_opted_out = d.is_marketing_opted_out
release_welcome_email = d.release_welcome_email
# ============ Morning Briefing ============ #
diff --git a/autogpt_platform/backend/backend/data/db_manager_test.py b/autogpt_platform/backend/backend/data/db_manager_test.py
index 377b9b4ed7..98badbf370 100644
--- a/autogpt_platform/backend/backend/data/db_manager_test.py
+++ b/autogpt_platform/backend/backend/data/db_manager_test.py
@@ -22,3 +22,8 @@ def test_bot_analytics_methods_registered() -> None:
def test_add_store_agent_rpc_request_schema_is_constructible() -> None:
manager = DatabaseManager()
manager._create_fastapi_endpoint(manager.add_store_agent_to_library)
+
+
+def test_the_audience_consumer_can_read_the_opt_out() -> None:
+ assert hasattr(DatabaseManager, "is_marketing_opted_out")
+ assert hasattr(DatabaseManagerAsyncClient, "is_marketing_opted_out")
diff --git a/autogpt_platform/backend/backend/data/model.py b/autogpt_platform/backend/backend/data/model.py
index 8a517f107a..ba6d0b33b7 100644
--- a/autogpt_platform/backend/backend/data/model.py
+++ b/autogpt_platform/backend/backend/data/model.py
@@ -97,6 +97,20 @@ class User(BaseModel):
description="User timezone (IANA timezone identifier or 'not-set')",
)
+ # Consent captured at signup (see record_signup_consent).
+ terms_accepted_at: Optional[datetime] = Field(
+ None, description="When the user accepted the terms and privacy policy"
+ )
+ terms_version: Optional[str] = Field(
+ None, description="Version of the terms and privacy policy accepted"
+ )
+ marketing_opt_out_at: Optional[datetime] = Field(
+ None, description="When the user opted out of marketing email"
+ )
+ marketing_opt_out_source: Optional[str] = Field(
+ None, description="Where the marketing opt-out came from"
+ )
+
# Default Otto connection for chats nobody routed explicitly. Kept as
# plain strings here: the data layer stores the choice, the copilot layer
# decides what a given value means (and treats one it doesn't recognise as
@@ -156,6 +170,10 @@ class User(BaseModel):
alerts_enabled=prisma_user.alertsEnabled,
notify_on_store_verdict=prisma_user.notifyOnStoreVerdict,
timezone=prisma_user.timezone or USER_TIMEZONE_NOT_SET,
+ terms_accepted_at=prisma_user.termsAcceptedAt,
+ terms_version=prisma_user.termsVersion,
+ marketing_opt_out_at=prisma_user.marketingOptOutAt,
+ marketing_opt_out_source=prisma_user.marketingOptOutSource,
default_chat_auth_provider=prisma_user.defaultChatAuthProvider,
default_chat_credential_id=prisma_user.defaultChatCredentialId,
)
diff --git a/autogpt_platform/backend/backend/data/model_test.py b/autogpt_platform/backend/backend/data/model_test.py
index ac0309a61f..898b0b7701 100644
--- a/autogpt_platform/backend/backend/data/model_test.py
+++ b/autogpt_platform/backend/backend/data/model_test.py
@@ -1,7 +1,10 @@
+from datetime import datetime, timezone
+
import pytest
+from prisma.models import User as PrismaUser
from pydantic import SecretStr
-from backend.data.model import HostScopedCredentials, NodeExecutionStats
+from backend.data.model import HostScopedCredentials, NodeExecutionStats, User
class TestHostScopedCredentials:
@@ -247,3 +250,53 @@ class TestNodeExecutionStatsIadd:
b = NodeExecutionStats()
a += b
assert a.provider_cost_type == "tokens"
+
+
+class TestUserFromDbConsent:
+ @staticmethod
+ def _row(**consent: datetime | str | None) -> PrismaUser:
+ now = datetime(2026, 10, 2, tzinfo=timezone.utc)
+ return PrismaUser.model_validate(
+ {
+ "id": "user-1",
+ "email": "[email protected]",
+ "emailVerified": True,
+ "createdAt": now,
+ "updatedAt": now,
+ "metadata": "{}",
+ "integrations": "",
+ "maxEmailsPerDay": 3,
+ "briefingFrequency": "WEEKLY",
+ "alertsEnabled": True,
+ "notifyOnStoreVerdict": True,
+ "timezone": "not-set",
+ "subscriptionTier": "NO_TIER",
+ **consent,
+ }
+ )
+
+ def test_maps_the_consent_fields(self):
+ accepted_at = datetime(2026, 10, 2, 12, 0, tzinfo=timezone.utc)
+ opted_out_at = datetime(2026, 10, 2, 12, 1, tzinfo=timezone.utc)
+
+ user = User.from_db(
+ self._row(
+ termsAcceptedAt=accepted_at,
+ termsVersion="2026-10",
+ marketingOptOutAt=opted_out_at,
+ marketingOptOutSource="signup",
+ )
+ )
+
+ assert user.terms_accepted_at == accepted_at
+ assert user.terms_version == "2026-10"
+ assert user.marketing_opt_out_at == opted_out_at
+ assert user.marketing_opt_out_source == "signup"
+
+ def test_an_account_without_consent_maps_to_none(self):
+ user = User.from_db(self._row())
+
+ assert user.terms_accepted_at is None
+ assert user.terms_version is None
+ assert user.marketing_opt_out_at is None
+ assert user.marketing_opt_out_source is None
diff --git a/autogpt_platform/backend/backend/data/notifications.py b/autogpt_platform/backend/backend/data/notifications.py
index dd01148fb8..2cddde1195 100644
--- a/autogpt_platform/backend/backend/data/notifications.py
+++ b/autogpt_platform/backend/backend/data/notifications.py
@@ -430,6 +430,10 @@ class AudienceAction(Enum):
# Someone opened Stripe checkout: into the checkout openers group, with
# the fields GTM segments them on (see `mailerlite.record_checkout_opened`).
CHECKOUT_OPENED = "checkout_opened"
+ # The account refused marketing: an existing subscriber is marked
+ # unsubscribed, and nobody is created (see `mailerlite.unsubscribe`). The
+ # only change queued for an opted-out account, since it is the refusal.
+ UNSUBSCRIBE = "unsubscribe"
class SubscriberField(str, Enum):
diff --git a/autogpt_platform/backend/backend/data/user.py b/autogpt_platform/backend/backend/data/user.py
index b1d00f1c47..d527d5c1f7 100644
--- a/autogpt_platform/backend/backend/data/user.py
+++ b/autogpt_platform/backend/backend/data/user.py
@@ -12,7 +12,7 @@ from urllib.parse import quote_plus
from autogpt_libs.auth.models import DEFAULT_USER_ID
from fastapi import HTTPException
from prisma.enums import BriefingFrequency, SubscriptionTier
-from prisma.errors import UniqueViolationError
+from prisma.errors import RecordNotFoundError, UniqueViolationError
from prisma.models import AuthAccount, AuthUser
from prisma.models import User as PrismaUser
from prisma.types import (
@@ -24,7 +24,7 @@ from prisma.types import (
)
from pydantic import BaseModel, ConfigDict
-from backend.data.db import prisma, query_raw_with_schema
+from backend.data.db import prisma, query_raw_with_schema, transaction
from backend.data.model import (
CREDENTIALS_ADAPTER,
Credentials,
@@ -32,10 +32,16 @@ from backend.data.model import (
UserIntegrations,
UserMetadata,
)
-from backend.data.notifications import NotificationPreference, NotificationPreferenceDTO
+from backend.data.notifications import (
+ AudienceAction,
+ NotificationPreference,
+ NotificationPreferenceDTO,
+)
from backend.data.org_migration import ensure_personal_org
from backend.data.posthog_lifecycle_sync import schedule_posthog_lifecycle_sync
from backend.data.subscription_trial import get_subscription_trial
+from backend.notifications.queue import queue_audience_change
+from backend.notifications.subscriber_fields import audience_event
from backend.util.cache import cached
from backend.util.encryption import JSONCryptor
from backend.util.exceptions import DatabaseError, NotFoundError
@@ -964,6 +970,188 @@ async def update_user_timezone(user_id: str, timezone: str) -> User:
raise DatabaseError(f"Failed to update timezone for user {user_id}: {e}") from e
+MARKETING_OPT_OUT_SOURCE_SIGNUP = "signup"
+MARKETING_OPT_OUT_SOURCE_EMAIL_UNSUBSCRIBE = "email_unsubscribe"
+
+
+async def record_signup_consent(
+ user_id: str, terms_version: str, marketing_opt_out: bool
+) -> User:
+ """Record what the user agreed to on the signup page.
+
+ Idempotent, so a retried call is harmless: the terms are stamped again only
+ for a newer version (an older one never replaces a newer acceptance), and
+ an opt-out keeps its first date and source, including one recorded after
+ this call read the row (a concurrent call, or an unsubscribe). Both are
+ written in one transaction, so a failure leaves neither half behind.
+ `marketing_opt_out=False` changes nothing: this can refuse marketing but
+ never take a refusal back, which is a settings action.
+
+ A refusal this call records is passed on to MailerLite, so someone who is
+ already a subscriber there stops getting marketing email too.
+
+ Returns the row as read after any write, so it shows whichever refusal won.
+ """
+ try:
+ current = await PrismaUser.prisma().find_unique(where={"id": user_id})
+ if current is None:
+ raise NotFoundError(f"User not found with ID: {user_id}")
+
+ # Versions are YYYY-MM or YYYY-MM-DD, so they order as strings.
+ stamp_terms = (
+ current.termsAcceptedAt is None
+ or current.termsVersion is None
+ or terms_version > current.termsVersion
+ )
+ opt_out = marketing_opt_out and current.marketingOptOutAt is None
+ if not stamp_terms and not opt_out:
+ return User.from_db(current)
+
+ terms_stamped, opted_out = await _write_signup_consent(
+ user_id, terms_version if stamp_terms else None, opt_out
+ )
+ if terms_stamped or opted_out:
+ # Same invalidation as update_user_timezone: the MailerLite gate
+ # reads the opt-out through get_user_by_id, so a stale cached user
+ # would let a checkout opened right after signup through.
+ _invalidate_user_caches(user_id, current.email)
+ if opted_out and current.email:
+ await _unsubscribe_from_marketing(user_id, current.email)
+
+ user = await PrismaUser.prisma().find_unique(where={"id": user_id})
+ if user is None:
+ raise NotFoundError(f"User not found with ID: {user_id}")
+ return User.from_db(user)
+ except NotFoundError:
+ raise
+ except RecordNotFoundError as e:
+ # The account was deleted between the read and the write. Prisma's
+ # `update` returns None for that, but a write that requires the row
+ # can raise it instead; either way it is a 404, not a database error.
+ raise NotFoundError(f"User not found with ID: {user_id}") from e
+ except Exception as e:
+ raise DatabaseError(
+ f"Failed to record signup consent for user {user_id}: {e}"
+ ) from e
+
+
+async def _write_signup_consent(
+ user_id: str, terms_version: str | None, opt_out: bool
+) -> tuple[bool, bool]:
+ """Stamp the terms (unless `terms_version` is None) and, when `opt_out`,
+ the opt-out, in one transaction. Returns whether each reached the row.
+
+ The opt-out is conditional on none being stored, so a refusal recorded
+ since the caller read the row keeps its own date and source.
+ """
+ now = datetime.now(timezone.utc)
+ terms_stamped = opted_out = False
+ async with transaction() as tx:
+ if terms_version is not None:
+ stamped = await PrismaUser.prisma(tx).update(
+ where={"id": user_id},
+ data={"termsAcceptedAt": now, "termsVersion": terms_version},
+ )
+ terms_stamped = stamped is not None
+ if opt_out:
+ opted_out = (
+ await PrismaUser.prisma(tx).update_many(
+ where={"id": user_id, "marketingOptOutAt": None},
+ data={
+ "marketingOptOutAt": now,
+ "marketingOptOutSource": MARKETING_OPT_OUT_SOURCE_SIGNUP,
+ },
+ )
+ > 0
+ )
+ return terms_stamped, opted_out
+
+
+async def _unsubscribe_from_marketing(user_id: str, email: str) -> None:
+ """Queue the change that marks an existing MailerLite subscriber
+ unsubscribed (it never creates one). The refusal is already stored, so a
+ failure here is logged rather than raised: the consumer re-reads it before
+ every other MailerLite write, so only the unsubscribe itself is lost."""
+ try:
+ event = audience_event(AudienceAction.UNSUBSCRIBE, email, user_id)
+ if event is None:
+ return
+ result = await queue_audience_change(event)
+ if not result.success:
+ logger.error(
+ f"Could not queue the MailerLite unsubscribe for user {user_id}: "
+ f"{result.message}"
+ )
+ except Exception:
+ logger.exception(
+ f"Could not queue the MailerLite unsubscribe for user {user_id}"
+ )
+
+
+def _escape_like(value: str) -> str:
+ """`value` as a literal LIKE/ILIKE pattern (backslash is the default escape)."""
+ return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
+
+
+async def record_marketing_opt_out_by_email(email: str, source: str) -> str | None:
+ """Record that the account at `email` refused marketing, from `source`.
+
+ For refusals made outside the app, such as an unsubscribe in MailerLite.
+ The address is matched exactly, then case-insensitively. First refusal
+ wins: an account already opted out keeps its date and source, so a
+ redelivered call changes nothing. Returns the account's ID only when this
+ call recorded the refusal; None for an unknown address or a repeat.
+ """
+ try:
+ row = await PrismaUser.prisma().find_unique(where={"email": email})
+ if row is None:
+ # Prisma's case-insensitive `equals` is a Postgres ILIKE, where `_`
+ # and `%` are wildcards: escape them so only this address matches,
+ # and act only when exactly one account does.
+ matches = await PrismaUser.prisma().find_many(
+ where={"email": {"equals": _escape_like(email), "mode": "insensitive"}},
+ take=2,
+ )
+ row = matches[0] if len(matches) == 1 else None
+ if row is None or row.marketingOptOutAt is not None:
+ return None
+ written = await PrismaUser.prisma().update_many(
+ where={"id": row.id, "marketingOptOutAt": None},
+ data={
+ "marketingOptOutAt": datetime.now(timezone.utc),
+ "marketingOptOutSource": source,
+ },
+ )
+ if not written:
+ return None
+ _invalidate_user_caches(row.id, row.email)
+ return row.id
+ except Exception as e:
+ # The address stays out of the message: it would reach the logs.
+ raise DatabaseError(f"Failed to record a marketing opt-out: {e}") from e
+
+
+async def is_marketing_opted_out(user_id: str) -> bool:
+ """Whether the account refused marketing, read from the database rather
+ than the user cache, for the last check before a MailerLite write. An
+ account that no longer exists counts as opted out: nothing about it should
+ reach MailerLite either."""
+ try:
+ row = await PrismaUser.prisma().find_unique(where={"id": user_id})
+ except Exception as e:
+ raise DatabaseError(
+ f"Failed to read the marketing opt-out for user {user_id}: {e}"
+ ) from e
+ return row is None or row.marketingOptOutAt is not None
+
+
+def _invalidate_user_caches(user_id: str, email: str | None) -> None:
+ get_user_by_id.cache_delete(user_id)
+ if email:
+ get_user_by_email.cache_delete(email)
+ get_or_create_user.cache_clear()
+
+
class BriefingCandidate(BaseModel):
"""The fields the briefing pass needs to decide whether a user is due.
@@ -1048,7 +1236,7 @@ async def set_last_briefing_at(user_id: str, sent_at: datetime) -> None:
class BillingEmailRecipient(BaseModel):
- """The four fields the billing emails need about a customer.
+ """The fields the billing emails need about a customer.
A narrow model rather than the Prisma `User`, because this crosses the
DatabaseManager RPC boundary: the lifecycle handlers run in the REST API
@@ -1061,6 +1249,9 @@ class BillingEmailRecipient(BaseModel):
email: str
name: str | None = None
welcome_email_sent_at: datetime | None = None
+ # Set when the customer refused marketing: billing emails still go out,
+ # MailerLite never hears of them (notifications/consent.py).
+ marketing_opt_out_at: datetime | None = None
async def get_billing_email_recipient(
@@ -1079,6 +1270,7 @@ async def get_billing_email_recipient(
email=row.email,
name=row.name,
welcome_email_sent_at=row.welcomeEmailSentAt,
+ marketing_opt_out_at=row.marketingOptOutAt,
)
except Exception as e:
raise DatabaseError(
diff --git a/autogpt_platform/backend/backend/data/user_test.py b/autogpt_platform/backend/backend/data/user_test.py
index 1dffa896ce..e631e651b4 100644
--- a/autogpt_platform/backend/backend/data/user_test.py
+++ b/autogpt_platform/backend/backend/data/user_test.py
@@ -1,14 +1,24 @@
"""Unit tests for helpers in backend.data.user."""
import asyncio
+from collections.abc import AsyncIterator, Iterator
+from contextlib import asynccontextmanager
from datetime import datetime, timezone
-from unittest.mock import AsyncMock, MagicMock, patch
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock, call, patch
import prisma.errors
import pytest
from backend.data import user as user_module
-from backend.data.user import update_user_timezone
+from backend.data.notifications import AudienceAction, NotificationResult
+from backend.data.user import (
+ get_billing_email_recipient,
+ is_marketing_opted_out,
+ record_marketing_opt_out_by_email,
+ record_signup_consent,
+ update_user_timezone,
+)
from backend.util.exceptions import DatabaseError, NotFoundError
@@ -244,6 +254,732 @@ class TestUpdateUserTimezone:
assert calls == ["clear", "ensure"]
+TERMS_VERSION = "2026-10"
+EARLIER_TERMS_VERSION = "2025-01"
+CONSENTED_AT = datetime(2026, 1, 5, 9, 30, tzinfo=timezone.utc)
+TERMS_FIELDS = {"termsAcceptedAt", "termsVersion"}
+OPT_OUT_FIELDS = {"marketingOptOutAt", "marketingOptOutSource"}
+
+
+def _consent_row(
+ terms_accepted_at: datetime | None = None,
+ terms_version: str | None = None,
+ marketing_opt_out_at: datetime | None = None,
+ marketing_opt_out_source: str | None = None,
+ email: str | None = "[email protected]",
+) -> MagicMock:
+ """A Prisma User row carrying only what record_signup_consent reads."""
+ return MagicMock(
+ id="user-1",
+ email=email,
+ termsAcceptedAt=terms_accepted_at,
+ termsVersion=terms_version,
+ marketingOptOutAt=marketing_opt_out_at,
+ marketingOptOutSource=marketing_opt_out_source,
+ )
+
+
+def _accepted(opted_out: bool, version: str = TERMS_VERSION) -> MagicMock:
+ return _consent_row(
+ terms_accepted_at=CONSENTED_AT,
+ terms_version=version,
+ marketing_opt_out_at=CONSENTED_AT if opted_out else None,
+ marketing_opt_out_source="signup" if opted_out else None,
+ )
+
+
+def _terms_written(db: MagicMock) -> dict[str, Any]:
+ db.update.assert_awaited_once()
+ assert db.update.await_args is not None
+ assert db.update.await_args.kwargs["where"] == {"id": "user-1"}
+ return db.update.await_args.kwargs["data"]
+
+
+def _opt_out_written(db: MagicMock) -> dict[str, Any]:
+ """Conditional on no refusal being stored, whatever the earlier read saw."""
+ db.update_many.assert_awaited_once()
+ assert db.update_many.await_args is not None
+ assert db.update_many.await_args.kwargs["where"] == {
+ "id": "user-1",
+ "marketingOptOutAt": None,
+ }
+ return db.update_many.await_args.kwargs["data"]
+
+
+class TestRecordSignupConsent:
+ @pytest.fixture
+ def db(self) -> Iterator[MagicMock]:
+ """`PrismaUser.prisma()`, read and written. from_db hands the row back
+ unchanged, so a test can tell which of the rows it got."""
+ with (
+ patch.object(user_module, "PrismaUser") as mock_prisma_user,
+ patch.object(user_module.User, "from_db", side_effect=lambda row: row),
+ ):
+ db = mock_prisma_user.prisma.return_value
+ db.find_unique = AsyncMock(return_value=_consent_row())
+ db.update = AsyncMock(return_value=_consent_row())
+ db.update_many = AsyncMock(return_value=1)
+ db.clients = mock_prisma_user.prisma
+ yield db
+
+ @pytest.fixture(autouse=True)
+ def tx(self) -> Iterator[MagicMock]:
+ """`transaction()`. `exits` records how each block was left: None for
+ a commit, the exception for a rollback."""
+ tx = MagicMock(name="tx")
+ tx.exits = []
+
+ @asynccontextmanager
+ async def fake_transaction() -> AsyncIterator[MagicMock]:
+ try:
+ yield tx
+ except BaseException as e:
+ tx.exits.append(e)
+ raise
+ tx.exits.append(None)
+
+ with patch.object(user_module, "transaction", fake_transaction):
+ yield tx
+
+ @pytest.fixture(autouse=True)
+ def caches(self) -> Iterator[MagicMock]:
+ """The three user caches as children of one mock, so `mock_calls` shows
+ whether any of them was touched."""
+ caches = MagicMock()
+ with (
+ patch.object(
+ user_module.get_user_by_id, "cache_delete", caches.by_id_delete
+ ),
+ patch.object(
+ user_module.get_user_by_email, "cache_delete", caches.by_email_delete
+ ),
+ patch.object(
+ user_module.get_or_create_user, "cache_clear", caches.or_create_clear
+ ),
+ ):
+ yield caches
+
+ @pytest.fixture(autouse=True)
+ def queued(self) -> Iterator[AsyncMock]:
+ """`queue_audience_change`: what reached the MailerLite queue."""
+ queued = AsyncMock(return_value=NotificationResult(success=True, message=""))
+ with patch.object(user_module, "queue_audience_change", queued):
+ yield queued
+
+ @pytest.mark.asyncio
+ async def test_first_call_stamps_the_terms_and_the_opt_out(self, db: MagicMock):
+ fresh = _accepted(True)
+ db.find_unique.side_effect = [_consent_row(), fresh]
+ before = datetime.now(timezone.utc)
+
+ result = await record_signup_consent("user-1", TERMS_VERSION, True)
+
+ assert db.find_unique.await_args_list == [
+ call(where={"id": "user-1"}),
+ call(where={"id": "user-1"}),
+ ]
+ terms = _terms_written(db)
+ opt_out = _opt_out_written(db)
+ assert set(terms) == TERMS_FIELDS
+ assert set(opt_out) == OPT_OUT_FIELDS
+ assert terms["termsVersion"] == TERMS_VERSION
+ assert opt_out["marketingOptOutSource"] == "signup"
+ assert before <= terms["termsAcceptedAt"] <= datetime.now(timezone.utc)
+ assert opt_out["marketingOptOutAt"] == terms["termsAcceptedAt"]
+ assert result is fresh
+
+ @pytest.mark.asyncio
+ async def test_first_call_without_opt_out_stamps_only_the_terms(
+ self, db: MagicMock
+ ):
+ await record_signup_consent("user-1", TERMS_VERSION, False)
+
+ terms = _terms_written(db)
+ assert set(terms) == TERMS_FIELDS
+ assert terms["termsVersion"] == TERMS_VERSION
+ db.update_many.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "opted_out,marketing_opt_out",
+ [
+ pytest.param(True, True, id="retried-opt-out"),
+ pytest.param(True, False, id="no-opt-out-keeps-the-existing-one"),
+ pytest.param(False, False, id="retried-without-opt-out"),
+ ],
+ )
+ async def test_nothing_new_writes_nothing_and_keeps_the_caches(
+ self,
+ db: MagicMock,
+ caches: MagicMock,
+ opted_out: bool,
+ marketing_opt_out: bool,
+ ):
+ current = _accepted(opted_out)
+ db.find_unique.return_value = current
+
+ result = await record_signup_consent("user-1", TERMS_VERSION, marketing_opt_out)
+
+ assert result is current
+ db.find_unique.assert_awaited_once()
+ db.update.assert_not_awaited()
+ db.update_many.assert_not_awaited()
+ assert caches.mock_calls == []
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("marketing_opt_out", [True, False])
+ async def test_new_terms_version_restamps_the_terms_and_keeps_the_opt_out(
+ self, db: MagicMock, marketing_opt_out: bool
+ ):
+ db.find_unique.return_value = _accepted(True, version=EARLIER_TERMS_VERSION)
+
+ await record_signup_consent("user-1", TERMS_VERSION, marketing_opt_out)
+
+ terms = _terms_written(db)
+ assert set(terms) == TERMS_FIELDS
+ assert terms["termsVersion"] == TERMS_VERSION
+ assert terms["termsAcceptedAt"] > CONSENTED_AT
+ db.update_many.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_a_version_without_an_acceptance_date_is_stamped(self, db: MagicMock):
+ db.find_unique.return_value = _consent_row(terms_version=TERMS_VERSION)
+
+ await record_signup_consent("user-1", TERMS_VERSION, False)
+
+ assert set(_terms_written(db)) == TERMS_FIELDS
+
+ @pytest.mark.asyncio
+ async def test_opt_out_after_accepting_the_same_terms_writes_only_the_opt_out(
+ self, db: MagicMock
+ ):
+ db.find_unique.return_value = _accepted(False)
+
+ await record_signup_consent("user-1", TERMS_VERSION, True)
+
+ db.update.assert_not_awaited()
+ opt_out = _opt_out_written(db)
+ assert set(opt_out) == OPT_OUT_FIELDS
+ assert opt_out["marketingOptOutSource"] == "signup"
+ assert opt_out["marketingOptOutAt"] > CONSENTED_AT
+
+ @pytest.mark.asyncio
+ async def test_a_refusal_recorded_since_the_read_is_not_overwritten(
+ self, db: MagicMock, caches: MagicMock
+ ):
+ """The read saw no refusal, but one landed before the write (a
+ concurrent call, or an unsubscribe). The conditional write matches no
+ row, and the caller gets that refusal back."""
+ unsubscribed = _consent_row(
+ terms_accepted_at=CONSENTED_AT,
+ terms_version=TERMS_VERSION,
+ marketing_opt_out_at=CONSENTED_AT,
+ marketing_opt_out_source="email_unsubscribe",
+ )
+ db.find_unique.side_effect = [_accepted(False), unsubscribed]
+ db.update_many.return_value = 0
+
+ result = await record_signup_consent("user-1", TERMS_VERSION, True)
+
+ _opt_out_written(db)
+ db.update.assert_not_awaited()
+ assert result is unsubscribed
+ assert caches.mock_calls == []
+
+ @pytest.mark.asyncio
+ async def test_a_write_invalidates_all_three_user_caches(
+ self, db: MagicMock, caches: MagicMock
+ ):
+ db.find_unique.return_value = _consent_row(email="[email protected]")
+
+ await record_signup_consent("user-1", TERMS_VERSION, True)
+
+ caches.by_id_delete.assert_called_once_with("user-1")
+ caches.by_email_delete.assert_called_once_with("[email protected]")
+ caches.or_create_clear.assert_called_once_with()
+
+ @pytest.mark.asyncio
+ async def test_a_write_skips_the_email_cache_when_the_row_has_no_email(
+ self, db: MagicMock, caches: MagicMock
+ ):
+ db.find_unique.return_value = _consent_row(email=None)
+
+ await record_signup_consent("user-1", TERMS_VERSION, True)
+
+ caches.by_id_delete.assert_called_once_with("user-1")
+ caches.by_email_delete.assert_not_called()
+ caches.or_create_clear.assert_called_once_with()
+
+ @pytest.mark.asyncio
+ async def test_missing_user_raises_not_found(
+ self, db: MagicMock, caches: MagicMock
+ ):
+ db.find_unique.return_value = None
+
+ with pytest.raises(NotFoundError, match="user-1"):
+ await record_signup_consent("user-1", TERMS_VERSION, True)
+
+ db.update.assert_not_awaited()
+ db.update_many.assert_not_awaited()
+ assert caches.mock_calls == []
+
+ @pytest.mark.asyncio
+ async def test_user_deleted_before_the_write_raises_not_found(
+ self, db: MagicMock, caches: MagicMock
+ ):
+ """prisma-client-py's `update` catches Prisma's P2025 and returns None
+ (prisma/actions.py), so this is what a deleted row looks like."""
+ db.find_unique.side_effect = [_consent_row(), None]
+ db.update.return_value = None
+ db.update_many.return_value = 0
+
+ with pytest.raises(NotFoundError, match="user-1"):
+ await record_signup_consent("user-1", TERMS_VERSION, True)
+
+ assert caches.mock_calls == []
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("failing_call", ["update", "update_many"])
+ async def test_a_record_not_found_error_is_a_not_found(
+ self, db: MagicMock, caches: MagicMock, failing_call: str
+ ):
+ """Prisma's own error for a row that vanished mid-write maps to the
+ 404, not to a database failure."""
+ getattr(db, failing_call).side_effect = prisma.errors.RecordNotFoundError(
+ {"user_facing_error": {"message": "Record to update not found."}}
+ )
+
+ with pytest.raises(NotFoundError, match="user-1"):
+ await record_signup_consent("user-1", TERMS_VERSION, True)
+
+ assert caches.mock_calls == []
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("marketing_opt_out", [True, False])
+ async def test_an_older_version_never_replaces_a_newer_acceptance(
+ self, db: MagicMock, marketing_opt_out: bool
+ ):
+ db.find_unique.return_value = _accepted(False)
+
+ await record_signup_consent("user-1", EARLIER_TERMS_VERSION, marketing_opt_out)
+
+ db.update.assert_not_called()
+ if marketing_opt_out:
+ assert set(_opt_out_written(db)) == OPT_OUT_FIELDS
+ else:
+ db.update_many.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_both_writes_share_one_committed_transaction(
+ self, db: MagicMock, tx: MagicMock
+ ):
+ await record_signup_consent("user-1", TERMS_VERSION, True)
+
+ assert db.clients.call_args_list.count(call(tx)) == 2
+ _terms_written(db)
+ _opt_out_written(db)
+ assert tx.exits == [None]
+
+ @pytest.mark.asyncio
+ async def test_a_failed_opt_out_write_rolls_back_the_terms(
+ self, db: MagicMock, tx: MagicMock, caches: MagicMock
+ ):
+ failure = RuntimeError("opt-out write failed")
+ db.update_many.side_effect = failure
+
+ with pytest.raises(DatabaseError):
+ await record_signup_consent("user-1", TERMS_VERSION, True)
+
+ _terms_written(db)
+ assert tx.exits == [failure]
+ assert caches.mock_calls == []
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("failing_call", ["find_unique", "update", "update_many"])
+ async def test_wraps_prisma_errors_in_database_error(
+ self, db: MagicMock, caches: MagicMock, failing_call: str
+ ):
+ calls = {
+ "find_unique": db.find_unique,
+ "update": db.update,
+ "update_many": db.update_many,
+ }
+ calls[failing_call].side_effect = RuntimeError("connection lost")
+
+ with pytest.raises(DatabaseError) as exc:
+ await record_signup_consent("user-1", TERMS_VERSION, True)
+
+ assert "user-1" in str(exc.value)
+ assert "connection lost" in str(exc.value)
+ assert caches.mock_calls == []
+
+
+class TestSignupRefusalReachesMailerLite:
+ """A refusal this call records unsubscribes an existing MailerLite
+ subscriber; nothing else ever queues a MailerLite change from here."""
+
+ @pytest.fixture
+ def db(self) -> Iterator[MagicMock]:
+ with (
+ patch.object(user_module, "PrismaUser") as mock_prisma_user,
+ patch.object(user_module.User, "from_db", side_effect=lambda row: row),
+ patch.object(user_module.get_user_by_id, "cache_delete"),
+ patch.object(user_module.get_user_by_email, "cache_delete"),
+ patch.object(user_module.get_or_create_user, "cache_clear"),
+ ):
+ db = mock_prisma_user.prisma.return_value
+ db.find_unique = AsyncMock(return_value=_consent_row())
+ db.update = AsyncMock(return_value=_consent_row())
+ db.update_many = AsyncMock(return_value=1)
+ yield db
+
+ @pytest.fixture(autouse=True)
+ def tx(self) -> Iterator[None]:
+ @asynccontextmanager
+ async def fake_transaction() -> AsyncIterator[MagicMock]:
+ yield MagicMock(name="tx")
+
+ with patch.object(user_module, "transaction", fake_transaction):
+ yield
+
+ @pytest.fixture
+ def queued(self) -> Iterator[AsyncMock]:
+ queued = AsyncMock(return_value=NotificationResult(success=True, message=""))
+ with patch.object(user_module, "queue_audience_change", queued):
+ yield queued
+
+ @pytest.mark.asyncio
+ async def test_a_new_refusal_queues_an_unsubscribe(
+ self, db: MagicMock, queued: AsyncMock
+ ):
+ await record_signup_consent("user-1", TERMS_VERSION, True)
+
+ queued.assert_awaited_once()
+ event = queued.await_args.args[0]
+ assert event.action is AudienceAction.UNSUBSCRIBE
+ assert event.email == "[email protected]"
+ assert event.user_id == "user-1"
+ assert event.fields == {}
+
+ @pytest.mark.asyncio
+ async def test_the_unsubscribe_is_queued_after_the_refusal_is_committed(
+ self, db: MagicMock, queued: AsyncMock
+ ):
+ """Queued before the commit, the consumer could find the account still
+ opted in, and a rolled-back refusal would still unsubscribe."""
+ order: list[str] = []
+ db.update_many.side_effect = lambda **_: order.append("write") or 1
+ queued.side_effect = lambda _: order.append("queue") or NotificationResult(
+ success=True, message=""
+ )
+
+ @asynccontextmanager
+ async def fake_transaction() -> AsyncIterator[MagicMock]:
+ yield MagicMock(name="tx")
+ order.append("commit")
+
+ with patch.object(user_module, "transaction", fake_transaction):
+ await record_signup_consent("user-1", TERMS_VERSION, True)
+
+ assert order == ["write", "commit", "queue"]
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "current,marketing_opt_out,written",
+ [
+ pytest.param(_accepted(True), True, 1, id="already-refused"),
+ pytest.param(_consent_row(), False, 1, id="no-refusal"),
+ pytest.param(
+ _accepted(False, EARLIER_TERMS_VERSION), False, 1, id="new-terms-only"
+ ),
+ pytest.param(_consent_row(), True, 0, id="refused-concurrently"),
+ ],
+ )
+ async def test_nothing_is_queued_without_a_new_refusal(
+ self,
+ db: MagicMock,
+ queued: AsyncMock,
+ current: MagicMock,
+ marketing_opt_out: bool,
+ written: int,
+ ):
+ db.find_unique.return_value = current
+ db.update_many.return_value = written
+
+ await record_signup_consent("user-1", TERMS_VERSION, marketing_opt_out)
+
+ queued.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_an_account_without_an_email_queues_nothing(
+ self, db: MagicMock, queued: AsyncMock
+ ):
+ db.find_unique.return_value = _consent_row(email=None)
+
+ await record_signup_consent("user-1", TERMS_VERSION, True)
+
+ queued.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "failure",
+ [
+ pytest.param(
+ {"return_value": NotificationResult(success=False, message="down")},
+ id="not-queued",
+ ),
+ pytest.param({"side_effect": RuntimeError("broker gone")}, id="raised"),
+ ],
+ )
+ async def test_a_queue_failure_still_returns_the_recorded_refusal(
+ self, db: MagicMock, failure: dict, caplog
+ ):
+ """The refusal is stored either way, and the consumer re-reads it
+ before every other MailerLite write, so the caller is not failed."""
+ fresh = _accepted(True)
+ db.find_unique.side_effect = [_consent_row(), fresh]
+
+ with (
+ patch.object(user_module, "queue_audience_change", AsyncMock(**failure)),
+ caplog.at_level("ERROR"),
+ ):
+ result = await record_signup_consent("user-1", TERMS_VERSION, True)
+
+ assert result is fresh
+ assert "Could not queue the MailerLite unsubscribe for user user-1" in (
+ caplog.text
+ )
+ assert "[email protected]" not in caplog.text
+
+
+class TestRecordMarketingOptOutByEmail:
+ """A refusal made outside the app (an unsubscribe in MailerLite)."""
+
+ @pytest.fixture
+ def db(self) -> Iterator[MagicMock]:
+ with patch.object(user_module, "PrismaUser") as mock_prisma_user:
+ db = mock_prisma_user.prisma.return_value
+ db.find_unique = AsyncMock(return_value=_consent_row())
+ db.find_many = AsyncMock(return_value=[])
+ db.update_many = AsyncMock(return_value=1)
+ yield db
+
+ @pytest.fixture(autouse=True)
+ def caches(self) -> Iterator[MagicMock]:
+ caches = MagicMock()
+ with (
+ patch.object(
+ user_module.get_user_by_id, "cache_delete", caches.by_id_delete
+ ),
+ patch.object(
+ user_module.get_user_by_email, "cache_delete", caches.by_email_delete
+ ),
+ patch.object(
+ user_module.get_or_create_user, "cache_clear", caches.or_create_clear
+ ),
+ ):
+ yield caches
+
+ @pytest.mark.asyncio
+ async def test_records_the_refusal_with_its_source(
+ self, db: MagicMock, caches: MagicMock
+ ):
+ before = datetime.now(timezone.utc)
+
+ result = await record_marketing_opt_out_by_email(
+ "[email protected]", "email_unsubscribe"
+ )
+
+ assert result == "user-1"
+ db.find_unique.assert_awaited_once_with(where={"email": "[email protected]"})
+ db.find_many.assert_not_awaited()
+ data = _opt_out_written(db)
+ assert data["marketingOptOutSource"] == "email_unsubscribe"
+ assert before <= data["marketingOptOutAt"] <= datetime.now(timezone.utc)
+ caches.by_id_delete.assert_called_once_with("user-1")
+ caches.by_email_delete.assert_called_once_with("[email protected]")
+ caches.or_create_clear.assert_called_once_with()
+
+ @pytest.mark.asyncio
+ async def test_falls_back_to_a_case_insensitive_match(self, db: MagicMock):
+ db.find_unique.return_value = None
+ db.find_many.return_value = [_consent_row(email="[email protected]")]
+
+ result = await record_marketing_opt_out_by_email(
+ "[email protected]", "email_unsubscribe"
+ )
+
+ assert result == "user-1"
+ db.find_many.assert_awaited_once_with(
+ where={"email": {"equals": "[email protected]", "mode": "insensitive"}},
+ take=2,
+ )
+ _opt_out_written(db)
+
+ @pytest.mark.asyncio
+ async def test_like_wildcards_in_the_address_match_only_themselves(
+ self, db: MagicMock
+ ):
+ """The fallback is an ILIKE: unescaped, `john_smith@` would also match
+ `john.smith@` and opt out someone else."""
+ db.find_unique.return_value = None
+
+ await record_marketing_opt_out_by_email(
+ "john_smith%[email protected]", "email_unsubscribe"
+ )
+
+ db.find_many.assert_awaited_once_with(
+ where={
+ "email": {
+ "equals": "john\\_smith\\%[email protected]",
+ "mode": "insensitive",
+ }
+ },
+ take=2,
+ )
+
+ @pytest.mark.asyncio
+ async def test_an_ambiguous_case_insensitive_match_writes_nothing(
+ self, db: MagicMock, caches: MagicMock
+ ):
+ db.find_unique.return_value = None
+ db.find_many.return_value = [
+ _consent_row(email="[email protected]"),
+ _consent_row(email="[email protected]"),
+ ]
+
+ assert (
+ await record_marketing_opt_out_by_email(
+ "[email protected]", "email_unsubscribe"
+ )
+ is None
+ )
+ db.update_many.assert_not_awaited()
+ assert caches.mock_calls == []
+
+ @pytest.mark.asyncio
+ async def test_an_unknown_address_writes_nothing(
+ self, db: MagicMock, caches: MagicMock
+ ):
+ db.find_unique.return_value = None
+
+ assert (
+ await record_marketing_opt_out_by_email(
+ "[email protected]", "email_unsubscribe"
+ )
+ is None
+ )
+ db.update_many.assert_not_awaited()
+ assert caches.mock_calls == []
+
+ @pytest.mark.asyncio
+ async def test_the_first_refusal_wins(self, db: MagicMock, caches: MagicMock):
+ """Already opted out at signup: a later unsubscribe keeps that date and
+ source, so a redelivered webhook changes nothing either."""
+ db.find_unique.return_value = _accepted(True)
+
+ assert (
+ await record_marketing_opt_out_by_email(
+ "[email protected]", "email_unsubscribe"
+ )
+ is None
+ )
+ db.update_many.assert_not_awaited()
+ assert caches.mock_calls == []
+
+ @pytest.mark.asyncio
+ async def test_a_refusal_recorded_since_the_read_is_kept(
+ self, db: MagicMock, caches: MagicMock
+ ):
+ db.update_many.return_value = 0
+
+ assert (
+ await record_marketing_opt_out_by_email(
+ "[email protected]", "email_unsubscribe"
+ )
+ is None
+ )
+ _opt_out_written(db)
+ assert caches.mock_calls == []
+
+ @pytest.mark.asyncio
+ async def test_a_database_failure_names_no_address(self, db: MagicMock):
+ db.find_unique.side_effect = RuntimeError("connection lost")
+
+ with pytest.raises(DatabaseError) as raised:
+ await record_marketing_opt_out_by_email(
+ "[email protected]", "email_unsubscribe"
+ )
+
+ assert "[email protected]" not in str(raised.value)
+
+
+class TestIsMarketingOptedOut:
+ """The audience consumer's last check before a MailerLite write."""
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "row,expected",
+ [
+ pytest.param(_accepted(True), True, id="opted-out"),
+ pytest.param(_accepted(False), False, id="opted-in"),
+ pytest.param(None, True, id="deleted-account"),
+ ],
+ )
+ async def test_reads_the_row_not_the_cache(
+ self, row: MagicMock | None, expected: bool
+ ):
+ with (
+ patch.object(user_module, "PrismaUser") as mock_prisma_user,
+ patch.object(user_module, "get_user_by_id") as cached,
+ ):
+ db = mock_prisma_user.prisma.return_value
+ db.find_unique = AsyncMock(return_value=row)
+
+ assert await is_marketing_opted_out("user-1") is expected
+
+ db.find_unique.assert_awaited_once_with(where={"id": "user-1"})
+ cached.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_a_failed_read_raises(self):
+ with patch.object(user_module, "PrismaUser") as mock_prisma_user:
+ mock_prisma_user.prisma.return_value.find_unique = AsyncMock(
+ side_effect=RuntimeError("connection lost")
+ )
+
+ with pytest.raises(DatabaseError, match="user-1"):
+ await is_marketing_opted_out("user-1")
+
+
+class TestGetBillingEmailRecipient:
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("opted_out_at", [None, CONSENTED_AT])
+ async def test_maps_the_marketing_opt_out(self, opted_out_at: datetime | None):
+ row = MagicMock(
+ id="user-1",
+ welcomeEmailSentAt=None,
+ marketingOptOutAt=opted_out_at,
+ )
+ row.name = "User"
+
+ with patch.object(user_module, "prisma") as mock_prisma:
+ mock_prisma.user.find_first = AsyncMock(return_value=row)
+ recipient = await get_billing_email_recipient("cus_123")
+
+ mock_prisma.user.find_first.assert_awaited_once_with(
+ where={"stripeCustomerId": "cus_123"}
+ )
+ assert recipient == user_module.BillingEmailRecipient(
+ id="user-1",
+ name="User",
+ welcome_email_sent_at=None,
+ marketing_opt_out_at=opted_out_at,
+ )
+
+
class TestTableBackedCredentials:
"""get/set_user_credentials — the IntegrationCredential-backed seam the
credential store runs on after the blob→table migration."""
diff --git a/autogpt_platform/backend/backend/notifications/audience_consent_recheck_test.py b/autogpt_platform/backend/backend/notifications/audience_consent_recheck_test.py
new file mode 100644
index 0000000000..7870b11b58
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/audience_consent_recheck_test.py
@@ -0,0 +1,118 @@
+"""The audience consumer re-reads the opt-out right before each MailerLite
+write, so a change queued just before a refusal is never applied."""
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from backend.data.notifications import AudienceAction, SubscriberField
+from backend.notifications import mailerlite, subscriber_fields
+from backend.notifications.notifications import NotificationManager
+
+
+HANDLERS = {
+ AudienceAction.ENROLL_TOUR: "enroll_in_onboarding",
+ AudienceAction.ADD_CHANGELOG: "add_to_changelog",
+ AudienceAction.REMOVE_CHANGELOG: "remove_from_changelog",
+ AudienceAction.ADD_TRIAL: "add_to_trial",
+ AudienceAction.REMOVE_TRIAL: "remove_from_trial",
+ AudienceAction.UPDATE_FIELDS: "update_fields",
+ AudienceAction.SIGNUP: "record_signup",
+ AudienceAction.CHECKOUT_OPENED: "record_checkout_opened",
+ AudienceAction.UNSUBSCRIBE: "unsubscribe",
+}
+WRITES = [action for action in AudienceAction if action != AudienceAction.UNSUBSCRIBE]
+
+
[email protected](autouse=True)
+def handlers(monkeypatch) -> dict[AudienceAction, AsyncMock]:
+ monkeypatch.setattr(mailerlite, "configured", lambda: True)
+ mocks = {}
+ for action, name in HANDLERS.items():
+ mocks[action] = AsyncMock()
+ monkeypatch.setattr(mailerlite, name, mocks[action])
+ return mocks
+
+
+async def _consume(action: AudienceAction) -> bool:
+ event = subscriber_fields.audience_event(
+ action, EMAIL, "user-1", {SubscriberField.STATUS: "signed"}
+ )
+ assert event is not None
+ return await NotificationManager._process_audience_change(
+ MagicMock(), event.model_dump_json()
+ )
+
+
+def test_every_action_is_covered():
+ assert set(HANDLERS) == set(AudienceAction)
+
+
[email protected]("action", WRITES, ids=lambda a: a.value)
+async def test_a_change_for_an_opted_out_account_is_dropped(
+ audience_consent: SimpleNamespace, handlers, action, caplog
+):
+ audience_consent.is_marketing_opted_out.return_value = True
+
+ with caplog.at_level("DEBUG", logger="backend.notifications.consent"):
+ assert await _consume(action)
+
+ audience_consent.is_marketing_opted_out.assert_awaited_once_with("user-1")
+ handlers[action].assert_not_awaited()
+ assert mailerlite.pseudonym(EMAIL) in caplog.text
+ assert EMAIL not in caplog.text
+
+
[email protected]("action", WRITES, ids=lambda a: a.value)
+async def test_a_change_for_an_opted_in_account_is_applied(
+ audience_consent: SimpleNamespace, handlers, action
+):
+ assert await _consume(action)
+
+ audience_consent.is_marketing_opted_out.assert_awaited_once_with("user-1")
+ handlers[action].assert_awaited_once()
+
+
[email protected]("opted_out", [True, False])
+async def test_the_unsubscribe_always_goes_through(
+ audience_consent: SimpleNamespace, handlers, opted_out
+):
+ """It carries the refusal, so it is the one write an opted-out account
+ gets; there is nothing to re-read."""
+ audience_consent.is_marketing_opted_out.return_value = opted_out
+
+ assert await _consume(AudienceAction.UNSUBSCRIBE)
+
+ handlers[AudienceAction.UNSUBSCRIBE].assert_awaited_once()
+ assert handlers[AudienceAction.UNSUBSCRIBE].await_args.args[0] == EMAIL
+ audience_consent.is_marketing_opted_out.assert_not_awaited()
+
+
+async def test_a_failed_read_retries_rather_than_writes(
+ audience_consent: SimpleNamespace, handlers
+):
+ """Unknown consent is never taken as consent: the message is retried."""
+ audience_consent.is_marketing_opted_out.side_effect = RuntimeError("rpc down")
+
+ with pytest.raises(RuntimeError):
+ await _consume(AudienceAction.CHECKOUT_OPENED)
+
+ handlers[AudienceAction.CHECKOUT_OPENED].assert_not_awaited()
+
+
+async def test_without_mailerlite_nothing_is_read(
+ audience_consent: SimpleNamespace, handlers, monkeypatch
+):
+ monkeypatch.setattr(mailerlite, "configured", lambda: False)
+
+ assert await _consume(AudienceAction.CHECKOUT_OPENED)
+
+ audience_consent.is_marketing_opted_out.assert_not_awaited()
+ handlers[AudienceAction.CHECKOUT_OPENED].assert_not_awaited()
diff --git a/autogpt_platform/backend/backend/notifications/checkout_audience_test.py b/autogpt_platform/backend/backend/notifications/checkout_audience_test.py
index c2bcaa4827..9a6c19b7bc 100644
--- a/autogpt_platform/backend/backend/notifications/checkout_audience_test.py
+++ b/autogpt_platform/backend/backend/notifications/checkout_audience_test.py
@@ -189,6 +189,7 @@ async def test_every_audience_action_has_a_handler(monkeypatch):
"update_fields",
"record_signup",
"record_checkout_opened",
+ "unsubscribe",
):
handlers[name] = AsyncMock()
monkeypatch.setattr(mailerlite, name, handlers[name])
diff --git a/autogpt_platform/backend/backend/notifications/checkout_backfill.py b/autogpt_platform/backend/backend/notifications/checkout_backfill.py
index e8c34d81ef..66a1e919d4 100644
--- a/autogpt_platform/backend/backend/notifications/checkout_backfill.py
+++ b/autogpt_platform/backend/backend/notifications/checkout_backfill.py
@@ -4,7 +4,8 @@ fields GTM segments on (`audience_enrichment`).
Only accounts with at least one Stripe Checkout Session are openers. Nobody
else is written, so the accounts that never reached checkout stay out of
-MailerLite.
+MailerLite. An opener who opted out of marketing stays out too (`consent.py`):
+they are counted, never planned.
Each person is written with one subscriber upsert, one at a time and paced,
never a /batch: MailerLite processes an upsert-only batch as an import, and
@@ -28,6 +29,7 @@ from pydantic import BaseModel
from backend.data.notifications import SubscriberField
from backend.notifications.audience_enrichment import checkout_fields, merge_with_held
+from backend.notifications.consent import marketing_allowed
from backend.notifications.mailerlite import (
API_BASE,
_client,
@@ -82,6 +84,8 @@ class OpenerPlan(BaseModel):
openers: int
# Addresses MailerLite would refuse, such as a reserved domain.
invalid: int
+ # Openers who refused marketing, left out of the plan and the tallies.
+ opted_out: int
# What the openers end up with, for the report.
country_sources: dict[str, int]
countries: dict[str, int]
@@ -110,13 +114,16 @@ def plan(
openers: list[Opener], current: Current, members: Mapping[str, str]
) -> OpenerPlan:
changes: list[OpenerChange] = []
- invalid = 0
+ invalid = opted_out = 0
sources: Counter[str] = Counter()
countries: Counter[str] = Counter()
email_types: Counter[str] = Counter()
methods: Counter[str] = Counter()
exclude = 0
for opener in openers:
+ if not marketing_allowed(opener.person):
+ opted_out += 1
+ continue
email = opener.person.email
if not _valid(email):
invalid += 1
@@ -142,6 +149,7 @@ def plan(
changes=changes,
openers=len(openers),
invalid=invalid,
+ opted_out=opted_out,
country_sources=dict(sources),
countries=dict(countries),
email_types=dict(email_types),
diff --git a/autogpt_platform/backend/backend/notifications/checkout_backfill_test.py b/autogpt_platform/backend/backend/notifications/checkout_backfill_test.py
index a9083e5ed1..574b748785 100644
--- a/autogpt_platform/backend/backend/notifications/checkout_backfill_test.py
+++ b/autogpt_platform/backend/backend/notifications/checkout_backfill_test.py
@@ -13,6 +13,7 @@ from backend.notifications.mailerlite_backfill import Subscription
from backend.notifications.mailerlite_field_backfill import Person
OPENED = int(datetime(2026, 7, 15, 9, 0, tzinfo=UTC).timestamp())
+OPTED_OUT = datetime(2026, 10, 2, tzinfo=UTC)
def _opener(email="[email protected]", subscriptions=None, **kwargs):
@@ -24,6 +25,7 @@ def _opener(email="[email protected]", subscriptions=None, **kwargs):
subscriptions=subscriptions or [],
stripe_customer_id="cus_1",
timezone=kwargs.pop("timezone", "Asia/Kolkata"),
+ marketing_opt_out_at=kwargs.pop("opted_out_at", None),
),
opened_at=OPENED,
signin_providers=["google"],
@@ -309,3 +311,34 @@ async def test_a_failed_stripe_refresh_is_counted_and_retried_later(monkeypatch)
)
assert result == (0, 1, 0)
client.post.assert_not_awaited()
+
+
+def _with_an_opted_out_opener() -> checkout_backfill.OpenerPlan:
+ """Held by MailerLite but outside the group, and German: every reason to
+ be written and tallied, had they not opted out."""
+ opted_out = _opener(
+ email="[email protected]", stripe_country="DE", opted_out_at=OPTED_OUT
+ )
+ return checkout_backfill.plan(
+ [opted_out, _opener()], current={"[email protected]": {}}, members={}
+ )
+
+
+def test_an_opted_out_opener_is_counted_but_never_planned_or_tallied():
+ plan = _with_an_opted_out_opener()
+ assert [c.opener.person.email for c in plan.changes] == ["[email protected]"]
+ assert plan.openers == 2
+ assert plan.opted_out == 1
+ assert plan.invalid == 0
+ assert plan.countries == {"IN": 1}
+ assert plan.exclude_de_at == 0
+ assert sum(plan.email_types.values()) == 1
+
+
+async def test_an_opted_out_opener_is_never_written(monkeypatch):
+ plan = _with_an_opted_out_opener()
+ result, client = await _apply_with(monkeypatch, plan, held=None, refresh=None)
+ assert result == (1, 0, 0)
+ written = [c.kwargs["json"]["email"] for c in client.post.await_args_list]
+ assert written == ["[email protected]"]
diff --git a/autogpt_platform/backend/backend/notifications/conftest.py b/autogpt_platform/backend/backend/notifications/conftest.py
index 0e19555d56..db0b39bece 100644
--- a/autogpt_platform/backend/backend/notifications/conftest.py
+++ b/autogpt_platform/backend/backend/notifications/conftest.py
@@ -21,6 +21,7 @@ from prisma.enums import BriefingFrequency
from backend.data.alerts import MaturedAlertPage
from backend.data.notifications import NotificationPreference
+from backend.notifications import notifications as delivery
NOW = datetime(2026, 8, 3, 7, 30, tzinfo=timezone.utc)
@@ -61,6 +62,7 @@ def make_db_client(**overrides) -> SimpleNamespace:
)
),
get_user_by_id=AsyncMock(return_value=None),
+ is_marketing_opted_out=AsyncMock(return_value=False),
get_user_email_verification=AsyncMock(return_value=True),
# Alert conditions
get_users_with_matured_alerts=AsyncMock(
@@ -92,3 +94,16 @@ def make_db_client(**overrides) -> SimpleNamespace:
@pytest.fixture
def db_client() -> SimpleNamespace:
return make_db_client()
+
+
[email protected](autouse=True)
+def audience_consent(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:
+ """The audience consumer re-reads the opt-out before every MailerLite
+ write. Opted in unless a test says otherwise, so the suites about what
+ MailerLite receives need no database; set `is_marketing_opted_out` on the
+ returned client to change it."""
+ client = make_db_client()
+ monkeypatch.setattr(
+ delivery, "get_database_manager_async_client", lambda **_: client
+ )
+ return client
diff --git a/autogpt_platform/backend/backend/notifications/consent.py b/autogpt_platform/backend/backend/notifications/consent.py
new file mode 100644
index 0000000000..8991df1efa
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/consent.py
@@ -0,0 +1,61 @@
+"""Whether an account may exist in MailerLite at all.
+
+Someone who refused marketing (on the signup page; later, by unsubscribing from
+an email or in settings) is never written to MailerLite: no subscriber, no
+group, no fields, and no "opted out" placeholder either. Every MailerLite write
+upserts the subscriber, a group removal or a field update included (see
+`mailerlite.py`), so every path that queues an audience change asks
+`marketing_allowed` first, and the backfills leave such accounts out of their
+plan. Billing and account emails are service mail and are not affected.
+"""
+
+import logging
+from datetime import datetime
+from typing import Protocol
+
+from backend.data.notifications import AudienceAction
+from backend.notifications.mailerlite import pseudonym
+
+logger = logging.getLogger(__name__)
+
+# Never a stored value, so a missing attribute cannot pass for an unset one.
+_MISSING = object()
+
+
+class MarketingConsent(Protocol):
+ @property
+ def marketing_opt_out_at(self) -> datetime | None: ...
+
+
+class MarketingContact(MarketingConsent, Protocol):
+ """An account an audience change would be queued for."""
+
+ @property
+ def id(self) -> str: ...
+
+ @property
+ def email(self) -> str: ...
+
+
+def marketing_allowed(user: MarketingConsent) -> bool:
+ # Shared-cache entries can outlive a rolling deploy. A user pickled by the
+ # previous version has no `marketing_opt_out_at`, so read it defensively
+ # until that cache entry expires. Its consent is unknown, so this fails
+ # closed without raising: only the MailerLite change is skipped, never the
+ # caller's own work (a trial notice), and the backfills catch it up.
+ return getattr(user, "marketing_opt_out_at", _MISSING) is None
+
+
+def audience_change_allowed(user: MarketingContact, action: AudienceAction) -> bool:
+ """Whether `action` may be queued for this account. A refusal is logged."""
+ if marketing_allowed(user):
+ return True
+ log_opted_out_skip(user.email, action.value)
+ return False
+
+
+def log_opted_out_skip(email: str, what: str) -> None:
+ """At debug level and by pseudonym, so the address never reaches a log."""
+ logger.debug(
+ "Skipping MailerLite %s for %s: opted out of marketing", what, pseudonym(email)
+ )
diff --git a/autogpt_platform/backend/backend/notifications/consent_test.py b/autogpt_platform/backend/backend/notifications/consent_test.py
new file mode 100644
index 0000000000..3fc0b9638a
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/consent_test.py
@@ -0,0 +1,80 @@
+"""Someone who refused marketing never enters MailerLite, and the skip is
+logged at debug level by pseudonym, never by address."""
+
+import logging
+import pickle
+from datetime import UTC, datetime
+
+import pytest
+
+from backend.data.model import User
+from backend.data.notifications import AudienceAction
+from backend.data.user import BillingEmailRecipient
+from backend.notifications import consent
+from backend.notifications.mailerlite import pseudonym
+
+OPTED_OUT = datetime(2026, 10, 2, 12, 0, tzinfo=UTC)
+
+
+def _user(opted_out_at: datetime | None) -> BillingEmailRecipient:
+ return BillingEmailRecipient(
+ id="user-1", email=EMAIL, marketing_opt_out_at=opted_out_at
+ )
+
+
+def test_marketing_is_allowed_until_they_opt_out():
+ assert consent.marketing_allowed(_user(None))
+ assert not consent.marketing_allowed(_user(OPTED_OUT))
+
+
+CONSENT_FIELDS = (
+ "terms_accepted_at",
+ "terms_version",
+ "marketing_opt_out_at",
+ "marketing_opt_out_source",
+)
+
+
+def _cached_before_consent() -> User:
+ """A `User` as the shared cache hands it back when the previous release
+ pickled it, before the consent fields existed."""
+ user = User(id="user-1", email=EMAIL, created_at=OPTED_OUT, updated_at=OPTED_OUT)
+ for field in CONSENT_FIELDS:
+ del user.__dict__[field]
+ return pickle.loads(pickle.dumps(user))
+
+
+def test_a_user_cached_before_the_consent_fields_is_skipped_without_raising():
+ """During a rolling deploy its consent is unknown, so it fails closed: the
+ MailerLite change is skipped and the backfills catch it up later."""
+ stale = _cached_before_consent()
+ assert not set(CONSENT_FIELDS) & set(stale.__dict__)
+
+ assert not consent.marketing_allowed(stale)
+ assert not consent.audience_change_allowed(stale, AudienceAction.ADD_TRIAL)
+
+
+def test_an_allowed_change_logs_nothing(caplog):
+ with caplog.at_level(logging.DEBUG, logger=consent.__name__):
+ assert consent.audience_change_allowed(
+ _user(None), AudienceAction.CHECKOUT_OPENED
+ )
+ assert caplog.records == []
+
+
[email protected]("action", list(AudienceAction))
+def test_a_refused_change_is_logged_by_pseudonym_at_debug(caplog, action):
+ with caplog.at_level(logging.DEBUG, logger=consent.__name__):
+ assert not consent.audience_change_allowed(_user(OPTED_OUT), action)
+ (record,) = caplog.records
+ assert record.levelno == logging.DEBUG
+ assert pseudonym(EMAIL) in record.getMessage()
+ assert action.value in record.getMessage()
+ assert EMAIL not in caplog.text
+
+
+def test_the_skip_never_reaches_an_info_log(caplog):
+ with caplog.at_level(logging.INFO, logger=consent.__name__):
+ consent.log_opted_out_skip(EMAIL, "checkout_opened")
+ assert caplog.records == []
diff --git a/autogpt_platform/backend/backend/notifications/lifecycle.py b/autogpt_platform/backend/backend/notifications/lifecycle.py
index 9faa63807f..4e7ba14620 100644
--- a/autogpt_platform/backend/backend/notifications/lifecycle.py
+++ b/autogpt_platform/backend/backend/notifications/lifecycle.py
@@ -6,6 +6,10 @@ the false→true flip rather than every subscription update — live here rather
than in the webhook router, so the webhook stays a dispatcher.
Trial enrollment and conversion notices are handled separately in `trial.py`.
+
+A customer who opted out of marketing still gets every one of these emails;
+only the MailerLite audience changes that ride along are skipped for them
+(`consent.py`).
"""
import logging
@@ -28,6 +32,7 @@ from backend.data.notifications import (
from backend.data.stripe_client import stripe_call
from backend.data.user import BillingEmailRecipient
from backend.notifications import subscriber_fields
+from backend.notifications.consent import audience_change_allowed
from backend.notifications.dedupe import claim_once, release_claim
from backend.notifications.lifecycle_plan import (
card_from_invoice,
@@ -113,6 +118,8 @@ async def on_checkout_completed(session: dict, subscription: dict) -> None:
fields = subscriber_fields.subscribed(subscription.get("start_date"))
if user.welcome_email_sent_at is not None:
+ if not audience_change_allowed(user, AudienceAction.ADD_CHANGELOG):
+ return
event = audience_event(
AudienceAction.ADD_CHANGELOG, user.email, user.id, fields
)
@@ -151,6 +158,8 @@ async def on_checkout_completed(session: dict, subscription: dict) -> None:
await _release_welcome(user)
raise
+ if not audience_change_allowed(user, AudienceAction.ENROLL_TOUR):
+ return
# Must not propagate: the welcome is already out and the claim is durable,
# so a Stripe retry would take the returning-customer branch and enrol them
# in the changelog instead of the tour. Report it rather than fail.
@@ -266,9 +275,8 @@ async def on_subscription_updated(subscription: dict, previous: dict) -> None:
),
claim_key,
)
- await subscriber_fields.queue_fields(
- user.id,
- user.email,
+ await _queue_fields(
+ user,
subscriber_fields.subscription_canceled(subscription.get("canceled_at")),
)
return
@@ -288,9 +296,7 @@ async def on_subscription_updated(subscription: dict, previous: dict) -> None:
),
claim_key,
)
- await subscriber_fields.queue_fields(
- user.id, user.email, subscriber_fields.subscription_resumed()
- )
+ await _queue_fields(user, subscriber_fields.subscription_resumed())
async def on_subscription_deleted(subscription: dict) -> None:
@@ -329,6 +335,8 @@ async def on_subscription_deleted(subscription: dict) -> None:
user_id=user.id, subscription_tier=tier, billing_cycle=cycle, reason=reason
)
# Churned users get win-back only, never the monthly update.
+ if not audience_change_allowed(user, AudienceAction.REMOVE_CHANGELOG):
+ return
event = audience_event(
AudienceAction.REMOVE_CHANGELOG,
user.email,
@@ -339,6 +347,13 @@ async def on_subscription_deleted(subscription: dict) -> None:
await queue_audience_change(event)
+async def _queue_fields(
+ user: BillingEmailRecipient, fields: subscriber_fields.Fields
+) -> None:
+ if audience_change_allowed(user, AudienceAction.UPDATE_FIELDS):
+ await subscriber_fields.queue_fields(user.id, user.email, fields)
+
+
def _churn_reason(subscription: dict) -> str | None:
"""Stripe's ``cancellation_details.reason``, except that our own cancel
after a failed renewal is involuntary churn, not a requested one."""
diff --git a/autogpt_platform/backend/backend/notifications/lifecycle_test.py b/autogpt_platform/backend/backend/notifications/lifecycle_test.py
index 3b81448e3e..92e5651400 100644
--- a/autogpt_platform/backend/backend/notifications/lifecycle_test.py
+++ b/autogpt_platform/backend/backend/notifications/lifecycle_test.py
@@ -25,6 +25,7 @@ from backend.notifications import lifecycle, lifecycle_plan, subscriber_fields
from backend.notifications.lifecycle_plan import card_from_invoice
CUSTOMER = "cus_1"
+OPTED_OUT = datetime(2026, 10, 2, tzinfo=timezone.utc)
PLAN_PATCH = "backend.notifications.lifecycle.plan_from_subscription"
INVOICE_PLAN_PATCH = "backend.notifications.lifecycle.plan_from_invoice"
@@ -32,11 +33,12 @@ INVOICE_PLAN_PATCH = "backend.notifications.lifecycle.plan_from_invoice"
class _User:
"""Shaped like `BillingEmailRecipient`, which is what the RPC returns."""
- def __init__(self, welcome_sent_at=None):
+ def __init__(self, welcome_sent_at=None, opted_out_at=None):
self.id = "user-1"
self.email = "[email protected]"
self.name = "Sam Carter"
self.welcome_email_sent_at = welcome_sent_at
+ self.marketing_opt_out_at = opted_out_at
def _subscription(**over) -> dict:
@@ -692,3 +694,82 @@ async def test_welcome_matches_the_recipients_expert_access(enabled, error, capl
finally:
for item in reversed(patches):
item.stop()
+
+
+# ── opted out of marketing ─────────────────────────────────────────────────
+#
+# Every billing email still goes out; MailerLite never hears of them.
+
+
+async def test_an_opted_out_first_subscription_is_welcomed_but_not_enrolled():
+ user = _User(welcome_sent_at=None, opted_out_at=OPTED_OUT)
+ with patch(
+ "backend.notifications.lifecycle._claim_welcome",
+ AsyncMock(return_value=True),
+ ) as claimed:
+ calls = await _run(
+ lambda: lifecycle.on_checkout_completed(
+ {"customer": CUSTOMER}, _subscription()
+ ),
+ user,
+ )
+ claimed.assert_awaited_once_with(user)
+ queued = calls["notify"].await_args.args[0]
+ assert queued.type is NotificationType.SUBSCRIPTION_WELCOME
+ calls["audience"].assert_not_called()
+
+
+async def test_an_opted_out_returning_customer_is_not_added_to_the_changelog():
+ user = _User(
+ welcome_sent_at=datetime(2026, 1, 1, tzinfo=timezone.utc),
+ opted_out_at=OPTED_OUT,
+ )
+ calls = await _run(
+ lambda: lifecycle.on_checkout_completed(
+ {"customer": CUSTOMER}, _subscription()
+ ),
+ user,
+ )
+ calls["notify"].assert_not_awaited()
+ calls["audience"].assert_not_called()
+
+
+ "subscription, previous, sent",
+ [
+ (
+ _subscription(cancel_at_period_end=True, canceled_at=1789100000),
+ {"cancel_at_period_end": False},
+ NotificationType.SUBSCRIPTION_CANCELLED,
+ ),
+ (
+ _subscription(cancel_at_period_end=False),
+ {"cancel_at_period_end": True, "canceled_at": 1789100000},
+ NotificationType.SUBSCRIPTION_RESUMED,
+ ),
+ ],
+ ids=["cancelled", "resumed"],
+)
+async def test_an_opted_out_cancel_or_resume_emails_but_writes_no_fields(
+ fields_on, subscription, previous, sent
+):
+ calls = await _run(
+ lambda: lifecycle.on_subscription_updated(subscription, previous),
+ _User(opted_out_at=OPTED_OUT),
+ )
+ assert calls["notify"].await_args.args[0].type is sent
+ fields_on.assert_not_called()
+
+
+async def test_an_opted_out_churn_emails_but_leaves_mailerlite_alone():
+ calls = await _run(
+ lambda: lifecycle.on_subscription_deleted(_subscription()),
+ _User(opted_out_at=OPTED_OUT),
+ )
+ queued = calls["notify"].await_args.args[0]
+ assert queued.type is NotificationType.SUBSCRIPTION_ENDED
+ calls["audience"].assert_not_called()
diff --git a/autogpt_platform/backend/backend/notifications/mailerlite.py b/autogpt_platform/backend/backend/notifications/mailerlite.py
index e59ab96e41..ba3cced75f 100644
--- a/autogpt_platform/backend/backend/notifications/mailerlite.py
+++ b/autogpt_platform/backend/backend/notifications/mailerlite.py
@@ -19,6 +19,14 @@ transition:
checkout joins it, and nobody else enters MailerLite through us: a signup
alone does not create a subscriber. GTM segments it for outreach.
+Someone who opted out of marketing enters none of these. Every write below
+upserts the subscriber, a removal or a field update included, so nothing is
+queued for them at all (`consent.py`), the backfills leave them out, and the
+consumer re-reads the opt-out right before each write, which drops a change
+queued just before the refusal. The one exception is `unsubscribe`, which
+carries the refusal itself to someone MailerLite already has, and never
+creates a subscriber.
+
Subscriber fields (`SubscriberField`) are the backend's alone: every write
comes from here, and MailerLite automations only read them.
@@ -42,7 +50,7 @@ from backend.util.settings import Settings
logger = logging.getLogger(__name__)
-def _pseudonym(email: str) -> str:
+def pseudonym(email: str) -> str:
"""A stable, non-reversible handle for logs.
A subscriber's address is personal data; putting it in a log line or an
@@ -57,6 +65,9 @@ settings = Settings()
API_BASE = settings.config.mailerlite_api_url.rstrip("/")
_OK_STATUSES = (200, 201, 202, 204)
+# Subscriber statuses MailerLite sends nothing to, so an unsubscribe has
+# nothing left to do. The API cannot set them back to active either.
+_NOT_MAILED_STATUSES = ("unsubscribed", "bounced", "junk")
# The type MailerLite stores each of our custom fields as, which is also what
# `ensure_fields` creates. A date is written YYYY-MM-DD.
@@ -208,6 +219,38 @@ async def record_checkout_opened(email: str, fields: Fields | None = None) -> No
)
+async def unsubscribe(email: str, fields: Fields | None = None) -> None:
+ """The account refused marketing: mark the subscriber unsubscribed so no
+ campaign or automation reaches them. Someone MailerLite does not have is
+ left alone, since creating a subscriber is exactly what the refusal rules
+ out, and so is one MailerLite already does not mail. `fields` is ignored:
+ nothing else is written for someone who refused.
+
+ An update by subscriber ID (`PUT /subscribers/{id}`), not the upsert the
+ other writes use, so it can never create anyone."""
+ _require_token()
+ subscriber = await _find_subscriber(email)
+ if subscriber is None or not subscriber.get("id"):
+ logger.info(
+ f"No MailerLite subscriber for {pseudonym(email)}; nothing to unsubscribe"
+ )
+ return
+ if subscriber.get("status") in _NOT_MAILED_STATUSES:
+ return
+ response = await _client().put(
+ f"{API_BASE}/subscribers/{subscriber['id']}",
+ headers=_headers(),
+ json={"status": "unsubscribed"},
+ )
+ # 404 means the subscriber was deleted since the lookup: nobody to mail.
+ if response.status not in _OK_STATUSES and response.status != 404:
+ raise MailerLiteError(
+ f"Unsubscribing MailerLite subscriber {pseudonym(email)} failed with "
+ f"{response.status}"
+ )
+ logger.info(f"Unsubscribed {pseudonym(email)} in MailerLite")
+
+
async def ensure_fields() -> list[SubscriberField]:
"""Create any of our fields MailerLite does not have yet, and return the
ones created. Idempotent, and checked once per process."""
@@ -279,7 +322,7 @@ async def _remove_from_group(
subscriber_id = await _find_subscriber_id(email)
if subscriber_id is None:
logger.info(
- "No MailerLite subscriber for %s; nothing to remove", _pseudonym(email)
+ "No MailerLite subscriber for %s; nothing to remove", pseudonym(email)
)
return
@@ -290,10 +333,10 @@ async def _remove_from_group(
# 404 means they are already out of the group, which is the desired state.
if response.status not in _OK_STATUSES and response.status != 404:
raise MailerLiteError(
- f"Removing subscriber {_pseudonym(email)} from the {description} group "
+ f"Removing subscriber {pseudonym(email)} from the {description} group "
f"failed with {response.status}"
)
- logger.info(f"Removed {_pseudonym(email)} from the MailerLite {description} group")
+ logger.info(f"Removed {pseudonym(email)} from the MailerLite {description} group")
async def _add_to_group(
@@ -308,7 +351,7 @@ async def _add_to_group(
await ensure_fields()
body["fields"] = _payload(fields)
await _upsert(email, body, f"{description} group")
- logger.info("Added %s to the MailerLite %s group", _pseudonym(email), description)
+ logger.info("Added %s to the MailerLite %s group", pseudonym(email), description)
async def _upsert(email: str, body: dict, description: str) -> None:
@@ -317,7 +360,7 @@ async def _upsert(email: str, body: dict, description: str) -> None:
)
if response.status not in _OK_STATUSES:
raise MailerLiteError(
- f"MailerLite {description} for subscriber {_pseudonym(email)} "
+ f"MailerLite {description} for subscriber {pseudonym(email)} "
f"failed with {response.status}"
)
@@ -338,7 +381,7 @@ async def _find_subscriber(email: str) -> dict | None:
return None
if response.status not in _OK_STATUSES:
raise MailerLiteError(
- f"Looking up MailerLite subscriber {_pseudonym(email)} failed with "
+ f"Looking up MailerLite subscriber {pseudonym(email)} failed with "
f"{response.status}"
)
return (response.json() or {}).get("data") or {}
diff --git a/autogpt_platform/backend/backend/notifications/mailerlite_backfill.py b/autogpt_platform/backend/backend/notifications/mailerlite_backfill.py
index 7a30c462b3..7139bf0428 100644
--- a/autogpt_platform/backend/backend/notifications/mailerlite_backfill.py
+++ b/autogpt_platform/backend/backend/notifications/mailerlite_backfill.py
@@ -10,6 +10,9 @@ the tour group is left alone: they are either mid-tour, and must not get the
changelog yet, or they finished it and MailerLite's automation has already
moved them across.
+A customer who opted out of marketing is left out entirely, removals
+included: they never enter MailerLite (`consent.py`).
+
Idempotent by construction: current membership is read first, so a second run
finds nothing to do and a failed call is simply picked up by the next run.
"""
@@ -17,19 +20,21 @@ finds nothing to do and a failed call is simply picked up by the next run.
import asyncio
import logging
import re
+from datetime import datetime
from enum import Enum
from typing import Any
from urllib.parse import urlencode
from pydantic import BaseModel
+from backend.notifications.consent import marketing_allowed
from backend.notifications.mailerlite import (
API_BASE,
MailerLiteError,
_client,
_headers,
- _pseudonym,
_require_config,
+ pseudonym,
)
from backend.util.settings import Settings
@@ -66,6 +71,7 @@ class Decision(str, Enum):
SKIP_IN_TOUR = "skip_in_tour"
SKIP_NO_TRIAL_GROUP = "skip_no_trial_group"
SKIP_UNSETTLED = "skip_unsettled"
+ SKIP_OPTED_OUT = "skip_opted_out"
ALREADY_CORRECT = "already_correct"
@@ -101,6 +107,8 @@ class Customer(BaseModel):
user_id: str
email: str
subscriptions: list[Subscription]
+ # Set when they refused marketing: they must never enter MailerLite.
+ marketing_opt_out_at: datetime | None = None
class Audience(BaseModel):
@@ -157,6 +165,10 @@ def decide(
customer: Customer, audience: Audience, trial_enabled: bool
) -> PlannedChange:
standing = classify(customer.subscriptions)
+ if not marketing_allowed(customer):
+ return PlannedChange(
+ customer=customer, standing=standing, decisions=[Decision.SKIP_OPTED_OUT]
+ )
email = customer.email.strip().lower()
in_tour = email in audience.tour
in_changelog = email in audience.changelog
@@ -283,7 +295,7 @@ def _refusal(email: str, answer: BatchAnswer) -> str:
"""A refused call, for the log: the pseudonym, the top-level domain and
MailerLite's reason. Enough to spot a pattern without naming anyone."""
return (
- f"{_pseudonym(email)} at {_top_level_domain(email)} with {answer.code} "
+ f"{pseudonym(email)} at {_top_level_domain(email)} with {answer.code} "
f"({_failure_reason(answer.body, email)})"
)
@@ -314,7 +326,7 @@ def _failure_reason(body: Any, email: str) -> str:
listed = problems if isinstance(problems, list) else [problems]
parts.append(f"{field}: {'; '.join(str(p) for p in listed)}")
reason = " | ".join(parts) or "no reason given"
- return re.sub(re.escape(email.strip()), _pseudonym(email), reason, flags=re.I)
+ return re.sub(re.escape(email.strip()), pseudonym(email), reason, flags=re.I)
async def _send_batch(requests: list[dict]) -> list[BatchAnswer]:
diff --git a/autogpt_platform/backend/backend/notifications/mailerlite_backfill_test.py b/autogpt_platform/backend/backend/notifications/mailerlite_backfill_test.py
index c26244ac73..2864b973ba 100644
--- a/autogpt_platform/backend/backend/notifications/mailerlite_backfill_test.py
+++ b/autogpt_platform/backend/backend/notifications/mailerlite_backfill_test.py
@@ -1,6 +1,7 @@
"""The backfill must put each existing customer where the live handlers would
have, and never fight MailerLite's own tour → changelog handoff."""
+from datetime import UTC, datetime
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
@@ -16,6 +17,7 @@ from backend.notifications.mailerlite_backfill import (
)
TOUR, CHANGELOG, TRIAL = "grp_tour", "grp_changelog", "grp_trial"
+OPTED_OUT = datetime(2026, 10, 2, tzinfo=UTC)
@pytest.fixture
@@ -282,7 +284,7 @@ async def test_apply_counts_failures_and_treats_gone_as_removed(
assert result.failed[Decision.ADD_CHANGELOG] == 1
assert result.succeeded[Decision.REMOVE_CHANGELOG] == 1
assert "[email protected]" not in caplog.text.lower()
- assert f"{mailerlite._pseudonym('[email protected]')} at .io with 422" in caplog.text
+ assert f"{mailerlite.pseudonym('[email protected]')} at .io with 422" in caplog.text
assert "The given data was invalid." in caplog.text
assert "is not a deliverable address" in caplog.text
@@ -400,3 +402,69 @@ def _paging_forever(page: dict):
return _response(200, page)
return get
+
+
+# ── opted out of marketing ─────────────────────────────────────────────────
+
+
+def _opted_out(email: str, *statuses: str) -> Customer:
+ return _customer(email, *statuses).model_copy(
+ update={"marketing_opt_out_at": OPTED_OUT}
+ )
+
+
+ "statuses, audience",
+ [
+ (["active"], _audience()),
+ (["active"], _audience(trial=["[email protected]"])),
+ (["trialing"], _audience()),
+ (["trialing+cancel"], _audience(trial=["[email protected]"])),
+ (["canceled"], _audience(changelog=["[email protected]"])),
+ (["unpaid"], _audience()),
+ ],
+)
+def test_an_opted_out_customer_is_only_ever_skipped(statuses, audience):
+ """Not even a removal: a customer who refused marketing gets no MailerLite
+ call of any kind."""
+ change = mailerlite_backfill.decide(
+ _opted_out("[email protected]", *statuses), audience, trial_enabled=True
+ )
+ assert change.decisions == [Decision.SKIP_OPTED_OUT]
+ assert Decision.SKIP_OPTED_OUT not in mailerlite_backfill.CHANGES
+
+
+async def test_apply_never_writes_an_opted_out_customer(
+ configured, no_sleep, monkeypatch
+):
+ client = MagicMock()
+ client.post = AsyncMock(
+ side_effect=lambda url, **kw: _batch_ok(kw["json"]["requests"])
+ )
+ monkeypatch.setattr(mailerlite_backfill, "_client", lambda: client)
+ audience = _audience(changelog=["[email protected]"], trial=["[email protected]"])
+ changes = mailerlite_backfill.plan(
+ [
+ _opted_out("[email protected]", "active"),
+ _opted_out("[email protected]", "canceled"),
+ _opted_out("[email protected]", "active"),
+ _customer("[email protected]", "active"),
+ ],
+ audience,
+ )
+
+ result = await mailerlite_backfill.apply(changes, audience)
+
+ sent = [call.kwargs["json"]["requests"] for call in client.post.await_args_list]
+ assert sent == [
+ [
+ {
+ "method": "POST",
+ "path": "api/subscribers",
+ "body": {"email": "[email protected]", "groups": [CHANGELOG]},
+ }
+ ]
+ ]
+ assert sum(result.succeeded.values()) == 1
+ assert sum(result.failed.values()) == 0
diff --git a/autogpt_platform/backend/backend/notifications/mailerlite_field_backfill.py b/autogpt_platform/backend/backend/notifications/mailerlite_field_backfill.py
index 23781b43e8..a760e8391c 100644
--- a/autogpt_platform/backend/backend/notifications/mailerlite_field_backfill.py
+++ b/autogpt_platform/backend/backend/notifications/mailerlite_field_backfill.py
@@ -4,7 +4,9 @@ Signups were never synced and the lifecycle handlers only react to new
events, so this works out each account's fields from scratch: the signup date
from our database, the rest from Stripe, by the rules in `subscriber_fields.py`.
Only accounts with a Stripe customer are given (see `cli/mailerlite_backfill`):
-MailerLite holds checkout openers, not every signup.
+MailerLite holds checkout openers, not every signup. An account that opted out
+of marketing is never written, since a field write creates the subscriber
+(`consent.py`).
Resumable by construction: the fields MailerLite already holds are read first
and only the difference is written, so an interrupted or repeated run picks up
@@ -20,6 +22,7 @@ from urllib.parse import urlencode
from pydantic import BaseModel, EmailStr, TypeAdapter, ValidationError
from backend.data.notifications import SubscriberField, SubscriptionStatus
+from backend.notifications.consent import marketing_allowed
from backend.notifications.mailerlite import (
API_BASE,
MailerLiteError,
@@ -59,6 +62,8 @@ class Person(BaseModel):
stripe_customer_id: str | None = None
# The browser's IANA timezone, for the checkout opener's country.
timezone: str | None = None
+ # Set when they refused marketing: they must never enter MailerLite.
+ marketing_opt_out_at: datetime | None = None
class FieldChange(BaseModel):
@@ -75,6 +80,8 @@ class FieldPlan(BaseModel):
changes: list[FieldChange]
# Addresses MailerLite would refuse, such as a reserved domain.
invalid: int
+ # People who refused marketing, left out of the plan and the statuses.
+ opted_out: int
def standing(subscriptions: list[Subscription]) -> tuple[SubscriptionStatus, Fields]:
@@ -131,9 +138,15 @@ def plan(people: list[Person], current: Current, *, create: bool = True) -> Fiel
backfill brings new people in, since a Stripe customer alone does not
mean they opened checkout (the billing portal creates one too)."""
result = FieldPlan(
- statuses={s: 0 for s in SubscriptionStatus}, changes=[], invalid=0
+ statuses={s: 0 for s in SubscriptionStatus},
+ changes=[],
+ invalid=0,
+ opted_out=0,
)
for person in people:
+ if not marketing_allowed(person):
+ result.opted_out += 1
+ continue
if not _valid(person.email):
result.invalid += 1
continue
diff --git a/autogpt_platform/backend/backend/notifications/mailerlite_field_backfill_test.py b/autogpt_platform/backend/backend/notifications/mailerlite_field_backfill_test.py
index e9604b8c7c..6db7e292db 100644
--- a/autogpt_platform/backend/backend/notifications/mailerlite_field_backfill_test.py
+++ b/autogpt_platform/backend/backend/notifications/mailerlite_field_backfill_test.py
@@ -292,3 +292,24 @@ def test_without_create_only_existing_subscribers_are_planned():
)
assert [c.person.email for c in plan.changes] == ["[email protected]"]
assert not any(c.new for c in plan.changes)
+
+
[email protected]("create", [True, False])
+def test_an_opted_out_person_is_counted_and_never_written(create):
+ """A field write creates the subscriber, so someone who refused marketing
+ is left out even when MailerLite already holds them with stale fields."""
+ opted_out = _person("[email protected]", _paid("active")).model_copy(
+ update={"marketing_opt_out_at": CREATED}
+ )
+ plan = backfill.plan(
+ [opted_out, _person("[email protected]", _paid("active"))],
+ {
+ "[email protected]": {"subscription_status": "signed"},
+ "[email protected]": {"subscription_status": "signed"},
+ },
+ create=create,
+ )
+ assert [c.person.email for c in plan.changes] == ["[email protected]"]
+ assert plan.opted_out == 1
+ assert plan.invalid == 0
+ assert plan.statuses[S.SUBSCRIBED] == 1
diff --git a/autogpt_platform/backend/backend/notifications/mailerlite_unsubscribe_test.py b/autogpt_platform/backend/backend/notifications/mailerlite_unsubscribe_test.py
new file mode 100644
index 0000000000..9db6263552
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/mailerlite_unsubscribe_test.py
@@ -0,0 +1,144 @@
+"""A refusal reaches someone MailerLite already has, and never creates anyone.
+
+`unsubscribe` is the one MailerLite write queued for an opted-out account, so
+it must not go through the upsert every other write uses: that would create
+the very subscriber the refusal rules out.
+"""
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.data.notifications import AudienceAction
+from backend.notifications import mailerlite, subscriber_fields
+from backend.notifications.notifications import NotificationManager
+
+
+
[email protected](autouse=True)
+def mailerlite_configured(monkeypatch):
+ fake = SimpleNamespace(
+ config=SimpleNamespace(
+ mailerlite_checkout_group_id="grp_checkout",
+ mailerlite_changelog_group_id="grp_changelog",
+ mailerlite_trial_group_id="",
+ ),
+ secrets=SimpleNamespace(mailerlite_api_token="token"),
+ )
+ monkeypatch.setattr(mailerlite, "settings", fake)
+ return fake
+
+
+def _response(status: int, body: dict | None = None) -> MagicMock:
+ response = MagicMock(status=status)
+ response.json.return_value = body or {}
+ return response
+
+
+def _client(held: dict | None, put_status: int = 200) -> MagicMock:
+ """MailerLite holding `held` for EMAIL (None: nobody)."""
+ client = MagicMock()
+ client.get = AsyncMock(
+ return_value=_response(404) if held is None else _response(200, {"data": held})
+ )
+ client.put = AsyncMock(return_value=_response(put_status))
+ client.post = AsyncMock(return_value=_response(200))
+ client.delete = AsyncMock(return_value=_response(200))
+ return client
+
+
[email protected]("status", ["active", "unconfirmed", None])
+async def test_a_subscriber_is_marked_unsubscribed_by_id(status):
+ client = _client({"id": "ml_1", "status": status})
+ with patch.object(mailerlite, "_client", return_value=client):
+ await mailerlite.unsubscribe(EMAIL)
+
+ client.get.assert_awaited_once()
+ assert client.get.await_args.args[0].endswith(f"/subscribers/{EMAIL}")
+ client.put.assert_awaited_once()
+ assert client.put.await_args.args[0].endswith("/subscribers/ml_1")
+ assert client.put.await_args.kwargs["json"] == {"status": "unsubscribed"}
+ client.post.assert_not_awaited()
+ client.delete.assert_not_awaited()
+
+
+async def test_someone_mailerlite_does_not_have_is_never_created(caplog):
+ client = _client(None)
+ with (
+ patch.object(mailerlite, "_client", return_value=client),
+ caplog.at_level("INFO"),
+ ):
+ await mailerlite.unsubscribe(EMAIL)
+
+ client.put.assert_not_awaited()
+ client.post.assert_not_awaited()
+ assert "nothing to unsubscribe" in caplog.text
+ assert EMAIL not in caplog.text
+
+
[email protected]("status", ["unsubscribed", "bounced", "junk"])
+async def test_a_subscriber_mailerlite_already_does_not_mail_is_left_alone(status):
+ client = _client({"id": "ml_1", "status": status})
+ with patch.object(mailerlite, "_client", return_value=client):
+ await mailerlite.unsubscribe(EMAIL)
+
+ client.put.assert_not_awaited()
+ client.post.assert_not_awaited()
+
+
+async def test_fields_are_never_written_for_someone_who_refused():
+ client = _client({"id": "ml_1", "status": "active"})
+ with patch.object(mailerlite, "_client", return_value=client):
+ await mailerlite.unsubscribe(EMAIL, {next(iter(mailerlite.FIELD_TYPES)): "x"})
+
+ assert client.put.await_args.kwargs["json"] == {"status": "unsubscribed"}
+ client.post.assert_not_awaited()
+
+
+async def test_a_subscriber_deleted_since_the_lookup_is_done():
+ client = _client({"id": "ml_1", "status": "active"}, put_status=404)
+ with patch.object(mailerlite, "_client", return_value=client):
+ await mailerlite.unsubscribe(EMAIL)
+
+
+async def test_a_failed_write_raises_so_the_queue_retries():
+ client = _client({"id": "ml_1", "status": "active"}, put_status=500)
+ with (
+ patch.object(mailerlite, "_client", return_value=client),
+ pytest.raises(mailerlite.MailerLiteError) as raised,
+ ):
+ await mailerlite.unsubscribe(EMAIL)
+
+ assert EMAIL not in str(raised.value)
+ assert mailerlite.pseudonym(EMAIL) in str(raised.value)
+
+
+async def test_without_a_token_it_is_not_configured(mailerlite_configured):
+ mailerlite_configured.secrets.mailerlite_api_token = ""
+ with pytest.raises(mailerlite.MailerLiteNotConfigured):
+ await mailerlite.unsubscribe(EMAIL)
+
+
+async def test_the_consumer_routes_an_unsubscribe_to_it(monkeypatch):
+ handler = AsyncMock()
+ monkeypatch.setattr(mailerlite, "unsubscribe", handler)
+ event = subscriber_fields.audience_event(
+ AudienceAction.UNSUBSCRIBE, EMAIL, "user-1"
+ )
+ assert event is not None
+
+ assert await NotificationManager._process_audience_change(
+ MagicMock(), event.model_dump_json()
+ )
+
+ handler.assert_awaited_once_with(EMAIL, None)
diff --git a/autogpt_platform/backend/backend/notifications/notifications.py b/autogpt_platform/backend/backend/notifications/notifications.py
index 042bff0f0c..aaecd3854a 100644
--- a/autogpt_platform/backend/backend/notifications/notifications.py
+++ b/autogpt_platform/backend/backend/notifications/notifications.py
@@ -36,6 +36,7 @@ from backend.data.user import (
generate_unsubscribe_link,
)
from backend.notifications import briefing_runner, mailerlite
+from backend.notifications.consent import log_opted_out_skip
from backend.notifications.dedupe import claim_daily_send
from backend.notifications.email import EmailSender
from backend.notifications.preferences import SERVICE_MESSAGES, wants_notification
@@ -74,6 +75,18 @@ def _utc_today() -> date:
return datetime.now(tz=timezone.utc).date()
+async def _opted_out_since_queued(event: AudienceEventModel) -> bool:
+ """Re-read the opt-out right before the write. A change queued just before
+ the account refused marketing must not reach MailerLite: every write but the
+ unsubscribe upserts the subscriber. The unsubscribe is the refusal itself,
+ so it always goes through."""
+ if event.action is AudienceAction.UNSUBSCRIBE:
+ return False
+ return await get_database_manager_async_client(
+ should_retry=False
+ ).is_marketing_opted_out(event.user_id)
+
+
def _is_channel_loss(error: BaseException) -> bool:
"""Every leaf is the queue iterator failing to nack on a dead channel.
@@ -392,6 +405,10 @@ class NotificationManager(AppService):
_mailerlite_off_logged = True
return True
+ if await _opted_out_since_queued(event):
+ log_opted_out_skip(event.email, event.action.value)
+ return True
+
handler = {
AudienceAction.ENROLL_TOUR: mailerlite.enroll_in_onboarding,
AudienceAction.ADD_CHANGELOG: mailerlite.add_to_changelog,
@@ -401,6 +418,7 @@ class NotificationManager(AppService):
AudienceAction.UPDATE_FIELDS: mailerlite.update_fields,
AudienceAction.SIGNUP: mailerlite.record_signup,
AudienceAction.CHECKOUT_OPENED: mailerlite.record_checkout_opened,
+ AudienceAction.UNSUBSCRIBE: mailerlite.unsubscribe,
}[event.action]
try:
await handler(event.email, event.fields or None)
diff --git a/autogpt_platform/backend/backend/notifications/trial.py b/autogpt_platform/backend/backend/notifications/trial.py
index b9fe29d519..f35d023f50 100644
--- a/autogpt_platform/backend/backend/notifications/trial.py
+++ b/autogpt_platform/backend/backend/notifications/trial.py
@@ -88,7 +88,7 @@ async def notify_trial(subscription: dict, kind: TrialNoticeKind) -> bool:
if not await claim_once(claim):
return True
try:
- await queue_trial_audience_change(kind, user_id, user.email, current)
+ await queue_trial_audience_change(kind, user, current)
result = await queue_notification_async(
NotificationEventModel[TrialUpdateData](
user_id=user_id, type=NotificationType.TRIAL_UPDATE, data=data
@@ -100,7 +100,7 @@ async def notify_trial(subscription: dict, kind: TrialNoticeKind) -> bool:
await release_claim(claim)
raise
if kind == "converted":
- await join_paying_audience(user_id, user.email)
+ await join_paying_audience(user)
_track_billing_event(
TRIAL_NOTICE_EVENTS[kind],
user_id,
diff --git a/autogpt_platform/backend/backend/notifications/trial_audience.py b/autogpt_platform/backend/backend/notifications/trial_audience.py
index 510522e28d..3a007306ef 100644
--- a/autogpt_platform/backend/backend/notifications/trial_audience.py
+++ b/autogpt_platform/backend/backend/notifications/trial_audience.py
@@ -11,6 +11,9 @@ paying audience the way a first checkout does.
The subscriber's status and dates (`subscriber_fields.py`) ride on the same
event. The notification service writes only the fields while the trial group
is not configured.
+
+Nothing is queued for a customer who opted out of marketing (`consent.py`);
+their trial notices and claims are unaffected.
"""
import logging
@@ -19,6 +22,7 @@ from collections.abc import Callable, Mapping
from backend.data.db_accessors import user_db
from backend.data.notifications import AudienceAction
from backend.notifications import subscriber_fields
+from backend.notifications.consent import MarketingContact, audience_change_allowed
from backend.notifications.queue import queue_audience_change
from backend.notifications.subscriber_fields import Fields, audience_event
@@ -46,7 +50,7 @@ _TRIAL_FIELDS: Mapping[str, Callable[[dict], Fields]] = {
async def queue_trial_audience_change(
- kind: str, user_id: str, email: str, subscription: dict
+ kind: str, user: MarketingContact, subscription: dict
) -> None:
"""Queue the trial group change and field update for this notice, if it
has either.
@@ -57,9 +61,10 @@ async def queue_trial_audience_change(
settings: only the notification service holds them.
"""
action = _TRIAL_GROUP_CHANGES.get(kind)
- if action is None:
+ if action is None or not audience_change_allowed(user, action):
return
- event = audience_event(action, email, user_id, _TRIAL_FIELDS[kind](subscription))
+ fields = _TRIAL_FIELDS[kind](subscription)
+ event = audience_event(action, user.email, user.id, fields)
if event is None:
return
result = await queue_audience_change(event)
@@ -67,28 +72,32 @@ async def queue_trial_audience_change(
raise RuntimeError(f"Could not queue {action.value}: {result.message}")
-async def join_paying_audience(user_id: str, email: str) -> None:
+async def join_paying_audience(user: MarketingContact) -> None:
"""The onboarding tour for a first subscription, else the changelog.
The conversion notice stands in for the subscription welcome, so this takes
the same welcome claim a first checkout does: a later resubscription is
- then treated as the returning customer it is. Called once the notice is
+ then treated as the returning customer it is. A customer who opted out of
+ marketing takes the claim too, since it decides who gets the welcome
+ email, and only the audience change is skipped. Called once the notice is
out, so, like the tour enrolment after a welcome, a failure is reported
rather than raised: a Stripe retry would find the notice claimed and do
nothing, so raising could only fail the webhook.
"""
try:
- first = await user_db().claim_welcome_email(user_id)
+ first = await user_db().claim_welcome_email(user.id)
action = AudienceAction.ENROLL_TOUR if first else AudienceAction.ADD_CHANGELOG
- event = audience_event(action, email, user_id)
+ if not audience_change_allowed(user, action):
+ return
+ event = audience_event(action, user.email, user.id)
if event is None:
return
result = await queue_audience_change(event)
except Exception:
- logger.exception(f"Trial for user {user_id} converted but was not enrolled")
+ logger.exception(f"Trial for user {user.id} converted but was not enrolled")
return
if not result.success:
logger.error(
- f"Trial for user {user_id} converted but {action.value} could not be "
+ f"Trial for user {user.id} converted but {action.value} could not be "
f"queued: {result.message}"
)
diff --git a/autogpt_platform/backend/backend/notifications/trial_audience_test.py b/autogpt_platform/backend/backend/notifications/trial_audience_test.py
index 8df26ee8ed..71cc2df3f2 100644
--- a/autogpt_platform/backend/backend/notifications/trial_audience_test.py
+++ b/autogpt_platform/backend/backend/notifications/trial_audience_test.py
@@ -8,6 +8,7 @@ from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from prisma.enums import NotificationType
from backend.data.notifications import (
AudienceAction,
@@ -22,6 +23,7 @@ from backend.notifications import mailerlite
from backend.notifications import notifications as delivery
from backend.notifications import trial as notices
from backend.notifications import trial_audience
+from backend.notifications.consent_test import _cached_before_consent
from backend.notifications.notifications import NotificationManager
@@ -108,10 +110,14 @@ async def _notify(
raises=False,
email=EMAIL,
claim_welcome=None,
+ opted_out_at=None,
+ user=None,
):
audience = audience or AsyncMock(return_value=NotificationResult(success=True))
notice = AsyncMock(return_value=NotificationResult(success=True))
- user = SimpleNamespace(name="Sam", email=email)
+ user = user or SimpleNamespace(
+ id="user-1", name="Sam", email=email, marketing_opt_out_at=opted_out_at
+ )
users = MagicMock(
get_user_by_id=AsyncMock(return_value=user),
claim_welcome_email=claim_welcome or AsyncMock(return_value=not welcomed),
@@ -240,6 +246,52 @@ async def test_joining_the_paying_audience_never_fails_the_sent_conversion(trial
release.assert_not_awaited()
[email protected]("kind", ["started", "canceled", "resumed", "ended"])
+async def test_an_opted_out_trialist_gets_the_notice_but_no_group_change(trial, kind):
+ trial, raw = _state(trial, kind)
+ got, notice, release = await _notify(
+ trial, raw, kind, opted_out_at=datetime.now(UTC)
+ )
+ assert got == []
+ notice.assert_awaited_once()
+ release.assert_not_awaited()
+
+
[email protected]("welcomed", [False, True])
+async def test_an_opted_out_conversion_still_takes_the_welcome_claim(trial, welcomed):
+ """The claim decides whether a later resubscription is welcomed as a first
+ subscription; that is service mail, so it is taken whatever the consent.
+ Only the tour or changelog is skipped."""
+ trial, raw = _state(trial, "converted")
+ claim = AsyncMock(return_value=not welcomed)
+ got, notice, _ = await _notify(
+ trial, raw, "converted", claim_welcome=claim, opted_out_at=datetime.now(UTC)
+ )
+ assert got == []
+ claim.assert_awaited_once_with("user-1")
+ notice.assert_awaited_once()
+
+
[email protected]("kind", ["started", "canceled", "converted"])
+async def test_a_trialist_cached_before_the_consent_fields_still_gets_the_notice(
+ trial, kind
+):
+ """During a rolling deploy the shared cache can hand back a user pickled by
+ the previous release, with no opt-out to read. Its MailerLite changes are
+ skipped; the notice is still queued and its claim kept."""
+ trial, raw = _state(trial, kind)
+ got, notice, release = await _notify(
+ trial, raw, kind, user=_cached_before_consent()
+ )
+ assert got == []
+ notice.assert_awaited_once()
+ assert notice.await_args_list[0].args[0].type == NotificationType.TRIAL_UPDATE
+ release.assert_not_awaited()
+
+
@pytest.fixture
def consumer_configured(monkeypatch):
monkeypatch.setattr(mailerlite, "configured", lambda: True)
diff --git a/autogpt_platform/backend/backend/notifications/trial_test.py b/autogpt_platform/backend/backend/notifications/trial_test.py
index d402b21e49..9456d133d0 100644
--- a/autogpt_platform/backend/backend/notifications/trial_test.py
+++ b/autogpt_platform/backend/backend/notifications/trial_test.py
@@ -141,7 +141,12 @@ async def test_notice_uses_shared_notification_queue(trial, outcome):
"user_db",
return_value=MagicMock(
get_user_by_id=AsyncMock(
- return_value=SimpleNamespace(name="Sam", email="[email protected]")
+ return_value=SimpleNamespace(
+ id="user-1",
+ name="Sam",
+ marketing_opt_out_at=None,
+ )
)
),
),
diff --git a/autogpt_platform/backend/backend/util/settings.py b/autogpt_platform/backend/backend/util/settings.py
index b8f2ee81b6..7c5a157d5d 100644
--- a/autogpt_platform/backend/backend/util/settings.py
+++ b/autogpt_platform/backend/backend/util/settings.py
@@ -1130,6 +1130,13 @@ class Secrets(UpdateTrackingModel["Secrets"], BaseSettings):
default="",
description="MailerLite API token used to manage tour and changelog audiences",
)
+ mailerlite_webhook_secret: str = Field(
+ default="",
+ description=(
+ "Signing secret of the MailerLite webhook that reports unsubscribes. "
+ "Blank refuses every call to that webhook."
+ ),
+ )
unsubscribe_secret_key: str = Field(
default="",
diff --git a/autogpt_platform/backend/migrations/20261007120000_user_consent_fields/migration.sql b/autogpt_platform/backend/migrations/20261007120000_user_consent_fields/migration.sql
new file mode 100644
index 0000000000..6bdd7f0930
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20261007120000_user_consent_fields/migration.sql
@@ -0,0 +1,9 @@
+-- Consent captured at signup (SECRT-2783): which terms the account agreed to
+-- and when, and a marketing opt-out that keeps it out of MailerLite.
+
+-- Nullable with no default: a catalog-only change, no table rewrite.
+-- AlterTable
+ALTER TABLE "User" ADD COLUMN "marketingOptOutAt" TIMESTAMP(3),
+ADD COLUMN "marketingOptOutSource" TEXT,
+ADD COLUMN "termsAcceptedAt" TIMESTAMP(3),
+ADD COLUMN "termsVersion" TEXT;
diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prisma
index 9fd355e203..6a21eef230 100644
--- a/autogpt_platform/backend/schema.prisma
+++ b/autogpt_platform/backend/schema.prisma
@@ -129,6 +129,14 @@ model User {
timezone String @default("not-set")
+ // Consent captured at signup. termsVersion names the terms and privacy
+ // policy text the account agreed to (frontend lib/legal.ts TERMS_VERSION).
+ // A set marketingOptOutAt keeps the account out of MailerLite entirely.
+ termsAcceptedAt DateTime?
+ termsVersion String?
+ marketingOptOutAt DateTime?
+ marketingOptOutSource String? // "signup" | "email_unsubscribe" | "settings"
+
// Default AutoPilot connection for chats the caller didn't route explicitly
// (bot links, schedules, a fresh /copilot session). NULL means "automatic" —
// the server picks, exactly as it did before this setting existed. The
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 59e2f05968..299c7d816b 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
@@ -1,3 +1,4 @@
+import { TERMS_VERSION } from "@/lib/legal";
import { APIError } from "better-auth/api";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -8,6 +9,7 @@ const getOnboardingStatusMock = vi.fn();
const captureExceptionMock = vi.fn();
const scheduleAccountCreatedGoalMock = vi.fn();
const markAccountCreatedMock = vi.fn();
+const recordUserConsentMock = vi.fn();
vi.mock("@/lib/auth/auth", () => ({
auth: {
@@ -23,6 +25,8 @@ vi.mock("@/lib/auth/server/rollbackSession", () => ({
vi.mock("@/app/api/__generated__/endpoints/auth/auth", () => ({
postV1GetOrCreateUser: (...args: unknown[]) => createUserMock(...args),
+ postV1RecordUserConsent: (...args: unknown[]) =>
+ recordUserConsentMock(...args),
}));
vi.mock("@/services/analytics/datafast-server", async (importOriginal) => ({
@@ -69,6 +73,7 @@ beforeEach(() => {
captureExceptionMock.mockReset();
scheduleAccountCreatedGoalMock.mockReset();
markAccountCreatedMock.mockReset();
+ recordUserConsentMock.mockReset().mockResolvedValue({ status: 200 });
vi.spyOn(console, "error").mockImplementation(() => undefined);
});
@@ -209,6 +214,34 @@ describe("login", () => {
expect(result).toEqual({ success: true, next: "/onboarding" });
});
+ it("records the terms when this login is the call that created the account", async () => {
+ // A mail scanner opened the verification link first, so the owner's own
+ // sign-in is what sets the account up.
+ signInEmailMock.mockResolvedValue({ user: { id: "user-1" } });
+ createUserMock.mockResolvedValue(userResponse(true));
+ getOnboardingStatusMock.mockResolvedValue({ shouldShowOnboarding: true });
+
+ await login("[email protected]", "hunter2-password");
+
+ expect(recordUserConsentMock).toHaveBeenCalledTimes(1);
+ expect(recordUserConsentMock).toHaveBeenCalledWith({
+ terms_version: TERMS_VERSION,
+ marketing_opt_out: false,
+ });
+ });
+
+ it("still signs the new account in when the consent write fails", async () => {
+ signInEmailMock.mockResolvedValue({ user: { id: "user-1" } });
+ createUserMock.mockResolvedValue(userResponse(true));
+ recordUserConsentMock.mockRejectedValue(new Error("backend down"));
+ getOnboardingStatusMock.mockResolvedValue({ shouldShowOnboarding: true });
+
+ const result = await login("[email protected]", "hunter2-password");
+
+ expect(rollbackSessionMock).not.toHaveBeenCalled();
+ 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));
@@ -218,6 +251,7 @@ describe("login", () => {
expect(scheduleAccountCreatedGoalMock).not.toHaveBeenCalled();
expect(markAccountCreatedMock).not.toHaveBeenCalled();
+ expect(recordUserConsentMock).not.toHaveBeenCalled();
});
it("rolls back and counts nothing when provisioning answers an error status", async () => {
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 395bb99063..77a22b2697 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/login/actions.ts
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/login/actions.ts
@@ -6,6 +6,7 @@ import {
EMAIL_NOT_VERIFIED_CODE,
getEmailVerificationCallbackURL,
} from "@/lib/auth/email-verification";
+import { recordSignupConsent } from "@/lib/auth/server/recordSignupConsent";
import { rollbackSession } from "@/lib/auth/server/rollbackSession";
import { markAccountCreated } from "@/services/analytics/account-created-server";
import {
@@ -33,16 +34,18 @@ export async function login(
};
}
+ let userID: string;
try {
- await auth.api.signInEmail({
+ const signInResult = await auth.api.signInEmail({
body: {
email: parsed.data.email,
password: parsed.data.password,
// Only used for the link Better Auth emails to an unverified user.
- callbackURL: getEmailVerificationCallbackURL(next),
+ callbackURL: getEmailVerificationCallbackURL({ next }),
},
headers: await headers(),
});
+ userID = signInResult.user.id;
} catch (error) {
if (error instanceof APIError) {
// Right password, unverified address: Better Auth has just emailed a
@@ -78,6 +81,10 @@ export async function login(
if (accountCreated) {
await scheduleAccountCreatedGoal("email");
await markAccountCreated("email");
+ // The account was made on /signup, under its legal line, so the terms
+ // are recorded here. A refusal made there rode in the verification link
+ // and can't be recovered at login (SECRT-2851). Never throws.
+ await recordSignupConsent({ userID, marketingOptOut: false });
}
const { shouldShowOnboarding } = await getOnboardingStatus();
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 3e1b0a9c8e..2de2708dc1 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
@@ -1,3 +1,5 @@
+import { ApiError } from "@/lib/autogpt-server-api/helpers";
+import { TERMS_VERSION } from "@/lib/legal";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { signup } from "../actions";
@@ -7,12 +9,14 @@ const mocks = vi.hoisted(() => ({
signUpEmail: vi.fn(),
rollbackSession: vi.fn(),
postV1GetOrCreateUser: vi.fn(),
+ postV1RecordUserConsent: vi.fn(),
scheduleAccountCreatedGoal: vi.fn(),
cookieSet: vi.fn(),
}));
vi.mock("@/app/api/__generated__/endpoints/auth/auth", () => ({
postV1GetOrCreateUser: mocks.postV1GetOrCreateUser,
+ postV1RecordUserConsent: mocks.postV1RecordUserConsent,
}));
vi.mock("@/app/api/helpers", () => ({
getOnboardingStatus: mocks.getOnboardingStatus,
@@ -46,7 +50,10 @@ describe("email signup account creation tracking", () => {
vi.clearAllMocks();
// 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.signUpEmail.mockResolvedValue({
+ token: "session-token",
+ user: { id: "user-1" },
+ });
mocks.getOnboardingStatus.mockResolvedValue({
shouldShowOnboarding: true,
});
@@ -63,7 +70,7 @@ describe("email signup account creation tracking", () => {
"ValidPassword123!",
"ValidPassword123!",
- true,
+ false,
);
expect(result.success).toBe(true);
@@ -89,12 +96,13 @@ describe("email signup account creation tracking", () => {
"ValidPassword123!",
"ValidPassword123!",
- true,
+ false,
);
expect(result.success).toBe(true);
expect(mocks.scheduleAccountCreatedGoal).not.toHaveBeenCalled();
expect(mocks.cookieSet).not.toHaveBeenCalled();
+ expect(mocks.postV1RecordUserConsent).not.toHaveBeenCalled();
});
it("does not track an unverified sign-up; the verification link does", async () => {
@@ -129,7 +137,7 @@ describe("email signup account creation tracking", () => {
"ValidPassword123!",
"ValidPassword123!",
- true,
+ false,
);
expect(result.success).toBe(false);
@@ -139,5 +147,87 @@ describe("email signup account creation tracking", () => {
// account setup.
expect(mocks.rollbackSession).toHaveBeenCalledOnce();
expect(mocks.scheduleAccountCreatedGoal).not.toHaveBeenCalled();
+ expect(mocks.postV1RecordUserConsent).not.toHaveBeenCalled();
+ });
+});
+
+describe("email signup consent", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.spyOn(console, "error").mockImplementation(() => undefined);
+ mocks.signUpEmail.mockResolvedValue({
+ token: "session-token",
+ user: { id: "user-1" },
+ });
+ mocks.getOnboardingStatus.mockResolvedValue({
+ shouldShowOnboarding: true,
+ });
+ mocks.postV1RecordUserConsent.mockResolvedValue({ status: 200, data: {} });
});
+
+ function provisioningResponse(accountCreated: boolean) {
+ return {
+ status: 200,
+ data: {},
+ headers: new Headers({
+ "X-AutoGPT-User-Created": String(accountCreated),
+ }),
+ };
+ }
+
+ function signupWith(marketingOptOut: boolean) {
+ return signup(
+ "ValidPassword123!",
+ "ValidPassword123!",
+ marketingOptOut,
+ );
+ }
+
+ it.each([true, false])(
+ "records terms acceptance with marketing_opt_out=%s on a new account",
+ async (marketingOptOut) => {
+ mocks.postV1GetOrCreateUser.mockResolvedValue(provisioningResponse(true));
+
+ const result = await signupWith(marketingOptOut);
+
+ expect(result).toEqual({ success: true, next: "/onboarding" });
+ expect(mocks.postV1RecordUserConsent).toHaveBeenCalledOnce();
+ expect(mocks.postV1RecordUserConsent).toHaveBeenCalledWith({
+ terms_version: TERMS_VERSION,
+ marketing_opt_out: marketingOptOut,
+ });
+ },
+ );
+
+ it("records nothing for an account that already existed", async () => {
+ mocks.postV1GetOrCreateUser.mockResolvedValue(provisioningResponse(false));
+
+ const result = await signupWith(true);
+
+ expect(result).toEqual({ success: true, next: "/onboarding" });
+ expect(mocks.postV1RecordUserConsent).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["the backend rejects the write", new ApiError("Server error", 500, {})],
+ ["the request never arrives", new TypeError("Failed to fetch")],
+ ])(
+ "still completes signup without a rollback when %s",
+ async (_label, error) => {
+ mocks.postV1GetOrCreateUser.mockResolvedValue(provisioningResponse(true));
+ mocks.postV1RecordUserConsent.mockRejectedValue(error);
+
+ const result = await signupWith(true);
+
+ expect(result).toEqual({ success: true, next: "/onboarding" });
+ expect(mocks.rollbackSession).not.toHaveBeenCalled();
+ expect(mocks.captureException).toHaveBeenCalledOnce();
+ expect(mocks.captureException).toHaveBeenCalledWith(error, {
+ tags: { signup_step: "record_consent" },
+ user: { id: "user-1" },
+ extra: { marketingOptOut: true },
+ });
+ },
+ );
});
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
index beba842d96..be1c2846d0 100644
--- 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
@@ -47,7 +47,6 @@ function submitSignupForm() {
screen.getByLabelText("Confirm Password", { selector: "input" }),
{ target: { value: password } },
);
- fireEvent.click(screen.getByRole("checkbox"));
fireEvent.click(screen.getByRole("button", { name: "Sign up" }));
}
@@ -60,7 +59,11 @@ function verificationRequired() {
}
async function waitOutCooldown() {
- for (let second = 0; second < 60; second++) {
+ // Each second re-arms its timer after a render, and shouldAdvanceTime moves
+ // the fake clock in 20ms steps meanwhile, so the countdown can trail exactly
+ // 60s by a step: tick until the button frees up instead.
+ for (let second = 0; second < 65; second++) {
+ if (screen.queryByRole("button", { name: "Resend email" })) return;
await act(async () => {
vi.advanceTimersByTime(1000);
});
@@ -121,6 +124,34 @@ describe("SignupPage with email verification required", () => {
).toHaveProperty("disabled", true);
});
+ test("a resent link still carries the sign-up's marketing opt-out", 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 />);
+
+ fireEvent.click(screen.getByRole("button", { name: "opt out" }));
+ 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&marketing_opt_out=1",
+ },
+ ]);
+ });
+ });
+
test("keeps the button available when the resend fails", async () => {
vi.useFakeTimers({ shouldAdvanceTime: true });
server.use(
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 440cda9bfa..49ddcf9987 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
@@ -1,5 +1,6 @@
import type { ReactNode } from "react";
import { renderToStaticMarkup } from "react-dom/server";
+import userEvent from "@testing-library/user-event";
import {
render,
screen,
@@ -7,10 +8,21 @@ import {
waitFor,
} from "@/tests/integrations/test-utils";
import SignupPage from "../page";
-import { beforeEach, describe, expect, test, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
const mockUseAuth = vi.hoisted(() => vi.fn());
const mockSignupAction = vi.hoisted(() => vi.fn());
+const capture = vi.hoisted(() => vi.fn());
+const setMarketingOptOutFlag = vi.hoisted(() => vi.fn());
+const navigation = vi.hoisted(() => ({
+ searchParams: new URLSearchParams(),
+}));
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ replace: vi.fn(), push: vi.fn(), refresh: vi.fn() }),
+ useSearchParams: () => navigation.searchParams,
+ usePathname: () => "/signup",
+}));
vi.mock("@/providers/onboarding/onboarding-provider", () => ({
default: ({ children }: { children: ReactNode }) => <>{children}</>,
@@ -24,6 +36,48 @@ vi.mock("../actions", () => ({
signup: mockSignupAction,
}));
+vi.mock("posthog-js", () => ({
+ default: { __loaded: true, is_capturing: () => true, capture },
+}));
+
+vi.mock("@/services/analytics/marketing-opt-out-cookie", () => ({
+ setMarketingOptOutFlag,
+}));
+
+const PROVIDER_LOGIN_URL = "/api/auth/login/with-provider";
+
+function fillValidForm() {
+ fireEvent.change(screen.getByLabelText("Email"), {
+ target: { value: "[email protected]" },
+ });
+ fireEvent.change(screen.getByLabelText("Password", { selector: "input" }), {
+ target: { value: "validpassword123" },
+ });
+ fireEvent.change(
+ screen.getByLabelText("Confirm Password", { selector: "input" }),
+ { target: { value: "validpassword123" } },
+ );
+}
+
+function getLegalLine() {
+ return screen.getByText(/By continuing you agree to our/);
+}
+
+function stubProviderFetch() {
+ return vi
+ .spyOn(globalThis, "fetch")
+ .mockImplementation(async () => new Response(JSON.stringify({})));
+}
+
+function providerFetchCallOrder(
+ fetchSpy: ReturnType<typeof stubProviderFetch>,
+) {
+ const index = fetchSpy.mock.calls.findIndex(
+ ([input]) => input === PROVIDER_LOGIN_URL,
+ );
+ return fetchSpy.mock.invocationCallOrder[index];
+}
+
describe("SignupPage", () => {
beforeEach(() => {
mockUseAuth.mockReturnValue({
@@ -32,14 +86,21 @@ describe("SignupPage", () => {
isLoggedIn: false,
});
mockSignupAction.mockReset();
- });
-
- test("shows existing user feedback from signup action", async () => {
mockSignupAction.mockResolvedValue({
success: false,
error: "user_already_exists",
});
+ capture.mockReset();
+ setMarketingOptOutFlag.mockReset();
+ navigation.searchParams = new URLSearchParams();
+ });
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ });
+
+ test("shows existing user feedback from signup action", async () => {
render(<SignupPage />);
fireEvent.change(screen.getByLabelText("Email"), {
@@ -54,7 +115,6 @@ describe("SignupPage", () => {
target: { value: "validpassword123" },
},
);
- fireEvent.click(screen.getByRole("checkbox"));
fireEvent.click(screen.getByRole("button", { name: "Sign up" }));
await waitFor(() => {
@@ -62,7 +122,7 @@ describe("SignupPage", () => {
"validpassword123",
"validpassword123",
- true,
+ false,
null,
);
});
@@ -72,6 +132,350 @@ describe("SignupPage", () => {
).toBeDefined();
});
+ test("signs up without a terms checkbox", async () => {
+ render(<SignupPage />);
+
+ expect(screen.queryByRole("checkbox")).toBeNull();
+ expect(screen.queryByText(/I agree to the/)).toBeNull();
+
+ fillValidForm();
+ fireEvent.click(screen.getByRole("button", { name: "Sign up" }));
+
+ await waitFor(() => expect(mockSignupAction).toHaveBeenCalledTimes(1));
+ });
+
+ test("puts the Log in link under the title, keeping ?next=", () => {
+ navigation.searchParams = new URLSearchParams({
+ next: "/library?tab=runs",
+ });
+
+ render(<SignupPage />);
+
+ const logInLinks = screen.getAllByRole("link", { name: "Log in" });
+ expect(logInLinks).toHaveLength(1);
+ const [logIn] = logInLinks;
+ expect(logIn.getAttribute("href")).toBe(
+ "/login?next=%2Flibrary%3Ftab%3Druns",
+ );
+ expect(logIn.parentElement?.textContent).toBe("Already a member? Log in");
+
+ const header = screen.getByRole("heading", {
+ name: "Create your account",
+ }).parentElement;
+ expect(header?.textContent).toBe(
+ "Create your accountAlready a member? Log in",
+ );
+ expect(header?.nextElementSibling?.tagName).toBe("FORM");
+ });
+
+ test("shows the legal line with the terms and privacy links", () => {
+ render(<SignupPage />);
+
+ expect(getLegalLine().textContent).toBe(
+ "By continuing you agree to our Terms of Use and Privacy Policy. We may email you product updates and offers; opt out.",
+ );
+
+ const terms = screen.getByRole("link", { name: "Terms of Use" });
+ expect(terms.getAttribute("href")).toBe(
+ "https://agpt.co/legal/platform-terms-of-use",
+ );
+ expect(terms.getAttribute("target")).toBe("_blank");
+ expect(terms.getAttribute("rel")).toBe("noopener noreferrer");
+
+ const privacy = screen.getByRole("link", { name: "Privacy Policy" });
+ expect(privacy.getAttribute("href")).toBe(
+ "https://agpt.co/legal/platform-privacy-policy",
+ );
+ expect(privacy.getAttribute("target")).toBe("_blank");
+ expect(privacy.getAttribute("rel")).toBe("noopener noreferrer");
+ });
+
+ test("renders the legal line right after the form when there is no Google button", () => {
+ render(<SignupPage />);
+
+ expect(
+ screen.queryByRole("button", { name: /continue with google/i }),
+ ).toBeNull();
+ const previous = getLegalLine().previousElementSibling;
+ expect(previous?.tagName).toBe("FORM");
+ expect(previous?.lastElementChild?.textContent).toBe("Sign up");
+ });
+
+ test("renders the legal line right after the Google button in cloud", () => {
+ vi.stubEnv("NEXT_PUBLIC_BEHAVE_AS", "CLOUD");
+
+ render(<SignupPage />);
+
+ expect(getLegalLine().previousElementSibling).toBe(
+ screen.getByRole("button", { name: /continue with google/i }),
+ );
+ });
+
+ test("opting out swaps the sentence, keeps focus on the toggle and submits the opt-out", async () => {
+ const user = userEvent.setup();
+ render(<SignupPage />);
+
+ const toggle = screen.getByRole("button", { name: "opt out" });
+ await user.click(toggle);
+
+ expect(getLegalLine().textContent).toBe(
+ "By continuing you agree to our Terms of Use and Privacy Policy. You won't get marketing emails. Undo.",
+ );
+ expect(screen.getByRole("button", { name: "Undo" })).toBe(toggle);
+ expect(document.activeElement).toBe(toggle);
+ expect(
+ screen
+ .getByText("You won't get marketing emails.")
+ .closest("[aria-live]")
+ ?.getAttribute("aria-live"),
+ ).toBe("polite");
+ expect(screen.queryByText(/We may email you/)).toBeNull();
+
+ fillValidForm();
+ fireEvent.click(screen.getByRole("button", { name: "Sign up" }));
+
+ await waitFor(() => {
+ expect(mockSignupAction).toHaveBeenCalledWith(
+ "validpassword123",
+ "validpassword123",
+ true,
+ null,
+ );
+ });
+ });
+
+ test("Undo restores the copy and submits without an opt-out", async () => {
+ const user = userEvent.setup();
+ render(<SignupPage />);
+
+ const toggle = screen.getByRole("button", { name: "opt out" });
+ await user.click(toggle);
+ await user.click(screen.getByRole("button", { name: "Undo" }));
+
+ expect(getLegalLine().textContent).toBe(
+ "By continuing you agree to our Terms of Use and Privacy Policy. We may email you product updates and offers; opt out.",
+ );
+ expect(screen.getByRole("button", { name: "opt out" })).toBe(toggle);
+ expect(document.activeElement).toBe(toggle);
+
+ fillValidForm();
+ fireEvent.click(screen.getByRole("button", { name: "Sign up" }));
+
+ await waitFor(() => {
+ expect(mockSignupAction).toHaveBeenCalledWith(
+ "validpassword123",
+ "validpassword123",
+ false,
+ null,
+ );
+ });
+ });
+
+ test("captures the opt-out once with only its surface and never on Undo", async () => {
+ const user = userEvent.setup();
+ render(<SignupPage />);
+
+ expect(capture).not.toHaveBeenCalled();
+
+ await user.click(screen.getByRole("button", { name: "opt out" }));
+ expect(capture.mock.calls).toEqual([
+ ["marketing_opted_out", { surface: "signup" }],
+ ]);
+
+ await user.click(screen.getByRole("button", { name: "Undo" }));
+ expect(capture).toHaveBeenCalledTimes(1);
+ });
+
+ test("Google signup carries an opt-out across the redirect, set before leaving", async () => {
+ vi.stubEnv("NEXT_PUBLIC_BEHAVE_AS", "CLOUD");
+ const fetchSpy = stubProviderFetch();
+ const user = userEvent.setup();
+ render(<SignupPage />);
+
+ await user.click(screen.getByRole("button", { name: "opt out" }));
+ await user.click(
+ screen.getByRole("button", { name: /continue with google/i }),
+ );
+
+ await waitFor(() => {
+ expect(fetchSpy).toHaveBeenCalledWith(
+ PROVIDER_LOGIN_URL,
+ expect.objectContaining({ method: "POST" }),
+ );
+ });
+ expect(setMarketingOptOutFlag.mock.calls).toEqual([[true]]);
+ expect(setMarketingOptOutFlag.mock.invocationCallOrder[0]).toBeLessThan(
+ providerFetchCallOrder(fetchSpy),
+ );
+ });
+
+ test("Google signup clears any stale opt-out when the user did not opt out", async () => {
+ vi.stubEnv("NEXT_PUBLIC_BEHAVE_AS", "CLOUD");
+ const fetchSpy = stubProviderFetch();
+ const user = userEvent.setup();
+ render(<SignupPage />);
+
+ await user.click(
+ screen.getByRole("button", { name: /continue with google/i }),
+ );
+
+ await waitFor(() => {
+ expect(fetchSpy).toHaveBeenCalledWith(
+ PROVIDER_LOGIN_URL,
+ expect.objectContaining({ method: "POST" }),
+ );
+ });
+ expect(setMarketingOptOutFlag.mock.calls).toEqual([[false]]);
+ expect(setMarketingOptOutFlag.mock.invocationCallOrder[0]).toBeLessThan(
+ providerFetchCallOrder(fetchSpy),
+ );
+ expect(capture).not.toHaveBeenCalled();
+ });
+
+ test.each([
+ { optOut: true, label: "with an opt-out" },
+ { optOut: false, label: "without an opt-out" },
+ ])(
+ "email signup $label clears the Google opt-out cookie before creating the account",
+ async ({ optOut }) => {
+ const user = userEvent.setup();
+ render(<SignupPage />);
+
+ if (optOut)
+ await user.click(screen.getByRole("button", { name: "opt out" }));
+ fillValidForm();
+ fireEvent.click(screen.getByRole("button", { name: "Sign up" }));
+
+ await waitFor(() => expect(mockSignupAction).toHaveBeenCalled());
+ // The server action records the refusal itself; a cookie left set would
+ // be applied to whichever Google sign-in comes next in this browser.
+ expect(setMarketingOptOutFlag.mock.calls).toEqual([[false]]);
+ expect(setMarketingOptOutFlag.mock.invocationCallOrder[0]).toBeLessThan(
+ mockSignupAction.mock.invocationCallOrder[0],
+ );
+ },
+ );
+
+ test.each([true, false])(
+ "an email signup that must verify its address leaves no opt-out cookie (opted out: %s)",
+ async (optOut) => {
+ // No session yet, so the action records nothing: the emailed link
+ // itself carries the refusal to /auth/callback (see actions.ts).
+ mockSignupAction.mockResolvedValue({
+ success: true,
+ verificationRequired: true,
+ email: "[email protected]",
+ });
+ const user = userEvent.setup();
+ render(<SignupPage />);
+
+ if (optOut)
+ await user.click(screen.getByRole("button", { name: "opt out" }));
+ fillValidForm();
+ fireEvent.click(screen.getByRole("button", { name: "Sign up" }));
+
+ expect(await screen.findByText("[email protected]")).toBeDefined();
+ expect(setMarketingOptOutFlag.mock.calls).toEqual([[false]]);
+ expect(mockSignupAction.mock.calls[0][3]).toBe(optOut);
+ },
+ );
+
+ test("locks the opt-out toggle while an email signup is pending and frees it on failure", async () => {
+ let finishSignup: (result: unknown) => void = () => undefined;
+ mockSignupAction.mockReturnValue(
+ new Promise((resolve) => {
+ finishSignup = resolve;
+ }),
+ );
+ const user = userEvent.setup();
+ render(<SignupPage />);
+
+ fillValidForm();
+ fireEvent.click(screen.getByRole("button", { name: "Sign up" }));
+
+ await waitFor(() => {
+ expect(mockSignupAction).toHaveBeenCalledWith(
+ "validpassword123",
+ "validpassword123",
+ false,
+ null,
+ );
+ });
+ const toggle = screen.getByRole<HTMLButtonElement>("button", {
+ name: "opt out",
+ });
+ await waitFor(() => expect(toggle.disabled).toBe(true));
+
+ await user.click(toggle);
+
+ expect(getLegalLine().textContent).toBe(
+ "By continuing you agree to our Terms of Use and Privacy Policy. We may email you product updates and offers; opt out.",
+ );
+ expect(capture).not.toHaveBeenCalled();
+
+ finishSignup({ success: false, error: "Signup failed" });
+ await waitFor(() => expect(toggle.disabled).toBe(false));
+
+ await user.click(toggle);
+
+ expect(getLegalLine().textContent).toBe(
+ "By continuing you agree to our Terms of Use and Privacy Policy. You won't get marketing emails. Undo.",
+ );
+ expect(capture.mock.calls).toEqual([
+ ["marketing_opted_out", { surface: "signup" }],
+ ]);
+ });
+
+ test("locks the opt-out toggle while a Google signup is starting and frees it on failure", async () => {
+ vi.stubEnv("NEXT_PUBLIC_BEHAVE_AS", "CLOUD");
+ let finishProviderStart: (response: Response) => void = () => undefined;
+ vi.spyOn(globalThis, "fetch").mockImplementation((input) =>
+ input === PROVIDER_LOGIN_URL
+ ? new Promise<Response>((resolve) => {
+ finishProviderStart = resolve;
+ })
+ : Promise.resolve(new Response(JSON.stringify({}))),
+ );
+ const user = userEvent.setup();
+ render(<SignupPage />);
+
+ await user.click(
+ screen.getByRole("button", { name: /continue with google/i }),
+ );
+
+ expect(setMarketingOptOutFlag.mock.calls).toEqual([[false]]);
+ const toggle = screen.getByRole<HTMLButtonElement>("button", {
+ name: "opt out",
+ });
+ await waitFor(() => expect(toggle.disabled).toBe(true));
+
+ await user.click(toggle);
+
+ expect(getLegalLine().textContent).toBe(
+ "By continuing you agree to our Terms of Use and Privacy Policy. We may email you product updates and offers; opt out.",
+ );
+ expect(capture).not.toHaveBeenCalled();
+
+ finishProviderStart(
+ new Response(JSON.stringify({ error: "Provider unavailable" }), {
+ status: 500,
+ }),
+ );
+ await waitFor(() => expect(toggle.disabled).toBe(false));
+
+ await user.click(toggle);
+
+ expect(getLegalLine().textContent).toBe(
+ "By continuing you agree to our Terms of Use and Privacy Policy. You won't get marketing emails. Undo.",
+ );
+ expect(capture.mock.calls).toEqual([
+ ["marketing_opted_out", { surface: "signup" }],
+ ]);
+ });
+
test("does not link to the demo tour", () => {
render(<SignupPage />);
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 18d9f7c9d6..d15f94244b 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
@@ -1,9 +1,13 @@
+import { ApiError } from "@/lib/autogpt-server-api/helpers";
+import { TERMS_VERSION } from "@/lib/legal";
import { APIError } from "better-auth/api";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const signUpEmailMock = vi.fn();
const rollbackSessionMock = vi.fn();
const postV1GetOrCreateUserMock = vi.fn();
+const postV1RecordUserConsentMock = vi.fn();
+const wasAccountCreatedMock = vi.fn();
const getOnboardingStatusMock = vi.fn();
const isWaitlistErrorMock = vi.fn();
const logWaitlistErrorMock = vi.fn();
@@ -24,15 +28,21 @@ vi.mock("@/lib/auth/server/rollbackSession", () => ({
vi.mock("@/app/api/__generated__/endpoints/auth/auth", () => ({
postV1GetOrCreateUser: (...args: unknown[]) =>
postV1GetOrCreateUserMock(...args),
+ postV1RecordUserConsent: (...args: unknown[]) =>
+ postV1RecordUserConsentMock(...args),
}));
// DataFast account tracking is exercised by actions.test.ts; stub it here so
// wasAccountCreated doesn't read .headers off the minimal mocked response.
vi.mock("@/services/analytics/datafast-server", () => ({
- wasAccountCreated: () => false,
+ wasAccountCreated: (...args: unknown[]) => wasAccountCreatedMock(...args),
scheduleAccountCreatedGoal: vi.fn(),
}));
+vi.mock("@/services/analytics/account-created-server", () => ({
+ markAccountCreated: vi.fn(),
+}));
+
vi.mock("@/app/api/helpers", async (importActual) => {
const actual = await importActual<typeof import("@/app/api/helpers")>();
return {
@@ -60,13 +70,15 @@ const email = "[email protected]";
const validPassword = "a-long-enough-password";
function signupWithValidPayload() {
- return signup(email, validPassword, validPassword, true);
+ return signup(email, validPassword, validPassword, false);
}
beforeEach(() => {
signUpEmailMock.mockReset();
rollbackSessionMock.mockReset();
postV1GetOrCreateUserMock.mockReset();
+ postV1RecordUserConsentMock.mockReset().mockResolvedValue({ status: 200 });
+ wasAccountCreatedMock.mockReset().mockReturnValue(false);
getOnboardingStatusMock.mockReset();
isWaitlistErrorMock.mockReset().mockReturnValue(false);
logWaitlistErrorMock.mockReset();
@@ -105,6 +117,72 @@ describe("signup", () => {
expect(result).toEqual({ success: true, next: "/onboarding" });
});
+ it("puts a marketing refusal in the verification link", async () => {
+ signUpEmailMock.mockResolvedValue({ token: null, user: { id: "user-1" } });
+
+ await signup(email, validPassword, validPassword, true, "/marketplace");
+
+ expect(signUpEmailMock.mock.calls[0][0].body.callbackURL).toBe(
+ "/auth/callback?method=email&next=%2Fmarketplace&marketing_opt_out=1",
+ );
+ });
+
+ it("records terms acceptance on the account it just created", async () => {
+ signUpEmailMock.mockResolvedValue({
+ token: "session-token",
+ user: { id: "user-1" },
+ });
+ postV1GetOrCreateUserMock.mockResolvedValue({ status: 200, data: {} });
+ wasAccountCreatedMock.mockReturnValue(true);
+ getOnboardingStatusMock.mockResolvedValue({ shouldShowOnboarding: true });
+
+ const result = await signup(email, validPassword, validPassword, true);
+
+ expect(postV1RecordUserConsentMock).toHaveBeenCalledTimes(1);
+ expect(postV1RecordUserConsentMock).toHaveBeenCalledWith({
+ terms_version: TERMS_VERSION,
+ marketing_opt_out: true,
+ });
+ expect(result).toEqual({ success: true, next: "/onboarding" });
+ });
+
+ it("does not record consent when signing up into an existing account", async () => {
+ signUpEmailMock.mockResolvedValue({
+ token: "session-token",
+ user: { id: "user-1" },
+ });
+ postV1GetOrCreateUserMock.mockResolvedValue({ status: 200, data: {} });
+ getOnboardingStatusMock.mockResolvedValue({ shouldShowOnboarding: false });
+
+ const result = await signup(email, validPassword, validPassword, true);
+
+ expect(postV1RecordUserConsentMock).not.toHaveBeenCalled();
+ expect(result).toEqual({ success: true, next: "/home" });
+ });
+
+ it("keeps the new account signed in when the consent write fails", async () => {
+ signUpEmailMock.mockResolvedValue({
+ token: "session-token",
+ user: { id: "user-1" },
+ });
+ postV1GetOrCreateUserMock.mockResolvedValue({ status: 200, data: {} });
+ wasAccountCreatedMock.mockReturnValue(true);
+ postV1RecordUserConsentMock.mockRejectedValue(
+ new ApiError("Unprocessable Entity", 422, {}),
+ );
+ getOnboardingStatusMock.mockResolvedValue({ shouldShowOnboarding: true });
+
+ const result = await signupWithValidPayload();
+
+ expect(postV1RecordUserConsentMock).toHaveBeenCalledWith({
+ terms_version: TERMS_VERSION,
+ marketing_opt_out: false,
+ });
+ expect(rollbackSessionMock).not.toHaveBeenCalled();
+ expect(captureExceptionMock).toHaveBeenCalledTimes(1);
+ expect(result).toEqual({ success: true, next: "/onboarding" });
+ });
+
it("routes straight to /home when onboarding is already complete", async () => {
signUpEmailMock.mockResolvedValue({
token: "session-token",
@@ -178,6 +256,7 @@ describe("signup", () => {
expect(captureExceptionMock).toHaveBeenCalledTimes(1);
expect(rollbackSessionMock).toHaveBeenCalledTimes(1);
+ expect(postV1RecordUserConsentMock).not.toHaveBeenCalled();
expect(result).toEqual({
success: false,
error: "Failed to complete account setup. Please try again.",
@@ -205,8 +284,14 @@ describe("signup", () => {
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");
+ await signup(email, validPassword, validPassword, false, "/marketplace");
+ await signup(
+ email,
+ validPassword,
+ validPassword,
+ false,
+ "https://evil.com",
+ );
expect(signUpEmailMock.mock.calls[0][0].body.callbackURL).toBe(
"/auth/callback?method=email&next=%2Fmarketplace",
@@ -217,7 +302,7 @@ describe("signup", () => {
});
it("rejects a password shorter than 12 characters without calling Better Auth", async () => {
- const result = await signup(email, "short-pass", "short-pass", true);
+ const result = await signup(email, "short-pass", "short-pass", false);
expect(result).toEqual({ success: false, error: "Invalid signup payload" });
expect(signUpEmailMock).not.toHaveBeenCalled();
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 6dbfd4b584..e9addcc9d4 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/signup/actions.ts
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/signup/actions.ts
@@ -4,6 +4,7 @@ import { postV1GetOrCreateUser } from "@/app/api/__generated__/endpoints/auth/au
import { getOnboardingStatus } from "@/app/api/helpers";
import { auth } from "@/lib/auth/auth";
import { getEmailVerificationCallbackURL } from "@/lib/auth/email-verification";
+import { recordSignupConsent } from "@/lib/auth/server/recordSignupConsent";
import { rollbackSession } from "@/lib/auth/server/rollbackSession";
import { markAccountCreated } from "@/services/analytics/account-created-server";
import {
@@ -20,7 +21,7 @@ export async function signup(
email: string,
password: string,
confirmPassword: string,
- agreeToTerms: boolean,
+ marketingOptOut: boolean,
next?: string | null,
) {
try {
@@ -28,7 +29,7 @@ export async function signup(
email,
password,
confirmPassword,
- agreeToTerms,
+ marketingOptOut,
});
if (!parsed.success) {
@@ -46,7 +47,10 @@ export async function signup(
email: parsed.data.email,
password: parsed.data.password,
name: parsed.data.email.split("@")[0],
- callbackURL: getEmailVerificationCallbackURL(next),
+ callbackURL: getEmailVerificationCallbackURL({
+ next,
+ marketingOptOut: parsed.data.marketingOptOut,
+ }),
},
headers: await headers(),
});
@@ -80,8 +84,8 @@ export async function signup(
// 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.
+ // account the same way). The platform user, the sign-up conversion and
+ // the consent record wait for that link, which lands on /auth/callback.
if (!signUpResult.token) {
return {
success: true,
@@ -95,6 +99,12 @@ export async function signup(
if (wasAccountCreated(createUserResponse)) {
await scheduleAccountCreatedGoal("email");
await markAccountCreated("email");
+ // Never throws, so a failed consent write can't reach the rollback
+ // below: the account exists and the signup still succeeds.
+ await recordSignupConsent({
+ userID: signUpResult.user.id,
+ marketingOptOut: parsed.data.marketingOptOut,
+ });
}
} catch (createUserError) {
console.error("Error creating user during signup:", createUserError);
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/signup/components/SignupLegalLine.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/signup/components/SignupLegalLine.tsx
new file mode 100644
index 0000000000..b2c6df6b77
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/signup/components/SignupLegalLine.tsx
@@ -0,0 +1,53 @@
+import {
+ Link,
+ linkBaseClasses,
+ linkVariantClasses,
+} from "@/components/atoms/Link/Link";
+import { Text } from "@/components/atoms/Text/Text";
+import { PRIVACY_POLICY_URL, TERMS_OF_USE_URL } from "@/lib/legal";
+import { cn } from "@/lib/utils";
+
+interface Props {
+ optedOut: boolean;
+ onToggle: () => void;
+ disabled?: boolean;
+}
+
+export function SignupLegalLine({ optedOut, onToggle, disabled }: Props) {
+ return (
+ <Text variant="body" className="mt-6 text-center !text-slate-500">
+ By continuing you agree to our{" "}
+ <Link href={TERMS_OF_USE_URL} variant="secondary" isExternal>
+ Terms of Use
+ </Link>{" "}
+ and{" "}
+ <Link href={PRIVACY_POLICY_URL} variant="secondary" isExternal>
+ Privacy Policy
+ </Link>
+ .{" "}
+ <span aria-live="polite">
+ {optedOut ? (
+ <span className="text-slate-950">
+ You won&apos;t get marketing emails.
+ </span>
+ ) : (
+ "We may email you product updates and offers;"
+ )}
+ </span>{" "}
+ <button
+ type="button"
+ onClick={onToggle}
+ disabled={disabled}
+ className={cn(
+ linkBaseClasses,
+ linkVariantClasses.secondary,
+ "rounded-sm focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2",
+ "disabled:cursor-not-allowed disabled:opacity-50",
+ )}
+ >
+ {optedOut ? "Undo" : "opt out"}
+ </button>
+ .
+ </Text>
+ );
+}
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 45a291cf71..23387959f6 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/signup/page.tsx
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/signup/page.tsx
@@ -1,13 +1,6 @@
"use client";
-import { Checkbox } from "@/components/__legacy__/ui/checkbox";
-import {
- Form,
- FormControl,
- FormField,
- FormItem,
- FormLabel,
-} from "@/components/__legacy__/ui/form";
+import { Form, FormField } from "@/components/__legacy__/ui/form";
import { Button } from "@/components/atoms/Button/Button";
import { Input } from "@/components/atoms/Input/Input";
import { Link } from "@/components/atoms/Link/Link";
@@ -22,10 +15,9 @@ import { MobileWarningBanner } from "@/components/auth/MobileWarningBanner";
import { environment } from "@/services/environment";
import { useSearchParams } from "next/navigation";
import { LoadingSignup } from "./components/LoadingSignup";
+import { SignupLegalLine } from "./components/SignupLegalLine";
import { SignupMarketingPanel } from "./components/SignupMarketingPanel";
import { useSignupPage } from "./useSignupPage";
-import { Alert02Icon } from "@hugeicons/core-free-icons";
-import { Icon } from "@/components/atoms/Icon/Icon";
export const dynamic = "force-dynamic";
@@ -45,9 +37,12 @@ export default function SignupPage() {
hasInitializedAuth,
isLoading,
isGoogleLoading,
+ isSigningUp,
isCloudEnv,
showNotAllowedModal,
+ optedOut,
handleSubmit,
+ handleToggleMarketingOptOut,
handleProviderSignup,
handleCloseNotAllowedModal,
handleStartAgain,
@@ -64,6 +59,7 @@ export default function SignupPage() {
email={verificationEmail}
reason="signup"
next={safeNextUrl}
+ marketingOptOut={optedOut}
onBack={handleStartAgain}
/>
</AuthSplitLayout>
@@ -71,7 +67,6 @@ export default function SignupPage() {
}
const confirmPasswordError = form.formState.errors.confirmPassword?.message;
- const termsError = form.formState.errors.agreeToTerms?.message;
return (
<AuthSplitLayout marketing={<SignupMarketingPanel />}>
@@ -79,6 +74,12 @@ export default function SignupPage() {
<Text variant="h3" as="h1" className="!text-slate-950">
Create your account
</Text>
+ <Text variant="body" className="mt-1 !text-slate-500">
+ Already a member?{" "}
+ <Link href={loginHref} variant="secondary">
+ Log in
+ </Link>
+ </Text>
</div>
<Form {...form}>
@@ -128,60 +129,6 @@ export default function SignupPage() {
/>
)}
/>
- <FormField
- control={form.control}
- name="agreeToTerms"
- render={({ field }) => (
- <>
- <FormItem className="mt-6 flex w-full flex-row items-center -space-y-1 space-x-2">
- <FormControl>
- <Checkbox
- checked={field.value}
- onCheckedChange={field.onChange}
- className="relative bottom-px"
- />
- </FormControl>
- <div>
- <FormLabel className="flex flex-wrap items-center gap-1">
- <Text
- variant="body-medium"
- className="inline-block text-slate-950"
- >
- I agree to the
- </Text>
- <Link
- href="https://agpt.co/legal/platform-terms-of-use"
- variant="secondary"
- >
- Terms of Use
- </Link>
- <Text
- variant="body-medium"
- className="inline-block text-slate-950"
- >
- and
- </Text>
- <Link
- href="https://agpt.co/legal/platform-privacy-policy"
- variant="secondary"
- >
- Privacy Policy
- </Link>
- </FormLabel>
- </div>
- </FormItem>
- {termsError ? (
- <div className="flex items-center gap-2">
- <Icon icon={Alert02Icon} className="h-4 w-4 text-red-500" />
- <Text variant="small-medium" className="!text-red-500">
- {termsError}
- </Text>
- </div>
- ) : null}
- </>
- )}
- />
-
<Button
variant="primary"
loading={isLoading}
@@ -204,6 +151,12 @@ export default function SignupPage() {
</>
) : null}
+ <SignupLegalLine
+ optedOut={optedOut}
+ onToggle={handleToggleMarketingOptOut}
+ disabled={isSigningUp}
+ />
+
<AuthFeedback
type="signup"
message={feedback}
@@ -212,15 +165,6 @@ export default function SignupPage() {
/>
</Form>
- <div className="mt-6 inline-flex w-full items-center justify-center gap-1">
- <Text variant="body-medium" className="!text-slate-500">
- Already a member?
- </Text>
- <Link href={loginHref} variant="secondary">
- Log in
- </Link>
- </div>
-
<MobileWarningBanner />
<EmailNotAllowedModal
isOpen={showNotAllowedModal}
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 813ee2443c..4889a35033 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/signup/useSignupPage.ts
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/signup/useSignupPage.ts
@@ -2,6 +2,8 @@ import { useToast } from "@/components/molecules/Toast/use-toast";
import { useCaptureMarketingPrompt } from "@/hooks/useCaptureMarketingPrompt";
import { sanitizeAuthNext } from "@/lib/auth-redirect";
import { useAuth } from "@/lib/auth/hooks/useAuth";
+import { setMarketingOptOutFlag } from "@/services/analytics/marketing-opt-out-cookie";
+import { trackSignupMarketingOptOut } from "@/services/analytics/signup-analytics";
import { environment } from "@/services/environment";
import { LoginProvider, signupFormSchema } from "@/types/auth";
import { zodResolver } from "@hookform/resolvers/zod";
@@ -50,16 +52,27 @@ export function useSignupPage() {
}
}, [isLoggedIn, isSigningUp, nextUrl, router]);
- const form = useForm<z.infer<typeof signupFormSchema>>({
+ const form = useForm<
+ z.input<typeof signupFormSchema>,
+ unknown,
+ z.output<typeof signupFormSchema>
+ >({
resolver: zodResolver(signupFormSchema),
defaultValues: {
email: "",
password: "",
confirmPassword: "",
- agreeToTerms: false,
+ marketingOptOut: false,
},
});
+ function handleToggleMarketingOptOut() {
+ if (isSigningUp) return;
+ const optOut = !form.getValues("marketingOptOut");
+ form.setValue("marketingOptOut", optOut, { shouldDirty: true });
+ if (optOut) trackSignupMarketingOptOut();
+ }
+
async function handleProviderSignup(provider: LoginProvider) {
setIsGoogleLoading(true);
setIsSigningUp(true);
@@ -71,6 +84,8 @@ export function useSignupPage() {
: `/auth/callback`;
const fullCallbackUrl = `${window.location.origin}${callbackUrl}`;
+ setMarketingOptOutFlag(form.getValues("marketingOptOut") ?? false);
+
const response = await fetch("/api/auth/login/with-provider", {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -102,7 +117,11 @@ export function useSignupPage() {
}
}
- async function handleSignup(data: z.infer<typeof signupFormSchema>) {
+ async function handleSignup(data: z.output<typeof signupFormSchema>) {
+ // The server action records this signup's choice; the cookie is only for
+ // the Google round trip. Clear it so neither this choice nor one left from
+ // an abandoned Google attempt is applied to a later Google sign-in.
+ setMarketingOptOutFlag(false);
setIsLoading(true);
if (data.email.includes("@agpt.co")) {
@@ -123,7 +142,7 @@ export function useSignupPage() {
data.email,
data.password,
data.confirmPassword,
- data.agreeToTerms,
+ data.marketingOptOut,
nextUrl,
);
@@ -148,6 +167,9 @@ export function useSignupPage() {
}
if (result.verificationRequired) {
+ // There is no session yet, so the action recorded nothing. The emailed
+ // link carries the refusal and lands on /auth/callback, which records
+ // it with the terms.
setVerificationEmail(result.email);
setIsLoading(false);
setIsSigningUp(false);
@@ -188,10 +210,13 @@ export function useSignupPage() {
hasInitializedAuth,
isLoading,
isGoogleLoading,
+ isSigningUp,
isCloudEnv,
isUserLoading,
showNotAllowedModal,
+ optedOut: form.watch("marketingOptOut") ?? false,
handleSubmit: form.handleSubmit(handleSignup),
+ handleToggleMarketingOptOut,
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
index 24d62dbe04..89d437df81 100644
--- 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
@@ -9,6 +9,7 @@ const mocks = vi.hoisted(() => ({
getServerSession: vi.fn(),
scheduleAccountCreatedGoal: vi.fn(),
cookieSet: vi.fn(),
+ recordUserConsent: vi.fn(),
provisionedUserIDs: new Set<string>(),
}));
@@ -37,6 +38,7 @@ vi.mock("@/app/api/__generated__/endpoints/auth/auth", () => ({
headers: new Headers({ "X-AutoGPT-User-Created": String(created) }),
};
}),
+ postV1RecordUserConsent: mocks.recordUserConsent,
}));
vi.mock("@/app/api/helpers", () => ({
@@ -50,7 +52,11 @@ vi.mock("@/services/analytics/datafast-server", async (importOriginal) => ({
}));
vi.mock("next/headers", () => ({
headers: vi.fn(async () => new Headers()),
- cookies: vi.fn(async () => ({ set: mocks.cookieSet })),
+ cookies: vi.fn(async () => ({
+ set: mocks.cookieSet,
+ get: vi.fn(),
+ delete: vi.fn(),
+ })),
}));
vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));
vi.mock("@sentry/nextjs", () => ({ captureException: vi.fn() }));
@@ -109,4 +115,26 @@ describe("sign_up conversion across email verification", () => {
expect(mocks.scheduleAccountCreatedGoal).toHaveBeenCalledOnce();
expect(mocks.cookieSet).toHaveBeenCalledOnce();
});
+
+ it.each([true, false])(
+ "records the sign-up's marketing opt-out (%s) from the link, opened in any browser",
+ async (marketingOptOut) => {
+ mocks.signUpEmail.mockResolvedValue({ token: null, user: { id: "u-1" } });
+ mocks.getServerSession.mockResolvedValue(null);
+ mocks.recordUserConsent.mockResolvedValue({ status: 200, data: {} });
+
+ await signup("[email protected]", password, password, marketingOptOut);
+
+ // No cookie travels with it: only the link the email carries.
+ const callbackURL = mocks.signUpEmail.mock.calls[0][0].body.callbackURL;
+ mocks.getServerSession.mockResolvedValue({ user: { id: "u-1" } });
+
+ await clickVerificationLink(callbackURL);
+
+ expect(mocks.recordUserConsent).toHaveBeenCalledOnce();
+ expect(mocks.recordUserConsent).toHaveBeenCalledWith(
+ expect.objectContaining({ marketing_opt_out: marketingOptOut }),
+ );
+ },
+ );
});
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 b23ab1e832..d93d13df85 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
@@ -1,11 +1,18 @@
+import { ApiError } from "@/lib/autogpt-server-api/helpers";
+import { TERMS_VERSION } from "@/lib/legal";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const getServerSessionMock = vi.fn();
const postV1GetOrCreateUserMock = vi.fn();
+const postV1RecordUserConsentMock = vi.fn();
+const rollbackSessionMock = vi.fn();
const getOnboardingStatusMock = vi.fn();
const revalidatePathMock = vi.fn();
const scheduleAccountCreatedGoalMock = vi.fn();
const cookieSetMock = vi.fn();
+const cookieGetMock = vi.fn();
+const cookieDeleteMock = vi.fn();
+const captureExceptionMock = vi.fn();
vi.mock("@/lib/auth/server/getServerSession", () => ({
getServerSession: () => getServerSessionMock(),
@@ -14,6 +21,12 @@ vi.mock("@/lib/auth/server/getServerSession", () => ({
vi.mock("@/app/api/__generated__/endpoints/auth/auth", () => ({
postV1GetOrCreateUser: (...args: unknown[]) =>
postV1GetOrCreateUserMock(...args),
+ postV1RecordUserConsent: (...args: unknown[]) =>
+ postV1RecordUserConsentMock(...args),
+}));
+
+vi.mock("@/lib/auth/server/rollbackSession", () => ({
+ rollbackSession: () => rollbackSessionMock(),
}));
// Keep the real wasAccountCreated (it reads the provisioning response header);
@@ -31,7 +44,12 @@ vi.mock("@/app/api/helpers", () => ({
}));
vi.mock("next/headers", () => ({
- cookies: () => Promise.resolve({ set: cookieSetMock }),
+ cookies: () =>
+ Promise.resolve({
+ set: cookieSetMock,
+ get: cookieGetMock,
+ delete: cookieDeleteMock,
+ }),
headers: () => new Headers(),
}));
@@ -39,6 +57,10 @@ vi.mock("next/cache", () => ({
revalidatePath: (...args: unknown[]) => revalidatePathMock(...args),
}));
+vi.mock("@sentry/nextjs", () => ({
+ captureException: (...args: unknown[]) => captureExceptionMock(...args),
+}));
+
import { GET } from "../route";
class BackendApiErrorStub extends Error {
@@ -83,7 +105,12 @@ beforeEach(() => {
getOnboardingStatusMock.mockReset();
revalidatePathMock.mockReset();
scheduleAccountCreatedGoalMock.mockReset();
+ postV1RecordUserConsentMock.mockReset().mockResolvedValue({ status: 200 });
+ rollbackSessionMock.mockReset();
cookieSetMock.mockReset();
+ cookieGetMock.mockReset();
+ cookieDeleteMock.mockReset();
+ captureExceptionMock.mockReset();
vi.spyOn(console, "error").mockImplementation(() => undefined);
});
@@ -163,6 +190,108 @@ describe("auth callback GET — account creation tracking", () => {
});
});
+describe("auth callback GET — signup consent", () => {
+ const optOutCookie = { name: "agpt_marketing_opt_out", value: "1" };
+
+ beforeEach(() => {
+ vi.stubEnv("NODE_ENV", "development");
+ getServerSessionMock.mockResolvedValue({ user: { id: "user-1" } });
+ getOnboardingStatusMock.mockResolvedValue({ shouldShowOnboarding: true });
+ });
+
+ function withOptOutCookie() {
+ cookieGetMock.mockImplementation((name: string) =>
+ name === optOutCookie.name ? optOutCookie : undefined,
+ );
+ }
+
+ it("records a marketing refusal carried by the cookie and clears it", async () => {
+ withOptOutCookie();
+ postV1GetOrCreateUserMock.mockResolvedValue(provisioningResponse(true));
+
+ const response = await GET(makeCallbackRequest());
+
+ expect(response.headers.get("location")).toBe(`${origin}/onboarding`);
+ expect(postV1RecordUserConsentMock).toHaveBeenCalledOnce();
+ expect(postV1RecordUserConsentMock).toHaveBeenCalledWith({
+ terms_version: TERMS_VERSION,
+ marketing_opt_out: true,
+ });
+ expect(cookieDeleteMock).toHaveBeenCalledWith("agpt_marketing_opt_out");
+ });
+
+ it("records terms acceptance without a refusal when there is no cookie", async () => {
+ postV1GetOrCreateUserMock.mockResolvedValue(provisioningResponse(true));
+
+ await GET(makeCallbackRequest());
+
+ expect(postV1RecordUserConsentMock).toHaveBeenCalledOnce();
+ expect(postV1RecordUserConsentMock).toHaveBeenCalledWith({
+ terms_version: TERMS_VERSION,
+ marketing_opt_out: false,
+ });
+ expect(cookieDeleteMock).not.toHaveBeenCalled();
+ });
+
+ it("records the refusal on a returning account and clears the cookie", async () => {
+ withOptOutCookie();
+ postV1GetOrCreateUserMock.mockResolvedValue(provisioningResponse(false));
+
+ await GET(makeCallbackRequest());
+
+ expect(postV1RecordUserConsentMock).toHaveBeenCalledOnce();
+ expect(postV1RecordUserConsentMock).toHaveBeenCalledWith({
+ terms_version: TERMS_VERSION,
+ marketing_opt_out: true,
+ });
+ expect(cookieDeleteMock).toHaveBeenCalledWith("agpt_marketing_opt_out");
+ expect(scheduleAccountCreatedGoalMock).not.toHaveBeenCalled();
+ });
+
+ it("records nothing for a returning account that did not opt out", async () => {
+ postV1GetOrCreateUserMock.mockResolvedValue(provisioningResponse(false));
+
+ await GET(makeCallbackRequest());
+
+ expect(postV1RecordUserConsentMock).not.toHaveBeenCalled();
+ expect(cookieDeleteMock).not.toHaveBeenCalled();
+ });
+
+ it("keeps the refusal for the retry when provisioning fails", async () => {
+ withOptOutCookie();
+ postV1GetOrCreateUserMock.mockRejectedValue(new Error("backend down"));
+
+ const response = await GET(makeCallbackRequest());
+
+ expect(response.headers.get("location")).toBe(
+ `${origin}/error?message=user-creation-failed`,
+ );
+ expect(rollbackSessionMock).toHaveBeenCalledOnce();
+ expect(cookieDeleteMock).not.toHaveBeenCalled();
+ expect(postV1RecordUserConsentMock).not.toHaveBeenCalled();
+ });
+
+ it("still lands the user on the normal next page when the consent write fails", async () => {
+ withOptOutCookie();
+ postV1GetOrCreateUserMock.mockResolvedValue(provisioningResponse(true));
+ const error = new ApiError("Internal Server Error", 500, {});
+ postV1RecordUserConsentMock.mockRejectedValue(error);
+
+ const response = await GET(
+ makeCallbackRequest("/auth/callback?next=/marketplace"),
+ );
+
+ expect(response.headers.get("location")).toBe(`${origin}/marketplace`);
+ expect(revalidatePathMock).toHaveBeenCalledWith("/marketplace", "layout");
+ expect(rollbackSessionMock).not.toHaveBeenCalled();
+ expect(captureExceptionMock).toHaveBeenCalledWith(error, {
+ tags: { signup_step: "record_consent" },
+ user: { id: "user-1" },
+ extra: { marketingOptOut: true },
+ });
+ });
+});
+
describe("auth callback GET — email verification link", () => {
beforeEach(() => {
vi.stubEnv("NODE_ENV", "development");
@@ -189,6 +318,60 @@ describe("auth callback GET — email verification link", () => {
);
});
+ it("records the terms and a refusal carried from /signup once the link signs a new account in", async () => {
+ getServerSessionMock.mockResolvedValue({ user: { id: "user-1" } });
+ cookieGetMock.mockImplementation((name: string) =>
+ name === "agpt_marketing_opt_out"
+ ? { name: "agpt_marketing_opt_out", value: "1" }
+ : undefined,
+ );
+ postV1GetOrCreateUserMock.mockResolvedValue(provisioningResponse(true));
+ getOnboardingStatusMock.mockResolvedValue({ shouldShowOnboarding: true });
+
+ await GET(makeCallbackRequest("/auth/callback?method=email"));
+
+ expect(postV1RecordUserConsentMock).toHaveBeenCalledOnce();
+ expect(postV1RecordUserConsentMock).toHaveBeenCalledWith({
+ terms_version: TERMS_VERSION,
+ marketing_opt_out: true,
+ });
+ expect(cookieDeleteMock).toHaveBeenCalledWith("agpt_marketing_opt_out");
+ });
+
+ it("records a refusal carried by the link when it creates the account", async () => {
+ getServerSessionMock.mockResolvedValue({ user: { id: "user-1" } });
+ postV1GetOrCreateUserMock.mockResolvedValue(provisioningResponse(true));
+ getOnboardingStatusMock.mockResolvedValue({ shouldShowOnboarding: true });
+
+ await GET(
+ makeCallbackRequest("/auth/callback?method=email&marketing_opt_out=1"),
+ );
+
+ expect(postV1RecordUserConsentMock).toHaveBeenCalledOnce();
+ expect(postV1RecordUserConsentMock).toHaveBeenCalledWith({
+ terms_version: TERMS_VERSION,
+ marketing_opt_out: true,
+ });
+ });
+
+ it.each([
+ ["an existing account", "/auth/callback?method=email&marketing_opt_out=1"],
+ ["a Google sign-in", "/auth/callback?marketing_opt_out=1"],
+ ])("ignores the link's refusal for %s", async (_, path) => {
+ getServerSessionMock.mockResolvedValue({ user: { id: "user-1" } });
+ postV1GetOrCreateUserMock.mockResolvedValue(
+ provisioningResponse(path.includes("method=email") ? false : true),
+ );
+ getOnboardingStatusMock.mockResolvedValue({ shouldShowOnboarding: true });
+
+ await GET(makeCallbackRequest(path));
+
+ const calls = postV1RecordUserConsentMock.mock.calls;
+ expect(calls.every(([body]) => body.marketing_opt_out === false)).toBe(
+ true,
+ );
+ });
+
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));
@@ -340,6 +523,7 @@ describe("auth callback GET — user creation failures", () => {
`${origin}/error?message=server-error`,
);
expect(scheduleAccountCreatedGoalMock).not.toHaveBeenCalled();
+ expect(rollbackSessionMock).toHaveBeenCalledOnce();
});
it("redirects to rate-limited when the backend rejects with 429", async () => {
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 0ec6b80499..10dfad42ac 100644
--- a/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.ts
@@ -4,8 +4,10 @@ import { sanitizeAuthNext } from "@/lib/auth-redirect";
import {
EMAIL_VERIFICATION_NOTICE_PARAM,
type EmailVerificationNotice,
+ hasMarketingOptOutParam,
} from "@/lib/auth/email-verification";
import { getServerSession } from "@/lib/auth/server/getServerSession";
+import { recordSignupConsent } from "@/lib/auth/server/recordSignupConsent";
import { rollbackSession } from "@/lib/auth/server/rollbackSession";
import { type SignupMethod } from "@/services/analytics/account-created-cookie";
import { markAccountCreated } from "@/services/analytics/account-created-server";
@@ -13,6 +15,7 @@ import {
scheduleAccountCreatedGoal,
wasAccountCreated,
} from "@/services/analytics/datafast-server";
+import { takeMarketingOptOutFlag } from "@/services/analytics/marketing-opt-out-server";
import { revalidatePath } from "next/cache";
import { NextResponse } from "next/server";
@@ -72,10 +75,34 @@ export async function GET(request: Request) {
if (session?.user) {
try {
const createUserResponse = await postV1GetOrCreateUser();
- if (wasAccountCreated(createUserResponse)) {
+ // Consumed once the user exists, new or returning, so it applies to
+ // this sign-in only. Not taken before provisioning succeeds: a failure
+ // redirects to /error and the retry must still carry the refusal.
+ // Never throws, so it can't reach the rollback below.
+ const cookieOptOut = await takeMarketingOptOutFlag();
+ const accountCreated = wasAccountCreated(createUserResponse);
+ // An email sign-up's refusal comes in its verification link. Only the
+ // account the link creates takes it, so a crafted link can't change an
+ // existing account.
+ const marketingOptOut =
+ cookieOptOut ||
+ (accountCreated &&
+ signupMethod === "email" &&
+ hasMarketingOptOutParam(searchParams));
+ if (accountCreated) {
await scheduleAccountCreatedGoal(signupMethod);
await markAccountCreated(signupMethod);
}
+ // A returning account that opted out on /signup before continuing with
+ // Google records the refusal too: the page has already told them they
+ // won't get marketing emails. Never throws, so a failed consent write
+ // can't reach the rollback below or change where the user lands.
+ if (accountCreated || marketingOptOut) {
+ await recordSignupConsent({
+ userID: session.user.id,
+ marketingOptOut,
+ });
+ }
const { shouldShowOnboarding } = await getOnboardingStatus();
// Prefer a sanitized ?next (relative paths only — sanitizeAuthNext drops
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index cc87fab031..871855cecf 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -3071,6 +3071,46 @@
"security": [{ "HTTPBearerJWT": [] }]
}
},
+ "/api/auth/user/consent": {
+ "post": {
+ "tags": ["v1", "auth"],
+ "summary": "Record user consent",
+ "description": "Record the terms version accepted at signup and, if the user refused\nmarketing email, the opt-out. Idempotent; never clears an opt-out.",
+ "operationId": "postV1Record user consent",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RecordUserConsentRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/UserConsentResponse" }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ },
+ "security": [{ "HTTPBearerJWT": [] }]
+ }
+ },
"/api/auth/user/email": {
"post": {
"tags": ["v1", "auth"],
@@ -6247,6 +6287,19 @@
"security": [{ "APIKeyAuthenticator-X-Postmark-Webhook-Token": [] }]
}
},
+ "/api/email/mailerlite/webhook": {
+ "post": {
+ "tags": ["v1", "email"],
+ "summary": "Handle MailerLite webhooks",
+ "operationId": "postV1Handle mailerlite webhooks",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": { "application/json": { "schema": {} } }
+ }
+ }
+ }
+ },
"/api/email/unsubscribe": {
"post": {
"tags": ["v1", "email"],
@@ -28528,6 +28581,24 @@
"required": ["experiment_key", "variant"],
"title": "RecordAssignmentRequest"
},
+ "RecordUserConsentRequest": {
+ "properties": {
+ "terms_version": {
+ "type": "string",
+ "maxLength": 32,
+ "minLength": 1,
+ "pattern": "^[0-9]{4}-[0-9]{2}(-[0-9]{2})?$",
+ "title": "Terms Version"
+ },
+ "marketing_opt_out": {
+ "type": "boolean",
+ "title": "Marketing Opt Out"
+ }
+ },
+ "type": "object",
+ "required": ["terms_version", "marketing_opt_out"],
+ "title": "RecordUserConsentRequest"
+ },
"RefundRequest": {
"properties": {
"id": { "type": "string", "title": "Id" },
@@ -33148,6 +33219,34 @@
"type": "object",
"title": "UserAttributionInput"
},
+ "UserConsentResponse": {
+ "properties": {
+ "terms_accepted_at": {
+ "anyOf": [
+ { "type": "string", "format": "date-time" },
+ { "type": "null" }
+ ],
+ "title": "Terms Accepted At"
+ },
+ "terms_version": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Terms Version"
+ },
+ "marketing_opt_out_at": {
+ "anyOf": [
+ { "type": "string", "format": "date-time" },
+ { "type": "null" }
+ ],
+ "title": "Marketing Opt Out At"
+ },
+ "marketing_opt_out_source": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Marketing Opt Out Source"
+ }
+ },
+ "type": "object",
+ "title": "UserConsentResponse"
+ },
"UserCostSummary": {
"properties": {
"user_id": {
diff --git a/autogpt_platform/frontend/src/components/auth/CheckYourInbox/CheckYourInbox.tsx b/autogpt_platform/frontend/src/components/auth/CheckYourInbox/CheckYourInbox.tsx
index d847f3d017..486eb131bd 100644
--- a/autogpt_platform/frontend/src/components/auth/CheckYourInbox/CheckYourInbox.tsx
+++ b/autogpt_platform/frontend/src/components/auth/CheckYourInbox/CheckYourInbox.tsx
@@ -15,14 +15,22 @@ interface Props {
email: string;
reason: CheckYourInboxReason;
next?: string | null;
+ marketingOptOut?: boolean;
onBack: () => void;
}
-export function CheckYourInbox({ email, reason, next, onBack }: Props) {
+export function CheckYourInbox({
+ email,
+ reason,
+ next,
+ marketingOptOut,
+ onBack,
+}: Props) {
const copy = CHECK_YOUR_INBOX_COPY[reason];
const { cooldown, isResending, canResend, handleResend } = useCheckYourInbox({
email,
next,
+ marketingOptOut,
});
return (
diff --git a/autogpt_platform/frontend/src/components/auth/CheckYourInbox/useCheckYourInbox.ts b/autogpt_platform/frontend/src/components/auth/CheckYourInbox/useCheckYourInbox.ts
index 4a510b7ea9..59888075d0 100644
--- a/autogpt_platform/frontend/src/components/auth/CheckYourInbox/useCheckYourInbox.ts
+++ b/autogpt_platform/frontend/src/components/auth/CheckYourInbox/useCheckYourInbox.ts
@@ -10,9 +10,10 @@ import {
interface Args {
email: string;
next?: string | null;
+ marketingOptOut?: boolean;
}
-export function useCheckYourInbox({ email, next }: Args) {
+export function useCheckYourInbox({ email, next, marketingOptOut }: Args) {
const { toast } = useToast();
const [cooldown, setCooldown] = useState(RESEND_COOLDOWN_SECONDS);
const [isResending, setIsResending] = useState(false);
@@ -34,7 +35,7 @@ export function useCheckYourInbox({ email, next }: Args) {
// per-IP rate limit applies.
const { error } = await authClient.sendVerificationEmail({
email,
- callbackURL: getEmailVerificationCallbackURL(next),
+ callbackURL: getEmailVerificationCallbackURL({ next, marketingOptOut }),
});
if (error) {
showResendFailed(error.status === 429);
diff --git a/autogpt_platform/frontend/src/lib/auth/email-verification.ts b/autogpt_platform/frontend/src/lib/auth/email-verification.ts
index 89d77e9f07..dbbaa6bd22 100644
--- a/autogpt_platform/frontend/src/lib/auth/email-verification.ts
+++ b/autogpt_platform/frontend/src/lib/auth/email-verification.ts
@@ -19,13 +19,31 @@ export const EMAIL_NOT_VERIFIED_CODE = "EMAIL_NOT_VERIFIED";
export const EMAIL_VERIFICATION_NOTICE_PARAM = "email_verification";
export type EmailVerificationNotice = "expired" | "verified";
-export function getEmailVerificationCallbackURL(next?: string | null) {
+// A sign-up's marketing refusal rides in the link itself, so it survives the
+// link being opened on another device or long after sign-up. The callback
+// honours it only for the account that link creates.
+const MARKETING_OPT_OUT_PARAM = "marketing_opt_out";
+
+interface CallbackURLArgs {
+ next?: string | null;
+ marketingOptOut?: boolean;
+}
+
+export function getEmailVerificationCallbackURL({
+ next,
+ marketingOptOut = false,
+}: CallbackURLArgs = {}) {
const params = new URLSearchParams({ method: "email" });
const safeNext = sanitizeAuthNext(next);
if (safeNext) params.set("next", safeNext);
+ if (marketingOptOut) params.set(MARKETING_OPT_OUT_PARAM, "1");
return `/auth/callback?${params.toString()}`;
}
+export function hasMarketingOptOutParam(searchParams: URLSearchParams) {
+ return searchParams.get(MARKETING_OPT_OUT_PARAM) === "1";
+}
+
// 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.
diff --git a/autogpt_platform/frontend/src/lib/auth/server/__tests__/recordSignupConsent.test.ts b/autogpt_platform/frontend/src/lib/auth/server/__tests__/recordSignupConsent.test.ts
new file mode 100644
index 0000000000..6a7a2d40b2
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/auth/server/__tests__/recordSignupConsent.test.ts
@@ -0,0 +1,61 @@
+import { ApiError } from "@/lib/autogpt-server-api/helpers";
+import { TERMS_VERSION } from "@/lib/legal";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ postV1RecordUserConsent: vi.fn(),
+ captureException: vi.fn(),
+}));
+
+vi.mock("@/app/api/__generated__/endpoints/auth/auth", () => ({
+ postV1RecordUserConsent: mocks.postV1RecordUserConsent,
+}));
+vi.mock("@sentry/nextjs", () => ({
+ captureException: mocks.captureException,
+}));
+
+import { recordSignupConsent } from "../recordSignupConsent";
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.spyOn(console, "error").mockImplementation(() => undefined);
+ mocks.postV1RecordUserConsent.mockResolvedValue({ status: 200, data: {} });
+});
+
+describe("recordSignupConsent", () => {
+ it.each([true, false])(
+ "records the current terms version with marketing_opt_out=%s",
+ async (marketingOptOut) => {
+ await recordSignupConsent({ userID: "user-1", marketingOptOut });
+
+ expect(mocks.postV1RecordUserConsent).toHaveBeenCalledOnce();
+ expect(mocks.postV1RecordUserConsent).toHaveBeenCalledWith({
+ terms_version: TERMS_VERSION,
+ marketing_opt_out: marketingOptOut,
+ });
+ expect(mocks.captureException).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([
+ ["an ApiError from a non-2xx response", new ApiError("Bad", 500, {})],
+ ["a network failure", new TypeError("Failed to fetch")],
+ ])("reports %s without throwing", async (_label, error) => {
+ mocks.postV1RecordUserConsent.mockRejectedValue(error);
+
+ await expect(
+ recordSignupConsent({ userID: "user-1", marketingOptOut: true }),
+ ).resolves.toBeUndefined();
+
+ expect(mocks.captureException).toHaveBeenCalledOnce();
+ expect(mocks.captureException).toHaveBeenCalledWith(error, {
+ tags: { signup_step: "record_consent" },
+ user: { id: "user-1" },
+ extra: { marketingOptOut: true },
+ });
+ expect(console.error).toHaveBeenCalledWith(
+ "Failed to record signup consent:",
+ error,
+ );
+ });
+});
diff --git a/autogpt_platform/frontend/src/lib/auth/server/recordSignupConsent.ts b/autogpt_platform/frontend/src/lib/auth/server/recordSignupConsent.ts
new file mode 100644
index 0000000000..ce451e2672
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/auth/server/recordSignupConsent.ts
@@ -0,0 +1,34 @@
+import { postV1RecordUserConsent } from "@/app/api/__generated__/endpoints/auth/auth";
+import { TERMS_VERSION } from "@/lib/legal";
+import * as Sentry from "@sentry/nextjs";
+
+interface Args {
+ userID: string;
+ marketingOptOut: boolean;
+}
+
+/**
+ * Records terms acceptance, and a marketing refusal if there was one, on an
+ * account created in the same request. Never throws: a failed consent write is
+ * reported, but it must not fail or roll back the signup. The report names the
+ * account and the choice, because nothing retries the write and a lost refusal
+ * can only be re-applied by hand.
+ */
+export async function recordSignupConsent({
+ userID,
+ marketingOptOut,
+}: Args): Promise<void> {
+ try {
+ await postV1RecordUserConsent({
+ terms_version: TERMS_VERSION,
+ marketing_opt_out: marketingOptOut,
+ });
+ } catch (error) {
+ console.error("Failed to record signup consent:", error);
+ Sentry.captureException(error, {
+ tags: { signup_step: "record_consent" },
+ user: { id: userID },
+ extra: { marketingOptOut },
+ });
+ }
+}
diff --git a/autogpt_platform/frontend/src/lib/legal.ts b/autogpt_platform/frontend/src/lib/legal.ts
new file mode 100644
index 0000000000..1e005bf787
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/legal.ts
@@ -0,0 +1,9 @@
+export const TERMS_OF_USE_URL = "https://agpt.co/legal/platform-terms-of-use";
+export const PRIVACY_POLICY_URL =
+ "https://agpt.co/legal/platform-privacy-policy";
+// Bump when the terms or the privacy policy change. Stored on the user as
+// termsVersion so we can tell which text a given account agreed to. Format
+// YYYY-MM (or YYYY-MM-DD for a second change in a month). The backend records
+// only versions in RECOGNIZED_TERMS_VERSIONS (backend/api/model.py): add the
+// new one there, and deploy it, before bumping this.
+export const TERMS_VERSION = "2026-10";
diff --git a/autogpt_platform/frontend/src/playwright/utils/signup.ts b/autogpt_platform/frontend/src/playwright/utils/signup.ts
index c316c05c49..0f3cf48651 100644
--- a/autogpt_platform/frontend/src/playwright/utils/signup.ts
+++ b/autogpt_platform/frontend/src/playwright/utils/signup.ts
@@ -23,7 +23,7 @@ export async function signupTestUser(
const userEmail = email || faker.internet.email();
const userPassword = password || faker.internet.password({ length: 12 });
- const { getText, getField, getRole, getButton, getId } = getSelectors(page);
+ const { getText, getField, getButton, getId } = getSelectors(page);
try {
// Navigate to signup page
@@ -41,10 +41,6 @@ export async function signupTestUser(
const confirmPasswordInput = page.locator("#confirmPassword");
await confirmPasswordInput.fill(userPassword);
- // Agree to terms and submit. Scope to the Terms checkbox by accessible
- // name — in dev/local the AgentationDevtool renders extra checkboxes
- // globally, so a bare getByRole("checkbox") trips Playwright strict mode.
- await getRole("checkbox", /agree to the terms/i).click();
const signupButton = getButton("Sign up");
await signupButton.click();
diff --git a/autogpt_platform/frontend/src/services/analytics/__tests__/marketing-opt-out-cookie.test.ts b/autogpt_platform/frontend/src/services/analytics/__tests__/marketing-opt-out-cookie.test.ts
new file mode 100644
index 0000000000..64479eb895
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/__tests__/marketing-opt-out-cookie.test.ts
@@ -0,0 +1,132 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ cookies: vi.fn(),
+ cookieGet: vi.fn(),
+ cookieDelete: vi.fn(),
+ captureException: vi.fn(),
+}));
+
+vi.mock("next/headers", () => ({ cookies: mocks.cookies }));
+vi.mock("@sentry/nextjs", () => ({
+ captureException: mocks.captureException,
+}));
+
+import {
+ MARKETING_OPT_OUT_COOKIE,
+ setMarketingOptOutFlag,
+} from "../marketing-opt-out-cookie";
+import { takeMarketingOptOutFlag } from "../marketing-opt-out-server";
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+});
+
+describe("setMarketingOptOutFlag", () => {
+ function captureCookieWrites() {
+ return vi
+ .spyOn(document, "cookie", "set")
+ .mockImplementation(() => undefined);
+ }
+
+ it("writes a short-lived Secure refusal outside local stacks", () => {
+ vi.stubEnv("NEXT_PUBLIC_BEHAVE_AS", "CLOUD");
+ const write = captureCookieWrites();
+
+ setMarketingOptOutFlag(true);
+
+ expect(write).toHaveBeenCalledExactlyOnceWith(
+ "agpt_marketing_opt_out=1; Path=/; Max-Age=600; SameSite=Lax; Secure",
+ );
+ });
+
+ it("drops Secure on local stacks, which run on http", () => {
+ vi.stubEnv("NEXT_PUBLIC_BEHAVE_AS", "LOCAL");
+ const write = captureCookieWrites();
+
+ setMarketingOptOutFlag(true);
+
+ expect(write).toHaveBeenCalledExactlyOnceWith(
+ "agpt_marketing_opt_out=1; Path=/; Max-Age=600; SameSite=Lax",
+ );
+ });
+
+ it("clears the flag instead of writing a non-refusal", () => {
+ const write = captureCookieWrites();
+
+ setMarketingOptOutFlag(false);
+
+ expect(write).toHaveBeenCalledExactlyOnceWith(
+ "agpt_marketing_opt_out=; Path=/; Max-Age=0",
+ );
+ });
+
+ it("removes a refusal left by an earlier attempt that was undone", () => {
+ vi.stubEnv("NEXT_PUBLIC_BEHAVE_AS", "LOCAL");
+
+ setMarketingOptOutFlag(true);
+ expect(document.cookie).toContain(`${MARKETING_OPT_OUT_COOKIE}=1`);
+
+ setMarketingOptOutFlag(false);
+ expect(document.cookie).not.toContain(`${MARKETING_OPT_OUT_COOKIE}=1`);
+ });
+});
+
+describe("takeMarketingOptOutFlag", () => {
+ beforeEach(() => {
+ mocks.cookies.mockReset().mockResolvedValue({
+ get: mocks.cookieGet,
+ delete: mocks.cookieDelete,
+ });
+ mocks.cookieGet.mockReset();
+ mocks.cookieDelete.mockReset();
+ mocks.captureException.mockReset();
+ });
+
+ it("returns true for a refusal and deletes the cookie", async () => {
+ mocks.cookieGet.mockReturnValue({
+ name: MARKETING_OPT_OUT_COOKIE,
+ value: "1",
+ });
+
+ await expect(takeMarketingOptOutFlag()).resolves.toBe(true);
+
+ expect(mocks.cookieGet).toHaveBeenCalledWith(MARKETING_OPT_OUT_COOKIE);
+ expect(mocks.cookieDelete).toHaveBeenCalledExactlyOnceWith(
+ MARKETING_OPT_OUT_COOKIE,
+ );
+ });
+
+ it("treats any other value as not refused but still deletes it", async () => {
+ mocks.cookieGet.mockReturnValue({
+ name: MARKETING_OPT_OUT_COOKIE,
+ value: "true",
+ });
+
+ await expect(takeMarketingOptOutFlag()).resolves.toBe(false);
+
+ expect(mocks.cookieDelete).toHaveBeenCalledExactlyOnceWith(
+ MARKETING_OPT_OUT_COOKIE,
+ );
+ });
+
+ it("returns false and leaves the store alone when there is no cookie", async () => {
+ mocks.cookieGet.mockReturnValue(undefined);
+
+ await expect(takeMarketingOptOutFlag()).resolves.toBe(false);
+
+ expect(mocks.cookieDelete).not.toHaveBeenCalled();
+ });
+
+ it("returns false and reports the error when the cookie store fails", async () => {
+ const error = new Error("cookies() called outside a request scope");
+ mocks.cookies.mockRejectedValue(error);
+
+ await expect(takeMarketingOptOutFlag()).resolves.toBe(false);
+
+ expect(mocks.captureException).toHaveBeenCalledExactlyOnceWith(error, {
+ tags: { signup_step: "read_marketing_opt_out" },
+ });
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-events.test.ts b/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-events.test.ts
index e144aafb79..56e0e4ed16 100644
--- a/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-events.test.ts
+++ b/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-events.test.ts
@@ -45,6 +45,7 @@ const LIVE_EVENT_NAMES = [
"intro_followup_sent",
"intro_path",
"later_dump_completed",
+ "marketing_opted_out",
"onboarding_step_viewed",
"paywall_viewed",
"plan_selected",
diff --git a/autogpt_platform/frontend/src/services/analytics/__tests__/signup-analytics.test.ts b/autogpt_platform/frontend/src/services/analytics/__tests__/signup-analytics.test.ts
new file mode 100644
index 0000000000..3fd1dc52e7
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/__tests__/signup-analytics.test.ts
@@ -0,0 +1,75 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const { posthog, consent } = vi.hoisted(() => ({
+ posthog: {
+ __loaded: true,
+ is_capturing: vi.fn(() => true),
+ capture: vi.fn(),
+ },
+ consent: {
+ answer: null as { analytics: boolean } | null,
+ listeners: [] as (() => void)[],
+ },
+}));
+
+vi.mock("posthog-js", () => ({ default: posthog }));
+
+vi.mock("@/services/consent/consent", () => ({
+ getConsentAnswer: () => consent.answer,
+ isAwaitingConsentAnswer: () => false,
+ isConsentManagerConfigured: () => true,
+ subscribeToConsent: (listener: () => void) => {
+ consent.listeners.push(listener);
+ return () => undefined;
+ },
+ subscribeToConsentPrompt: () => () => undefined,
+}));
+
+import { resetPostHogCaptureQueueForTests } from "../posthog-capture";
+import { trackSignupMarketingOptOut } from "../signup-analytics";
+
+beforeEach(() => {
+ posthog.capture.mockReset();
+ posthog.is_capturing.mockReturnValue(true);
+ consent.answer = null;
+ consent.listeners = [];
+});
+
+afterEach(() => {
+ resetPostHogCaptureQueueForTests();
+});
+
+describe("trackSignupMarketingOptOut", () => {
+ it("reports the opt-out with only its surface", () => {
+ trackSignupMarketingOptOut();
+
+ expect(posthog.capture.mock.calls).toEqual([
+ ["marketing_opted_out", { surface: "signup" }],
+ ]);
+ });
+
+ it("holds the opt-out until analytics consent is given, then sends it", () => {
+ posthog.is_capturing.mockReturnValue(false);
+ consent.answer = { analytics: true };
+
+ trackSignupMarketingOptOut();
+ expect(posthog.capture).not.toHaveBeenCalled();
+
+ posthog.is_capturing.mockReturnValue(true);
+ consent.listeners.forEach((listener) => listener());
+
+ expect(posthog.capture).toHaveBeenCalledTimes(1);
+ expect(posthog.capture.mock.calls[0].slice(0, 2)).toEqual([
+ "marketing_opted_out",
+ { surface: "signup" },
+ ]);
+ });
+
+ it("swallows a blocked analytics host rather than breaking signup", () => {
+ posthog.capture.mockImplementation(() => {
+ throw new Error("blocked by client");
+ });
+
+ expect(() => trackSignupMarketingOptOut()).not.toThrow();
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/analytics/marketing-opt-out-cookie.ts b/autogpt_platform/frontend/src/services/analytics/marketing-opt-out-cookie.ts
new file mode 100644
index 0000000000..ec5c07a3df
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/marketing-opt-out-cookie.ts
@@ -0,0 +1,21 @@
+import { environment } from "@/services/environment";
+
+export const MARKETING_OPT_OUT_COOKIE = "agpt_marketing_opt_out";
+export const MARKETING_OPT_OUT_COOKIE_MAX_AGE_SECONDS = 600;
+
+// Carries a signup-page marketing opt-out across the Google OAuth round trip:
+// set here before leaving for Google, read and cleared by /auth/callback (see
+// marketing-opt-out-server.ts). Only a refusal is ever written; a missing
+// cookie means the person did not opt out. Clearing on the way out drops a
+// refusal left over from an abandoned attempt that the person has since undone.
+export function setMarketingOptOutFlag(optedOut: boolean): void {
+ if (typeof document === "undefined") return;
+
+ if (!optedOut) {
+ document.cookie = `${MARKETING_OPT_OUT_COOKIE}=; Path=/; Max-Age=0`;
+ return;
+ }
+
+ const secure = environment.isLocal() ? "" : "; Secure";
+ document.cookie = `${MARKETING_OPT_OUT_COOKIE}=1; Path=/; Max-Age=${MARKETING_OPT_OUT_COOKIE_MAX_AGE_SECONDS}; SameSite=Lax${secure}`;
+}
diff --git a/autogpt_platform/frontend/src/services/analytics/marketing-opt-out-server.ts b/autogpt_platform/frontend/src/services/analytics/marketing-opt-out-server.ts
new file mode 100644
index 0000000000..006ab0e5af
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/marketing-opt-out-server.ts
@@ -0,0 +1,23 @@
+import * as Sentry from "@sentry/nextjs";
+import { cookies } from "next/headers";
+import { MARKETING_OPT_OUT_COOKIE } from "./marketing-opt-out-cookie";
+
+// Reads and clears the signup-page marketing refusal carried across the Google
+// OAuth round trip (see marketing-opt-out-cookie.ts). A missing cookie means
+// the person did not opt out. Best effort: an unreadable cookie counts as not
+// refused rather than failing the sign-in.
+export async function takeMarketingOptOutFlag(): Promise<boolean> {
+ try {
+ const cookieStore = await cookies();
+ const flag = cookieStore.get(MARKETING_OPT_OUT_COOKIE);
+ if (!flag) return false;
+
+ cookieStore.delete(MARKETING_OPT_OUT_COOKIE);
+ return flag.value === "1";
+ } catch (error) {
+ Sentry.captureException(error, {
+ tags: { signup_step: "read_marketing_opt_out" },
+ });
+ return false;
+ }
+}
diff --git a/autogpt_platform/frontend/src/services/analytics/posthog-events.ts b/autogpt_platform/frontend/src/services/analytics/posthog-events.ts
index 6b7283b41e..692764f65b 100644
--- a/autogpt_platform/frontend/src/services/analytics/posthog-events.ts
+++ b/autogpt_platform/frontend/src/services/analytics/posthog-events.ts
@@ -23,6 +23,15 @@ export const FeatureFlagEvent = {
FEATURE_FLAG_MISMATCHED: "feature_flag_mismatched",
} as const;
+// Marketing email refusals made in the app. `surface` says where; the
+// refusal itself is stored on the user (`marketingOptOutAt`).
+export const MarketingConsentEvent = {
+ // `surface: "signup"`: "opt out" in the legal line under the signup buttons
+ // was clicked (not Undo). Nothing else rides along: there is no user yet,
+ // so it only measures the opt-out rate.
+ MARKETING_OPTED_OUT: "marketing_opted_out",
+} as const;
+
export const ExpertsFunnelEvent = {
EXPERTS_SECTION_VIEWED: "experts_section_viewed",
HOME_VIEWED: "home_viewed",
@@ -163,6 +172,7 @@ export const MonetizationEvent = {
export const PostHogEvent = {
...PageEvent,
...FeatureFlagEvent,
+ ...MarketingConsentEvent,
...ExpertsFunnelEvent,
...HireFlowEvent,
...BrainDumpEvent,
diff --git a/autogpt_platform/frontend/src/services/analytics/signup-analytics.ts b/autogpt_platform/frontend/src/services/analytics/signup-analytics.ts
new file mode 100644
index 0000000000..de99db961b
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/signup-analytics.ts
@@ -0,0 +1,10 @@
+import { MarketingConsentEvent } from "@/services/analytics/posthog-events";
+import { capturePostHogEvent } from "./posthog-capture";
+
+// Only the surface: there is no user yet, and no email may ride along. Held
+// until the cookie banner is answered, like every other browser event.
+export function trackSignupMarketingOptOut() {
+ capturePostHogEvent(MarketingConsentEvent.MARKETING_OPTED_OUT, {
+ surface: "signup",
+ });
+}
diff --git a/autogpt_platform/frontend/src/types/__tests__/auth.test.ts b/autogpt_platform/frontend/src/types/__tests__/auth.test.ts
index db5cb661fa..2a4f2919c1 100644
--- a/autogpt_platform/frontend/src/types/__tests__/auth.test.ts
+++ b/autogpt_platform/frontend/src/types/__tests__/auth.test.ts
@@ -7,7 +7,6 @@ describe("signupFormSchema", () => {
email: "not-an-email",
password: "short",
confirmPassword: "different",
- agreeToTerms: false,
});
expect(result.success).toBe(false);
@@ -23,19 +22,47 @@ describe("signupFormSchema", () => {
"Password must contain at least 12 characters",
);
expect(fieldErrors.confirmPassword).toContain("Passwords don't match");
- expect(fieldErrors.agreeToTerms).toContain(
- "You must agree to the Terms of Use and Privacy Policy",
- );
});
- test("accepts a valid signup payload", () => {
+ test("accepts a valid signup payload without a terms checkbox", () => {
const result = signupFormSchema.safeParse({
password: "validpassword123",
confirmPassword: "validpassword123",
- agreeToTerms: true,
});
expect(result.success).toBe(true);
});
+
+ test("defaults to not opted out of marketing emails", () => {
+ const result = signupFormSchema.parse({
+ email: "[email protected]",
+ password: "validpassword123",
+ confirmPassword: "validpassword123",
+ });
+
+ expect(result.marketingOptOut).toBe(false);
+ });
+
+ test("keeps a marketing opt-out", () => {
+ const result = signupFormSchema.parse({
+ email: "[email protected]",
+ password: "validpassword123",
+ confirmPassword: "validpassword123",
+ marketingOptOut: true,
+ });
+
+ expect(result.marketingOptOut).toBe(true);
+ });
+
+ test("rejects a non-boolean marketing opt-out", () => {
+ const result = signupFormSchema.safeParse({
+ email: "[email protected]",
+ password: "validpassword123",
+ confirmPassword: "validpassword123",
+ marketingOptOut: "yes",
+ });
+
+ expect(result.success).toBe(false);
+ });
});
diff --git a/autogpt_platform/frontend/src/types/auth.ts b/autogpt_platform/frontend/src/types/auth.ts
index f2c9b7ed6a..faca89600e 100644
--- a/autogpt_platform/frontend/src/types/auth.ts
+++ b/autogpt_platform/frontend/src/types/auth.ts
@@ -32,9 +32,7 @@ export const signupFormSchema = z
.string()
.min(AUTH_PASSWORD_MIN_LENGTH, MIN_LENGTH_MESSAGE)
.max(64, "Password must contain at most 64 characters"),
- agreeToTerms: z.boolean().refine((value) => value === true, {
- message: "You must agree to the Terms of Use and Privacy Policy",
- }),
+ marketingOptOut: z.boolean().default(false),
})
.refine((data) => data.password === data.confirmPassword, {
message: "Passwords don't match",
diff --git a/docs/engineering/tracking-plan.md b/docs/engineering/tracking-plan.md
index e13f64149e..08bbfbb6cb 100644
--- a/docs/engineering/tracking-plan.md
+++ b/docs/engineering/tracking-plan.md
@@ -143,6 +143,7 @@ what replaced them.
| `tour_scenario_started` | browser | live | `scenario` | A tour scenario starts playing. |
| `tour_scenario_completed` | browser | live | `scenario` | A tour scenario reaches its end. |
| `tour_cta_clicked` | browser | live | `label` (`free-trial`, `signup`, `pricing`, `another-scenario`, `self-host`, `share`), `placement` where the CTA has one, `surface` (`tour`, `marketplace`) on sidebar-card clicks | A tour or logged-out marketplace call to action is clicked. |
+| `marketing_opted_out` | browser | live | `surface` (`signup`) | Someone refuses marketing email in the app. `signup`: "opt out" is clicked in the legal line under the signup buttons (not "Undo"); nothing else is sent, since there is no user yet, so it only gives the opt-out rate. The refusal itself is stored on the user (`marketingOptOutAt`). |
| `signup_completed` | backend | live | `signup_method` (the auth provider, e.g. `email`, `google`: from the user's first Better Auth account row, where `credential` is reported as `email`, else from a Supabase token's `app_metadata.provider`; omitted when neither has it) | The user row is created (`data/user.py`), whichever request creates it. |
Sidebar CTA clicks retain the tour event names for compatibility. Filter
@@ -416,9 +417,10 @@ line:
families, ...) come with the plan's phases, not with this list.
- **Events the plan has no name for keep their own**, e.g.
`integration_connected`, `schedule_created`, `hire_started`,
- `billing_portal_opened`, `tour_*`, `tab_intro_*`, `voice_*` and
- `credential_*`. `briefing_opened` is the briefing shown on home, a
- different action from the plan's `briefing_opened_in_chat`.
+ `billing_portal_opened`, `marketing_opted_out`, `tour_*`,
+ `tab_intro_*`, `voice_*` and `credential_*`. `briefing_opened` is the
+ briefing shown on home, a different action from the plan's
+ `briefing_opened_in_chat`.
## Events not in the constants modules