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
+84 -1
View File
@@ -19,8 +19,10 @@ import {
clients,
projects,
comments,
client_emails,
otp_codes,
} from "@/db/schema";
import { eq, asc, inArray } from "drizzle-orm";
import { eq, asc, and, isNull } from "drizzle-orm";
import { z } from "zod";
// ── ENTITY RESOLUTION ────────────────────────────────────────────────────────
@@ -380,4 +382,85 @@ export async function postAdminComment(id: string, formData: FormData) {
await db.insert(comments).values({ entity_type, entity_id, author: "admin", body });
const { path } = await resolveEntity(id);
revalidatePath(path);
}
// ── ACCESSI PORTALE (whitelist OTP) ──────────────────────────────────────────
// La whitelist è l'unico modo per entrare nel portale: nessuna auto-registrazione.
// Solo l'admin scrive qui — il gate OTP in /client/[token] si limita a leggerla.
const clientEmailSchema = z.object({
email: z
.string()
.trim()
.toLowerCase()
.min(1, "Email richiesta")
.email("Email non valida"),
});
export type AccessActionResult = { ok: true } | { ok: false; error: string };
export async function addClientEmail(
clientId: string,
formData: FormData
): Promise<AccessActionResult> {
await requireAdmin();
const parsed = clientEmailSchema.safeParse({ email: formData.get("email") });
if (!parsed.success) {
return { ok: false, error: parsed.error.issues[0].message };
}
const exists = await db
.select({ id: clients.id })
.from(clients)
.where(eq(clients.id, clientId))
.limit(1);
if (!exists[0]) return { ok: false, error: "Cliente non trovato" };
try {
await db.insert(client_emails).values({ client_id: clientId, email: parsed.data.email });
} catch {
// Unique index su (client_id, lower(email)): il duplicato non è un errore
// per l'admin, l'email è già autorizzata. Nessun altro vincolo può fallire qui.
return { ok: false, error: "Questa email è già autorizzata" };
}
revalidatePath(`/admin/clients/${clientId}`);
return { ok: true };
}
export async function removeClientEmail(
clientId: string,
emailId: string
): Promise<AccessActionResult> {
await requireAdmin();
// client_id nella WHERE: impedisce di cancellare una riga di un altro cliente
// passando un emailId arbitrario.
await db
.delete(client_emails)
.where(and(eq(client_emails.id, emailId), eq(client_emails.client_id, clientId)));
revalidatePath(`/admin/clients/${clientId}`);
return { ok: true };
}
/**
* Revoca tutte le sessioni portale già emesse per il cliente.
* Non cancella nulla: alza sessions_valid_from a "adesso", e ogni cookie firmato
* prima di questo istante smette di validare. I codici OTP pendenti vengono
* invalidati insieme, così un codice già inviato non riapre l'accesso.
*/
export async function revokeClientSessions(clientId: string): Promise<AccessActionResult> {
await requireAdmin();
const now = new Date();
await db.update(clients).set({ sessions_valid_from: now }).where(eq(clients.id, clientId));
await db
.update(otp_codes)
.set({ consumed_at: now })
.where(and(eq(otp_codes.client_id, clientId), isNull(otp_codes.consumed_at)));
revalidatePath(`/admin/clients/${clientId}`);
return { ok: true };
}
+10 -2
View File
@@ -1,6 +1,11 @@
import { notFound } from "next/navigation";
import { getClientWithProjects, getClientActiveOffers } from "@/lib/admin-queries";
import {
getClientWithProjects,
getClientActiveOffers,
getClientEmails,
} from "@/lib/admin-queries";
import { ClientActions } from "@/components/admin/ClientActions";
import { ClientAccessSection } from "@/components/admin/ClientAccessSection";
import Link from "next/link";
export const revalidate = 0;
@@ -11,9 +16,10 @@ export default async function ClientDetailPage({
params: Promise<{ id: string }>;
}) {
const { id } = await params;
const [data, activeOffers] = await Promise.all([
const [data, activeOffers, accessEmails] = await Promise.all([
getClientWithProjects(id),
getClientActiveOffers(id),
getClientEmails(id),
]);
if (!data) notFound();
@@ -167,6 +173,8 @@ export default async function ClientDetailPage({
</div>
</div>
)}
<ClientAccessSection clientId={id} emails={accessEmails} />
</div>
);
}
+65
View File
@@ -0,0 +1,65 @@
// Richiesta del codice OTP per accedere al portale cliente.
//
// OTP-07 (no enumeration): la risposta è IDENTICA che l'email sia in whitelist
// o no — stesso status, stesso corpo, nessuna differenza osservabile. Chi ha il
// link non deve poter scoprire quali indirizzi sono autorizzati.
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { rateLimit } from "@/lib/rate-limit";
import { getClientIdentityByToken } from "@/lib/client-view";
import { isEmailWhitelisted, issueOtp } from "@/lib/otp";
import { otpEmailTemplate, sendEmail } from "@/lib/mailer";
const schema = z.object({
token: z.string().min(1),
email: z.string().trim().toLowerCase().email(),
});
// Sempre questa, in ogni esito non-tecnico.
const NEUTRAL = {
message: "Se l'indirizzo è autorizzato, riceverai un codice tra pochi istanti.",
};
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: "Indirizzo email non valido" }, { status: 400 });
}
const { token, email } = parsed.data;
// Bucket per IP+cliente: 3 invii ogni 10 minuti. Impedisce di usare
// l'endpoint come mail-bomber e di sondare la whitelist a raffica.
if (!rateLimit(`otp-req:${ip}:${token}`, 3, 10 * 60_000)) {
return NextResponse.json(
{ error: "Troppe richieste. Riprova tra qualche minuto." },
{ status: 429 }
);
}
const client = await getClientIdentityByToken(token);
// Anche il cliente inesistente riceve la risposta neutra: il proxy ha già
// filtrato i link non validi, qui non si aggiunge un secondo oracolo.
if (!client) return NextResponse.json(NEUTRAL, { status: 200 });
if (!(await isEmailWhitelisted(client.id, email))) {
return NextResponse.json(NEUTRAL, { status: 200 });
}
const code = await issueOtp(client.id, email);
const { subject, html } = otpEmailTemplate(code, client.brand_name);
const sent = await sendEmail({ to: email, subject, html });
// Il fallimento di Resend si logga ma non si racconta al client, altrimenti
// "errore di invio" vs risposta neutra distinguerebbe le email in whitelist.
if (!sent.ok) console.error("[otp/request] invio fallito:", sent.error);
return NextResponse.json(NEUTRAL, { status: 200 });
} catch (err) {
console.error("/api/client/otp/request error:", err);
return NextResponse.json({ error: "Errore interno" }, { status: 500 });
}
}
+67
View File
@@ -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 });
}
}
+14 -1
View File
@@ -5,10 +5,23 @@ export const metadata: Metadata = {
description: 'Project status dashboard',
};
/**
* ⚠️ Il gate OTP NON sta qui, e non per dimenticanza.
*
* Nell'App Router il segmento `page` viene renderizzato in parallelo al layout:
* un layout che restituisce il form di accesso al posto di `{children}` nasconde
* la dashboard a schermo, ma la page ha già interrogato il DB e i suoi dati
* finiscono comunque nel payload RSC dell'HTML. Testato — fasi, task e pagamenti
* erano leggibili nel sorgente della pagina di accesso.
*
* Il gate è quindi in cima a ogni page sotto /client/[token]/ via
* getClientGate() (src/lib/client-gate.ts). Ogni NUOVA route qui sotto deve
* fare lo stesso, prima di qualsiasi query.
*/
export default function ClientLayout({
children,
}: {
children: React.ReactNode;
}) {
return <>{children}</>;
}
}
+10
View File
@@ -7,7 +7,9 @@ import {
type ClientView,
type ClientProjectSummary,
} from "@/lib/client-view";
import { getClientGate } from "@/lib/client-gate";
import { ClientDashboard } from "@/components/client-dashboard";
import { OtpGate } from "@/components/client/OtpGate";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import type { Comment } from "@/db/schema";
@@ -99,6 +101,14 @@ export default async function ClientPage({
}) {
const { token } = await params;
// ⚠️ Il gate va PRIMA di ogni query sui dati del progetto: se si interroga il
// DB e poi si decide di mostrare il form, i dati sono già nel payload RSC
// dell'HTML anche se non compaiono a schermo. Vedi src/lib/client-gate.ts.
const { client: identity, session } = await getClientGate(token);
if (identity && !session) {
return <OtpGate token={token} brandName={identity.brand_name} />;
}
const clientData = await getCachedClientData(token);
if (!clientData) notFound();
@@ -0,0 +1,148 @@
"use client";
// Gestione della whitelist email che apre il portale di un cliente (gate OTP v2.3).
// Scritto a token semantici anche se la pagina che lo ospita è ancora a palette
// vecchia: quando /admin/clients/[id] verrà rifatta, questa sezione non si tocca.
import { useRef, useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import {
addClientEmail,
removeClientEmail,
revokeClientSessions,
} from "@/app/admin/clients/[id]/actions";
import type { ClientAccessEmail } from "@/lib/admin-queries";
import { Button } from "@/components/ui/button";
export function ClientAccessSection({
clientId,
emails,
}: {
clientId: string;
emails: ClientAccessEmail[];
}) {
const [error, setError] = useState<string | null>(null);
const [revokeArmed, setRevokeArmed] = useState(false);
const [revokedAt, setRevokedAt] = useState<string | null>(null);
const [isPending, startTransition] = useTransition();
const formRef = useRef<HTMLFormElement>(null);
const router = useRouter();
function handleAdd(formData: FormData) {
setError(null);
startTransition(async () => {
const res = await addClientEmail(clientId, formData);
if (!res.ok) {
setError(res.error);
return;
}
formRef.current?.reset();
router.refresh();
});
}
function handleRemove(emailId: string) {
startTransition(async () => {
await removeClientEmail(clientId, emailId);
router.refresh();
});
}
function handleRevoke() {
if (!revokeArmed) {
setRevokeArmed(true);
return;
}
startTransition(async () => {
await revokeClientSessions(clientId);
setRevokeArmed(false);
setRevokedAt(new Date().toLocaleString("it-IT"));
router.refresh();
});
}
return (
<section className="mt-8">
<div className="mb-3 flex items-end justify-between gap-4 flex-wrap">
<div>
<p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
Accessi al portale
</p>
<p className="mt-1 text-xs text-muted-foreground">
Solo queste email possono richiedere il codice di accesso. Chi ha il link ma
non è in elenco non entra.
</p>
</div>
{revokeArmed ? (
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">
Tutti dovranno rifare l&apos;accesso. Confermi?
</span>
<Button size="sm" variant="destructive" onClick={handleRevoke} disabled={isPending}>
, revoca
</Button>
<Button size="sm" variant="ghost" onClick={() => setRevokeArmed(false)}>
Annulla
</Button>
</div>
) : (
<Button size="sm" variant="outline" onClick={handleRevoke} disabled={isPending}>
Revoca sessioni attive
</Button>
)}
</div>
{revokedAt && (
<p className="mb-3 text-xs text-muted-foreground">
Sessioni revocate il {revokedAt}.
</p>
)}
<div className="rounded-xl border border-border bg-card">
{emails.length === 0 ? (
<p className="px-4 py-6 text-center text-sm text-muted-foreground">
Nessuna email autorizzata il cliente non può ancora accedere al portale.
</p>
) : (
<ul className="divide-y divide-border">
{emails.map((e) => (
<li key={e.id} className="flex items-center justify-between gap-3 px-4 py-2.5">
<span className="min-w-0 truncate font-mono text-sm text-foreground">
{e.email}
</span>
<button
onClick={() => handleRemove(e.id)}
disabled={isPending}
className="shrink-0 text-xs text-muted-foreground underline-offset-2 hover:text-destructive hover:underline disabled:opacity-50"
>
Rimuovi
</button>
</li>
))}
</ul>
)}
<form
ref={formRef}
action={handleAdd}
className="flex items-center gap-2 border-t border-border px-4 py-3"
>
<input
type="email"
name="email"
required
placeholder="email@cliente.it"
autoComplete="off"
className="min-w-0 flex-1 rounded-lg border border-border bg-background px-3 py-1.5 text-sm text-foreground placeholder:text-muted-foreground focus:border-ring focus:outline-none focus:ring-1 focus:ring-ring"
/>
<Button type="submit" size="sm" disabled={isPending}>
Aggiungi
</Button>
</form>
</div>
{error && <p className="mt-2 text-xs text-destructive">{error}</p>}
</section>
);
}
+154
View File
@@ -0,0 +1,154 @@
"use client";
// Schermata di accesso al portale cliente: email → codice a 6 cifre.
// Design system a token, dual light/dark. Non usa ui/dialog.tsx, che è ancora
// a palette raw e romperebbe il tema scuro.
import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
type Step = "email" | "code";
export function OtpGate({ token, brandName }: { token: string; brandName: string }) {
const [step, setStep] = useState<Step>("email");
const [email, setEmail] = useState("");
const [code, setCode] = useState("");
const [notice, setNotice] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const router = useRouter();
async function requestCode(e: React.FormEvent) {
e.preventDefault();
setLoading(true);
setError(null);
try {
const res = await fetch("/api/client/otp/request", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token, email }),
});
const data = await res.json();
if (!res.ok) {
setError(data.error ?? "Errore. Riprova.");
return;
}
// La risposta è neutra per costruzione: si passa allo step successivo
// anche se l'email non è autorizzata, altrimenti l'UI rivelerebbe la
// whitelist che l'API si è preoccupata di non rivelare.
setNotice(data.message);
setStep("code");
} catch {
setError("Connessione non riuscita. Riprova.");
} finally {
setLoading(false);
}
}
async function submitCode(e: React.FormEvent) {
e.preventDefault();
setLoading(true);
setError(null);
try {
const res = await fetch("/api/client/otp/verify", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token, email, code }),
});
const data = await res.json();
if (!res.ok) {
setError(data.error ?? "Codice non valido.");
return;
}
// Il cookie è già impostato dalla risposta: basta ricaricare e il layout
// lascerà passare.
router.refresh();
} catch {
setError("Connessione non riuscita. Riprova.");
} finally {
setLoading(false);
}
}
return (
<main className="flex min-h-screen items-center justify-center bg-background px-4 py-12">
<div className="w-full max-w-sm">
<p className="mb-1 text-sm text-muted-foreground">{brandName}</p>
<h1 className="mb-2 text-2xl font-semibold tracking-tight text-foreground">
Accedi al tuo portale
</h1>
{step === "email" ? (
<>
<p className="mb-6 text-sm leading-relaxed text-muted-foreground">
Inserisci l&apos;indirizzo email concordato: ti inviamo un codice per entrare.
</p>
<form onSubmit={requestCode} className="space-y-3">
<input
type="email"
value={email}
onChange={(ev) => setEmail(ev.target.value)}
required
autoFocus
autoComplete="email"
placeholder="nome@azienda.it"
className="w-full rounded-lg border border-border bg-card px-3 py-2.5 text-sm text-foreground placeholder:text-muted-foreground focus:border-ring focus:outline-none focus:ring-1 focus:ring-ring"
/>
<Button type="submit" disabled={loading} className="w-full">
{loading ? "Invio…" : "Inviami il codice"}
</Button>
</form>
</>
) : (
<>
<p className="mb-6 text-sm leading-relaxed text-muted-foreground">{notice}</p>
<form onSubmit={submitCode} className="space-y-3">
<input
type="text"
inputMode="numeric"
pattern="[0-9]{6}"
maxLength={6}
value={code}
onChange={(ev) => setCode(ev.target.value.replace(/\D/g, ""))}
required
autoFocus
autoComplete="one-time-code"
placeholder="000000"
className="w-full rounded-lg border border-border bg-card px-3 py-2.5 text-center font-mono text-lg tracking-[0.4em] text-foreground placeholder:tracking-[0.4em] placeholder:text-muted-foreground focus:border-ring focus:outline-none focus:ring-1 focus:ring-ring"
/>
<Button type="submit" disabled={loading || code.length !== 6} className="w-full">
{loading ? "Verifica…" : "Entra"}
</Button>
</form>
<button
onClick={() => {
setStep("email");
setCode("");
setError(null);
setNotice(null);
}}
className="mt-4 text-xs text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"
>
Usa un altro indirizzo
</button>
</>
)}
{error && <p className="mt-4 text-sm text-destructive">{error}</p>}
<p className="mt-8 text-xs leading-relaxed text-muted-foreground">
Il codice scade dopo 15 minuti. Una volta entrato resti collegato per 90 giorni su
questo dispositivo.
</p>
</div>
</main>
);
}
+62
View File
@@ -0,0 +1,62 @@
-- Additive: email OTP access gate for the client portal (milestone v2.3).
--
-- Il portale /client/<slug> era protetto dal solo token in URL: chi ha il link
-- entra. Da qui l'admin registra le email autorizzate per cliente (whitelist,
-- niente auto-registrazione) e il cliente si identifica con un codice usa-e-getta
-- prima di vedere la dashboard.
--
-- client_emails → whitelist 1-a-molti (un cliente può avere più soci)
-- otp_codes → codici emessi, hashati; il codice in chiaro non è mai persistito
-- clients.sessions_valid_from → revoca: alzarla invalida in blocco le sessioni
-- già emesse per quel cliente
--
-- Nessun DROP, nessun TRUNCATE, nessuna colonna rimossa. Le tabelle protette
-- (clients, projects, payments, phases) sono toccate solo in ADD COLUMN.
-- Applicare a prod via SSH+docker exec PRIMA di pushare il codice dipendente.
-- Idempotente: safe to re-run.
-- ── Whitelist email per cliente ──────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS client_emails (
id text PRIMARY KEY,
client_id text NOT NULL REFERENCES clients(id) ON DELETE CASCADE,
email text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
-- Unicità case-insensitive: mario@x.it e Mario@X.it sono la stessa persona.
CREATE UNIQUE INDEX IF NOT EXISTS client_emails_client_email_idx
ON client_emails (client_id, lower(email));
-- ── Codici OTP ───────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS otp_codes (
id text PRIMARY KEY,
client_id text NOT NULL REFERENCES clients(id) ON DELETE CASCADE,
email text NOT NULL,
code_hash text NOT NULL,
expires_at timestamptz NOT NULL,
consumed_at timestamptz,
attempts integer NOT NULL DEFAULT 0,
created_at timestamptz NOT NULL DEFAULT now()
);
-- Lookup del codice più recente per (cliente, email) in fase di verifica.
CREATE INDEX IF NOT EXISTS otp_codes_client_email_idx
ON otp_codes (client_id, lower(email), created_at DESC);
-- ── Revoca sessioni ──────────────────────────────────────────────────────────
-- NULL = nessuna revoca mai effettuata; ogni sessione firmata è valida.
ALTER TABLE clients ADD COLUMN IF NOT EXISTS sessions_valid_from timestamptz;
-- ── Seed whitelist dai contatti già presenti ────────────────────────────────
-- clients.email arriva dalla conversione lead→cliente (migration 0011). Chi ce
-- l'ha parte con la whitelist già popolata e non resta fuori dal proprio portale.
INSERT INTO client_emails (id, client_id, email)
SELECT
substr(md5(random()::text || c.id), 1, 21),
c.id,
btrim(c.email)
FROM clients c
WHERE c.email IS NOT NULL
AND btrim(c.email) <> ''
AND btrim(c.email) LIKE '%@%'
ON CONFLICT DO NOTHING;
+54 -1
View File
@@ -40,11 +40,60 @@ export const clients = pgTable("clients", {
// Conversazioni inbox: timestamp of the admin's last read of this client's
// conversation. NULL = never read (treated as unread). Set via markConversationRead.
admin_last_read_at: timestamp("admin_last_read_at", { withTimezone: true }),
// OTP gate (v2.3): revoca in blocco delle sessioni portale già emesse.
// Una sessione è valida solo se firmata DOPO questo istante. NULL = mai revocate.
sessions_valid_from: timestamp("sessions_valid_from", { withTimezone: true }),
created_at: timestamp("created_at", { withTimezone: true })
.notNull()
.defaultNow(),
});
// ============ CLIENT ACCESS (OTP) ============
// Whitelist admin-gestita: nessuna auto-registrazione. Un cliente può avere più
// email (i soci del progetto accedono allo stesso portale).
export const client_emails = pgTable(
"client_emails",
{
id: text("id")
.primaryKey()
.$defaultFn(() => nanoid()),
client_id: text("client_id")
.notNull()
.references(() => clients.id, { onDelete: "cascade" }),
email: text("email").notNull(),
created_at: timestamp("created_at", { withTimezone: true })
.notNull()
.defaultNow(),
},
(table) => [
// L'indice reale è su (client_id, lower(email)) — vedi 0015_otp_access.sql.
// Drizzle non modella le expression index: qui serve solo a documentarlo.
uniqueIndex("client_emails_client_email_idx").on(table.client_id, table.email),
]
);
// Codici OTP emessi. Si persiste solo l'hash: il codice in chiaro vive nell'email.
export const otp_codes = pgTable(
"otp_codes",
{
id: text("id")
.primaryKey()
.$defaultFn(() => nanoid()),
client_id: text("client_id")
.notNull()
.references(() => clients.id, { onDelete: "cascade" }),
email: text("email").notNull(),
code_hash: text("code_hash").notNull(),
expires_at: timestamp("expires_at", { withTimezone: true }).notNull(),
consumed_at: timestamp("consumed_at", { withTimezone: true }),
attempts: integer("attempts").notNull().default(0),
created_at: timestamp("created_at", { withTimezone: true })
.notNull()
.defaultNow(),
},
(table) => [index("otp_codes_client_email_idx").on(table.client_id, table.email)]
);
// ============ PROJECTS ============
export const projects = pgTable("projects", {
id: text("id")
@@ -799,4 +848,8 @@ export type NewReminder = typeof reminders.$inferInsert;
export type ClientTranscript = typeof clientTranscripts.$inferSelect;
export type NewClientTranscript = typeof clientTranscripts.$inferInsert;
export type Proposal = typeof proposals.$inferSelect;
export type NewProposal = typeof proposals.$inferInsert;
export type NewProposal = typeof proposals.$inferInsert;
export type ClientEmail = typeof client_emails.$inferSelect;
export type NewClientEmail = typeof client_emails.$inferInsert;
export type OtpCode = typeof otp_codes.$inferSelect;
export type NewOtpCode = typeof otp_codes.$inferInsert;
+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 };
}