fix(billing): withdraw free minutes from temp-mail farms and re-registrations
- users.free_plan_denied (nullable, additive ALTER at boot): when set, free_plan_eligible is False for any sign-in method; paid plans and top-ups are untouched. is_free_user keeps such accounts on the free 7-day retention. - Sign-up (magic link and Google) stamps "recreated_after_deletion" when the address's fingerprint is in account_deletions within FREE_REDO_BLOCK_DAYS (90): deleting and re-registering reset the monthly 20 minutes. - A magic-link request for an existing account re-checks its MX and stamps "disposable_mx" when it matches the list (never blocks the sign-in). - disposable_mx.txt: wabblywabble.com, wallywatts.com (the sep-2026 farm, ~100 front domains), den.yt, temp-mail-pro.com. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
4bcdc36a6f
commit
8a8db96ec3
9 changed files with 252 additions and 4 deletions
|
|
@ -94,6 +94,28 @@ def email_fingerprint(email: str) -> str:
|
||||||
return hashlib.sha256(email_policy.normalize_email(email).encode()).hexdigest()
|
return hashlib.sha256(email_policy.normalize_email(email).encode()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
async def free_plan_denial_for_signup(session, email: str) -> Optional[str]:
|
||||||
|
"""``User.free_plan_denied`` value for a brand-new account, or None.
|
||||||
|
|
||||||
|
An address whose account was erased in the last FREE_REDO_BLOCK_DAYS
|
||||||
|
comes back without the free allowance: the ledger is keyed by user id, so
|
||||||
|
a new row would otherwise start the month with a fresh 20 minutes. Paid
|
||||||
|
plans and top-ups work as for anyone. Matched on the same fingerprint the
|
||||||
|
erasure stored, so it needs no new personal data.
|
||||||
|
"""
|
||||||
|
from .config import FREE_REDO_BLOCK_DAYS
|
||||||
|
if not email or FREE_REDO_BLOCK_DAYS <= 0:
|
||||||
|
return None
|
||||||
|
since = _now() - timedelta(days=FREE_REDO_BLOCK_DAYS)
|
||||||
|
hit = (await session.execute(
|
||||||
|
select(AccountDeletion.id).where(
|
||||||
|
AccountDeletion.email_sha256 == email_fingerprint(email),
|
||||||
|
AccountDeletion.deleted_at >= since,
|
||||||
|
).limit(1)
|
||||||
|
)).scalar_one_or_none()
|
||||||
|
return "recreated_after_deletion" if hit is not None else None
|
||||||
|
|
||||||
|
|
||||||
async def _session_user(request: Request):
|
async def _session_user(request: Request):
|
||||||
"""The signed-in user, refusing API-key auth.
|
"""The signed-in user, refusing API-key auth.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -214,12 +214,35 @@ async def request_magic_link(payload: MagicLinkRequest, request: Request):
|
||||||
if verdict == email_policy.MX_NONE:
|
if verdict == email_policy.MX_NONE:
|
||||||
raise HTTPException(status_code=400, detail=(
|
raise HTTPException(status_code=400, detail=(
|
||||||
"That email domain can't receive mail. Please double-check the address."))
|
"That email domain can't receive mail. Please double-check the address."))
|
||||||
|
else:
|
||||||
|
# The account keeps signing in, but eligibility for the free minutes
|
||||||
|
# is re-checked: a temp-mail front whose MX joined disposable_mx.txt
|
||||||
|
# after the account was made would otherwise keep its free plan
|
||||||
|
# forever (568 such accounts in sep-2026).
|
||||||
|
await _deny_free_if_disposable_mx(email)
|
||||||
|
|
||||||
link = f"{settings.frontend_url}/#/auth/verify?ml={raw_token}"
|
link = f"{settings.frontend_url}/#/auth/verify?ml={raw_token}"
|
||||||
await send_magic_link_email(email, link)
|
await send_magic_link_email(email, link)
|
||||||
return {"ok": True}
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
async def _deny_free_if_disposable_mx(email: str):
|
||||||
|
"""Mark an existing account's free plan withdrawn when its mail domain's
|
||||||
|
MX is a known temp-mail host. Best effort: never blocks the sign-in."""
|
||||||
|
try:
|
||||||
|
if await email_policy.mx_verdict(email) != email_policy.MX_DISPOSABLE:
|
||||||
|
return
|
||||||
|
from sqlalchemy import update
|
||||||
|
async with database.session() as session:
|
||||||
|
async with session.begin():
|
||||||
|
await session.execute(
|
||||||
|
update(User)
|
||||||
|
.where(User.email == email, User.free_plan_denied.is_(None))
|
||||||
|
.values(free_plan_denied="disposable_mx"))
|
||||||
|
except Exception as e:
|
||||||
|
print(f"⚠️ free-plan MX re-check failed: {e}")
|
||||||
|
|
||||||
|
|
||||||
async def purge_stale_magic_tokens():
|
async def purge_stale_magic_tokens():
|
||||||
"""Drop token rows too old to matter for auth or rate limiting.
|
"""Drop token rows too old to matter for auth or rate limiting.
|
||||||
|
|
||||||
|
|
@ -253,7 +276,9 @@ async def verify_magic_link(payload: MagicVerifyRequest):
|
||||||
select(User).where(User.email == email)
|
select(User).where(User.email == email)
|
||||||
)).scalar_one_or_none()
|
)).scalar_one_or_none()
|
||||||
if user is None:
|
if user is None:
|
||||||
user = User(email=email, last_login_at=_now())
|
from .account import free_plan_denial_for_signup
|
||||||
|
user = User(email=email, last_login_at=_now(),
|
||||||
|
free_plan_denied=await free_plan_denial_for_signup(session, email))
|
||||||
session.add(user)
|
session.add(user)
|
||||||
await session.flush()
|
await session.flush()
|
||||||
else:
|
else:
|
||||||
|
|
|
||||||
|
|
@ -32,6 +32,10 @@ PLAN_MINUTES = {
|
||||||
# cloud/metering.py against a synthetic calendar-month period. Setting
|
# cloud/metering.py against a synthetic calendar-month period. Setting
|
||||||
# FREE_PLAN_MINUTES = 0 disables the free plan.
|
# FREE_PLAN_MINUTES = 0 disables the free plan.
|
||||||
FREE_PLAN_MINUTES = 20
|
FREE_PLAN_MINUTES = 20
|
||||||
|
# An address erased (DELETE /api/account) within this many days gets no free
|
||||||
|
# minutes when it signs up again: deleting and re-registering was a way to
|
||||||
|
# reset the monthly allowance (15 re-registrations by 6 accounts, sep-2026).
|
||||||
|
FREE_REDO_BLOCK_DAYS = 90
|
||||||
# Free is open to Google accounts AND permanent email accounts; disposable /
|
# Free is open to Google accounts AND permanent email accounts; disposable /
|
||||||
# temp-mail domains are blocked at sign-up (cloud/email_policy) and aliases are
|
# temp-mail domains are blocked at sign-up (cloud/email_policy) and aliases are
|
||||||
# normalized, so the plan isn't a multi-account faucet.
|
# normalized, so the plan isn't a multi-account faucet.
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,8 @@ _sessionmaker = None
|
||||||
_ADDITIVE_COLUMNS = (
|
_ADDITIVE_COLUMNS = (
|
||||||
"ALTER TABLE users ADD COLUMN IF NOT EXISTS "
|
"ALTER TABLE users ADD COLUMN IF NOT EXISTS "
|
||||||
"marketing_opt_out BOOLEAN NOT NULL DEFAULT false",
|
"marketing_opt_out BOOLEAN NOT NULL DEFAULT false",
|
||||||
|
# Nullable, no default: a catalog-only change, no table rewrite.
|
||||||
|
"ALTER TABLE users ADD COLUMN IF NOT EXISTS free_plan_denied VARCHAR(32)",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -16,3 +16,11 @@ mailinator.com
|
||||||
mohmal.com
|
mohmal.com
|
||||||
temp-mail.org
|
temp-mail.org
|
||||||
yopmail.com
|
yopmail.com
|
||||||
|
# Sep-2026 free-minute farm: ~100 rotating front domains (airychen.com,
|
||||||
|
# meonvr.com, findize.com, ...) all MX to these two hosts; 567 accounts.
|
||||||
|
wabblywabble.com
|
||||||
|
wallywatts.com
|
||||||
|
# Fronts forexzig.com, fxzig.com, denipl.net -> mx2.den.yt
|
||||||
|
den.yt
|
||||||
|
# Fronts aminating.com, mailshan.com, draughtier.com -> temp-mail-pro.com
|
||||||
|
temp-mail-pro.com
|
||||||
|
|
|
||||||
|
|
@ -386,6 +386,11 @@ def free_plan_eligible(user) -> bool:
|
||||||
"""
|
"""
|
||||||
if user is None or config.FREE_PLAN_MINUTES <= 0:
|
if user is None or config.FREE_PLAN_MINUTES <= 0:
|
||||||
return False
|
return False
|
||||||
|
# Denied accounts (re-registered after an erasure, temp-mail MX): no free
|
||||||
|
# minutes whatever the sign-in method. getattr: test doubles and rows
|
||||||
|
# loaded before the column existed.
|
||||||
|
if getattr(user, "free_plan_denied", None):
|
||||||
|
return False
|
||||||
if user.google_sub:
|
if user.google_sub:
|
||||||
return True
|
return True
|
||||||
# Email account: eligible unless the domain is disposable.
|
# Email account: eligible unless the domain is disposable.
|
||||||
|
|
@ -409,10 +414,18 @@ def free_period_end(now: datetime | None = None) -> datetime:
|
||||||
|
|
||||||
|
|
||||||
async def is_free_user(session, user_id) -> bool:
|
async def is_free_user(session, user_id) -> bool:
|
||||||
"""Google-authed user currently on the free plan (no active/trialing sub)."""
|
"""User currently on the free tier (no active/trialing sub).
|
||||||
|
|
||||||
|
Used by the retention sweeps: an account whose free minutes were withdrawn
|
||||||
|
(``free_plan_denied``) still keeps its library on the free 7-day expiry,
|
||||||
|
not forever.
|
||||||
|
"""
|
||||||
if await _active_subscription(session, user_id):
|
if await _active_subscription(session, user_id):
|
||||||
return False
|
return False
|
||||||
return free_plan_eligible(await session.get(User, user_id))
|
user = await session.get(User, user_id)
|
||||||
|
if user is not None and getattr(user, "free_plan_denied", None):
|
||||||
|
return True
|
||||||
|
return free_plan_eligible(user)
|
||||||
|
|
||||||
|
|
||||||
async def _plan_used_this_period(session, user_id, period_end) -> Decimal:
|
async def _plan_used_this_period(session, user_id, period_end) -> Decimal:
|
||||||
|
|
|
||||||
|
|
@ -35,6 +35,14 @@ class User(Base):
|
||||||
# existing database.
|
# existing database.
|
||||||
marketing_opt_out = Column(Boolean, nullable=False, server_default="false",
|
marketing_opt_out = Column(Boolean, nullable=False, server_default="false",
|
||||||
default=False)
|
default=False)
|
||||||
|
# Why this account gets no free monthly minutes, or NULL (the normal case).
|
||||||
|
# Set at sign-up for an address erased in the last FREE_REDO_BLOCK_DAYS
|
||||||
|
# ("recreated_after_deletion": deleting and re-registering handed out a
|
||||||
|
# fresh 20 minutes), and for accounts whose mail domain turns out to be a
|
||||||
|
# temp-mail front ("disposable_mx"), which the domain list alone cannot
|
||||||
|
# see. Paid plans and top-ups are untouched; clearing it restores the free
|
||||||
|
# plan. Added to existing databases by cloud/database._ADDITIVE_COLUMNS.
|
||||||
|
free_plan_denied = Column(String(32), nullable=True)
|
||||||
|
|
||||||
|
|
||||||
class MagicLinkToken(Base):
|
class MagicLinkToken(Base):
|
||||||
|
|
|
||||||
|
|
@ -95,7 +95,9 @@ async def google_callback(request: Request):
|
||||||
select(User).where(User.email == email)
|
select(User).where(User.email == email)
|
||||||
)).scalar_one_or_none()
|
)).scalar_one_or_none()
|
||||||
if user is None:
|
if user is None:
|
||||||
user = User(email=email, google_sub=google_sub, last_login_at=_now())
|
from .account import free_plan_denial_for_signup
|
||||||
|
user = User(email=email, google_sub=google_sub, last_login_at=_now(),
|
||||||
|
free_plan_denied=await free_plan_denial_for_signup(session, email))
|
||||||
session.add(user)
|
session.add(user)
|
||||||
await session.flush()
|
await session.flush()
|
||||||
else:
|
else:
|
||||||
|
|
|
||||||
164
tests/test_free_plan_denied.py
Normal file
164
tests/test_free_plan_denied.py
Normal file
|
|
@ -0,0 +1,164 @@
|
||||||
|
"""Free minutes withdrawn from abusive sign-ups (``User.free_plan_denied``).
|
||||||
|
|
||||||
|
Two leaks, both measured in prod on 22-sep-2026:
|
||||||
|
- a temp-mail farm (~100 rotating front domains, all MX'd to
|
||||||
|
wabblywabble.com / wallywatts.com): 568 accounts, 4.828 free minutes;
|
||||||
|
- delete-and-re-register: the ledger is keyed by user id, so a new row for the
|
||||||
|
same address started with a fresh 20 minutes (15 times, 6 addresses).
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from cloud import account, config, email_policy, metering
|
||||||
|
|
||||||
|
|
||||||
|
def _user(**kw):
|
||||||
|
base = dict(google_sub=None, email="real@gmail.com", free_plan_denied=None)
|
||||||
|
base.update(kw)
|
||||||
|
return SimpleNamespace(**base)
|
||||||
|
|
||||||
|
|
||||||
|
class TestEligibility:
|
||||||
|
def test_denied_account_gets_no_free_minutes(self):
|
||||||
|
assert metering.free_plan_eligible(_user(free_plan_denied="disposable_mx")) is False
|
||||||
|
|
||||||
|
def test_denied_google_account_gets_no_free_minutes_either(self):
|
||||||
|
assert metering.free_plan_eligible(
|
||||||
|
_user(google_sub="g-1", free_plan_denied="recreated_after_deletion")) is False
|
||||||
|
|
||||||
|
def test_normal_accounts_are_unchanged(self):
|
||||||
|
assert metering.free_plan_eligible(_user()) is True
|
||||||
|
assert metering.free_plan_eligible(_user(google_sub="g-1")) is True
|
||||||
|
|
||||||
|
def test_rows_without_the_attribute_still_work(self):
|
||||||
|
assert metering.free_plan_eligible(SimpleNamespace(google_sub="g", email="a@gmail.com")) is True
|
||||||
|
|
||||||
|
|
||||||
|
class TestFarmMx:
|
||||||
|
@pytest.mark.parametrize("hosts", [
|
||||||
|
["mail.wabblywabble.com", "mail.wallywatts.com"],
|
||||||
|
["mail.wallywatts.com"],
|
||||||
|
["mx2.den.yt"],
|
||||||
|
["temp-mail-pro.com"],
|
||||||
|
["prd-smtp.10minutemail.com"],
|
||||||
|
])
|
||||||
|
def test_farm_mx_hosts_are_disposable(self, hosts):
|
||||||
|
assert email_policy.classify_mx_hosts(hosts) == email_policy.MX_DISPOSABLE
|
||||||
|
|
||||||
|
def test_real_mx_hosts_are_fine(self):
|
||||||
|
assert email_policy.classify_mx_hosts(["gmail-smtp-in.l.google.com"]) == email_policy.MX_OK
|
||||||
|
assert email_policy.classify_mx_hosts(["mx.yandex.net"]) == email_policy.MX_OK
|
||||||
|
|
||||||
|
|
||||||
|
class _Result:
|
||||||
|
def __init__(self, value):
|
||||||
|
self._value = value
|
||||||
|
|
||||||
|
def scalar_one_or_none(self):
|
||||||
|
return self._value
|
||||||
|
|
||||||
|
|
||||||
|
class _Session:
|
||||||
|
def __init__(self, value):
|
||||||
|
self.value = value
|
||||||
|
self.statements = []
|
||||||
|
|
||||||
|
async def execute(self, stmt):
|
||||||
|
self.statements.append(stmt)
|
||||||
|
return _Result(self.value)
|
||||||
|
|
||||||
|
|
||||||
|
class TestSignupAfterDeletion:
|
||||||
|
def test_recent_erasure_denies_the_free_plan(self):
|
||||||
|
s = _Session(value="some-id")
|
||||||
|
assert asyncio.run(account.free_plan_denial_for_signup(s, "Foo.Bar@gmail.com")) \
|
||||||
|
== "recreated_after_deletion"
|
||||||
|
params = s.statements[0].compile().params
|
||||||
|
# Same fingerprint the erasure stored (normalised address)...
|
||||||
|
assert account.email_fingerprint("foobar@gmail.com") in params.values()
|
||||||
|
# ...and only erasures inside the window count.
|
||||||
|
cutoffs = [v for v in params.values() if isinstance(v, datetime)]
|
||||||
|
assert cutoffs
|
||||||
|
expected = datetime.now(timezone.utc) - timedelta(days=config.FREE_REDO_BLOCK_DAYS)
|
||||||
|
assert abs((cutoffs[0] - expected).total_seconds()) < 60
|
||||||
|
|
||||||
|
def test_no_erasure_keeps_the_free_plan(self):
|
||||||
|
assert asyncio.run(account.free_plan_denial_for_signup(_Session(None), "a@gmail.com")) is None
|
||||||
|
|
||||||
|
def test_window_zero_disables_the_check(self, monkeypatch):
|
||||||
|
monkeypatch.setattr(config, "FREE_REDO_BLOCK_DAYS", 0)
|
||||||
|
s = _Session("some-id")
|
||||||
|
assert asyncio.run(account.free_plan_denial_for_signup(s, "a@gmail.com")) is None
|
||||||
|
assert s.statements == []
|
||||||
|
|
||||||
|
|
||||||
|
class TestMagicLinkSignup:
|
||||||
|
"""verify_magic_link stamps the new row; an existing row is untouched."""
|
||||||
|
|
||||||
|
def _run(self, monkeypatch, existing_user, deleted_before):
|
||||||
|
from cloud import auth
|
||||||
|
|
||||||
|
token_row = SimpleNamespace(used_at=None, email="again@gmail.com",
|
||||||
|
expires_at=datetime.now(timezone.utc) + timedelta(minutes=5))
|
||||||
|
added = []
|
||||||
|
|
||||||
|
class _Res:
|
||||||
|
def __init__(self, v):
|
||||||
|
self.v = v
|
||||||
|
|
||||||
|
def scalar_one_or_none(self):
|
||||||
|
return self.v
|
||||||
|
|
||||||
|
class _Sess:
|
||||||
|
calls = 0
|
||||||
|
|
||||||
|
async def execute(self, stmt):
|
||||||
|
_Sess.calls += 1
|
||||||
|
return _Res(token_row if _Sess.calls == 1 else existing_user)
|
||||||
|
|
||||||
|
def add(self, obj):
|
||||||
|
obj.id = "new-id"
|
||||||
|
added.append(obj)
|
||||||
|
|
||||||
|
async def flush(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def begin(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
async def __aenter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
async def __aexit__(self, *a):
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def _denial(session, email):
|
||||||
|
return "recreated_after_deletion" if deleted_before else None
|
||||||
|
|
||||||
|
async def _load(session, uid):
|
||||||
|
return SimpleNamespace(entitled=False)
|
||||||
|
|
||||||
|
monkeypatch.setattr(auth.database, "session", lambda: _Sess())
|
||||||
|
monkeypatch.setattr(account, "free_plan_denial_for_signup", _denial)
|
||||||
|
monkeypatch.setattr(auth, "_load_current_user", _load)
|
||||||
|
monkeypatch.setattr(auth, "issue_jwt", lambda uid, email: "jwt")
|
||||||
|
asyncio.run(auth.verify_magic_link(auth.MagicVerifyRequest(token="t")))
|
||||||
|
return added
|
||||||
|
|
||||||
|
def test_new_account_after_deletion_is_denied(self, monkeypatch):
|
||||||
|
added = self._run(monkeypatch, existing_user=None, deleted_before=True)
|
||||||
|
assert added[0].free_plan_denied == "recreated_after_deletion"
|
||||||
|
|
||||||
|
def test_new_account_without_deletion_is_eligible(self, monkeypatch):
|
||||||
|
added = self._run(monkeypatch, existing_user=None, deleted_before=False)
|
||||||
|
assert added[0].free_plan_denied is None
|
||||||
|
|
||||||
|
def test_existing_account_is_not_restamped(self, monkeypatch):
|
||||||
|
existing = SimpleNamespace(id="u1", email="again@gmail.com", free_plan_denied=None,
|
||||||
|
last_login_at=None)
|
||||||
|
added = self._run(monkeypatch, existing_user=existing, deleted_before=True)
|
||||||
|
assert added == []
|
||||||
|
assert existing.free_plan_denied is None
|
||||||
Loading…
Reference in a new issue