feat: a new account is confirmed with a code sent to its e-mail
All checks were successful
Build and deploy / Validate source (push) Successful in 17s
Build and deploy / Integration suite on a real stack (push) Successful in 4m25s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m22s

Anyone could open an account on someone else's e-mail. Now "Criar conta"
e-mails a 6-digit code, and the account exists only once it is entered: one
big field that takes a paste or the phone's autofill and confirms by itself,
"Reenviar código" after 60 s, "Trocar e-mail", and the sign-in box hidden
meanwhile.

Security: 15 minutes per code, 5 wrong attempts, at most 5 codes, limits per
address and per source; the password is hashed at the first step and the code
stored only as a hash, its e-mail erased once sent. An address that already
has an account gets the same answer on screen and a "você já tem conta"
e-mail instead of a code, so the form does not reveal who is registered.
Without e-mail (MAIL_ADAPTER=off) the account is created at once, as before.

The browser test reads the code from a local-only endpoint that exists only
where e-mail stays in the log. Tested: mail_test (wrong, locked, resent,
expired codes, existing address, erasure after SMTP), the full suite and the
browser test in a CI-style stack, and the screens in Brave on desktop and phone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-14 15:18:37 -03:00
parent 5a431f8422
commit 95be624cca
14 changed files with 337 additions and 29 deletions

View File

@@ -15,9 +15,9 @@ from ..artwork import submit_files
from ..core.auth import (DUMMY_PASSWORD_HASH, audit, client_ip, new_session, owner, login_failed, password_hash,
password_matches, rate_limit, session_row, throttle, transfer_guest)
from ..core.models import (ArtworkSubmission, EmailChange, ForgotPassword, Login, PasswordChange, PasswordReset,
ProfileUpdate, Register)
ProfileUpdate, Register, SignupCode, SignupResend)
from .. import mail
from ..runtime import PUBLIC_ORIGIN, STATES, file_rows, order_code, owned_order, storage
from ..runtime import ENVIRONMENT, PUBLIC_ORIGIN, STATES, file_rows, order_code, owned_order, storage
from ..scanning import require_clean
router = APIRouter()
@@ -28,6 +28,36 @@ def current(request):
except HTTPException: return None
# Signup: with e-mail on, the account exists only once the code sent to the
# address is entered, so nobody opens an account on someone else's e-mail. The
# answer is the same whether or not the address already has an account: that
# address gets a notice to sign in instead of a code, and no code works.
CODE_ATTEMPTS = 5
CODE_SENDS = 5
RESEND_SECONDS = 60
def signup_code(c, signup_id, email, exists):
"""A fresh code for a signup (or the notice for an address that already has
an account), queued by e-mail. Returns the code's hash, None for the notice."""
if exists:
mail.queue(c, 'account', email, 'Você já tem conta · DTF Dropstar',
'Olá!\n\nAlguém tentou criar uma conta no DTF Dropstar com este e-mail, mas ele já tem conta.\n\n'
f'Para entrar: {PUBLIC_ORIGIN}/conta/entrar\n'
'Esqueceu a senha? Na mesma página, clique em “Esqueci minha senha”.\n\n'
'Se não foi você, ignore este e-mail: nada muda na sua conta.')
return None
code = f'{secrets.randbelow(10 ** 6):06d}'
mail.queue(c, 'code', email, f'{code} é o seu código · DTF Dropstar',
f'Olá!\n\nO seu código para criar a conta no DTF Dropstar é:\n\n{code}\n\n'
f'Ele vale por {mail.CODE_MINUTES} minutos. Se não foi você, ignore este e-mail.')
return code_digest(signup_id, code)
def code_digest(signup_id, code):
return hashlib.sha256(f'{signup_id}:{code}'.encode()).hexdigest()
@router.post('/api/account/register')
def register(body: Register, request: Request, response: Response):
email = body.customer.mail.strip().lower()
@@ -35,15 +65,32 @@ def register(body: Register, request: Request, response: Response):
# Registration attempts keep counting against the email, as before.
login_failed(email)
previous = current(request)
encoded = password_hash(body.password)
identity = uuid4()
profile = body.customer.model_dump()
profile['mail'] = email
with db.connect() as c:
if previous and c.execute('SELECT id FROM dtf_local.accounts WHERE id=%s', (previous['owner'],)).fetchone():
raise HTTPException(409, 'Saia da conta atual antes de criar outra.')
if mail.configured():
rate_limit('signup-account', email, CODE_SENDS, 3600)
signup_id = uuid4()
with db.connect() as c:
exists = c.execute('SELECT 1 FROM dtf_local.accounts WHERE email=%s', (email,)).fetchone()
digest = signup_code(c, signup_id, email, exists)
c.execute('''INSERT INTO dtf_local.account_signups(id,email,profile,password_hash,code_hash,expires_at)
VALUES(%s,%s,%s,%s,%s,now() + %s * interval '1 minute')''',
(signup_id, email, Jsonb(profile), password_hash(body.password), digest, mail.CODE_MINUTES))
audit('account_signup_started', ip=client_ip(request))
return {'verify': str(signup_id), 'email': email, 'minutes': mail.CODE_MINUTES, 'resend_seconds': RESEND_SECONDS}
# Without e-mail there is no code to send: the account is created at once.
return create_account(profile=profile, password=password_hash(body.password), previous=previous, response=response)
def create_account(profile, password, previous, response):
identity = uuid4()
try:
with db.connect() as c:
if previous and c.execute('SELECT id FROM dtf_local.accounts WHERE id=%s', (previous['owner'],)).fetchone():
raise HTTPException(409, 'Saia da conta atual antes de criar outra.')
c.execute('INSERT INTO dtf_local.accounts(id,email,password_hash,profile) VALUES(%s,%s,%s,%s)', (identity,email,encoded,Jsonb(profile)))
c.execute('INSERT INTO dtf_local.accounts(id,email,password_hash,profile) VALUES(%s,%s,%s,%s)',
(identity, profile['mail'], password, Jsonb(profile)))
if previous: transfer_guest(c, previous, identity)
new_session(c, response, identity)
except UniqueViolation:
@@ -51,6 +98,69 @@ def register(body: Register, request: Request, response: Response):
audit('account_registered', account=str(identity))
return {'customer': profile}
@router.post('/api/account/register/verify')
def register_verify(body: SignupCode, request: Request, response: Response):
rate_limit('signup-verify', client_ip(request), 30)
with db.connect() as c:
signup = c.execute('SELECT * FROM dtf_local.account_signups WHERE id=%s AND done_at IS NULL FOR UPDATE',
(body.signup,)).fetchone()
if not signup or signup['expires_at'] <= datetime.now(timezone.utc):
raise HTTPException(410, 'Este código venceu. Clique em “Reenviar código”.')
if signup['attempts'] >= CODE_ATTEMPTS:
raise HTTPException(429, 'Muitas tentativas com este código. Clique em “Reenviar código”.')
right = signup['code_hash'] and secrets.compare_digest(signup['code_hash'], code_digest(signup['id'], body.code))
if not right:
c.execute('UPDATE dtf_local.account_signups SET attempts=attempts+1 WHERE id=%s', (signup['id'],))
left = CODE_ATTEMPTS - signup['attempts'] - 1
audit('account_signup_code_wrong', ip=client_ip(request))
# Committed with the attempt: the connection's block ends cleanly.
wrong = HTTPException(400, 'Código incorreto. ' + (f'Restam {left} tentativas.' if left > 1 else
'Resta 1 tentativa.' if left == 1 else 'Clique em “Reenviar código”.'))
else:
wrong = None
c.execute('UPDATE dtf_local.account_signups SET done_at=now() WHERE id=%s', (signup['id'],))
if wrong:
raise wrong
return create_account(profile=signup['profile'], password=signup['password_hash'],
previous=current(request), response=response)
@router.get('/api/account/register/dev-code')
def register_dev_code(signup: UUID):
"""The local stack's last code for a signup, for the browser test, which
cannot read the database. Only where e-mail stays in the log; elsewhere
the code exists only in the customer's inbox."""
if ENVIRONMENT != 'local' or mail.ADAPTER != 'log':
raise HTTPException(404, 'Not found')
with db.connect() as c:
row = c.execute('''SELECT m.body FROM dtf_local.account_signups s JOIN dtf_local.mail_queue m
ON m.to_addr=s.email AND m.kind='code' WHERE s.id=%s ORDER BY m.id DESC LIMIT 1''', (signup,)).fetchone()
if not row:
raise HTTPException(404, 'Not found')
return {'code': next(word for word in row['body'].split() if word.isdigit() and len(word) == 6)}
@router.post('/api/account/register/resend')
def register_resend(body: SignupResend, request: Request):
rate_limit('signup-verify', client_ip(request), 30)
with db.connect() as c:
signup = c.execute('SELECT * FROM dtf_local.account_signups WHERE id=%s AND done_at IS NULL FOR UPDATE',
(body.signup,)).fetchone()
if not signup:
raise HTTPException(410, 'Este cadastro venceu. Preencha os dados de novo.')
wait = RESEND_SECONDS - (datetime.now(timezone.utc) - signup['sent_at']).total_seconds()
if wait > 0:
raise HTTPException(429, f'Aguarde {int(wait) + 1} s para pedir outro código.')
if signup['sends'] >= CODE_SENDS:
raise HTTPException(429, 'Limite de códigos atingido. Preencha os dados de novo em alguns minutos.')
exists = c.execute('SELECT 1 FROM dtf_local.accounts WHERE email=%s', (signup['email'],)).fetchone()
digest = signup_code(c, signup['id'], signup['email'], exists)
c.execute('''UPDATE dtf_local.account_signups SET code_hash=%s, attempts=0, sends=sends+1, sent_at=now(),
expires_at=now() + %s * interval '1 minute' WHERE id=%s''', (digest, mail.CODE_MINUTES, signup['id']))
audit('account_signup_code_resent', ip=client_ip(request))
return {'ok': True, 'minutes': mail.CODE_MINUTES, 'resend_seconds': RESEND_SECONDS}
@router.post('/api/account/login')
def login(body: Login, request: Request, response: Response):
email = body.email.strip().lower()

View File

@@ -254,6 +254,13 @@ class PasswordChange(StrictModel):
current: str = Field(min_length=1, max_length=128)
new: str = Field(min_length=12, max_length=128)
class SignupCode(StrictModel):
signup: UUID
code: str = Field(pattern=r'^[0-9]{6}$')
class SignupResend(StrictModel):
signup: UUID
class ForgotPassword(StrictModel):
email: str = Field(min_length=3, max_length=254)

View File

@@ -11,8 +11,8 @@ retried. MAIL_ADAPTER chooses where they go:
stack, where there is no mail server;
smtp sent through SMTP_HOST as MAIL_FROM.
A recovery message carries a link that signs in, so its text is erased once it
is sent (or once the link expired unsent); only its subject stays as a record.
A recovery link or a signup code lets someone in, so its text is erased once
it is sent (or once it expired unsent); only its subject stays as a record.
"""
import logging
import os
@@ -25,6 +25,10 @@ ADAPTER = os.environ.get('MAIL_ADAPTER', 'off')
# Every Kanban link in an alert points here.
KANBAN_ORIGIN = os.environ.get('KANBAN_ORIGIN', '').rstrip('/')
RESET_MINUTES = 60
CODE_MINUTES = 15
# Messages that let someone in: their text is erased once sent, or once they
# expired unsent (minutes).
SECRET_KINDS = {'reset': RESET_MINUTES, 'code': CODE_MINUTES}
MAX_ATTEMPTS = 12
log = logging.getLogger('dtf.mail')
@@ -131,10 +135,11 @@ def send_pending(connect, limit=5, ids=None):
if not configured():
return
with connect() as c:
# A recovery link that expired before it could be sent is useless.
c.execute(f"""UPDATE dtf_local.mail_queue SET body='', last_error='expirou sem ser enviado', failed_at=now()
WHERE kind='reset' AND sent_at IS NULL AND failed_at IS NULL
AND created_at < now() - interval '{RESET_MINUTES} minutes'""")
# A link or a code that expired before it could be sent is useless.
for kind, minutes in SECRET_KINDS.items():
c.execute("""UPDATE dtf_local.mail_queue SET body='', last_error='expirou sem ser enviado', failed_at=now()
WHERE kind=%s AND sent_at IS NULL AND failed_at IS NULL
AND created_at < now() - %s * interval '1 minute'""", (kind, minutes))
rows = c.execute('''SELECT * FROM dtf_local.mail_queue WHERE sent_at IS NULL AND failed_at IS NULL
AND (id = ANY(%s) OR (%s::bigint[] IS NULL AND available_at <= now()))
ORDER BY id FOR UPDATE SKIP LOCKED LIMIT %s''', (ids or [], ids, limit)).fetchall()
@@ -151,7 +156,7 @@ def send_pending(connect, limit=5, ids=None):
log.warning('mail to %s failed (attempt %s): %s', row['to_addr'], attempts, exc)
continue
# The local log keeps the text so the link can be followed by hand.
erase = row['kind'] == 'reset' and ADAPTER != 'log'
erase = row['kind'] in SECRET_KINDS and ADAPTER != 'log'
c.execute('''UPDATE dtf_local.mail_queue SET sent_at=now(), attempts=attempts+1, last_error=NULL,
body=CASE WHEN %s THEN '' ELSE body END WHERE id=%s''', (erase, row['id']))

View File

@@ -260,7 +260,7 @@ CREATE TABLE IF NOT EXISTS dtf_local.operator_machines (
-- E-mail (app/mail.py): queued in the transaction that caused it, sent by the
-- worker. A recovery message's text is erased once sent; the subject stays.
CREATE TABLE IF NOT EXISTS dtf_local.mail_queue (
id bigserial PRIMARY KEY, kind text NOT NULL CHECK(kind IN ('reset','alert','test')),
id bigserial PRIMARY KEY, kind text NOT NULL,
to_addr text NOT NULL, subject text NOT NULL, body text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(), available_at timestamptz NOT NULL DEFAULT now(),
attempts int NOT NULL DEFAULT 0, last_error text, sent_at timestamptz, failed_at timestamptz
@@ -282,3 +282,18 @@ ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS alerts boolean NOT NULL
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contact_since timestamptz;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contact_by text;
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contact_note text;
-- E-mail kinds: a password-recovery link, a signup code, the notice that an
-- account already exists, the team's alerts and a test.
ALTER TABLE dtf_local.mail_queue DROP CONSTRAINT IF EXISTS mail_queue_kind_check;
ALTER TABLE dtf_local.mail_queue ADD CONSTRAINT mail_queue_kind_check
CHECK(kind IN ('reset','code','account','alert','test'));
-- A signup waiting for its e-mail code. The account is created only when the
-- code is entered; the password is already hashed and the code only hashed.
CREATE TABLE IF NOT EXISTS dtf_local.account_signups (
id uuid PRIMARY KEY, email text NOT NULL, profile jsonb NOT NULL, password_hash text NOT NULL,
code_hash text, created_at timestamptz NOT NULL DEFAULT now(), sent_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz NOT NULL, sends int NOT NULL DEFAULT 1, attempts int NOT NULL DEFAULT 0,
done_at timestamptz
);
CREATE INDEX IF NOT EXISTS account_signups_created ON dtf_local.account_signups(created_at);

View File

@@ -42,6 +42,8 @@ def cleanup():
c.execute('UPDATE dtf_local.uploads SET purged_at=now() WHERE id=%s', (row['id'],))
c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (row['id'],))
c.execute('DELETE FROM dtf_local.sessions WHERE expires_at<=now()')
c.execute("DELETE FROM dtf_local.account_signups WHERE created_at<now()-interval '1 day'")
c.execute("DELETE FROM dtf_local.password_resets WHERE expires_at<now()-interval '1 day'")
c.execute('DELETE FROM dtf_local.operator_sessions WHERE expires_at<=now()')
c.execute("DELETE FROM dtf_local.login_attempts WHERE started_at<now()-interval '1 day'")
c.execute("DELETE FROM dtf_local.security_events WHERE created_at<now()-interval '30 days'")