import { randomBytes, randomUUID } from "node:crypto"; import { mkdir, writeFile } from "node:fs/promises"; import path from "node:path"; import { Readable } from "node:stream"; import { z } from "zod"; import sharp from "sharp"; import { AppError, attachUser, clientIp, createMailer, createRateLimiter, currentUser, hashPassword, link, rateLimitKey, requireAuth, sha256, verifyPassword, type App, type Config, type Db, type SessionUser, } from "@cohaise/server"; import { audit } from "../access.js"; import { absolutePath, fileExists, openForDownload } from "../storage.js"; const AVATAR_MAX_BYTES = 8 * 1024 * 1024; const AVATAR_PX = 512; const HOUR_MS = 3600_000; const avatarRelativePath = (userId: string): string => path.posix.join("avatars", `${userId}.webp`); const newToken = (): string => randomBytes(32).toString("base64url"); const parse = (schema: z.ZodType, body: unknown): T => { const result = schema.safeParse(body); if (!result.success) { const issue = result.error.issues[0]; throw AppError.badRequest( issue ? `${issue.path.join(".") || "corps"} : ${issue.message}` : "Corps invalide.", ); } return result.data; }; const profileInput = z.object({ first_name: z.string().trim().min(1).max(50), last_name: z.string().trim().min(1).max(50), }); const forgotInput = z.object({ email: z.string().trim().email().max(255) }); const resetInput = z.object({ token: z.string().min(10).max(400), password: z.string().min(8).max(1024), }); const emailChangeInput = z.object({ password: z.string().min(1).max(1024), new_email: z.string().trim().email().max(255), }); export const registerAccountRoutes = (app: App, db: Db, config: Config): void => { app.use("/api/cloud/account/*", attachUser(db)); app.use("/api/cloud/account", attachUser(db)); const mailer = createMailer(config); const limiter = createRateLimiter(config.RATE_LIMIT_LOGIN_MAX, config.RATE_LIMIT_LOGIN_WINDOW_MS); const throttle = (context: Parameters[0], extra: string): void => { const ip = clientIp(context, config.TRUST_PROXY); const key = `${rateLimitKey(ip)}:${extra}`; if (!limiter.allow(key)) { throw AppError.unprocessable("Trop de tentatives. Reessayez dans une minute."); } }; app.patch("/api/cloud/account/profile", requireAuth, async (context) => { const user = currentUser(context); const data = parse(profileInput, await context.req.json().catch(() => null)); await db.exec("UPDATE users SET first_name = ?, last_name = ? WHERE id = ?", [ data.first_name, data.last_name, user.id, ]); await audit(db, context, user, "profile.update", "user", user.id, null, config.TRUST_PROXY); return context.json({ ok: true, first_name: data.first_name, last_name: data.last_name }); }); app.get("/api/cloud/account/sessions", requireAuth, async (context) => { const user = currentUser(context); const current = sha256(context.get("token") ?? ""); const rows = await db.query<{ id: string; token_hash: string; ip_address: string | null; user_agent: string | null; created_at: string; last_seen_at: string; expires_at: string; }>( `SELECT id, token_hash, ip_address, user_agent, created_at, last_seen_at, expires_at FROM user_sessions WHERE user_id = ? AND revoked_at IS NULL AND expires_at > UTC_TIMESTAMP() ORDER BY last_seen_at DESC`, [user.id], ); return context.json({ sessions: rows.map((row) => ({ id: row.id, ip_address: row.ip_address, user_agent: row.user_agent, created_at: row.created_at, last_seen_at: row.last_seen_at, expires_at: row.expires_at, current: row.token_hash === current, })), }); }); app.delete("/api/cloud/account/sessions/:id", requireAuth, async (context) => { const user = currentUser(context); const id = context.req.param("id") ?? ""; const result = await db.exec( "UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE id = ? AND user_id = ? AND revoked_at IS NULL", [id, user.id], ); if (result.affectedRows === 0) throw AppError.notFound("Session introuvable."); return context.json({ ok: true }); }); app.delete("/api/cloud/account/sessions", requireAuth, async (context) => { const user = currentUser(context); const current = sha256(context.get("token") ?? ""); await db.exec( "UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ? AND token_hash <> ? AND revoked_at IS NULL", [user.id, current], ); return context.json({ ok: true }); }); app.put("/api/cloud/account/avatar", requireAuth, async (context) => { const user = currentUser(context); const declared = Number(context.req.header("content-length") ?? ""); if (!Number.isSafeInteger(declared) || declared <= 0) { throw AppError.badRequest("Envoi d'image invalide."); } if (declared > AVATAR_MAX_BYTES) { throw AppError.payloadTooLarge("L'image ne doit pas depasser 8 Mo."); } const source = Buffer.from(await context.req.arrayBuffer()); let processed: Buffer; try { processed = await sharp(source, { failOn: "none" }) .rotate() .resize(AVATAR_PX, AVATAR_PX, { fit: "cover" }) .webp({ quality: 82 }) .toBuffer(); } catch { throw AppError.badRequest("Le fichier n'est pas une image exploitable."); } const location = await db.one<{ id: number }>( `SELECT id FROM storage_locations WHERE is_active = 1 AND deleted_at IS NULL ORDER BY id LIMIT 1`, ); if (!location) throw AppError.serviceUnavailable("Aucun emplacement de stockage disponible."); const relative = avatarRelativePath(user.id); const destination = absolutePath(config.VARIANT_DIR, relative); await mkdir(path.dirname(destination), { recursive: true }); await writeFile(destination, processed); const size = processed.byteLength; const previous = await db.one<{ storage_location_id: number; size_bytes: number }>( "SELECT storage_location_id, size_bytes FROM user_avatars WHERE user_id = ?", [user.id], ); await db.transaction(async (connection) => { if (previous) { await connection.execute( "UPDATE storage_locations SET used_bytes = GREATEST(0, CAST(used_bytes AS SIGNED) - ?) WHERE id = ?", [previous.size_bytes, previous.storage_location_id], ); } await connection.execute( `UPDATE storage_locations SET used_bytes = used_bytes + ? WHERE id = ?`, [size, location.id], ); await connection.execute( `INSERT INTO user_avatars (user_id, storage_location_id, original_path, mime_type, size_bytes, width, height) VALUES (?, ?, ?, 'image/webp', ?, ?, ?) ON DUPLICATE KEY UPDATE storage_location_id = VALUES(storage_location_id), original_path = VALUES(original_path), mime_type = VALUES(mime_type), size_bytes = VALUES(size_bytes), width = VALUES(width), height = VALUES(height)`, [user.id, location.id, relative, processed.byteLength, AVATAR_PX, AVATAR_PX], ); }); await audit(db, context, user, "avatar.update", "user", user.id, null, config.TRUST_PROXY); return context.json({ ok: true }); }); app.get("/api/cloud/account/avatar/:userId", requireAuth, async (context) => { const target = context.req.param("userId") ?? ""; const row = await db.one<{ original_path: string; size_bytes: number }>( "SELECT original_path, size_bytes FROM user_avatars WHERE user_id = ?", [target], ); if (!row) throw AppError.notFound("Avatar introuvable."); const absolute = absolutePath(config.VARIANT_DIR, row.original_path); if (!(await fileExists(absolute))) throw AppError.notFound("Avatar introuvable."); const stream = Readable.toWeb(openForDownload(absolute)) as ReadableStream; return new Response(stream, { headers: { "content-type": "image/webp", "content-length": String(row.size_bytes), "cache-control": "private, max-age=86400", }, }); }); app.delete("/api/cloud/account/avatar", requireAuth, async (context) => { const user = currentUser(context); const row = await db.one<{ storage_location_id: number; size_bytes: number }>( "SELECT storage_location_id, size_bytes FROM user_avatars WHERE user_id = ?", [user.id], ); if (!row) throw AppError.notFound("Avatar introuvable."); await db.transaction(async (connection) => { await connection.execute("DELETE FROM user_avatars WHERE user_id = ?", [user.id]); await connection.execute( "UPDATE storage_locations SET used_bytes = GREATEST(0, CAST(used_bytes AS SIGNED) - ?) WHERE id = ?", [row.size_bytes, row.storage_location_id], ); }); return context.json({ ok: true }); }); app.post("/api/cloud/account/forgot-password", async (context) => { const data = parse(forgotInput, await context.req.json().catch(() => null)); throttle(context, `forgot:${data.email.toLowerCase()}`); const user = await db.one<{ id: string; email: string }>( "SELECT id, email FROM users WHERE active_email = ? AND is_active = 1", [data.email], ); // Reponse identique que le compte existe ou non : rien ne permet de // decouvrir une adresse enregistree. if (user) { const token = newToken(); await db.exec( "INSERT INTO password_reset_tokens (id, user_id, token_hash, expires_at) VALUES (?, ?, ?, ?)", [randomUUID(), user.id, sha256(token), new Date(Date.now() + HOUR_MS)], ); const url = link(config, `/reset-password?token=${encodeURIComponent(token)}`); await mailer .send({ to: user.email, subject: "CoHaiSe Cloud — reinitialisation du mot de passe", text: `Une reinitialisation de mot de passe a ete demandee pour ce compte.\n\n${url}\n\nCe lien expire dans une heure. Si vous n'etes pas a l'origine de cette demande, ignorez ce message.`, }) .catch(() => undefined); } return context.json({ ok: true }); }); app.post("/api/cloud/account/reset-password", async (context) => { const data = parse(resetInput, await context.req.json().catch(() => null)); throttle(context, "reset"); const row = await db.one<{ id: string; user_id: string }>( `SELECT id, user_id FROM password_reset_tokens WHERE token_hash = ? AND used_at IS NULL AND expires_at > UTC_TIMESTAMP()`, [sha256(data.token)], ); if (!row) throw AppError.badRequest("Lien invalide ou expire."); const hash = await hashPassword(data.password); const account = await db.one<{ email: string; first_name: string; last_name: string }>( "SELECT email, first_name, last_name FROM users WHERE id = ?", [row.user_id], ); await db.transaction(async (connection) => { await connection.execute( "UPDATE users SET password_hash = ?, must_change_password = 0, password_changed_at = UTC_TIMESTAMP() WHERE id = ?", [hash, row.user_id], ); await connection.execute( "UPDATE password_reset_tokens SET used_at = UTC_TIMESTAMP() WHERE id = ?", [row.id], ); await connection.execute( "UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ? AND revoked_at IS NULL", [row.user_id], ); }); if (account) { const actor: SessionUser = { id: row.user_id, email: account.email, first_name: account.first_name, last_name: account.last_name, role_slug: "user", role_name: "", is_active: 1, must_change_password: 0, }; await audit(db, context, actor, "password.reset", "user", row.user_id, null, config.TRUST_PROXY); } return context.json({ ok: true }); }); app.post("/api/cloud/account/email-change", requireAuth, async (context) => { const user = currentUser(context); const data = parse(emailChangeInput, await context.req.json().catch(() => null)); throttle(context, `email:${user.id}`); const row = await db.one<{ password_hash: string }>( "SELECT password_hash FROM users WHERE id = ? AND deleted_at IS NULL", [user.id], ); if (!row || !(await verifyPassword(data.password, row.password_hash))) { throw AppError.unauthorized("Mot de passe incorrect."); } if (data.new_email.toLowerCase() === user.email.toLowerCase()) { throw AppError.badRequest("La nouvelle adresse est identique a l'actuelle."); } const taken = await db.one("SELECT id FROM users WHERE active_email = ?", [data.new_email]); if (taken) throw AppError.conflict("Cette adresse est deja utilisee."); const token = newToken(); await db.exec( `INSERT INTO email_change_requests (id, user_id, new_email, token_hash, expires_at) VALUES (?, ?, ?, ?, ?)`, [randomUUID(), user.id, data.new_email, sha256(token), new Date(Date.now() + HOUR_MS)], ); const url = link(config, `/confirm-email?token=${encodeURIComponent(token)}`); await mailer .send({ to: data.new_email, subject: "CoHaiSe Cloud — confirmez votre nouvelle adresse", text: `Une demande de changement d'adresse a ete faite pour votre compte CoHaiSe Cloud.\n\n${url}\n\nCe lien expire dans une heure. Sans confirmation, l'adresse reste inchangee.`, }) .catch(() => undefined); await audit( db, context, user, "email.change_request", "user", user.id, { new_email: data.new_email }, config.TRUST_PROXY, ); return context.json({ ok: true }); }); app.post("/api/cloud/account/email-change/confirm", async (context) => { const data = parse( z.object({ token: z.string().min(10).max(400) }), await context.req.json().catch(() => null), ); const row = await db.one<{ id: string; user_id: string; new_email: string }>( `SELECT id, user_id, new_email FROM email_change_requests WHERE token_hash = ? AND used_at IS NULL AND expires_at > UTC_TIMESTAMP()`, [sha256(data.token)], ); if (!row) throw AppError.badRequest("Lien invalide ou expire."); const taken = await db.one("SELECT id FROM users WHERE active_email = ? AND id <> ?", [ row.new_email, row.user_id, ]); if (taken) throw AppError.conflict("Cette adresse est deja utilisee."); await db.transaction(async (connection) => { await connection.execute("UPDATE users SET email = ? WHERE id = ?", [ row.new_email, row.user_id, ]); await connection.execute( "UPDATE email_change_requests SET used_at = UTC_TIMESTAMP() WHERE id = ?", [row.id], ); }); return context.json({ ok: true, email: row.new_email }); }); };