feat: logo et favicon, confirmation modale, fil d'ariane, e-mails sombres (#4)
CD — Déploiement / deploy (push) Failing after 25s
CD — Déploiement / deploy (push) Failing after 25s
- logo embarque dans les e-mails (CID) et gabarit repense en mode sombre - favicon multi-tailles + icone PNG, logo a gauche du titre (app et auth) - modale de confirmation animee a la place de window.confirm - bouton retour et fil d'ariane dans l'explorateur --------- Co-authored-by: xEsiah <[email protected]> Reviewed-on: #4 Reviewed-by: Esiah <[email protected]> Co-authored-by: Gitea Actions <-[email protected]>
This commit was merged in pull request #4.
This commit is contained in:
@@ -0,0 +1,425 @@
|
||||
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,
|
||||
branding,
|
||||
clientIp,
|
||||
createMailer,
|
||||
createRateLimiter,
|
||||
currentUser,
|
||||
hashPassword,
|
||||
link,
|
||||
rateLimitKey,
|
||||
renderMail,
|
||||
requireAuth,
|
||||
sha256,
|
||||
verifyPassword,
|
||||
type App,
|
||||
type Config,
|
||||
type Db,
|
||||
type SessionUser,
|
||||
} from "../lib/index.js";
|
||||
import { audit } from "../access.js";
|
||||
import { absolutePath, diskUsage, 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 = <T>(schema: z.ZodType<T>, 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 brand = branding(config);
|
||||
const limiter = createRateLimiter(config.RATE_LIMIT_LOGIN_MAX, config.RATE_LIMIT_LOGIN_WINDOW_MS);
|
||||
|
||||
const throttle = (context: Parameters<typeof clientIp>[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 disk = await diskUsage(config.VARIANT_DIR);
|
||||
if (disk !== null && processed.byteLength > disk.available_bytes) {
|
||||
throw AppError.insufficientStorage("Espace disque insuffisant sur le serveur.");
|
||||
}
|
||||
|
||||
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<Uint8Array>;
|
||||
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)}`);
|
||||
const mail = renderMail(brand, {
|
||||
preview: "Reinitialisez le mot de passe de votre compte.",
|
||||
heading: "Reinitialisation du mot de passe",
|
||||
intro:
|
||||
"Une reinitialisation de mot de passe a ete demandee pour votre compte CoHaiSe Cloud. Choisissez un nouveau mot de passe en suivant le lien ci-dessous.",
|
||||
cta: { label: "Choisir un mot de passe", url },
|
||||
note: "Ce lien expire dans une heure. Si vous n'etes pas a l'origine de cette demande, ignorez ce message : votre mot de passe reste inchange.",
|
||||
});
|
||||
await mailer
|
||||
.send({
|
||||
to: user.email,
|
||||
subject: "CoHaiSe Cloud — reinitialisation du mot de passe",
|
||||
...mail,
|
||||
})
|
||||
.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)}`);
|
||||
const mail = renderMail(brand, {
|
||||
preview: "Confirmez votre nouvelle adresse e-mail.",
|
||||
heading: "Confirmez votre nouvelle adresse",
|
||||
intro:
|
||||
"Une demande de changement d'adresse a ete faite pour votre compte CoHaiSe Cloud. Confirmez la nouvelle adresse en suivant le lien ci-dessous.",
|
||||
cta: { label: "Confirmer l'adresse", url },
|
||||
note: "Ce lien expire dans une heure. Sans confirmation, l'adresse reste inchangee.",
|
||||
});
|
||||
await mailer
|
||||
.send({
|
||||
to: data.new_email,
|
||||
subject: "CoHaiSe Cloud — confirmez votre nouvelle adresse",
|
||||
text: mail.text,
|
||||
html: mail.html,
|
||||
})
|
||||
.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 });
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,453 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
AppError,
|
||||
attachUser,
|
||||
branding,
|
||||
createMailer,
|
||||
currentUser,
|
||||
hashPassword,
|
||||
link,
|
||||
renderMail,
|
||||
requireAuth,
|
||||
type App,
|
||||
type Config,
|
||||
type Db,
|
||||
} from "../lib/index.js";
|
||||
import { diskUsage } from "../storage.js";
|
||||
|
||||
const uuidParam = z
|
||||
.string()
|
||||
.regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i, "Identifiant invalide.");
|
||||
|
||||
const createUserSchema = z.object({
|
||||
email: z.string().trim().email().max(255),
|
||||
first_name: z.string().trim().min(1).max(50),
|
||||
last_name: z.string().trim().min(1).max(50),
|
||||
role_slug: z.enum(["admin", "user"]).default("user"),
|
||||
quota_bytes: z.number().int().positive().nullish(),
|
||||
max_file_bytes: z.number().int().positive().nullish(),
|
||||
password: z.string().min(8).max(1024).nullish(),
|
||||
});
|
||||
|
||||
const updateUserSchema = z.object({
|
||||
first_name: z.string().trim().min(1).max(50).optional(),
|
||||
last_name: z.string().trim().min(1).max(50).optional(),
|
||||
role_slug: z.enum(["admin", "user"]).optional(),
|
||||
quota_bytes: z.number().int().positive().optional(),
|
||||
max_file_bytes: z.number().int().positive().optional(),
|
||||
is_active: z.boolean().optional(),
|
||||
});
|
||||
|
||||
const createLocationSchema = z.object({
|
||||
name: z.string().trim().min(1).max(100),
|
||||
slug: z.string().regex(/^[a-z0-9][a-z0-9-]{0,99}$/, "Identifiant technique invalide."),
|
||||
mount_path: z.string().trim().min(1).max(255),
|
||||
quota_bytes: z.number().int().positive().nullish(),
|
||||
});
|
||||
|
||||
const updateLocationSchema = z.object({
|
||||
name: z.string().trim().min(1).max(100).optional(),
|
||||
quota_bytes: z.number().int().positive().nullable().optional(),
|
||||
is_active: z.boolean().optional(),
|
||||
});
|
||||
|
||||
const parse = <T>(schema: z.ZodType<T>, 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;
|
||||
};
|
||||
|
||||
interface AdminUserRow {
|
||||
id: string;
|
||||
email: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
role_slug: string;
|
||||
quota_bytes: number;
|
||||
used_bytes: number;
|
||||
max_file_bytes: number;
|
||||
is_active: number;
|
||||
must_change_password: number;
|
||||
last_login_at: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
const publicUser = (row: AdminUserRow) => ({
|
||||
id: row.id,
|
||||
email: row.email,
|
||||
first_name: row.first_name,
|
||||
last_name: row.last_name,
|
||||
role_slug: row.role_slug,
|
||||
quota_bytes: row.quota_bytes,
|
||||
used_bytes: row.used_bytes,
|
||||
max_file_bytes: row.max_file_bytes,
|
||||
is_active: row.is_active === 1,
|
||||
must_change_password: row.must_change_password === 1,
|
||||
last_login_at: row.last_login_at,
|
||||
created_at: row.created_at,
|
||||
});
|
||||
|
||||
const SELECT_USER = `
|
||||
SELECT u.id, u.email, u.first_name, u.last_name, r.slug AS role_slug,
|
||||
u.quota_bytes, u.used_bytes, u.max_file_bytes, u.is_active,
|
||||
u.must_change_password, u.last_login_at, u.created_at
|
||||
FROM users u
|
||||
JOIN roles r ON r.id = u.role_id`;
|
||||
|
||||
const UNITS = ["o", "Ko", "Mo", "Go", "To", "Po"];
|
||||
|
||||
/** Taille lisible, pour les messages d'erreur destines a l'administrateur. */
|
||||
const humanBytes = (bytes: number): string => {
|
||||
let value = bytes;
|
||||
let unit = 0;
|
||||
while (value >= 1024 && unit < UNITS.length - 1) {
|
||||
value /= 1024;
|
||||
unit += 1;
|
||||
}
|
||||
return `${value.toFixed(unit === 0 || value >= 10 ? 0 : 1)} ${UNITS[unit]}`;
|
||||
};
|
||||
|
||||
/** Mot de passe aleatoire, lisible a la frappe, sans caractere ambigu. */
|
||||
const generatePasswordValue = (): string => {
|
||||
const alphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
||||
const bytes = new Uint8Array(18);
|
||||
globalThis.crypto.getRandomValues(bytes);
|
||||
let out = "";
|
||||
for (const byte of bytes) out += alphabet[byte % alphabet.length];
|
||||
return out;
|
||||
};
|
||||
|
||||
export const registerAdminRoutes = (app: App, db: Db, config: Config): void => {
|
||||
app.use("/api/cloud/admin/*", attachUser(db));
|
||||
app.use("/api/cloud/admin", attachUser(db));
|
||||
const mailer = createMailer(config);
|
||||
const brand = branding(config);
|
||||
|
||||
const requireAdmin = (context: Parameters<typeof currentUser>[0]): void => {
|
||||
if (currentUser(context).role_slug !== "admin") throw AppError.forbidden();
|
||||
};
|
||||
|
||||
/**
|
||||
* Un quota ne peut depasser la capacite reelle du disque qui porte les
|
||||
* medias : au-dela, la limite est un chiffre mort que le support ne pourra
|
||||
* jamais honorer. Le controle est ignore si le support n'est pas lisible
|
||||
* (chemin absent dans le conteneur), pour ne pas bloquer la configuration.
|
||||
*/
|
||||
const assertQuotaFits = async (quota: number): Promise<void> => {
|
||||
const disk = await diskUsage(config.MEDIA_DIR);
|
||||
if (disk !== null && quota > disk.total_bytes) {
|
||||
throw AppError.badRequest(
|
||||
`Le quota depasse la capacite du disque (${humanBytes(disk.total_bytes)}).`,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
app.get("/api/cloud/admin/stats", requireAuth, async (context) => {
|
||||
requireAdmin(context);
|
||||
const [users] = await db.query<{ count: number }>(
|
||||
"SELECT COUNT(*) AS count FROM users WHERE deleted_at IS NULL",
|
||||
);
|
||||
const [folders] = await db.query<{ count: number }>(
|
||||
"SELECT COUNT(*) AS count FROM folders WHERE deleted_at IS NULL",
|
||||
);
|
||||
const [files] = await db.query<{ count: number; bytes: number }>(
|
||||
"SELECT COUNT(*) AS count, COALESCE(SUM(size_bytes), 0) AS bytes FROM files WHERE deleted_at IS NULL",
|
||||
);
|
||||
const [trash] = await db.query<{ count: number }>(
|
||||
"SELECT COUNT(*) AS count FROM files WHERE deleted_at IS NOT NULL",
|
||||
);
|
||||
const locations = await db.query<{
|
||||
id: number;
|
||||
name: string;
|
||||
used_bytes: number;
|
||||
quota_bytes: number | null;
|
||||
}>(
|
||||
`SELECT id, name, used_bytes, quota_bytes FROM storage_locations
|
||||
WHERE deleted_at IS NULL ORDER BY id`,
|
||||
);
|
||||
return context.json({
|
||||
users: users?.count ?? 0,
|
||||
folders: folders?.count ?? 0,
|
||||
files: files?.count ?? 0,
|
||||
usedBytes: Number(files?.bytes ?? 0),
|
||||
trashFiles: trash?.count ?? 0,
|
||||
locations,
|
||||
disk: await diskUsage(config.MEDIA_DIR),
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/api/cloud/admin/users", requireAuth, async (context) => {
|
||||
requireAdmin(context);
|
||||
const query = (context.req.query("q") ?? "").trim();
|
||||
const rows = query
|
||||
? await db.query<AdminUserRow>(
|
||||
`${SELECT_USER}
|
||||
WHERE u.deleted_at IS NULL
|
||||
AND (u.email LIKE ? OR u.first_name LIKE ? OR u.last_name LIKE ?)
|
||||
ORDER BY u.email LIMIT 500`,
|
||||
[`%${query}%`, `%${query}%`, `%${query}%`],
|
||||
)
|
||||
: await db.query<AdminUserRow>(
|
||||
`${SELECT_USER} WHERE u.deleted_at IS NULL ORDER BY u.email LIMIT 500`,
|
||||
);
|
||||
return context.json({ users: rows.map(publicUser) });
|
||||
});
|
||||
|
||||
app.post("/api/cloud/admin/users", requireAuth, async (context) => {
|
||||
requireAdmin(context);
|
||||
const data = parse(createUserSchema, await context.req.json().catch(() => null));
|
||||
|
||||
const role = await db.one<{ id: number }>("SELECT id FROM roles WHERE slug = ?", [data.role_slug]);
|
||||
if (!role) throw AppError.badRequest("Role inconnu.");
|
||||
|
||||
const existing = await db.one("SELECT id FROM users WHERE active_email = ?", [data.email]);
|
||||
if (existing) throw AppError.conflict("Ce compte existe deja.");
|
||||
|
||||
const password = data.password ?? generatePasswordValue();
|
||||
const hash = await hashPassword(password);
|
||||
const id = randomUUID();
|
||||
|
||||
await db.exec(
|
||||
`INSERT INTO users
|
||||
(id, email, first_name, last_name, password_hash, role_id,
|
||||
quota_bytes, max_file_bytes, must_change_password, password_changed_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?,
|
||||
COALESCE(?, (SELECT CAST(setting_value AS UNSIGNED) FROM settings WHERE setting_key = 'default_quota_bytes'), 429496729600),
|
||||
COALESCE(?, 5368709120),
|
||||
1, NULL)`,
|
||||
[id, data.email, data.first_name, data.last_name, hash, role.id, data.quota_bytes ?? null, data.max_file_bytes ?? null],
|
||||
);
|
||||
|
||||
const created = await db.required<AdminUserRow>(`${SELECT_USER} WHERE u.id = ?`, [id]);
|
||||
|
||||
const mail = renderMail(brand, {
|
||||
preview: "Votre acces CoHaiSe Cloud est pret.",
|
||||
heading: "Votre compte a ete cree",
|
||||
intro: `Un compte CoHaiSe Cloud vient d'etre ouvert pour ${data.first_name}. Connectez-vous avec les identifiants ci-dessous.`,
|
||||
credentials: { email: data.email, password },
|
||||
cta: { label: "Se connecter", url: link(config, "/login") },
|
||||
note: "Ce mot de passe est temporaire : il vous sera demande de le changer des la premiere connexion.",
|
||||
});
|
||||
await mailer
|
||||
.send({
|
||||
to: data.email,
|
||||
subject: "CoHaiSe Cloud — votre compte est pret",
|
||||
text: mail.text,
|
||||
html: mail.html,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
|
||||
return context.json({ user: publicUser(created), password }, 201);
|
||||
});
|
||||
|
||||
app.patch("/api/cloud/admin/users/:id", requireAuth, async (context) => {
|
||||
const actor = currentUser(context);
|
||||
requireAdmin(context);
|
||||
const id = context.req.param("id") ?? "";
|
||||
if (!uuidParam.safeParse(id).success) throw AppError.notFound("Compte introuvable.");
|
||||
|
||||
const existing = await db.one<AdminUserRow>(`${SELECT_USER} WHERE u.id = ? AND u.deleted_at IS NULL`, [id]);
|
||||
if (!existing) throw AppError.notFound("Compte introuvable.");
|
||||
|
||||
const data = parse(updateUserSchema, await context.req.json().catch(() => null));
|
||||
|
||||
if (data.role_slug !== undefined && data.role_slug !== existing.role_slug) {
|
||||
const role = await db.one<{ id: number }>("SELECT id FROM roles WHERE slug = ?", [data.role_slug]);
|
||||
if (!role) throw AppError.badRequest("Role inconnu.");
|
||||
if (id === actor.id) throw AppError.badRequest("Vous ne pouvez pas modifier votre propre role.");
|
||||
if (existing.role_slug === "admin") {
|
||||
const [count] = await db.query<{ count: number }>(
|
||||
`SELECT COUNT(*) AS count FROM users u JOIN roles r ON r.id = u.role_id
|
||||
WHERE r.slug = 'admin' AND u.is_active = 1 AND u.deleted_at IS NULL`,
|
||||
);
|
||||
if ((count?.count ?? 0) <= 1) {
|
||||
throw AppError.badRequest("Impossible de retirer le dernier administrateur.");
|
||||
}
|
||||
}
|
||||
await db.exec("UPDATE users SET role_id = ? WHERE id = ?", [role.id, id]);
|
||||
}
|
||||
|
||||
if (data.first_name !== undefined) {
|
||||
await db.exec("UPDATE users SET first_name = ? WHERE id = ?", [data.first_name, id]);
|
||||
}
|
||||
if (data.last_name !== undefined) {
|
||||
await db.exec("UPDATE users SET last_name = ? WHERE id = ?", [data.last_name, id]);
|
||||
}
|
||||
if (data.quota_bytes !== undefined) {
|
||||
if (data.quota_bytes < existing.used_bytes) {
|
||||
throw AppError.badRequest("Le quota ne peut pas etre inferieur a l'espace deja utilise.");
|
||||
}
|
||||
await db.exec("UPDATE users SET quota_bytes = ? WHERE id = ?", [data.quota_bytes, id]);
|
||||
}
|
||||
if (data.max_file_bytes !== undefined) {
|
||||
await db.exec("UPDATE users SET max_file_bytes = ? WHERE id = ?", [data.max_file_bytes, id]);
|
||||
}
|
||||
if (data.is_active !== undefined) {
|
||||
if (!data.is_active && id === actor.id) {
|
||||
throw AppError.badRequest("Vous ne pouvez pas desactiver votre propre compte.");
|
||||
}
|
||||
await db.exec("UPDATE users SET is_active = ? WHERE id = ?", [data.is_active ? 1 : 0, id]);
|
||||
if (!data.is_active) {
|
||||
await db.exec(
|
||||
"UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ? AND revoked_at IS NULL",
|
||||
[id],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const updated = await db.required<AdminUserRow>(`${SELECT_USER} WHERE u.id = ?`, [id]);
|
||||
return context.json({ user: publicUser(updated) });
|
||||
});
|
||||
|
||||
app.delete("/api/cloud/admin/users/:id", requireAuth, async (context) => {
|
||||
const actor = currentUser(context);
|
||||
requireAdmin(context);
|
||||
const id = context.req.param("id") ?? "";
|
||||
if (!uuidParam.safeParse(id).success) throw AppError.notFound("Compte introuvable.");
|
||||
if (id === actor.id) throw AppError.badRequest("Vous ne pouvez pas supprimer votre propre compte.");
|
||||
|
||||
const result = await db.exec(
|
||||
"UPDATE users SET deleted_at = UTC_TIMESTAMP(), is_active = 0 WHERE id = ? AND deleted_at IS NULL",
|
||||
[id],
|
||||
);
|
||||
if (result.affectedRows === 0) throw AppError.notFound("Compte introuvable.");
|
||||
await db.exec("UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ?", [id]);
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
|
||||
app.post("/api/cloud/admin/users/:id/reset-password", requireAuth, async (context) => {
|
||||
requireAdmin(context);
|
||||
const id = context.req.param("id") ?? "";
|
||||
if (!uuidParam.safeParse(id).success) throw AppError.notFound("Compte introuvable.");
|
||||
|
||||
const user = await db.one<{ email: string }>(
|
||||
"SELECT email FROM users WHERE id = ? AND deleted_at IS NULL",
|
||||
[id],
|
||||
);
|
||||
if (!user) throw AppError.notFound("Compte introuvable.");
|
||||
|
||||
const password = generatePasswordValue();
|
||||
const hash = await hashPassword(password);
|
||||
await db.exec(
|
||||
"UPDATE users SET password_hash = ?, must_change_password = 1, password_changed_at = NULL WHERE id = ?",
|
||||
[hash, id],
|
||||
);
|
||||
await db.exec(
|
||||
"UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ? AND revoked_at IS NULL",
|
||||
[id],
|
||||
);
|
||||
|
||||
// Le mot de passe est rendu une seule fois et envoye au compte. Un echec
|
||||
// d'envoi n'invalide pas la reinitialisation.
|
||||
const mail = renderMail(brand, {
|
||||
preview: "Un nouveau mot de passe a ete genere pour votre compte.",
|
||||
heading: "Mot de passe reinitialise",
|
||||
intro: "Un administrateur a reinitialise le mot de passe de votre compte CoHaiSe Cloud.",
|
||||
credentials: { email: user.email, password },
|
||||
cta: { label: "Se connecter", url: link(config, "/login") },
|
||||
note: "Ce mot de passe est temporaire : il vous sera demande de le changer des la premiere connexion.",
|
||||
});
|
||||
await mailer
|
||||
.send({
|
||||
to: user.email,
|
||||
subject: "CoHaiSe Cloud — mot de passe reinitialise",
|
||||
text: mail.text,
|
||||
html: mail.html,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
|
||||
return context.json({ password });
|
||||
});
|
||||
|
||||
app.get("/api/cloud/admin/storage-locations", requireAuth, async (context) => {
|
||||
requireAdmin(context);
|
||||
const rows = await db.query(
|
||||
`SELECT id, name, slug, mount_path, quota_bytes, used_bytes, is_active, created_at
|
||||
FROM storage_locations WHERE deleted_at IS NULL ORDER BY id`,
|
||||
);
|
||||
return context.json({ locations: rows, disk: await diskUsage(config.MEDIA_DIR) });
|
||||
});
|
||||
|
||||
app.post("/api/cloud/admin/storage-locations", requireAuth, async (context) => {
|
||||
requireAdmin(context);
|
||||
const data = parse(createLocationSchema, await context.req.json().catch(() => null));
|
||||
if (data.quota_bytes !== undefined && data.quota_bytes !== null) {
|
||||
await assertQuotaFits(data.quota_bytes);
|
||||
}
|
||||
try {
|
||||
await db.exec(
|
||||
`INSERT INTO storage_locations (name, slug, mount_path, quota_bytes)
|
||||
VALUES (?, ?, ?, ?)`,
|
||||
[data.name, data.slug, data.mount_path, data.quota_bytes ?? null],
|
||||
);
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Un emplacement porte deja ce nom ou ce chemin.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return context.json({ ok: true }, 201);
|
||||
});
|
||||
|
||||
app.patch("/api/cloud/admin/storage-locations/:id", requireAuth, async (context) => {
|
||||
requireAdmin(context);
|
||||
const id = Number(context.req.param("id"));
|
||||
if (!Number.isInteger(id) || id <= 0) throw AppError.notFound("Emplacement introuvable.");
|
||||
const data = parse(updateLocationSchema, await context.req.json().catch(() => null));
|
||||
|
||||
const row = await db.one<{ used_bytes: number }>(
|
||||
"SELECT used_bytes FROM storage_locations WHERE id = ? AND deleted_at IS NULL",
|
||||
[id],
|
||||
);
|
||||
if (!row) throw AppError.notFound("Emplacement introuvable.");
|
||||
if (data.quota_bytes !== undefined && data.quota_bytes !== null && data.quota_bytes < row.used_bytes) {
|
||||
throw AppError.badRequest("Le quota est inferieur a l'espace deja utilise.");
|
||||
}
|
||||
if (data.quota_bytes !== undefined && data.quota_bytes !== null) {
|
||||
await assertQuotaFits(data.quota_bytes);
|
||||
}
|
||||
|
||||
const fields: string[] = [];
|
||||
const values: unknown[] = [];
|
||||
if (data.name !== undefined) {
|
||||
fields.push("name = ?");
|
||||
values.push(data.name);
|
||||
}
|
||||
if (data.quota_bytes !== undefined) {
|
||||
fields.push("quota_bytes = ?");
|
||||
values.push(data.quota_bytes);
|
||||
}
|
||||
if (data.is_active !== undefined) {
|
||||
fields.push("is_active = ?");
|
||||
values.push(data.is_active ? 1 : 0);
|
||||
}
|
||||
if (fields.length === 0) throw AppError.badRequest("Rien a modifier.");
|
||||
values.push(id);
|
||||
await db.exec(`UPDATE storage_locations SET ${fields.join(", ")} WHERE id = ?`, values);
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
|
||||
app.get("/api/cloud/admin/audit", requireAuth, async (context) => {
|
||||
requireAdmin(context);
|
||||
const limit = Math.min(500, Math.max(1, Number(context.req.query("limit")) || 100));
|
||||
const offset = Math.max(0, Number(context.req.query("offset")) || 0);
|
||||
const action = context.req.query("action");
|
||||
const rows = action
|
||||
? await db.query(
|
||||
`SELECT id, user_id, user_email, action, resource, resource_id, details, ip_address, created_at
|
||||
FROM audit_logs WHERE action = ? ORDER BY created_at DESC LIMIT ${limit} OFFSET ${offset}`,
|
||||
[action],
|
||||
)
|
||||
: await db.query(
|
||||
`SELECT id, user_id, user_email, action, resource, resource_id, details, ip_address, created_at
|
||||
FROM audit_logs ORDER BY created_at DESC LIMIT ${limit} OFFSET ${offset}`,
|
||||
);
|
||||
return context.json({ entries: rows });
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,179 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
AppError,
|
||||
attachUser,
|
||||
clearSessionCookie,
|
||||
clientIp,
|
||||
createRateLimiter,
|
||||
createSession,
|
||||
currentUser,
|
||||
hashPassword,
|
||||
isHttpsRequest,
|
||||
rateLimitKey,
|
||||
requireAuth,
|
||||
revokeSession,
|
||||
setSessionCookie,
|
||||
sha256,
|
||||
verifyPassword,
|
||||
type App,
|
||||
type Config,
|
||||
type Db,
|
||||
} from "../lib/index.js";
|
||||
|
||||
const credentials = z.object({
|
||||
email: z.string().trim().min(3).max(255),
|
||||
password: z.string().min(1).max(1024),
|
||||
});
|
||||
|
||||
/**
|
||||
* Hachage de repli, calcule paresseusement a la premiere echec de connexion.
|
||||
* Sans lui, un compte inexistant repond plus vite qu'un compte existant, ce qui
|
||||
* permet d'enumerer les adresses e-mail en mesurant le temps de reponse.
|
||||
*/
|
||||
let dummyHash: Promise<string> | undefined;
|
||||
const decoyHash = (): Promise<string> => (dummyHash ??= hashPassword("aucun-compte-ne-correspond"));
|
||||
|
||||
interface UserRow {
|
||||
id: string;
|
||||
email: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
password_hash: string;
|
||||
role_slug: string;
|
||||
role_name: string;
|
||||
quota_bytes: number;
|
||||
used_bytes: number;
|
||||
max_file_bytes: number;
|
||||
must_change_password: number;
|
||||
is_active: number;
|
||||
}
|
||||
|
||||
const publicUser = (row: UserRow) => ({
|
||||
id: row.id,
|
||||
email: row.email,
|
||||
first_name: row.first_name,
|
||||
last_name: row.last_name,
|
||||
role_slug: row.role_slug,
|
||||
role_name: row.role_name,
|
||||
quota_bytes: row.quota_bytes,
|
||||
used_bytes: row.used_bytes,
|
||||
max_file_bytes: row.max_file_bytes,
|
||||
must_change_password: row.must_change_password === 1,
|
||||
});
|
||||
|
||||
const SELECT_USER = `
|
||||
SELECT u.id, u.email, u.first_name, u.last_name, u.password_hash,
|
||||
r.slug AS role_slug, r.name AS role_name,
|
||||
u.quota_bytes, u.used_bytes, u.max_file_bytes, u.must_change_password, u.is_active
|
||||
FROM users u
|
||||
JOIN roles r ON r.id = u.role_id`;
|
||||
|
||||
export const registerAuthRoutes = (app: App, db: Db, config: Config): void => {
|
||||
app.use("/api/cloud/*", attachUser(db));
|
||||
const limiter = createRateLimiter(config.RATE_LIMIT_LOGIN_MAX, config.RATE_LIMIT_LOGIN_WINDOW_MS);
|
||||
|
||||
app.post("/api/cloud/auth/login", async (context) => {
|
||||
// Borne les tentatives par IP : une attaque par dictionnaire sur un mot de
|
||||
// passe faible est arretee avant le calcul scrypt, couteux.
|
||||
const ip = clientIp(context, config.TRUST_PROXY);
|
||||
if (!limiter.allow(rateLimitKey(ip))) {
|
||||
throw AppError.unprocessable("Trop de tentatives de connexion. Reessayez dans une minute.");
|
||||
}
|
||||
|
||||
const parsed = credentials.safeParse(await context.req.json().catch(() => null));
|
||||
if (!parsed.success) throw AppError.badRequest("Identifiants invalides.");
|
||||
|
||||
const { email, password } = parsed.data;
|
||||
const row = await db.one<UserRow>(`${SELECT_USER} WHERE u.active_email = ?`, [email]);
|
||||
|
||||
// Meme travail dans les deux cas, pour que le temps de reponse ne
|
||||
// revele pas si l'adresse existe.
|
||||
const stored = row && row.is_active === 1 ? row.password_hash : await decoyHash();
|
||||
if (!row || row.is_active !== 1 || !(await verifyPassword(password, stored))) {
|
||||
throw AppError.unauthorized("Identifiants invalides.");
|
||||
}
|
||||
|
||||
const forwarded = context.req.header("x-forwarded-for");
|
||||
const { token, expiresAt } = await createSession(
|
||||
db,
|
||||
row.id,
|
||||
{
|
||||
ipAddress: config.TRUST_PROXY && forwarded ? forwarded.split(",")[0]?.trim() : null,
|
||||
userAgent: context.req.header("user-agent"),
|
||||
},
|
||||
config.SESSION_TTL_HOURS,
|
||||
);
|
||||
|
||||
await db.exec("UPDATE users SET last_login_at = UTC_TIMESTAMP() WHERE id = ?", [row.id]);
|
||||
// Le marqueur Secure suit le protocole reellement annonce, pas
|
||||
// NODE_ENV : un deploiement en HTTP local doit rester utilisable, un
|
||||
// deploiement https:// ne doit jamais poser de cookie cleartext.
|
||||
// Le schema reel de la requete, pas PUBLIC_ORIGIN : voir isHttpsRequest.
|
||||
const secure = isHttpsRequest(context, config.TRUST_PROXY);
|
||||
setSessionCookie(context, token, expiresAt, secure);
|
||||
|
||||
return context.json({ user: publicUser(row) });
|
||||
});
|
||||
|
||||
app.post("/api/cloud/auth/logout", requireAuth, async (context) => {
|
||||
const token = context.get("token");
|
||||
if (token) await revokeSession(db, token);
|
||||
clearSessionCookie(context);
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
|
||||
app.get("/api/cloud/auth/me", requireAuth, async (context) => {
|
||||
const session = currentUser(context);
|
||||
const row = await db.one<UserRow>(`${SELECT_USER} WHERE u.id = ?`, [session.id]);
|
||||
if (!row) throw AppError.unauthorized();
|
||||
return context.json({ user: publicUser(row) });
|
||||
});
|
||||
|
||||
const changePassword = z.object({
|
||||
current: z.string().min(1).max(1024),
|
||||
next: z.string().min(8).max(1024),
|
||||
});
|
||||
|
||||
/**
|
||||
* Changement impose a la premiere connexion. Les autres sessions sont
|
||||
* revoquees : si le compte avait ete ouvert ailleurs, l'ancien mot de passe
|
||||
* ne doit plus rien ouvrir.
|
||||
*/
|
||||
app.post("/api/cloud/auth/change-password", requireAuth, async (context) => {
|
||||
const session = currentUser(context);
|
||||
const parsed = changePassword.safeParse(await context.req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
throw AppError.badRequest("Le nouveau mot de passe doit contenir au moins 8 caracteres.");
|
||||
}
|
||||
|
||||
const row = await db.one<{ password_hash: string }>(
|
||||
"SELECT password_hash FROM users WHERE id = ? AND deleted_at IS NULL",
|
||||
[session.id],
|
||||
);
|
||||
if (!row) throw AppError.unauthorized();
|
||||
|
||||
if (!(await verifyPassword(parsed.data.current, row.password_hash))) {
|
||||
throw AppError.unauthorized("Mot de passe actuel incorrect.");
|
||||
}
|
||||
if (parsed.data.current === parsed.data.next) {
|
||||
throw AppError.badRequest("Le nouveau mot de passe doit differer de l'actuel.");
|
||||
}
|
||||
|
||||
const hash = await hashPassword(parsed.data.next);
|
||||
await db.exec(
|
||||
`UPDATE users
|
||||
SET password_hash = ?, must_change_password = 0, password_changed_at = UTC_TIMESTAMP()
|
||||
WHERE id = ?`,
|
||||
[hash, session.id],
|
||||
);
|
||||
// La session courante est conservee, toutes les autres sont revoquees.
|
||||
await db.exec(
|
||||
`UPDATE user_sessions
|
||||
SET revoked_at = UTC_TIMESTAMP()
|
||||
WHERE user_id = ? AND revoked_at IS NULL AND token_hash <> ?`,
|
||||
[session.id, sha256(context.get("token") ?? "")],
|
||||
);
|
||||
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,539 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import path from "node:path";
|
||||
import { Readable } from "node:stream";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
AppError,
|
||||
attachUser,
|
||||
currentUser,
|
||||
requireAuth,
|
||||
requireRole,
|
||||
type App,
|
||||
type Config,
|
||||
type Db,
|
||||
} from "../lib/index.js";
|
||||
import { audit, canRead, canWrite, canWriteExplicit } from "../access.js";
|
||||
import { indexMedia, thumbnailSize } from "../media.js";
|
||||
import {
|
||||
absolutePath,
|
||||
chooseLocation,
|
||||
discard,
|
||||
diskUsage,
|
||||
ensureDir,
|
||||
fileExists,
|
||||
openForDownload,
|
||||
publish,
|
||||
relativePathFor,
|
||||
temporaryPath,
|
||||
writeBody,
|
||||
} from "../storage.js";
|
||||
|
||||
const uuid = z
|
||||
.string()
|
||||
.regex(
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
|
||||
"Identifiant invalide.",
|
||||
);
|
||||
|
||||
const MIME = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,127}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,127}$/;
|
||||
|
||||
const renameInput = z.object({
|
||||
name: z.string().trim().min(1).max(255),
|
||||
});
|
||||
|
||||
const moveInput = z.object({
|
||||
folderId: uuid.nullish(),
|
||||
});
|
||||
|
||||
const parse = <T>(schema: z.ZodType<T>, 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;
|
||||
};
|
||||
|
||||
interface FileRow {
|
||||
id: string;
|
||||
folder_id: string | null;
|
||||
name: string;
|
||||
mime_type: string | null;
|
||||
size_bytes: number;
|
||||
checksum_sha256: string | null;
|
||||
relative_path: string;
|
||||
owner_id: string | null;
|
||||
is_starred: number;
|
||||
download_count: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
const SELECT_FILE = `SELECT id, folder_id, name, mime_type, size_bytes, checksum_sha256,
|
||||
relative_path, owner_id, is_starred, download_count, created_at, updated_at
|
||||
FROM files`;
|
||||
|
||||
const publicFile = (row: FileRow) => ({
|
||||
id: row.id,
|
||||
folder_id: row.folder_id,
|
||||
name: row.name,
|
||||
mime_type: row.mime_type,
|
||||
size_bytes: row.size_bytes,
|
||||
checksum_sha256: row.checksum_sha256,
|
||||
owner_id: row.owner_id,
|
||||
is_starred: row.is_starred === 1,
|
||||
download_count: row.download_count,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
});
|
||||
|
||||
/** Nom d'affichage : ni separateur, ni sequence d'echappement, ni point seul. */
|
||||
const assertName = (raw: string | undefined): string => {
|
||||
const name = (raw ?? "").trim();
|
||||
if (!name || name.length > 255) {
|
||||
throw AppError.badRequest("Le nom du fichier doit contenir entre 1 et 255 caracteres.");
|
||||
}
|
||||
if (name === "." || name === ".." || /[/\\\0-\x1f]/.test(name)) {
|
||||
throw AppError.badRequest("Le nom du fichier ne peut pas contenir de separateur.");
|
||||
}
|
||||
return name;
|
||||
};
|
||||
|
||||
const mimeOf = (header: string | undefined): string => {
|
||||
const value = (header ?? "").split(";")[0]?.trim().toLowerCase() ?? "";
|
||||
return MIME.test(value) ? value : "application/octet-stream";
|
||||
};
|
||||
|
||||
/** Le nom HTTP ne contient que des octets ASCII imprimables, UTF-8 en prime. */
|
||||
const contentDisposition = (name: string): string => {
|
||||
const ascii = name.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_");
|
||||
return `attachment; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(name)}`;
|
||||
};
|
||||
|
||||
export const registerFileRoutes = (app: App, db: Db, config: Config): void => {
|
||||
app.use("/api/cloud/files/*", attachUser(db));
|
||||
app.use("/api/cloud/files", attachUser(db));
|
||||
|
||||
/**
|
||||
* Depot en un seul passage. Le corps n'est pas un formulaire multipart mais
|
||||
* l'objet brut : le navigateur envoie le File tel quel, ce qui evite de
|
||||
* faire tenir plusieurs gigaoctets en memoire pendant le decoupage.
|
||||
*/
|
||||
app.put(
|
||||
"/api/cloud/files",
|
||||
requireAuth,
|
||||
requireRole("admin", "user"),
|
||||
async (context) => {
|
||||
const user = currentUser(context);
|
||||
const name = assertName(context.req.query("name"));
|
||||
const rawFolder = context.req.query("folderId");
|
||||
const folderId = rawFolder === undefined || rawFolder === "" ? null : rawFolder;
|
||||
|
||||
if (folderId !== null) {
|
||||
if (!uuid.safeParse(folderId).success) {
|
||||
throw AppError.badRequest("Identifiant de dossier invalide.");
|
||||
}
|
||||
const folder = await db.one(
|
||||
"SELECT 1 AS present FROM folders WHERE id = ? AND deleted_at IS NULL",
|
||||
[folderId],
|
||||
);
|
||||
if (!folder) throw AppError.notFound("Dossier introuvable.");
|
||||
if (!(await canWrite(db, user, folderId))) {
|
||||
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier.");
|
||||
}
|
||||
}
|
||||
|
||||
const declaredHeader = context.req.header("content-length");
|
||||
if (declaredHeader === undefined) {
|
||||
throw new AppError(411, "LENGTH_REQUIRED", "En-tête Content-Length manquant.");
|
||||
}
|
||||
const declared = Number(declaredHeader);
|
||||
if (!Number.isSafeInteger(declared) || declared < 0) {
|
||||
throw AppError.badRequest("Longueur de corps invalide.");
|
||||
}
|
||||
|
||||
const budget = await db.one<{
|
||||
used_bytes: number;
|
||||
quota_bytes: number;
|
||||
max_file_bytes: number;
|
||||
}>(
|
||||
"SELECT used_bytes, quota_bytes, max_file_bytes FROM users WHERE id = ? AND deleted_at IS NULL",
|
||||
[user.id],
|
||||
);
|
||||
if (!budget) throw AppError.unauthorized();
|
||||
|
||||
// Les deux bornes sont verifiees avant d'ecrire quoi que ce soit.
|
||||
if (declared > budget.max_file_bytes) {
|
||||
throw AppError.payloadTooLarge(
|
||||
`Fichier trop volumineux (maximum ${budget.max_file_bytes} octets).`,
|
||||
);
|
||||
}
|
||||
if (BigInt(budget.used_bytes) + BigInt(declared) > BigInt(budget.quota_bytes)) {
|
||||
throw AppError.payloadTooLarge("Votre quota de stockage est depasse.");
|
||||
}
|
||||
|
||||
const duplicate = await db.one(
|
||||
`SELECT 1 AS taken FROM files
|
||||
WHERE folder_id <=> ? AND active_name = ? AND deleted_at IS NULL LIMIT 1`,
|
||||
[folderId, name],
|
||||
);
|
||||
if (duplicate) throw AppError.conflict("Ce nom existe deja ici.");
|
||||
|
||||
// Le disque est verifie avant l'ecriture : sans cela un support plein
|
||||
// ferait echouer le depot en cours de route (ENOSPC), apres avoir
|
||||
// annonce au client que le quota etait disponible.
|
||||
const disk = await diskUsage(config.MEDIA_DIR);
|
||||
if (disk !== null && declared > disk.available_bytes) {
|
||||
throw AppError.insufficientStorage(
|
||||
"Espace disque insuffisant sur le serveur pour ce fichier.",
|
||||
);
|
||||
}
|
||||
|
||||
const location = await chooseLocation(db, BigInt(declared));
|
||||
const id = randomUUID();
|
||||
const relative = relativePathFor(location.slug, id, name);
|
||||
const destination = absolutePath(config.MEDIA_DIR, relative);
|
||||
const temporary = temporaryPath(config.MEDIA_DIR, location.slug);
|
||||
|
||||
await ensureDir(path.dirname(destination));
|
||||
|
||||
const body = context.req.raw.body;
|
||||
if (!body) throw AppError.badRequest("Corps de requete vide.");
|
||||
|
||||
let written;
|
||||
try {
|
||||
written = await writeBody(temporary, body, declared, budget.max_file_bytes);
|
||||
} catch (error) {
|
||||
await discard(temporary);
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Publication puis ecriture en base : si la base refuse, le fichier
|
||||
// est retire, il ne reste aucun orphelin dans les deux sens.
|
||||
await publish(temporary, destination);
|
||||
|
||||
try {
|
||||
await db.transaction(async (connection) => {
|
||||
const [quota] = await connection.execute(
|
||||
`UPDATE users SET used_bytes = used_bytes + ?
|
||||
WHERE id = ? AND used_bytes + ? <= quota_bytes`,
|
||||
[written.size, user.id, written.size],
|
||||
);
|
||||
if ((quota as { affectedRows: number }).affectedRows === 0) {
|
||||
throw AppError.payloadTooLarge("Votre quota de stockage est depasse.");
|
||||
}
|
||||
|
||||
const [inserted] = await connection.execute(
|
||||
`INSERT INTO files
|
||||
(id, storage_location_id, folder_id, name, mime_type, size_bytes,
|
||||
checksum_sha256, relative_path, owner_id, created_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
[
|
||||
id,
|
||||
location.id,
|
||||
folderId,
|
||||
name,
|
||||
mimeOf(context.req.header("content-type")),
|
||||
written.size,
|
||||
written.checksum,
|
||||
relative,
|
||||
user.id,
|
||||
user.id,
|
||||
],
|
||||
);
|
||||
|
||||
const [support] = await connection.execute(
|
||||
`UPDATE storage_locations
|
||||
SET used_bytes = used_bytes + ?
|
||||
WHERE id = ? AND (quota_bytes IS NULL OR used_bytes + ? <= quota_bytes)`,
|
||||
[written.size, location.id, written.size],
|
||||
);
|
||||
if ((support as { affectedRows: number }).affectedRows === 0) {
|
||||
throw AppError.payloadTooLarge("L'espace disponible sur le support est insuffisant.");
|
||||
}
|
||||
void inserted;
|
||||
});
|
||||
} catch (error) {
|
||||
await discard(destination);
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Ce nom existe deja ici.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Vignette et metadonnees : best-effort, le depot reste valide si sharp
|
||||
// echoue sur un format exotique.
|
||||
await indexMedia(db, config, id, mimeOf(context.req.header("content-type")), destination).catch(
|
||||
() => undefined,
|
||||
);
|
||||
|
||||
await audit(
|
||||
db,
|
||||
context,
|
||||
user,
|
||||
"file.upload",
|
||||
"file",
|
||||
id,
|
||||
{ name, size: written.size, folder_id: folderId },
|
||||
config.TRUST_PROXY,
|
||||
);
|
||||
|
||||
const created = await db.required<FileRow>(`${SELECT_FILE} WHERE id = ?`, [id]);
|
||||
return context.json({ file: publicFile(created) }, 201);
|
||||
},
|
||||
);
|
||||
|
||||
app.get("/api/cloud/files", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const rawFolder = context.req.query("folderId");
|
||||
const folderId = rawFolder === undefined || rawFolder === "" ? null : rawFolder;
|
||||
|
||||
if (folderId !== null && !uuid.safeParse(folderId).success) {
|
||||
throw AppError.badRequest("Identifiant de dossier invalide.");
|
||||
}
|
||||
|
||||
// Contre l'IDOR : un dossier qui n'appartient pas a la session rend une
|
||||
// liste vide plutot que de confirmer son existence.
|
||||
if (folderId !== null && user.role_slug !== "admin" && !(await canRead(db, user, folderId))) {
|
||||
const readable = await db.one(
|
||||
`SELECT 1 AS granted FROM folders f
|
||||
WHERE f.id = ? AND f.deleted_at IS NULL AND f.owner_id = ? LIMIT 1`,
|
||||
[folderId, user.id],
|
||||
);
|
||||
if (!readable) throw AppError.notFound("Dossier introuvable.");
|
||||
}
|
||||
|
||||
const rows = await db.query<FileRow>(
|
||||
`${SELECT_FILE}
|
||||
WHERE deleted_at IS NULL
|
||||
AND (folder_id <=> ?)
|
||||
AND ( ? = 1
|
||||
OR owner_id = ?
|
||||
OR ( folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folders f
|
||||
WHERE f.id = files.folder_id AND f.access_type = 'public' ) )
|
||||
OR ( folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folder_permissions fp
|
||||
WHERE fp.folder_id = files.folder_id
|
||||
AND fp.user_id = ?
|
||||
AND fp.level IN ('read', 'write', 'admin')
|
||||
AND ( fp.expires_at IS NULL
|
||||
OR fp.expires_at > UTC_TIMESTAMP() ) ) ) )
|
||||
ORDER BY name`,
|
||||
[folderId, user.role_slug === "admin" ? 1 : 0, user.id, user.id],
|
||||
);
|
||||
|
||||
return context.json({ folderId, files: rows.map(publicFile) });
|
||||
});
|
||||
|
||||
app.get("/api/cloud/files/:id/download", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const rawId = context.req.param("id");
|
||||
if (!uuid.safeParse(rawId).success) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
const row = await db.one<FileRow>(`${SELECT_FILE} WHERE id = ? AND deleted_at IS NULL`, [rawId]);
|
||||
if (!row) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
const allowed =
|
||||
user.role_slug === "admin" ||
|
||||
(row.owner_id !== null && row.owner_id === user.id) ||
|
||||
(row.folder_id !== null && (await canRead(db, user, row.folder_id)));
|
||||
if (!allowed) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
const absolute = absolutePath(config.MEDIA_DIR, row.relative_path);
|
||||
if (!(await fileExists(absolute))) throw AppError.notFound("Fichier introuvable sur le support.");
|
||||
|
||||
await db
|
||||
.exec(
|
||||
`UPDATE files
|
||||
SET download_count = download_count + 1, last_accessed_at = UTC_TIMESTAMP()
|
||||
WHERE id = ?`,
|
||||
[row.id],
|
||||
)
|
||||
.catch(() => undefined);
|
||||
|
||||
const mime = row.mime_type ?? "application/octet-stream";
|
||||
const stream = Readable.toWeb(openForDownload(absolute)) as ReadableStream<Uint8Array>;
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
"content-type": mime,
|
||||
"content-length": String(row.size_bytes),
|
||||
"content-disposition": contentDisposition(row.name),
|
||||
// Le type vient de la base, jamais du contenu : un fichier HTML
|
||||
// telecharge ne doit jamais etre rendu en navigation.
|
||||
"x-content-type-options": "nosniff",
|
||||
"cache-control": "private, max-age=0, must-revalidate",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
/** Vignette d'image. Memes droits que le telechargement, cache prive. */
|
||||
app.get("/api/cloud/files/:id/thumbnail", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const rawId = context.req.param("id");
|
||||
if (!uuid.safeParse(rawId).success) throw AppError.notFound("Image introuvable.");
|
||||
|
||||
const row = await db.one<FileRow>(`${SELECT_FILE} WHERE id = ? AND deleted_at IS NULL`, [rawId]);
|
||||
if (!row) throw AppError.notFound("Image introuvable.");
|
||||
|
||||
const allowed =
|
||||
user.role_slug === "admin" ||
|
||||
(row.owner_id !== null && row.owner_id === user.id) ||
|
||||
(row.folder_id !== null && (await canRead(db, user, row.folder_id)));
|
||||
if (!allowed) throw AppError.notFound("Image introuvable.");
|
||||
|
||||
const variant = await db.one<{ path: string }>(
|
||||
"SELECT path FROM file_variants WHERE file_id = ? AND purpose = 'thumbnail'",
|
||||
[row.id],
|
||||
);
|
||||
if (!variant) throw AppError.notFound("Vignette introuvable.");
|
||||
|
||||
const size = await thumbnailSize(config, variant.path);
|
||||
if (size === null) throw AppError.notFound("Vignette introuvable.");
|
||||
|
||||
const absolute = absolutePath(config.VARIANT_DIR, variant.path);
|
||||
const stream = Readable.toWeb(openForDownload(absolute)) as ReadableStream<Uint8Array>;
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
"content-type": "image/webp",
|
||||
"content-length": String(size),
|
||||
"cache-control": "private, max-age=86400",
|
||||
"x-content-type-options": "nosniff",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
/** Renomme un fichier. Le chemin physique ne bouge pas : il suit l'UUID. */
|
||||
app.patch("/api/cloud/files/:id", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const rawId = context.req.param("id");
|
||||
if (!uuid.safeParse(rawId).success) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
const row = await db.one<FileRow>(`${SELECT_FILE} WHERE id = ? AND deleted_at IS NULL`, [rawId]);
|
||||
if (!row) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
const owner = row.owner_id !== null && row.owner_id === user.id;
|
||||
const permitted =
|
||||
user.role_slug === "admin" ||
|
||||
owner ||
|
||||
(row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id)));
|
||||
if (!permitted) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
const { name: rawName } = parse(renameInput, await context.req.json().catch(() => null));
|
||||
const name = assertName(rawName);
|
||||
|
||||
try {
|
||||
await db.exec(
|
||||
"UPDATE files SET name = ? WHERE id = ? AND deleted_at IS NULL",
|
||||
[name, row.id],
|
||||
);
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Ce nom existe deja ici.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const updated = await db.required<FileRow>(`${SELECT_FILE} WHERE id = ?`, [row.id]);
|
||||
await audit(db, context, user, "file.rename", "file", row.id, { name }, config.TRUST_PROXY);
|
||||
return context.json({ file: publicFile(updated) });
|
||||
});
|
||||
|
||||
/** Deplace un fichier vers un autre dossier, racine comprise. */
|
||||
app.post("/api/cloud/files/:id/move", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const rawId = context.req.param("id");
|
||||
if (!uuid.safeParse(rawId).success) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
const row = await db.one<FileRow>(`${SELECT_FILE} WHERE id = ? AND deleted_at IS NULL`, [rawId]);
|
||||
if (!row) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
const owner = row.owner_id !== null && row.owner_id === user.id;
|
||||
const canLeave =
|
||||
user.role_slug === "admin" ||
|
||||
owner ||
|
||||
(row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id)));
|
||||
if (!canLeave) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
const { folderId } = parse(moveInput, await context.req.json().catch(() => null));
|
||||
const destination = folderId ?? null;
|
||||
|
||||
if (destination !== null && !(await canWrite(db, user, destination))) {
|
||||
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier.");
|
||||
}
|
||||
|
||||
try {
|
||||
await db.exec("UPDATE files SET folder_id = ? WHERE id = ?", [destination, row.id]);
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Un fichier du meme nom existe deja dans la destination.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const updated = await db.required<FileRow>(`${SELECT_FILE} WHERE id = ?`, [row.id]);
|
||||
await audit(db, context, user, "file.move", "file", row.id, { folderId: destination }, config.TRUST_PROXY);
|
||||
return context.json({ file: publicFile(updated) });
|
||||
});
|
||||
|
||||
/** Bascule le marqueur favori. */
|
||||
app.put("/api/cloud/files/:id/star", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const rawId = context.req.param("id");
|
||||
if (!uuid.safeParse(rawId).success) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
const row = await db.one<FileRow>(`${SELECT_FILE} WHERE id = ? AND deleted_at IS NULL`, [rawId]);
|
||||
if (!row) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
const allowed =
|
||||
user.role_slug === "admin" ||
|
||||
(row.owner_id !== null && row.owner_id === user.id) ||
|
||||
(row.folder_id !== null && (await canRead(db, user, row.folder_id)));
|
||||
if (!allowed) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
await db.exec("UPDATE files SET is_starred = 1 - is_starred WHERE id = ?", [row.id]);
|
||||
const updated = await db.required<FileRow>(`${SELECT_FILE} WHERE id = ?`, [row.id]);
|
||||
return context.json({ file: publicFile(updated) });
|
||||
});
|
||||
|
||||
app.delete("/api/cloud/files/:id", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const rawId = context.req.param("id");
|
||||
if (!uuid.safeParse(rawId).success) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
const row = await db.one<FileRow>(`${SELECT_FILE} WHERE id = ? AND deleted_at IS NULL`, [rawId]);
|
||||
if (!row) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
const owner = row.owner_id !== null && row.owner_id === user.id;
|
||||
const permitted =
|
||||
user.role_slug === "admin" ||
|
||||
owner ||
|
||||
(row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id)));
|
||||
if (!permitted) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
// Suppression logique : le fichier reste sur disque le temps de la
|
||||
// retention (trash_retention_days), et son nom redevient disponible grace
|
||||
// a la colonne active_name.
|
||||
const result = await db.exec(
|
||||
"UPDATE files SET deleted_at = UTC_TIMESTAMP() WHERE id = ? AND deleted_at IS NULL",
|
||||
[row.id],
|
||||
);
|
||||
if (result.affectedRows === 0) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
await audit(
|
||||
db,
|
||||
context,
|
||||
user,
|
||||
"file.delete",
|
||||
"file",
|
||||
row.id,
|
||||
{ name: row.name, size: row.size_bytes, folder_id: row.folder_id },
|
||||
config.TRUST_PROXY,
|
||||
);
|
||||
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,397 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
AppError,
|
||||
attachUser,
|
||||
currentUser,
|
||||
requireAuth,
|
||||
requireRole,
|
||||
type App,
|
||||
type Config,
|
||||
type Db,
|
||||
} from "../lib/index.js";
|
||||
import { audit, canManageFolder, canRead, canWrite } from "../access.js";
|
||||
|
||||
const uuid = z
|
||||
.string()
|
||||
.regex(
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
|
||||
"Identifiant invalide.",
|
||||
);
|
||||
|
||||
const createFolder = z.object({
|
||||
name: z.string().trim().min(1).max(255),
|
||||
parentId: uuid.nullish(),
|
||||
description: z.string().trim().max(2000).nullish(),
|
||||
});
|
||||
|
||||
const updateFolder = z.object({
|
||||
name: z.string().trim().min(1).max(255).optional(),
|
||||
description: z.string().trim().max(2000).nullish(),
|
||||
});
|
||||
|
||||
const moveFolder = z.object({
|
||||
parentId: uuid.nullish(),
|
||||
});
|
||||
|
||||
const permissionInput = z.object({
|
||||
email: z.string().trim().min(3).max(255),
|
||||
level: z.enum(["read", "write", "admin"]),
|
||||
expiresAt: z.string().datetime().nullish(),
|
||||
});
|
||||
|
||||
interface FolderRow {
|
||||
id: string;
|
||||
parent_id: string | null;
|
||||
name: string;
|
||||
description: string | null;
|
||||
owner_id: string | null;
|
||||
access_type: string;
|
||||
is_system: number;
|
||||
storage_location_id: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
const SELECT_FOLDER = `SELECT f.id, f.parent_id, f.name, f.description, f.owner_id,
|
||||
f.access_type, f.is_system, f.storage_location_id, f.created_at, f.updated_at
|
||||
FROM folders f`;
|
||||
|
||||
const publicFolder = (row: FolderRow) => ({
|
||||
id: row.id,
|
||||
parent_id: row.parent_id,
|
||||
name: row.name,
|
||||
description: row.description,
|
||||
owner_id: row.owner_id,
|
||||
access_type: row.access_type,
|
||||
is_system: row.is_system === 1,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
});
|
||||
|
||||
const assertName = (raw: string): string => {
|
||||
const name = raw.trim();
|
||||
if (!name || name.length > 255) {
|
||||
throw AppError.badRequest("Le nom du dossier doit contenir entre 1 et 255 caracteres.");
|
||||
}
|
||||
if (name === "." || name === ".." || /[/\\\0-\x1f]/.test(name)) {
|
||||
throw AppError.badRequest("Le nom du dossier ne peut pas contenir de separateur.");
|
||||
}
|
||||
return name;
|
||||
};
|
||||
|
||||
const parse = <T>(schema: z.ZodType<T>, 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;
|
||||
};
|
||||
|
||||
/** Id du dossier et de tous ses descendants, y compris lui-meme. */
|
||||
const subtreeIds = async (db: Db, rootId: string): Promise<string[]> => {
|
||||
const rows = await db.query<{ id: string }>(
|
||||
`WITH RECURSIVE subtree AS (
|
||||
SELECT id FROM folders WHERE id = ?
|
||||
UNION ALL
|
||||
SELECT f.id FROM folders f JOIN subtree s ON f.parent_id = s.id
|
||||
)
|
||||
SELECT id FROM subtree`,
|
||||
[rootId],
|
||||
);
|
||||
return rows.map((row) => row.id);
|
||||
};
|
||||
|
||||
export const registerFolderRoutes = (app: App, db: Db, config: Config): void => {
|
||||
app.use("/api/cloud/folders/*", attachUser(db));
|
||||
app.use("/api/cloud/folders", attachUser(db));
|
||||
|
||||
app.get("/api/cloud/folders", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const rawParent = context.req.query("parentId");
|
||||
const parentId = rawParent === undefined || rawParent === "" ? null : rawParent;
|
||||
|
||||
if (parentId !== null && !uuid.safeParse(parentId).success) {
|
||||
throw AppError.badRequest("Identifiant de dossier invalide.");
|
||||
}
|
||||
|
||||
if (user.role_slug !== "admin" && parentId !== null) {
|
||||
// Contre l'IDOR : on ne liste un dossier que si la session y a acces.
|
||||
if (!(await canRead(db, user, parentId))) {
|
||||
throw AppError.notFound("Dossier introuvable.");
|
||||
}
|
||||
}
|
||||
|
||||
const rows = await db.query<FolderRow>(
|
||||
`${SELECT_FOLDER}
|
||||
WHERE f.deleted_at IS NULL
|
||||
AND (f.parent_id <=> ?)
|
||||
AND ( ? = 1
|
||||
OR f.owner_id = ?
|
||||
OR f.access_type = 'public'
|
||||
OR EXISTS ( SELECT 1 FROM folder_permissions fp
|
||||
WHERE fp.folder_id = f.id AND fp.user_id = ?
|
||||
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )
|
||||
ORDER BY f.name`,
|
||||
[parentId, user.role_slug === "admin" ? 1 : 0, user.id, user.id],
|
||||
);
|
||||
|
||||
return context.json({ parentId, folders: rows.map(publicFolder) });
|
||||
});
|
||||
|
||||
app.post(
|
||||
"/api/cloud/folders",
|
||||
requireAuth,
|
||||
requireRole("admin", "user"),
|
||||
async (context) => {
|
||||
const user = currentUser(context);
|
||||
const { name: rawName, parentId, description } = parse(
|
||||
createFolder,
|
||||
await context.req.json().catch(() => null),
|
||||
);
|
||||
const name = assertName(rawName);
|
||||
|
||||
if (parentId) {
|
||||
if (!(await canWrite(db, user, parentId))) {
|
||||
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier.");
|
||||
}
|
||||
}
|
||||
|
||||
const duplicate = await db.one(
|
||||
`SELECT 1 AS taken FROM folders
|
||||
WHERE parent_id <=> ? AND active_name = ? AND deleted_at IS NULL LIMIT 1`,
|
||||
[parentId ?? null, name],
|
||||
);
|
||||
if (duplicate) throw AppError.conflict("Ce nom existe deja ici.");
|
||||
|
||||
const parent = parentId
|
||||
? await db.one<{ id: string; storage_location_id: number }>(
|
||||
"SELECT id, storage_location_id FROM folders WHERE id = ? AND deleted_at IS NULL",
|
||||
[parentId],
|
||||
)
|
||||
: null;
|
||||
if (parentId && !parent) throw AppError.notFound("Dossier parent introuvable.");
|
||||
|
||||
const locationId =
|
||||
parent?.storage_location_id ??
|
||||
(
|
||||
await db.one<{ id: number }>(
|
||||
`SELECT id FROM storage_locations
|
||||
WHERE is_active = 1 AND deleted_at IS NULL ORDER BY id LIMIT 1`,
|
||||
)
|
||||
)?.id;
|
||||
if (locationId === undefined) {
|
||||
throw AppError.serviceUnavailable("Aucun emplacement de stockage disponible.");
|
||||
}
|
||||
|
||||
const id = randomUUID();
|
||||
try {
|
||||
await db.exec(
|
||||
`INSERT INTO folders (id, storage_location_id, parent_id, name, description, owner_id, created_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
[id, locationId, parentId ?? null, name, description ?? null, user.id, user.id],
|
||||
);
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Ce nom existe deja ici.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const created = await db.required<FolderRow>(`${SELECT_FOLDER} WHERE f.id = ?`, [id]);
|
||||
|
||||
await audit(db, context, user, "folder.create", "folder", id, { name }, config.TRUST_PROXY);
|
||||
|
||||
return context.json({ folder: publicFolder(created) }, 201);
|
||||
},
|
||||
);
|
||||
|
||||
app.patch("/api/cloud/folders/:id", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const id = context.req.param("id") ?? "";
|
||||
if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
const existing = await db.one<FolderRow>(`${SELECT_FOLDER} WHERE f.id = ? AND f.deleted_at IS NULL`, [id]);
|
||||
if (!existing) throw AppError.notFound("Dossier introuvable.");
|
||||
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
const data = parse(updateFolder, await context.req.json().catch(() => null));
|
||||
if (data.name === undefined && data.description === undefined) {
|
||||
throw AppError.badRequest("Rien a modifier.");
|
||||
}
|
||||
const name = data.name === undefined ? existing.name : assertName(data.name);
|
||||
|
||||
try {
|
||||
await db.exec(
|
||||
"UPDATE folders SET name = ?, description = ? WHERE id = ?",
|
||||
[name, data.description === undefined ? existing.description : data.description, id],
|
||||
);
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Ce nom existe deja ici.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const updated = await db.required<FolderRow>(`${SELECT_FOLDER} WHERE f.id = ?`, [id]);
|
||||
await audit(db, context, user, "folder.update", "folder", id, { name }, config.TRUST_PROXY);
|
||||
return context.json({ folder: publicFolder(updated) });
|
||||
});
|
||||
|
||||
app.post("/api/cloud/folders/:id/move", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const id = context.req.param("id") ?? "";
|
||||
if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
const existing = await db.one<FolderRow>(`${SELECT_FOLDER} WHERE f.id = ? AND f.deleted_at IS NULL`, [id]);
|
||||
if (!existing) throw AppError.notFound("Dossier introuvable.");
|
||||
if (existing.is_system === 1) throw AppError.forbidden("Le dossier public ne peut pas etre deplace.");
|
||||
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
const { parentId } = parse(moveFolder, await context.req.json().catch(() => null));
|
||||
|
||||
if (parentId !== null && parentId !== undefined) {
|
||||
if (!(await canWrite(db, user, parentId))) {
|
||||
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier de destination.");
|
||||
}
|
||||
// Refuse un deplacement dans soi-meme ou dans un descendant : sans cela,
|
||||
// l'arborescence se detache du graphe et devient inaccessible.
|
||||
const descendants = await subtreeIds(db, id);
|
||||
if (descendants.includes(parentId)) {
|
||||
throw AppError.badRequest("Impossible de deplacer un dossier dans lui-meme.");
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await db.exec("UPDATE folders SET parent_id = ? WHERE id = ?", [parentId ?? null, id]);
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Ce nom existe deja dans la destination.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const updated = await db.required<FolderRow>(`${SELECT_FOLDER} WHERE f.id = ?`, [id]);
|
||||
await audit(db, context, user, "folder.move", "folder", id, { parentId: parentId ?? null }, config.TRUST_PROXY);
|
||||
return context.json({ folder: publicFolder(updated) });
|
||||
});
|
||||
|
||||
/** Suppression logique recursive : le dossier, ses descendants et leurs fichiers. */
|
||||
app.delete("/api/cloud/folders/:id", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const id = context.req.param("id") ?? "";
|
||||
if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
const existing = await db.one<FolderRow>(`${SELECT_FOLDER} WHERE f.id = ? AND f.deleted_at IS NULL`, [id]);
|
||||
if (!existing) throw AppError.notFound("Dossier introuvable.");
|
||||
if (existing.is_system === 1) throw AppError.forbidden("Le dossier public ne peut pas etre supprime.");
|
||||
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
const ids = await subtreeIds(db, id);
|
||||
const placeholders = ids.map(() => "?").join(",");
|
||||
await db.transaction(async (connection) => {
|
||||
await connection.execute(
|
||||
`UPDATE folders SET deleted_at = UTC_TIMESTAMP() WHERE id IN (${placeholders}) AND deleted_at IS NULL`,
|
||||
ids,
|
||||
);
|
||||
await connection.execute(
|
||||
`UPDATE files SET deleted_at = UTC_TIMESTAMP() WHERE folder_id IN (${placeholders}) AND deleted_at IS NULL`,
|
||||
ids,
|
||||
);
|
||||
});
|
||||
|
||||
await audit(db, context, user, "folder.delete", "folder", id, { name: existing.name }, config.TRUST_PROXY);
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
|
||||
// --- Permissions nominatives -------------------------------------------
|
||||
|
||||
app.get("/api/cloud/folders/:id/permissions", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const id = context.req.param("id") ?? "";
|
||||
if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable.");
|
||||
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
const rows = await db.query<{
|
||||
user_id: string;
|
||||
email: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
level: string;
|
||||
expires_at: string | null;
|
||||
created_at: string;
|
||||
}>(
|
||||
`SELECT fp.user_id, u.email, u.first_name, u.last_name, fp.level, fp.expires_at, fp.created_at
|
||||
FROM folder_permissions fp
|
||||
JOIN users u ON u.id = fp.user_id
|
||||
WHERE fp.folder_id = ?
|
||||
ORDER BY u.email`,
|
||||
[id],
|
||||
);
|
||||
return context.json({
|
||||
permissions: rows.map((row) => ({
|
||||
user_id: row.user_id,
|
||||
email: row.email,
|
||||
first_name: row.first_name,
|
||||
last_name: row.last_name,
|
||||
level: row.level,
|
||||
expires_at: row.expires_at,
|
||||
created_at: row.created_at,
|
||||
})),
|
||||
});
|
||||
});
|
||||
|
||||
app.post("/api/cloud/folders/:id/permissions", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const id = context.req.param("id") ?? "";
|
||||
if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable.");
|
||||
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
const { email, level, expiresAt } = parse(
|
||||
permissionInput,
|
||||
await context.req.json().catch(() => null),
|
||||
);
|
||||
|
||||
const target = await db.one<{ id: string }>(
|
||||
"SELECT id FROM users WHERE active_email = ? AND deleted_at IS NULL",
|
||||
[email],
|
||||
);
|
||||
if (!target) throw AppError.notFound("Aucun compte ne correspond a cette adresse.");
|
||||
if (target.id === user.id) {
|
||||
throw AppError.badRequest("Vous etes deja proprietaire de ce dossier.");
|
||||
}
|
||||
|
||||
const expires = expiresAt ? new Date(expiresAt) : null;
|
||||
await db.exec(
|
||||
`INSERT INTO folder_permissions (id, folder_id, user_id, level, expires_at, granted_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON DUPLICATE KEY UPDATE level = VALUES(level), expires_at = VALUES(expires_at), granted_by = VALUES(granted_by)`,
|
||||
[randomUUID(), id, target.id, level, expires, user.id],
|
||||
);
|
||||
|
||||
await audit(db, context, user, "folder.share", "folder", id, { email, level }, config.TRUST_PROXY);
|
||||
return context.json({ ok: true }, 201);
|
||||
});
|
||||
|
||||
app.delete("/api/cloud/folders/:id/permissions/:userId", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const id = context.req.param("id") ?? "";
|
||||
const userId = context.req.param("userId") ?? "";
|
||||
if (!uuid.safeParse(id).success || !uuid.safeParse(userId).success) {
|
||||
throw AppError.notFound("Dossier introuvable.");
|
||||
}
|
||||
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
const result = await db.exec(
|
||||
"DELETE FROM folder_permissions WHERE folder_id = ? AND user_id = ?",
|
||||
[id, userId],
|
||||
);
|
||||
if (result.affectedRows === 0) throw AppError.notFound("Partage introuvable.");
|
||||
|
||||
await audit(db, context, user, "folder.unshare", "folder", id, { userId }, config.TRUST_PROXY);
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,85 @@
|
||||
import {
|
||||
AppError,
|
||||
attachUser,
|
||||
currentUser,
|
||||
requireAuth,
|
||||
type App,
|
||||
type Db,
|
||||
} from "../lib/index.js";
|
||||
|
||||
/**
|
||||
* Galerie : liste des fichiers accompagnes de leur nature (image, video,
|
||||
* document...), filtree par les memes droits que l'explorateur. Le dossier
|
||||
* public et les permissions nominatives sont pris en compte, sans exception.
|
||||
*/
|
||||
|
||||
const KINDS = ["image", "video", "audio", "document", "archive", "other"] as const;
|
||||
|
||||
export const registerMediaRoutes = (app: App, db: Db): void => {
|
||||
app.use("/api/cloud/media", attachUser(db));
|
||||
|
||||
app.get("/api/cloud/media", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const kind = context.req.query("kind") ?? "";
|
||||
if (kind !== "" && !(KINDS as readonly string[]).includes(kind)) {
|
||||
throw AppError.badRequest("Type de media inconnu.");
|
||||
}
|
||||
const limit = Math.min(200, Math.max(1, Number(context.req.query("limit")) || 60));
|
||||
const offset = Math.max(0, Number(context.req.query("offset")) || 0);
|
||||
|
||||
const rows = await db.query<{
|
||||
id: string;
|
||||
folder_id: string | null;
|
||||
name: string;
|
||||
mime_type: string | null;
|
||||
size_bytes: number;
|
||||
owner_id: string | null;
|
||||
is_starred: number;
|
||||
kind: string | null;
|
||||
width: number | null;
|
||||
height: number | null;
|
||||
created_at: string;
|
||||
has_thumbnail: number;
|
||||
}>(
|
||||
`SELECT fi.id, fi.folder_id, fi.name, fi.mime_type, fi.size_bytes, fi.owner_id,
|
||||
fi.is_starred, mm.kind, mm.width, mm.height, fi.created_at,
|
||||
EXISTS ( SELECT 1 FROM file_variants fv
|
||||
WHERE fv.file_id = fi.id AND fv.purpose = 'thumbnail' ) AS has_thumbnail
|
||||
FROM files fi
|
||||
LEFT JOIN media_metadata mm ON mm.file_id = fi.id
|
||||
WHERE fi.deleted_at IS NULL
|
||||
AND ( ? = '' OR mm.kind = ? )
|
||||
AND ( ? = 1
|
||||
OR fi.owner_id = ?
|
||||
OR ( fi.folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folders f
|
||||
WHERE f.id = fi.folder_id AND f.access_type = 'public' ) )
|
||||
OR ( fi.folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folder_permissions fp
|
||||
WHERE fp.folder_id = fi.folder_id AND fp.user_id = ?
|
||||
AND fp.level IN ('read', 'write', 'admin')
|
||||
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) ) )
|
||||
ORDER BY fi.created_at DESC
|
||||
LIMIT ${limit} OFFSET ${offset}`,
|
||||
[kind, kind, user.role_slug === "admin" ? 1 : 0, user.id, user.id],
|
||||
);
|
||||
|
||||
return context.json({
|
||||
kind: kind || null,
|
||||
items: rows.map((row) => ({
|
||||
id: row.id,
|
||||
folder_id: row.folder_id,
|
||||
name: row.name,
|
||||
mime_type: row.mime_type,
|
||||
size_bytes: row.size_bytes,
|
||||
owner_id: row.owner_id,
|
||||
is_starred: row.is_starred === 1,
|
||||
kind: row.kind,
|
||||
width: row.width,
|
||||
height: row.height,
|
||||
created_at: row.created_at,
|
||||
has_thumbnail: row.has_thumbnail === 1,
|
||||
})),
|
||||
});
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,113 @@
|
||||
import {
|
||||
AppError,
|
||||
attachUser,
|
||||
currentUser,
|
||||
requireAuth,
|
||||
type App,
|
||||
type Db,
|
||||
} from "../lib/index.js";
|
||||
|
||||
/**
|
||||
* Recherche par nom, filtree par les droits de la session. Le motif est
|
||||
* echappe : `%` et `_` saisis par l'utilisateur deviennent des caracteres
|
||||
* litteraux, jamais des jokers SQL. L'echappement par defaut de LIKE (barre
|
||||
* oblique inverse) suffit.
|
||||
*/
|
||||
|
||||
const escapeLike = (value: string): string =>
|
||||
value.replace(/[\\%_]/g, (match) => `\\${match}`);
|
||||
|
||||
const LIMIT = 100;
|
||||
|
||||
export const registerSearchRoutes = (app: App, db: Db): void => {
|
||||
app.use("/api/cloud/search", attachUser(db));
|
||||
|
||||
app.get("/api/cloud/search", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const q = (context.req.query("q") ?? "").trim();
|
||||
if (q.length < 1) throw AppError.badRequest("Indiquez un terme de recherche.");
|
||||
const admin = user.role_slug === "admin";
|
||||
const pattern = `%${escapeLike(q).slice(0, 110)}%`;
|
||||
|
||||
const folders = await db.query<{
|
||||
id: string;
|
||||
parent_id: string | null;
|
||||
name: string;
|
||||
description: string | null;
|
||||
owner_id: string | null;
|
||||
access_type: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}>(
|
||||
`SELECT f.id, f.parent_id, f.name, f.description, f.owner_id,
|
||||
f.access_type, f.created_at, f.updated_at
|
||||
FROM folders f
|
||||
WHERE f.deleted_at IS NULL
|
||||
AND f.name LIKE ?
|
||||
AND ( ? = 1
|
||||
OR f.owner_id = ?
|
||||
OR f.access_type = 'public'
|
||||
OR EXISTS ( SELECT 1 FROM folder_permissions fp
|
||||
WHERE fp.folder_id = f.id AND fp.user_id = ?
|
||||
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )
|
||||
ORDER BY f.name
|
||||
LIMIT ${LIMIT}`,
|
||||
[pattern, admin ? 1 : 0, user.id, user.id],
|
||||
);
|
||||
|
||||
const files = await db.query<{
|
||||
id: string;
|
||||
folder_id: string | null;
|
||||
name: string;
|
||||
mime_type: string | null;
|
||||
size_bytes: number;
|
||||
owner_id: string | null;
|
||||
is_starred: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}>(
|
||||
`SELECT fi.id, fi.folder_id, fi.name, fi.mime_type, fi.size_bytes, fi.owner_id,
|
||||
fi.is_starred, fi.created_at, fi.updated_at
|
||||
FROM files fi
|
||||
WHERE fi.deleted_at IS NULL
|
||||
AND fi.name LIKE ?
|
||||
AND ( ? = 1
|
||||
OR fi.owner_id = ?
|
||||
OR ( fi.folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folders f
|
||||
WHERE f.id = fi.folder_id AND f.access_type = 'public' ) )
|
||||
OR ( fi.folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folder_permissions fp
|
||||
WHERE fp.folder_id = fi.folder_id AND fp.user_id = ?
|
||||
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) ) )
|
||||
ORDER BY fi.name
|
||||
LIMIT ${LIMIT}`,
|
||||
[pattern, admin ? 1 : 0, user.id, user.id],
|
||||
);
|
||||
|
||||
return context.json({
|
||||
query: q,
|
||||
folders: folders.map((row) => ({
|
||||
id: row.id,
|
||||
parent_id: row.parent_id,
|
||||
name: row.name,
|
||||
description: row.description,
|
||||
owner_id: row.owner_id,
|
||||
access_type: row.access_type,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
})),
|
||||
files: files.map((row) => ({
|
||||
id: row.id,
|
||||
folder_id: row.folder_id,
|
||||
name: row.name,
|
||||
mime_type: row.mime_type,
|
||||
size_bytes: row.size_bytes,
|
||||
owner_id: row.owner_id,
|
||||
is_starred: row.is_starred === 1,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
})),
|
||||
});
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,378 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
AppError,
|
||||
attachUser,
|
||||
currentUser,
|
||||
requireAuth,
|
||||
type App,
|
||||
type Config,
|
||||
type Db,
|
||||
} from "../lib/index.js";
|
||||
import { audit } from "../access.js";
|
||||
import { absolutePath, discard } from "../storage.js";
|
||||
|
||||
const uuid = z
|
||||
.string()
|
||||
.regex(
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
|
||||
"Identifiant invalide.",
|
||||
);
|
||||
|
||||
/**
|
||||
* La corbeille se prete a l'echelle d'un utilisateur : un proprietaire voit ses
|
||||
* propres elements supprimes, un administrateur voit tout. Un element supprime
|
||||
* dont le parent est lui aussi supprime n'est pas liste : c'est la racine de la
|
||||
* suppression qui porte l'action.
|
||||
*/
|
||||
const subtreeIds = async (db: Db, rootId: string): Promise<string[]> => {
|
||||
const rows = await db.query<{ id: string }>(
|
||||
`WITH RECURSIVE subtree AS (
|
||||
SELECT id FROM folders WHERE id = ?
|
||||
UNION ALL
|
||||
SELECT f.id FROM folders f JOIN subtree s ON f.parent_id = s.id
|
||||
)
|
||||
SELECT id FROM subtree`,
|
||||
[rootId],
|
||||
);
|
||||
return rows.map((row) => row.id);
|
||||
};
|
||||
|
||||
/** Remonte la chaine des parents et annule leur suppression. */
|
||||
const restoreAncestors = async (db: Db, folderId: string | null): Promise<void> => {
|
||||
let current = folderId;
|
||||
const guard = new Set<string>();
|
||||
while (current !== null && !guard.has(current)) {
|
||||
guard.add(current);
|
||||
const parent = await db.one<{ parent_id: string | null }>(
|
||||
"SELECT parent_id FROM folders WHERE id = ?",
|
||||
[current],
|
||||
);
|
||||
if (!parent) break;
|
||||
await db.exec("UPDATE folders SET deleted_at = NULL WHERE id = ?", [current]);
|
||||
current = parent.parent_id;
|
||||
}
|
||||
};
|
||||
|
||||
/** Supprime physiquement des fichiers et rend leur espace aux quotas. */
|
||||
const purgeFiles = async (db: Db, config: Config, fileIds: string[]): Promise<void> => {
|
||||
if (fileIds.length === 0) return;
|
||||
const placeholders = fileIds.map(() => "?").join(",");
|
||||
|
||||
const rows = await db.query<{
|
||||
id: string;
|
||||
relative_path: string;
|
||||
size_bytes: number;
|
||||
owner_id: string | null;
|
||||
storage_location_id: number;
|
||||
}>(
|
||||
`SELECT id, relative_path, size_bytes, owner_id, storage_location_id
|
||||
FROM files WHERE id IN (${placeholders})`,
|
||||
fileIds,
|
||||
);
|
||||
|
||||
await Promise.all(
|
||||
rows.map((row) => discard(absolutePath(config.MEDIA_DIR, row.relative_path))),
|
||||
);
|
||||
|
||||
await db.transaction(async (connection) => {
|
||||
for (const row of rows) {
|
||||
if (row.owner_id) {
|
||||
await connection.execute(
|
||||
"UPDATE users SET used_bytes = GREATEST(0, CAST(used_bytes AS SIGNED) - ?) WHERE id = ?",
|
||||
[row.size_bytes, row.owner_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],
|
||||
);
|
||||
}
|
||||
await connection.execute(`DELETE FROM files WHERE id IN (${placeholders})`, fileIds);
|
||||
});
|
||||
};
|
||||
|
||||
/** Suppression definitive d'un dossier : ses fichiers puis lui-meme. */
|
||||
const purgeFolderTree = async (db: Db, config: Config, rootId: string): Promise<void> => {
|
||||
const folderIds = await subtreeIds(db, rootId);
|
||||
const folderPlaceholders = folderIds.map(() => "?").join(",");
|
||||
const files = await db.query<{ id: string }>(
|
||||
`SELECT id FROM files WHERE folder_id IN (${folderPlaceholders})`,
|
||||
folderIds,
|
||||
);
|
||||
await purgeFiles(db, config, files.map((row) => row.id));
|
||||
await db.exec(`DELETE FROM folders WHERE id IN (${folderPlaceholders})`, folderIds);
|
||||
};
|
||||
|
||||
interface TrashFileRow {
|
||||
id: string;
|
||||
folder_id: string | null;
|
||||
name: string;
|
||||
mime_type: string | null;
|
||||
size_bytes: number;
|
||||
owner_id: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
deleted_at: string;
|
||||
}
|
||||
|
||||
interface TrashFolderRow {
|
||||
id: string;
|
||||
parent_id: string | null;
|
||||
name: string;
|
||||
description: string | null;
|
||||
owner_id: string | null;
|
||||
access_type: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
deleted_at: string;
|
||||
}
|
||||
|
||||
const publicFile = (row: TrashFileRow) => ({
|
||||
id: row.id,
|
||||
folder_id: row.folder_id,
|
||||
name: row.name,
|
||||
mime_type: row.mime_type,
|
||||
size_bytes: row.size_bytes,
|
||||
owner_id: row.owner_id,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
deleted_at: row.deleted_at,
|
||||
});
|
||||
|
||||
const publicFolder = (row: TrashFolderRow) => ({
|
||||
id: row.id,
|
||||
parent_id: row.parent_id,
|
||||
name: row.name,
|
||||
description: row.description,
|
||||
owner_id: row.owner_id,
|
||||
access_type: row.access_type,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
deleted_at: row.deleted_at,
|
||||
});
|
||||
|
||||
export const registerTrashRoutes = (app: App, db: Db, config: Config): void => {
|
||||
app.use("/api/cloud/trash/*", attachUser(db));
|
||||
app.use("/api/cloud/trash", attachUser(db));
|
||||
|
||||
app.get("/api/cloud/trash", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const admin = user.role_slug === "admin";
|
||||
|
||||
// Seuls les elements dont le parent n'est pas lui-meme supprime figurent en
|
||||
// tete de corbeille : le reste suit la suppression du parent.
|
||||
const folders = await db.query<TrashFolderRow>(
|
||||
`SELECT f.id, f.parent_id, f.name, f.description, f.owner_id, f.access_type,
|
||||
f.created_at, f.updated_at, f.deleted_at
|
||||
FROM folders f
|
||||
LEFT JOIN folders p ON p.id = f.parent_id
|
||||
WHERE f.deleted_at IS NOT NULL
|
||||
AND f.is_system = 0
|
||||
AND (p.id IS NULL OR p.deleted_at IS NULL)
|
||||
AND ( ? = 1 OR f.owner_id = ? )
|
||||
ORDER BY f.deleted_at DESC`,
|
||||
[admin ? 1 : 0, user.id],
|
||||
);
|
||||
|
||||
const files = await db.query<TrashFileRow>(
|
||||
`SELECT fi.id, fi.folder_id, fi.name, fi.mime_type, fi.size_bytes, fi.owner_id,
|
||||
fi.created_at, fi.updated_at, fi.deleted_at
|
||||
FROM files fi
|
||||
LEFT JOIN folders p ON p.id = fi.folder_id
|
||||
WHERE fi.deleted_at IS NOT NULL
|
||||
AND (p.id IS NULL OR p.deleted_at IS NULL)
|
||||
AND ( ? = 1 OR fi.owner_id = ? )
|
||||
ORDER BY fi.deleted_at DESC`,
|
||||
[admin ? 1 : 0, user.id],
|
||||
);
|
||||
|
||||
const retentionDays = await db.one<{ setting_value: string }>(
|
||||
"SELECT setting_value FROM settings WHERE setting_key = 'trash_retention_days'",
|
||||
);
|
||||
|
||||
return context.json({
|
||||
retentionDays: retentionDays ? Number(retentionDays.setting_value) : 30,
|
||||
folders: folders.map(publicFolder),
|
||||
files: files.map(publicFile),
|
||||
});
|
||||
});
|
||||
|
||||
app.post("/api/cloud/trash/folders/:id/restore", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const id = context.req.param("id") ?? "";
|
||||
if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
const row = await db.one<{ owner_id: string | null; parent_id: string | null; name: string }>(
|
||||
`SELECT owner_id, parent_id, name FROM folders
|
||||
WHERE id = ? AND deleted_at IS NOT NULL AND is_system = 0`,
|
||||
[id],
|
||||
);
|
||||
if (!row) throw AppError.notFound("Dossier introuvable.");
|
||||
if (user.role_slug !== "admin" && row.owner_id !== user.id) {
|
||||
throw AppError.notFound("Dossier introuvable.");
|
||||
}
|
||||
|
||||
await restoreAncestors(db, row.parent_id);
|
||||
const folderIds = await subtreeIds(db, id);
|
||||
const placeholders = folderIds.map(() => "?").join(",");
|
||||
try {
|
||||
await db.transaction(async (connection) => {
|
||||
await connection.execute(
|
||||
`UPDATE folders SET deleted_at = NULL WHERE id IN (${placeholders})`,
|
||||
folderIds,
|
||||
);
|
||||
await connection.execute(
|
||||
`UPDATE files SET deleted_at = NULL WHERE folder_id IN (${placeholders})`,
|
||||
folderIds,
|
||||
);
|
||||
});
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Un element du meme nom occupe deja cet emplacement.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
await audit(db, context, user, "trash.restore", "folder", id, { name: row.name }, config.TRUST_PROXY);
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
|
||||
app.post("/api/cloud/trash/files/:id/restore", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const id = context.req.param("id") ?? "";
|
||||
if (!uuid.safeParse(id).success) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
const row = await db.one<{ owner_id: string | null; folder_id: string | null; name: string }>(
|
||||
"SELECT owner_id, folder_id, name FROM files WHERE id = ? AND deleted_at IS NOT NULL",
|
||||
[id],
|
||||
);
|
||||
if (!row) throw AppError.notFound("Fichier introuvable.");
|
||||
if (user.role_slug !== "admin" && row.owner_id !== user.id) {
|
||||
throw AppError.notFound("Fichier introuvable.");
|
||||
}
|
||||
|
||||
await restoreAncestors(db, row.folder_id);
|
||||
try {
|
||||
await db.exec("UPDATE files SET deleted_at = NULL WHERE id = ?", [id]);
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Un fichier du meme nom existe deja dans ce dossier.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
await audit(db, context, user, "trash.restore", "file", id, { name: row.name }, config.TRUST_PROXY);
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
|
||||
app.delete("/api/cloud/trash/folders/:id", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const id = context.req.param("id") ?? "";
|
||||
if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
const row = await db.one<{ owner_id: string | null; name: string }>(
|
||||
"SELECT owner_id, name FROM folders WHERE id = ? AND deleted_at IS NOT NULL AND is_system = 0",
|
||||
[id],
|
||||
);
|
||||
if (!row) throw AppError.notFound("Dossier introuvable.");
|
||||
if (user.role_slug !== "admin" && row.owner_id !== user.id) {
|
||||
throw AppError.notFound("Dossier introuvable.");
|
||||
}
|
||||
|
||||
await purgeFolderTree(db, config, id);
|
||||
await audit(db, context, user, "trash.purge", "folder", id, { name: row.name }, config.TRUST_PROXY);
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
|
||||
app.delete("/api/cloud/trash/files/:id", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const id = context.req.param("id") ?? "";
|
||||
if (!uuid.safeParse(id).success) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
const row = await db.one<{ owner_id: string | null; name: string }>(
|
||||
"SELECT owner_id, name FROM files WHERE id = ? AND deleted_at IS NOT NULL",
|
||||
[id],
|
||||
);
|
||||
if (!row) throw AppError.notFound("Fichier introuvable.");
|
||||
if (user.role_slug !== "admin" && row.owner_id !== user.id) {
|
||||
throw AppError.notFound("Fichier introuvable.");
|
||||
}
|
||||
|
||||
await purgeFiles(db, config, [id]);
|
||||
await audit(db, context, user, "trash.purge", "file", id, { name: row.name }, config.TRUST_PROXY);
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
|
||||
/** Vide la corbeille du compte appelant (tous les elements purges). */
|
||||
app.delete("/api/cloud/trash", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const admin = user.role_slug === "admin";
|
||||
|
||||
const folders = await db.query<{ id: string }>(
|
||||
`SELECT f.id FROM folders f
|
||||
LEFT JOIN folders p ON p.id = f.parent_id
|
||||
WHERE f.deleted_at IS NOT NULL AND f.is_system = 0
|
||||
AND (p.id IS NULL OR p.deleted_at IS NULL)
|
||||
AND ( ? = 1 OR f.owner_id = ? )`,
|
||||
[admin ? 1 : 0, user.id],
|
||||
);
|
||||
const files = await db.query<{ id: string }>(
|
||||
`SELECT fi.id FROM files fi
|
||||
LEFT JOIN folders p ON p.id = fi.folder_id
|
||||
WHERE fi.deleted_at IS NOT NULL
|
||||
AND (p.id IS NULL OR p.deleted_at IS NULL)
|
||||
AND ( ? = 1 OR fi.owner_id = ? )`,
|
||||
[admin ? 1 : 0, user.id],
|
||||
);
|
||||
|
||||
for (const folder of folders) await purgeFolderTree(db, config, folder.id);
|
||||
await purgeFiles(db, config, files.map((row) => row.id));
|
||||
|
||||
await audit(
|
||||
db,
|
||||
context,
|
||||
user,
|
||||
"trash.empty",
|
||||
"trash",
|
||||
null,
|
||||
{ folders: folders.length, files: files.length },
|
||||
config.TRUST_PROXY,
|
||||
);
|
||||
return context.json({ ok: true, folders: folders.length, files: files.length });
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Purge planifiee : les elements supprimes au-dela de la retention disparaissent
|
||||
* au demarrage. Aucun ordonnanceur externe n'est requis.
|
||||
*/
|
||||
export const purgeExpiredTrash = async (db: Db, config: Config): Promise<number> => {
|
||||
const setting = await db.one<{ setting_value: string }>(
|
||||
"SELECT setting_value FROM settings WHERE setting_key = 'trash_retention_days'",
|
||||
);
|
||||
const days = setting ? Number(setting.setting_value) : 30;
|
||||
if (!Number.isFinite(days) || days <= 0) return 0;
|
||||
|
||||
const folders = await db.query<{ id: string }>(
|
||||
`SELECT f.id FROM folders f
|
||||
LEFT JOIN folders p ON p.id = f.parent_id
|
||||
WHERE f.deleted_at IS NOT NULL AND f.is_system = 0
|
||||
AND (p.id IS NULL OR p.deleted_at IS NULL)
|
||||
AND f.deleted_at < UTC_TIMESTAMP() - INTERVAL ? DAY
|
||||
ORDER BY f.deleted_at`,
|
||||
[days],
|
||||
);
|
||||
const files = await db.query<{ id: string }>(
|
||||
`SELECT fi.id FROM files fi
|
||||
LEFT JOIN folders p ON p.id = fi.folder_id
|
||||
WHERE fi.deleted_at IS NOT NULL
|
||||
AND (p.id IS NULL OR p.deleted_at IS NULL)
|
||||
AND fi.deleted_at < UTC_TIMESTAMP() - INTERVAL ? DAY
|
||||
ORDER BY fi.deleted_at`,
|
||||
[days],
|
||||
);
|
||||
|
||||
for (const folder of folders) await purgeFolderTree(db, config, folder.id);
|
||||
await purgeFiles(db, config, files.map((row) => row.id));
|
||||
return folders.length + files.length;
|
||||
};
|
||||
Reference in New Issue
Block a user