feat(auth): gate OTP email sul portale cliente (v2.3 Phases 23-25)
Il portale /client/<slug> era protetto dal solo token in URL: chiunque ricevesse o intercettasse il link entrava, per sempre, senza identificarsi. Ora l'admin registra le email autorizzate per cliente e il cliente si identifica con un codice usa-e-getta prima di vedere qualsiasi dato. - Resend 6.18.1 + src/lib/mailer.ts (Result tipizzato, mai catch silenzioso) - migration 0015 (gia applicata a prod): client_emails, otp_codes, clients.sessions_valid_from. Additiva pura, conteggi verificati pre/post - admin: sezione "Accessi al portale" in /admin/clients/[id] con whitelist e revoca sessioni in blocco - gate: codice 6 cifre CSPRNG, hash SHA-256 (mai il codice in chiaro), TTL 15 min, max 5 tentativi, rate limit su entrambi gli endpoint, risposta identica per email in whitelist e non (no enumeration) - sessione: cookie HMAC per-cliente, 90 giorni, httpOnly/secure/lax Il gate sta in cima alla page, NON nel layout: nell'App Router il segmento page viene renderizzato in parallelo al layout, quindi gattare nel layout nascondeva la dashboard a schermo ma lasciava fasi, task e pagamenti nel payload RSC dell'HTML (46907 byte -> 17594 dopo il fix). Verificato. Verifica: build OK, 9/9 test E2E in locale contro il DB di produzione. NON DEPLOYARE prima di: RESEND_API_KEY+RESEND_FROM su Coolify e whitelist popolata per i 3 clienti reali (oggi vuota) - altrimenti il gate li chiude fuori dal loro portale. Checklist in .planning/STATE.md. SEND-01/02 (invio preventivo via email) rinviati a v2.4 su richiesta. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
// Verifica del codice OTP: se corretto, emette il cookie di sessione (90 giorni).
|
||||
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { rateLimit } from "@/lib/rate-limit";
|
||||
import { getClientIdentityByToken } from "@/lib/client-view";
|
||||
import { verifyOtp } from "@/lib/otp";
|
||||
import {
|
||||
SESSION_MAX_AGE_SECONDS,
|
||||
createSessionValue,
|
||||
sessionCookieName,
|
||||
} from "@/lib/client-session";
|
||||
|
||||
const schema = z.object({
|
||||
token: z.string().min(1),
|
||||
email: z.string().trim().toLowerCase().email(),
|
||||
code: z.string().trim().regex(/^\d{6}$/, "Il codice ha 6 cifre"),
|
||||
});
|
||||
|
||||
// Codice sbagliato, scaduto o inesistente danno lo stesso messaggio: dire
|
||||
// "scaduto" a un codice mai emesso confermerebbe che l'email è in whitelist.
|
||||
const INVALID = "Codice non valido o scaduto. Richiedine uno nuovo.";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const ip = request.headers.get("x-forwarded-for") ?? request.headers.get("x-real-ip") ?? "unknown";
|
||||
|
||||
try {
|
||||
const parsed = schema.safeParse(await request.json());
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: INVALID }, { status: 400 });
|
||||
}
|
||||
const { token, email, code } = parsed.data;
|
||||
|
||||
// 5 tentativi ogni 15 minuti per IP+cliente: con 1M di codici possibili e
|
||||
// TTL 15 min, indovinare per forza bruta è fuori portata.
|
||||
if (!rateLimit(`otp-vrf:${ip}:${token}`, 5, 15 * 60_000)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Troppi tentativi. Riprova tra qualche minuto." },
|
||||
{ status: 429 }
|
||||
);
|
||||
}
|
||||
|
||||
const client = await getClientIdentityByToken(token);
|
||||
if (!client) return NextResponse.json({ error: INVALID }, { status: 400 });
|
||||
|
||||
const result = await verifyOtp(client.id, email, code);
|
||||
if (!result.ok) {
|
||||
return NextResponse.json({ error: INVALID }, { status: 400 });
|
||||
}
|
||||
|
||||
const response = NextResponse.json({ success: true }, { status: 200 });
|
||||
response.cookies.set({
|
||||
name: sessionCookieName(client.id),
|
||||
value: await createSessionValue(client.id, email),
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
sameSite: "lax",
|
||||
path: "/client",
|
||||
maxAge: SESSION_MAX_AGE_SECONDS,
|
||||
});
|
||||
|
||||
return response;
|
||||
} catch (err) {
|
||||
console.error("/api/client/otp/verify error:", err);
|
||||
return NextResponse.json({ error: "Errore interno" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user