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:
2026-07-29 12:10:33 +02:00
parent b27b9d07ac
commit 8158038145
25 changed files with 1237 additions and 60 deletions
+18
View File
@@ -23,6 +23,7 @@ import {
leads,
tags,
clientTranscripts,
client_emails,
} from "@/db/schema";
import { eq, inArray, asc, desc, isNull, sql, and } from "drizzle-orm";
import { getPool } from "@/lib/taxonomy";
@@ -1098,6 +1099,23 @@ export async function getClientIdFromLead(leadId: string): Promise<string | null
return row?.client_id ?? null;
}
// ── ACCESSI PORTALE (whitelist OTP) ──────────────────────────────────────────
export type ClientAccessEmail = { id: string; email: string; created_at: Date };
/** Email autorizzate ad accedere al portale di un cliente. Admin-only. */
export async function getClientEmails(clientId: string): Promise<ClientAccessEmail[]> {
return db
.select({
id: client_emails.id,
email: client_emails.email,
created_at: client_emails.created_at,
})
.from(client_emails)
.where(eq(client_emails.client_id, clientId))
.orderBy(asc(client_emails.created_at));
}
export type LeadFieldOptions = { status: string[]; tags: string[] };
export async function getLeadFieldOptions(): Promise<LeadFieldOptions> {
+43
View File
@@ -0,0 +1,43 @@
import { cache } from "react";
import { cookies } from "next/headers";
import { getClientIdentityByToken, type ClientIdentity } from "@/lib/client-view";
import { sessionCookieName, verifySessionValue, type ClientSession } from "@/lib/client-session";
export type GateResult =
| { client: null; session: null }
| { client: ClientIdentity; session: ClientSession | null };
// cache(): layout e page risolvono lo stesso cliente nella stessa richiesta
// senza fare due giri di query.
const resolveClient = cache(getClientIdentityByToken);
/**
* Stato di accesso al portale per un token/slug.
*
* ⚠️ Va chiamata all'INIZIO della page, PRIMA di qualsiasi query sui dati del
* progetto — e la page deve tornare il gate se `session` è null.
*
* Metterla solo nel layout NON basta e non è una svista: nell'App Router il
* segmento `page` viene renderizzato in parallelo al layout, quindi un layout
* che non renderizza `{children}` nasconde la dashboard a schermo ma la sua
* query è già partita e il payload RSC finisce comunque nell'HTML. Verificato:
* fasi, task e pagamenti erano leggibili nel sorgente della pagina di accesso.
*/
export async function getClientGate(tokenOrSlug: string): Promise<GateResult> {
const client = await resolveClient(tokenOrSlug);
if (!client) return { client: null, session: null };
const cookieStore = await cookies();
const session = await verifySessionValue(
cookieStore.get(sessionCookieName(client.id))?.value,
client.id
);
// Revoca admin: una sessione firmata prima di sessions_valid_from non vale più.
const revoked =
session !== null &&
client.sessions_valid_from !== null &&
session.iat < client.sessions_valid_from.getTime();
return { client, session: revoked ? null : session };
}
+99
View File
@@ -0,0 +1,99 @@
// Sessione del portale cliente dopo la verifica OTP (v2.3).
//
// Stateless e firmata, come la sessione admin: nessuna tabella sessions da
// mantenere. Il payload porta client_id + email + istante di emissione, il tutto
// firmato HMAC-SHA256 con NEXTAUTH_SECRET — non falsificabile senza il segreto.
//
// La revoca lato admin non cancella cookie (non si può): alza
// clients.sessions_valid_from, e il gate scarta ogni sessione emessa prima.
// Per questo `iat` fa parte del payload firmato.
//
// Web Crypto, come admin-gate.ts e otp.ts: stesso modulo in edge e node.
export const SESSION_MAX_AGE_SECONDS = 90 * 24 * 60 * 60; // 90 giorni
export type ClientSession = { clientId: string; email: string; iat: number };
/**
* Un cookie per cliente: aprire il portale del cliente B non sloggia dal
* portale del cliente A. clientId è un nanoid — caratteri già validi in un
* nome di cookie.
*/
export function sessionCookieName(clientId: string): string {
return `ch_sess_${clientId}`;
}
function b64urlEncode(s: string): string {
const bytes = new TextEncoder().encode(s);
let binary = "";
for (const b of bytes) binary += String.fromCharCode(b);
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
function b64urlDecode(s: string): string {
const binary = atob(s.replace(/-/g, "+").replace(/_/g, "/"));
const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));
return new TextDecoder().decode(bytes);
}
async function sign(payload: string): Promise<string> {
const secret = process.env.NEXTAUTH_SECRET;
if (!secret) throw new Error("NEXTAUTH_SECRET must be set");
const key = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode(`${secret}:client-session:v1`),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"]
);
const sig = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(payload));
return Array.from(new Uint8Array(sig))
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}
/** Confronto a tempo costante — evita di far trapelare la firma dai tempi di risposta. */
function safeEqual(a: string, b: string): boolean {
if (a.length !== b.length) return false;
let diff = 0;
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
return diff === 0;
}
export async function createSessionValue(clientId: string, email: string): Promise<string> {
const payload = b64urlEncode(
JSON.stringify({ clientId, email, iat: Date.now() } satisfies ClientSession)
);
return `${payload}.${await sign(payload)}`;
}
/**
* Ritorna la sessione solo se: la firma è valida, il cookie appartiene a QUESTO
* cliente, e non ha superato la durata massima. Il confronto con
* sessions_valid_from (revoca admin) resta al chiamante, che ha già il record cliente.
*/
export async function verifySessionValue(
value: string | undefined,
clientId: string
): Promise<ClientSession | null> {
if (!value) return null;
const [payload, signature] = value.split(".");
if (!payload || !signature) return null;
if (!safeEqual(await sign(payload), signature)) return null;
let session: ClientSession;
try {
session = JSON.parse(b64urlDecode(payload));
} catch {
return null;
}
if (session.clientId !== clientId) return null;
if (typeof session.iat !== "number") return null;
if (Date.now() - session.iat > SESSION_MAX_AGE_SECONDS * 1000) return null;
return session;
}
+36
View File
@@ -158,6 +158,42 @@ export interface ClientProjectSummary {
}>;
}
/**
* Identità minima del cliente per il gate OTP: chi è, come si chiama il brand
* (per l'email) e da quando le sessioni sono valide (revoca admin).
* Nessun dato di progetto — il gate gira PRIMA che il cliente sia autenticato,
* quindi non deve caricare né esporre nulla di più.
* Ordine slug→token identico a getClientWithProjectsByToken e al proxy (D-06).
*/
export type ClientIdentity = {
id: string;
brand_name: string;
sessions_valid_from: Date | null;
};
export async function getClientIdentityByToken(
tokenOrSlug: string
): Promise<ClientIdentity | null> {
const cols = {
id: clients.id,
brand_name: clients.brand_name,
sessions_valid_from: clients.sessions_valid_from,
};
try {
let rows = await db.select(cols).from(clients).where(eq(clients.slug, tokenOrSlug)).limit(1);
if (rows.length === 0) {
rows = await db.select(cols).from(clients).where(eq(clients.token, tokenOrSlug)).limit(1);
}
return rows[0] ?? null;
} catch (err) {
console.error("[client-view] getClientIdentityByToken error:", err);
return null;
}
}
/**
* Resolves a token-or-slug to a client and returns the client's active projects.
* Lookup order: slug first, then token — mirrors middleware order (D-06).
+83
View File
@@ -0,0 +1,83 @@
// Unico punto di invio email dell'app (Resend).
//
// Il chiamante DEVE poter distinguere "non ho inviato di proposito" da "l'invio
// è fallito": la route OTP risponde sempre con lo stesso messaggio al client
// (no enumeration), ma internamente deve sapere se Resend è giù per loggarlo.
// Per questo sendEmail non lancia e non ingoia — ritorna un Result esplicito.
import { Resend } from "resend";
export type SendResult =
| { ok: true; id: string }
| { ok: false; error: string };
type SendInput = {
to: string;
subject: string;
html: string;
};
let client: Resend | null = null;
/** Lazy: le env var vengono lette all'invio, non all'import del modulo. */
function getClient(): Resend {
if (!client) {
const key = process.env.RESEND_API_KEY;
if (!key) throw new Error("RESEND_API_KEY must be set");
client = new Resend(key);
}
return client;
}
export async function sendEmail({ to, subject, html }: SendInput): Promise<SendResult> {
const from = process.env.RESEND_FROM;
if (!from) return { ok: false, error: "RESEND_FROM non configurata" };
try {
const { data, error } = await getClient().emails.send({ from, to, subject, html });
if (error) return { ok: false, error: error.message };
if (!data) return { ok: false, error: "Resend non ha restituito un id" };
return { ok: true, id: data.id };
} catch (e) {
return { ok: false, error: e instanceof Error ? e.message : "Errore invio email" };
}
}
// ── Template ────────────────────────────────────────────────────────────────
/**
* Email del codice OTP per l'accesso al portale cliente.
* HTML inline e minimale: i client di posta ignorano <style> e le classi CSS.
* Il codice non compare mai nel subject (resta visibile nelle notifiche push).
*/
export function otpEmailTemplate(code: string, brandName: string): { subject: string; html: string } {
return {
subject: "Il tuo codice di accesso",
html: `<!doctype html>
<html lang="it">
<body style="margin:0;padding:32px 16px;background:#f6f6f4;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif;color:#1a1a1a;">
<table role="presentation" cellpadding="0" cellspacing="0" style="max-width:480px;margin:0 auto;background:#ffffff;border-radius:12px;padding:32px;">
<tr><td>
<p style="margin:0 0 8px;font-size:14px;color:#71717a;">${escapeHtml(brandName)}</p>
<h1 style="margin:0 0 24px;font-size:20px;font-weight:600;">Il tuo codice di accesso</h1>
<p style="margin:0 0 24px;font-size:15px;line-height:1.6;">Inserisci questo codice nella pagina del portale per accedere:</p>
<p style="margin:0 0 24px;font-size:32px;font-weight:700;letter-spacing:8px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;">${escapeHtml(code)}</p>
<p style="margin:0 0 8px;font-size:14px;color:#71717a;line-height:1.6;">Il codice scade tra 15 minuti e può essere usato una sola volta.</p>
<p style="margin:0;font-size:14px;color:#71717a;line-height:1.6;">Se non hai richiesto tu l'accesso, ignora questa email.</p>
</td></tr>
</table>
</body>
</html>`,
};
}
/** Il brand name arriva dal DB ed è admin-controlled, ma finisce in HTML: si sanifica comunque. */
function escapeHtml(s: string): string {
return s
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
+129
View File
@@ -0,0 +1,129 @@
// Emissione e verifica dei codici OTP che aprono il portale cliente (v2.3).
//
// Il codice in chiaro esiste solo nell'email: in DB va l'hash. Chi legge otp_codes
// (backup, dump, accesso al Postgres) non ottiene un codice utilizzabile.
//
// Web Crypto invece di node:crypto — stesso motivo di src/lib/admin-gate.ts:
// il modulo deve funzionare identico in edge e node runtime.
import { customAlphabet } from "nanoid";
import { and, desc, eq, isNull, sql } from "drizzle-orm";
import { db } from "@/db";
import { client_emails, otp_codes } from "@/db/schema";
import { safeEqual } from "@/lib/admin-gate";
export const OTP_TTL_MS = 15 * 60 * 1000;
export const OTP_MAX_ATTEMPTS = 5;
// 6 cifre. customAlphabet è CSPRNG-backed, mai Math.random().
// Lo spazio è piccolo (1M) di proposito — è compensato da TTL 15 min,
// max 5 tentativi per codice e rate limit sull'endpoint di verifica.
const randomCode = customAlphabet("0123456789", 6);
async function hashCode(code: string, clientId: string): Promise<string> {
const secret = process.env.NEXTAUTH_SECRET;
if (!secret) throw new Error("NEXTAUTH_SECRET must be set");
// clientId nel materiale: lo stesso codice per due clienti dà hash diversi,
// quindi un hash rubato non è riutilizzabile altrove.
const data = new TextEncoder().encode(`${secret}:otp:v1:${clientId}:${code}`);
const digest = await crypto.subtle.digest("SHA-256", data);
return Array.from(new Uint8Array(digest))
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}
/** L'email è nella whitelist di questo cliente? Confronto case-insensitive. */
export async function isEmailWhitelisted(clientId: string, email: string): Promise<boolean> {
const rows = await db
.select({ id: client_emails.id })
.from(client_emails)
.where(
and(
eq(client_emails.client_id, clientId),
sql`lower(${client_emails.email}) = ${email.trim().toLowerCase()}`
)
)
.limit(1);
return rows.length > 0;
}
/**
* Genera un codice, ne salva l'hash e lo restituisce in chiaro al chiamante
* (che lo manda via email e poi lo dimentica).
* I codici precedenti ancora aperti per la stessa coppia vengono consumati:
* richiedere un nuovo codice invalida il vecchio.
*/
export async function issueOtp(clientId: string, email: string): Promise<string> {
const normalized = email.trim().toLowerCase();
await db
.update(otp_codes)
.set({ consumed_at: new Date() })
.where(
and(
eq(otp_codes.client_id, clientId),
sql`lower(${otp_codes.email}) = ${normalized}`,
isNull(otp_codes.consumed_at)
)
);
const code = randomCode();
await db.insert(otp_codes).values({
client_id: clientId,
email: normalized,
code_hash: await hashCode(code, clientId),
expires_at: new Date(Date.now() + OTP_TTL_MS),
});
return code;
}
export type VerifyResult = { ok: true } | { ok: false; reason: "invalid" | "expired" | "attempts" };
/**
* Verifica il codice contro l'ultimo emesso per (cliente, email).
* In caso di successo lo marca consumato — un codice vale una volta sola.
*/
export async function verifyOtp(
clientId: string,
email: string,
code: string
): Promise<VerifyResult> {
const normalized = email.trim().toLowerCase();
const rows = await db
.select()
.from(otp_codes)
.where(
and(
eq(otp_codes.client_id, clientId),
sql`lower(${otp_codes.email}) = ${normalized}`,
isNull(otp_codes.consumed_at)
)
)
.orderBy(desc(otp_codes.created_at))
.limit(1);
const row = rows[0];
if (!row) return { ok: false, reason: "invalid" };
if (row.expires_at.getTime() < Date.now()) return { ok: false, reason: "expired" };
if (row.attempts >= OTP_MAX_ATTEMPTS) {
// Bruciato: consumalo, così il prossimo tentativo non riparte da questo.
await db.update(otp_codes).set({ consumed_at: new Date() }).where(eq(otp_codes.id, row.id));
return { ok: false, reason: "attempts" };
}
const candidate = await hashCode(code.trim(), clientId);
if (!safeEqual(candidate, row.code_hash)) {
await db
.update(otp_codes)
.set({ attempts: row.attempts + 1 })
.where(eq(otp_codes.id, row.id));
return { ok: false, reason: "invalid" };
}
await db.update(otp_codes).set({ consumed_at: new Date() }).where(eq(otp_codes.id, row.id));
return { ok: true };
}