Compare commits

..
2 Commits
Author SHA1 Message Date
Esiah e9851c482d chore: remove agent-oriented comments from the codebase
PR — Ouverture automatique / create-pr (push) Successful in 3s
2026-11-04 15:50:36 +01:00
Esiah 60d6fcaf94 feat(ui): set per-section document titles 2026-11-04 15:16:10 +01:00
103 changed files with 4711 additions and 5415 deletions
+5 -6
View File
@@ -7,14 +7,13 @@ Application autonome — front **et** back dans ce dépôt.
```
frontend application React + Vite, design system inclus (src/ui, src/styles)
backend API : routes (src/routes/*Routes.ts) + services (src/services/*Service.ts)
docker/ images nginx et API
backend API : socle serveur (src/lib), auth, dossiers, fichiers, médias
docker/ images nginx et API
```
Chaque application porte son propre code : le socle serveur
(`backend/src/{config,middleware,utils}`) et le design system
(`frontend/src/ui`) appartiennent au Cloud et ne sont partagés avec aucun autre
dépôt.
Chaque application porte son propre code : le socle serveur (`backend/src/lib`)
et le design system (`frontend/src/ui`) appartiennent au Cloud et ne sont
partagés avec aucun autre dépôt.
## Démarrer
+3 -5
View File
@@ -4,11 +4,9 @@ Stockage privé de fichiers. Le contenu ne vit jamais dans la base : MariaDB ne
décrit que des métadonnées, les octets restent sur le disque sous
`storage_locations.mount_path`.
Le service **existe et sert ce modèle** : 11 routeurs sous `/api/cloud`
(`src/routes/{authRoutes,accountRoutes,adminRoutes,chatRoutes,directoryRoutes,fileRoutes,folderRoutes,mediaRoutes,searchRoutes,trashRoutes,uploadRoutes}.ts`),
adossés aux services métier de `src/services/*Service.ts`. Le détail des
endpoints, des droits et du déploiement est dans
[`../../docs/api.md`](../../docs/api.md),
Le service **existe et sert ce modèle** : 10 routes sous `/api/cloud`
(`src/routes/{auth,folders,files}.ts`). Le détail des endpoints, des droits et
du déploiement est dans [`../../docs/api.md`](../../docs/api.md),
[`../../docs/security.md`](../../docs/security.md) et
[`../../docs/architecture.md`](../../docs/architecture.md).
@@ -1,9 +1,6 @@
import type { Context } from "hono";
import type { Db } from "../config/db.js";
import type { SessionUser } from "../models/types.js";
import { clientIp } from "../utils/http.js";
import { clientIp as sharedClientIp, type Db, type SessionUser } from "./lib/index.js";
/** Fragment SQL de lisibilite d'un dossier, partage par les requetes du chat. */
export const READ_SQL = `( f.owner_id = ?
OR f.access_type = 'public'
OR EXISTS ( SELECT 1 FROM folder_permissions fp
@@ -121,7 +118,9 @@ export const canTraverse = async (
return descendant !== null;
};
/** Consigne une action dans le journal d'audit (silencieux en cas d'echec). */
const clientIp = (context: Context, trustProxy: boolean): string | null =>
sharedClientIp(context, trustProxy);
export const audit = async (
db: Db,
context: Context,
+2 -4
View File
@@ -1,9 +1,6 @@
#!/usr/bin/env node
import { randomUUID } from "node:crypto";
import { ConfigError, loadDbConfig } from "./config/appConfig.js";
import { Db } from "./config/db.js";
import { hashPassword } from "./services/authService.js";
import { AppError, toSafeError } from "./utils/errors.js";
import { ConfigError, loadDbConfig, hashPassword, AppError, toSafeError } from "./lib/index.js";
const USAGE = `Utilisation : cohaise-admin --email <adr> --first <prenom> --last <nom> [options]
@@ -87,6 +84,7 @@ const main = async (argv: string[]): Promise<number> => {
throw error;
}
const { Db } = await import("./lib/index.js");
const db = new Db(config);
try {
+4 -4
View File
@@ -2,10 +2,10 @@
import { pathToFileURL } from "node:url";
import { resolve } from "node:path";
import { ConfigError, loadDbConfig } from "./config/appConfig.js";
import { Db } from "./config/db.js";
import { AppError, toSafeError } from "./utils/errors.js";
import { listMigrations, runMigrations } from "./utils/migrate.js";
import { ConfigError, loadDbConfig } from "./lib/config.js";
import { Db } from "./lib/db.js";
import { AppError, toSafeError } from "./lib/errors.js";
import { listMigrations, runMigrations } from "./lib/migrate.js";
interface Options {
dir: string;
+12 -15
View File
@@ -1,20 +1,17 @@
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { startService } from "./utils/service.js";
import { purgeExpiredSessions } from "./services/authService.js";
import { purgeExpiredTrash } from "./services/trashService.js";
import { purgeExpiredUploads } from "./services/uploadService.js";
import { registerAccountRoutes } from "./routes/accountRoutes.js";
import { registerAdminRoutes } from "./routes/adminRoutes.js";
import { registerAuthRoutes } from "./routes/authRoutes.js";
import { registerChatRoutes } from "./routes/chatRoutes.js";
import { registerDirectoryRoutes } from "./routes/directoryRoutes.js";
import { registerFileRoutes } from "./routes/fileRoutes.js";
import { registerFolderRoutes } from "./routes/folderRoutes.js";
import { registerMediaRoutes } from "./routes/mediaRoutes.js";
import { registerSearchRoutes } from "./routes/searchRoutes.js";
import { registerTrashRoutes } from "./routes/trashRoutes.js";
import { registerUploadRoutes } from "./routes/uploadRoutes.js";
import { purgeExpiredSessions, startService } from "./lib/index.js";
import { registerAccountRoutes } from "./routes/account.js";
import { registerAdminRoutes } from "./routes/admin.js";
import { registerAuthRoutes } from "./routes/auth.js";
import { registerChatRoutes } from "./routes/chat.js";
import { registerDirectoryRoutes } from "./routes/directory.js";
import { registerFileRoutes } from "./routes/files.js";
import { registerFolderRoutes } from "./routes/folders.js";
import { registerMediaRoutes } from "./routes/media.js";
import { registerSearchRoutes } from "./routes/search.js";
import { registerTrashRoutes, purgeExpiredTrash } from "./routes/trash.js";
import { purgeExpiredUploads, registerUploadRoutes } from "./routes/uploads.js";
const migrationsDir = join(dirname(fileURLToPath(import.meta.url)), "../migrations");
@@ -7,10 +7,10 @@ import {
timingSafeEqual,
} from "node:crypto";
import { promisify } from "node:util";
import type { Db } from "../config/db.js";
import type { Config } from "../config/appConfig.js";
import type { SessionMeta, SessionUser } from "../models/types.js";
import { AppError } from "../utils/errors.js";
import type { Context, Next } from "hono";
import { getCookie, setCookie, deleteCookie } from "hono/cookie";
import type { Db } from "./db.js";
import { AppError } from "./errors.js";
const scrypt = promisify(scryptCallback) as (
password: string | Buffer,
@@ -52,6 +52,22 @@ export const sha256 = (value: string): string => createHash("sha256").update(val
export const sessionTokenHash = (token: string, secret: string): string =>
createHmac("sha256", secret).update(token).digest("hex");
export interface SessionUser {
id: string;
email: string;
first_name: string;
last_name: string;
role_slug: string;
role_name: string;
is_active: number;
must_change_password: number;
}
export interface SessionMeta {
ipAddress?: string | null | undefined;
userAgent?: string | null | undefined;
}
export const SESSION_COOKIE = "cohaise_session";
export const createSession = async (
@@ -118,124 +134,82 @@ export const purgeExpiredSessions = async (db: Db): Promise<number> => {
return result.affectedRows;
};
export 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;
theme: string;
language: string;
avatar_updated_at: Date | null;
export const isHttpsRequest = (context: Context, trustProxy: boolean): boolean => {
if (trustProxy) {
const forwarded = context.req.header("x-forwarded-proto");
if (forwarded) return forwarded.split(",")[0]?.trim() === "https";
}
return context.req.raw.url.startsWith("https:");
};
export const setSessionCookie = (
context: Context,
token: string,
expiresAt: Date,
secure: boolean,
): void => {
setCookie(context, SESSION_COOKIE, token, {
httpOnly: true,
sameSite: "Lax",
secure,
path: "/",
expires: expiresAt,
});
};
export const clearSessionCookie = (context: Context): void => {
deleteCookie(context, SESSION_COOKIE, { path: "/" });
};
export interface AuthState {
user: SessionUser;
token: string;
}
export 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,
u.theme, u.language,
ua.updated_at AS avatar_updated_at
FROM users u
JOIN roles r ON r.id = u.role_id
LEFT JOIN user_avatars ua ON ua.user_id = u.id`;
export const attachUser =
(db: Db, secret: string) =>
async (context: Context, next: Next): Promise<void> => {
const token = getCookie(context, SESSION_COOKIE);
if (token) {
const user = await resolveSession(db, token, secret);
if (user) {
context.set("user", user);
context.set("token", token);
} else {
clearSessionCookie(context);
}
}
await next();
};
export 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,
theme: row.theme,
language: row.language,
has_avatar: row.avatar_updated_at !== null,
avatar_updated_at: row.avatar_updated_at,
});
const PASSWORD_CHANGE_ALLOWED = new Set([
"/api/cloud/auth/me",
"/api/cloud/auth/change-password",
"/api/cloud/auth/logout",
]);
export type PublicUser = ReturnType<typeof publicUser>;
let dummyHash: Promise<string> | undefined;
const decoyHash = (): Promise<string> => (dummyHash ??= hashPassword("aucun-compte-ne-correspond"));
/** Verifie les identifiants, cree la session et marque la derniere connexion. */
export const login = async (
db: Db,
config: Config,
email: string,
password: string,
meta: SessionMeta,
): Promise<{ user: PublicUser; token: string; expiresAt: Date }> => {
const row = await db.one<UserRow>(`${SELECT_USER} WHERE u.active_email = ?`, [email]);
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.");
export const requireAuth = async (context: Context, next: Next): Promise<void> => {
const user = context.get("user") as SessionUser | undefined;
if (!user) throw AppError.unauthorized();
if (user.must_change_password === 1 && !PASSWORD_CHANGE_ALLOWED.has(context.req.path)) {
throw AppError.forbidden("Vous devez changer votre mot de passe avant de continuer.");
}
const { token, expiresAt } = await createSession(
db,
row.id,
meta,
config.SESSION_TTL_HOURS,
config.SESSION_SECRET,
);
await db.exec("UPDATE users SET last_login_at = UTC_TIMESTAMP() WHERE id = ?", [row.id]);
return { user: publicUser(row), token, expiresAt };
await next();
};
/** Renvoie le profil public de l'utilisateur courant. */
export const me = async (db: Db, userId: string): Promise<PublicUser> => {
const row = await db.one<UserRow>(`${SELECT_USER} WHERE u.id = ?`, [userId]);
if (!row) throw AppError.unauthorized();
return publicUser(row);
};
export const requireRole =
(...slugs: string[]) =>
async (context: Context, next: Next): Promise<void> => {
const user = context.get("user") as SessionUser | undefined;
if (!user) throw AppError.unauthorized();
if (!slugs.includes(user.role_slug)) {
throw AppError.forbidden(`Action reservee au role : ${slugs.join(", ")}.`);
}
await next();
};
/** Change le mot de passe et revoque toutes les autres sessions. */
export const changePassword = async (
db: Db,
config: Config,
userId: string,
currentToken: string,
currentPassword: string,
nextPassword: string,
): Promise<void> => {
const row = await db.one<{ password_hash: string }>(
"SELECT password_hash FROM users WHERE id = ? AND deleted_at IS NULL",
[userId],
);
if (!row) throw AppError.unauthorized();
if (!(await verifyPassword(currentPassword, row.password_hash))) {
throw AppError.unauthorized("Mot de passe actuel incorrect.");
}
if (currentPassword === nextPassword) {
throw AppError.badRequest("Le nouveau mot de passe doit differer de l'actuel.");
}
const hash = await hashPassword(nextPassword);
await db.exec(
`UPDATE users
SET password_hash = ?, must_change_password = 0, password_changed_at = UTC_TIMESTAMP()
WHERE id = ?`,
[hash, userId],
);
await db.exec(
`UPDATE user_sessions
SET revoked_at = UTC_TIMESTAMP()
WHERE user_id = ? AND revoked_at IS NULL AND token_hash <> ?`,
[userId, sessionTokenHash(currentToken, config.SESSION_SECRET)],
);
export const currentUser = (context: Context): SessionUser => {
const user = context.get("user") as SessionUser | undefined;
if (!user) throw AppError.unauthorized();
return user;
};
@@ -1,5 +1,5 @@
import mysql, { type Pool, type PoolConnection, type ResultSetHeader, type RowDataPacket } from "mysql2/promise";
import type { DbConfig } from "./appConfig.js";
import type { DbConfig } from "./config.js";
export interface QueryError {
code: string;
@@ -1,9 +1,9 @@
import { randomUUID } from "node:crypto";
import { Hono, type Context, type Next } from "hono";
import { cors } from "hono/cors";
import type { SessionUser } from "../models/types.js";
import type { Config } from "../config/appConfig.js";
import type { Db } from "../config/db.js";
import type { SessionUser } from "./auth.js";
import type { Config } from "./config.js";
import type { Db } from "./db.js";
import { AppError, toSafeError } from "./errors.js";
export interface Logger {
+61
View File
@@ -0,0 +1,61 @@
export {
loadConfig,
loadDbConfig,
ConfigError,
type Config,
type DbConfig,
} from "./config.js";
export { Db } from "./db.js";
export { AppError, toSafeError, type SafeError } from "./errors.js";
export {
createApp,
createLogger,
clientIp,
JSON_BODY_MAX_BYTES,
readBodyCapped,
readJson,
type App,
type AppEnv,
type AppOptions,
type Logger,
type RouteDeps,
} from "./http.js";
export {
attachUser,
clearSessionCookie,
createSession,
currentUser,
isHttpsRequest,
hashPassword,
requireAuth,
requireRole,
purgeExpiredSessions,
revokeSession,
SESSION_COOKIE,
sessionTokenHash,
setSessionCookie,
sha256,
verifyPassword,
type SessionUser,
} from "./auth.js";
export {
listMigrations,
runMigrations,
assertNoDrift,
type MigrationResult,
} from "./migrate.js";
export { createMailer, link, type Mailer, type MailMessage } from "./mail.js";
export {
branding,
renderMail,
type Branding,
type MailContent,
type RenderedMail,
} from "./mail-template.js";
export { createRateLimiter, rateLimitKey, type RateLimiter } from "./ratelimit.js";
export {
prepareService,
startService,
type Service,
type ServiceOptions,
} from "./service.js";
@@ -1,17 +1,4 @@
import { readFileSync } from "node:fs";
import { createTransport, type Transporter } from "nodemailer";
import type { Config } from "../config/appConfig.js";
export interface MailMessage {
to: string;
subject: string;
text: string;
html?: string;
}
export interface Mailer {
send: (message: MailMessage) => Promise<void>;
}
import type { Config } from "./config.js";
export interface Branding {
appName: string;
@@ -21,6 +8,16 @@ export interface Branding {
footer: string;
}
export const LOGO_CID = "cohaise-logo";
export const branding = (config: Config): Branding => ({
appName: "CoHaiSe Cloud",
origin: config.PUBLIC_ORIGIN,
logoUrl: config.MAIL_LOGO_URL ?? `cid:${LOGO_CID}`,
color: "#b71c1c",
footer: config.SMTP_FROM,
});
export interface MailContent {
preview: string;
heading: string;
@@ -36,71 +33,6 @@ export interface RenderedMail {
text: string;
}
export const LOGO_CID = "cohaise-logo";
const LOGO_PATH = new URL("../../src/assets/logo.png", import.meta.url);
const loadLogo = (): Buffer | null => {
try {
return readFileSync(LOGO_PATH);
} catch {
return null;
}
};
const mailers = new WeakMap<Config, Mailer>();
/** Transport SMTP partage (un par configuration). */
export const getMailer = (config: Config): Mailer => {
const existing = mailers.get(config);
if (existing) return existing;
const mailer = createMailer(config);
mailers.set(config, mailer);
return mailer;
};
export const createMailer = (config: Config): Mailer => {
const transport: Transporter = createTransport({
host: config.SMTP_HOST,
port: config.SMTP_PORT,
secure: config.SMTP_SECURE,
...(config.SMTP_USER
? { auth: { user: config.SMTP_USER, pass: config.SMTP_PASSWORD ?? "" } }
: {}),
disableFileAccess: true,
disableUrlAccess: true,
});
const logo = config.MAIL_LOGO_URL ? null : loadLogo();
return {
send: async (message) => {
const inlineLogo = logo !== null && message.html?.includes(`cid:${LOGO_CID}`) === true;
await transport.sendMail({
from: config.SMTP_FROM,
to: message.to,
subject: message.subject,
text: message.text,
...(message.html ? { html: message.html } : {}),
...(inlineLogo
? { attachments: [{ filename: "logo.png", content: logo, cid: LOGO_CID }] }
: {}),
});
},
};
};
export const link = (config: Config, path: string): string =>
new URL(path, config.PUBLIC_ORIGIN).toString();
export const branding = (config: Config): Branding => ({
appName: "CoHaiSe Cloud",
origin: config.PUBLIC_ORIGIN,
logoUrl: config.MAIL_LOGO_URL ?? `cid:${LOGO_CID}`,
color: "#b71c1c",
footer: config.SMTP_FROM,
});
const escapeHtml = (value: string): string =>
value
.replace(/&/g, "&amp;")
@@ -198,4 +130,4 @@ export const renderMail = (brand: Branding, content: MailContent): RenderedMail
lines.push("", "Message automatique : merci de ne pas repondre a cet e-mail.", brand.footer);
return { html, text: lines.join("\n") };
};
};
+59
View File
@@ -0,0 +1,59 @@
import { readFileSync } from "node:fs";
import { createTransport, type Transporter } from "nodemailer";
import type { Config } from "./config.js";
import { LOGO_CID } from "./mail-template.js";
const LOGO_PATH = new URL("../../src/assets/logo.png", import.meta.url);
const loadLogo = (): Buffer | null => {
try {
return readFileSync(LOGO_PATH);
} catch {
return null;
}
};
export interface MailMessage {
to: string;
subject: string;
text: string;
html?: string;
}
export interface Mailer {
send: (message: MailMessage) => Promise<void>;
}
export const createMailer = (config: Config): Mailer => {
const transport: Transporter = createTransport({
host: config.SMTP_HOST,
port: config.SMTP_PORT,
secure: config.SMTP_SECURE,
...(config.SMTP_USER
? { auth: { user: config.SMTP_USER, pass: config.SMTP_PASSWORD ?? "" } }
: {}),
disableFileAccess: true,
disableUrlAccess: true,
});
const logo = config.MAIL_LOGO_URL ? null : loadLogo();
return {
send: async (message) => {
const inlineLogo = logo !== null && message.html?.includes(`cid:${LOGO_CID}`) === true;
await transport.sendMail({
from: config.SMTP_FROM,
to: message.to,
subject: message.subject,
text: message.text,
...(message.html ? { html: message.html } : {}),
...(inlineLogo
? { attachments: [{ filename: "logo.png", content: logo, cid: LOGO_CID }] }
: {}),
});
},
};
};
export const link = (config: Config, path: string): string =>
new URL(path, config.PUBLIC_ORIGIN).toString();
@@ -1,7 +1,7 @@
import { createHash } from "node:crypto";
import { readdir, readFile } from "node:fs/promises";
import path from "node:path";
import type { Db } from "../config/db.js";
import type { Db } from "./db.js";
export interface MigrationFile {
version: string;
@@ -1,9 +1,9 @@
import { createServer, type Server } from "node:http";
import { type AddressInfo } from "node:net";
import { getRequestListener } from "@hono/node-server";
import { ConfigError, loadConfig, type Config } from "../config/appConfig.js";
import { ConfigError, loadConfig, type Config } from "./config.js";
import { AppError } from "./errors.js";
import { Db } from "../config/db.js";
import { Db } from "./db.js";
import {
createLogger,
createApp,
@@ -2,10 +2,8 @@ import { randomUUID } from "node:crypto";
import { mkdir, stat } from "node:fs/promises";
import path from "node:path";
import sharp from "sharp";
import type { Config } from "../config/appConfig.js";
import type { Db } from "../config/db.js";
import type { SessionUser } from "../models/types.js";
import { absolutePath } from "./storageService.js";
import type { Config, Db } from "./lib/index.js";
import { absolutePath } from "./storage.js";
export type MediaKind = "image" | "video" | "audio" | "document" | "archive" | "other";
@@ -81,7 +79,6 @@ const writeThumbnail = async (source: string, destination: string): Promise<Thum
return { width: info.width, height: info.height, size: info.size };
};
/** Indexe un fichier : classification, vignette et metadonnees d'image. */
export const indexMedia = async (
db: Db,
config: Config,
@@ -130,88 +127,3 @@ export const thumbnailSize = async (config: Config, relative: string): Promise<n
return null;
}
};
const KINDS = ["image", "video", "audio", "document", "archive", "other"] as const;
export interface GalleryItem {
id: string;
folder_id: string | null;
name: string;
mime_type: string | null;
size_bytes: number;
owner_id: string | null;
is_starred: boolean;
kind: string | null;
width: number | null;
height: number | null;
created_at: string;
has_thumbnail: boolean;
}
/** Galerie des medias visibles, filtrable par type. */
export const gallery = async (
db: Db,
user: SessionUser,
kind: string,
limit: number,
offset: number,
): Promise<GalleryItem[]> => {
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,
(ufs.file_id IS NOT NULL) AS 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 user_file_stars ufs ON ufs.file_id = fi.id AND ufs.user_id = ?
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 folders f2
WHERE f2.id = fi.folder_id AND f2.owner_id = ? ) )
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}`,
[user.id, kind, kind, 0, user.id, user.id, user.id],
);
return 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,
}));
};
export const galleryKinds = KINDS;
-87
View File
@@ -1,87 +0,0 @@
import type { Context, Next } from "hono";
import { deleteCookie, getCookie, setCookie } from "hono/cookie";
import type { Db } from "../config/db.js";
import type { SessionUser } from "../models/types.js";
import { AppError } from "../utils/errors.js";
import { resolveSession, SESSION_COOKIE } from "../services/authService.js";
export const isHttpsRequest = (context: Context, trustProxy: boolean): boolean => {
if (trustProxy) {
const forwarded = context.req.header("x-forwarded-proto");
if (forwarded) return forwarded.split(",")[0]?.trim() === "https";
}
return context.req.raw.url.startsWith("https:");
};
export const setSessionCookie = (
context: Context,
token: string,
expiresAt: Date,
secure: boolean,
): void => {
setCookie(context, SESSION_COOKIE, token, {
httpOnly: true,
sameSite: "Lax",
secure,
path: "/",
expires: expiresAt,
});
};
export const clearSessionCookie = (context: Context): void => {
deleteCookie(context, SESSION_COOKIE, { path: "/" });
};
export interface AuthState {
user: SessionUser;
token: string;
}
/** Resout la session depuis le cookie et l'attache au contexte. */
export const attachUser =
(db: Db, secret: string) =>
async (context: Context, next: Next): Promise<void> => {
const token = getCookie(context, SESSION_COOKIE);
if (token) {
const user = await resolveSession(db, token, secret);
if (user) {
context.set("user", user);
context.set("token", token);
} else {
clearSessionCookie(context);
}
}
await next();
};
const PASSWORD_CHANGE_ALLOWED = new Set([
"/api/cloud/auth/me",
"/api/cloud/auth/change-password",
"/api/cloud/auth/logout",
]);
export const requireAuth = async (context: Context, next: Next): Promise<void> => {
const user = context.get("user") as SessionUser | undefined;
if (!user) throw AppError.unauthorized();
if (user.must_change_password === 1 && !PASSWORD_CHANGE_ALLOWED.has(context.req.path)) {
throw AppError.forbidden("Vous devez changer votre mot de passe avant de continuer.");
}
await next();
};
export const requireRole =
(...slugs: string[]) =>
async (context: Context, next: Next): Promise<void> => {
const user = context.get("user") as SessionUser | undefined;
if (!user) throw AppError.unauthorized();
if (!slugs.includes(user.role_slug)) {
throw AppError.forbidden(`Action reservee au role : ${slugs.join(", ")}.`);
}
await next();
};
export const currentUser = (context: Context): SessionUser => {
const user = context.get("user") as SessionUser | undefined;
if (!user) throw AppError.unauthorized();
return user;
};
-37
View File
@@ -1,37 +0,0 @@
/**
* Types partages entre les middlewares, les services et les routes.
*/
/** Utilisateur courant porte par la session (contexte Hono). */
export interface SessionUser {
id: string;
email: string;
first_name: string;
last_name: string;
role_slug: string;
role_name: string;
is_active: number;
must_change_password: number;
}
/** Metadonnees enregistrees a la creation d'une session. */
export interface SessionMeta {
ipAddress?: string | null | undefined;
userAgent?: string | null | undefined;
}
/** Ligne `files` (partagee entre fileService et uploadService). */
export 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;
}
+452
View File
@@ -0,0 +1,452 @@
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,
readBodyCapped,
readJson,
renderMail,
requireAuth,
sessionTokenHash,
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 preferencesInput = z.object({
theme: z.enum(["system", "light", "dark"]),
language: z.enum(["fr", "en"]),
});
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, config.SESSION_SECRET));
app.use("/api/cloud/account", attachUser(db, config.SESSION_SECRET));
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 readJson(context));
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/preferences", requireAuth, async (context) => {
const user = currentUser(context);
const row = await db.one<{ theme: string; language: string }>(
"SELECT theme, language FROM users WHERE id = ? AND deleted_at IS NULL",
[user.id],
);
if (!row) throw AppError.notFound("Compte introuvable.");
return context.json({ theme: row.theme, language: row.language });
});
app.patch("/api/cloud/account/preferences", requireAuth, async (context) => {
const user = currentUser(context);
const data = parse(preferencesInput, await readJson(context));
await db.exec("UPDATE users SET theme = ?, language = ? WHERE id = ?", [
data.theme,
data.language,
user.id,
]);
return context.json({ theme: data.theme, language: data.language });
});
app.get("/api/cloud/account/sessions", requireAuth, async (context) => {
const user = currentUser(context);
const current = sessionTokenHash(context.get("token") ?? "", config.SESSION_SECRET);
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 = sessionTokenHash(context.get("token") ?? "", config.SESSION_SECRET);
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 = await readBodyCapped(context, AVATAR_MAX_BYTES);
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 readJson(context));
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],
);
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 readJson(context));
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 readJson(context));
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 readJson(context),
);
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 });
});
};
-197
View File
@@ -1,197 +0,0 @@
import { Readable } from "node:stream";
import { z } from "zod";
import type { Config } from "../config/appConfig.js";
import type { Db } from "../config/db.js";
import type { SessionUser } from "../models/types.js";
import { attachUser, currentUser, requireAuth } from "../middleware/auth.js";
import { audit } from "../services/auditService.js";
import {
confirmEmailChange,
deleteAvatar,
forgotPassword,
getAvatar,
getPreferences,
listSessions,
requestEmailChange,
resetPassword,
revokeOtherSessions,
revokeSessionById,
updatePreferences,
updateProfile,
uploadAvatar,
} from "../services/accountService.js";
import { openForDownload } from "../services/storageService.js";
import { AppError } from "../utils/errors.js";
import { clientIp, readBodyCapped, readJson, type App } from "../utils/http.js";
import { createRateLimiter, rateLimitKey } from "../utils/ratelimit.js";
import { parse } from "../utils/validators.js";
const AVATAR_MAX_BYTES = 8 * 1024 * 1024;
const profileInput = z.object({
first_name: z.string().trim().min(1).max(50),
last_name: z.string().trim().min(1).max(50),
});
const preferencesInput = z.object({
theme: z.enum(["system", "light", "dark"]),
language: z.enum(["fr", "en"]),
});
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, config.SESSION_SECRET));
app.use("/api/cloud/account", attachUser(db, config.SESSION_SECRET));
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 readJson(context));
const updated = await updateProfile(db, user, data.first_name, data.last_name);
await audit(db, context, user, "profile.update", "user", user.id, null, config.TRUST_PROXY);
return context.json({ ok: true, ...updated });
});
app.get("/api/cloud/account/preferences", requireAuth, async (context) => {
const user = currentUser(context);
return context.json(await getPreferences(db, user));
});
app.patch("/api/cloud/account/preferences", requireAuth, async (context) => {
const user = currentUser(context);
const data = parse(preferencesInput, await readJson(context));
return context.json(await updatePreferences(db, user, data.theme, data.language));
});
app.get("/api/cloud/account/sessions", requireAuth, async (context) => {
const user = currentUser(context);
const sessions = await listSessions(db, config, user, context.get("token") ?? "");
return context.json({ sessions });
});
app.delete("/api/cloud/account/sessions/:id", requireAuth, async (context) => {
const user = currentUser(context);
await revokeSessionById(db, user, context.req.param("id") ?? "");
return context.json({ ok: true });
});
app.delete("/api/cloud/account/sessions", requireAuth, async (context) => {
const user = currentUser(context);
await revokeOtherSessions(db, config, user, context.get("token") ?? "");
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 = await readBodyCapped(context, AVATAR_MAX_BYTES);
await uploadAvatar(db, config, user, source);
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 avatar = await getAvatar(db, config, context.req.param("userId") ?? "");
if (!avatar) throw AppError.notFound("Avatar introuvable.");
const stream = Readable.toWeb(openForDownload(avatar.absolute)) as ReadableStream<Uint8Array>;
return new Response(stream, {
headers: {
"content-type": "image/webp",
"content-length": String(avatar.size),
"cache-control": "private, max-age=86400",
},
});
});
app.delete("/api/cloud/account/avatar", requireAuth, async (context) => {
const user = currentUser(context);
await deleteAvatar(db, user);
return context.json({ ok: true });
});
app.post("/api/cloud/account/forgot-password", async (context) => {
const data = parse(forgotInput, await readJson(context));
throttle(context, `forgot:${data.email.toLowerCase()}`);
await forgotPassword(db, config, data.email);
return context.json({ ok: true });
});
app.post("/api/cloud/account/reset-password", async (context) => {
const data = parse(resetInput, await readJson(context));
throttle(context, "reset");
const actor = await resetPassword(db, data.token, data.password);
if (actor) {
const sessionUser: SessionUser = {
id: actor.userId,
email: actor.email,
first_name: actor.first_name,
last_name: actor.last_name,
role_slug: "user",
role_name: "",
is_active: 1,
must_change_password: 0,
};
await audit(db, context, sessionUser, "password.reset", "user", actor.userId, 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 readJson(context));
throttle(context, `email:${user.id}`);
await requestEmailChange(db, config, user, data.password, data.new_email);
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 readJson(context),
);
const email = await confirmEmailChange(db, data.token);
return context.json({ ok: true, email });
});
};
+541
View File
@@ -0,0 +1,541 @@
import { randomInt, randomUUID } from "node:crypto";
import { z } from "zod";
import {
AppError,
attachUser,
branding,
createMailer,
currentUser,
hashPassword,
link,
renderMail,
requireAuth,
readJson,
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"];
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]}`;
};
const generatePasswordValue = (): string => {
const alphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
let out = "";
for (let index = 0; index < 18; index += 1) out += alphabet[randomInt(alphabet.length)];
return out;
};
const rehomeUserFolders = async (db: Db, userId: string): Promise<{ kept: number; deleted: number }> => {
const folders = await db.query<{ id: string; parent_id: string | null }>(
"SELECT id, parent_id FROM folders WHERE owner_id = ? AND deleted_at IS NULL AND is_system = 0",
[userId],
);
if (folders.length === 0) return { kept: 0, deleted: 0 };
const ids = folders.map((folder) => folder.id);
const placeholders = ids.map(() => "?").join(",");
const candidates = await db.query<{
folder_id: string;
user_id: string;
level: string;
created_at: string;
}>(
`SELECT fp.folder_id, fp.user_id, fp.level, fp.created_at
FROM folder_permissions fp
JOIN users u ON u.id = fp.user_id AND u.deleted_at IS NULL AND u.is_active = 1
WHERE fp.folder_id IN (${placeholders})
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() )
ORDER BY FIELD(fp.level, 'admin', 'write', 'read'), fp.created_at ASC`,
[...ids],
);
const newOwner = new Map<string, string>();
for (const row of candidates) {
if (!newOwner.has(row.folder_id)) newOwner.set(row.folder_id, row.user_id);
}
const owned = new Map(folders.map((folder) => [folder.id, folder.parent_id]));
const keepIds = [...newOwner.keys()];
const deleteIds = ids.filter((id) => !newOwner.has(id));
await db.transaction(async (connection) => {
for (const [id, owner] of newOwner) {
const parentId = owned.get(id) ?? null;
const parentGone = parentId !== null && owned.has(parentId) && !newOwner.has(parentId);
await connection.execute(
"UPDATE folders SET owner_id = ?, parent_id = ? WHERE id = ?",
[owner, parentGone ? null : parentId, id],
);
}
if (deleteIds.length > 0) {
const delPh = deleteIds.map(() => "?").join(",");
await connection.execute(
`UPDATE folders SET parent_id = NULL
WHERE parent_id IN (${delPh}) AND deleted_at IS NULL
AND owner_id <> ? AND id NOT IN (${keepIds.map(() => "?").join(",") || "''"})`,
[...deleteIds, userId, ...(keepIds.length > 0 ? keepIds : [])],
);
await connection.execute(
`UPDATE folders SET deleted_at = UTC_TIMESTAMP() WHERE id IN (${delPh}) AND deleted_at IS NULL`,
deleteIds,
);
await connection.execute(
`UPDATE files SET deleted_at = UTC_TIMESTAMP() WHERE folder_id IN (${delPh}) AND deleted_at IS NULL`,
deleteIds,
);
}
await connection.execute("DELETE FROM folder_permissions WHERE user_id = ?", [userId]);
await connection.execute("DELETE FROM user_file_stars WHERE user_id = ?", [userId]);
});
return { kept: keepIds.length, deleted: deleteIds.length };
};
export const registerAdminRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/admin/*", attachUser(db, config.SESSION_SECRET));
app.use("/api/cloud/admin", attachUser(db, config.SESSION_SECRET));
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();
};
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 readJson(context));
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) }, 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 readJson(context));
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.");
const rehomed = await rehomeUserFolders(db, id);
await db.exec("UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ?", [id]);
return context.json({ ok: true, folders: rehomed });
});
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],
);
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({ ok: true });
});
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 readJson(context));
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 readJson(context));
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/filters", requireAuth, async (context) => {
requireAdmin(context);
const actions = await db.query<{ action: string }>(
"SELECT DISTINCT action FROM audit_logs ORDER BY action ASC",
);
const users = await db.query<{ user_id: string; user_email: string | null }>(
`SELECT user_id, MAX(user_email) AS user_email
FROM audit_logs
WHERE user_id IS NOT NULL
GROUP BY user_id
ORDER BY user_email ASC`,
);
return context.json({
actions: actions.map((row) => row.action),
users: users.map((row) => ({ id: row.user_id, email: row.user_email })),
});
});
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") || null;
const userId = context.req.query("userId") || null;
const conditions: string[] = [];
const params: unknown[] = [];
if (action) {
conditions.push("action = ?");
params.push(action);
}
if (userId) {
conditions.push("user_id = ?");
params.push(userId);
}
const where = conditions.length > 0 ? ` WHERE ${conditions.join(" AND ")}` : "";
const rows = await db.query(
`SELECT id, user_id, user_email, action, resource, resource_id, details, ip_address, created_at
FROM audit_logs${where} ORDER BY created_at DESC LIMIT ${limit} OFFSET ${offset}`,
params,
);
return context.json({ entries: rows });
});
};
-148
View File
@@ -1,148 +0,0 @@
import { z } from "zod";
import type { Config } from "../config/appConfig.js";
import type { Db } from "../config/db.js";
import { attachUser, currentUser, requireAuth } from "../middleware/auth.js";
import {
auditEntries,
auditFilters,
createStorageLocation,
createUser,
deleteUser,
getStats,
listStorageLocations,
listUsers,
publicUser,
resetUserPassword,
updateStorageLocation,
updateUser,
} from "../services/adminService.js";
import { AppError } from "../utils/errors.js";
import { readJson, type App } from "../utils/http.js";
import { parse, uuid } from "../utils/validators.js";
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(),
});
export const registerAdminRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/admin/*", attachUser(db, config.SESSION_SECRET));
app.use("/api/cloud/admin", attachUser(db, config.SESSION_SECRET));
const requireAdmin = (context: Parameters<typeof currentUser>[0]): void => {
if (currentUser(context).role_slug !== "admin") throw AppError.forbidden();
};
app.get("/api/cloud/admin/stats", requireAuth, async (context) => {
requireAdmin(context);
return context.json(await getStats(db, config));
});
app.get("/api/cloud/admin/users", requireAuth, async (context) => {
requireAdmin(context);
const users = await listUsers(db, context.req.query("q") ?? "");
return context.json({ users: users.map(publicUser) });
});
app.post("/api/cloud/admin/users", requireAuth, async (context) => {
requireAdmin(context);
const data = parse(createUserSchema, await readJson(context));
const created = await createUser(db, config, data);
return context.json({ user: publicUser(created) }, 201);
});
app.patch("/api/cloud/admin/users/:id", requireAuth, async (context) => {
const actor = currentUser(context);
requireAdmin(context);
const id = context.req.param("id") ?? "";
if (!uuid.safeParse(id).success) throw AppError.notFound("Compte introuvable.");
const data = parse(updateUserSchema, await readJson(context));
const updated = await updateUser(db, actor.id, id, data);
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 (!uuid.safeParse(id).success) throw AppError.notFound("Compte introuvable.");
const rehomed = await deleteUser(db, actor.id, id);
return context.json({ ok: true, folders: rehomed });
});
app.post("/api/cloud/admin/users/:id/reset-password", requireAuth, async (context) => {
requireAdmin(context);
const id = context.req.param("id") ?? "";
if (!uuid.safeParse(id).success) throw AppError.notFound("Compte introuvable.");
await resetUserPassword(db, config, id);
return context.json({ ok: true });
});
app.get("/api/cloud/admin/storage-locations", requireAuth, async (context) => {
requireAdmin(context);
return context.json(await listStorageLocations(db, config));
});
app.post("/api/cloud/admin/storage-locations", requireAuth, async (context) => {
requireAdmin(context);
const data = parse(createLocationSchema, await readJson(context));
await createStorageLocation(db, config, data);
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 readJson(context));
await updateStorageLocation(db, config, id, data);
return context.json({ ok: true });
});
app.get("/api/cloud/admin/audit/filters", requireAuth, async (context) => {
requireAdmin(context);
return context.json(await auditFilters(db));
});
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") || null;
const userId = context.req.query("userId") || null;
const entries = await auditEntries(db, { limit, offset, action, userId });
return context.json({ entries });
});
};
+177
View File
@@ -0,0 +1,177 @@
import { z } from "zod";
import {
AppError,
attachUser,
clearSessionCookie,
clientIp,
createRateLimiter,
createSession,
currentUser,
hashPassword,
isHttpsRequest,
rateLimitKey,
readJson,
requireAuth,
revokeSession,
sessionTokenHash,
setSessionCookie,
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),
});
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;
theme: string;
language: string;
avatar_updated_at: Date | null;
}
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,
theme: row.theme,
language: row.language,
has_avatar: row.avatar_updated_at !== null,
avatar_updated_at: row.avatar_updated_at,
});
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,
u.theme, u.language,
ua.updated_at AS avatar_updated_at
FROM users u
JOIN roles r ON r.id = u.role_id
LEFT JOIN user_avatars ua ON ua.user_id = u.id`;
export const registerAuthRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/*", async (context, next) => {
await next();
context.header("cache-control", "no-store");
});
app.use("/api/cloud/*", attachUser(db, config.SESSION_SECRET));
const limiter = createRateLimiter(config.RATE_LIMIT_LOGIN_MAX, config.RATE_LIMIT_LOGIN_WINDOW_MS);
app.post("/api/cloud/auth/login", async (context) => {
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 readJson(context));
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]);
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,
config.SESSION_SECRET,
);
await db.exec("UPDATE users SET last_login_at = UTC_TIMESTAMP() WHERE id = ?", [row.id]);
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, config.SESSION_SECRET);
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),
});
app.post("/api/cloud/auth/change-password", requireAuth, async (context) => {
const session = currentUser(context);
const parsed = changePassword.safeParse(await readJson(context));
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],
);
await db.exec(
`UPDATE user_sessions
SET revoked_at = UTC_TIMESTAMP()
WHERE user_id = ? AND revoked_at IS NULL AND token_hash <> ?`,
[session.id, sessionTokenHash(context.get("token") ?? "", config.SESSION_SECRET)],
);
return context.json({ ok: true });
});
};
-87
View File
@@ -1,87 +0,0 @@
import { z } from "zod";
import type { Config } from "../config/appConfig.js";
import type { Db } from "../config/db.js";
import {
attachUser,
clearSessionCookie,
currentUser,
isHttpsRequest,
requireAuth,
setSessionCookie,
} from "../middleware/auth.js";
import { changePassword, login, me, revokeSession } from "../services/authService.js";
import { AppError } from "../utils/errors.js";
import { clientIp, readJson, type App } from "../utils/http.js";
import { createRateLimiter, rateLimitKey } from "../utils/ratelimit.js";
const credentials = z.object({
email: z.string().trim().min(3).max(255),
password: z.string().min(1).max(1024),
});
const changePasswordInput = z.object({
current: z.string().min(1).max(1024),
next: z.string().min(8).max(1024),
});
export const registerAuthRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/*", async (context, next) => {
await next();
context.header("cache-control", "no-store");
});
app.use("/api/cloud/*", attachUser(db, config.SESSION_SECRET));
const limiter = createRateLimiter(config.RATE_LIMIT_LOGIN_MAX, config.RATE_LIMIT_LOGIN_WINDOW_MS);
app.post("/api/cloud/auth/login", async (context) => {
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 readJson(context));
if (!parsed.success) throw AppError.badRequest("Identifiants invalides.");
const forwarded = context.req.header("x-forwarded-for");
const { user, token, expiresAt } = await login(db, config, parsed.data.email, parsed.data.password, {
ipAddress: config.TRUST_PROXY && forwarded ? forwarded.split(",")[0]?.trim() : null,
userAgent: context.req.header("user-agent"),
});
const secure = isHttpsRequest(context, config.TRUST_PROXY);
setSessionCookie(context, token, expiresAt, secure);
return context.json({ user });
});
app.post("/api/cloud/auth/logout", requireAuth, async (context) => {
const token = context.get("token");
if (token) await revokeSession(db, token, config.SESSION_SECRET);
clearSessionCookie(context);
return context.json({ ok: true });
});
app.get("/api/cloud/auth/me", requireAuth, async (context) => {
const session = currentUser(context);
return context.json({ user: await me(db, session.id) });
});
app.post("/api/cloud/auth/change-password", requireAuth, async (context) => {
const session = currentUser(context);
const parsed = changePasswordInput.safeParse(await readJson(context));
if (!parsed.success) {
throw AppError.badRequest("Le nouveau mot de passe doit contenir au moins 8 caracteres.");
}
await changePassword(
db,
config,
session.id,
context.get("token") ?? "",
parsed.data.current,
parsed.data.next,
);
return context.json({ ok: true });
});
};
+355
View File
@@ -0,0 +1,355 @@
import { z } from "zod";
import {
AppError,
createRateLimiter,
currentUser,
readJson,
requireAuth,
type App,
type Config,
type Db,
} from "../lib/index.js";
import { audit, canManageFolder, canRead, READ_SQL } 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 sendInput = z.object({
body: z.string().trim().min(1, "Message vide.").max(2000, "Message trop long."),
});
const editInput = z.object({
body: z.string().trim().min(1, "Message vide.").max(2000, "Message trop long."),
});
const DATETIME_CURSOR = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,6})?$/;
interface MessageRow {
id: number;
user_id: string | null;
body: string;
created_at: string;
edited_at: string | null;
is_pinned: number;
first_name: string | null;
last_name: string | null;
avatar_updated_at: Date | null;
}
const SELECT_MESSAGE = `
SELECT m.id, m.user_id, m.body, m.created_at, m.edited_at, m.is_pinned,
u.first_name, u.last_name, ua.updated_at AS avatar_updated_at
FROM chat_messages m
LEFT JOIN users u ON u.id = m.user_id
LEFT JOIN user_avatars ua ON ua.user_id = m.user_id`;
const publicMessage = (row: MessageRow) => ({
id: row.id,
user_id: row.user_id,
first_name: row.first_name,
last_name: row.last_name,
body: row.body,
created_at: row.created_at,
edited_at: row.edited_at,
is_pinned: row.is_pinned === 1,
has_avatar: row.user_id !== null && row.avatar_updated_at !== null,
avatar_updated_at: row.avatar_updated_at,
});
export const registerChatRoutes = (app: App, db: Db, config: Config): void => {
const limiter = createRateLimiter(20, 10_000);
const assertFolder = async (
folderId: string,
): Promise<{ id: string; owner_id: string | null; access_type: string }> => {
if (!uuid.safeParse(folderId).success) throw AppError.notFound("Dossier introuvable.");
const folder = await db.one<{ id: string; owner_id: string | null; access_type: string }>(
"SELECT id, owner_id, access_type FROM folders WHERE id = ? AND deleted_at IS NULL",
[folderId],
);
if (!folder) throw AppError.notFound("Dossier introuvable.");
return folder;
};
const markRead = async (folderId: string, userId: string, messageId: number): Promise<void> => {
if (messageId <= 0) return;
await db
.exec(
`INSERT INTO chat_reads (folder_id, user_id, last_read_message_id)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE
last_read_message_id = GREATEST(last_read_message_id, ?),
updated_at = UTC_TIMESTAMP(3)`,
[folderId, userId, messageId, messageId],
)
.catch(() => undefined);
};
app.get("/api/cloud/chat/unread", requireAuth, async (context) => {
const user = currentUser(context);
const rows = await db.query<{ folder_id: string; unread: number }>(
`SELECT f.id AS folder_id, COUNT(m.id) AS unread
FROM folders f
JOIN chat_messages m
ON m.folder_id = f.id
AND m.deleted_at IS NULL
AND m.user_id <> ?
WHERE f.deleted_at IS NULL
AND m.id > COALESCE (
( SELECT cr.last_read_message_id
FROM chat_reads cr
WHERE cr.folder_id = f.id AND cr.user_id = ? ), 0 )
AND ${READ_SQL}
GROUP BY f.id
HAVING unread > 0`,
[user.id, user.id, user.id, user.id],
);
const unread: Record<string, number> = {};
for (const row of rows) unread[row.folder_id] = Number(row.unread);
return context.json({ unread });
});
app.get("/api/cloud/folders/:folderId/chat/members", requireAuth, async (context) => {
const user = currentUser(context);
const folderId = context.req.param("folderId") ?? "";
const folder = await assertFolder(folderId);
if (!(await canRead(db, user, folderId))) throw AppError.notFound("Dossier introuvable.");
const rows = await db.query<{
id: string;
first_name: string;
last_name: string;
role_slug: string;
avatar_updated_at: Date | null;
last_login_at: string | null;
}>(
`SELECT u.id, u.first_name, u.last_name, r.slug AS role_slug,
ua.updated_at AS avatar_updated_at, u.last_login_at
FROM users u
JOIN roles r ON r.id = u.role_id
LEFT JOIN user_avatars ua ON ua.user_id = u.id
WHERE u.deleted_at IS NULL AND u.is_active = 1
AND ( u.id = ?
OR ? = 1
OR EXISTS ( SELECT 1 FROM folder_permissions fp
WHERE fp.folder_id = ? AND fp.user_id = u.id
AND fp.level IN ('read', 'write', 'admin')
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )
ORDER BY u.first_name ASC, u.last_name ASC`,
[folder.owner_id, folder.access_type === "public" ? 1 : 0, folderId],
);
return context.json({
members: rows.map((row) => ({
id: row.id,
first_name: row.first_name,
last_name: row.last_name,
role_slug: row.role_slug,
has_avatar: row.avatar_updated_at !== null,
avatar_updated_at: row.avatar_updated_at,
last_login_at: row.last_login_at,
is_self: row.id === user.id,
})),
});
});
app.get("/api/cloud/folders/:folderId/chat/messages", requireAuth, async (context) => {
const user = currentUser(context);
const folderId = context.req.param("folderId") ?? "";
await assertFolder(folderId);
if (!(await canRead(db, user, folderId))) throw AppError.notFound("Dossier introuvable.");
const limit = Math.min(200, Math.max(1, Number(context.req.query("limit")) || 50));
const after = Math.max(0, Number(context.req.query("after")) || 0);
const cursorRow = await db.one<{ chat_cursor: string }>(
"SELECT DATE_FORMAT(CURRENT_TIMESTAMP(3), '%Y-%m-%dT%H:%i:%s.%f') AS chat_cursor",
);
const serverCursor = cursorRow?.chat_cursor ?? "1970-01-01T00:00:00.000000";
const editedAfterRaw = context.req.query("editedAfter");
const editedSince =
typeof editedAfterRaw === "string" && DATETIME_CURSOR.test(editedAfterRaw)
? editedAfterRaw
: serverCursor;
const rows =
after > 0
? await db.query<MessageRow>(
`${SELECT_MESSAGE}
WHERE m.folder_id = ? AND m.deleted_at IS NULL
AND ( m.id > ?
OR ( m.edited_at IS NOT NULL AND m.edited_at >= ? ) )
ORDER BY m.id ASC
LIMIT ${limit}`,
[folderId, after, editedSince],
)
: (
await db.query<MessageRow>(
`${SELECT_MESSAGE}
WHERE m.folder_id = ? AND m.deleted_at IS NULL
ORDER BY m.id DESC
LIMIT ${limit}`,
[folderId],
)
).reverse();
const newest = rows.reduce((max, row) => Math.max(max, row.id), 0);
await markRead(folderId, user.id, newest);
return context.json({ messages: rows.map(publicMessage), cursor: serverCursor });
});
app.post("/api/cloud/folders/:folderId/chat/messages", requireAuth, async (context) => {
const user = currentUser(context);
const folderId = context.req.param("folderId") ?? "";
await assertFolder(folderId);
if (!(await canRead(db, user, folderId))) throw AppError.notFound("Dossier introuvable.");
if (!limiter.allow(user.id)) {
throw AppError.unprocessable("Vous envoyez des messages trop rapidement.");
}
const parsed = sendInput.safeParse(await readJson(context));
if (!parsed.success) {
throw AppError.badRequest(parsed.error.issues[0]?.message ?? "Message invalide.");
}
const result = await db.exec(
"INSERT INTO chat_messages (folder_id, user_id, body) VALUES (?, ?, ?)",
[folderId, user.id, parsed.data.body],
);
const row = await db.required<MessageRow>(`${SELECT_MESSAGE} WHERE m.id = ?`, [result.insertId]);
return context.json({ message: publicMessage(row) }, 201);
});
app.patch(
"/api/cloud/folders/:folderId/chat/messages/:id",
requireAuth,
async (context) => {
const user = currentUser(context);
const folderId = context.req.param("folderId") ?? "";
const id = Number(context.req.param("id"));
await assertFolder(folderId);
if (!(await canRead(db, user, folderId))) throw AppError.notFound("Dossier introuvable.");
if (!Number.isSafeInteger(id) || id <= 0) throw AppError.notFound("Message introuvable.");
if (!limiter.allow(user.id)) {
throw AppError.unprocessable("Vous envoyez des messages trop rapidement.");
}
const parsed = editInput.safeParse(await readJson(context));
if (!parsed.success) {
throw AppError.badRequest(parsed.error.issues[0]?.message ?? "Message invalide.");
}
const result = await db.exec(
`UPDATE chat_messages
SET body = ?, edited_at = CURRENT_TIMESTAMP(3)
WHERE id = ? AND folder_id = ? AND user_id = ? AND deleted_at IS NULL`,
[parsed.data.body, id, folderId, user.id],
);
if (result.affectedRows === 0) throw AppError.notFound("Message introuvable.");
await audit(
db,
context,
user,
"chat.edit",
"message",
String(id),
{ folderId },
config.TRUST_PROXY,
);
const row = await db.required<MessageRow>(`${SELECT_MESSAGE} WHERE m.id = ?`, [id]);
return context.json({ message: publicMessage(row) });
},
);
app.put(
"/api/cloud/folders/:folderId/chat/messages/:id/pin",
requireAuth,
async (context) => {
const user = currentUser(context);
const folderId = context.req.param("folderId") ?? "";
const id = Number(context.req.param("id"));
await assertFolder(folderId);
if (!(await canRead(db, user, folderId))) throw AppError.notFound("Dossier introuvable.");
if (!Number.isSafeInteger(id) || id <= 0) throw AppError.notFound("Message introuvable.");
if (!limiter.allow(user.id)) {
throw AppError.unprocessable("Vous envoyez des messages trop rapidement.");
}
const result = await db.exec(
"UPDATE chat_messages SET is_pinned = 1 - is_pinned WHERE id = ? AND folder_id = ? AND deleted_at IS NULL",
[id, folderId],
);
if (result.affectedRows === 0) throw AppError.notFound("Message introuvable.");
const row = await db.required<{ is_pinned: number }>(
"SELECT is_pinned FROM chat_messages WHERE id = ?",
[id],
);
const pinned = row.is_pinned === 1;
await audit(
db,
context,
user,
pinned ? "chat.pin" : "chat.unpin",
"message",
String(id),
{ folderId },
config.TRUST_PROXY,
);
return context.json({ pinned });
},
);
app.get("/api/cloud/folders/:folderId/chat/pins", requireAuth, async (context) => {
const user = currentUser(context);
const folderId = context.req.param("folderId") ?? "";
await assertFolder(folderId);
if (!(await canRead(db, user, folderId))) throw AppError.notFound("Dossier introuvable.");
const rows = await db.query<MessageRow>(
`${SELECT_MESSAGE}
WHERE m.folder_id = ? AND m.is_pinned = 1 AND m.deleted_at IS NULL
ORDER BY m.id DESC
LIMIT 50`,
[folderId],
);
return context.json({ messages: rows.map(publicMessage) });
});
app.delete(
"/api/cloud/folders/:folderId/chat/messages/:id",
requireAuth,
async (context) => {
const user = currentUser(context);
const folderId = context.req.param("folderId") ?? "";
const id = Number(context.req.param("id"));
await assertFolder(folderId);
if (!(await canRead(db, user, folderId))) throw AppError.notFound("Dossier introuvable.");
if (!Number.isSafeInteger(id) || id <= 0) throw AppError.notFound("Message introuvable.");
const row = await db.one<{ user_id: string | null }>(
"SELECT user_id FROM chat_messages WHERE id = ? AND folder_id = ? AND deleted_at IS NULL",
[id, folderId],
);
if (!row || (row.user_id !== user.id && !(await canManageFolder(db, user, folderId)))) {
throw AppError.notFound("Message introuvable.");
}
await db.exec(
"UPDATE chat_messages SET deleted_at = CURRENT_TIMESTAMP(3), is_pinned = 0 WHERE id = ?",
[id],
);
await audit(db, context, user, "chat.delete", "message", String(id), { folderId }, config.TRUST_PROXY);
return context.json({ ok: true });
},
);
};
-162
View File
@@ -1,162 +0,0 @@
import { z } from "zod";
import type { Config } from "../config/appConfig.js";
import type { Db } from "../config/db.js";
import { currentUser, requireAuth } from "../middleware/auth.js";
import { audit } from "../services/auditService.js";
import {
deleteMessage,
editMessage,
members,
messages,
pins,
publicMessage,
sendMessage,
togglePin,
unreadCounts,
} from "../services/chatService.js";
import { AppError } from "../utils/errors.js";
import { readJson, type App } from "../utils/http.js";
import { createRateLimiter } from "../utils/ratelimit.js";
const sendInput = z.object({
body: z.string().trim().min(1, "Message vide.").max(2000, "Message trop long."),
});
const editInput = z.object({
body: z.string().trim().min(1, "Message vide.").max(2000, "Message trop long."),
});
export const registerChatRoutes = (app: App, db: Db, config: Config): void => {
const limiter = createRateLimiter(20, 10_000);
const assertRate = (user: { id: string }): void => {
if (!limiter.allow(user.id)) {
throw AppError.unprocessable("Vous envoyez des messages trop rapidement.");
}
};
app.get("/api/cloud/chat/unread", requireAuth, async (context) => {
const user = currentUser(context);
const unread = await unreadCounts(db, user);
return context.json({ unread });
});
app.get("/api/cloud/folders/:folderId/chat/members", requireAuth, async (context) => {
const user = currentUser(context);
const rows = await members(db, user, context.req.param("folderId") ?? "");
return context.json({
members: rows.map((row) => ({
id: row.id,
first_name: row.first_name,
last_name: row.last_name,
role_slug: row.role_slug,
has_avatar: row.avatar_updated_at !== null,
avatar_updated_at: row.avatar_updated_at,
last_login_at: row.last_login_at,
is_self: row.is_self,
})),
});
});
app.get("/api/cloud/folders/:folderId/chat/messages", requireAuth, async (context) => {
const user = currentUser(context);
const folderId = context.req.param("folderId") ?? "";
const limit = Math.min(200, Math.max(1, Number(context.req.query("limit")) || 50));
const after = Math.max(0, Number(context.req.query("after")) || 0);
const editedAfterRaw = context.req.query("editedAfter");
const editedAfter = typeof editedAfterRaw === "string" ? editedAfterRaw : null;
const result = await messages(db, user, folderId, { after, limit, editedAfter });
return context.json({ messages: result.messages.map(publicMessage), cursor: result.cursor });
});
app.post("/api/cloud/folders/:folderId/chat/messages", requireAuth, async (context) => {
const user = currentUser(context);
const folderId = context.req.param("folderId") ?? "";
assertRate(user);
const parsed = sendInput.safeParse(await readJson(context));
if (!parsed.success) {
throw AppError.badRequest(parsed.error.issues[0]?.message ?? "Message invalide.");
}
const message = await sendMessage(db, user, folderId, parsed.data.body);
return context.json({ message: publicMessage(message) }, 201);
});
app.patch(
"/api/cloud/folders/:folderId/chat/messages/:id",
requireAuth,
async (context) => {
const user = currentUser(context);
const folderId = context.req.param("folderId") ?? "";
const id = Number(context.req.param("id"));
if (!Number.isSafeInteger(id) || id <= 0) throw AppError.notFound("Message introuvable.");
assertRate(user);
const parsed = editInput.safeParse(await readJson(context));
if (!parsed.success) {
throw AppError.badRequest(parsed.error.issues[0]?.message ?? "Message invalide.");
}
const message = await editMessage(db, user, folderId, id, parsed.data.body);
await audit(
db,
context,
user,
"chat.edit",
"message",
String(id),
{ folderId },
config.TRUST_PROXY,
);
return context.json({ message: publicMessage(message) });
},
);
app.put(
"/api/cloud/folders/:folderId/chat/messages/:id/pin",
requireAuth,
async (context) => {
const user = currentUser(context);
const folderId = context.req.param("folderId") ?? "";
const id = Number(context.req.param("id"));
if (!Number.isSafeInteger(id) || id <= 0) throw AppError.notFound("Message introuvable.");
assertRate(user);
const pinned = await togglePin(db, user, folderId, id);
await audit(
db,
context,
user,
pinned ? "chat.pin" : "chat.unpin",
"message",
String(id),
{ folderId },
config.TRUST_PROXY,
);
return context.json({ pinned });
},
);
app.get("/api/cloud/folders/:folderId/chat/pins", requireAuth, async (context) => {
const user = currentUser(context);
const rows = await pins(db, user, context.req.param("folderId") ?? "");
return context.json({ messages: rows.map(publicMessage) });
});
app.delete(
"/api/cloud/folders/:folderId/chat/messages/:id",
requireAuth,
async (context) => {
const user = currentUser(context);
const folderId = context.req.param("folderId") ?? "";
const id = Number(context.req.param("id"));
if (!Number.isSafeInteger(id) || id <= 0) throw AppError.notFound("Message introuvable.");
await deleteMessage(db, user, folderId, id);
await audit(db, context, user, "chat.delete", "message", String(id), { folderId }, config.TRUST_PROXY);
return context.json({ ok: true });
},
);
};
+43
View File
@@ -0,0 +1,43 @@
import {
attachUser,
currentUser,
requireAuth,
type App,
type Config,
type Db,
} from "../lib/index.js";
export const registerDirectoryRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/directory", attachUser(db, config.SESSION_SECRET));
app.get("/api/cloud/directory", requireAuth, async (context) => {
const user = currentUser(context);
const rows = await db.query<{
id: string;
first_name: string;
last_name: string;
email: string;
avatar_updated_at: Date | null;
}>(
`SELECT u.id, u.first_name, u.last_name, u.email,
ua.updated_at AS avatar_updated_at
FROM users u
LEFT JOIN user_avatars ua ON ua.user_id = u.id
WHERE u.deleted_at IS NULL AND u.is_active = 1 AND u.id <> ?
ORDER BY u.first_name ASC, u.last_name ASC
LIMIT 1000`,
[user.id],
);
return context.json({
users: rows.map((row) => ({
id: row.id,
first_name: row.first_name,
last_name: row.last_name,
email: row.email,
has_avatar: row.avatar_updated_at !== null,
avatar_updated_at: row.avatar_updated_at,
})),
});
});
};
-15
View File
@@ -1,15 +0,0 @@
import type { Config } from "../config/appConfig.js";
import type { Db } from "../config/db.js";
import { attachUser, currentUser, requireAuth } from "../middleware/auth.js";
import { listUsers } from "../services/directoryService.js";
import type { App } from "../utils/http.js";
export const registerDirectoryRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/directory", attachUser(db, config.SESSION_SECRET));
app.get("/api/cloud/directory", requireAuth, async (context) => {
const user = currentUser(context);
const users = await listUsers(db, user);
return context.json({ users });
});
};
-327
View File
@@ -1,327 +0,0 @@
import { Readable } from "node:stream";
import { z } from "zod";
import type { Config } from "../config/appConfig.js";
import type { Db } from "../config/db.js";
import { attachUser, currentUser, requireAuth, requireRole } from "../middleware/auth.js";
import { audit } from "../services/auditService.js";
import {
deleteFile,
getFile,
listFavorites,
listFiles,
moveFile,
publicFile,
renameFile,
toggleStar,
uploadFile,
} from "../services/fileService.js";
import { thumbnailSize } from "../services/mediaService.js";
import { absolutePath, fileExists, openForDownload } from "../services/storageService.js";
import { AppError } from "../utils/errors.js";
import { readJson, type App } from "../utils/http.js";
import { assertName, mimeOf, parse, uuid } from "../utils/validators.js";
const renameInput = z.object({
name: z.string().trim().min(1).max(255),
});
const moveInput = z.object({
folderId: uuid.nullish(),
});
const contentDisposition = (name: string, inline = false): string => {
const ascii = name.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_");
const kind = inline ? "inline" : "attachment";
return `${kind}; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(name)}`;
};
const BYTE_RANGE = /^bytes=(\d*)-(\d*)$/;
const parseRange = (
header: string | undefined,
total: number,
): { start: number; end: number } | "invalid" | null => {
if (!header) return null;
const match = BYTE_RANGE.exec(header.trim());
if (!match) return null;
const [, rawStart, rawEnd] = match;
let start: number;
let end: number;
if (rawStart === "") {
const suffix = Number(rawEnd);
if (!Number.isInteger(suffix) || suffix <= 0) return "invalid";
start = Math.max(0, total - suffix);
end = total - 1;
} else {
start = Number(rawStart);
end = rawEnd === "" ? total - 1 : Number(rawEnd);
}
if (!Number.isInteger(start) || !Number.isInteger(end)) return "invalid";
if (start < 0 || start >= total) return "invalid";
if (end >= total) end = total - 1;
if (end < start) return "invalid";
return { start, end };
};
const isPreviewable = (mime: string): boolean => {
const value = mime.toLowerCase();
if (value === "image/svg+xml") return false;
return (
value.startsWith("image/") ||
value.startsWith("video/") ||
value.startsWith("audio/") ||
value === "application/pdf" ||
value === "text/plain"
);
};
interface ServeOptions {
absolute: string;
size: number;
mime: string;
disposition: string;
range: string | undefined;
}
const serveFile = ({ absolute, size, mime, disposition, range }: ServeOptions): Response => {
const headers: Record<string, string> = {
"content-type": mime,
"content-disposition": disposition,
"accept-ranges": "bytes",
"cache-control": "private, max-age=0, must-revalidate",
"x-content-type-options": "nosniff",
};
const parsed = parseRange(range, size);
if (parsed === "invalid") {
return new Response(null, {
status: 416,
headers: { ...headers, "content-range": `bytes */${size}` },
});
}
if (parsed) {
const stream = Readable.toWeb(openForDownload(absolute, parsed)) as ReadableStream<Uint8Array>;
return new Response(stream, {
status: 206,
headers: {
...headers,
"content-range": `bytes ${parsed.start}-${parsed.end}/${size}`,
"content-length": String(parsed.end - parsed.start + 1),
},
});
}
const stream = Readable.toWeb(openForDownload(absolute)) as ReadableStream<Uint8Array>;
return new Response(stream, { headers: { ...headers, "content-length": String(size) } });
};
export const registerFileRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/files/*", attachUser(db, config.SESSION_SECRET));
app.use("/api/cloud/files", attachUser(db, config.SESSION_SECRET));
app.put(
"/api/cloud/files",
requireAuth,
requireRole("admin", "user"),
async (context) => {
const user = currentUser(context);
const name = assertName(context.req.query("name"), "fichier");
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.");
}
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 created = await uploadFile(db, config, user, {
name,
folderId,
declared,
mimeType: mimeOf(context.req.header("content-type")),
body: context.req.raw.body,
});
await audit(
db,
context,
user,
"file.upload",
"file",
created.id,
{ name, size: created.size_bytes, folder_id: folderId },
config.TRUST_PROXY,
);
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.");
}
const files = await listFiles(db, user, folderId);
return context.json({ folderId, files: files.map(publicFile) });
});
app.get("/api/cloud/favorites", requireAuth, async (context) => {
const user = currentUser(context);
const files = await listFavorites(db, user);
return context.json({
files: files.map((row) => ({ ...publicFile(row), folder_name: row.folder_name })),
});
});
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 getFile(db, user, rawId);
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);
return serveFile({
absolute,
size: row.size_bytes,
mime: row.mime_type ?? "application/octet-stream",
disposition: contentDisposition(row.name),
range: context.req.header("range"),
});
});
app.get("/api/cloud/files/:id/preview", 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 getFile(db, user, rawId);
const mime = (row.mime_type ?? "").toLowerCase();
if (!isPreviewable(mime)) throw AppError.notFound("Apercu indisponible.");
const absolute = absolutePath(config.MEDIA_DIR, row.relative_path);
if (!(await fileExists(absolute))) throw AppError.notFound("Fichier introuvable sur le support.");
return serveFile({
absolute,
size: row.size_bytes,
mime: row.mime_type ?? "application/octet-stream",
disposition: contentDisposition(row.name, true),
range: context.req.header("range"),
});
});
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 getFile(db, user, rawId);
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",
},
});
});
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 { name: rawName } = parse(renameInput, await readJson(context));
const name = assertName(rawName, "fichier");
const updated = await renameFile(db, user, rawId, name);
await audit(db, context, user, "file.rename", "file", rawId, { name }, config.TRUST_PROXY);
return context.json({ file: publicFile(updated) });
});
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 { folderId } = parse(moveInput, await readJson(context));
const destination = folderId ?? null;
const updated = await moveFile(db, user, rawId, destination);
await audit(
db,
context,
user,
"file.move",
"file",
rawId,
{ folderId: destination },
config.TRUST_PROXY,
);
return context.json({ file: publicFile(updated) });
});
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 updated = await toggleStar(db, user, rawId);
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 deleteFile(db, user, rawId);
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 });
});
};
+667
View File
@@ -0,0 +1,667 @@
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,
readJson,
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;
};
export 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;
}
export const SELECT_FILE = `SELECT f.id, f.folder_id, f.name, f.mime_type, f.size_bytes, f.checksum_sha256,
f.relative_path, f.owner_id,
EXISTS (SELECT 1 FROM user_file_stars s WHERE s.file_id = f.id AND s.user_id = ?) AS is_starred,
f.download_count, f.created_at, f.updated_at
FROM files f`;
export 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,
});
export 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;
};
export const mimeOf = (header: string | undefined): string => {
const value = (header ?? "").split(";")[0]?.trim().toLowerCase() ?? "";
return MIME.test(value) ? value : "application/octet-stream";
};
const contentDisposition = (name: string, inline = false): string => {
const ascii = name.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_");
const kind = inline ? "inline" : "attachment";
return `${kind}; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(name)}`;
};
const BYTE_RANGE = /^bytes=(\d*)-(\d*)$/;
const parseRange = (
header: string | undefined,
total: number,
): { start: number; end: number } | "invalid" | null => {
if (!header) return null;
const match = BYTE_RANGE.exec(header.trim());
if (!match) return null;
const [, rawStart, rawEnd] = match;
let start: number;
let end: number;
if (rawStart === "") {
const suffix = Number(rawEnd);
if (!Number.isInteger(suffix) || suffix <= 0) return "invalid";
start = Math.max(0, total - suffix);
end = total - 1;
} else {
start = Number(rawStart);
end = rawEnd === "" ? total - 1 : Number(rawEnd);
}
if (!Number.isInteger(start) || !Number.isInteger(end)) return "invalid";
if (start < 0 || start >= total) return "invalid";
if (end >= total) end = total - 1;
if (end < start) return "invalid";
return { start, end };
};
const isPreviewable = (mime: string): boolean => {
const value = mime.toLowerCase();
if (value === "image/svg+xml") return false;
return (
value.startsWith("image/") ||
value.startsWith("video/") ||
value.startsWith("audio/") ||
value === "application/pdf" ||
value === "text/plain"
);
};
interface ServeOptions {
absolute: string;
size: number;
mime: string;
disposition: string;
range: string | undefined;
}
const serveFile = ({ absolute, size, mime, disposition, range }: ServeOptions): Response => {
const headers: Record<string, string> = {
"content-type": mime,
"content-disposition": disposition,
"accept-ranges": "bytes",
"cache-control": "private, max-age=0, must-revalidate",
"x-content-type-options": "nosniff",
};
const parsed = parseRange(range, size);
if (parsed === "invalid") {
return new Response(null, {
status: 416,
headers: { ...headers, "content-range": `bytes */${size}` },
});
}
if (parsed) {
const stream = Readable.toWeb(openForDownload(absolute, parsed)) as ReadableStream<Uint8Array>;
return new Response(stream, {
status: 206,
headers: {
...headers,
"content-range": `bytes ${parsed.start}-${parsed.end}/${size}`,
"content-length": String(parsed.end - parsed.start + 1),
},
});
}
const stream = Readable.toWeb(openForDownload(absolute)) as ReadableStream<Uint8Array>;
return new Response(stream, { headers: { ...headers, "content-length": String(size) } });
};
export const registerFileRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/files/*", attachUser(db, config.SESSION_SECRET));
app.use("/api/cloud/files", attachUser(db, config.SESSION_SECRET));
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();
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
AND ( folder_id IS NOT NULL OR owner_id = ? )
LIMIT 1`,
[folderId, name, user.id],
);
if (duplicate) throw AppError.conflict("Ce nom existe deja ici.");
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;
}
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;
}
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 f.id = ?`, [user.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.");
}
if (folderId !== null && !(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 f.deleted_at IS NULL
AND (f.folder_id <=> ?)
AND ( ? = 1
OR f.owner_id = ?
OR ( f.folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folders f2
WHERE f2.id = f.folder_id AND f2.access_type = 'public' ) )
OR ( f.folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folders f3
WHERE f3.id = f.folder_id
AND f3.owner_id = ? ) )
OR ( f.folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folder_permissions fp
WHERE fp.folder_id = f.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 is_starred DESC, f.name`,
[user.id, folderId, 0, user.id, user.id, user.id],
);
return context.json({ folderId, files: rows.map(publicFile) });
});
app.get("/api/cloud/favorites", requireAuth, async (context) => {
const user = currentUser(context);
const rows = await db.query<FileRow & { folder_name: string | null }>(
`SELECT fi.id, fi.folder_id, fi.name, fi.mime_type, fi.size_bytes, fi.checksum_sha256,
fi.relative_path, fi.owner_id, 1 AS is_starred, fi.download_count,
fi.created_at, fi.updated_at, fo.name AS folder_name
FROM files fi
JOIN user_file_stars ufs ON ufs.file_id = fi.id AND ufs.user_id = ?
LEFT JOIN folders fo ON fo.id = fi.folder_id
WHERE fi.deleted_at IS NULL
AND ( 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.deleted_at IS NULL
AND f.access_type = 'public' ) )
OR ( fi.folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folders f
WHERE f.id = fi.folder_id AND f.deleted_at IS NULL
AND f.owner_id = ? ) )
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 ufs.created_at DESC`,
[user.id, user.id, user.id, user.id],
);
return context.json({
files: rows.map((row) => ({ ...publicFile(row), folder_name: row.folder_name })),
});
});
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 f.id = ? AND f.deleted_at IS NULL`, [user.id, rawId]);
if (!row) throw AppError.notFound("Fichier introuvable.");
const allowed =
(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);
return serveFile({
absolute,
size: row.size_bytes,
mime: row.mime_type ?? "application/octet-stream",
disposition: contentDisposition(row.name),
range: context.req.header("range"),
});
});
app.get("/api/cloud/files/:id/preview", 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 f.id = ? AND f.deleted_at IS NULL`, [user.id, rawId]);
if (!row) throw AppError.notFound("Fichier introuvable.");
const allowed =
(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 mime = (row.mime_type ?? "").toLowerCase();
if (!isPreviewable(mime)) throw AppError.notFound("Apercu indisponible.");
const absolute = absolutePath(config.MEDIA_DIR, row.relative_path);
if (!(await fileExists(absolute))) throw AppError.notFound("Fichier introuvable sur le support.");
return serveFile({
absolute,
size: row.size_bytes,
mime: row.mime_type ?? "application/octet-stream",
disposition: contentDisposition(row.name, true),
range: context.req.header("range"),
});
});
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 f.id = ? AND f.deleted_at IS NULL`, [user.id, rawId]);
if (!row) throw AppError.notFound("Image introuvable.");
const allowed =
(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",
},
});
});
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 f.id = ? AND f.deleted_at IS NULL`, [user.id, rawId]);
if (!row) throw AppError.notFound("Fichier introuvable.");
const owner = row.owner_id !== null && row.owner_id === user.id;
const permitted =
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 readJson(context));
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 f.id = ?`, [user.id, row.id]);
await audit(db, context, user, "file.rename", "file", row.id, { name }, config.TRUST_PROXY);
return context.json({ file: publicFile(updated) });
});
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 f.id = ? AND f.deleted_at IS NULL`, [user.id, rawId]);
if (!row) throw AppError.notFound("Fichier introuvable.");
const owner = row.owner_id !== null && row.owner_id === user.id;
const canLeave =
owner ||
(row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id)));
if (!canLeave) throw AppError.notFound("Fichier introuvable.");
const { folderId } = parse(moveInput, await readJson(context));
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 f.id = ?`, [user.id, row.id]);
await audit(db, context, user, "file.move", "file", row.id, { folderId: destination }, config.TRUST_PROXY);
return context.json({ file: publicFile(updated) });
});
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 f.id = ? AND f.deleted_at IS NULL`, [user.id, rawId]);
if (!row) throw AppError.notFound("Fichier introuvable.");
const allowed =
(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 starred = await db.one(
"SELECT 1 AS mark FROM user_file_stars WHERE user_id = ? AND file_id = ?",
[user.id, row.id],
);
if (starred) {
await db.exec(
"DELETE FROM user_file_stars WHERE user_id = ? AND file_id = ?",
[user.id, row.id],
);
} else {
await db.exec(
"INSERT INTO user_file_stars (user_id, file_id) VALUES (?, ?)",
[user.id, row.id],
);
}
const updated = await db.required<FileRow>(`${SELECT_FILE} WHERE f.id = ?`, [user.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 f.id = ? AND f.deleted_at IS NULL`, [user.id, rawId]);
if (!row) throw AppError.notFound("Fichier introuvable.");
const owner = row.owner_id !== null && row.owner_id === user.id;
const permitted =
owner ||
(row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id)));
if (!permitted) throw AppError.notFound("Fichier introuvable.");
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 });
});
};
-164
View File
@@ -1,164 +0,0 @@
import { z } from "zod";
import type { Config } from "../config/appConfig.js";
import type { Db } from "../config/db.js";
import { attachUser, currentUser, requireAuth, requireRole } from "../middleware/auth.js";
import { audit } from "../services/auditService.js";
import {
createFolder,
deleteFolder,
grantPermission,
listFolders,
listPermissions,
moveFolder,
publicFolder,
renameFolder,
revokePermission,
} from "../services/folderService.js";
import { AppError } from "../utils/errors.js";
import { readJson, type App } from "../utils/http.js";
import { assertName, parse, uuid } from "../utils/validators.js";
const createFolderInput = z.object({
name: z.string().trim().min(1).max(255),
parentId: uuid.nullish(),
});
const updateFolderInput = z.object({
name: z.string().trim().min(1).max(255),
});
const moveFolderInput = 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(),
});
export const registerFolderRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/folders/*", attachUser(db, config.SESSION_SECRET));
app.use("/api/cloud/folders", attachUser(db, config.SESSION_SECRET));
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.");
}
const folders = await listFolders(db, user, parentId);
return context.json({ parentId, folders: folders.map(publicFolder) });
});
app.post(
"/api/cloud/folders",
requireAuth,
requireRole("admin", "user"),
async (context) => {
const user = currentUser(context);
const { name: rawName, parentId } = parse(createFolderInput, await readJson(context));
const name = assertName(rawName, "dossier");
const created = await createFolder(db, user, name, parentId ?? null);
await audit(db, context, user, "folder.create", "folder", created.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 data = parse(updateFolderInput, await readJson(context));
const name = assertName(data.name, "dossier");
const updated = await renameFolder(db, user, id, name);
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 { parentId } = parse(moveFolderInput, await readJson(context));
const updated = await moveFolder(db, user, id, parentId ?? null);
await audit(
db,
context,
user,
"folder.move",
"folder",
id,
{ parentId: parentId ?? null },
config.TRUST_PROXY,
);
return context.json({ folder: publicFolder(updated) });
});
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 removed = await deleteFolder(db, user, id);
await audit(db, context, user, "folder.delete", "folder", id, { name: removed.name }, config.TRUST_PROXY);
return context.json({ ok: true });
});
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.");
const permissions = await listPermissions(db, user, id);
return context.json({
permissions: permissions.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.");
const { email, level, expiresAt } = parse(permissionInput, await readJson(context));
const granted = await grantPermission(db, user, id, { email, level, expiresAt: expiresAt ?? null });
await audit(db, context, user, "folder.share", "folder", id, granted, 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.");
}
await revokePermission(db, user, id, userId);
await audit(db, context, user, "folder.unshare", "folder", id, { userId }, config.TRUST_PROXY);
return context.json({ ok: true });
});
};
+384
View File
@@ -0,0 +1,384 @@
import { randomUUID } from "node:crypto";
import { z } from "zod";
import {
AppError,
attachUser,
currentUser,
requireAuth,
requireRole,
readJson,
type App,
type Config,
type Db,
} from "../lib/index.js";
import { audit, canManageFolder, canTraverse, 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(),
});
const updateFolder = z.object({
name: z.string().trim().min(1).max(255),
});
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;
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.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,
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;
};
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, config.SESSION_SECRET));
app.use("/api/cloud/folders", attachUser(db, config.SESSION_SECRET));
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 (parentId !== null) {
if (!(await canTraverse(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 <=> ?)
ORDER BY f.name`,
[parentId],
);
const visible: FolderRow[] = [];
for (const row of rows) {
if (row.owner_id === user.id || (await canTraverse(db, user, row.id))) {
visible.push(row);
}
}
return context.json({ parentId, folders: visible.map(publicFolder) });
});
app.post(
"/api/cloud/folders",
requireAuth,
requireRole("admin", "user"),
async (context) => {
const user = currentUser(context);
const { name: rawName, parentId } = parse(
createFolder,
await readJson(context),
);
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
AND ( parent_id IS NOT NULL OR owner_id = ? )
LIMIT 1`,
[parentId ?? null, name, user.id],
);
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, owner_id, created_by)
VALUES (?, ?, ?, ?, ?, ?)`,
[id, locationId, parentId ?? null, name, 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 readJson(context));
const name = assertName(data.name);
try {
await db.exec("UPDATE folders SET name = ? WHERE id = ?", [name, 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 readJson(context));
if (parentId !== null && parentId !== undefined) {
if (!(await canWrite(db, user, parentId))) {
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier de destination.");
}
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) });
});
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 });
});
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 readJson(context),
);
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 });
});
};
+85
View File
@@ -0,0 +1,85 @@
import {
AppError,
attachUser,
currentUser,
requireAuth,
type App,
type Config,
type Db,
} from "../lib/index.js";
const KINDS = ["image", "video", "audio", "document", "archive", "other"] as const;
export const registerMediaRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/media", attachUser(db, config.SESSION_SECRET));
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,
(ufs.file_id IS NOT NULL) AS 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 user_file_stars ufs ON ufs.file_id = fi.id AND ufs.user_id = ?
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 folders f2
WHERE f2.id = fi.folder_id AND f2.owner_id = ? ) )
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}`,
[user.id, kind, kind, 0, user.id, 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,
})),
});
});
};
-23
View File
@@ -1,23 +0,0 @@
import type { Config } from "../config/appConfig.js";
import type { Db } from "../config/db.js";
import { attachUser, currentUser, requireAuth } from "../middleware/auth.js";
import { gallery, galleryKinds } from "../services/mediaService.js";
import { AppError } from "../utils/errors.js";
import type { App } from "../utils/http.js";
export const registerMediaRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/media", attachUser(db, config.SESSION_SECRET));
app.get("/api/cloud/media", requireAuth, async (context) => {
const user = currentUser(context);
const kind = context.req.query("kind") ?? "";
if (kind !== "" && !(galleryKinds 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 items = await gallery(db, user, kind, limit, offset);
return context.json({ kind: kind || null, items });
});
};
+108
View File
@@ -0,0 +1,108 @@
import {
AppError,
attachUser,
currentUser,
requireAuth,
type App,
type Config,
type Db,
} from "../lib/index.js";
const escapeLike = (value: string): string =>
value.replace(/[\\%_]/g, (match) => `\\${match}`);
const LIMIT = 100;
export const registerSearchRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/search", attachUser(db, config.SESSION_SECRET));
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 pattern = `%${escapeLike(q).slice(0, 110)}%`;
const folders = await db.query<{
id: string;
parent_id: string | null;
name: string;
owner_id: string | null;
access_type: string;
created_at: string;
updated_at: string;
}>(
`SELECT f.id, f.parent_id, f.name, 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, 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,
(ufs.file_id IS NOT NULL) AS is_starred, fi.created_at, fi.updated_at
FROM files fi
LEFT JOIN user_file_stars ufs ON ufs.file_id = fi.id AND ufs.user_id = ?
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 folders f2
WHERE f2.id = fi.folder_id AND f2.owner_id = ? ) )
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}`,
[user.id, pattern, 0, user.id, user.id, user.id],
);
return context.json({
query: q,
folders: folders.map((row) => ({
id: row.id,
parent_id: row.parent_id,
name: row.name,
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,
})),
});
});
};
-18
View File
@@ -1,18 +0,0 @@
import type { Config } from "../config/appConfig.js";
import type { Db } from "../config/db.js";
import { attachUser, currentUser, requireAuth } from "../middleware/auth.js";
import { search } from "../services/searchService.js";
import { AppError } from "../utils/errors.js";
import type { App } from "../utils/http.js";
export const registerSearchRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/search", attachUser(db, config.SESSION_SECRET));
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.");
return context.json(await search(db, user, q));
});
};
+364
View File
@@ -0,0 +1,364 @@
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.",
);
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);
};
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;
}
};
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,
);
const variants = await db.query<{ path: string }>(
`SELECT path FROM file_variants WHERE file_id IN (${placeholders})`,
fileIds,
);
await Promise.all([
...rows.map((row) => discard(absolutePath(config.MEDIA_DIR, row.relative_path))),
...variants.map((variant) => discard(absolutePath(config.VARIANT_DIR, variant.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);
});
};
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;
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,
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, config.SESSION_SECRET));
app.use("/api/cloud/trash", attachUser(db, config.SESSION_SECRET));
app.get("/api/cloud/trash", requireAuth, async (context) => {
const user = currentUser(context);
const folders = await db.query<TrashFolderRow>(
`SELECT f.id, f.parent_id, f.name, 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 f.owner_id = ?
ORDER BY f.deleted_at DESC`,
[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 fi.owner_id = ?
ORDER BY fi.deleted_at DESC`,
[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 (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 (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 (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 (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 });
});
app.delete("/api/cloud/trash", requireAuth, async (context) => {
const user = currentUser(context);
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.owner_id = ?`,
[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 fi.owner_id = ?`,
[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 });
});
};
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;
};
-90
View File
@@ -1,90 +0,0 @@
import type { Config } from "../config/appConfig.js";
import type { Db } from "../config/db.js";
import { attachUser, currentUser, requireAuth } from "../middleware/auth.js";
import { audit } from "../services/auditService.js";
import {
emptyTrash,
listTrash,
publicTrashFile,
publicTrashFolder,
purgeFile,
purgeFolder,
restoreFile,
restoreFolder,
} from "../services/trashService.js";
import { AppError } from "../utils/errors.js";
import type { App } from "../utils/http.js";
import { uuid } from "../utils/validators.js";
export const registerTrashRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/trash/*", attachUser(db, config.SESSION_SECRET));
app.use("/api/cloud/trash", attachUser(db, config.SESSION_SECRET));
app.get("/api/cloud/trash", requireAuth, async (context) => {
const user = currentUser(context);
const content = await listTrash(db, user);
return context.json({
retentionDays: content.retentionDays,
folders: content.folders.map(publicTrashFolder),
files: content.files.map(publicTrashFile),
});
});
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 restoreFolder(db, user, id);
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 restoreFile(db, user, id);
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 purgeFolder(db, config, user, 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 purgeFile(db, config, user, id);
await audit(db, context, user, "trash.purge", "file", id, { name: row.name }, config.TRUST_PROXY);
return context.json({ ok: true });
});
app.delete("/api/cloud/trash", requireAuth, async (context) => {
const user = currentUser(context);
const result = await emptyTrash(db, config, user);
await audit(
db,
context,
user,
"trash.empty",
"trash",
null,
{ folders: result.folders, files: result.files },
config.TRUST_PROXY,
);
return context.json({ ok: true, folders: result.folders, files: result.files });
});
};
-122
View File
@@ -1,122 +0,0 @@
import { z } from "zod";
import type { Config } from "../config/appConfig.js";
import type { Db } from "../config/db.js";
import { attachUser, currentUser, requireAuth, requireRole } from "../middleware/auth.js";
import { audit } from "../services/auditService.js";
import { publicFile } from "../services/fileService.js";
import {
cancelUpload,
completeUpload,
createUploadSession,
getUploadSession,
receiveChunk,
} from "../services/uploadService.js";
import { AppError } from "../utils/errors.js";
import { readJson, type App } from "../utils/http.js";
import { assertName, mimeOf, parse, uuid } from "../utils/validators.js";
const createInput = z.object({
name: z.string().trim().min(1).max(255),
folderId: uuid.nullish(),
size: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
mimeType: z.string().max(255).nullish(),
});
export const registerUploadRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/uploads/*", attachUser(db, config.SESSION_SECRET));
app.use("/api/cloud/uploads", attachUser(db, config.SESSION_SECRET));
app.post(
"/api/cloud/uploads",
requireAuth,
requireRole("admin", "user"),
async (context) => {
const user = currentUser(context);
const data = parse(createInput, await readJson(context));
const name = assertName(data.name, "fichier");
const folderId = data.folderId ?? null;
const upload = await createUploadSession(db, config, user, {
name,
folderId,
size: data.size,
mimeType: mimeOf(data.mimeType ?? undefined),
});
await audit(
db,
context,
user,
"file.upload.start",
"file",
upload.uploadId,
{ name, size: data.size, folder_id: folderId },
config.TRUST_PROXY,
);
return context.json({ upload }, 201);
},
);
app.get("/api/cloud/uploads/:id", requireAuth, async (context) => {
const user = currentUser(context);
const upload = await getUploadSession(db, user, context.req.param("id") ?? "");
return context.json({ upload });
});
app.put("/api/cloud/uploads/:id/chunks", requireAuth, async (context) => {
const user = currentUser(context);
const id = context.req.param("id") ?? "";
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 morceau invalide.");
}
const body = context.req.raw.body;
if (!body) throw AppError.badRequest("Corps de requete vide.");
const upload = await receiveChunk(db, user, id, body, declared);
return context.json({ upload });
});
app.post("/api/cloud/uploads/:id/complete", requireAuth, async (context) => {
const user = currentUser(context);
const id = context.req.param("id") ?? "";
const created = await completeUpload(db, config, user, id);
await audit(
db,
context,
user,
"file.upload",
"file",
created.id,
{ name: created.name, size: created.size_bytes, folder_id: created.folder_id },
config.TRUST_PROXY,
);
return context.json({ file: publicFile(created) }, 201);
});
app.delete("/api/cloud/uploads/:id", requireAuth, async (context) => {
const user = currentUser(context);
const row = await cancelUpload(db, user, context.req.param("id") ?? "");
await audit(
db,
context,
user,
"file.upload.cancel",
"file",
row.id,
{ name: row.name },
config.TRUST_PROXY,
);
return context.json({ ok: true });
});
};
+450
View File
@@ -0,0 +1,450 @@
import { randomUUID } from "node:crypto";
import { stat } from "node:fs/promises";
import path from "node:path";
import { z } from "zod";
import {
AppError,
attachUser,
currentUser,
requireAuth,
requireRole,
readJson,
type App,
type Config,
type Db,
} from "../lib/index.js";
import { audit, canWrite } from "../access.js";
import { indexMedia } from "../media.js";
import {
absolutePath,
chooseLocation,
discard,
diskUsage,
ensureDir,
fileExists,
hashFile,
listUploadTemps,
preallocateUpload,
publish,
relativePathFor,
uploadTempPath,
writeChunk,
} from "../storage.js";
import { SELECT_FILE, assertName, mimeOf, publicFile, type FileRow } from "./files.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.",
);
export const CHUNK_SIZE = 50 * 1024 * 1024;
const SESSION_TTL_MS = 24 * 60 * 60 * 1000;
const createInput = z.object({
name: z.string().trim().min(1).max(255),
folderId: uuid.nullish(),
size: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
mimeType: z.string().max(255).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 UploadSessionRow {
id: string;
user_id: string;
folder_id: string | null;
storage_location_id: number;
name: string;
mime_type: string | null;
size_bytes: number | string;
received_bytes: number | string;
chunk_size: number;
relative_path: string;
temp_path: string;
expires_at: string | Date;
}
const SELECT_SESSION = `SELECT id, user_id, folder_id, storage_location_id, name, mime_type,
size_bytes, received_bytes, chunk_size, relative_path, temp_path, expires_at
FROM upload_sessions`;
const sessionPublic = (row: UploadSessionRow) => ({
uploadId: row.id,
name: row.name,
folderId: row.folder_id,
size: Number(row.size_bytes),
chunkSize: row.chunk_size,
uploadedBytes: Number(row.received_bytes),
expiresAt: new Date(row.expires_at).toISOString(),
});
const dropSession = async (db: Db, row: UploadSessionRow): Promise<void> => {
await discard(row.temp_path);
await db.exec("DELETE FROM upload_sessions WHERE id = ?", [row.id]).catch(() => undefined);
};
const loadSession = async (
db: Db,
user: { id: string },
id: string,
): Promise<UploadSessionRow> => {
if (!uuid.safeParse(id).success) throw AppError.notFound("Session d'envoi introuvable.");
const row = await db.one<UploadSessionRow>(`${SELECT_SESSION} WHERE id = ? AND user_id = ?`, [
id,
user.id,
]);
if (!row) throw AppError.notFound("Session d'envoi introuvable.");
if (new Date(row.expires_at).getTime() <= Date.now()) {
await dropSession(db, row);
throw AppError.notFound("Session d'envoi expiree.");
}
return row;
};
const assertNameFree = async (
db: Db,
user: { id: string },
folderId: string | null,
name: string,
): Promise<void> => {
const duplicate = await db.one(
`SELECT 1 AS taken FROM files
WHERE folder_id <=> ? AND active_name = ? AND deleted_at IS NULL
AND ( folder_id IS NOT NULL OR owner_id = ? )
LIMIT 1`,
[folderId, name, user.id],
);
if (duplicate) throw AppError.conflict("Ce nom existe deja ici.");
};
export const registerUploadRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/uploads/*", attachUser(db, config.SESSION_SECRET));
app.use("/api/cloud/uploads", attachUser(db, config.SESSION_SECRET));
app.post(
"/api/cloud/uploads",
requireAuth,
requireRole("admin", "user"),
async (context) => {
const user = currentUser(context);
const data = parse(createInput, await readJson(context));
const name = assertName(data.name);
const folderId = data.folderId ?? null;
const size = data.size;
if (folderId !== null && !(await canWrite(db, user, folderId))) {
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier.");
}
const budget = await db.one<{
used_bytes: number | string;
quota_bytes: number | string;
max_file_bytes: number | string;
}>(
"SELECT used_bytes, quota_bytes, max_file_bytes FROM users WHERE id = ? AND deleted_at IS NULL",
[user.id],
);
if (!budget) throw AppError.unauthorized();
const pending = await db.one<{ bytes: number | string | null }>(
`SELECT COALESCE(SUM(size_bytes - received_bytes), 0) AS bytes
FROM upload_sessions
WHERE user_id = ? AND expires_at > UTC_TIMESTAMP()`,
[user.id],
);
if (BigInt(size) > BigInt(budget.max_file_bytes)) {
throw AppError.payloadTooLarge(
`Fichier trop volumineux (maximum ${budget.max_file_bytes} octets).`,
);
}
if (
BigInt(budget.used_bytes) + BigInt(pending?.bytes ?? 0) + BigInt(size) >
BigInt(budget.quota_bytes)
) {
throw AppError.payloadTooLarge("Votre quota de stockage est depasse.");
}
await assertNameFree(db, user, folderId, name);
const disk = await diskUsage(config.MEDIA_DIR);
if (disk !== null && BigInt(size) > BigInt(disk.available_bytes)) {
throw AppError.insufficientStorage(
"Espace disque insuffisant sur le serveur pour ce fichier.",
);
}
const location = await chooseLocation(db, BigInt(size));
const id = randomUUID();
const relative = relativePathFor(location.slug, id, name);
const temporary = uploadTempPath(config.MEDIA_DIR, id);
await preallocateUpload(temporary, size);
try {
await db.exec(
`INSERT INTO upload_sessions
(id, user_id, folder_id, storage_location_id, name, mime_type, size_bytes,
received_bytes, chunk_size, relative_path, temp_path, expires_at)
VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?)`,
[
id,
user.id,
folderId,
location.id,
name,
mimeOf(data.mimeType ?? undefined),
size,
CHUNK_SIZE,
relative,
temporary,
new Date(Date.now() + SESSION_TTL_MS),
],
);
} catch (error) {
await discard(temporary);
throw error;
}
const created = await db.required<UploadSessionRow>(`${SELECT_SESSION} WHERE id = ?`, [id]);
await audit(
db,
context,
user,
"file.upload.start",
"file",
id,
{ name, size, folder_id: folderId },
config.TRUST_PROXY,
);
return context.json({ upload: sessionPublic(created) }, 201);
},
);
app.get("/api/cloud/uploads/:id", requireAuth, async (context) => {
const user = currentUser(context);
const row = await loadSession(db, user, context.req.param("id") ?? "");
return context.json({ upload: sessionPublic(row) });
});
app.put("/api/cloud/uploads/:id/chunks", requireAuth, async (context) => {
const user = currentUser(context);
const row = await loadSession(db, user, context.req.param("id") ?? "");
const offset = Number(row.received_bytes);
const size = Number(row.size_bytes);
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 morceau invalide.");
}
if (declared > row.chunk_size) {
throw AppError.payloadTooLarge(`Morceau trop volumineux (maximum ${row.chunk_size} octets).`);
}
if (offset + declared > size) {
throw AppError.badRequest("Le morceau depasse la taille annoncee du fichier.");
}
const body = context.req.raw.body;
if (!body) throw AppError.badRequest("Corps de requete vide.");
const written = await writeChunk(row.temp_path, offset, body, declared);
if (written !== declared) {
throw AppError.badRequest(
`Longueur incoherente : ${declared} octets annonces, ${written} recus.`,
);
}
const reserved = await db.exec(
`UPDATE upload_sessions
SET received_bytes = received_bytes + ?
WHERE id = ? AND user_id = ? AND received_bytes = ?
AND received_bytes + ? <= size_bytes AND expires_at > UTC_TIMESTAMP()`,
[declared, row.id, user.id, offset, declared],
);
if (reserved.affectedRows === 0) {
const fresh = await db.one<UploadSessionRow>(
`${SELECT_SESSION} WHERE id = ? AND user_id = ?`,
[row.id, user.id],
);
if (!fresh) throw AppError.notFound("Session d'envoi introuvable.");
if (Number(fresh.received_bytes) < offset + declared) {
throw AppError.conflict("Morceau deja recu ou session modifiee. Reprenez depuis le statut.");
}
return context.json({ upload: sessionPublic(fresh) });
}
return context.json({ upload: sessionPublic({ ...row, received_bytes: offset + declared }) });
});
app.post("/api/cloud/uploads/:id/complete", requireAuth, async (context) => {
const user = currentUser(context);
const row = await loadSession(db, user, context.req.param("id") ?? "");
const size = Number(row.size_bytes);
const received = Number(row.received_bytes);
if (received !== size) {
throw AppError.badRequest("Envoi incomplet : des morceaux sont encore manquants.");
}
if (!(await fileExists(row.temp_path))) {
await dropSession(db, row);
throw AppError.notFound("Fichier temporaire introuvable. Relancez l'envoi.");
}
const budget = await db.one<{ max_file_bytes: number | string }>(
"SELECT max_file_bytes FROM users WHERE id = ? AND deleted_at IS NULL",
[user.id],
);
if (!budget) {
await dropSession(db, row);
throw AppError.unauthorized();
}
if (BigInt(size) > BigInt(budget.max_file_bytes)) {
await dropSession(db, row);
throw AppError.payloadTooLarge(
`Fichier trop volumineux (maximum ${budget.max_file_bytes} octets).`,
);
}
if (row.folder_id !== null && !(await canWrite(db, user, row.folder_id))) {
await dropSession(db, row);
throw AppError.forbidden("Vous ne pouvez plus ecrire dans ce dossier.");
}
try {
await assertNameFree(db, user, row.folder_id, row.name);
} catch (error) {
await dropSession(db, row);
throw error;
}
const checksum = await hashFile(row.temp_path);
const destination = absolutePath(config.MEDIA_DIR, row.relative_path);
await ensureDir(path.dirname(destination));
await publish(row.temp_path, 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`,
[size, user.id, size],
);
if ((quota as { affectedRows: number }).affectedRows === 0) {
throw AppError.payloadTooLarge("Votre quota de stockage est depasse.");
}
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)`,
[size, row.storage_location_id, size],
);
if ((support as { affectedRows: number }).affectedRows === 0) {
throw AppError.payloadTooLarge("L'espace disponible sur le support est insuffisant.");
}
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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
row.id,
row.storage_location_id,
row.folder_id,
row.name,
row.mime_type ?? "application/octet-stream",
size,
checksum,
row.relative_path,
user.id,
user.id,
],
);
await connection.execute("DELETE FROM upload_sessions WHERE id = ?", [row.id]);
});
} catch (error) {
await publish(destination, row.temp_path).catch(async () => {
await discard(destination);
await db.exec("DELETE FROM upload_sessions WHERE id = ?", [row.id]).catch(() => undefined);
});
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Ce nom existe deja ici.");
}
throw error;
}
await indexMedia(db, config, row.id, row.mime_type ?? "application/octet-stream", destination).catch(
() => undefined,
);
await audit(
db,
context,
user,
"file.upload",
"file",
row.id,
{ name: row.name, size, folder_id: row.folder_id },
config.TRUST_PROXY,
);
const created = await db.required<FileRow>(`${SELECT_FILE} WHERE f.id = ?`, [user.id, row.id]);
return context.json({ file: publicFile(created) }, 201);
});
app.delete("/api/cloud/uploads/:id", requireAuth, async (context) => {
const user = currentUser(context);
const row = await loadSession(db, user, context.req.param("id") ?? "");
await dropSession(db, row);
await audit(
db,
context,
user,
"file.upload.cancel",
"file",
row.id,
{ name: row.name },
config.TRUST_PROXY,
);
return context.json({ ok: true });
});
};
export const purgeExpiredUploads = async (db: Db, config: Config): Promise<number> => {
const expired = await db.query<UploadSessionRow>(
`${SELECT_SESSION} WHERE expires_at <= UTC_TIMESTAMP()`,
);
for (const row of expired) await discard(row.temp_path);
const result = await db.exec("DELETE FROM upload_sessions WHERE expires_at <= UTC_TIMESTAMP()");
const cutoff = Date.now() - SESSION_TTL_MS;
for (const temporary of await listUploadTemps(config.MEDIA_DIR)) {
const info = await stat(temporary).catch(() => null);
if (info !== null && info.mtimeMs < cutoff) await discard(temporary);
}
return result.affectedRows;
};
-373
View File
@@ -1,373 +0,0 @@
import { randomBytes, randomUUID } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import sharp from "sharp";
import type { Config } from "../config/appConfig.js";
import type { Db } from "../config/db.js";
import type { SessionUser } from "../models/types.js";
import { AppError } from "../utils/errors.js";
import { hashPassword, sessionTokenHash, sha256, verifyPassword } from "./authService.js";
import { branding, getMailer, link, renderMail } from "./mailService.js";
import { absolutePath, diskUsage, fileExists } from "./storageService.js";
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");
export const updateProfile = async (
db: Db,
user: SessionUser,
first_name: string,
last_name: string,
): Promise<{ first_name: string; last_name: string }> => {
await db.exec("UPDATE users SET first_name = ?, last_name = ? WHERE id = ?", [
first_name,
last_name,
user.id,
]);
return { first_name, last_name };
};
export const getPreferences = async (
db: Db,
user: SessionUser,
): Promise<{ theme: string; language: string }> => {
const row = await db.one<{ theme: string; language: string }>(
"SELECT theme, language FROM users WHERE id = ? AND deleted_at IS NULL",
[user.id],
);
if (!row) throw AppError.notFound("Compte introuvable.");
return { theme: row.theme, language: row.language };
};
export const updatePreferences = async (
db: Db,
user: SessionUser,
theme: string,
language: string,
): Promise<{ theme: string; language: string }> => {
await db.exec("UPDATE users SET theme = ?, language = ? WHERE id = ?", [
theme,
language,
user.id,
]);
return { theme, language };
};
export interface SessionInfo {
id: string;
ip_address: string | null;
user_agent: string | null;
created_at: string;
last_seen_at: string;
expires_at: string;
current: boolean;
}
/** Sessions actives de l'utilisateur, la session courante marquee. */
export const listSessions = async (
db: Db,
config: Config,
user: SessionUser,
currentToken: string,
): Promise<SessionInfo[]> => {
const current = sessionTokenHash(currentToken, config.SESSION_SECRET);
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 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,
}));
};
export const revokeSessionById = async (db: Db, user: SessionUser, id: string): Promise<void> => {
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.");
};
export const revokeOtherSessions = async (
db: Db,
config: Config,
user: SessionUser,
currentToken: string,
): Promise<void> => {
const current = sessionTokenHash(currentToken, config.SESSION_SECRET);
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],
);
};
/** Traite l'image recue (recadrage, webp) et met a jour l'avatar + le quota. */
export const uploadAvatar = async (
db: Db,
config: Config,
user: SessionUser,
source: Buffer,
): Promise<void> => {
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],
);
});
};
/** Chemin et taille de l'avatar d'un utilisateur (null si absent). */
export const getAvatar = async (
db: Db,
config: Config,
userId: string,
): Promise<{ absolute: string; size: number } | null> => {
const row = await db.one<{ original_path: string; size_bytes: number }>(
"SELECT original_path, size_bytes FROM user_avatars WHERE user_id = ?",
[userId],
);
if (!row) return null;
const absolute = absolutePath(config.VARIANT_DIR, row.original_path);
if (!(await fileExists(absolute))) return null;
return { absolute, size: row.size_bytes };
};
export const deleteAvatar = async (db: Db, user: SessionUser): Promise<void> => {
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],
);
});
};
/** Cree un jeton de reinitialisation et envoie le lien (silencieux si compte absent). */
export const forgotPassword = async (db: Db, config: Config, email: string): Promise<void> => {
const user = await db.one<{ id: string; email: string }>(
"SELECT id, email FROM users WHERE active_email = ? AND is_active = 1",
[email],
);
if (!user) return;
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(branding(config), {
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 getMailer(config)
.send({
to: user.email,
subject: "CoHaiSe Cloud — reinitialisation du mot de passe",
...mail,
})
.catch(() => undefined);
};
export interface ResetActor {
userId: string;
email: string;
first_name: string;
last_name: string;
}
/** Applique la reinitialisation du mot de passe. Renvoie l'acteur pour l'audit. */
export const resetPassword = async (
db: Db,
token: string,
password: string,
): Promise<ResetActor | null> => {
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(token)],
);
if (!row) throw AppError.badRequest("Lien invalide ou expire.");
const hash = await hashPassword(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) return null;
return {
userId: row.user_id,
email: account.email,
first_name: account.first_name,
last_name: account.last_name,
};
};
/** Demande un changement d'adresse : verifie le mot de passe puis envoie le lien. */
export const requestEmailChange = async (
db: Db,
config: Config,
user: SessionUser,
password: string,
newEmail: string,
): Promise<void> => {
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(password, row.password_hash))) {
throw AppError.unauthorized("Mot de passe incorrect.");
}
if (newEmail.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 = ?", [newEmail]);
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, newEmail, sha256(token), new Date(Date.now() + HOUR_MS)],
);
const url = link(config, `/confirm-email?token=${encodeURIComponent(token)}`);
const mail = renderMail(branding(config), {
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 getMailer(config)
.send({
to: newEmail,
subject: "CoHaiSe Cloud — confirmez votre nouvelle adresse",
text: mail.text,
html: mail.html,
})
.catch(() => undefined);
};
/** Confirme le changement d'adresse. Renvoie la nouvelle adresse. */
export const confirmEmailChange = async (db: Db, token: string): Promise<string> => {
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(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 row.new_email;
};
-494
View File
@@ -1,494 +0,0 @@
import { randomInt, randomUUID } from "node:crypto";
import type { Config } from "../config/appConfig.js";
import type { Db } from "../config/db.js";
import { AppError } from "../utils/errors.js";
import { hashPassword } from "./authService.js";
import { branding, getMailer, link, renderMail } from "./mailService.js";
import { diskUsage } from "./storageService.js";
export 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;
}
export 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"];
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]}`;
};
const generatePasswordValue = (): string => {
const alphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
let out = "";
for (let index = 0; index < 18; index += 1) out += alphabet[randomInt(alphabet.length)];
return out;
};
/** Reaffecte ou supprime les dossiers d'un compte supprime. */
const rehomeUserFolders = async (
db: Db,
userId: string,
): Promise<{ kept: number; deleted: number }> => {
const folders = await db.query<{ id: string; parent_id: string | null }>(
"SELECT id, parent_id FROM folders WHERE owner_id = ? AND deleted_at IS NULL AND is_system = 0",
[userId],
);
if (folders.length === 0) return { kept: 0, deleted: 0 };
const ids = folders.map((folder) => folder.id);
const placeholders = ids.map(() => "?").join(",");
const candidates = await db.query<{
folder_id: string;
user_id: string;
level: string;
created_at: string;
}>(
`SELECT fp.folder_id, fp.user_id, fp.level, fp.created_at
FROM folder_permissions fp
JOIN users u ON u.id = fp.user_id AND u.deleted_at IS NULL AND u.is_active = 1
WHERE fp.folder_id IN (${placeholders})
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() )
ORDER BY FIELD(fp.level, 'admin', 'write', 'read'), fp.created_at ASC`,
[...ids],
);
const newOwner = new Map<string, string>();
for (const row of candidates) {
if (!newOwner.has(row.folder_id)) newOwner.set(row.folder_id, row.user_id);
}
const owned = new Map(folders.map((folder) => [folder.id, folder.parent_id]));
const keepIds = [...newOwner.keys()];
const deleteIds = ids.filter((id) => !newOwner.has(id));
await db.transaction(async (connection) => {
for (const [id, owner] of newOwner) {
const parentId = owned.get(id) ?? null;
const parentGone = parentId !== null && owned.has(parentId) && !newOwner.has(parentId);
await connection.execute(
"UPDATE folders SET owner_id = ?, parent_id = ? WHERE id = ?",
[owner, parentGone ? null : parentId, id],
);
}
if (deleteIds.length > 0) {
const delPh = deleteIds.map(() => "?").join(",");
await connection.execute(
`UPDATE folders SET parent_id = NULL
WHERE parent_id IN (${delPh}) AND deleted_at IS NULL
AND owner_id <> ? AND id NOT IN (${keepIds.map(() => "?").join(",") || "''"})`,
[...deleteIds, userId, ...(keepIds.length > 0 ? keepIds : [])],
);
await connection.execute(
`UPDATE folders SET deleted_at = UTC_TIMESTAMP() WHERE id IN (${delPh}) AND deleted_at IS NULL`,
deleteIds,
);
await connection.execute(
`UPDATE files SET deleted_at = UTC_TIMESTAMP() WHERE folder_id IN (${delPh}) AND deleted_at IS NULL`,
deleteIds,
);
}
await connection.execute("DELETE FROM folder_permissions WHERE user_id = ?", [userId]);
await connection.execute("DELETE FROM user_file_stars WHERE user_id = ?", [userId]);
});
return { kept: keepIds.length, deleted: deleteIds.length };
};
const assertQuotaFits = async (config: Config, 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)}).`,
);
}
};
export const getStats = async (db: Db, config: Config) => {
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 {
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),
};
};
export const listUsers = async (db: Db, q: string): Promise<AdminUserRow[]> => {
const query = q.trim();
if (query) {
return 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}%`],
);
}
return db.query<AdminUserRow>(
`${SELECT_USER} WHERE u.deleted_at IS NULL ORDER BY u.email LIMIT 500`,
);
};
export interface CreateUserInput {
email: string;
first_name: string;
last_name: string;
role_slug: string;
quota_bytes?: number | null | undefined;
max_file_bytes?: number | null | undefined;
password?: string | null | undefined;
}
export const createUser = async (
db: Db,
config: Config,
data: CreateUserInput,
): Promise<AdminUserRow> => {
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(branding(config), {
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 getMailer(config)
.send({
to: data.email,
subject: "CoHaiSe Cloud — votre compte est pret",
text: mail.text,
html: mail.html,
})
.catch(() => undefined);
return created;
};
export interface UpdateUserInput {
first_name?: string | undefined;
last_name?: string | undefined;
role_slug?: string | undefined;
quota_bytes?: number | undefined;
max_file_bytes?: number | undefined;
is_active?: boolean | undefined;
}
export const updateUser = async (
db: Db,
actorId: string,
id: string,
data: UpdateUserInput,
): Promise<AdminUserRow> => {
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.");
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 === actorId) 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 === actorId) {
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],
);
}
}
return db.required<AdminUserRow>(`${SELECT_USER} WHERE u.id = ?`, [id]);
};
/** Supprime (logiquement) un compte et reattribue ses dossiers. */
export const deleteUser = async (
db: Db,
actorId: string,
id: string,
): Promise<{ kept: number; deleted: number }> => {
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.");
if (id === actorId) throw AppError.badRequest("Vous ne pouvez pas supprimer votre propre compte.");
const rehomed = await rehomeUserFolders(db, id);
await db.exec("UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ?", [id]);
return rehomed;
};
/** Reinitialise le mot de passe d'un compte et envoie les identifiants. */
export const resetUserPassword = async (db: Db, config: Config, id: string): Promise<void> => {
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],
);
const mail = renderMail(branding(config), {
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 getMailer(config)
.send({
to: user.email,
subject: "CoHaiSe Cloud — mot de passe reinitialise",
text: mail.text,
html: mail.html,
})
.catch(() => undefined);
};
export interface StorageLocationRow {
id: number;
name: string;
slug: string;
mount_path: string;
quota_bytes: number | null;
used_bytes: number;
is_active: number;
created_at: string;
}
export const listStorageLocations = async (db: Db, config: Config) => ({
locations: await db.query<StorageLocationRow>(
`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`,
),
disk: await diskUsage(config.MEDIA_DIR),
});
export const createStorageLocation = async (
db: Db,
config: Config,
data: { name: string; slug: string; mount_path: string; quota_bytes?: number | null | undefined },
): Promise<void> => {
if (data.quota_bytes !== undefined && data.quota_bytes !== null) {
await assertQuotaFits(config, 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;
}
};
export const updateStorageLocation = async (
db: Db,
config: Config,
id: number,
data: { name?: string | undefined; quota_bytes?: number | null | undefined; is_active?: boolean | undefined },
): Promise<void> => {
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(config, 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);
};
export const auditFilters = async (db: Db) => {
const actions = await db.query<{ action: string }>(
"SELECT DISTINCT action FROM audit_logs ORDER BY action ASC",
);
const users = await db.query<{ user_id: string; user_email: string | null }>(
`SELECT user_id, MAX(user_email) AS user_email
FROM audit_logs
WHERE user_id IS NOT NULL
GROUP BY user_id
ORDER BY user_email ASC`,
);
return {
actions: actions.map((row) => row.action),
users: users.map((row) => ({ id: row.user_id, email: row.user_email })),
};
};
export const auditEntries = async (
db: Db,
options: { limit: number; offset: number; action?: string | null; userId?: string | null },
) => {
const conditions: string[] = [];
const params: unknown[] = [];
if (options.action) {
conditions.push("action = ?");
params.push(options.action);
}
if (options.userId) {
conditions.push("user_id = ?");
params.push(options.userId);
}
const where = conditions.length > 0 ? ` WHERE ${conditions.join(" AND ")}` : "";
return db.query(
`SELECT id, user_id, user_email, action, resource, resource_id, details, ip_address, created_at
FROM audit_logs${where} ORDER BY created_at DESC LIMIT ${options.limit} OFFSET ${options.offset}`,
params,
);
};
-278
View File
@@ -1,278 +0,0 @@
import type { Db } from "../config/db.js";
import type { SessionUser } from "../models/types.js";
import { AppError } from "../utils/errors.js";
import { canManageFolder, canRead, READ_SQL } from "./auditService.js";
const DATETIME_CURSOR = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,6})?$/;
export interface MessageRow {
id: number;
user_id: string | null;
body: string;
created_at: string;
edited_at: string | null;
is_pinned: number;
first_name: string | null;
last_name: string | null;
avatar_updated_at: Date | null;
}
const SELECT_MESSAGE = `
SELECT m.id, m.user_id, m.body, m.created_at, m.edited_at, m.is_pinned,
u.first_name, u.last_name, ua.updated_at AS avatar_updated_at
FROM chat_messages m
LEFT JOIN users u ON u.id = m.user_id
LEFT JOIN user_avatars ua ON ua.user_id = m.user_id`;
export const publicMessage = (row: MessageRow) => ({
id: row.id,
user_id: row.user_id,
first_name: row.first_name,
last_name: row.last_name,
body: row.body,
created_at: row.created_at,
edited_at: row.edited_at,
is_pinned: row.is_pinned === 1,
has_avatar: row.user_id !== null && row.avatar_updated_at !== null,
avatar_updated_at: row.avatar_updated_at,
});
const assertFolder = async (
db: Db,
folderId: string,
): Promise<{ id: string; owner_id: string | null; access_type: string }> => {
const folder = await db.one<{ id: string; owner_id: string | null; access_type: string }>(
"SELECT id, owner_id, access_type FROM folders WHERE id = ? AND deleted_at IS NULL",
[folderId],
);
if (!folder) throw AppError.notFound("Dossier introuvable.");
return folder;
};
const assertReadableFolder = async (
db: Db,
user: SessionUser,
folderId: string,
): Promise<{ id: string; owner_id: string | null; access_type: string }> => {
const folder = await assertFolder(db, folderId);
if (!(await canRead(db, user, folderId))) throw AppError.notFound("Dossier introuvable.");
return folder;
};
const markRead = async (db: Db, folderId: string, userId: string, messageId: number): Promise<void> => {
if (messageId <= 0) return;
await db
.exec(
`INSERT INTO chat_reads (folder_id, user_id, last_read_message_id)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE
last_read_message_id = GREATEST(last_read_message_id, ?),
updated_at = UTC_TIMESTAMP(3)`,
[folderId, userId, messageId, messageId],
)
.catch(() => undefined);
};
/** Nombre de messages non lus par dossier. */
export const unreadCounts = async (db: Db, user: SessionUser): Promise<Record<string, number>> => {
const rows = await db.query<{ folder_id: string; unread: number }>(
`SELECT f.id AS folder_id, COUNT(m.id) AS unread
FROM folders f
JOIN chat_messages m
ON m.folder_id = f.id
AND m.deleted_at IS NULL
AND m.user_id <> ?
WHERE f.deleted_at IS NULL
AND m.id > COALESCE (
( SELECT cr.last_read_message_id
FROM chat_reads cr
WHERE cr.folder_id = f.id AND cr.user_id = ? ), 0 )
AND ${READ_SQL}
GROUP BY f.id
HAVING unread > 0`,
[user.id, user.id, user.id, user.id],
);
const unread: Record<string, number> = {};
for (const row of rows) unread[row.folder_id] = Number(row.unread);
return unread;
};
export interface ChatMember {
id: string;
first_name: string;
last_name: string;
role_slug: string;
avatar_updated_at: Date | null;
last_login_at: string | null;
is_self: boolean;
}
export const members = async (
db: Db,
user: SessionUser,
folderId: string,
): Promise<ChatMember[]> => {
const folder = await assertReadableFolder(db, user, folderId);
const rows = await db.query<Omit<ChatMember, "is_self">>(
`SELECT u.id, u.first_name, u.last_name, r.slug AS role_slug,
ua.updated_at AS avatar_updated_at, u.last_login_at
FROM users u
JOIN roles r ON r.id = u.role_id
LEFT JOIN user_avatars ua ON ua.user_id = u.id
WHERE u.deleted_at IS NULL AND u.is_active = 1
AND ( u.id = ?
OR ? = 1
OR EXISTS ( SELECT 1 FROM folder_permissions fp
WHERE fp.folder_id = ? AND fp.user_id = u.id
AND fp.level IN ('read', 'write', 'admin')
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )
ORDER BY u.first_name ASC, u.last_name ASC`,
[folder.owner_id, folder.access_type === "public" ? 1 : 0, folderId],
);
return rows.map((row) => ({ ...row, is_self: row.id === user.id }));
};
export const messages = async (
db: Db,
user: SessionUser,
folderId: string,
options: { after?: number; limit?: number; editedAfter?: string | null },
): Promise<{ messages: MessageRow[]; cursor: string }> => {
await assertReadableFolder(db, user, folderId);
const limit = Math.min(200, Math.max(1, options.limit ?? 50));
const after = Math.max(0, options.after ?? 0);
const cursorRow = await db.one<{ chat_cursor: string }>(
"SELECT DATE_FORMAT(CURRENT_TIMESTAMP(3), '%Y-%m-%dT%H:%i:%s.%f') AS chat_cursor",
);
const serverCursor = cursorRow?.chat_cursor ?? "1970-01-01T00:00:00.000000";
const editedAfterRaw = options.editedAfter;
const editedSince =
typeof editedAfterRaw === "string" && DATETIME_CURSOR.test(editedAfterRaw)
? editedAfterRaw
: serverCursor;
const rows =
after > 0
? await db.query<MessageRow>(
`${SELECT_MESSAGE}
WHERE m.folder_id = ? AND m.deleted_at IS NULL
AND ( m.id > ?
OR ( m.edited_at IS NOT NULL AND m.edited_at >= ? ) )
ORDER BY m.id ASC
LIMIT ${limit}`,
[folderId, after, editedSince],
)
: (
await db.query<MessageRow>(
`${SELECT_MESSAGE}
WHERE m.folder_id = ? AND m.deleted_at IS NULL
ORDER BY m.id DESC
LIMIT ${limit}`,
[folderId],
)
).reverse();
const newest = rows.reduce((max, row) => Math.max(max, row.id), 0);
await markRead(db, folderId, user.id, newest);
return { messages: rows, cursor: serverCursor };
};
export const sendMessage = async (
db: Db,
user: SessionUser,
folderId: string,
body: string,
): Promise<MessageRow> => {
await assertReadableFolder(db, user, folderId);
const result = await db.exec(
"INSERT INTO chat_messages (folder_id, user_id, body) VALUES (?, ?, ?)",
[folderId, user.id, body],
);
return db.required<MessageRow>(`${SELECT_MESSAGE} WHERE m.id = ?`, [result.insertId]);
};
export const editMessage = async (
db: Db,
user: SessionUser,
folderId: string,
id: number,
body: string,
): Promise<MessageRow> => {
await assertReadableFolder(db, user, folderId);
const result = await db.exec(
`UPDATE chat_messages
SET body = ?, edited_at = CURRENT_TIMESTAMP(3)
WHERE id = ? AND folder_id = ? AND user_id = ? AND deleted_at IS NULL`,
[body, id, folderId, user.id],
);
if (result.affectedRows === 0) throw AppError.notFound("Message introuvable.");
return db.required<MessageRow>(`${SELECT_MESSAGE} WHERE m.id = ?`, [id]);
};
export const togglePin = async (
db: Db,
user: SessionUser,
folderId: string,
id: number,
): Promise<boolean> => {
await assertReadableFolder(db, user, folderId);
const result = await db.exec(
"UPDATE chat_messages SET is_pinned = 1 - is_pinned WHERE id = ? AND folder_id = ? AND deleted_at IS NULL",
[id, folderId],
);
if (result.affectedRows === 0) throw AppError.notFound("Message introuvable.");
const row = await db.required<{ is_pinned: number }>(
"SELECT is_pinned FROM chat_messages WHERE id = ?",
[id],
);
return row.is_pinned === 1;
};
export const pins = async (
db: Db,
user: SessionUser,
folderId: string,
): Promise<MessageRow[]> => {
await assertReadableFolder(db, user, folderId);
return db.query<MessageRow>(
`${SELECT_MESSAGE}
WHERE m.folder_id = ? AND m.is_pinned = 1 AND m.deleted_at IS NULL
ORDER BY m.id DESC
LIMIT 50`,
[folderId],
);
};
export const deleteMessage = async (
db: Db,
user: SessionUser,
folderId: string,
id: number,
): Promise<void> => {
await assertReadableFolder(db, user, folderId);
const row = await db.one<{ user_id: string | null }>(
"SELECT user_id FROM chat_messages WHERE id = ? AND folder_id = ? AND deleted_at IS NULL",
[id, folderId],
);
if (!row || (row.user_id !== user.id && !(await canManageFolder(db, user, folderId)))) {
throw AppError.notFound("Message introuvable.");
}
await db.exec(
"UPDATE chat_messages SET deleted_at = CURRENT_TIMESTAMP(3), is_pinned = 0 WHERE id = ?",
[id],
);
};
-40
View File
@@ -1,40 +0,0 @@
import type { Db } from "../config/db.js";
import type { SessionUser } from "../models/types.js";
export interface DirectoryUser {
id: string;
first_name: string;
last_name: string;
email: string;
has_avatar: boolean;
avatar_updated_at: Date | null;
}
/** Annuaire des comptes actifs (hors soi-meme). */
export const listUsers = async (db: Db, user: SessionUser): Promise<DirectoryUser[]> => {
const rows = await db.query<{
id: string;
first_name: string;
last_name: string;
email: string;
avatar_updated_at: Date | null;
}>(
`SELECT u.id, u.first_name, u.last_name, u.email,
ua.updated_at AS avatar_updated_at
FROM users u
LEFT JOIN user_avatars ua ON ua.user_id = u.id
WHERE u.deleted_at IS NULL AND u.is_active = 1 AND u.id <> ?
ORDER BY u.first_name ASC, u.last_name ASC
LIMIT 1000`,
[user.id],
);
return rows.map((row) => ({
id: row.id,
first_name: row.first_name,
last_name: row.last_name,
email: row.email,
has_avatar: row.avatar_updated_at !== null,
avatar_updated_at: row.avatar_updated_at,
}));
};
-364
View File
@@ -1,364 +0,0 @@
import { randomUUID } from "node:crypto";
import path from "node:path";
import type { Config } from "../config/appConfig.js";
import type { Db } from "../config/db.js";
import type { FileRow, SessionUser } from "../models/types.js";
import { AppError } from "../utils/errors.js";
import { canRead, canWrite, canWriteExplicit } from "./auditService.js";
import { indexMedia } from "./mediaService.js";
import {
absolutePath,
chooseLocation,
discard,
diskUsage,
ensureDir,
publish,
relativePathFor,
temporaryPath,
writeBody,
} from "./storageService.js";
export const SELECT_FILE = `SELECT f.id, f.folder_id, f.name, f.mime_type, f.size_bytes, f.checksum_sha256,
f.relative_path, f.owner_id,
EXISTS (SELECT 1 FROM user_file_stars s WHERE s.file_id = f.id AND s.user_id = ?) AS is_starred,
f.download_count, f.created_at, f.updated_at
FROM files f`;
export 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,
});
export const assertNameFree = async (
db: Db,
user: { id: string },
folderId: string | null,
name: string,
): Promise<void> => {
const duplicate = await db.one(
`SELECT 1 AS taken FROM files
WHERE folder_id <=> ? AND active_name = ? AND deleted_at IS NULL
AND ( folder_id IS NOT NULL OR owner_id = ? )
LIMIT 1`,
[folderId, name, user.id],
);
if (duplicate) throw AppError.conflict("Ce nom existe deja ici.");
};
export interface UploadInput {
name: string;
folderId: string | null;
declared: number;
mimeType: string;
body: ReadableStream<Uint8Array> | null;
}
/** Envoi direct (petits fichiers) : controle, ecriture disque et enregistrement. */
export const uploadFile = async (
db: Db,
config: Config,
user: SessionUser,
input: UploadInput,
): Promise<FileRow> => {
const { name, folderId, declared, mimeType, body } = input;
if (folderId !== null) {
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 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();
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.");
}
await assertNameFree(db, user, folderId, name);
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));
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;
}
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,
mimeType,
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;
}
await indexMedia(db, config, id, mimeType, destination).catch(() => undefined);
return db.required<FileRow>(`${SELECT_FILE} WHERE f.id = ?`, [user.id, id]);
};
/** Liste les fichiers d'un dossier (ou de la racine). */
export const listFiles = async (
db: Db,
user: SessionUser,
folderId: string | null,
): Promise<FileRow[]> => {
if (folderId !== null && !(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.");
}
return db.query<FileRow>(
`${SELECT_FILE}
WHERE f.deleted_at IS NULL
AND (f.folder_id <=> ?)
AND ( ? = 1
OR f.owner_id = ?
OR ( f.folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folders f2
WHERE f2.id = f.folder_id AND f2.access_type = 'public' ) )
OR ( f.folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folders f3
WHERE f3.id = f.folder_id
AND f3.owner_id = ? ) )
OR ( f.folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folder_permissions fp
WHERE fp.folder_id = f.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 is_starred DESC, f.name`,
[user.id, folderId, 0, user.id, user.id, user.id],
);
};
/** Liste les fichiers etoiles de l'utilisateur. */
export const listFavorites = async (
db: Db,
user: SessionUser,
): Promise<(FileRow & { folder_name: string | null })[]> =>
db.query<FileRow & { folder_name: string | null }>(
`SELECT fi.id, fi.folder_id, fi.name, fi.mime_type, fi.size_bytes, fi.checksum_sha256,
fi.relative_path, fi.owner_id, 1 AS is_starred, fi.download_count,
fi.created_at, fi.updated_at, fo.name AS folder_name
FROM files fi
JOIN user_file_stars ufs ON ufs.file_id = fi.id AND ufs.user_id = ?
LEFT JOIN folders fo ON fo.id = fi.folder_id
WHERE fi.deleted_at IS NULL
AND ( 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.deleted_at IS NULL
AND f.access_type = 'public' ) )
OR ( fi.folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folders f
WHERE f.id = fi.folder_id AND f.deleted_at IS NULL
AND f.owner_id = ? ) )
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 ufs.created_at DESC`,
[user.id, user.id, user.id, user.id],
);
/** Charge un fichier en verifiant la lisibilite (ou la gestion) de l'utilisateur. */
export const getFile = async (
db: Db,
user: SessionUser,
id: string,
options: { manage?: boolean } = {},
): Promise<FileRow> => {
const row = await db.one<FileRow>(`${SELECT_FILE} WHERE f.id = ? AND f.deleted_at IS NULL`, [
user.id,
id,
]);
if (!row) throw AppError.notFound("Fichier introuvable.");
if (options.manage) {
const owner = row.owner_id !== null && row.owner_id === user.id;
const permitted =
owner || (row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id)));
if (!permitted) throw AppError.notFound("Fichier introuvable.");
return row;
}
const allowed =
(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.");
return row;
};
export const renameFile = async (
db: Db,
user: SessionUser,
id: string,
name: string,
): Promise<FileRow> => {
const row = await getFile(db, user, id, { manage: true });
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;
}
return db.required<FileRow>(`${SELECT_FILE} WHERE f.id = ?`, [user.id, row.id]);
};
export const moveFile = async (
db: Db,
user: SessionUser,
id: string,
folderId: string | null,
): Promise<FileRow> => {
const row = await getFile(db, user, id, { manage: true });
if (folderId !== null && !(await canWrite(db, user, folderId))) {
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier.");
}
try {
await db.exec("UPDATE files SET folder_id = ? WHERE id = ?", [folderId, 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;
}
return db.required<FileRow>(`${SELECT_FILE} WHERE f.id = ?`, [user.id, row.id]);
};
export const toggleStar = async (db: Db, user: SessionUser, id: string): Promise<FileRow> => {
const row = await getFile(db, user, id);
const starred = await db.one(
"SELECT 1 AS mark FROM user_file_stars WHERE user_id = ? AND file_id = ?",
[user.id, row.id],
);
if (starred) {
await db.exec("DELETE FROM user_file_stars WHERE user_id = ? AND file_id = ?", [
user.id,
row.id,
]);
} else {
await db.exec("INSERT INTO user_file_stars (user_id, file_id) VALUES (?, ?)", [
user.id,
row.id,
]);
}
return db.required<FileRow>(`${SELECT_FILE} WHERE f.id = ?`, [user.id, row.id]);
};
/** Deplace le fichier vers la corbeille (suppression logique). */
export const deleteFile = async (db: Db, user: SessionUser, id: string): Promise<FileRow> => {
const row = await getFile(db, user, id, { manage: true });
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.");
return row;
};
-290
View File
@@ -1,290 +0,0 @@
import { randomUUID } from "node:crypto";
import type { Db } from "../config/db.js";
import type { SessionUser } from "../models/types.js";
import { AppError } from "../utils/errors.js";
import { canManageFolder, canTraverse, canWrite } from "./auditService.js";
export interface FolderRow {
id: string;
parent_id: string | null;
name: string;
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.owner_id,
f.access_type, f.is_system, f.storage_location_id, f.created_at, f.updated_at
FROM folders f`;
export const publicFolder = (row: FolderRow) => ({
id: row.id,
parent_id: row.parent_id,
name: row.name,
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 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);
};
/** Liste les dossiers visibles sous un parent (racine si null). */
export const listFolders = async (
db: Db,
user: SessionUser,
parentId: string | null,
): Promise<FolderRow[]> => {
if (parentId !== null && !(await canTraverse(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 <=> ?)
ORDER BY f.name`,
[parentId],
);
const visible: FolderRow[] = [];
for (const row of rows) {
if (row.owner_id === user.id || (await canTraverse(db, user, row.id))) {
visible.push(row);
}
}
return visible;
};
export const createFolder = async (
db: Db,
user: SessionUser,
name: string,
parentId: string | null,
): Promise<FolderRow> => {
if (parentId && !(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
AND ( parent_id IS NOT NULL OR owner_id = ? )
LIMIT 1`,
[parentId ?? null, name, user.id],
);
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, owner_id, created_by)
VALUES (?, ?, ?, ?, ?, ?)`,
[id, locationId, parentId ?? null, name, user.id, user.id],
);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Ce nom existe deja ici.");
}
throw error;
}
return db.required<FolderRow>(`${SELECT_FOLDER} WHERE f.id = ?`, [id]);
};
export const renameFolder = async (
db: Db,
user: SessionUser,
id: string,
name: string,
): Promise<FolderRow> => {
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.");
try {
await db.exec("UPDATE folders SET name = ? WHERE id = ?", [name, id]);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Ce nom existe deja ici.");
}
throw error;
}
return db.required<FolderRow>(`${SELECT_FOLDER} WHERE f.id = ?`, [id]);
};
export const moveFolder = async (
db: Db,
user: SessionUser,
id: string,
parentId: string | null,
): Promise<FolderRow> => {
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.");
if (parentId !== null) {
if (!(await canWrite(db, user, parentId))) {
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier de destination.");
}
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, id]);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Ce nom existe deja dans la destination.");
}
throw error;
}
return db.required<FolderRow>(`${SELECT_FOLDER} WHERE f.id = ?`, [id]);
};
/** Deplace le dossier et son arborescence vers la corbeille. */
export const deleteFolder = async (
db: Db,
user: SessionUser,
id: string,
): Promise<FolderRow> => {
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,
);
});
return existing;
};
export interface FolderPermissionRow {
user_id: string;
email: string;
first_name: string;
last_name: string;
level: string;
expires_at: string | null;
created_at: string;
}
export const listPermissions = async (
db: Db,
user: SessionUser,
id: string,
): Promise<FolderPermissionRow[]> => {
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
const rows = await db.query<FolderPermissionRow>(
`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 rows;
};
export const grantPermission = async (
db: Db,
user: SessionUser,
id: string,
input: { email: string; level: string; expiresAt: string | null },
): Promise<{ email: string; level: string }> => {
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
const target = await db.one<{ id: string }>(
"SELECT id FROM users WHERE active_email = ? AND deleted_at IS NULL",
[input.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 = input.expiresAt ? new Date(input.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, input.level, expires, user.id],
);
return { email: input.email, level: input.level };
};
export const revokePermission = async (
db: Db,
user: SessionUser,
id: string,
userId: string,
): Promise<void> => {
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.");
};
-111
View File
@@ -1,111 +0,0 @@
import type { Db } from "../config/db.js";
import type { SessionUser } from "../models/types.js";
const escapeLike = (value: string): string =>
value.replace(/[\\%_]/g, (match) => `\\${match}`);
const LIMIT = 100;
export interface SearchResult {
query: string;
folders: {
id: string;
parent_id: string | null;
name: string;
owner_id: string | null;
access_type: string;
created_at: string;
updated_at: string;
}[];
files: {
id: string;
folder_id: string | null;
name: string;
mime_type: string | null;
size_bytes: number;
owner_id: string | null;
is_starred: boolean;
created_at: string;
updated_at: string;
}[];
}
/** Recherche globale dans les dossiers et fichiers visibles. */
export const search = async (db: Db, user: SessionUser, q: string): Promise<SearchResult> => {
const pattern = `%${escapeLike(q).slice(0, 110)}%`;
const folders = await db.query<SearchResult["folders"][number]>(
`SELECT f.id, f.parent_id, f.name, 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, 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,
(ufs.file_id IS NOT NULL) AS is_starred, fi.created_at, fi.updated_at
FROM files fi
LEFT JOIN user_file_stars ufs ON ufs.file_id = fi.id AND ufs.user_id = ?
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 folders f2
WHERE f2.id = fi.folder_id AND f2.owner_id = ? ) )
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}`,
[user.id, pattern, 0, user.id, user.id, user.id],
);
return {
query: q,
folders: folders.map((row) => ({
id: row.id,
parent_id: row.parent_id,
name: row.name,
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,
})),
};
};
-337
View File
@@ -1,337 +0,0 @@
import type { Config } from "../config/appConfig.js";
import type { Db } from "../config/db.js";
import type { SessionUser } from "../models/types.js";
import { AppError } from "../utils/errors.js";
import { absolutePath, discard } from "./storageService.js";
export 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;
}
export interface TrashFolderRow {
id: string;
parent_id: string | null;
name: string;
owner_id: string | null;
access_type: string;
created_at: string;
updated_at: string;
deleted_at: string;
}
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);
};
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;
}
};
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,
);
const variants = await db.query<{ path: string }>(
`SELECT path FROM file_variants WHERE file_id IN (${placeholders})`,
fileIds,
);
await Promise.all([
...rows.map((row) => discard(absolutePath(config.MEDIA_DIR, row.relative_path))),
...variants.map((variant) => discard(absolutePath(config.VARIANT_DIR, variant.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);
});
};
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);
};
export const publicTrashFolder = (row: TrashFolderRow) => ({
id: row.id,
parent_id: row.parent_id,
name: row.name,
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 publicTrashFile = (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,
});
export interface TrashContent {
retentionDays: number;
folders: TrashFolderRow[];
files: TrashFileRow[];
}
/** Contenu de la corbeille de l'utilisateur. */
export const listTrash = async (db: Db, user: SessionUser): Promise<TrashContent> => {
const folders = await db.query<TrashFolderRow>(
`SELECT f.id, f.parent_id, f.name, 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 f.owner_id = ?
ORDER BY f.deleted_at DESC`,
[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 fi.owner_id = ?
ORDER BY fi.deleted_at DESC`,
[user.id],
);
const retentionDays = await db.one<{ setting_value: string }>(
"SELECT setting_value FROM settings WHERE setting_key = 'trash_retention_days'",
);
return {
retentionDays: retentionDays ? Number(retentionDays.setting_value) : 30,
folders,
files,
};
};
export const restoreFolder = async (
db: Db,
user: SessionUser,
id: string,
): Promise<TrashFolderRow> => {
const row = await db.one<TrashFolderRow>(
`SELECT id, parent_id, name, owner_id, access_type, created_at, updated_at, deleted_at
FROM folders
WHERE id = ? AND deleted_at IS NOT NULL AND is_system = 0`,
[id],
);
if (!row || 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;
}
return row;
};
export const restoreFile = async (
db: Db,
user: SessionUser,
id: string,
): Promise<TrashFileRow> => {
const row = await db.one<TrashFileRow>(
`SELECT id, folder_id, name, mime_type, size_bytes, owner_id, created_at, updated_at, deleted_at
FROM files WHERE id = ? AND deleted_at IS NOT NULL`,
[id],
);
if (!row || 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;
}
return row;
};
/** Suppression definitive d'un dossier corbeille et de son arborescence. */
export const purgeFolder = async (
db: Db,
config: Config,
user: SessionUser,
id: string,
): Promise<TrashFolderRow> => {
const row = await db.one<TrashFolderRow>(
`SELECT id, parent_id, name, owner_id, access_type, created_at, updated_at, deleted_at
FROM folders
WHERE id = ? AND deleted_at IS NOT NULL AND is_system = 0`,
[id],
);
if (!row || row.owner_id !== user.id) throw AppError.notFound("Dossier introuvable.");
await purgeFolderTree(db, config, id);
return row;
};
/** Suppression definitive d'un fichier corbeille. */
export const purgeFile = async (
db: Db,
config: Config,
user: SessionUser,
id: string,
): Promise<TrashFileRow> => {
const row = await db.one<TrashFileRow>(
`SELECT id, folder_id, name, mime_type, size_bytes, owner_id, created_at, updated_at, deleted_at
FROM files WHERE id = ? AND deleted_at IS NOT NULL`,
[id],
);
if (!row || row.owner_id !== user.id) throw AppError.notFound("Fichier introuvable.");
await purgeFiles(db, config, [id]);
return row;
};
/** Vide la corbeille de l'utilisateur. */
export const emptyTrash = async (
db: Db,
config: Config,
user: SessionUser,
): Promise<{ folders: number; files: number }> => {
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.owner_id = ?`,
[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 fi.owner_id = ?`,
[user.id],
);
for (const folder of folders) await purgeFolderTree(db, config, folder.id);
await purgeFiles(db, config, files.map((row) => row.id));
return { folders: folders.length, files: files.length };
};
/** Purge automatique des elements expirant (retention configurable). */
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;
};
-376
View File
@@ -1,376 +0,0 @@
import { randomUUID } from "node:crypto";
import { stat } from "node:fs/promises";
import path from "node:path";
import type { Config } from "../config/appConfig.js";
import type { Db } from "../config/db.js";
import type { FileRow, SessionUser } from "../models/types.js";
import { AppError } from "../utils/errors.js";
import { canWrite } from "./auditService.js";
import { indexMedia } from "./mediaService.js";
import { assertNameFree, SELECT_FILE } from "./fileService.js";
import {
absolutePath,
chooseLocation,
discard,
diskUsage,
ensureDir,
fileExists,
hashFile,
listUploadTemps,
preallocateUpload,
publish,
relativePathFor,
uploadTempPath,
writeChunk,
} from "./storageService.js";
export const CHUNK_SIZE = 50 * 1024 * 1024;
const SESSION_TTL_MS = 24 * 60 * 60 * 1000;
interface UploadSessionRow {
id: string;
user_id: string;
folder_id: string | null;
storage_location_id: number;
name: string;
mime_type: string | null;
size_bytes: number | string;
received_bytes: number | string;
chunk_size: number;
relative_path: string;
temp_path: string;
expires_at: string | Date;
}
const SELECT_SESSION = `SELECT id, user_id, folder_id, storage_location_id, name, mime_type,
size_bytes, received_bytes, chunk_size, relative_path, temp_path, expires_at
FROM upload_sessions`;
export const sessionPublic = (row: UploadSessionRow) => ({
uploadId: row.id,
name: row.name,
folderId: row.folder_id,
size: Number(row.size_bytes),
chunkSize: row.chunk_size,
uploadedBytes: Number(row.received_bytes),
expiresAt: new Date(row.expires_at).toISOString(),
});
export type UploadSession = ReturnType<typeof sessionPublic>;
const dropSession = async (db: Db, row: UploadSessionRow): Promise<void> => {
await discard(row.temp_path);
await db.exec("DELETE FROM upload_sessions WHERE id = ?", [row.id]).catch(() => undefined);
};
const loadSession = async (
db: Db,
user: { id: string },
id: string,
): Promise<UploadSessionRow> => {
const row = await db.one<UploadSessionRow>(`${SELECT_SESSION} WHERE id = ? AND user_id = ?`, [
id,
user.id,
]);
if (!row) throw AppError.notFound("Session d'envoi introuvable.");
if (new Date(row.expires_at).getTime() <= Date.now()) {
await dropSession(db, row);
throw AppError.notFound("Session d'envoi expiree.");
}
return row;
};
export interface CreateUploadInput {
name: string;
folderId: string | null;
size: number;
mimeType: string;
}
/** Cree une session d'envoi morcele avec preallocation du fichier temporaire. */
export const createUploadSession = async (
db: Db,
config: Config,
user: SessionUser,
input: CreateUploadInput,
): Promise<UploadSession> => {
const { name, folderId, size, mimeType } = input;
if (folderId !== null && !(await canWrite(db, user, folderId))) {
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier.");
}
const budget = await db.one<{
used_bytes: number | string;
quota_bytes: number | string;
max_file_bytes: number | string;
}>(
"SELECT used_bytes, quota_bytes, max_file_bytes FROM users WHERE id = ? AND deleted_at IS NULL",
[user.id],
);
if (!budget) throw AppError.unauthorized();
const pending = await db.one<{ bytes: number | string | null }>(
`SELECT COALESCE(SUM(size_bytes - received_bytes), 0) AS bytes
FROM upload_sessions
WHERE user_id = ? AND expires_at > UTC_TIMESTAMP()`,
[user.id],
);
if (BigInt(size) > BigInt(budget.max_file_bytes)) {
throw AppError.payloadTooLarge(
`Fichier trop volumineux (maximum ${budget.max_file_bytes} octets).`,
);
}
if (
BigInt(budget.used_bytes) + BigInt(pending?.bytes ?? 0) + BigInt(size) >
BigInt(budget.quota_bytes)
) {
throw AppError.payloadTooLarge("Votre quota de stockage est depasse.");
}
await assertNameFree(db, user, folderId, name);
const disk = await diskUsage(config.MEDIA_DIR);
if (disk !== null && BigInt(size) > BigInt(disk.available_bytes)) {
throw AppError.insufficientStorage(
"Espace disque insuffisant sur le serveur pour ce fichier.",
);
}
const location = await chooseLocation(db, BigInt(size));
const id = randomUUID();
const relative = relativePathFor(location.slug, id, name);
const temporary = uploadTempPath(config.MEDIA_DIR, id);
await preallocateUpload(temporary, size);
try {
await db.exec(
`INSERT INTO upload_sessions
(id, user_id, folder_id, storage_location_id, name, mime_type, size_bytes,
received_bytes, chunk_size, relative_path, temp_path, expires_at)
VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?)`,
[
id,
user.id,
folderId,
location.id,
name,
mimeType,
size,
CHUNK_SIZE,
relative,
temporary,
new Date(Date.now() + SESSION_TTL_MS),
],
);
} catch (error) {
await discard(temporary);
throw error;
}
const created = await db.required<UploadSessionRow>(`${SELECT_SESSION} WHERE id = ?`, [id]);
return sessionPublic(created);
};
export const getUploadSession = async (
db: Db,
user: SessionUser,
id: string,
): Promise<UploadSession> => {
const row = await loadSession(db, user, id);
return sessionPublic(row);
};
/** Ecrit un morceau a l'offset attendu et met a jour la progression. */
export const receiveChunk = async (
db: Db,
user: SessionUser,
id: string,
body: ReadableStream<Uint8Array>,
declared: number,
): Promise<UploadSession> => {
const row = await loadSession(db, user, id);
const offset = Number(row.received_bytes);
const size = Number(row.size_bytes);
if (declared > row.chunk_size) {
throw AppError.payloadTooLarge(`Morceau trop volumineux (maximum ${row.chunk_size} octets).`);
}
if (offset + declared > size) {
throw AppError.badRequest("Le morceau depasse la taille annoncee du fichier.");
}
const written = await writeChunk(row.temp_path, offset, body, declared);
if (written !== declared) {
throw AppError.badRequest(
`Longueur incoherente : ${declared} octets annonces, ${written} recus.`,
);
}
const reserved = await db.exec(
`UPDATE upload_sessions
SET received_bytes = received_bytes + ?
WHERE id = ? AND user_id = ? AND received_bytes = ?
AND received_bytes + ? <= size_bytes AND expires_at > UTC_TIMESTAMP()`,
[declared, row.id, user.id, offset, declared],
);
if (reserved.affectedRows === 0) {
const fresh = await db.one<UploadSessionRow>(
`${SELECT_SESSION} WHERE id = ? AND user_id = ?`,
[row.id, user.id],
);
if (!fresh) throw AppError.notFound("Session d'envoi introuvable.");
if (Number(fresh.received_bytes) < offset + declared) {
throw AppError.conflict("Morceau deja recu ou session modifiee. Reprenez depuis le statut.");
}
return sessionPublic(fresh);
}
return sessionPublic({ ...row, received_bytes: offset + declared });
};
/** Finalise l'envoi : controle, publication et enregistrement du fichier. */
export const completeUpload = async (
db: Db,
config: Config,
user: SessionUser,
id: string,
): Promise<FileRow> => {
const row = await loadSession(db, user, id);
const size = Number(row.size_bytes);
const received = Number(row.received_bytes);
if (received !== size) {
throw AppError.badRequest("Envoi incomplet : des morceaux sont encore manquants.");
}
if (!(await fileExists(row.temp_path))) {
await dropSession(db, row);
throw AppError.notFound("Fichier temporaire introuvable. Relancez l'envoi.");
}
const budget = await db.one<{ max_file_bytes: number | string }>(
"SELECT max_file_bytes FROM users WHERE id = ? AND deleted_at IS NULL",
[user.id],
);
if (!budget) {
await dropSession(db, row);
throw AppError.unauthorized();
}
if (BigInt(size) > BigInt(budget.max_file_bytes)) {
await dropSession(db, row);
throw AppError.payloadTooLarge(
`Fichier trop volumineux (maximum ${budget.max_file_bytes} octets).`,
);
}
if (row.folder_id !== null && !(await canWrite(db, user, row.folder_id))) {
await dropSession(db, row);
throw AppError.forbidden("Vous ne pouvez plus ecrire dans ce dossier.");
}
try {
await assertNameFree(db, user, row.folder_id, row.name);
} catch (error) {
await dropSession(db, row);
throw error;
}
const checksum = await hashFile(row.temp_path);
const destination = absolutePath(config.MEDIA_DIR, row.relative_path);
await ensureDir(path.dirname(destination));
await publish(row.temp_path, 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`,
[size, user.id, size],
);
if ((quota as { affectedRows: number }).affectedRows === 0) {
throw AppError.payloadTooLarge("Votre quota de stockage est depasse.");
}
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)`,
[size, row.storage_location_id, size],
);
if ((support as { affectedRows: number }).affectedRows === 0) {
throw AppError.payloadTooLarge("L'espace disponible sur le support est insuffisant.");
}
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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
row.id,
row.storage_location_id,
row.folder_id,
row.name,
row.mime_type ?? "application/octet-stream",
size,
checksum,
row.relative_path,
user.id,
user.id,
],
);
await connection.execute("DELETE FROM upload_sessions WHERE id = ?", [row.id]);
});
} catch (error) {
await publish(destination, row.temp_path).catch(async () => {
await discard(destination);
await db.exec("DELETE FROM upload_sessions WHERE id = ?", [row.id]).catch(() => undefined);
});
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Ce nom existe deja ici.");
}
throw error;
}
await indexMedia(db, config, row.id, row.mime_type ?? "application/octet-stream", destination).catch(
() => undefined,
);
return db.required<FileRow>(`${SELECT_FILE} WHERE f.id = ?`, [user.id, row.id]);
};
export const cancelUpload = async (
db: Db,
user: SessionUser,
id: string,
): Promise<UploadSessionRow> => {
const row = await loadSession(db, user, id);
await dropSession(db, row);
return row;
};
/** Purge les sessions d'envoi expirees et leurs fichiers temporaires. */
export const purgeExpiredUploads = async (db: Db, config: Config): Promise<number> => {
const expired = await db.query<UploadSessionRow>(
`${SELECT_SESSION} WHERE expires_at <= UTC_TIMESTAMP()`,
);
for (const row of expired) await discard(row.temp_path);
const result = await db.exec("DELETE FROM upload_sessions WHERE expires_at <= UTC_TIMESTAMP()");
const cutoff = Date.now() - SESSION_TTL_MS;
for (const temporary of await listUploadTemps(config.MEDIA_DIR)) {
const info = await stat(temporary).catch(() => null);
if (info !== null && info.mtimeMs < cutoff) await discard(temporary);
}
return result.affectedRows;
};
@@ -4,8 +4,7 @@ import { mkdir, open, readdir, rename, rm, stat, statfs } from "node:fs/promises
import path from "node:path";
import { Readable, Transform } from "node:stream";
import { pipeline } from "node:stream/promises";
import { AppError } from "../utils/errors.js";
import type { Db } from "../config/db.js";
import { AppError, type Db } from "./lib/index.js";
const SLUG = /^[a-z0-9][a-z0-9-]{0,99}$/;
const EXTENSION = /^[.][a-z0-9]{1,10}$/i;
-47
View File
@@ -1,47 +0,0 @@
import { z } from "zod";
import { AppError } from "./errors.js";
/** Identifiant UUID canonique (fichiers, dossiers, sessions...). */
export 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.",
);
/** Valide un corps JSON avec zod et leve une erreur 400 explicite. */
export 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;
};
/** Valide et nettoie un nom de fichier ou de dossier. */
export const assertName = (
raw: string | undefined,
what: "fichier" | "dossier",
): string => {
const name = (raw ?? "").trim();
if (!name || name.length > 255) {
throw AppError.badRequest(
`Le nom du ${what} doit contenir entre 1 et 255 caracteres.`,
);
}
if (name === "." || name === ".." || /[/\\\0-\x1f]/.test(name)) {
throw AppError.badRequest(`Le nom du ${what} ne peut pas contenir de separateur.`);
}
return name;
};
const MIME = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,127}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,127}$/;
/** Normalise un en-tete Content-Type, avec repli sur application/octet-stream. */
export const mimeOf = (header: string | undefined): string => {
const value = (header ?? "").split(";")[0]?.trim().toLowerCase() ?? "";
return MIME.test(value) ? value : "application/octet-stream";
};
+7 -11
View File
@@ -32,8 +32,8 @@ CI). L'exécuter avant de déclarer un travail fini.
seulement. Le checksum bloquerait le démarrage.
5. **API admin** : les routes `/api/cloud/admin/*` existent (UI Administration).
La CLI (`make admin`) reste pour l'amorçage et les cas hors ligne.
6. **Chemin disque** : toujours via `services/storageService.ts` (`resolveInside`),
jamais par concaténation depuis une entrée utilisateur.
6. **Chemin disque** : toujours via `storage.ts` (`resolveInside`), jamais par
concaténation depuis une entrée utilisateur.
7. **404 plutôt que 403** sur une ressource non accessible : ne pas introduire
d'énumération.
8. **CSP stricte** : pas de script en ligne dans `index.html` (utiliser un
@@ -42,17 +42,13 @@ CI). L'exécuter avant de déclarer un travail fini.
## Conventions
- TypeScript strict, project references racine.
- Back : `routes/*Routes.ts` (HTTP fin) appellent `services/*Service.ts`
(métier) ; le socle vit dans `config/`, `middleware/`, `utils/`, les types
partagés dans `models/types.ts`.
- Hono + Zod : toute route avec corps passe par un schéma Zod dédié.
- Erreurs : `AppError` + codes (`utils/errors.ts`) — jamais `throw` brut, jamais
de détail de schéma dans une 500.
- Erreurs : `AppError` + codes (`errors.ts`) — jamais `throw` brut, jamais de
détail de schéma dans une 500.
- SQL : requêtes préparées uniquement, pas de `raw()` hors DDL.
- Front : un client HTTP (`frontend/src/services/apiClient.ts`), puis un service
par domaine (`services/*Service.ts`), `credentials: "same-origin"`. React
Router 7 (`App.tsx`) + `AppShell`, contexte de session dans
`contexts/SessionContext.tsx`.
- Front : un seul client HTTP (`frontend/src/lib/api.ts`),
`credentials: "same-origin"`. React Router 7 (`App.tsx`) + `AppShell`, contexte
de session dans `lib/session.tsx`.
- `.editorconfig` : 2 espaces, LF, UTF-8.
## Design system
+6 -6
View File
@@ -91,7 +91,7 @@ l'offset exact.
### Discussion (chat d'un dossier et membres)
Chaque dossier possède son propre salon. Le droit d'accès au dossier fait loi :
lecture comme écriture passent par `canRead` (`backend/src/services/auditService.ts`), donc le
lecture comme écriture passent par `canRead` (`backend/src/access.ts`), donc le
salon d'un dossier `public` est ouvert à tout compte authentifié. La lecture est
en texte brut, React échappe le rendu. La synchronisation est incrémentale par
identifiant (`after`), sans WebSocket.
@@ -158,7 +158,7 @@ utilise alors le sien.
## Droits d'accès
Calculés **en base à chaque requête**, depuis la session — jamais depuis un
en-tête (`backend/src/services/auditService.ts`).
en-tête (`backend/src/access.ts`).
| Concept | Règle |
| --- | --- |
@@ -190,9 +190,9 @@ par tous les membres authentifiés, en écriture pour son propriétaire.
## Courriels
Les messages sortants sont construits par `backend/src/services/mailService.ts`
(gabarit HTML aux couleurs de l'app (`#b71c1c`), logo, bouton d'action et mention
**ne pas répondre**). Un repli texte accompagne chaque envoi.
Les messages sortants sont construits par `backend/src/lib/mail-template.ts` :
gabarit HTML aux couleurs de l'app (`#b71c1c`), logo, bouton d'action et mention
**ne pas répondre**. Un repli texte accompagne chaque envoi.
Le logo `backend/src/assets/logo.png` est **embarqué** dans le message (pièce
jointe `cid`), donc visible même quand le client bloque les images distantes.
@@ -229,7 +229,7 @@ audit_logs, user_file_stars, chat_reads`.
## Erreurs métier
`AppError` avec codes stables (`backend/src/utils/errors.ts`). Correspondances
`AppError` avec codes stables (`backend/src/lib/errors.ts`). Correspondances
MariaDB : `1062` → 409, `1146` → 503 `NOT_MIGRATED`, `1406` → 422. Le corps d'une
500 ne contient jamais de détail de schéma. Réponse normalisée :
+20 -30
View File
@@ -9,36 +9,27 @@ Node/TypeScript, une base MariaDB, un stockage de fichiers monté en volume.
| Élément | Où |
| --- | --- |
| React 19 + Vite 8 + Tailwind 4 + react-router-dom 7 | `frontend` |
| Hono | `backend/src/index.ts` (`src/utils` pour le socle HTTP) |
| MariaDB (`mysql2`) | `backend/src/config/db.ts` |
| Nodemailer | `backend/src/services/mailService.ts` |
| sharp (vignettes) | `backend/src/services/mediaService.ts` |
| Validation Zod | `backend/src/config/appConfig.ts`, `src/utils/validators.ts` et chaque route |
| Hono | `backend/src/index.ts` (`src/lib` pour le socle) |
| MariaDB (`mysql2`) | `backend/src/lib/db.ts` |
| Nodemailer | `backend/src/lib/mail.ts` |
| sharp (vignettes) | `backend/src/media.ts` |
| Validation Zod | `backend/src/lib/config.ts` et chaque route |
## Découpage
```
backend/src/config/ configuration et connexion base (appConfig, db)
backend/src/middleware/ gardes HTTP (auth : session, rôles)
backend/src/models/ types partages (types.ts)
backend/src/routes/ routeurs HTTP fins, un par domaine (*Routes.ts)
backend/src/services/ logique metier, un fichier par domaine (*Service.ts)
backend/src/utils/ socle technique : errors, http, ratelimit, validators, migrate, service
backend/src/ index.ts (bootstrap), cli.ts, admin.ts
backend/migrations/ 000 … 010
frontend/src/services/ clients API par domaine (*Service.ts + apiClient.ts)
frontend/src/contexts/ SessionContext, ThemeContext, I18nContext
frontend/src/types/ types partages du front
frontend/src/utils/ formatage (format.ts)
frontend/src/ui/ design system (boutons, cartes, champs, spinner)
frontend/src/ router + AppShell + pages/
docker/ Dockerfile(.app/.api), nginx/, publish.sh
backend/src/lib/ socle serveur : config, db, mail, mail-template, ratelimit, http, service, auth, errors
backend/src/ routes/, access.ts, storage.ts, media.ts, admin.ts
backend/migrations/ 000 … 006
frontend/src/ui/ design system (boutons, cartes, champs, spinner)
frontend/src/ router + AppShell + pages/
docker/ Dockerfile(.app/.api), nginx/, publish.sh
```
`backend/src/utils` porte la mécanique générique (erreurs, HTTP, migrations,
limitation de débit, validation), `backend/src/services` porte le métier :
sessions, droits, quotas, chemins disque, traitement média, courriel.
Tout vit dans un seul paquet, sans dépendance de workspace.
`backend/src/lib` porte la mécanique générique (sessions, erreurs,
migrations, courriel, limitation de débit), le reste de `backend` porte le
métier : droits, quotas, chemins disque, traitement média. Tout vit dans un seul
paquet, sans dépendance de workspace.
## Chaîne de démarrage
@@ -67,9 +58,8 @@ app-build (publish.sh, terminé avant nginx)
- Pages : `Login`, `ForgotPassword`, `ResetPassword`, `ConfirmEmail`,
`ChangePassword`, `Browser`, `Search`, `Gallery`, `Trash`, `Profile`,
`Admin` (comptes / stockage / journal).
- Client HTTP unique `services/apiClient.ts` (base `/api/cloud`, `same-origin`) ;
services par domaine dans `services/*Service.ts` ; contexte de session
`contexts/SessionContext.tsx` ; dialogues réutilisables dans
- Client HTTP unique `lib/api.ts` (base `/api/cloud`, `same-origin`) ; contexte
de session `lib/session.tsx` ; dialogues réutilisables dans
`components/dialogs.tsx`.
- En-têtes nginx : CSP stricte, HSTS, `nosniff`, `Referrer-Policy`,
`Permissions-Policy` (`docker/nginx/snippets/`). `X-Frame-Options` est
@@ -88,9 +78,9 @@ app-build (publish.sh, terminé avant nginx)
## Stockage et médias
- `MEDIA_DIR=/data/media/originals`, `VARIANT_DIR=/data/media/variants`.
- Chemin physique `${MEDIA_DIR}/<slug>/<uuid><ext>` (`storageService.ts`), nom
affiché jamais dans le chemin.
- `mediaService.ts` : classification (`image/video/audio/document/archive/other`),
- Chemin physique `${MEDIA_DIR}/<slug>/<uuid><ext>` (`storage.ts`), nom affiché
jamais dans le chemin.
- `media.ts` : classification (`image/video/audio/document/archive/other`),
vignette (`sharp`, seuil 480 px) écrite dans `VARIANT_DIR`, métadonnées dans
`media_metadata` / `file_variants`. Indexation **best-effort** après upload.
- Avatars dans `user_avatars`.
+1 -1
View File
@@ -12,7 +12,7 @@ Réponse sur **`http://localhost:8083`**.
La configuration est validée **avant** l'ouverture d'aucun port : si une variable
manque ou est mal formée, le process s'arrête en listant exactement ce qui
pose problème (`backend/src/config/appConfig.ts`).
pose problème (`backend/src/lib/config.ts`).
## Variables
+3 -3
View File
@@ -18,7 +18,7 @@
### Limitation de débit
- **Applicatif** : `createRateLimiter` (`backend/src/utils/ratelimit.ts`) par IP
- **Applicatif** : `createRateLimiter` (`backend/src/lib/ratelimit.ts`) par IP
sur `auth/login`, `account/forgot-password`, `account/reset-password`,
`account/email-change`. Réglages `RATE_LIMIT_LOGIN_MAX` (10) et
`RATE_LIMIT_LOGIN_WINDOW_MS` (60 s).
@@ -36,7 +36,7 @@
### Droits d'accès
Calculés **en base à chaque requête**, depuis la session — jamais depuis un
en-tête (`backend/src/services/auditService.ts`). Lecture : propriétaire, permission
en-tête (`backend/src/access.ts`). Lecture : propriétaire, permission
`folder_permissions` (`read`/`write`/`admin`), ou dossier `public`. Écriture :
`write`/`admin`. **404 plutôt que 403** : jamais d'indice sur l'existence d'une
ressource.
@@ -64,7 +64,7 @@ d'écriture par compte sur 10 s), édition et épinglage compris.
### Courriel
Nodemailer (`backend/src/services/mailService.ts`) avec `SMTP_HOST`. `PUBLIC_ORIGIN`
Nodemailer (`backend/src/lib/mail.ts`) avec `SMTP_HOST`. `PUBLIC_ORIGIN`
(obligatoire) construit les liens de réinitialisation et de confirmation ;
aucun HTML utilisateur n'est injecté dans les messages.
+1 -1
View File
@@ -54,7 +54,7 @@ Design system local à `frontend/src/ui` : `Button`, `Card`, `Input`,
| Élément | Attendu |
| --- | --- |
| Socle & design system | internes à `backend/src/{config,middleware,utils}` et `frontend/src/ui` |
| Socle & design system | internes à `backend/src/lib` et `frontend/src/ui` |
| Port HTTP | `8083` (`COHAISE_HTTP_PORT`) |
| Dépôt | autonome, importance égale front et back |
| `.env` | jamais versionné (`.env.example` seulement) |
+8 -8
View File
@@ -33,13 +33,13 @@ fichier est copié dans l'image, pas monté.
## Modifier une route
1. Schéma d'entrée : Zod dans `backend/src/routes/<entity>Routes.ts`.
2. Droits : passer par `backend/src/services/auditService.ts` (jamais par un
paramètre venu du client).
1. Schéma d'entrée : Zod dans `backend/src/routes/<entity>.ts`.
2. Droits : passer par `backend/src/access.ts` (jamais par un paramètre
venu du client).
3. Réponse : renvoyer **404** si la ressource n'est pas censée exister pour ce
compte, 403 seulement pour une règle explicite.
4. Erreur métier : `AppError` depuis `backend/src/utils/errors.ts`.
5. Audit si l'action est sensible (`audit()` dans `services/auditService.ts`).
4. Erreur métier : `AppError` depuis `backend/src/lib/errors.ts`.
5. Audit si l'action est sensible (`audit()` dans `access.ts`).
6. `make check`, puis redémarrage de l'API (`docker compose up -d api`).
## Modifier le schéma
@@ -65,10 +65,10 @@ Le design system vit dans `frontend/src/ui` (+ `src/styles`).
| Besoin | Fichier |
| --- | --- |
| Droit d'accès à un dossier/fichier | `backend/src/services/auditService.ts` |
| Droit d'accès à un dossier/fichier | `backend/src/access.ts` |
| Taille/quota par défaut | migration `004`, table `users` / `settings` |
| Chemin physique des fichiers | `backend/src/services/storageService.ts` |
| En-têtes, CORS, healthz | `backend/src/utils/http.ts` |
| Chemin physique des fichiers | `backend/src/storage.ts` |
| En-têtes, CORS, healthz | `backend/src/lib/http.ts` |
| Durée de session | `SESSION_TTL_HOURS` |
| Port | `COHAISE_HTTP_PORT` (nginx), `COHAISE_API_PORT` (API) |
| Interface (parcours dossiers) | `frontend/src/pages/Browser.tsx` |
+1 -1
View File
@@ -1,6 +1,6 @@
import { Navigate, Outlet, Route, Routes } from "react-router-dom";
import { Spinner } from "./ui/index.js";
import { useSession } from "./contexts/SessionContext.js";
import { useSession } from "./lib/session.js";
import { AppShell } from "./components/AppShell.js";
import { AuthLayout } from "./components/AuthLayout.js";
import { DocumentTitle } from "./components/DocumentTitle.js";
+2 -2
View File
@@ -7,8 +7,8 @@ import {
} from "react";
import { NavLink, Outlet } from "react-router-dom";
import { cn } from "../ui/index.js";
import { useSession } from "../contexts/SessionContext.js";
import { useI18n } from "../contexts/I18nContext.js";
import { useSession } from "../lib/session.js";
import { useI18n } from "../lib/i18n.js";
import { Avatar } from "./Avatar.js";
import { ColorBendsBackdrop } from "./ColorBendsBackdrop.js";
import {
+2 -2
View File
@@ -1,4 +1,4 @@
import { accountService } from "../services/accountService.js";
import { api } from "../lib/api.js";
import { cn } from "../ui/index.js";
const initials = (first: string, last: string): string =>
@@ -29,7 +29,7 @@ export const Avatar = ({
{initials(firstName, lastName)}
{hasAvatar ? (
<img
src={`${accountService.avatarUrl(userId)}?v=${encodeURIComponent(avatarUpdatedAt ?? "")}`}
src={`${api.avatarUrl(userId)}?v=${encodeURIComponent(avatarUpdatedAt ?? "")}`}
alt=""
className="absolute inset-0 h-full w-full object-cover"
onError={(event) => {
+1 -1
View File
@@ -1,6 +1,6 @@
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
import { useI18n } from "../contexts/I18nContext.js";
import { useI18n } from "../lib/i18n.js";
const BRAND = "CoHaiSe Cloud";
+20 -16
View File
@@ -8,13 +8,17 @@ import {
type KeyboardEvent as ReactKeyboardEvent,
} from "react";
import { Button, Spinner, cn } from "../ui/index.js";
import { ApiError } from "../services/apiClient.js";
import { chatService } from "../services/chatService.js";
import { formatDate, formatDateTimeSeconds } from "../utils/format.js";
import type { ChatMember, ChatMessage } from "../types/index.js";
import { useI18n } from "../contexts/I18nContext.js";
import {
ApiError,
api,
formatDate,
formatDateTimeSeconds,
type ChatMember,
type ChatMessage,
} from "../lib/api.js";
import { useI18n } from "../lib/i18n.js";
import { getLocale } from "../lib/locale.js";
import { useSession } from "../contexts/SessionContext.js";
import { useSession } from "../lib/session.js";
import { useConfirm } from "./confirm.js";
import { Avatar } from "./Avatar.js";
import { ColorBendsBackdrop } from "./ColorBendsBackdrop.js";
@@ -138,7 +142,7 @@ export const FolderChat = ({
);
const loadMembers = useCallback(async () => {
const { members: list } = await chatService.chatMembers(folderId);
const { members: list } = await api.chatMembers(folderId);
setMembers(list);
}, [folderId]);
@@ -152,9 +156,9 @@ export const FolderChat = ({
void (async () => {
try {
const [memberResult, messageResult, pinResult] = await Promise.all([
chatService.chatMembers(folderId),
chatService.chatMessages(folderId, 0, 50),
chatService.chatPins(folderId),
api.chatMembers(folderId),
api.chatMessages(folderId, 0, 50),
api.chatPins(folderId),
]);
if (!active) return;
setMembers(memberResult.members);
@@ -187,13 +191,13 @@ export const FolderChat = ({
if (document.hidden) return;
try {
const [result, pinResult] = await Promise.all([
chatService.chatMessages(
api.chatMessages(
folderId,
lastIdRef.current,
100,
editedSinceRef.current,
),
chatService.chatPins(folderId),
api.chatPins(folderId),
]);
editedSinceRef.current = result.cursor;
mergeMessages(result.messages);
@@ -246,7 +250,7 @@ export const FolderChat = ({
setSending(true);
setError(null);
try {
const { message } = await chatService.chatSend(folderId, body);
const { message } = await api.chatSend(folderId, body);
stickToBottomRef.current = true;
mergeMessages([message]);
setDraft("");
@@ -273,7 +277,7 @@ export const FolderChat = ({
return;
setDeletingId(message.id);
try {
await chatService.chatDeleteMessage(folderId, message.id);
await api.chatDeleteMessage(folderId, message.id);
setMessages((previous) =>
previous.filter((item) => item.id !== message.id),
);
@@ -305,7 +309,7 @@ export const FolderChat = ({
setSavingEdit(true);
setError(null);
try {
const { message: updated } = await chatService.chatEditMessage(
const { message: updated } = await api.chatEditMessage(
folderId,
message.id,
body,
@@ -333,7 +337,7 @@ export const FolderChat = ({
setPinningId(message.id);
setError(null);
try {
const { pinned } = await chatService.chatTogglePin(folderId, message.id);
const { pinned } = await api.chatTogglePin(folderId, message.id);
const updated = { ...message, is_pinned: pinned };
mergeMessages([updated]);
setPins((previous) =>
+3 -3
View File
@@ -1,4 +1,4 @@
import { fileService } from "../services/fileService.js";
import { api } from "../lib/api.js";
import { mediaKind } from "../lib/media.js";
import { ArchiveIcon, AudioIcon, FileIcon, PlayIcon } from "./icons.js";
@@ -18,7 +18,7 @@ export const MediaThumb = ({
if (kind === "image") {
return (
<img
src={fileService.thumbnailUrl(id)}
src={api.thumbnailUrl(id)}
alt=""
loading="lazy"
className="pointer-events-none h-full w-full object-cover"
@@ -32,7 +32,7 @@ export const MediaThumb = ({
return (
<span className="relative block h-full w-full bg-black">
<video
src={`${fileService.previewUrl(id)}#t=0.1`}
src={`${api.previewUrl(id)}#t=0.1`}
preload="metadata"
muted
playsInline
+9 -9
View File
@@ -1,7 +1,7 @@
import { useEffect, useState } from "react";
import { cn } from "../ui/index.js";
import { fileService } from "../services/fileService.js";
import { useI18n } from "../contexts/I18nContext.js";
import { api } from "../lib/api.js";
import { useI18n } from "../lib/i18n.js";
import { ArrowLeftIcon, ArrowRightIcon, CloseIcon, DownloadIcon, FileIcon } from "./icons.js";
export interface MediaViewerItem {
@@ -38,7 +38,7 @@ const TextViewer = ({ id }: { id: string }) => {
let active = true;
setText(null);
setFailed(false);
void fetch(fileService.previewUrl(id))
void fetch(api.previewUrl(id))
.then((response) => (response.ok ? response.text() : Promise.reject(new Error("failed"))))
.then((body) => {
if (active) setText(body);
@@ -80,7 +80,7 @@ const Panel = ({
<div className="flex flex-wrap items-center justify-center gap-2">
{openable ? (
<a
href={fileService.previewUrl(item.id)}
href={api.previewUrl(item.id)}
target="_blank"
rel="noopener noreferrer"
className={actionClass}
@@ -88,7 +88,7 @@ const Panel = ({
{t("Ouvrir")}
</a>
) : null}
<a href={fileService.downloadUrl(item.id)} download={item.name} className={actionClass}>
<a href={api.downloadUrl(item.id)} download={item.name} className={actionClass}>
<DownloadIcon className="h-4 w-4" />
{t("Télécharger")}
</a>
@@ -103,7 +103,7 @@ const Body = ({ item }: { item: MediaViewerItem }) => {
if (kind === "image") {
return (
<img
src={fileService.previewUrl(item.id)}
src={api.previewUrl(item.id)}
alt={item.name}
className="max-h-full max-w-full rounded-md object-contain shadow-2xl"
/>
@@ -112,7 +112,7 @@ const Body = ({ item }: { item: MediaViewerItem }) => {
if (kind === "video") {
return (
<video
src={fileService.previewUrl(item.id)}
src={api.previewUrl(item.id)}
controls
autoPlay
className="max-h-full max-w-full rounded-md bg-black shadow-2xl"
@@ -124,7 +124,7 @@ const Body = ({ item }: { item: MediaViewerItem }) => {
<div className="flex w-full max-w-md flex-col items-center gap-4 rounded-lg bg-black/40 p-6">
<FileIcon className="h-10 w-10 text-white/70" />
<p className="max-w-full truncate text-sm text-white/90">{item.name}</p>
<audio src={fileService.previewUrl(item.id)} controls autoPlay className="w-full" />
<audio src={api.previewUrl(item.id)} controls autoPlay className="w-full" />
</div>
);
}
@@ -173,7 +173,7 @@ export const MediaViewer = ({
<p className="min-w-0 truncate text-sm font-medium">{current.name}</p>
<div className="flex shrink-0 items-center gap-2">
<a
href={fileService.downloadUrl(current.id)}
href={api.downloadUrl(current.id)}
download={current.name}
className={controlClass}
aria-label={t("Télécharger")}
+1 -1
View File
@@ -5,7 +5,7 @@ import {
useState,
type ReactNode,
} from "react";
import { useI18n } from "../contexts/I18nContext.js";
import { useI18n } from "../lib/i18n.js";
import { Modal } from "./feedback.js";
import { IconAction } from "./IconAction.js";
import { CloseIcon, TrashIcon, MoveIcon } from "./icons.js";
+19 -17
View File
@@ -1,12 +1,14 @@
import { useEffect, useState, type FormEvent } from "react";
import { Button, Input, cn } from "../ui/index.js";
import { ApiError } from "../services/apiClient.js";
import { directoryService } from "../services/directoryService.js";
import { fileService } from "../services/fileService.js";
import { folderService } from "../services/folderService.js";
import { formatDate } from "../utils/format.js";
import type { DirectoryUser, Folder, FolderPermission } from "../types/index.js";
import { useI18n } from "../contexts/I18nContext.js";
import {
ApiError,
api,
formatDate,
type DirectoryUser,
type Folder,
type FolderPermission,
} from "../lib/api.js";
import { useI18n } from "../lib/i18n.js";
import { Alert, Modal } from "./feedback.js";
import { CloseIcon, MoveIcon, PenIcon, PlusIcon, TrashIcon } from "./icons.js";
import { IconAction } from "./IconAction.js";
@@ -46,7 +48,7 @@ export const CreateFolderDialog = ({
setBusy(true);
setError(null);
try {
await folderService.createFolder(name, parentId);
await api.createFolder(name, parentId);
onCreated();
} catch (caught) {
setError(messageOf(caught, t("Création impossible.")));
@@ -110,8 +112,8 @@ export const RenameDialog = ({
setBusy(true);
setError(null);
try {
if (target.type === "folder") await folderService.updateFolder(target.id, name);
else await fileService.renameFile(target.id, name);
if (target.type === "folder") await api.updateFolder(target.id, name);
else await api.renameFile(target.id, name);
onDone();
} catch (caught) {
setError(messageOf(caught, t("Renommage impossible.")));
@@ -164,7 +166,7 @@ const loadTree = async (): Promise<TreeEntry[]> => {
const entries: TreeEntry[] = [];
const walk = async (parentId: string | null, prefix: string, depth: number): Promise<void> => {
if (depth > 6) return;
const { folders } = await folderService.folders(parentId);
const { folders } = await api.folders(parentId);
for (const folder of folders) {
entries.push({ id: folder.id, label: `${prefix}${folder.name}` });
await walk(folder.id, `${prefix}${folder.name} / `, depth + 1);
@@ -207,8 +209,8 @@ export const MoveDialog = ({
const parentId = destination === "" ? null : destination;
try {
for (const item of items) {
if (item.type === "folder") await folderService.moveFolder(item.id, parentId);
else await fileService.moveFile(item.id, parentId);
if (item.type === "folder") await api.moveFolder(item.id, parentId);
else await api.moveFile(item.id, parentId);
}
onDone();
} catch (caught) {
@@ -295,8 +297,8 @@ export const ShareDialog = ({
const load = async () => {
try {
const [{ permissions: list }, { users }] = await Promise.all([
folderService.folderPermissions(folder.id),
directoryService.directory(),
api.folderPermissions(folder.id),
api.directory(),
]);
setPermissions(list);
setMembers(users);
@@ -322,7 +324,7 @@ export const ShareDialog = ({
setError(null);
try {
const iso = expiresAt ? new Date(expiresAt).toISOString() : null;
await folderService.grantPermission(folder.id, email, level, expiresAt ? iso : null);
await api.grantPermission(folder.id, email, level, expiresAt ? iso : null);
setEmail("");
setExpiresAt("");
await load();
@@ -336,7 +338,7 @@ export const ShareDialog = ({
const revoke = async (userId: string) => {
setError(null);
try {
await folderService.revokePermission(folder.id, userId);
await api.revokePermission(folder.id, userId);
await load();
} catch (caught) {
setError(messageOf(caught, t("Révocation impossible.")));
+1 -1
View File
@@ -1,6 +1,6 @@
import { useEffect, useMemo, type ReactNode } from "react";
import { cn } from "../ui/index.js";
import { useI18n } from "../contexts/I18nContext.js";
import { useI18n } from "../lib/i18n.js";
import { CloseIcon } from "./icons.js";
import { usePageHeader } from "./AppShell.js";
+1 -1
View File
@@ -6,7 +6,7 @@ import {
type ReactNode,
} from "react";
import { cn } from "../ui/index.js";
import { useI18n } from "../contexts/I18nContext.js";
import { useI18n } from "../lib/i18n.js";
import { CloseIcon } from "./icons.js";
type ToastTone = "success" | "error" | "info";
+605
View File
@@ -0,0 +1,605 @@
import { getLanguage, getLocale } from "./locale";
export type Theme = "system" | "light" | "dark";
export type Language = "fr" | "en";
export interface User {
id: string;
email: string;
first_name: string;
last_name: string;
role_slug: string;
role_name: string;
quota_bytes: number;
used_bytes: number;
max_file_bytes: number;
must_change_password: boolean;
theme: Theme;
language: Language;
has_avatar: boolean;
avatar_updated_at: string | null;
}
export interface Folder {
id: string;
parent_id: string | null;
name: string;
owner_id: string | null;
access_type: string;
is_system: boolean;
created_at: string;
updated_at: string;
}
export interface UploadedFile {
id: string;
folder_id: string | null;
name: string;
mime_type: string | null;
size_bytes: number;
checksum_sha256: string | null;
owner_id: string | null;
is_starred: boolean;
download_count: number;
created_at: string;
updated_at: string;
}
export interface UploadSession {
uploadId: string;
name: string;
folderId: string | null;
size: number;
chunkSize: number;
uploadedBytes: number;
expiresAt: string;
}
export const LARGE_UPLOAD_THRESHOLD = 90 * 1024 * 1024;
export interface FavoriteFile extends UploadedFile {
folder_name: string | null;
}
export interface FolderPermission {
user_id: string;
email: string;
first_name: string;
last_name: string;
level: string;
expires_at: string | null;
created_at: string;
}
export interface SessionInfo {
id: string;
ip_address: string | null;
user_agent: string | null;
created_at: string;
last_seen_at: string;
expires_at: string;
current: boolean;
}
export interface TrashFolder {
id: string;
parent_id: string | null;
name: string;
owner_id: string | null;
access_type: string;
created_at: string;
updated_at: string;
deleted_at: string;
}
export interface TrashFile {
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;
}
export interface MediaItem {
id: string;
folder_id: string | null;
name: string;
mime_type: string | null;
size_bytes: number;
owner_id: string | null;
is_starred: boolean;
kind: string | null;
width: number | null;
height: number | null;
created_at: string;
has_thumbnail: boolean;
}
export interface AdminUser {
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: boolean;
must_change_password: boolean;
last_login_at: string | null;
created_at: string;
}
export interface StorageLocation {
id: number;
name: string;
slug: string;
mount_path: string;
quota_bytes: number | null;
used_bytes: number;
is_active: boolean;
created_at: string;
}
export interface AdminStats {
users: number;
folders: number;
files: number;
usedBytes: number;
trashFiles: number;
locations: { id: number; name: string; used_bytes: number; quota_bytes: number | null }[];
}
export interface AuditEntry {
id: number;
user_id: string | null;
user_email: string | null;
action: string;
resource: string;
resource_id: string | null;
details: string | null;
ip_address: string | null;
created_at: string;
}
export interface ChatMember {
id: string;
first_name: string;
last_name: string;
role_slug: string;
has_avatar: boolean;
avatar_updated_at: string | null;
last_login_at: string | null;
is_self: boolean;
}
export interface ChatMessage {
id: number;
user_id: string | null;
first_name: string | null;
last_name: string | null;
body: string;
created_at: string;
edited_at: string | null;
is_pinned: boolean;
has_avatar: boolean;
avatar_updated_at: string | null;
}
export interface DirectoryUser {
id: string;
first_name: string;
last_name: string;
email: string;
has_avatar: boolean;
avatar_updated_at: string | null;
}
export class ApiError extends Error {
readonly status: number;
constructor(status: number, message: string) {
super(message);
this.name = "ApiError";
this.status = status;
}
}
const BASE = "/api/cloud";
const messageOf = (body: unknown, fallback: string): string =>
(body as { error?: { message?: string } } | null)?.error?.message ?? fallback;
const request = async <T>(path: string, init?: RequestInit): Promise<T> => {
let response: Response;
try {
response = await fetch(`${BASE}${path}`, {
credentials: "same-origin",
...init,
headers: {
...(init?.body ? { "content-type": "application/json" } : {}),
...init?.headers,
},
});
} catch {
throw new ApiError(0, "Serveur injoignable. Verifiez votre connexion.");
}
const body: unknown = await response.json().catch(() => null);
if (!response.ok) throw new ApiError(response.status, messageOf(body, "Une erreur est survenue."));
return body as T;
};
const post = <T>(path: string, payload?: unknown): Promise<T> =>
request<T>(path, {
method: "POST",
...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
});
const patch = <T>(path: string, payload: unknown): Promise<T> =>
request<T>(path, { method: "PATCH", body: JSON.stringify(payload) });
const put = <T>(path: string, payload?: unknown): Promise<T> =>
request<T>(path, {
method: "PUT",
...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
});
const del = <T>(path: string): Promise<T> => request<T>(path, { method: "DELETE" });
const query = (params: Record<string, string | number | null | undefined>): string => {
const search = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (value !== null && value !== undefined && value !== "") search.set(key, String(value));
}
const suffix = search.toString();
return suffix ? `?${suffix}` : "";
};
const putBinary = async <T>(path: string, body: BodyInit, type: string): Promise<T> => {
let response: Response;
try {
response = await fetch(`${BASE}${path}`, {
method: "PUT",
credentials: "same-origin",
headers: type ? { "content-type": type } : {},
body,
});
} catch {
throw new ApiError(0, "Serveur injoignable. Verifiez votre connexion.");
}
const parsed: unknown = await response.json().catch(() => null);
if (!response.ok) throw new ApiError(response.status, messageOf(parsed, "L'envoi a echoue."));
return parsed as T;
};
const resumeKey = (file: File, folderId: string | null): string =>
`cohaise.upload:${folderId ?? "root"}:${file.name}:${file.size}:${file.lastModified}`;
const readResume = (key: string): string | null => {
try {
return window.localStorage.getItem(key);
} catch {
return null;
}
};
const writeResume = (key: string, uploadId: string): void => {
try {
window.localStorage.setItem(key, uploadId);
} catch {
}
};
const clearResume = (key: string): void => {
try {
window.localStorage.removeItem(key);
} catch {
}
};
const sendChunk = (
uploadId: string,
blob: Blob,
onProgress: (loaded: number) => void,
): Promise<void> =>
new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("PUT", `${BASE}/uploads/${encodeURIComponent(uploadId)}/chunks`);
xhr.withCredentials = true;
xhr.setRequestHeader("content-type", "application/octet-stream");
xhr.upload.onprogress = (event) => {
if (event.lengthComputable) onProgress(event.loaded);
};
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve();
return;
}
let parsed: unknown = null;
try {
parsed = JSON.parse(xhr.responseText);
} catch {
}
reject(new ApiError(xhr.status, messageOf(parsed, "L'envoi du morceau a echoue.")));
};
xhr.onerror = () => reject(new ApiError(0, "Serveur injoignable. Verifiez votre connexion."));
xhr.onabort = () => reject(new ApiError(0, "Envoi interrompu."));
xhr.send(blob);
});
const sessionPath = (uploadId: string): string => `/uploads/${encodeURIComponent(uploadId)}`;
const uploadFileResumable = async (
file: File,
folderId: string | null,
onProgress?: (loaded: number, total: number) => void,
): Promise<{ file: UploadedFile }> => {
const key = resumeKey(file, folderId);
let upload: UploadSession | null = null;
const saved = readResume(key);
if (saved !== null) {
try {
const result = await request<{ upload: UploadSession }>(sessionPath(saved));
if (result.upload.name === file.name && result.upload.size === file.size) {
upload = result.upload;
} else {
clearResume(key);
}
} catch (error) {
if (error instanceof ApiError && error.status === 404) clearResume(key);
else throw error;
}
}
if (upload === null) {
const result = await post<{ upload: UploadSession }>("/uploads", {
name: file.name,
folderId,
size: file.size,
mimeType: file.type || null,
});
upload = result.upload;
writeResume(key, upload.uploadId);
}
const uploadId = upload.uploadId;
let offset = upload.uploadedBytes;
let attempts = 0;
while (offset < file.size) {
const end = Math.min(offset + upload.chunkSize, file.size);
try {
await sendChunk(uploadId, file.slice(offset, end), (loaded) =>
onProgress?.(offset + loaded, file.size),
);
offset = end;
attempts = 0;
} catch (error) {
const transient =
!(error instanceof ApiError) ||
error.status === 0 ||
error.status === 409 ||
error.status >= 500;
attempts += 1;
if (!transient || attempts > 4) throw error;
await new Promise((resolve) => setTimeout(resolve, 400 * attempts));
const status = await request<{ upload: UploadSession }>(sessionPath(uploadId));
if (status.upload.name !== file.name || status.upload.size !== file.size) {
throw new ApiError(409, "La session d'envoi ne correspond plus au fichier.");
}
offset = status.upload.uploadedBytes;
}
}
onProgress?.(file.size, file.size);
const result = await post<{ file: UploadedFile }>(`${sessionPath(uploadId)}/complete`);
clearResume(key);
return result;
};
export const api = {
me: () => request<{ user: User }>("/auth/me"),
login: (email: string, password: string) =>
post<{ user: User }>("/auth/login", { email, password }),
logout: () => post<{ ok: boolean }>("/auth/logout"),
changePassword: (current: string, next: string) =>
post<{ ok: boolean }>("/auth/change-password", { current, next }),
forgotPassword: (email: string) => post<{ ok: boolean }>("/account/forgot-password", { email }),
resetPassword: (token: string, password: string) =>
post<{ ok: boolean }>("/account/reset-password", { token, password }),
requestEmailChange: (password: string, new_email: string) =>
post<{ ok: boolean }>("/account/email-change", { password, new_email }),
confirmEmailChange: (token: string) =>
post<{ ok: boolean; email: string }>("/account/email-change/confirm", { token }),
updateProfile: (first_name: string, last_name: string) =>
patch<{ ok: boolean }>("/account/profile", { first_name, last_name }),
preferences: () => request<{ theme: Theme; language: Language }>("/account/preferences"),
updatePreferences: (theme: Theme, language: Language) =>
patch<{ theme: Theme; language: Language }>("/account/preferences", { theme, language }),
sessions: () => request<{ sessions: SessionInfo[] }>("/account/sessions"),
revokeSession: (id: string) => del<{ ok: boolean }>(`/account/sessions/${encodeURIComponent(id)}`),
revokeOtherSessions: () => del<{ ok: boolean }>("/account/sessions"),
avatarUrl: (userId: string) => `${BASE}/account/avatar/${encodeURIComponent(userId)}`,
uploadAvatar: (file: File) => putBinary<{ ok: boolean }>("/account/avatar", file, file.type),
deleteAvatar: () => del<{ ok: boolean }>("/account/avatar"),
directory: () => request<{ users: DirectoryUser[] }>("/directory"),
folders: (parentId?: string | null) =>
request<{ parentId: string | null; folders: Folder[] }>(
`/folders${query({ parentId })}`,
),
createFolder: (name: string, parentId?: string | null) =>
post<{ folder: Folder }>("/folders", { name, parentId: parentId ?? null }),
updateFolder: (id: string, name: string) =>
patch<{ folder: Folder }>(`/folders/${encodeURIComponent(id)}`, { name }),
moveFolder: (id: string, parentId: string | null) =>
post<{ folder: Folder }>(`/folders/${encodeURIComponent(id)}/move`, { parentId }),
deleteFolder: (id: string) => del<{ ok: boolean }>(`/folders/${encodeURIComponent(id)}`),
folderPermissions: (id: string) =>
request<{ permissions: FolderPermission[] }>(
`/folders/${encodeURIComponent(id)}/permissions`,
),
grantPermission: (id: string, email: string, level: string, expiresAt: string | null) =>
post<{ ok: boolean }>(`/folders/${encodeURIComponent(id)}/permissions`, {
email,
level,
expiresAt,
}),
revokePermission: (id: string, userId: string) =>
del<{ ok: boolean }>(
`/folders/${encodeURIComponent(id)}/permissions/${encodeURIComponent(userId)}`,
),
files: (folderId?: string | null) =>
request<{ folderId: string | null; files: UploadedFile[] }>(`/files${query({ folderId })}`),
uploadFile: (
file: File,
folderId: string | null,
onProgress?: (loaded: number, total: number) => void,
) => {
if (file.size >= LARGE_UPLOAD_THRESHOLD) {
return uploadFileResumable(file, folderId, onProgress);
}
return putBinary<{ file: UploadedFile }>(
`/files${query({ name: file.name, folderId })}`,
file,
file.type,
).then((result) => {
onProgress?.(file.size, file.size);
return result;
});
},
uploadSession: (uploadId: string) =>
request<{ upload: UploadSession }>(sessionPath(uploadId)),
cancelUpload: (uploadId: string) => del<{ ok: boolean }>(sessionPath(uploadId)),
renameFile: (id: string, name: string) =>
patch<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}`, { name }),
moveFile: (id: string, folderId: string | null) =>
post<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}/move`, { folderId }),
starFile: (id: string) =>
request<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}/star`, { method: "PUT" }),
favorites: () => request<{ files: FavoriteFile[] }>("/favorites"),
deleteFile: (id: string) => del<{ ok: boolean }>(`/files/${encodeURIComponent(id)}`),
downloadUrl: (id: string) => `${BASE}/files/${encodeURIComponent(id)}/download`,
thumbnailUrl: (id: string) => `${BASE}/files/${encodeURIComponent(id)}/thumbnail`,
previewUrl: (id: string) => `${BASE}/files/${encodeURIComponent(id)}/preview`,
trash: () =>
request<{ retentionDays: number; folders: TrashFolder[]; files: TrashFile[] }>("/trash"),
restoreFolder: (id: string) =>
post<{ ok: boolean }>(`/trash/folders/${encodeURIComponent(id)}/restore`),
restoreFile: (id: string) =>
post<{ ok: boolean }>(`/trash/files/${encodeURIComponent(id)}/restore`),
purgeFolder: (id: string) => del<{ ok: boolean }>(`/trash/folders/${encodeURIComponent(id)}`),
purgeFile: (id: string) => del<{ ok: boolean }>(`/trash/files/${encodeURIComponent(id)}`),
emptyTrash: () => del<{ ok: boolean }>("/trash"),
search: (q: string) =>
request<{ query: string; folders: Folder[]; files: UploadedFile[] }>(`/search${query({ q })}`),
gallery: (kind: string, limit = 60, offset = 0) =>
request<{ kind: string | null; items: MediaItem[] }>(
`/media${query({ kind, limit, offset })}`,
),
chatMembers: (folderId: string) =>
request<{ members: ChatMember[] }>(`/folders/${encodeURIComponent(folderId)}/chat/members`),
chatMessages: (folderId: string, after = 0, limit = 50, editedAfter?: string | null) =>
request<{ messages: ChatMessage[]; cursor: string }>(
`/folders/${encodeURIComponent(folderId)}/chat/messages${query({ after, limit, editedAfter })}`,
),
chatSend: (folderId: string, body: string) =>
post<{ message: ChatMessage }>(`/folders/${encodeURIComponent(folderId)}/chat/messages`, { body }),
chatEditMessage: (folderId: string, id: number, body: string) =>
patch<{ message: ChatMessage }>(`/folders/${encodeURIComponent(folderId)}/chat/messages/${id}`, {
body,
}),
chatTogglePin: (folderId: string, id: number) =>
put<{ pinned: boolean }>(
`/folders/${encodeURIComponent(folderId)}/chat/messages/${id}/pin`,
),
chatPins: (folderId: string) =>
request<{ messages: ChatMessage[] }>(`/folders/${encodeURIComponent(folderId)}/chat/pins`),
chatDeleteMessage: (folderId: string, id: number) =>
del<{ ok: boolean }>(`/folders/${encodeURIComponent(folderId)}/chat/messages/${id}`),
chatUnread: () => request<{ unread: Record<string, number> }>("/chat/unread"),
adminStats: () => request<AdminStats>("/admin/stats"),
adminUsers: (q?: string) =>
request<{ users: AdminUser[] }>(`/admin/users${query({ q })}`),
adminCreateUser: (payload: {
email: string;
first_name: string;
last_name: string;
role_slug: string;
quota_bytes?: number | null;
max_file_bytes?: number | null;
}) => post<{ user: AdminUser }>("/admin/users", payload),
adminUpdateUser: (
id: string,
payload: Partial<{
first_name: string;
last_name: string;
role_slug: string;
quota_bytes: number;
max_file_bytes: number;
is_active: boolean;
}>,
) => patch<{ user: AdminUser }>(`/admin/users/${encodeURIComponent(id)}`, payload),
adminDeleteUser: (id: string) => del<{ ok: boolean }>(`/admin/users/${encodeURIComponent(id)}`),
adminResetPassword: (id: string) =>
post<{ ok: boolean }>(`/admin/users/${encodeURIComponent(id)}/reset-password`),
adminStorageLocations: () =>
request<{ locations: StorageLocation[] }>("/admin/storage-locations"),
adminCreateStorageLocation: (payload: {
name: string;
slug: string;
mount_path: string;
quota_bytes?: number | null;
}) => post<{ ok: boolean }>("/admin/storage-locations", payload),
adminUpdateStorageLocation: (
id: number,
payload: { name?: string; quota_bytes?: number | null; is_active?: boolean },
) => patch<{ ok: boolean }>(`/admin/storage-locations/${id}`, payload),
adminAudit: (limit = 100, offset = 0, action?: string, userId?: string) =>
request<{ entries: AuditEntry[] }>(`/admin/audit${query({ limit, offset, action, userId })}`),
adminAuditFilters: () =>
request<{ actions: string[]; users: { id: string; email: string | null }[] }>(
"/admin/audit/filters",
),
};
export const formatBytes = (bytes: number): string => {
const english = getLanguage() === "en";
if (bytes < 1024) return `${bytes} ${english ? "B" : "o"}`;
const units = english ? ["KB", "MB", "GB", "TB"] : ["Ko", "Mo", "Go", "To"];
let value = bytes;
let index = -1;
do {
value /= 1024;
index += 1;
} while (value >= 1024 && index < units.length - 1);
return `${value.toLocaleString(getLocale(), { maximumFractionDigits: value < 10 ? 1 : 0 })} ${units[index]}`;
};
export const formatDate = (value: string | null): string =>
value ? new Date(value).toLocaleString(getLocale(), { dateStyle: "medium", timeStyle: "short" }) : "—";
export const formatDateTimeSeconds = (value: string | null): string =>
value
? new Date(value).toLocaleString(getLocale(), {
day: "2-digit",
month: "short",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
})
: "—";
@@ -5,8 +5,8 @@ import {
useMemo,
type ReactNode,
} from "react";
import type { Language } from "../types/index.js";
import { setLanguage } from "../lib/locale.js";
import type { Language } from "./api.js";
import { setLanguage } from "./locale.js";
const en: Record<string, string> = {
"Annuler": "Cancel",
+1 -1
View File
@@ -1,4 +1,4 @@
import type { Language } from "../types/index.js";
import type { Language } from "./api";
let language: Language = "fr";
@@ -7,8 +7,7 @@ import {
useState,
type ReactNode,
} from "react";
import type { User } from "../types/index.js";
import { authService } from "../services/authService.js";
import { api, type User } from "./api.js";
interface SessionValue {
user: User | null;
@@ -26,7 +25,7 @@ export const SessionProvider = ({ children }: { children: ReactNode }) => {
const refresh = useCallback(async () => {
try {
const { user: current } = await authService.me();
const { user: current } = await api.me();
setUser(current);
} catch {
setUser(null);
@@ -40,7 +39,7 @@ export const SessionProvider = ({ children }: { children: ReactNode }) => {
}, [refresh]);
const logout = useCallback(async () => {
await authService.logout().catch(() => undefined);
await api.logout().catch(() => undefined);
setUser(null);
}, []);
@@ -1,5 +1,5 @@
import { useEffect, type ReactNode } from "react";
import type { Theme } from "../types/index.js";
import type { Theme } from "./api.js";
const STORAGE_KEY = "cohaise-theme";
+3 -3
View File
@@ -2,9 +2,9 @@ import { StrictMode, type ReactNode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { App } from "./App.js";
import { SessionProvider, useSession } from "./contexts/SessionContext.js";
import { I18nProvider } from "./contexts/I18nContext.js";
import { ThemeProvider } from "./contexts/ThemeContext.js";
import { SessionProvider, useSession } from "./lib/session.js";
import { I18nProvider } from "./lib/i18n.js";
import { ThemeProvider } from "./lib/theme.js";
import { ConfirmProvider } from "./components/confirm.js";
import { ToastProvider } from "./components/toast.js";
import "./styles/index.css";
+23 -18
View File
@@ -1,10 +1,15 @@
import { useEffect, useRef, useState, type FormEvent } from "react";
import { Button, Input, Spinner } from "../ui/index.js";
import { ApiError } from "../services/apiClient.js";
import { adminService } from "../services/adminService.js";
import { formatDate } from "../utils/format.js";
import type { AdminStats, AdminUser, AuditEntry, StorageLocation } from "../types/index.js";
import { useI18n } from "../contexts/I18nContext.js";
import {
ApiError,
api,
formatDate,
type AdminStats,
type AdminUser,
type AuditEntry,
type StorageLocation,
} from "../lib/api.js";
import { useI18n } from "../lib/i18n.js";
import { getLocale } from "../lib/locale.js";
import { Alert, Badge, EmptyState, Modal, PageHeader } from "../components/feedback.js";
import { useConfirm } from "../components/confirm.js";
@@ -58,7 +63,7 @@ export const AdminUsers = () => {
termRef.current = term;
setError(null);
try {
const { users: list } = await adminService.adminUsers(term || undefined);
const { users: list } = await api.adminUsers(term || undefined);
setUsers(list);
} catch (caught) {
setError(messageOf(caught, t("Chargement impossible.")));
@@ -68,7 +73,7 @@ export const AdminUsers = () => {
useEffect(() => {
void load("");
adminService
api
.adminStats()
.then(setStats)
.catch(() => undefined);
@@ -78,7 +83,7 @@ export const AdminUsers = () => {
setBusy(user.id);
setError(null);
try {
await adminService.adminUpdateUser(user.id, { is_active: !user.is_active });
await api.adminUpdateUser(user.id, { is_active: !user.is_active });
await load(termRef.current);
} catch (caught) {
setError(messageOf(caught, t("Mise à jour impossible.")));
@@ -92,7 +97,7 @@ export const AdminUsers = () => {
setError(null);
setNotice(null);
try {
await adminService.adminResetPassword(user.id);
await api.adminResetPassword(user.id);
setNotice(t("Mot de passe réinitialisé. Les identifiants ont été envoyés à {email}.", { email: user.email }));
} catch (caught) {
setError(messageOf(caught, t("Réinitialisation impossible.")));
@@ -114,7 +119,7 @@ export const AdminUsers = () => {
setBusy(user.id);
setError(null);
try {
await adminService.adminDeleteUser(user.id);
await api.adminDeleteUser(user.id);
await load(termRef.current);
} catch (caught) {
setError(messageOf(caught, t("Suppression impossible.")));
@@ -293,7 +298,7 @@ const CreateUserDialog = ({
setBusy(true);
setError(null);
try {
const { user } = await adminService.adminCreateUser({
const { user } = await api.adminCreateUser({
email: email.trim(),
first_name: firstName.trim(),
last_name: lastName.trim(),
@@ -411,7 +416,7 @@ const EditUserDialog = ({
setBusy(true);
setError(null);
try {
await adminService.adminUpdateUser(user.id, {
await api.adminUpdateUser(user.id, {
first_name: firstName.trim(),
last_name: lastName.trim(),
role_slug: role,
@@ -506,7 +511,7 @@ export const AdminStorage = () => {
const load = async () => {
setError(null);
try {
const { locations: list } = await adminService.adminStorageLocations();
const { locations: list } = await api.adminStorageLocations();
setLocations(list);
} catch (caught) {
setError(messageOf(caught, t("Chargement impossible.")));
@@ -521,7 +526,7 @@ export const AdminStorage = () => {
const toggle = async (location: StorageLocation) => {
setError(null);
try {
await adminService.adminUpdateStorageLocation(location.id, { is_active: !location.is_active });
await api.adminUpdateStorageLocation(location.id, { is_active: !location.is_active });
await load();
} catch (caught) {
setError(messageOf(caught, t("Mise à jour impossible.")));
@@ -615,7 +620,7 @@ const CreateLocationDialog = ({
setBusy(true);
setError(null);
try {
await adminService.adminCreateStorageLocation({
await api.adminCreateStorageLocation({
name: name.trim(),
slug: slug.trim(),
mount_path: mountPath.trim(),
@@ -701,7 +706,7 @@ export const AdminAudit = () => {
const load = async (nextAction: string, nextUser: string) => {
setError(null);
try {
const { entries: list } = await adminService.adminAudit(
const { entries: list } = await api.adminAudit(
100,
0,
nextAction || undefined,
@@ -716,7 +721,7 @@ export const AdminAudit = () => {
useEffect(() => {
void load("", "");
void adminService
void api
.adminAuditFilters()
.then(setFilters)
.catch(() => undefined);
@@ -734,7 +739,7 @@ export const AdminAudit = () => {
setLoadingMore(true);
setError(null);
try {
const { entries: more } = await adminService.adminAudit(
const { entries: more } = await api.adminAudit(
100,
entries.length,
action || undefined,
+21 -20
View File
@@ -6,14 +6,15 @@ import {
type DragEvent,
} from "react";
import { Card, Spinner, cn } from "../ui/index.js";
import { ApiError } from "../services/apiClient.js";
import { chatService } from "../services/chatService.js";
import { fileService } from "../services/fileService.js";
import { folderService } from "../services/folderService.js";
import { formatBytes } from "../utils/format.js";
import type { Folder, UploadedFile } from "../types/index.js";
import { useSession } from "../contexts/SessionContext.js";
import { useI18n } from "../contexts/I18nContext.js";
import {
ApiError,
api,
formatBytes,
type Folder,
type UploadedFile,
} from "../lib/api.js";
import { useSession } from "../lib/session.js";
import { useI18n } from "../lib/i18n.js";
import { getLocale } from "../lib/locale.js";
import { mediaKind } from "../lib/media.js";
import { EmptyState, PageHeader } from "../components/feedback.js";
@@ -113,8 +114,8 @@ export const Browser = () => {
setError(null);
try {
const [folderResult, fileResult] = await Promise.all([
folderService.folders(parentId),
fileService.files(parentId),
api.folders(parentId),
api.files(parentId),
]);
if (sequence !== loadSeq.current) return;
setFolders(folderResult.folders);
@@ -140,7 +141,7 @@ export const Browser = () => {
const refreshUnread = useCallback(async () => {
try {
const { unread: counts } = await chatService.chatUnread();
const { unread: counts } = await api.chatUnread();
setUnread(counts);
} catch {
}
@@ -204,7 +205,7 @@ export const Browser = () => {
for (let i = 0; i < filesArr.length; i++) {
const f = filesArr[i] as File;
update(i + 1, 0);
await fileService.uploadFile(f, current.id, (loaded) => update(i + 1, loaded));
await api.uploadFile(f, current.id, (loaded) => update(i + 1, loaded));
completedBytes += f.size;
}
void refresh();
@@ -241,7 +242,7 @@ export const Browser = () => {
for (let i = 0; i < filesArr.length; i++) {
const f = filesArr[i] as File;
update(i + 1, 0);
await fileService.uploadFile(f, folderId, (loaded) => update(i + 1, loaded));
await api.uploadFile(f, folderId, (loaded) => update(i + 1, loaded));
completedBytes += f.size;
}
void refresh();
@@ -344,9 +345,9 @@ export const Browser = () => {
setError(null);
try {
if (target.type === "folder") {
await folderService.deleteFolder(target.id);
await api.deleteFolder(target.id);
} else {
await fileService.deleteFile(target.id);
await api.deleteFile(target.id);
void refresh();
}
await reload();
@@ -375,8 +376,8 @@ export const Browser = () => {
setError(null);
try {
for (const target of selectedItems) {
if (target.type === "folder") await folderService.deleteFolder(target.id);
else await fileService.deleteFile(target.id);
if (target.type === "folder") await api.deleteFolder(target.id);
else await api.deleteFile(target.id);
}
clearSelection();
await reload();
@@ -394,7 +395,7 @@ export const Browser = () => {
const toggleStar = async (file: UploadedFile) => {
setError(null);
try {
const { file: updated } = await fileService.starFile(file.id);
const { file: updated } = await api.starFile(file.id);
setFiles((previous) =>
previous.map((item) => (item.id === updated.id ? updated : item)),
);
@@ -660,7 +661,7 @@ export const Browser = () => {
}
for (const target of files) {
const link = document.createElement("a");
link.href = fileService.downloadUrl(target.id);
link.href = api.downloadUrl(target.id);
link.download = target.name;
link.click();
}
@@ -904,7 +905,7 @@ export const Browser = () => {
/>
<a
href={fileService.downloadUrl(file.id)}
href={api.downloadUrl(file.id)}
download={file.name}
aria-label={t("Télécharger {name}", { name: file.name })}
title={t("Télécharger {name}", { name: file.name })}
+4 -5
View File
@@ -2,10 +2,9 @@ import { useState, type FormEvent } from "react";
import { useNavigate } from "react-router-dom";
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input } from "../ui/index.js";
import { Alert } from "../components/feedback.js";
import { ApiError } from "../services/apiClient.js";
import { authService } from "../services/authService.js";
import { useSession } from "../contexts/SessionContext.js";
import { useI18n } from "../contexts/I18nContext.js";
import { ApiError, api } from "../lib/api.js";
import { useSession } from "../lib/session.js";
import { useI18n } from "../lib/i18n.js";
export const ChangePassword = () => {
const { user, refresh, logout } = useSession();
@@ -26,7 +25,7 @@ export const ChangePassword = () => {
setBusy(true);
setError(null);
try {
await authService.changePassword(current, next);
await api.changePassword(current, next);
await refresh();
navigate("/files", { replace: true });
} catch (caught) {
+4 -5
View File
@@ -2,10 +2,9 @@ import { useEffect, useRef, useState } from "react";
import { Link, useSearchParams } from "react-router-dom";
import { Button, Card, CardContent, CardHeader, CardTitle, Spinner } from "../ui/index.js";
import { Alert } from "../components/feedback.js";
import { ApiError } from "../services/apiClient.js";
import { accountService } from "../services/accountService.js";
import { useSession } from "../contexts/SessionContext.js";
import { useI18n } from "../contexts/I18nContext.js";
import { ApiError, api } from "../lib/api.js";
import { useSession } from "../lib/session.js";
import { useI18n } from "../lib/i18n.js";
export const ConfirmEmail = () => {
const [params] = useSearchParams();
@@ -24,7 +23,7 @@ export const ConfirmEmail = () => {
setError(t("Ce lien est incomplet ou invalide."));
return;
}
accountService
api
.confirmEmailChange(token)
.then(() => {
setState("success");
+5 -8
View File
@@ -1,15 +1,12 @@
import { useEffect, useState } from "react";
import { Spinner } from "../ui/index.js";
import { ApiError } from "../services/apiClient.js";
import { fileService } from "../services/fileService.js";
import { formatBytes } from "../utils/format.js";
import type { FavoriteFile } from "../types/index.js";
import { ApiError, api, formatBytes, type FavoriteFile } from "../lib/api.js";
import { Alert, EmptyState, PageHeader } from "../components/feedback.js";
import { MediaViewer } from "../components/MediaViewer.js";
import { MediaThumb } from "../components/MediaThumb.js";
import { IconAction } from "../components/IconAction.js";
import { DownloadIcon, FolderIcon, StarIcon } from "../components/icons.js";
import { useI18n } from "../contexts/I18nContext.js";
import { useI18n } from "../lib/i18n.js";
export const Favorites = () => {
const { t } = useI18n();
@@ -20,7 +17,7 @@ export const Favorites = () => {
useEffect(() => {
setLoading(true);
void fileService
void api
.favorites()
.then(({ files: list }) => {
setFiles(list);
@@ -36,7 +33,7 @@ export const Favorites = () => {
const unstar = async (file: FavoriteFile) => {
setError(null);
try {
await fileService.starFile(file.id);
await api.starFile(file.id);
setFiles((previous) => previous.filter((item) => item.id !== file.id));
} catch (caught) {
setError(caught instanceof ApiError ? caught.message : t("Action impossible."));
@@ -93,7 +90,7 @@ export const Favorites = () => {
/>
<a
href={fileService.downloadUrl(file.id)}
href={api.downloadUrl(file.id)}
download={file.name}
aria-label={t("Télécharger {name}", { name: file.name })}
title={t("Télécharger {name}", { name: file.name })}
+3 -4
View File
@@ -2,9 +2,8 @@ import { useState, type FormEvent } from "react";
import { Link } from "react-router-dom";
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input } from "../ui/index.js";
import { Alert } from "../components/feedback.js";
import { ApiError } from "../services/apiClient.js";
import { accountService } from "../services/accountService.js";
import { useI18n } from "../contexts/I18nContext.js";
import { ApiError, api } from "../lib/api.js";
import { useI18n } from "../lib/i18n.js";
export const ForgotPassword = () => {
const { t } = useI18n();
@@ -18,7 +17,7 @@ export const ForgotPassword = () => {
setBusy(true);
setError(null);
try {
await accountService.forgotPassword(email);
await api.forgotPassword(email);
setSent(true);
} catch (caught) {
setError(caught instanceof ApiError ? caught.message : t("Demande impossible."));
+4 -7
View File
@@ -1,14 +1,11 @@
import { useCallback, useEffect, useState } from "react";
import { Button, Spinner, cn } from "../ui/index.js";
import { ApiError } from "../services/apiClient.js";
import { mediaService } from "../services/mediaService.js";
import { formatBytes } from "../utils/format.js";
import type { MediaItem } from "../types/index.js";
import { ApiError, api, formatBytes, type MediaItem } from "../lib/api.js";
import { Alert, EmptyState, PageHeader } from "../components/feedback.js";
import { MediaViewer } from "../components/MediaViewer.js";
import { MediaThumb } from "../components/MediaThumb.js";
import { ImageIcon } from "../components/icons.js";
import { useI18n } from "../contexts/I18nContext.js";
import { useI18n } from "../lib/i18n.js";
const KINDS = [
{ value: "", label: "Tout" },
@@ -33,7 +30,7 @@ export const Gallery = () => {
useEffect(() => {
setLoading(true);
void mediaService
void api
.gallery(kind, PAGE, 0)
.then(({ items: first }) => {
setItems(first);
@@ -50,7 +47,7 @@ export const Gallery = () => {
setLoadingMore(true);
setError(null);
try {
const { items: more } = await mediaService.gallery(kind, PAGE, items.length);
const { items: more } = await api.gallery(kind, PAGE, items.length);
setItems((previous) => [...previous, ...more]);
} catch (caught) {
setError(caught instanceof ApiError ? caught.message : t("Chargement impossible."));
+4 -5
View File
@@ -1,10 +1,9 @@
import { useState, type FormEvent } from "react";
import { Link, Navigate, useNavigate } from "react-router-dom";
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input } from "../ui/index.js";
import { ApiError } from "../services/apiClient.js";
import { authService } from "../services/authService.js";
import { useSession } from "../contexts/SessionContext.js";
import { useI18n } from "../contexts/I18nContext.js";
import { ApiError, api } from "../lib/api.js";
import { useSession } from "../lib/session.js";
import { useI18n } from "../lib/i18n.js";
export const Login = () => {
const { user, setUser } = useSession();
@@ -22,7 +21,7 @@ export const Login = () => {
setBusy(true);
setError(null);
try {
const { user: current } = await authService.login(email, password);
const { user: current } = await api.login(email, password);
setUser(current);
navigate(current.must_change_password ? "/change-password" : "/files", { replace: true });
} catch (caught) {
+12 -15
View File
@@ -1,11 +1,8 @@
import { useEffect, useRef, useState, type FormEvent } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle, Input, Spinner } from "../ui/index.js";
import { ApiError } from "../services/apiClient.js";
import { accountService } from "../services/accountService.js";
import { formatDate } from "../utils/format.js";
import type { Language, SessionInfo, Theme } from "../types/index.js";
import { useSession } from "../contexts/SessionContext.js";
import { useI18n } from "../contexts/I18nContext.js";
import { ApiError, api, formatDate, type Language, type SessionInfo, type Theme } from "../lib/api.js";
import { useSession } from "../lib/session.js";
import { useI18n } from "../lib/i18n.js";
import { Alert, Badge, PageHeader } from "../components/feedback.js";
import { useConfirm } from "../components/confirm.js";
import { IconAction } from "../components/IconAction.js";
@@ -64,7 +61,7 @@ export const Profile = () => {
const loadSessions = async () => {
setSessionsError(null);
try {
const { sessions: list } = await accountService.sessions();
const { sessions: list } = await api.sessions();
setSessions(list);
} catch (caught) {
setSessionsError(caught instanceof ApiError ? caught.message : t("Chargement impossible."));
@@ -82,7 +79,7 @@ export const Profile = () => {
setProfileError(null);
setProfileMessage(null);
try {
await accountService.updateProfile(firstName.trim(), lastName.trim());
await api.updateProfile(firstName.trim(), lastName.trim());
await refresh();
setProfileMessage(t("Informations enregistrées."));
} catch (caught) {
@@ -98,7 +95,7 @@ export const Profile = () => {
setPrefError(null);
setPrefMessage(null);
try {
await accountService.updatePreferences(theme, language);
await api.updatePreferences(theme, language);
await refresh();
setPrefMessage(t("Préférences enregistrées."));
} catch (caught) {
@@ -114,7 +111,7 @@ export const Profile = () => {
setEmailError(null);
setEmailMessage(null);
try {
await accountService.requestEmailChange(password, newEmail.trim());
await api.requestEmailChange(password, newEmail.trim());
setPassword("");
setNewEmail("");
setEmailMessage(t("Un e-mail de confirmation a été envoyé à la nouvelle adresse."));
@@ -129,7 +126,7 @@ export const Profile = () => {
if (!file) return;
setAvatarError(null);
try {
await accountService.uploadAvatar(file);
await api.uploadAvatar(file);
await refresh();
} catch (caught) {
setAvatarError(caught instanceof ApiError ? caught.message : t("Envoi impossible."));
@@ -141,7 +138,7 @@ export const Profile = () => {
const removeAvatar = async () => {
setAvatarError(null);
try {
await accountService.deleteAvatar();
await api.deleteAvatar();
await refresh();
} catch (caught) {
setAvatarError(caught instanceof ApiError ? caught.message : t("Suppression impossible."));
@@ -161,7 +158,7 @@ export const Profile = () => {
setRevoking(session.id);
setSessionsError(null);
try {
await accountService.revokeSession(session.id);
await api.revokeSession(session.id);
if (session.current) {
await refresh();
return;
@@ -177,7 +174,7 @@ export const Profile = () => {
const revokeOthers = async () => {
setSessionsError(null);
try {
await accountService.revokeOtherSessions();
await api.revokeOtherSessions();
setSessions((previous) => (previous ?? []).filter((item) => item.current));
} catch (caught) {
setSessionsError(caught instanceof ApiError ? caught.message : t("Révocation impossible."));
@@ -308,7 +305,7 @@ export const Profile = () => {
<div className="flex items-center gap-4">
<span className="flex h-16 w-16 shrink-0 items-center justify-center overflow-hidden rounded-full border border-border bg-surface-muted">
<img
src={`${accountService.avatarUrl(user.id)}?v=${user.avatar_updated_at ?? ""}`}
src={`${api.avatarUrl(user.id)}?v=${user.avatar_updated_at ?? ""}`}
alt=""
className="h-full w-full object-cover"
onError={(event) => {
+3 -4
View File
@@ -2,9 +2,8 @@ import { useState, type FormEvent } from "react";
import { Link, useSearchParams } from "react-router-dom";
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input } from "../ui/index.js";
import { Alert } from "../components/feedback.js";
import { ApiError } from "../services/apiClient.js";
import { accountService } from "../services/accountService.js";
import { useI18n } from "../contexts/I18nContext.js";
import { ApiError, api } from "../lib/api.js";
import { useI18n } from "../lib/i18n.js";
export const ResetPassword = () => {
const { t } = useI18n();
@@ -25,7 +24,7 @@ export const ResetPassword = () => {
setBusy(true);
setError(null);
try {
await accountService.resetPassword(token, password);
await api.resetPassword(token, password);
setDone(true);
} catch (caught) {
setError(caught instanceof ApiError ? caught.message : t("Réinitialisation impossible."));
+4 -8
View File
@@ -1,14 +1,10 @@
import { useState, type FormEvent } from "react";
import { Input, Spinner } from "../ui/index.js";
import { ApiError } from "../services/apiClient.js";
import { fileService } from "../services/fileService.js";
import { searchService } from "../services/searchService.js";
import { formatBytes } from "../utils/format.js";
import type { Folder, UploadedFile } from "../types/index.js";
import { ApiError, api, formatBytes, type Folder, type UploadedFile } from "../lib/api.js";
import { Alert, EmptyState, PageHeader } from "../components/feedback.js";
import { IconAction } from "../components/IconAction.js";
import { DownloadIcon, FileIcon, FolderIcon, SearchIcon } from "../components/icons.js";
import { useI18n } from "../contexts/I18nContext.js";
import { useI18n } from "../lib/i18n.js";
interface Results {
folders: Folder[];
@@ -32,7 +28,7 @@ export const Search = () => {
setLoading(true);
setError(null);
try {
const { folders, files } = await searchService.search(query);
const { folders, files } = await api.search(query);
setResults({ folders, files });
} catch (caught) {
setError(caught instanceof ApiError ? caught.message : t("Recherche impossible."));
@@ -130,7 +126,7 @@ export const Search = () => {
</span>
</span>
<a
href={fileService.downloadUrl(file.id)}
href={api.downloadUrl(file.id)}
download={file.name}
aria-label={t("Télécharger {name}", { name: file.name })}
className="inline-flex h-8 w-8 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-surface-hover hover:text-foreground"
+15 -11
View File
@@ -1,14 +1,18 @@
import { useCallback, useEffect, useState } from "react";
import { Spinner } from "../ui/index.js";
import { ApiError } from "../services/apiClient.js";
import { trashService } from "../services/trashService.js";
import { formatBytes, formatDate } from "../utils/format.js";
import type { TrashFile, TrashFolder } from "../types/index.js";
import {
ApiError,
api,
formatBytes,
formatDate,
type TrashFile,
type TrashFolder,
} from "../lib/api.js";
import { Alert, EmptyState, PageHeader } from "../components/feedback.js";
import { useConfirm } from "../components/confirm.js";
import { IconAction } from "../components/IconAction.js";
import { FileIcon, FolderIcon, RestoreIcon, TrashEmptyIcon, TrashIcon } from "../components/icons.js";
import { useI18n } from "../contexts/I18nContext.js";
import { useI18n } from "../lib/i18n.js";
interface TrashData {
retentionDays: number;
@@ -28,7 +32,7 @@ export const Trash = () => {
setLoading(true);
setError(null);
try {
setData(await trashService.trash());
setData(await api.trash());
} catch (caught) {
setError(caught instanceof ApiError ? caught.message : t("Chargement impossible."));
setData(null);
@@ -63,7 +67,7 @@ export const Trash = () => {
confirmIcon: <TrashEmptyIcon className="h-4 w-4" />,
});
if (!ok) return;
void run("empty", () => trashService.emptyTrash());
void run("empty", () => api.emptyTrash());
};
const purge = async (key: string, name: string, action: () => Promise<unknown>) => {
@@ -141,7 +145,7 @@ export const Trash = () => {
icon={<RestoreIcon className="h-4 w-4" />}
isLoading={busy === `restore-${folder.id}`}
onClick={() =>
void run(`restore-${folder.id}`, () => trashService.restoreFolder(folder.id))
void run(`restore-${folder.id}`, () => api.restoreFolder(folder.id))
}
/>
<IconAction
@@ -151,7 +155,7 @@ export const Trash = () => {
isLoading={busy === `purge-${folder.id}`}
onClick={() =>
void purge(`purge-${folder.id}`, folder.name, () =>
trashService.purgeFolder(folder.id),
api.purgeFolder(folder.id),
)
}
/>
@@ -186,7 +190,7 @@ export const Trash = () => {
icon={<RestoreIcon className="h-4 w-4" />}
isLoading={busy === `restore-${file.id}`}
onClick={() =>
void run(`restore-${file.id}`, () => trashService.restoreFile(file.id))
void run(`restore-${file.id}`, () => api.restoreFile(file.id))
}
/>
<IconAction
@@ -195,7 +199,7 @@ export const Trash = () => {
isLoading={busy === `purge-${file.id}`}
tone="danger"
onClick={() =>
void purge(`purge-${file.id}`, file.name, () => trashService.purgeFile(file.id))
void purge(`purge-${file.id}`, file.name, () => api.purgeFile(file.id))
}
/>
</li>
-24
View File
@@ -1,24 +0,0 @@
import type { SessionInfo, Theme, Language } from "../types/index.js";
import { BASE, del, get, patch, post, putBinary } from "./apiClient.js";
export const accountService = {
forgotPassword: (email: string) => post<{ ok: boolean }>("/account/forgot-password", { email }),
resetPassword: (token: string, password: string) =>
post<{ ok: boolean }>("/account/reset-password", { token, password }),
requestEmailChange: (password: string, new_email: string) =>
post<{ ok: boolean }>("/account/email-change", { password, new_email }),
confirmEmailChange: (token: string) =>
post<{ ok: boolean; email: string }>("/account/email-change/confirm", { token }),
updateProfile: (first_name: string, last_name: string) =>
patch<{ ok: boolean }>("/account/profile", { first_name, last_name }),
preferences: () => get<{ theme: Theme; language: Language }>("/account/preferences"),
updatePreferences: (theme: Theme, language: Language) =>
patch<{ theme: Theme; language: Language }>("/account/preferences", { theme, language }),
sessions: () => get<{ sessions: SessionInfo[] }>("/account/sessions"),
revokeSession: (id: string) => del<{ ok: boolean }>(`/account/sessions/${encodeURIComponent(id)}`),
revokeOtherSessions: () => del<{ ok: boolean }>("/account/sessions"),
avatarUrl: (userId: string) => `${BASE}/account/avatar/${encodeURIComponent(userId)}`,
uploadAvatar: (file: File) => putBinary<{ ok: boolean }>("/account/avatar", file, file.type),
deleteAvatar: () => del<{ ok: boolean }>("/account/avatar"),
};
-48
View File
@@ -1,48 +0,0 @@
import type { AdminStats, AdminUser, AuditEntry, StorageLocation } from "../types/index.js";
import { del, get, patch, post, query } from "./apiClient.js";
export const adminService = {
adminStats: () => get<AdminStats>("/admin/stats"),
adminUsers: (q?: string) =>
get<{ users: AdminUser[] }>(`/admin/users${query({ q })}`),
adminCreateUser: (payload: {
email: string;
first_name: string;
last_name: string;
role_slug: string;
quota_bytes?: number | null;
max_file_bytes?: number | null;
}) => post<{ user: AdminUser }>("/admin/users", payload),
adminUpdateUser: (
id: string,
payload: Partial<{
first_name: string;
last_name: string;
role_slug: string;
quota_bytes: number;
max_file_bytes: number;
is_active: boolean;
}>,
) => patch<{ user: AdminUser }>(`/admin/users/${encodeURIComponent(id)}`, payload),
adminDeleteUser: (id: string) => del<{ ok: boolean }>(`/admin/users/${encodeURIComponent(id)}`),
adminResetPassword: (id: string) =>
post<{ ok: boolean }>(`/admin/users/${encodeURIComponent(id)}/reset-password`),
adminStorageLocations: () =>
get<{ locations: StorageLocation[] }>("/admin/storage-locations"),
adminCreateStorageLocation: (payload: {
name: string;
slug: string;
mount_path: string;
quota_bytes?: number | null;
}) => post<{ ok: boolean }>("/admin/storage-locations", payload),
adminUpdateStorageLocation: (
id: number,
payload: { name?: string; quota_bytes?: number | null; is_active?: boolean },
) => patch<{ ok: boolean }>(`/admin/storage-locations/${id}`, payload),
adminAudit: (limit = 100, offset = 0, action?: string, userId?: string) =>
get<{ entries: AuditEntry[] }>(`/admin/audit${query({ limit, offset, action, userId })}`),
adminAuditFilters: () =>
get<{ actions: string[]; users: { id: string; email: string | null }[] }>(
"/admin/audit/filters",
),
};
-82
View File
@@ -1,82 +0,0 @@
export class ApiError extends Error {
readonly status: number;
constructor(status: number, message: string) {
super(message);
this.name = "ApiError";
this.status = status;
}
}
export const BASE = "/api/cloud";
/** Au-dela de ce seuil, l'envoi passe par des sessions morcelees. */
export const LARGE_UPLOAD_THRESHOLD = 90 * 1024 * 1024;
const messageOf = (body: unknown, fallback: string): string =>
(body as { error?: { message?: string } } | null)?.error?.message ?? fallback;
export const request = async <T>(path: string, init?: RequestInit): Promise<T> => {
let response: Response;
try {
response = await fetch(`${BASE}${path}`, {
credentials: "same-origin",
...init,
headers: {
...(init?.body ? { "content-type": "application/json" } : {}),
...init?.headers,
},
});
} catch {
throw new ApiError(0, "Serveur injoignable. Verifiez votre connexion.");
}
const body: unknown = await response.json().catch(() => null);
if (!response.ok) throw new ApiError(response.status, messageOf(body, "Une erreur est survenue."));
return body as T;
};
export const get = <T>(path: string): Promise<T> => request<T>(path);
export const post = <T>(path: string, payload?: unknown): Promise<T> =>
request<T>(path, {
method: "POST",
...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
});
export const patch = <T>(path: string, payload: unknown): Promise<T> =>
request<T>(path, { method: "PATCH", body: JSON.stringify(payload) });
export const put = <T>(path: string, payload?: unknown): Promise<T> =>
request<T>(path, {
method: "PUT",
...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
});
export const del = <T>(path: string): Promise<T> => request<T>(path, { method: "DELETE" });
export const query = (params: Record<string, string | number | null | undefined>): string => {
const search = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (value !== null && value !== undefined && value !== "") search.set(key, String(value));
}
const suffix = search.toString();
return suffix ? `?${suffix}` : "";
};
export const putBinary = async <T>(path: string, body: BodyInit, type: string): Promise<T> => {
let response: Response;
try {
response = await fetch(`${BASE}${path}`, {
method: "PUT",
credentials: "same-origin",
headers: type ? { "content-type": type } : {},
body,
});
} catch {
throw new ApiError(0, "Serveur injoignable. Verifiez votre connexion.");
}
const parsed: unknown = await response.json().catch(() => null);
if (!response.ok) throw new ApiError(response.status, messageOf(parsed, "L'envoi a echoue."));
return parsed as T;
};
-11
View File
@@ -1,11 +0,0 @@
import type { User } from "../types/index.js";
import { get, post } from "./apiClient.js";
export const authService = {
me: () => get<{ user: User }>("/auth/me"),
login: (email: string, password: string) =>
post<{ user: User }>("/auth/login", { email, password }),
logout: () => post<{ ok: boolean }>("/auth/logout"),
changePassword: (current: string, next: string) =>
post<{ ok: boolean }>("/auth/change-password", { current, next }),
};
-26
View File
@@ -1,26 +0,0 @@
import type { ChatMember, ChatMessage } from "../types/index.js";
import { del, get, patch, post, put, query } from "./apiClient.js";
export const chatService = {
chatMembers: (folderId: string) =>
get<{ members: ChatMember[] }>(`/folders/${encodeURIComponent(folderId)}/chat/members`),
chatMessages: (folderId: string, after = 0, limit = 50, editedAfter?: string | null) =>
get<{ messages: ChatMessage[]; cursor: string }>(
`/folders/${encodeURIComponent(folderId)}/chat/messages${query({ after, limit, editedAfter })}`,
),
chatSend: (folderId: string, body: string) =>
post<{ message: ChatMessage }>(`/folders/${encodeURIComponent(folderId)}/chat/messages`, { body }),
chatEditMessage: (folderId: string, id: number, body: string) =>
patch<{ message: ChatMessage }>(`/folders/${encodeURIComponent(folderId)}/chat/messages/${id}`, {
body,
}),
chatTogglePin: (folderId: string, id: number) =>
put<{ pinned: boolean }>(
`/folders/${encodeURIComponent(folderId)}/chat/messages/${id}/pin`,
),
chatPins: (folderId: string) =>
get<{ messages: ChatMessage[] }>(`/folders/${encodeURIComponent(folderId)}/chat/pins`),
chatDeleteMessage: (folderId: string, id: number) =>
del<{ ok: boolean }>(`/folders/${encodeURIComponent(folderId)}/chat/messages/${id}`),
chatUnread: () => get<{ unread: Record<string, number> }>("/chat/unread"),
};
@@ -1,6 +0,0 @@
import type { DirectoryUser } from "../types/index.js";
import { get } from "./apiClient.js";
export const directoryService = {
directory: () => get<{ users: DirectoryUser[] }>("/directory"),
};
-36
View File
@@ -1,36 +0,0 @@
import type { FavoriteFile, UploadedFile } from "../types/index.js";
import { BASE, del, get, patch, post, put, query, putBinary, LARGE_UPLOAD_THRESHOLD } from "./apiClient.js";
import { uploadService } from "./uploadService.js";
export const fileService = {
files: (folderId?: string | null) =>
get<{ folderId: string | null; files: UploadedFile[] }>(`/files${query({ folderId })}`),
uploadFile: (
file: File,
folderId: string | null,
onProgress?: (loaded: number, total: number) => void,
) => {
if (file.size >= LARGE_UPLOAD_THRESHOLD) {
return uploadService.uploadFileResumable(file, folderId, onProgress);
}
return putBinary<{ file: UploadedFile }>(
`/files${query({ name: file.name, folderId })}`,
file,
file.type,
).then((result) => {
onProgress?.(file.size, file.size);
return result;
});
},
renameFile: (id: string, name: string) =>
patch<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}`, { name }),
moveFile: (id: string, folderId: string | null) =>
post<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}/move`, { folderId }),
starFile: (id: string) =>
put<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}/star`),
favorites: () => get<{ files: FavoriteFile[] }>("/favorites"),
deleteFile: (id: string) => del<{ ok: boolean }>(`/files/${encodeURIComponent(id)}`),
downloadUrl: (id: string) => `${BASE}/files/${encodeURIComponent(id)}/download`,
thumbnailUrl: (id: string) => `${BASE}/files/${encodeURIComponent(id)}/thumbnail`,
previewUrl: (id: string) => `${BASE}/files/${encodeURIComponent(id)}/preview`,
};
-30
View File
@@ -1,30 +0,0 @@
import type { Folder, FolderPermission } from "../types/index.js";
import { del, get, patch, post, query } from "./apiClient.js";
export const folderService = {
folders: (parentId?: string | null) =>
get<{ parentId: string | null; folders: Folder[] }>(
`/folders${query({ parentId })}`,
),
createFolder: (name: string, parentId?: string | null) =>
post<{ folder: Folder }>("/folders", { name, parentId: parentId ?? null }),
updateFolder: (id: string, name: string) =>
patch<{ folder: Folder }>(`/folders/${encodeURIComponent(id)}`, { name }),
moveFolder: (id: string, parentId: string | null) =>
post<{ folder: Folder }>(`/folders/${encodeURIComponent(id)}/move`, { parentId }),
deleteFolder: (id: string) => del<{ ok: boolean }>(`/folders/${encodeURIComponent(id)}`),
folderPermissions: (id: string) =>
get<{ permissions: FolderPermission[] }>(
`/folders/${encodeURIComponent(id)}/permissions`,
),
grantPermission: (id: string, email: string, level: string, expiresAt: string | null) =>
post<{ ok: boolean }>(`/folders/${encodeURIComponent(id)}/permissions`, {
email,
level,
expiresAt,
}),
revokePermission: (id: string, userId: string) =>
del<{ ok: boolean }>(
`/folders/${encodeURIComponent(id)}/permissions/${encodeURIComponent(userId)}`,
),
};
-9
View File
@@ -1,9 +0,0 @@
import type { MediaItem } from "../types/index.js";
import { get, query } from "./apiClient.js";
export const mediaService = {
gallery: (kind: string, limit = 60, offset = 0) =>
get<{ kind: string | null; items: MediaItem[] }>(
`/media${query({ kind, limit, offset })}`,
),
};
-7
View File
@@ -1,7 +0,0 @@
import type { Folder, UploadedFile } from "../types/index.js";
import { get, query } from "./apiClient.js";
export const searchService = {
search: (q: string) =>
get<{ query: string; folders: Folder[]; files: UploadedFile[] }>(`/search${query({ q })}`),
};
-14
View File
@@ -1,14 +0,0 @@
import type { TrashFile, TrashFolder } from "../types/index.js";
import { del, get, post } from "./apiClient.js";
export const trashService = {
trash: () =>
get<{ retentionDays: number; folders: TrashFolder[]; files: TrashFile[] }>("/trash"),
restoreFolder: (id: string) =>
post<{ ok: boolean }>(`/trash/folders/${encodeURIComponent(id)}/restore`),
restoreFile: (id: string) =>
post<{ ok: boolean }>(`/trash/files/${encodeURIComponent(id)}/restore`),
purgeFolder: (id: string) => del<{ ok: boolean }>(`/trash/folders/${encodeURIComponent(id)}`),
purgeFile: (id: string) => del<{ ok: boolean }>(`/trash/files/${encodeURIComponent(id)}`),
emptyTrash: () => del<{ ok: boolean }>("/trash"),
};

Some files were not shown because too many files have changed in this diff Show More