Le niveau `cloud` etait redondant : il ne reste qu'une seule application. - backend/cloud/* -> backend/*, frontend/cloud/* -> frontend/* - workspaces npm : frontend et backend ; reference tsconfig ./backend - extends tsconfig.base corrige (../ au lieu de ../../) - docker-compose : APP_DIR backend/frontend, montage ./backend/migrations - deploy.yml : reconstruit aussi l'image migrate - chemins mis a jour dans les docs, le Makefile et docker/README.md
224 lines
7.3 KiB
TypeScript
224 lines
7.3 KiB
TypeScript
import { createHash, randomBytes, randomUUID, scrypt as scryptCallback, timingSafeEqual } from "node:crypto";
|
|
import { promisify } from "node:util";
|
|
import type { Context, Next } from "hono";
|
|
import { getCookie, setCookie, deleteCookie } from "hono/cookie";
|
|
import type { Db } from "./db.js";
|
|
import { AppError } from "./errors.js";
|
|
|
|
const scrypt = promisify(scryptCallback) as (
|
|
password: string | Buffer,
|
|
salt: Buffer,
|
|
keylen: number,
|
|
options: { N: number; r: number; p: number; maxmem?: number },
|
|
) => Promise<Buffer>;
|
|
|
|
/**
|
|
* scrypt du module natif, pas une dependance externe. Une lib native a compiler
|
|
* est la facon la plus rapide de casser un build sur une machine cible : argon2
|
|
* ou bcrypt produisent un binaire qui n'est pas portable sans outilchain.
|
|
* node:crypto est deja la, et scrypt est un KDF defini par RFC 7914.
|
|
*/
|
|
const SCRYPT = { N: 16384, r: 8, p: 1, keylen: 64, maxmem: 32 * 1024 * 1024 };
|
|
|
|
export const hashPassword = async (password: string): Promise<string> => {
|
|
if (Buffer.byteLength(password) < 8) {
|
|
throw AppError.badRequest("Le mot de passe doit contenir au moins 8 caracteres.");
|
|
}
|
|
const salt = randomBytes(16);
|
|
const derived = await scrypt(password, salt, SCRYPT.keylen, SCRYPT);
|
|
return `scrypt$${SCRYPT.N}$${SCRYPT.r}$${SCRYPT.p}$${salt.toString("base64")}$${derived.toString("base64")}`;
|
|
};
|
|
|
|
export const verifyPassword = async (password: string, stored: string): Promise<boolean> => {
|
|
const parts = stored.split("$");
|
|
if (parts.length !== 6 || parts[0] !== "scrypt") return false;
|
|
const [, n, r, p, saltB64, hashB64] = parts;
|
|
const salt = Buffer.from(saltB64 ?? "", "base64");
|
|
const expected = Buffer.from(hashB64 ?? "", "base64");
|
|
if (expected.length === 0) return false;
|
|
|
|
const derived = await scrypt(password, salt, expected.length, {
|
|
N: Number(n),
|
|
r: Number(r),
|
|
p: Number(p),
|
|
maxmem: SCRYPT.maxmem,
|
|
});
|
|
return derived.length === expected.length && timingSafeEqual(derived, expected);
|
|
};
|
|
|
|
export const sha256 = (value: string): string => createHash("sha256").update(value).digest("hex");
|
|
|
|
/**
|
|
* Portrait de l'utilisateur porte par la session.
|
|
*
|
|
* Les budgets de stockage n'y figurent pas : une valeur figee dans un cookie
|
|
* serait fausse des la premiere ecriture. Chaque route qui en a besoin relit
|
|
* les colonnes en base au moment de l'usage.
|
|
*/
|
|
export interface SessionUser {
|
|
id: string;
|
|
email: string;
|
|
first_name: string;
|
|
last_name: string;
|
|
role_slug: string;
|
|
role_name: string;
|
|
is_active: number;
|
|
must_change_password: number;
|
|
}
|
|
|
|
export interface SessionMeta {
|
|
ipAddress?: string | null | undefined;
|
|
userAgent?: string | null | undefined;
|
|
}
|
|
|
|
export const SESSION_COOKIE = "cohaise_session";
|
|
|
|
/**
|
|
* Le jeton brut part dans le cookie, son empreinte SHA-256 dans la base.
|
|
* Une copie de la base ne donne donc aucune session ouvrable : il faudrait
|
|
* en plus la table des cookies, qui n'existe pas.
|
|
*/
|
|
export const createSession = async (
|
|
db: Db,
|
|
userId: string,
|
|
meta: SessionMeta,
|
|
ttlHours: number,
|
|
): Promise<{ token: string; expiresAt: Date }> => {
|
|
const token = randomBytes(32).toString("base64url");
|
|
const expiresAt = new Date(Date.now() + ttlHours * 3600_000);
|
|
|
|
await db.exec(
|
|
`INSERT INTO user_sessions (id, user_id, token_hash, ip_address, user_agent, expires_at)
|
|
VALUES (?, ?, ?, ?, ?, ?)`,
|
|
[
|
|
randomUUID(),
|
|
userId,
|
|
sha256(token),
|
|
meta.ipAddress ?? null,
|
|
meta.userAgent?.slice(0, 255) ?? null,
|
|
expiresAt,
|
|
],
|
|
);
|
|
return { token, expiresAt };
|
|
};
|
|
|
|
export const resolveSession = async (db: Db, token: string): Promise<SessionUser | null> => {
|
|
const row = await db.one<SessionUser & { last_seen_at: string }>(
|
|
`SELECT u.id, u.email, u.first_name, u.last_name,
|
|
r.slug AS role_slug, r.name AS role_name,
|
|
u.is_active, u.must_change_password,
|
|
s.last_seen_at
|
|
FROM user_sessions s
|
|
JOIN users u ON u.id = s.user_id
|
|
JOIN roles r ON r.id = u.role_id
|
|
WHERE s.token_hash = ?
|
|
AND s.revoked_at IS NULL
|
|
AND s.expires_at > UTC_TIMESTAMP()
|
|
AND u.deleted_at IS NULL
|
|
AND u.is_active = 1`,
|
|
[sha256(token)],
|
|
);
|
|
if (!row) return null;
|
|
// Etat vu, avec un decalage de 60 s pour ne pas ecrire a chaque requete.
|
|
await db.exec(
|
|
"UPDATE user_sessions SET last_seen_at = UTC_TIMESTAMP() WHERE token_hash = ? AND last_seen_at < UTC_TIMESTAMP(3) - INTERVAL 60 SECOND",
|
|
[sha256(token)],
|
|
);
|
|
return row;
|
|
};
|
|
|
|
export const revokeSession = async (db: Db, token: string): Promise<void> => {
|
|
await db.exec("UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE token_hash = ?", [
|
|
sha256(token),
|
|
]);
|
|
};
|
|
|
|
export const purgeExpiredSessions = async (db: Db): Promise<number> => {
|
|
const result = await db.exec("DELETE FROM user_sessions WHERE expires_at < UTC_TIMESTAMP()");
|
|
return result.affectedRows;
|
|
};
|
|
|
|
/**
|
|
* Secure depend du schema reel de la requete, pas d'une origine configuree.
|
|
*
|
|
* Deriver Secure de PUBLIC_ORIGIN rendait tout test local impossible : le
|
|
* navigateur rejette en HTTP un cookie marque Secure, donc la connexion
|
|
* echouait sans message exploitable. A l'inverse, un cookie non Secure servi en
|
|
* HTTPS laisserait le jeton circuler en clair.
|
|
*
|
|
* X-Forwarded-Proto n'est pris en compte que si le service fait confiance a son
|
|
* proxy ; sinon la connexion parle d'elle-meme.
|
|
*/
|
|
export const isHttpsRequest = (context: Context, trustProxy: boolean): boolean => {
|
|
if (trustProxy) {
|
|
const forwarded = context.req.header("x-forwarded-proto");
|
|
if (forwarded) return forwarded.split(",")[0]?.trim() === "https";
|
|
}
|
|
return context.req.raw.url.startsWith("https:");
|
|
};
|
|
|
|
export const setSessionCookie = (
|
|
context: Context,
|
|
token: string,
|
|
expiresAt: Date,
|
|
secure: boolean,
|
|
): void => {
|
|
setCookie(context, SESSION_COOKIE, token, {
|
|
httpOnly: true,
|
|
sameSite: "Lax",
|
|
secure,
|
|
path: "/",
|
|
expires: expiresAt,
|
|
});
|
|
};
|
|
|
|
export const clearSessionCookie = (context: Context): void => {
|
|
deleteCookie(context, SESSION_COOKIE, { path: "/" });
|
|
};
|
|
|
|
export interface AuthState {
|
|
user: SessionUser;
|
|
token: string;
|
|
}
|
|
|
|
/** Lit le cookie et attache l'utilisateur, sans exiger qu'il existe. */
|
|
export const attachUser =
|
|
(db: Db) =>
|
|
async (context: Context, next: Next): Promise<void> => {
|
|
const token = getCookie(context, SESSION_COOKIE);
|
|
if (token) {
|
|
const user = await resolveSession(db, token);
|
|
if (user) {
|
|
context.set("user", user);
|
|
context.set("token", token);
|
|
} else {
|
|
clearSessionCookie(context);
|
|
}
|
|
}
|
|
await next();
|
|
};
|
|
|
|
export const requireAuth = async (context: Context, next: Next): Promise<void> => {
|
|
const user = context.get("user") as SessionUser | undefined;
|
|
if (!user) throw AppError.unauthorized();
|
|
await next();
|
|
};
|
|
|
|
/** Le role est impose en base, jamais en entete, donc ni cacheable ni falsifiable. */
|
|
export const requireRole =
|
|
(...slugs: string[]) =>
|
|
async (context: Context, next: Next): Promise<void> => {
|
|
const user = context.get("user") as SessionUser | undefined;
|
|
if (!user) throw AppError.unauthorized();
|
|
if (!slugs.includes(user.role_slug)) {
|
|
throw AppError.forbidden(`Action reservee au role : ${slugs.join(", ")}.`);
|
|
}
|
|
await next();
|
|
};
|
|
|
|
export const currentUser = (context: Context): SessionUser => {
|
|
const user = context.get("user") as SessionUser | undefined;
|
|
if (!user) throw AppError.unauthorized();
|
|
return user;
|
|
};
|