diff --git a/backend/alembic/versions/add_email_password_auth.py b/backend/alembic/versions/add_email_password_auth.py
new file mode 100644
index 0000000000000000000000000000000000000000..2decda9bf4c8116dc555970a3472a8c940719dfe
--- /dev/null
+++ b/backend/alembic/versions/add_email_password_auth.py
@@ -0,0 +1,79 @@
+"""Add built-in email/password sign-in: users.password_hash + verification codes
+
+Our own provider alongside Google/Apple/Microsoft. Accounts stay bound to exactly
+one provider for life (no linking), so an email account needs no id column — the
+credential is the password hash added here, and mailbox control is proven by a
+one-time code before the users row is created at all.
+
+`email_verification_codes` holds pending signups (email + the hashed password the
+user typed) and password-reset codes. Pending signups deliberately do NOT live in
+`users`: is_active=False already means soft-deleted, and users.email is UNIQUE, so
+an abandoned signup parked there would squat the address permanently.
+
+Purely additive: one nullable column plus a new table, no backfill and no
+constraint changes, so it takes no disruptive lock on `users`.
+
+Revision ID: add_email_password_auth
+Revises: add_microsoft_auth_provider
+Create Date: 2026-09-15
+
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = "add_email_password_auth"
+down_revision = "add_microsoft_auth_provider"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ op.add_column("users", sa.Column("password_hash", sa.String(length=255), nullable=True))
+
+ op.create_table(
+ "email_verification_codes",
+ sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
+ sa.Column("email", sa.String(length=320), nullable=False),
+ sa.Column("purpose", sa.String(length=20), nullable=False),
+ sa.Column("code_hash", sa.String(length=64), nullable=False),
+ sa.Column("pending_password_hash", sa.String(length=255), nullable=True),
+ sa.Column("pending_name", sa.String(length=255), nullable=True),
+ sa.Column("attempts", sa.Integer(), nullable=False, server_default="0"),
+ sa.Column("expires_at", sa.DateTime(), nullable=False),
+ sa.Column("used", sa.Boolean(), nullable=False, server_default=sa.text("false")),
+ sa.Column("last_sent_at", sa.DateTime(), nullable=False, server_default=sa.func.now()),
+ sa.Column("created_at", sa.DateTime(), nullable=False, server_default=sa.func.now()),
+ )
+ op.create_index(
+ "ix_email_verification_codes_email", "email_verification_codes", ["email"]
+ )
+ # Every lookup is by (email, purpose) — codes are scoped to one purpose so a
+ # signup code can never be replayed as a password reset.
+ op.create_index(
+ "ix_email_verification_codes_email_purpose",
+ "email_verification_codes",
+ ["email", "purpose"],
+ )
+
+
+def downgrade() -> None:
+ # An email/password account's ONLY credential is password_hash — there is no
+ # external identity provider to fall back on, so dropping it would lock these
+ # users out permanently. Refuse rather than silently orphan real accounts; an
+ # operator must migrate or remove them first.
+ conn = op.get_bind()
+ orphans = conn.execute(
+ sa.text("SELECT COUNT(*) FROM users WHERE auth_provider = 'email'")
+ ).scalar()
+ if orphans:
+ raise RuntimeError(
+ f"Cannot downgrade: {orphans} email/password user(s) would lose their only "
+ "credential. Migrate or remove these accounts first."
+ )
+
+ op.drop_index(
+ "ix_email_verification_codes_email_purpose", table_name="email_verification_codes"
+ )
+ op.drop_index("ix_email_verification_codes_email", table_name="email_verification_codes")
+ op.drop_table("email_verification_codes")
+ op.drop_column("users", "password_hash")
diff --git a/backend/alembic/versions/add_user_token_version.py b/backend/alembic/versions/add_user_token_version.py
new file mode 100644
index 0000000000000000000000000000000000000000..25ce85d645bc5e0ad6720625def1fa2f46cb8787
--- /dev/null
+++ b/backend/alembic/versions/add_user_token_version.py
@@ -0,0 +1,40 @@
+"""Add users.token_version for JWT revocation
+
+Our access tokens are stateless, so until now nothing could invalidate one
+before it expired: logging out only cleared the browser's copy, and changing a
+password left any already-issued token working for the rest of its 72 hours (30
+days for an MCP refresh token). Every token now carries the account's counter as
+a "tv" claim, and get_current_user rejects any token whose claim no longer
+matches — so bumping this column revokes them all at once.
+
+Defaults to 0, which is also how a token minted before the claim existed is read,
+so deploying this signs nobody out.
+
+Purely additive: one NOT NULL column with a server default, no backfill.
+
+Revision ID: add_user_token_version
+Revises: add_email_password_auth
+Create Date: 2026-09-15
+
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = "add_user_token_version"
+down_revision = "add_email_password_auth"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "users",
+ sa.Column("token_version", sa.Integer(), nullable=False, server_default="0"),
+ )
+
+
+def downgrade() -> None:
+ # Safe to drop: losing the column means tokens stop being checked against it,
+ # which restores the previous (weaker) behaviour rather than locking anyone
+ # out. Tokens already issued keep working until they expire.
+ op.drop_column("users", "token_version")
diff --git a/backend/alembic/versions/drop_apple_microsoft_auth.py b/backend/alembic/versions/drop_apple_microsoft_auth.py
new file mode 100644
index 0000000000000000000000000000000000000000..f2f38d65b833b142804eb0237bd962f30431c627
--- /dev/null
+++ b/backend/alembic/versions/drop_apple_microsoft_auth.py
@@ -0,0 +1,91 @@
+"""Remove Apple and Microsoft sign-in: drop users.apple_id and users.microsoft_id
+
+Undoes add_apple_auth_provider and add_microsoft_auth_provider. It has to be a
+new forward revision rather than an alembic downgrade of those two: both sit
+upstream of add_email_password_auth and add_user_token_version, so reverting
+them would take the built-in email/password provider down with them.
+
+google_id deliberately stays NULLABLE. add_apple_auth_provider made it nullable
+because an Apple-only account has none, but email/password accounts have none
+either — restoring NOT NULL here would break every account created by our own
+provider. Nullability is now owned by add_email_password_auth's world, not by
+Apple's.
+
+auth_provider stays: it still distinguishes 'google' from 'email'. Only the two
+removed providers' id columns go.
+
+Revision ID: drop_apple_microsoft_auth
+Revises: add_user_token_version
+Create Date: 2026-09-16
+
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = "drop_apple_microsoft_auth"
+down_revision = "add_user_token_version"
+branch_labels = None
+depends_on = None
+
+
+def _index_names(conn, table: str) -> set[str]:
+ """Indexes actually present, so a re-run or a drifted DB doesn't hard-fail."""
+ return {ix["name"] for ix in sa.inspect(conn).get_indexes(table)}
+
+
+def _column_names(conn, table: str) -> set[str]:
+ return {c["name"] for c in sa.inspect(conn).get_columns(table)}
+
+
+def upgrade() -> None:
+ conn = op.get_bind()
+
+ # An Apple/Microsoft account's ONLY credential is the id column dropped
+ # below: no password_hash, no google_id. Dropping it would strand real
+ # accounts with an auth_provider the code no longer understands, unable to
+ # sign in and unable to recover. Refuse and let an operator decide — the
+ # same guard the two original migrations' downgrades use.
+ stranded = conn.execute(
+ sa.text(
+ "SELECT COUNT(*) FROM users WHERE auth_provider IN ('apple', 'microsoft')"
+ )
+ ).scalar()
+ if stranded:
+ raise RuntimeError(
+ f"Cannot drop Apple/Microsoft sign-in: {stranded} account(s) still use it "
+ "and would lose their only credential. Migrate or remove these accounts "
+ "first (e.g. move them to email/password, or soft-delete them)."
+ )
+
+ indexes = _index_names(conn, "users")
+ columns = _column_names(conn, "users")
+
+ if "ix_users_apple_id" in indexes:
+ op.drop_index("ix_users_apple_id", table_name="users")
+ if "apple_id" in columns:
+ op.drop_column("users", "apple_id")
+
+ if "ix_users_microsoft_id" in indexes:
+ op.drop_index("ix_users_microsoft_id", table_name="users")
+ if "microsoft_id" in columns:
+ op.drop_column("users", "microsoft_id")
+
+
+def downgrade() -> None:
+ """Restore both columns, empty.
+
+ The ids themselves are gone — this brings back the shape, not the data, so
+ re-enabling either provider means every affected user signs in afresh.
+ """
+ conn = op.get_bind()
+ columns = _column_names(conn, "users")
+
+ if "apple_id" not in columns:
+ op.add_column("users", sa.Column("apple_id", sa.String(length=255), nullable=True))
+ op.create_index("ix_users_apple_id", "users", ["apple_id"], unique=True)
+
+ if "microsoft_id" not in columns:
+ op.add_column(
+ "users", sa.Column("microsoft_id", sa.String(length=255), nullable=True)
+ )
+ op.create_index("ix_users_microsoft_id", "users", ["microsoft_id"], unique=True)
diff --git a/backend/app/auth.py b/backend/app/auth.py
index d80ba3e3ee9affa487d7862c56cc085dbb83e3ae..94cda9d0236473a7a8c2d697443a57192ce8c16c 100644
--- a/backend/app/auth.py
+++ b/backend/app/auth.py
@@ -19,32 +19,56 @@ security = HTTPBearer()
REFRESH_TOKEN_EXPIRATION_DAYS = 30
-def create_access_token(user_id: int) -> str:
- """Create a JWT access token for a user."""
+def create_access_token(user_id: int, token_version: int = 0) -> str:
+ """Create a JWT access token for a user.
+
+ ``token_version`` stamps the account's current revocation counter into the
+ token; see ``token_version_is_current``. It defaults to 0 so callers that
+ only hold a user id still mint a working token for an account that has never
+ revoked anything — but any path that CAN pass the real value should, or a
+ later bump will not invalidate the token it issued.
+ """
payload = {
"sub": str(user_id),
"exp": datetime.utcnow() + timedelta(hours=settings.JWT_EXPIRATION_HOURS),
"iat": datetime.utcnow(),
"typ": "access",
+ "tv": token_version,
}
return jwt.encode(payload, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM)
-def create_refresh_token(user_id: int) -> str:
+def create_refresh_token(user_id: int, token_version: int = 0) -> str:
"""Create a JWT refresh token for a user (30-day TTL).
Used by the MCP OAuth provider so claude.ai can refresh access tokens
- without redoing the Google login.
+ without redoing the Google login. Carries the same ``tv`` claim, so a
+ password reset disconnects the integration rather than leaving a 30-day
+ credential alive behind a changed password.
"""
payload = {
"sub": str(user_id),
"exp": datetime.utcnow() + timedelta(days=REFRESH_TOKEN_EXPIRATION_DAYS),
"iat": datetime.utcnow(),
"typ": "refresh",
+ "tv": token_version,
}
return jwt.encode(payload, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM)
+def token_version_is_current(payload: dict | None, user: "User") -> bool:
+ """Whether a decoded token is still valid for ``user``'s revocation counter.
+
+ Tokens minted before the ``tv`` claim existed are treated as version 0, which
+ is every account's starting value — so deploying this does not sign anyone
+ out. Once an account revokes for the first time its counter moves to 1 and
+ those legacy tokens stop validating along with everything else.
+ """
+ if payload is None:
+ return False
+ return int(payload.get("tv", 0)) == int(user.token_version or 0)
+
+
def decode_access_token(token: str) -> Optional[int]:
"""Decode and validate a JWT token. Returns user_id or None.
@@ -75,8 +99,12 @@ def get_current_user(
db: Session = Depends(get_db),
) -> User:
"""FastAPI dependency: extract and validate the current user from JWT."""
- user_id = decode_access_token(credentials.credentials)
- if user_id is None:
+ payload = decode_token_full(credentials.credentials)
+ try:
+ user_id = int(payload["sub"]) if payload else 0
+ except (KeyError, TypeError, ValueError):
+ user_id = 0
+ if not user_id:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or expired token",
@@ -88,4 +116,13 @@ def get_current_user(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="User not found or inactive",
)
+ # Revoked: the account's counter has moved on since this token was issued.
+ # Same 401 as an expired token, because to the client it means the same
+ # thing — sign in again — and distinguishing them tells an attacker holding
+ # a stale token that the account exists and was deliberately cut off.
+ if not token_version_is_current(payload, user):
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="Invalid or expired token",
+ )
return user
diff --git a/backend/app/config.py b/backend/app/config.py
index 1cf8bc57289f9d0a26916a58239d5578eb5bd7a1..baa5721828a88091d3056d03a0359536c32f2a92 100644
--- a/backend/app/config.py
+++ b/backend/app/config.py
@@ -96,17 +96,6 @@ class Settings(BaseSettings):
GOOGLE_CLIENT_ID: str = ""
GOOGLE_CLIENT_SECRET: str = ""
- # Sign in with Apple. APPLE_CLIENT_ID is the *Services ID* (e.g.
- # "com.firebird.blog2video.web"), which is the `aud` claim of the identity
- # token the browser hands us. We verify that token directly rather than
- # exchanging an auth code, so no Apple private key is needed server-side.
- APPLE_CLIENT_ID: str = ""
-
- # Sign in with Microsoft. MICROSOFT_CLIENT_ID is the Entra ID app
- # registration's *Application (client) ID*, matched against the ID token's
- # `aud`. No client secret: the SPA hands us an ID token we verify directly.
- MICROSOFT_CLIENT_ID: str = ""
-
# Stripe
STRIPE_SECRET_KEY: str = ""
STRIPE_PUBLISHABLE_KEY: str = ""
diff --git a/backend/app/database.py b/backend/app/database.py
index d7f258dd565b4da2c8148e8d1a147647efff1fe2..e76dd7272f6966cb5880b55f1a02a76795ac5eae 100644
--- a/backend/app/database.py
+++ b/backend/app/database.py
@@ -175,6 +175,10 @@ def _migrate_sqlite(eng) -> None:
"get_started_email_sent_at": "DATETIME",
"referrals_given": "INTEGER DEFAULT 0",
"referral_video_bonus": "INTEGER DEFAULT 0",
+ # Built-in email/password auth. NULL for social accounts.
+ "password_hash": "VARCHAR(255)",
+ # JWT revocation counter; see app/auth.py.
+ "token_version": "INTEGER DEFAULT 0",
}
with eng.begin() as conn:
for col_name, col_def in user_migrations.items():
@@ -716,6 +720,7 @@ def init_db():
SupportConversation,
SupportMessage,
ProjectMember,
+ EmailVerificationCode,
)
from app.models.subscription import seed_plans
diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py
index 1b52b7f6e6f227d1601a80ec87fa2a2364f57775..f2609b5e8bb395be9adc39034c3bda8c6dac1e02 100644
--- a/backend/app/models/__init__.py
+++ b/backend/app/models/__init__.py
@@ -40,6 +40,7 @@ from app.models.support_conversation import (
SupportMessageRole,
)
from app.models.mcp_oauth import MCPClient, MCPAuthCode
+from app.models.email_verification import EmailVerificationCode, VerificationPurpose
__all__ = [
@@ -54,4 +55,5 @@ __all__ = [
"SupportConversation", "SupportMessage", "SupportMessageRole",
"SupportConversation", "SupportMessage", "SupportMessageRole",
"MCPClient", "MCPAuthCode",
+ "EmailVerificationCode", "VerificationPurpose",
]
diff --git a/backend/app/models/email_verification.py b/backend/app/models/email_verification.py
new file mode 100644
index 0000000000000000000000000000000000000000..be6585b2f15712bd52fe507d61fb8193ed0c85f1
--- /dev/null
+++ b/backend/app/models/email_verification.py
@@ -0,0 +1,71 @@
+"""Short-lived email verification codes for built-in email/password auth.
+
+Two purposes share one table:
+
+- SIGNUP — issued by ``/api/auth/email/register/start``. Holds the password the
+ user typed, ALREADY HASHED, until the code is verified. This is why a pending
+ registration lives here and not as an inactive ``users`` row: ``is_active=False``
+ already means "soft-deleted, offer reactivation", and ``users.email`` is UNIQUE,
+ so an abandoned signup parked there would squat the address forever and would be
+ reported to other providers as a deleted account. The invariant this preserves is
+ worth stating plainly: **a row in ``users`` always means a real, verified account.**
+- PASSWORD_RESET — issued by ``/api/auth/password/forgot/start`` against an account
+ that already exists, so it carries no pending password.
+
+Modelled on ``MCPAuthCode`` (app/models/mcp_oauth.py): a code row with an expiry and
+a used flag, deleted once spent.
+"""
+import enum
+from datetime import datetime
+
+from sqlalchemy import Boolean, DateTime, Index, Integer, String, func
+from sqlalchemy.orm import Mapped, mapped_column
+
+from app.database import Base
+
+
+class VerificationPurpose(str, enum.Enum):
+ """What a code authorizes. Codes are scoped to one purpose so a signup code
+ can never be replayed as a password reset (or vice versa)."""
+
+ SIGNUP = "signup"
+ PASSWORD_RESET = "password_reset"
+
+
+class EmailVerificationCode(Base):
+ __tablename__ = "email_verification_codes"
+
+ id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
+ # Not a foreign key: for SIGNUP no user exists yet, by design.
+ email: Mapped[str] = mapped_column(String(320), nullable=False, index=True)
+ purpose: Mapped[str] = mapped_column(String(20), nullable=False)
+
+ # sha256 hex of the 6-digit code — NOT a password hash. A 6-digit code has
+ # only 10^6 possible values, so a slow KDF would cost real CPU on every
+ # verify while an attacker holding the table brute-forces it offline
+ # regardless. The defences that actually matter are the 5-attempt burn and
+ # the 10-minute expiry below.
+ code_hash: Mapped[str] = mapped_column(String(64), nullable=False)
+
+ # SIGNUP only: what becomes User.password_hash / User.name on verification.
+ pending_password_hash: Mapped[str | None] = mapped_column(String(255), nullable=True)
+ pending_name: Mapped[str | None] = mapped_column(String(255), nullable=True)
+
+ attempts: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default="0")
+ expires_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
+ used: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default="0")
+ # Drives the resend cooldown. Stored here rather than in the in-process rate
+ # limiter because this one must hold across workers and restarts.
+ last_sent_at: Mapped[datetime] = mapped_column(
+ DateTime, nullable=False, server_default=func.now()
+ )
+ created_at: Mapped[datetime] = mapped_column(
+ DateTime, nullable=False, server_default=func.now()
+ )
+
+ # Deliberately NOT unique: issuing a code deletes prior rows for the same
+ # (email, purpose) and inserts a fresh one, so at most one is live anyway.
+ # A unique constraint would turn a benign double-submit into a 500.
+ __table_args__ = (
+ Index("ix_email_verification_codes_email_purpose", "email", "purpose"),
+ )
diff --git a/backend/app/models/user.py b/backend/app/models/user.py
index 52d21ad65c7dce7a9d9390d6207653c03443403f..b828369be88e7a95f7df01e4667b802011c1b61d 100644
--- a/backend/app/models/user.py
+++ b/backend/app/models/user.py
@@ -18,14 +18,24 @@ class AuthProvider(str, enum.Enum):
An account is created by exactly one provider and stays bound to it for
life — we deliberately do not link providers, so an email registered with
- Google can never be signed into with Apple or Microsoft (and vice versa).
- Stored as a plain VARCHAR rather than a DB enum so adding a provider is a
- code change, not a Postgres type migration.
+ Google can never be signed into with a password (and vice versa). Stored as
+ a plain VARCHAR rather than a DB enum so adding a provider is a code change,
+ not a Postgres type migration.
+
+ EMAIL is our own built-in provider: no external identity provider, no
+ subject id — the credential is ``User.password_hash`` and mailbox control
+ is proven by a one-time code before the account is created at all. It is
+ therefore the one provider with no id column, and is deliberately absent
+ from ``_PROVIDER_ID_COLUMN`` in services/auth_identity.py.
+
+ Apple and Microsoft were removed in ``drop_apple_microsoft_auth``; that
+ migration refuses to run while any row still carries those values, so the
+ enum can safely omit them — a stray legacy row would now raise on load
+ (see AuthProviderType) rather than silently degrade to a string.
"""
GOOGLE = "google"
- APPLE = "apple"
- MICROSOFT = "microsoft"
+ EMAIL = "email"
@property
def label(self) -> str:
@@ -41,8 +51,7 @@ class AuthProvider(str, enum.Enum):
_PROVIDER_LABELS: dict[AuthProvider, str] = {
AuthProvider.GOOGLE: "Google",
- AuthProvider.APPLE: "Apple",
- AuthProvider.MICROSOFT: "Microsoft",
+ AuthProvider.EMAIL: "Email",
}
@@ -177,18 +186,36 @@ class User(Base):
picture: Mapped[str | None] = mapped_column(String(2048), nullable=True)
# ─── Identity ────────────────────────────────────────────────────────────
- # Exactly one of google_id / apple_id / microsoft_id is set, matching
- # auth_provider. Each keeps a UNIQUE index; NULLs are not considered equal
- # by Postgres or SQLite, so any number of rows may leave the others empty.
+ # google_id is set iff auth_provider is GOOGLE; an EMAIL account has none
+ # (its credential is password_hash below). It keeps a UNIQUE index, and
+ # NULLs are not considered equal by Postgres or SQLite, so any number of
+ # email accounts may leave it empty.
google_id: Mapped[str | None] = mapped_column(String(255), unique=True, nullable=True, index=True)
- apple_id: Mapped[str | None] = mapped_column(String(255), unique=True, nullable=True, index=True)
- microsoft_id: Mapped[str | None] = mapped_column(String(255), unique=True, nullable=True, index=True)
auth_provider: Mapped[AuthProvider] = mapped_column(
AuthProviderType(),
default=AuthProvider.GOOGLE,
server_default=AuthProvider.GOOGLE.value,
nullable=False,
)
+ # Argon2id encoded hash, set only for AuthProvider.EMAIL accounts — the
+ # social providers hold the credential themselves, so this stays NULL for
+ # them and verify_password() treats NULL as "never matches". A row only
+ # ever gets one once a one-time code has proven the mailbox (see
+ # services/email_verification.py), so an unverified email never puts a
+ # credential in this table.
+ password_hash: Mapped[str | None] = mapped_column(String(255), nullable=True)
+
+ # Bumped to invalidate every JWT already issued for this account. Our tokens
+ # are stateless, so without this there is no way to revoke one before it
+ # expires: signing out only clears the browser's copy, and changing a
+ # password would leave a thief's token working for the rest of its 72 hours.
+ # Every token carries the value current at issue (the "tv" claim) and
+ # get_current_user rejects any that no longer matches. Tokens minted before
+ # this column existed have no claim and are read as 0, which is the default,
+ # so adding it logs nobody out.
+ token_version: Mapped[int] = mapped_column(
+ Integer, nullable=False, default=0, server_default="0"
+ )
# Subscription
plan: Mapped[PlanTier] = mapped_column(Enum(PlanTier), default=PlanTier.FREE)
diff --git a/backend/app/routers/auth.py b/backend/app/routers/auth.py
index 0092c459c84360f944c3dd67b2cca402154c3077..5f89a18df77ee715018b5e4bca019069c9c33332 100644
--- a/backend/app/routers/auth.py
+++ b/backend/app/routers/auth.py
@@ -1,11 +1,19 @@
"""
-Social authentication router (Google and Apple).
-Frontend sends the provider's ID token, backend verifies it and returns a JWT.
+Authentication router.
+
+Social (Google): the frontend sends the provider's ID token, the backend
+verifies it and returns a JWT.
+
+Built-in email + password: registration proves mailbox control with a one-time
+code BEFORE any account exists, then every later sign-in is password-only. Both
+providers share ``_finalize_login`` and the identity rules in
+``app.services.auth_identity``, so one-account-per-email holds across them.
"""
import os
+import re
import shutil
-from fastapi import APIRouter, Depends, HTTPException, Query
-from pydantic import BaseModel
+from fastapi import APIRouter, Depends, HTTPException, Query, Request
+from pydantic import BaseModel, Field, field_validator
from sqlalchemy.orm import Session
from google.oauth2 import id_token
from google.auth.transport import requests as google_requests
@@ -13,18 +21,23 @@ from google.auth.transport import requests as google_requests
from app.config import settings
from app.database import get_db
from app.models.user import User, AuthProvider, PlanTier, PAID_TIERS, FREE_TIER_INCLUDED_VIDEOS, FREE_TIER_CUSTOM_TEMPLATES, FREE_AI_EDIT_CREDITS
-from app.services.auth_identity import resolve_or_create_user
-from app.services.apple_auth import (
- APPLE_PRIVATE_RELAY_DOMAIN,
- AppleAuthError,
- full_name_from_apple_payload,
- verify_apple_identity_token,
+from app.services.auth_identity import (
+ assert_email_available_for_password,
+ create_password_user,
+ resolve_or_create_user,
+ resolve_password_user,
+ _handle_soft_deleted,
)
-from app.services.microsoft_auth import (
- MicrosoftAuthError,
- MicrosoftNoEmailError,
- verify_microsoft_id_token,
+from app.models.email_verification import EmailVerificationCode, VerificationPurpose
+from app.services.email import email_service, EmailServiceError
+from app.services import email_verification as verification
+from app.services.password import (
+ hash_password,
+ needs_rehash,
+ validate_password,
+ verify_password,
)
+from app.services import rate_limit
from app.models.project import Project
from app.models.subscription import Subscription
from app.auth import create_access_token, get_current_user
@@ -42,16 +55,64 @@ class GoogleLoginRequest(BaseModel):
credential: str # Google ID token from frontend
-class AppleLoginRequest(BaseModel):
- identity_token: str # Apple identity token (JWT) from frontend
- # Apple returns the user's name ONLY on the very first authorization, in a
- # payload beside the token rather than inside it. The frontend forwards it
- # when present; every subsequent sign-in has nothing here.
- user: dict | None = None
+# ─── Email + password request models ─────────────────────────────────────────
+# Addresses are validated with a deliberately permissive regex rather than
+# pydantic's EmailStr: EmailStr needs the `email-validator` package, and a
+# missing optional dependency there is an import-time crash of the entire API.
+# Real validation is the one-time code — an address that cannot receive mail
+# never becomes an account, whatever its shape.
+_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
+
+# Passwords are accepted at min_length=1 here and checked by validate_password()
+# in the handler, so a too-short password returns our `password_too_short` code
+# rather than pydantic's 422 envelope, which the frontend's error parser can't read.
+_PasswordField = Field(min_length=1, max_length=512)
+_CodeField = Field(min_length=6, max_length=6, pattern=r"^\d{6}$")
+
+
+class _EmailBody(BaseModel):
+ email: str = Field(min_length=3, max_length=320)
+
+ @field_validator("email")
+ @classmethod
+ def _normalize_email(cls, v: str) -> str:
+ v = v.strip().lower()
+ if not _EMAIL_RE.match(v):
+ raise ValueError("invalid_email")
+ return v
+
+
+class EmailLoginRequest(_EmailBody):
+ password: str = _PasswordField
+
+
+class EmailRegisterStartRequest(_EmailBody):
+ password: str = _PasswordField
+ name: str | None = Field(default=None, max_length=255)
+
+
+class EmailCodeRequest(_EmailBody):
+ code: str = _CodeField
+
+class EmailResendRequest(_EmailBody):
+ pass
-class MicrosoftLoginRequest(BaseModel):
- id_token: str # Microsoft ID token (JWT) from MSAL
+
+class ForgotPasswordStartRequest(_EmailBody):
+ pass
+
+
+class ForgotPasswordCompleteRequest(_EmailBody):
+ code: str = _CodeField
+ new_password: str = _PasswordField
+
+
+class CodeSentResponse(BaseModel):
+ """Acknowledges that a code was issued. Carries no account information."""
+ status: str = "code_sent"
+ expires_in: int = verification.CODE_TTL_SECONDS
+ resend_in: int = verification.RESEND_COOLDOWN_SECONDS
class AuthResponse(BaseModel):
@@ -210,7 +271,10 @@ def _finalize_login(
ensure_free_voices_for_user(db, user.id)
- return AuthResponse(access_token=create_access_token(user.id), user=_serialize_user(user))
+ return AuthResponse(
+ access_token=create_access_token(user.id, user.token_version or 0),
+ user=_serialize_user(user),
+ )
@router.post("/google", response_model=AuthResponse)
@@ -223,7 +287,7 @@ def google_login(
"""
Verify Google ID token and create/login user.
Returns a JWT access token.
- If the email belongs to an Apple account, returns 409 wrong_auth_provider.
+ If the email belongs to an email/password account, returns 409 wrong_auth_provider.
If user was soft-deleted (is_active=False), returns 403 with account_deleted
unless reactivate=true, in which case the account is reactivated as a free user.
"""
@@ -254,85 +318,339 @@ def google_login(
return _finalize_login(db, user, created_new_user=created_new_user, ref_code=ref_code)
-@router.post("/apple", response_model=AuthResponse)
-def apple_login(
- body: AppleLoginRequest,
- reactivate: bool = Query(False, description="Confirm reactivation of a previously deleted account"),
- ref_code: str | None = Query(None, description="Referral code from an invite link"),
+# ─── Built-in email + password ───────────────────────────────────────────────
+
+
+def _send_code_or_502(send, to_email: str, code: str, *, kind: str) -> None:
+ """Deliver a one-time code, converting provider failure into 502.
+
+ The caller must have COMMITTED the code row first: if the send fails we want
+ a durable, resendable code rather than a rolled-back one, so the user can
+ simply press "Resend" instead of starting over.
+ """
+ try:
+ send(to_email, code)
+ except EmailServiceError as e:
+ logger.error("[AUTH] Failed to send %s code to %s: %s", kind, to_email, e)
+ raise HTTPException(status_code=502, detail="email_send_failed")
+
+
+@router.post("/email/register/start", response_model=CodeSentResponse)
+def email_register_start(
+ body: EmailRegisterStartRequest,
+ request: Request,
db: Session = Depends(get_db),
):
+ """Begin email/password registration by emailing a one-time code.
+
+ No account is created here. The password is hashed and parked on the code row
+ until the address is verified, so an unverified email never puts a credential
+ in the users table and never squats a unique email address.
+
+ Errors, all raised BEFORE any code is issued or sent, and in this order —
+ the address outranks the password, so someone who already has an account is
+ told so rather than being asked to fix a password they will never use:
+ 409 wrong_auth_provider — the address belongs to a social account.
+ 409 email_already_registered — the address is already an email/password
+ account, whether live OR soft-deleted.
+ 422 password_too_short / password_too_long /
+ password_needs_uppercase / password_needs_special — policy violation,
+ raised only once the address is known to be free.
+
+ A soft-deleted account deliberately answers the SAME 409 as a live one and
+ never 403 account_deleted. Reactivation is a decision about an account you
+ are signing in to, so it belongs to the login and password-reset flows, which
+ authenticate first; offering it here would put a "Reactivate your account?"
+ prompt on a form that says "Create your account" and hand it to anyone who
+ guessed the address. Collapsing the two also stops this endpoint from
+ reporting, unauthenticated, whether a known address is deleted or live.
"""
- Verify an Apple identity token and create/login user.
- Mirrors the Google endpoint's contract exactly.
+ rate_limit.register_limiter.check(rate_limit.client_key(request))
+
+ email = body.email
+
+ # The address is checked BEFORE the password policy, deliberately. These two
+ # orderings answer different questions, and for an address that already has
+ # an account the policy answer is noise: the user is being told to fix a
+ # password they are not going to use, on a form they should not be on. The
+ # only useful reply is "this account exists — sign in", whatever they typed.
+ existing = assert_email_available_for_password(db, email)
+ if existing is not None:
+ # Identical response for live and soft-deleted; see the docstring. The
+ # frontend routes both to the sign-in form, where a deleted account then
+ # gets the reactivation prompt once the password is proven.
+ rate_limit.register_limiter.record_failure(rate_limit.client_key(request))
+ raise HTTPException(status_code=409, detail={"code": "email_already_registered"})
+
+ # Only now does the password matter — this address is actually going to
+ # become an account.
+ validate_password(body.password)
+
+ _row, code = verification.issue_code(
+ db,
+ email=email,
+ purpose=VerificationPurpose.SIGNUP,
+ pending_password_hash=hash_password(body.password),
+ pending_name=(body.name or "").strip() or email.split("@")[0],
+ )
+ db.commit()
+
+ _send_code_or_502(
+ email_service.send_verification_code_email, email, code, kind="signup"
+ )
+ return CodeSentResponse()
+
+
+@router.post("/email/register/verify", response_model=AuthResponse)
+def email_register_verify(
+ body: EmailCodeRequest,
+ request: Request,
+ ref_code: str | None = Query(None, description="Referral code from an invite link"),
+ db: Session = Depends(get_db),
+):
+ """Verify the signup code and create the account.
- Rejects "Hide My Email" relay addresses with 400 apple_private_email: a relay
- address is a different mailbox from the user's real one, so accepting it
- would create a second account for the same person.
+ The provider check is repeated here, not just at start: a Google signup for
+ the same address can land in the window between the two calls, and that must
+ lose to the account that already exists rather than 500 on the unique index.
"""
- try:
- identity = verify_apple_identity_token(body.identity_token)
- except AppleAuthError as e:
- raise HTTPException(status_code=401, detail=str(e))
+ rate_limit.verify_limiter.check(rate_limit.client_key(request))
- if identity.is_private_email:
- raise HTTPException(status_code=400, detail="apple_private_email")
+ email = body.email
+ row = verification.consume_code(
+ db, email=email, purpose=VerificationPurpose.SIGNUP, code=body.code
+ )
- apple_name = full_name_from_apple_payload(body.user)
+ existing = assert_email_available_for_password(db, email)
+ if existing is not None:
+ raise HTTPException(status_code=409, detail={"code": "email_already_registered"})
- user, created_new_user = resolve_or_create_user(
+ user, created = create_password_user(
db,
- provider=AuthProvider.APPLE,
- provider_user_id=identity.apple_id,
- email=identity.email,
- name=apple_name or identity.email.split("@")[0],
- picture=None, # Apple provides no profile picture
- # Only overwrite an existing account's name when Apple actually sent one
- # (first authorization only) — never with the email-derived fallback.
- refresh_name=apple_name is not None,
- reactivate=reactivate,
+ email=email,
+ name=row.pending_name or email.split("@")[0],
+ password_hash=row.pending_password_hash,
)
+ db.delete(row)
- return _finalize_login(db, user, created_new_user=created_new_user, ref_code=ref_code)
+ rate_limit.verify_limiter.clear(rate_limit.client_key(request))
+ return _finalize_login(db, user, created_new_user=created, ref_code=ref_code)
+
+
+@router.post("/email/register/resend", response_model=CodeSentResponse)
+def email_register_resend(
+ body: EmailResendRequest,
+ request: Request,
+ db: Session = Depends(get_db),
+):
+ """Re-send the signup code, reusing the password already captured at start.
+ Returns 429 resend_too_soon (with Retry-After) inside the 60s cooldown, and
+ 400 no_pending_registration when there is nothing to resend.
+ """
+ rate_limit.resend_limiter.check(rate_limit.email_key(body.email))
+
+ email = body.email
+ pending = (
+ db.query(EmailVerificationCode)
+ .filter(
+ EmailVerificationCode.email == email,
+ EmailVerificationCode.purpose == VerificationPurpose.SIGNUP.value,
+ EmailVerificationCode.used.is_(False),
+ )
+ .order_by(EmailVerificationCode.created_at.desc(), EmailVerificationCode.id.desc())
+ .first()
+ )
+ if pending is None:
+ rate_limit.resend_limiter.record_failure(rate_limit.email_key(body.email))
+ raise HTTPException(status_code=400, detail="no_pending_registration")
-@router.post("/microsoft", response_model=AuthResponse)
-def microsoft_login(
- body: MicrosoftLoginRequest,
+ # Never re-ask for the password: reuse what start() hashed.
+ _row, code = verification.issue_code(
+ db,
+ email=email,
+ purpose=VerificationPurpose.SIGNUP,
+ pending_password_hash=pending.pending_password_hash,
+ pending_name=pending.pending_name,
+ )
+ db.commit()
+
+ _send_code_or_502(
+ email_service.send_verification_code_email, email, code, kind="signup"
+ )
+ return CodeSentResponse()
+
+
+@router.post("/email/login", response_model=AuthResponse)
+def email_login(
+ body: EmailLoginRequest,
+ request: Request,
reactivate: bool = Query(False, description="Confirm reactivation of a previously deleted account"),
- ref_code: str | None = Query(None, description="Referral code from an invite link"),
db: Session = Depends(get_db),
):
+ """Sign in with email and password. No code is sent — verification happened at signup.
+
+ Ordering is deliberate and load-bearing:
+ 1. resolve_password_user -> 409 wrong_auth_provider / 401 invalid_credentials
+ 2. verify_password -> 401 invalid_credentials
+ 3. only THEN reactivation
+ Checking the password before step 3 is what stops a wrong password plus
+ ?reactivate=true from resurrecting a soft-deleted account on a failed login.
"""
- Verify a Microsoft ID token and create/login user.
- Mirrors the Google endpoint's contract exactly. Accepts both personal
- Microsoft accounts (outlook.com/hotmail.com/live.com) and work/school
- accounts from any Microsoft 365 tenant.
+ ip_key = rate_limit.client_key(request)
+ mail_key = rate_limit.email_key(body.email)
+ rate_limit.login_ip_limiter.check(ip_key)
+ rate_limit.login_email_limiter.check(mail_key)
+
+ def _reject() -> HTTPException:
+ rate_limit.login_ip_limiter.record_failure(ip_key)
+ rate_limit.login_email_limiter.record_failure(mail_key)
+ return HTTPException(status_code=401, detail="invalid_credentials")
+
+ # A 409 here is a correct answer for a legitimate user, so it must not count
+ # as a failed attempt — otherwise someone who forgot they used Google gets
+ # locked out for 15 minutes for asking.
+ user = resolve_password_user(db, email=body.email)
+
+ if not verify_password(body.password, user.password_hash):
+ raise _reject()
+
+ if not user.is_active:
+ # Password is already proven; safe to run the reactivation gate, which
+ # raises 403 account_deleted unless the client confirmed.
+ _handle_soft_deleted(user, reactivate=reactivate, allow_reactivation=True)
+
+ # Opportunistically migrate hashes to current Argon2 parameters while we
+ # hold the plaintext. _finalize_login commits.
+ if needs_rehash(user.password_hash):
+ user.password_hash = hash_password(body.password)
+
+ rate_limit.login_ip_limiter.clear(ip_key)
+ rate_limit.login_email_limiter.clear(mail_key)
+ # ref_code is inert on login (no new user), passed as None to say so.
+ return _finalize_login(db, user, created_new_user=False, ref_code=None)
+
+
+@router.post("/password/forgot/start", response_model=CodeSentResponse)
+def forgot_password_start(
+ body: ForgotPasswordStartRequest,
+ request: Request,
+ reactivate: bool = Query(False, description="Confirm reactivation of a previously deleted account"),
+ db: Session = Depends(get_db),
+):
+ """Email a password-reset code.
+
+ Enumeration behaviour differs from registration on purpose. A social-owned
+ address still returns 409 naming the provider, because the user needs to know
+ there is no password to reset. But an address with NO account returns a
+ normal 200 and sends nothing: there is no recovery path to offer, so naming
+ it would turn this into a bulk address-harvesting endpoint for free.
+
+ A soft-deleted account returns 403 account_deleted, and ``?reactivate=true``
+ is the confirmation that revives it. This is the ONLY recovery path for
+ someone who deleted their account and has also forgotten the password — the
+ login route needs the old password, which by definition they don't have.
+
+ Reactivation here deliberately issues no token: it restores the account and
+ then emails the reset code exactly as for a live account, so the user still
+ has to prove mailbox control and set a new password before
+ ``forgot/complete`` signs them in. Reviving on an unauthenticated request is
+ safe precisely because it grants no access — the mailbox, not this call, is
+ what unlocks the account.
+ """
+ rate_limit.forgot_ip_limiter.check(rate_limit.client_key(request))
+ rate_limit.forgot_email_limiter.check(rate_limit.email_key(body.email))
+
+ email = body.email
+ user = assert_email_available_for_password(db, email)
+
+ if user is None:
+ rate_limit.forgot_ip_limiter.record_failure(rate_limit.client_key(request))
+ return CodeSentResponse()
+
+ if not user.is_active:
+ # Raises 403 account_deleted unless the client confirmed; on confirm it
+ # restores the row in the session, committed below alongside the code.
+ _handle_soft_deleted(user, reactivate=reactivate, allow_reactivation=True)
+ logger.info("[AUTH] Reactivated account %s via password reset", user.id)
+
+ _row, code = verification.issue_code(
+ db, email=email, purpose=VerificationPurpose.PASSWORD_RESET
+ )
+ db.commit()
+
+ _send_code_or_502(
+ email_service.send_password_reset_code_email, email, code, kind="password reset"
+ )
+ return CodeSentResponse()
+
- Returns 400 microsoft_no_email when the account shares no usable email
- address — without one we cannot enforce one-account-per-email.
+@router.post("/password/forgot/check")
+def forgot_password_check(
+ body: EmailCodeRequest,
+ request: Request,
+ db: Session = Depends(get_db),
+):
+ """Validate a reset code without spending it.
+
+ Lets the UI reject a wrong code at the "enter your code" step instead of
+ walking the user to the new-password screen and only failing on submit. The
+ code is NOT consumed here — forgot/complete still does that, because it is
+ what authorizes the actual password change.
+
+ Same error codes as forgot/complete's consume step, including the shared
+ attempt counter, so this cannot be used to brute-force the code for free.
"""
- try:
- identity = verify_microsoft_id_token(body.id_token)
- except MicrosoftNoEmailError:
- # Valid token, but the account shares no email — a fixable settings
- # problem rather than an untrusted token, so 400 with specific copy.
- raise HTTPException(status_code=400, detail="microsoft_no_email")
- except MicrosoftAuthError as e:
- raise HTTPException(status_code=401, detail=str(e))
+ rate_limit.verify_limiter.check(rate_limit.client_key(request))
- user, created_new_user = resolve_or_create_user(
- db,
- provider=AuthProvider.MICROSOFT,
- provider_user_id=identity.microsoft_id,
- email=identity.email,
- # Unlike Apple, Microsoft sends `name` on every sign-in, so the stored
- # name can be refreshed normally.
- name=identity.name or identity.email.split("@")[0],
- picture=None, # Graph photo needs a separate authenticated call
- reactivate=reactivate,
+ verification.check_code(
+ db, email=body.email, purpose=VerificationPurpose.PASSWORD_RESET, code=body.code
)
+ return {"status": "code_valid"}
- return _finalize_login(db, user, created_new_user=created_new_user, ref_code=ref_code)
+
+@router.post("/password/forgot/complete", response_model=AuthResponse)
+def forgot_password_complete(
+ body: ForgotPasswordCompleteRequest,
+ request: Request,
+ db: Session = Depends(get_db),
+):
+ """Verify the reset code, set the new password, and sign the user in.
+
+ The code is consumed here and nowhere earlier — verifying it in a separate
+ round trip would spend it and leave nothing to authorize the actual change.
+ """
+ rate_limit.verify_limiter.check(rate_limit.client_key(request))
+
+ email = body.email
+ validate_password(body.new_password)
+
+ verification.consume_code(
+ db, email=email, purpose=VerificationPurpose.PASSWORD_RESET, code=body.code
+ )
+
+ user = resolve_password_user(db, email=email)
+ if not user.is_active:
+ raise HTTPException(
+ status_code=403,
+ detail="account_deleted",
+ headers={"X-Account-Deleted": "true"},
+ )
+
+ user.password_hash = hash_password(body.new_password)
+ # Revoke every token issued under the OLD password. This is the point of a
+ # password reset when the account is already compromised: without it the
+ # attacker's session survives the reset that was meant to evict them, for up
+ # to 72 hours (30 days for an MCP refresh token). _finalize_login below reads
+ # the bumped value, so the user's own new token is minted against it and they
+ # stay signed in on this device.
+ user.token_version = (user.token_version or 0) + 1
+ # Drop every code for this address, both purposes: an in-flight signup code
+ # must not stay replayable now that the credential has changed.
+ verification.clear_codes(db, email=email)
+
+ rate_limit.login_email_limiter.clear(rate_limit.email_key(email))
+ return _finalize_login(db, user, created_new_user=False, ref_code=None)
@router.get("/me", response_model=UserOut)
@@ -349,7 +667,20 @@ def logout_cleanup(
"""
Handle logout. Data is NOT deleted here — the periodic cleanup task
handles deletion after 24 hours for free-tier users.
+
+ Bumps token_version so the JWT just used stops working immediately. Our
+ tokens are stateless, so without this signing out would only clear the
+ browser's copy and leave the credential valid for the rest of its 72 hours —
+ which matters most on a shared or public machine, exactly where people press
+ "log out" deliberately.
+
+ Note this signs the account out everywhere, not just this browser: with one
+ counter per user there is no way to revoke a single token. That is the
+ conservative direction for a security control, and it is what "log out"
+ already implies to most people.
"""
+ user.token_version = (user.token_version or 0) + 1
+ db.commit()
return {"detail": "Logged out"}
@@ -425,6 +756,10 @@ def delete_account(
if used > FREE_TIER_INCLUDED_VIDEOS:
user.videos_used_this_period = FREE_TIER_INCLUDED_VIDEOS
user.is_active = False
+ # NOTE: password_hash is deliberately NOT cleared here. For an email
+ # account it is the only credential, and reactivation authenticates with
+ # it (POST /email/login?reactivate=true) — clearing it would make a
+ # deleted email account uniquely unrecoverable, unlike every social one.
user.stripe_customer_id = None
user.stripe_subscription_id = None
user.plan = PlanTier.FREE
diff --git a/backend/app/routers/collab_ws.py b/backend/app/routers/collab_ws.py
index 9b329690f85116d9acb7688961f146e987cf62da..6379d9cbeb295b59e5bf2bd6133aa455ca4798ca 100644
--- a/backend/app/routers/collab_ws.py
+++ b/backend/app/routers/collab_ws.py
@@ -24,7 +24,7 @@ from fastapi import APIRouter, WebSocket, WebSocketDisconnect, Query
from starlette.websockets import WebSocketState
from app.database import SessionLocal
-from app.auth import decode_access_token
+from app.auth import decode_token_full, token_version_is_current
from app.models.user import User
from app.models.project import Project
from app.services.access import get_member
@@ -214,7 +214,8 @@ def _authenticate(token: Optional[str], db) -> Optional[User]:
if not token:
return None
try:
- user_id = decode_access_token(token)
+ payload = decode_token_full(token)
+ user_id = int(payload["sub"]) if payload else 0
except Exception:
return None
if not user_id:
@@ -222,6 +223,10 @@ def _authenticate(token: Optional[str], db) -> Optional[User]:
user = db.query(User).filter(User.id == user_id).first()
if not user or not user.is_active:
return None
+ # Mirror get_current_user: a revoked token must not open a socket either,
+ # or logging out would leave a live collaboration session behind.
+ if not token_version_is_current(payload, user):
+ return None
return user
diff --git a/backend/app/routers/mcp_transport.py b/backend/app/routers/mcp_transport.py
index 30b3175aab2fcad21ab16352b3df10f2a88750ea..5f597028f31560fc7c8a50022081b102ffe660b8 100644
--- a/backend/app/routers/mcp_transport.py
+++ b/backend/app/routers/mcp_transport.py
@@ -574,6 +574,11 @@ async def _mcp_endpoint(request) -> None:
"""
method = request.scope.get("method", "GET")
token = _extract_token_from_scope(request.scope)
+ # A cheap signature/expiry pre-filter, not the authorization boundary: this
+ # layer has no DB session, and the tool handlers below call back into this
+ # same API over HTTP with the very same JWT, where get_current_user enforces
+ # the account's token_version. A revoked token therefore gets past this line
+ # and is then refused by every call it tries to make.
user_id = decode_access_token(token) if token else None
if user_id is None:
from starlette.responses import JSONResponse
diff --git a/backend/app/services/apple_auth.py b/backend/app/services/apple_auth.py
deleted file mode 100644
index 7db2a3fe6090a35387f438023f8554741efef419..0000000000000000000000000000000000000000
--- a/backend/app/services/apple_auth.py
+++ /dev/null
@@ -1,168 +0,0 @@
-"""Verify "Sign in with Apple" identity tokens.
-
-Apple ships no server-side helper equivalent to Google's
-``id_token.verify_oauth2_token``, so we do it by hand: fetch Apple's public
-JWKS, pick the key named by the token header's ``kid``, and verify the RS256
-signature plus the issuer/audience/expiry claims.
-
-We verify the *identity token* the browser receives, rather than exchanging an
-authorization code. That mirrors how the Google path works here and means no
-Apple private key (and no client secret JWT) has to live in the deployment.
-"""
-from __future__ import annotations
-
-import threading
-import time
-from dataclasses import dataclass
-
-import jwt
-import requests
-from jwt import PyJWKSet
-
-from app.config import settings
-from app.observability.logging import get_logger
-
-logger = get_logger(__name__)
-
-APPLE_ISSUER = "https://appleid.apple.com"
-APPLE_JWKS_URL = "https://appleid.apple.com/auth/keys"
-
-# Apple's relay addresses for "Hide My Email". Such an address is a distinct
-# mailbox from the user's real one, so accepting it would create a second
-# account for the same human — which defeats our one-account-per-email rule.
-APPLE_PRIVATE_RELAY_DOMAIN = "@privaterelay.appleid.com"
-
-# Apple rotates signing keys, so the fetched set is cached only briefly.
-_JWKS_TTL_SECONDS = 6 * 60 * 60
-
-_jwks_lock = threading.Lock()
-_jwks_cache: PyJWKSet | None = None
-_jwks_fetched_at: float = 0.0
-
-# Fetched with `requests` rather than PyJWKClient: PyJWKClient uses urllib,
-# which relies on the host's OpenSSL CA store and fails with
-# CERTIFICATE_VERIFY_FAILED wherever that store isn't populated (macOS with a
-# python.org build, slim containers). `requests` ships certifi, so this works
-# the same everywhere.
-_JWKS_TIMEOUT_SECONDS = 10
-
-
-class AppleAuthError(ValueError):
- """Raised when an Apple identity token cannot be trusted."""
-
-
-@dataclass(frozen=True)
-class AppleIdentity:
- """The claims we care about from a verified Apple identity token."""
-
- apple_id: str # stable per-user id ("sub"); never reused
- email: str
- email_verified: bool
- is_private_email: bool
-
-
-def _get_jwks(force_refresh: bool = False) -> PyJWKSet:
- """Return Apple's signing-key set, refetching when stale or on demand."""
- global _jwks_cache, _jwks_fetched_at
- with _jwks_lock:
- expired = (time.time() - _jwks_fetched_at) > _JWKS_TTL_SECONDS
- if _jwks_cache is None or expired or force_refresh:
- resp = requests.get(APPLE_JWKS_URL, timeout=_JWKS_TIMEOUT_SECONDS)
- resp.raise_for_status()
- _jwks_cache = PyJWKSet.from_dict(resp.json())
- _jwks_fetched_at = time.time()
- return _jwks_cache
-
-
-def _signing_key_for(identity_token: str, force_refresh: bool = False):
- """Select the JWK named by the token header's ``kid``."""
- kid = jwt.get_unverified_header(identity_token).get("kid")
- if not kid:
- raise AppleAuthError("Apple token header has no key id")
- for key in _get_jwks(force_refresh).keys:
- if key.key_id == kid:
- return key
- raise KeyError(f"no Apple signing key for kid {kid!r}")
-
-
-def _claim_is_true(value: object) -> bool:
- """Apple sends these booleans as either real bools or the strings "true"/"false"."""
- return value is True or value == "true"
-
-
-def verify_apple_identity_token(identity_token: str) -> AppleIdentity:
- """Verify an Apple identity token and return its identity claims.
-
- Raises AppleAuthError on any failure — an unfetchable JWKS, an unknown key,
- a bad signature, a wrong issuer/audience, an expired token, or a missing
- email claim. Callers map this to a 401.
- """
- if not settings.APPLE_CLIENT_ID:
- # Misconfiguration, not a bad token; surface it distinctly in the logs.
- logger.error("[APPLE AUTH] APPLE_CLIENT_ID is not configured")
- raise AppleAuthError("Apple sign-in is not configured")
-
- # A key rotated in after our cache was built shows up as an unknown kid, so
- # retry exactly once against a freshly fetched JWKS before giving up.
- last_error: Exception | None = None
- signing_key = None
- for force_refresh in (False, True):
- try:
- signing_key = _signing_key_for(identity_token, force_refresh)
- break
- except (KeyError, jwt.PyJWKError, requests.RequestException, ValueError) as e:
- last_error = e
- if signing_key is None:
- logger.error("[APPLE AUTH] Could not resolve Apple signing key: %s", last_error)
- raise AppleAuthError(f"Could not verify Apple token: {last_error}")
-
- try:
- claims = jwt.decode(
- identity_token,
- signing_key.key,
- algorithms=["RS256"],
- audience=settings.APPLE_CLIENT_ID,
- issuer=APPLE_ISSUER,
- options={"require": ["exp", "iss", "aud", "sub"]},
- )
- except jwt.InvalidTokenError as e:
- logger.warning("[APPLE AUTH] Identity token rejected: %s", e)
- raise AppleAuthError(f"Invalid Apple token: {e}")
-
- apple_id = claims.get("sub")
- email = (claims.get("email") or "").strip().lower()
- if not apple_id:
- raise AppleAuthError("Apple token has no subject")
- if not email:
- # Happens when the user revoked email sharing; we cannot key an account.
- raise AppleAuthError("Email not provided by Apple")
-
- return AppleIdentity(
- apple_id=apple_id,
- email=email,
- email_verified=_claim_is_true(claims.get("email_verified")),
- is_private_email=(
- _claim_is_true(claims.get("is_private_email"))
- or email.endswith(APPLE_PRIVATE_RELAY_DOMAIN)
- ),
- )
-
-
-def full_name_from_apple_payload(payload: dict | None) -> str | None:
- """Build a display name from Apple's first-authorization ``user`` payload.
-
- Apple sends the user's name exactly once — on the first authorization, in a
- field alongside the token, never inside the token itself. The frontend
- forwards it when present; every later sign-in has nothing here.
- """
- if not isinstance(payload, dict):
- return None
- name = payload.get("name")
- if not isinstance(name, dict):
- return None
- parts = [
- str(name.get("firstName") or "").strip(),
- str(name.get("lastName") or "").strip(),
- ]
- full = " ".join(p for p in parts if p).strip()
- return full or None
diff --git a/backend/app/services/auth_identity.py b/backend/app/services/auth_identity.py
index 949187e36674e8d0a6391fb44bee2eca02c8198e..91d7e5dce6cda3348eeb8f3b4e7851b5e5da8b66 100644
--- a/backend/app/services/auth_identity.py
+++ b/backend/app/services/auth_identity.py
@@ -1,4 +1,4 @@
-"""Resolve a verified social identity to a Blog2Video user account.
+"""Resolve a verified identity to a Blog2Video user account.
This is the single enforcement point for our identity rules, shared by the web
login endpoints and the MCP OAuth bridge so the two can never disagree about
@@ -10,9 +10,25 @@ which accounts may exist:
3. The wrong-provider error outranks the soft-delete/reactivation prompt, so a
deleted account is told which provider reactivates it.
-Callers pass an already-verified identity; token verification lives in the
-provider-specific modules (google via the google-auth lib, apple via
-``app.services.apple_auth``).
+Two entry points apply those rules to two shapes of identity:
+
+- ``resolve_or_create_user`` — social providers, which supply an external subject
+ id. Callers pass an already-verified identity; token verification lives in the
+ provider-specific modules (google via the google-auth lib). Google is currently
+ the only one, but the path stays provider-agnostic: it is driven by
+ ``_PROVIDER_ID_COLUMN``, so adding one back is an entry there plus a column.
+- ``assert_email_available_for_password`` / ``resolve_password_user`` /
+ ``create_password_user`` — our built-in email+password provider, which has no
+ external subject id at all. They share ``wrong_provider_error``,
+ ``_lookup_by_email`` and ``_handle_soft_deleted`` with the social path, so
+ rules 1-3 hold identically across both.
+
+Password auth is deliberately a parallel path rather than an extra entry in
+``_PROVIDER_ID_COLUMN``: that map drives a lookup, a subject-id rebind and an
+insert kwarg, all three of which are meaningless without a subject id. Mapping
+EMAIL to None would need a guard at each site and would break the map's
+fail-loudly property. The split has a second benefit — the MCP OAuth bridge calls
+``resolve_or_create_user``, so password accounts structurally cannot reach it.
"""
from __future__ import annotations
@@ -28,16 +44,20 @@ from app.models.user import (
User,
)
from app.observability.logging import get_logger
+from app.services.password import verify_password_dummy
logger = get_logger(__name__)
-# The column holding each provider's stable user id. Adding a provider is an
-# entry here plus the matching column — the resolution rules below are
+# The column holding each provider's stable user id. Adding a SOCIAL provider is
+# an entry here plus the matching column — the resolution rules below are
# deliberately provider-agnostic.
+#
+# AuthProvider.EMAIL is intentionally absent: our built-in provider has no
+# external subject id (the credential is users.password_hash). Its absence is
+# load-bearing — _lookup_by_provider_id raising KeyError for EMAIL is what
+# guarantees the social path can never be entered with a password account.
_PROVIDER_ID_COLUMN: dict[AuthProvider, str] = {
AuthProvider.GOOGLE: "google_id",
- AuthProvider.APPLE: "apple_id",
- AuthProvider.MICROSOFT: "microsoft_id",
}
@@ -81,7 +101,6 @@ def resolve_or_create_user(
email: str,
name: str,
picture: str | None = None,
- refresh_name: bool = True,
reactivate: bool = False,
allow_reactivation: bool = True,
) -> tuple[User, bool]:
@@ -108,7 +127,7 @@ def resolve_or_create_user(
if existing:
if existing.auth_provider is not provider:
raise wrong_provider_error(existing)
- # Same provider, new subject id. Apple/Google subject ids are stable
+ # Same provider, new subject id. Google subject ids are stable
# and never reused, so this is a re-issue rather than a new person;
# adopt the new id instead of stranding the account.
logger.info(
@@ -131,11 +150,9 @@ def resolve_or_create_user(
if not created and not user.is_active:
_handle_soft_deleted(user, reactivate=reactivate, allow_reactivation=allow_reactivation)
elif not created:
- # Normal login: refresh profile fields from the provider. Apple sends a
- # name only on first authorization, so it passes refresh_name=False to
- # avoid clobbering the stored name with an email-derived placeholder.
- if refresh_name:
- user.name = name
+ # Normal login: refresh profile fields from the provider, which is
+ # authoritative for them and sends both on every sign-in.
+ user.name = name
user.picture = picture or user.picture
return user, created
@@ -182,6 +199,106 @@ def _create_user(
return user, True
+# ─── Built-in email + password provider ─────────────────────────────────────
+
+
+def assert_email_available_for_password(db: Session, email: str) -> User | None:
+ """Gate an email address for password signup/reset. Returns the existing row, if any.
+
+ Raises 409 ``wrong_auth_provider`` when the address belongs to a social
+ account. Callers MUST run this before hashing a password, before issuing a
+ one-time code, and before sending any email — so someone whose address is
+ already a Google account is told so immediately rather than after a pointless
+ round trip through their inbox.
+
+ Enumeration, deliberately: a 409 confirms both that the address is registered
+ and which provider owns it. That is the point — the login modal turns it into
+ a one-click switch to the right provider, and the alternative is a user who
+ cannot sign in and is told nothing about why. Do not "fix" this into a
+ generic error without replacing that recovery path. Where there is no such UX
+ payoff (a forgotten password for an address with no account at all) the
+ routers stay quiet instead; see routers/auth.py.
+
+ Returns None when the address is free, or the ``User`` when it is an existing
+ EMAIL account — the caller decides what that means, since it is
+ ``email_already_registered`` for signup but the normal case for a reset.
+ """
+ existing = _lookup_by_email(db, email.strip().lower())
+ if existing is not None and existing.auth_provider is not AuthProvider.EMAIL:
+ raise wrong_provider_error(existing)
+ return existing
+
+
+def resolve_password_user(db: Session, *, email: str) -> User:
+ """Return the EMAIL account for ``email``, or raise the login error.
+
+ Deliberately does NOT touch ``is_active``. A soft-deleted account must have
+ its password verified before ``_handle_soft_deleted`` reactivates it —
+ otherwise a wrong password plus ``?reactivate=true`` would resurrect someone
+ else's account on a request that then returns 401. The router owns that
+ ordering; see ``email_login``.
+
+ Raises:
+ 409 ``wrong_auth_provider`` — the address belongs to a social provider.
+ 401 ``invalid_credentials`` — no such account (body and timing identical to
+ a wrong password, so this is not an
+ account-existence oracle).
+ """
+ user = _lookup_by_email(db, email.strip().lower())
+ if user is None:
+ # Burn a verification's worth of time so "no such account" is not
+ # measurably faster than "wrong password".
+ verify_password_dummy()
+ raise HTTPException(status_code=401, detail="invalid_credentials")
+ if user.auth_provider is not AuthProvider.EMAIL:
+ raise wrong_provider_error(user)
+ return user
+
+
+def create_password_user(
+ db: Session, *, email: str, name: str, password_hash: str
+) -> tuple[User, bool]:
+ """Insert a verified email/password account, tolerating a concurrent signup.
+
+ Only ever called after a one-time code has proven mailbox control, which is
+ what lets a row appear in ``users`` at all — see
+ ``app/models/email_verification.py``.
+ """
+ email = email.strip().lower()
+ user = User(
+ email=email,
+ name=name,
+ picture=None,
+ auth_provider=AuthProvider.EMAIL,
+ password_hash=password_hash,
+ plan=PlanTier.FREE,
+ videos_used_this_period=0,
+ video_limit_bonus=0,
+ is_active=True,
+ )
+ db.add(user)
+ try:
+ db.flush()
+ except IntegrityError:
+ # Two signups raced on the unique email index. Mirror _create_user: roll
+ # back and re-resolve against the row the winner committed, so the loser
+ # gets the correct 409 instead of a raw 500.
+ db.rollback()
+ logger.info("[AUTH] Concurrent password signup for %s; re-resolving", email)
+ winner = _lookup_by_email(db, email)
+ if winner is None:
+ raise
+ if winner.auth_provider is not AuthProvider.EMAIL:
+ raise wrong_provider_error(winner)
+ # Do NOT adopt the winner's row: its password hash is a different secret
+ # from the one this request just verified, so logging this caller in
+ # would hand them an account whose password they may not know.
+ raise HTTPException(
+ status_code=409, detail={"code": "email_already_registered"}
+ )
+ return user, True
+
+
def _handle_soft_deleted(
user: User, *, reactivate: bool, allow_reactivation: bool
) -> None:
diff --git a/backend/app/services/email.py b/backend/app/services/email.py
index d7318de7871ea9eafae03650d85a26f519f751d0..87445fdc33a18784f8f65beda23dec5b3d4c1ed6 100644
--- a/backend/app/services/email.py
+++ b/backend/app/services/email.py
@@ -1030,6 +1030,123 @@ class EmailService:
from_email=getattr(settings, "NOREPLY_EMAIL", "noreply@blog2video.app"),
)
+ # ─── Email/password auth codes ───────────────────────────────────────────
+ # Both are TRANSACTIONAL: no unsubscribe link, and callers must NOT check
+ # user.email_unsubscribed. Someone who opted out of product emails must still
+ # be able to verify their address and reset their password — suppressing
+ # these would lock them out of their own account.
+
+ def _build_code_html(self, headline: str, body_paragraph: str, code: str) -> str:
+ """Branded shell with the code shown large and selectable.
+
+ Deliberately not _build_html: that renders a CTA button, and a one-time
+ code has nothing to link to — the user reads it and types it back.
+ """
+ from app.services.email_verification import CODE_TTL_SECONDS
+
+ minutes = CODE_TTL_SECONDS // 60
+ return f"""
+
+
+
+
+ {html.escape(headline)}
+
+
+
+
+
+
+
+
+
+ Blog2Video
+
+
+
+
+
+
{html.escape(headline)}
+
{body_paragraph}
+
+ {html.escape(code)}
+
+
+ This code expires in {minutes} minutes. If you didn't request it, you can safely ignore this email.
+
+
+
+
+
+
Team Blog2Video
+
+
+
+
+
+
+
+"""
+
+ def send_verification_code_email(self, to_email: str, code: str) -> None:
+ """Signup verification code — proves the user controls this mailbox."""
+ from app.services.email_verification import CODE_TTL_SECONDS
+
+ minutes = CODE_TTL_SECONDS // 60
+ subject = f"{code} is your Blog2Video verification code"
+ text_content = (
+ f"Your Blog2Video verification code is {code}\n\n"
+ f"Enter it to finish creating your account. "
+ f"This code expires in {minutes} minutes.\n\n"
+ f"If you didn't request it, you can safely ignore this email.\n\n"
+ f"Team Blog2Video\n"
+ )
+ html_content = self._build_code_html(
+ headline="Verify your email address",
+ body_paragraph=(
+ "Enter this code to finish creating your Blog2Video account."
+ ),
+ code=code,
+ )
+ self.provider.send_email(
+ to=to_email,
+ subject=subject,
+ html_content=html_content,
+ text_content=text_content,
+ from_email=getattr(settings, "NOREPLY_EMAIL", "noreply@blog2video.app"),
+ )
+
+ def send_password_reset_code_email(self, to_email: str, code: str) -> None:
+ """Password-reset code for an existing email/password account."""
+ from app.services.email_verification import CODE_TTL_SECONDS
+
+ minutes = CODE_TTL_SECONDS // 60
+ subject = f"{code} is your Blog2Video password reset code"
+ text_content = (
+ f"Your Blog2Video password reset code is {code}\n\n"
+ f"Enter it to choose a new password. "
+ f"This code expires in {minutes} minutes.\n\n"
+ f"If you didn't request a password reset, you can safely ignore this "
+ f"email — your password has not changed.\n\n"
+ f"Team Blog2Video\n"
+ )
+ html_content = self._build_code_html(
+ headline="Reset your password",
+ body_paragraph=(
+ "Enter this code to choose a new password. If you didn't request a "
+ "reset, your password has not changed."
+ ),
+ code=code,
+ )
+ self.provider.send_email(
+ to=to_email,
+ subject=subject,
+ html_content=html_content,
+ text_content=text_content,
+ from_email=getattr(settings, "NOREPLY_EMAIL", "noreply@blog2video.app"),
+ )
+
def send_collab_invite_email(
self, to_email: str, inviter_name: str, project_name: str, accept_link: str
) -> None:
diff --git a/backend/app/services/email_verification.py b/backend/app/services/email_verification.py
new file mode 100644
index 0000000000000000000000000000000000000000..9287ac7598881b4e0840da84a9cbca4d204b4a20
--- /dev/null
+++ b/backend/app/services/email_verification.py
@@ -0,0 +1,226 @@
+"""Issue and consume the one-time codes that gate email/password auth.
+
+Two rules here are deliberately stored in the database rather than in the
+in-process rate limiter (services/rate_limit.py): the 60-second resend cooldown
+and the 5-attempt burn. Those two MUST hold across workers and restarts — an
+attacker who can reset a counter by waiting for a redeploy has no attempt limit
+at all — whereas the per-IP limits are only a speed bump in front of Argon2.
+"""
+from __future__ import annotations
+
+import hashlib
+import hmac
+import secrets
+from datetime import datetime, timedelta
+
+from fastapi import HTTPException
+from sqlalchemy.orm import Session
+
+from app.models.email_verification import EmailVerificationCode, VerificationPurpose
+from app.observability.logging import get_logger
+
+logger = get_logger(__name__)
+
+CODE_LENGTH = 6
+CODE_TTL_SECONDS = 10 * 60
+MAX_CODE_ATTEMPTS = 5
+RESEND_COOLDOWN_SECONDS = 60
+
+# Rows older than this are dead weight; swept opportunistically on issue.
+_PURGE_AFTER = timedelta(days=1)
+
+
+def generate_code() -> str:
+ """A cryptographically random 6-digit code, zero-padded.
+
+ ``secrets``, not ``random`` — the latter's Mersenne Twister state is
+ recoverable from observed output. Returned as a STRING and kept one all the
+ way to the client: ``039123`` is a valid code and an int would eat the zero.
+ """
+ return f"{secrets.randbelow(10 ** CODE_LENGTH):0{CODE_LENGTH}d}"
+
+
+def hash_code(code: str) -> str:
+ """sha256 hex of a code. See the model docstring for why this isn't a KDF."""
+ return hashlib.sha256(code.encode("utf-8")).hexdigest()
+
+
+def _active_code(
+ db: Session, email: str, purpose: VerificationPurpose
+) -> EmailVerificationCode | None:
+ """The newest unused code for this (email, purpose), if any."""
+ return (
+ db.query(EmailVerificationCode)
+ .filter(
+ EmailVerificationCode.email == email,
+ EmailVerificationCode.purpose == purpose.value,
+ EmailVerificationCode.used.is_(False),
+ )
+ .order_by(EmailVerificationCode.created_at.desc(), EmailVerificationCode.id.desc())
+ .first()
+ )
+
+
+def purge_expired(db: Session) -> int:
+ """Delete long-dead code rows. Cheap and indexed; called on issue."""
+ cutoff = datetime.utcnow() - _PURGE_AFTER
+ deleted = (
+ db.query(EmailVerificationCode)
+ .filter(EmailVerificationCode.expires_at < cutoff)
+ .delete(synchronize_session=False)
+ )
+ return deleted or 0
+
+
+def issue_code(
+ db: Session,
+ *,
+ email: str,
+ purpose: VerificationPurpose,
+ pending_password_hash: str | None = None,
+ pending_name: str | None = None,
+) -> tuple[EmailVerificationCode, str]:
+ """Create a fresh code, returning ``(row, plaintext_code)`` for the caller to send.
+
+ Enforces the resend cooldown. Any previous code for this (email, purpose) is
+ deleted, so exactly one is live at a time and an old code stops working the
+ moment a new one is sent.
+
+ Raises 429 ``resend_too_soon`` (with ``Retry-After``) inside the cooldown.
+ The caller must commit — the code must be durable before the email goes out,
+ or a send that succeeds against a rolled-back row hands the user a dead code.
+ """
+ now = datetime.utcnow()
+ purge_expired(db)
+
+ existing = _active_code(db, email, purpose)
+ if existing is not None:
+ elapsed = (now - existing.last_sent_at).total_seconds()
+ if elapsed < RESEND_COOLDOWN_SECONDS:
+ retry_in = max(1, int(RESEND_COOLDOWN_SECONDS - elapsed))
+ raise HTTPException(
+ status_code=429,
+ detail="resend_too_soon",
+ headers={"Retry-After": str(retry_in)},
+ )
+
+ db.query(EmailVerificationCode).filter(
+ EmailVerificationCode.email == email,
+ EmailVerificationCode.purpose == purpose.value,
+ ).delete(synchronize_session=False)
+
+ code = generate_code()
+ row = EmailVerificationCode(
+ email=email,
+ purpose=purpose.value,
+ code_hash=hash_code(code),
+ pending_password_hash=pending_password_hash,
+ pending_name=pending_name,
+ attempts=0,
+ expires_at=now + timedelta(seconds=CODE_TTL_SECONDS),
+ used=False,
+ last_sent_at=now,
+ created_at=now,
+ )
+ db.add(row)
+ db.flush()
+ return row, code
+
+
+def consume_code(
+ db: Session, *, email: str, purpose: VerificationPurpose, code: str
+) -> EmailVerificationCode:
+ """Verify a code and mark it used, or raise.
+
+ Failure paths COMMIT the incremented attempt counter before raising. If they
+ didn't, the router's rollback on the HTTPException would undo the increment
+ and the 5-attempt cap would silently never trigger — the code could be
+ brute-forced at whatever rate the per-IP limiter allows.
+
+ Raises:
+ 400 ``code_invalid`` — no live code, or the wrong digits (with
+ ``attempts_remaining`` so the UI can warn).
+ 400 ``code_expired`` — past the 10-minute window.
+ 429 ``code_attempts_exceeded`` — 5th wrong try; the code is burned.
+ """
+ row = _active_code(db, email, purpose)
+ if row is None:
+ raise HTTPException(status_code=400, detail="code_invalid")
+
+ if row.expires_at <= datetime.utcnow():
+ db.delete(row)
+ db.commit()
+ raise HTTPException(status_code=400, detail="code_expired")
+
+ if not hmac.compare_digest(hash_code(code), row.code_hash):
+ row.attempts = (row.attempts or 0) + 1
+ if row.attempts >= MAX_CODE_ATTEMPTS:
+ # Burn it: a code that has survived five guesses has leaked enough
+ # signal that reissuing is the only safe move.
+ db.delete(row)
+ db.commit()
+ logger.info("[AUTH] Burned %s code for %s after %d attempts",
+ purpose.value, email, MAX_CODE_ATTEMPTS)
+ raise HTTPException(status_code=429, detail="code_attempts_exceeded")
+ remaining = MAX_CODE_ATTEMPTS - row.attempts
+ db.commit()
+ raise HTTPException(
+ status_code=400,
+ detail={"code": "code_invalid", "attempts_remaining": remaining},
+ )
+
+ row.used = True
+ db.flush()
+ return row
+
+
+def check_code(
+ db: Session, *, email: str, purpose: VerificationPurpose, code: str
+) -> None:
+ """Validate a code WITHOUT spending it. Raises exactly as consume_code does.
+
+ The reset flow needs this because the code authorizes the password change at
+ the very end — consuming it at the "enter your code" step would leave nothing
+ to submit the new password with. So this runs the same expiry / mismatch /
+ burn logic and leaves ``used`` alone, letting the UI reject a wrong code up
+ front while the real consumption still happens in forgot/complete.
+
+ The attempt counter IS incremented and committed on a mismatch, same as
+ consume_code — otherwise this endpoint would be a free, unlimited oracle for
+ brute-forcing the code that consume_code carefully rate-limits.
+ """
+ row = _active_code(db, email, purpose)
+ if row is None:
+ raise HTTPException(status_code=400, detail="code_invalid")
+
+ if row.expires_at <= datetime.utcnow():
+ db.delete(row)
+ db.commit()
+ raise HTTPException(status_code=400, detail="code_expired")
+
+ if not hmac.compare_digest(hash_code(code), row.code_hash):
+ row.attempts = (row.attempts or 0) + 1
+ if row.attempts >= MAX_CODE_ATTEMPTS:
+ db.delete(row)
+ db.commit()
+ logger.info("[AUTH] Burned %s code for %s after %d attempts",
+ purpose.value, email, MAX_CODE_ATTEMPTS)
+ raise HTTPException(status_code=429, detail="code_attempts_exceeded")
+ remaining = MAX_CODE_ATTEMPTS - row.attempts
+ db.commit()
+ raise HTTPException(
+ status_code=400,
+ detail={"code": "code_invalid", "attempts_remaining": remaining},
+ )
+ # Valid: deliberately no `used = True` — forgot/complete still consumes it.
+
+
+def clear_codes(db: Session, *, email: str) -> None:
+ """Drop every code for an email, whatever its purpose.
+
+ Called after a password reset: an in-flight signup code for the same address
+ must not remain replayable once the account's credential has changed.
+ """
+ db.query(EmailVerificationCode).filter(
+ EmailVerificationCode.email == email
+ ).delete(synchronize_session=False)
diff --git a/backend/app/services/mcp_provider.py b/backend/app/services/mcp_provider.py
index be3a75e1eb6857a4bab0dc102a3399d2382e4247..23e8e5a12df933e910e535964622b5a0309a6295 100644
--- a/backend/app/services/mcp_provider.py
+++ b/backend/app/services/mcp_provider.py
@@ -49,6 +49,18 @@ from app.models.mcp_oauth import MCPAuthCode, MCPClient
AUTH_CODE_TTL_SECONDS = 600 # 10 minutes
+def _token_version(db, user_id: int) -> int:
+ """The account's current revocation counter, or 0 if it has no row.
+
+ Read at issue time so the token carries the value it must still match to be
+ accepted; see app/auth.py::token_version_is_current.
+ """
+ from app.models.user import User
+
+ value = db.query(User.token_version).filter(User.id == user_id).scalar()
+ return int(value or 0)
+
+
class BlogVideoOAuthProvider(
OAuthAuthorizationServerProvider[AuthorizationCode, RefreshToken, AccessToken]
):
@@ -176,8 +188,9 @@ class BlogVideoOAuthProvider(
row.used = True
db.commit()
- access_token = create_access_token(row.user_id)
- refresh_token = create_refresh_token(row.user_id)
+ tv = _token_version(db, row.user_id)
+ access_token = create_access_token(row.user_id, tv)
+ refresh_token = create_refresh_token(row.user_id, tv)
return OAuthToken(
access_token=access_token,
token_type="Bearer",
@@ -215,8 +228,18 @@ class BlogVideoOAuthProvider(
if not payload or payload.get("typ") != "refresh":
raise ValueError("Invalid refresh token")
user_id = int(payload["sub"])
- new_access = create_access_token(user_id)
- new_refresh = create_refresh_token(user_id)
+ # A revoked refresh token must not mint a fresh pair, or revocation
+ # would be undone by the next refresh — the 30-day credential would
+ # quietly reissue itself past a password change.
+ db = SessionLocal()
+ try:
+ tv = _token_version(db, user_id)
+ finally:
+ db.close()
+ if int(payload.get("tv", 0)) != tv:
+ raise ValueError("Invalid refresh token")
+ new_access = create_access_token(user_id, tv)
+ new_refresh = create_refresh_token(user_id, tv)
return OAuthToken(
access_token=new_access,
token_type="Bearer",
diff --git a/backend/app/services/microsoft_auth.py b/backend/app/services/microsoft_auth.py
deleted file mode 100644
index e4c8251e80d2c19c11b3c97a6687be1d7991697e..0000000000000000000000000000000000000000
--- a/backend/app/services/microsoft_auth.py
+++ /dev/null
@@ -1,172 +0,0 @@
-"""Verify "Sign in with Microsoft" ID tokens (Microsoft Entra ID / Azure AD).
-
-Mirrors ``app.services.apple_auth``: fetch Microsoft's public JWKS, pick the key
-named by the token header's ``kid``, and verify the RS256 signature plus the
-audience, issuer and expiry claims.
-
-We verify the *ID token* the browser receives from MSAL, rather than exchanging
-an authorization code, so no client secret has to live in the deployment.
-"""
-from __future__ import annotations
-
-import threading
-import time
-from dataclasses import dataclass
-
-import jwt
-import requests
-from jwt import PyJWKSet
-
-from app.config import settings
-from app.observability.logging import get_logger
-
-logger = get_logger(__name__)
-
-# The "common" endpoint accepts both personal Microsoft accounts (outlook.com,
-# hotmail.com, live.com) and any organization's Microsoft 365 tenant.
-MICROSOFT_JWKS_URL = "https://login.microsoftonline.com/common/discovery/v2.0/keys"
-
-# Microsoft rotates signing keys, so the fetched set is cached only briefly.
-_JWKS_TTL_SECONDS = 6 * 60 * 60
-
-_jwks_lock = threading.Lock()
-_jwks_cache: PyJWKSet | None = None
-_jwks_fetched_at: float = 0.0
-
-# Fetched with `requests` rather than PyJWKClient: PyJWKClient uses urllib,
-# which relies on the host's OpenSSL CA store and fails with
-# CERTIFICATE_VERIFY_FAILED wherever that store isn't populated (macOS with a
-# python.org build, slim containers). `requests` ships certifi, so this works
-# the same everywhere.
-_JWKS_TIMEOUT_SECONDS = 10
-
-
-class MicrosoftAuthError(ValueError):
- """Raised when a Microsoft ID token cannot be trusted."""
-
-
-class MicrosoftNoEmailError(MicrosoftAuthError):
- """The token was valid but carried no usable email address.
-
- Distinct from the general error because it is a fixable account-settings
- problem rather than an untrusted token, so the router answers 400 (with
- specific UI copy) instead of 401.
- """
-
-
-@dataclass(frozen=True)
-class MicrosoftIdentity:
- """The claims we care about from a verified Microsoft ID token."""
-
- microsoft_id: str # stable per-user object id ("oid")
- email: str
- name: str | None
- tenant_id: str | None
-
-
-def _get_jwks(force_refresh: bool = False) -> PyJWKSet:
- """Return Microsoft's signing-key set, refetching when stale or on demand."""
- global _jwks_cache, _jwks_fetched_at
- with _jwks_lock:
- expired = (time.time() - _jwks_fetched_at) > _JWKS_TTL_SECONDS
- if _jwks_cache is None or expired or force_refresh:
- resp = requests.get(MICROSOFT_JWKS_URL, timeout=_JWKS_TIMEOUT_SECONDS)
- resp.raise_for_status()
- _jwks_cache = PyJWKSet.from_dict(resp.json())
- _jwks_fetched_at = time.time()
- return _jwks_cache
-
-
-def _signing_key_for(id_token: str, force_refresh: bool = False):
- """Select the JWK named by the token header's ``kid``."""
- kid = jwt.get_unverified_header(id_token).get("kid")
- if not kid:
- raise MicrosoftAuthError("Microsoft token header has no key id")
- for key in _get_jwks(force_refresh).keys:
- if key.key_id == kid:
- return key
- raise KeyError(f"no Microsoft signing key for kid {kid!r}")
-
-
-def _email_from_claims(claims: dict) -> str:
- """Pick the account's email address, or raise if there isn't a usable one.
-
- Without an email we cannot enforce one-account-per-email, so a token that
- carries none is rejected rather than being keyed on something else.
- ``preferred_username`` is the normal source for both personal and org
- accounts, but it is a UPN and is only trusted when actually email-shaped.
- """
- email = (claims.get("email") or "").strip().lower()
- if email:
- return email
-
- upn = (claims.get("preferred_username") or "").strip().lower()
- if "@" in upn:
- return upn
-
- raise MicrosoftNoEmailError("Email not provided by Microsoft")
-
-
-def verify_microsoft_id_token(id_token: str) -> MicrosoftIdentity:
- """Verify a Microsoft ID token and return its identity claims.
-
- Raises MicrosoftAuthError on any failure — an unfetchable JWKS, an unknown
- key, a bad signature, a wrong audience/issuer, an expired token, or a
- missing email claim. Callers map this to a 401.
- """
- if not settings.MICROSOFT_CLIENT_ID:
- # Misconfiguration, not a bad token; surface it distinctly in the logs.
- logger.error("[MICROSOFT AUTH] MICROSOFT_CLIENT_ID is not configured")
- raise MicrosoftAuthError("Microsoft sign-in is not configured")
-
- # A key rotated in after our cache was built shows up as an unknown kid, so
- # retry exactly once against a freshly fetched JWKS before giving up.
- last_error: Exception | None = None
- signing_key = None
- for force_refresh in (False, True):
- try:
- signing_key = _signing_key_for(id_token, force_refresh)
- break
- except (KeyError, jwt.PyJWKError, requests.RequestException, ValueError) as e:
- last_error = e
- if signing_key is None:
- logger.error("[MICROSOFT AUTH] Could not resolve signing key: %s", last_error)
- raise MicrosoftAuthError(f"Could not verify Microsoft token: {last_error}")
-
- try:
- claims = jwt.decode(
- id_token,
- signing_key.key,
- algorithms=["RS256"],
- audience=settings.MICROSOFT_CLIENT_ID,
- # The issuer is per-tenant under the "common" endpoint, so it cannot
- # be matched against one constant — it is checked against the
- # token's own `tid` below instead.
- options={"verify_iss": False, "require": ["exp", "iss", "aud"]},
- )
- except jwt.InvalidTokenError as e:
- logger.warning("[MICROSOFT AUTH] ID token rejected: %s", e)
- raise MicrosoftAuthError(f"Invalid Microsoft token: {e}")
-
- # Bind the issuer to the tenant that minted the token. Hard-coding a single
- # issuer would reject every organizational account; skipping the check would
- # accept a well-formed token from an unrelated tenant.
- tenant_id = claims.get("tid")
- issuer = claims.get("iss")
- if not tenant_id or issuer != f"https://login.microsoftonline.com/{tenant_id}/v2.0":
- logger.warning("[MICROSOFT AUTH] Issuer/tenant mismatch: iss=%r tid=%r", issuer, tenant_id)
- raise MicrosoftAuthError("Invalid Microsoft token issuer")
-
- # `oid` is the durable per-user object id. `sub` is pairwise per application
- # and changes if the app registration is recreated, which would strand every
- # existing account — so prefer `oid` and only fall back when it is absent.
- microsoft_id = claims.get("oid") or claims.get("sub")
- if not microsoft_id:
- raise MicrosoftAuthError("Microsoft token has no subject")
-
- return MicrosoftIdentity(
- microsoft_id=microsoft_id,
- email=_email_from_claims(claims),
- name=(claims.get("name") or "").strip() or None,
- tenant_id=tenant_id,
- )
diff --git a/backend/app/services/password.py b/backend/app/services/password.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0d97c7ebdece4453fd4cbe3b4f71d89cbd2efe4
--- /dev/null
+++ b/backend/app/services/password.py
@@ -0,0 +1,127 @@
+"""Password hashing and policy for built-in email/password sign-in.
+
+Argon2id via argon2-cffi. Chosen over bcrypt because bcrypt silently truncates
+its input at 72 bytes — ``"a" * 72 + "X"`` and ``"a" * 72 + "Y"`` are the same
+password to it — and the usual SHA-256 pre-hash workaround bakes an encoding
+decision into every stored hash that can never be changed afterwards. Argon2id
+has no input length limit and carries its parameters inside the encoded hash, so
+the cost can be raised later and existing hashes upgraded on next login via
+``needs_rehash``.
+
+Policy is a length minimum plus two composition rules (one capital, one special
+character). Note that composition rules are a product decision rather than a
+security win — NIST SP 800-63B advises against them, because they push users
+toward predictable substitutions ("Password1!") without adding much real entropy.
+Length is what actually helps, which is why the minimum stays and is checked
+first.
+"""
+from __future__ import annotations
+
+import re
+
+from fastapi import HTTPException
+
+from argon2 import PasswordHasher
+from argon2.exceptions import (
+ HashingError,
+ InvalidHashError,
+ VerificationError,
+ VerifyMismatchError,
+)
+
+MIN_PASSWORD_LENGTH = 8
+# Not a security limit — an upper bound on KDF input so a huge body can't be used
+# to burn CPU. We reject rather than truncate: silently ignoring the tail is the
+# exact bcrypt failure mode this module exists to avoid.
+MAX_PASSWORD_LENGTH = 256
+
+_UPPERCASE_RE = re.compile(r"[A-Z]")
+# Anything that is not a letter or digit counts, including spaces and non-ASCII
+# punctuation. Deliberately broad: the rule exists to widen the character space,
+# and a narrow allowlist would reject a non-English speaker's perfectly good
+# password for using the "wrong" symbol.
+_SPECIAL_RE = re.compile(r"[^A-Za-z0-9]")
+
+# Defaults are Argon2id with ~64 MiB per verify. That memory cost is per
+# concurrent verification, so if the API runs on a small instance lower it to the
+# OWASP 19 MiB profile (memory_cost=19456) rather than weakening time_cost.
+_hasher = PasswordHasher()
+
+# Precomputed hash of a value nobody can supply, used to equalize response time
+# when an email has no account at all. Without it, "no such user" returns
+# measurably faster than "wrong password" and the login endpoint becomes an
+# account-existence oracle. Module-level so the cost is paid once at import.
+_DUMMY_HASH = _hasher.hash("blog2video-nonexistent-account-timing-equalizer")
+
+
+def validate_password(password: str) -> None:
+ """Enforce the password policy, raising the API's error codes.
+
+ Authoritative: the frontend mirrors these rules for instant feedback, but the
+ browser is not a security boundary — anyone can POST straight to the API — so
+ every path that SETS a password calls this.
+
+ Critically, it is never called on the login path. The policy governs
+ passwords being set, never ones being used: re-validating at sign-in would
+ lock every existing user out of their own account the moment a rule is added.
+ ``verify_password`` must stay free of policy for exactly that reason.
+
+ Each failure has its own code so the UI can say precisely what is missing
+ rather than restating the whole policy.
+ """
+ if len(password) < MIN_PASSWORD_LENGTH:
+ raise HTTPException(status_code=422, detail="password_too_short")
+ if len(password) > MAX_PASSWORD_LENGTH:
+ raise HTTPException(status_code=422, detail="password_too_long")
+ if not _UPPERCASE_RE.search(password):
+ raise HTTPException(status_code=422, detail="password_needs_uppercase")
+ if not _SPECIAL_RE.search(password):
+ raise HTTPException(status_code=422, detail="password_needs_special")
+
+
+def hash_password(password: str) -> str:
+ """Return an Argon2id encoded hash (algorithm, params and salt included)."""
+ return _hasher.hash(password)
+
+
+def verify_password(password: str, password_hash: str | None) -> bool:
+ """Check a password against a stored hash, returning False rather than raising.
+
+ ``password_hash`` is None for every social account, which must read as "does
+ not match" — never as an error the caller might mishandle into a successful
+ login. A corrupt or unparseable hash is treated the same way. The dummy verify
+ on the None path keeps the timing indistinguishable from a real mismatch.
+ """
+ if not password_hash:
+ verify_password_dummy()
+ return False
+ try:
+ return _hasher.verify(password_hash, password)
+ except (VerifyMismatchError, InvalidHashError, VerificationError):
+ return False
+
+
+def verify_password_dummy() -> None:
+ """Burn one verification's worth of time against a throwaway hash.
+
+ Called on paths that reject before a real hash is available (no such account),
+ so response time doesn't reveal whether the email exists.
+ """
+ try:
+ _hasher.verify(_DUMMY_HASH, "")
+ except (VerifyMismatchError, InvalidHashError, VerificationError, HashingError):
+ pass
+
+
+def needs_rehash(password_hash: str | None) -> bool:
+ """True when a stored hash predates the current Argon2 parameters.
+
+ Callers re-hash on successful login, so raising the cost factor migrates
+ accounts as their owners sign in, with no bulk job and no forced reset.
+ """
+ if not password_hash:
+ return False
+ try:
+ return _hasher.check_needs_rehash(password_hash)
+ except InvalidHashError:
+ return False
diff --git a/backend/app/services/rate_limit.py b/backend/app/services/rate_limit.py
new file mode 100644
index 0000000000000000000000000000000000000000..0fcb0a16109b691c4aaa6ea3743031b2ce40f3b1
--- /dev/null
+++ b/backend/app/services/rate_limit.py
@@ -0,0 +1,164 @@
+"""In-process rate limiting for unauthenticated auth endpoints.
+
+Generalizes the per-IP lockout in routers/template_studio.py so login, signup and
+password-reset can share one implementation.
+
+SCOPE, stated plainly: this is per-process state. Under ``uvicorn --workers N``
+or several containers the effective allowance is N x the configured number, and a
+restart clears it entirely. That is acceptable for what it is — a speed bump in
+front of an Argon2 verification, where the KDF is the real cost bound — but it is
+NOT a control to point at in a compliance document, and it must never be the only
+thing enforcing a security-critical limit. The two limits that genuinely must
+hold across workers (the 60s resend cooldown and the 5-attempt code burn) live in
+the database instead; see services/email_verification.py. Swapping this for Redis
+later means reimplementing this class and nothing else.
+"""
+from __future__ import annotations
+
+import hashlib
+import time
+from dataclasses import dataclass
+from threading import Lock
+
+from fastapi import HTTPException, Request
+
+
+@dataclass(frozen=True)
+class RateLimitPolicy:
+ max_attempts: int
+ lockout_seconds: int
+ # Attempts stop counting toward the limit once this long has passed since the
+ # last one, so an occasional typo over a week never accumulates into a lockout.
+ window_seconds: int
+
+
+class InProcessRateLimiter:
+ """Failure-counting limiter with a fixed lockout. Not a token bucket.
+
+ Only failures are recorded, so a user typing their password correctly is
+ never throttled no matter how often they sign in.
+ """
+
+ def __init__(self, name: str, policy: RateLimitPolicy) -> None:
+ self.name = name
+ self.policy = policy
+ self._entries: dict[str, dict[str, float]] = {}
+ self._lock = Lock()
+
+ def check(self, key: str) -> None:
+ """Raise 429 if ``key`` is currently locked out."""
+ now = time.time()
+ with self._lock:
+ self._sweep(now)
+ entry = self._entries.get(key)
+ if entry and entry["locked_until"] > now:
+ retry_in = max(1, int(entry["locked_until"] - now))
+ raise HTTPException(
+ status_code=429,
+ detail="too_many_attempts",
+ headers={"Retry-After": str(retry_in)},
+ )
+
+ def record_failure(self, key: str) -> int:
+ """Count a failed attempt. Returns attempts remaining before lockout."""
+ now = time.time()
+ with self._lock:
+ entry = self._entries.get(key)
+ if entry is None or now - entry["last_seen"] > self.policy.window_seconds:
+ entry = {"count": 0.0, "locked_until": 0.0, "last_seen": now}
+ entry["count"] += 1
+ entry["last_seen"] = now
+ if entry["count"] >= self.policy.max_attempts:
+ entry["locked_until"] = now + self.policy.lockout_seconds
+ entry["count"] = 0.0
+ self._entries[key] = entry
+ return max(0, self.policy.max_attempts - int(entry["count"]))
+
+ def clear(self, key: str) -> None:
+ """Forget a key's failures — called on a successful authentication."""
+ with self._lock:
+ self._entries.pop(key, None)
+
+ def reset(self) -> None:
+ """Drop all state. For tests, which would otherwise bleed into each other."""
+ with self._lock:
+ self._entries.clear()
+
+ def _sweep(self, now: float) -> None:
+ """Drop entries that are neither locked nor inside their window.
+
+ The template-studio limiter this is modelled on leaks one dict entry per
+ IP forever; these endpoints face the open internet, so that is a slow
+ memory leak rather than a curiosity.
+ """
+ if len(self._entries) < 512:
+ return
+ stale = [
+ k
+ for k, e in self._entries.items()
+ if e["locked_until"] <= now
+ and now - e["last_seen"] > self.policy.window_seconds
+ ]
+ for k in stale:
+ self._entries.pop(k, None)
+
+
+def client_key(request: Request) -> str:
+ """Best-effort client identifier, preferring X-Forwarded-For behind a proxy."""
+ fwd = (request.headers.get("x-forwarded-for") or "").split(",")[0].strip()
+ if fwd:
+ return fwd
+ return request.client.host if request.client else "unknown"
+
+
+def email_key(email: str) -> str:
+ """Hashed key for per-account limiting.
+
+ Hashed so the limiter's state isn't a plaintext list of who has been trying
+ to sign in — it lives in memory, but it also reaches logs and crash dumps.
+ """
+ return hashlib.sha256(email.strip().lower().encode("utf-8")).hexdigest()
+
+
+_MINUTE = 60
+_HOUR = 60 * 60
+
+# Login is limited on BOTH axes on purpose: per-IP alone lets a botnet credential-
+# stuff a single account, per-email alone lets one host spray many accounts.
+login_ip_limiter = InProcessRateLimiter(
+ "login_ip", RateLimitPolicy(max_attempts=10, lockout_seconds=15 * _MINUTE, window_seconds=15 * _MINUTE)
+)
+login_email_limiter = InProcessRateLimiter(
+ "login_email", RateLimitPolicy(max_attempts=5, lockout_seconds=15 * _MINUTE, window_seconds=15 * _MINUTE)
+)
+register_limiter = InProcessRateLimiter(
+ "register", RateLimitPolicy(max_attempts=5, lockout_seconds=_HOUR, window_seconds=_HOUR)
+)
+resend_limiter = InProcessRateLimiter(
+ "resend", RateLimitPolicy(max_attempts=5, lockout_seconds=_HOUR, window_seconds=_HOUR)
+)
+verify_limiter = InProcessRateLimiter(
+ "verify", RateLimitPolicy(max_attempts=20, lockout_seconds=15 * _MINUTE, window_seconds=15 * _MINUTE)
+)
+forgot_ip_limiter = InProcessRateLimiter(
+ "forgot_ip", RateLimitPolicy(max_attempts=5, lockout_seconds=_HOUR, window_seconds=_HOUR)
+)
+forgot_email_limiter = InProcessRateLimiter(
+ "forgot_email", RateLimitPolicy(max_attempts=5, lockout_seconds=_HOUR, window_seconds=_HOUR)
+)
+
+ALL_LIMITERS = (
+ login_ip_limiter,
+ login_email_limiter,
+ register_limiter,
+ resend_limiter,
+ verify_limiter,
+ forgot_ip_limiter,
+ forgot_email_limiter,
+)
+
+
+def reset_all_limiters() -> None:
+ """Clear every limiter. Used by the test suite between cases."""
+ for limiter in ALL_LIMITERS:
+ limiter.reset()
diff --git a/backend/app/support/identity.py b/backend/app/support/identity.py
index ebf62f6941ae666810fcde117d1631335ac2199a..31ce632e1bc447d8a179598e7f9e6383e3267a9e 100644
--- a/backend/app/support/identity.py
+++ b/backend/app/support/identity.py
@@ -27,6 +27,15 @@ class SupportIdentity:
def _extract_jwt_user(request: Request) -> Optional[int]:
+ """Best-effort user id from the bearer token, or None for anonymous visitors.
+
+ Signature and expiry only — this helper has no DB session, so unlike
+ get_current_user it cannot check the account's token_version. A revoked
+ token can therefore still attribute a support-chat message to its user until
+ it expires. Accepted deliberately: this identity only labels conversations
+ and gates sending a message, never reads or mutates account data. Anything
+ that touches user data must depend on get_current_user instead.
+ """
auth = request.headers.get("authorization") or request.headers.get("Authorization")
if not auth:
return None
diff --git a/backend/requirements.txt b/backend/requirements.txt
index 54e56961b2751c63d6bc94461b706b44695bd16b..11d2f1504f89acb75c037a63e8532de1792dfa65 100644
--- a/backend/requirements.txt
+++ b/backend/requirements.txt
@@ -30,9 +30,16 @@ opentelemetry-instrumentation-logging>=0.45b0
# Auth & Billing
PyJWT>=2.8.0
-# Required by PyJWT to verify Apple's RS256 identity tokens (services/apple_auth.py).
+# Kept as an explicit pin rather than an implicit transitive of google-auth /
+# requests. Our own tokens are HS256 and need no asymmetric crypto, so nothing
+# here depends on it directly since Apple sign-in was removed.
cryptography>=42.0.0
google-auth>=2.29.0
+# Password hashing for built-in email/password sign-in (services/password.py).
+# Argon2id rather than bcrypt: bcrypt silently truncates input at 72 bytes, so two
+# different long passwords can collide, and the SHA-256 pre-hash workaround is a
+# format decision you can never reverse. Ships prebuilt wheels — no compiler needed.
+argon2-cffi>=23.1.0
stripe>=10.0.0
# PostgreSQL driver
diff --git a/backend/templates/newspaper/meta.json b/backend/templates/newspaper/meta.json
index 330fd1db2e70d199d4e217b8dac5d8238df47936..c5c38b9061f731deff3f4738511fe2e7fc300678 100644
--- a/backend/templates/newspaper/meta.json
+++ b/backend/templates/newspaper/meta.json
@@ -35,11 +35,11 @@
"label": "News Headline",
"defaults": {
"titleFontSize": {
- "portrait": 66,
+ "portrait": 68,
"landscape": 62
},
"descriptionFontSize": {
- "portrait": 35,
+ "portrait": 37,
"landscape": 28
},
"category": "News",
@@ -106,11 +106,11 @@
"label": "News Headline — Broadsheet",
"defaults": {
"titleFontSize": {
- "portrait": 54,
+ "portrait": 65,
"landscape": 54
},
"descriptionFontSize": {
- "portrait": 29,
+ "portrait": 32,
"landscape": 27
}
}
@@ -119,11 +119,11 @@
"label": "News Headline — Stacked Deck",
"defaults": {
"titleFontSize": {
- "portrait": 54,
+ "portrait": 66,
"landscape": 50
},
"descriptionFontSize": {
- "portrait": 31,
+ "portrait": 33,
"landscape": 26
}
}
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 2f03c4d50a472bd301d576260b264c07800f010f..88916aef3da0a0ce7a2129e6605297d44b6da48c 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -100,6 +100,8 @@ def kill_network(monkeypatch):
"send_custom_template_request_email",
"send_referral_invite_email",
"send_support_escalation_email",
+ "send_verification_code_email",
+ "send_password_reset_code_email",
):
monkeypatch.setattr(
email_module.EmailService, method,
diff --git a/backend/tests/test_auth_providers.py b/backend/tests/test_auth_providers.py
index 3c5e904498ea63b242b30a3c12015511582ff1a8..7f80a8c70c8bc8f756193efad81dff14e393e9f2 100644
--- a/backend/tests/test_auth_providers.py
+++ b/backend/tests/test_auth_providers.py
@@ -1,24 +1,26 @@
"""
-Depth tier — multi-provider identity rules (Google + Apple + Microsoft).
+Depth tier — multi-provider identity rules (Google + built-in email/password).
The invariant under test: one account per email, forever, bound for life to the
provider that created it. A second provider presenting a known email is always
rejected (409 wrong_auth_provider) — never linked, never duplicated — and that
rejection outranks the soft-delete/reactivation prompt.
+
+Apple and Microsoft sign-in were removed (see the drop_apple_microsoft_auth
+migration), so the cross-provider cases here run Google against our own
+email/password provider — the only pair that still exists. The rules themselves
+are provider-agnostic and live in services/auth_identity.py.
"""
import pytest
import app.routers.auth as auth_router
from app.models.user import AuthProvider, PlanTier, User
-from app.services.apple_auth import AppleAuthError, AppleIdentity
-from app.services.microsoft_auth import (
- MicrosoftAuthError,
- MicrosoftIdentity,
- MicrosoftNoEmailError,
-)
+from app.services.password import hash_password
pytestmark = pytest.mark.depth
+PASSWORD = "Correct-Horse-1"
+
# ─── Helpers ────────────────────────────────────────────────────────────────
@@ -30,54 +32,40 @@ def _mock_google(monkeypatch, *, sub, email, name="Google User"):
)
-def _mock_apple(monkeypatch, *, sub, email, private=False):
- monkeypatch.setattr(
- auth_router, "verify_apple_identity_token",
- lambda *a, **k: AppleIdentity(
- apple_id=sub, email=email, email_verified=True, is_private_email=private
- ),
- raising=True,
- )
-
-
-def _mock_microsoft(monkeypatch, *, oid, email, name="Microsoft User"):
- monkeypatch.setattr(
- auth_router, "verify_microsoft_id_token",
- lambda *a, **k: MicrosoftIdentity(
- microsoft_id=oid, email=email, name=name, tenant_id="tenant-1"
- ),
- raising=True,
- )
-
-
def _google_login(client, **params):
return client.post("/api/auth/google", json={"credential": "tok"}, params=params)
-def _apple_login(client, user=None, **params):
- body = {"identity_token": "tok"}
- if user is not None:
- body["user"] = user
- return client.post("/api/auth/apple", json=body, params=params)
+def _email_login(client, email, password=PASSWORD, **params):
+ return client.post(
+ "/api/auth/email/login", json={"email": email, "password": password}, params=params
+ )
-def _microsoft_login(client, **params):
- return client.post("/api/auth/microsoft", json={"id_token": "tok"}, params=params)
+def _email_register_start(client, email, password=PASSWORD):
+ return client.post(
+ "/api/auth/email/register/start", json={"email": email, "password": password}
+ )
# Mirrors auth_identity._PROVIDER_ID_COLUMN — kept explicit so a new provider
-# fails here loudly rather than silently writing the wrong column.
+# fails here loudly rather than silently writing the wrong column. EMAIL is
+# absent on purpose: it has no external subject id, its credential is
+# password_hash.
_ID_COLUMN = {
AuthProvider.GOOGLE: "google_id",
- AuthProvider.APPLE: "apple_id",
- AuthProvider.MICROSOFT: "microsoft_id",
}
-def _make_user(db, *, email, provider, sub, **kw):
+def _make_user(db, *, email, provider, sub=None, **kw):
+ ident = (
+ {_ID_COLUMN[provider]: sub}
+ if provider in _ID_COLUMN
+ else {"password_hash": hash_password(kw.pop("password", PASSWORD))}
+ )
user = User(
email=email, name="Existing", auth_provider=provider,
- plan=kw.pop("plan", PlanTier.FREE), **{_ID_COLUMN[provider]: sub}, **kw,
+ plan=kw.pop("plan", PlanTier.FREE), **ident, **kw,
)
db.add(user)
db.commit()
@@ -87,57 +75,41 @@ def _make_user(db, *, email, provider, sub, **kw):
# ─── Rule 3: an email never yields a second account ─────────────────────────
-def test_google_account__apple_login_same_email__409_and_no_new_account(
- client, db_session, monkeypatch
+def test_google_account__email_signup_same_email__409_and_no_new_account(
+ client, db_session
):
- existing = _make_user(
- db_session, email="dup@test.local", provider=AuthProvider.GOOGLE, sub="g-1"
- )
- _mock_apple(monkeypatch, sub="a-1", email="dup@test.local")
+ _make_user(db_session, email="taken@test.local", provider=AuthProvider.GOOGLE, sub="g-1")
- resp = _apple_login(client)
+ resp = _email_register_start(client, "taken@test.local")
assert resp.status_code == 409
detail = resp.json()["detail"]
assert detail["code"] == "wrong_auth_provider"
assert detail["provider"] == "google"
assert detail["provider_label"] == "Google"
- assert detail["deleted"] is False
-
- # No second account, and the existing row is untouched.
- assert db_session.query(User).filter_by(email="dup@test.local").count() == 1
- db_session.refresh(existing)
- assert existing.google_id == "g-1"
- assert existing.apple_id is None
- assert existing.auth_provider is AuthProvider.GOOGLE
+ assert db_session.query(User).count() == 1
-def test_apple_account__google_login_same_email__409(client, db_session, monkeypatch):
- existing = _make_user(
- db_session, email="dup2@test.local", provider=AuthProvider.APPLE, sub="a-2"
- )
- _mock_google(monkeypatch, sub="g-2", email="dup2@test.local")
+def test_email_account__google_login_same_email__409(client, db_session, monkeypatch):
+ """The mirror image: a password account is not signed into with Google."""
+ _make_user(db_session, email="mine@test.local", provider=AuthProvider.EMAIL)
+ _mock_google(monkeypatch, sub="g-2", email="mine@test.local")
resp = _google_login(client)
assert resp.status_code == 409
detail = resp.json()["detail"]
- assert detail["provider"] == "apple"
- assert detail["provider_label"] == "Apple"
-
- # The pre-existing bug this guards: google_id must NOT be overwritten.
- db_session.refresh(existing)
- assert existing.google_id is None
- assert existing.apple_id == "a-2"
- assert db_session.query(User).filter_by(email="dup2@test.local").count() == 1
+ assert detail["provider"] == "email"
+ assert detail["provider_label"] == "Email"
+ assert db_session.query(User).count() == 1
def test_email_match_is_case_insensitive(client, db_session, monkeypatch):
"""A mixed-case legacy row must still be found, or it would be duplicated."""
- _make_user(db_session, email="MiXeD@test.local", provider=AuthProvider.GOOGLE, sub="g-3")
- _mock_apple(monkeypatch, sub="a-3", email="mixed@test.local")
+ _make_user(db_session, email="MiXeD@test.local", provider=AuthProvider.EMAIL)
+ _mock_google(monkeypatch, sub="g-3", email="mixed@test.local")
- resp = _apple_login(client)
+ resp = _google_login(client)
assert resp.status_code == 409
assert db_session.query(User).count() == 1
@@ -145,21 +117,20 @@ def test_email_match_is_case_insensitive(client, db_session, monkeypatch):
# ─── Rule 2: deleted account + wrong provider ───────────────────────────────
-def test_deleted_google_account__apple_login__409_with_deleted_flag(
- client, db_session, monkeypatch
+def test_deleted_google_account__email_signup__409_with_deleted_flag(
+ client, db_session
):
- """Wrong-provider outranks account_deleted, and says so via deleted=True."""
+ """Wrong-provider outranks the deletion prompt, and says so — otherwise the
+ user is offered a reactivation they cannot complete on this provider."""
_make_user(
db_session, email="gone@test.local", provider=AuthProvider.GOOGLE,
- sub="g-4", is_active=False,
+ sub="g-gone", is_active=False,
)
- _mock_apple(monkeypatch, sub="a-4", email="gone@test.local")
- resp = _apple_login(client)
+ resp = _email_register_start(client, "gone@test.local")
- assert resp.status_code == 409 # NOT 403 account_deleted
+ assert resp.status_code == 409
detail = resp.json()["detail"]
- assert detail["code"] == "wrong_auth_provider"
assert detail["provider"] == "google"
assert detail["deleted"] is True
@@ -167,89 +138,34 @@ def test_deleted_google_account__apple_login__409_with_deleted_flag(
def test_deleted_google_account__google_login__still_403_account_deleted(
client, db_session, monkeypatch
):
- """The correct provider keeps the existing reactivation flow."""
_make_user(
- db_session, email="gone2@test.local", provider=AuthProvider.GOOGLE,
- sub="g-5", is_active=False,
+ db_session, email="back@test.local", provider=AuthProvider.GOOGLE,
+ sub="g-back", is_active=False,
)
- _mock_google(monkeypatch, sub="g-5", email="gone2@test.local")
+ _mock_google(monkeypatch, sub="g-back", email="back@test.local")
- assert _google_login(client).status_code == 403
- assert _google_login(client).json()["detail"] == "account_deleted"
+ resp = _google_login(client)
- resp = _google_login(client, reactivate="true")
- assert resp.status_code == 200
- assert resp.json()["user"]["auth_provider"] == "google"
+ assert resp.status_code == 403
+ assert resp.json()["detail"] == "account_deleted"
-def test_deleted_apple_account__apple_login_reactivates(client, db_session, monkeypatch):
+def test_deleted_google_account__google_login_reactivates(
+ client, db_session, monkeypatch
+):
user = _make_user(
- db_session, email="gone3@test.local", provider=AuthProvider.APPLE,
- sub="a-5", is_active=False, plan=PlanTier.PRO,
+ db_session, email="revive@test.local", provider=AuthProvider.GOOGLE,
+ sub="g-revive", is_active=False, plan=PlanTier.PRO,
)
- _mock_apple(monkeypatch, sub="a-5", email="gone3@test.local")
+ _mock_google(monkeypatch, sub="g-revive", email="revive@test.local")
- assert _apple_login(client).status_code == 403
- resp = _apple_login(client, reactivate="true")
+ resp = _google_login(client, reactivate=True)
assert resp.status_code == 200
db_session.refresh(user)
assert user.is_active is True
- assert user.plan == PlanTier.FREE
-
-
-# ─── Apple sign-up specifics ────────────────────────────────────────────────
-
-def test_apple_signup__creates_apple_bound_account(client, db_session, monkeypatch):
- _mock_apple(monkeypatch, sub="a-new", email="fresh@test.local")
-
- resp = _apple_login(client, user={"name": {"firstName": "Ada", "lastName": "Lovelace"}})
-
- assert resp.status_code == 200
- assert resp.json()["user"]["auth_provider"] == "apple"
- user = db_session.query(User).filter_by(email="fresh@test.local").one()
- assert user.auth_provider is AuthProvider.APPLE
- assert user.apple_id == "a-new"
- assert user.google_id is None
- assert user.name == "Ada Lovelace"
-
-
-def test_apple_relogin__does_not_clobber_name_with_email_stub(
- client, db_session, monkeypatch
-):
- """Apple sends the name only on first authorization; later logins must not
- overwrite it with the email-derived placeholder."""
- _mock_apple(monkeypatch, sub="a-name", email="ada@test.local")
- _apple_login(client, user={"name": {"firstName": "Ada", "lastName": "Lovelace"}})
-
- _apple_login(client) # second sign-in: no user payload
-
- user = db_session.query(User).filter_by(email="ada@test.local").one()
- assert user.name == "Ada Lovelace"
-
-
-def test_apple_private_relay_email__rejected_and_no_account(
- client, db_session, monkeypatch
-):
- _mock_apple(
- monkeypatch, sub="a-priv",
- email="abc123@privaterelay.appleid.com", private=True,
- )
-
- resp = _apple_login(client)
-
- assert resp.status_code == 400
- assert resp.json()["detail"] == "apple_private_email"
- assert db_session.query(User).count() == 0
-
-
-def test_apple_invalid_token__401(client, monkeypatch):
- def _boom(*a, **k):
- raise AppleAuthError("Invalid Apple token: signature mismatch")
-
- monkeypatch.setattr(auth_router, "verify_apple_identity_token", _boom, raising=True)
-
- assert _apple_login(client).status_code == 401
+ # Reactivation is always as a FREE user.
+ assert user.plan is PlanTier.FREE
# ─── Google regression: nothing about the existing flow changed ─────────────
@@ -265,7 +181,7 @@ def test_google_signup__still_works_and_reports_provider(client, db_session, mon
assert body["user"]["auth_provider"] == "google"
user = db_session.query(User).filter_by(email="newgoogle@test.local").one()
assert user.google_id == "g-new"
- assert user.apple_id is None
+ assert user.password_hash is None
assert user.auth_provider is AuthProvider.GOOGLE
@@ -280,6 +196,22 @@ def test_google_relogin__same_account_no_duplicate(client, db_session, monkeypat
assert db_session.query(User).filter_by(email="repeat@test.local").count() == 1
+def test_google_relogin__refreshes_name_from_the_provider(
+ client, db_session, monkeypatch
+):
+ """Google sends name and picture on every sign-in and is authoritative for
+ them, so a changed profile name lands on the row."""
+ user = _make_user(
+ db_session, email="renamed@test.local", provider=AuthProvider.GOOGLE, sub="g-rename"
+ )
+ _mock_google(monkeypatch, sub="g-rename", email="renamed@test.local", name="New Name")
+
+ assert _google_login(client).status_code == 200
+
+ db_session.refresh(user)
+ assert user.name == "New Name"
+
+
def test_same_provider_new_subject_id__rebinds_instead_of_duplicating(
client, db_session, monkeypatch
):
@@ -297,6 +229,24 @@ def test_same_provider_new_subject_id__rebinds_instead_of_duplicating(
assert db_session.query(User).filter_by(email="reissue@test.local").count() == 1
+# ─── Removed providers ──────────────────────────────────────────────────────
+
+@pytest.mark.parametrize("path", ["/api/auth/apple", "/api/auth/microsoft"])
+def test_removed_provider_routes_are_gone(client, path):
+ """Apple and Microsoft sign-in were removed; their routes must not linger."""
+ resp = client.post(path, json={"identity_token": "tok", "id_token": "tok"})
+
+ assert resp.status_code == 404
+
+
+@pytest.mark.parametrize("value", ["apple", "microsoft"])
+def test_removed_providers_are_not_valid_auth_provider_values(value):
+ """The enum coerces on load, so a legacy row fails loudly rather than
+ silently degrading to a bare string."""
+ with pytest.raises(ValueError):
+ AuthProvider(value)
+
+
# ─── Concurrency ────────────────────────────────────────────────────────────
def test_concurrent_signup_race__resolves_instead_of_500(
@@ -331,235 +281,3 @@ def test_concurrent_signup_race__resolves_instead_of_500(
assert resp.status_code == 200
assert db_session.query(User).filter_by(email="race@test.local").count() == 1
-
-
-# ─── Microsoft ──────────────────────────────────────────────────────────────
-
-def test_microsoft_signup__creates_microsoft_bound_account(
- client, db_session, monkeypatch
-):
- _mock_microsoft(monkeypatch, oid="ms-new", email="new@outlook.com", name="Grace H")
-
- resp = _microsoft_login(client)
-
- assert resp.status_code == 200
- assert resp.json()["user"]["auth_provider"] == "microsoft"
- user = db_session.query(User).filter_by(email="new@outlook.com").one()
- assert user.auth_provider is AuthProvider.MICROSOFT
- assert user.microsoft_id == "ms-new"
- assert user.google_id is None
- assert user.apple_id is None
- assert user.name == "Grace H"
-
-
-def test_google_account__microsoft_login_same_email__409_and_no_new_account(
- client, db_session, monkeypatch
-):
- existing = _make_user(
- db_session, email="dup-ms@test.local", provider=AuthProvider.GOOGLE, sub="g-ms"
- )
- _mock_microsoft(monkeypatch, oid="ms-1", email="dup-ms@test.local")
-
- resp = _microsoft_login(client)
-
- assert resp.status_code == 409
- detail = resp.json()["detail"]
- assert detail["code"] == "wrong_auth_provider"
- assert detail["provider"] == "google"
- assert detail["provider_label"] == "Google"
- assert detail["deleted"] is False
-
- assert db_session.query(User).filter_by(email="dup-ms@test.local").count() == 1
- db_session.refresh(existing)
- assert existing.google_id == "g-ms"
- assert existing.microsoft_id is None
-
-
-def test_microsoft_account__google_login_same_email__409_labels_microsoft(
- client, db_session, monkeypatch
-):
- """Guards the AuthProvider.label mapping.
-
- A two-way ternary would mislabel Microsoft as "Apple" here, telling the user
- to sign in with a provider that does not own their account.
- """
- existing = _make_user(
- db_session, email="ms-owner@test.local", provider=AuthProvider.MICROSOFT, sub="ms-2"
- )
- _mock_google(monkeypatch, sub="g-2b", email="ms-owner@test.local")
-
- resp = _google_login(client)
-
- assert resp.status_code == 409
- detail = resp.json()["detail"]
- assert detail["provider"] == "microsoft"
- assert detail["provider_label"] == "Microsoft"
-
- db_session.refresh(existing)
- assert existing.google_id is None
- assert existing.microsoft_id == "ms-2"
-
-
-def test_microsoft_and_apple__reject_each_other(client, db_session, monkeypatch):
- _make_user(
- db_session, email="cross@test.local", provider=AuthProvider.APPLE, sub="a-x"
- )
- _mock_microsoft(monkeypatch, oid="ms-x", email="cross@test.local")
- resp = _microsoft_login(client)
- assert resp.status_code == 409
- assert resp.json()["detail"]["provider_label"] == "Apple"
-
- _make_user(
- db_session, email="cross2@test.local", provider=AuthProvider.MICROSOFT, sub="ms-y"
- )
- _mock_apple(monkeypatch, sub="a-y", email="cross2@test.local")
- resp = _apple_login(client)
- assert resp.status_code == 409
- assert resp.json()["detail"]["provider_label"] == "Microsoft"
-
-
-def test_deleted_google_account__microsoft_login__409_with_deleted_flag(
- client, db_session, monkeypatch
-):
- """Wrong-provider outranks account_deleted, for the new provider too."""
- _make_user(
- db_session, email="gone-ms@test.local", provider=AuthProvider.GOOGLE,
- sub="g-gone-ms", is_active=False,
- )
- _mock_microsoft(monkeypatch, oid="ms-gone", email="gone-ms@test.local")
-
- resp = _microsoft_login(client)
-
- assert resp.status_code == 409 # NOT 403 account_deleted
- detail = resp.json()["detail"]
- assert detail["provider"] == "google"
- assert detail["deleted"] is True
-
-
-def test_deleted_microsoft_account__microsoft_login_reactivates(
- client, db_session, monkeypatch
-):
- user = _make_user(
- db_session, email="ms-dead@test.local", provider=AuthProvider.MICROSOFT,
- sub="ms-dead", is_active=False, plan=PlanTier.PRO,
- )
- _mock_microsoft(monkeypatch, oid="ms-dead", email="ms-dead@test.local")
-
- assert _microsoft_login(client).status_code == 403
- resp = _microsoft_login(client, reactivate="true")
-
- assert resp.status_code == 200
- db_session.refresh(user)
- assert user.is_active is True
- assert user.plan == PlanTier.FREE
-
-
-def test_microsoft_relogin__same_account_no_duplicate(client, db_session, monkeypatch):
- _mock_microsoft(monkeypatch, oid="ms-rep", email="repeat-ms@test.local")
-
- first = _microsoft_login(client)
- second = _microsoft_login(client)
-
- assert first.status_code == second.status_code == 200
- assert first.json()["user"]["id"] == second.json()["user"]["id"]
- assert db_session.query(User).filter_by(email="repeat-ms@test.local").count() == 1
-
-
-def test_microsoft_no_email__400_and_no_account(client, db_session, monkeypatch):
- def _boom(*a, **k):
- raise MicrosoftNoEmailError("Email not provided by Microsoft")
-
- monkeypatch.setattr(auth_router, "verify_microsoft_id_token", _boom, raising=True)
-
- resp = _microsoft_login(client)
-
- assert resp.status_code == 400
- assert resp.json()["detail"] == "microsoft_no_email"
- assert db_session.query(User).count() == 0
-
-
-def test_microsoft_invalid_token__401(client, monkeypatch):
- def _boom(*a, **k):
- raise MicrosoftAuthError("Invalid Microsoft token: signature mismatch")
-
- monkeypatch.setattr(auth_router, "verify_microsoft_id_token", _boom, raising=True)
-
- assert _microsoft_login(client).status_code == 401
-
-
-# ─── Microsoft token verification (claim handling) ──────────────────────────
-# These exercise microsoft_auth directly rather than through the router, since
-# the router tests mock verification out.
-
-def _ms_claims(**over):
- base = {
- "oid": "oid-1", "sub": "sub-1", "tid": "tenant-1",
- "iss": "https://login.microsoftonline.com/tenant-1/v2.0",
- "aud": "test-client", "exp": 9999999999,
- "email": "person@outlook.com", "name": "A Person",
- }
- base.update(over)
- return base
-
-
-def _verify_with(monkeypatch, claims, client_id="test-client"):
- """Drive verify_microsoft_id_token with decode/JWKS stubbed out."""
- import app.services.microsoft_auth as ms
- from app.config import settings
-
- monkeypatch.setattr(settings, "MICROSOFT_CLIENT_ID", client_id, raising=False)
- monkeypatch.setattr(ms, "_signing_key_for", lambda *a, **k: type("K", (), {"key": "k"})(), raising=True)
- monkeypatch.setattr(ms.jwt, "decode", lambda *a, **k: claims, raising=True)
- return ms.verify_microsoft_id_token("tok")
-
-
-def test_verify__prefers_oid_over_sub(monkeypatch):
- identity = _verify_with(monkeypatch, _ms_claims())
- # `sub` is pairwise per-app and changes if the registration is recreated.
- assert identity.microsoft_id == "oid-1"
-
-
-def test_verify__falls_back_to_sub_when_oid_absent(monkeypatch):
- claims = _ms_claims()
- del claims["oid"]
- assert _verify_with(monkeypatch, claims).microsoft_id == "sub-1"
-
-
-def test_verify__issuer_must_match_token_tenant(monkeypatch):
- # Well-formed token from an unrelated tenant: iss and tid disagree.
- claims = _ms_claims(iss="https://login.microsoftonline.com/other-tenant/v2.0")
- with pytest.raises(MicrosoftAuthError, match="issuer"):
- _verify_with(monkeypatch, claims)
-
-
-def test_verify__org_tenant_issuer_accepted(monkeypatch):
- # Any tenant is fine as long as iss matches that tenant — this is what
- # makes work/school accounts work under the "common" endpoint.
- claims = _ms_claims(tid="contoso", iss="https://login.microsoftonline.com/contoso/v2.0")
- assert _verify_with(monkeypatch, claims).tenant_id == "contoso"
-
-
-def test_verify__uses_preferred_username_when_email_missing(monkeypatch):
- claims = _ms_claims(preferred_username="Work.User@contoso.com")
- del claims["email"]
- assert _verify_with(monkeypatch, claims).email == "work.user@contoso.com"
-
-
-def test_verify__rejects_non_email_upn(monkeypatch):
- # A UPN that isn't email-shaped is not a deliverable address.
- claims = _ms_claims(preferred_username="DOMAIN\\user")
- del claims["email"]
- with pytest.raises(MicrosoftNoEmailError):
- _verify_with(monkeypatch, claims)
-
-
-def test_verify__rejects_when_no_email_claims_at_all(monkeypatch):
- claims = _ms_claims()
- del claims["email"]
- with pytest.raises(MicrosoftNoEmailError):
- _verify_with(monkeypatch, claims)
-
-
-def test_verify__unconfigured_client_id_fails_closed(monkeypatch):
- with pytest.raises(MicrosoftAuthError, match="not configured"):
- _verify_with(monkeypatch, _ms_claims(), client_id="")
diff --git a/backend/tests/test_email_password_auth.py b/backend/tests/test_email_password_auth.py
new file mode 100644
index 0000000000000000000000000000000000000000..2673d7bda77606b44f1e9801b15b20b260534a2c
--- /dev/null
+++ b/backend/tests/test_email_password_auth.py
@@ -0,0 +1,714 @@
+"""
+Depth tier — built-in email/password auth.
+
+Two invariants carry most of the weight here:
+
+1. One account per email, across ALL four providers. A social-owned address is
+ rejected before a password is accepted, before a code is issued, and before
+ any mail is sent — a user whose address is a Google account learns that
+ immediately rather than after a round trip through their inbox.
+2. A row in ``users`` always means a real, verified account. A pending signup
+ lives on a code row, never as an inactive user, so an abandoned registration
+ can neither squat the unique email nor masquerade as a deleted account.
+"""
+from datetime import datetime, timedelta
+
+import pytest
+
+import app.routers.auth as auth_router
+from app.models.email_verification import EmailVerificationCode, VerificationPurpose
+from app.models.user import AuthProvider, PlanTier, User
+from app.services import rate_limit
+from app.services.password import hash_password
+
+pytestmark = pytest.mark.depth
+
+CODE = "123456"
+PASSWORD = "Correct-Horse-1"
+
+
+# ─── Fixtures & helpers ─────────────────────────────────────────────────────
+
+@pytest.fixture(autouse=True)
+def _fixed_code(monkeypatch):
+ """Pin the generated code and clear limiter state between tests.
+
+ The limiters are module-level singletons, so without the reset a test that
+ trips a lockout silently breaks every later test sharing its key.
+ """
+ monkeypatch.setattr(
+ auth_router.verification, "generate_code", lambda: CODE, raising=True
+ )
+ rate_limit.reset_all_limiters()
+ yield
+ rate_limit.reset_all_limiters()
+
+
+@pytest.fixture()
+def sent(monkeypatch):
+ """Capture outgoing codes: list of (kind, email, code)."""
+ out: list[tuple[str, str, str]] = []
+ monkeypatch.setattr(
+ auth_router.email_service, "send_verification_code_email",
+ lambda to, code: out.append(("signup", to, code)), raising=True,
+ )
+ monkeypatch.setattr(
+ auth_router.email_service, "send_password_reset_code_email",
+ lambda to, code: out.append(("reset", to, code)), raising=True,
+ )
+ return out
+
+
+def _start(client, email, password=PASSWORD, **body):
+ return client.post(
+ "/api/auth/email/register/start",
+ json={"email": email, "password": password, **body},
+ )
+
+
+def _verify(client, email, code=CODE, **params):
+ return client.post(
+ "/api/auth/email/register/verify", json={"email": email, "code": code}, params=params
+ )
+
+
+def _login(client, email, password=PASSWORD, **params):
+ return client.post(
+ "/api/auth/email/login", json={"email": email, "password": password}, params=params
+ )
+
+
+def _forgot_start(client, email, **params):
+ return client.post(
+ "/api/auth/password/forgot/start", json={"email": email}, params=params
+ )
+
+
+def _forgot_complete(client, email, new_password, code=CODE):
+ return client.post(
+ "/api/auth/password/forgot/complete",
+ json={"email": email, "code": code, "new_password": new_password},
+ )
+
+
+def _register(client, email, password=PASSWORD):
+ """Complete a full signup, returning the auth response body."""
+ assert _start(client, email, password).status_code == 200
+ res = _verify(client, email)
+ assert res.status_code == 200, res.text
+ return res.json()
+
+
+def _make_social(db, *, email, provider, **kw):
+ column = {AuthProvider.GOOGLE: "google_id"}[provider]
+ user = User(
+ email=email, name="Existing", auth_provider=provider,
+ plan=kw.pop("plan", PlanTier.FREE), is_active=kw.pop("is_active", True),
+ **{column: f"{provider.value}-sub"}, **kw,
+ )
+ db.add(user)
+ db.commit()
+ db.refresh(user)
+ return user
+
+
+def _make_email_user(db, *, email, password=PASSWORD, **kw):
+ user = User(
+ email=email, name="Email User", auth_provider=AuthProvider.EMAIL,
+ password_hash=hash_password(password),
+ plan=kw.pop("plan", PlanTier.FREE), is_active=kw.pop("is_active", True), **kw,
+ )
+ db.add(user)
+ db.commit()
+ db.refresh(user)
+ return user
+
+
+def _codes(db, email=None, purpose=None):
+ q = db.query(EmailVerificationCode)
+ if email:
+ q = q.filter(EmailVerificationCode.email == email)
+ if purpose:
+ q = q.filter(EmailVerificationCode.purpose == purpose.value)
+ return q.all()
+
+
+# ─── One account per email, across providers ────────────────────────────────
+
+@pytest.mark.parametrize("provider", [AuthProvider.GOOGLE])
+def test_register_rejects_socially_owned_email_before_issuing_any_code(
+ client, db_session, sent, provider
+):
+ """The core guarantee: 409 lands with nothing issued and nothing sent."""
+ _make_social(db_session, email="taken@test.local", provider=provider)
+
+ res = _start(client, "taken@test.local")
+
+ assert res.status_code == 409
+ detail = res.json()["detail"]
+ assert detail["code"] == "wrong_auth_provider"
+ assert detail["provider"] == provider.value
+ assert sent == []
+ assert _codes(db_session, "taken@test.local") == []
+
+
+def test_register_start_does_not_hash_into_users_table(client, db_session, sent):
+ """No user row exists between start and verify — Decision B's invariant."""
+ assert _start(client, "pending@test.local").status_code == 200
+
+ assert db_session.query(User).filter_by(email="pending@test.local").first() is None
+ codes = _codes(db_session, "pending@test.local", VerificationPurpose.SIGNUP)
+ assert len(codes) == 1
+ # The password is present but hashed, and the code is not stored in the clear.
+ assert codes[0].pending_password_hash.startswith("$argon2")
+ assert codes[0].code_hash != CODE
+ assert sent == [("signup", "pending@test.local", CODE)]
+
+
+def test_social_login_rejects_email_owned_address(client, db_session, monkeypatch):
+ """The rule holds in the other direction: social login onto an email account."""
+ _make_email_user(db_session, email="mine@test.local")
+
+ monkeypatch.setattr(
+ auth_router.id_token, "verify_oauth2_token",
+ lambda *a, **k: {"sub": "g1", "email": "mine@test.local", "name": "G"},
+ raising=True,
+ )
+
+ res = client.post("/api/auth/google", json={"credential": "tok"})
+
+ assert res.status_code == 409
+ detail = res.json()["detail"]
+ assert detail["provider"] == "email"
+ assert detail["provider_label"] == "Email"
+
+
+def test_email_matching_is_case_insensitive(client, db_session, sent):
+ _register(client, "mixed@test.local")
+
+ assert _start(client, "MIXED@Test.Local").status_code == 409
+ assert _login(client, "MIXED@Test.Local").status_code == 200
+
+
+def test_forgot_rejects_socially_owned_email(client, db_session, sent):
+ _make_social(db_session, email="g@test.local", provider=AuthProvider.GOOGLE)
+
+ res = _forgot_start(client, "g@test.local")
+
+ assert res.status_code == 409
+ assert res.json()["detail"]["provider"] == "google"
+ assert sent == []
+ assert _codes(db_session, "g@test.local") == []
+
+
+# ─── Registration ───────────────────────────────────────────────────────────
+
+def test_register_happy_path_creates_verified_account(client, db_session, sent):
+ data = _register(client, "new@test.local")
+
+ assert data["access_token"]
+ assert data["user"]["auth_provider"] == "email"
+ user = db_session.query(User).filter_by(email="new@test.local").one()
+ assert user.is_active is True
+ assert user.password_hash and user.password_hash != PASSWORD
+ # The code row is spent, not left behind.
+ assert _codes(db_session, "new@test.local") == []
+
+
+@pytest.mark.parametrize(
+ "password,expected",
+ [
+ ("abc1234", "password_too_short"), # 7 chars
+ ("Ab1!", "password_too_short"), # short wins over the rest
+ ("lowercase-only-1", "password_needs_uppercase"),
+ ("NoSymbolsHere123", "password_needs_special"),
+ ],
+)
+def test_register_rejects_policy_violations_without_issuing_a_code(
+ client, db_session, sent, password, expected
+):
+ """Every policy failure is rejected before a code is issued or mail is sent."""
+ res = _start(client, "policy@test.local", password=password)
+
+ assert res.status_code == 422
+ assert res.json()["detail"] == expected
+ assert sent == []
+ assert _codes(db_session, "policy@test.local") == []
+
+
+def test_login_never_applies_the_password_policy(client, db_session):
+ """A stored password that breaks the CURRENT rules must still sign in.
+
+ Policy governs passwords being set, never ones being used. If sign-in
+ re-validated, adding a rule would lock every existing user out of their own
+ account — so this guards the one thing a future "tighten the policy" change
+ is most likely to break.
+ """
+ _make_email_user(db_session, email="legacy@test.local", password="allsmall-nosymbol")
+
+ assert _login(client, "legacy@test.local", password="allsmall-nosymbol").status_code == 200
+
+
+def test_forgot_complete_enforces_the_full_policy(client, db_session, sent):
+ """The reset path sets a password, so it gets the same rules as signup."""
+ _make_email_user(db_session, email="weak@test.local")
+ assert _forgot_start(client, "weak@test.local").status_code == 200
+
+ res = _forgot_complete(client, "weak@test.local", "nocapitals-or-symbols1")
+
+ assert res.status_code == 422
+ assert res.json()["detail"] == "password_needs_uppercase"
+ # The old password still works — a rejected reset changes nothing.
+ assert _login(client, "weak@test.local").status_code == 200
+
+
+def test_register_start_on_existing_email_account_conflicts(client, db_session, sent):
+ _register(client, "dupe@test.local")
+ sent.clear()
+
+ res = _start(client, "dupe@test.local")
+
+ assert res.status_code == 409
+ assert res.json()["detail"]["code"] == "email_already_registered"
+ assert sent == []
+
+
+@pytest.mark.parametrize(
+ "password",
+ ["short", "nouppercase-1!", "NoSpecialChar1"],
+ ids=["too_short", "no_uppercase", "no_special"],
+)
+def test_existing_account_outranks_the_password_policy(
+ client, db_session, sent, password
+):
+ """An address that already has an account answers 409, whatever was typed.
+
+ Checking the policy first would tell someone to fix a password they are never
+ going to use, on a form they should not be on — and hides the one fact that
+ actually helps them ("you already have an account, sign in"). The client
+ relies on this: it stops gating submit on the policy so a wrong password on
+ the signup form still surfaces the existing account instead of doing nothing.
+
+ The one case NOT covered here is an over-length password: _PasswordField caps
+ it at 512 chars, so pydantic rejects the body with a 422 before the handler
+ runs. That bound is deliberately left in front — it costs no DB work and no
+ real user types 512 characters into a login box.
+ """
+ _make_email_user(db_session, email="exists@test.local")
+
+ res = _start(client, "exists@test.local", password=password)
+
+ assert res.status_code == 409
+ assert res.json()["detail"]["code"] == "email_already_registered"
+ assert sent == []
+ assert _codes(db_session, "exists@test.local") == []
+
+
+def test_policy_still_applies_once_the_address_is_free(client, db_session, sent):
+ """The reordering must not weaken the policy for real signups."""
+ res = _start(client, "brandnew@test.local", password="short")
+
+ assert res.status_code == 422
+ assert res.json()["detail"] == "password_too_short"
+ assert sent == []
+
+
+def test_register_start_on_deleted_account_says_already_registered(
+ client, db_session, sent
+):
+ """Signup must NEVER surface reactivation.
+
+ A soft-deleted account answers exactly as a live one: reactivation is a
+ decision about an account you are signing in to, so a form headed "Create
+ your account" must not offer it. The login and password-reset flows own that
+ prompt, after the password (or a mailbox code) is proven.
+ """
+ user = _make_email_user(db_session, email="deleted@test.local", is_active=False)
+
+ res = _start(client, "deleted@test.local")
+
+ assert res.status_code == 409
+ assert res.json()["detail"]["code"] == "email_already_registered"
+ assert "X-Account-Deleted" not in res.headers
+ assert sent == []
+ assert _codes(db_session, "deleted@test.local") == []
+ # And signup left the account exactly as deleted as it found it.
+ db_session.refresh(user)
+ assert user.is_active is False
+
+
+def test_register_start_cannot_tell_deleted_from_live(client, db_session, sent):
+ """The two responses are byte-identical, so this endpoint is not an oracle
+ for whether a known address is deleted or active."""
+ _make_email_user(db_session, email="live@test.local")
+ _make_email_user(db_session, email="dead@test.local", is_active=False)
+
+ live = _start(client, "live@test.local")
+ dead = _start(client, "dead@test.local")
+
+ assert live.status_code == dead.status_code == 409
+ assert live.json() == dead.json()
+
+
+def test_wrong_code_burns_after_five_attempts(client, db_session, sent):
+ assert _start(client, "brute@test.local").status_code == 200
+
+ for expected_remaining in (4, 3, 2, 1):
+ res = _verify(client, "brute@test.local", code="000000")
+ assert res.status_code == 400
+ assert res.json()["detail"]["attempts_remaining"] == expected_remaining
+
+ res = _verify(client, "brute@test.local", code="000000")
+ assert res.status_code == 429
+ assert res.json()["detail"] == "code_attempts_exceeded"
+ # Burned: even the correct code is now worthless, and no account was made.
+ assert _codes(db_session, "brute@test.local") == []
+ assert _verify(client, "brute@test.local").status_code == 400
+ assert db_session.query(User).filter_by(email="brute@test.local").first() is None
+
+
+def test_expired_code_is_rejected(client, db_session, sent):
+ assert _start(client, "slow@test.local").status_code == 200
+ row = _codes(db_session, "slow@test.local")[0]
+ row.expires_at = datetime.utcnow() - timedelta(seconds=1)
+ db_session.commit()
+
+ res = _verify(client, "slow@test.local")
+
+ assert res.status_code == 400
+ assert res.json()["detail"] == "code_expired"
+ assert db_session.query(User).filter_by(email="slow@test.local").first() is None
+
+
+def test_resend_respects_cooldown_then_invalidates_the_old_code(client, db_session, sent):
+ assert _start(client, "resend@test.local").status_code == 200
+ old_hash = _codes(db_session, "resend@test.local")[0].code_hash
+
+ res = client.post("/api/auth/email/register/resend", json={"email": "resend@test.local"})
+ assert res.status_code == 429
+ assert res.json()["detail"] == "resend_too_soon"
+ assert int(res.headers["Retry-After"]) > 0
+
+ row = _codes(db_session, "resend@test.local")[0]
+ row.last_sent_at = datetime.utcnow() - timedelta(seconds=120)
+ db_session.commit()
+
+ # A different code this time, so we can prove the old one stopped working.
+ import app.services.email_verification as verification_mod
+ original = verification_mod.generate_code
+ verification_mod.generate_code = lambda: "654321"
+ try:
+ res = client.post(
+ "/api/auth/email/register/resend", json={"email": "resend@test.local"}
+ )
+ finally:
+ verification_mod.generate_code = original
+
+ assert res.status_code == 200
+ rows = _codes(db_session, "resend@test.local")
+ assert len(rows) == 1 and rows[0].code_hash != old_hash
+ # The password captured at start survives the resend — never re-asked for.
+ assert rows[0].pending_password_hash.startswith("$argon2")
+
+
+def test_resend_without_pending_registration(client, db_session, sent):
+ res = client.post("/api/auth/email/register/resend", json={"email": "nobody@test.local"})
+
+ assert res.status_code == 400
+ assert res.json()["detail"] == "no_pending_registration"
+ assert sent == []
+
+
+def test_social_signup_between_start_and_verify_loses(client, db_session, sent):
+ """A Google account created in the window wins; verify 409s rather than 500s."""
+ assert _start(client, "race@test.local").status_code == 200
+ _make_social(db_session, email="race@test.local", provider=AuthProvider.GOOGLE)
+
+ res = _verify(client, "race@test.local")
+
+ assert res.status_code == 409
+ assert res.json()["detail"]["code"] == "wrong_auth_provider"
+
+
+def test_ref_code_grants_referral_bonus_on_verify(client, db_session, sent):
+ from app.models.referral import Referral, REFERRAL_BONUS_VIDEOS
+
+ referrer = _make_email_user(db_session, email="referrer@test.local")
+ db_session.add(Referral(code="FRIEND", referrer_id=referrer.id, is_active=True))
+ db_session.commit()
+
+ assert _start(client, "invited@test.local").status_code == 200
+ res = _verify(client, "invited@test.local", ref_code="FRIEND")
+
+ assert res.status_code == 200
+ invited = db_session.query(User).filter_by(email="invited@test.local").one()
+ assert invited.referral_video_bonus == REFERRAL_BONUS_VIDEOS
+
+
+# ─── Login ──────────────────────────────────────────────────────────────────
+
+def test_login_succeeds_with_correct_password(client, db_session):
+ _make_email_user(db_session, email="who@test.local")
+
+ res = _login(client, "who@test.local")
+
+ assert res.status_code == 200
+ assert res.json()["user"]["auth_provider"] == "email"
+
+
+def test_wrong_password_and_unknown_email_are_indistinguishable(client, db_session):
+ _make_email_user(db_session, email="known@test.local")
+
+ wrong = _login(client, "known@test.local", password="not-the-password")
+ unknown = _login(client, "nobody@test.local")
+
+ assert wrong.status_code == unknown.status_code == 401
+ assert wrong.json() == unknown.json() == {"detail": "invalid_credentials"}
+
+
+def test_social_account_password_login_409s_before_touching_the_hash(client, db_session):
+ """A Google row has password_hash=None; it must 409, never 401."""
+ _make_social(db_session, email="g2@test.local", provider=AuthProvider.GOOGLE)
+
+ res = _login(client, "g2@test.local")
+
+ assert res.status_code == 409
+ assert res.json()["detail"]["provider"] == "google"
+
+
+def test_soft_deleted_account_requires_confirmation_then_reactivates(client, db_session):
+ _make_email_user(db_session, email="gone@test.local", is_active=False, plan=PlanTier.PRO)
+
+ res = _login(client, "gone@test.local")
+ assert res.status_code == 403
+ assert res.json()["detail"] == "account_deleted"
+
+ res = _login(client, "gone@test.local", reactivate=True)
+ assert res.status_code == 200
+ user = db_session.query(User).filter_by(email="gone@test.local").one()
+ db_session.refresh(user)
+ assert user.is_active is True
+ assert user.plan is PlanTier.FREE
+
+
+def test_wrong_password_cannot_reactivate_a_deleted_account(client, db_session):
+ """The ordering trap: reactivation must never precede the password check."""
+ _make_email_user(db_session, email="ghost@test.local", is_active=False)
+
+ res = _login(client, "ghost@test.local", password="wrong-password", reactivate=True)
+
+ assert res.status_code == 401
+ user = db_session.query(User).filter_by(email="ghost@test.local").one()
+ db_session.refresh(user)
+ assert user.is_active is False
+
+
+def test_login_locks_out_after_repeated_failures(client, db_session):
+ _make_email_user(db_session, email="target@test.local")
+
+ for _ in range(5):
+ assert _login(client, "target@test.local", password="nope").status_code == 401
+
+ res = _login(client, "target@test.local", password="nope")
+ assert res.status_code == 429
+ assert res.json()["detail"] == "too_many_attempts"
+ assert int(res.headers["Retry-After"]) > 0
+ # Even the correct password is refused while locked out.
+ assert _login(client, "target@test.local").status_code == 429
+
+
+def test_wrong_provider_does_not_count_as_a_failed_attempt(client, db_session):
+ """A 409 is a correct answer, so asking repeatedly must not lock anyone out."""
+ _make_social(db_session, email="g3@test.local", provider=AuthProvider.GOOGLE)
+
+ for _ in range(8):
+ assert _login(client, "g3@test.local").status_code == 409
+
+ assert _login(client, "g3@test.local").status_code == 409
+
+
+# ─── Forgot password ────────────────────────────────────────────────────────
+
+def test_forgot_start_is_silent_for_unknown_email(client, db_session, sent):
+ res = _forgot_start(client, "stranger@test.local")
+
+ assert res.status_code == 200
+ assert res.json()["status"] == "code_sent"
+ assert sent == []
+ assert _codes(db_session, "stranger@test.local") == []
+
+
+def test_forgot_start_on_deleted_account_requires_confirmation(client, db_session, sent):
+ """Without ?reactivate=true it stays deleted and no code goes out."""
+ _make_email_user(db_session, email="rip@test.local", is_active=False)
+
+ res = _forgot_start(client, "rip@test.local")
+
+ assert res.status_code == 403
+ assert res.json()["detail"] == "account_deleted"
+ assert sent == []
+ assert _codes(db_session, "rip@test.local") == []
+ user = db_session.query(User).filter_by(email="rip@test.local").one()
+ db_session.refresh(user)
+ assert user.is_active is False
+
+
+def test_forgot_start_reactivates_on_confirm_without_signing_in(client, db_session, sent):
+ """The whole point: a deleted account whose password is also forgotten.
+
+ Confirming reactivation revives the account and emails a code — it must NOT
+ hand back a token, or the confirmation click alone would be a way into an
+ account without knowing the password or holding the mailbox.
+ """
+ _make_email_user(db_session, email="back@test.local", is_active=False, plan=PlanTier.PRO)
+
+ res = _forgot_start(client, "back@test.local", reactivate=True)
+
+ assert res.status_code == 200
+ assert res.json()["status"] == "code_sent"
+ assert "access_token" not in res.json()
+ assert sent == [("reset", "back@test.local", CODE)]
+
+ user = db_session.query(User).filter_by(email="back@test.local").one()
+ db_session.refresh(user)
+ assert user.is_active is True
+ # Reactivation is always as a FREE user, exactly as on the login path.
+ assert user.plan is PlanTier.FREE
+
+ # And the reset still has to be completed to get a session.
+ res = _forgot_complete(client, "back@test.local", "Brand-New-Password1")
+ assert res.status_code == 200
+ assert res.json()["access_token"]
+ assert _login(client, "back@test.local", password="Brand-New-Password1").status_code == 200
+
+
+def test_forgot_start_reactivate_flag_is_inert_for_unknown_email(client, db_session, sent):
+ """?reactivate=true must not become an account-existence oracle."""
+ res = _forgot_start(client, "nobody@test.local", reactivate=True)
+
+ assert res.status_code == 200
+ assert sent == []
+ assert db_session.query(User).filter_by(email="nobody@test.local").first() is None
+
+
+def test_forgot_start_reactivate_cannot_revive_a_social_account(client, db_session, sent):
+ """The wrong-provider 409 still outranks reactivation — there is no password
+ to reset on a Google account, so reviving it here would be the wrong door."""
+ _make_social(
+ db_session, email="gdead@test.local", provider=AuthProvider.GOOGLE, is_active=False
+ )
+
+ res = _forgot_start(client, "gdead@test.local", reactivate=True)
+
+ assert res.status_code == 409
+ assert res.json()["detail"]["provider"] == "google"
+ user = db_session.query(User).filter_by(email="gdead@test.local").one()
+ db_session.refresh(user)
+ assert user.is_active is False
+
+
+def test_forgot_password_replaces_the_credential(client, db_session, sent):
+ _make_email_user(db_session, email="reset@test.local")
+
+ assert _forgot_start(client, "reset@test.local").status_code == 200
+ assert sent == [("reset", "reset@test.local", CODE)]
+
+ res = _forgot_complete(client, "reset@test.local", "Brand-New-Password1")
+ assert res.status_code == 200
+ assert res.json()["access_token"]
+
+ assert _login(client, "reset@test.local").status_code == 401
+ assert _login(client, "reset@test.local", password="Brand-New-Password1").status_code == 200
+ assert _codes(db_session, "reset@test.local") == []
+
+
+def test_forgot_complete_rejects_short_password_and_keeps_the_old_one(
+ client, db_session, sent
+):
+ _make_email_user(db_session, email="keep@test.local")
+ assert _forgot_start(client, "keep@test.local").status_code == 200
+
+ res = _forgot_complete(client, "keep@test.local", "short")
+
+ assert res.status_code == 422
+ assert res.json()["detail"] == "password_too_short"
+ assert _login(client, "keep@test.local").status_code == 200
+
+
+def test_signup_and_reset_codes_are_not_interchangeable(client, db_session, sent):
+ """Codes are scoped to a purpose, so neither can be replayed as the other."""
+ _make_email_user(db_session, email="scope@test.local")
+ assert _forgot_start(client, "scope@test.local").status_code == 200
+
+ # A reset code cannot complete a registration...
+ assert _verify(client, "scope@test.local").status_code == 400
+
+ # ...and a signup code cannot complete a reset.
+ db_session.query(EmailVerificationCode).delete()
+ db_session.add(
+ EmailVerificationCode(
+ email="scope@test.local",
+ purpose=VerificationPurpose.SIGNUP.value,
+ code_hash=auth_router.verification.hash_code(CODE),
+ expires_at=datetime.utcnow() + timedelta(minutes=10),
+ last_sent_at=datetime.utcnow(),
+ created_at=datetime.utcnow(),
+ )
+ )
+ db_session.commit()
+
+ assert _forgot_complete(client, "scope@test.local", "Another-Password1").status_code == 400
+
+
+# ─── forgot/check — validate without consuming ──────────────────────────────
+
+def test_forgot_check_accepts_valid_code_without_spending_it(client, db_session, sent):
+ """The whole point: checking must not consume, or complete() has nothing left."""
+ _make_email_user(db_session, email="chk@test.local")
+ assert _forgot_start(client, "chk@test.local").status_code == 200
+
+ res = client.post(
+ "/api/auth/password/forgot/check",
+ json={"email": "chk@test.local", "code": CODE},
+ )
+ assert res.status_code == 200
+ assert res.json()["status"] == "code_valid"
+
+ # Still usable afterwards — the code was validated, not spent.
+ assert _forgot_complete(client, "chk@test.local", "Brand-New-Password1").status_code == 200
+ assert _login(client, "chk@test.local", password="Brand-New-Password1").status_code == 200
+
+
+def test_forgot_check_rejects_wrong_code(client, db_session, sent):
+ _make_email_user(db_session, email="chkbad@test.local")
+ assert _forgot_start(client, "chkbad@test.local").status_code == 200
+
+ res = client.post(
+ "/api/auth/password/forgot/check",
+ json={"email": "chkbad@test.local", "code": "000000"},
+ )
+ assert res.status_code == 400
+ assert res.json()["detail"]["code"] == "code_invalid"
+ # The real code still works, so a wrong guess did not destroy it.
+ assert _forgot_complete(client, "chkbad@test.local", "Brand-New-Password1").status_code == 200
+
+
+def test_forgot_check_is_not_a_free_brute_force_oracle(client, db_session, sent):
+ """Attempts must count here too, or this endpoint bypasses the 5-try cap."""
+ _make_email_user(db_session, email="chkbrute@test.local")
+ assert _forgot_start(client, "chkbrute@test.local").status_code == 200
+
+ for _ in range(4):
+ assert client.post(
+ "/api/auth/password/forgot/check",
+ json={"email": "chkbrute@test.local", "code": "000000"},
+ ).status_code == 400
+
+ res = client.post(
+ "/api/auth/password/forgot/check",
+ json={"email": "chkbrute@test.local", "code": "000000"},
+ )
+ assert res.status_code == 429
+ assert res.json()["detail"] == "code_attempts_exceeded"
+ # Burned: even the correct code is gone now.
+ assert _forgot_complete(client, "chkbrute@test.local", "Brand-New-Password1").status_code == 400
diff --git a/backend/tests/test_token_revocation.py b/backend/tests/test_token_revocation.py
new file mode 100644
index 0000000000000000000000000000000000000000..62c2216eb5f16329ae26f62ff811528390191c93
--- /dev/null
+++ b/backend/tests/test_token_revocation.py
@@ -0,0 +1,275 @@
+"""
+Depth tier — JWT revocation via users.token_version.
+
+Our access tokens are stateless, so the only thing standing between a leaked
+token and a live session is this counter. The properties under test:
+
+1. Bumping the counter invalidates every token issued before the bump.
+2. Logging out and resetting a password both bump it — the two moments a user
+ expects their old sessions to die.
+3. A token minted before the ``tv`` claim existed still works, so shipping this
+ signs nobody out.
+"""
+import jwt as pyjwt
+import pytest
+
+from app.auth import create_access_token, create_refresh_token
+from app.config import settings
+from app.models.user import AuthProvider, PlanTier, User
+from app.services import rate_limit
+from app.services.password import hash_password
+
+import app.routers.auth as auth_router
+
+pytestmark = pytest.mark.depth
+
+CODE = "123456"
+PASSWORD = "Correct-Horse-1"
+
+
+@pytest.fixture(autouse=True)
+def _fixed_code(monkeypatch):
+ monkeypatch.setattr(
+ auth_router.verification, "generate_code", lambda: CODE, raising=True
+ )
+ rate_limit.reset_all_limiters()
+ yield
+ rate_limit.reset_all_limiters()
+
+
+@pytest.fixture()
+def sent(monkeypatch):
+ out: list[tuple[str, str]] = []
+ monkeypatch.setattr(
+ auth_router.email_service, "send_password_reset_code_email",
+ lambda to, code: out.append((to, code)), raising=True,
+ )
+ return out
+
+
+def _make_email_user(db, *, email, password=PASSWORD, **kw):
+ user = User(
+ email=email, name="Token User", auth_provider=AuthProvider.EMAIL,
+ password_hash=hash_password(password), plan=PlanTier.FREE, is_active=True, **kw,
+ )
+ db.add(user)
+ db.commit()
+ db.refresh(user)
+ return user
+
+
+def _bearer(token: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {token}"}
+
+
+# ─── The core property ──────────────────────────────────────────────────────
+
+def test_token_is_accepted_while_the_version_matches(client, db_session):
+ user = _make_email_user(db_session, email="tv1@test.local")
+
+ token = create_access_token(user.id, user.token_version)
+
+ assert client.get("/api/auth/me", headers=_bearer(token)).status_code == 200
+
+
+def test_bumping_the_version_invalidates_an_existing_token(client, db_session):
+ user = _make_email_user(db_session, email="tv2@test.local")
+ token = create_access_token(user.id, user.token_version)
+ assert client.get("/api/auth/me", headers=_bearer(token)).status_code == 200
+
+ user.token_version = (user.token_version or 0) + 1
+ db_session.commit()
+
+ res = client.get("/api/auth/me", headers=_bearer(token))
+ assert res.status_code == 401
+ # Same body as an expired token: telling a holder of a stale token that it
+ # was deliberately revoked confirms the account exists.
+ assert res.json()["detail"] == "Invalid or expired token"
+
+
+def test_legacy_token_without_the_claim_still_works(client, db_session):
+ """A token minted before `tv` existed reads as version 0 — deploying this
+ must not sign the entire userbase out."""
+ user = _make_email_user(db_session, email="tv3@test.local")
+ assert (user.token_version or 0) == 0
+
+ legacy = pyjwt.encode(
+ {"sub": str(user.id), "exp": 9999999999, "iat": 0, "typ": "access"},
+ settings.JWT_SECRET,
+ algorithm=settings.JWT_ALGORITHM,
+ )
+
+ assert client.get("/api/auth/me", headers=_bearer(legacy)).status_code == 200
+
+
+def test_legacy_token_dies_once_the_account_revokes_once(client, db_session):
+ user = _make_email_user(db_session, email="tv4@test.local")
+ legacy = pyjwt.encode(
+ {"sub": str(user.id), "exp": 9999999999, "iat": 0, "typ": "access"},
+ settings.JWT_SECRET,
+ algorithm=settings.JWT_ALGORITHM,
+ )
+
+ user.token_version = 1
+ db_session.commit()
+
+ assert client.get("/api/auth/me", headers=_bearer(legacy)).status_code == 401
+
+
+def test_new_users_start_at_version_zero(client, db_session):
+ user = _make_email_user(db_session, email="tv5@test.local")
+ assert user.token_version == 0
+
+
+# ─── Revocation triggers ────────────────────────────────────────────────────
+
+def test_logout_revokes_the_token_it_was_called_with(client, db_session):
+ user = _make_email_user(db_session, email="out@test.local")
+ token = create_access_token(user.id, user.token_version)
+
+ assert client.post("/api/auth/logout", headers=_bearer(token)).status_code == 200
+
+ # The very token that authorized the logout is now dead — the whole point on
+ # a shared machine, where the copy left behind is the threat.
+ assert client.get("/api/auth/me", headers=_bearer(token)).status_code == 401
+ db_session.refresh(user)
+ assert user.token_version == 1
+
+
+def test_password_reset_revokes_tokens_issued_under_the_old_password(
+ client, db_session, sent
+):
+ """The reset is meant to evict whoever knew the old password."""
+ user = _make_email_user(db_session, email="reset@test.local")
+ stolen = create_access_token(user.id, user.token_version)
+ assert client.get("/api/auth/me", headers=_bearer(stolen)).status_code == 200
+
+ assert client.post(
+ "/api/auth/password/forgot/start", json={"email": "reset@test.local"}
+ ).status_code == 200
+ res = client.post(
+ "/api/auth/password/forgot/complete",
+ json={
+ "email": "reset@test.local",
+ "code": CODE,
+ "new_password": "Brand-New-Password1",
+ },
+ )
+ assert res.status_code == 200
+
+ # The attacker's token is dead...
+ assert client.get("/api/auth/me", headers=_bearer(stolen)).status_code == 401
+ # ...while the token handed back by the reset works, so the legitimate user
+ # is not bounced out of the browser they just reset from.
+ fresh = res.json()["access_token"]
+ assert client.get("/api/auth/me", headers=_bearer(fresh)).status_code == 200
+
+
+def test_login_issues_a_token_carrying_the_current_version(client, db_session):
+ """After a revocation, signing in again must work — the new token has to be
+ minted against the bumped counter, not a stale one."""
+ user = _make_email_user(db_session, email="again@test.local")
+ user.token_version = 7
+ db_session.commit()
+
+ res = client.post(
+ "/api/auth/email/login",
+ json={"email": "again@test.local", "password": PASSWORD},
+ )
+ assert res.status_code == 200
+
+ token = res.json()["access_token"]
+ assert client.get("/api/auth/me", headers=_bearer(token)).status_code == 200
+ assert pyjwt.decode(
+ token, settings.JWT_SECRET, algorithms=[settings.JWT_ALGORITHM]
+ )["tv"] == 7
+
+
+def test_signup_issues_a_token_that_works(client, db_session, monkeypatch):
+ monkeypatch.setattr(
+ auth_router.email_service, "send_verification_code_email",
+ lambda to, code: None, raising=True,
+ )
+ assert client.post(
+ "/api/auth/email/register/start",
+ json={"email": "fresh@test.local", "password": PASSWORD},
+ ).status_code == 200
+ res = client.post(
+ "/api/auth/email/register/verify",
+ json={"email": "fresh@test.local", "code": CODE},
+ )
+
+ assert res.status_code == 200
+ token = res.json()["access_token"]
+ assert client.get("/api/auth/me", headers=_bearer(token)).status_code == 200
+
+
+# ─── MCP refresh tokens ─────────────────────────────────────────────────────
+
+async def test_revoked_refresh_token_cannot_mint_a_new_pair(db_session, monkeypatch):
+ """Otherwise revocation undoes itself: the 30-day MCP credential would
+ quietly reissue past a password change."""
+ from mcp.server.auth.provider import RefreshToken
+
+ import app.services.mcp_provider as mcp_provider
+
+ user = _make_email_user(db_session, email="mcp@test.local")
+ stale = create_refresh_token(user.id, user.token_version)
+
+ user.token_version = (user.token_version or 0) + 1
+ db_session.commit()
+
+ # The provider opens its own SessionLocal(), which under the suite's
+ # rolled-back outer transaction would see an empty database. Point it at the
+ # test session so it reads the row we just bumped.
+ monkeypatch.setattr(
+ mcp_provider, "SessionLocal", lambda: _NonClosing(db_session), raising=True
+ )
+
+ provider = mcp_provider.BlogVideoOAuthProvider()
+ with pytest.raises(ValueError):
+ await provider.exchange_refresh_token(
+ client=None,
+ refresh_token=RefreshToken(
+ token=stale, client_id="c1", scopes=[], expires_at=9999999999
+ ),
+ scopes=[],
+ )
+
+
+async def test_current_refresh_token_still_mints_a_new_pair(db_session, monkeypatch):
+ """The guard must not break ordinary refreshes — claude.ai renews on a timer,
+ so a false rejection here silently disconnects the integration."""
+ from mcp.server.auth.provider import RefreshToken
+
+ import app.services.mcp_provider as mcp_provider
+
+ user = _make_email_user(db_session, email="mcp-ok@test.local")
+ good = create_refresh_token(user.id, user.token_version)
+
+ monkeypatch.setattr(
+ mcp_provider, "SessionLocal", lambda: _NonClosing(db_session), raising=True
+ )
+
+ provider = mcp_provider.BlogVideoOAuthProvider()
+ out = await provider.exchange_refresh_token(
+ client=None,
+ refresh_token=RefreshToken(
+ token=good, client_id="c1", scopes=[], expires_at=9999999999
+ ),
+ scopes=[],
+ )
+ assert out.access_token and out.refresh_token
+
+
+class _NonClosing:
+ """Wrap the test session so provider code calling .close() doesn't end it."""
+
+ def __init__(self, session):
+ self._session = session
+
+ def __getattr__(self, name):
+ return getattr(self._session, name)
+
+ def close(self):
+ pass
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 53c80f61b6f879d0ebf1038a353c80e9067706b7..c927ee4ede5dbc104ba24696340eaa318e4b81ee 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -8,7 +8,6 @@
"name": "blog2video-frontend",
"version": "0.1.0",
"dependencies": {
- "@azure/msal-browser": "^5.21.0",
"@babel/standalone": "^7.29.1",
"@fontsource/archivo-black": "^5.2.8",
"@fontsource/arimo": "^5.2.8",
@@ -103,27 +102,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
- "node_modules/@azure/msal-browser": {
- "version": "5.21.0",
- "resolved": "https://registry.npmjs.org/@azure/msal-browser/-/msal-browser-5.21.0.tgz",
- "integrity": "sha512-80OcuXDErmcEDAIH9pBtSqBsed2sPT/IWmbG3xHLoPMl5zc8TINd6SlJAbVSmN5huGa3xGAg5qR7VnpaIEK0Zw==",
- "license": "MIT",
- "dependencies": {
- "@azure/msal-common": "16.14.0"
- },
- "engines": {
- "node": ">=0.8.0"
- }
- },
- "node_modules/@azure/msal-common": {
- "version": "16.14.0",
- "resolved": "https://registry.npmjs.org/@azure/msal-common/-/msal-common-16.14.0.tgz",
- "integrity": "sha512-A4rb55hI86Q9tBl/+jBj7TMz7iX2RFgQs/nExFzcAtoI/BFRVdaH5SL/MivrYD7qvweMpN8AgVvVMHV8UBYxew==",
- "license": "MIT",
- "engines": {
- "node": ">=0.8.0"
- }
- },
"node_modules/@babel/code-frame": {
"version": "7.29.0",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz",
diff --git a/frontend/package.json b/frontend/package.json
index 80a8fe1720aa7dac70d163a4b72f8561d5d93dcf..13c9b4707a2f71b112dffb929a3f575446b02505 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -17,7 +17,6 @@
"kit:check": "node ../scripts/sync-generated-kit.mjs --check"
},
"dependencies": {
- "@azure/msal-browser": "^5.21.0",
"@babel/standalone": "^7.29.1",
"@fontsource/archivo-black": "^5.2.8",
"@fontsource/arimo": "^5.2.8",
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 44429b35eccfb8257da3d2e5c5fb8edfe0febb50..e242c2e7ba59cb4d2c6eb8b4ce72d8e7de05226b 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -13,6 +13,7 @@ import Landing from "./pages/Landing";
import PdfLanding from "./pages/PdfLanding";
import { applyFavicon, isPdfBrand, useBrand, markPdfOrigin } from "./brand/brand";
import Pricing from "./pages/Pricing";
+import AuthPage from "./pages/AuthPage";
import Dashboard from "./pages/Dashboard";
import ProjectView from "./pages/ProjectView";
import Subscription from "./pages/Subscription";
@@ -189,6 +190,10 @@ function AppRoutes() {
(corePages.ts) with inbound links from several others. */}
} />
} />
+ {/* Full-page sign-in / sign-up. Two paths, one component, so "Sign up"
+ is directly linkable rather than reachable only via a toggle. */}
+ } />
+ } />
} />
} />
} />
diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts
index 55ef10d88136fcaa4fd5a4369f4454ff1d10fef2..32d2956f284b80002aefd63fa37f0a00e48c88fa 100644
--- a/frontend/src/api/client.ts
+++ b/frontend/src/api/client.ts
@@ -479,36 +479,69 @@ export const googleLogin = (credential: string, reactivate = false, refCode?: st
return api.post("/auth/google", { credential }, { params });
};
-/** Name payload Apple sends on the FIRST authorization only. */
-export interface AppleUserPayload {
- name?: { firstName?: string; lastName?: string };
+// ─── Email + password auth ────────────────────────────────
+// Built-in provider. Registration proves the mailbox with a one-time code before
+// the account exists; every later sign-in is password-only.
+//
+// These use `publicApi`, NOT `api`: the authed client's interceptor treats any
+// 401 as an expired session — it clears the stored token and hard-redirects to
+// "/". A mistyped password returns 401 by design, so on `api` it would log an
+// already-signed-in user out and reload the page out from under the modal,
+// and the redirect would race the error the form needs to display.
+
+/** Acknowledges a one-time code was issued. Carries no account information. */
+export interface CodeSentResponse {
+ status: string;
+ /** Seconds until the code expires. */
+ expires_in: number;
+ /** Seconds before a resend is allowed. */
+ resend_in: number;
}
-export const appleLogin = (
- identityToken: string,
- user?: AppleUserPayload | null,
- reactivate = false,
- refCode?: string | null
-) => {
- const params: Record = { reactivate };
- if (refCode) params.ref_code = refCode;
- return api.post(
- "/auth/apple",
- { identity_token: identityToken, user: user ?? null },
- { params }
- );
-};
+export const emailRegisterStart = (email: string, password: string, name?: string | null) =>
+ publicApi.post("/auth/email/register/start", {
+ email,
+ password,
+ name: name ?? null,
+ });
-export const microsoftLogin = (
- idToken: string,
- reactivate = false,
- refCode?: string | null
-) => {
- const params: Record = { reactivate };
+export const emailRegisterVerify = (email: string, code: string, refCode?: string | null) => {
+ const params: Record = {};
if (refCode) params.ref_code = refCode;
- return api.post("/auth/microsoft", { id_token: idToken }, { params });
+ return publicApi.post("/auth/email/register/verify", { email, code }, { params });
};
+export const emailRegisterResend = (email: string) =>
+ publicApi.post("/auth/email/register/resend", { email });
+
+export const emailLogin = (email: string, password: string, reactivate = false) =>
+ publicApi.post(
+ "/auth/email/login",
+ { email, password },
+ { params: { reactivate } }
+ );
+
+/** `reactivate` confirms revival of a soft-deleted account. It still only emails
+ * a code — no token is issued, so the reset must be completed to get a session. */
+export const forgotPasswordStart = (email: string, reactivate = false) =>
+ publicApi.post(
+ "/auth/password/forgot/start",
+ { email },
+ { params: { reactivate } }
+ );
+
+/** Validate a reset code without spending it, so the UI can reject a wrong
+ * code before advancing to the new-password step. */
+export const forgotPasswordCheck = (email: string, code: string) =>
+ publicApi.post<{ status: string }>("/auth/password/forgot/check", { email, code });
+
+export const forgotPasswordComplete = (email: string, code: string, newPassword: string) =>
+ publicApi.post("/auth/password/forgot/complete", {
+ email,
+ code,
+ new_password: newPassword,
+ });
+
// Share B2V (referral/invite) disabled
// export const getAffiliateStats = () => api.get("/affiliate/stats");
// export const sendAffiliateInvites = (emails: string[]) =>
diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts
index 1161b8c406226b83ccd3fd7c5c635a06a2519603..ae1298bb5d14c6346bdd93714f84f1e024f90341 100644
--- a/frontend/src/api/types.ts
+++ b/frontend/src/api/types.ts
@@ -80,8 +80,12 @@ export const AVATAR_BG_PRESETS: { value: string; label: string }[] = [
{ value: "#F1F5F9", label: "Paper" },
];
-/** The sign-in provider an account is permanently bound to. */
-export type AuthProvider = "google" | "apple" | "microsoft";
+/**
+ * The sign-in provider an account is permanently bound to. "email" is our own
+ * built-in provider (email + password), the only one with no external identity
+ * provider behind it.
+ */
+export type AuthProvider = "google" | "email";
/**
* Human-facing provider names. An explicit map rather than a ternary: this
@@ -90,10 +94,38 @@ export type AuthProvider = "google" | "apple" | "microsoft";
*/
export const AUTH_PROVIDER_LABELS: Record = {
google: "Google",
- apple: "Apple",
- microsoft: "Microsoft",
+ email: "Email",
};
+/**
+ * Minimum password length, mirroring MIN_PASSWORD_LENGTH in the backend's
+ * services/password.py. Used for instant feedback only — the server is
+ * authoritative, and sign-in must never be blocked on it client-side, or a
+ * password predating a policy change would become unusable.
+ */
+export const MIN_PASSWORD_LENGTH = 8;
+
+/**
+ * The password policy, mirroring validate_password() in the backend's
+ * services/password.py. Shown as a live checklist while choosing a password.
+ *
+ * Feedback only, and only where a password is being SET (signup, reset). The
+ * login form must never apply these — an existing password that predates a rule
+ * still has to reach the server, which decides.
+ */
+export const PASSWORD_RULES: { test: (p: string) => boolean; label: string }[] = [
+ {
+ test: (p) => p.length >= MIN_PASSWORD_LENGTH,
+ label: `At least ${MIN_PASSWORD_LENGTH} characters`,
+ },
+ { test: (p) => /[A-Z]/.test(p), label: "One capital letter" },
+ // Matches the backend's deliberately broad definition: anything that is not a
+ // letter or digit, so non-ASCII punctuation counts too.
+ { test: (p) => /[^A-Za-z0-9]/.test(p), label: "One special character" },
+];
+
+export const passwordMeetsPolicy = (p: string) => PASSWORD_RULES.every((r) => r.test(p));
+
export interface UserInfo {
id: number;
email: string;
diff --git a/frontend/src/components/auth/AuthFlow.tsx b/frontend/src/components/auth/AuthFlow.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..da6747863390441bffaf688eed48d0d6396d2208
--- /dev/null
+++ b/frontend/src/components/auth/AuthFlow.tsx
@@ -0,0 +1,1173 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import ReactDOM from "react-dom";
+import { GoogleLogin } from "@react-oauth/google";
+
+import { useSocialLogin, type LoginError } from "../../hooks/useSocialLogin";
+import { useEmailAuth } from "../../hooks/useEmailAuth";
+import { PASSWORD_RULES, passwordMeetsPolicy } from "../../api/types";
+import {
+ copyLink,
+ detectInAppBrowser,
+ escapeToSystemBrowser,
+} from "../../lib/inAppBrowser";
+
+export interface LoginModalCopy {
+ title?: string;
+ subtitle?: string;
+}
+
+interface LoginModalProps extends LoginModalCopy {
+ open: boolean;
+ onClose: () => void;
+ /** Runs on a successful sign-in; the provider uses it to close the modal. */
+ onSuccess?: () => void;
+ /** Suppresses the default post-login redirect (see LoginModalContext). */
+ skipRedirect?: boolean;
+}
+
+/** Fallback copy when a call site supplies none. Keyed to the opening mode so a
+ * surface that defaults to the sign-up form is not headed "Sign in". */
+const DEFAULT_COPY = {
+ login: {
+ title: "Sign in to Blog2Video",
+ subtitle: "Choose how you'd like to continue.",
+ },
+ signup: {
+ title: "Create your Blog2Video account",
+ subtitle: "Choose how you'd like to get started.",
+ },
+} as const;
+
+/**
+ * Per-stage heading. The first stage keeps whatever copy the call site passed —
+ * the ~11 CTAs that open this modal each set their own — while the later stages
+ * describe the step the user is actually on.
+ */
+const STAGE_COPY: Record = {
+ otp: {
+ title: "Check your email",
+ subtitle: "We sent you a 6-digit code. Enter it below to finish signing up.",
+ },
+ forgot_email: {
+ title: "Reset your password",
+ subtitle: "We'll email you a code to set a new password.",
+ },
+ forgot_code: { title: "Check your email", subtitle: "Enter the 6-digit code we sent you." },
+ forgot_password: { title: "Choose a new password", subtitle: "Pick something you'll remember." },
+};
+
+/**
+ * Errors that belong under a specific input rather than in the modal's banner.
+ *
+ * These are all "what you typed was wrong" — the message is only useful next to
+ * the field you retype. The banner is reserved for errors about the modal as a
+ * whole, which is also why account_deleted is excluded: it carries a Reactivate
+ * button that needs the box to read as one unit.
+ */
+const FIELD_LEVEL_ERRORS = new Set([
+ "invalid_credentials",
+ "password_policy",
+ "code_invalid",
+ "code_expired",
+ "code_burned",
+ "resend_cooldown",
+]);
+
+const isFieldLevelError = (e: LoginError | null) =>
+ e !== null && FIELD_LEVEL_ERRORS.has(e.kind);
+
+/**
+ * "This address already has a password account", in either of the two shapes the
+ * backend sends it. Mirrors isExistingEmailAccount in useEmailAuth — both must
+ * agree, or the hook would route the user to the sign-in form while the banner
+ * kept claiming something else.
+ */
+const isExistingAccountError = (e: LoginError | null) =>
+ e !== null &&
+ (e.kind === "email_already_registered" ||
+ (e.kind === "wrong_provider" && e.provider === "email"));
+
+/** Inline validation message: red text, no box, sits under its field. */
+function FieldError({ children }: { children: React.ReactNode }) {
+ return
{children}
;
+}
+
+/**
+ * Width of the sign-in column, shared by the provider rows, the divider and
+ * every stage form. Set once per render by the variant: the page has a wider
+ * card to fill, the modal keeps its original 300px. A module-level value rather
+ * than a prop because EmailAuthForm/CodeForm would otherwise have to forward it
+ * through every stage purely to change one number.
+ */
+let COLUMN_WIDTH_CLASS = "w-[300px]";
+
+const INPUT_CLASS =
+ "w-full rounded-lg border border-gray-300 px-3 py-2 text-sm text-gray-900 outline-none transition placeholder:text-gray-400 focus:border-purple-500 focus:ring-2 focus:ring-purple-100";
+const PRIMARY_BUTTON_CLASS =
+ "w-full rounded-lg bg-purple-600 px-4 py-2.5 text-sm font-medium text-white transition hover:bg-purple-700 disabled:cursor-not-allowed disabled:opacity-50";
+
+/**
+ * The sign-in surface itself — everything inside the modal's box.
+ *
+ * Extracted so the dialog (LoginModal) and the full page (AuthPage) render the
+ * SAME flow rather than two copies. A fork here would drift exactly the way a
+ * second copy of parseLoginError would: one surface would quietly stop handling
+ * a 409, a burned code, or the reactivation prompt.
+ *
+ * `variant` only affects chrome-adjacent details (heading size, the terms
+ * footer); every behaviour — staging, error placement, provider narrowing — is
+ * identical on both.
+ */
+export interface AuthFlowProps extends LoginModalCopy {
+ /** False while a modal is closed, so the reset effect does not run. */
+ active?: boolean;
+ variant?: "modal" | "page";
+ /** Opening intent. Defaults to "signup" so every surface that does not say
+ * otherwise (the modal, the in-place tool gates) opens on the sign-up form;
+ * /signin passes "login" explicitly. */
+ mode?: "login" | "signup";
+ onSuccess?: () => void;
+ skipRedirect?: boolean;
+ /** Modal only: renders the back chevron beside the heading. */
+ onClose?: () => void;
+}
+
+export default function AuthFlow({
+ active = true,
+ variant = "modal",
+ mode = "signup",
+ onSuccess,
+ skipRedirect,
+ title,
+ subtitle,
+}: AuthFlowProps) {
+ const {
+ signInWithGoogle,
+ onGoogleError,
+ signingIn,
+ error,
+ reactivate,
+ reactivating,
+ dismissError,
+ reset,
+ } = useSocialLogin({ onSuccess, skipRedirect });
+
+ const emailAuth = useEmailAuth({ onSuccess, skipRedirect, initialMode: mode });
+
+ // Keyed to the LIVE stage mode, not the mount-time prop: the "Already have an
+ // account? Sign in" toggle flips stage.mode, and a heading frozen at mount
+ // would keep saying "Create your account" over a sign-in form.
+ const activeMode =
+ "mode" in emailAuth.stage ? emailAuth.stage.mode : mode;
+ const fallback = DEFAULT_COPY[activeMode];
+ const resolvedTitle = title ?? fallback.title;
+ const resolvedSubtitle = subtitle ?? fallback.subtitle;
+
+ // Only consult the UA once the modal opens; the result never changes for a
+ // given page load, but this keeps the check out of the render path.
+ const [inApp, setInApp] = useState(false);
+ const [showInstructions, setShowInstructions] = useState(false);
+ const [copied, setCopied] = useState(false);
+
+ const resetEmail = emailAuth.reset;
+ useEffect(() => {
+ if (!active) return;
+ setInApp(detectInAppBrowser().isInApp);
+ setShowInstructions(false);
+ setCopied(false);
+ reset();
+ resetEmail();
+ }, [active, reset, resetEmail]);
+
+ // Either path can be mid-flight; the modal must stay inert for both.
+ const busy = signingIn || emailAuth.busy;
+
+ /* Which hook failed MOST RECENTLY.
+ *
+ * Two independent error states feed one banner, and the surface lets a user
+ * move between them without leaving it: a Google attempt rejected because the
+ * address is an email account, then an email attempt rejected because a
+ * different address is a Google account. This used to be `error ??
+ * emailAuth.error`, which is not "whichever hook just failed" but "the social
+ * hook wins if it EVER failed" — the social error is never cleared by the
+ * email flow (the hooks are isolated; useEmailAuth can only clear its own),
+ * so the first rejection masked every later one. The banner kept naming the
+ * wrong provider, and `onlyProvider` below inherited the same stale value, so
+ * the UI also failed to narrow to the provider that would actually work.
+ *
+ * Tracked by REFERENCE, not by value: parseLoginError builds a fresh object
+ * on every call, so a repeat of the same failure still registers as new. */
+ const [lastErrorSource, setLastErrorSource] = useState<"social" | "email" | null>(null);
+ const prevErrors = useRef<{ social: LoginError | null; email: LoginError | null }>({
+ social: null,
+ email: null,
+ });
+ const emailError = emailAuth.error;
+ useEffect(() => {
+ const prev = prevErrors.current;
+ prevErrors.current = { social: error, email: emailError };
+ // A newly-set error claims the banner. Checked independently so that a
+ // render where one is set while the other is cleared still resolves.
+ if (error !== prev.social && error !== null) setLastErrorSource("social");
+ else if (emailError !== prev.email && emailError !== null) setLastErrorSource("email");
+ else if (error === null && emailError === null) setLastErrorSource(null);
+ }, [error, emailError]);
+
+ /** The error the UI should speak for: the most recent one, with the other as
+ * a fallback so clearing one never blanks a banner the other still owns. */
+ const activeError =
+ lastErrorSource === "email" ? (emailError ?? error) : (error ?? emailError);
+
+ // A soft-deleted account asks for confirmation in its own dialog rather than
+ // offering a button inside the error banner — see ReactivateConfirm.
+ // Three routes, because reactivating from the forgot-password step reactivates
+ // WITHOUT signing in — it emails a reset code instead — so it needs its own
+ // confirm copy and its own retry.
+ // Never on the SIGNUP form: reactivation is a decision about an account you
+ // are signing in to, and "Reactivate your account?" over "Create your account"
+ // reads as a non-sequitur. The backend already answers signup with
+ // `email_already_registered` for a deleted account, so this is belt and
+ // braces — and it also guarantees the dialog is only rendered where a pending
+ // retry exists, since useEmailAuth holds one only in login mode. A dialog
+ // whose confirm button silently does nothing is worse than no dialog.
+ const emailStageIsSignupPassword =
+ emailAuth.stage.name === "password" && emailAuth.stage.mode === "signup";
+ //
+ // Routed off the SAME most-recent-error rule as the banner. It used to check
+ // emailAuth.error first and fall back to the social one — the exact opposite
+ // precedence — so the dialog and the banner could disagree about which hook
+ // had won and describe two different accounts at once.
+ const deletedIsFromEmailHook =
+ activeError === emailError && emailError?.kind === "account_deleted";
+ const deletedError =
+ deletedIsFromEmailHook && !emailStageIsSignupPassword
+ ? emailAuth.stage.name === "forgot_email" || emailAuth.stage.name === "forgot_code"
+ ? ("forgot" as const)
+ : ("email" as const)
+ : activeError === error && error?.kind === "account_deleted"
+ ? ("social" as const)
+ : null;
+ // The email form is showing its own persistent "already registered" notice,
+ // so the banner must not duplicate it. See the render site below.
+ const switchedToLoginNotice =
+ emailAuth.stage.name === "password" &&
+ emailAuth.stage.switchedFromSignup === true;
+
+ /* A social sign-in rejected because the address is an email+password account
+ ("Your account is registered with an email and password. Sign in below").
+ The email flow is the way forward, so switch it to the SIGN-IN form — the
+ surface otherwise sat on the sign-up form, telling the user to sign in
+ below while showing them a registration form and an empty address box.
+
+ useEmailAuth already does this for its own failures (recoverToLogin), but a
+ Google rejection comes from useSocialLogin, which knows nothing about the
+ email stage machine. AuthFlow is the only place that sees both.
+
+ Note it can only flip the mode, not prefill the address: the social error
+ carries no email — that lives inside the provider token. */
+ const setEmailMode = emailAuth.setMode;
+ const socialWrongProviderIsEmail =
+ error?.kind === "wrong_provider" && error.provider === "email";
+ /* Fire ONCE per rejection, not on every render while the error is up.
+ Keying this on the live stage mode made it a lock instead of a correction:
+ the error lives in useSocialLogin, so emailAuth.setMode cannot clear it, and
+ every attempt to switch back to "Sign up" was immediately undone by this
+ effect on the next render — the toggle looked dead. The ref lets us steer
+ the user once and then leave the choice to them. */
+ const correctedForWrongProvider = useRef(false);
+ useEffect(() => {
+ if (!socialWrongProviderIsEmail) {
+ correctedForWrongProvider.current = false;
+ return;
+ }
+ if (!correctedForWrongProvider.current) {
+ correctedForWrongProvider.current = true;
+ setEmailMode("login");
+ }
+ }, [socialWrongProviderIsEmail, setEmailMode]);
+
+ const handleEscape = useCallback(() => {
+ // Android can hand off to Chrome; iOS cannot, so fall back to instructions.
+ if (!escapeToSystemBrowser(window.location.href)) setShowInstructions(true);
+ }, []);
+
+ const handleCopy = useCallback(async () => {
+ const ok = await copyLink(window.location.href);
+ setCopied(ok);
+ if (ok) setTimeout(() => setCopied(false), 2000);
+ }, []);
+
+ /* After a wrong-provider rejection we know exactly which provider owns the
+ email, so offer only that one — recovery becomes a single click instead of
+ another guess between several buttons.
+
+ "email" is deliberately NOT a narrowing. The narrowing exists to reduce a
+ row of social buttons down to the one that works; when the answer is our own
+ email/password provider there is nothing to reduce — that form is already
+ the screen. Treating it as one suppressed the back chevron and the stage
+ heading, which is how the user ended up on a dead-end screen with an empty
+ address box and no way out. */
+ const onlyProvider =
+ activeError?.kind === "wrong_provider" && activeError.provider !== "email"
+ ? activeError.provider
+ : null;
+
+ const stage = emailAuth.stage;
+ // Past the first step the user is inside a flow, so provider buttons are just
+ // noise — EXCEPT after a wrong-provider rejection, where the named provider is
+ // the only way forward and hiding it would strand the user on an error they
+ // cannot act on.
+ const midEmailFlow = stage.name !== "email" && onlyProvider === null;
+ // The email form hides for the mirror-image reason: once we know the account
+ // belongs to a social provider, a password is not a way in. (onlyProvider is
+ // never "email" — see above — so a narrowing always means "hide this form".)
+ const showEmailForm = onlyProvider === null;
+ // The password step reads differently depending on intent, so it is resolved
+ // here rather than from the static map.
+ const stageCopy =
+ onlyProvider !== null
+ ? undefined
+ : stage.name === "password"
+ ? stage.mode === "signup"
+ ? { title: "Create your account", subtitle: "Choose a password to finish signing up." }
+ : { title: "Enter your password", subtitle: "Sign in with your email and password." }
+ : STAGE_COPY[stage.name];
+
+ // One list so adding a provider back is a single entry. Google is the only
+ // social provider now (Apple and Microsoft were removed), but the list shape
+ // is what drives the divider, the narrowing below and the row layout, so it
+ // stays a list rather than a hardcoded button.
+ const providers = [
+ {
+ id: "google",
+ enabled: true,
+ render: () => (
+ /* GIS renders a Google-hosted iframe, so it must mount only once this
+ container is laid out — i.e. after the modal is open. */
+
+ ),
+ },
+ ].filter(
+ (p) =>
+ p.enabled &&
+ !midEmailFlow &&
+ (onlyProvider === null || onlyProvider === p.id)
+ );
+
+ const isPage = variant === "page";
+ COLUMN_WIDTH_CLASS = isPage ? "w-[340px]" : "w-[300px]";
+
+ return (
+ <>
+ {/* After a wrong-provider rejection the stage heading ("Enter your
+ password") contradicts what is on screen, so fall back to the
+ call site's own copy. */}
+
+ {midEmailFlow && (
+
+ )}
+
+ {stageCopy?.title ?? resolvedTitle}
+
+
+
+ {stageCopy?.subtitle ?? resolvedSubtitle}
+
+
+
+ {/* The spinner REPLACES the body only for social sign-in. Swapping the
+ email form out would unmount it, and remounting resets its field
+ state — so a rejected password would come back to an empty box and
+ the user could not act on the error they were just shown. During an
+ email request the form stays mounted and disables itself instead. */}
+ {signingIn ? (
+
+
+
+ {reactivating ? "Reactivating your account…" : "Signing you in…"}
+
+
+ ) : (
+
+ {/* In-app browsers block OAuth popups, so the provider buttons are
+ useless there — but email/password needs no popup and works
+ fine, so the escape notice now sits ABOVE the email form
+ rather than replacing every way in. */}
+ {inApp && (
+
+ )}
+
+ {/* Field-level failures render under the field they belong to, so
+ the message sits where the user is looking and where the fix
+ is. Only errors that are about the whole modal — the wrong
+ provider, a deleted account and its Reactivate button — stay up
+ here as a banner.
+
+ "Already registered" is excluded while the form is showing its
+ own persistent notice for it: the banner would say the same
+ thing twice, and would then vanish on the next submit while the
+ inline one (the accurate, lasting explanation) remains. */}
+ {activeError &&
+ !isFieldLevelError(activeError) &&
+ activeError.kind !== "account_deleted" &&
+ !(switchedToLoginNotice && isExistingAccountError(activeError)) && (
+
+ )}
+
+ {/* One fixed-width row per provider. Google Identity Services
+ renders its own iframe and does not honour `width` exactly, so
+ the row — not the button — defines the box; our own buttons
+ stretch to fill it and GIS is centred inside it. That keeps all
+ three the same width even though one is not ours to style. */}
+ {!inApp &&
+ providers.map((p) => (
+
+ )}
+
+ {/* Asks the one question the 403 raises. The email flow holds the typed
+ credential for the retry; the social flow holds the provider token. */}
+ {deletedError && (
+
+ )}
+ >
+ );
+}
+
+/**
+ * The staged email + password form.
+ *
+ * Every stage is a plain controlled form — no zod, no react-hook-form, matching
+ * the rest of the app (see ContactModal). The address is never probed for
+ * existence before the password step: an "is this registered?" endpoint would be
+ * an enumeration oracle with no other purpose, so instead everyone reaches the
+ * password step and the sign-in result disambiguates.
+ */
+function EmailAuthForm({
+ auth,
+ busy,
+ onDismissSocialError,
+}: {
+ auth: ReturnType;
+ busy: boolean;
+ /** Clears useSocialLogin's error, which auth.setMode cannot reach. */
+ onDismissSocialError?: () => void;
+}) {
+ const { stage } = auth;
+ // The address lives on the stage, not in local state: an error can route the
+ // user between stages, and a remount would wipe a local copy — which is how
+ // they ended up staring at an empty box under "sign in with your password".
+ const email = stage.name === "email" ? stage.email : "";
+ const setEmail = auth.setEmailValue;
+ const [password, setPassword] = useState("");
+ const [confirmPassword, setConfirmPassword] = useState("");
+ const [code, setCode] = useState("");
+ const [newPassword, setNewPassword] = useState("");
+ const [showPassword, setShowPassword] = useState(false);
+
+ // Clear the step-local fields on a stage CHANGE, so a code typed for a burned
+ // attempt doesn't linger into the next step. Deliberately keyed on the stage
+ // name only: a failed request leaves the stage unchanged, so the password the
+ // user just typed survives for them to correct or to register with.
+ const stageName = stage.name;
+ useEffect(() => {
+ setCode("");
+ setNewPassword("");
+ setConfirmPassword("");
+ setShowPassword(false);
+ if (stageName === "email" || stageName === "password") setPassword("");
+ }, [stageName]);
+
+ // The signup -> sign-in flip is the one transition that does NOT change
+ // stage.name, so the effect above cannot catch it and the password the user
+ // chose for a NEW account would stay in the box under a "Sign in" button.
+ // Submitting that is either a confusing "email and password don't match" that
+ // buries the real reason, or — if the two happen to match — an unrequested
+ // sign-in. Clear it and make them type the password for the account that
+ // actually exists.
+ const switchedFromSignup =
+ stage.name === "password" && stage.switchedFromSignup === true;
+ useEffect(() => {
+ if (switchedFromSignup) {
+ setPassword("");
+ setConfirmPassword("");
+ }
+ }, [switchedFromSignup]);
+
+ const stageEmail = "email" in stage ? stage.email : "";
+
+ switch (stage.name) {
+ case "email": {
+ const signup = stage.mode === "signup";
+ return (
+
+ );
+ }
+
+ case "password": {
+ const signup = stage.mode === "signup";
+ // Only complain about a mismatch once they've actually started the second
+ // field — flagging one they haven't reached yet reads as an error.
+ const mismatch = signup && confirmPassword.length > 0 && confirmPassword !== password;
+ // Deliberately NOT gated on the password policy or the confirm match.
+ //
+ // The live checklist and the mismatch hint already guide someone writing a
+ // real new password. But when the address ALREADY has an account, none of
+ // that is the point: blocking submit means the request is never made, so
+ // the one thing the user needs to hear — "this account exists, sign in" —
+ // can never be said, and pressing the button appears to do nothing. Let it
+ // through and let the server answer; a genuine policy violation comes back
+ // as a 422 and renders inline under the field, which is the same place the
+ // checklist already points.
+ const canSubmit = !busy && Boolean(password);
+ return (
+
+ );
+ }
+
+ case "otp":
+ return (
+ auth.submitCode(stageEmail, code)}
+ onResend={() => auth.resendCode(stageEmail)}
+ />
+ );
+
+ case "forgot_email":
+ return (
+
+ );
+
+ case "forgot_code":
+ return (
+ auth.submitResetCode(stageEmail, code)}
+ onResend={() => auth.requestResetCode(stageEmail)}
+ />
+ );
+
+ case "forgot_password": {
+ // Setting a password, so it gets the same rules and the same confirmation
+ // as signup — the server enforces them here either way.
+ const resetMismatch = confirmPassword.length > 0 && confirmPassword !== newPassword;
+ const resetOk =
+ !busy && passwordMeetsPolicy(newPassword) && confirmPassword === newPassword;
+ return (
+
+ );
+ }
+
+ default:
+ return null;
+ }
+}
+
+/**
+ * Password field with a reveal toggle.
+ *
+ * The toggle is icon-only, so it carries an aria-label that flips with the state
+ * — without one it is an unlabelled button to a screen reader. type="button"
+ * keeps it from submitting the form it sits inside.
+ */
+function PasswordInput({
+ id,
+ label,
+ value,
+ onChange,
+ placeholder,
+ autoComplete,
+ autoFocus,
+ visible,
+ onToggleVisible,
+ invalid,
+}: {
+ id: string;
+ /** The field's accessible name. Not rendered — the design is placeholder-only,
+ * so this is what a screen reader announces instead. */
+ label: string;
+ value: string;
+ onChange: (v: string) => void;
+ /** Hint inside the box; falls back to the label when omitted. */
+ placeholder?: string;
+ autoComplete: string;
+ autoFocus?: boolean;
+ visible: boolean;
+ onToggleVisible: () => void;
+ invalid?: boolean;
+}) {
+ return (
+
+ );
+}
+
+/**
+ * Confirmation dialog for reactivating a soft-deleted account.
+ *
+ * Its own dialog rather than a button inside an error banner, because this is a
+ * consequential, one-way choice: the backend restores the account as a FREE user
+ * and clears purchased bonuses. A confirm step with an explicit Cancel makes the
+ * trade visible instead of hiding it behind a single click on a red notice.
+ *
+ * Rendered ABOVE the login modal (z-[110] over its z-[100]) so it reads as a
+ * question about the screen behind it, and the backdrop is inert while the
+ * request is in flight to avoid orphaning it.
+ */
+function ReactivateConfirm({
+ busy,
+ body,
+ onConfirm,
+ onCancel,
+}: {
+ busy: boolean;
+ /** What happens on confirm. Differs by route: reactivating from the login step
+ * signs the user straight in, while from the forgot-password step it only
+ * emails a code — saying so avoids promising a session they won't get yet. */
+ body: string;
+ onConfirm: () => void;
+ onCancel: () => void;
+}) {
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape" && !busy) onCancel();
+ };
+ document.addEventListener("keydown", onKey);
+ return () => document.removeEventListener("keydown", onKey);
+ }, [busy, onCancel]);
+
+ return ReactDOM.createPortal(
+
+
+
+
+ Reactivate your account?
+
+
+ {body}
+
+
+
+
+
+
+
,
+ document.body
+ );
+}
+
+/**
+ * In-app browsers (Instagram, LinkedIn, TikTok…) block OAuth popups, and the
+ * provider buttons fail silently there. We show no sign-in options at all —
+ * only the way out to a real browser.
+ */
+function InAppEscape({
+ showInstructions,
+ copied,
+ onEscape,
+ onCopy,
+}: {
+ showInstructions: boolean;
+ copied: boolean;
+ onEscape: () => void;
+ onCopy: () => void;
+}) {
+ return (
+
+
+
Open this page in your browser to sign in
+
+ Sign-in isn't allowed inside this in-app browser. Tap the{" "}
+ ⋯ menu above and choose{" "}
+ “Open in Safari” (or{" "}
+ “Open in Browser”), then sign in.
+
+ {showInstructions && (
+
+ Copy the link below if the menu doesn't offer that option.
+
+ )}
+
+
+
+
+
+
+ );
+}
diff --git a/frontend/src/components/auth/LoginModal.tsx b/frontend/src/components/auth/LoginModal.tsx
index 4673055d3d0af9e3d0df4ff99b3251ee2e058176..90ded3d0cadfd2acda22fa69fee9736f9b5c44df 100644
--- a/frontend/src/components/auth/LoginModal.tsx
+++ b/frontend/src/components/auth/LoginModal.tsx
@@ -1,22 +1,9 @@
-import { useCallback, useEffect, useState } from "react";
+import { useEffect } from "react";
import ReactDOM from "react-dom";
-import { GoogleLogin } from "@react-oauth/google";
-import AppleAuthButton from "../public/AppleAuthButton";
-import MicrosoftAuthButton from "../public/MicrosoftAuthButton";
-import { useSocialLogin } from "../../hooks/useSocialLogin";
-import { isAppleSignInConfigured } from "../../lib/appleSignIn";
-import { isMicrosoftSignInConfigured } from "../../lib/microsoftSignIn";
-import {
- copyLink,
- detectInAppBrowser,
- escapeToSystemBrowser,
-} from "../../lib/inAppBrowser";
+import AuthFlow, { type LoginModalCopy } from "./AuthFlow";
-export interface LoginModalCopy {
- title?: string;
- subtitle?: string;
-}
+export type { LoginModalCopy };
interface LoginModalProps extends LoginModalCopy {
open: boolean;
@@ -27,126 +14,45 @@ interface LoginModalProps extends LoginModalCopy {
skipRedirect?: boolean;
}
-const DEFAULT_TITLE = "Sign in to Blog2Video";
-const DEFAULT_SUBTITLE = "Choose how you'd like to continue.";
-
/**
- * The single sign-in surface for the whole app.
+ * Dialog chrome around the shared sign-in surface.
+ *
+ * The flow itself lives in AuthFlow, which the full-page /signin and /signup
+ * routes render too — so this file is only the portal, backdrop and close
+ * button. Keeping one implementation is what stops the modal and the page
+ * drifting apart on things like the 409 provider narrowing or the burned-code
+ * recovery.
*
- * Every "Get started" / "Sign in" CTA opens this modal and the user picks a
- * provider here, so provider choice, error recovery, and the in-app-browser
- * escape flow are implemented once instead of per page.
+ * Still used by the in-place tool gates (SignupGate, the /tools widgets, the
+ * support widget), which sign the user in WITHOUT navigating away so a
+ * half-filled form survives. Plain CTAs link to /signin instead.
*/
export default function LoginModal({
open,
onClose,
onSuccess,
skipRedirect,
- title = DEFAULT_TITLE,
- subtitle = DEFAULT_SUBTITLE,
+ title,
+ subtitle,
}: LoginModalProps) {
- const {
- signInWithGoogle,
- signInWithApple,
- signInWithMicrosoft,
- onGoogleError,
- signingIn,
- error,
- reactivate,
- reset,
- } = useSocialLogin({ onSuccess, skipRedirect });
-
- // Only consult the UA once the modal opens; the result never changes for a
- // given page load, but this keeps the check out of the render path.
- const [inApp, setInApp] = useState(false);
- const [showInstructions, setShowInstructions] = useState(false);
- const [copied, setCopied] = useState(false);
-
- useEffect(() => {
- if (!open) return;
- setInApp(detectInAppBrowser().isInApp);
- setShowInstructions(false);
- setCopied(false);
- reset();
- }, [open, reset]);
-
- // Escape closes, and the backdrop is inert while a sign-in is in flight so a
- // stray click can't orphan an in-progress exchange.
+ // Escape closes. The backdrop stays clickable here rather than tracking the
+ // flow's busy state, which now lives inside AuthFlow.
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => {
- if (e.key === "Escape" && !signingIn) onClose();
+ if (e.key === "Escape") onClose();
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
- }, [open, signingIn, onClose]);
-
- const handleEscape = useCallback(() => {
- // Android can hand off to Chrome; iOS cannot, so fall back to instructions.
- if (!escapeToSystemBrowser(window.location.href)) setShowInstructions(true);
- }, []);
-
- const handleCopy = useCallback(async () => {
- const ok = await copyLink(window.location.href);
- setCopied(ok);
- if (ok) setTimeout(() => setCopied(false), 2000);
- }, []);
+ }, [open, onClose]);
if (!open) return null;
- // After a wrong-provider rejection we know exactly which provider owns the
- // email, so offer only that one — recovery becomes a single click instead of
- // another guess between several buttons.
- const onlyProvider = error?.kind === "wrong_provider" ? error.provider : null;
-
- // One list so adding a provider is a single entry. A provider whose client id
- // isn't configured hides itself, which is what makes this safe to ship before
- // the provider's console setup is done.
- const providers = [
- {
- id: "apple",
- enabled: isAppleSignInConfigured(),
- render: () => (
-
- ),
- },
- {
- id: "google",
- enabled: true,
- render: () => (
- /* GIS renders a Google-hosted iframe, so it must mount only once this
- container is laid out — i.e. after the modal is open. */
-
- ),
- },
- {
- id: "microsoft",
- enabled: isMicrosoftSignInConfigured(),
- render: () => (
-
- ),
- },
- ].filter((p) => p.enabled && (onlyProvider === null || onlyProvider === p.id));
-
return ReactDOM.createPortal(
@@ -167,132 +72,16 @@ export default function LoginModal({
-
- {title}
-
-
{subtitle}
-
-
- {inApp ? (
-
- ) : signingIn ? (
-
-
-
Signing you in…
-
- ) : (
-
- {error && }
-
- {/* One fixed-width row per provider. Google Identity Services
- renders its own iframe and does not honour `width` exactly, so
- the row — not the button — defines the box; our own buttons
- stretch to fill it and GIS is centred inside it. That keeps all
- three the same width even though one is not ours to style. */}
- {providers.map((p) => (
-
- );
-}
-
-/**
- * In-app browsers (Instagram, LinkedIn, TikTok…) block OAuth popups, and the
- * provider buttons fail silently there. We show no sign-in options at all —
- * only the way out to a real browser.
- */
-function InAppEscape({
- showInstructions,
- copied,
- onEscape,
- onCopy,
-}: {
- showInstructions: boolean;
- copied: boolean;
- onEscape: () => void;
- onCopy: () => void;
-}) {
- return (
-
-
-
Open this page in your browser to sign in
-
- Sign-in isn't allowed inside this in-app browser. Tap the{" "}
- ⋯ menu above and choose{" "}
- “Open in Safari” (or{" "}
- “Open in Browser”), then sign in.
-
- {showInstructions && (
-
- Copy the link below if the menu doesn't offer that option.
-
- )}
-
-
-
-
-
-
- );
-}
diff --git a/frontend/src/components/public/AppleAuthButton.tsx b/frontend/src/components/public/AppleAuthButton.tsx
deleted file mode 100644
index 5e3df1864841b843ea484bf132b0d4f35552bf4a..0000000000000000000000000000000000000000
--- a/frontend/src/components/public/AppleAuthButton.tsx
+++ /dev/null
@@ -1,50 +0,0 @@
-/**
- * "Sign in with Apple" button.
- *
- * Styled to Apple's Human Interface Guidelines — white pill, black Apple logo,
- * the exact wording. Stretches to fill its row in LoginModal, which is what
- * keeps it the same width as the Google button (whose iframe we cannot size
- * directly).
- */
-interface AppleAuthButtonProps {
- onClick: () => void;
- disabled?: boolean;
- /** Match the Google button's width, in px, so the two pills align. */
- width?: string;
- text?: "signin_with" | "continue_with";
-}
-
-export default function AppleAuthButton({
- onClick,
- disabled = false,
- text = "continue_with",
-}: AppleAuthButtonProps) {
- const label = text === "signin_with" ? "Sign in with Apple" : "Continue with Apple";
-
- return (
-
- );
-}
diff --git a/frontend/src/components/public/MicrosoftAuthButton.tsx b/frontend/src/components/public/MicrosoftAuthButton.tsx
deleted file mode 100644
index 6b554cf73013af084e273820561dcb8c769a5d56..0000000000000000000000000000000000000000
--- a/frontend/src/components/public/MicrosoftAuthButton.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-/**
- * "Sign in with Microsoft" button.
- *
- * Follows Microsoft's branding guidance — white surface, grey border, the
- * four-square logo in its fixed colours, and the prescribed wording. Stretches
- * to fill its row in LoginModal, which is what keeps it the same width as the
- * Google button (whose iframe we cannot size directly).
- */
-interface MicrosoftAuthButtonProps {
- onClick: () => void;
- disabled?: boolean;
- text?: "signin_with" | "continue_with";
-}
-
-export default function MicrosoftAuthButton({
- onClick,
- disabled = false,
- text = "continue_with",
-}: MicrosoftAuthButtonProps) {
- const label =
- text === "signin_with" ? "Sign in with Microsoft" : "Continue with Microsoft";
-
- return (
-
- );
-}
diff --git a/frontend/src/components/remotion/imageBoxConfig.ts b/frontend/src/components/remotion/imageBoxConfig.ts
index 3dcd789542c2121ca0108f2ee67bcd164e47dfd2..026cafe2643160517e40d00b484c4ed41aa5409c 100644
--- a/frontend/src/components/remotion/imageBoxConfig.ts
+++ b/frontend/src/components/remotion/imageBoxConfig.ts
@@ -562,10 +562,12 @@ export const LAYOUT_IMAGE_BOX_DIMS: Record = {
// pull_quote__v2 / ending_socials__v2 are intentionally absent — they render
// no image (both bases are in meta.json `layouts_without_image`).
- // Polaroid-style card, tilted, pinned right (landscape) / centred (portrait).
+ // Polaroid-style card, tilted, pinned right (landscape) / bottom (portrait).
news_headline: {
landscape: { w: 0.435, h: 0.594 }, // measured 557 × 428
- portrait: { w: 0.841, h: 0.381 }, // measured 606 × 487
+ // Portrait card moved from top:15% to bottom:6% and 35%→34% tall so the
+ // copy no longer overlaps it; height re-derived accordingly.
+ portrait: { w: 0.841, h: 0.370 }, // 0.34 frame height + the card's padding
},
// Tilted photo card beside the lead column.
diff --git a/frontend/src/components/remotion/newspaper/layouts/NewsHeadline.tsx b/frontend/src/components/remotion/newspaper/layouts/NewsHeadline.tsx
index 9ee57e4b55a7f25ac09a7ad921ebcf3770a48e40..b70b8e26a4088e522ad1a75d7a6ed5e6c32674d1 100644
--- a/frontend/src/components/remotion/newspaper/layouts/NewsHeadline.tsx
+++ b/frontend/src/components/remotion/newspaper/layouts/NewsHeadline.tsx
@@ -212,7 +212,7 @@ export const NewsHeadline: React.FC<
: [words[0], words[Math.floor(words.length / 2)], words[words.length - 1]];
// Calculate description font size for relative scaling
- const actualDescriptionFontSize = descriptionFontSize ?? (p ? 35 : 28);
+ const actualDescriptionFontSize = descriptionFontSize ?? (p ? 37 : 28);
const categoryBaseFontSize = p ? 28 : 24; // Base for category without descriptionFontSize
const authorBaseFontSize = p ? 20 : 16; // Base for author without descriptionFontSize
// A clip fills the same visual slot as a still, so it must not
@@ -233,7 +233,7 @@ export const NewsHeadline: React.FC<
const titleRef = React.useRef(null);
const categoryRef = React.useRef(null);
- const actualTitleFontSize = titleFontSize ?? (p ? 77 : 68);
+ const actualTitleFontSize = titleFontSize ?? (p ? 68 : 62);
/* Stage 1 — the headline fits its own share of the column.
The title is `flex-shrink:0`, so its clientHeight always equals its content
@@ -243,7 +243,11 @@ export const NewsHeadline: React.FC<
fits inside its share is left completely alone. */
const titleBudgetPx = React.useMemo(() => {
// Container height minus its vertical padding (percentages of the frame).
- const padFrac = portraitNoImage ? 0.12 + 0.1 : p ? 0.15 : 0.14;
+ // Portrait-with-image: 12% top pad + the picture's MINIMUM 25.5% band, so
+ // ~62.5% of the frame is available to copy. The original 0.15 overstated
+ // the column by ~493px on a 1280-tall frame, which is what let the auto-fit
+ // grow the headline straight down into the photo.
+ const padFrac = portraitNoImage ? 0.12 + 0.1 : p ? 0.375 : 0.14;
const inner = videoHeight * (1 - padFrac);
// The headline may claim at most this much of the usable column; the rest
// is reserved for the category chip, byline and narration.
@@ -284,15 +288,22 @@ export const NewsHeadline: React.FC<
of those is affected by centering. */
const [categoryH, setCategoryH] = React.useState(0);
const [titleH, setTitleH] = React.useState(0);
+ /* The narration's REAL rendered height, not its budget. Needed because a
+ user-set font size makes useFitText a no-op (minPx === targetPx), so the
+ copy keeps its chosen size and simply occupies more room — the case where
+ the picture has to give way instead of the text being clipped. */
+ const [narrationH, setNarrationH] = React.useState(0);
React.useLayoutEffect(() => {
setCategoryH(categoryRef.current?.offsetHeight ?? 0);
setTitleH(titleRef.current?.offsetHeight ?? 0);
+ setNarrationH(narrationRef.current?.offsetHeight ?? 0);
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [titlePx, cat, stats, title]);
+ }, [titlePx, cat, stats, title, narration, actualDescriptionFontSize, descriptionFontSizeIsUserSet, videoHeight]);
const narrationBudgetPx = React.useMemo(() => {
if (portraitNoImage) return undefined; // that variant's own clientHeight IS the true budget (single flex:1 child).
- const padFrac = p ? 0.15 : 0.14;
+ // Mirrors titleBudgetPx: the picture's minimum band is not available to copy.
+ const padFrac = p ? 0.375 : 0.14;
const inner = videoHeight * (1 - padFrac);
const categoryMargin = p ? 20 : 30;
const titleMargin = p ? 40 : 36;
@@ -302,6 +313,35 @@ export const NewsHeadline: React.FC<
return Math.max(1, (inner - used) * 0.92);
}, [videoHeight, p, portraitNoImage, categoryH, titleH]);
+ /* ── Portrait picture band ────────────────────────────────────────────────
+ The card's height is derived, not fixed. The copy is laid out first and the
+ picture takes whatever is left below it, so when the text grows — a long
+ headline, a long narration, or a user-set font size that useFitText is not
+ allowed to shrink — the IMAGE COMPRESSES instead of the copy being clipped
+ or running underneath the card.
+
+ Clamped at both ends: never taller than 42% (so the picture stays a
+ picture and not the whole page), never shorter than 16% (so heavy copy
+ leaves a photo that is still recognisable rather than a sliver). */
+ const PORTRAIT_CARD_MAX_FRAC = 0.42;
+ const PORTRAIT_CARD_MIN_FRAC = 0.16;
+ const PORTRAIT_CARD_BOTTOM_FRAC = 0.06;
+ const portraitCardHeightFrac = React.useMemo(() => {
+ if (!p || !hasVisual) return PORTRAIT_CARD_MAX_FRAC;
+ const topPad = 0.12 * videoHeight;
+ const categoryMargin = 20;
+ const titleMargin = 40;
+ const gap = 0.035 * videoHeight;
+ // Where the copy actually ends, measured rather than assumed.
+ const textBottom =
+ topPad + categoryH + categoryMargin + titleH + titleMargin + narrationH;
+ const leftover =
+ videoHeight - textBottom - gap - PORTRAIT_CARD_BOTTOM_FRAC * videoHeight;
+ const frac = leftover / videoHeight;
+ return Math.min(PORTRAIT_CARD_MAX_FRAC, Math.max(PORTRAIT_CARD_MIN_FRAC, frac));
+ }, [p, hasVisual, videoHeight, categoryH, titleH, narrationH]);
+
+
const { px: narrationPx } = useFitText(
narrationRef,
actualDescriptionFontSize,
@@ -336,12 +376,21 @@ export const NewsHeadline: React.FC<
(null);
const narrationRef = React.useRef(null);
- const titleTargetPx = titleFontSize ?? (p ? 54 : 54);
- const narrationTargetPx = descriptionFontSize ?? (p ? 29 : 27);
+ const titleTargetPx = titleFontSize ?? (p ? 65 : 54);
+ const narrationTargetPx = descriptionFontSize ?? (p ? 32 : 27);
const stackBudgetPx = Math.round(videoHeight * (hasVisual ? (p ? 0.34 : 0.32) : p ? 0.55 : 0.5));
const titleBudgetPx = Math.round(stackBudgetPx * (narration ? 0.66 : 1));
diff --git a/frontend/src/components/remotion/newspaper/layouts/NewsHeadlineV3.tsx b/frontend/src/components/remotion/newspaper/layouts/NewsHeadlineV3.tsx
index fb086475066a08b7c018efcfc9362ef4b9d5dbd4..293d37a1deb5bdee9b746e4e3622a5d6c1b00c3f 100644
--- a/frontend/src/components/remotion/newspaper/layouts/NewsHeadlineV3.tsx
+++ b/frontend/src/components/remotion/newspaper/layouts/NewsHeadlineV3.tsx
@@ -141,8 +141,8 @@ export const NewsHeadlineV3: React.FC<
first ten frames, in the equivalent newspaper opening scene). */
const titleRef = React.useRef(null);
const narrationRef = React.useRef(null);
- const titleTargetPx = titleFontSize ?? (p ? 54 : 50);
- const narrationTargetPx = descriptionFontSize ?? (p ? 31 : 26);
+ const titleTargetPx = titleFontSize ?? (p ? 66 : 50);
+ const narrationTargetPx = descriptionFontSize ?? (p ? 33 : 26);
const stackBudgetPx = Math.round(videoHeight * (hasVisual ? (p ? 0.32 : 0.62) : p ? 0.6 : 0.62));
const titleBudgetPx = Math.round(stackBudgetPx * (narration ? 0.6 : 1));
diff --git a/frontend/src/components/remotion/nightfall/layouts/SplitGlass.tsx b/frontend/src/components/remotion/nightfall/layouts/SplitGlass.tsx
index 080daa051e3a8679e4cef4d5338f035953682777..b7f36d225a8cdaaa4558e11f5b1030166b80c50b 100644
--- a/frontend/src/components/remotion/nightfall/layouts/SplitGlass.tsx
+++ b/frontend/src/components/remotion/nightfall/layouts/SplitGlass.tsx
@@ -79,10 +79,14 @@ export const SplitGlass: React.FC = ({
// Portrait specific animation timings and values
const pEntryStart = 15;
const pEntrySettled = pEntryStart + 40; // When entry animation settles
- const pHoldDuration = 60; // How long cards are visible and stable
+ // Cards hold well past the point the text is readable before leaving, so the
+ // exit reads as a deliberate beat rather than the cards drifting off mid-read.
+ const pHoldDuration = 85;
const pHoldEnd = pEntrySettled + pHoldDuration;
const pExitStart = pHoldEnd; // When exit animation starts
- const pExitEnd = pExitStart + 30; // When exit animation finishes
+ // Short window: once they go, they go. A long exit made the cards hang
+ // around half-faded, which read as sinking rather than flowing away.
+ const pExitEnd = pExitStart + 20; // When exit animation finishes
// Portrait card opacity (fade in, stay, fade out)
const pCardOpacity = interpolate(
@@ -92,11 +96,13 @@ export const SplitGlass: React.FC = ({
{ extrapolateRight: "clamp" }
);
- // Portrait card Y position (start high, settle, stay, drop down)
+ // Portrait card Y position (start high, settle, stay, sweep away)
+ // Travels well past the old 300px so the cards clear frame while the fade
+ // is still running — they flow out instead of fading in place.
const pCardTransformY = interpolate(
frame,
[pEntryStart, pEntrySettled, pExitStart, pExitEnd],
- [-300, 0, 0, 300],
+ [-300, 0, 0, 700],
{ extrapolateRight: "clamp" }
);
diff --git a/frontend/src/hooks/useEmailAuth.ts b/frontend/src/hooks/useEmailAuth.ts
new file mode 100644
index 0000000000000000000000000000000000000000..47cb8e9af5a5fdd337baa1948426f51c347295a5
--- /dev/null
+++ b/frontend/src/hooks/useEmailAuth.ts
@@ -0,0 +1,411 @@
+import { useCallback, useState } from "react";
+
+import {
+ emailLogin,
+ emailRegisterResend,
+ emailRegisterStart,
+ emailRegisterVerify,
+ forgotPasswordCheck,
+ forgotPasswordComplete,
+ forgotPasswordStart,
+} from "../api/client";
+import { useAuth } from "./useAuth";
+import { usePostLoginRedirect } from "./usePostLoginRedirect";
+import { parseLoginError, type LoginError } from "./useSocialLogin";
+import { getErrorMessage } from "../contexts/ErrorModalContext";
+
+/**
+ * Built-in email + password sign-in, as a staged flow inside the login modal.
+ *
+ * Mirrors useSocialLogin's contract (same onSuccess/skipRedirect options, the
+ * same LoginError shape, the same held-credential reactivation retry) so the
+ * modal can treat both paths identically and the 409 wrong-provider recovery
+ * works the same whichever one produced it.
+ */
+
+/** Seconds between code resends; matches RESEND_COOLDOWN_SECONDS server-side. */
+const RESEND_COOLDOWN_SECONDS = 60;
+
+/**
+ * Which of the two intents the user picked on the first step.
+ *
+ * It only changes wording and which request the password step fires — it is NOT
+ * a security boundary. Signing up with an address that already exists still
+ * returns 409, and logging in with one that doesn't still returns the same
+ * ambiguous 401, so picking the "wrong" one costs a click, never information.
+ */
+export type EmailMode = "login" | "signup";
+
+export type EmailStage =
+ // `email` carries the address too, so stepping back (or being routed back by
+ // an error) never makes the user retype what they already entered.
+ | { name: "email"; mode: EmailMode; email: string }
+ /**
+ * `switchedFromSignup` marks the one transition the user did not ask for:
+ * they submitted a SIGNUP and the address turned out to already exist, so we
+ * flipped them to the sign-in form. The form reads it to clear the carried-over
+ * password and keep the "account already exists" notice up.
+ *
+ * Without it the signup password sat in a login box under a "Sign in" button,
+ * so the next submit either said "email and password don't match" (burying the
+ * real reason) or — when the two passwords happened to match — silently signed
+ * them in, which is not what anyone clicking "Sign up" asked for.
+ */
+ | { name: "password"; email: string; mode: EmailMode; switchedFromSignup?: boolean }
+ | { name: "otp"; email: string; resendAt: number }
+ | { name: "forgot_email"; email: string }
+ | { name: "forgot_code"; email: string; resendAt: number }
+ | { name: "forgot_password"; email: string; code: string };
+
+interface UseEmailAuthOptions {
+ onSuccess?: () => void;
+ skipRedirect?: boolean;
+ /** Which intent the surface opens in. Defaults to "signup": most people
+ * reaching a sign-in surface from a CTA are new, and an existing user is one
+ * click from the "Already have an account? Sign in" toggle. /signin passes
+ * "login" explicitly so that route still opens on the sign-in form. */
+ initialMode?: EmailMode;
+}
+
+function resendAtFrom(resendIn?: number): number {
+ return Date.now() + (resendIn ?? RESEND_COOLDOWN_SECONDS) * 1000;
+}
+
+export function useEmailAuth({
+ onSuccess,
+ skipRedirect = false,
+ initialMode = "signup",
+}: UseEmailAuthOptions = {}) {
+ const { login } = useAuth();
+ const redirectAfterLogin = usePostLoginRedirect();
+
+ const [stage, setStage] = useState({ name: "email", mode: initialMode, email: "" });
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState(null);
+ /**
+ * What the account-deleted prompt should retry, held exactly as useSocialLogin
+ * holds the provider token.
+ *
+ * Two shapes, because a deleted account can be met on two different steps and
+ * they are reactivated by different requests:
+ * login — the typed credential; retried as emailLogin(?reactivate=true).
+ * forgot — the address alone; retried as forgotPasswordStart(?reactivate=true).
+ * The forgot case has no password to hold by definition, which is why it can't
+ * reuse the login retry — that was the bug: `reactivate` bailed on a null
+ * `pending` and the confirm button did nothing.
+ */
+ type PendingReactivation =
+ | { via: "login"; email: string; password: string }
+ | { via: "forgot"; email: string };
+ const [pending, setPending] = useState(null);
+ /** True while the in-flight request is a reactivation rather than a sign-in.
+ * `busy` alone can't distinguish them, and the two need different wording. */
+ const [reactivating, setReactivating] = useState(false);
+
+ const finish = useCallback(
+ async (token: string, user: Parameters[1]) => {
+ localStorage.removeItem("b2v_ref_code");
+ login(token, user);
+ onSuccess?.();
+ if (!skipRedirect) await redirectAfterLogin();
+ },
+ [login, redirectAfterLogin, onSuccess, skipRedirect]
+ );
+
+ /** Switch between "Log in" and "Sign up" on the first step. */
+ const setMode = useCallback((mode: EmailMode) => {
+ setError(null);
+ setStage((s) =>
+ s.name === "email"
+ ? { name: "email", mode, email: s.email }
+ : s.name === "password"
+ ? { name: "password", email: s.email, mode }
+ : s
+ );
+ }, []);
+
+ /** Step 1: an address was entered. We never probe whether it exists — that
+ * would be an account-existence oracle with no other purpose — so both modes
+ * go to the password step and the request's outcome disambiguates. */
+ const submitEmail = useCallback((email: string, mode: EmailMode) => {
+ setError(null);
+ setStage({ name: "password", email: email.trim().toLowerCase(), mode });
+ }, []);
+
+ /** Keep the stage's address in step with the field as the user types, so any
+ * error that routes them elsewhere still has it. */
+ const setEmailValue = useCallback((email: string) => {
+ setStage((s) => (s.name === "email" ? { ...s, email } : s));
+ }, []);
+
+ /**
+ * "This address already has a password account" — however it was phrased.
+ *
+ * The backend says this two ways: `email_already_registered` when signup finds
+ * a live account, and a `wrong_provider` 409 naming "email" when the account
+ * is found by the shared identity check. They mean the same thing to the user,
+ * and every path that can raise either must route to the SAME place, or they
+ * end up reading "sign in with your password" on a screen that has no password
+ * field — and, worse, an empty email box they must retype.
+ */
+ const isExistingEmailAccount = (parsed: LoginError) =>
+ parsed.kind === "email_already_registered" ||
+ (parsed.kind === "wrong_provider" && parsed.provider === "email");
+
+ /** Step 2. In login mode this signs in; in signup mode it requests a code.
+ * Either way a mismatch between the mode and reality is recoverable in one
+ * click — the errors below flip the user to the other mode rather than
+ * dead-ending them. */
+ const submitPassword = useCallback(
+ async (email: string, password: string, mode: EmailMode) => {
+ setBusy(true);
+ setError(null);
+ try {
+ if (mode === "signup") {
+ const res = await emailRegisterStart(email, password);
+ setStage({ name: "otp", email, resendAt: resendAtFrom(res.data.resend_in) });
+ setBusy(false);
+ return;
+ }
+ const res = await emailLogin(email, password);
+ await finish(res.data.access_token, res.data.user);
+ } catch (err) {
+ const parsed = parseLoginError(err);
+ // Only a LOGIN can offer reactivation. The signup endpoint answers
+ // `email_already_registered` for a deleted account rather than 403, so
+ // this should be unreachable in signup mode — but the mode gate stays as
+ // defence in depth: holding a freshly-typed signup password as the
+ // credential for an existing account would let the confirm button sign
+ // someone in with a password that account never had.
+ if (parsed.kind === "account_deleted" && mode === "login") {
+ setPending({ via: "login", email, password });
+ }
+ // Signed up with an address that already exists -> they meant to log in.
+ // Flagged as an involuntary switch so the form drops the signup password
+ // instead of offering it for one-click sign-in under a new label.
+ if (isExistingEmailAccount(parsed)) {
+ setStage({ name: "password", email, mode: "login", switchedFromSignup: true });
+ }
+ setError(parsed);
+ setBusy(false);
+ }
+ },
+ [finish]
+ );
+
+ const submitCode = useCallback(
+ async (email: string, code: string) => {
+ setBusy(true);
+ setError(null);
+ try {
+ const refCode = localStorage.getItem("b2v_ref_code");
+ const res = await emailRegisterVerify(email, code, refCode);
+ await finish(res.data.access_token, res.data.user);
+ } catch (err) {
+ const parsed = parseLoginError(err);
+ // A burned code can't be retried — send them back to start over.
+ if (parsed.kind === "code_burned") setStage({ name: "password", email, mode: "signup" });
+ // Someone registered this address while the code was in flight, so the
+ // pending signup is moot — hand them the sign-in form for it.
+ else if (isExistingEmailAccount(parsed)) {
+ setStage({ name: "password", email, mode: "login", switchedFromSignup: true });
+ }
+ setError(parsed);
+ setBusy(false);
+ }
+ },
+ [finish]
+ );
+
+ const resendCode = useCallback(async (email: string) => {
+ setBusy(true);
+ setError(null);
+ try {
+ const res = await emailRegisterResend(email);
+ setStage({ name: "otp", email, resendAt: resendAtFrom(res.data.resend_in) });
+ setBusy(false);
+ } catch (err) {
+ const parsed = parseLoginError(err);
+ // Cooldown: keep the user on the code step, just re-arm the timer.
+ if (parsed.kind === "resend_cooldown") {
+ setStage({ name: "otp", email, resendAt: resendAtFrom(parsed.retryAfter) });
+ } else if (isExistingEmailAccount(parsed)) {
+ setStage({ name: "password", email, mode: "login", switchedFromSignup: true });
+ }
+ setError(parsed);
+ setBusy(false);
+ }
+ }, []);
+
+ // ─── Forgot password ──────────────────────────────────────────────────
+
+ const startForgot = useCallback((email: string) => {
+ setError(null);
+ setStage({ name: "forgot_email", email });
+ }, []);
+
+ /** Ask for a reset code. `confirmReactivate` revives a soft-deleted account
+ * first; it still only emails a code, so this never signs anyone in. */
+ const requestResetCode = useCallback(async (email: string, confirmReactivate = false) => {
+ setBusy(true);
+ if (confirmReactivate) setReactivating(true);
+ setError(null);
+ try {
+ const res = await forgotPasswordStart(email, confirmReactivate);
+ setPending(null);
+ setStage({ name: "forgot_code", email, resendAt: resendAtFrom(res.data.resend_in) });
+ setBusy(false);
+ setReactivating(false);
+ } catch (err) {
+ const parsed = parseLoginError(err);
+ // Deleted account: hold the address so the confirm dialog can retry this
+ // same request with ?reactivate=true. There is no password to hold here —
+ // the user is on this path precisely because they don't have it.
+ if (parsed.kind === "account_deleted") setPending({ via: "forgot", email });
+ setError(parsed);
+ setBusy(false);
+ setReactivating(false);
+ }
+ }, []);
+
+ /** The code is carried forward, not verified separately: checking it in its
+ * own round trip would consume it and leave nothing to authorize the change. */
+ const submitResetCode = useCallback(async (email: string, code: string) => {
+ setBusy(true);
+ setError(null);
+ try {
+ // Validate up front so a wrong code is rejected HERE rather than walking
+ // the user through choosing a new password and only failing on submit.
+ // This does not spend the code — forgot/complete still consumes it, since
+ // that is what authorizes the actual password change.
+ await forgotPasswordCheck(email, code);
+ setStage({ name: "forgot_password", email, code });
+ setBusy(false);
+ } catch (err) {
+ const parsed = parseLoginError(err);
+ // A burned or expired code can't be retried — send them back to request
+ // a fresh one instead of leaving them on a dead input.
+ if (parsed.kind === "code_burned" || parsed.kind === "code_expired") {
+ setStage({ name: "forgot_email", email });
+ }
+ setError(parsed);
+ setBusy(false);
+ }
+ }, []);
+
+ const completeReset = useCallback(
+ async (email: string, code: string, newPassword: string) => {
+ setBusy(true);
+ setError(null);
+ try {
+ const res = await forgotPasswordComplete(email, code, newPassword);
+ await finish(res.data.access_token, res.data.user);
+ } catch (err) {
+ const parsed = parseLoginError(err);
+ // The code was rejected, so go back and let them re-enter it.
+ if (
+ parsed.kind === "code_invalid" ||
+ parsed.kind === "code_expired" ||
+ parsed.kind === "code_burned"
+ ) {
+ setStage({ name: "forgot_code", email, resendAt: 0 });
+ }
+ setError(parsed);
+ setBusy(false);
+ }
+ },
+ [finish]
+ );
+
+ /**
+ * Confirm reactivation of a soft-deleted account, by whichever route met it.
+ *
+ * From the login step the held password reactivates and signs in directly.
+ * From the forgot-password step there is no password, so it reactivates and
+ * emails a reset code instead — the user lands on the code step and only
+ * reaches a session after setting a new one, which is the whole point: a
+ * confirmation click must not itself be a way into an account whose password
+ * the clicker doesn't know.
+ */
+ const reactivate = useCallback(async () => {
+ if (!pending) return;
+ if (pending.via === "forgot") {
+ await requestResetCode(pending.email, true);
+ return;
+ }
+ setBusy(true);
+ setReactivating(true);
+ setError(null);
+ try {
+ const res = await emailLogin(pending.email, pending.password, true);
+ setPending(null);
+ await finish(res.data.access_token, res.data.user);
+ } catch (err) {
+ setError({
+ kind: "generic",
+ message: getErrorMessage(err, "Failed to reactivate account."),
+ });
+ setBusy(false);
+ setReactivating(false);
+ }
+ }, [pending, finish, requestResetCode]);
+
+ /** One step back, preserving the address so it needn't be retyped. */
+ const back = useCallback(() => {
+ setError(null);
+ setPending(null);
+ setStage((s) => {
+ switch (s.name) {
+ case "password":
+ return { name: "email", mode: s.mode, email: s.email };
+ case "otp":
+ return { name: "password", email: s.email, mode: "signup" };
+ case "forgot_email":
+ return { name: "password", email: s.email, mode: "login" };
+ case "forgot_code":
+ return { name: "forgot_email", email: s.email };
+ case "forgot_password":
+ return { name: "forgot_code", email: s.email, resendAt: 0 };
+ default:
+ return s;
+ }
+ });
+ }, []);
+
+ /** Dismiss the current error without leaving the step or losing what was typed.
+ * Used by the reactivation prompt's Cancel, which must not restart the flow. */
+ const dismissError = useCallback(() => {
+ setError(null);
+ setPending(null);
+ setReactivating(false);
+ }, []);
+
+ const reset = useCallback(() => {
+ setReactivating(false);
+ setStage({ name: "email", mode: initialMode, email: "" });
+ setError(null);
+ setPending(null);
+ setBusy(false);
+ }, [initialMode]);
+
+ return {
+ stage,
+ busy,
+ error,
+ setMode,
+ setEmailValue,
+ submitEmail,
+ submitPassword,
+ submitCode,
+ resendCode,
+ startForgot,
+ requestResetCode,
+ submitResetCode,
+ completeReset,
+ reactivate,
+ reactivating,
+ dismissError,
+ back,
+ reset,
+ };
+}
diff --git a/frontend/src/hooks/useSocialLogin.ts b/frontend/src/hooks/useSocialLogin.ts
index 17df661ba3ebdea4600baf23902f9a01f4a20544..198a95ad6091172e3cdc046cbfa1ba88587f2671 100644
--- a/frontend/src/hooks/useSocialLogin.ts
+++ b/frontend/src/hooks/useSocialLogin.ts
@@ -1,12 +1,14 @@
import { useCallback, useState } from "react";
import type { CredentialResponse } from "@react-oauth/google";
-import { appleLogin, googleLogin, microsoftLogin } from "../api/client";
-import type { AuthProvider } from "../api/types";
+import { googleLogin } from "../api/client";
+import {
+ AUTH_PROVIDER_LABELS,
+ MIN_PASSWORD_LENGTH,
+ type AuthProvider,
+} from "../api/types";
import { useAuth } from "./useAuth";
import { usePostLoginRedirect } from "./usePostLoginRedirect";
-import { AppleSignInCancelled, signInWithApple } from "../lib/appleSignIn";
-import { MicrosoftSignInCancelled, signInWithMicrosoft } from "../lib/microsoftSignIn";
import { getErrorMessage } from "../contexts/ErrorModalContext";
/**
@@ -16,14 +18,25 @@ import { getErrorMessage } from "../contexts/ErrorModalContext";
* login() → redirect with their own error handling, and only three of them
* understood the `account_deleted` response. Centralizing it means a new
* provider or a new failure mode is handled once.
+ *
+ * Google is the only social provider (Apple and Microsoft were removed), but
+ * the shape stays general: parseLoginError below is shared with the email +
+ * password flow, which is the other half of every error case here.
*/
/** What the UI should show; anything unmapped falls through to `message`. */
export type LoginErrorKind =
| "wrong_provider"
| "account_deleted"
- | "apple_private_email"
- | "microsoft_no_email"
+ // Email + password
+ | "email_already_registered"
+ | "invalid_credentials"
+ | "password_policy"
+ | "code_invalid"
+ | "code_expired"
+ | "code_burned"
+ | "resend_cooldown"
+ | "rate_limited"
| "generic";
export interface LoginError {
@@ -34,6 +47,10 @@ export interface LoginError {
providerLabel?: string;
/** For "wrong_provider": that account is soft-deleted, so word it as reactivation. */
deleted?: boolean;
+ /** For "code_invalid": guesses left before the code is burned. */
+ attemptsRemaining?: number;
+ /** For 429s: seconds until the caller may retry. */
+ retryAfter?: number;
}
interface WrongProviderDetail {
@@ -43,11 +60,24 @@ interface WrongProviderDetail {
deleted: boolean;
}
-function parseLoginError(err: unknown): LoginError {
- const res = (err as { response?: { status?: number; data?: { detail?: unknown } } })
- ?.response;
+/**
+ * Maps a backend auth error onto what the UI should show.
+ *
+ * Exported because email/password auth shares it. A second copy would drift on
+ * the 409 shape and silently break the one-click provider switch, which is the
+ * whole reason the backend sends a machine-readable body.
+ */
+export function parseLoginError(err: unknown): LoginError {
+ const res = (err as {
+ response?: {
+ status?: number;
+ data?: { detail?: unknown };
+ headers?: Record;
+ };
+ })?.response;
const status = res?.status;
const detail = res?.data?.detail;
+ const retryAfter = Number(res?.headers?.["retry-after"]) || undefined;
// 409: the email belongs to the other provider. The body names it so we can
// offer a one-click switch rather than making the user guess.
@@ -56,17 +86,26 @@ function parseLoginError(err: unknown): LoginError {
if (d.code === "wrong_auth_provider" && d.provider) {
// The backend always sends provider_label; the map is a defensive
// fallback that must name the right provider, never a two-way guess.
- const label =
- d.provider_label ??
- ({ google: "Google", apple: "Apple", microsoft: "Microsoft" }[d.provider] ?? d.provider);
+ const label = d.provider_label ?? AUTH_PROVIDER_LABELS[d.provider] ?? d.provider;
+ const isEmail = d.provider === "email";
return {
kind: "wrong_provider",
provider: d.provider,
providerLabel: label,
deleted: Boolean(d.deleted),
message: d.deleted
- ? `Your account is registered with ${label}. Sign in with ${label} to reactivate it.`
- : `You already have an account with ${label}. Sign in with ${label} to continue.`,
+ ? isEmail
+ ? "Your account is registered with an email and password. Sign in below to reactivate it."
+ : `Your account is registered with ${label}. Sign in with ${label} to reactivate it.`
+ : isEmail
+ ? "You already have an account with this email. Sign in with your email to continue."
+ : `You already have an account with ${label}. Sign in with ${label} to continue.`,
+ };
+ }
+ if (d.code === "email_already_registered") {
+ return {
+ kind: "email_already_registered",
+ message: "You already have an account with this email. Sign in instead.",
};
}
}
@@ -75,19 +114,93 @@ function parseLoginError(err: unknown): LoginError {
return { kind: "account_deleted", message: "This account was deleted." };
}
- if (status === 400 && detail === "apple_private_email") {
+ // ─── Email + password ──────────────────────────────────────────────────
+ if (status === 401 && detail === "invalid_credentials") {
+ return {
+ kind: "invalid_credentials",
+ // Deliberately ambiguous, mirroring the backend: this is the same response
+ // for a wrong password and an address with no account.
+ message: "That email and password don't match.",
+ };
+ }
+
+ if (
+ status === 422 &&
+ typeof detail === "string" &&
+ (detail.startsWith("password_too_") || detail.startsWith("password_needs_"))
+ ) {
+ const messages: Record = {
+ password_too_short: `Password must be at least ${MIN_PASSWORD_LENGTH} characters.`,
+ password_too_long: "That password is too long.",
+ password_needs_uppercase: "Password must include a capital letter.",
+ password_needs_special: "Password must include a special character.",
+ };
+ return {
+ kind: "password_policy",
+ message: messages[detail] ?? "That password doesn't meet the requirements.",
+ };
+ }
+
+ if (status === 400 && detail && typeof detail === "object") {
+ const d = detail as { code?: string; attempts_remaining?: number };
+ if (d.code === "code_invalid") {
+ const left = d.attempts_remaining;
+ return {
+ kind: "code_invalid",
+ attemptsRemaining: left,
+ message:
+ left === undefined
+ ? "That code isn't right."
+ : `That code isn't right. ${left} attempt${left === 1 ? "" : "s"} left.`,
+ };
+ }
+ }
+
+ if (status === 400 && detail === "code_invalid") {
+ return { kind: "code_invalid", message: "That code isn't right." };
+ }
+
+ if (status === 400 && detail === "code_expired") {
+ return { kind: "code_expired", message: "That code has expired. Request a new one." };
+ }
+
+ if (status === 429 && detail === "code_attempts_exceeded") {
return {
- kind: "apple_private_email",
- message:
- "Please share your email to continue. Choose your Apple email instead of “Hide My Email” when signing in.",
+ kind: "code_burned",
+ message: "Too many incorrect codes. Start again to get a new one.",
};
}
- if (status === 400 && detail === "microsoft_no_email") {
+ if (status === 429 && detail === "resend_too_soon") {
return {
- kind: "microsoft_no_email",
- message:
- "Your Microsoft account didn't share an email address. Add one to your Microsoft account, or sign in another way.",
+ kind: "resend_cooldown",
+ retryAfter,
+ message: `Please wait ${retryAfter ?? 60}s before requesting another code.`,
+ };
+ }
+
+ if (status === 429 && detail === "too_many_attempts") {
+ const mins = retryAfter ? Math.max(1, Math.ceil(retryAfter / 60)) : null;
+ return {
+ kind: "rate_limited",
+ retryAfter,
+ message: mins
+ ? `Too many attempts. Try again in ${mins} minute${mins === 1 ? "" : "s"}.`
+ : "Too many attempts. Please try again later.",
+ };
+ }
+
+ if (status === 400 && detail === "no_pending_registration") {
+ return {
+ kind: "generic",
+ message: "That registration expired. Please start again.",
+ };
+ }
+
+ if (status === 502 && detail === "email_send_failed") {
+ return {
+ kind: "generic",
+ message: "We couldn't send the email just now. Please try again in a moment.",
};
}
@@ -119,14 +232,12 @@ export function useSocialLogin({
const redirectAfterLogin = usePostLoginRedirect();
const [signingIn, setSigningIn] = useState(false);
+ /** True while the in-flight request is a reactivation rather than a first
+ * sign-in, so the UI can say which one it is. */
+ const [reactivating, setReactivating] = useState(false);
const [error, setError] = useState(null);
/** Held so the account-deleted prompt can retry the same credential. */
- const [pending, setPending] = useState<
- | { provider: "google"; credential: string }
- | { provider: "apple"; identityToken: string }
- | { provider: "microsoft"; idToken: string }
- | null
- >(null);
+ const [pending, setPending] = useState<{ credential: string } | null>(null);
const finish = useCallback(
async (token: string, user: Parameters[1]) => {
@@ -152,7 +263,7 @@ export function useSocialLogin({
} catch (err) {
const parsed = parseLoginError(err);
if (parsed.kind === "account_deleted") {
- setPending({ provider: "google", credential: response.credential });
+ setPending({ credential: response.credential });
}
setError(parsed);
setSigningIn(false);
@@ -161,95 +272,14 @@ export function useSocialLogin({
[finish]
);
- const startAppleSignIn = useCallback(async () => {
- setSigningIn(true);
- setError(null);
- const refCode = localStorage.getItem("b2v_ref_code");
-
- // Obtain the token first, so the exchange below can hold on to it for a
- // possible reactivation retry.
- let identityToken: string;
- let appleUser: Awaited>["user"];
- try {
- ({ identityToken, user: appleUser } = await signInWithApple());
- } catch (err) {
- // Closing the popup is a deliberate action, not an error to report.
- if (err instanceof AppleSignInCancelled) {
- setSigningIn(false);
- return;
- }
- setError({
- kind: "generic",
- message: getErrorMessage(err, "Apple sign-in failed. Please try again."),
- });
- setSigningIn(false);
- return;
- }
-
- try {
- const res = await appleLogin(identityToken, appleUser, false, refCode);
- await finish(res.data.access_token, res.data.user);
- } catch (err) {
- const parsed = parseLoginError(err);
- if (parsed.kind === "account_deleted") {
- setPending({ provider: "apple", identityToken });
- }
- setError(parsed);
- setSigningIn(false);
- }
- }, [finish]);
-
- const startMicrosoftSignIn = useCallback(async () => {
- setSigningIn(true);
- setError(null);
- const refCode = localStorage.getItem("b2v_ref_code");
-
- // Obtain the token first, so the exchange below can hold on to it for a
- // possible reactivation retry.
- let idToken: string;
- try {
- ({ idToken } = await signInWithMicrosoft());
- } catch (err) {
- // Closing the popup is a deliberate action, not an error to report.
- if (err instanceof MicrosoftSignInCancelled) {
- setSigningIn(false);
- return;
- }
- setError({
- kind: "generic",
- message: getErrorMessage(err, "Microsoft sign-in failed. Please try again."),
- });
- setSigningIn(false);
- return;
- }
-
- try {
- const res = await microsoftLogin(idToken, false, refCode);
- await finish(res.data.access_token, res.data.user);
- } catch (err) {
- const parsed = parseLoginError(err);
- if (parsed.kind === "account_deleted") {
- setPending({ provider: "microsoft", idToken });
- }
- setError(parsed);
- setSigningIn(false);
- }
- }, [finish]);
-
/** Confirm reactivation of a soft-deleted account, reusing the held credential. */
const reactivate = useCallback(async () => {
if (!pending) return;
setSigningIn(true);
+ setReactivating(true);
setError(null);
try {
- let res;
- if (pending.provider === "google") {
- res = await googleLogin(pending.credential, true);
- } else if (pending.provider === "apple") {
- res = await appleLogin(pending.identityToken, null, true);
- } else {
- res = await microsoftLogin(pending.idToken, true);
- }
+ const res = await googleLogin(pending.credential, true);
setPending(null);
await finish(res.data.access_token, res.data.user);
} catch (err) {
@@ -258,22 +288,31 @@ export function useSocialLogin({
message: getErrorMessage(err, "Failed to reactivate account."),
});
setSigningIn(false);
+ setReactivating(false);
}
}, [pending, finish]);
+ /** Dismiss the current error without clearing the in-flight sign-in state. */
+ const dismissError = useCallback(() => {
+ setError(null);
+ setPending(null);
+ setReactivating(false);
+ }, []);
+
const reset = useCallback(() => {
setError(null);
setPending(null);
setSigningIn(false);
+ setReactivating(false);
}, []);
return {
signInWithGoogle,
- signInWithApple: startAppleSignIn,
- signInWithMicrosoft: startMicrosoftSignIn,
signingIn,
error,
reactivate,
+ reactivating,
+ dismissError,
reset,
/** Google sign-in failed inside GIS, before any token reached us. */
onGoogleError: useCallback(
diff --git a/frontend/src/lib/appleSignIn.ts b/frontend/src/lib/appleSignIn.ts
deleted file mode 100644
index 424e037bd30275d94d2230d52e970fdceb210434..0000000000000000000000000000000000000000
--- a/frontend/src/lib/appleSignIn.ts
+++ /dev/null
@@ -1,116 +0,0 @@
-/**
- * Sign in with Apple, via Apple's official JS SDK loaded on demand.
- *
- * We use the popup flow so the browser hands us an identity token in-page,
- * exactly like Google Identity Services gives us a credential — no server
- * redirect, and the same shape of call site for both providers.
- *
- * Apple returns the user's NAME only on the very first authorization, in the
- * response's `user` field rather than inside the token. Callers must forward it
- * to the backend on that first sign-in or the name is lost forever.
- */
-
-const APPLE_SDK_URL =
- "https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js";
-
-export interface AppleSignInResult {
- identityToken: string;
- /** Present only on the user's first authorization for this Services ID. */
- user?: { name?: { firstName?: string; lastName?: string } };
-}
-
-interface AppleAuthResponse {
- authorization?: { id_token?: string };
- user?: { name?: { firstName?: string; lastName?: string } };
-}
-
-declare global {
- interface Window {
- AppleID?: {
- auth: {
- init: (config: Record) => void;
- signIn: () => Promise;
- };
- };
- }
-}
-
-/** Raised when the user closes the Apple popup — not a real failure. */
-export class AppleSignInCancelled extends Error {
- constructor() {
- super("Apple sign-in cancelled");
- this.name = "AppleSignInCancelled";
- }
-}
-
-let sdkPromise: Promise | null = null;
-
-function loadAppleSdk(): Promise {
- if (window.AppleID) return Promise.resolve();
- // Cache the in-flight load so two buttons don't inject two script tags.
- if (sdkPromise) return sdkPromise;
-
- sdkPromise = new Promise((resolve, reject) => {
- const existing = document.querySelector(
- `script[src="${APPLE_SDK_URL}"]`
- );
- if (existing) {
- existing.addEventListener("load", () => resolve());
- existing.addEventListener("error", () => reject(new Error("Apple SDK failed to load")));
- return;
- }
- const script = document.createElement("script");
- script.src = APPLE_SDK_URL;
- script.async = true;
- script.onload = () => resolve();
- script.onerror = () => {
- sdkPromise = null; // allow a retry on the next click
- reject(new Error("Apple SDK failed to load"));
- };
- document.head.appendChild(script);
- });
- return sdkPromise;
-}
-
-export function isAppleSignInConfigured(): boolean {
- return Boolean(import.meta.env.VITE_APPLE_CLIENT_ID);
-}
-
-/**
- * Open Apple's sign-in popup and resolve with the identity token.
- *
- * Throws AppleSignInCancelled if the user dismissed the popup, so callers can
- * stay silent instead of showing an error for a deliberate action.
- */
-export async function signInWithApple(): Promise {
- const clientId = import.meta.env.VITE_APPLE_CLIENT_ID;
- if (!clientId) throw new Error("Apple sign-in is not configured");
-
- await loadAppleSdk();
- if (!window.AppleID) throw new Error("Apple SDK failed to load");
-
- window.AppleID.auth.init({
- clientId,
- scope: "name email",
- // Apple validates this against the Services ID's registered Return URLs;
- // an unregistered origin is rejected outright.
- redirectURI: window.location.origin,
- usePopup: true,
- });
-
- let response: AppleAuthResponse;
- try {
- response = await window.AppleID.auth.signIn();
- } catch (err: unknown) {
- const code = (err as { error?: string })?.error;
- if (code === "popup_closed_by_user" || code === "user_cancelled_authorize") {
- throw new AppleSignInCancelled();
- }
- throw new Error("Apple sign-in failed. Please try again.");
- }
-
- const identityToken = response?.authorization?.id_token;
- if (!identityToken) throw new Error("Apple sign-in returned no identity token");
-
- return { identityToken, user: response.user };
-}
diff --git a/frontend/src/lib/microsoftSignIn.ts b/frontend/src/lib/microsoftSignIn.ts
deleted file mode 100644
index 2fb8dd6ff983038e158533514f70c40c3f7bf8aa..0000000000000000000000000000000000000000
--- a/frontend/src/lib/microsoftSignIn.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-/**
- * Sign in with Microsoft, via MSAL loaded on demand.
- *
- * Uses the popup flow so the browser hands us an ID token in-page, exactly like
- * Google Identity Services gives us a credential and Apple gives us an identity
- * token — same shape of call site for all three providers.
- *
- * MSAL is ~40KB gzipped, so it is imported dynamically inside the click handler
- * rather than at module scope: visitors who never sign in never download it.
- */
-import type { PublicClientApplication } from "@azure/msal-browser";
-
-export interface MicrosoftSignInResult {
- idToken: string;
-}
-
-/** Raised when the user closes the MSAL popup — not a real failure. */
-export class MicrosoftSignInCancelled extends Error {
- constructor() {
- super("Microsoft sign-in cancelled");
- this.name = "MicrosoftSignInCancelled";
- }
-}
-
-// MSAL throws these when the user dismisses or blocks the popup.
-const CANCEL_CODES = new Set([
- "user_cancelled",
- "popup_window_error",
- "empty_window_error",
-]);
-
-let msalPromise: Promise | null = null;
-
-async function getMsal(): Promise {
- const clientId = import.meta.env.VITE_MICROSOFT_CLIENT_ID;
- if (!clientId) throw new Error("Microsoft sign-in is not configured");
-
- // Cache the initialized instance so a second click doesn't re-download or
- // re-initialize; MSAL requires initialize() before any auth call in v3+.
- if (!msalPromise) {
- msalPromise = (async () => {
- const { PublicClientApplication: PCA } = await import("@azure/msal-browser");
- const instance = new PCA({
- auth: {
- clientId,
- // "common" accepts personal Microsoft accounts (outlook.com,
- // hotmail.com, live.com) and any organization's Microsoft 365 tenant.
- authority: "https://login.microsoftonline.com/common",
- redirectUri: window.location.origin,
- },
- cache: {
- // sessionStorage, not localStorage: MSAL's own account cache should
- // not outlive the tab or sit alongside our long-lived b2v_token.
- cacheLocation: "sessionStorage",
- },
- });
- await instance.initialize();
- return instance;
- })().catch((err) => {
- msalPromise = null; // allow a retry on the next click
- throw err;
- });
- }
- return msalPromise;
-}
-
-export function isMicrosoftSignInConfigured(): boolean {
- return Boolean(import.meta.env.VITE_MICROSOFT_CLIENT_ID);
-}
-
-/**
- * Open Microsoft's sign-in popup and resolve with the ID token.
- *
- * Throws MicrosoftSignInCancelled if the user dismissed the popup, so callers
- * can stay silent instead of showing an error for a deliberate action.
- */
-export async function signInWithMicrosoft(): Promise {
- const msal = await getMsal();
-
- let result;
- try {
- result = await msal.loginPopup({ scopes: ["openid", "profile", "email"] });
- } catch (err: unknown) {
- const code = (err as { errorCode?: string })?.errorCode;
- if (code && CANCEL_CODES.has(code)) {
- throw new MicrosoftSignInCancelled();
- }
- throw new Error("Microsoft sign-in failed. Please try again.");
- }
-
- if (!result?.idToken) throw new Error("Microsoft sign-in returned no ID token");
- return { idToken: result.idToken };
-}
diff --git a/frontend/src/pages/AuthPage.tsx b/frontend/src/pages/AuthPage.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..14101db67a62aca929981cee773e86199ba98da8
--- /dev/null
+++ b/frontend/src/pages/AuthPage.tsx
@@ -0,0 +1,54 @@
+import { useEffect } from "react";
+import { useLocation, useNavigate } from "react-router-dom";
+
+import PublicHeader from "../components/public/PublicHeader";
+import AuthFlow from "../components/auth/AuthFlow";
+import { useAuth } from "../hooks/useAuth";
+
+interface AuthPageProps {
+ /**
+ * Which route rendered this page. Kept so the two paths stay distinguishable
+ * (and linkable), but it no longer forces a form: both open on sign-up, and
+ * the toggle inside the flow switches to sign-in.
+ */
+ mode?: "signin" | "signup";
+}
+
+/**
+ * Full-page sign-in / sign-up, with the site header.
+ *
+ * Renders the same AuthFlow as the modal, so every stage — password, OTP,
+ * forgot-password, the reactivation prompt — behaves identically on both
+ * surfaces. Plain CTAs (Landing, Pricing, PdfLanding) route here; the in-place
+ * tool gates still use the modal, because navigating away would discard the
+ * half-filled form they are gating.
+ */
+export default function AuthPage(_props: AuthPageProps) {
+ const { user, loading } = useAuth();
+ const navigate = useNavigate();
+ const location = useLocation();
+
+ // Someone already signed in has no business here — send them on rather than
+ // showing a form that would immediately bounce them.
+ useEffect(() => {
+ if (!loading && user) navigate("/dashboard", { replace: true });
+ }, [user, loading, navigate]);
+
+ return (
+
+
+
+ {/* Centred in the viewport minus the header, and borderless: on a full
+ page the card outline reads as a modal that forgot to close. */}
+
+
+ {/* No `mode` or copy override: both routes fall through to AuthFlow's
+ signup default and its mode-derived DEFAULT_COPY, so /signin opens
+ on the sign-up form too. Returning users take the "Already have an
+ account? Sign in" toggle inside the flow. */}
+
+
+
+
+ );
+}
diff --git a/frontend/src/pages/FreeTemplatesPage.tsx b/frontend/src/pages/FreeTemplatesPage.tsx
index ec16c46ee01818778458bbceea080ec079fab3d8..e05964e74f3d601cd087d5320a5509a913b77061 100644
--- a/frontend/src/pages/FreeTemplatesPage.tsx
+++ b/frontend/src/pages/FreeTemplatesPage.tsx
@@ -4,7 +4,6 @@ import PublicHeader from "../components/public/PublicHeader";
import PublicFooter from "../components/public/PublicFooter";
import Seo from "../components/seo/Seo";
import { useAuth } from "../hooks/useAuth";
-import { useLoginModal } from "../contexts/LoginModalContext";
import { useNavigate } from "react-router-dom";
import { BACKEND_URL } from "../api/client";
import { templateProfiles } from "../content/marketingBase";
@@ -66,7 +65,7 @@ const TEMPLATE_DISPLAY: Record = {
};
function DownloadModal({ slug, onClose, onDownloadStarted }: ModalProps) {
- const { openLogin } = useLoginModal();
+ const navigate = useNavigate();
const [error, setError] = useState(null);
const displayName = slug ? (TEMPLATE_DISPLAY[slug] ?? slug) : "";
@@ -78,7 +77,7 @@ function DownloadModal({ slug, onClose, onDownloadStarted }: ModalProps) {
localStorage.setItem(PENDING_DOWNLOAD_KEY, JSON.stringify(slug));
onDownloadStarted(slug);
onClose();
- openLogin({ title: "Sign in to download", subtitle: "Your download starts right after you sign in." });
+ navigate("/signin");
};
if (!slug) return null;
diff --git a/frontend/src/pages/Landing.tsx b/frontend/src/pages/Landing.tsx
index 4fc4ede22623689b27f32fba488db8f7dd0de810..dcc1b4ce5c7b87708e5dbca8e83930fcb4464a4b 100644
--- a/frontend/src/pages/Landing.tsx
+++ b/frontend/src/pages/Landing.tsx
@@ -2,7 +2,6 @@ import { useState, useEffect, useRef, useMemo } from "react";
import { Link, useNavigate, useSearchParams } from "react-router-dom";
import { useAuth } from "../hooks/useAuth";
import { useScrollReveal } from "../hooks/useScrollReveal";
-import { useLoginModal } from "../contexts/LoginModalContext";
import FullTemplateShowcase from "../components/FullTemplateShowcase";
import CoverflowCarousel, { type CoverflowTemplate, type CoverflowOrientation } from "../components/CoverflowCarousel";
import OrientationToggle from "../components/OrientationToggle";
@@ -456,7 +455,6 @@ function LandingDemoSection({ demos }: { demos: DemoVideo[] }) {
export default function Landing() {
const { user } = useAuth();
const navigate = useNavigate();
- const { openLogin } = useLoginModal();
const [searchParams] = useSearchParams();
const [demos, setDemos] = useState(INITIAL_DEMOS);
const [navOpen, setNavOpen] = useState(false);
@@ -543,8 +541,8 @@ export default function Landing() {
// Auto-open sign-in when redirected here with ?signin=1
useEffect(() => {
if (searchParams.get("signin") !== "1") return;
- openLogin();
- }, [searchParams, openLogin]);
+ navigate("/signin");
+ }, [searchParams, navigate]);
// Auto-fetch OG images for demos that don't have one; fall back to YouTube thumbnail
useEffect(() => {
@@ -574,7 +572,7 @@ export default function Landing() {
// Every sign-in CTA opens the shared login modal, which owns provider choice,
// error recovery, and the in-app-browser escape flow.
- const handleGenerateClick = () => openLogin();
+ const handleGenerateClick = () => navigate("/signin");
// "Explore the MCP connector" CTA: go straight there if signed in, otherwise
// sign in and route to /mcp-connector once authenticated.
@@ -584,7 +582,7 @@ export default function Landing() {
return;
}
localStorage.setItem("b2v_pending_mcp", "1");
- openLogin();
+ navigate("/signin");
};
// "Try AI presenters" CTA: avatars are configured per-project, there's no
@@ -596,7 +594,7 @@ export default function Landing() {
navigate("/dashboard");
return;
}
- openLogin();
+ navigate("/signin");
};
return (
@@ -1196,7 +1194,7 @@ export default function Landing() {