feat(abuse): abrir free a email normal + bloquear dominios desechables

El free ya no exige Google: cualquier cuenta Google o de email permanente
entra. Para que no sea un grifo de minutos gratis:
- Bloqueo de dominios desechables/temp-mail en el registro por email
  (cloud/disposable_domains.txt, 155 dominios: los clásicos temp-mail + los
  vistos en nuestra propia DB). Refrescable desde el proyecto upstream.
- Normalización de alias: gmail dots/+tags y +tags de otros proveedores se
  colapsan a una sola cuenta canónica, para que foo+1@ / f.oo@ no minten
  cuentas infinitas. Aplicado en magic-link y en Google OAuth.
- free_plan_eligible: Google siempre; email solo si el dominio no es
  desechable (defensa en profundidad además del bloqueo en registro).
- Popup de bienvenida ahora sale una vez por navegador en el primer registro
  (Google o email), no solo a los no-entitled; el botón free arranca directo
  sin forzar Google.

Verificado: registro con mailinator/luckfeed -> 400; gmail -> 200. 115 tests
(9 nuevos de email_policy).
This commit is contained in:
juancarlos.cavero 2026-07-21 00:45:54 +02:00
parent fe0f32e86b
commit 26135fb485
11 changed files with 328 additions and 44 deletions

View file

@ -18,7 +18,7 @@ from pydantic import BaseModel, EmailStr
from sqlalchemy import select, func, and_
from .config import settings
from . import database, metering
from . import database, metering, email_policy
from .models import User, MagicLinkToken, UploadPostProfile
router = APIRouter()
@ -131,7 +131,15 @@ class MagicVerifyRequest(BaseModel):
async def request_magic_link(payload: MagicLinkRequest, request: Request):
from .emails import send_magic_link_email
email = payload.email.lower()
# Block temp-mail before doing anything else — the free plan is open to
# email accounts now, so disposable domains would be a free-minute farm.
if email_policy.is_disposable(payload.email):
raise HTTPException(status_code=400, detail=(
"That email provider isn't supported. Please use a permanent "
"address (Gmail, Outlook, iCloud…) or sign in with Google."))
# Normalize (strip +tags / Gmail dots) so aliases can't mint extra accounts.
email = email_policy.normalize_email(payload.email)
async with database.session() as session:
async with session.begin():
window_start = _now() - timedelta(minutes=MAGIC_RATE_WINDOW_MIN)

View file

@ -32,9 +32,9 @@ PLAN_MINUTES = {
# cloud/metering.py against a synthetic calendar-month period. Setting
# FREE_PLAN_MINUTES = 0 disables the free plan.
FREE_PLAN_MINUTES = 20
# Gate the free allowance behind Google sign-in; magic-link-only accounts are
# disposable-email fodder and stay unentitled.
FREE_REQUIRES_GOOGLE = True
# 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
# normalized, so the plan isn't a multi-account faucet.
# The 20-minute monthly quota is the only bound on free usage — no daily job
# cap (it confused users and the minute ledger already caps real cost).
# Free users' clips expire from R2 after this many days (paid libraries are

View file

@ -0,0 +1,165 @@
# Disposable / temp-mail domains blocked from sign-up (one per line, lowercase).
# Comments (#) and blank lines ignored. Refreshable from the upstream project
# https://github.com/disposable-email-domains/disposable-email-domains
# — this is a strong curated subset plus every abusive domain seen in our own
# sign-ups. Add new ones here as they appear.
# --- Observed in our own DB ---
web-library.net
diarshop.com
hidepost.net
luckfeed.com
vltmail.com
buyreview.us
xhseeds.com
kdpsl.org
lasttea.com
gicont.com
# --- Classic temp-mail providers (and common aliases) ---
10minutemail.com
10minutemail.net
20minutemail.com
33mail.com
guerrillamail.com
guerrillamail.net
guerrillamail.org
guerrillamail.biz
guerrillamail.de
guerrillamailblock.com
sharklasers.com
grr.la
spam4.me
mailinator.com
mailinator.net
mailinator2.com
notmailinator.com
reconmail.com
tempmail.com
temp-mail.org
temp-mail.io
tempmail.net
tempmailo.com
tempr.email
tempmailaddress.com
tempinbox.com
throwawaymail.com
throwam.com
trashmail.com
trashmail.net
trashmail.io
trashmail.de
trash-mail.com
getnada.com
nada.email
maildrop.cc
mailnesia.com
mailcatch.com
dispostable.com
fakeinbox.com
fakemailgenerator.com
mytemp.email
tmail.com
tmails.net
mohmal.com
emailondeck.com
yopmail.com
yopmail.net
yopmail.fr
cool.fr.nf
jetable.fr.nf
nospam.ze.tc
nomail.xl.cx
mega.zik.dj
speed.1s.fr
courriel.fr.nf
moncourrier.fr.nf
monemail.fr.nf
monmail.fr.nf
inboxbear.com
inboxkitten.com
burnermail.io
33mail.com
anonaddy.com
anonaddy.me
mozmail.com
duck.com
relay.firefox.com
mailslurp.com
harakirimail.com
mailhog.io
mailtemp.net
mailexpire.com
spambox.us
spamgourmet.com
spamex.com
mailnull.com
spamherelots.com
tempemail.co
disposablemail.com
disposable.com
emailfake.com
fakemail.net
tempemails.io
1secmail.com
1secmail.net
1secmail.org
esiix.com
wwjmp.com
xojxe.com
vjuum.com
laafd.com
txcct.com
dpptd.com
oosln.com
bbmail.uk
byom.de
mailcuk.com
smailpro.com
tmpmail.org
tmpmail.net
tmpbox.net
minuteinbox.com
mailpoof.com
tempmailer.com
tempmailer.de
tempmailgen.com
tempail.com
altmails.com
altinbox.net
inboxes.com
easytrashmail.com
crazymailing.com
mailtothis.com
mailimate.com
etempmail.net
teleworm.us
armyspy.com
cuvox.de
dayrep.com
einrot.com
fleckens.hu
gustr.com
jourrapide.com
rhyta.com
superrito.com
teleg.eu
throaway.net
mailbox52.ga
tempmail.plus
tempmailbox.net
disbox.net
disbox.org
tmpeml.com
tmpeml.info
mail-temp.com
mailtm.com
mail.tm
linshiyouxiang.net
mailscrap.com
robot-mail.com
givmail.com
zetmail.com
mailtrap.io
correotemporal.org
correotemporal.com

64
cloud/email_policy.py Normal file
View file

@ -0,0 +1,64 @@
"""Email hygiene for sign-up: block disposable domains, normalize aliases.
Two abuse vectors this closes, now that the free plan is open to email (not
just Google) accounts:
* temp-mail domains → free-minute farms (blocklist below).
* provider aliases (gmail dots / +tags) → one address becomes infinite
accounts → normalized to a single canonical form.
"""
import os
_DOMAINS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"disposable_domains.txt")
# Providers where a "+tag" suffix and (for Google) dots are ignored by the
# mail server, so foo+1@ and f.oo@ all deliver to the same inbox.
_DOT_INSENSITIVE = {"gmail.com", "googlemail.com"}
_PLUS_ALIASING = _DOT_INSENSITIVE | {
"outlook.com", "hotmail.com", "live.com", "icloud.com", "me.com",
"fastmail.com", "protonmail.com", "proton.me", "yahoo.com",
}
def _load_disposable() -> set:
domains = set()
try:
with open(_DOMAINS_FILE, encoding="utf-8") as f:
for line in f:
line = line.strip().lower()
if line and not line.startswith("#"):
domains.add(line)
except FileNotFoundError:
pass
return domains
_DISPOSABLE = _load_disposable()
def is_disposable(email: str) -> bool:
"""True if the address's domain is a known disposable/temp-mail provider."""
domain = (email or "").rsplit("@", 1)[-1].strip().lower()
return domain in _DISPOSABLE
def normalize_email(email: str) -> str:
"""Canonical form used as the account key.
Lowercases; strips a +tag from providers that ignore it; strips dots from
the Gmail local part. Non-aliasing providers keep their local part intact
so we never merge two genuinely different addresses.
"""
email = (email or "").strip().lower()
if "@" not in email:
return email
local, domain = email.rsplit("@", 1)
if domain in _PLUS_ALIASING and "+" in local:
local = local.split("+", 1)[0]
if domain in _DOT_INSENSITIVE:
local = local.replace(".", "")
return f"{local}@{domain}"
def disposable_count() -> int:
return len(_DISPOSABLE)

View file

@ -123,15 +123,19 @@ async def _active_subscription(session, user_id):
def free_plan_eligible(user) -> bool:
"""True if this ``User`` row qualifies for the free monthly allowance.
Free minutes are only for Google-authenticated accounts: magic-link-only
sign-ins accept disposable-email domains and would make the free plan a
multi-account faucet. FREE_PLAN_MINUTES = 0 disables the free plan.
Google accounts always qualify. Email (magic-link) accounts qualify too,
as long as the address isn't a disposable/temp-mail domain — sign-up already
blocks those (cloud/email_policy), and this is the defense-in-depth check so
an old disposable account can't slip through. FREE_PLAN_MINUTES = 0 disables
the free plan entirely.
"""
if user is None or config.FREE_PLAN_MINUTES <= 0:
return False
if config.FREE_REQUIRES_GOOGLE and not user.google_sub:
return False
return True
if user.google_sub:
return True
# Email account: eligible unless the domain is disposable.
from . import email_policy
return not email_policy.is_disposable(user.email or "")
def free_period_end(now: datetime | None = None) -> datetime:

View file

@ -16,7 +16,7 @@ from starlette.responses import RedirectResponse
from sqlalchemy import select
from .config import settings
from . import database
from . import database, email_policy
from .models import User
from .auth import issue_jwt
@ -77,7 +77,9 @@ async def google_callback(request: Request):
userinfo = token.get("userinfo")
if not userinfo:
userinfo = await oauth.google.userinfo(token=token)
email = (userinfo.get("email") or "").lower()
# Normalize (Gmail dots / +tags) so a Google login and a magic-link account
# for the same real inbox key to one account.
email = email_policy.normalize_email(userinfo.get("email") or "")
google_sub = userinfo.get("sub")
if not email:
return RedirectResponse(f"{settings.frontend_url}/#/auth/callback?error=noemail")

View file

@ -541,10 +541,11 @@ function App() {
const keysMissing = !billingEnabled && (!apiKey || !uploadPostKey);
const needsPlan = billingEnabled && !isManaged; // hosted, signed-out or no active plan/trial
// Fresh sign-up with no entitlement yet: show the plan-choice popup once
// (AuthContext set the flag after the auth redirect) instead of the pricing page.
// Fresh sign-up: show the welcome plan-choice popup once (AuthContext set the
// flag after the auth redirect). Fires for free users too, so it's gated on
// being signed in rather than on entitlement.
useEffect(() => {
if (billingEnabled && isSignedIn && !isManaged) {
if (billingEnabled && isSignedIn) {
let flagged = false;
try { flagged = localStorage.getItem('os_show_plan_choice') === '1'; } catch (_) { /* ignore */ }
if (flagged) {
@ -552,7 +553,7 @@ function App() {
try { localStorage.removeItem('os_show_plan_choice'); } catch (_) { /* ignore */ }
}
}
}, [billingEnabled, isSignedIn, isManaged]);
}, [billingEnabled, isSignedIn]);
// Included in the plan (fully managed, no keys): Clip Generator + YouTube Studio.
// Advanced (bring your own fal.ai + ElevenLabs keys): AI Shorts + AI Agent.
const INCLUDED_TOOL_TABS = ['dashboard', 'thumbnails'];

View file

@ -1,6 +1,5 @@
import React, { useState, useEffect } from 'react';
import { Check, Loader2, Zap, ArrowRight } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { apiJson } from '../lib/api';
import Modal from './ui/Modal';
@ -8,12 +7,10 @@ const PLAN_ORDER = ['starter', 'creator', 'pro'];
const FREE_MINUTES = 20;
const fmt = (a, c) => new Intl.NumberFormat('en-US', { style: 'currency', currency: (c || 'usd').toUpperCase(), maximumFractionDigits: 0 }).format((a || 0) / 100);
// Shown right after a sign-up that isn't entitled yet, instead of dumping the
// user on the full pricing page. Free is the default choice; paid plans check
// out inline. The free tier needs a Google account (abuse gate), so for an
// email-only user the free CTA offers Google sign-in.
// Welcome popup after sign-up, instead of dumping the user on the pricing page.
// Free is the default (any Google or permanent-email account qualifies), paid
// plans check out inline.
export default function PlanChoiceModal({ onClose }) {
const { loginWithGoogle, googleAuthEnabled } = useAuth();
const [plans, setPlans] = useState([]);
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState(null);
@ -39,10 +36,8 @@ export default function PlanChoiceModal({ onClose }) {
};
const startFree = () => {
// Free needs Google; loginWithGoogle re-auths the account as Google-linked,
// which flips them to entitled. A user already on Google never sees this.
if (googleAuthEnabled) loginWithGoogle();
else onClose();
// A signed-in user with a valid account is already on Free — just start.
onClose();
};
return (
@ -66,9 +61,7 @@ export default function PlanChoiceModal({ onClose }) {
<button onClick={startFree} className="w-full btn-primary text-sm">
Start free <ArrowRight size={15} />
</button>
{googleAuthEnabled && (
<p className="text-center text-[11px] text-muted mt-2 lowercase">continue with google</p>
)}
<p className="text-center text-[11px] text-muted mt-2 lowercase">no card · start clipping now</p>
</div>
{/* Paid — compact list */}

View file

@ -69,12 +69,17 @@ export function AuthProvider({ children }) {
// This handler only runs on the auth redirect, so a resolved user here is
// a fresh sign-in / sign-up — the top of the conversion funnel.
if (signedInMe?.user) track('Signup', { props: { method: kind === 'verify' ? 'magic_link' : 'google' } });
// Everyone lands in the app. A signed-in user with no entitlement yet
// (email-only sign-up) gets a plan-choice popup there instead of being
// dumped on the pricing page. Google sign-ins are already on the free
// plan, so they never see it.
if (signedInMe?.user && !signedInMe?.entitled) {
try { localStorage.setItem('os_show_plan_choice', '1'); } catch (_) { /* ignore */ }
// Everyone lands in the app. Show the welcome plan-choice popup once per
// browser (on the first auth) for anyone not already on a paid plan —
// free is the default, paid is one click away. Never a pricing-page dump.
const paid = ['starter', 'creator', 'pro'].includes(signedInMe?.plan);
let welcomed = false;
try { welcomed = localStorage.getItem('os_welcomed') === '1'; } catch (_) { /* ignore */ }
if (signedInMe?.user && !paid && !welcomed) {
try {
localStorage.setItem('os_show_plan_choice', '1');
localStorage.setItem('os_welcomed', '1');
} catch (_) { /* ignore */ }
}
} catch (e) {
// fall through — user lands signed-out

View file

@ -0,0 +1,40 @@
"""Disposable-domain blocking and email alias normalization."""
from cloud import email_policy as ep
class TestDisposable:
def test_known_temp_mail_blocked(self):
assert ep.is_disposable("x@mailinator.com") is True
assert ep.is_disposable("y@10minutemail.com") is True
def test_db_observed_domains_blocked(self):
assert ep.is_disposable("a@luckfeed.com") is True
assert ep.is_disposable("b@web-library.net") is True
def test_real_providers_allowed(self):
for e in ("real@gmail.com", "u@outlook.com", "u@icloud.com", "u@yandex.ru"):
assert ep.is_disposable(e) is False
def test_case_insensitive(self):
assert ep.is_disposable("X@MailInator.CoM") is True
def test_list_loaded(self):
assert ep.disposable_count() > 50
class TestNormalize:
def test_gmail_dots_and_tags_stripped(self):
assert ep.normalize_email("Foo.Bar+promo@gmail.com") == "foobar@gmail.com"
assert ep.normalize_email("a.b.c@googlemail.com") == "abc@googlemail.com"
def test_other_providers_strip_tag_keep_dots(self):
assert ep.normalize_email("user+tag@outlook.com") == "user@outlook.com"
# Dots are significant outside Gmail — must be preserved.
assert ep.normalize_email("first.last@outlook.com") == "first.last@outlook.com"
def test_non_aliasing_provider_untouched(self):
assert ep.normalize_email("normal@yahoo.com") == "normal@yahoo.com"
assert ep.normalize_email("a.b@protonmail.com") == "a.b@protonmail.com"
def test_lowercased(self):
assert ep.normalize_email("USER@Example.COM") == "user@example.com"

View file

@ -7,16 +7,22 @@ import pytest
from cloud import config, metering
def _user(google_sub="g-123"):
return SimpleNamespace(google_sub=google_sub)
def _user(google_sub="g-123", email="x@gmail.com"):
return SimpleNamespace(google_sub=google_sub, email=email)
class TestFreePlanEligible:
def test_google_user_is_eligible(self):
assert metering.free_plan_eligible(_user()) is True
def test_magic_link_only_user_is_not_eligible(self):
assert metering.free_plan_eligible(_user(google_sub=None)) is False
def test_permanent_email_user_is_eligible(self):
# Free is open to real email accounts now, not just Google.
assert metering.free_plan_eligible(_user(google_sub=None, email="real@gmail.com")) is True
assert metering.free_plan_eligible(_user(google_sub=None, email="real@outlook.com")) is True
def test_disposable_email_user_is_not_eligible(self):
assert metering.free_plan_eligible(_user(google_sub=None, email="x@mailinator.com")) is False
assert metering.free_plan_eligible(_user(google_sub=None, email="x@luckfeed.com")) is False
def test_none_user_is_not_eligible(self):
assert metering.free_plan_eligible(None) is False
@ -25,10 +31,6 @@ class TestFreePlanEligible:
monkeypatch.setattr(config, "FREE_PLAN_MINUTES", 0)
assert metering.free_plan_eligible(_user()) is False
def test_google_gate_can_be_disabled(self, monkeypatch):
monkeypatch.setattr(config, "FREE_REQUIRES_GOOGLE", False)
assert metering.free_plan_eligible(_user(google_sub=None)) is True
class TestFreePeriodEnd:
@pytest.mark.parametrize("now, expected", [