feat(ui): glass layout, icon actions and new icon set (#21)
CD — Deployment / deploy (push) Successful in 33s
CD — Deployment / deploy (push) Successful in 33s
PR automatique de feat/ui-glass-layout-icons vers main. --------- Co-authored-by: xEsiah <[email protected]> Reviewed-on: #21 Reviewed-by: Esiah <[email protected]> Co-authored-by: Gitea Actions <-[email protected]>
This commit was merged in pull request #21.
This commit is contained in:
+16
-3
@@ -25,13 +25,13 @@ void startService({
|
||||
registerAuthRoutes(app, db, config);
|
||||
registerAccountRoutes(app, db, config);
|
||||
registerChatRoutes(app, db, config);
|
||||
registerDirectoryRoutes(app, db);
|
||||
registerDirectoryRoutes(app, db, config);
|
||||
registerFolderRoutes(app, db, config);
|
||||
registerFileRoutes(app, db, config);
|
||||
registerUploadRoutes(app, db, config);
|
||||
registerMediaRoutes(app, db);
|
||||
registerMediaRoutes(app, db, config);
|
||||
registerTrashRoutes(app, db, config);
|
||||
registerSearchRoutes(app, db);
|
||||
registerSearchRoutes(app, db, config);
|
||||
registerAdminRoutes(app, db, config);
|
||||
},
|
||||
onReady: async ({ db, config, logger }) => {
|
||||
@@ -48,5 +48,18 @@ void startService({
|
||||
logger.error("purge des envois inacheves", { error: String(error) }),
|
||||
);
|
||||
}, 60 * 60 * 1000).unref();
|
||||
|
||||
// Sessions expirees et corbeille hors retention : sans ce balayage, elles
|
||||
// ne disparaissent qu'au redemarrage. Les jetons expires sont deja refuses
|
||||
// a chaque requete ; il s'agit ici d'eviter une table qui grossit sans fin
|
||||
// et de faire respecter la retention de la corbeille sans redemarrage.
|
||||
setInterval(() => {
|
||||
void purgeExpiredSessions(db).catch((error: unknown) =>
|
||||
logger.error("purge des sessions expirees", { error: String(error) }),
|
||||
);
|
||||
void purgeExpiredTrash(db, config).catch((error: unknown) =>
|
||||
logger.error("purge de la corbeille", { error: String(error) }),
|
||||
);
|
||||
}, 60 * 60 * 1000).unref();
|
||||
},
|
||||
});
|
||||
|
||||
+50
-12
@@ -1,4 +1,11 @@
|
||||
import { createHash, randomBytes, randomUUID, scrypt as scryptCallback, timingSafeEqual } from "node:crypto";
|
||||
import {
|
||||
createHash,
|
||||
createHmac,
|
||||
randomBytes,
|
||||
randomUUID,
|
||||
scrypt as scryptCallback,
|
||||
timingSafeEqual,
|
||||
} from "node:crypto";
|
||||
import { promisify } from "node:util";
|
||||
import type { Context, Next } from "hono";
|
||||
import { getCookie, setCookie, deleteCookie } from "hono/cookie";
|
||||
@@ -48,6 +55,17 @@ export const verifyPassword = async (password: string, stored: string): Promise<
|
||||
|
||||
export const sha256 = (value: string): string => createHash("sha256").update(value).digest("hex");
|
||||
|
||||
/**
|
||||
* Empreinte du jeton de session : SHA-256 poivre par SESSION_SECRET.
|
||||
*
|
||||
* Sans ce poivre, une ecriture frauduleuse dans `user_sessions` suffirait a
|
||||
* forger une session : l'attaquant connaitrait le hachage a poser. Le secret
|
||||
* vit hors de la base, donc une fuite de la base seule ne donne aucune session
|
||||
* ouvrable.
|
||||
*/
|
||||
export const sessionTokenHash = (token: string, secret: string): string =>
|
||||
createHmac("sha256", secret).update(token).digest("hex");
|
||||
|
||||
/**
|
||||
* Portrait de l'utilisateur porte par la session.
|
||||
*
|
||||
@@ -74,15 +92,17 @@ export interface SessionMeta {
|
||||
export const SESSION_COOKIE = "cohaise_session";
|
||||
|
||||
/**
|
||||
* Le jeton brut part dans le cookie, son empreinte SHA-256 dans la base.
|
||||
* Une copie de la base ne donne donc aucune session ouvrable : il faudrait
|
||||
* en plus la table des cookies, qui n'existe pas.
|
||||
* Le jeton brut part dans le cookie, son empreinte HMAC-SHA-256 (poivree par
|
||||
* SESSION_SECRET) dans la base. Une copie de la base ne donne donc aucune
|
||||
* session ouvrable : il faudrait en plus la table des cookies, qui n'existe pas,
|
||||
* et le secret, qui vit hors de la base.
|
||||
*/
|
||||
export const createSession = async (
|
||||
db: Db,
|
||||
userId: string,
|
||||
meta: SessionMeta,
|
||||
ttlHours: number,
|
||||
secret: string,
|
||||
): Promise<{ token: string; expiresAt: Date }> => {
|
||||
const token = randomBytes(32).toString("base64url");
|
||||
const expiresAt = new Date(Date.now() + ttlHours * 3600_000);
|
||||
@@ -93,7 +113,7 @@ export const createSession = async (
|
||||
[
|
||||
randomUUID(),
|
||||
userId,
|
||||
sha256(token),
|
||||
sessionTokenHash(token, secret),
|
||||
meta.ipAddress ?? null,
|
||||
meta.userAgent?.slice(0, 255) ?? null,
|
||||
expiresAt,
|
||||
@@ -102,7 +122,11 @@ export const createSession = async (
|
||||
return { token, expiresAt };
|
||||
};
|
||||
|
||||
export const resolveSession = async (db: Db, token: string): Promise<SessionUser | null> => {
|
||||
export const resolveSession = async (
|
||||
db: Db,
|
||||
token: string,
|
||||
secret: string,
|
||||
): Promise<SessionUser | null> => {
|
||||
const row = await db.one<SessionUser & { last_seen_at: string }>(
|
||||
`SELECT u.id, u.email, u.first_name, u.last_name,
|
||||
r.slug AS role_slug, r.name AS role_name,
|
||||
@@ -116,20 +140,20 @@ export const resolveSession = async (db: Db, token: string): Promise<SessionUser
|
||||
AND s.expires_at > UTC_TIMESTAMP()
|
||||
AND u.deleted_at IS NULL
|
||||
AND u.is_active = 1`,
|
||||
[sha256(token)],
|
||||
[sessionTokenHash(token, secret)],
|
||||
);
|
||||
if (!row) return null;
|
||||
// Etat vu, avec un decalage de 60 s pour ne pas ecrire a chaque requete.
|
||||
await db.exec(
|
||||
"UPDATE user_sessions SET last_seen_at = UTC_TIMESTAMP() WHERE token_hash = ? AND last_seen_at < UTC_TIMESTAMP(3) - INTERVAL 60 SECOND",
|
||||
[sha256(token)],
|
||||
[sessionTokenHash(token, secret)],
|
||||
);
|
||||
return row;
|
||||
};
|
||||
|
||||
export const revokeSession = async (db: Db, token: string): Promise<void> => {
|
||||
export const revokeSession = async (db: Db, token: string, secret: string): Promise<void> => {
|
||||
await db.exec("UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE token_hash = ?", [
|
||||
sha256(token),
|
||||
sessionTokenHash(token, secret),
|
||||
]);
|
||||
};
|
||||
|
||||
@@ -183,11 +207,11 @@ export interface AuthState {
|
||||
|
||||
/** Lit le cookie et attache l'utilisateur, sans exiger qu'il existe. */
|
||||
export const attachUser =
|
||||
(db: Db) =>
|
||||
(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);
|
||||
const user = await resolveSession(db, token, secret);
|
||||
if (user) {
|
||||
context.set("user", user);
|
||||
context.set("token", token);
|
||||
@@ -198,9 +222,23 @@ export const attachUser =
|
||||
await next();
|
||||
};
|
||||
|
||||
/**
|
||||
* Routes encore accessibles lorsqu'un changement de mot de passe est impose :
|
||||
* lire son profil, changer le mot de passe, se deconnecter. Tout le reste est
|
||||
* refuse cote serveur, et pas seulement par la redirection du client.
|
||||
*/
|
||||
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();
|
||||
};
|
||||
|
||||
|
||||
@@ -75,6 +75,62 @@ export const clientIp = (context: Context, trustProxy: boolean): string | null =
|
||||
return address ? address.slice(0, 45) : null;
|
||||
};
|
||||
|
||||
/** Taille maximale d'un corps JSON. Les envois de fichiers ont leur propre flux borne. */
|
||||
export const JSON_BODY_MAX_BYTES = 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Lit le corps de la requete en memoire, avec une borne dure sur les octets
|
||||
* reellement recus. `content-length` est verifie d'abord pour refuser tot, mais
|
||||
* la lecture bornee est la vraie garantie : un client peut mentir sur l'en-tete
|
||||
* et envoyer davantage que ce qu'il annonce.
|
||||
*/
|
||||
export const readBodyCapped = async (context: Context, maxBytes: number): Promise<Buffer> => {
|
||||
const declared = Number(context.req.header("content-length") ?? "");
|
||||
if (Number.isFinite(declared) && declared > maxBytes) {
|
||||
throw AppError.payloadTooLarge("Corps de requete trop volumineux.");
|
||||
}
|
||||
|
||||
const body = context.req.raw.body;
|
||||
if (body === null) return Buffer.alloc(0);
|
||||
|
||||
const chunks: Uint8Array[] = [];
|
||||
let received = 0;
|
||||
const reader = body.getReader();
|
||||
try {
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
received += value.byteLength;
|
||||
if (received > maxBytes) {
|
||||
await reader.cancel().catch(() => undefined);
|
||||
throw AppError.payloadTooLarge("Corps de requete trop volumineux.");
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
return Buffer.concat(chunks);
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse le corps JSON avec la meme borne. Un corps absent ou illisible rend
|
||||
* `null`, comme l'ancien `req.json().catch(() => null)` : les routes continuent
|
||||
* de repondre par leur validation zod habituelle.
|
||||
*/
|
||||
export const readJson = async (
|
||||
context: Context,
|
||||
maxBytes = JSON_BODY_MAX_BYTES,
|
||||
): Promise<unknown> => {
|
||||
const buffer = await readBodyCapped(context, maxBytes);
|
||||
if (buffer.byteLength === 0) return null;
|
||||
try {
|
||||
return JSON.parse(buffer.toString("utf8")) as unknown;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/** Dependances remises aux routes metier au montage. */
|
||||
export interface RouteDeps {
|
||||
db: Db;
|
||||
|
||||
@@ -11,6 +11,9 @@ export {
|
||||
createApp,
|
||||
createLogger,
|
||||
clientIp,
|
||||
JSON_BODY_MAX_BYTES,
|
||||
readBodyCapped,
|
||||
readJson,
|
||||
type App,
|
||||
type AppEnv,
|
||||
type AppOptions,
|
||||
@@ -29,6 +32,7 @@ export {
|
||||
purgeExpiredSessions,
|
||||
revokeSession,
|
||||
SESSION_COOKIE,
|
||||
sessionTokenHash,
|
||||
setSessionCookie,
|
||||
sha256,
|
||||
verifyPassword,
|
||||
|
||||
+12
-1
@@ -48,6 +48,17 @@ export const classify = (mime: string | null): MediaKind => {
|
||||
export const isImage = (mime: string | null): boolean =>
|
||||
(mime ?? "").toLowerCase().startsWith("image/");
|
||||
|
||||
/**
|
||||
* Le SVG est une image au sens MIME, mais pas une image sure a decoder :
|
||||
* librsvg peut resolvere des references externes et son moteur est une surface
|
||||
* d'attaque supplementaire. Il est deja exclu de l'apercu en ligne ; on ne le
|
||||
* passe pas non plus a sharp pour la vignette. Le fichier reste telechargeable.
|
||||
*/
|
||||
const isRasterImage = (mime: string | null): boolean => {
|
||||
const value = (mime ?? "").toLowerCase();
|
||||
return value.startsWith("image/") && value !== "image/svg+xml";
|
||||
};
|
||||
|
||||
export const thumbnailRelativePath = (fileId: string): string =>
|
||||
path.posix.join("thumbnails", `${fileId}.webp`);
|
||||
|
||||
@@ -99,7 +110,7 @@ export const indexMedia = async (
|
||||
): Promise<void> => {
|
||||
const kind = classify(mimeType);
|
||||
|
||||
if (!isImage(mimeType)) {
|
||||
if (!isRasterImage(mimeType)) {
|
||||
await db.exec(
|
||||
`INSERT INTO media_metadata (file_id, kind) VALUES (?, ?)
|
||||
ON DUPLICATE KEY UPDATE kind = VALUES(kind)`,
|
||||
|
||||
@@ -15,8 +15,11 @@ import {
|
||||
hashPassword,
|
||||
link,
|
||||
rateLimitKey,
|
||||
readBodyCapped,
|
||||
readJson,
|
||||
renderMail,
|
||||
requireAuth,
|
||||
sessionTokenHash,
|
||||
sha256,
|
||||
verifyPassword,
|
||||
type App,
|
||||
@@ -69,8 +72,8 @@ const emailChangeInput = z.object({
|
||||
});
|
||||
|
||||
export const registerAccountRoutes = (app: App, db: Db, config: Config): void => {
|
||||
app.use("/api/cloud/account/*", attachUser(db));
|
||||
app.use("/api/cloud/account", attachUser(db));
|
||||
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);
|
||||
@@ -85,7 +88,7 @@ export const registerAccountRoutes = (app: App, db: Db, config: Config): void =>
|
||||
|
||||
app.patch("/api/cloud/account/profile", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const data = parse(profileInput, await context.req.json().catch(() => null));
|
||||
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,
|
||||
@@ -107,7 +110,7 @@ export const registerAccountRoutes = (app: App, db: Db, config: Config): void =>
|
||||
|
||||
app.patch("/api/cloud/account/preferences", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const data = parse(preferencesInput, await context.req.json().catch(() => null));
|
||||
const data = parse(preferencesInput, await readJson(context));
|
||||
await db.exec("UPDATE users SET theme = ?, language = ? WHERE id = ?", [
|
||||
data.theme,
|
||||
data.language,
|
||||
@@ -118,7 +121,7 @@ export const registerAccountRoutes = (app: App, db: Db, config: Config): void =>
|
||||
|
||||
app.get("/api/cloud/account/sessions", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const current = sha256(context.get("token") ?? "");
|
||||
const current = sessionTokenHash(context.get("token") ?? "", config.SESSION_SECRET);
|
||||
const rows = await db.query<{
|
||||
id: string;
|
||||
token_hash: string;
|
||||
@@ -160,7 +163,7 @@ export const registerAccountRoutes = (app: App, db: Db, config: Config): void =>
|
||||
|
||||
app.delete("/api/cloud/account/sessions", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const current = sha256(context.get("token") ?? "");
|
||||
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],
|
||||
@@ -178,7 +181,7 @@ export const registerAccountRoutes = (app: App, db: Db, config: Config): void =>
|
||||
throw AppError.payloadTooLarge("L'image ne doit pas depasser 8 Mo.");
|
||||
}
|
||||
|
||||
const source = Buffer.from(await context.req.arrayBuffer());
|
||||
const source = await readBodyCapped(context, AVATAR_MAX_BYTES);
|
||||
let processed: Buffer;
|
||||
try {
|
||||
processed = await sharp(source, { failOn: "none" })
|
||||
@@ -274,7 +277,7 @@ export const registerAccountRoutes = (app: App, db: Db, config: Config): void =>
|
||||
});
|
||||
|
||||
app.post("/api/cloud/account/forgot-password", async (context) => {
|
||||
const data = parse(forgotInput, await context.req.json().catch(() => null));
|
||||
const data = parse(forgotInput, await readJson(context));
|
||||
throttle(context, `forgot:${data.email.toLowerCase()}`);
|
||||
|
||||
const user = await db.one<{ id: string; email: string }>(
|
||||
@@ -312,7 +315,7 @@ export const registerAccountRoutes = (app: App, db: Db, config: Config): void =>
|
||||
});
|
||||
|
||||
app.post("/api/cloud/account/reset-password", async (context) => {
|
||||
const data = parse(resetInput, await context.req.json().catch(() => null));
|
||||
const data = parse(resetInput, await readJson(context));
|
||||
throttle(context, "reset");
|
||||
|
||||
const row = await db.one<{ id: string; user_id: string }>(
|
||||
@@ -362,7 +365,7 @@ export const registerAccountRoutes = (app: App, db: Db, config: Config): void =>
|
||||
|
||||
app.post("/api/cloud/account/email-change", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const data = parse(emailChangeInput, await context.req.json().catch(() => null));
|
||||
const data = parse(emailChangeInput, await readJson(context));
|
||||
throttle(context, `email:${user.id}`);
|
||||
|
||||
const row = await db.one<{ password_hash: string }>(
|
||||
@@ -419,7 +422,7 @@ export const registerAccountRoutes = (app: App, db: Db, config: Config): void =>
|
||||
app.post("/api/cloud/account/email-change/confirm", async (context) => {
|
||||
const data = parse(
|
||||
z.object({ token: z.string().min(10).max(400) }),
|
||||
await context.req.json().catch(() => null),
|
||||
await readJson(context),
|
||||
);
|
||||
|
||||
const row = await db.one<{ id: string; user_id: string; new_email: string }>(
|
||||
|
||||
+11
-10
@@ -1,4 +1,4 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { randomInt, randomUUID } from "node:crypto";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
AppError,
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
link,
|
||||
renderMail,
|
||||
requireAuth,
|
||||
readJson,
|
||||
type App,
|
||||
type Config,
|
||||
type Db,
|
||||
@@ -116,10 +117,10 @@ const humanBytes = (bytes: number): string => {
|
||||
/** Mot de passe aleatoire, lisible a la frappe, sans caractere ambigu. */
|
||||
const generatePasswordValue = (): string => {
|
||||
const alphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
||||
const bytes = new Uint8Array(18);
|
||||
globalThis.crypto.getRandomValues(bytes);
|
||||
// randomInt borne directement l'intervalle : pas de biais modulo, contrairement
|
||||
// a `octet % longueur` qui favorise les premiers caracteres de l'alphabet.
|
||||
let out = "";
|
||||
for (const byte of bytes) out += alphabet[byte % alphabet.length];
|
||||
for (let index = 0; index < 18; index += 1) out += alphabet[randomInt(alphabet.length)];
|
||||
return out;
|
||||
};
|
||||
|
||||
@@ -208,8 +209,8 @@ const rehomeUserFolders = async (db: Db, userId: string): Promise<{ kept: number
|
||||
};
|
||||
|
||||
export const registerAdminRoutes = (app: App, db: Db, config: Config): void => {
|
||||
app.use("/api/cloud/admin/*", attachUser(db));
|
||||
app.use("/api/cloud/admin", attachUser(db));
|
||||
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);
|
||||
|
||||
@@ -285,7 +286,7 @@ export const registerAdminRoutes = (app: App, db: Db, config: Config): void => {
|
||||
|
||||
app.post("/api/cloud/admin/users", requireAuth, async (context) => {
|
||||
requireAdmin(context);
|
||||
const data = parse(createUserSchema, await context.req.json().catch(() => null));
|
||||
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.");
|
||||
@@ -339,7 +340,7 @@ export const registerAdminRoutes = (app: App, db: Db, config: Config): void => {
|
||||
const existing = await db.one<AdminUserRow>(`${SELECT_USER} WHERE u.id = ? AND u.deleted_at IS NULL`, [id]);
|
||||
if (!existing) throw AppError.notFound("Compte introuvable.");
|
||||
|
||||
const data = parse(updateUserSchema, await context.req.json().catch(() => null));
|
||||
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]);
|
||||
@@ -465,7 +466,7 @@ export const registerAdminRoutes = (app: App, db: Db, config: Config): void => {
|
||||
|
||||
app.post("/api/cloud/admin/storage-locations", requireAuth, async (context) => {
|
||||
requireAdmin(context);
|
||||
const data = parse(createLocationSchema, await context.req.json().catch(() => null));
|
||||
const data = parse(createLocationSchema, await readJson(context));
|
||||
if (data.quota_bytes !== undefined && data.quota_bytes !== null) {
|
||||
await assertQuotaFits(data.quota_bytes);
|
||||
}
|
||||
@@ -488,7 +489,7 @@ export const registerAdminRoutes = (app: App, db: Db, config: Config): void => {
|
||||
requireAdmin(context);
|
||||
const id = Number(context.req.param("id"));
|
||||
if (!Number.isInteger(id) || id <= 0) throw AppError.notFound("Emplacement introuvable.");
|
||||
const data = parse(updateLocationSchema, await context.req.json().catch(() => null));
|
||||
const 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",
|
||||
|
||||
@@ -10,10 +10,11 @@ import {
|
||||
hashPassword,
|
||||
isHttpsRequest,
|
||||
rateLimitKey,
|
||||
readJson,
|
||||
requireAuth,
|
||||
revokeSession,
|
||||
sessionTokenHash,
|
||||
setSessionCookie,
|
||||
sha256,
|
||||
verifyPassword,
|
||||
type App,
|
||||
type Config,
|
||||
@@ -87,7 +88,7 @@ export const registerAuthRoutes = (app: App, db: Db, config: Config): void => {
|
||||
context.header("cache-control", "no-store");
|
||||
});
|
||||
|
||||
app.use("/api/cloud/*", attachUser(db));
|
||||
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) => {
|
||||
@@ -98,7 +99,7 @@ export const registerAuthRoutes = (app: App, db: Db, config: Config): void => {
|
||||
throw AppError.unprocessable("Trop de tentatives de connexion. Reessayez dans une minute.");
|
||||
}
|
||||
|
||||
const parsed = credentials.safeParse(await context.req.json().catch(() => null));
|
||||
const parsed = credentials.safeParse(await readJson(context));
|
||||
if (!parsed.success) throw AppError.badRequest("Identifiants invalides.");
|
||||
|
||||
const { email, password } = parsed.data;
|
||||
@@ -120,6 +121,7 @@ export const registerAuthRoutes = (app: App, db: Db, config: Config): void => {
|
||||
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]);
|
||||
@@ -135,7 +137,7 @@ export const registerAuthRoutes = (app: App, db: Db, config: Config): void => {
|
||||
|
||||
app.post("/api/cloud/auth/logout", requireAuth, async (context) => {
|
||||
const token = context.get("token");
|
||||
if (token) await revokeSession(db, token);
|
||||
if (token) await revokeSession(db, token, config.SESSION_SECRET);
|
||||
clearSessionCookie(context);
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
@@ -159,7 +161,7 @@ export const registerAuthRoutes = (app: App, db: Db, config: Config): void => {
|
||||
*/
|
||||
app.post("/api/cloud/auth/change-password", requireAuth, async (context) => {
|
||||
const session = currentUser(context);
|
||||
const parsed = changePassword.safeParse(await context.req.json().catch(() => null));
|
||||
const parsed = changePassword.safeParse(await readJson(context));
|
||||
if (!parsed.success) {
|
||||
throw AppError.badRequest("Le nouveau mot de passe doit contenir au moins 8 caracteres.");
|
||||
}
|
||||
@@ -189,7 +191,7 @@ export const registerAuthRoutes = (app: App, db: Db, config: Config): void => {
|
||||
`UPDATE user_sessions
|
||||
SET revoked_at = UTC_TIMESTAMP()
|
||||
WHERE user_id = ? AND revoked_at IS NULL AND token_hash <> ?`,
|
||||
[session.id, sha256(context.get("token") ?? "")],
|
||||
[session.id, sessionTokenHash(context.get("token") ?? "", config.SESSION_SECRET)],
|
||||
);
|
||||
|
||||
return context.json({ ok: true });
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
AppError,
|
||||
createRateLimiter,
|
||||
currentUser,
|
||||
readJson,
|
||||
requireAuth,
|
||||
type App,
|
||||
type Config,
|
||||
@@ -258,7 +259,7 @@ export const registerChatRoutes = (app: App, db: Db, config: Config): void => {
|
||||
if (!limiter.allow(user.id)) {
|
||||
throw AppError.unprocessable("Vous envoyez des messages trop rapidement.");
|
||||
}
|
||||
const parsed = sendInput.safeParse(await context.req.json().catch(() => null));
|
||||
const parsed = sendInput.safeParse(await readJson(context));
|
||||
if (!parsed.success) {
|
||||
throw AppError.badRequest(parsed.error.issues[0]?.message ?? "Message invalide.");
|
||||
}
|
||||
@@ -292,7 +293,7 @@ export const registerChatRoutes = (app: App, db: Db, config: Config): void => {
|
||||
throw AppError.unprocessable("Vous envoyez des messages trop rapidement.");
|
||||
}
|
||||
|
||||
const parsed = editInput.safeParse(await context.req.json().catch(() => null));
|
||||
const parsed = editInput.safeParse(await readJson(context));
|
||||
if (!parsed.success) {
|
||||
throw AppError.badRequest(parsed.error.issues[0]?.message ?? "Message invalide.");
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
currentUser,
|
||||
requireAuth,
|
||||
type App,
|
||||
type Config,
|
||||
type Db,
|
||||
} from "../lib/index.js";
|
||||
|
||||
@@ -11,8 +12,8 @@ import {
|
||||
* destinataire lors d'un partage. La session courante est exclue : on ne se
|
||||
* partage pas un dossier a soi-meme. Aucune donnee sensible n'est exposee.
|
||||
*/
|
||||
export const registerDirectoryRoutes = (app: App, db: Db): void => {
|
||||
app.use("/api/cloud/directory", attachUser(db));
|
||||
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);
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
currentUser,
|
||||
requireAuth,
|
||||
requireRole,
|
||||
readJson,
|
||||
type App,
|
||||
type Config,
|
||||
type Db,
|
||||
@@ -206,8 +207,8 @@ const serveFile = ({ absolute, size, mime, disposition, range }: ServeOptions):
|
||||
};
|
||||
|
||||
export const registerFileRoutes = (app: App, db: Db, config: Config): void => {
|
||||
app.use("/api/cloud/files/*", attachUser(db));
|
||||
app.use("/api/cloud/files", attachUser(db));
|
||||
app.use("/api/cloud/files/*", attachUser(db, config.SESSION_SECRET));
|
||||
app.use("/api/cloud/files", attachUser(db, config.SESSION_SECRET));
|
||||
|
||||
/**
|
||||
* Depot en un seul passage. Le corps n'est pas un formulaire multipart mais
|
||||
@@ -589,7 +590,7 @@ export const registerFileRoutes = (app: App, db: Db, config: Config): void => {
|
||||
(row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id)));
|
||||
if (!permitted) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
const { name: rawName } = parse(renameInput, await context.req.json().catch(() => null));
|
||||
const { name: rawName } = parse(renameInput, await readJson(context));
|
||||
const name = assertName(rawName);
|
||||
|
||||
try {
|
||||
@@ -624,7 +625,7 @@ export const registerFileRoutes = (app: App, db: Db, config: Config): void => {
|
||||
(row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id)));
|
||||
if (!canLeave) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
const { folderId } = parse(moveInput, await context.req.json().catch(() => null));
|
||||
const { folderId } = parse(moveInput, await readJson(context));
|
||||
const destination = folderId ?? null;
|
||||
|
||||
if (destination !== null && !(await canWrite(db, user, destination))) {
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
currentUser,
|
||||
requireAuth,
|
||||
requireRole,
|
||||
readJson,
|
||||
type App,
|
||||
type Config,
|
||||
type Db,
|
||||
@@ -102,8 +103,8 @@ const subtreeIds = async (db: Db, rootId: string): Promise<string[]> => {
|
||||
};
|
||||
|
||||
export const registerFolderRoutes = (app: App, db: Db, config: Config): void => {
|
||||
app.use("/api/cloud/folders/*", attachUser(db));
|
||||
app.use("/api/cloud/folders", attachUser(db));
|
||||
app.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);
|
||||
@@ -149,7 +150,7 @@ export const registerFolderRoutes = (app: App, db: Db, config: Config): void =>
|
||||
const user = currentUser(context);
|
||||
const { name: rawName, parentId } = parse(
|
||||
createFolder,
|
||||
await context.req.json().catch(() => null),
|
||||
await readJson(context),
|
||||
);
|
||||
const name = assertName(rawName);
|
||||
|
||||
@@ -222,7 +223,7 @@ export const registerFolderRoutes = (app: App, db: Db, config: Config): void =>
|
||||
if (!existing) throw AppError.notFound("Dossier introuvable.");
|
||||
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
const data = parse(updateFolder, await context.req.json().catch(() => null));
|
||||
const data = parse(updateFolder, await readJson(context));
|
||||
const name = assertName(data.name);
|
||||
|
||||
try {
|
||||
@@ -249,7 +250,7 @@ export const registerFolderRoutes = (app: App, db: Db, config: Config): void =>
|
||||
if (existing.is_system === 1) throw AppError.forbidden("Le dossier public ne peut pas etre deplace.");
|
||||
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
const { parentId } = parse(moveFolder, await context.req.json().catch(() => null));
|
||||
const { parentId } = parse(moveFolder, await readJson(context));
|
||||
|
||||
if (parentId !== null && parentId !== undefined) {
|
||||
if (!(await canWrite(db, user, parentId))) {
|
||||
@@ -350,7 +351,7 @@ export const registerFolderRoutes = (app: App, db: Db, config: Config): void =>
|
||||
|
||||
const { email, level, expiresAt } = parse(
|
||||
permissionInput,
|
||||
await context.req.json().catch(() => null),
|
||||
await readJson(context),
|
||||
);
|
||||
|
||||
const target = await db.one<{ id: string }>(
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
currentUser,
|
||||
requireAuth,
|
||||
type App,
|
||||
type Config,
|
||||
type Db,
|
||||
} from "../lib/index.js";
|
||||
|
||||
@@ -15,8 +16,8 @@ import {
|
||||
|
||||
const KINDS = ["image", "video", "audio", "document", "archive", "other"] as const;
|
||||
|
||||
export const registerMediaRoutes = (app: App, db: Db): void => {
|
||||
app.use("/api/cloud/media", attachUser(db));
|
||||
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);
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
currentUser,
|
||||
requireAuth,
|
||||
type App,
|
||||
type Config,
|
||||
type Db,
|
||||
} from "../lib/index.js";
|
||||
|
||||
@@ -19,8 +20,8 @@ const escapeLike = (value: string): string =>
|
||||
|
||||
const LIMIT = 100;
|
||||
|
||||
export const registerSearchRoutes = (app: App, db: Db): void => {
|
||||
app.use("/api/cloud/search", attachUser(db));
|
||||
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);
|
||||
|
||||
@@ -158,8 +158,8 @@ const publicFolder = (row: TrashFolderRow) => ({
|
||||
});
|
||||
|
||||
export const registerTrashRoutes = (app: App, db: Db, config: Config): void => {
|
||||
app.use("/api/cloud/trash/*", attachUser(db));
|
||||
app.use("/api/cloud/trash", attachUser(db));
|
||||
app.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);
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
currentUser,
|
||||
requireAuth,
|
||||
requireRole,
|
||||
readJson,
|
||||
type App,
|
||||
type Config,
|
||||
type Db,
|
||||
@@ -143,8 +144,8 @@ const assertNameFree = async (
|
||||
};
|
||||
|
||||
export const registerUploadRoutes = (app: App, db: Db, config: Config): void => {
|
||||
app.use("/api/cloud/uploads/*", attachUser(db));
|
||||
app.use("/api/cloud/uploads", attachUser(db));
|
||||
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",
|
||||
@@ -152,7 +153,7 @@ export const registerUploadRoutes = (app: App, db: Db, config: Config): void =>
|
||||
requireRole("admin", "user"),
|
||||
async (context) => {
|
||||
const user = currentUser(context);
|
||||
const data = parse(createInput, await context.req.json().catch(() => null));
|
||||
const data = parse(createInput, await readJson(context));
|
||||
const name = assertName(data.name);
|
||||
const folderId = data.folderId ?? null;
|
||||
const size = data.size;
|
||||
|
||||
Reference in New Issue
Block a user