chore: initial import of CoHaiSe Cloud
PR — Ouverture automatique / create-pr (push) Failing after 1s

Standalone files & media application: React/Vite frontend with the @cohaise/ui design system, Hono + MariaDB backend, nginx reverse proxy, Docker Compose stack, migrations 000-006, and project docs.

Adds Gitea Actions workflows for deployment, automatic pull requests, and Renovate dependency updates.
This commit is contained in:
2026-10-14 15:24:06 +02:00
commit cc397e96d8
113 changed files with 12678 additions and 0 deletions
+207
View File
@@ -0,0 +1,207 @@
# Cloud — modèle de données
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** : 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).
## Modèle de données
```mermaid
erDiagram
roles ||--o{ users : "attribue"
users ||--o{ user_sessions : "ouvre"
users ||--o{ user_avatars : "a pour photo"
users ||--o{ password_reset_tokens : "demande"
users ||--o{ email_change_requests : "demande"
users ||--o{ folders : "proprietaire"
users ||--o{ files : "proprietaire"
users ||--o{ folder_permissions : "beneficie"
users ||--o{ audit_logs : "trace"
storage_locations ||--o{ folders : "contient"
storage_locations ||--o{ files : "contient"
storage_locations ||--o{ user_avatars : "contient"
folders ||--o{ folders : "parent de"
folders ||--o{ files : "contient"
folders ||--o{ folder_permissions : "accede"
files ||--o{ media_metadata : "decrit"
files ||--o{ file_variants : "derive"
```
## Tables
15 tables en base après `005` (`share_links` ayant été supprimée par `004`).
Seules celles marquées « `/…` » sont atteignables depuis le front.
| Table | Rôle | Exposée par l'API |
|---|---|---|
| `roles` | `admin` et `user` (le `readonly` de `002` a été retiré par `004`) | indirectement (`users.role_slug`) |
| `users` | Comptes : prénom, nom, e-mail, mot de passe, quotas | `/auth/*` |
| `user_sessions` | Appareils connectés, révocation, expiration | session interne |
| `user_avatars` | Photo de profil, une ligne par compte | non |
| `password_reset_tokens` | Réinitialisation de mot de passe, hachée | non (aucune route) |
| `email_change_requests` | Validation du nouvel e-mail d'un compte | non (aucune route) |
| `storage_locations` | Volumes de stockage et quotas globaux | non (interne à `storage.ts`) |
| `folders` | Arborescence, avec `access_type` | `/folders` |
| `folder_permissions` | Droits nominatifs sur un dossier `shared` | non (aucune route) |
| `files` | Métadonnées de l'original, jamais ré-écrit | `/files` |
| `media_metadata` | Dimensions, durée, codecs, EXIF, couleur dominante | non (galerie non exposée) |
| `file_variants` | Miniatures et aperçus WebP dérivés | non |
| `settings` | Configuration clé-valeur | non |
| `audit_logs` | Piste d'audit | non (écrit par `audit()`) |
| `schema_migrations` | Versions appliquées | non |
## Trois notions à ne pas confondre
| Notion | Où elle vit | Ce que c'est |
|---|---|---|
| Le fichier | le disque | les octets d'origine, jamais ré-encodés |
| La ligne `files` | la base | le nom, la taille, la somme de contrôle, le chemin |
| La ligne `media_metadata` | la base | ce qu'un lecteur sait du fichier : dimensions, durée, appareil |
Un fichier dénué de `media_metadata` reste valide : un PDF ou un ZIP n'ont pas
de dimensions. C'est le comportement voulu, une entrée de galerie non encore
analysée doit rester listable.
## Originaux intacts, aperçus dérivés
Aucun fichier téléversé n'est ré-encodé. Le contenu reçu est écrit tel quel et
sa somme SHA-256 est mémorisée, ce qui sert à la fois de preuve d'intégrité et
de détection de doublon. Les WebP d'aperçu sont des fichiers **supplémentaires**
décrits par `file_variants`, avec un `purpose` valant `thumbnail` ou `preview` ;
un `UNIQUE` sur `(file_id, purpose)` interdit d'en empiler deux du même type.
La conséquence assumée : une photo contient ses coordonnées GPS, et puisqu'aucun
fichier n'est modifié, ces coordonnées restent lisibles dans l'original. Les
aperçus WebP sont ré-encodés et ne les portent pas.
## Trois types d'accès aux dossiers
`folders.access_type` porte l'intention, et non une garde :
| Valeur | Qui accède | Écriture |
|---|---|---|
| `private` | le propriétaire seul | le propriétaire |
| `shared` | le propriétaire et les comptes listés dans `folder_permissions` | selon le niveau `read`, `write` ou `admin` |
| `public` | tous les comptes de l'installation | tous peuvent ajouter, personne ne supprime les fichiers d'autrui |
Un seul dossier de l'instance porte `is_system = 1`, et l'unicité est réelle en
base : la colonne générée `system_marker` vaut `1` pour lui et `NULL` pour tous
les autres, donc un second dossier système viole `uq_folders_system`.
`chk_folders_system` impose en outre qu'un dossier système soit `public`.
Les dossiers enfants d'un dossier `public` restent soumis à l'unicité de nom :
deux enfants ne peuvent pas s'appeler pareil, puisque leur `parent_id` n'est pas
`NULL`. La limite ne concerne que la racine, dont les éléments ont
`parent_id IS NULL`.
Le niveau d'accès est **vérifié à chaque requête** en base, depuis la session :
voir [`../../docs/api.md`](../../docs/api.md).
## Budget et plafond par utilisateur
Deux réglages distincts, tous deux portés par `users` :
| Colonne | Effet |
|---|---|
| `quota_bytes` | volume total que le compte peut occuper, borné par `chk_users_quota` |
| `max_file_bytes` | taille maximale d'un dépôt unique |
`used_bytes` est maintenu par l'application et borné en base : impossible
d'écrire `used_bytes > quota_bytes`, quelle que soit la requête. Le quota est en
outre **re-vérifié en transaction** au moment de l'écriture. `max_file_bytes`, en
revanche, ne peut pas être garanti par une contrainte, car il compare une ligne
de `files` à une ligne d'`users` : c'est à l'application de le vérifier, sur la
taille déclarée et sur la taille réellement reçue.
`default_quota_bytes` et `max_upload_bytes` dans `settings` ne sont pas des
plafonds globaux, seulement les valeurs proposées à la création d'un compte.
## Unicité après suppression logique
Un nom ou une adresse peut être réutilisé après une suppression logique, grâce à
des colonnes générées :
```sql
active_email VARCHAR(255) GENERATED ALWAYS AS (IF(deleted_at IS NULL, email, NULL)) STORED,
UNIQUE KEY uq_users_email (active_email)
```
La ligne supprimée produit `NULL`, et en SQL plusieurs `NULL` ne sont pas
égaux : l'index ne la voit plus. C'est cette propriété qui sert deux fois, pour
libérer une adresse de compte et pour autoriser la réimportation d'un fichier au
même nom.
## Métadonnées : la part utile et le reste
Ce que la galerie filtre ou affiche est mis en colonnes indexées : `taken_at`,
`width`, `height`, `duration_ms`, `kind`, `video_codec`, `camera_make`,
`camera_model`, `dominant_color`. Le reste des EXIF, qui peut représenter une
trentaine de réglages d'objectif pour quelques kilo-octets et n'est jamais lu,
est facultatif et compressé dans `extra_metadata`. Rien n'oblige à le remplir.
## Chemin physique
Le nom affiché **n'entre jamais dans le chemin** : `${MEDIA_DIR}/<slug>/<uuid><ext>`,
avec `resolveInside()` qui refuse toute cible hors base. Le choix de
l'emplacement se fait parmi les `storage_locations` actifs, en privilégiant la
plus grande marge disponible.
## Migrations
| Fichier | Contenu |
|---|---|
| `000_schema_migrations.sql` | table de suivi des versions |
| `001_initial_schema.sql` | 11 tables, 17 clés étrangères, 14 `CHECK` |
| `002_reference_data.sql` | rôles, emplacement principal, réglages |
| `003_integrity_backstop.sql` | `CHECK` d'audit, interdiction du dossier parent de lui-même |
| `004_cloud_requirements.sql` | identité complète, sessions, validation d'e-mail, avatar, `access_type`, médias, variantes, budget par compte, suppression des liens publics |
| `005_storage_location_realign.sql` | `mount_path` réaligné sur `/data/media`, quota 400 Go, garde-fou sur les emplacements sans quota |
| `006_public_folder.sql` | crée le dossier système « Public », retire les réglages devenus morts |
`004` porte le passage d'un modèle de partage public vers un stockage privé :
elle supprime `share_links`, scinde `display_name` en `first_name` et
`last_name`, et remplace le plafond global `max_upload_bytes` par les deux
colonnes portées par `users`. Elle a aussi supprimé le rôle `readonly`, qui
venait d'une supposition et non d'un besoin formulé.
Une migration appliquée ne se modifie jamais : le checksum la fige. Voir
[`../../docs/deployment.md`](../../docs/deployment.md).
## Sécurité (couche modèle)
- Suppression d'un rôle encore attribué, ou d'un emplacement contenant des
données : refusée par la base (`ON DELETE RESTRICT`).
- Sessions et jetons stockés hachés en `CHAR(64)` ; `password_changed_at`
permet de dater un changement.
- Les identifiants de dossier et de fichier sont des UUID, non devinables.
- `audit_logs` survit à la suppression d'un utilisateur (`ON DELETE SET NULL`)
plus un instantané `user_email`, `ip_address`, `user_agent`.
En-têtes (CSP/HSTS), CORS et limitation de débit sont décrits dans
[`../../docs/security.md`](../../docs/security.md). Il n'y a **pas** de jeton
CSRF : les écritures sont des `POST`/`PUT`/`DELETE` et le cookie de session est
`SameSite=Lax`, ce qui bloque les écritures inter-origines.
## Limites actuelles
- **La règle « ne pas supprimer les fichiers d'autrui » n'est pas en base.**
Aucune contrainte SQL ne peut exprimer « le propriétaire ou un administrateur » :
elle ne vit que dans l'API, et une personne ouvrant un client SQL la contourne.
`audit_logs` est le seul rempart réel.
- **`max_file_bytes` n'est pas appliqué en base** (voir plus haut).
- **Les cycles profonds ne sont pas empêchés.** `chk_folders_not_self_parent`
bloque le parent direct de lui-même, mais `A → B → A` reste possible et demande
un parcours `WITH RECURSIVE` au moment d'un déplacement.
- **Deux éléments racine peuvent porter le même nom**, dossier ou fichier, puisque
leur clé étrangère de parent vaut `NULL`.
- `extra_metadata` n'est pas contraint en taille.
- **Partages publics par lien** : retirés par `004` ; le seul espace partagé est
le dossier système « Public » (`006`), ouvert à tout compte authentifié.
- Les réglages `allow_public_shares` et `default_share_expiry_days` ont été
supprimés par `006` (données mortes).
@@ -0,0 +1,5 @@
CREATE TABLE IF NOT EXISTS schema_migrations (
version VARCHAR(64) NOT NULL,
applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (version)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
@@ -0,0 +1,201 @@
CREATE TABLE roles (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
slug VARCHAR(50) NOT NULL,
name VARCHAR(100) NOT NULL,
description VARCHAR(255) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_roles_slug (slug),
CONSTRAINT chk_roles_slug CHECK (CHAR_LENGTH(slug) > 0)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE users (
id CHAR(36) NOT NULL,
email VARCHAR(255) NOT NULL,
password_hash VARCHAR(255) NOT NULL,
display_name VARCHAR(100) NOT NULL,
role_id INT UNSIGNED NOT NULL,
quota_bytes BIGINT UNSIGNED NULL,
is_active TINYINT(1) NOT NULL DEFAULT 1,
must_change_password TINYINT(1) NOT NULL DEFAULT 0,
last_login_at DATETIME(3) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted_at DATETIME NULL,
active_email VARCHAR(255) GENERATED ALWAYS AS (IF(deleted_at IS NULL, email, NULL)) STORED,
PRIMARY KEY (id),
UNIQUE KEY uq_users_email (active_email),
KEY idx_users_role (role_id),
KEY idx_users_deleted (deleted_at),
CONSTRAINT chk_users_email CHECK (CHAR_LENGTH(email) > 0),
CONSTRAINT chk_users_display_name CHECK (CHAR_LENGTH(display_name) > 0),
CONSTRAINT fk_users_role FOREIGN KEY (role_id) REFERENCES roles (id) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE password_reset_tokens (
id CHAR(36) NOT NULL,
user_id CHAR(36) NOT NULL,
token_hash CHAR(64) NOT NULL,
expires_at DATETIME(3) NOT NULL,
used_at DATETIME(3) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_prt_hash (token_hash),
KEY idx_prt_user (user_id),
KEY idx_prt_expiry (expires_at),
CONSTRAINT fk_prt_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE storage_locations (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
slug VARCHAR(100) NOT NULL,
mount_path VARCHAR(255) NOT NULL,
quota_bytes BIGINT UNSIGNED NULL,
used_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
is_active TINYINT(1) NOT NULL DEFAULT 1,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted_at DATETIME NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_locations_slug (slug),
UNIQUE KEY uq_locations_path (mount_path),
KEY idx_locations_active (is_active),
CONSTRAINT chk_locations_name CHECK (CHAR_LENGTH(name) > 0),
CONSTRAINT chk_locations_quota CHECK (quota_bytes IS NULL OR used_bytes <= quota_bytes)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE folders (
id CHAR(36) NOT NULL,
storage_location_id INT UNSIGNED NOT NULL,
parent_id CHAR(36) NULL,
name VARCHAR(255) NOT NULL,
description TEXT NULL,
owner_id CHAR(36) NULL,
created_by CHAR(36) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted_at DATETIME NULL,
active_name VARCHAR(255) GENERATED ALWAYS AS (IF(deleted_at IS NULL, name, NULL)) STORED,
PRIMARY KEY (id),
UNIQUE KEY uq_folders_name (parent_id, active_name),
KEY idx_folders_parent (parent_id),
KEY idx_folders_location (storage_location_id),
KEY idx_folders_owner (owner_id),
KEY idx_folders_deleted (deleted_at),
KEY idx_folders_list (deleted_at, created_at, id),
CONSTRAINT chk_folders_name CHECK (CHAR_LENGTH(name) > 0),
CONSTRAINT fk_folders_location FOREIGN KEY (storage_location_id) REFERENCES storage_locations (id) ON DELETE RESTRICT,
CONSTRAINT fk_folders_parent FOREIGN KEY (parent_id) REFERENCES folders (id) ON DELETE CASCADE,
CONSTRAINT fk_folders_owner FOREIGN KEY (owner_id) REFERENCES users (id) ON DELETE SET NULL,
CONSTRAINT fk_folders_creator FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE files (
id CHAR(36) NOT NULL,
storage_location_id INT UNSIGNED NOT NULL,
folder_id CHAR(36) NULL,
name VARCHAR(255) NOT NULL,
mime_type VARCHAR(255) NULL,
size_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
checksum_sha256 CHAR(64) NULL,
relative_path VARCHAR(1024) NOT NULL,
is_starred TINYINT(1) NOT NULL DEFAULT 0,
download_count INT UNSIGNED NOT NULL DEFAULT 0,
last_accessed_at DATETIME(3) NULL,
owner_id CHAR(36) NULL,
created_by CHAR(36) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted_at DATETIME NULL,
active_name VARCHAR(255) GENERATED ALWAYS AS (IF(deleted_at IS NULL, name, NULL)) STORED,
PRIMARY KEY (id),
UNIQUE KEY uq_files_name (folder_id, active_name),
KEY idx_files_folder (folder_id),
KEY idx_files_location (storage_location_id),
KEY idx_files_owner (owner_id),
KEY idx_files_checksum (checksum_sha256),
KEY idx_files_starred (is_starred),
KEY idx_files_deleted (deleted_at),
KEY idx_files_list (deleted_at, created_at, id),
KEY idx_files_size (storage_location_id, size_bytes),
CONSTRAINT chk_files_name CHECK (CHAR_LENGTH(name) > 0),
CONSTRAINT chk_files_relative_path CHECK (CHAR_LENGTH(relative_path) > 0),
CONSTRAINT chk_files_checksum CHECK (checksum_sha256 IS NULL OR CHAR_LENGTH(checksum_sha256) = 64),
CONSTRAINT fk_files_location FOREIGN KEY (storage_location_id) REFERENCES storage_locations (id) ON DELETE RESTRICT,
CONSTRAINT fk_files_folder FOREIGN KEY (folder_id) REFERENCES folders (id) ON DELETE CASCADE,
CONSTRAINT fk_files_owner FOREIGN KEY (owner_id) REFERENCES users (id) ON DELETE SET NULL,
CONSTRAINT fk_files_creator FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE folder_permissions (
id CHAR(36) NOT NULL,
folder_id CHAR(36) NOT NULL,
user_id CHAR(36) NOT NULL,
level VARCHAR(20) NOT NULL DEFAULT 'read',
expires_at DATETIME(3) NULL,
granted_by CHAR(36) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_folder_permissions (folder_id, user_id),
KEY idx_folder_permissions_user (user_id),
KEY idx_folder_permissions_expiry (expires_at),
CONSTRAINT chk_folder_permissions_level CHECK (level IN ('read', 'write', 'admin')),
CONSTRAINT fk_folder_permissions_folder FOREIGN KEY (folder_id) REFERENCES folders (id) ON DELETE CASCADE,
CONSTRAINT fk_folder_permissions_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
CONSTRAINT fk_folder_permissions_grantor FOREIGN KEY (granted_by) REFERENCES users (id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE share_links (
id CHAR(36) NOT NULL,
token VARCHAR(64) NOT NULL,
file_id CHAR(36) NULL,
folder_id CHAR(36) NULL,
permission VARCHAR(20) NOT NULL DEFAULT 'read',
password_hash VARCHAR(255) NULL,
expires_at DATETIME(3) NULL,
max_downloads INT UNSIGNED NULL,
download_count INT UNSIGNED NOT NULL DEFAULT 0,
is_active TINYINT(1) NOT NULL DEFAULT 1,
revoked_at DATETIME(3) NULL,
created_by CHAR(36) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_share_links_token (token),
KEY idx_share_links_file (file_id),
KEY idx_share_links_folder (folder_id),
KEY idx_share_links_active (is_active, expires_at),
CONSTRAINT chk_share_links_target CHECK ((file_id IS NULL) <> (folder_id IS NULL)),
CONSTRAINT chk_share_links_permission CHECK (permission IN ('read', 'download')),
CONSTRAINT chk_share_links_downloads CHECK (max_downloads IS NULL OR download_count <= max_downloads),
CONSTRAINT fk_share_links_file FOREIGN KEY (file_id) REFERENCES files (id) ON DELETE CASCADE,
CONSTRAINT fk_share_links_folder FOREIGN KEY (folder_id) REFERENCES folders (id) ON DELETE CASCADE,
CONSTRAINT fk_share_links_creator FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE settings (
setting_key VARCHAR(64) NOT NULL,
setting_value VARCHAR(255) NOT NULL,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (setting_key)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE audit_logs (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id CHAR(36) NULL,
user_email VARCHAR(255) NULL,
action VARCHAR(50) NOT NULL,
resource VARCHAR(50) NOT NULL,
resource_id VARCHAR(64) NULL,
details LONGTEXT NULL,
ip_address VARCHAR(45) NULL,
user_agent VARCHAR(255) NULL,
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
PRIMARY KEY (id),
KEY idx_audit_created (created_at),
KEY idx_audit_user (user_id),
KEY idx_audit_resource (resource, resource_id),
CONSTRAINT chk_audit_details CHECK (details IS NULL OR JSON_VALID(details)),
CONSTRAINT fk_audit_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
@@ -0,0 +1,13 @@
INSERT INTO roles (slug, name, description) VALUES
('admin', 'Administrateur', 'Accès total, gestion des emplacements de stockage et des utilisateurs'),
('user', 'Utilisateur', 'Peut créer, déplacer et partager des fichiers dans les emplacements qui lui sont attribués'),
('readonly', 'Lecture seule', 'Peut consulter et télécharger, ne peut ni modifier ni partager');
INSERT INTO storage_locations (name, slug, mount_path, quota_bytes, used_bytes) VALUES
('Stockage principal', 'principal', '/srv/cohaise/cloud', 429496729600, 0);
INSERT INTO settings (setting_key, setting_value) VALUES
('trash_retention_days', '30'),
('max_upload_bytes', '5368709120'),
('default_share_expiry_days', '7'),
('allow_public_shares', 'true');
@@ -0,0 +1,6 @@
ALTER TABLE audit_logs
ADD CONSTRAINT chk_audit_action CHECK (CHAR_LENGTH(action) > 0),
ADD CONSTRAINT chk_audit_resource CHECK (CHAR_LENGTH(resource) > 0);
ALTER TABLE folders
ADD CONSTRAINT chk_folders_not_self_parent CHECK (parent_id IS NULL OR parent_id <> id);
@@ -0,0 +1,136 @@
ALTER TABLE users DROP COLUMN display_name;
ALTER TABLE users
ADD COLUMN first_name VARCHAR(50) NOT NULL AFTER email,
ADD COLUMN last_name VARCHAR(50) NOT NULL AFTER first_name,
MODIFY COLUMN quota_bytes BIGINT UNSIGNED NOT NULL DEFAULT 429496729600,
ADD COLUMN used_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER quota_bytes,
ADD COLUMN max_file_bytes BIGINT UNSIGNED NOT NULL DEFAULT 5368709120 AFTER used_bytes,
ADD COLUMN password_changed_at DATETIME(3) NULL AFTER must_change_password,
ADD CONSTRAINT chk_users_first_name CHECK (CHAR_LENGTH(first_name) > 0),
ADD CONSTRAINT chk_users_last_name CHECK (CHAR_LENGTH(last_name) > 0),
ADD CONSTRAINT chk_users_quota CHECK (used_bytes <= quota_bytes);
CREATE TABLE user_sessions (
id CHAR(36) NOT NULL,
user_id CHAR(36) NOT NULL,
token_hash CHAR(64) NOT NULL,
ip_address VARCHAR(45) NULL,
user_agent VARCHAR(255) NULL,
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
last_seen_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
expires_at DATETIME(3) NOT NULL,
revoked_at DATETIME(3) NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_user_sessions_hash (token_hash),
KEY idx_user_sessions_user (user_id, revoked_at),
KEY idx_user_sessions_expiry (expires_at),
CONSTRAINT fk_user_sessions_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE email_change_requests (
id CHAR(36) NOT NULL,
user_id CHAR(36) NOT NULL,
new_email VARCHAR(255) NOT NULL,
token_hash CHAR(64) NOT NULL,
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
expires_at DATETIME(3) NOT NULL,
used_at DATETIME(3) NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_email_change_hash (token_hash),
KEY idx_email_change_user (user_id),
KEY idx_email_change_expiry (expires_at),
CONSTRAINT chk_email_change_new CHECK (CHAR_LENGTH(new_email) > 0),
CONSTRAINT fk_email_change_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE user_avatars (
user_id CHAR(36) NOT NULL,
storage_location_id INT UNSIGNED NOT NULL,
original_path VARCHAR(1024) NOT NULL,
mime_type VARCHAR(100) NOT NULL,
size_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
width INT UNSIGNED NOT NULL,
height INT UNSIGNED NOT NULL,
checksum_sha256 CHAR(64) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (user_id),
CONSTRAINT chk_avatar_dimensions CHECK (width > 0 AND height > 0),
CONSTRAINT chk_avatar_path CHECK (CHAR_LENGTH(original_path) > 0),
CONSTRAINT fk_avatar_location FOREIGN KEY (storage_location_id) REFERENCES storage_locations (id) ON DELETE RESTRICT,
CONSTRAINT fk_avatar_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
ALTER TABLE folders
ADD COLUMN access_type VARCHAR(10) NOT NULL DEFAULT 'private' AFTER name,
ADD COLUMN is_system TINYINT(1) NOT NULL DEFAULT 0 AFTER access_type,
ADD COLUMN system_marker TINYINT(1) GENERATED ALWAYS AS (IF(is_system = 1, 1, NULL)) STORED,
ADD UNIQUE KEY uq_folders_system (system_marker),
ADD CONSTRAINT chk_folders_access CHECK (access_type IN ('private', 'shared', 'public')),
ADD CONSTRAINT chk_folders_system CHECK (is_system = 0 OR access_type = 'public');
CREATE TABLE media_metadata (
file_id CHAR(36) NOT NULL,
kind VARCHAR(20) NOT NULL,
width INT UNSIGNED NULL,
height INT UNSIGNED NULL,
duration_ms BIGINT UNSIGNED NULL,
container VARCHAR(20) NULL,
video_codec VARCHAR(40) NULL,
audio_codec VARCHAR(40) NULL,
bitrate INT UNSIGNED NULL,
frame_rate DECIMAL(6,2) NULL,
orientation TINYINT UNSIGNED NULL,
has_audio TINYINT(1) NOT NULL DEFAULT 0,
taken_at DATETIME NULL,
camera_make VARCHAR(100) NULL,
camera_model VARCHAR(100) NULL,
dominant_color CHAR(7) NULL,
extra_metadata MEDIUMBLOB NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (file_id),
KEY idx_media_kind (kind),
KEY idx_media_taken (taken_at),
KEY idx_media_duration (duration_ms),
CONSTRAINT chk_media_kind CHECK (kind IN ('image', 'video', 'audio', 'document', 'archive', 'other')),
CONSTRAINT chk_media_width CHECK (width IS NULL OR width > 0),
CONSTRAINT chk_media_height CHECK (height IS NULL OR height > 0),
CONSTRAINT chk_media_duration CHECK (duration_ms IS NULL OR duration_ms > 0),
CONSTRAINT chk_media_color CHECK (dominant_color IS NULL OR dominant_color REGEXP '^#[0-9a-fA-F]{6}$'),
CONSTRAINT fk_media_file FOREIGN KEY (file_id) REFERENCES files (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE file_variants (
id CHAR(36) NOT NULL,
file_id CHAR(36) NOT NULL,
purpose VARCHAR(20) NOT NULL,
format VARCHAR(20) NOT NULL DEFAULT 'webp',
path VARCHAR(1024) NOT NULL,
size_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
width INT UNSIGNED NULL,
height INT UNSIGNED NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_file_variants_purpose (file_id, purpose),
KEY idx_file_variants_file (file_id),
CONSTRAINT chk_variants_purpose CHECK (purpose IN ('thumbnail', 'preview')),
CONSTRAINT chk_variants_path CHECK (CHAR_LENGTH(path) > 0),
CONSTRAINT chk_variants_width CHECK (width IS NULL OR width > 0),
CONSTRAINT chk_variants_height CHECK (height IS NULL OR height > 0),
CONSTRAINT fk_variants_file FOREIGN KEY (file_id) REFERENCES files (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
DELETE FROM settings WHERE setting_key IN ('max_upload_bytes', 'default_share_expiry_days', 'allow_public_shares');
INSERT INTO settings (setting_key, setting_value) VALUES
('default_quota_bytes', '429496729600'),
('default_max_file_bytes', '5368709120');
DELETE FROM roles WHERE slug = 'readonly';
UPDATE roles SET description = 'Acces total : gestion des comptes, des quotas et des emplacements de stockage' WHERE slug = 'admin';
UPDATE roles SET description = 'Gere ses fichiers, partage des dossiers nominativement et alimente le dossier Public' WHERE slug = 'user';
DROP TABLE share_links;
@@ -0,0 +1,25 @@
-- 005_storage_location_realign.sql
--
-- 002 seedait mount_path='/srv/cohaise/cloud' et quota_bytes=429496729600.
-- L'etat reel du deploiement s'en est ecarte sur les deux points :
--
-- * mount_path doit designer le point de montage reel du conteneur, sans
-- quoi le diagnostic depuis l'interieur (ou une liberation d'espace) vise
-- un chemin qui n'existe pas ;
-- * quota_bytes vaut 4096 octets, ce qui rend impossible tout envoi
-- reel puisque storage_locations.used_bytes est borne par cette valeur.
--
-- Les donnees deja posees ne sont pas modifiees : 002 reste tel quel, et ce
-- fichier corrige l'etat observe une fois pour toutes.
UPDATE storage_locations
SET mount_path = '/data/media',
quota_bytes = 429496729600
WHERE slug = 'principal';
-- Garde-fou : si un emplacement actif ne porte pas de quota, il doit au
-- minimum accueillir le plus grand fichier admis par un compte.
UPDATE storage_locations
SET quota_bytes = 429496729600
WHERE quota_bytes IS NULL
OR quota_bytes < 5368709120;
@@ -0,0 +1,24 @@
-- 006_public_folder.sql
--
-- Le modele prevoyait depuis 004 un dossier systeme public (folders.is_system,
-- access_type='public'), mais aucune ligne n'existait : les comptes n'avaient
-- donc aucun espace commun. Cette migration cree ce dossier une seule fois.
--
-- Elle retire aussi deux reglages sans effet depuis la suppression de
-- share_links par 004 (donnees mortes).
-- Un unique dossier systeme, a la racine, rattache au premier emplacement actif.
-- Idempotent : ne fait rien si un dossier systeme existe deja.
INSERT INTO folders
(id, storage_location_id, parent_id, name, description, owner_id, created_by, access_type, is_system)
SELECT UUID(), sl.id, NULL, 'Public',
'Espace commun : chaque compte peut y deposer des fichiers.',
NULL, NULL, 'public', 1
FROM storage_locations sl
WHERE sl.is_active = 1
AND sl.deleted_at IS NULL
AND NOT EXISTS (SELECT 1 FROM folders f WHERE f.is_system = 1)
ORDER BY sl.id
LIMIT 1;
DELETE FROM settings WHERE setting_key IN ('allow_public_shares', 'default_share_expiry_days');
+27
View File
@@ -0,0 +1,27 @@
{
"name": "@cohaise/cloud",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"build": "tsc --build",
"clean": "node --eval \"import('node:fs').then(fs => { fs.rmSync('dist', { recursive: true, force: true }); fs.rmSync('tsconfig.tsbuildinfo', { force: true }); })\"",
"typecheck": "tsc --noEmit",
"start": "node dist/index.js",
"admin": "node dist/admin.js"
},
"dependencies": {
"@cohaise/server": "*",
"nodemailer": "^10.1.1",
"sharp": "^0.35.5",
"zod": "^4.6.5"
},
"devDependencies": {
"@types/node": "^24.0.0",
"@types/nodemailer": "^8.0.2",
"typescript": "^7.0.2"
},
"bin": {
"cohaise-admin": "./dist/admin.js"
}
}
+137
View File
@@ -0,0 +1,137 @@
import type { Context } from "hono";
import { clientIp as sharedClientIp, type Db, type SessionUser } from "@cohaise/server";
/**
* Les droits sont toujours recalcules depuis la session serveur. Le role de
* l'utilisateur ne vient jamais d'un en-tete client : une requete qui se
* declare admin n'a aucun effet sur cette evaluation.
*/
/**
* SQL de lecture repetee : proprietaire, permission nominative non expiree, ou
* dossier public (accessible a tout compte authentifie).
*/
export const READ_SQL = `( 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.level IN ('read', 'write', 'admin')
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )`;
export const canWrite = async (db: Db, user: SessionUser, folderId: string): Promise<boolean> => {
if (user.role_slug === "admin") return true;
const row = await db.one(
`SELECT 1 AS granted
FROM folders f
WHERE f.id = ? AND f.deleted_at IS NULL
AND ( 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.level IN ('write', 'admin')
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )
LIMIT 1`,
[folderId, user.id, user.id],
);
return row !== null;
};
export const canRead = async (db: Db, user: SessionUser, folderId: string): Promise<boolean> => {
if (user.role_slug === "admin") return true;
const row = await db.one(
`SELECT 1 AS granted
FROM folders f
WHERE f.id = ? AND f.deleted_at IS NULL
AND ( 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.level IN ('read', 'write', 'admin')
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )
LIMIT 1`,
[folderId, user.id, user.id],
);
return row !== null;
};
/**
* Ecriture explicite : proprietaire du dossier, ou permission nominative
* `write`/`admin`. Un dossier public en est exclu : il autorise le depot, mais
* pas la modification ni la suppression des fichiers d'autrui.
*/
export const canWriteExplicit = async (
db: Db,
user: SessionUser,
folderId: string,
): Promise<boolean> => {
if (user.role_slug === "admin") return true;
const row = await db.one(
`SELECT 1 AS granted
FROM folders f
WHERE f.id = ? AND f.deleted_at IS NULL
AND ( f.owner_id = ?
OR EXISTS ( SELECT 1 FROM folder_permissions fp
WHERE fp.folder_id = f.id AND fp.user_id = ?
AND fp.level IN ('write', 'admin')
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )
LIMIT 1`,
[folderId, user.id, user.id],
);
return row !== null;
};
/**
* Gestion du dossier (renommer, deplacer, supprimer, regler les permissions) :
* reservee au proprietaire ou a un administrateur. Un dossier public permet
* d'ajouter, pas de reorganiser l'espace commun.
*/
export const canManageFolder = async (
db: Db,
user: SessionUser,
folderId: string,
): Promise<boolean> => {
if (user.role_slug === "admin") return true;
const row = await db.one(
`SELECT 1 AS granted FROM folders
WHERE id = ? AND deleted_at IS NULL AND owner_id = ? LIMIT 1`,
[folderId, user.id],
);
return row !== null;
};
const clientIp = (context: Context, trustProxy: boolean): string | null =>
sharedClientIp(context, trustProxy);
/**
* Journalise une action sensible. audit_logs survit a la suppression du compte
* (ON DELETE SET NULL) avec un instantane de l'e-mail : c'est la seule trace
* qui reste une fois l'utilisateur efface.
*/
export const audit = async (
db: Db,
context: Context,
user: SessionUser,
action: string,
resource: string,
resourceId: string | null,
details: Record<string, unknown> | null,
trustProxy: boolean,
): Promise<void> => {
await db
.exec(
`INSERT INTO audit_logs
(user_id, user_email, action, resource, resource_id, details, ip_address, user_agent)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
[
user.id,
user.email,
action,
resource,
resourceId,
details ? JSON.stringify(details) : null,
clientIp(context, trustProxy),
(context.req.header("user-agent") ?? "").slice(0, 255) || null,
],
)
.catch(() => undefined);
};
+174
View File
@@ -0,0 +1,174 @@
#!/usr/bin/env node
import { randomUUID } from "node:crypto";
import { ConfigError, loadDbConfig, hashPassword, AppError, toSafeError } from "@cohaise/server";
/**
* Creation et reinitialisation des comptes, en dehors de toute requete HTTP.
*
* Cette commande ne lit que les variables DB : elle doit pouvoir creer le
* premier administrateur alors que l'API n'a pas encore le droit de demarrer.
*
* node dist/admin.js --email [email protected] --first Jean --last Dupont [--role admin]
* node dist/admin.js --email [email protected] --reset
*
* Mot de passe : ADMIN_PASSWORD dans l'environnement, sinon --password,
* sinon un mot de passe aleatoire est genere et affiche une seule fois.
*/
const USAGE = `Utilisation : cohaise-admin --email <adr> --first <prenom> --last <nom> [options]
--email <adr> Adresse du compte (obligatoire)
--first <nom> Prenom (obligatoire a la creation)
--last <nom> Nom (obligatoire a la creation)
--role <slug> admin | user (defaut : admin)
--password <mdp> Mot de passe, sinon variable ADMIN_PASSWORD
--reset Reinitialise le mot de passe d'un compte existant
--help Cette aide`;
interface Args {
email: string;
first: string;
last: string;
role: string;
password?: string;
reset: boolean;
help: boolean;
}
const parseArgs = (argv: string[]): Args => {
const args: Args = { email: "", first: "", last: "", role: "admin", reset: false, help: false };
const value = (index: number): string => {
const next = argv[index + 1];
if (next === undefined || next.startsWith("--")) {
throw AppError.badRequest(`Valeur manquante pour ${argv[index]}`);
}
return next;
};
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (arg === undefined) continue;
if (arg === "--email") args.email = value(index++);
else if (arg === "--first") args.first = value(index++);
else if (arg === "--last") args.last = value(index++);
else if (arg === "--role") args.role = value(index++);
else if (arg === "--password") args.password = value(index++);
else if (arg === "--reset") args.reset = true;
else if (arg === "--help" || arg === "-h") args.help = true;
else throw AppError.badRequest(`Argument inconnu : ${arg}`);
}
return args;
};
/** Mot de passe aleatoire, lisible a la frappe, sans caractere ambigu. */
const generatePassword = (): string => {
const alphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
const bytes = new Uint8Array(18);
globalThis.crypto.getRandomValues(bytes);
let out = "";
for (const byte of bytes) out += alphabet[byte % alphabet.length];
return out;
};
const main = async (argv: string[]): Promise<number> => {
let args: Args;
try {
args = parseArgs(argv);
} catch (error) {
console.error(` ${toSafeError(error).message}\n\n${USAGE}`);
return 2;
}
if (args.help) {
console.log(USAGE);
return 0;
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(args.email)) {
console.error(" Adresse e-mail invalide.");
return 2;
}
let config;
try {
config = loadDbConfig();
} catch (error) {
if (error instanceof ConfigError) {
console.error(` Configuration invalide :\n - ${error.issues.join("\n - ")}`);
return 2;
}
throw error;
}
const { Db } = await import("@cohaise/server");
const db = new Db(config);
try {
const role = await db.one<{ id: number }>("SELECT id FROM roles WHERE slug = ?", [args.role]);
if (!role) {
console.error(` Role inconnu : ${args.role}`);
return 2;
}
const existing = await db.one<{ id: string }>(
"SELECT id FROM users WHERE active_email = ?",
[args.email],
);
if (existing && !args.reset) {
console.error(` Ce compte existe deja : ${args.email}`);
console.error(" Utilisez --reset pour reinitialiser son mot de passe.");
return 1;
}
const password = args.password ?? process.env.ADMIN_PASSWORD ?? generatePassword();
if (Buffer.byteLength(password) < 8) {
console.error(" Le mot de passe doit contenir au moins 8 caracteres.");
return 2;
}
const hash = await hashPassword(password);
if (existing) {
await db.exec(
`UPDATE users SET password_hash = ?, must_change_password = 1, password_changed_at = NULL,
is_active = 1, deleted_at = NULL
WHERE id = ?`,
[hash, existing.id],
);
console.log(` Mot de passe reinitialise pour ${args.email}`);
console.log(` Mot de passe : ${password}`);
console.log(" Un changement de mot de passe sera demande a la premiere connexion.");
return 0;
}
if (!args.first || !args.last) {
console.error(" --first et --last sont obligatoires a la creation.");
console.error(`\n${USAGE}`);
return 2;
}
const id = randomUUID();
await db.exec(
`INSERT INTO users (id, email, first_name, last_name, password_hash, role_id, must_change_password, password_changed_at)
VALUES (?, ?, ?, ?, ?, ?, 1, NULL)`,
[id, args.email, args.first, args.last, hash, role.id],
);
console.log(` Compte cree : ${args.email} (${args.role})`);
console.log(` Mot de passe : ${password}`);
console.log(" Un changement de mot de passe sera demande a la premiere connexion.");
return 0;
} catch (error) {
const safe = toSafeError(error);
console.error(` Echec : ${safe.code} — ${safe.message}`);
return 1;
} finally {
await db.close().catch(() => undefined);
}
};
main(process.argv.slice(2)).then(
(code) => process.exit(code),
(error) => {
console.error(` Erreur inattendue : ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
},
);
+37
View File
@@ -0,0 +1,37 @@
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { purgeExpiredSessions, startService } from "@cohaise/server";
import { registerAccountRoutes } from "./routes/account.js";
import { registerAdminRoutes } from "./routes/admin.js";
import { registerAuthRoutes } from "./routes/auth.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";
// Les migrations sont relues au demarrage. L'operation est idempotente et
// refuse de servir si une migration deja appliquee a change : une base non
// migree rend donc l'API inaccessible plutot que de renvoyer des erreurs 500.
const migrationsDir = join(dirname(fileURLToPath(import.meta.url)), "../migrations");
void startService({
service: "cloud",
migrationsDir,
routes: (app, { db, config }) => {
registerAuthRoutes(app, db, config);
registerAccountRoutes(app, db, config);
registerFolderRoutes(app, db, config);
registerFileRoutes(app, db, config);
registerMediaRoutes(app, db);
registerTrashRoutes(app, db, config);
registerSearchRoutes(app, db);
registerAdminRoutes(app, db, config);
},
onReady: async ({ db, config, logger }) => {
// Entretien au demarrage : sessions expirees et corbeille hors retention.
const sessions = await purgeExpiredSessions(db);
const purged = await purgeExpiredTrash(db, config);
logger.info("entretien au demarrage", { sessions, purged });
},
});
+141
View File
@@ -0,0 +1,141 @@
import { randomUUID } from "node:crypto";
import { mkdir, stat } from "node:fs/promises";
import path from "node:path";
import sharp from "sharp";
import type { Config, Db } from "@cohaise/server";
import { absolutePath } from "./storage.js";
/**
* Traitement des images : vignette et metadonnees.
*
* sharp charge une bibliotheque native ; les images sont decodees en flux et
* la vignette est ecrite en WebP, format nettement plus compact que le JPEG
* d'origine pour un rendu equivalent dans une grille.
*/
export type MediaKind = "image" | "video" | "audio" | "document" | "archive" | "other";
const THUMBNAIL_PX = 480;
export const classify = (mime: string | null): MediaKind => {
const value = (mime ?? "").toLowerCase();
if (value.startsWith("image/")) return "image";
if (value.startsWith("video/")) return "video";
if (value.startsWith("audio/")) return "audio";
if (
value === "application/pdf" ||
value.startsWith("text/") ||
value.includes("word") ||
value.includes("excel") ||
value.includes("presentation") ||
value.includes("opendocument")
) {
return "document";
}
if (
value.includes("zip") ||
value.includes("tar") ||
value.includes("gzip") ||
value.includes("rar") ||
value.includes("7z") ||
value.includes("compressed")
) {
return "archive";
}
return "other";
};
export const isImage = (mime: string | null): boolean =>
(mime ?? "").toLowerCase().startsWith("image/");
export const thumbnailRelativePath = (fileId: string): string =>
path.posix.join("thumbnails", `${fileId}.webp`);
interface ImageProbe {
width: number | null;
height: number | null;
orientation: number | null;
}
const probeImage = async (source: string): Promise<ImageProbe> => {
const meta = await sharp(source, { failOn: "none" }).metadata();
return {
width: meta.width ?? null,
height: meta.height ?? null,
orientation: meta.orientation ?? null,
};
};
interface ThumbnailResult {
width: number;
height: number;
size: number;
}
const writeThumbnail = async (source: string, destination: string): Promise<ThumbnailResult> => {
await mkdir(path.dirname(destination), { recursive: true });
const info = await sharp(source, { failOn: "none" })
.rotate()
.resize(THUMBNAIL_PX, THUMBNAIL_PX, { fit: "inside", withoutEnlargement: true })
.webp({ quality: 80 })
.toFile(destination);
return { width: info.width, height: info.height, size: info.size };
};
/**
* Indexe un fichier qui vient d'etre ecrit. Les insertions sont idempotentes
* (ON DUPLICATE KEY) : un fichier deja indexe est simplement remis a jour.
*
* Un echec ici ne doit jamais faire echouer le depot lui-meme : le fichier est
* deja publie et payable, seule la vignette manquerait. L'appelant ignore donc
* l'erreur.
*/
export const indexMedia = async (
db: Db,
config: Config,
fileId: string,
mimeType: string | null,
source: string,
): Promise<void> => {
const kind = classify(mimeType);
if (!isImage(mimeType)) {
await db.exec(
`INSERT INTO media_metadata (file_id, kind) VALUES (?, ?)
ON DUPLICATE KEY UPDATE kind = VALUES(kind)`,
[fileId, kind],
);
return;
}
const probe = await probeImage(source);
const relative = thumbnailRelativePath(fileId);
const thumbnail = await writeThumbnail(source, absolutePath(config.VARIANT_DIR, relative));
await db.exec(
`INSERT INTO file_variants
(id, file_id, purpose, format, path, size_bytes, width, height)
VALUES (?, ?, 'thumbnail', 'webp', ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE path = VALUES(path), size_bytes = VALUES(size_bytes),
width = VALUES(width), height = VALUES(height)`,
[randomUUID(), fileId, relative, thumbnail.size, thumbnail.width, thumbnail.height],
);
await db.exec(
`INSERT INTO media_metadata (file_id, kind, width, height, orientation)
VALUES (?, 'image', ?, ?, ?)
ON DUPLICATE KEY UPDATE kind = VALUES(kind), width = VALUES(width),
height = VALUES(height), orientation = VALUES(orientation)`,
[fileId, probe.width, probe.height, probe.orientation],
);
};
/** Taille d'une vignette deja ecrite, ou null si le fichier a disparu. */
export const thumbnailSize = async (config: Config, relative: string): Promise<number | null> => {
try {
const info = await stat(absolutePath(config.VARIANT_DIR, relative));
return info.size;
} catch {
return null;
}
};
+400
View File
@@ -0,0 +1,400 @@
import { randomBytes, randomUUID } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { Readable } from "node:stream";
import { z } from "zod";
import sharp from "sharp";
import {
AppError,
attachUser,
clientIp,
createMailer,
createRateLimiter,
currentUser,
hashPassword,
link,
rateLimitKey,
requireAuth,
sha256,
verifyPassword,
type App,
type Config,
type Db,
type SessionUser,
} from "@cohaise/server";
import { audit } from "../access.js";
import { absolutePath, fileExists, openForDownload } from "../storage.js";
const AVATAR_MAX_BYTES = 8 * 1024 * 1024;
const AVATAR_PX = 512;
const HOUR_MS = 3600_000;
const avatarRelativePath = (userId: string): string => path.posix.join("avatars", `${userId}.webp`);
const newToken = (): string => randomBytes(32).toString("base64url");
const parse = <T>(schema: z.ZodType<T>, body: unknown): T => {
const result = schema.safeParse(body);
if (!result.success) {
const issue = result.error.issues[0];
throw AppError.badRequest(
issue ? `${issue.path.join(".") || "corps"} : ${issue.message}` : "Corps invalide.",
);
}
return result.data;
};
const profileInput = z.object({
first_name: z.string().trim().min(1).max(50),
last_name: z.string().trim().min(1).max(50),
});
const forgotInput = z.object({ email: z.string().trim().email().max(255) });
const resetInput = z.object({
token: z.string().min(10).max(400),
password: z.string().min(8).max(1024),
});
const emailChangeInput = z.object({
password: z.string().min(1).max(1024),
new_email: z.string().trim().email().max(255),
});
export const registerAccountRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/account/*", attachUser(db));
app.use("/api/cloud/account", attachUser(db));
const mailer = createMailer(config);
const limiter = createRateLimiter(config.RATE_LIMIT_LOGIN_MAX, config.RATE_LIMIT_LOGIN_WINDOW_MS);
const throttle = (context: Parameters<typeof clientIp>[0], extra: string): void => {
const ip = clientIp(context, config.TRUST_PROXY);
const key = `${rateLimitKey(ip)}:${extra}`;
if (!limiter.allow(key)) {
throw AppError.unprocessable("Trop de tentatives. Reessayez dans une minute.");
}
};
app.patch("/api/cloud/account/profile", requireAuth, async (context) => {
const user = currentUser(context);
const data = parse(profileInput, await context.req.json().catch(() => null));
await db.exec("UPDATE users SET first_name = ?, last_name = ? WHERE id = ?", [
data.first_name,
data.last_name,
user.id,
]);
await audit(db, context, user, "profile.update", "user", user.id, null, config.TRUST_PROXY);
return context.json({ ok: true, first_name: data.first_name, last_name: data.last_name });
});
app.get("/api/cloud/account/sessions", requireAuth, async (context) => {
const user = currentUser(context);
const current = sha256(context.get("token") ?? "");
const rows = await db.query<{
id: string;
token_hash: string;
ip_address: string | null;
user_agent: string | null;
created_at: string;
last_seen_at: string;
expires_at: string;
}>(
`SELECT id, token_hash, ip_address, user_agent, created_at, last_seen_at, expires_at
FROM user_sessions
WHERE user_id = ? AND revoked_at IS NULL AND expires_at > UTC_TIMESTAMP()
ORDER BY last_seen_at DESC`,
[user.id],
);
return context.json({
sessions: rows.map((row) => ({
id: row.id,
ip_address: row.ip_address,
user_agent: row.user_agent,
created_at: row.created_at,
last_seen_at: row.last_seen_at,
expires_at: row.expires_at,
current: row.token_hash === current,
})),
});
});
app.delete("/api/cloud/account/sessions/:id", requireAuth, async (context) => {
const user = currentUser(context);
const id = context.req.param("id") ?? "";
const result = await db.exec(
"UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE id = ? AND user_id = ? AND revoked_at IS NULL",
[id, user.id],
);
if (result.affectedRows === 0) throw AppError.notFound("Session introuvable.");
return context.json({ ok: true });
});
app.delete("/api/cloud/account/sessions", requireAuth, async (context) => {
const user = currentUser(context);
const current = sha256(context.get("token") ?? "");
await db.exec(
"UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ? AND token_hash <> ? AND revoked_at IS NULL",
[user.id, current],
);
return context.json({ ok: true });
});
app.put("/api/cloud/account/avatar", requireAuth, async (context) => {
const user = currentUser(context);
const declared = Number(context.req.header("content-length") ?? "");
if (!Number.isSafeInteger(declared) || declared <= 0) {
throw AppError.badRequest("Envoi d'image invalide.");
}
if (declared > AVATAR_MAX_BYTES) {
throw AppError.payloadTooLarge("L'image ne doit pas depasser 8 Mo.");
}
const source = Buffer.from(await context.req.arrayBuffer());
let processed: Buffer;
try {
processed = await sharp(source, { failOn: "none" })
.rotate()
.resize(AVATAR_PX, AVATAR_PX, { fit: "cover" })
.webp({ quality: 82 })
.toBuffer();
} catch {
throw AppError.badRequest("Le fichier n'est pas une image exploitable.");
}
const location = await db.one<{ id: number }>(
`SELECT id FROM storage_locations
WHERE is_active = 1 AND deleted_at IS NULL ORDER BY id LIMIT 1`,
);
if (!location) throw AppError.serviceUnavailable("Aucun emplacement de stockage disponible.");
const relative = avatarRelativePath(user.id);
const destination = absolutePath(config.VARIANT_DIR, relative);
await mkdir(path.dirname(destination), { recursive: true });
await writeFile(destination, processed);
const size = processed.byteLength;
const previous = await db.one<{ storage_location_id: number; size_bytes: number }>(
"SELECT storage_location_id, size_bytes FROM user_avatars WHERE user_id = ?",
[user.id],
);
await db.transaction(async (connection) => {
if (previous) {
await connection.execute(
"UPDATE storage_locations SET used_bytes = GREATEST(0, CAST(used_bytes AS SIGNED) - ?) WHERE id = ?",
[previous.size_bytes, previous.storage_location_id],
);
}
await connection.execute(
`UPDATE storage_locations SET used_bytes = used_bytes + ? WHERE id = ?`,
[size, location.id],
);
await connection.execute(
`INSERT INTO user_avatars (user_id, storage_location_id, original_path, mime_type, size_bytes, width, height)
VALUES (?, ?, ?, 'image/webp', ?, ?, ?)
ON DUPLICATE KEY UPDATE storage_location_id = VALUES(storage_location_id),
original_path = VALUES(original_path), mime_type = VALUES(mime_type),
size_bytes = VALUES(size_bytes), width = VALUES(width), height = VALUES(height)`,
[user.id, location.id, relative, processed.byteLength, AVATAR_PX, AVATAR_PX],
);
});
await audit(db, context, user, "avatar.update", "user", user.id, null, config.TRUST_PROXY);
return context.json({ ok: true });
});
app.get("/api/cloud/account/avatar/:userId", requireAuth, async (context) => {
const target = context.req.param("userId") ?? "";
const row = await db.one<{ original_path: string; size_bytes: number }>(
"SELECT original_path, size_bytes FROM user_avatars WHERE user_id = ?",
[target],
);
if (!row) throw AppError.notFound("Avatar introuvable.");
const absolute = absolutePath(config.VARIANT_DIR, row.original_path);
if (!(await fileExists(absolute))) throw AppError.notFound("Avatar introuvable.");
const stream = Readable.toWeb(openForDownload(absolute)) as ReadableStream<Uint8Array>;
return new Response(stream, {
headers: {
"content-type": "image/webp",
"content-length": String(row.size_bytes),
"cache-control": "private, max-age=86400",
},
});
});
app.delete("/api/cloud/account/avatar", requireAuth, async (context) => {
const user = currentUser(context);
const row = await db.one<{ storage_location_id: number; size_bytes: number }>(
"SELECT storage_location_id, size_bytes FROM user_avatars WHERE user_id = ?",
[user.id],
);
if (!row) throw AppError.notFound("Avatar introuvable.");
await db.transaction(async (connection) => {
await connection.execute("DELETE FROM user_avatars WHERE user_id = ?", [user.id]);
await connection.execute(
"UPDATE storage_locations SET used_bytes = GREATEST(0, CAST(used_bytes AS SIGNED) - ?) WHERE id = ?",
[row.size_bytes, row.storage_location_id],
);
});
return context.json({ ok: true });
});
app.post("/api/cloud/account/forgot-password", async (context) => {
const data = parse(forgotInput, await context.req.json().catch(() => null));
throttle(context, `forgot:${data.email.toLowerCase()}`);
const user = await db.one<{ id: string; email: string }>(
"SELECT id, email FROM users WHERE active_email = ? AND is_active = 1",
[data.email],
);
// Reponse identique que le compte existe ou non : rien ne permet de
// decouvrir une adresse enregistree.
if (user) {
const token = newToken();
await db.exec(
"INSERT INTO password_reset_tokens (id, user_id, token_hash, expires_at) VALUES (?, ?, ?, ?)",
[randomUUID(), user.id, sha256(token), new Date(Date.now() + HOUR_MS)],
);
const url = link(config, `/reset-password?token=${encodeURIComponent(token)}`);
await mailer
.send({
to: user.email,
subject: "CoHaiSe Cloud — reinitialisation du mot de passe",
text: `Une reinitialisation de mot de passe a ete demandee pour ce compte.\n\n${url}\n\nCe lien expire dans une heure. Si vous n'etes pas a l'origine de cette demande, ignorez ce message.`,
})
.catch(() => undefined);
}
return context.json({ ok: true });
});
app.post("/api/cloud/account/reset-password", async (context) => {
const data = parse(resetInput, await context.req.json().catch(() => null));
throttle(context, "reset");
const row = await db.one<{ id: string; user_id: string }>(
`SELECT id, user_id FROM password_reset_tokens
WHERE token_hash = ? AND used_at IS NULL AND expires_at > UTC_TIMESTAMP()`,
[sha256(data.token)],
);
if (!row) throw AppError.badRequest("Lien invalide ou expire.");
const hash = await hashPassword(data.password);
const account = await db.one<{ email: string; first_name: string; last_name: string }>(
"SELECT email, first_name, last_name FROM users WHERE id = ?",
[row.user_id],
);
await db.transaction(async (connection) => {
await connection.execute(
"UPDATE users SET password_hash = ?, must_change_password = 0, password_changed_at = UTC_TIMESTAMP() WHERE id = ?",
[hash, row.user_id],
);
await connection.execute(
"UPDATE password_reset_tokens SET used_at = UTC_TIMESTAMP() WHERE id = ?",
[row.id],
);
await connection.execute(
"UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ? AND revoked_at IS NULL",
[row.user_id],
);
});
if (account) {
const actor: SessionUser = {
id: row.user_id,
email: account.email,
first_name: account.first_name,
last_name: account.last_name,
role_slug: "user",
role_name: "",
is_active: 1,
must_change_password: 0,
};
await audit(db, context, actor, "password.reset", "user", row.user_id, null, config.TRUST_PROXY);
}
return context.json({ ok: true });
});
app.post("/api/cloud/account/email-change", requireAuth, async (context) => {
const user = currentUser(context);
const data = parse(emailChangeInput, await context.req.json().catch(() => null));
throttle(context, `email:${user.id}`);
const row = await db.one<{ password_hash: string }>(
"SELECT password_hash FROM users WHERE id = ? AND deleted_at IS NULL",
[user.id],
);
if (!row || !(await verifyPassword(data.password, row.password_hash))) {
throw AppError.unauthorized("Mot de passe incorrect.");
}
if (data.new_email.toLowerCase() === user.email.toLowerCase()) {
throw AppError.badRequest("La nouvelle adresse est identique a l'actuelle.");
}
const taken = await db.one("SELECT id FROM users WHERE active_email = ?", [data.new_email]);
if (taken) throw AppError.conflict("Cette adresse est deja utilisee.");
const token = newToken();
await db.exec(
`INSERT INTO email_change_requests (id, user_id, new_email, token_hash, expires_at)
VALUES (?, ?, ?, ?, ?)`,
[randomUUID(), user.id, data.new_email, sha256(token), new Date(Date.now() + HOUR_MS)],
);
const url = link(config, `/confirm-email?token=${encodeURIComponent(token)}`);
await mailer
.send({
to: data.new_email,
subject: "CoHaiSe Cloud — confirmez votre nouvelle adresse",
text: `Une demande de changement d'adresse a ete faite pour votre compte CoHaiSe Cloud.\n\n${url}\n\nCe lien expire dans une heure. Sans confirmation, l'adresse reste inchangee.`,
})
.catch(() => undefined);
await audit(
db,
context,
user,
"email.change_request",
"user",
user.id,
{ new_email: data.new_email },
config.TRUST_PROXY,
);
return context.json({ ok: true });
});
app.post("/api/cloud/account/email-change/confirm", async (context) => {
const data = parse(
z.object({ token: z.string().min(10).max(400) }),
await context.req.json().catch(() => null),
);
const row = await db.one<{ id: string; user_id: string; new_email: string }>(
`SELECT id, user_id, new_email FROM email_change_requests
WHERE token_hash = ? AND used_at IS NULL AND expires_at > UTC_TIMESTAMP()`,
[sha256(data.token)],
);
if (!row) throw AppError.badRequest("Lien invalide ou expire.");
const taken = await db.one("SELECT id FROM users WHERE active_email = ? AND id <> ?", [
row.new_email,
row.user_id,
]);
if (taken) throw AppError.conflict("Cette adresse est deja utilisee.");
await db.transaction(async (connection) => {
await connection.execute("UPDATE users SET email = ? WHERE id = ?", [
row.new_email,
row.user_id,
]);
await connection.execute(
"UPDATE email_change_requests SET used_at = UTC_TIMESTAMP() WHERE id = ?",
[row.id],
);
});
return context.json({ ok: true, email: row.new_email });
});
};
+386
View File
@@ -0,0 +1,386 @@
import { randomUUID } from "node:crypto";
import { z } from "zod";
import {
AppError,
attachUser,
createMailer,
currentUser,
hashPassword,
requireAuth,
type App,
type Config,
type Db,
} from "@cohaise/server";
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`;
/** Mot de passe aleatoire, lisible a la frappe, sans caractere ambigu. */
const generatePasswordValue = (): string => {
const alphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
const bytes = new Uint8Array(18);
globalThis.crypto.getRandomValues(bytes);
let out = "";
for (const byte of bytes) out += alphabet[byte % alphabet.length];
return out;
};
export const registerAdminRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/admin/*", attachUser(db));
app.use("/api/cloud/admin", attachUser(db));
const mailer = createMailer(config);
const 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);
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,
});
});
app.get("/api/cloud/admin/users", requireAuth, async (context) => {
requireAdmin(context);
const query = (context.req.query("q") ?? "").trim();
const rows = query
? await db.query<AdminUserRow>(
`${SELECT_USER}
WHERE u.deleted_at IS NULL
AND (u.email LIKE ? OR u.first_name LIKE ? OR u.last_name LIKE ?)
ORDER BY u.email LIMIT 500`,
[`%${query}%`, `%${query}%`, `%${query}%`],
)
: await db.query<AdminUserRow>(
`${SELECT_USER} WHERE u.deleted_at IS NULL ORDER BY u.email LIMIT 500`,
);
return context.json({ users: rows.map(publicUser) });
});
app.post("/api/cloud/admin/users", requireAuth, async (context) => {
requireAdmin(context);
const data = parse(createUserSchema, await context.req.json().catch(() => null));
const role = await db.one<{ id: number }>("SELECT id FROM roles WHERE slug = ?", [data.role_slug]);
if (!role) throw AppError.badRequest("Role inconnu.");
const existing = await db.one("SELECT id FROM users WHERE active_email = ?", [data.email]);
if (existing) throw AppError.conflict("Ce compte existe deja.");
const password = data.password ?? generatePasswordValue();
const hash = await hashPassword(password);
const id = randomUUID();
await db.exec(
`INSERT INTO users
(id, email, first_name, last_name, password_hash, role_id,
quota_bytes, max_file_bytes, must_change_password, password_changed_at)
VALUES (?, ?, ?, ?, ?, ?,
COALESCE(?, (SELECT CAST(setting_value AS UNSIGNED) FROM settings WHERE setting_key = 'default_quota_bytes'), 429496729600),
COALESCE(?, 5368709120),
1, NULL)`,
[id, data.email, data.first_name, data.last_name, hash, role.id, data.quota_bytes ?? null, data.max_file_bytes ?? null],
);
const created = await db.required<AdminUserRow>(`${SELECT_USER} WHERE u.id = ?`, [id]);
return context.json({ user: publicUser(created), password }, 201);
});
app.patch("/api/cloud/admin/users/:id", requireAuth, async (context) => {
const actor = currentUser(context);
requireAdmin(context);
const id = context.req.param("id") ?? "";
if (!uuidParam.safeParse(id).success) throw AppError.notFound("Compte introuvable.");
const existing = await db.one<AdminUserRow>(`${SELECT_USER} WHERE u.id = ? AND u.deleted_at IS NULL`, [id]);
if (!existing) throw AppError.notFound("Compte introuvable.");
const data = parse(updateUserSchema, await context.req.json().catch(() => null));
if (data.role_slug !== undefined && data.role_slug !== existing.role_slug) {
const role = await db.one<{ id: number }>("SELECT id FROM roles WHERE slug = ?", [data.role_slug]);
if (!role) throw AppError.badRequest("Role inconnu.");
if (id === actor.id) throw AppError.badRequest("Vous ne pouvez pas modifier votre propre role.");
if (existing.role_slug === "admin") {
const [count] = await db.query<{ count: number }>(
`SELECT COUNT(*) AS count FROM users u JOIN roles r ON r.id = u.role_id
WHERE r.slug = 'admin' AND u.is_active = 1 AND u.deleted_at IS NULL`,
);
if ((count?.count ?? 0) <= 1) {
throw AppError.badRequest("Impossible de retirer le dernier administrateur.");
}
}
await db.exec("UPDATE users SET role_id = ? WHERE id = ?", [role.id, id]);
}
if (data.first_name !== undefined) {
await db.exec("UPDATE users SET first_name = ? WHERE id = ?", [data.first_name, id]);
}
if (data.last_name !== undefined) {
await db.exec("UPDATE users SET last_name = ? WHERE id = ?", [data.last_name, id]);
}
if (data.quota_bytes !== undefined) {
if (data.quota_bytes < existing.used_bytes) {
throw AppError.badRequest("Le quota ne peut pas etre inferieur a l'espace deja utilise.");
}
await db.exec("UPDATE users SET quota_bytes = ? WHERE id = ?", [data.quota_bytes, id]);
}
if (data.max_file_bytes !== undefined) {
await db.exec("UPDATE users SET max_file_bytes = ? WHERE id = ?", [data.max_file_bytes, id]);
}
if (data.is_active !== undefined) {
if (!data.is_active && id === actor.id) {
throw AppError.badRequest("Vous ne pouvez pas desactiver votre propre compte.");
}
await db.exec("UPDATE users SET is_active = ? WHERE id = ?", [data.is_active ? 1 : 0, id]);
if (!data.is_active) {
await db.exec(
"UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ? AND revoked_at IS NULL",
[id],
);
}
}
const updated = await db.required<AdminUserRow>(`${SELECT_USER} WHERE u.id = ?`, [id]);
return context.json({ user: publicUser(updated) });
});
app.delete("/api/cloud/admin/users/:id", requireAuth, async (context) => {
const actor = currentUser(context);
requireAdmin(context);
const id = context.req.param("id") ?? "";
if (!uuidParam.safeParse(id).success) throw AppError.notFound("Compte introuvable.");
if (id === actor.id) throw AppError.badRequest("Vous ne pouvez pas supprimer votre propre compte.");
const result = await db.exec(
"UPDATE users SET deleted_at = UTC_TIMESTAMP(), is_active = 0 WHERE id = ? AND deleted_at IS NULL",
[id],
);
if (result.affectedRows === 0) throw AppError.notFound("Compte introuvable.");
await db.exec("UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ?", [id]);
return context.json({ ok: true });
});
app.post("/api/cloud/admin/users/:id/reset-password", requireAuth, async (context) => {
requireAdmin(context);
const id = context.req.param("id") ?? "";
if (!uuidParam.safeParse(id).success) throw AppError.notFound("Compte introuvable.");
const user = await db.one<{ email: string }>(
"SELECT email FROM users WHERE id = ? AND deleted_at IS NULL",
[id],
);
if (!user) throw AppError.notFound("Compte introuvable.");
const password = generatePasswordValue();
const hash = await hashPassword(password);
await db.exec(
"UPDATE users SET password_hash = ?, must_change_password = 1, password_changed_at = NULL WHERE id = ?",
[hash, id],
);
await db.exec(
"UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ? AND revoked_at IS NULL",
[id],
);
// Le mot de passe est rendu une seule fois et envoye au compte. Un echec
// d'envoi n'invalide pas la reinitialisation.
await mailer
.send({
to: user.email,
subject: "CoHaiSe Cloud — mot de passe reinitialise",
text: `Un administrateur a reinitialise le mot de passe de votre compte.\n\nMot de passe provisoire : ${password}\n\nIl vous sera demande de le changer a la prochaine connexion.`,
})
.catch(() => undefined);
return context.json({ password });
});
app.get("/api/cloud/admin/storage-locations", requireAuth, async (context) => {
requireAdmin(context);
const rows = await db.query(
`SELECT id, name, slug, mount_path, quota_bytes, used_bytes, is_active, created_at
FROM storage_locations WHERE deleted_at IS NULL ORDER BY id`,
);
return context.json({ locations: rows });
});
app.post("/api/cloud/admin/storage-locations", requireAuth, async (context) => {
requireAdmin(context);
const data = parse(createLocationSchema, await context.req.json().catch(() => null));
try {
await db.exec(
`INSERT INTO storage_locations (name, slug, mount_path, quota_bytes)
VALUES (?, ?, ?, ?)`,
[data.name, data.slug, data.mount_path, data.quota_bytes ?? null],
);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Un emplacement porte deja ce nom ou ce chemin.");
}
throw error;
}
return context.json({ ok: true }, 201);
});
app.patch("/api/cloud/admin/storage-locations/:id", requireAuth, async (context) => {
requireAdmin(context);
const id = Number(context.req.param("id"));
if (!Number.isInteger(id) || id <= 0) throw AppError.notFound("Emplacement introuvable.");
const data = parse(updateLocationSchema, await context.req.json().catch(() => null));
const row = await db.one<{ used_bytes: number }>(
"SELECT used_bytes FROM storage_locations WHERE id = ? AND deleted_at IS NULL",
[id],
);
if (!row) throw AppError.notFound("Emplacement introuvable.");
if (data.quota_bytes !== undefined && data.quota_bytes !== null && data.quota_bytes < row.used_bytes) {
throw AppError.badRequest("Le quota est inferieur a l'espace deja utilise.");
}
const fields: string[] = [];
const values: unknown[] = [];
if (data.name !== undefined) {
fields.push("name = ?");
values.push(data.name);
}
if (data.quota_bytes !== undefined) {
fields.push("quota_bytes = ?");
values.push(data.quota_bytes);
}
if (data.is_active !== undefined) {
fields.push("is_active = ?");
values.push(data.is_active ? 1 : 0);
}
if (fields.length === 0) throw AppError.badRequest("Rien a modifier.");
values.push(id);
await db.exec(`UPDATE storage_locations SET ${fields.join(", ")} WHERE id = ?`, values);
return context.json({ ok: true });
});
app.get("/api/cloud/admin/audit", requireAuth, async (context) => {
requireAdmin(context);
const limit = Math.min(500, Math.max(1, Number(context.req.query("limit")) || 100));
const offset = Math.max(0, Number(context.req.query("offset")) || 0);
const action = context.req.query("action");
const rows = action
? await db.query(
`SELECT id, user_id, user_email, action, resource, resource_id, details, ip_address, created_at
FROM audit_logs WHERE action = ? ORDER BY created_at DESC LIMIT ${limit} OFFSET ${offset}`,
[action],
)
: await db.query(
`SELECT id, user_id, user_email, action, resource, resource_id, details, ip_address, created_at
FROM audit_logs ORDER BY created_at DESC LIMIT ${limit} OFFSET ${offset}`,
);
return context.json({ entries: rows });
});
};
+179
View File
@@ -0,0 +1,179 @@
import { z } from "zod";
import {
AppError,
attachUser,
clearSessionCookie,
clientIp,
createRateLimiter,
createSession,
currentUser,
hashPassword,
isHttpsRequest,
rateLimitKey,
requireAuth,
revokeSession,
setSessionCookie,
sha256,
verifyPassword,
type App,
type Config,
type Db,
} from "@cohaise/server";
const credentials = z.object({
email: z.string().trim().min(3).max(255),
password: z.string().min(1).max(1024),
});
/**
* Hachage de repli, calcule paresseusement a la premiere echec de connexion.
* Sans lui, un compte inexistant repond plus vite qu'un compte existant, ce qui
* permet d'enumerer les adresses e-mail en mesurant le temps de reponse.
*/
let dummyHash: Promise<string> | undefined;
const decoyHash = (): Promise<string> => (dummyHash ??= hashPassword("aucun-compte-ne-correspond"));
interface UserRow {
id: string;
email: string;
first_name: string;
last_name: string;
password_hash: string;
role_slug: string;
role_name: string;
quota_bytes: number;
used_bytes: number;
max_file_bytes: number;
must_change_password: number;
is_active: number;
}
const publicUser = (row: UserRow) => ({
id: row.id,
email: row.email,
first_name: row.first_name,
last_name: row.last_name,
role_slug: row.role_slug,
role_name: row.role_name,
quota_bytes: row.quota_bytes,
used_bytes: row.used_bytes,
max_file_bytes: row.max_file_bytes,
must_change_password: row.must_change_password === 1,
});
const SELECT_USER = `
SELECT u.id, u.email, u.first_name, u.last_name, u.password_hash,
r.slug AS role_slug, r.name AS role_name,
u.quota_bytes, u.used_bytes, u.max_file_bytes, u.must_change_password, u.is_active
FROM users u
JOIN roles r ON r.id = u.role_id`;
export const registerAuthRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/*", attachUser(db));
const limiter = createRateLimiter(config.RATE_LIMIT_LOGIN_MAX, config.RATE_LIMIT_LOGIN_WINDOW_MS);
app.post("/api/cloud/auth/login", async (context) => {
// Borne les tentatives par IP : une attaque par dictionnaire sur un mot de
// passe faible est arretee avant le calcul scrypt, couteux.
const ip = clientIp(context, config.TRUST_PROXY);
if (!limiter.allow(rateLimitKey(ip))) {
throw AppError.unprocessable("Trop de tentatives de connexion. Reessayez dans une minute.");
}
const parsed = credentials.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) throw AppError.badRequest("Identifiants invalides.");
const { email, password } = parsed.data;
const row = await db.one<UserRow>(`${SELECT_USER} WHERE u.active_email = ?`, [email]);
// Meme travail dans les deux cas, pour que le temps de reponse ne
// revele pas si l'adresse existe.
const stored = row && row.is_active === 1 ? row.password_hash : await decoyHash();
if (!row || row.is_active !== 1 || !(await verifyPassword(password, stored))) {
throw AppError.unauthorized("Identifiants invalides.");
}
const forwarded = context.req.header("x-forwarded-for");
const { token, expiresAt } = await createSession(
db,
row.id,
{
ipAddress: config.TRUST_PROXY && forwarded ? forwarded.split(",")[0]?.trim() : null,
userAgent: context.req.header("user-agent"),
},
config.SESSION_TTL_HOURS,
);
await db.exec("UPDATE users SET last_login_at = UTC_TIMESTAMP() WHERE id = ?", [row.id]);
// Le marqueur Secure suit le protocole reellement annonce, pas
// NODE_ENV : un deploiement en HTTP local doit rester utilisable, un
// deploiement https:// ne doit jamais poser de cookie cleartext.
// Le schema reel de la requete, pas PUBLIC_ORIGIN : voir isHttpsRequest.
const secure = isHttpsRequest(context, config.TRUST_PROXY);
setSessionCookie(context, token, expiresAt, secure);
return context.json({ user: publicUser(row) });
});
app.post("/api/cloud/auth/logout", requireAuth, async (context) => {
const token = context.get("token");
if (token) await revokeSession(db, token);
clearSessionCookie(context);
return context.json({ ok: true });
});
app.get("/api/cloud/auth/me", requireAuth, async (context) => {
const session = currentUser(context);
const row = await db.one<UserRow>(`${SELECT_USER} WHERE u.id = ?`, [session.id]);
if (!row) throw AppError.unauthorized();
return context.json({ user: publicUser(row) });
});
const changePassword = z.object({
current: z.string().min(1).max(1024),
next: z.string().min(8).max(1024),
});
/**
* Changement impose a la premiere connexion. Les autres sessions sont
* revoquees : si le compte avait ete ouvert ailleurs, l'ancien mot de passe
* ne doit plus rien ouvrir.
*/
app.post("/api/cloud/auth/change-password", requireAuth, async (context) => {
const session = currentUser(context);
const parsed = changePassword.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) {
throw AppError.badRequest("Le nouveau mot de passe doit contenir au moins 8 caracteres.");
}
const row = await db.one<{ password_hash: string }>(
"SELECT password_hash FROM users WHERE id = ? AND deleted_at IS NULL",
[session.id],
);
if (!row) throw AppError.unauthorized();
if (!(await verifyPassword(parsed.data.current, row.password_hash))) {
throw AppError.unauthorized("Mot de passe actuel incorrect.");
}
if (parsed.data.current === parsed.data.next) {
throw AppError.badRequest("Le nouveau mot de passe doit differer de l'actuel.");
}
const hash = await hashPassword(parsed.data.next);
await db.exec(
`UPDATE users
SET password_hash = ?, must_change_password = 0, password_changed_at = UTC_TIMESTAMP()
WHERE id = ?`,
[hash, session.id],
);
// La session courante est conservee, toutes les autres sont revoquees.
await db.exec(
`UPDATE user_sessions
SET revoked_at = UTC_TIMESTAMP()
WHERE user_id = ? AND revoked_at IS NULL AND token_hash <> ?`,
[session.id, sha256(context.get("token") ?? "")],
);
return context.json({ ok: true });
});
};
+528
View File
@@ -0,0 +1,528 @@
import { randomUUID } from "node:crypto";
import path from "node:path";
import { Readable } from "node:stream";
import { z } from "zod";
import {
AppError,
attachUser,
currentUser,
requireAuth,
requireRole,
type App,
type Config,
type Db,
} from "@cohaise/server";
import { audit, canRead, canWrite, canWriteExplicit } from "../access.js";
import { indexMedia, thumbnailSize } from "../media.js";
import {
absolutePath,
chooseLocation,
discard,
ensureDir,
fileExists,
openForDownload,
publish,
relativePathFor,
temporaryPath,
writeBody,
} from "../storage.js";
const uuid = z
.string()
.regex(
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
"Identifiant invalide.",
);
const MIME = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,127}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,127}$/;
const renameInput = z.object({
name: z.string().trim().min(1).max(255),
});
const moveInput = z.object({
folderId: uuid.nullish(),
});
const parse = <T>(schema: z.ZodType<T>, body: unknown): T => {
const result = schema.safeParse(body);
if (!result.success) {
const issue = result.error.issues[0];
throw AppError.badRequest(
issue ? `${issue.path.join(".") || "corps"} : ${issue.message}` : "Corps invalide.",
);
}
return result.data;
};
interface FileRow {
id: string;
folder_id: string | null;
name: string;
mime_type: string | null;
size_bytes: number;
checksum_sha256: string | null;
relative_path: string;
owner_id: string | null;
is_starred: number;
download_count: number;
created_at: string;
updated_at: string;
}
const SELECT_FILE = `SELECT id, folder_id, name, mime_type, size_bytes, checksum_sha256,
relative_path, owner_id, is_starred, download_count, created_at, updated_at
FROM files`;
const publicFile = (row: FileRow) => ({
id: row.id,
folder_id: row.folder_id,
name: row.name,
mime_type: row.mime_type,
size_bytes: row.size_bytes,
checksum_sha256: row.checksum_sha256,
owner_id: row.owner_id,
is_starred: row.is_starred === 1,
download_count: row.download_count,
created_at: row.created_at,
updated_at: row.updated_at,
});
/** Nom d'affichage : ni separateur, ni sequence d'echappement, ni point seul. */
const assertName = (raw: string | undefined): string => {
const name = (raw ?? "").trim();
if (!name || name.length > 255) {
throw AppError.badRequest("Le nom du fichier doit contenir entre 1 et 255 caracteres.");
}
if (name === "." || name === ".." || /[/\\\0-\x1f]/.test(name)) {
throw AppError.badRequest("Le nom du fichier ne peut pas contenir de separateur.");
}
return name;
};
const mimeOf = (header: string | undefined): string => {
const value = (header ?? "").split(";")[0]?.trim().toLowerCase() ?? "";
return MIME.test(value) ? value : "application/octet-stream";
};
/** Le nom HTTP ne contient que des octets ASCII imprimables, UTF-8 en prime. */
const contentDisposition = (name: string): string => {
const ascii = name.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_");
return `attachment; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(name)}`;
};
export const registerFileRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/files/*", attachUser(db));
app.use("/api/cloud/files", attachUser(db));
/**
* Depot en un seul passage. Le corps n'est pas un formulaire multipart mais
* l'objet brut : le navigateur envoie le File tel quel, ce qui evite de
* faire tenir plusieurs gigaoctets en memoire pendant le decoupage.
*/
app.put(
"/api/cloud/files",
requireAuth,
requireRole("admin", "user"),
async (context) => {
const user = currentUser(context);
const name = assertName(context.req.query("name"));
const rawFolder = context.req.query("folderId");
const folderId = rawFolder === undefined || rawFolder === "" ? null : rawFolder;
if (folderId !== null) {
if (!uuid.safeParse(folderId).success) {
throw AppError.badRequest("Identifiant de dossier invalide.");
}
const folder = await db.one(
"SELECT 1 AS present FROM folders WHERE id = ? AND deleted_at IS NULL",
[folderId],
);
if (!folder) throw AppError.notFound("Dossier introuvable.");
if (!(await canWrite(db, user, folderId))) {
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier.");
}
}
const declaredHeader = context.req.header("content-length");
if (declaredHeader === undefined) {
throw new AppError(411, "LENGTH_REQUIRED", "En-tête Content-Length manquant.");
}
const declared = Number(declaredHeader);
if (!Number.isSafeInteger(declared) || declared < 0) {
throw AppError.badRequest("Longueur de corps invalide.");
}
const budget = await db.one<{
used_bytes: number;
quota_bytes: number;
max_file_bytes: number;
}>(
"SELECT used_bytes, quota_bytes, max_file_bytes FROM users WHERE id = ? AND deleted_at IS NULL",
[user.id],
);
if (!budget) throw AppError.unauthorized();
// Les deux bornes sont verifiees avant d'ecrire quoi que ce soit.
if (declared > budget.max_file_bytes) {
throw AppError.payloadTooLarge(
`Fichier trop volumineux (maximum ${budget.max_file_bytes} octets).`,
);
}
if (BigInt(budget.used_bytes) + BigInt(declared) > BigInt(budget.quota_bytes)) {
throw AppError.payloadTooLarge("Votre quota de stockage est depasse.");
}
const duplicate = await db.one(
`SELECT 1 AS taken FROM files
WHERE folder_id <=> ? AND active_name = ? AND deleted_at IS NULL LIMIT 1`,
[folderId, name],
);
if (duplicate) throw AppError.conflict("Ce nom existe deja ici.");
const location = await chooseLocation(db, BigInt(declared));
const id = randomUUID();
const relative = relativePathFor(location.slug, id, name);
const destination = absolutePath(config.MEDIA_DIR, relative);
const temporary = temporaryPath(config.MEDIA_DIR, location.slug);
await ensureDir(path.dirname(destination));
const body = context.req.raw.body;
if (!body) throw AppError.badRequest("Corps de requete vide.");
let written;
try {
written = await writeBody(temporary, body, declared, budget.max_file_bytes);
} catch (error) {
await discard(temporary);
throw error;
}
// Publication puis ecriture en base : si la base refuse, le fichier
// est retire, il ne reste aucun orphelin dans les deux sens.
await publish(temporary, destination);
try {
await db.transaction(async (connection) => {
const [quota] = await connection.execute(
`UPDATE users SET used_bytes = used_bytes + ?
WHERE id = ? AND used_bytes + ? <= quota_bytes`,
[written.size, user.id, written.size],
);
if ((quota as { affectedRows: number }).affectedRows === 0) {
throw AppError.payloadTooLarge("Votre quota de stockage est depasse.");
}
const [inserted] = await connection.execute(
`INSERT INTO files
(id, storage_location_id, folder_id, name, mime_type, size_bytes,
checksum_sha256, relative_path, owner_id, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
id,
location.id,
folderId,
name,
mimeOf(context.req.header("content-type")),
written.size,
written.checksum,
relative,
user.id,
user.id,
],
);
const [support] = await connection.execute(
`UPDATE storage_locations
SET used_bytes = used_bytes + ?
WHERE id = ? AND (quota_bytes IS NULL OR used_bytes + ? <= quota_bytes)`,
[written.size, location.id, written.size],
);
if ((support as { affectedRows: number }).affectedRows === 0) {
throw AppError.payloadTooLarge("L'espace disponible sur le support est insuffisant.");
}
void inserted;
});
} catch (error) {
await discard(destination);
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Ce nom existe deja ici.");
}
throw error;
}
// Vignette et metadonnees : best-effort, le depot reste valide si sharp
// echoue sur un format exotique.
await indexMedia(db, config, id, mimeOf(context.req.header("content-type")), destination).catch(
() => undefined,
);
await audit(
db,
context,
user,
"file.upload",
"file",
id,
{ name, size: written.size, folder_id: folderId },
config.TRUST_PROXY,
);
const created = await db.required<FileRow>(`${SELECT_FILE} WHERE id = ?`, [id]);
return context.json({ file: publicFile(created) }, 201);
},
);
app.get("/api/cloud/files", requireAuth, async (context) => {
const user = currentUser(context);
const rawFolder = context.req.query("folderId");
const folderId = rawFolder === undefined || rawFolder === "" ? null : rawFolder;
if (folderId !== null && !uuid.safeParse(folderId).success) {
throw AppError.badRequest("Identifiant de dossier invalide.");
}
// Contre l'IDOR : un dossier qui n'appartient pas a la session rend une
// liste vide plutot que de confirmer son existence.
if (folderId !== null && user.role_slug !== "admin" && !(await canRead(db, user, folderId))) {
const readable = await db.one(
`SELECT 1 AS granted FROM folders f
WHERE f.id = ? AND f.deleted_at IS NULL AND f.owner_id = ? LIMIT 1`,
[folderId, user.id],
);
if (!readable) throw AppError.notFound("Dossier introuvable.");
}
const rows = await db.query<FileRow>(
`${SELECT_FILE}
WHERE deleted_at IS NULL
AND (folder_id <=> ?)
AND ( ? = 1
OR owner_id = ?
OR ( folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folders f
WHERE f.id = files.folder_id AND f.access_type = 'public' ) )
OR ( folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folder_permissions fp
WHERE fp.folder_id = files.folder_id
AND fp.user_id = ?
AND fp.level IN ('read', 'write', 'admin')
AND ( fp.expires_at IS NULL
OR fp.expires_at > UTC_TIMESTAMP() ) ) ) )
ORDER BY name`,
[folderId, user.role_slug === "admin" ? 1 : 0, user.id, user.id],
);
return context.json({ folderId, files: rows.map(publicFile) });
});
app.get("/api/cloud/files/:id/download", requireAuth, async (context) => {
const user = currentUser(context);
const rawId = context.req.param("id");
if (!uuid.safeParse(rawId).success) throw AppError.notFound("Fichier introuvable.");
const row = await db.one<FileRow>(`${SELECT_FILE} WHERE id = ? AND deleted_at IS NULL`, [rawId]);
if (!row) throw AppError.notFound("Fichier introuvable.");
const allowed =
user.role_slug === "admin" ||
(row.owner_id !== null && row.owner_id === user.id) ||
(row.folder_id !== null && (await canRead(db, user, row.folder_id)));
if (!allowed) throw AppError.notFound("Fichier introuvable.");
const absolute = absolutePath(config.MEDIA_DIR, row.relative_path);
if (!(await fileExists(absolute))) throw AppError.notFound("Fichier introuvable sur le support.");
await db
.exec(
`UPDATE files
SET download_count = download_count + 1, last_accessed_at = UTC_TIMESTAMP()
WHERE id = ?`,
[row.id],
)
.catch(() => undefined);
const mime = row.mime_type ?? "application/octet-stream";
const stream = Readable.toWeb(openForDownload(absolute)) as ReadableStream<Uint8Array>;
return new Response(stream, {
headers: {
"content-type": mime,
"content-length": String(row.size_bytes),
"content-disposition": contentDisposition(row.name),
// Le type vient de la base, jamais du contenu : un fichier HTML
// telecharge ne doit jamais etre rendu en navigation.
"x-content-type-options": "nosniff",
"cache-control": "private, max-age=0, must-revalidate",
},
});
});
/** Vignette d'image. Memes droits que le telechargement, cache prive. */
app.get("/api/cloud/files/:id/thumbnail", requireAuth, async (context) => {
const user = currentUser(context);
const rawId = context.req.param("id");
if (!uuid.safeParse(rawId).success) throw AppError.notFound("Image introuvable.");
const row = await db.one<FileRow>(`${SELECT_FILE} WHERE id = ? AND deleted_at IS NULL`, [rawId]);
if (!row) throw AppError.notFound("Image introuvable.");
const allowed =
user.role_slug === "admin" ||
(row.owner_id !== null && row.owner_id === user.id) ||
(row.folder_id !== null && (await canRead(db, user, row.folder_id)));
if (!allowed) throw AppError.notFound("Image introuvable.");
const variant = await db.one<{ path: string }>(
"SELECT path FROM file_variants WHERE file_id = ? AND purpose = 'thumbnail'",
[row.id],
);
if (!variant) throw AppError.notFound("Vignette introuvable.");
const size = await thumbnailSize(config, variant.path);
if (size === null) throw AppError.notFound("Vignette introuvable.");
const absolute = absolutePath(config.VARIANT_DIR, variant.path);
const stream = Readable.toWeb(openForDownload(absolute)) as ReadableStream<Uint8Array>;
return new Response(stream, {
headers: {
"content-type": "image/webp",
"content-length": String(size),
"cache-control": "private, max-age=86400",
"x-content-type-options": "nosniff",
},
});
});
/** Renomme un fichier. Le chemin physique ne bouge pas : il suit l'UUID. */
app.patch("/api/cloud/files/:id", requireAuth, async (context) => {
const user = currentUser(context);
const rawId = context.req.param("id");
if (!uuid.safeParse(rawId).success) throw AppError.notFound("Fichier introuvable.");
const row = await db.one<FileRow>(`${SELECT_FILE} WHERE id = ? AND deleted_at IS NULL`, [rawId]);
if (!row) throw AppError.notFound("Fichier introuvable.");
const owner = row.owner_id !== null && row.owner_id === user.id;
const permitted =
user.role_slug === "admin" ||
owner ||
(row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id)));
if (!permitted) throw AppError.notFound("Fichier introuvable.");
const { name: rawName } = parse(renameInput, await context.req.json().catch(() => null));
const name = assertName(rawName);
try {
await db.exec(
"UPDATE files SET name = ? WHERE id = ? AND deleted_at IS NULL",
[name, row.id],
);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Ce nom existe deja ici.");
}
throw error;
}
const updated = await db.required<FileRow>(`${SELECT_FILE} WHERE id = ?`, [row.id]);
await audit(db, context, user, "file.rename", "file", row.id, { name }, config.TRUST_PROXY);
return context.json({ file: publicFile(updated) });
});
/** Deplace un fichier vers un autre dossier, racine comprise. */
app.post("/api/cloud/files/:id/move", requireAuth, async (context) => {
const user = currentUser(context);
const rawId = context.req.param("id");
if (!uuid.safeParse(rawId).success) throw AppError.notFound("Fichier introuvable.");
const row = await db.one<FileRow>(`${SELECT_FILE} WHERE id = ? AND deleted_at IS NULL`, [rawId]);
if (!row) throw AppError.notFound("Fichier introuvable.");
const owner = row.owner_id !== null && row.owner_id === user.id;
const canLeave =
user.role_slug === "admin" ||
owner ||
(row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id)));
if (!canLeave) throw AppError.notFound("Fichier introuvable.");
const { folderId } = parse(moveInput, await context.req.json().catch(() => null));
const destination = folderId ?? null;
if (destination !== null && !(await canWrite(db, user, destination))) {
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier.");
}
try {
await db.exec("UPDATE files SET folder_id = ? WHERE id = ?", [destination, row.id]);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Un fichier du meme nom existe deja dans la destination.");
}
throw error;
}
const updated = await db.required<FileRow>(`${SELECT_FILE} WHERE id = ?`, [row.id]);
await audit(db, context, user, "file.move", "file", row.id, { folderId: destination }, config.TRUST_PROXY);
return context.json({ file: publicFile(updated) });
});
/** Bascule le marqueur favori. */
app.put("/api/cloud/files/:id/star", requireAuth, async (context) => {
const user = currentUser(context);
const rawId = context.req.param("id");
if (!uuid.safeParse(rawId).success) throw AppError.notFound("Fichier introuvable.");
const row = await db.one<FileRow>(`${SELECT_FILE} WHERE id = ? AND deleted_at IS NULL`, [rawId]);
if (!row) throw AppError.notFound("Fichier introuvable.");
const allowed =
user.role_slug === "admin" ||
(row.owner_id !== null && row.owner_id === user.id) ||
(row.folder_id !== null && (await canRead(db, user, row.folder_id)));
if (!allowed) throw AppError.notFound("Fichier introuvable.");
await db.exec("UPDATE files SET is_starred = 1 - is_starred WHERE id = ?", [row.id]);
const updated = await db.required<FileRow>(`${SELECT_FILE} WHERE id = ?`, [row.id]);
return context.json({ file: publicFile(updated) });
});
app.delete("/api/cloud/files/:id", requireAuth, async (context) => {
const user = currentUser(context);
const rawId = context.req.param("id");
if (!uuid.safeParse(rawId).success) throw AppError.notFound("Fichier introuvable.");
const row = await db.one<FileRow>(`${SELECT_FILE} WHERE id = ? AND deleted_at IS NULL`, [rawId]);
if (!row) throw AppError.notFound("Fichier introuvable.");
const owner = row.owner_id !== null && row.owner_id === user.id;
const permitted =
user.role_slug === "admin" ||
owner ||
(row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id)));
if (!permitted) throw AppError.notFound("Fichier introuvable.");
// Suppression logique : le fichier reste sur disque le temps de la
// retention (trash_retention_days), et son nom redevient disponible grace
// a la colonne active_name.
const result = await db.exec(
"UPDATE files SET deleted_at = UTC_TIMESTAMP() WHERE id = ? AND deleted_at IS NULL",
[row.id],
);
if (result.affectedRows === 0) throw AppError.notFound("Fichier introuvable.");
await audit(
db,
context,
user,
"file.delete",
"file",
row.id,
{ name: row.name, size: row.size_bytes, folder_id: row.folder_id },
config.TRUST_PROXY,
);
return context.json({ ok: true });
});
};
+397
View File
@@ -0,0 +1,397 @@
import { randomUUID } from "node:crypto";
import { z } from "zod";
import {
AppError,
attachUser,
currentUser,
requireAuth,
requireRole,
type App,
type Config,
type Db,
} from "@cohaise/server";
import { audit, canManageFolder, canRead, canWrite } from "../access.js";
const uuid = z
.string()
.regex(
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
"Identifiant invalide.",
);
const createFolder = z.object({
name: z.string().trim().min(1).max(255),
parentId: uuid.nullish(),
description: z.string().trim().max(2000).nullish(),
});
const updateFolder = z.object({
name: z.string().trim().min(1).max(255).optional(),
description: z.string().trim().max(2000).nullish(),
});
const moveFolder = z.object({
parentId: uuid.nullish(),
});
const permissionInput = z.object({
email: z.string().trim().min(3).max(255),
level: z.enum(["read", "write", "admin"]),
expiresAt: z.string().datetime().nullish(),
});
interface FolderRow {
id: string;
parent_id: string | null;
name: string;
description: string | null;
owner_id: string | null;
access_type: string;
is_system: number;
storage_location_id: number;
created_at: string;
updated_at: string;
}
const SELECT_FOLDER = `SELECT f.id, f.parent_id, f.name, f.description, f.owner_id,
f.access_type, f.is_system, f.storage_location_id, f.created_at, f.updated_at
FROM folders f`;
const publicFolder = (row: FolderRow) => ({
id: row.id,
parent_id: row.parent_id,
name: row.name,
description: row.description,
owner_id: row.owner_id,
access_type: row.access_type,
is_system: row.is_system === 1,
created_at: row.created_at,
updated_at: row.updated_at,
});
const assertName = (raw: string): string => {
const name = raw.trim();
if (!name || name.length > 255) {
throw AppError.badRequest("Le nom du dossier doit contenir entre 1 et 255 caracteres.");
}
if (name === "." || name === ".." || /[/\\\0-\x1f]/.test(name)) {
throw AppError.badRequest("Le nom du dossier ne peut pas contenir de separateur.");
}
return name;
};
const parse = <T>(schema: z.ZodType<T>, body: unknown): T => {
const result = schema.safeParse(body);
if (!result.success) {
const issue = result.error.issues[0];
throw AppError.badRequest(
issue ? `${issue.path.join(".") || "corps"} : ${issue.message}` : "Corps invalide.",
);
}
return result.data;
};
/** Id du dossier et de tous ses descendants, y compris lui-meme. */
const subtreeIds = async (db: Db, rootId: string): Promise<string[]> => {
const rows = await db.query<{ id: string }>(
`WITH RECURSIVE subtree AS (
SELECT id FROM folders WHERE id = ?
UNION ALL
SELECT f.id FROM folders f JOIN subtree s ON f.parent_id = s.id
)
SELECT id FROM subtree`,
[rootId],
);
return rows.map((row) => row.id);
};
export const registerFolderRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/folders/*", attachUser(db));
app.use("/api/cloud/folders", attachUser(db));
app.get("/api/cloud/folders", requireAuth, async (context) => {
const user = currentUser(context);
const rawParent = context.req.query("parentId");
const parentId = rawParent === undefined || rawParent === "" ? null : rawParent;
if (parentId !== null && !uuid.safeParse(parentId).success) {
throw AppError.badRequest("Identifiant de dossier invalide.");
}
if (user.role_slug !== "admin" && parentId !== null) {
// Contre l'IDOR : on ne liste un dossier que si la session y a acces.
if (!(await canRead(db, user, parentId))) {
throw AppError.notFound("Dossier introuvable.");
}
}
const rows = await db.query<FolderRow>(
`${SELECT_FOLDER}
WHERE f.deleted_at IS NULL
AND (f.parent_id <=> ?)
AND ( ? = 1
OR f.owner_id = ?
OR f.access_type = 'public'
OR EXISTS ( SELECT 1 FROM folder_permissions fp
WHERE fp.folder_id = f.id AND fp.user_id = ?
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )
ORDER BY f.name`,
[parentId, user.role_slug === "admin" ? 1 : 0, user.id, user.id],
);
return context.json({ parentId, folders: rows.map(publicFolder) });
});
app.post(
"/api/cloud/folders",
requireAuth,
requireRole("admin", "user"),
async (context) => {
const user = currentUser(context);
const { name: rawName, parentId, description } = parse(
createFolder,
await context.req.json().catch(() => null),
);
const name = assertName(rawName);
if (parentId) {
if (!(await canWrite(db, user, parentId))) {
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier.");
}
}
const duplicate = await db.one(
`SELECT 1 AS taken FROM folders
WHERE parent_id <=> ? AND active_name = ? AND deleted_at IS NULL LIMIT 1`,
[parentId ?? null, name],
);
if (duplicate) throw AppError.conflict("Ce nom existe deja ici.");
const parent = parentId
? await db.one<{ id: string; storage_location_id: number }>(
"SELECT id, storage_location_id FROM folders WHERE id = ? AND deleted_at IS NULL",
[parentId],
)
: null;
if (parentId && !parent) throw AppError.notFound("Dossier parent introuvable.");
const locationId =
parent?.storage_location_id ??
(
await db.one<{ id: number }>(
`SELECT id FROM storage_locations
WHERE is_active = 1 AND deleted_at IS NULL ORDER BY id LIMIT 1`,
)
)?.id;
if (locationId === undefined) {
throw AppError.serviceUnavailable("Aucun emplacement de stockage disponible.");
}
const id = randomUUID();
try {
await db.exec(
`INSERT INTO folders (id, storage_location_id, parent_id, name, description, owner_id, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
[id, locationId, parentId ?? null, name, description ?? null, user.id, user.id],
);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Ce nom existe deja ici.");
}
throw error;
}
const created = await db.required<FolderRow>(`${SELECT_FOLDER} WHERE f.id = ?`, [id]);
await audit(db, context, user, "folder.create", "folder", id, { name }, config.TRUST_PROXY);
return context.json({ folder: publicFolder(created) }, 201);
},
);
app.patch("/api/cloud/folders/:id", requireAuth, async (context) => {
const user = currentUser(context);
const id = context.req.param("id") ?? "";
if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable.");
const existing = await db.one<FolderRow>(`${SELECT_FOLDER} WHERE f.id = ? AND f.deleted_at IS NULL`, [id]);
if (!existing) throw AppError.notFound("Dossier introuvable.");
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
const data = parse(updateFolder, await context.req.json().catch(() => null));
if (data.name === undefined && data.description === undefined) {
throw AppError.badRequest("Rien a modifier.");
}
const name = data.name === undefined ? existing.name : assertName(data.name);
try {
await db.exec(
"UPDATE folders SET name = ?, description = ? WHERE id = ?",
[name, data.description === undefined ? existing.description : data.description, id],
);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Ce nom existe deja ici.");
}
throw error;
}
const updated = await db.required<FolderRow>(`${SELECT_FOLDER} WHERE f.id = ?`, [id]);
await audit(db, context, user, "folder.update", "folder", id, { name }, config.TRUST_PROXY);
return context.json({ folder: publicFolder(updated) });
});
app.post("/api/cloud/folders/:id/move", requireAuth, async (context) => {
const user = currentUser(context);
const id = context.req.param("id") ?? "";
if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable.");
const existing = await db.one<FolderRow>(`${SELECT_FOLDER} WHERE f.id = ? AND f.deleted_at IS NULL`, [id]);
if (!existing) throw AppError.notFound("Dossier introuvable.");
if (existing.is_system === 1) throw AppError.forbidden("Le dossier public ne peut pas etre deplace.");
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
const { parentId } = parse(moveFolder, await context.req.json().catch(() => null));
if (parentId !== null && parentId !== undefined) {
if (!(await canWrite(db, user, parentId))) {
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier de destination.");
}
// Refuse un deplacement dans soi-meme ou dans un descendant : sans cela,
// l'arborescence se detache du graphe et devient inaccessible.
const descendants = await subtreeIds(db, id);
if (descendants.includes(parentId)) {
throw AppError.badRequest("Impossible de deplacer un dossier dans lui-meme.");
}
}
try {
await db.exec("UPDATE folders SET parent_id = ? WHERE id = ?", [parentId ?? null, id]);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Ce nom existe deja dans la destination.");
}
throw error;
}
const updated = await db.required<FolderRow>(`${SELECT_FOLDER} WHERE f.id = ?`, [id]);
await audit(db, context, user, "folder.move", "folder", id, { parentId: parentId ?? null }, config.TRUST_PROXY);
return context.json({ folder: publicFolder(updated) });
});
/** Suppression logique recursive : le dossier, ses descendants et leurs fichiers. */
app.delete("/api/cloud/folders/:id", requireAuth, async (context) => {
const user = currentUser(context);
const id = context.req.param("id") ?? "";
if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable.");
const existing = await db.one<FolderRow>(`${SELECT_FOLDER} WHERE f.id = ? AND f.deleted_at IS NULL`, [id]);
if (!existing) throw AppError.notFound("Dossier introuvable.");
if (existing.is_system === 1) throw AppError.forbidden("Le dossier public ne peut pas etre supprime.");
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
const ids = await subtreeIds(db, id);
const placeholders = ids.map(() => "?").join(",");
await db.transaction(async (connection) => {
await connection.execute(
`UPDATE folders SET deleted_at = UTC_TIMESTAMP() WHERE id IN (${placeholders}) AND deleted_at IS NULL`,
ids,
);
await connection.execute(
`UPDATE files SET deleted_at = UTC_TIMESTAMP() WHERE folder_id IN (${placeholders}) AND deleted_at IS NULL`,
ids,
);
});
await audit(db, context, user, "folder.delete", "folder", id, { name: existing.name }, config.TRUST_PROXY);
return context.json({ ok: true });
});
// --- Permissions nominatives -------------------------------------------
app.get("/api/cloud/folders/:id/permissions", requireAuth, async (context) => {
const user = currentUser(context);
const id = context.req.param("id") ?? "";
if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable.");
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
const rows = await db.query<{
user_id: string;
email: string;
first_name: string;
last_name: string;
level: string;
expires_at: string | null;
created_at: string;
}>(
`SELECT fp.user_id, u.email, u.first_name, u.last_name, fp.level, fp.expires_at, fp.created_at
FROM folder_permissions fp
JOIN users u ON u.id = fp.user_id
WHERE fp.folder_id = ?
ORDER BY u.email`,
[id],
);
return context.json({
permissions: rows.map((row) => ({
user_id: row.user_id,
email: row.email,
first_name: row.first_name,
last_name: row.last_name,
level: row.level,
expires_at: row.expires_at,
created_at: row.created_at,
})),
});
});
app.post("/api/cloud/folders/:id/permissions", requireAuth, async (context) => {
const user = currentUser(context);
const id = context.req.param("id") ?? "";
if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable.");
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
const { email, level, expiresAt } = parse(
permissionInput,
await context.req.json().catch(() => null),
);
const target = await db.one<{ id: string }>(
"SELECT id FROM users WHERE active_email = ? AND deleted_at IS NULL",
[email],
);
if (!target) throw AppError.notFound("Aucun compte ne correspond a cette adresse.");
if (target.id === user.id) {
throw AppError.badRequest("Vous etes deja proprietaire de ce dossier.");
}
const expires = expiresAt ? new Date(expiresAt) : null;
await db.exec(
`INSERT INTO folder_permissions (id, folder_id, user_id, level, expires_at, granted_by)
VALUES (?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE level = VALUES(level), expires_at = VALUES(expires_at), granted_by = VALUES(granted_by)`,
[randomUUID(), id, target.id, level, expires, user.id],
);
await audit(db, context, user, "folder.share", "folder", id, { email, level }, config.TRUST_PROXY);
return context.json({ ok: true }, 201);
});
app.delete("/api/cloud/folders/:id/permissions/:userId", requireAuth, async (context) => {
const user = currentUser(context);
const id = context.req.param("id") ?? "";
const userId = context.req.param("userId") ?? "";
if (!uuid.safeParse(id).success || !uuid.safeParse(userId).success) {
throw AppError.notFound("Dossier introuvable.");
}
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
const result = await db.exec(
"DELETE FROM folder_permissions WHERE folder_id = ? AND user_id = ?",
[id, userId],
);
if (result.affectedRows === 0) throw AppError.notFound("Partage introuvable.");
await audit(db, context, user, "folder.unshare", "folder", id, { userId }, config.TRUST_PROXY);
return context.json({ ok: true });
});
};
+85
View File
@@ -0,0 +1,85 @@
import {
AppError,
attachUser,
currentUser,
requireAuth,
type App,
type Db,
} from "@cohaise/server";
/**
* Galerie : liste des fichiers accompagnes de leur nature (image, video,
* document...), filtree par les memes droits que l'explorateur. Le dossier
* public et les permissions nominatives sont pris en compte, sans exception.
*/
const KINDS = ["image", "video", "audio", "document", "archive", "other"] as const;
export const registerMediaRoutes = (app: App, db: Db): void => {
app.use("/api/cloud/media", attachUser(db));
app.get("/api/cloud/media", requireAuth, async (context) => {
const user = currentUser(context);
const kind = context.req.query("kind") ?? "";
if (kind !== "" && !(KINDS as readonly string[]).includes(kind)) {
throw AppError.badRequest("Type de media inconnu.");
}
const limit = Math.min(200, Math.max(1, Number(context.req.query("limit")) || 60));
const offset = Math.max(0, Number(context.req.query("offset")) || 0);
const rows = await db.query<{
id: string;
folder_id: string | null;
name: string;
mime_type: string | null;
size_bytes: number;
owner_id: string | null;
is_starred: number;
kind: string | null;
width: number | null;
height: number | null;
created_at: string;
has_thumbnail: number;
}>(
`SELECT fi.id, fi.folder_id, fi.name, fi.mime_type, fi.size_bytes, fi.owner_id,
fi.is_starred, mm.kind, mm.width, mm.height, fi.created_at,
EXISTS ( SELECT 1 FROM file_variants fv
WHERE fv.file_id = fi.id AND fv.purpose = 'thumbnail' ) AS has_thumbnail
FROM files fi
LEFT JOIN media_metadata mm ON mm.file_id = fi.id
WHERE fi.deleted_at IS NULL
AND ( ? = '' OR mm.kind = ? )
AND ( ? = 1
OR fi.owner_id = ?
OR ( fi.folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folders f
WHERE f.id = fi.folder_id AND f.access_type = 'public' ) )
OR ( fi.folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folder_permissions fp
WHERE fp.folder_id = fi.folder_id AND fp.user_id = ?
AND fp.level IN ('read', 'write', 'admin')
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) ) )
ORDER BY fi.created_at DESC
LIMIT ${limit} OFFSET ${offset}`,
[kind, kind, user.role_slug === "admin" ? 1 : 0, user.id, user.id],
);
return context.json({
kind: kind || null,
items: rows.map((row) => ({
id: row.id,
folder_id: row.folder_id,
name: row.name,
mime_type: row.mime_type,
size_bytes: row.size_bytes,
owner_id: row.owner_id,
is_starred: row.is_starred === 1,
kind: row.kind,
width: row.width,
height: row.height,
created_at: row.created_at,
has_thumbnail: row.has_thumbnail === 1,
})),
});
});
};
+113
View File
@@ -0,0 +1,113 @@
import {
AppError,
attachUser,
currentUser,
requireAuth,
type App,
type Db,
} from "@cohaise/server";
/**
* Recherche par nom, filtree par les droits de la session. Le motif est
* echappe : `%` et `_` saisis par l'utilisateur deviennent des caracteres
* litteraux, jamais des jokers SQL. L'echappement par defaut de LIKE (barre
* oblique inverse) suffit.
*/
const escapeLike = (value: string): string =>
value.replace(/[\\%_]/g, (match) => `\\${match}`);
const LIMIT = 100;
export const registerSearchRoutes = (app: App, db: Db): void => {
app.use("/api/cloud/search", attachUser(db));
app.get("/api/cloud/search", requireAuth, async (context) => {
const user = currentUser(context);
const q = (context.req.query("q") ?? "").trim();
if (q.length < 1) throw AppError.badRequest("Indiquez un terme de recherche.");
const admin = user.role_slug === "admin";
const pattern = `%${escapeLike(q).slice(0, 110)}%`;
const folders = await db.query<{
id: string;
parent_id: string | null;
name: string;
description: string | null;
owner_id: string | null;
access_type: string;
created_at: string;
updated_at: string;
}>(
`SELECT f.id, f.parent_id, f.name, f.description, f.owner_id,
f.access_type, f.created_at, f.updated_at
FROM folders f
WHERE f.deleted_at IS NULL
AND f.name LIKE ?
AND ( ? = 1
OR f.owner_id = ?
OR f.access_type = 'public'
OR EXISTS ( SELECT 1 FROM folder_permissions fp
WHERE fp.folder_id = f.id AND fp.user_id = ?
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )
ORDER BY f.name
LIMIT ${LIMIT}`,
[pattern, admin ? 1 : 0, user.id, user.id],
);
const files = await db.query<{
id: string;
folder_id: string | null;
name: string;
mime_type: string | null;
size_bytes: number;
owner_id: string | null;
is_starred: number;
created_at: string;
updated_at: string;
}>(
`SELECT fi.id, fi.folder_id, fi.name, fi.mime_type, fi.size_bytes, fi.owner_id,
fi.is_starred, fi.created_at, fi.updated_at
FROM files fi
WHERE fi.deleted_at IS NULL
AND fi.name LIKE ?
AND ( ? = 1
OR fi.owner_id = ?
OR ( fi.folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folders f
WHERE f.id = fi.folder_id AND f.access_type = 'public' ) )
OR ( fi.folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folder_permissions fp
WHERE fp.folder_id = fi.folder_id AND fp.user_id = ?
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) ) )
ORDER BY fi.name
LIMIT ${LIMIT}`,
[pattern, admin ? 1 : 0, user.id, user.id],
);
return context.json({
query: q,
folders: folders.map((row) => ({
id: row.id,
parent_id: row.parent_id,
name: row.name,
description: row.description,
owner_id: row.owner_id,
access_type: row.access_type,
created_at: row.created_at,
updated_at: row.updated_at,
})),
files: files.map((row) => ({
id: row.id,
folder_id: row.folder_id,
name: row.name,
mime_type: row.mime_type,
size_bytes: row.size_bytes,
owner_id: row.owner_id,
is_starred: row.is_starred === 1,
created_at: row.created_at,
updated_at: row.updated_at,
})),
});
});
};
+378
View File
@@ -0,0 +1,378 @@
import { z } from "zod";
import {
AppError,
attachUser,
currentUser,
requireAuth,
type App,
type Config,
type Db,
} from "@cohaise/server";
import { audit } from "../access.js";
import { absolutePath, discard } from "../storage.js";
const uuid = z
.string()
.regex(
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
"Identifiant invalide.",
);
/**
* La corbeille se prete a l'echelle d'un utilisateur : un proprietaire voit ses
* propres elements supprimes, un administrateur voit tout. Un element supprime
* dont le parent est lui aussi supprime n'est pas liste : c'est la racine de la
* suppression qui porte l'action.
*/
const subtreeIds = async (db: Db, rootId: string): Promise<string[]> => {
const rows = await db.query<{ id: string }>(
`WITH RECURSIVE subtree AS (
SELECT id FROM folders WHERE id = ?
UNION ALL
SELECT f.id FROM folders f JOIN subtree s ON f.parent_id = s.id
)
SELECT id FROM subtree`,
[rootId],
);
return rows.map((row) => row.id);
};
/** Remonte la chaine des parents et annule leur suppression. */
const restoreAncestors = async (db: Db, folderId: string | null): Promise<void> => {
let current = folderId;
const guard = new Set<string>();
while (current !== null && !guard.has(current)) {
guard.add(current);
const parent = await db.one<{ parent_id: string | null }>(
"SELECT parent_id FROM folders WHERE id = ?",
[current],
);
if (!parent) break;
await db.exec("UPDATE folders SET deleted_at = NULL WHERE id = ?", [current]);
current = parent.parent_id;
}
};
/** Supprime physiquement des fichiers et rend leur espace aux quotas. */
const purgeFiles = async (db: Db, config: Config, fileIds: string[]): Promise<void> => {
if (fileIds.length === 0) return;
const placeholders = fileIds.map(() => "?").join(",");
const rows = await db.query<{
id: string;
relative_path: string;
size_bytes: number;
owner_id: string | null;
storage_location_id: number;
}>(
`SELECT id, relative_path, size_bytes, owner_id, storage_location_id
FROM files WHERE id IN (${placeholders})`,
fileIds,
);
await Promise.all(
rows.map((row) => discard(absolutePath(config.MEDIA_DIR, row.relative_path))),
);
await db.transaction(async (connection) => {
for (const row of rows) {
if (row.owner_id) {
await connection.execute(
"UPDATE users SET used_bytes = GREATEST(0, CAST(used_bytes AS SIGNED) - ?) WHERE id = ?",
[row.size_bytes, row.owner_id],
);
}
await connection.execute(
"UPDATE storage_locations SET used_bytes = GREATEST(0, CAST(used_bytes AS SIGNED) - ?) WHERE id = ?",
[row.size_bytes, row.storage_location_id],
);
}
await connection.execute(`DELETE FROM files WHERE id IN (${placeholders})`, fileIds);
});
};
/** Suppression definitive d'un dossier : ses fichiers puis lui-meme. */
const purgeFolderTree = async (db: Db, config: Config, rootId: string): Promise<void> => {
const folderIds = await subtreeIds(db, rootId);
const folderPlaceholders = folderIds.map(() => "?").join(",");
const files = await db.query<{ id: string }>(
`SELECT id FROM files WHERE folder_id IN (${folderPlaceholders})`,
folderIds,
);
await purgeFiles(db, config, files.map((row) => row.id));
await db.exec(`DELETE FROM folders WHERE id IN (${folderPlaceholders})`, folderIds);
};
interface TrashFileRow {
id: string;
folder_id: string | null;
name: string;
mime_type: string | null;
size_bytes: number;
owner_id: string | null;
created_at: string;
updated_at: string;
deleted_at: string;
}
interface TrashFolderRow {
id: string;
parent_id: string | null;
name: string;
description: string | null;
owner_id: string | null;
access_type: string;
created_at: string;
updated_at: string;
deleted_at: string;
}
const publicFile = (row: TrashFileRow) => ({
id: row.id,
folder_id: row.folder_id,
name: row.name,
mime_type: row.mime_type,
size_bytes: row.size_bytes,
owner_id: row.owner_id,
created_at: row.created_at,
updated_at: row.updated_at,
deleted_at: row.deleted_at,
});
const publicFolder = (row: TrashFolderRow) => ({
id: row.id,
parent_id: row.parent_id,
name: row.name,
description: row.description,
owner_id: row.owner_id,
access_type: row.access_type,
created_at: row.created_at,
updated_at: row.updated_at,
deleted_at: row.deleted_at,
});
export const registerTrashRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/trash/*", attachUser(db));
app.use("/api/cloud/trash", attachUser(db));
app.get("/api/cloud/trash", requireAuth, async (context) => {
const user = currentUser(context);
const admin = user.role_slug === "admin";
// Seuls les elements dont le parent n'est pas lui-meme supprime figurent en
// tete de corbeille : le reste suit la suppression du parent.
const folders = await db.query<TrashFolderRow>(
`SELECT f.id, f.parent_id, f.name, f.description, f.owner_id, f.access_type,
f.created_at, f.updated_at, f.deleted_at
FROM folders f
LEFT JOIN folders p ON p.id = f.parent_id
WHERE f.deleted_at IS NOT NULL
AND f.is_system = 0
AND (p.id IS NULL OR p.deleted_at IS NULL)
AND ( ? = 1 OR f.owner_id = ? )
ORDER BY f.deleted_at DESC`,
[admin ? 1 : 0, user.id],
);
const files = await db.query<TrashFileRow>(
`SELECT fi.id, fi.folder_id, fi.name, fi.mime_type, fi.size_bytes, fi.owner_id,
fi.created_at, fi.updated_at, fi.deleted_at
FROM files fi
LEFT JOIN folders p ON p.id = fi.folder_id
WHERE fi.deleted_at IS NOT NULL
AND (p.id IS NULL OR p.deleted_at IS NULL)
AND ( ? = 1 OR fi.owner_id = ? )
ORDER BY fi.deleted_at DESC`,
[admin ? 1 : 0, user.id],
);
const retentionDays = await db.one<{ setting_value: string }>(
"SELECT setting_value FROM settings WHERE setting_key = 'trash_retention_days'",
);
return context.json({
retentionDays: retentionDays ? Number(retentionDays.setting_value) : 30,
folders: folders.map(publicFolder),
files: files.map(publicFile),
});
});
app.post("/api/cloud/trash/folders/:id/restore", requireAuth, async (context) => {
const user = currentUser(context);
const id = context.req.param("id") ?? "";
if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable.");
const row = await db.one<{ owner_id: string | null; parent_id: string | null; name: string }>(
`SELECT owner_id, parent_id, name FROM folders
WHERE id = ? AND deleted_at IS NOT NULL AND is_system = 0`,
[id],
);
if (!row) throw AppError.notFound("Dossier introuvable.");
if (user.role_slug !== "admin" && row.owner_id !== user.id) {
throw AppError.notFound("Dossier introuvable.");
}
await restoreAncestors(db, row.parent_id);
const folderIds = await subtreeIds(db, id);
const placeholders = folderIds.map(() => "?").join(",");
try {
await db.transaction(async (connection) => {
await connection.execute(
`UPDATE folders SET deleted_at = NULL WHERE id IN (${placeholders})`,
folderIds,
);
await connection.execute(
`UPDATE files SET deleted_at = NULL WHERE folder_id IN (${placeholders})`,
folderIds,
);
});
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Un element du meme nom occupe deja cet emplacement.");
}
throw error;
}
await audit(db, context, user, "trash.restore", "folder", id, { name: row.name }, config.TRUST_PROXY);
return context.json({ ok: true });
});
app.post("/api/cloud/trash/files/:id/restore", requireAuth, async (context) => {
const user = currentUser(context);
const id = context.req.param("id") ?? "";
if (!uuid.safeParse(id).success) throw AppError.notFound("Fichier introuvable.");
const row = await db.one<{ owner_id: string | null; folder_id: string | null; name: string }>(
"SELECT owner_id, folder_id, name FROM files WHERE id = ? AND deleted_at IS NOT NULL",
[id],
);
if (!row) throw AppError.notFound("Fichier introuvable.");
if (user.role_slug !== "admin" && row.owner_id !== user.id) {
throw AppError.notFound("Fichier introuvable.");
}
await restoreAncestors(db, row.folder_id);
try {
await db.exec("UPDATE files SET deleted_at = NULL WHERE id = ?", [id]);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Un fichier du meme nom existe deja dans ce dossier.");
}
throw error;
}
await audit(db, context, user, "trash.restore", "file", id, { name: row.name }, config.TRUST_PROXY);
return context.json({ ok: true });
});
app.delete("/api/cloud/trash/folders/:id", requireAuth, async (context) => {
const user = currentUser(context);
const id = context.req.param("id") ?? "";
if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable.");
const row = await db.one<{ owner_id: string | null; name: string }>(
"SELECT owner_id, name FROM folders WHERE id = ? AND deleted_at IS NOT NULL AND is_system = 0",
[id],
);
if (!row) throw AppError.notFound("Dossier introuvable.");
if (user.role_slug !== "admin" && row.owner_id !== user.id) {
throw AppError.notFound("Dossier introuvable.");
}
await purgeFolderTree(db, config, id);
await audit(db, context, user, "trash.purge", "folder", id, { name: row.name }, config.TRUST_PROXY);
return context.json({ ok: true });
});
app.delete("/api/cloud/trash/files/:id", requireAuth, async (context) => {
const user = currentUser(context);
const id = context.req.param("id") ?? "";
if (!uuid.safeParse(id).success) throw AppError.notFound("Fichier introuvable.");
const row = await db.one<{ owner_id: string | null; name: string }>(
"SELECT owner_id, name FROM files WHERE id = ? AND deleted_at IS NOT NULL",
[id],
);
if (!row) throw AppError.notFound("Fichier introuvable.");
if (user.role_slug !== "admin" && row.owner_id !== user.id) {
throw AppError.notFound("Fichier introuvable.");
}
await purgeFiles(db, config, [id]);
await audit(db, context, user, "trash.purge", "file", id, { name: row.name }, config.TRUST_PROXY);
return context.json({ ok: true });
});
/** Vide la corbeille du compte appelant (tous les elements purges). */
app.delete("/api/cloud/trash", requireAuth, async (context) => {
const user = currentUser(context);
const admin = user.role_slug === "admin";
const folders = await db.query<{ id: string }>(
`SELECT f.id FROM folders f
LEFT JOIN folders p ON p.id = f.parent_id
WHERE f.deleted_at IS NOT NULL AND f.is_system = 0
AND (p.id IS NULL OR p.deleted_at IS NULL)
AND ( ? = 1 OR f.owner_id = ? )`,
[admin ? 1 : 0, user.id],
);
const files = await db.query<{ id: string }>(
`SELECT fi.id FROM files fi
LEFT JOIN folders p ON p.id = fi.folder_id
WHERE fi.deleted_at IS NOT NULL
AND (p.id IS NULL OR p.deleted_at IS NULL)
AND ( ? = 1 OR fi.owner_id = ? )`,
[admin ? 1 : 0, user.id],
);
for (const folder of folders) await purgeFolderTree(db, config, folder.id);
await purgeFiles(db, config, files.map((row) => row.id));
await audit(
db,
context,
user,
"trash.empty",
"trash",
null,
{ folders: folders.length, files: files.length },
config.TRUST_PROXY,
);
return context.json({ ok: true, folders: folders.length, files: files.length });
});
};
/**
* Purge planifiee : les elements supprimes au-dela de la retention disparaissent
* au demarrage. Aucun ordonnanceur externe n'est requis.
*/
export const purgeExpiredTrash = async (db: Db, config: Config): Promise<number> => {
const setting = await db.one<{ setting_value: string }>(
"SELECT setting_value FROM settings WHERE setting_key = 'trash_retention_days'",
);
const days = setting ? Number(setting.setting_value) : 30;
if (!Number.isFinite(days) || days <= 0) return 0;
const folders = await db.query<{ id: string }>(
`SELECT f.id FROM folders f
LEFT JOIN folders p ON p.id = f.parent_id
WHERE f.deleted_at IS NOT NULL AND f.is_system = 0
AND (p.id IS NULL OR p.deleted_at IS NULL)
AND f.deleted_at < UTC_TIMESTAMP() - INTERVAL ? DAY
ORDER BY f.deleted_at`,
[days],
);
const files = await db.query<{ id: string }>(
`SELECT fi.id FROM files fi
LEFT JOIN folders p ON p.id = fi.folder_id
WHERE fi.deleted_at IS NOT NULL
AND (p.id IS NULL OR p.deleted_at IS NULL)
AND fi.deleted_at < UTC_TIMESTAMP() - INTERVAL ? DAY
ORDER BY fi.deleted_at`,
[days],
);
for (const folder of folders) await purgeFolderTree(db, config, folder.id);
await purgeFiles(db, config, files.map((row) => row.id));
return folders.length + files.length;
};
+142
View File
@@ -0,0 +1,142 @@
import { createHash, randomUUID } from "node:crypto";
import { createReadStream, createWriteStream } from "node:fs";
import { mkdir, rename, rm, stat } from "node:fs/promises";
import path from "node:path";
import { Readable, Transform } from "node:stream";
import { pipeline } from "node:stream/promises";
import { AppError, type Db } from "@cohaise/server";
/**
* Chemin physique : ${MEDIA_DIR}/${slug emplacement}/${uuid}.
*
* Le nom affiche n'apparait jamais dans le chemin. Outre qu'il evite toute
* escape via "../", il empeche deux depots homonymes de se marcher dessus et
* rend l'arborescence disque ininteressante a parcourir pour un tiers.
*/
const SLUG = /^[a-z0-9][a-z0-9-]{0,99}$/;
const EXTENSION = /^[.][a-z0-9]{1,10}$/i;
export interface StoredLocation {
id: number;
slug: string;
}
/** Extension conservee pour la lisibilite sur disque, jamais pour le routage. */
const extensionOf = (name: string): string => {
const ext = path.posix.extname(name);
return EXTENSION.test(ext) ? ext.toLowerCase() : "";
};
export const relativePathFor = (slug: string, uuid: string, name: string): string =>
path.posix.join(slug, uuid + extensionOf(name));
const resolveInside = (mediaDir: string, relative: string): string => {
const base = path.resolve(mediaDir);
const target = path.resolve(base, relative);
if (target !== base && !target.startsWith(base + path.sep)) {
throw AppError.badRequest("Chemin de stockage invalide.");
}
return target;
};
export const absolutePath = (mediaDir: string, relative: string): string =>
resolveInside(mediaDir, relative);
/**
* Choix de l'emplacement : celui qui offre le plus de marge. Les comptes sont
* eux-memes plafonnes, donc cette valeur sert a ne pas remplir un support
* tandis qu'un autre reste vide.
*/
export const chooseLocation = async (db: Db, bytes: bigint): Promise<StoredLocation> => {
const rows = await db.query<{ id: number; slug: string; remaining: number | null }>(
`SELECT id, slug,
CASE WHEN quota_bytes IS NULL THEN NULL
ELSE quota_bytes - used_bytes END AS remaining
FROM storage_locations
WHERE is_active = 1 AND deleted_at IS NULL
ORDER BY (remaining IS NULL) DESC, remaining DESC, id
LIMIT 1`,
);
const row = rows[0];
if (!row || !SLUG.test(row.slug)) {
throw AppError.serviceUnavailable("Aucun emplacement de stockage disponible.");
}
if (row.remaining !== null && BigInt(row.remaining) < bytes) {
throw AppError.payloadTooLarge("L'espace disponible sur le support est insuffisant.");
}
return { id: row.id, slug: row.slug };
};
interface WriteResult {
size: number;
checksum: string;
}
/**
* Ecrit le corps de la requete sur disque en une seule passe : hachage,
* comptage et gravure avancent ensemble, sans jamais faire tenir le fichier
* en memoire. La lecture est interrompue des que la borne est depassee, donc
* un envoi enorme ne remplit pas d'abord le disque pour echouer ensuite.
*/
export const writeBody = async (
destination: string,
body: ReadableStream<Uint8Array>,
declared: number,
maxBytes: number,
): Promise<WriteResult> => {
const hash = createHash("sha256");
let received = 0;
const meter = new Transform({
transform(chunk: Buffer, _encoding, callback) {
received += chunk.length;
if (received > maxBytes) {
callback(AppError.payloadTooLarge(`Fichier trop volumineux (maximum ${maxBytes} octets).`));
return;
}
hash.update(chunk);
callback(null, chunk);
},
});
const source = Readable.fromWeb(body as Parameters<typeof Readable.fromWeb>[0]);
await pipeline(source, meter, createWriteStream(destination, { flags: "wx" }));
// Taille declaree et taille recue doivent concorder : sans quoi le quota
// aurait ete reserve sur une valeur que le disque n'a pas confirmee.
if (received !== declared) {
throw AppError.badRequest(
`Longueur incoherente : ${declared} octets annonces, ${received} recus.`,
);
}
return { size: received, checksum: hash.digest("hex") };
};
export const ensureDir = async (directory: string): Promise<void> => {
await mkdir(directory, { recursive: true });
};
/** Publie un fichier temporaire : meme systeme de fichiers, donc operation atomique. */
export const publish = async (temporary: string, destination: string): Promise<void> => {
await rename(temporary, destination);
};
export const discard = async (...paths: string[]): Promise<void> => {
await Promise.all(paths.map((entry) => rm(entry, { force: true }).catch(() => undefined)));
};
export const temporaryPath = (mediaDir: string, slug: string): string =>
path.join(path.resolve(mediaDir), slug, `.upload-${randomUUID()}`);
export const fileExists = async (absolute: string): Promise<boolean> => {
try {
const info = await stat(absolute);
return info.isFile();
} catch {
return false;
}
};
export const openForDownload = (absolute: string) => createReadStream(absolute);
+17
View File
@@ -0,0 +1,17 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2023"],
"types": ["node"],
"rootDir": "src",
"outDir": "dist",
"composite": true,
"declaration": true,
"sourceMap": true
},
"include": ["src/**/*.ts"],
"references": [{ "path": "../shared" }]
}