diff --git a/src/App.tsx b/src/App.tsx
index 2d550b1..107cb8a 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -1,9 +1,9 @@
-import { FormEvent, useEffect, useMemo, useRef, useState } from 'react'
+import { useEffect, useMemo, useRef, useState } from 'react'
import type { Session } from '@supabase/supabase-js'
import { supabase } from './lib/supabase'
import DocsPage from './docs/DocsPage'
import PlayerHub from './PlayerHub'
-import WebAuth, { VerifyEmail } from './WebAuth'
+import WebAuth, { RequestPasswordRecovery, ResetPasswordPage, VerifyEmail } from './WebAuth'
import SimpleLanding from './SimpleLanding'
import SpidoCodeZeroPage from './SpidoCodeZeroPage'
import SpidoCodeGamePage from './SpidoCodeGamePage'
@@ -1360,187 +1360,6 @@ function Footer() {
)
}
-function PasswordField({
- label,
- value,
- onChange,
- autoComplete,
-}: {
- label: string
- value: string
- onChange: (value: string) => void
- autoComplete: string
-}) {
- const [visible, setVisible] = useState(false)
- return (
-
- )
-}
-
-function ResetPasswordPage() {
- const [password, setPassword] = useState('')
- const [confirmPassword, setConfirmPassword] = useState('')
- const [status, setStatus] = useState<'checking' | 'ready' | 'submitting' | 'success' | 'invalid'>('checking')
- const [message, setMessage] = useState('Validando enlace de recuperación…')
-
- useEffect(() => {
- const client = supabase
- if (!client) {
- setStatus('invalid')
- setMessage('La página todavía no tiene configuradas las variables públicas de Supabase.')
- return
- }
-
- let active = true
- const validateSession = async () => {
- const { data, error } = await client.auth.getSession()
- if (!active) return
- if (error || !data.session) {
- setStatus('invalid')
- setMessage('El enlace no contiene una sesión de recuperación válida o ya expiró.')
- } else {
- setStatus('ready')
- setMessage('Crea una contraseña nueva para tu cuenta de SPIDOCODE.')
- }
- }
-
- const { data: listener } = client.auth.onAuthStateChange((event, session) => {
- if (!active) return
- if (event === 'PASSWORD_RECOVERY' && session) {
- setStatus('ready')
- setMessage('Crea una contraseña nueva para tu cuenta de SPIDOCODE.')
- }
- })
- void validateSession()
- return () => {
- active = false
- listener.subscription.unsubscribe()
- }
- }, [])
-
- async function submit(event: FormEvent) {
- event.preventDefault()
- if (status !== 'ready') return
-
- if (password.length < 6) {
- setMessage('La contraseña debe tener al menos 6 caracteres.')
- return
- }
- if (password !== confirmPassword) {
- setMessage('Las contraseñas no coinciden.')
- return
- }
-
- if (!supabase) {
- setStatus('invalid')
- setMessage('La página todavía no tiene configuradas las variables públicas de Supabase.')
- return
- }
-
- setStatus('submitting')
- setMessage('Actualizando contraseña…')
-
- try {
- const { error } = await supabase.auth.updateUser({ password })
- if (error) throw error
-
- window.history.replaceState({}, document.title, '/reset-password')
- setStatus('success')
- setMessage('Tu contraseña fue actualizada correctamente. Ya puedes volver a SPIDOCODE e iniciar sesión.')
- setPassword('')
- setConfirmPassword('')
- } catch (error) {
- setStatus('ready')
- const raw = error instanceof Error ? error.message : 'No fue posible actualizar la contraseña.'
- if (/expired|invalid.*token|jwt/i.test(raw)) {
- setStatus('invalid')
- setMessage('El enlace expiró o ya no es válido. Solicita un correo de recuperación nuevo desde SPIDOCODE.')
- } else {
- setMessage('No pudimos actualizar la contraseña. Inténtalo nuevamente en unos segundos.')
- }
- }
- }
-
- return (
-
-
-
-
-
- AUTH CHANNEL ONLINE
-
-
-
-
- SECURE RECOVERY // SPIDOCODE
-
- Restablecer contraseña
- {message}
-
- {status === 'success' ? (
-
-
Contraseña actualizada ✓
-
Puedes cerrar esta pestaña y volver al juego.
-
- ) : status === 'invalid' ? (
-
-
Enlace no disponible
-
- Vuelve a SPIDOCODE y solicita "¿Olvidaste tu contraseña?" nuevamente.
-
-
- ) : (
-
- )}
-
-
-
-
- )
-}
-
function LandingPage() {
return (
@@ -1572,7 +1391,9 @@ function LandingPage() {
export default function App() {
const pathname = window.location.pathname.replace(/\/+$/, '') || '/'
- if (pathname === '/reset-password') return
+ if (pathname === '/recuperar-contrasena') return
+ if (pathname === '/confirmar-recuperacion') return
+ if (pathname === '/reset-password') return
if (pathname === '/docs') return
if (pathname === '/perfil') return
if (pathname === '/registro') return
diff --git a/src/WebAuth.css b/src/WebAuth.css
index 26a1bcf..6123ea7 100644
--- a/src/WebAuth.css
+++ b/src/WebAuth.css
@@ -196,3 +196,29 @@
text-underline-offset: 3px;
}
.spido-verify-page :is(a, button):focus-visible { outline: 2px solid #285837; outline-offset: 4px; }
+
+.spido-auth-recovery {
+ display: grid;
+ place-items: center;
+ padding: clamp(20px, 5vw, 56px) 16px;
+}
+.spido-auth-recovery .spido-auth-card {
+ width: min(100%, 460px);
+ display: grid;
+ gap: 14px;
+ overflow-wrap: anywhere;
+}
+.spido-auth-recovery h1 {
+ margin: 0;
+ font: 700 clamp(1.65rem, 5vw, 2.35rem)/1.12 'Spido Pixel', monospace;
+}
+.spido-auth-recovery p { margin: 0; color: #4c515f; font-size: 14px; line-height: 1.6; }
+.spido-auth-recovery p.spido-auth-error { color: #892633; }
+.spido-auth-recovery-link {
+ justify-self: start;
+ color: #285837;
+ font-size: 13px;
+ font-weight: 600;
+ text-decoration: underline;
+ text-underline-offset: 3px;
+}
diff --git a/src/WebAuth.tsx b/src/WebAuth.tsx
index 841c1d6..f033a7f 100644
--- a/src/WebAuth.tsx
+++ b/src/WebAuth.tsx
@@ -1,5 +1,5 @@
-import { useEffect, useRef, useState, type FormEvent } from 'react'
-import { supabase } from './lib/supabase'
+import { useEffect, useLayoutEffect, useRef, useState, type FormEvent, type ReactNode } from 'react'
+import { closeRecoveryClient, exchangeRecoveryLink, recoveryLinkClient, supabase, verifyRecoveryHash, type RecoveryClient } from './lib/supabase'
import './WebAuth.css'
const VERIFICATION_WAIT_MS = 60_000
@@ -224,6 +224,7 @@ export default function WebAuth({ mode }: { mode: 'register' | 'login' }) {
{registering &&
}
+ {!registering &&
¿Olvidaste tu contraseña?}
{status&&
{status}
}
@@ -234,3 +235,236 @@ export default function WebAuth({ mode }: { mode: 'register' | 'login' }) {
}
+
+const RECOVERY_PATH = '/recuperar-contrasena'
+const RECOVERY_REDIRECT = 'https://www.spidocode.com/reset-password'
+const RECOVERY_WAIT_MS = 60_000
+
+function RecoveryCard({ title, children }: { title: string; children: ReactNode }) {
+ return (
+
+
+
+ )
+}
+
+export function RequestPasswordRecovery() {
+ const [email, setEmail] = useState('')
+ const [requestedEmail, setRequestedEmail] = useState('')
+ const [remaining, setRemaining] = useState(0)
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState('')
+ const requesting = useRef(false)
+ const deadline = useRef(0)
+
+ useEffect(() => {
+ const tick = () => setRemaining(Math.max(0, Math.ceil((deadline.current - Date.now()) / 1000)))
+ const timer = window.setInterval(tick, 500)
+ return () => window.clearInterval(timer)
+ }, [])
+
+ async function submit(event: FormEvent) {
+ event.preventDefault()
+ if (!recoveryLinkClient || requesting.current || Date.now() < deadline.current) return
+ requesting.current = true
+ setBusy(true)
+ setError('')
+ const address = requestedEmail || email.trim()
+ try {
+ const { error: requestError } = await recoveryLinkClient.auth.resetPasswordForEmail(
+ address, { redirectTo: RECOVERY_REDIRECT },
+ )
+ if (requestError && isRateLimited(requestError)) {
+ setError('Hay demasiadas solicitudes. Espera antes de volver a intentarlo.')
+ } else {
+ // SMTP and account-specific outcomes get the same response as an accepted request.
+ setRequestedEmail(address)
+ }
+ } catch {
+ setRequestedEmail(address)
+ } finally {
+ deadline.current = Date.now() + RECOVERY_WAIT_MS
+ setRemaining(60)
+ requesting.current = false
+ setBusy(false)
+ }
+ }
+
+ return (
+
+ {requestedEmail ? <>
+ Si podemos tramitar tu solicitud, recibirás un enlace. Revisa también la carpeta Spam.
+ Abre el enlace del correo y pulsa Continuar para verificarlo.
+ {/@gmail\.com$/i.test(requestedEmail) && (
+ Abrir Gmail (nueva pestaña)
+ )}
+ > : Introduce el correo asociado a tu cuenta de SPIDOCODE.
}
+ {!recoveryLinkClient && La recuperación no está disponible en este entorno.
}
+
+ {remaining > 0 && Podrás volver a intentarlo en {remaining} s.
}
+ {error && {error}
}
+
+ )
+}
+
+export function ResetPasswordPage({ legacy = false }: { legacy?: boolean }) {
+ const [status, setStatus] = useState<'checking' | 'confirm' | 'verifying' | 'ready' | 'submitting' | 'success' | 'invalid'>('checking')
+ const [password, setPassword] = useState('')
+ const [confirm, setConfirm] = useState('')
+ const [error, setError] = useState('')
+ const clientRef = useRef(null)
+ const pendingHash = useRef('')
+ const initialized = useRef(false)
+ const active = useRef(false)
+ const busy = useRef(false)
+
+ useLayoutEffect(() => {
+ active.current = true
+ if (!initialized.current) {
+ initialized.current = true
+ const url = new URL(window.location.href)
+ if (legacy && url.searchParams.has('code')) {
+ setStatus('confirm')
+ } else {
+ if (!legacy) pendingHash.current = new URLSearchParams(url.hash.slice(1)).get('token_hash') ?? ''
+ window.history.replaceState(window.history.state, '', url.pathname)
+ setStatus(pendingHash.current ? 'confirm' : 'invalid')
+ }
+ }
+
+ function stop() {
+ active.current = false
+ const client = clientRef.current
+ clientRef.current = null
+ if (client) void closeRecoveryClient(client)
+ }
+
+ function leavePage() {
+ pendingHash.current = ''
+ setPassword('')
+ setConfirm('')
+ setStatus(previous => previous === 'success' ? previous : 'invalid')
+ stop()
+ }
+
+ window.addEventListener('pagehide', leavePage)
+ return () => {
+ window.removeEventListener('pagehide', leavePage)
+ stop()
+ // Strict Mode repeats effect setup before this microtask runs.
+ queueMicrotask(() => { if (!active.current) pendingHash.current = '' })
+ }
+ }, [legacy])
+
+ async function verify() {
+ if (!active.current || busy.current || status !== 'confirm') return
+ busy.current = true
+ setStatus('verifying')
+ const hash = pendingHash.current
+ pendingHash.current = ''
+
+ try {
+ const client = legacy ? await exchangeRecoveryLink() : await verifyRecoveryHash(hash)
+ if (!active.current) {
+ if (client) await closeRecoveryClient(client)
+ return
+ }
+ clientRef.current = client
+ setStatus(client ? 'ready' : 'invalid')
+ } catch {
+ if (active.current) setStatus('invalid')
+ } finally {
+ busy.current = false
+ }
+ }
+
+ function clearPasswords() {
+ setPassword('')
+ setConfirm('')
+ }
+
+ async function submit(event: FormEvent) {
+ event.preventDefault()
+ const client = clientRef.current
+ if (!active.current || status !== 'ready' || !client || busy.current) return
+ setError('')
+ if (password !== confirm) {
+ setError('Las contraseñas no coinciden.')
+ return
+ }
+ busy.current = true
+ setStatus('submitting')
+ try {
+ const { error: updateError } = await client.auth.updateUser({ password })
+ if (!active.current) return
+ if (updateError) {
+ if (updateError.status === 401 || ['session_not_found', 'session_expired', 'bad_jwt'].includes(updateError.code ?? '')) {
+ clientRef.current = null
+ clearPasswords()
+ void closeRecoveryClient(client)
+ setStatus('invalid')
+ return
+ }
+ setError(updateError.code === 'weak_password' ? 'La contraseña no cumple los requisitos de seguridad. Elige una más segura.' :
+ updateError.code === 'same_password' ? 'Elige una contraseña distinta de la anterior.' :
+ 'No pudimos actualizar la contraseña. Inténtalo nuevamente.')
+ setStatus('ready')
+ return
+ }
+
+ clientRef.current = null
+ clearPasswords()
+ const closed = await closeRecoveryClient(client)
+ if (!active.current) return
+ if (!closed) setError('No se pudo revocar la sesión temporal. El cambio de contraseña ya se realizó.')
+ setStatus('success')
+ } catch {
+ if (!active.current) return
+ setError('No pudimos actualizar la contraseña. Inténtalo nuevamente.')
+ setStatus('ready')
+ } finally {
+ busy.current = false
+ }
+ }
+
+ return (
+
+ {(status === 'checking' || status === 'verifying') && Validando enlace de recuperación…
}
+ {status === 'confirm' && <>
+ Verifica el enlace del correo para elegir una nueva contraseña.
+
+ >}
+ {status === 'invalid' && <>
+ No pudimos verificar el enlace. Puede haber vencido o haberse usado. Solicita un enlace nuevo.
+ Solicitar un enlace nuevo
+ >}
+ {status === 'success' && Tu contraseña se actualizó. Ya puedes iniciar sesión con la nueva contraseña.
}
+ {(status === 'ready' || status === 'submitting') && <>
+ Crea una contraseña nueva para tu cuenta de SPIDOCODE.
+
+ >}
+ {error && {error}
}
+
+ )
+}
diff --git a/src/lib/supabase.ts b/src/lib/supabase.ts
index b048ccb..7e3bf6d 100644
--- a/src/lib/supabase.ts
+++ b/src/lib/supabase.ts
@@ -6,9 +6,107 @@ const publishableKey = import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY as string |
export const supabase = supabaseUrl && publishableKey
? createClient(supabaseUrl.replace(/\/$/, ''), publishableKey, {
auth: {
- detectSessionInUrl: true,
+ detectSessionInUrl: !['/reset-password', '/confirmar-recuperacion'].includes(window.location.pathname.replace(/\/+$/, '')),
persistSession: true,
autoRefreshToken: true,
},
})
: null
+
+const recoveryKey = 'spidocode-auth-recovery'
+const isVerifier = (key: string) => key.endsWith('-code-verifier')
+
+export const recoveryLinkClient = supabaseUrl && publishableKey
+ ? createClient(supabaseUrl.replace(/\/$/, ''), publishableKey, {
+ auth: {
+ flowType: 'pkce',
+ storageKey: recoveryKey,
+ detectSessionInUrl: false,
+ autoRefreshToken: false,
+ // Persist only the SDK's verifier across navigation, never a recovery session.
+ storage: {
+ getItem: key => isVerifier(key) ? localStorage.getItem(key) : null,
+ setItem: (key, value) => { if (isVerifier(key)) localStorage.setItem(key, value) },
+ removeItem: key => { if (isVerifier(key)) localStorage.removeItem(key) },
+ },
+ },
+ })
+ : null
+
+export async function exchangeRecoveryLink() {
+ if (!supabaseUrl || !publishableKey || !recoveryLinkClient) return null
+
+ const url = new URL(window.location.href)
+ const code = url.searchParams.get('code')
+ const fragment = new URLSearchParams(url.hash.slice(1))
+ const failed = [url.searchParams, fragment].some(params => params.has('error') || params.has('error_code'))
+ const clearUrl = () => window.history.replaceState(window.history.state, '', url.pathname)
+ if (!code || failed) {
+ clearUrl()
+ return null
+ }
+
+ // Subscribe before redeeming the code, so initialization cannot race the event.
+ let recoveryToken: string | undefined
+ const { data: { subscription } } = recoveryLinkClient.auth.onAuthStateChange((event, session) => {
+ if (event === 'PASSWORD_RECOVERY') recoveryToken = session?.access_token
+ })
+ try {
+ const { data, error } = await recoveryLinkClient.auth.exchangeCodeForSession(code)
+ if (error || !data.session || recoveryToken !== data.session.access_token) return null
+
+ // Bind updates to this specific account in SDK-managed, per-page memory.
+ const client = createRecoveryClient()
+ if (!client) return null
+ try {
+ const { data: bound, error: bindError } = await client.auth.setSession(data.session)
+ if (!bindError && bound.user?.id === data.session.user.id) return client
+ } catch {
+ // An unusable exchange must never authorize a password update.
+ }
+ await closeRecoveryClient(client)
+ return null
+ } finally {
+ subscription.unsubscribe()
+ clearUrl()
+ }
+}
+
+function createRecoveryClient() {
+ if (!supabaseUrl || !publishableKey) return null
+ return createClient(supabaseUrl.replace(/\/$/, ''), publishableKey, {
+ auth: {
+ storageKey: recoveryKey + '-active',
+ detectSessionInUrl: false,
+ persistSession: false,
+ autoRefreshToken: false,
+ },
+ })
+}
+
+export type RecoveryClient = NonNullable>
+
+export async function closeRecoveryClient(client: RecoveryClient) {
+ try {
+ const { error } = await client.auth.signOut({ scope: 'local' })
+ return !error
+ } catch {
+ return false
+ } finally {
+ await client.auth.dispose().catch(() => undefined)
+ }
+}
+
+export async function verifyRecoveryHash(hash: string) {
+ const client = createRecoveryClient()
+ if (!client) return null
+ let verified = false
+ try {
+ const { data, error } = await client.auth.verifyOtp({ token_hash: hash, type: 'recovery' })
+ if (error) throw error
+ verified = Boolean(data.session && data.user && data.session.user.id === data.user.id)
+ return verified ? client : null
+ } finally {
+ if (!verified) await closeRecoveryClient(client)
+ }
+}
diff --git a/vercel.json b/vercel.json
index b6447c3..874eb1b 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1,9 +1,33 @@
{
+ "headers": [
+ {
+ "source": "/confirmar-recuperacion",
+ "headers": [
+ { "key": "Referrer-Policy", "value": "no-referrer" },
+ { "key": "Cache-Control", "value": "no-store" }
+ ]
+ },
+ {
+ "source": "/reset-password",
+ "headers": [
+ { "key": "Referrer-Policy", "value": "no-referrer" },
+ { "key": "Cache-Control", "value": "no-store" }
+ ]
+ }
+ ],
"rewrites": [
+ {
+ "source": "/confirmar-recuperacion",
+ "destination": "/index.html"
+ },
{
"source": "/verificar-correo",
"destination": "/index.html"
},
+ {
+ "source": "/recuperar-contrasena",
+ "destination": "/index.html"
+ },
{
"source": "/reset-password",
"destination": "/index.html"