Recuperación de cuenta en Next.js (3 flujos + reset), con Turnstile

- lib/recover.ts: requestRecovery(type,email) -> password (crea token en
  home_passwordreset + email), accountname (email con las cuentas), activation
  (reenvía enlace); respuesta genérica anti-enumeración. resetPassword(token,pass)
  re-deriva el verifier SRP6 v2 (bnetMakeRegistration) y actualiza battlenet_accounts,
  marca el token usado.
- Routes /api/auth/recover (Turnstile) y /api/auth/reset-password.
- Páginas app/[locale]/recover (RecoverForm: selector de tipo + email + Turnstile) y
  reset-password (ResetForm con token de la URL). Catálogos Recover, Reset.

Verificado: recover sin captcha -> captchaFailed; reset token inválido -> invalidLink;
páginas 200. Reutiliza home_passwordreset de Django. Crypto de reset ya validada.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-12 23:07:16 +00:00
parent aa61f79a55
commit 3573b7eb40
9 changed files with 391 additions and 0 deletions
@@ -0,0 +1,62 @@
'use client'
import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { Turnstile } from '@/components/Turnstile'
const ERROR_KEYS = ['invalidEmail', 'captchaFailed'] as const
const SITE_KEY = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY
export function RecoverForm() {
const t = useTranslations('Recover')
const [type, setType] = useState('password')
const [email, setEmail] = useState('')
const [captcha, setCaptcha] = useState('')
const [busy, setBusy] = useState(false)
const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)
async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
if (busy) return
setBusy(true)
setMessage(null)
try {
const res = await fetch('/api/auth/recover', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ type, email: email.trim(), turnstileToken: captcha }),
})
const data: { success?: boolean; error?: string } = await res.json()
if (data.success) setMessage({ ok: true, text: t('success') })
else {
const key = (ERROR_KEYS as readonly string[]).includes(data.error ?? '') ? data.error! : 'genericError'
setMessage({ ok: false, text: t(key) })
}
} catch {
setMessage({ ok: false, text: t('genericError') })
} finally {
setBusy(false)
}
}
const field = 'w-full rounded border border-amber-900/60 bg-[#2c1e14] px-3 py-2'
return (
<div className="mx-auto max-w-sm">
<form onSubmit={handleSubmit} className="space-y-3">
<label className="block text-left text-sm text-amber-200/70">{t('type')}</label>
<select value={type} onChange={(e) => setType(e.target.value)} className={field}>
<option value="password">{t('typePassword')}</option>
<option value="accountname">{t('typeAccountName')}</option>
<option value="activation">{t('typeActivation')}</option>
</select>
<input type="email" placeholder={t('email')} value={email} onChange={(e) => setEmail(e.target.value)} required className={field} />
<Turnstile onVerify={setCaptcha} />
<button type="submit" disabled={busy || (!!SITE_KEY && !captcha)} className="w-full rounded bg-amber-600 px-4 py-2 font-semibold text-[#1b120b] disabled:opacity-60">
{busy ? t('sending') : t('submit')}
</button>
</form>
{message && <p className={`mt-3 text-center ${message.ok ? 'text-green-400' : 'text-red-400'}`}>{message.text}</p>}
</div>
)
}
+14
View File
@@ -0,0 +1,14 @@
import { getTranslations, setRequestLocale } from 'next-intl/server'
import { RecoverForm } from './RecoverForm'
export default async function RecoverPage({ params }: { params: Promise<{ locale: string }> }) {
const { locale } = await params
setRequestLocale(locale)
const t = await getTranslations('Recover')
return (
<main className="mx-auto max-w-3xl px-4 py-8">
<h1 className="mb-6 text-center text-2xl font-bold text-amber-500">{t('title')}</h1>
<RecoverForm />
</main>
)
}
@@ -0,0 +1,66 @@
'use client'
import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { useRouter, Link } from '@/i18n/navigation'
const ERROR_KEYS = ['invalidLink', 'expiredLink', 'passwordMismatch', 'passwordTooLong', 'accountNotFound'] as const
export function ResetForm({ token }: { token: string }) {
const t = useTranslations('Reset')
const router = useRouter()
const [password, setPassword] = useState('')
const [confPassword, setConfPassword] = useState('')
const [busy, setBusy] = useState(false)
const [done, setDone] = useState(false)
const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)
async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
if (busy || done) return
setBusy(true)
setMessage(null)
try {
const res = await fetch('/api/auth/reset-password', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token, password, confPassword }),
})
const data: { success?: boolean; error?: string } = await res.json()
if (data.success) {
setDone(true)
setMessage({ ok: true, text: t('success') })
setTimeout(() => router.push('/login'), 2500)
} else {
const key = (ERROR_KEYS as readonly string[]).includes(data.error ?? '') ? data.error! : 'genericError'
setMessage({ ok: false, text: t(key) })
}
} catch {
setMessage({ ok: false, text: t('genericError') })
} finally {
setBusy(false)
}
}
const field = 'w-full rounded border border-amber-900/60 bg-[#2c1e14] px-3 py-2'
return (
<div className="mx-auto max-w-sm text-center">
<form onSubmit={handleSubmit} className="space-y-3">
<input type="password" maxLength={16} placeholder={t('password')} value={password} onChange={(e) => setPassword(e.target.value)} required className={field} />
<input type="password" maxLength={16} placeholder={t('confPassword')} value={confPassword} onChange={(e) => setConfPassword(e.target.value)} required className={field} />
<button type="submit" disabled={busy || done} className="w-full rounded bg-amber-600 px-4 py-2 font-semibold text-[#1b120b] disabled:opacity-60">
{busy ? t('saving') : t('submit')}
</button>
</form>
{message && <p className={`mt-3 ${message.ok ? 'text-green-400' : 'text-red-400'}`}>{message.text}</p>}
{done && (
<p className="mt-4">
<Link href="/login" className="text-sky-400 underline">
{t('goLogin')}
</Link>
</p>
)}
</div>
)
}
@@ -0,0 +1,22 @@
import { getTranslations, setRequestLocale } from 'next-intl/server'
import { ResetForm } from './ResetForm'
export default async function ResetPasswordPage({
params,
searchParams,
}: {
params: Promise<{ locale: string }>
searchParams: Promise<{ token?: string }>
}) {
const { locale } = await params
setRequestLocale(locale)
const { token } = await searchParams
const t = await getTranslations('Reset')
return (
<main className="mx-auto max-w-lg px-4 py-8">
<h1 className="mb-6 text-center text-2xl font-bold text-amber-500">{t('title')}</h1>
<ResetForm token={token ?? ''} />
</main>
)
}
+22
View File
@@ -0,0 +1,22 @@
import { requestRecovery } from '@/lib/recover'
import { verifyTurnstile } from '@/lib/turnstile'
export async function POST(request: Request) {
let type = ''
let email = ''
let turnstileToken = ''
try {
const body = await request.json()
type = String(body.type ?? '')
email = String(body.email ?? '')
turnstileToken = String(body.turnstileToken ?? '')
} catch {
return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 })
}
const ip = (request.headers.get('x-forwarded-for') || '').split(',')[0].trim()
if (!(await verifyTurnstile(turnstileToken, ip))) {
return Response.json({ success: false, error: 'captchaFailed' })
}
const result = await requestRecovery(type, email)
return Response.json(result)
}
@@ -0,0 +1,18 @@
import { resetPassword } from '@/lib/recover'
export async function POST(request: Request) {
let token = ''
let password = ''
let confPassword = ''
try {
const body = await request.json()
token = String(body.token ?? '')
password = String(body.password ?? '').trim()
confPassword = String(body.confPassword ?? '').trim()
} catch {
return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 })
}
if (!token) return Response.json({ success: false, error: 'invalidLink' })
const result = await resetPassword(token, password, confPassword)
return Response.json(result)
}