From cc397e96d8e876ab78c367e380eba783d46f4a5a Mon Sep 17 00:00:00 2001 From: xEsiah Date: Wed, 14 Oct 2026 15:24:06 +0200 Subject: [PATCH] chore: initial import of CoHaiSe Cloud 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. --- .dockerignore | 20 + .editorconfig | 12 + .env.example | 54 + .github/workflows/deploy.yml | 37 + .github/workflows/pr.yml | 49 + .github/workflows/renovate.yml | 33 + .gitignore | 24 + Makefile | 85 ++ README.md | 90 ++ backend/cloud/README.md | 207 +++ .../migrations/000_schema_migrations.sql | 5 + .../cloud/migrations/001_initial_schema.sql | 201 +++ .../cloud/migrations/002_reference_data.sql | 13 + .../migrations/003_integrity_backstop.sql | 6 + .../migrations/004_cloud_requirements.sql | 136 ++ .../005_storage_location_realign.sql | 25 + .../cloud/migrations/006_public_folder.sql | 24 + backend/cloud/package.json | 27 + backend/cloud/src/access.ts | 137 ++ backend/cloud/src/admin.ts | 174 +++ backend/cloud/src/index.ts | 37 + backend/cloud/src/media.ts | 141 +++ backend/cloud/src/routes/account.ts | 400 ++++++ backend/cloud/src/routes/admin.ts | 386 ++++++ backend/cloud/src/routes/auth.ts | 179 +++ backend/cloud/src/routes/files.ts | 528 ++++++++ backend/cloud/src/routes/folders.ts | 397 ++++++ backend/cloud/src/routes/media.ts | 85 ++ backend/cloud/src/routes/search.ts | 113 ++ backend/cloud/src/routes/trash.ts | 378 ++++++ backend/cloud/src/storage.ts | 142 +++ backend/cloud/tsconfig.json | 17 + backend/shared/package.json | 33 + backend/shared/src/auth.ts | 223 ++++ backend/shared/src/cli.ts | 137 ++ backend/shared/src/config.ts | 111 ++ backend/shared/src/db.ts | 107 ++ backend/shared/src/errors.ts | 97 ++ backend/shared/src/http.ts | 171 +++ backend/shared/src/index.ts | 50 + backend/shared/src/mail.ts | 48 + backend/shared/src/migrate.ts | 144 +++ backend/shared/src/ratelimit.ts | 52 + backend/shared/src/service.ts | 152 +++ backend/shared/tsconfig.json | 17 + docker-compose.yml | 167 +++ docker/Dockerfile | 9 + docker/Dockerfile.api | 39 + docker/Dockerfile.app | 18 + docker/README.md | 102 ++ docker/nginx/cloud.conf | 62 + docker/nginx/snippets/cache-immutable.conf | 1 + docker/nginx/snippets/cache-no-cache.conf | 1 + docker/nginx/snippets/proxy-api.conf | 14 + docker/nginx/snippets/security-headers.conf | 8 + docker/publish.sh | 17 + docs/agents.md | 75 ++ docs/api.md | 140 ++ docs/architecture.md | 96 ++ docs/deployment.md | 191 +++ docs/security.md | 78 ++ docs/standards.md | 59 + docs/workflow.md | 93 ++ frontend/cloud/index.html | 14 + frontend/cloud/package.json | 27 + frontend/cloud/public/theme.js | 10 + frontend/cloud/src/App.tsx | 73 ++ frontend/cloud/src/components/AppShell.tsx | 154 +++ frontend/cloud/src/components/IconAction.tsx | 31 + frontend/cloud/src/components/dialogs.tsx | 381 ++++++ frontend/cloud/src/components/feedback.tsx | 136 ++ frontend/cloud/src/components/icons.tsx | 160 +++ frontend/cloud/src/lib/api.ts | 370 ++++++ frontend/cloud/src/lib/session.tsx | 58 + frontend/cloud/src/main.tsx | 22 + frontend/cloud/src/pages/Admin.tsx | 753 +++++++++++ frontend/cloud/src/pages/Browser.tsx | 449 +++++++ frontend/cloud/src/pages/ChangePassword.tsx | 108 ++ frontend/cloud/src/pages/ConfirmEmail.tsx | 81 ++ frontend/cloud/src/pages/ForgotPassword.tsx | 91 ++ frontend/cloud/src/pages/Gallery.tsx | 142 +++ frontend/cloud/src/pages/Login.tsx | 91 ++ frontend/cloud/src/pages/Profile.tsx | 316 +++++ frontend/cloud/src/pages/ResetPassword.tsx | 106 ++ frontend/cloud/src/pages/Search.tsx | 138 ++ frontend/cloud/src/pages/Trash.tsx | 185 +++ frontend/cloud/src/styles/index.css | 4 + frontend/cloud/tsconfig.json | 11 + frontend/cloud/vite.config.ts | 19 + frontend/shared/README.md | 186 +++ frontend/shared/fonts/cinzel-latin.woff2 | Bin 0 -> 25904 bytes .../shared/fonts/jetbrains-mono-latin.woff2 | Bin 0 -> 31432 bytes frontend/shared/fonts/orbitron-latin.woff2 | Bin 0 -> 11800 bytes frontend/shared/fonts/poppins-400.woff2 | Bin 0 -> 7884 bytes frontend/shared/fonts/poppins-600.woff2 | Bin 0 -> 8000 bytes frontend/shared/package.json | 38 + frontend/shared/src/components/Button.tsx | 72 ++ frontend/shared/src/components/Card.tsx | 49 + frontend/shared/src/components/Input.tsx | 72 ++ frontend/shared/src/components/Skeleton.tsx | 32 + frontend/shared/src/components/Spinner.tsx | 36 + frontend/shared/src/index.ts | 10 + frontend/shared/src/lib/cn.ts | 5 + frontend/shared/src/styles/fonts.css | 61 + frontend/shared/src/styles/index.css | 3 + frontend/shared/src/styles/theme.css | 105 ++ frontend/shared/src/styles/tokens.css | 176 +++ frontend/shared/tsconfig.json | 15 + package-lock.json | 1128 +++++++++++++++++ package.json | 21 + renovate.json | 27 + tsconfig.base.json | 23 + tsconfig.json | 15 + 113 files changed, 12678 insertions(+) create mode 100644 .dockerignore create mode 100644 .editorconfig create mode 100644 .env.example create mode 100644 .github/workflows/deploy.yml create mode 100644 .github/workflows/pr.yml create mode 100644 .github/workflows/renovate.yml create mode 100644 .gitignore create mode 100644 Makefile create mode 100644 README.md create mode 100644 backend/cloud/README.md create mode 100644 backend/cloud/migrations/000_schema_migrations.sql create mode 100644 backend/cloud/migrations/001_initial_schema.sql create mode 100644 backend/cloud/migrations/002_reference_data.sql create mode 100644 backend/cloud/migrations/003_integrity_backstop.sql create mode 100644 backend/cloud/migrations/004_cloud_requirements.sql create mode 100644 backend/cloud/migrations/005_storage_location_realign.sql create mode 100644 backend/cloud/migrations/006_public_folder.sql create mode 100644 backend/cloud/package.json create mode 100644 backend/cloud/src/access.ts create mode 100644 backend/cloud/src/admin.ts create mode 100644 backend/cloud/src/index.ts create mode 100644 backend/cloud/src/media.ts create mode 100644 backend/cloud/src/routes/account.ts create mode 100644 backend/cloud/src/routes/admin.ts create mode 100644 backend/cloud/src/routes/auth.ts create mode 100644 backend/cloud/src/routes/files.ts create mode 100644 backend/cloud/src/routes/folders.ts create mode 100644 backend/cloud/src/routes/media.ts create mode 100644 backend/cloud/src/routes/search.ts create mode 100644 backend/cloud/src/routes/trash.ts create mode 100644 backend/cloud/src/storage.ts create mode 100644 backend/cloud/tsconfig.json create mode 100644 backend/shared/package.json create mode 100644 backend/shared/src/auth.ts create mode 100644 backend/shared/src/cli.ts create mode 100644 backend/shared/src/config.ts create mode 100644 backend/shared/src/db.ts create mode 100644 backend/shared/src/errors.ts create mode 100644 backend/shared/src/http.ts create mode 100644 backend/shared/src/index.ts create mode 100644 backend/shared/src/mail.ts create mode 100644 backend/shared/src/migrate.ts create mode 100644 backend/shared/src/ratelimit.ts create mode 100644 backend/shared/src/service.ts create mode 100644 backend/shared/tsconfig.json create mode 100644 docker-compose.yml create mode 100644 docker/Dockerfile create mode 100644 docker/Dockerfile.api create mode 100644 docker/Dockerfile.app create mode 100644 docker/README.md create mode 100644 docker/nginx/cloud.conf create mode 100644 docker/nginx/snippets/cache-immutable.conf create mode 100644 docker/nginx/snippets/cache-no-cache.conf create mode 100644 docker/nginx/snippets/proxy-api.conf create mode 100644 docker/nginx/snippets/security-headers.conf create mode 100644 docker/publish.sh create mode 100644 docs/agents.md create mode 100644 docs/api.md create mode 100644 docs/architecture.md create mode 100644 docs/deployment.md create mode 100644 docs/security.md create mode 100644 docs/standards.md create mode 100644 docs/workflow.md create mode 100644 frontend/cloud/index.html create mode 100644 frontend/cloud/package.json create mode 100644 frontend/cloud/public/theme.js create mode 100644 frontend/cloud/src/App.tsx create mode 100644 frontend/cloud/src/components/AppShell.tsx create mode 100644 frontend/cloud/src/components/IconAction.tsx create mode 100644 frontend/cloud/src/components/dialogs.tsx create mode 100644 frontend/cloud/src/components/feedback.tsx create mode 100644 frontend/cloud/src/components/icons.tsx create mode 100644 frontend/cloud/src/lib/api.ts create mode 100644 frontend/cloud/src/lib/session.tsx create mode 100644 frontend/cloud/src/main.tsx create mode 100644 frontend/cloud/src/pages/Admin.tsx create mode 100644 frontend/cloud/src/pages/Browser.tsx create mode 100644 frontend/cloud/src/pages/ChangePassword.tsx create mode 100644 frontend/cloud/src/pages/ConfirmEmail.tsx create mode 100644 frontend/cloud/src/pages/ForgotPassword.tsx create mode 100644 frontend/cloud/src/pages/Gallery.tsx create mode 100644 frontend/cloud/src/pages/Login.tsx create mode 100644 frontend/cloud/src/pages/Profile.tsx create mode 100644 frontend/cloud/src/pages/ResetPassword.tsx create mode 100644 frontend/cloud/src/pages/Search.tsx create mode 100644 frontend/cloud/src/pages/Trash.tsx create mode 100644 frontend/cloud/src/styles/index.css create mode 100644 frontend/cloud/tsconfig.json create mode 100644 frontend/cloud/vite.config.ts create mode 100644 frontend/shared/README.md create mode 100644 frontend/shared/fonts/cinzel-latin.woff2 create mode 100644 frontend/shared/fonts/jetbrains-mono-latin.woff2 create mode 100644 frontend/shared/fonts/orbitron-latin.woff2 create mode 100644 frontend/shared/fonts/poppins-400.woff2 create mode 100644 frontend/shared/fonts/poppins-600.woff2 create mode 100644 frontend/shared/package.json create mode 100644 frontend/shared/src/components/Button.tsx create mode 100644 frontend/shared/src/components/Card.tsx create mode 100644 frontend/shared/src/components/Input.tsx create mode 100644 frontend/shared/src/components/Skeleton.tsx create mode 100644 frontend/shared/src/components/Spinner.tsx create mode 100644 frontend/shared/src/index.ts create mode 100644 frontend/shared/src/lib/cn.ts create mode 100644 frontend/shared/src/styles/fonts.css create mode 100644 frontend/shared/src/styles/index.css create mode 100644 frontend/shared/src/styles/theme.css create mode 100644 frontend/shared/src/styles/tokens.css create mode 100644 frontend/shared/tsconfig.json create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 renovate.json create mode 100644 tsconfig.base.json create mode 100644 tsconfig.json diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..0eff9ca --- /dev/null +++ b/.dockerignore @@ -0,0 +1,20 @@ +node_modules +**/node_modules +**/dist +**/build +**/*.tsbuildinfo +**/.env +**/.env.* +!**/.env.example +.git +.gitignore +.vscode +.idea +*.log +npm-debug.log* +.DS_Store +Thumbs.db +docs +README.md +**/*.md +Makefile diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..8c52ff9 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,12 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_style = space +indent_size = 2 +insert_final_newline = true +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..6c9d947 --- /dev/null +++ b/.env.example @@ -0,0 +1,54 @@ +# CoHaiSe Cloud — modele de configuration.non + +# --- Pont HTTP ----------------------------------------------------------- +# Port ouvert par nginx sur la machine hote. +COHAISE_HTTP_PORT=8083 + +# --- Base --------------------------------------------------------------- +COHAISE_DB_PORT=3407 +CLOUD_DATABASE=cohaise_cloud +CLOUD_DB_USER=cohaise_cloud +CLOUD_DB_PASSWORD= +# Mot de passe root du conteneur, utilise uniquement par la sauvegarde. +CLOUD_DB_ROOT_PASSWORD= + +# --- Session (obligatoire pour toute API) ------------------------------- +# Secret de chiffrement des sessions. Obligatoire, 32 caracteres minimum. +# Generation : +# node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))" +SESSION_SECRET= +# Duree de vie d'une session, en heures (336 = 14 jours). +SESSION_TTL_HOURS=336 + +# --- API ----------------------------------------------------------------- +COHAISE_API_PORT=3101 +# Origine publique absolue : sert aux liens envoyes par courriel +# (reinitialisation de mot de passe, changement d'adresse). Obligatoire. +PUBLIC_ORIGIN=https://cloud.exemple.fr +# Origines autorisees pour CORS, separes par des virgules. Vide = desactive. +CLOUD_CORS_ORIGIN= +# Connexions simultanees a la base par instance d'API. +CLOUD_DB_CONNECTION_LIMIT=8 + +# --- Courriel (SMTP) ------------------------------------------------------ +# Obligatoire : l'API refuse de demarrer sans. Un relais local sans +# authentification est accepte (laisser SMTP_USER et SMTP_PASSWORD vides). +SMTP_HOST= +SMTP_PORT=587 +SMTP_USER= +SMTP_PASSWORD= +# Adresse d'expedition, ex. "CoHaiSe Cloud ". +SMTP_FROM= +# true si le serveur SMTP exige TLS des la connexion (port 465). +SMTP_SECURE=false + +# --- Limitation des connexions ------------------------------------------- +# Tentatives de connexion autorisees par fenetre et par IP. +RATE_LIMIT_LOGIN_MAX=10 +RATE_LIMIT_LOGIN_WINDOW_MS=60000 + +# --- Exploitation -------------------------------------------------------- +# silent | error | warn | info | debug +LOG_LEVEL=info +# true si une reverse proxy (nginx) termine TLS devant l'API. +TRUST_PROXY=true diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..b4f2995 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,37 @@ +name: CD — Déploiement + +on: + push: + branches: [main] + paths: + - "backend/**" + - "frontend/**" + - "docker/**" + - "docker-compose.yml" + - "Makefile" + - ".github/workflows/deploy.yml" + workflow_dispatch: + +concurrency: + group: deploy-cloud + cancel-in-progress: false + +jobs: + deploy: + runs-on: self-hosted + steps: + - name: Récupérer puis reconstruire + env: + # Chemin du dépôt sur le serveur. Défini via le secret DEPLOY_DIR si + # besoin ; sinon la valeur par défaut ci-dessous est utilisée. + DEPLOY_DIR: ${{ secrets.DEPLOY_DIR }} + run: | + set -eu + dir="${DEPLOY_DIR:-/srv/apps/cohaise-cloud/CoHaiSe-CLOUD}" + cd "$dir" + git pull --ff-only origin main + make check + make front + docker compose build api nginx + docker compose up -d api nginx + docker image prune -f diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml new file mode 100644 index 0000000..7877bc0 --- /dev/null +++ b/.github/workflows/pr.yml @@ -0,0 +1,49 @@ +name: PR — Ouverture automatique + +on: + push: + branches-ignore: [main] + +jobs: + create-pr: + runs-on: self-hosted + permissions: + contents: write + pull-requests: write + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Ouvrir (ou vérifier) la pull request + env: + GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} + API: ${{ github.server_url }}/api/v1 + REPO: ${{ github.repository }} + BRANCH: ${{ github.ref_name }} + run: | + set -eu + title=$(git log -1 --pretty=%s) + body=$(git log -1 --pretty=%b) + [ -n "$body" ] || body="PR automatique de $BRANCH vers main." + + open=$(curl -fsS -H "Authorization: token $GITEA_TOKEN" \ + "$API/repos/$REPO/pulls?state=open&limit=50" \ + | python3 -c 'import json,os,sys; b=os.environ["BRANCH"]; print(sum(1 for p in json.load(sys.stdin) if p.get("head", {}).get("ref") == b))') + if [ "$open" -gt 0 ]; then + echo "Une PR est déjà ouverte pour $BRANCH." + exit 0 + fi + + python3 - "$BRANCH" "$title" "$body" <<'PY' > /tmp/pr.json + import json, sys + branch, title, body = sys.argv[1], sys.argv[2], sys.argv[3] + print(json.dumps({"base": "main", "head": branch, "title": title, "body": body})) + PY + + curl -fsS -X POST \ + -H "Authorization: token $GITEA_TOKEN" \ + -H "Content-Type: application/json" \ + --data @/tmp/pr.json \ + "$API/repos/$REPO/pulls" + echo "PR créée." diff --git a/.github/workflows/renovate.yml b/.github/workflows/renovate.yml new file mode 100644 index 0000000..6a854cb --- /dev/null +++ b/.github/workflows/renovate.yml @@ -0,0 +1,33 @@ +name: Renovate + +on: + schedule: + - cron: "0 4 * * 1" + workflow_dispatch: + +concurrency: + group: renovate + cancel-in-progress: false + +jobs: + renovate: + runs-on: self-hosted + steps: + - name: Mettre à jour les dépendances + env: + RENOVATE_PLATFORM: gitea + RENOVATE_ENDPOINT: ${{ github.server_url }} + RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }} + RENOVATE_REPOSITORIES: ${{ github.repository }} + run: | + set -eu + mkdir -p /srv/apps/cohaise-cloud/renovate-cache + docker run --rm \ + -e RENOVATE_PLATFORM \ + -e RENOVATE_ENDPOINT \ + -e RENOVATE_TOKEN \ + -e RENOVATE_REPOSITORIES \ + -e RENOVATE_ONBOARDING=false \ + -e LOG_LEVEL=info \ + -v /srv/apps/cohaise-cloud/renovate-cache:/tmp/renovate \ + ghcr.io/renovatebot/renovate:latest diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2e31670 --- /dev/null +++ b/.gitignore @@ -0,0 +1,24 @@ +node_modules/ +dist/ +build/ +coverage/ +.vite/ +*.tsbuildinfo + +# Sauvegardes de base : contiennent les donnees, jamais versionnees. +backups/ + +.env +.env.* +!.env.example + +*.log +npm-debug.log* + +.DS_Store +Thumbs.db + +.idea/ +.vscode/* +!.vscode/extensions.json +!.vscode/settings.json diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..f47e47c --- /dev/null +++ b/Makefile @@ -0,0 +1,85 @@ +COMPOSE=docker compose + +.PHONY: help up down build logs ps front front-build db migrate admin backup dev typecheck check + +help: + @echo "CoHaiSe Cloud" + @echo "" + @echo " make up Demarrer l'app (front, API, base)" + @echo " make down Arreter (les volumes sont conserves)" + @echo " make ps Etat des conteneurs" + @echo " make logs Suivre les journaux" + @echo " make build Construire les images sans arreter" + @echo "" + @echo "Publication" + @echo " make front Reconstruire et publier le front" + @echo " make front-build Construire l'image du front sans publier" + @echo "" + @echo "Donnees" + @echo " make db Redemarrer la base" + @echo " make migrate Appliquer les migrations SQL" + @echo " make backup Sauvegarder la base dans ./backups" + @echo " make admin ARGS=... Creer ou reinitialiser un compte" + @echo "" + @echo "Developpement, sans Docker" + @echo " make dev Vite sur 5174, API sur 3101" + @echo "" + @echo "Verification" + @echo " make typecheck Verifier les types" + @echo " make check typecheck + build" + +up: + $(COMPOSE) up -d + +down: + $(COMPOSE) down + +build: + $(COMPOSE) build + +logs: + $(COMPOSE) logs -f + +ps: + $(COMPOSE) ps + +front: + $(COMPOSE) up -d --build --force-recreate app-build + +front-build: + $(COMPOSE) build app-build + +db: + $(COMPOSE) restart db + +# Chemin explicite, utilisable avant le premier demarrage comme pour verifier +# qu'aucune migration n'a ete oubliee. Les migrations partent aussi +# automatiquement au demarrage (depends_on: service_completed_successfully). +migrate: + $(COMPOSE) build migrate + $(COMPOSE) run --rm migrate + +# Dump SQL compresse, horodate, ecrit dans ./backups (jamais versionne). +# Le mot de passe est lu par le conteneur lui-meme : il ne transitent ni par la +# ligne de commande ni par le depot. +backup: + @mkdir -p backups + @stamp=$$(date +%Y%m%dT%H%M%SZ); \ + $(COMPOSE) exec -T db sh -c 'mariadb-dump --single-transaction --routines --events --password="$$MARIADB_ROOT_PASSWORD" "$$MARIADB_DATABASE"' | gzip > backups/cloud-$$stamp.sql.gz; \ + echo " backups/cloud-$$stamp.sql.gz $$(du -h backups/cloud-$$stamp.sql.gz | cut -f1)" + +# Cree ou reinitialise un compte. Ne lit que les variables de base : usable +# meme tant que l'API ne peut pas demarrer. +# make admin ARGS="--email a@b.c --first Jean --last Dupont" +# make admin ARGS="--email a@b.c --reset" +admin: + $(COMPOSE) run --rm --no-deps api node dist/admin.js $(ARGS) + +dev: + npm run dev --workspace=frontend/cloud + +typecheck: + npm run typecheck + +check: typecheck + npm run build diff --git a/README.md b/README.md new file mode 100644 index 0000000..91acdf4 --- /dev/null +++ b/README.md @@ -0,0 +1,90 @@ +# CoHaiSe Cloud + +Fichiers et médias : arborescence de dossiers, envoi, téléchargement. +Application autonome — front **et** back dans ce dépôt. + +## Structure + +``` +frontend/shared design system (@cohaise/ui) — copie propre à cette app +frontend/cloud application React + Vite +backend/shared couche serveur (@cohaise/server) : config, base, sessions +backend/cloud API : auth, dossiers, fichiers +docker/ images nginx et API +``` + +Les paquets `shared` (design system et couche serveur) vivent dans ce dépôt et en +suivent le cycle de vie : un correctif ici n'a pas à être répliqué ailleurs. + +## Démarrer + +```bash +cp .env.example .env # puis renseigner les mots de passe et SESSION_SECRET +make up # front + API + base, migrations comprises +make front # reconstruire et publier le front +``` + +L'app répond sur **`http://localhost:8083`** (variable `COHAISE_HTTP_PORT`). + +| Variable | Rôle | Défaut | +|---|---|---| +| `COHAISE_HTTP_PORT` | port nginx côté machine hôte | `8083` | +| `COHAISE_API_PORT` | port de l'API | `3101` | +| `COHAISE_DB_PORT` | port MariaDB | `3407` | +| `CLOUD_DB_USER` / `CLOUD_DB_PASSWORD` | identifiants base | — | +| `CLOUD_DB_ROOT_PASSWORD` | root, pour la sauvegarde | — | +| `SESSION_SECRET` | signature des sessions, obligatoire | — | + +Le démarrage échoue avec la liste exacte des variables manquantes ou mal formées, +avant l'ouverture d'aucun port. C'est voulu. + +## Commandes + +```bash +make help # liste complète +make ps # état des conteneurs +make logs # journaux +make front # reconstruire et publier le front +make migrate # appliquer les migrations SQL explicitement +make backup # dump horodaté dans ./backups +make admin ARGS=... # créer ou réinitialiser un compte +make dev # Vite sur 5174, API sur 3101, sans Docker +make check # typecheck + build +``` + +### Comptes + +Le premier compte se crée par CLI, jamais par une route publique : + +```bash +make admin ARGS="--email moi@exemple.fr --first Jean --last Dupont" +make admin ARGS="--email moi@exemple.fr --reset" +``` + +Les mots de passe sont lus par le conteneur lui-même : ils ne transitent ni par la +ligne de commande ni par le dépôt. + +## Migrations + +Les fichiers sont numérotés et appliqués dans l'ordre. Une migration déjà appliquée +ne se modifie jamais : une correction passe par un nouveau fichier. + +| Fichier | Contenu | +|---|---| +| `000_schema_migrations.sql` | table de suivi des versions | +| `001_initial_schema.sql` | schéma initial | +| `002_reference_data.sql` | rôles, étapes, pays, réglages | +| `003_integrity_backstop.sql` | clé étrangère `users.role_id`, `CHECK` d'intégrité | +| `004_cloud_requirements.sql` | exigences du Cloud | +| `005_storage_location_realign.sql` | emplacement physique des fichiers | + +Au démarrage, `runMigrations()` ne joue que les migrations manquantes, et +`assertNoDrift()` refuse de servir si un fichier déjà appliqué a été modifié entre +temps : une base non maîtrisée rend l'API inaccessible plutôt que de renvoyer des +erreurs 500. + +## Tests + +```bash +make check # types + build +``` diff --git a/backend/cloud/README.md b/backend/cloud/README.md new file mode 100644 index 0000000..178b91c --- /dev/null +++ b/backend/cloud/README.md @@ -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}//`, +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). diff --git a/backend/cloud/migrations/000_schema_migrations.sql b/backend/cloud/migrations/000_schema_migrations.sql new file mode 100644 index 0000000..103c6ba --- /dev/null +++ b/backend/cloud/migrations/000_schema_migrations.sql @@ -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; diff --git a/backend/cloud/migrations/001_initial_schema.sql b/backend/cloud/migrations/001_initial_schema.sql new file mode 100644 index 0000000..a54413e --- /dev/null +++ b/backend/cloud/migrations/001_initial_schema.sql @@ -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; diff --git a/backend/cloud/migrations/002_reference_data.sql b/backend/cloud/migrations/002_reference_data.sql new file mode 100644 index 0000000..b169163 --- /dev/null +++ b/backend/cloud/migrations/002_reference_data.sql @@ -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'); diff --git a/backend/cloud/migrations/003_integrity_backstop.sql b/backend/cloud/migrations/003_integrity_backstop.sql new file mode 100644 index 0000000..825d435 --- /dev/null +++ b/backend/cloud/migrations/003_integrity_backstop.sql @@ -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); diff --git a/backend/cloud/migrations/004_cloud_requirements.sql b/backend/cloud/migrations/004_cloud_requirements.sql new file mode 100644 index 0000000..7b03f07 --- /dev/null +++ b/backend/cloud/migrations/004_cloud_requirements.sql @@ -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; diff --git a/backend/cloud/migrations/005_storage_location_realign.sql b/backend/cloud/migrations/005_storage_location_realign.sql new file mode 100644 index 0000000..43ca475 --- /dev/null +++ b/backend/cloud/migrations/005_storage_location_realign.sql @@ -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; diff --git a/backend/cloud/migrations/006_public_folder.sql b/backend/cloud/migrations/006_public_folder.sql new file mode 100644 index 0000000..84e6908 --- /dev/null +++ b/backend/cloud/migrations/006_public_folder.sql @@ -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'); diff --git a/backend/cloud/package.json b/backend/cloud/package.json new file mode 100644 index 0000000..7fb2470 --- /dev/null +++ b/backend/cloud/package.json @@ -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" + } +} diff --git a/backend/cloud/src/access.ts b/backend/cloud/src/access.ts new file mode 100644 index 0000000..7d8d1fb --- /dev/null +++ b/backend/cloud/src/access.ts @@ -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 => { + 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 => { + 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 => { + 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 => { + 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 | null, + trustProxy: boolean, +): Promise => { + 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); +}; diff --git a/backend/cloud/src/admin.ts b/backend/cloud/src/admin.ts new file mode 100644 index 0000000..ace2c61 --- /dev/null +++ b/backend/cloud/src/admin.ts @@ -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 a@b.c --first Jean --last Dupont [--role admin] + * node dist/admin.js --email a@b.c --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 --first --last [options] + + --email Adresse du compte (obligatoire) + --first Prenom (obligatoire a la creation) + --last Nom (obligatoire a la creation) + --role admin | user (defaut : admin) + --password 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 => { + 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); + }, +); diff --git a/backend/cloud/src/index.ts b/backend/cloud/src/index.ts new file mode 100644 index 0000000..8bfa78e --- /dev/null +++ b/backend/cloud/src/index.ts @@ -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 }); + }, +}); diff --git a/backend/cloud/src/media.ts b/backend/cloud/src/media.ts new file mode 100644 index 0000000..dd0eedc --- /dev/null +++ b/backend/cloud/src/media.ts @@ -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 => { + 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 => { + 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 => { + 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 => { + try { + const info = await stat(absolutePath(config.VARIANT_DIR, relative)); + return info.size; + } catch { + return null; + } +}; diff --git a/backend/cloud/src/routes/account.ts b/backend/cloud/src/routes/account.ts new file mode 100644 index 0000000..e3b9202 --- /dev/null +++ b/backend/cloud/src/routes/account.ts @@ -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 = (schema: z.ZodType, 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[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; + 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 }); + }); +}; diff --git a/backend/cloud/src/routes/admin.ts b/backend/cloud/src/routes/admin.ts new file mode 100644 index 0000000..65b81db --- /dev/null +++ b/backend/cloud/src/routes/admin.ts @@ -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 = (schema: z.ZodType, 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[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( + `${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( + `${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(`${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(`${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(`${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 }); + }); +}; diff --git a/backend/cloud/src/routes/auth.ts b/backend/cloud/src/routes/auth.ts new file mode 100644 index 0000000..1327a04 --- /dev/null +++ b/backend/cloud/src/routes/auth.ts @@ -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 | undefined; +const decoyHash = (): Promise => (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(`${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(`${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 }); + }); +}; diff --git a/backend/cloud/src/routes/files.ts b/backend/cloud/src/routes/files.ts new file mode 100644 index 0000000..21869ea --- /dev/null +++ b/backend/cloud/src/routes/files.ts @@ -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 = (schema: z.ZodType, 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(`${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( + `${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(`${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; + + 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(`${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; + 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(`${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(`${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(`${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(`${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(`${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(`${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(`${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 }); + }); +}; diff --git a/backend/cloud/src/routes/folders.ts b/backend/cloud/src/routes/folders.ts new file mode 100644 index 0000000..54ab944 --- /dev/null +++ b/backend/cloud/src/routes/folders.ts @@ -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 = (schema: z.ZodType, 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 => { + 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( + `${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(`${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(`${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(`${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(`${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(`${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(`${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 }); + }); +}; diff --git a/backend/cloud/src/routes/media.ts b/backend/cloud/src/routes/media.ts new file mode 100644 index 0000000..dddf7d2 --- /dev/null +++ b/backend/cloud/src/routes/media.ts @@ -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, + })), + }); + }); +}; diff --git a/backend/cloud/src/routes/search.ts b/backend/cloud/src/routes/search.ts new file mode 100644 index 0000000..8bbe2cb --- /dev/null +++ b/backend/cloud/src/routes/search.ts @@ -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, + })), + }); + }); +}; diff --git a/backend/cloud/src/routes/trash.ts b/backend/cloud/src/routes/trash.ts new file mode 100644 index 0000000..2b38d26 --- /dev/null +++ b/backend/cloud/src/routes/trash.ts @@ -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 => { + 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 => { + let current = folderId; + const guard = new Set(); + 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 => { + 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 => { + 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( + `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( + `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 => { + 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; +}; diff --git a/backend/cloud/src/storage.ts b/backend/cloud/src/storage.ts new file mode 100644 index 0000000..8d2f81e --- /dev/null +++ b/backend/cloud/src/storage.ts @@ -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 => { + 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, + declared: number, + maxBytes: number, +): Promise => { + 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[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 => { + 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 => { + await rename(temporary, destination); +}; + +export const discard = async (...paths: string[]): Promise => { + 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 => { + try { + const info = await stat(absolute); + return info.isFile(); + } catch { + return false; + } +}; + +export const openForDownload = (absolute: string) => createReadStream(absolute); diff --git a/backend/cloud/tsconfig.json b/backend/cloud/tsconfig.json new file mode 100644 index 0000000..ab1723a --- /dev/null +++ b/backend/cloud/tsconfig.json @@ -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" }] +} diff --git a/backend/shared/package.json b/backend/shared/package.json new file mode 100644 index 0000000..204681c --- /dev/null +++ b/backend/shared/package.json @@ -0,0 +1,33 @@ +{ + "name": "@cohaise/server", + "version": "0.0.0", + "private": true, + "type": "module", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "files": [ + "dist" + ], + "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" + }, + "devDependencies": { + "@types/node": "^24.0.0", + "typescript": "^7.0.2" + }, + "dependencies": { + "@hono/node-server": "^2.1.3", + "hono": "^4.13.13", + "mysql2": "^3.24.5", + "zod": "^4.6.5" + }, + "bin": { + "cohaise-migrate": "./dist/cli.js" + } +} diff --git a/backend/shared/src/auth.ts b/backend/shared/src/auth.ts new file mode 100644 index 0000000..a33344f --- /dev/null +++ b/backend/shared/src/auth.ts @@ -0,0 +1,223 @@ +import { createHash, randomBytes, randomUUID, scrypt as scryptCallback, timingSafeEqual } from "node:crypto"; +import { promisify } from "node:util"; +import type { Context, Next } from "hono"; +import { getCookie, setCookie, deleteCookie } from "hono/cookie"; +import type { Db } from "./db.js"; +import { AppError } from "./errors.js"; + +const scrypt = promisify(scryptCallback) as ( + password: string | Buffer, + salt: Buffer, + keylen: number, + options: { N: number; r: number; p: number; maxmem?: number }, +) => Promise; + +/** + * scrypt du module natif, pas une dependance externe. Une lib native a compiler + * est la facon la plus rapide de casser un build sur une machine cible : argon2 + * ou bcrypt produisent un binaire qui n'est pas portable sans outilchain. + * node:crypto est deja la, et scrypt est un KDF defini par RFC 7914. + */ +const SCRYPT = { N: 16384, r: 8, p: 1, keylen: 64, maxmem: 32 * 1024 * 1024 }; + +export const hashPassword = async (password: string): Promise => { + if (Buffer.byteLength(password) < 8) { + throw AppError.badRequest("Le mot de passe doit contenir au moins 8 caracteres."); + } + const salt = randomBytes(16); + const derived = await scrypt(password, salt, SCRYPT.keylen, SCRYPT); + return `scrypt$${SCRYPT.N}$${SCRYPT.r}$${SCRYPT.p}$${salt.toString("base64")}$${derived.toString("base64")}`; +}; + +export const verifyPassword = async (password: string, stored: string): Promise => { + const parts = stored.split("$"); + if (parts.length !== 6 || parts[0] !== "scrypt") return false; + const [, n, r, p, saltB64, hashB64] = parts; + const salt = Buffer.from(saltB64 ?? "", "base64"); + const expected = Buffer.from(hashB64 ?? "", "base64"); + if (expected.length === 0) return false; + + const derived = await scrypt(password, salt, expected.length, { + N: Number(n), + r: Number(r), + p: Number(p), + maxmem: SCRYPT.maxmem, + }); + return derived.length === expected.length && timingSafeEqual(derived, expected); +}; + +export const sha256 = (value: string): string => createHash("sha256").update(value).digest("hex"); + +/** + * Portrait de l'utilisateur porte par la session. + * + * Les budgets de stockage n'y figurent pas : une valeur figee dans un cookie + * serait fausse des la premiere ecriture. Chaque route qui en a besoin relit + * les colonnes en base au moment de l'usage. + */ +export interface SessionUser { + id: string; + email: string; + first_name: string; + last_name: string; + role_slug: string; + role_name: string; + is_active: number; + must_change_password: number; +} + +export interface SessionMeta { + ipAddress?: string | null | undefined; + userAgent?: string | null | undefined; +} + +export const SESSION_COOKIE = "cohaise_session"; + +/** + * Le jeton brut part dans le cookie, son empreinte SHA-256 dans la base. + * Une copie de la base ne donne donc aucune session ouvrable : il faudrait + * en plus la table des cookies, qui n'existe pas. + */ +export const createSession = async ( + db: Db, + userId: string, + meta: SessionMeta, + ttlHours: number, +): Promise<{ token: string; expiresAt: Date }> => { + const token = randomBytes(32).toString("base64url"); + const expiresAt = new Date(Date.now() + ttlHours * 3600_000); + + await db.exec( + `INSERT INTO user_sessions (id, user_id, token_hash, ip_address, user_agent, expires_at) + VALUES (?, ?, ?, ?, ?, ?)`, + [ + randomUUID(), + userId, + sha256(token), + meta.ipAddress ?? null, + meta.userAgent?.slice(0, 255) ?? null, + expiresAt, + ], + ); + return { token, expiresAt }; +}; + +export const resolveSession = async (db: Db, token: string): Promise => { + const row = await db.one( + `SELECT u.id, u.email, u.first_name, u.last_name, + r.slug AS role_slug, r.name AS role_name, + u.is_active, u.must_change_password, + s.last_seen_at + FROM user_sessions s + JOIN users u ON u.id = s.user_id + JOIN roles r ON r.id = u.role_id + WHERE s.token_hash = ? + AND s.revoked_at IS NULL + AND s.expires_at > UTC_TIMESTAMP() + AND u.deleted_at IS NULL + AND u.is_active = 1`, + [sha256(token)], + ); + if (!row) return null; + // Etat vu, avec un decalage de 60 s pour ne pas ecrire a chaque requete. + await db.exec( + "UPDATE user_sessions SET last_seen_at = UTC_TIMESTAMP() WHERE token_hash = ? AND last_seen_at < UTC_TIMESTAMP(3) - INTERVAL 60 SECOND", + [sha256(token)], + ); + return row; +}; + +export const revokeSession = async (db: Db, token: string): Promise => { + await db.exec("UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE token_hash = ?", [ + sha256(token), + ]); +}; + +export const purgeExpiredSessions = async (db: Db): Promise => { + const result = await db.exec("DELETE FROM user_sessions WHERE expires_at < UTC_TIMESTAMP()"); + return result.affectedRows; +}; + +/** + * Secure depend du schema reel de la requete, pas d'une origine configuree. + * + * Deriver Secure de PUBLIC_ORIGIN rendait tout test local impossible : le + * navigateur rejette en HTTP un cookie marque Secure, donc la connexion + * echouait sans message exploitable. A l'inverse, un cookie non Secure servi en + * HTTPS laisserait le jeton circuler en clair. + * + * X-Forwarded-Proto n'est pris en compte que si le service fait confiance a son + * proxy ; sinon la connexion parle d'elle-meme. + */ +export const isHttpsRequest = (context: Context, trustProxy: boolean): boolean => { + if (trustProxy) { + const forwarded = context.req.header("x-forwarded-proto"); + if (forwarded) return forwarded.split(",")[0]?.trim() === "https"; + } + return context.req.raw.url.startsWith("https:"); +}; + +export const setSessionCookie = ( + context: Context, + token: string, + expiresAt: Date, + secure: boolean, +): void => { + setCookie(context, SESSION_COOKIE, token, { + httpOnly: true, + sameSite: "Lax", + secure, + path: "/", + expires: expiresAt, + }); +}; + +export const clearSessionCookie = (context: Context): void => { + deleteCookie(context, SESSION_COOKIE, { path: "/" }); +}; + +export interface AuthState { + user: SessionUser; + token: string; +} + +/** Lit le cookie et attache l'utilisateur, sans exiger qu'il existe. */ +export const attachUser = + (db: Db) => + async (context: Context, next: Next): Promise => { + const token = getCookie(context, SESSION_COOKIE); + if (token) { + const user = await resolveSession(db, token); + if (user) { + context.set("user", user); + context.set("token", token); + } else { + clearSessionCookie(context); + } + } + await next(); + }; + +export const requireAuth = async (context: Context, next: Next): Promise => { + const user = context.get("user") as SessionUser | undefined; + if (!user) throw AppError.unauthorized(); + await next(); +}; + +/** Le role est impose en base, jamais en entete, donc ni cacheable ni falsifiable. */ +export const requireRole = + (...slugs: string[]) => + async (context: Context, next: Next): Promise => { + const user = context.get("user") as SessionUser | undefined; + if (!user) throw AppError.unauthorized(); + if (!slugs.includes(user.role_slug)) { + throw AppError.forbidden(`Action reservee au role : ${slugs.join(", ")}.`); + } + await next(); + }; + +export const currentUser = (context: Context): SessionUser => { + const user = context.get("user") as SessionUser | undefined; + if (!user) throw AppError.unauthorized(); + return user; +}; diff --git a/backend/shared/src/cli.ts b/backend/shared/src/cli.ts new file mode 100644 index 0000000..7f338b3 --- /dev/null +++ b/backend/shared/src/cli.ts @@ -0,0 +1,137 @@ +#!/usr/bin/env node + +import { pathToFileURL } from "node:url"; +import { resolve } from "node:path"; +import { ConfigError, loadDbConfig } from "./config.js"; +import { Db } from "./db.js"; +import { AppError, toSafeError } from "./errors.js"; +import { listMigrations, runMigrations } from "./migrate.js"; + +/** + * Point d'entree des migrations : `node dist/cli.js --dir `. + * + * Le conteneur de migration n'a besoin d'aucun secret lisible a la main : + * les variables sont resolues par Docker depuis .env au lancement. + * + * Codes de sortie : + * 0 tout est applique, ou rien a faire + * 1 erreur (connexion, SQL, migration) OU derive detectee + * 2 configuration incomplete + */ + +interface Options { + dir: string; + dryRun: boolean; + check: boolean; + help: boolean; +} + +const USAGE = `Utilisation : cohaise-migrate --dir [--dry-run] [--check] + + --dir Dossier contenant les fichiers NNN_nom.sql (obligatoire) + --dry-run Analyse sans ecrire en base + --check Echoue s'il reste une migration a appliquer + --help Cette aide`; + +const parseArgs = (argv: string[]): Options => { + const options: Options = { dir: "", dryRun: false, check: false, help: false }; + for (let index = 0; index < argv.length; index += 1) { + const arg = argv[index]; + if (arg === undefined) continue; + if (arg === "--dry-run") options.dryRun = true; + else if (arg === "--check") options.check = true; + else if (arg === "--help" || arg === "-h") options.help = true; + else if (arg === "--dir") { + options.dir = argv[index + 1] ?? ""; + index += 1; + } else if (arg.startsWith("--dir=")) { + options.dir = arg.slice("--dir=".length); + } else { + throw AppError.badRequest(`Argument inconnu : ${arg}`, { argument: arg }); + } + } + return options; +}; + +const main = async (argv: string[]): Promise => { + let options: Options; + try { + options = parseArgs(argv); + } catch (error) { + const safe = toSafeError(error); + console.error(` ${safe.message}\n\n${USAGE}`); + return 2; + } + + if (options.help) { + console.log(USAGE); + return 0; + } + if (!options.dir) { + console.error(` --dir est obligatoire\n\n${USAGE}`); + 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 dir = resolve(options.dir); + const db = new Db(config); + + try { + const migrations = await listMigrations(dir); + if (migrations.length === 0) { + console.log(` Aucune migration trouvee dans ${dir}`); + return 0; + } + + const result = await runMigrations(db, dir, { dryRun: options.dryRun }); + const prefix = options.dryRun ? "[dry-run] " : ""; + + console.log( + `${prefix}${migrations.length} migration(s) · ${result.applied.length} appliquee(s) · ` + + `${result.skipped.length} deja en place · ${result.drifted.length} derivee(s)`, + ); + for (const version of result.applied) console.log(` + ${version}`); + for (const drift of result.drifted) { + console.error(` ! ${drift.version} modifiee depuis son execution (checksum attendu ${drift.recorded.slice(0, 12)}…, trouve ${drift.current.slice(0, 12)}…)`); + } + + if (result.drifted.length > 0) return 1; + if (options.check && result.applied.length > 0) return 1; + return 0; + } catch (error) { + const safe = toSafeError(error); + console.error(` Echec : ${safe.code} — ${safe.message}`); + if (error instanceof AppError && error.status >= 500 && error.message.includes("migree")) { + console.error(" Appliquez d'abord les migrations : cohaise-migrate --dir "); + } + return 1; + } finally { + await db.close().catch(() => undefined); + } +}; + +const isDirectRun = + process.argv[1] !== undefined && + import.meta.url === pathToFileURL(process.argv[1]).href; + +if (isDirectRun) { + 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); + }, + ); +} + +export { main, parseArgs }; diff --git a/backend/shared/src/config.ts b/backend/shared/src/config.ts new file mode 100644 index 0000000..a7d99bb --- /dev/null +++ b/backend/shared/src/config.ts @@ -0,0 +1,111 @@ +import { z } from "zod"; + +/** + * Configuration lue une seule fois au demarrage. L'objet est fige : + * si une variable manque ou est mal formee, le processus s'arrete avant + * d'ouvrir le moindre port, avec la liste exacte de ce qui pose probleme. + * Une API qui demarre puis echoue sur la premiere requete est un defaut de + * deploiement, pas un defaut d'ecriture de code. + */ + +const bool = (fallback: boolean) => + z + .string() + .optional() + .transform((value) => { + if (value === undefined || value === "") return fallback; + return !["0", "false", "no", "off"].includes(value.toLowerCase()); + }); + +const port = (fallback: number) => + z.coerce.number().int().min(1).max(65535).default(fallback); + +const positiveInt = (fallback: number) => + z.coerce.number().int().positive().default(fallback); + +const schema = z.object({ + NODE_ENV: z.enum(["development", "production", "test"]).default("development"), + LOG_LEVEL: z.enum(["silent", "error", "warn", "info", "debug"]).default("info"), + + PORT: port(3000), + /** Origine publique absolue, indispensable aux liens envoyes par courriel. */ + PUBLIC_ORIGIN: z.url(), + + DB_HOST: z.string().min(1), + DB_PORT: port(3306), + DB_USER: z.string().min(1), + DB_PASSWORD: z.string().min(1), + DB_NAME: z.string().min(1), + + DB_CONNECTION_LIMIT: positiveInt(8), + DB_CONNECT_TIMEOUT_MS: positiveInt(10_000), + + MEDIA_DIR: z.string().min(1).default("/data/media/originals"), + VARIANT_DIR: z.string().min(1).default("/data/media/variants"), + + SESSION_SECRET: z.string().min(32), + SESSION_TTL_HOURS: positiveInt(24 * 14), + + TRUST_PROXY: bool(false), + CORS_ORIGIN: z.string().optional().transform((v) => v ?? null), + + // Envoi de courriel : obligatoire, l'application refuse de demarrer sans, + // car la reinitialisation de mot de passe et le changement d'adresse en + // dependent. Un relais local sans authentification reste possible : seuls + // l'hote et l'expediteur sont exiges. + SMTP_HOST: z.string().min(1), + SMTP_PORT: port(587), + SMTP_USER: z.string().optional().transform((v) => (v ? v : null)), + SMTP_PASSWORD: z.string().optional().transform((v) => (v ? v : null)), + SMTP_FROM: z.string().min(3), + SMTP_SECURE: bool(false), + + // Limitation des tentatives de connexion, appliquee dans le processus. + RATE_LIMIT_LOGIN_MAX: positiveInt(10), + RATE_LIMIT_LOGIN_WINDOW_MS: positiveInt(60_000), +}); + +export type Config = Readonly>; + +export class ConfigError extends Error { + readonly issues: string[]; + constructor(issues: string[]) { + super(`Configuration invalide (${issues.length}) :\n - ${issues.join("\n - ")}`); + this.name = "ConfigError"; + this.issues = issues; + } +} + +export const loadConfig = (env: NodeJS.ProcessEnv = process.env): Config => { + const parsed = schema.safeParse(env); + if (!parsed.success) throw new ConfigError(issuesOf(parsed.error)); + return Object.freeze(parsed.data); +}; + +/** Sous-ensemble DB, pour les outils qui n'ouvrent aucun port (migrations, CLI). */ +const dbSchema = z.object({ + NODE_ENV: z.enum(["development", "production", "test"]).default("development"), + LOG_LEVEL: z.enum(["silent", "error", "warn", "info", "debug"]).default("info"), + DB_HOST: z.string().min(1), + DB_PORT: port(3306), + DB_USER: z.string().min(1), + DB_PASSWORD: z.string().min(1), + DB_NAME: z.string().min(1), + DB_CONNECTION_LIMIT: positiveInt(8), + DB_CONNECT_TIMEOUT_MS: positiveInt(10_000), +}); + +export type DbConfig = Readonly>; + +export const loadDbConfig = (env: NodeJS.ProcessEnv = process.env): DbConfig => { + const parsed = dbSchema.safeParse(env); + if (!parsed.success) throw new ConfigError(issuesOf(parsed.error)); + return Object.freeze(parsed.data); +}; + +const issuesOf = (error: z.ZodError): string[] => + error.issues.map((issue) => { + const path = issue.path.join(".") || "(racine)"; + const missing = issue.code === "invalid_type" && issue.input === undefined; + return missing ? `${path} : variable absente` : `${path} : ${issue.message}`; + }); diff --git a/backend/shared/src/db.ts b/backend/shared/src/db.ts new file mode 100644 index 0000000..1697a1b --- /dev/null +++ b/backend/shared/src/db.ts @@ -0,0 +1,107 @@ +import mysql, { type Pool, type PoolConnection, type ResultSetHeader, type RowDataPacket } from "mysql2/promise"; +import type { DbConfig } from "./config.js"; + +export interface QueryError { + code: string; + errno: number; + sqlMessage?: string; +} + +export class Db { + readonly pool: Pool; + + constructor(config: DbConfig) { + this.pool = mysql.createPool({ + host: config.DB_HOST, + port: config.DB_PORT, + user: config.DB_USER, + password: config.DB_PASSWORD, + database: config.DB_NAME, + waitForConnections: true, + connectionLimit: config.DB_CONNECTION_LIMIT, + connectTimeout: config.DB_CONNECT_TIMEOUT_MS, + timezone: "Z", + charset: "utf8mb4_unicode_ci", + decimalNumbers: true, + // Porte refermee sur les requetes empilees : sans cet option, une + // contamination d'une lecture echappait en INSERT ou en DROP. Les valeurs + // sont toujours transmises en parametres, jamais concatenees dans le SQL. + multipleStatements: false, + namedPlaceholders: false, + }); + } + + /** Lecture en protocole prepare : les valeurs sont binaires, jamais des chains de texte. */ + async query(sql: string, params: unknown[] = []): Promise { + const [rows] = await this.pool.execute(sql, params as never); + return rows as T[]; + } + + /** Requete brute, sans parametres, reservee au DDL des migrations. + Certains etats DDL ne passent pas le protocole prepare de MariaDB. */ + async raw(sql: string): Promise { + await this.pool.query(sql); + } + + async one(sql: string, params: unknown[] = []): Promise { + const rows = await this.query(sql, params); + return (rows[0] as T | undefined) ?? null; + } + + /** Le premier resultat, ou une erreur explicite plutot qu'un undefined silencieux. */ + async required(sql: string, params: unknown[] = []): Promise { + const row = await this.one(sql, params); + if (row === null) { + throw Object.assign(new Error("Ligne introuvable"), { status: 404, code: "NOT_FOUND" }); + } + return row; + } + + async exec(sql: string, params: unknown[] = []): Promise { + const [result] = await this.pool.execute(sql, params as never); + return result as ResultSetHeader; + } + + async transaction(fn: (connection: PoolConnection) => Promise): Promise { + const connection = await this.pool.getConnection(); + try { + await connection.beginTransaction(); + const result = await fn(connection); + await connection.commit(); + return result; + } catch (error) { + await connection.rollback(); + throw error; + } finally { + connection.release(); + } + } + + /** Forme courte des erreurs de contrainte, pour les repondre en 409 et non en 500. */ + static classify(error: unknown): { status: number; message: string } { + const errno = (error as { errno?: number })?.errno; + const sqlMessage = (error as { sqlMessage?: string })?.sqlMessage ?? ""; + switch (errno) { + case 1062: + return { status: 409, message: "Cette valeur existe deja." }; + case 1451: + case 1452: + return { status: 409, message: "Operation impossible : des enregistrements en referent encore." }; + case 1406: + return { status: 422, message: "Valeur trop longue pour la colonne." }; + case 1146: + return { status: 503, message: "Table absente : la base n'est peut-etre pas migree." }; + case 1045: + return { status: 503, message: "Acces refuse par la base de donnees." }; + case 1040: + case 1203: + return { status: 503, message: "Trop de connexions a la base de donnees." }; + default: + return errno === undefined ? { status: 500, message: "Erreur interne." } : { status: 500, message: sqlMessage || "Erreur de base de donnees." }; + } + } + + async close(): Promise { + await this.pool.end(); + } +} diff --git a/backend/shared/src/errors.ts b/backend/shared/src/errors.ts new file mode 100644 index 0000000..5e6d87a --- /dev/null +++ b/backend/shared/src/errors.ts @@ -0,0 +1,97 @@ +/** + * Erreurs portees par un code HTTP. Une erreur qui n'en porte pas est + * consideree interne : on journalise le detail, on ne le rend jamais au + * client, parce que le message d'une exception ne doit pas decrire le schema. + */ + +export class AppError extends Error { + readonly status: number; + readonly code: string; + readonly details?: Record; + + constructor(status: number, code: string, message: string, details?: Record) { + super(message); + this.name = "AppError"; + this.status = status; + this.code = code; + if (details !== undefined) this.details = details; + } + + static badRequest(message: string, details?: Record) { + return new AppError(400, "BAD_REQUEST", message, details); + } + static unauthorized(message = "Authentification requise.") { + return new AppError(401, "UNAUTHORIZED", message); + } + static forbidden(message = "Vous ne pouvez pas effectuer cette action.") { + return new AppError(403, "FORBIDDEN", message); + } + static notFound(message = "Ressource introuvable.") { + return new AppError(404, "NOT_FOUND", message); + } + static conflict(message: string) { + return new AppError(409, "CONFLICT", message); + } + static payloadTooLarge(message = "Fichier trop volumineux.") { + return new AppError(413, "PAYLOAD_TOO_LARGE", message); + } + static unprocessable(message: string, details?: Record) { + return new AppError(422, "UNPROCESSABLE", message, details); + } + static serviceUnavailable(message = "Service momentanement indisponible.") { + return new AppError(503, "UNAVAILABLE", message); + } +} + +export interface SafeError { + status: number; + code: string; + message: string; + details?: Record; +} + +export const toSafeError = (error: unknown): SafeError => { + if (error instanceof AppError) { + return error.details !== undefined + ? { status: error.status, code: error.code, message: error.message, details: error.details } + : { status: error.status, code: error.code, message: error.message }; + } + + const status = (error as { status?: number })?.status; + const code = (error as { code?: string })?.code; + if (typeof status === "number" && status >= 400 && status < 500) { + return { status, code: code ?? "BAD_REQUEST", message: (error as Error).message }; + } + + // Une erreur MariaDB connue est un probleme d'exploitation, pas un crash. + const errno = (error as { errno?: number })?.errno; + if (errno !== undefined) { + const { status: dbStatus, message } = classifyDbError(errno); + return { status: dbStatus, code: errno === 1146 ? "NOT_MIGRATED" : "DATABASE", message }; + } + + return { status: 500, code: "INTERNAL", message: "Erreur interne." }; +}; + +const classifyDbError = (errno: number): { status: number; message: string } => { + switch (errno) { + case 1062: + return { status: 409, message: "Cette valeur existe deja." }; + case 1451: + case 1452: + return { status: 409, message: "Operation impossible : des enregistrements en referent encore." }; + case 1406: + return { status: 422, message: "Valeur trop longue pour la colonne." }; + case 1146: + return { status: 503, message: "Base non migree. Lancez les migrations avant de servir." }; + case 1045: + return { status: 503, message: "Acces refuse par la base de donnees." }; + case 1040: + case 1203: + return { status: 503, message: "Trop de connexions a la base de donnees." }; + case 1053: + return { status: 503, message: "Base de donnees en cours d'initialisation." }; + default: + return { status: 503, message: "Base de donnees indisponible." }; + } +}; diff --git a/backend/shared/src/http.ts b/backend/shared/src/http.ts new file mode 100644 index 0000000..de0a920 --- /dev/null +++ b/backend/shared/src/http.ts @@ -0,0 +1,171 @@ +import { randomUUID } from "node:crypto"; +import { Hono, type Context, type Next } from "hono"; +import { cors } from "hono/cors"; +import type { SessionUser } from "./auth.js"; +import type { Config } from "./config.js"; +import type { Db } from "./db.js"; +import { AppError, toSafeError } from "./errors.js"; + +export interface Logger { + level: Config["LOG_LEVEL"]; + info: (message: string, fields?: Record) => void; + warn: (message: string, fields?: Record) => void; + error: (message: string, fields?: Record) => void; + debug: (message: string, fields?: Record) => void; +} + +const ORDER: Record = { + silent: 0, + error: 1, + warn: 2, + info: 3, + debug: 4, +}; + +export const createLogger = (level: Config["LOG_LEVEL"], service: string): Logger => { + const emit = (name: keyof typeof ORDER, message: string, fields?: Record) => { + if (ORDER[name] > ORDER[level]) return; + const line = JSON.stringify({ + ts: new Date().toISOString(), + level: name, + service, + msg: message, + ...fields, + }); + if (name === "error") console.error(line); + else console.log(line); + }; + + return { + level, + info: (message, fields) => emit("info", message, fields), + warn: (message, fields) => emit("warn", message, fields), + error: (message, fields) => emit("error", message, fields), + debug: (message, fields) => emit("debug", message, fields), + }; +}; + +/** Variables transportees par chaque requete : tracee d'identification. */ +export interface AppEnv { + Variables: { + requestId: string; + /** Posee par attachUser quand le cookie de session est valide. */ + user?: SessionUser; + token?: string; + }; +} + +/** Type public d'une application CoHaiSe, impose aux routes metier. */ +export type App = Hono; + +/** + * IP reelle de l'appelant : X-Forwarded-For n'est cru que si le service fait + * confiance a son proxy. La valeur est tronquee a la taille de la colonne. + */ +export const clientIp = (context: Context, trustProxy: boolean): string | null => { + if (trustProxy) { + const forwarded = context.req.header("x-forwarded-for"); + const first = forwarded?.split(",")[0]?.trim(); + if (first) return first.slice(0, 45); + } + const env = context.env as + | { incoming?: { socket?: { remoteAddress?: string } } } + | undefined; + const address = env?.incoming?.socket?.remoteAddress; + return address ? address.slice(0, 45) : null; +}; + +/** Dependances remises aux routes metier au montage. */ +export interface RouteDeps { + db: Db; + config: Config; + logger: Logger; +} + +export interface AppOptions { + service: string; + config: Config; + db: Db; + logger: Logger; + /** Routes metier, montees sous /api/ dans le routing. */ + routes: (app: App, deps: RouteDeps) => void; + /** Vrai quand l'API doit repondre a /healthz avec l'etat de la base. */ + probeDb?: boolean; +} + +export const createApp = ({ service, config, db, logger, routes, probeDb = true }: AppOptions): App => { + const app = new Hono(); + + app.use("*", async (context: Context, next: Next) => { + const requestId = context.req.header("x-request-id") ?? randomUUID(); + context.set("requestId", requestId); + context.res.headers.set("x-request-id", requestId); + context.res.headers.set("x-content-type-options", "nosniff"); + context.res.headers.set("referrer-policy", "same-origin"); + context.res.headers.set("x-frame-options", "DENY"); + const started = performance.now(); + await next(); + const duration = Math.round(performance.now() - started); + if (context.req.method !== "OPTIONS") { + logger.debug("requete", { + requestId, + method: context.req.method, + path: new URL(context.req.url).pathname, + status: context.res.status, + durationMs: duration, + }); + } + }); + + if (config.CORS_ORIGIN) { + app.use( + "*", + cors({ + origin: config.CORS_ORIGIN.split(",").map((value) => value.trim()), + credentials: true, + maxAge: 600, + }), + ); + } + + app.get("/healthz", async (context) => { + if (!probeDb) return context.json({ status: "ok", service }, 200); + const started = performance.now(); + try { + await db.query("SELECT 1"); + return context.json( + { status: "ok", service, db: "up", latencyMs: Math.round(performance.now() - started) }, + 200, + ); + } catch (error) { + logger.error("sante base en echec", { error: String(error) }); + return context.json({ status: "degraded", service, db: "down" }, 503); + } + }); + + routes(app, { db, config, logger }); + + app.notFound((context) => + context.json({ error: { status: 404, code: "NOT_FOUND", message: "Route introuvable." } }, 404), + ); + + app.onError((error, context) => { + const safe = toSafeError(error); + const requestId = context.get("requestId"); + if (safe.status >= 500) { + logger.error("erreur non geree", { + requestId, + code: safe.code, + message: error instanceof Error ? error.message : String(error), + stack: error instanceof Error ? error.stack : undefined, + }); + } else { + logger.debug("refus", { requestId, code: safe.code, status: safe.status }); + } + return context.json({ error: { ...safe, requestId } }, safe.status as 500); + }); + + return app; +}; + +export { AppError }; diff --git a/backend/shared/src/index.ts b/backend/shared/src/index.ts new file mode 100644 index 0000000..ca4ba65 --- /dev/null +++ b/backend/shared/src/index.ts @@ -0,0 +1,50 @@ +export { + loadConfig, + loadDbConfig, + ConfigError, + type Config, + type DbConfig, +} from "./config.js"; +export { Db } from "./db.js"; +export { AppError, toSafeError, type SafeError } from "./errors.js"; +export { + createApp, + createLogger, + clientIp, + type App, + type AppEnv, + type AppOptions, + type Logger, + type RouteDeps, +} from "./http.js"; +export { + attachUser, + clearSessionCookie, + createSession, + currentUser, + isHttpsRequest, + hashPassword, + requireAuth, + requireRole, + purgeExpiredSessions, + revokeSession, + SESSION_COOKIE, + setSessionCookie, + sha256, + verifyPassword, + type SessionUser, +} from "./auth.js"; +export { + listMigrations, + runMigrations, + assertNoDrift, + type MigrationResult, +} from "./migrate.js"; +export { createMailer, link, type Mailer, type MailMessage } from "./mail.js"; +export { createRateLimiter, rateLimitKey, type RateLimiter } from "./ratelimit.js"; +export { + prepareService, + startService, + type Service, + type ServiceOptions, +} from "./service.js"; diff --git a/backend/shared/src/mail.ts b/backend/shared/src/mail.ts new file mode 100644 index 0000000..9512130 --- /dev/null +++ b/backend/shared/src/mail.ts @@ -0,0 +1,48 @@ +import { createTransport, type Transporter } from "nodemailer"; +import type { Config } from "./config.js"; + +/** + * Envoi de courriel via SMTP. + * + * Le transport est construit une seule fois au demarrage. L'application exige + * les variables SMTP_* : sans elles, elle refuse de demarrer plutot que de + * laisser une reinitialisation de mot de passe silencieusement sans effet. + */ + +export interface MailMessage { + to: string; + subject: string; + text: string; +} + +export interface Mailer { + send: (message: MailMessage) => Promise; +} + +export const createMailer = (config: Config): Mailer => { + const transport: Transporter = createTransport({ + host: config.SMTP_HOST, + port: config.SMTP_PORT, + secure: config.SMTP_SECURE, + ...(config.SMTP_USER + ? { auth: { user: config.SMTP_USER, pass: config.SMTP_PASSWORD ?? "" } } + : {}), + disableFileAccess: true, + disableUrlAccess: true, + }); + + return { + send: async (message) => { + await transport.sendMail({ + from: config.SMTP_FROM, + to: message.to, + subject: message.subject, + text: message.text, + }); + }, + }; +}; + +/** Lien absolu construit sur PUBLIC_ORIGIN, qui est valide au demarrage. */ +export const link = (config: Config, path: string): string => + new URL(path, config.PUBLIC_ORIGIN).toString(); diff --git a/backend/shared/src/migrate.ts b/backend/shared/src/migrate.ts new file mode 100644 index 0000000..ff35052 --- /dev/null +++ b/backend/shared/src/migrate.ts @@ -0,0 +1,144 @@ +import { createHash } from "node:crypto"; +import { readdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import type { Db } from "./db.js"; + +/** + * Applique les fichiers NNN_nom.sql dans l'ordre lexical, et uniquement ceux + * qui ne sont pas encore marques comme appliques. Idempotent : un second appel + * ne reexecute rien. + * + * Limite connue et assumee : le DDL MariaDB n'est pas transactionnel. Un fichier + * echoue au milieu, le reste des statements n'est pas applique et le fichier + * n'est pas enregistre. Le repasser reprend depuis son debut. C'est pourquoi + * chaque migration part de la ou la precedente a fini, et pourquoi une migration + * en desordre doit etre reparue et pas seulement sauvegardee depuis sa moitie. + */ + +export interface MigrationFile { + version: string; + file: string; + sql: string; + checksum: string; +} + +export interface MigrationResult { + applied: string[]; + skipped: string[]; + /** Migrations deja appliquees dont le contenu du fichier a change depuis. */ + drifted: { version: string; recorded: string; current: string }[]; +} + +// Les deux bases utilisent un prefixe a trois chiffres (000, 001, …) ; +// quatre est accepte pour ne pas interdire le passage a un dossier plus large. +const FILE_PATTERN = /^(\d{3,4}_[a-z0-9_]+)\.sql$/; + +export const listMigrations = async (dir: string): Promise => { + const entries = await readdir(dir); + const files = entries.filter((entry) => FILE_PATTERN.test(entry)).sort(); + + return Promise.all( + files.map(async (file) => { + const sql = await readFile(path.join(dir, file), "utf8"); + return { + version: FILE_PATTERN.exec(file)?.[1] ?? file, + file, + sql, + checksum: createHash("sha256").update(sql).digest("hex"), + }; + }), + ); +}; + +const ensureLedger = async (db: Db): Promise => { + await db.raw(` + 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 + `); + // Creer la colonne ici plutot que dans une migration : ajouter une ligne a un + // registre qui enregistre lui-meme les lignes ajoutees boucle sur lui-meme. + await db.raw( + "ALTER TABLE schema_migrations ADD COLUMN IF NOT EXISTS checksum CHAR(64) NULL AFTER applied_at", + ); +}; + +export const runMigrations = async ( + db: Db, + dir: string, + options: { dryRun?: boolean } = {}, +): Promise => { + const files = await listMigrations(dir); + await ensureLedger(db); + + const applied = new Map(); + const rows = await db.query<{ version: string; checksum: string | null }>( + "SELECT version, checksum FROM schema_migrations", + ); + for (const row of rows) applied.set(row.version, { checksum: row.checksum }); + + const result: MigrationResult = { applied: [], skipped: [], drifted: [] }; + + for (const migration of files) { + const record = applied.get(migration.version); + + if (record) { + result.skipped.push(migration.version); + if (record.checksum && record.checksum !== migration.checksum) { + result.drifted.push({ + version: migration.version, + recorded: record.checksum, + current: migration.checksum, + }); + } + continue; + } + + if (options.dryRun) { + result.applied.push(migration.version); + continue; + } + + // Un statement par un statement : un filet de faille reste visible et le + // point d'arret reste reproductible plutot qu'un bloc de 400 lignes perdu. + // + // Les lignes de commentaire sont retirees, pas le statement entier : un + // en-tete de fichier ou une legende au-dessus d'un INSERT ne doit pas + // faire sauter la requete, et encore moins la faire sauter en silence + // pendant que la version est enregistree comme appliquee. + const statements = migration.sql + .split(/;\s*(?:\r?\n|$)/) + .map((statement) => + statement + .split(/\r?\n/) + .filter((line) => !line.trim().startsWith("--")) + .join("\n") + .trim(), + ) + .filter((statement) => statement.length > 0); + + for (const statement of statements) await db.raw(statement); + + await db.exec("INSERT INTO schema_migrations (version, checksum) VALUES (?, ?)", [ + migration.version, + migration.checksum, + ]); + result.applied.push(migration.version); + } + + return result; +}; + +export const assertNoDrift = (result: MigrationResult): void => { + if (result.drifted.length === 0) return; + const lines = result.drifted.map( + (d) => ` ${d.version} : appliquee ${d.recorded.slice(0, 12)}, fichier ${d.current.slice(0, 12)}`, + ); + throw new Error( + `Migrations deja appliquees modifiees depuis leur execution (${result.drifted.length}) :\n` + + `${lines.join("\n")}\n` + + "Une migration appliquee ne se modifie pas : creez un nouveau fichier.", + ); +}; diff --git a/backend/shared/src/ratelimit.ts b/backend/shared/src/ratelimit.ts new file mode 100644 index 0000000..7dcb39d --- /dev/null +++ b/backend/shared/src/ratelimit.ts @@ -0,0 +1,52 @@ +/** + * Limiteur de debit en memoire. + * + * Volontairement minimal : une seule instance d'API, donc un simple compteur + * glissant par cle suffit. La protection robuste contre une attaque repartie + * vit dans nginx (`limit_req`) ; celle-ci couvre le cas ou l'API est jointe + * directement, sans proxy. + * + * La memoire est bornee : les entrees purgees a chaque appel ne s'accumulent + * pas, et une entree dont toutes les tentatives sont sorties de la fenetre est + * oubliee. + */ + +interface Bucket { + count: number; + resetAt: number; +} + +export interface RateLimiter { + /** Vrai quand la tentative est permise ; faux une fois la borne atteinte. */ + allow: (key: string) => boolean; +} + +export const createRateLimiter = (max: number, windowMs: number): RateLimiter => { + const buckets = new Map(); + + const prune = (now: number): void => { + for (const [key, bucket] of buckets) { + if (bucket.resetAt <= now) buckets.delete(key); + } + }; + + return { + allow: (key) => { + const now = Date.now(); + // Purge a chaque appel : le cout est proportionnel au nombre de cles + // actives, borne par la fenetre, jamais par l'historique complet. + prune(now); + const bucket = buckets.get(key); + if (!bucket || bucket.resetAt <= now) { + buckets.set(key, { count: 1, resetAt: now + windowMs }); + return true; + } + if (bucket.count >= max) return false; + bucket.count += 1; + return true; + }, + }; +}; + +/** Identifiant de limitation : IP reelle si le proxy est de confiance, sinon socket. */ +export const rateLimitKey = (ip: string | null): string => ip ?? "unknown"; diff --git a/backend/shared/src/service.ts b/backend/shared/src/service.ts new file mode 100644 index 0000000..f12482a --- /dev/null +++ b/backend/shared/src/service.ts @@ -0,0 +1,152 @@ +import { createServer, type Server } from "node:http"; +import { type AddressInfo } from "node:net"; +import { getRequestListener } from "@hono/node-server"; +import { ConfigError, loadConfig, type Config } from "./config.js"; +import { AppError } from "./errors.js"; +import { Db } from "./db.js"; +import { + createLogger, + createApp, + type App, + type AppOptions, + type Logger, + type RouteDeps, +} from "./http.js"; +import { assertNoDrift, runMigrations } from "./migrate.js"; + +export interface ServiceOptions { + service: string; + /** Dossier contenant les fichiers NNN_nom.sql de cette application. */ + migrationsDir?: string; + routes: (app: App, deps: RouteDeps) => void; + probeDb?: boolean; + /** + * Tache d'entretien executee une fois la base joignable et migree, avant + * l'ouverture du port (purge des sessions ou de la corbeille). + */ + onReady?: (deps: RouteDeps) => Promise | void; +} + +export interface Service { + config: Config; + db: Db; + logger: Logger; + app: App; +} + +const fail = (error: unknown): never => { + if (error instanceof ConfigError) { + console.error(`\n [${new Date().toISOString()}] Demarrage refuse\n`); + console.error(error.message); + console.error( + "\n Verifiez .env (ou les variables du conteneur). .env.example recense l'ensemble du format attendu.\n", + ); + } else { + console.error( + `\n [${new Date().toISOString()}] Demarrage refuse : ${ + error instanceof Error ? error.message : String(error) + }\n`, + ); + if (error instanceof Error && error.stack) console.error(error.stack); + } + process.exit(1); +}; + +/** + * Prepare le service sans lancer d'ecoute. Utile pour la CLI de migration et + * pour les tests, qui n'ont pas besoin d'un port. + */ +export const prepareService = async (options: ServiceOptions): Promise => { + const config = loadConfig(); + const logger = createLogger(config.LOG_LEVEL, options.service); + const db = new Db(config); + + if (options.migrationsDir) { + const result = await runMigrations(db, options.migrationsDir); + assertNoDrift(result); + if (result.applied.length > 0) { + logger.info("migrations appliquees", { versions: result.applied }); + } + if (result.drifted.length > 0) { + logger.warn("migrations modifiees depuis leur execution", { + versions: result.drifted.map((d) => d.version), + }); + } + } + + if (options.onReady) { + try { + await options.onReady({ db, config, logger }); + } catch (error) { + // L'entretien ne doit jamais empecher de servir : une purge en echec est + // signalee, la base reste exploitable. + logger.error("tache de demarrage en echec", { + error: error instanceof Error ? error.message : String(error), + }); + } + } + + const app = createApp({ + service: options.service, + config, + db, + logger, + routes: options.routes, + probeDb: options.probeDb ?? true, + }); + + return { config, db, logger, app }; +}; + +/** Demarre, ecoute, et s'arrete proprement. */ +export const startService = async (options: ServiceOptions): Promise => { + let prepared: Service; + try { + prepared = await prepareService(options); + } catch (error) { + return fail(error); + } + + const { config, db, logger, app } = prepared; + const server: Server = createServer(getRequestListener(app.fetch)); + + server.keepAliveTimeout = 65_000; + server.headersTimeout = 70_000; + + const shutdown = async (signal: string) => { + logger.info("arret demande", { signal }); + // Le SIGTERM de docker stop a un delai limite : fermer d'abord l'ecoute + // evite de nouvelles requetes, puis attendre les requetes en cours. + server.close(async () => { + await db.close().catch((error: unknown) => logger.error("fermeture base", { error: String(error) })); + logger.info("arret termine"); + process.exit(0); + }); + setTimeout(() => { + logger.warn("arret force apres delai"); + process.exit(1); + }, 10_000).unref(); + }; + + process.on("SIGTERM", () => void shutdown("SIGTERM")); + process.on("SIGINT", () => void shutdown("SIGINT")); + process.on("unhandledRejection", (reason) => { + logger.error("rejet de promesse non gere", { reason: String(reason) }); + }); + + await new Promise((resolve) => { + server.listen(config.PORT, "0.0.0.0", () => resolve()); + }); + + const address = server.address() as AddressInfo; + logger.info("api prete", { + port: address.port, + env: config.NODE_ENV, + db: `${config.DB_HOST}:${config.DB_PORT}/${config.DB_NAME}`, + }); + + return server; +}; + +export { AppError, ConfigError, Db, createApp, createLogger, loadConfig, runMigrations }; +export type { AppOptions, Config, Logger, RouteDeps }; diff --git a/backend/shared/tsconfig.json b/backend/shared/tsconfig.json new file mode 100644 index 0000000..c62df5b --- /dev/null +++ b/backend/shared/tsconfig.json @@ -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, + "declarationMap": true, + "sourceMap": true + }, + "include": ["src/**/*.ts"] +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..119484b --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,167 @@ +name: cohaise-cloud + +x-timezone: &timezone + TZ: Europe/Paris + +x-restart: &restart + restart: unless-stopped + +# Publication du front : build Vite puis export atomique dans le volume nginx. +x-app: &app + container_name: cohaise-cloud-builder + restart: "no" + build: + context: . + dockerfile: docker/Dockerfile.app + target: export + command: sh /publish.sh + volumes: + - ./docker/publish.sh:/publish.sh:ro + +# Les services de migration tournent l'executable cohaise-migrate depuis +# backend/shared. Ils ne lisent aucun fichier .env : Docker resout les +# variables ci-dessous au lancement, elles ne passent donc jamais par un +# terminal ni par le depot. +x-migrate-build: &migrate-build + context: . + dockerfile: docker/Dockerfile.api + # Le build utilise le reseau de l'hote : le demon Docker resout parfois un + # DNS mort (routeur), ce qui casse `npm ci` dans le conteneur. + network: host + args: + APP_DIR: backend/shared + +services: + app-build: + <<: *app + build: + context: . + dockerfile: docker/Dockerfile.app + target: export + network: host + args: + APP_DIR: frontend/cloud + volumes: + - app_data:/output + - ./docker/publish.sh:/publish.sh:ro + + nginx: + container_name: cohaise-cloud-nginx + build: + context: . + dockerfile: docker/Dockerfile + ports: + # Tunnel Cloudflare en amont : n'ecouter que sur la boucle locale. + - "127.0.0.1:${COHAISE_HTTP_PORT:-8083}:80" + environment: + <<: *timezone + volumes: + - app_data:/usr/share/nginx/html + healthcheck: + test: ["CMD-SHELL", "wget -qO- http://127.0.0.1/healthz || exit 1"] + interval: 10s + timeout: 3s + retries: 3 + <<: *restart + + db: + container_name: cohaise-cloud-db + image: mariadb:11.4 + environment: + <<: *timezone + MARIADB_ROOT_PASSWORD: ${CLOUD_DB_ROOT_PASSWORD} + MARIADB_DATABASE: ${CLOUD_DATABASE} + MARIADB_USER: ${CLOUD_DB_USER} + MARIADB_PASSWORD: ${CLOUD_DB_PASSWORD} + ports: + - "127.0.0.1:${COHAISE_DB_PORT:-3407}:3306" + healthcheck: + test: + [ + "CMD-SHELL", + "healthcheck.sh --connect --innodb_initialized", + ] + interval: 10s + timeout: 5s + retries: 5 + volumes: + - db_data:/var/lib/mysql + <<: *restart + + migrate: + build: *migrate-build + image: cohaise-cloud-migrate + restart: "no" + depends_on: + db: + condition: service_healthy + environment: + <<: *timezone + NODE_ENV: production + LOG_LEVEL: ${LOG_LEVEL:-info} + DB_HOST: db + DB_PORT: "3306" + DB_USER: ${CLOUD_DB_USER} + DB_PASSWORD: ${CLOUD_DB_PASSWORD} + DB_NAME: ${CLOUD_DATABASE} + command: ["node", "dist/cli.js", "--dir", "/migrations"] + volumes: + - ./backend/cloud/migrations:/migrations:ro + + api: + container_name: cohaise-cloud-api + build: + context: . + dockerfile: docker/Dockerfile.api + network: host + args: + APP_DIR: backend/cloud + image: cohaise-cloud-api + restart: unless-stopped + depends_on: + db: + condition: service_healthy + migrate: + condition: service_completed_successfully + environment: + <<: *timezone + NODE_ENV: production + LOG_LEVEL: ${LOG_LEVEL:-info} + PORT: "8080" + DB_HOST: db + DB_PORT: "3306" + DB_USER: ${CLOUD_DB_USER} + DB_PASSWORD: ${CLOUD_DB_PASSWORD} + DB_NAME: ${CLOUD_DATABASE} + DB_CONNECTION_LIMIT: ${CLOUD_DB_CONNECTION_LIMIT:-8} + SESSION_SECRET: ${SESSION_SECRET} + SESSION_TTL_HOURS: ${SESSION_TTL_HOURS:-336} + PUBLIC_ORIGIN: ${PUBLIC_ORIGIN} + SMTP_HOST: ${SMTP_HOST} + SMTP_PORT: ${SMTP_PORT:-587} + SMTP_USER: ${SMTP_USER:-} + SMTP_PASSWORD: ${SMTP_PASSWORD:-} + SMTP_FROM: ${SMTP_FROM} + SMTP_SECURE: ${SMTP_SECURE:-false} + RATE_LIMIT_LOGIN_MAX: ${RATE_LIMIT_LOGIN_MAX:-10} + RATE_LIMIT_LOGIN_WINDOW_MS: ${RATE_LIMIT_LOGIN_WINDOW_MS:-60000} + TRUST_PROXY: ${TRUST_PROXY:-true} + CORS_ORIGIN: ${CLOUD_CORS_ORIGIN:-} + MEDIA_DIR: /data/media/originals + VARIANT_DIR: /data/media/variants + ports: + - "127.0.0.1:${COHAISE_API_PORT:-3101}:8080" + volumes: + - media_data:/data/media + healthcheck: + test: ["CMD", "wget", "-qO-", "http://127.0.0.1:8080/healthz"] + interval: 15s + timeout: 5s + retries: 5 + start_period: 20s + <<: *restart + +volumes: + app_data: + db_data: + media_data: diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 0000000..a57cc84 --- /dev/null +++ b/docker/Dockerfile @@ -0,0 +1,9 @@ +FROM nginx:1.27-alpine + +RUN rm -f /etc/nginx/conf.d/default.conf \ + && mkdir -p /usr/share/nginx/html + +COPY docker/nginx/cloud.conf /etc/nginx/conf.d/app.conf +COPY docker/nginx/snippets /etc/nginx/snippets + +EXPOSE 80 diff --git a/docker/Dockerfile.api b/docker/Dockerfile.api new file mode 100644 index 0000000..8508dac --- /dev/null +++ b/docker/Dockerfile.api @@ -0,0 +1,39 @@ +# Image des services API Node du Cloud. APP_DIR choisit le paquet a construire +# (API ou CLI de migration) ; les deux partagent la meme methode de build. +FROM node:22-alpine AS builder + +ARG APP_DIR + +WORKDIR /repo + +COPY package.json package-lock.json tsconfig.json tsconfig.base.json ./ +COPY backend ./backend + +RUN --mount=type=cache,target=/root/.npm npm ci +RUN npm run build --workspace=backend/shared +RUN npm run build --workspace=${APP_DIR} + +# On ne embarque pas les devDependencies dans l'image de production. +RUN npm prune --omit=dev && npm cache clean --force + +FROM node:22-alpine AS export + +ARG APP_DIR + +ENV NODE_ENV=production + +WORKDIR /repo + +COPY --from=builder /repo/package.json ./package.json +COPY --from=builder /repo/package-lock.json ./package-lock.json +COPY --from=builder /repo/node_modules ./node_modules +# backend/shared est le paquet @cohaise/server : les liens de workspace +# de node_modules pointent dessus, il doit donc voyager avec l'application. +COPY --from=builder /repo/backend/shared ./backend/shared +COPY --from=builder /repo/${APP_DIR} ./${APP_DIR} + +WORKDIR /repo/${APP_DIR} + +EXPOSE 8080 + +CMD ["node", "dist/index.js"] diff --git a/docker/Dockerfile.app b/docker/Dockerfile.app new file mode 100644 index 0000000..624f7e4 --- /dev/null +++ b/docker/Dockerfile.app @@ -0,0 +1,18 @@ +FROM node:22-alpine AS builder + +WORKDIR /repo + +ARG APP_DIR + +COPY package.json package-lock.json tsconfig.json tsconfig.base.json ./ +COPY frontend ./frontend + +RUN --mount=type=cache,target=/root/.npm npm ci +RUN npm run build --workspace=frontend/shared +RUN npm run build --workspace=${APP_DIR} + +FROM alpine:3.21 AS export + +ARG APP_DIR + +COPY --from=builder /repo/${APP_DIR}/dist /app/dist diff --git a/docker/README.md b/docker/README.md new file mode 100644 index 0000000..6dcfc86 --- /dev/null +++ b/docker/README.md @@ -0,0 +1,102 @@ +# docker/ — images du Cloud + +Tout ce qui touche aux images : build du front, image nginx, image API, +configuration et publication. Ce dépôt en fabrique **quatre** (nginx, front, +API, CLI de migration), d'où ce dossier dédié plutôt que des `Dockerfile` à la +racine. + +Fonctionnement du service (ordre `db → migrate → api`, ports, healthchecks) : +[`../docs/deployment.md`](../docs/deployment.md). En-têtes et limites +d'upload : [`../docs/security.md`](../docs/security.md). + +## Fichiers + +| Fichier | Rôle | Consommé par | +| --- | --- | --- | +| `Dockerfile` | `nginx:1.27-alpine` + `nginx/cloud.conf` | service `nginx` | +| `Dockerfile.app` | build Vite (`node:22-alpine`), export `dist/` | service `app-build` | +| `Dockerfile.api` | build d'un paquet backend, `npm prune --omit=dev` | services `migrate` **et** `api` | +| `nginx/cloud.conf` | serveur : `/healthz`, proxy `/api/`, caches, SPA | copié dans l'image | +| `nginx/snippets/` | en-têtes de sécurité, règles de cache | inclus par `cloud.conf` | +| `publish.sh` | publication atomique dans `app_data` | monté dans `app-build` | + +## Images + +```sh +docker compose build # toutes +docker compose build api # seulement l'API +``` + +### `Dockerfile` (nginx) + +Supprime le `default.conf` par défaut, copie `cloud.conf` et les snippets, +`EXPOSE 80`. Aucun module ajouté. + +### `Dockerfile.app` (front) + +- `ARG APP_DIR` → `frontend/cloud` (passé par compose). +- Stage `builder` : `npm ci` (cache npm), puis + `npm run build --workspace=frontend/shared` **avant** + `--workspace=${APP_DIR}` — l'ordre est obligatoire, le front importe le + design system. +- Stage `export` : recopie `dist/` seul, sans sources ni `node_modules`. + +### `Dockerfile.api` (back, utilisé deux fois) + +`ARG APP_DIR` accepte deux valeurs : + +| Service | `APP_DIR` | Résultat | +| --- | --- | --- | +| `migrate` | `backend/shared` | binaire `cohaise-migrate` (`dist/cli.js`) | +| `api` | `backend/cloud` | serveur Hono (`dist/index.js`) | + +Même image, deux cibles : le conteneur `migrate` sert, joue les migrations puis +s'arrête ; `api` tourne en continu (`restart: unless-stopped`). + +## Le proxy nginx + +```nginx +location /healthz { … } +location /api/ { proxy_pass $cohaise_api$request_uri; client_max_body_size 5g; … } +location /assets/ { immutable 1 an } +location / { no-cache, fallback SPA → @spa } +``` + +- L'upstream `api` est résolu depuis `proxy.conf` (variable `cohaise_api`) : + l'API est appelée **en interne** sur le réseau compose, jamais via le port + `3101` publié — ce port sert au debug. +- `client_max_body_size 5g` doit rester **aligné** avec `users.max_file_bytes` + (défaut 5 Go) : nginx rejette avant que l'API ne renvoie son erreur métier. + +## Publication du front + +Service `app-build` : `command: sh /publish.sh` avec `app_data` monté. + +1. copie de `dist/` vers `releases/-` ; +2. bascule atomique du lien `current` (`ln -sfn` puis `mv -T`) ; +3. purge des releases plus vieilles que 5 minutes. + +Pendant la copie, nginx sert l'ancienne version : aucun reload, aucune coupure. + +## Migrations + +Le service `migrate` monte `./backend/cloud/migrations:/migrations:ro` (lecture +seule) et lance : + +```sh +node dist/cli.js --dir /migrations # défaut, à chaque démarrage +node dist/cli.js --dir /migrations --dry-run # simulation +node dist/cli.js --dir /migrations --check # 1 s'il en reste +``` + +Codes de sortie : `0` OK · `1` erreur ou dérive de checksum · `2` configuration. + +## Modifier la configuration + +`nginx/cloud.conf` et les snippets sont **copiés** dans l'image, pas montés : + +```sh +docker compose build nginx && docker compose up -d nginx +``` + +Une simple modification sur disque ne change rien au service en cours. diff --git a/docker/nginx/cloud.conf b/docker/nginx/cloud.conf new file mode 100644 index 0000000..3583fcc --- /dev/null +++ b/docker/nginx/cloud.conf @@ -0,0 +1,62 @@ +# Limitation de debit. La zone `login` couvre les points sensibles (connexion, +# reinitialisation) ; la zone `api` un trafic general soutenu sans etouffer les +# envois volumineux (burst eleve, pas de mise en file). +limit_req_zone $binary_remote_addr zone=login:10m rate=15r/m; +limit_req_zone $binary_remote_addr zone=api:10m rate=60r/s; + +server { + listen 80 default_server; + listen [::]:80 default_server; + server_name _; + + root /usr/share/nginx/html/current; + index index.html; + + include /etc/nginx/snippets/security-headers.conf; + + gzip on; + gzip_vary on; + gzip_min_length 1024; + gzip_types text/plain text/css application/javascript application/json image/svg+xml application/manifest+json; + + location = /healthz { + access_log off; + default_type text/plain; + return 200 "ok\n"; + } + + # Points d'entree sensibles : limitation serree par IP. Une expression + # reguliere prend le pas sur le prefixe /api/ ci-dessous. + location ~ ^/api/cloud/(auth/login|account/forgot-password|account/reset-password|account/email-change) { + include /etc/nginx/snippets/security-headers.conf; + limit_req zone=login burst=5 nodelay; + limit_req_status 429; + include /etc/nginx/snippets/proxy-api.conf; + } + + # L'API. Le resolver Docker est declare dans le snippet pour que le + # conteneur soit resolu a la demande : nginx peut demarrer avant l'API, et + # le front reste servi pendant un redemarrage de celle-ci. + location /api/ { + include /etc/nginx/snippets/security-headers.conf; + limit_req zone=api burst=120 nodelay; + include /etc/nginx/snippets/proxy-api.conf; + } + + location /assets/ { + include /etc/nginx/snippets/security-headers.conf; + include /etc/nginx/snippets/cache-immutable.conf; + expires 1y; + try_files $uri =404; + } + + location / { + include /etc/nginx/snippets/security-headers.conf; + include /etc/nginx/snippets/cache-no-cache.conf; + try_files $uri $uri/ @spa; + } + + location @spa { + try_files /index.html =404; + } +} diff --git a/docker/nginx/snippets/cache-immutable.conf b/docker/nginx/snippets/cache-immutable.conf new file mode 100644 index 0000000..4d329e2 --- /dev/null +++ b/docker/nginx/snippets/cache-immutable.conf @@ -0,0 +1 @@ +add_header Cache-Control "public, immutable" always; diff --git a/docker/nginx/snippets/cache-no-cache.conf b/docker/nginx/snippets/cache-no-cache.conf new file mode 100644 index 0000000..0d152e5 --- /dev/null +++ b/docker/nginx/snippets/cache-no-cache.conf @@ -0,0 +1 @@ +add_header Cache-Control "no-cache" always; diff --git a/docker/nginx/snippets/proxy-api.conf b/docker/nginx/snippets/proxy-api.conf new file mode 100644 index 0000000..41d706a --- /dev/null +++ b/docker/nginx/snippets/proxy-api.conf @@ -0,0 +1,14 @@ +# Relay vers l'API. Resolver Docker declare pour resoudre le conteneur a la +# demande : nginx peut demarrer avant l'API et lui survit pendant un +# redemarrage. +resolver 127.0.0.11 valid=30s ipv6=off; +set $cohaise_api http://api:8080; +proxy_pass $cohaise_api$request_uri; +proxy_http_version 1.1; +proxy_set_header Host $host; +proxy_set_header X-Real-IP $remote_addr; +proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; +proxy_set_header X-Forwarded-Proto $scheme; +proxy_read_timeout 60s; +# Aligne sur la borne de depot du Cloud. +client_max_body_size 5g; diff --git a/docker/nginx/snippets/security-headers.conf b/docker/nginx/snippets/security-headers.conf new file mode 100644 index 0000000..19c2c49 --- /dev/null +++ b/docker/nginx/snippets/security-headers.conf @@ -0,0 +1,8 @@ +# En-tetes de securite communs. CSP stricte : aucun script en ligne, aucun +# cadre, aucune origine externe. Les styles tolerent l'inline (attributs +# `style=` de React) : c'est une concession sans effet sur l'execution de code. +add_header Content-Security-Policy "default-src 'self'; base-uri 'none'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; font-src 'self' data:; connect-src 'self'" always; +add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; +add_header X-Content-Type-Options "nosniff" always; +add_header Referrer-Policy "strict-origin-when-cross-origin" always; +add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always; diff --git a/docker/publish.sh b/docker/publish.sh new file mode 100644 index 0000000..d6b7af1 --- /dev/null +++ b/docker/publish.sh @@ -0,0 +1,17 @@ +#!/bin/sh +set -eu + +SRC="${1:-/app/dist}" +DEST="${2:-/output}" + +REL="releases/$(date -u +%Y%m%dT%H%M%SZ)-$$" +KEEP=$(basename "$REL") + +mkdir -p "$DEST/$REL" +cp -a "$SRC/." "$DEST/$REL/" +touch "$DEST/$REL" + +ln -sfn "$REL" "$DEST/.current.tmp" +mv -T "$DEST/.current.tmp" "$DEST/current" + +find "$DEST/releases" -mindepth 1 -maxdepth 1 -type d ! -name "$KEEP" -mmin +5 -exec rm -rf {} + 2>/dev/null || true diff --git a/docs/agents.md b/docs/agents.md new file mode 100644 index 0000000..c5f963c --- /dev/null +++ b/docs/agents.md @@ -0,0 +1,75 @@ +# Agents — CoHaiSe Cloud + +Conventions pour reprendre ce dépôt seul. Démarrage rapide : `README.md`. +Détails : `architecture.md`, `api.md`, `deployment.md`, `security.md`. + +## Commandes + +| Action | Commande | +| --- | --- | +| Lever l'ensemble | `make up` | +| Dev front | `make dev` (Vite 5174 → proxy 3101) | +| Vérifier | `make check` (typecheck + build) | +| Republier le front | `make front` | +| Migrations | `make migrate` / `--check` via `docker compose run --rm migrate …` | +| Sauvegarder | `make backup` | +| Comptes | `make admin ARGS="--email … --first … --last …"` | +| Journal / état | `make logs`, `make ps` | +| Santé | `curl -I http://localhost:8083/healthz` | + +`make check` est le seul filet de sécurité automatique (ni linter, ni tests, ni +CI). L'exécuter avant de déclarer un travail fini. + +## Règles du dépôt + +1. **Ne pas lire `.env`** : secrets de production. Écrire un `SESSION_SECRET` + manquant est autorisé ; le diffuser, non. +2. **Ne pas committer ni pousser** sans demande explicite. +3. **Pas de `down -v`, pas de suppression de volume** : `db_data` porte les + données, `media_data` les fichiers. +4. **Ne jamais modifier une migration déjà appliquée** : nouveau fichier numéroté + seulement. Le checksum bloquerait le démarrage. +5. **API admin** : les routes `/api/cloud/admin/*` existent (UI Administration). + La CLI (`make admin`) reste pour l'amorçage et les cas hors ligne. +6. **Chemin disque** : toujours via `storage.ts` (`resolveInside`), jamais par + concaténation depuis une entrée utilisateur. +7. **404 plutôt que 403** sur une ressource non accessible : ne pas introduire + d'énumération. +8. **CSP stricte** : pas de script en ligne dans `index.html` (utiliser un + fichier dans `public/`, comme `theme.js`). + +## Conventions + +- TypeScript strict, project references racine. +- Hono + Zod : toute route avec corps passe par un schéma Zod dédié. +- Erreurs : `AppError` + codes (`errors.ts`) — jamais `throw` brut, jamais de + détail de schéma dans une 500. +- SQL : requêtes préparées uniquement, pas de `raw()` hors DDL. +- Front : un seul client HTTP (`frontend/cloud/src/lib/api.ts`), + `credentials: "same-origin"`. React Router 7 (`App.tsx`) + `AppShell`, contexte + de session dans `lib/session.tsx`. +- `.editorconfig` : 2 espaces, LF, UTF-8. + +## Design system + +`frontend/shared` (`@cohaise/ui`) vit dans ce dépôt. + +- `tokens.css` est la source unique des couleurs et typographies ; ne pas coder + de couleur en dur ailleurs. +- Un composant propre à une page se développe dans `frontend/cloud`, pas dans le + design system. +- Palette : accent carmin `#b71c1c`, destructif rouge `#d32f2f`/`#ef4444`, + avertissement jaune. Aucune orange. + +- **Aucun commit** : rien n'est encore historié, tout est untracked. + +## Pièges + +- **`.env` ≠ `.env.example`** : comparer avant de conclure à un bug de port. +- **README de paquet périmés** — utiliser ce dossier `docs/`. +- **Build Docker et DNS** : les `build:` passent par `network: host` ; si `npm ci` + échoue par `EAI_AGAIN`, le résolveur du démon est en cause. +- **Limitation de débit active** (applicatif + nginx) : un test en rafale peut + recevoir `419`/`503` côté API ou `503` nginx — ce n'est pas un bug. +- Après `make up`, vérifier l'ordre : `migrate` doit être `exited (0)` avant que + `api` ne devienne `healthy`. diff --git a/docs/api.md b/docs/api.md new file mode 100644 index 0000000..ac17bb4 --- /dev/null +++ b/docs/api.md @@ -0,0 +1,140 @@ +# API et modèle de données — CoHaiSe Cloud + +Base : **`/api/cloud`**, plus `GET /healthz` (sonde base, `503` si indisponible). +Middleware `attachUser` monté sur les préfixes ; `requireAuth` sur chaque route +sauf la connexion et les flux publics (mot de passe oublié, confirmation +d'adresse). + +## Routes + +### Session + +| Méthode | Chemin | Garde | +| --- | --- | --- | +| POST | `/api/cloud/auth/login` | publique, **limitée par IP** | +| POST | `/api/cloud/auth/logout` | `requireAuth` | +| GET | `/api/cloud/auth/me` | `requireAuth` | +| POST | `/api/cloud/auth/change-password` | `requireAuth` + Zod | + +### Compte + +| Méthode | Chemin | Garde | +| --- | --- | --- | +| PATCH | `/api/cloud/account/profile` | `requireAuth` | +| GET | `/api/cloud/account/sessions` | `requireAuth` | +| DELETE | `/api/cloud/account/sessions/:id` | `requireAuth` | +| DELETE | `/api/cloud/account/sessions` | `requireAuth` (les autres) | +| PUT | `/api/cloud/account/avatar` | `requireAuth` (corps brut image) | +| GET | `/api/cloud/account/avatar/:userId` | `requireAuth` | +| DELETE | `/api/cloud/account/avatar` | `requireAuth` | +| POST | `/api/cloud/account/forgot-password` | publique, **limitée par IP** | +| POST | `/api/cloud/account/reset-password` | publique, **limitée par IP** | +| POST | `/api/cloud/account/email-change` | `requireAuth`, **limitée** | +| POST | `/api/cloud/account/email-change/confirm` | publique (jeton) | + +### Dossiers et fichiers + +| Méthode | Chemin | Garde | +| --- | --- | --- | +| GET | `/api/cloud/folders` | `requireAuth` (visibles seulement) | +| POST | `/api/cloud/folders` | `requireAuth` | +| PATCH | `/api/cloud/folders/:id` | `requireAuth` + gestion du dossier | +| POST | `/api/cloud/folders/:id/move` | `requireAuth` + gestion | +| DELETE | `/api/cloud/folders/:id` | `requireAuth` + gestion (corbeille) | +| GET | `/api/cloud/folders/:id/permissions` | `requireAuth` + gestion | +| POST | `/api/cloud/folders/:id/permissions` | `requireAuth` + gestion | +| DELETE | `/api/cloud/folders/:id/permissions/:userId` | `requireAuth` + gestion | +| GET | `/api/cloud/files` | `requireAuth` | +| PUT | `/api/cloud/files` | `requireAuth` (corps brut, upload) | +| GET | `/api/cloud/files/:id/download` | `requireAuth` | +| GET | `/api/cloud/files/:id/thumbnail` | `requireAuth` | +| PATCH | `/api/cloud/files/:id` | `requireAuth` + écriture (renommer) | +| POST | `/api/cloud/files/:id/move` | `requireAuth` + écriture | +| PUT | `/api/cloud/files/:id/star` | `requireAuth` | +| DELETE | `/api/cloud/files/:id` | `requireAuth` + écriture (corbeille) | + +### Corbeille, recherche, galerie + +| Méthode | Chemin | Garde | +| --- | --- | --- | +| GET | `/api/cloud/trash` | `requireAuth` | +| POST | `/api/cloud/trash/folders/:id/restore` | `requireAuth` | +| POST | `/api/cloud/trash/files/:id/restore` | `requireAuth` | +| DELETE | `/api/cloud/trash/folders/:id` | `requireAuth` (purge) | +| DELETE | `/api/cloud/trash/files/:id` | `requireAuth` (purge) | +| DELETE | `/api/cloud/trash` | `requireAuth` (vider) | +| GET | `/api/cloud/search` | `requireAuth` | +| GET | `/api/cloud/media` | `requireAuth` | + +### Administration (`role_slug = admin`) + +| Méthode | Chemin | +| --- | --- | +| GET | `/api/cloud/admin/stats` | +| GET | `/api/cloud/admin/users` | +| POST | `/api/cloud/admin/users` | +| PATCH | `/api/cloud/admin/users/:id` | +| DELETE | `/api/cloud/admin/users/:id` | +| POST | `/api/cloud/admin/users/:id/reset-password` | +| GET | `/api/cloud/admin/storage-locations` | +| POST | `/api/cloud/admin/storage-locations` | +| PATCH | `/api/cloud/admin/storage-locations/:id` | +| GET | `/api/cloud/admin/audit` | + +## Droits d'accès + +Calculés **en base à chaque requête**, depuis la session — jamais depuis un +en-tête (`backend/cloud/src/access.ts`). + +| Concept | Règle | +| --- | --- | +| Rôles (`users.role_slug`) | `admin` passe tout, `user` par défaut ; `readonly` seedé par `002` puis supprimé par `004` | +| Lecture | propriétaire du dossier, **ou** ligne `folder_permissions` de niveau `read`/`write`/`admin`, **ou** dossier `access_type = 'public'` | +| Écriture | propriétaire, **ou** `write`/`admin` dans `folder_permissions` | +| Gestion (renommer/déplacer/partager/supprimer) | propriétaire, `admin` de partage, ou rôle global `admin` (`canManageFolder`) | +| Expiration | `expires_at NULL` ou future ; une permission expirée disparaît de la lecture | +| Listing | filtré en SQL — les entrées non visibles ne sont pas chargées puis masquées | +| Réponse | **404 plutôt que 403** : jamais d'indice sur l'existence d'une ressource | + +Le dossier **Public** (`006_public_folder.sql`, `access_type='public'`) est lisible +par tous les membres authentifiés, en écriture pour son propriétaire. + +## Validation et limites d'upload + +| Contrôle | Détail | +| --- | --- | +| Corps | `PUT /files` en flux brut (pas de multipart), `?name=` et `?folderId=` | +| Taille | plafond `users.max_file_bytes`, vérifié en flux (coupure si dépassement) | +| Quota | `users.used_bytes` + quota `storage_locations`, revérifiés avant écriture | +| Chemin disque | dérivé du slug + UUID, jamais du nom affiché (`storage.ts`) | +| Renommage | `PATCH /files/:id { name }`, `PATCH /folders/:id { name, description }` | +| Déplacement | `folderId`/`parentId` : refuse de placer un dossier dans son propre sous-arbre | + +## Modèle de données + +`backend/cloud/migrations/` — application stricte dans l'ordre, checksum SHA-256 +par fichier, dérive refusée au démarrage. + +| Fichier | Contenu | +| --- | --- | +| `000_schema_migrations.sql` | table de suivi (`version`, `applied_at`, `checksum`) | +| `001_initial_schema.sql` | `roles, users, password_reset_tokens, storage_locations, folders, files, folder_permissions, share_links, settings, audit_logs` | +| `002_reference_data.sql` | seeds : rôles, emplacement `principal`, réglages | +| `003_integrity_backstop.sql` | `CHECK` d'intégrité (audit, auto-parenté) | +| `004_cloud_requirements.sql` | `first_name`/`last_name`, `used_bytes`, `max_file_bytes`, `user_sessions`, `media_metadata`, `file_variants`, **suppression de `share_links`** | +| `005_storage_location_realign.sql` | réalignement des emplacements | +| `006_public_folder.sql` | `folders.access_type` / `is_system`, dossier `Public` | + +Tables actives : `users, user_sessions, folders, folder_permissions, files, +media_metadata, file_variants, user_avatars, storage_locations, settings, +password_reset_tokens, email_change_requests, audit_logs`. + +## Erreurs métier + +`AppError` avec codes stables (`backend/shared/src/errors.ts`). Correspondances +MariaDB : `1062` → 409, `1146` → 503 `NOT_MIGRATED`, `1406` → 422. Le corps d'une +500 ne contient jamais de détail de schéma. Réponse normalisée : + +```json +{ "error": { "status": 404, "code": "NOT_FOUND", "message": "…", "requestId": "…" } } +``` diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..3f60976 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,96 @@ +# Architecture — CoHaiSe Cloud + +Fichiers et médias : arborescence de dossiers, envoi, téléchargement, corbeille, +recherche, galerie, partage nominatif, comptes et administration. Une API +Node/TypeScript, une base MariaDB, un stockage de fichiers monté en volume. + +## Pile + +| Élément | Où | +| --- | --- | +| React 19 + Vite 8 + Tailwind 4 + react-router-dom 7 | `frontend/cloud` | +| Hono | `backend/cloud/src/index.ts` (`@cohaise/server` pour le socle) | +| MariaDB (`mysql2`) | `backend/shared/src/db.ts` | +| Nodemailer | `backend/shared/src/mail.ts` | +| sharp (vignettes) | `backend/cloud/src/media.ts` | +| Validation Zod | `backend/shared/src/config.ts` et chaque route | + +## Découpage + +``` +backend/shared/ @cohaise/server : config, db, mail, ratelimit, http, service, auth, errors +backend/cloud/ routes/, access.ts, storage.ts, media.ts, cli.ts +backend/cloud/migrations/ 000 … 006 +frontend/shared/ @cohaise/ui : Design System (boutons, cartes, champs, spinner) +frontend/cloud/ router + AppShell + pages/ +docker/ Dockerfile(.app/.api), nginx/, publish.sh +``` + +`backend/shared` est générique (sessions, erreurs, migrations, courriel, +limitation de débit) ; `backend/cloud` porte le métier : droits, quotas, chemins +disque, traitement média. + +## Chaîne de démarrage + +`docker-compose.yml` — projet **`cohaise-cloud`**, 5 services : + +``` +db ──healthy──▶ migrate (runMigrations + assertNoDrift, puis s'arrête) + │ + └──service_completed_successfully──▶ api ──▶ nginx +app-build (publish.sh, terminé avant nginx) +``` + +- `migrate` monte `./backend/cloud/migrations:/migrations:ro`. +- `api` refuse de démarrer si une migration appliquée a été modifiée (dérive de + checksum). `onReady` purge les sessions et la corbeille expirées. +- volumes : `app_data` (HTML), `db_data` (MariaDB), `media_data`. + +## API et front + +- API `/api/cloud` : voir [`api.md`](api.md). +- Front : React Router (`frontend/cloud/src/App.tsx`) avec gardes + `RequireAuth` / `RequireReady` / `RequireAdmin` et `AppShell` + (`components/AppShell.tsx`) : navigation latérale, en-tête, contenu. +- Pages : `Login`, `ForgotPassword`, `ResetPassword`, `ConfirmEmail`, + `ChangePassword`, `Browser`, `Search`, `Gallery`, `Trash`, `Profile`, + `Admin` (comptes / stockage / journal). +- Client HTTP unique `lib/api.ts` (base `/api/cloud`, `same-origin`) ; contexte + de session `lib/session.tsx` ; dialogues réutilisables dans + `components/dialogs.tsx`. +- En-têtes nginx : CSP stricte, HSTS, `nosniff`, `Referrer-Policy`, + `Permissions-Policy` (`docker/nginx/snippets/`). `X-Frame-Options` est + remplacé par `frame-ancestors 'none'` dans la CSP. +- Dev : Vite **5174**, proxy `/api` → `http://127.0.0.1:3101`. Prod : nginx sert + le SPA avec repli `try_files … @spa` (liens profonds pris en charge). + +## Sessions + +- Cookie `cohaise_session` : `httpOnly`, `SameSite=Lax`, `path=/`, `secure` + déduit du schéma réel (et de `TRUST_PROXY`). +- En base, uniquement le **SHA-256** du jeton. TTL `SESSION_TTL_HOURS`. +- Changement de mot de passe ⇒ révocation des autres sessions ; gestion fine + depuis la page compte. + +## Stockage et médias + +- `MEDIA_DIR=/data/media/originals`, `VARIANT_DIR=/data/media/variants`. +- Chemin physique `${MEDIA_DIR}//` (`storage.ts`), nom affiché + jamais dans le chemin. +- `media.ts` : classification (`image/video/audio/document/archive/other`), + vignette (`sharp`, seuil 480 px) écrite dans `VARIANT_DIR`, métadonnées dans + `media_metadata` / `file_variants`. Indexation **best-effort** après upload. +- Avatars dans `user_avatars`. + +## Corbeille + +Suppression douce (`deleted_at`). `purgeExpiredTrash` (démarrage + accès) purge +au-delà de `trash_retention_days`. Restauration et purge manuelles exposées via +`/trash`. + +## Limites connues + +- Upload séquentiel par `` : pas de drag & drop, pas de + reprise de transfert, pas de multipart. +- `docker/README.md` (et tout README de paquet) peut décrire un état antérieur : + se fier à `docs/`. diff --git a/docs/deployment.md b/docs/deployment.md new file mode 100644 index 0000000..2cc15de --- /dev/null +++ b/docs/deployment.md @@ -0,0 +1,191 @@ +# Déploiement — CoHaiSe Cloud + +## Démarrer + +```sh +cp .env.example .env # renseigner mots de passe + SESSION_SECRET (≥ 32 car.) +make up # db → migrate → api → nginx, front compris +make front # reconstruire et republier le front +``` + +Réponse sur **`http://localhost:8083`**. + +La configuration est validée **avant** l'ouverture d'aucun port : si une variable +manque ou est mal formée, le process s'arrête en listant exactement ce qui +pose problème (`backend/shared/src/config.ts`). + +## Variables + +| Variable | Rôle | Défaut | +| --- | --- | --- | +| `COHAISE_HTTP_PORT` | port nginx | `8083` | +| `COHAISE_API_PORT` | port API | `3101` | +| `COHAISE_DB_PORT` | port MariaDB | `3407` | +| `CLOUD_DATABASE` / `CLOUD_DB_USER` / `CLOUD_DB_PASSWORD` | base applicative | — | +| `CLOUD_DB_ROOT_PASSWORD` | root, réservé aux sauvegardes | — | +| `CLOUD_DB_CONNECTION_LIMIT` | taille du pool | `8` | +| `SESSION_SECRET` | **obligatoire**, ≥ 32 car. | — | +| `SESSION_TTL_HOURS` | durée de session | `336` | +| `PUBLIC_ORIGIN` | **obligatoire**, URL absolue servant aux liens courriel | — | +| `CLOUD_CORS_ORIGIN` | origines CORS (vide = CORS off) | vide | +| `SMTP_HOST` | **obligatoire**, relais d'envoi | — | +| `SMTP_PORT` | port SMTP | `587` | +| `SMTP_USER` / `SMTP_PASSWORD` | authentification (vides = relais local) | vide | +| `SMTP_FROM` | adresse d'expédition | — | +| `SMTP_SECURE` | TLS implicite (port 465) | `false` | +| `RATE_LIMIT_LOGIN_MAX` | tentatives par fenêtre | `10` | +| `RATE_LIMIT_LOGIN_WINDOW_MS` | largeur de fenêtre | `60000` | +| `LOG_LEVEL` | `silent…debug` | `info` | +| `TRUST_PROXY` | croire `X-Forwarded-*` | `true` | + +> `PUBLIC_ORIGIN`, `SMTP_HOST` et `SMTP_FROM` sont **obligatoires** : sans eux +> l'API refuse de démarrer (courriel de réinitialisation / confirmation). + +Variables fixes posées par compose : `PORT=8080`, `DB_HOST=db`, +`MEDIA_DIR=/data/media/originals`, `VARIANT_DIR=/data/media/variants`, +`NODE_ENV=production`, `TZ=Europe/Paris`. + +> **Écueil** : si une clé attendue manque dans `.env`, compose utilise +> silencieusement son **défaut**. En cas de doute, comparer avec `.env.example` : +> c'est la référence, pas `.env`. + +## Services + +| Service | Port | Santé | Rôle | +| --- | --- | --- | --- | +| `db` | `3407` | `healthcheck.sh --connect --innodb_initialized` | MariaDB, volume `db_data` | +| `migrate` | — | — | joue les migrations manquantes, puis s'arrête | +| `api` | `3101` | `GET :8080/healthz` (start 20 s) | Hono, volume `media_data` | +| `nginx` | `8083` | `GET /healthz` | sert le front, proxy `/api/` | +| `app-build` | — | — | build + publication atomique, `restart: "no"` | + +Ordre garanti par `depends_on` : `migrate` attend `db` healthy, `api` attend +`db` healthy **et** `migrate` terminé avec succès. + +> **Images** : la configuration nginx (CSP/HSTS, `limit_req`, snippets) est +> **copiée dans l'image**. Toute modification de `docker/nginx/` exige de +> reconstruire le service `nginx`. L'API embarque `sharp` (binaires précompilés +> musl attendus sur Alpine) ; vérifier le démarrage après un changement de base. + +## Commandes + +```sh +make help # liste complète +make ps / make logs # état et journaux +make front # reconstruire + republier le front +make db # redémarrer la base +make migrate # rejouer explicitement les migrations (hors démarrage) +make backup # dump horodaté → ./backups/cloud-.sql.gz +make admin ARGS=... # créer / réinitialiser un compte +make dev # Vite 5174, proxy /api → 3101 +make check # typecheck + build +make down # arrêt, volumes conservés +``` + +`make backup` lit le mot de passe **dans le conteneur** : il ne passe ni par la +commande, ni par le dépôt. + +## Migrations + +- Fichiers `NNN_nom.sql`, tri lexical, appliqués une seule fois, checksum + SHA-256 enregistré dans `schema_migrations`. +- **Une migration appliquée ne se modifie jamais** : une correction passe par + un nouveau numéro. Si le contenu d'un fichier déjà joué change, + `assertNoDrift()` refuse le démarrage de l'API. +- Application automatique au démarrage, ou manuelle : + +```sh +make migrate +docker compose run --rm migrate node dist/cli.js --dir /migrations --dry-run +docker compose run --rm migrate node dist/cli.js --dir /migrations --check # 1 s'il en reste +``` + +Codes de sortie : `0` OK, `1` erreur ou dérive, `2` configuration. + +## Comptes + +```sh +make admin ARGS="--email moi@exemple.fr --first Jean --last Dupont" +make admin ARGS="--email moi@exemple.fr --reset" +``` + +Options : `--email` (obligatoire), `--first`/`--last` (obligatoires à la +création), `--role` (défaut `admin`), `--password`, `--reset`. Sans +`--password`, le mot de passe est généré (18 caractères) et affiché **une +seule fois**. Un compte créé a `must_change_password=1`. + +Aucune route HTTP ne crée un compte. + +## Sauvegarde et restauration + +```sh +make backup # dump compressé dans ./backups/ +``` + +Le dossier `backups/` est gitignoré. Pour restaurer : `gunzip -c | make +… ` via un conteneur `db` en service — opération manuelle, à faire hors +démarrage automatique. + +## Exposition — Cloudflare Tunnel + +L'application est prête à être publiée derrière un tunnel Cloudflare : aucune +adresse ni aucun domaine n'est codé en dur. + +- `nginx` écoute sur `COHAISE_HTTP_PORT` (8083 par défaut) avec `server_name _` : + n'importe quel `Host` est accepté. +- `cloudflared` publie le service local (`http://127.0.0.1:8083`). +- Renseigner l'origine publique **exacte** vue par les navigateurs : + `PUBLIC_ORIGIN=https://cloud.example.com`. Elle sert aux liens envoyés par + courriel (réinitialisation, confirmation). +- `CLOUD_CORS_ORIGIN` ne sert qu'à un front servi depuis une autre origine ; + avec un tunnel unique, laisser vide. +- Les cookies de session passent en `Secure` dès que le proxy annonce + `X-Forwarded-Proto: https` (cloudflared le fait) : garder `TRUST_PROXY=true`. +- Certificat et HSTS sont assurés en amont par Cloudflare — ne pas exposer + directement le port 8083 sur Internet. + +Exemple `~/.cloudflared/config.yml` : + +```yaml +tunnel: +credentials-file: /home//.cloudflared/.json +ingress: + - hostname: cloud.example.com + service: http://127.0.0.1:8083 + - service: http_status:404 +``` + +Les ports `8083`, `3101` et `3407` sont publiés sur **127.0.0.1 uniquement** : +rien n'est joignable depuis l'extérieur en dehors du tunnel. + +## Intégration continue (Gitea Actions) + +Le dépôt vit sur Gitea. **Gitea Actions** reprend la syntaxe GitHub Actions, +mais exige sur l'instance : un **runner self-hosted** enregistré +(Administration → Actions → Runners) et les **Actions activées** sur le dépôt +(Paramètres du dépôt → section Actions/Unités). + +| Workflow | Déclencheur | Rôle | +| --- | --- | --- | +| `deploy.yml` | push `main` (backend/frontend/docker) ou manuel | `git pull`, `make check`, `make front`, rebuild `api`+`nginx` | +| `pr.yml` | push hors `main` | ouvre une PR vers `main` via l'API REST Gitea (`curl` + `python3`) | +| `renovate.yml` | hebdomadaire ou manuel | lance Renovate contre Gitea | + +À adapter avant activation : + +- **Chemin de déploiement** : `deploy.yml` lit le secret `DEPLOY_DIR` ; s'il + n'est pas défini, la valeur par défaut `/srv/apps/cohaise-cloud/CoHaiSe-CLOUD` + est utilisée. Créer le secret `DEPLOY_DIR` une fois le chemin réel connu. +- **Label du runner** : `runs-on: self-hosted` ; si le runner porte des labels + additionnels (ex. `gitea`, `docker`), les renseigner. +- **Secrets** (Paramètres → Actions → Secrets) : + - `pr.yml` utilise le `GITHUB_TOKEN` fourni par Gitea Actions. Si les PR sont + refusées, créer un secret `PAT` (jeton personnel Gitea, portée `repo`) et + remplacer `secrets.GITHUB_TOKEN`. + - `renovate.yml` exige `RENOVATE_TOKEN` : jeton personnel Gitea avec la portée + `repo`. +- `python3` doit être présent sur le runner (Debian l'a par défaut). + +**dependabot.yml n'est pas supporté par Gitea** : Renovate le remplace, avec +`renovate.json` (groupes npm backend/frontend, images Docker) et le workflow +`renovate.yml` (image `ghcr.io/renovatebot/renovate` en `RENOVATE_PLATFORM=gitea`). diff --git a/docs/security.md b/docs/security.md new file mode 100644 index 0000000..86efbe7 --- /dev/null +++ b/docs/security.md @@ -0,0 +1,78 @@ +# Sécurité — CoHaiSe Cloud + +## En place + +### Comptes et sessions + +| Mesure | Détail | +| --- | --- | +| Mots de passe | `scrypt` natif `node:crypto` (`N=16384, r=8, p=1`, keylen 64, sel 16 o.), comparaison `timingSafeEqual` | +| Stockage session | jeton aléatoire 32 o. côté client, **SHA-256** en base | +| Cookie | `cohaise_session`, `httpOnly`, `SameSite=Lax`, `path=/`, `secure` selon le schéma réel | +| Expiration | `SESSION_TTL_HOURS` (336 h) ; `revoked_at`, `is_active`, `deleted_at` vérifiés à chaque résolution | +| Révocation | logout, purge au démarrage, **toutes les autres sessions** au changement de mot de passe, gestion des sessions ouvertes depuis le compte | +| Anti-énumération | hash factice pour une adresse inconnue ; les flux « mot de passe oublié » répondent toujours `{ ok: true }` sans révéler l'existence du compte | +| Jetons à usage unique | réinitialisation de mot de passe et changement d'adresse stockés **hachés**, avec expiration | +| Changement d'adresse | mot de passe actuel exigé, confirmation **à la nouvelle adresse** avant application | + +### Limitation de débit + +- **Applicatif** : `createRateLimiter` (`backend/shared/src/ratelimit.ts`) par IP + sur `auth/login`, `account/forgot-password`, `account/reset-password`, + `account/email-change`. Réglages `RATE_LIMIT_LOGIN_MAX` (10) et + `RATE_LIMIT_LOGIN_WINDOW_MS` (60 s). +- **Edge nginx** : zones `limit_req` `login` (15 r/min, burst 5) et `api` + (60 r/s, burst élevé) — voir `docker/nginx/cloud.conf`. + +### Droits d'accès + +Calculés **en base à chaque requête**, depuis la session — jamais depuis un +en-tête (`backend/cloud/src/access.ts`). Lecture : propriétaire, permission +`folder_permissions` (`read`/`write`/`admin`), ou dossier `public`. Écriture : +`write`/`admin`. **404 plutôt que 403** : jamais d'indice sur l'existence d'une +ressource. + +### Courriel + +Nodemailer (`backend/shared/src/mail.ts`) avec `SMTP_HOST`. `PUBLIC_ORIGIN` +(obligatoire) construit les liens de réinitialisation et de confirmation ; +aucun HTML utilisateur n'est injecté dans les messages. + +### Transport et enveloppe + +- En-têtes API : `x-request-id`, `nosniff`, `referrer-policy: same-origin`. +- En-têtes nginx (`docker/nginx/snippets/security-headers.conf`) : + `Content-Security-Policy` (**`default-src 'self'`, `frame-ancestors 'none'`**, + pas de `unsafe-inline`), `Strict-Transport-Security`, + `X-Content-Type-Options`, `Referrer-Policy`, `Permissions-Policy`. +- SQL : requêtes préparées uniquement, `multipleStatements: false`. +- CORS désactivé par défaut (`CLOUD_CORS_ORIGIN` vide). + +> Le script d'amorçage du thème est sorti de `index.html` vers +> `public/theme.js` exprès : la CSP n'autorise pas `unsafe-inline`. + +### Stockage des fichiers + +- Chemin physique dérivé du slug + UUID, **jamais** du nom affiché ; + `resolveInside()` rejette toute cible hors `MEDIA_DIR`. +- Écriture temporaire `.upload-` puis `rename()` atomique ; copie **en + flux** (un fichier surdimensionné est coupé, pas bufferisé). +- Téléchargement : `content-disposition: attachment`, `nosniff`, + `cache-control: private, max-age=0, must-revalidate`. + +## Hors périmètre (assumé) + +| Sujet | État | +| --- | --- | +| CSRF | pas de jeton CSRF — reposé sur `SameSite=Lax` + `same-origin` ; acceptable tant que le front et l'API partagent l'origine | +| HTTPS | nginx écoute le 80 ; le terminus TLS est le tunnel cloudflared, hors dépôt | +| Chiffrement au repos | fichiers en clair ; seuls mots de passe, sessions et jetons sont dérivés | +| Détection antivirus | aucune analyse des fichiers envoyés | + +## À ne pas faire + +- Ne jamais renvoyer de stack ou de détail de schéma au client. +- Ne jamais ajouter de route qui prend un chemin disque en paramètre : passer + par `storage.ts`. +- Ne jamais persister le jeton de session en clair, ni logger un mot de passe. +- Ne pas réintroduire de script inline dans `index.html` (casserait la CSP). diff --git a/docs/standards.md b/docs/standards.md new file mode 100644 index 0000000..45f2233 --- /dev/null +++ b/docs/standards.md @@ -0,0 +1,59 @@ +# Standards — CoHaiSe Cloud + +Conventions appliquées dans ce dépôt. + +## Formatage + +`.editorconfig` : UTF-8, LF, indentation 2 espaces, `trim_trailing_whitespace` +désactivé pour les `.md`. Aucun Prettier/ESLint installé. + +## Palette + +Source unique : `frontend/shared/src/styles/tokens.css`. + +| Jeton | Rôle | Valeur | +| --- | --- | --- | +| `--cohaise-accent` | marque : liens, focus, primaire | carmin `#b71c1c` | +| `--cohaise-destructive` | suppression, erreurs, champs invalides | `#d32f2f` clair / `#ef4444` sombre | +| `--cohaise-destructive-foreground` | texte posé dessus | `#ffffff` clair / `#1a0505` sombre | +| `--cohaise-warning` | avertissement, badges d'état | jaune `yellow-500` | + +Règles : + +- **Aucune orange** : `--cohaise-amber-*` a été retiré de la palette. Ne pas le + réintroduire. +- `tokens.css` est la source unique des couleurs : toute couleur ajoutée doit être + déclarée là, puis exposée via `theme.css`. +- Toute couleur ajoutée doit passer deux contrastes : comme **texte** sur le fond + d'application, et comme **fond** avec un texte posé dessus (≥ 4.5:1). +- Une règle sombre va dans le bloc `.dark`, jamais en + `@media (prefers-color-scheme: dark)` : la préférence utilisateur prime. + +## Typographies + +Poppins (texte), Orbitron et Cinzel (display), JetBrains Mono (code) — +woff2 hébergés dans `frontend/shared/fonts/`, jamais par CDN. + +## Composants + +`@cohaise/ui` : `Button`, `Card`, `Input`, `Skeleton`, `Spinner`, `cn`. + +- Les composants du design system ne connaissent **jamais** le métier du Cloud. +- Une variante propre à cette app se développe dans `frontend/cloud`, pas dans + `frontend/shared`. + +## Côté serveur + +- Toute entrée validée par Zod, tout chemin disque via `storage.ts`. +- `AppError` + code stable ; les erreurs 500 renvoient un message générique. +- Journal JSON (`LOG_LEVEL`), audit en base pour les actions sensibles. +- Cookies : `httpOnly`, `SameSite=Lax`, `secure` selon le schéma réel. + +## Git et exploitation + +| Élément | Attendu | +| --- | --- | +| `shared` | vit dans ce dépôt, cycle de vie commun | +| Port HTTP | `8083` (`COHAISE_HTTP_PORT`) | +| Dépôt | autonome, importance égale front et back | +| `.env` | jamais versionné (`.env.example` seulement) | diff --git a/docs/workflow.md b/docs/workflow.md new file mode 100644 index 0000000..ab382f7 --- /dev/null +++ b/docs/workflow.md @@ -0,0 +1,93 @@ +# Workflow — CoHaiSe Cloud + +## Boucle de développement + +```sh +make dev # Vite sur http://localhost:5174, proxy /api → 127.0.0.1:3101 +``` + +Le front tourne hors Docker ; l'API et la base doivent être levées : + +```sh +make up # db + migrate + api (+ nginx si besoin) +``` + +Le proxy `vite.config.ts` envoie `/api` vers `3101`, donc les appels +`fetch('/api/cloud/…')` du code source fonctionnent à l'identique en dev et en +prod. + +## Vérification + +```sh +make check # npm run typecheck puis npm run build +curl -I http://localhost:8083/healthz +curl -s http://localhost:3101/healthz +``` + +Il n'y a **ni linter, ni framework de test, ni CI** : `typecheck` + `build` +sont les seules garanties automatiques. `.editorconfig` porte les conventions. + +Après un changement de `docker/nginx/cloud.conf` : l'image doit être +reconstruite (`docker compose build nginx && docker compose up -d nginx`) — le +fichier est copié dans l'image, pas monté. + +## Modifier une route + +1. Schéma d'entrée : Zod dans `backend/cloud/src/routes/.ts`. +2. Droits : passer par `backend/cloud/src/access.ts` (jamais par un paramètre + venu du client). +3. Réponse : renvoyer **404** si la ressource n'est pas censée exister pour ce + compte, 403 seulement pour une règle explicite. +4. Erreur métier : `AppError` depuis `backend/shared/src/errors.ts`. +5. Audit si l'action est sensible (`audit()` dans `access.ts`). +6. `make check`, puis redémarrage de l'API (`docker compose up -d api`). + +## Modifier le schéma + +1. Écrire `backend/cloud/migrations/00N_….sql` (número suivant, jamais éditer + un fichier déjà appliqué). +2. Vérifier : `docker compose run --rm migrate node dist/cli.js --dir /migrations --check` +3. Appliquer : `make migrate` ou redémarrage de l'API. +4. Décrire la migration dans `docs/api.md` (tableau des migrations). + +Le DDL MariaDB n'est pas transactionnel : une migration interrompue peut +laisser la base à moitié migrée. Dans ce cas, corriger par une **nouvelle** +migration, pas en éditant l'ancienne (le checksum bloquerait le démarrage). + +## Modifier le design system + +`frontend/shared` (`@cohaise/ui`) vit dans ce dépôt. + +- `tokens.css` porte les couleurs et typographies ; ne pas en coder ailleurs. +- Après modification : `npm run build --workspace=frontend/shared && make front`. + +## Où changer quoi + +| Besoin | Fichier | +| --- | --- | +| Droit d'accès à un dossier/fichier | `backend/cloud/src/access.ts` | +| Taille/quota par défaut | migration `004`, table `users` / `settings` | +| Chemin physique des fichiers | `backend/cloud/src/storage.ts` | +| En-têtes, CORS, healthz | `backend/shared/src/http.ts` | +| Durée de session | `SESSION_TTL_HOURS` | +| Port | `COHAISE_HTTP_PORT` (nginx), `COHAISE_API_PORT` (API) | +| Interface (parcours dossiers) | `frontend/cloud/src/pages/Browser.tsx` | +| Routes et gardes du front | `frontend/cloud/src/App.tsx` | +| Couleurs / composants | `frontend/shared/src/styles/tokens.css` | + +## Git + +- Branche `main`, remote `origin https://git.cohaise.dev/Esiah/CoHaiSe-CLOUD.git`. +- **Aucun commit pour l'instant** : l'historique est vierge. +- `.gitignore` exclut `.env`, `.env.*` (sauf `.env.example`), `backups/`, + `node_modules/`, `dist/`, `*.tsbuildinfo`. + +## Pièges connus + +1. **`.env` local désynchronisé** de `.env.example` : les clés `COHAISE_*` + manquantes basculent silencieusement sur les défauts compose. +2. **README de paquet** (`docker/README.md`, `backend/cloud/README.md`) : états + antérieurs du dépôt. Se fier à ce dossier `docs/`. +3. **Limitation de débit active** (applicatif + nginx) : une rafale peut renvoyer + `419`/`503`. +4. **CSP stricte** : aucun script inline dans `index.html` (voir `public/theme.js`). diff --git a/frontend/cloud/index.html b/frontend/cloud/index.html new file mode 100644 index 0000000..ef7166d --- /dev/null +++ b/frontend/cloud/index.html @@ -0,0 +1,14 @@ + + + + + + + CoHaiSe Cloud + + + +
+ + + diff --git a/frontend/cloud/package.json b/frontend/cloud/package.json new file mode 100644 index 0000000..b554d8a --- /dev/null +++ b/frontend/cloud/package.json @@ -0,0 +1,27 @@ +{ + "name": "@cohaise/cloud-web", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc --noEmit && vite build", + "typecheck": "tsc --noEmit", + "preview": "vite preview" + }, + "dependencies": { + "@cohaise/ui": "*", + "react": "^19.3.0", + "react-dom": "^19.3.0", + "react-router-dom": "^7.18.4" + }, + "devDependencies": { + "@tailwindcss/vite": "^4.3.3", + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "@vitejs/plugin-react": "^6.1.1", + "tailwindcss": "^4.3.3", + "typescript": "^7.0.2", + "vite": "^8.3.1" + } +} diff --git a/frontend/cloud/public/theme.js b/frontend/cloud/public/theme.js new file mode 100644 index 0000000..f2c3678 --- /dev/null +++ b/frontend/cloud/public/theme.js @@ -0,0 +1,10 @@ +(function () { + try { + var stored = localStorage.getItem("cohaise-theme"); + var prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches; + var theme = stored || (prefersDark ? "dark" : "light"); + if (theme === "dark") document.documentElement.classList.add("dark"); + } catch (error) { + void error; + } +})(); diff --git a/frontend/cloud/src/App.tsx b/frontend/cloud/src/App.tsx new file mode 100644 index 0000000..f690051 --- /dev/null +++ b/frontend/cloud/src/App.tsx @@ -0,0 +1,73 @@ +import { Navigate, Outlet, Route, Routes } from "react-router-dom"; +import { Spinner } from "@cohaise/ui"; +import { useSession } from "./lib/session.js"; +import { AppShell } from "./components/AppShell.js"; +import { Login } from "./pages/Login.js"; +import { ForgotPassword } from "./pages/ForgotPassword.js"; +import { ResetPassword } from "./pages/ResetPassword.js"; +import { ConfirmEmail } from "./pages/ConfirmEmail.js"; +import { ChangePassword } from "./pages/ChangePassword.js"; +import { Browser } from "./pages/Browser.js"; +import { Search } from "./pages/Search.js"; +import { Gallery } from "./pages/Gallery.js"; +import { Trash } from "./pages/Trash.js"; +import { Profile } from "./pages/Profile.js"; +import { AdminUsers, AdminStorage, AdminAudit } from "./pages/Admin.js"; + +const RequireAuth = () => { + const { user, loading } = useSession(); + if (loading) { + return ( +
+ +
+ ); + } + if (!user) return ; + return ; +}; + +const RequireReady = () => { + const { user } = useSession(); + if (user?.must_change_password) return ; + return ; +}; + +const RequireAdmin = () => { + const { user } = useSession(); + if (!user || user.role_slug !== "admin") return ; + return ; +}; + +export const App = () => ( + + } /> + } /> + } /> + } /> + + }> + } /> + + }> + }> + } /> + } /> + } /> + } /> + } /> + + + }> + }> + } /> + } /> + } /> + + + + + + } /> + +); diff --git a/frontend/cloud/src/components/AppShell.tsx b/frontend/cloud/src/components/AppShell.tsx new file mode 100644 index 0000000..cc6aadc --- /dev/null +++ b/frontend/cloud/src/components/AppShell.tsx @@ -0,0 +1,154 @@ +import { useState } from "react"; +import { NavLink, Outlet } from "react-router-dom"; +import { Button, cn } from "@cohaise/ui"; +import { useSession } from "../lib/session.js"; +import { + ActivityIcon, + CloseIcon, + FolderIcon, + HardDriveIcon, + ImageIcon, + LogoutIcon, + MenuIcon, + SearchNavIcon, + SettingsIcon, + ShieldIcon, + TrashIcon, +} from "./icons.js"; + +interface NavItem { + to: string; + label: string; + icon: typeof FolderIcon; +} + +const NAV: NavItem[] = [ + { to: "/files", label: "Fichiers", icon: FolderIcon }, + { to: "/search", label: "Recherche", icon: SearchNavIcon }, + { to: "/gallery", label: "Galerie", icon: ImageIcon }, + { to: "/trash", label: "Corbeille", icon: TrashIcon }, +]; + +const ADMIN_NAV: NavItem[] = [ + { to: "/admin/comptes", label: "Comptes", icon: ShieldIcon }, + { to: "/admin/stockage", label: "Stockage", icon: HardDriveIcon }, + { to: "/admin/audit", label: "Journal", icon: ActivityIcon }, +]; + +const ACCOUNT_NAV: NavItem = { to: "/profile", label: "Mon compte", icon: SettingsIcon }; + +const initials = (first: string, last: string): string => + `${first.charAt(0)}${last.charAt(0)}`.toUpperCase() || "?"; + +const navClass = ({ isActive }: { isActive: boolean }) => + cn( + "flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors", + isActive + ? "bg-accent/10 text-accent" + : "text-muted-foreground hover:bg-surface-hover hover:text-foreground", + ); + +export const AppShell = () => { + const { user, logout } = useSession(); + const [menuOpen, setMenuOpen] = useState(false); + if (!user) return null; + + const isAdmin = user.role_slug === "admin"; + const allNav = [...NAV, ...(isAdmin ? ADMIN_NAV : []), ACCOUNT_NAV]; + + const brand = ( + setMenuOpen(false)}> + + CoHaiSe + + + + Cloud + + + ); + + const renderLink = (item: NavItem) => { + const Icon = item.icon; + return ( + setMenuOpen(false)}> + + {item.label} + + ); + }; + + return ( +
+ + +
+
+
+
+ + {brand} +
+ +
+
+

+ {user.first_name} {user.last_name} +

+

+ {user.role_name} +

+
+ + +
+
+ + {menuOpen ? ( + + ) : null} +
+ +
+ +
+
+
+ ); +}; diff --git a/frontend/cloud/src/components/IconAction.tsx b/frontend/cloud/src/components/IconAction.tsx new file mode 100644 index 0000000..d3389db --- /dev/null +++ b/frontend/cloud/src/components/IconAction.tsx @@ -0,0 +1,31 @@ +import type { ReactNode } from "react"; +import { Spinner, cn } from "@cohaise/ui"; + +export const IconAction = ({ + label, + icon, + onClick, + isLoading = false, + tone = "neutral", +}: { + label: string; + icon: ReactNode; + onClick: () => void; + isLoading?: boolean; + tone?: "neutral" | "danger"; +}) => ( + +); diff --git a/frontend/cloud/src/components/dialogs.tsx b/frontend/cloud/src/components/dialogs.tsx new file mode 100644 index 0000000..65b1308 --- /dev/null +++ b/frontend/cloud/src/components/dialogs.tsx @@ -0,0 +1,381 @@ +import { useEffect, useState, type FormEvent } from "react"; +import { Button, Input, cn } from "@cohaise/ui"; +import { + ApiError, + api, + formatDate, + type Folder, + type FolderPermission, +} from "../lib/api.js"; +import { Alert, Modal } from "./feedback.js"; +import { TrashIcon } from "./icons.js"; + +const LEVELS = ["read", "write", "admin"] as const; +const LEVEL_LABEL: Record = { + read: "Lecture", + write: "Écriture", + admin: "Administration", +}; + +const messageOf = (caught: unknown, fallback: string): string => + caught instanceof ApiError ? caught.message : fallback; + +interface Target { + type: "folder" | "file"; + id: string; + name: string; +} + +export const CreateFolderDialog = ({ + parentId, + onClose, + onCreated, +}: { + parentId: string | null; + onClose: () => void; + onCreated: () => void; +}) => { + const [name, setName] = useState(""); + const [description, setDescription] = useState(""); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + const submit = async (event: FormEvent) => { + event.preventDefault(); + setBusy(true); + setError(null); + try { + await api.createFolder(name, parentId, description.trim() || undefined); + onCreated(); + } catch (caught) { + setError(messageOf(caught, "Création impossible.")); + } finally { + setBusy(false); + } + }; + + return ( + +
void submit(event)}> + setName(event.target.value)} + /> + setDescription(event.target.value)} + /> + {error ? {error} : null} +
+ + +
+
+
+ ); +}; + +export const RenameDialog = ({ + target, + onClose, + onDone, +}: { + target: Target; + onClose: () => void; + onDone: () => void; +}) => { + const [name, setName] = useState(target.name); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + const submit = async (event: FormEvent) => { + event.preventDefault(); + setBusy(true); + setError(null); + try { + if (target.type === "folder") await api.updateFolder(target.id, { name }); + else await api.renameFile(target.id, name); + onDone(); + } catch (caught) { + setError(messageOf(caught, "Renommage impossible.")); + } finally { + setBusy(false); + } + }; + + return ( + +
void submit(event)}> + setName(event.target.value)} + /> + {error ? {error} : null} +
+ + +
+
+
+ ); +}; + +interface TreeEntry { + id: string; + label: string; +} + +const loadTree = async (): Promise => { + const entries: TreeEntry[] = []; + const walk = async (parentId: string | null, prefix: string, depth: number): Promise => { + if (depth > 6) return; + const { folders } = await api.folders(parentId); + for (const folder of folders) { + entries.push({ id: folder.id, label: `${prefix}${folder.name}` }); + await walk(folder.id, `${prefix}${folder.name} / `, depth + 1); + } + }; + await walk(null, "", 0); + return entries; +}; + +export const MoveDialog = ({ + target, + onClose, + onDone, +}: { + target: Target; + onClose: () => void; + onDone: () => void; +}) => { + const [entries, setEntries] = useState(null); + const [destination, setDestination] = useState(""); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + useEffect(() => { + loadTree() + .then(setEntries) + .catch((caught: unknown) => setError(messageOf(caught, "Chargement des dossiers impossible."))); + }, []); + + const submit = async (event: FormEvent) => { + event.preventDefault(); + setBusy(true); + setError(null); + const parentId = destination === "" ? null : destination; + try { + if (target.type === "folder") await api.moveFolder(target.id, parentId); + else await api.moveFile(target.id, parentId); + onDone(); + } catch (caught) { + setError(messageOf(caught, "Déplacement impossible.")); + } finally { + setBusy(false); + } + }; + + return ( + +
void submit(event)}> +

+ Destination de {target.name}. +

+ {entries === null && !error ? ( + Chargement des dossiers… + ) : ( + + )} + {error ? {error} : null} +
+ + +
+
+
+ ); +}; + +export const ShareDialog = ({ + folder, + onClose, +}: { + folder: Folder; + onClose: () => void; +}) => { + const [permissions, setPermissions] = useState(null); + const [email, setEmail] = useState(""); + const [level, setLevel] = useState("read"); + const [expiresAt, setExpiresAt] = useState(""); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + const load = async () => { + try { + const { permissions: list } = await api.folderPermissions(folder.id); + setPermissions(list); + setError(null); + } catch (caught) { + setError(messageOf(caught, "Chargement des partages impossible.")); + setPermissions([]); + } + }; + + useEffect(() => { + void load(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [folder.id]); + + const grant = async (event: FormEvent) => { + event.preventDefault(); + setBusy(true); + setError(null); + try { + const iso = expiresAt ? new Date(expiresAt).toISOString() : null; + await api.grantPermission(folder.id, email, level, expiresAt ? iso : null); + setEmail(""); + setExpiresAt(""); + await load(); + } catch (caught) { + setError(messageOf(caught, "Partage impossible.")); + } finally { + setBusy(false); + } + }; + + const revoke = async (userId: string) => { + setError(null); + try { + await api.revokePermission(folder.id, userId); + await load(); + } catch (caught) { + setError(messageOf(caught, "Révocation impossible.")); + } + }; + + return ( + +
+
void grant(event)}> + setEmail(event.target.value)} + /> +
+ + setExpiresAt(event.target.value)} + /> +
+ {error ? {error} : null} +
+ +
+
+ +
+

+ Accès accordés +

+ {permissions === null ? ( + Chargement… + ) : permissions.length === 0 ? ( +

Aucun partage pour ce dossier.

+ ) : ( +
    + {permissions.map((permission) => ( +
  • + + + {permission.first_name} {permission.last_name} + + + {permission.email} · {LEVEL_LABEL[permission.level] ?? permission.level} + {permission.expires_at ? ` · jusqu'au ${formatDate(permission.expires_at)}` : ""} + + + +
  • + ))} +
+ )} +
+
+
+ ); +}; diff --git a/frontend/cloud/src/components/feedback.tsx b/frontend/cloud/src/components/feedback.tsx new file mode 100644 index 0000000..2398a9c --- /dev/null +++ b/frontend/cloud/src/components/feedback.tsx @@ -0,0 +1,136 @@ +import type { ReactNode } from "react"; +import { cn } from "@cohaise/ui"; +import { CloseIcon } from "./icons.js"; + +export const Modal = ({ + open, + title, + onClose, + children, +}: { + open: boolean; + title: string; + onClose: () => void; + children: React.ReactNode; +}) => { + if (!open) return null; + return ( +
+ + ); +}; + + +export const Alert = ({ + children, + tone = "error", + className, +}: { + children: ReactNode; + tone?: "error" | "success" | "info"; + className?: string; +}) => ( +

+ {children} +

+); + +export const PageHeader = ({ + title, + description, + actions, +}: { + title: string; + description?: string; + actions?: ReactNode; +}) => ( +
+
+

+ {title} +

+ {description ? ( +

{description}

+ ) : null} +
+ {actions ?
{actions}
: null} +
+); + +export const EmptyState = ({ + icon, + title, + description, + action, +}: { + icon?: ReactNode; + title: string; + description?: string; + action?: ReactNode; +}) => ( +
+ {icon ? {icon} : null} +

+ {title} +

+ {description ? ( +

{description}

+ ) : null} + {action} +
+); + +export const Badge = ({ + children, + tone = "neutral", +}: { + children: ReactNode; + tone?: "neutral" | "accent" | "warning" | "danger"; +}) => ( + + {children} + +); diff --git a/frontend/cloud/src/components/icons.tsx b/frontend/cloud/src/components/icons.tsx new file mode 100644 index 0000000..3c5e477 --- /dev/null +++ b/frontend/cloud/src/components/icons.tsx @@ -0,0 +1,160 @@ +import type { SVGProps } from "react"; + +type IconProps = SVGProps; + +const base = (props: IconProps) => ({ + viewBox: "0 0 24 24", + fill: "none", + stroke: "currentColor", + strokeWidth: 1.6, + strokeLinecap: "round" as const, + strokeLinejoin: "round" as const, + "aria-hidden": true, + ...props, +}); + +export const FolderIcon = (props: IconProps) => ( + + + +); + +export const FileIcon = (props: IconProps) => ( + + + + +); + +export const ImageIcon = (props: IconProps) => ( + + + + + +); + +export const UploadIcon = (props: IconProps) => ( + + + +); + +export const DownloadIcon = (props: IconProps) => ( + + + +); + +export const PlusIcon = (props: IconProps) => ( + + + +); + +export const TrashIcon = (props: IconProps) => ( + + + +); + +export const RestoreIcon = (props: IconProps) => ( + + + +); + +export const StarIcon = ({ filled, ...props }: IconProps & { filled?: boolean }) => ( + + + +); + +export const SearchIcon = (props: IconProps) => ( + + + + +); + +export const UsersIcon = (props: IconProps) => ( + + + + +); + +export const SettingsIcon = (props: IconProps) => ( + + + + +); + +export const LogoutIcon = (props: IconProps) => ( + + + +); + +export const ShieldIcon = (props: IconProps) => ( + + + + +); + +export const HardDriveIcon = (props: IconProps) => ( + + + + +); + +export const ActivityIcon = (props: IconProps) => ( + + + +); + +export const SearchNavIcon = (props: IconProps) => ( + + + + +); + +export const ShareIcon = (props: IconProps) => ( + + + + + + +); + +export const MenuIcon = (props: IconProps) => ( + + + +); + +export const CloseIcon = (props: IconProps) => ( + + + +); + +export const PenIcon = (props: IconProps) => ( + + + + +); + +export const MoveIcon = (props: IconProps) => ( + + + + +); diff --git a/frontend/cloud/src/lib/api.ts b/frontend/cloud/src/lib/api.ts new file mode 100644 index 0000000..dac0ecb --- /dev/null +++ b/frontend/cloud/src/lib/api.ts @@ -0,0 +1,370 @@ +export interface User { + id: string; + email: string; + first_name: string; + last_name: string; + role_slug: string; + role_name: string; + quota_bytes: number; + used_bytes: number; + max_file_bytes: number; + must_change_password: boolean; +} + +export interface Folder { + id: string; + parent_id: string | null; + name: string; + description: string | null; + owner_id: string | null; + access_type: string; + is_system: boolean; + created_at: string; + updated_at: string; +} + +export interface UploadedFile { + id: string; + folder_id: string | null; + name: string; + mime_type: string | null; + size_bytes: number; + checksum_sha256: string | null; + owner_id: string | null; + is_starred: boolean; + download_count: number; + created_at: string; + updated_at: string; +} + +export interface FolderPermission { + user_id: string; + email: string; + first_name: string; + last_name: string; + level: string; + expires_at: string | null; + created_at: string; +} + +export interface SessionInfo { + id: string; + ip_address: string | null; + user_agent: string | null; + created_at: string; + last_seen_at: string; + expires_at: string; + current: boolean; +} + +export interface TrashFolder { + id: string; + parent_id: string | null; + name: string; + description: string | null; + owner_id: string | null; + access_type: string; + created_at: string; + updated_at: string; + deleted_at: string; +} + +export interface TrashFile { + id: string; + folder_id: string | null; + name: string; + mime_type: string | null; + size_bytes: number; + owner_id: string | null; + created_at: string; + updated_at: string; + deleted_at: string; +} + +export interface MediaItem { + id: string; + folder_id: string | null; + name: string; + mime_type: string | null; + size_bytes: number; + owner_id: string | null; + is_starred: boolean; + kind: string | null; + width: number | null; + height: number | null; + created_at: string; + has_thumbnail: boolean; +} + +export interface AdminUser { + id: string; + email: string; + first_name: string; + last_name: string; + role_slug: string; + quota_bytes: number; + used_bytes: number; + max_file_bytes: number; + is_active: boolean; + must_change_password: boolean; + last_login_at: string | null; + created_at: string; +} + +export interface StorageLocation { + id: number; + name: string; + slug: string; + mount_path: string; + quota_bytes: number | null; + used_bytes: number; + is_active: boolean; + created_at: string; +} + +export interface AdminStats { + users: number; + folders: number; + files: number; + usedBytes: number; + trashFiles: number; + locations: { id: number; name: string; used_bytes: number; quota_bytes: number | null }[]; +} + +export interface AuditEntry { + id: number; + user_id: string | null; + user_email: string | null; + action: string; + resource: string; + resource_id: string | null; + details: string | null; + ip_address: string | null; + created_at: string; +} + +export class ApiError extends Error { + readonly status: number; + + constructor(status: number, message: string) { + super(message); + this.name = "ApiError"; + this.status = status; + } +} + +const BASE = "/api/cloud"; + +const messageOf = (body: unknown, fallback: string): string => + (body as { error?: { message?: string } } | null)?.error?.message ?? fallback; + +/** + * Un seul point d'entree HTTP. Le cookie de session est envoye + * automatiquement (same-origin), et toute erreur non-2xx devient une + * ApiError portant le message serveur, jamais un corps brut. + */ +const request = async (path: string, init?: RequestInit): Promise => { + let response: Response; + try { + response = await fetch(`${BASE}${path}`, { + credentials: "same-origin", + ...init, + headers: { + ...(init?.body ? { "content-type": "application/json" } : {}), + ...init?.headers, + }, + }); + } catch { + throw new ApiError(0, "Serveur injoignable. Verifiez votre connexion."); + } + + const body: unknown = await response.json().catch(() => null); + if (!response.ok) throw new ApiError(response.status, messageOf(body, "Une erreur est survenue.")); + return body as T; +}; + +const post = (path: string, payload?: unknown): Promise => + request(path, { + method: "POST", + ...(payload === undefined ? {} : { body: JSON.stringify(payload) }), + }); + +const patch = (path: string, payload: unknown): Promise => + request(path, { method: "PATCH", body: JSON.stringify(payload) }); + +const del = (path: string): Promise => request(path, { method: "DELETE" }); + +const query = (params: Record): string => { + const search = new URLSearchParams(); + for (const [key, value] of Object.entries(params)) { + if (value !== null && value !== undefined && value !== "") search.set(key, String(value)); + } + const suffix = search.toString(); + return suffix ? `?${suffix}` : ""; +}; + +/** Envoi d'un corps brut (fichier, image), hors JSON. */ +const putBinary = async (path: string, body: BodyInit, type: string): Promise => { + let response: Response; + try { + response = await fetch(`${BASE}${path}`, { + method: "PUT", + credentials: "same-origin", + headers: type ? { "content-type": type } : {}, + body, + }); + } catch { + throw new ApiError(0, "Serveur injoignable. Verifiez votre connexion."); + } + const parsed: unknown = await response.json().catch(() => null); + if (!response.ok) throw new ApiError(response.status, messageOf(parsed, "L'envoi a echoue.")); + return parsed as T; +}; + +export const api = { + // --- Session ----------------------------------------------------------- + me: () => request<{ user: User }>("/auth/me"), + login: (email: string, password: string) => + post<{ user: User }>("/auth/login", { email, password }), + logout: () => post<{ ok: boolean }>("/auth/logout"), + changePassword: (current: string, next: string) => + post<{ ok: boolean }>("/auth/change-password", { current, next }), + forgotPassword: (email: string) => post<{ ok: boolean }>("/account/forgot-password", { email }), + resetPassword: (token: string, password: string) => + post<{ ok: boolean }>("/account/reset-password", { token, password }), + requestEmailChange: (password: string, new_email: string) => + post<{ ok: boolean }>("/account/email-change", { password, new_email }), + confirmEmailChange: (token: string) => + post<{ ok: boolean; email: string }>("/account/email-change/confirm", { token }), + + // --- Compte ------------------------------------------------------------ + updateProfile: (first_name: string, last_name: string) => + patch<{ ok: boolean }>("/account/profile", { first_name, last_name }), + sessions: () => request<{ sessions: SessionInfo[] }>("/account/sessions"), + revokeSession: (id: string) => del<{ ok: boolean }>(`/account/sessions/${encodeURIComponent(id)}`), + revokeOtherSessions: () => del<{ ok: boolean }>("/account/sessions"), + avatarUrl: (userId: string) => `${BASE}/account/avatar/${encodeURIComponent(userId)}`, + uploadAvatar: (file: File) => putBinary<{ ok: boolean }>("/account/avatar", file, file.type), + deleteAvatar: () => del<{ ok: boolean }>("/account/avatar"), + + // --- Dossiers ---------------------------------------------------------- + folders: (parentId?: string | null) => + request<{ parentId: string | null; folders: Folder[] }>( + `/folders${query({ parentId })}`, + ), + createFolder: (name: string, parentId?: string | null, description?: string) => + post<{ folder: Folder }>("/folders", { name, parentId: parentId ?? null, description }), + updateFolder: (id: string, payload: { name?: string; description?: string | null }) => + patch<{ folder: Folder }>(`/folders/${encodeURIComponent(id)}`, payload), + moveFolder: (id: string, parentId: string | null) => + post<{ folder: Folder }>(`/folders/${encodeURIComponent(id)}/move`, { parentId }), + deleteFolder: (id: string) => del<{ ok: boolean }>(`/folders/${encodeURIComponent(id)}`), + folderPermissions: (id: string) => + request<{ permissions: FolderPermission[] }>( + `/folders/${encodeURIComponent(id)}/permissions`, + ), + grantPermission: (id: string, email: string, level: string, expiresAt: string | null) => + post<{ ok: boolean }>(`/folders/${encodeURIComponent(id)}/permissions`, { + email, + level, + expiresAt, + }), + revokePermission: (id: string, userId: string) => + del<{ ok: boolean }>( + `/folders/${encodeURIComponent(id)}/permissions/${encodeURIComponent(userId)}`, + ), + + // --- Fichiers ---------------------------------------------------------- + files: (folderId?: string | null) => + request<{ folderId: string | null; files: UploadedFile[] }>(`/files${query({ folderId })}`), + uploadFile: (file: File, folderId: string | null) => + putBinary<{ file: UploadedFile }>( + `/files${query({ name: file.name, folderId })}`, + file, + file.type, + ), + renameFile: (id: string, name: string) => + patch<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}`, { name }), + moveFile: (id: string, folderId: string | null) => + post<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}/move`, { folderId }), + starFile: (id: string) => + request<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}/star`, { method: "PUT" }), + deleteFile: (id: string) => del<{ ok: boolean }>(`/files/${encodeURIComponent(id)}`), + downloadUrl: (id: string) => `${BASE}/files/${encodeURIComponent(id)}/download`, + thumbnailUrl: (id: string) => `${BASE}/files/${encodeURIComponent(id)}/thumbnail`, + + // --- Corbeille, recherche, galerie ------------------------------------ + trash: () => + request<{ retentionDays: number; folders: TrashFolder[]; files: TrashFile[] }>("/trash"), + restoreFolder: (id: string) => + post<{ ok: boolean }>(`/trash/folders/${encodeURIComponent(id)}/restore`), + restoreFile: (id: string) => + post<{ ok: boolean }>(`/trash/files/${encodeURIComponent(id)}/restore`), + purgeFolder: (id: string) => del<{ ok: boolean }>(`/trash/folders/${encodeURIComponent(id)}`), + purgeFile: (id: string) => del<{ ok: boolean }>(`/trash/files/${encodeURIComponent(id)}`), + emptyTrash: () => del<{ ok: boolean }>("/trash"), + + search: (q: string) => + request<{ query: string; folders: Folder[]; files: UploadedFile[] }>(`/search${query({ q })}`), + gallery: (kind: string, limit = 60, offset = 0) => + request<{ kind: string | null; items: MediaItem[] }>( + `/media${query({ kind, limit, offset })}`, + ), + + // --- Administration ---------------------------------------------------- + adminStats: () => request("/admin/stats"), + adminUsers: (q?: string) => + request<{ users: AdminUser[] }>(`/admin/users${query({ q })}`), + adminCreateUser: (payload: { + email: string; + first_name: string; + last_name: string; + role_slug: string; + quota_bytes?: number | null; + max_file_bytes?: number | null; + }) => post<{ user: AdminUser; password: string }>("/admin/users", payload), + adminUpdateUser: ( + id: string, + payload: Partial<{ + first_name: string; + last_name: string; + role_slug: string; + quota_bytes: number; + max_file_bytes: number; + is_active: boolean; + }>, + ) => patch<{ user: AdminUser }>(`/admin/users/${encodeURIComponent(id)}`, payload), + adminDeleteUser: (id: string) => del<{ ok: boolean }>(`/admin/users/${encodeURIComponent(id)}`), + adminResetPassword: (id: string) => + post<{ password: string }>(`/admin/users/${encodeURIComponent(id)}/reset-password`), + adminStorageLocations: () => + request<{ locations: StorageLocation[] }>("/admin/storage-locations"), + adminCreateStorageLocation: (payload: { + name: string; + slug: string; + mount_path: string; + quota_bytes?: number | null; + }) => post<{ ok: boolean }>("/admin/storage-locations", payload), + adminUpdateStorageLocation: ( + id: number, + payload: { name?: string; quota_bytes?: number | null; is_active?: boolean }, + ) => patch<{ ok: boolean }>(`/admin/storage-locations/${id}`, payload), + adminAudit: (limit = 100, offset = 0, action?: string) => + request<{ entries: AuditEntry[] }>(`/admin/audit${query({ limit, offset, action })}`), +}; + +/** Octets en lecture humaine, sans precision inutile. */ +export const formatBytes = (bytes: number): string => { + if (bytes < 1024) return `${bytes} o`; + const units = ["Ko", "Mo", "Go", "To"]; + let value = bytes; + let index = -1; + do { + value /= 1024; + index += 1; + } while (value >= 1024 && index < units.length - 1); + return `${value.toLocaleString("fr-FR", { maximumFractionDigits: value < 10 ? 1 : 0 })} ${units[index]}`; +}; + +export const formatDate = (value: string | null): string => + value ? new Date(value).toLocaleString("fr-FR", { dateStyle: "medium", timeStyle: "short" }) : "—"; diff --git a/frontend/cloud/src/lib/session.tsx b/frontend/cloud/src/lib/session.tsx new file mode 100644 index 0000000..ba7740d --- /dev/null +++ b/frontend/cloud/src/lib/session.tsx @@ -0,0 +1,58 @@ +import { + createContext, + useCallback, + useContext, + useEffect, + useMemo, + useState, + type ReactNode, +} from "react"; +import { api, type User } from "./api.js"; + +interface SessionValue { + user: User | null; + loading: boolean; + refresh: () => Promise; + setUser: (user: User | null) => void; + logout: () => Promise; +} + +const SessionContext = createContext(null); + +export const SessionProvider = ({ children }: { children: ReactNode }) => { + const [user, setUser] = useState(null); + const [loading, setLoading] = useState(true); + + const refresh = useCallback(async () => { + try { + const { user: current } = await api.me(); + setUser(current); + } catch { + setUser(null); + } finally { + setLoading(false); + } + }, []); + + useEffect(() => { + void refresh(); + }, [refresh]); + + const logout = useCallback(async () => { + await api.logout().catch(() => undefined); + setUser(null); + }, []); + + const value = useMemo( + () => ({ user, loading, refresh, setUser, logout }), + [user, loading, refresh, logout], + ); + + return {children}; +}; + +export const useSession = (): SessionValue => { + const value = useContext(SessionContext); + if (!value) throw new Error("useSession doit etre utilise dans un SessionProvider."); + return value; +}; diff --git a/frontend/cloud/src/main.tsx b/frontend/cloud/src/main.tsx new file mode 100644 index 0000000..0ebf8f4 --- /dev/null +++ b/frontend/cloud/src/main.tsx @@ -0,0 +1,22 @@ +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import { BrowserRouter } from "react-router-dom"; +import { App } from "./App.js"; +import { SessionProvider } from "./lib/session.js"; +import "./styles/index.css"; + +const container = document.getElementById("root"); + +if (!container) { + throw new Error("Element racine introuvable"); +} + +createRoot(container).render( + + + + + + + , +); diff --git a/frontend/cloud/src/pages/Admin.tsx b/frontend/cloud/src/pages/Admin.tsx new file mode 100644 index 0000000..fcbb89f --- /dev/null +++ b/frontend/cloud/src/pages/Admin.tsx @@ -0,0 +1,753 @@ +import { useEffect, useRef, useState, type FormEvent } from "react"; +import { Button, Input, Spinner } from "@cohaise/ui"; +import { + ApiError, + api, + formatDate, + type AdminStats, + type AdminUser, + type AuditEntry, + type StorageLocation, +} from "../lib/api.js"; +import { Alert, Badge, EmptyState, Modal, PageHeader } from "../components/feedback.js"; +import { IconAction } from "../components/IconAction.js"; +import { + ActivityIcon, + HardDriveIcon, + PlusIcon, + TrashIcon, + UsersIcon, +} from "../components/icons.js"; + +const GB = 1024 ** 3; +const MB = 1024 ** 2; + +const messageOf = (caught: unknown, fallback: string): string => + caught instanceof ApiError ? caught.message : fallback; + +const toGb = (bytes: number): string => + (bytes / GB).toLocaleString("fr-FR", { maximumFractionDigits: 1 }); + +const StatCard = ({ label, value }: { label: string; value: string }) => ( +
+

+ {label} +

+

{value}

+
+); + +export const AdminUsers = () => { + const [users, setUsers] = useState(null); + const [stats, setStats] = useState(null); + const [q, setQ] = useState(""); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(null); + const [createOpen, setCreateOpen] = useState(false); + const [edit, setEdit] = useState(null); + const [credentials, setCredentials] = useState<{ email: string; password: string } | null>(null); + const termRef = useRef(""); + + const load = async (term: string) => { + termRef.current = term; + setError(null); + try { + const { users: list } = await api.adminUsers(term || undefined); + setUsers(list); + } catch (caught) { + setError(messageOf(caught, "Chargement impossible.")); + setUsers([]); + } + }; + + useEffect(() => { + void load(""); + api + .adminStats() + .then(setStats) + .catch(() => undefined); + }, []); + + const toggleActive = async (user: AdminUser) => { + setBusy(user.id); + setError(null); + try { + await api.adminUpdateUser(user.id, { is_active: !user.is_active }); + await load(termRef.current); + } catch (caught) { + setError(messageOf(caught, "Mise à jour impossible.")); + } finally { + setBusy(null); + } + }; + + const resetPassword = async (user: AdminUser) => { + setBusy(user.id); + setError(null); + try { + const { password } = await api.adminResetPassword(user.id); + setCredentials({ email: user.email, password }); + } catch (caught) { + setError(messageOf(caught, "Réinitialisation impossible.")); + } finally { + setBusy(null); + } + }; + + const removeUser = async (user: AdminUser) => { + if (!window.confirm(`Supprimer définitivement ${user.email} ?`)) return; + setBusy(user.id); + setError(null); + try { + await api.adminDeleteUser(user.id); + await load(termRef.current); + } catch (caught) { + setError(messageOf(caught, "Suppression impossible.")); + } finally { + setBusy(null); + } + }; + + return ( +
+ } + onClick={() => setCreateOpen(true)} + > + Nouveau membre + + } + /> + + {stats ? ( +
+ + + +
+ ) : null} + +
{ + event.preventDefault(); + void load(q); + }} + > +
+ setQ(event.target.value)} + /> +
+ +
+ + {error ? {error} : null} + + {users === null ? ( +
+ +
+ ) : users.length === 0 ? ( + } title="Aucun membre" /> + ) : ( +
    + {users.map((user) => ( +
  • + + + + {user.first_name} {user.last_name} + + {user.role_slug === "admin" ? Admin : null} + {!user.is_active ? Inactif : null} + {user.must_change_password ? À changer : null} + + + {user.email} · {toGb(user.used_bytes)} / {toGb(user.quota_bytes)} Go ·{" "} + {user.last_login_at + ? `vu le ${formatDate(user.last_login_at)}` + : "jamais connecté"} + + + +
    + + } + isLoading={busy === user.id} + onClick={() => void toggleActive(user)} + /> + } + isLoading={busy === user.id} + onClick={() => void resetPassword(user)} + /> + } + tone="danger" + isLoading={busy === user.id} + onClick={() => void removeUser(user)} + /> +
    +
  • + ))} +
+ )} + + {createOpen ? ( + setCreateOpen(false)} + onCreated={(email, password) => { + setCreateOpen(false); + setCredentials({ email, password }); + void load(termRef.current); + }} + /> + ) : null} + + {edit ? ( + setEdit(null)} + onSaved={() => { + setEdit(null); + void load(termRef.current); + }} + /> + ) : null} + + setCredentials(null)} /> +
+ ); +}; + +const CredentialsModal = ({ + credentials, + onClose, +}: { + credentials: { email: string; password: string } | null; + onClose: () => void; +}) => { + if (!credentials) return null; + return ( + +
+ + Transmettez ces informations par un canal sûr : le mot de passe ne sera plus affiché. + +
+
+
Adresse
+
{credentials.email}
+
+
+
Mot de passe
+
{credentials.password}
+
+
+
+ +
+
+
+ ); +}; + +const CreateUserDialog = ({ + onClose, + onCreated, +}: { + onClose: () => void; + onCreated: (email: string, password: string) => void; +}) => { + const [email, setEmail] = useState(""); + const [firstName, setFirstName] = useState(""); + const [lastName, setLastName] = useState(""); + const [role, setRole] = useState("user"); + const [quotaGb, setQuotaGb] = useState(""); + const [maxFileMb, setMaxFileMb] = useState(""); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + const submit = async (event: FormEvent) => { + event.preventDefault(); + setBusy(true); + setError(null); + try { + const { user, password } = await api.adminCreateUser({ + email: email.trim(), + first_name: firstName.trim(), + last_name: lastName.trim(), + role_slug: role, + quota_bytes: quotaGb ? Math.round(Number(quotaGb) * GB) : null, + max_file_bytes: maxFileMb ? Math.round(Number(maxFileMb) * MB) : null, + }); + onCreated(user.email, password); + } catch (caught) { + setError(messageOf(caught, "Création impossible.")); + } finally { + setBusy(false); + } + }; + + return ( + +
void submit(event)}> + setEmail(event.target.value)} + /> +
+ setFirstName(event.target.value)} + /> + setLastName(event.target.value)} + /> +
+ +
+ setQuotaGb(event.target.value)} + /> + setMaxFileMb(event.target.value)} + /> +
+ {error ? {error} : null} +
+ + +
+
+
+ ); +}; + +const EditUserDialog = ({ + user, + onClose, + onSaved, +}: { + user: AdminUser; + onClose: () => void; + onSaved: () => void; +}) => { + const [firstName, setFirstName] = useState(user.first_name); + const [lastName, setLastName] = useState(user.last_name); + const [role, setRole] = useState(user.role_slug); + const [quotaGb, setQuotaGb] = useState(String(Math.round(user.quota_bytes / GB))); + const [maxFileMb, setMaxFileMb] = useState(String(Math.round(user.max_file_bytes / MB))); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + const submit = async (event: FormEvent) => { + event.preventDefault(); + setBusy(true); + setError(null); + try { + await api.adminUpdateUser(user.id, { + first_name: firstName.trim(), + last_name: lastName.trim(), + role_slug: role, + quota_bytes: Math.round(Number(quotaGb) * GB), + max_file_bytes: Math.round(Number(maxFileMb) * MB), + }); + onSaved(); + } catch (caught) { + setError(messageOf(caught, "Enregistrement impossible.")); + } finally { + setBusy(false); + } + }; + + return ( + +
void submit(event)}> +
+ setFirstName(event.target.value)} + /> + setLastName(event.target.value)} + /> +
+ +
+ setQuotaGb(event.target.value)} + /> + setMaxFileMb(event.target.value)} + /> +
+ {error ? {error} : null} +
+ + +
+
+
+ ); +}; + +export const AdminStorage = () => { + const [locations, setLocations] = useState(null); + const [error, setError] = useState(null); + const [createOpen, setCreateOpen] = useState(false); + + const load = async () => { + setError(null); + try { + const { locations: list } = await api.adminStorageLocations(); + setLocations(list); + } catch (caught) { + setError(messageOf(caught, "Chargement impossible.")); + setLocations([]); + } + }; + + useEffect(() => { + void load(); + }, []); + + const toggle = async (location: StorageLocation) => { + setError(null); + try { + await api.adminUpdateStorageLocation(location.id, { is_active: !location.is_active }); + await load(); + } catch (caught) { + setError(messageOf(caught, "Mise à jour impossible.")); + } + }; + + return ( +
+ } + onClick={() => setCreateOpen(true)} + > + Nouvel emplacement + + } + /> + + {error ? {error} : null} + + {locations === null ? ( +
+ +
+ ) : locations.length === 0 ? ( + } title="Aucun emplacement" /> + ) : ( +
    + {locations.map((location) => ( +
  • + + + + {location.name} + + {!location.is_active ? Inactif : null} + + + {location.slug} · {location.mount_path} ·{" "} + {location.quota_bytes + ? `${toGb(location.used_bytes)} / ${toGb(location.quota_bytes)} Go` + : `${toGb(location.used_bytes)} Go utilisés`} + + + +
  • + ))} +
+ )} + + {createOpen ? ( + setCreateOpen(false)} + onCreated={() => { + setCreateOpen(false); + void load(); + }} + /> + ) : null} +
+ ); +}; + +const CreateLocationDialog = ({ + onClose, + onCreated, +}: { + onClose: () => void; + onCreated: () => void; +}) => { + const [name, setName] = useState(""); + const [slug, setSlug] = useState(""); + const [mountPath, setMountPath] = useState(""); + const [quotaGb, setQuotaGb] = useState(""); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + const submit = async (event: FormEvent) => { + event.preventDefault(); + setBusy(true); + setError(null); + try { + await api.adminCreateStorageLocation({ + name: name.trim(), + slug: slug.trim(), + mount_path: mountPath.trim(), + quota_bytes: quotaGb ? Math.round(Number(quotaGb) * GB) : null, + }); + onCreated(); + } catch (caught) { + setError(messageOf(caught, "Création impossible.")); + } finally { + setBusy(false); + } + }; + + return ( + +
void submit(event)}> + setName(event.target.value)} + /> + setSlug(event.target.value)} + /> + setMountPath(event.target.value)} + /> + setQuotaGb(event.target.value)} + /> + {error ? {error} : null} +
+ + +
+
+
+ ); +}; + +export const AdminAudit = () => { + const [entries, setEntries] = useState(null); + const [action, setAction] = useState(""); + const [error, setError] = useState(null); + const [loadingMore, setLoadingMore] = useState(false); + + const load = async (term: string) => { + setError(null); + try { + const { entries: list } = await api.adminAudit(100, 0, term || undefined); + setEntries(list); + } catch (caught) { + setError(messageOf(caught, "Chargement impossible.")); + setEntries([]); + } + }; + + useEffect(() => { + void load(""); + }, []); + + const loadMore = async () => { + if (!entries) return; + setLoadingMore(true); + setError(null); + try { + const { entries: more } = await api.adminAudit(100, entries.length, action || undefined); + setEntries((previous) => [...(previous ?? []), ...more]); + } catch (caught) { + setError(messageOf(caught, "Chargement impossible.")); + } finally { + setLoadingMore(false); + } + }; + + return ( +
+ + +
{ + event.preventDefault(); + void load(action); + }} + > +
+ setAction(event.target.value)} + /> +
+ +
+ + {error ? {error} : null} + + {entries === null ? ( +
+ +
+ ) : entries.length === 0 ? ( + } title="Aucune entrée" /> + ) : ( + <> +
    + {entries.map((entry) => ( +
  • + + + {entry.action} + + {entry.resource} + {entry.resource_id ? ` · ${entry.resource_id}` : ""} + + + + {entry.user_email ?? "système"} · {formatDate(entry.created_at)} + {entry.ip_address ? ` · ${entry.ip_address}` : ""} + + +
  • + ))} +
+ {entries.length >= 100 ? ( +
+ +
+ ) : null} + + )} +
+ ); +}; diff --git a/frontend/cloud/src/pages/Browser.tsx b/frontend/cloud/src/pages/Browser.tsx new file mode 100644 index 0000000..c160522 --- /dev/null +++ b/frontend/cloud/src/pages/Browser.tsx @@ -0,0 +1,449 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import { Button, Card, Spinner } from "@cohaise/ui"; +import { + ApiError, + api, + formatBytes, + type Folder, + type UploadedFile, +} from "../lib/api.js"; +import { useSession } from "../lib/session.js"; +import { Alert, Badge, EmptyState, PageHeader } from "../components/feedback.js"; +import { IconAction } from "../components/IconAction.js"; +import { + CreateFolderDialog, + MoveDialog, + RenameDialog, + ShareDialog, +} from "../components/dialogs.js"; +import { + DownloadIcon, + FileIcon, + FolderIcon, + MoveIcon, + PenIcon, + PlusIcon, + ShareIcon, + StarIcon, + TrashIcon, + UploadIcon, +} from "../components/icons.js"; + +interface Crumb { + id: string | null; + name: string; +} + +type Target = { type: "folder" | "file"; id: string; name: string }; + +type Dialog = + | { kind: "create" } + | { kind: "rename"; target: Target } + | { kind: "move"; target: Target } + | { kind: "share"; folder: Folder } + | null; + +const isImage = (file: UploadedFile): boolean => + (file.mime_type ?? "").toLowerCase().startsWith("image/"); + +export const Browser = () => { + const { user, refresh } = useSession(); + const [path, setPath] = useState([{ id: null, name: "Racine" }]); + const [folders, setFolders] = useState([]); + const [files, setFiles] = useState([]); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [uploading, setUploading] = useState(false); + const [removing, setRemoving] = useState(null); + const [dialog, setDialog] = useState(null); + const fileInputRef = useRef(null); + + const current = path[path.length - 1] ?? { id: null, name: "Racine" }; + + const load = useCallback(async (parentId: string | null) => { + setLoading(true); + setError(null); + try { + const [folderResult, fileResult] = await Promise.all([ + api.folders(parentId), + api.files(parentId), + ]); + setFolders(folderResult.folders); + setFiles(fileResult.files); + } catch (caught) { + setError(caught instanceof ApiError ? caught.message : "Chargement impossible."); + setFolders([]); + setFiles([]); + } finally { + setLoading(false); + } + }, []); + + useEffect(() => { + void load(current.id); + }, [current.id, load]); + + const reload = useCallback(() => load(current.id), [current.id, load]); + + const open = (folder: Folder) => { + setPath((previous) => [...previous, { id: folder.id, name: folder.name }]); + }; + + const goTo = (index: number) => setPath((previous) => previous.slice(0, index + 1)); + + const upload = async (selected: FileList | null) => { + if (!selected || selected.length === 0) return; + setUploading(true); + setError(null); + try { + for (const file of Array.from(selected)) { + await api.uploadFile(file, current.id); + } + void refresh(); + await reload(); + } catch (caught) { + setError(caught instanceof ApiError ? caught.message : "Envoi impossible."); + } finally { + setUploading(false); + if (fileInputRef.current) fileInputRef.current.value = ""; + } + }; + + const removeTarget = async (target: Target) => { + const label = target.type === "folder" ? "ce dossier" : "ce fichier"; + if (!window.confirm(`Placer ${label} dans la corbeille ?`)) return; + setRemoving(target.id); + setError(null); + try { + if (target.type === "folder") { + await api.deleteFolder(target.id); + } else { + await api.deleteFile(target.id); + void refresh(); + } + await reload(); + } catch (caught) { + setError(caught instanceof ApiError ? caught.message : "Suppression impossible."); + } finally { + setRemoving(null); + } + }; + + const toggleStar = async (file: UploadedFile) => { + setError(null); + try { + const { file: updated } = await api.starFile(file.id); + setFiles((previous) => previous.map((item) => (item.id === updated.id ? updated : item))); + } catch (caught) { + setError(caught instanceof ApiError ? caught.message : "Action impossible."); + } + }; + + const canWrite = user?.role_slug === "admin" || user?.role_slug === "user"; + const empty = folders.length === 0 && files.length === 0; + const quotaPercent = + user && user.quota_bytes > 0 + ? Math.min(100, Math.round((user.used_bytes / user.quota_bytes) * 100)) + : 0; + + return ( +
+ + + + + +
+
+
+ Espace utilisé + + {formatBytes(user?.used_bytes ?? 0)} sur {formatBytes(user?.quota_bytes ?? 0)} + +
+
+
+
+
+ + {canWrite ? ( +
+ void upload(event.target.files)} + /> + + +
+ ) : null} +
+ + + {error ? {error} : null} + + {loading ? ( +
+ +
+ ) : empty ? ( + } + title="Emplacement vide" + description="Créez un sous-dossier ou envoyez un fichier pour commencer." + /> + ) : ( +
+ {folders.length > 0 ? ( +
+

+ Dossiers +

+
    + {folders.map((folder) => ( +
  • + + {canWrite ? ( +
    + } + onClick={() => setDialog({ kind: "share", folder })} + /> + } + onClick={() => + setDialog({ + kind: "rename", + target: { type: "folder", id: folder.id, name: folder.name }, + }) + } + /> + } + onClick={() => + setDialog({ + kind: "move", + target: { type: "folder", id: folder.id, name: folder.name }, + }) + } + /> + } + isLoading={removing === folder.id} + tone="danger" + onClick={() => + void removeTarget({ type: "folder", id: folder.id, name: folder.name }) + } + /> +
    + ) : null} +
  • + ))} +
+
+ ) : null} + + {files.length > 0 ? ( +
+

+ Fichiers +

+
    + {files.map((file) => ( +
  • + + {isImage(file) ? ( + + ) : ( + + )} + + + + {file.name} + + + {formatBytes(file.size_bytes)} ·{" "} + {new Date(file.created_at).toLocaleDateString("fr-FR")} + + + + + } + onClick={() => void toggleStar(file)} + /> + + + + Télécharger + + + {canWrite ? ( + <> + } + onClick={() => + setDialog({ + kind: "rename", + target: { type: "file", id: file.id, name: file.name }, + }) + } + /> + } + onClick={() => + setDialog({ + kind: "move", + target: { type: "file", id: file.id, name: file.name }, + }) + } + /> + } + isLoading={removing === file.id} + tone="danger" + onClick={() => + void removeTarget({ type: "file", id: file.id, name: file.name }) + } + /> + + ) : null} +
  • + ))} +
+
+ ) : null} +
+ )} + + {dialog?.kind === "create" ? ( + setDialog(null)} + onCreated={() => { + setDialog(null); + void reload(); + }} + /> + ) : null} + + {dialog?.kind === "rename" ? ( + setDialog(null)} + onDone={() => { + setDialog(null); + void reload(); + }} + /> + ) : null} + + {dialog?.kind === "move" ? ( + setDialog(null)} + onDone={() => { + setDialog(null); + void reload(); + }} + /> + ) : null} + + {dialog?.kind === "share" ? ( + setDialog(null)} /> + ) : null} +
+ ); +}; diff --git a/frontend/cloud/src/pages/ChangePassword.tsx b/frontend/cloud/src/pages/ChangePassword.tsx new file mode 100644 index 0000000..6309895 --- /dev/null +++ b/frontend/cloud/src/pages/ChangePassword.tsx @@ -0,0 +1,108 @@ +import { useState, type FormEvent } from "react"; +import { useNavigate } from "react-router-dom"; +import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input } from "@cohaise/ui"; +import { Alert } from "../components/feedback.js"; +import { ApiError, api } from "../lib/api.js"; +import { useSession } from "../lib/session.js"; + +export const ChangePassword = () => { + const { user, refresh, logout } = useSession(); + const navigate = useNavigate(); + const [current, setCurrent] = useState(""); + const [next, setNext] = useState(""); + const [confirm, setConfirm] = useState(""); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + const submit = async (event: FormEvent) => { + event.preventDefault(); + if (next !== confirm) { + setError("Les deux mots de passe ne correspondent pas."); + return; + } + setBusy(true); + setError(null); + try { + await api.changePassword(current, next); + await refresh(); + navigate("/files", { replace: true }); + } catch (caught) { + setError(caught instanceof ApiError ? caught.message : "Changement impossible."); + } finally { + setBusy(false); + } + }; + + return ( +
+
+
+

+ CoHaiSe +

+

+ Nouveau mot de passe +

+

+ Bienvenue {user?.first_name ?? ""}. Ce mot de passe a été défini par un + administrateur : choisissez le vôtre. +

+
+ + + + Changement requis + + Les autres sessions ouvertes sur ce compte seront fermées. + + + +
void submit(event)}> + setCurrent(event.target.value)} + /> + setNext(event.target.value)} + /> + setConfirm(event.target.value)} + /> + {error ? {error} : null} + + +
+
+
+
+
+ ); +}; diff --git a/frontend/cloud/src/pages/ConfirmEmail.tsx b/frontend/cloud/src/pages/ConfirmEmail.tsx new file mode 100644 index 0000000..ac58456 --- /dev/null +++ b/frontend/cloud/src/pages/ConfirmEmail.tsx @@ -0,0 +1,81 @@ +import { useEffect, useRef, useState } from "react"; +import { Link, useSearchParams } from "react-router-dom"; +import { Button, Card, CardContent, CardHeader, CardTitle, Spinner } from "@cohaise/ui"; +import { Alert } from "../components/feedback.js"; +import { ApiError, api } from "../lib/api.js"; +import { useSession } from "../lib/session.js"; + +export const ConfirmEmail = () => { + const [params] = useSearchParams(); + const token = params.get("token") ?? ""; + const { refresh } = useSession(); + const [state, setState] = useState<"loading" | "success" | "error">("loading"); + const [error, setError] = useState(null); + const started = useRef(false); + + useEffect(() => { + if (started.current) return; + started.current = true; + if (!token) { + setState("error"); + setError("Ce lien est incomplet ou invalide."); + return; + } + api + .confirmEmailChange(token) + .then(() => { + setState("success"); + void refresh(); + }) + .catch((caught: unknown) => { + setState("error"); + setError(caught instanceof ApiError ? caught.message : "Confirmation impossible."); + }); + }, [token, refresh]); + + return ( +
+
+
+

+ CoHaiSe +

+

+ Changement d'adresse +

+
+ + + + Confirmation + + + {state === "loading" ? ( +
+ +
+ ) : state === "success" ? ( + <> + Votre adresse e-mail a été mise à jour. + + + + + ) : ( + <> + {error} + + + + + )} +
+
+
+
+ ); +}; diff --git a/frontend/cloud/src/pages/ForgotPassword.tsx b/frontend/cloud/src/pages/ForgotPassword.tsx new file mode 100644 index 0000000..6b93e75 --- /dev/null +++ b/frontend/cloud/src/pages/ForgotPassword.tsx @@ -0,0 +1,91 @@ +import { useState, type FormEvent } from "react"; +import { Link } from "react-router-dom"; +import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input } from "@cohaise/ui"; +import { Alert } from "../components/feedback.js"; +import { ApiError, api } from "../lib/api.js"; + +export const ForgotPassword = () => { + const [email, setEmail] = useState(""); + const [sent, setSent] = useState(false); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + const submit = async (event: FormEvent) => { + event.preventDefault(); + setBusy(true); + setError(null); + try { + await api.forgotPassword(email); + setSent(true); + } catch (caught) { + setError(caught instanceof ApiError ? caught.message : "Demande impossible."); + } finally { + setBusy(false); + } + }; + + return ( +
+
+
+

+ CoHaiSe +

+

+ Mot de passe oublié +

+
+ + + + Réinitialisation + + Nous vous enverrons un lien valable une heure. + + + + {sent ? ( +
+ + Si cette adresse correspond à un compte, un message contenant le lien de + réinitialisation vient d'être envoyé. + + + Retour à la connexion + +
+ ) : ( +
void submit(event)} + > + setEmail(event.target.value)} + /> + {error ? {error} : null} + + + Retour à la connexion + +
+ )} +
+
+
+
+ ); +}; diff --git a/frontend/cloud/src/pages/Gallery.tsx b/frontend/cloud/src/pages/Gallery.tsx new file mode 100644 index 0000000..e19ab86 --- /dev/null +++ b/frontend/cloud/src/pages/Gallery.tsx @@ -0,0 +1,142 @@ +import { useCallback, useEffect, useState } from "react"; +import { Button, Spinner, cn } from "@cohaise/ui"; +import { ApiError, api, formatBytes, type MediaItem } from "../lib/api.js"; +import { Alert, EmptyState, PageHeader } from "../components/feedback.js"; +import { FileIcon, ImageIcon } from "../components/icons.js"; + +const KINDS = [ + { value: "", label: "Tout" }, + { value: "image", label: "Images" }, + { value: "video", label: "Vidéos" }, + { value: "audio", label: "Audio" }, + { value: "document", label: "Documents" }, + { value: "archive", label: "Archives" }, + { value: "other", label: "Autres" }, +] as const; + +const PAGE = 60; + +export const Gallery = () => { + const [kind, setKind] = useState("image"); + const [items, setItems] = useState([]); + const [loading, setLoading] = useState(true); + const [loadingMore, setLoadingMore] = useState(false); + const [error, setError] = useState(null); + + useEffect(() => { + setLoading(true); + void api + .gallery(kind, PAGE, 0) + .then(({ items: first }) => { + setItems(first); + setError(null); + }) + .catch((caught: unknown) => { + setError(caught instanceof ApiError ? caught.message : "Chargement impossible."); + setItems([]); + }) + .finally(() => setLoading(false)); + }, [kind]); + + const loadMore = useCallback(async () => { + setLoadingMore(true); + setError(null); + try { + const { items: more } = await api.gallery(kind, PAGE, items.length); + setItems((previous) => [...previous, ...more]); + } catch (caught) { + setError(caught instanceof ApiError ? caught.message : "Chargement impossible."); + } finally { + setLoadingMore(false); + } + }, [kind, items.length]); + + return ( +
+ + +
+ {KINDS.map((option) => ( + + ))} +
+ + {error ? {error} : null} + + {loading ? ( +
+ +
+ ) : items.length === 0 ? ( + } + title="Aucun média" + description="Rien à afficher pour ce filtre." + /> + ) : ( + <> + + + {items.length >= PAGE ? ( +
+ +
+ ) : null} + + )} +
+ ); +}; diff --git a/frontend/cloud/src/pages/Login.tsx b/frontend/cloud/src/pages/Login.tsx new file mode 100644 index 0000000..38f630f --- /dev/null +++ b/frontend/cloud/src/pages/Login.tsx @@ -0,0 +1,91 @@ +import { useState, type FormEvent } from "react"; +import { Link, Navigate, useNavigate } from "react-router-dom"; +import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input } from "@cohaise/ui"; +import { ApiError, api } from "../lib/api.js"; +import { useSession } from "../lib/session.js"; + +export const Login = () => { + const { user, setUser } = useSession(); + const navigate = useNavigate(); + const [email, setEmail] = useState(""); + const [password, setPassword] = useState(""); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + if (user) return ; + + const submit = async (event: FormEvent) => { + event.preventDefault(); + setBusy(true); + setError(null); + try { + const { user: current } = await api.login(email, password); + setUser(current); + navigate(current.must_change_password ? "/change-password" : "/files", { replace: true }); + } catch (caught) { + setError(caught instanceof ApiError ? caught.message : "Connexion impossible."); + } finally { + setBusy(false); + } + }; + + return ( +
+
+
+

+ CoHaiSe +

+

+ Cloud +

+

+ Connectez-vous pour accéder à vos fichiers. +

+
+ + + + Connexion + Votre session reste ouverte 14 jours. + + +
void submit(event)}> + setEmail(event.target.value)} + /> + setPassword(event.target.value)} + {...(error ? { error } : {})} + /> + + +
+
+
+ +

+ + Mot de passe oublié ? + +

+
+
+ ); +}; diff --git a/frontend/cloud/src/pages/Profile.tsx b/frontend/cloud/src/pages/Profile.tsx new file mode 100644 index 0000000..76fab6d --- /dev/null +++ b/frontend/cloud/src/pages/Profile.tsx @@ -0,0 +1,316 @@ +import { useEffect, useRef, useState, type FormEvent } from "react"; +import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input, Spinner } from "@cohaise/ui"; +import { ApiError, api, formatDate, type SessionInfo } from "../lib/api.js"; +import { useSession } from "../lib/session.js"; +import { Alert, Badge, PageHeader } from "../components/feedback.js"; +import { TrashIcon } from "../components/icons.js"; + +export const Profile = () => { + const { user, refresh } = useSession(); + + const [firstName, setFirstName] = useState(user?.first_name ?? ""); + const [lastName, setLastName] = useState(user?.last_name ?? ""); + const [profileMessage, setProfileMessage] = useState(null); + const [profileError, setProfileError] = useState(null); + const [savingProfile, setSavingProfile] = useState(false); + + const [avatarNonce, setAvatarNonce] = useState(0); + const [avatarError, setAvatarError] = useState(null); + const avatarInput = useRef(null); + + const [password, setPassword] = useState(""); + const [newEmail, setNewEmail] = useState(""); + const [emailMessage, setEmailMessage] = useState(null); + const [emailError, setEmailError] = useState(null); + const [sendingEmail, setSendingEmail] = useState(false); + + const [sessions, setSessions] = useState(null); + const [sessionsError, setSessionsError] = useState(null); + const [revoking, setRevoking] = useState(null); + + useEffect(() => { + if (user) { + setFirstName((current) => (current === "" ? user.first_name : current)); + setLastName((current) => (current === "" ? user.last_name : current)); + } + }, [user]); + + const loadSessions = async () => { + setSessionsError(null); + try { + const { sessions: list } = await api.sessions(); + setSessions(list); + } catch (caught) { + setSessionsError(caught instanceof ApiError ? caught.message : "Chargement impossible."); + setSessions([]); + } + }; + + useEffect(() => { + void loadSessions(); + }, []); + + const saveProfile = async (event: FormEvent) => { + event.preventDefault(); + setSavingProfile(true); + setProfileError(null); + setProfileMessage(null); + try { + await api.updateProfile(firstName.trim(), lastName.trim()); + await refresh(); + setProfileMessage("Informations enregistrées."); + } catch (caught) { + setProfileError(caught instanceof ApiError ? caught.message : "Enregistrement impossible."); + } finally { + setSavingProfile(false); + } + }; + + const requestEmail = async (event: FormEvent) => { + event.preventDefault(); + setSendingEmail(true); + setEmailError(null); + setEmailMessage(null); + try { + await api.requestEmailChange(password, newEmail.trim()); + setPassword(""); + setNewEmail(""); + setEmailMessage("Un e-mail de confirmation a été envoyé à la nouvelle adresse."); + } catch (caught) { + setEmailError(caught instanceof ApiError ? caught.message : "Demande impossible."); + } finally { + setSendingEmail(false); + } + }; + + const changeAvatar = async (file: File | undefined) => { + if (!file) return; + setAvatarError(null); + try { + await api.uploadAvatar(file); + setAvatarNonce((value) => value + 1); + } catch (caught) { + setAvatarError(caught instanceof ApiError ? caught.message : "Envoi impossible."); + } finally { + if (avatarInput.current) avatarInput.current.value = ""; + } + }; + + const removeAvatar = async () => { + setAvatarError(null); + try { + await api.deleteAvatar(); + setAvatarNonce((value) => value + 1); + } catch (caught) { + setAvatarError(caught instanceof ApiError ? caught.message : "Suppression impossible."); + } + }; + + const revokeSession = async (session: SessionInfo) => { + if (session.current && !window.confirm("Fermer la session en cours ?")) return; + setRevoking(session.id); + setSessionsError(null); + try { + await api.revokeSession(session.id); + if (session.current) { + await refresh(); + return; + } + setSessions((previous) => (previous ?? []).filter((item) => item.id !== session.id)); + } catch (caught) { + setSessionsError(caught instanceof ApiError ? caught.message : "Révocation impossible."); + } finally { + setRevoking(null); + } + }; + + const revokeOthers = async () => { + setSessionsError(null); + try { + await api.revokeOtherSessions(); + setSessions((previous) => (previous ?? []).filter((item) => item.current)); + } catch (caught) { + setSessionsError(caught instanceof ApiError ? caught.message : "Révocation impossible."); + } + }; + + if (!user) { + return ( +
+ +
+ ); + } + + return ( +
+ + + + + Identité + Informations affichées dans l'interface. + + +
void saveProfile(event)}> +
+ setFirstName(event.target.value)} + /> + setLastName(event.target.value)} + /> +
+ {profileError ? {profileError} : null} + {profileMessage ? {profileMessage} : null} +
+ +
+
+
+
+ + + + Photo de profil + Image carrée, format PNG ou JPEG. + + +
+ + { + event.currentTarget.style.display = "none"; + }} + /> + +
+ void changeAvatar(event.target.files?.[0])} + /> +
+ + +
+

+ Si aucune image n'est définie, vos initiales sont affichées. +

+
+
+ {avatarError ? {avatarError} : null} +
+
+ + + + Adresse e-mail + Adresse actuelle : {user.email} + + +
void requestEmail(event)}> +
+ setNewEmail(event.target.value)} + /> + setPassword(event.target.value)} + /> +
+ {emailError ? {emailError} : null} + {emailMessage ? {emailMessage} : null} +
+ +
+
+
+
+ + + + Sessions ouvertes + Appareils actuellement connectés à votre compte. + + + {sessionsError ? {sessionsError} : null} + {sessions === null ? ( +
+ +
+ ) : sessions.length === 0 ? ( +

Aucune session active.

+ ) : ( +
    + {sessions.map((session) => ( +
  • + + + + {session.user_agent ? session.user_agent.slice(0, 60) : "Appareil inconnu"} + + {session.current ? Cette session : null} + + + {session.ip_address ?? "IP inconnue"} · vue le {formatDate(session.last_seen_at)} + + + +
  • + ))} +
+ )} +
+ +
+
+
+
+ ); +}; diff --git a/frontend/cloud/src/pages/ResetPassword.tsx b/frontend/cloud/src/pages/ResetPassword.tsx new file mode 100644 index 0000000..fe48059 --- /dev/null +++ b/frontend/cloud/src/pages/ResetPassword.tsx @@ -0,0 +1,106 @@ +import { useState, type FormEvent } from "react"; +import { Link, useSearchParams } from "react-router-dom"; +import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input } from "@cohaise/ui"; +import { Alert } from "../components/feedback.js"; +import { ApiError, api } from "../lib/api.js"; + +export const ResetPassword = () => { + const [params] = useSearchParams(); + const token = params.get("token") ?? ""; + const [password, setPassword] = useState(""); + const [confirm, setConfirm] = useState(""); + const [error, setError] = useState(null); + const [done, setDone] = useState(false); + const [busy, setBusy] = useState(false); + + const submit = async (event: FormEvent) => { + event.preventDefault(); + if (password !== confirm) { + setError("Les deux mots de passe ne correspondent pas."); + return; + } + setBusy(true); + setError(null); + try { + await api.resetPassword(token, password); + setDone(true); + } catch (caught) { + setError(caught instanceof ApiError ? caught.message : "Réinitialisation impossible."); + } finally { + setBusy(false); + } + }; + + return ( +
+
+
+

+ CoHaiSe +

+

+ Nouveau mot de passe +

+
+ + + + Réinitialisation + Choisissez un mot de passe robuste. + + + {!token ? ( +
+ Ce lien est incomplet ou invalide. + + Demander un nouveau lien + +
+ ) : done ? ( +
+ + Votre mot de passe a été réinitialisé. Vous pouvez vous connecter. + + + + +
+ ) : ( +
void submit(event)}> + setPassword(event.target.value)} + /> + setConfirm(event.target.value)} + /> + {error ? {error} : null} + +
+ )} +
+
+
+
+ ); +}; diff --git a/frontend/cloud/src/pages/Search.tsx b/frontend/cloud/src/pages/Search.tsx new file mode 100644 index 0000000..68281dc --- /dev/null +++ b/frontend/cloud/src/pages/Search.tsx @@ -0,0 +1,138 @@ +import { useState, type FormEvent } from "react"; +import { Button, Input, Spinner } from "@cohaise/ui"; +import { ApiError, api, formatBytes, type Folder, type UploadedFile } from "../lib/api.js"; +import { Alert, EmptyState, PageHeader } from "../components/feedback.js"; +import { DownloadIcon, FileIcon, FolderIcon, SearchIcon } from "../components/icons.js"; + +interface Results { + folders: Folder[]; + files: UploadedFile[]; +} + +export const Search = () => { + const [q, setQ] = useState(""); + const [results, setResults] = useState(null); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(null); + + const submit = async (event: FormEvent) => { + event.preventDefault(); + const query = q.trim(); + if (query.length < 2) { + setError("Saisissez au moins deux caractères."); + return; + } + setLoading(true); + setError(null); + try { + const { folders, files } = await api.search(query); + setResults({ folders, files }); + } catch (caught) { + setError(caught instanceof ApiError ? caught.message : "Recherche impossible."); + setResults(null); + } finally { + setLoading(false); + } + }; + + const total = results ? results.folders.length + results.files.length : 0; + + return ( +
+ + +
void submit(event)}> +
+ setQ(event.target.value)} + /> +
+ +
+ + {error ? {error} : null} + + {loading ? ( +
+ +
+ ) : results === null ? null : total === 0 ? ( + } + title="Aucun résultat" + description={`Rien ne correspond à « ${q.trim()} ».`} + /> + ) : ( +
+ {results.folders.length > 0 ? ( +
+

+ Dossiers +

+
    + {results.folders.map((folder) => ( +
  • + + + + + {folder.name} + +
  • + ))} +
+
+ ) : null} + + {results.files.length > 0 ? ( +
+

+ Fichiers +

+
    + {results.files.map((file) => ( +
  • + + + + + + {file.name} + + + {formatBytes(file.size_bytes)} + + + + + +
  • + ))} +
+
+ ) : null} +
+ )} +
+ ); +}; diff --git a/frontend/cloud/src/pages/Trash.tsx b/frontend/cloud/src/pages/Trash.tsx new file mode 100644 index 0000000..29d7c42 --- /dev/null +++ b/frontend/cloud/src/pages/Trash.tsx @@ -0,0 +1,185 @@ +import { useCallback, useEffect, useState } from "react"; +import { Button, Spinner } from "@cohaise/ui"; +import { + ApiError, + api, + formatBytes, + formatDate, + type TrashFile, + type TrashFolder, +} from "../lib/api.js"; +import { Alert, EmptyState, PageHeader } from "../components/feedback.js"; +import { IconAction } from "../components/IconAction.js"; +import { FileIcon, FolderIcon, RestoreIcon, TrashIcon } from "../components/icons.js"; + +interface TrashData { + retentionDays: number; + folders: TrashFolder[]; + files: TrashFile[]; +} + +export const Trash = () => { + const [data, setData] = useState(null); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(null); + + const load = useCallback(async () => { + setLoading(true); + setError(null); + try { + setData(await api.trash()); + } catch (caught) { + setError(caught instanceof ApiError ? caught.message : "Chargement impossible."); + setData(null); + } finally { + setLoading(false); + } + }, []); + + useEffect(() => { + void load(); + }, [load]); + + const run = async (key: string, action: () => Promise) => { + setBusy(key); + setError(null); + try { + await action(); + await load(); + } catch (caught) { + setError(caught instanceof ApiError ? caught.message : "Action impossible."); + } finally { + setBusy(null); + } + }; + + const emptyTrash = () => { + if (!window.confirm("Vider définitivement la corbeille ?")) return; + void run("empty", () => api.emptyTrash()); + }; + + const empty = data !== null && data.folders.length === 0 && data.files.length === 0; + + return ( +
+ + Vider la corbeille + + ) : undefined + } + /> + + {error ? {error} : null} + + {loading ? ( +
+ +
+ ) : empty ? ( + } + title="Corbeille vide" + description="Aucun élément supprimé pour le moment." + /> + ) : data ? ( +
+ {data.folders.length > 0 ? ( +
+

+ Dossiers +

+
    + {data.folders.map((folder) => ( +
  • + + + + + + {folder.name} + + + Supprimé le {formatDate(folder.deleted_at)} + + + } + isLoading={busy === `restore-${folder.id}`} + onClick={() => + void run(`restore-${folder.id}`, () => api.restoreFolder(folder.id)) + } + /> + } + tone="danger" + isLoading={busy === `purge-${folder.id}`} + onClick={() => { + if (window.confirm(`Supprimer définitivement « ${folder.name} » ?`)) { + void run(`purge-${folder.id}`, () => api.purgeFolder(folder.id)); + } + }} + /> +
  • + ))} +
+
+ ) : null} + + {data.files.length > 0 ? ( +
+

+ Fichiers +

+
    + {data.files.map((file) => ( +
  • + + + + + + {file.name} + + + {formatBytes(file.size_bytes)} · supprimé le {formatDate(file.deleted_at)} + + + } + isLoading={busy === `restore-${file.id}`} + onClick={() => + void run(`restore-${file.id}`, () => api.restoreFile(file.id)) + } + /> + } + isLoading={busy === `purge-${file.id}`} + tone="danger" + onClick={() => + void run(`purge-${file.id}`, () => api.purgeFile(file.id)) + } + /> +
  • + ))} +
+
+ ) : null} +
+ ) : null} +
+ ); +}; diff --git a/frontend/cloud/src/styles/index.css b/frontend/cloud/src/styles/index.css new file mode 100644 index 0000000..07ea97d --- /dev/null +++ b/frontend/cloud/src/styles/index.css @@ -0,0 +1,4 @@ +@import "tailwindcss"; +@import "@cohaise/ui/styles"; + +@source "../../../../frontend/shared/src"; diff --git a/frontend/cloud/tsconfig.json b/frontend/cloud/tsconfig.json new file mode 100644 index 0000000..ee988a6 --- /dev/null +++ b/frontend/cloud/tsconfig.json @@ -0,0 +1,11 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "jsx": "react-jsx", + "types": ["vite/client"], + "noEmit": true + }, + "include": ["src/**/*.ts", "src/**/*.tsx"] +} diff --git a/frontend/cloud/vite.config.ts b/frontend/cloud/vite.config.ts new file mode 100644 index 0000000..44c42d8 --- /dev/null +++ b/frontend/cloud/vite.config.ts @@ -0,0 +1,19 @@ +import { defineConfig } from "vite"; +import react from "@vitejs/plugin-react"; +import tailwindcss from "@tailwindcss/vite"; + +export default defineConfig({ + plugins: [react(), tailwindcss()], + server: { + host: true, + port: 5174, + // En developpement, l'API tourne sur 3001 ; en production nginx + // intercepte /api/ lui-meme. Meme chemin des deux cotes. + proxy: { + "/api": { + target: "http://127.0.0.1:3101", + changeOrigin: false, + }, + }, + }, +}); diff --git a/frontend/shared/README.md b/frontend/shared/README.md new file mode 100644 index 0000000..3fd8f1b --- /dev/null +++ b/frontend/shared/README.md @@ -0,0 +1,186 @@ +# @cohaise/ui + +Design system du Cloud. Point d'entrée unique des jetons de style +utilisés par `frontend/cloud`, garantissant une identité visuelle +homogène et la thématisation dynamique clair/sombre. + +## Couche de jetons + +Ce paquet expose une chaîne CSS en trois fichiers, du plus primitif au plus dérivé. + +| Fichier | Rôle | +|---|---| +| `src/styles/tokens.css` | Variables CSS brutes (`--cohaise-*`). Échelle de gris en `oklch`, jetons sémantiques, ombres, typographie, rayons, courbes et durées de mouvement. | +| `src/styles/theme.css` | Directive `@theme inline` mappant les variables brutes vers les utilitaires Tailwind (`bg-surface`, `text-muted-foreground`, `border-border`...). | +| `src/styles/index.css` | Point d'entrée, importe les deux fichiers ci-dessus. | + +### Mouvement + +Tailwind v4 ne réserve pas de namespace de thème aux durées : `duration-*` est un +utilitaire à valeur nue. Les trois durées sont donc exposées via `@utility` dans +`theme.css`, adossées aux jetons `--cohaise-duration-*`. + +`--default-transition-duration` et `--default-transition-timing-function` sont +également déclarés, si bien que toute classe `transition-*` hérite du mouvement du +design system sans avoir à le répéter : + +```css +.transition-colors { + transition-timing-function: var(--tw-ease, var(--cohaise-ease-out-soft)); + transition-duration: var(--tw-duration, var(--cohaise-duration-base)); +} +``` + +Les utilitaires `duration-fast`, `duration-base`, `duration-slow` et `ease-out-soft` +surchargent ces valeurs au cas par cas. + +### Chaîne de résolution + +```mermaid +flowchart TD + A["tokens.css
--cohaise-gray-*, --cohaise-crimson-*"] --> B["tokens.css
--cohaise-background, --cohaise-border, ..."] + B --> C["theme.css
@theme inline"] + C --> D["Tailwind CSS
compile les utilitaires"] + D --> E["frontend/cloud"] + + F["Classe .dark sur <html>"] -.->|surcharge les jetons sémantiques| B +``` + +L'échelle de gris et l'échelle carmin sont les seules sources de vérité des couleurs +brutes. Les jetons sémantiques n'y font référence que par `var()`, jamais par une valeur +littérale, sauf pour les statuts (`success`, `warning`, `info`) et l'ombre carmin, qui +n'existent que dans le mode sombre. + +La source de vérité du rouge est `--clr-accent` du site, soit `#b71c1c`, et non le +carmin `#c3073f` qui apparaît davantage dans la feuille de style compilée. Les deux +valeurs ont été retenues à un moment de la construction du thème : le carmin est plus +vif, la valeur déclarée plus profonde et moins magenta. Sur un outil de gestion de +fichiers, c'est la seconde qui tient le mieux sur de grandes surfaces. + +## Couleurs + +Les valeurs viennent de `esiah.dev`. Le fond sombre est un noir à dominante rouge +(`#050000`), pas un gris neutre, et l'accent est le carmin `#b71c1c`. + +| Rôle | Clair | Sombre | +|---|---|---| +| Fond | `#f7f5f4` | `#050000` | +| Surface | `#ffffff` | `#1a0505` | +| Surface surélevée | `#ffffff` | `#1e1e22` | +| Texte | `#1a1a1a` | `#f4f4f2` | +| Texte atténué | `#5c5656` | `#a8a0a0` | +| Primaire | `#b71c1c` | `#b71c1c` | +| Accent graphique | `#b71c1c` | `#c92a2a` | +| Filet de séparation | `#e8dcdc` | `#2e1c1c` | + +Un seul rouge de marque dans les deux modes, ce qui rend les captures et les +comparaisons d'écran reproductibles. Il n'est appliqué qu'en aplat plein, avec du texte +blanc dessus, où il atteint 6,57:1. + +`accent-graphic` est un ton séparé, réservé aux **petits éléments posés sur** une +surface : filet de carte, carré de liste, anneau de focus. Ces éléments sont lus comme +interface et relèvent du seuil de 3:1, or le rouge de marque ne donne que 2,65:1 sur la +surface sombre. Le même raisonnement impose une bordure de champ distincte, à 3,57:1 en +sombre et 3,73:1 en clair. + +**Le destructif est ambre, pas rouge.** C'est une décision de lisibilité, pas un goût : +l'accent du site est un rouge, donc un bouton « supprimer » rouge serait confondu avec un +bouton d'accent. `destructive` occupe donc le ton `oklch(0.768 0.188 70)`, déjà présent +dans la palette, et `warning` garde le jaune plus clair. Le prix à payer est que +« supprimer » et « attention » sont proches en teinte ; ils ne se croisent jamais dans le +même écran, et c'est un choix à revoir si l'interface grossit. + +**Les bordures de champs de formulaire ont leur propre jeton.** Les bordures +décoratives restent très discrètes, `1.2:1` sur le fond en mode sombre, pour respecter le +grain du site. Un champ de formulaire doit en revanche pouvoir être identifié sans le +remplir ni le survoler, ce que la WCAG 1.4.11 chiffre à `3:1`. `border-control` est +donc nettement plus clair, `3.5:1` en sombre et `3.7:1` en clair, et c'est lui que +`Input` utilise. Les deux valeurs ont été retenues en mesurant le contraste réel plutôt +qu'à l'œil. + +## Polices + +| Usage | Police | Variable | +|---|---|---| +| Titres, libellés, boutons | Orbitron | `--cohaise-font-display` | +| Texte courant et paragraphes | Poppins | `--cohaise-font-sans` | +| Marque | Orbitron | `--cohaise-font-logo` | +| Accroche courte, registre éditorial | Cinzel | `--cohaise-font-serif` | +| Code | JetBrains Mono et replis | `--cohaise-font-mono` | + +Le partage vient du site, où `body` est en Orbitron. Orbitron a une chasse très large : à +32 px, un titre paraît écrit à la main, et un mot-symbole doit être resserré pour ne pas +s'éparpiller. D'où quatre jetons d'interlettrage dédiés, dont un négatif pour les titres. + +Orbitron est donc cantonnée aux **chaînes courtes** — titres jusqu'à `h3`, libellés en +capitales, boutons — avec `tracking-label` en positif. Au-delà de `h3`, la chasse est trop +large pour la taille du texte. Le flux est en Poppins. C'est pourquoi `font-display` est +appliqué dans la couche `base` plutôt que laissé au soin de chaque composant : c'est la +seule façon d'éviter qu'un titre revienne en Poppins parce qu'un écran l'a oublié. + +Cinzel est conservée en réserve. C'est un bon caractère, mais une serif d'inscription +romaine sur des libellés d'interface ou un paragraphe devient vite illisible, et c'est +précisément ce qui donnait au premier jet de ce thème son aspect de thème généré. + +Les trois faces sont **auto-hébergées** dans `frontend/shared/fonts`, 53,6 Ko au total, +soit 30 Ko de moins que Roboto seul. Un appel à Google Fonts aurait fait fuiter l'adresse +IP de chaque visiteur de ton NAS vers un tiers, ce qui n'a pas sa place dans une +application privée. + +## Modes clair et sombre + +Le mode est piloté par la classe `.dark` appliquée sur ``. `:root` porte le mode +clair, `.dark` surcharge l'ensemble des jetons sémantiques. `color-scheme` est défini +sur les deux blocs pour aligner les contrôles natifs et les barres de défilement. + +```mermaid +flowchart LR + subgraph Light["`:root` — mode clair"] + LA["--cohaise-background
#f7f5f4"] + LB["--cohaise-foreground
#1a1a1a"] + LC["--cohaise-primary
#b71c1c"] + end + subgraph Dark["`.dark` — mode sombre"] + DA["--cohaise-background
#050000"] + DB["--cohaise-foreground
#f4f4f2"] + DC["--cohaise-primary
#b71c1c"] + end + Light -->|bascule de classe| Dark +``` + +Aucune règle `@media (prefers-color-scheme)` n'est déclarée : la bascule est +explicite, ce qui garantit un comportement unique quelle que soit la préférence +système. + +## Forme + +Les rayons sont quasi nuls, de 2 à 6 px, contre 4 à 12 px pour les valeurs par défaut de +Tailwind. Les tuiles à coins arrondis sont la signature la plus immédiate d'une interface +sans intention, et un registre d'instrument se lit dans l'angle autant que dans la +couleur. + +Trois marques complètent le registre : un filet carmin d'un pixel en tête de `Card`, un +carré plein de 6 px devant chaque élément de liste au lieu d'une puce ronde, et des +libellés en capitales espacées. Aucune n'est décorative au sens strict : elles servent à +séparer des blocs sans ajouter de bordure lourde, et à rendre les métriques denses +scannables. + +## Consommation + +```css +@import "tailwindcss"; +@import "@cohaise/ui/styles"; +``` + +L'application conserve la main sur la directive `tailwindcss` et sur sa configuration ; +ce paquet ne fournit que les jetons. Le build Vite résout l'entrée via le champ +`exports` du `package.json`. + +## Contraintes + +- Aucune valeur de couleur littérale n'est autorisée dans les composants : uniquement + des utilitaires derivés des jetons sémantiques, sinon la thématisation casse. +- `@theme inline` est obligatoire plutôt que `@theme`, car les utilitaires doivent + référencer la variable pour résoudre la valeur au changement de mode. +- Aucune durée ne doit être écrite en dur dans un composant (`duration-150` est + interdit) : passer par `duration-fast`, `duration-base` ou `duration-slow`. diff --git a/frontend/shared/fonts/cinzel-latin.woff2 b/frontend/shared/fonts/cinzel-latin.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..a54fd00bf0e964d4d13688d8e8907cf04350e214 GIT binary patch literal 25904 zcmV)DK*7IvPew8T0RR910A(-$6aWAK0N;E70A#@c0RR9100000000000000000000 z0000Qf_xkOSR8UcNLE2oi7EzQKT}jeR7xir0EBEWLJ4G6#hN3PB4OIGo6hZp83ukN+Jih2HOY zmEr%6^V*}Rlg_}l#m+5@HxKdu=l89uI!Oyk_p_7?Alxzk8vB5BtJzK8v_?W2Eukb3 zLQ6t`G(rd=1VRZ2h?K4%O>Bs02g|A03YI(T=~WA7X(#qO_4JCRzUNum@z?!%Jp2Bf zbCKjmMe5-~?Al*Ilg<+s^t=Ty3(Z1<#}3p%+gzwS9xPj`s^BNj86P{VF z{oYLD54z>QnhJ2|L1T&}fnX9T1pHE$W$Cx+`!Jgu{X&Owvj%)mR9|;5v!9C4o|$mF zUQxuF(hY=&PGlkjNsv@57=N0p_st{=c%Rr6P!cO3S=|a-VY0c8K;6*^Sm3t~wgsc&Y{D0RzZGk`-QWdVJl2GaVn{3|41!P&dnKzky zSezxQLv@BOc(cK*x+abu(Mq7othZOf{%LRYBm%mRj}MEWXBVDGw6 z)WFKswtsJ`*1nHmE~rF0!kIXmGjIk+nqHv#!{gxsJ`!c|MzS9xdW)N+KvZtN(r419H#_vB#Oi!5L`kC zF5QUT_V@j^T~~p07X(2t2!dcR2nK_}U=R!*-p)3abwyt$M!Tz5F91eW{GgJsf zStt-x2s#9F5`01uvMK-(455OE7|_s4lt@p{D7jWZ*dZJc&H;~HMf@!RL@C5Lh^m1) z^%^yGA|To!x*%@C`5Dd~IQQT@{BIltcp4N~2~0to606|hT!v?vK5Rv3)ES^x3 zSv6PCDpkFaG@3|+v$>KXpoiliJ~WY%8G7`wTnrdDU(vCF0S{=1fPmg~P0I$}4HokX z7=Wv!e#|-y(elq0$dKA9yCL~5ny6N0UOF>1<1;eFiQz&#i+k}yoQ>hw6YFCj`l34~ zM0wqn>-YWg>6sQ!T)Iw!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@Ovxq>>|kAvsZAyG>73Jodw`kDIqHnv^cdA#fWkxjxLN! zJc+lJ1Y)-cvEdv(kRj3Bg^++|3doFKfJzQzZIuEr^_3Eotd#~R1QT-@95_mY38tvg zEKiH^##QASR*cuSN|QNhi7#Gti{zE@I-Q(ZZQMZ)QZ$iLj#QnK zhLUtd5^bbGN%SkE?ed{wEtI67Y<~)+Ms-}=%Ld}vqBi@Hvi^f8(YR4@)10}ais&|F(pvCJnm}{LX zFLG5Ra>ekl%j9Fz4_zo-o*1W%5m5MPwlC;hb-xEz8wm>EsYzEkI#k9=ysI4{HxE$sN~Zm9PI1EXXnze!=&ph>ev z6O6Z6I)@e+o^fg|5}r7VupzgbI&_(&6Tom)=IWMbvZ*ms?Ls@XE1qVdYm?q#_E#BX?0FLFQSfDji>y$$wwN94bdAe0>`xR X$#4R-vrsx3nybCG2ayl&p29Bz@A~;s literal 0 HcmV?d00001 diff --git a/frontend/shared/fonts/jetbrains-mono-latin.woff2 b/frontend/shared/fonts/jetbrains-mono-latin.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..4d09cda4a4c3f4c08ae253dd8a9c5133a89b31b7 GIT binary patch literal 31432 zcmV)AK*YayPew8T0RR910D8y(6951J0W!b<0D4*g0RR9100000000000000000000 z0000QfjAq78XSR|at2^OQ&d4zfgmRy0EHqiOc4kQf!sKOtS$?N7634ToL&Jo0we>B z8U!E(heijZ3=9WbP!@4Q(d&)~x|7`bT&-&Hs*sy!%I%P-;oo1;Y=qU7#TGc(|No!1 zbc}(6-Unc&W>x(v|6ijW{&ED~YM3;NqM5 zD<4T=wzMtYPh95^;}_`JX3AL0=NBm|MNs~INH-XEao=Y_!%kt?!D?ulQ*qD)i|;=0 zMyAsL)zobjez|7GMeZu8at$|Jo3^}sqW#2F7lDn-7+EK2-y_J)W;gi_;R_)kVhkb1 z@EBtRjEDgvMvOGZh?u5`h4a~06@o%&8UDS7oz}`%!%COc>2GbR=-fClBJSu z$%zAY6Al2JX6Z=RIUM)hB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UQ1f@yrJn!fr-iL1}c_1l}<+mr&+^5Lac%f|J27Fzy1b78ZZ=G$vgdvKD`$4AI0rQ^NW zUpjkE`r~Q1<`+tJre*z+Z9GcTh_8bm7u5X~fhrZD(STO*N+~3_uJ%D^gr@CfDXip>}M{w@3~kWC+|NwYdy}rq^>-SWJOe?bb;Y ziGkPKNFSu?CQP2vljH5+2N7;A&WMZzL2w+5zZ(M7R7#6{n{O z#Gg2m_0_4i$&Rh`aPMho@_w~no*f+BY=4#a0l=5TrDx304-D6ZQe>7&SxLrA zEy%TZtdmJRCoLU{O+hlSe# n2(9rG{s=Adns=eIFL+JUL&fp`E2sX)l3(vv|4&*@ZUg`T;X1QK literal 0 HcmV?d00001 diff --git a/frontend/shared/fonts/orbitron-latin.woff2 b/frontend/shared/fonts/orbitron-latin.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..39d9db55bdf48b839d360769987abb69ae44ccfb GIT binary patch literal 11800 zcmV+zF6YsAPew8T0RR9104^8+6aWAK0A~;Y04=Bh0RR9100000000000000000000 z0000QfqxsD3LGduNLE2ogl7g|KT}jeRCFgM0EAdCU=auk(mcK<3xaq6FuEcEHUcCA zg=_>M1&2TfgJTQ_8!1{7ZVWeU9KZ&+^FX4gSA$b(@?R%!g>)O#&(i3mDWmMpOntHxhHVacg||tAp$8{-|`{`@X1e z;byD5Yyc(}LrbI%!~Y{U{=C4Xtu%(Vh`;H-e*DejcL|1Z5fw%r_@vVR8`H+7vHYhs z^SznO<@*23POgBcT4CxqyK~7N6%b`o24PwcqFD13xKEfay(a0H{|BPdjYz`}ySsv3cV6Tv>6SUBh)76^bw6aXc3;aG! zHFSNG)n<2W-oB%)d;h^6t!`L8V<<9?wN_MtfB8 z;e!M~K-K(gsDr4x`aB8?%Ec5piUvFJ^K(H+TSyQxhc~juKM;2>>S=h3dSAZZ&<}6@ zD=+uHzjrsfeB`tH9@c@kHd}{9ic)uiK!LvVz7ON}-{$*f^TO2L=c5-Pqf;|#G$wT) z41k~pI$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N zIBjxN$cP*fLmVZP)KwK`$II?^s_rmmT$9==xI#w8Cd6mAnO&v>)vFtk(;tNrBl3-4 zIIFIkAPALhQAj<~)}f1e-p+@Og|vE69BAtsW&xT3iPX^~!&J&>E2tzXFMwS=vNZ90C9((9MIeE6`Wjx?m4kd@1Dou>evgM30whv8Xg zT)Ww#G$F85Zw&8D>Y7Y+3n9Y{cS?GCS?5n~tK4pf?rEsT8(@B%Z*60S6gfC!0{O&S=0Q1&%B#fj@L(GmH%QB)gPmsR$AX zbTDEwZf=BqF-Mwzb)5 z+SabfwXK8K9dX9obP^offu}WWo;B*R5ENUSEM@VUILM<7XPPo~! zMo4u#jzM4~kx#@^H;f98h=@9_%rAn1iHsIoCP1y3<3)He?s<$osUztROlfc;T?;8!m1GRB=}4iQO&Q;6mW)V zD=@(Ge$IE0P5m{HX0ZKb(tmQ?JiL7T0)j%qh8tm|QAQghRho1e#u{h52`0*vB^wG_ zj$C>26)1#(g@Z>xL_$VEMMGDFfr*8UgNuhxKuAPPLP|ysqM)P#Q`6AW(K9eIF|)9; zDQ1UoaB^`g;mJUsW|--)RsJ%|BJ*w3X-5Wmb60DX9>TH0?xVMs!J}r;%`AWU2|QJQco>)$1S&&`PUtwAuDL;;2JO@Zm`k q7u|L*3=a_B6(4yfL?m7j6PIN0HLaC=Egty)l;Nb6Odihx0002ms`8-# literal 0 HcmV?d00001 diff --git a/frontend/shared/fonts/poppins-600.woff2 b/frontend/shared/fonts/poppins-600.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..921e962b91ded5f8574b8605d1e0b2af1294189f GIT binary patch literal 8000 zcmV-GAHU#tPew8T0RR9103SdA3;+NC06#zg03PfB0RR9100000000000000000000 z0000R9vm(PU;u$s3g&dtDhq=)00A}vBm;(M1Rw>2R0o6$8|pDd2Xfdr0LZr7OGMS? zxa|Kbfg3WwK1`7i5s?s%6EFgXW2k8V$)yu{Unz6MP5iHioyd4FH!(FP^J~)q@kidKi^%cn(b1c z=0RsV#87mG9BR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Ca{1mA4SYIC>r-jxIg}^2WYB~RW51IdS zgrWe0xz&K;KF`jebr`Ay*=kNG6>JqrO`f$Q0w$kIDg@wq7#g7Ki_5sRxg@dsV}3#J*>M=8f@mA;omi2+`S;+% zUKQwqlF;5+m89`*uvQqbyYyZ|#_R%XcA=2k!3KK=Cf+w+3_fnV6c?0+!U58H#MCyx zfZc_gaRf%b;K7$9DT$I6mbLyBlr6}=LOoumu7#5i=XowPcQV{rYL$^`#OIi`Re;;Dk}@Gz#Fu*G2(=hX8{wU^O#8J_`f@ulu+<#0S)|Lwtpr zJ;V>2p?uBhL;S6!J0t)UH57Ww0jF9U--qAi%E}a&t7@?ALXFv<;R@AC&e>pT6{|%G zjdMI;lg;r{h0Cw5v+^-RK1~+eW4fvGmaB5sRq$2X?1a%_ zYG^^JZnEu)=IiBj=R1hbe*#E-{D9wI0sU_v2*g^!)(H_ROt=VTvXP)}YoZ~+5z7r}{8D;X3YRf+KnU8(qQ@=9%%ICgtlEt6KT=lhYSUvEYL3TDZ z>eO=B&8gldHxieA7TlWMx0y$aR$H|BpFOr}*P+uxzguw4DW?+%uDj!gGtRo;qIaEh z-h28Tb;TPlB?x%^5y%?V%?gDt|AxS(hi!N~7vFdVTk|M7k;h;2zl-sjP9zd20001Q CEPT=c literal 0 HcmV?d00001 diff --git a/frontend/shared/package.json b/frontend/shared/package.json new file mode 100644 index 0000000..de83787 --- /dev/null +++ b/frontend/shared/package.json @@ -0,0 +1,38 @@ +{ + "name": "@cohaise/ui", + "version": "0.0.0", + "private": true, + "type": "module", + "sideEffects": ["**/*.css"], + "style": "./src/styles/index.css", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./styles": "./src/styles/index.css", + "./styles/tokens": "./src/styles/tokens.css", + "./styles/theme": "./src/styles/theme.css" + }, + "files": ["dist", "src/styles"], + "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" + }, + "peerDependencies": { + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "react": "^19.3.0", + "react-dom": "^19.3.0", + "typescript": "^7.0.2" + }, + "dependencies": { + "clsx": "^2.1.1", + "tailwind-merge": "^3.7.0" + } +} diff --git a/frontend/shared/src/components/Button.tsx b/frontend/shared/src/components/Button.tsx new file mode 100644 index 0000000..1a656c0 --- /dev/null +++ b/frontend/shared/src/components/Button.tsx @@ -0,0 +1,72 @@ +import type { ButtonHTMLAttributes, ReactNode } from "react"; +import { cn } from "../lib/cn.js"; +import { Spinner } from "./Spinner.js"; +import type { SpinnerSize } from "./Spinner.js"; + +const variantClasses = { + primary: "bg-primary text-primary-foreground hover:bg-primary-hover", + secondary: "border border-border-strong bg-surface text-foreground hover:bg-surface-hover", + ghost: "text-foreground hover:bg-surface-hover", + destructive: "bg-destructive text-destructive-foreground hover:bg-destructive-hover", +} as const; + +const sizeClasses = { + sm: "h-8 gap-1.5 rounded-sm px-3 text-[0.6875rem]", + md: "h-10 gap-2 rounded-md px-4 text-xs", + lg: "h-12 gap-2.5 rounded-lg px-6 text-sm", +} as const; + +const spinnerBySize: Record = { + sm: "xs", + md: "sm", + lg: "md", +}; + +export type ButtonVariant = keyof typeof variantClasses; +export type ButtonSize = keyof typeof sizeClasses; + +export interface ButtonProps extends ButtonHTMLAttributes { + variant?: ButtonVariant; + size?: ButtonSize; + isLoading?: boolean; + showTextWhileLoading?: boolean; + iconLeading?: ReactNode; + iconTrailing?: ReactNode; + fullWidth?: boolean; +} + +export const Button = ({ + variant = "primary", + size = "md", + isLoading = false, + showTextWhileLoading = true, + iconLeading, + iconTrailing, + fullWidth = false, + disabled, + type = "button", + className, + children, + ...props +}: ButtonProps) => ( + +); diff --git a/frontend/shared/src/components/Card.tsx b/frontend/shared/src/components/Card.tsx new file mode 100644 index 0000000..739f83f --- /dev/null +++ b/frontend/shared/src/components/Card.tsx @@ -0,0 +1,49 @@ +import type { HTMLAttributes } from "react"; +import { cn } from "../lib/cn.js"; + +export const Card = ({ className, ...props }: HTMLAttributes) => ( +
+); + +/* Signature du produit : un filet carmin d'un pixel en tete de carte. Invisible sur + une grille dense, mais c'est lui qui donne aux cartes leur epaisseur et evite + l'aspect de tuiles interchangeables. */ +export const CardHeader = ({ className, ...props }: HTMLAttributes) => ( +
+); + +export const CardTitle = ({ className, ...props }: HTMLAttributes) => ( +

+); + +export const CardDescription = ({ className, ...props }: HTMLAttributes) => ( +

+); + +export const CardContent = ({ className, ...props }: HTMLAttributes) => ( +

+); + +export const CardFooter = ({ className, ...props }: HTMLAttributes) => ( +
+); diff --git a/frontend/shared/src/components/Input.tsx b/frontend/shared/src/components/Input.tsx new file mode 100644 index 0000000..141afe8 --- /dev/null +++ b/frontend/shared/src/components/Input.tsx @@ -0,0 +1,72 @@ +import { useId } from "react"; +import type { InputHTMLAttributes, ReactNode } from "react"; +import { cn } from "../lib/cn.js"; + +export interface InputProps extends Omit, "size"> { + label?: ReactNode; + hint?: ReactNode; + error?: ReactNode; + sizeVariant?: "sm" | "md" | "lg"; +} + +const inputSize = { + sm: "h-8 px-2.5 text-xs", + md: "h-10 px-3 text-sm", + lg: "h-12 px-4 text-base", +} as const; + +export const Input = ({ + label, + hint, + error, + sizeVariant = "md", + id, + className, + disabled, + ...props +}: InputProps) => { + const generatedId = useId(); + const inputId = id ?? generatedId; + const messageId = `${inputId}-message`; + const isInvalid = error !== undefined && error !== null && error !== ""; + + return ( +
+ {label ? ( + + ) : null} + + + + {isInvalid || hint ? ( +

+ {isInvalid ? error : hint} +

+ ) : null} +
+ ); +}; diff --git a/frontend/shared/src/components/Skeleton.tsx b/frontend/shared/src/components/Skeleton.tsx new file mode 100644 index 0000000..71a7c09 --- /dev/null +++ b/frontend/shared/src/components/Skeleton.tsx @@ -0,0 +1,32 @@ +import type { HTMLAttributes } from "react"; +import { cn } from "../lib/cn.js"; + +export type SkeletonProps = HTMLAttributes & { + width?: string; + height?: string; + radius?: "sm" | "md" | "lg" | "xl" | "full"; +}; + +const skeletonRadius = { + sm: "rounded-sm", + md: "rounded-md", + lg: "rounded-lg", + xl: "rounded-xl", + full: "rounded-full", +} as const; + +export const Skeleton = ({ + width, + height, + radius = "md", + className, + style, + ...props +}: SkeletonProps) => ( +