From 7383e44ff4db41adf1924b52438adb8e1944933e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Wed, 14 Oct 2026 16:32:46 -0300 Subject: [PATCH] feat: a new account e-mail is confirmed with a code, and the old one is told Changing the e-mail in Dados da conta took effect at once, with nothing checking the new address: a typo locked the customer out, and anyone at a signed-in computer who knew the password could move the account to their own e-mail and then reset its password. Now the code goes to the new address, the account changes only once it is entered (same screen and limits as signup, and only the account that asked can complete it), and the old address gets "O e-mail da sua conta foi trocado", with the WhatsApp to call if it was not them. Without e-mail on, it changes at once as before. Signup and e-mail change share one code check (expiry, five attempts, the 60 s resend wait). Tested: mail_test (wrong password, same and taken e-mail, wrong code, another account's attempt, resend wait, the notice), the full suite in a CI-style stack, and the screen in Brave. Co-Authored-By: Claude Opus 5.5 --- app/api/customer.py | 131 +++++++++++++++++++++++++++++++++----------- app/core/models.py | 7 +++ app/schema.sql | 12 ++++ app/worker.py | 1 + docs/CONTEXT.md | 4 +- tests/mail_test.py | 38 ++++++++++++- web/portal.css | 1 + web/portal.html | 15 ++++- web/portal.js | 47 ++++++++++++++-- 9 files changed, 217 insertions(+), 39 deletions(-) diff --git a/app/api/customer.py b/app/api/customer.py index 4518236..469bb5f 100644 --- a/app/api/customer.py +++ b/app/api/customer.py @@ -14,8 +14,8 @@ from ..core import db 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, SignupCode, SignupResend) +from ..core.models import (ArtworkSubmission, EmailChange, EmailCode, EmailResend, ForgotPassword, Login, + PasswordChange, PasswordReset, ProfileUpdate, Register, SignupCode, SignupResend) from .. import mail from ..runtime import ENVIRONMENT, PUBLIC_ORIGIN, STATES, file_rows, order_code, owned_order, storage from ..scanning import require_clean @@ -47,11 +47,45 @@ def signup_code(c, signup_id, email, exists): '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 + return send_code(c, signup_id, email, 'criar a conta no DTF Dropstar') + + +def send_code(c, key, email, purpose): + """A fresh 6-digit code by e-mail for `purpose`; returns its hash.""" 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'Olá!\n\nO seu código para {purpose} é:\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) + return code_digest(key, code) + + +def checked_code(c, table, key, code, request, extra=''): + """The pending row a code confirms, locked, or the refusal to raise. A wrong + code counts against the row; the caller raises after its block commits.""" + row = c.execute(f'SELECT * FROM dtf_local.{table} WHERE id=%s AND done_at IS NULL {extra} FOR UPDATE', + key).fetchone() + if not row or row['expires_at'] <= datetime.now(timezone.utc): + return None, HTTPException(410, 'Este código venceu. Clique em “Reenviar código”.') + if row['attempts'] >= CODE_ATTEMPTS: + return None, HTTPException(429, 'Muitas tentativas com este código. Clique em “Reenviar código”.') + if row['code_hash'] and secrets.compare_digest(row['code_hash'], code_digest(row['id'], code)): + c.execute(f'UPDATE dtf_local.{table} SET done_at=now() WHERE id=%s', (row['id'],)) + return row, None + c.execute(f'UPDATE dtf_local.{table} SET attempts=attempts+1 WHERE id=%s', (row['id'],)) + left = CODE_ATTEMPTS - row['attempts'] - 1 + audit('code_wrong', kind=table, ip=client_ip(request)) + return None, 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”.')) + + +def resend_wait(row): + """Why another code cannot go yet, or None.""" + wait = RESEND_SECONDS - (datetime.now(timezone.utc) - row['sent_at']).total_seconds() + if wait > 0: + return HTTPException(429, f'Aguarde {int(wait) + 1} s para pedir outro código.') + if row['sends'] >= CODE_SENDS: + return HTTPException(429, 'Limite de códigos atingido. Comece de novo em alguns minutos.') + return None def code_digest(signup_id, code): @@ -101,27 +135,12 @@ def create_account(profile, password, previous, response): @router.post('/api/account/register/verify') def register_verify(body: SignupCode, request: Request, response: Response): - rate_limit('signup-verify', client_ip(request), 30) + rate_limit('code-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 + signup, refusal = checked_code(c, 'account_signups', (body.signup,), body.code, request) + # Raised outside the block, so a wrong attempt is counted, not rolled back. + if refusal: + raise refusal return create_account(profile=signup['profile'], password=signup['password_hash'], previous=current(request), response=response) @@ -143,17 +162,14 @@ def register_dev_code(signup: UUID): @router.post('/api/account/register/resend') def register_resend(body: SignupResend, request: Request): - rate_limit('signup-verify', client_ip(request), 30) + rate_limit('code-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.') + if refusal := resend_wait(signup): + raise refusal 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(), @@ -228,15 +244,66 @@ def change_email(body: EmailChange, request: Request, identity=Depends(owner)): if not password_matches(body.password, row['password_hash']): login_failed(row['email']) raise HTTPException(401, 'Senha incorreta.') - profile = {**row['profile'], 'mail': body.email} + if body.email == row['email']: + raise HTTPException(422, 'Este já é o e-mail da sua conta.') + if not mail.configured(): + return apply_email(identity, row, body.email) + # With e-mail on, the change waits for the code sent to the new address. + rate_limit('email-change', str(identity), CODE_SENDS, 3600) + change = uuid4() + with db.connect() as c: + if c.execute('SELECT 1 FROM dtf_local.accounts WHERE email=%s', (body.email,)).fetchone(): + raise HTTPException(409, 'Este e-mail já é de outra conta.') + digest = send_code(c, change, body.email, 'trocar o e-mail da sua conta no DTF Dropstar') + c.execute('''INSERT INTO dtf_local.email_changes(id,account_id,new_email,code_hash,expires_at) + VALUES(%s,%s,%s,%s,now() + %s * interval '1 minute')''', (change, identity, body.email, digest, mail.CODE_MINUTES)) + audit('account_email_change_started', account=str(identity)) + return {'verify': str(change), 'email': body.email, 'minutes': mail.CODE_MINUTES, 'resend_seconds': RESEND_SECONDS} + + +def apply_email(identity, row, email): + """Switch the account to the new e-mail and tell the old address.""" + profile = {**row['profile'], 'mail': email} try: with db.connect() as c: - c.execute('UPDATE dtf_local.accounts SET email=%s, profile=%s WHERE id=%s', (body.email, Jsonb(profile), identity)) + c.execute('UPDATE dtf_local.accounts SET email=%s, profile=%s WHERE id=%s', (email, Jsonb(profile), identity)) + mail.queue(c, 'notice', row['email'], 'O e-mail da sua conta foi trocado · DTF Dropstar', + f'Olá!\n\nO e-mail da sua conta no DTF Dropstar foi trocado para {email}. ' + 'A partir de agora, entre com ele.\n\n' + 'Se não foi você, fale com a Dropstar pelo WhatsApp 16 99428-0056.') except UniqueViolation: raise HTTPException(409, 'Este e-mail já é de outra conta.') audit('account_email_changed', account=str(identity)) return {'customer': profile} + +@router.post('/api/account/email/verify') +def change_email_verify(body: EmailCode, request: Request, identity=Depends(owner)): + rate_limit('code-verify', client_ip(request), 30) + with db.connect() as c: + change, refusal = checked_code(c, 'email_changes', (body.change, identity), body.code, request, + extra='AND account_id=%s') + row = account_row(c, identity) if change else None + if refusal: + raise refusal + return apply_email(identity, row, change['new_email']) + + +@router.post('/api/account/email/resend') +def change_email_resend(body: EmailResend, request: Request, identity=Depends(owner)): + rate_limit('code-verify', client_ip(request), 30) + with db.connect() as c: + change = c.execute('''SELECT * FROM dtf_local.email_changes WHERE id=%s AND account_id=%s AND done_at IS NULL + FOR UPDATE''', (body.change, identity)).fetchone() + if not change: + raise HTTPException(410, 'Esta troca venceu. Comece de novo.') + if refusal := resend_wait(change): + raise refusal + digest = send_code(c, change['id'], change['new_email'], 'trocar o e-mail da sua conta no DTF Dropstar') + c.execute('''UPDATE dtf_local.email_changes 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, change['id'])) + return {'ok': True, 'minutes': mail.CODE_MINUTES, 'resend_seconds': RESEND_SECONDS} + @router.post('/api/account/password') def change_password(body: PasswordChange, request: Request, identity=Depends(owner)): with db.connect() as c: diff --git a/app/core/models.py b/app/core/models.py index 169506e..864c4c1 100644 --- a/app/core/models.py +++ b/app/core/models.py @@ -261,6 +261,13 @@ class SignupCode(StrictModel): class SignupResend(StrictModel): signup: UUID +class EmailCode(StrictModel): + change: UUID + code: str = Field(pattern=r'^[0-9]{6}$') + +class EmailResend(StrictModel): + change: UUID + class ForgotPassword(StrictModel): email: str = Field(min_length=3, max_length=254) diff --git a/app/schema.sql b/app/schema.sql index 6583d85..b9fbd02 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -297,3 +297,15 @@ CREATE TABLE IF NOT EXISTS dtf_local.account_signups ( done_at timestamptz ); CREATE INDEX IF NOT EXISTS account_signups_created ON dtf_local.account_signups(created_at); + +-- A customer changing the account's e-mail: the change waits for the code sent +-- to the new address, as a signup does, and the old address is told. +CREATE TABLE IF NOT EXISTS dtf_local.email_changes ( + id uuid PRIMARY KEY, account_id uuid NOT NULL REFERENCES dtf_local.accounts(id) ON DELETE CASCADE, + new_email text NOT NULL, code_hash text NOT NULL, 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 +); +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','notice','alert','test')); diff --git a/app/worker.py b/app/worker.py index 3694d9d..c8cda42 100644 --- a/app/worker.py +++ b/app/worker.py @@ -43,6 +43,7 @@ def cleanup(): 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_atE-mail - + + + +

Senha

diff --git a/web/portal.js b/web/portal.js index 655b483..f2a57ba 100644 --- a/web/portal.js +++ b/web/portal.js @@ -310,12 +310,51 @@ $('fPerfil').onsubmit=async event=>{ conta=r.customer;aviso('Dados salvos.'); }catch(e){aviso(e.status===422?(algum?'Confira o WhatsApp e o endereço: todos os campos, menos o complemento, são necessários.':'Confira o WhatsApp.'):e.message,true);} }; +// A new e-mail is confirmed with the code sent to it before the account changes. +let troca=null, trocaTimer=null; +function emailTrocado(r){ + conta=r.customer;$('quem').textContent=conta.mail;$('dMail').value=conta.mail; + fechaTroca();aviso('E-mail alterado. Use o novo e-mail para entrar.'); +} +function fechaTroca(){ + clearInterval(trocaTimer);troca=null;$('fEmailCodigo').hidden=true;$('fEmail').hidden=false; +} +function trocaContagem(segundos){ + clearInterval(trocaTimer); + const b=$('emailReenviar');let falta=segundos; + const pinta=()=>{b.disabled=falta>0;b.textContent=falta>0?'Reenviar código ('+falta+' s)':'Reenviar código';}; + pinta();trocaTimer=setInterval(()=>{falta--;pinta();if(falta<=0)clearInterval(trocaTimer);},1000); +} $('fEmail').onsubmit=async event=>{ - event.preventDefault(); - try{const r=await api('/account/email',{email:$('dMail').value,password:$('dMailSenha').value}); - conta=r.customer;$('dMailSenha').value='';$('quem').textContent=conta.mail;aviso('E-mail alterado. Use o novo e-mail para entrar.');} - catch(e){aviso(e.status===422?'Confira o e-mail.':e.message,true);} + event.preventDefault();$('dMailOk').disabled=true; + try{ + const r=await api('/account/email',{email:$('dMail').value,password:$('dMailSenha').value}); + $('dMailSenha').value=''; + if(!r.verify){emailTrocado(r);return;} + troca=r.verify;$('emailNovo').textContent=r.email;$('emailCodigo').value=''; + $('fEmail').hidden=true;$('fEmailCodigo').hidden=false;aviso('');trocaContagem(r.resend_seconds);$('emailCodigo').focus(); + }catch(e){aviso(e.status===422&&!e.message.startsWith('Este')?'Confira o e-mail.':e.message,true);} + finally{$('dMailOk').disabled=false;} }; +$('emailCodigo').addEventListener('input',e=>{ + e.target.value=e.target.value.replace(/\D/g,'').slice(0,6); + if(e.target.value.length===6&&!$('emailCodigoOk').disabled)$('fEmailCodigo').requestSubmit(); +}); +$('fEmailCodigo').onsubmit=async event=>{ + event.preventDefault();$('emailCodigoOk').disabled=true; + try{emailTrocado(await api('/account/email/verify',{change:troca,code:$('emailCodigo').value}));} + catch(e){ + aviso(e.status===422?'O código tem 6 números.':e.message,true);$('emailCodigo').select(); + if(e.status===410||e.status===429){$('emailReenviar').disabled=false;$('emailReenviar').textContent='Reenviar código';clearInterval(trocaTimer);} + }finally{$('emailCodigoOk').disabled=false;} +}; +$('emailReenviar').onclick=async()=>{ + $('emailReenviar').disabled=true; + try{const r=await api('/account/email/resend',{change:troca});aviso('Enviamos um código novo para '+$('emailNovo').textContent+'.'); + trocaContagem(r.resend_seconds);$('emailCodigo').value='';$('emailCodigo').focus();} + catch(e){aviso(e.message,true);if(e.status===410)fechaTroca();else $('emailReenviar').disabled=false;} +}; +$('emailCancelar').onclick=()=>{aviso('');$('dMail').value=conta.mail;fechaTroca();}; $('fSenha').onsubmit=async event=>{ event.preventDefault(); try{await api('/account/password',{current:$('dAtual').value,new:$('dNova').value});