Up And Down : première version
This commit is contained in:
commit
89c5430308
76 files changed
+20730
No files matched your search
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"version": "0.0.1",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "upandown-dev",
|
||||
"runtimeExecutable": "sh",
|
||||
"runtimeArgs": ["-c", "LISTEN_ADDR=:8099 DATA_DIR=./.devdata AUTH_MODE=both REGISTRATION=approval ADMIN_USER=admin ADMIN_PASSWORD=dev-password-123 OIDC_ISSUER=https://idp.invalid OIDC_CLIENT_ID=upandown OIDC_NAME=Authentik ./bin/upandown"],
|
||||
"port": 8099
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
**/node_modules
|
||||
web/dist
|
||||
data
|
||||
.devdata
|
||||
bin
|
||||
*.md
|
||||
.git
|
||||
@@ -0,0 +1,22 @@
|
||||
UPANDOWN_PORT=8080
|
||||
# local, oidc, both ou none
|
||||
AUTH_MODE=local
|
||||
ADMIN_USER=
|
||||
ADMIN_PASSWORD=
|
||||
# closed, approval ou open
|
||||
REGISTRATION=closed
|
||||
OIDC_ISSUER=
|
||||
OIDC_CLIENT_ID=
|
||||
OIDC_CLIENT_SECRET=
|
||||
OIDC_REDIRECT_URL=
|
||||
OIDC_NAME=SSO
|
||||
OIDC_ALLOWED_GROUPS=
|
||||
OIDC_ADMIN_GROUPS=
|
||||
OIDC_ADMIN_EMAILS=
|
||||
SESSION_SECRET=
|
||||
PUBLIC_URL=
|
||||
MAX_UPLOAD_MB=0
|
||||
USER_QUOTA_MB=0
|
||||
COMMON_READONLY=false
|
||||
TRASH_DAYS=0
|
||||
HISTORY_KEEP=10
|
||||
@@ -0,0 +1,7 @@
|
||||
/data/
|
||||
/.devdata/
|
||||
/bin/
|
||||
web/dist/*
|
||||
!web/dist/.gitkeep
|
||||
frontend/node_modules/
|
||||
.DS_Store
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
# --- 1. Frontend : React + Vite -> /src/web/dist
|
||||
FROM node:22-alpine AS frontend
|
||||
WORKDIR /src/frontend
|
||||
COPY frontend/package.json frontend/package-lock.json ./
|
||||
RUN --mount=type=cache,target=/root/.npm npm ci --no-audit --no-fund
|
||||
COPY frontend/ ./
|
||||
RUN npm run build
|
||||
|
||||
# --- 2. Backend : binaire Go statique embarquant le frontend
|
||||
FROM golang:1.24-alpine AS backend
|
||||
ARG VERSION=dev
|
||||
WORKDIR /src
|
||||
COPY go.mod ./
|
||||
COPY cmd ./cmd
|
||||
COPY internal ./internal
|
||||
COPY web/embed.go ./web/
|
||||
COPY --from=frontend /src/web/dist ./web/dist
|
||||
RUN --mount=type=cache,target=/root/.cache/go-build \
|
||||
CGO_ENABLED=0 go test ./... && \
|
||||
CGO_ENABLED=0 go build -trimpath -ldflags="-s -w -X main.version=${VERSION}" -o /out/server ./cmd/server && \
|
||||
mkdir -p /out/data
|
||||
|
||||
# --- 3. Image finale : distroless, non-root (uid 65532)
|
||||
FROM gcr.io/distroless/static-debian12:nonroot
|
||||
COPY --from=backend /out/server /server
|
||||
COPY --from=backend --chown=65532:65532 /out/data /data
|
||||
ENV LISTEN_ADDR=:8080 DATA_DIR=/data
|
||||
VOLUME ["/data"]
|
||||
EXPOSE 8080
|
||||
USER nonroot:nonroot
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 CMD ["/server", "healthcheck"]
|
||||
ENTRYPOINT ["/server"]
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 vLab-BZH
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,26 @@
|
||||
# Licence MIT (traduction française)
|
||||
|
||||
> Traduction fournie à titre informatif. Seule la version anglaise du fichier [`LICENSE`](LICENSE) fait foi.
|
||||
|
||||
```text
|
||||
Copyright (c) 2026 vLab-BZH
|
||||
|
||||
L'autorisation est accordée, gracieusement, à toute personne obtenant une copie
|
||||
de ce logiciel et des fichiers de documentation associés (le « Logiciel »), de
|
||||
commercialiser le Logiciel sans restriction, notamment les droits d'utiliser,
|
||||
de copier, de modifier, de fusionner, de publier, de distribuer, de
|
||||
sous-licencier et/ou de vendre des copies du Logiciel, ainsi que d'autoriser
|
||||
les personnes auxquelles le Logiciel est fourni à le faire, sous réserve des
|
||||
conditions suivantes :
|
||||
|
||||
La déclaration de copyright ci-dessus et la présente autorisation doivent être
|
||||
incluses dans toutes copies ou parties substantielles du Logiciel.
|
||||
|
||||
LE LOGICIEL EST FOURNI « TEL QUEL », SANS GARANTIE D'AUCUNE SORTE, EXPLICITE OU
|
||||
IMPLICITE, NOTAMMENT SANS GARANTIE DE QUALITÉ MARCHANDE, D'ADÉQUATION À UN
|
||||
USAGE PARTICULIER ET D'ABSENCE DE CONTREFAÇON. EN AUCUN CAS LES AUTEURS OU
|
||||
TITULAIRES DU DROIT D'AUTEUR NE SERONT RESPONSABLES DE TOUT DOMMAGE,
|
||||
RÉCLAMATION OU AUTRE RESPONSABILITÉ, QUE CE SOIT DANS LE CADRE D'UN CONTRAT,
|
||||
D'UN DÉLIT OU AUTRE, EN PROVENANCE DE, CONSÉCUTIF À OU EN RELATION AVEC LE
|
||||
LOGICIEL OU SON UTILISATION, OU AVEC D'AUTRES ÉLÉMENTS DU LOGICIEL.
|
||||
```
|
||||
@@ -0,0 +1,90 @@
|
||||
# Up And Down
|
||||
|
||||
Dépôt et téléchargement de fichiers **auto-hébergé**, avec un navigateur de fichiers complet. Même modèle qu'[Excalicloud](https://github.com/vLab-BZH/excalicloud) (explorateur, espaces personnels, favoris, tags, corbeille, partage, authentification OIDC ou locale), mais pour des fichiers **de tout type**.
|
||||
|
||||
- **Envoi** : glisser-déposer de fichiers et de dossiers entiers, envoi en flux (pas de limite de mémoire), plusieurs fichiers en parallèle, progression, annulation, nouvel essai, choix « garder les deux / remplacer / ignorer », date de modification d'origine conservée.
|
||||
- **Navigation** : 4 affichages (liste, tableau triable, vignettes, galerie), recherche (noms, tags, **contenu des fichiers texte**), tags, favoris (fichiers et dossiers), sélection multiple, glisser-déposer pour déplacer, miniatures d'images (EXIF pris en compte).
|
||||
- **Aperçu intégré** : images, vidéo, audio, PDF, texte et code, avec navigation ←/→ dans le dossier.
|
||||
- **Téléchargement** : fichier (reprise possible, `Range`) ou dossier / sélection en **ZIP** généré en flux.
|
||||
- **Espaces** : arborescence commune + espace **Personnel** privé par utilisateur ; poubelle ; historique des versions (chaque remplacement garde l'ancien contenu, restauration en un clic).
|
||||
- **Partage** par lien (`/s/<jeton>`) d'un fichier ou d'un dossier : durée au choix, **mot de passe** facultatif, compteur de téléchargements, révocation, sans compte pour le destinataire.
|
||||
- **Comptes** : comptes locaux avec **inscription** (fermée, avec validation, ou libre), **connexion OIDC** (Authentik, Keycloak...), ou les deux. Rôles administrateur / utilisateur, quotas, jetons d'API.
|
||||
- **Sécurité** : conteneur non-root en lecture seule, un seul binaire Go (bibliothèque standard, aucune dépendance), fichiers servis sans jamais exécuter leur contenu dans l'origine de l'application.
|
||||
|
||||
## Démarrage
|
||||
|
||||
```bash
|
||||
cp .env.example .env # optionnel
|
||||
docker compose up -d --build
|
||||
# http://localhost:8080 : le premier compte créé devient l'administrateur
|
||||
```
|
||||
|
||||
Pour imposer l'administrateur : `ADMIN_USER` et `ADMIN_PASSWORD` dans `.env`. Les fichiers sont de simples fichiers sur le volume `./data` (`chown -R 65532:65532 ./data` pour un bind mount).
|
||||
|
||||
## Authentification
|
||||
|
||||
| `AUTH_MODE` | Comportement |
|
||||
|---|---|
|
||||
| `local` (défaut) | Comptes locaux (mot de passe PBKDF2-SHA256), inscription selon `REGISTRATION` |
|
||||
| `oidc` | Connexion uniquement via le fournisseur OIDC |
|
||||
| `both` | Formulaire local **et** bouton OIDC |
|
||||
| `none` | Aucune authentification intégrée (reverse proxy qui authentifie) ; un seul utilisateur, tout le monde administre |
|
||||
|
||||
**Inscription** (`REGISTRATION`, modifiable ensuite dans *Administration > Général*) : `closed` (l'administrateur crée les comptes), `approval` (les inscrits attendent la validation d'un administrateur), `open`. Tant qu'aucun administrateur n'existe, le premier compte créé (inscription ou première connexion OIDC) le devient.
|
||||
|
||||
**OIDC** : `OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET` (vide : client public, PKCE seul), URI de redirection `https://<hôte>/auth/callback` (ou `OIDC_REDIRECT_URL`). `OIDC_ALLOWED_GROUPS` restreint l'accès ; `OIDC_ADMIN_GROUPS` / `OIDC_ADMIN_EMAILS` désignent les administrateurs (synchronisés à chaque connexion). Les comptes OIDC sont créés à la première connexion ; un e-mail identique d'un autre sujet ne fusionne jamais deux comptes.
|
||||
|
||||
## Variables
|
||||
|
||||
| Variable | Défaut | Rôle |
|
||||
|---|---|---|
|
||||
| `LISTEN_ADDR` / `DATA_DIR` | `:8080` / `/data` | Écoute et volume |
|
||||
| `MAX_UPLOAD_MB` | `0` | Taille max d'un fichier (0 : illimité) |
|
||||
| `USER_QUOTA_MB` | `0` | Quota de l'espace personnel (0 : illimité) |
|
||||
| `COMMON_READONLY` | `false` | Commun en lecture seule pour les non-administrateurs |
|
||||
| `TRASH_DAYS` | `0` | Purge de la poubelle (0 : jamais) |
|
||||
| `HISTORY_KEEP` / `HISTORY_INTERVAL` / `HISTORY_MAX_AGE` | `10` / `0` / `0` | Versions gardées par fichier, écart minimal, âge maximal |
|
||||
| `SESSION_TTL` / `SESSION_SECRET` | `24h` / aléatoire | Session ; clé de signature (sinon `DATA_DIR/.session-secret`) |
|
||||
| `SHARE_SECRET` | aléatoire | Clé de signature des liens de partage |
|
||||
| `PUBLIC_URL` | | URL publique (cookies `Secure`) |
|
||||
|
||||
Les valeurs d'inscription, de quota, de lecture seule et de poubelle sont des défauts : une fois modifiées dans l'interface, c'est le réglage de l'interface qui prime.
|
||||
|
||||
## API et jetons
|
||||
|
||||
Chaque utilisateur peut créer des jetons (*Jetons d'API*) pour scripter :
|
||||
|
||||
```bash
|
||||
curl -T rapport.pdf -H "Authorization: Bearer upd_..." \
|
||||
"https://cloud.example.org/api/file?path=.perso/rapport.pdf&conflict=overwrite"
|
||||
curl -OJ -H "Authorization: Bearer upd_..." "https://cloud.example.org/api/file?path=.perso/rapport.pdf"
|
||||
```
|
||||
|
||||
Les routes sont décrites en tête de [`internal/api/api.go`](internal/api/api.go). `.perso/...` est l'espace personnel, `.favoris` les favoris, `.poubelle` la poubelle.
|
||||
|
||||
## Sécurité : ce qui est fait
|
||||
|
||||
- Un fichier déposé ne s'exécute jamais dans l'application : seuls les types sûrs (images, vidéo, audio, PDF, texte) s'affichent en ligne ; HTML, SVG hors `<img>`, scripts et inconnus sont téléchargés (`attachment`), le texte est servi en `text/plain`, et un SVG ouvert directement l'est sous un CSP `sandbox`.
|
||||
- Chemins normalisés sous la racine, noms cachés (`.trash`, `.accounts.json`...) refusés, liens symboliques ignorés ou refusés.
|
||||
- Sessions invalidées dès qu'un compte est désactivé ou supprimé ; limitation des tentatives de connexion, d'inscription et de déverrouillage de lien ; en-tête `Origin` contrôlé sur les requêtes modifiantes ; jeton d'un lien absent des journaux.
|
||||
- Jetons et mots de passe de liens conservés hachés ; liens non énumérables (id 128 bits signé HMAC).
|
||||
- Suppression d'un compte : son espace personnel est mis de côté (`.users-removed`), jamais hérité par un homonyme.
|
||||
|
||||
À faire par l'exploitant : TLS devant le service (Traefik, Caddy, nginx), purge de `.trash` / `.users-removed`, sauvegarde du volume.
|
||||
|
||||
## Développement
|
||||
|
||||
```bash
|
||||
go test ./... # backend (sans ouvrir de port)
|
||||
cd frontend && npm install && npm run build # construit web/dist, embarqué dans le binaire
|
||||
go run ./cmd/server # http://localhost:8080 (DATA_DIR=./data)
|
||||
cd frontend && npm run dev # rechargement à chaud, proxy vers :8080
|
||||
```
|
||||
|
||||
## Évolutions possibles
|
||||
|
||||
Envoi par morceaux (reprise après coupure, proxys à limite de corps), liens de dépôt (envoi seul), WebDAV, miniatures vidéo/PDF/WebP, recherche dans les PDF et documents Office, 2FA.
|
||||
|
||||
## Licence
|
||||
|
||||
MIT, voir [`LICENSE`](LICENSE). Une partie du code (authentification OIDC, explorateur, icônes Tabler) est reprise d'Excalicloud, voir [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md).
|
||||
@@ -0,0 +1,7 @@
|
||||
# Composants tiers
|
||||
|
||||
- **Excalicloud** (MIT, vLab-BZH) : paquet d'authentification OIDC (`internal/auth`), organisation du stockage (espaces personnels, favoris, corbeille, tags, partage) et composants de l'explorateur.
|
||||
- **Icônes Tabler** (MIT, Paweł Kuna) : tracés repris dans `frontend/src/icons.tsx` et `folderIcons.tsx`.
|
||||
- **React** (MIT, Meta), **Vite** (MIT).
|
||||
|
||||
Aucune autre dépendance : le serveur n'utilise que la bibliothèque standard de Go.
|
||||
@@ -0,0 +1,454 @@
|
||||
// Commande server : API de gestion de fichiers + frontend embarqué.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/vblogio/upandown/internal/api"
|
||||
"github.com/vblogio/upandown/internal/auth"
|
||||
"github.com/vblogio/upandown/internal/storage"
|
||||
"github.com/vblogio/upandown/internal/tokens"
|
||||
"github.com/vblogio/upandown/web"
|
||||
)
|
||||
|
||||
// version est renseignée au build (-ldflags "-X main.version=...").
|
||||
var version = "dev"
|
||||
|
||||
func env(key, def string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
// envBool lit un booléen ; une valeur illisible est une erreur de configuration.
|
||||
func envBool(key string, def bool) bool {
|
||||
v := os.Getenv(key)
|
||||
if v == "" {
|
||||
return def
|
||||
}
|
||||
b, err := strconv.ParseBool(v)
|
||||
if err != nil {
|
||||
fatal(key + " invalide (true ou false)")
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func envInt(key string, def int64) int64 {
|
||||
v := os.Getenv(key)
|
||||
if v == "" {
|
||||
return def
|
||||
}
|
||||
n, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil || n < 0 {
|
||||
fatal(key + " invalide (entier >= 0)")
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func fatal(msg string, args ...any) {
|
||||
slog.Error(msg, args...)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// secretEnv lit un secret dans NAME, ou dans le fichier NAME_FILE (secrets Docker).
|
||||
func secretEnv(name string) string {
|
||||
if v := os.Getenv(name); v != "" {
|
||||
return v
|
||||
}
|
||||
if f := os.Getenv(name + "_FILE"); f != "" {
|
||||
b, err := os.ReadFile(f)
|
||||
if err != nil {
|
||||
fatal(name+"_FILE illisible", "err", err)
|
||||
}
|
||||
return strings.TrimSpace(string(b))
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func main() {
|
||||
slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, nil)))
|
||||
|
||||
addr := env("LISTEN_ADDR", ":8080")
|
||||
// `server healthcheck` : sonde pour l'image distroless (pas de curl/wget).
|
||||
if len(os.Args) > 1 && os.Args[1] == "healthcheck" {
|
||||
os.Exit(healthcheck(addr))
|
||||
}
|
||||
dataDir := env("DATA_DIR", "./data")
|
||||
|
||||
store, err := storage.New(dataDir)
|
||||
if err != nil {
|
||||
fatal("initialisation du stockage", "dir", dataDir, "err", err)
|
||||
}
|
||||
if store.History, err = historyPolicy(); err != nil {
|
||||
fatal("historique", "err", err)
|
||||
}
|
||||
store.Defaults = storage.SettingsDefaults{
|
||||
Registration: strings.ToLower(env("REGISTRATION", storage.RegClosed)),
|
||||
QuotaMB: envInt("USER_QUOTA_MB", 0),
|
||||
CommonReadonly: envBool("COMMON_READONLY", false),
|
||||
TrashDays: int(envInt("TRASH_DAYS", 0)),
|
||||
}
|
||||
if !storage.ValidRegistration(store.Defaults.Registration) {
|
||||
fatal("REGISTRATION invalide (closed, approval ou open)")
|
||||
}
|
||||
// Clé de signature des liens de partage : SHARE_SECRET, sinon DATA_DIR/.share-secret.
|
||||
if secret := os.Getenv("SHARE_SECRET"); secret != "" {
|
||||
if len(secret) < 16 {
|
||||
fatal("SHARE_SECRET trop court (16 caractères minimum)")
|
||||
}
|
||||
store.SetShareSecret(secret)
|
||||
}
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
spaces := storage.NewSpaces(store)
|
||||
spaces.MaxUpload = envInt("MAX_UPLOAD_MB", 0) << 20 // 0 : illimité
|
||||
|
||||
mode := strings.ToLower(env("AUTH_MODE", "local"))
|
||||
handler := (&api.Handler{Store: store, Spaces: spaces, Mode: mode, Version: version}).Init()
|
||||
mux := http.NewServeMux()
|
||||
var root http.Handler = mux
|
||||
tokenStore, err := tokens.Open(dataDir)
|
||||
if err != nil {
|
||||
fatal("jetons d'accès", "err", err)
|
||||
}
|
||||
ts := &tokens.Server{Store: tokenStore, UserID: api.UserID}
|
||||
|
||||
switch mode {
|
||||
case "none":
|
||||
// Aucune authentification intégrée (reverse proxy avec SSO, usage local).
|
||||
slog.Warn("aucune authentification intégrée (AUTH_MODE=none) : à réserver à un reverse proxy qui authentifie")
|
||||
ts.Resolve = func(string) (*auth.User, bool) { return nil, true }
|
||||
case "local", "oidc", "both":
|
||||
accounts, err := auth.OpenAccounts(dataDir)
|
||||
if err != nil {
|
||||
fatal("comptes", "err", err)
|
||||
}
|
||||
handler.Accounts = accounts
|
||||
a, err := authentication(ctx, mode, dataDir, accounts, store, handler)
|
||||
if err != nil {
|
||||
fatal("authentification", "err", err)
|
||||
}
|
||||
a.Register(mux)
|
||||
handler.Auth = a
|
||||
root = a.Middleware(mux, public)
|
||||
ts.Resolve = func(id string) (*auth.User, bool) {
|
||||
acc, ok := accounts.Get(id)
|
||||
if !ok || acc.Status != auth.StatusActive {
|
||||
return nil, false
|
||||
}
|
||||
u := acc.User()
|
||||
return &u, true
|
||||
}
|
||||
handler.OnUserRemoved = tokenStore.RevokeUser
|
||||
default:
|
||||
fatal(fmt.Sprintf("AUTH_MODE %q inconnu (local, oidc, both ou none)", mode))
|
||||
}
|
||||
|
||||
handler.Register(mux)
|
||||
ts.Register(mux)
|
||||
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok")) })
|
||||
mux.Handle("/", spa())
|
||||
|
||||
h := logRequests(securityHeaders(sameOrigin(ts.Middleware(root, mux))))
|
||||
srv := &http.Server{
|
||||
Addr: addr,
|
||||
Handler: h,
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
// Pas de ReadTimeout ni de WriteTimeout : les dépôts et téléchargements de
|
||||
// gros fichiers peuvent durer longtemps ; seule l'inactivité est bornée.
|
||||
}
|
||||
go func() {
|
||||
slog.Info("démarrage", "addr", addr, "data", dataDir, "auth", mode, "version", version,
|
||||
"history_keep", store.History.Keep, "max_upload_mb", spaces.MaxUpload>>20)
|
||||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
fatal("serveur", "err", err)
|
||||
}
|
||||
}()
|
||||
<-ctx.Done()
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
_ = srv.Shutdown(shutdownCtx)
|
||||
slog.Info("arrêt")
|
||||
}
|
||||
|
||||
// authentication prépare l'authentification locale (comptes, inscription) et/ou OIDC.
|
||||
func authentication(ctx context.Context, mode, dataDir string, accounts *auth.Accounts, store *storage.Store, h *api.Handler) (*auth.Auth, error) {
|
||||
secret, err := auth.LoadSecret(os.Getenv("SESSION_SECRET"), dataDir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ttl, err := time.ParseDuration(env("SESSION_TTL", "24h"))
|
||||
if err != nil || ttl < 5*time.Minute {
|
||||
return nil, errors.New("SESSION_TTL invalide (ex. 24h, minimum 5m)")
|
||||
}
|
||||
pub := publicURL()
|
||||
secureCookies := strings.HasPrefix(pub, "https://") || strings.HasPrefix(os.Getenv("OIDC_REDIRECT_URL"), "https://")
|
||||
sessions := auth.NewSessions(secret, ttl, secureCookies)
|
||||
h.SecureCookies = secureCookies
|
||||
|
||||
a := auth.New(&auth.Auth{
|
||||
Accounts: accounts,
|
||||
Sessions: sessions,
|
||||
Local: mode == "local" || mode == "both",
|
||||
Registration: func() string {
|
||||
if st, err := store.ReadSettings(); err == nil {
|
||||
return st.Registration
|
||||
}
|
||||
return storage.RegClosed
|
||||
},
|
||||
OIDCName: env("OIDC_NAME", "SSO"),
|
||||
})
|
||||
h.OIDCName = a.OIDCName
|
||||
|
||||
if a.Local {
|
||||
if user := os.Getenv("ADMIN_USER"); user != "" {
|
||||
pass := secretEnv("ADMIN_PASSWORD")
|
||||
if pass == "" {
|
||||
return nil, errors.New("ADMIN_USER défini sans ADMIN_PASSWORD")
|
||||
}
|
||||
if err := accounts.EnsureAdmin(user, pass); err != nil {
|
||||
return nil, fmt.Errorf("administrateur initial : %w", err)
|
||||
}
|
||||
}
|
||||
if accounts.NeedsSetup() {
|
||||
slog.Warn("aucun administrateur : le premier compte créé (inscription) le deviendra ; définir ADMIN_USER et ADMIN_PASSWORD pour l'imposer")
|
||||
}
|
||||
}
|
||||
if mode == "local" {
|
||||
return a, nil
|
||||
}
|
||||
|
||||
// OIDC
|
||||
cfg, err := oidcConfig(secret, ttl)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg.Sessions = sessions
|
||||
policy := auth.OIDCPolicy{AdminGroups: fields(os.Getenv("OIDC_ADMIN_GROUPS")), AdminEmails: fields(os.Getenv("OIDC_ADMIN_EMAILS"))}
|
||||
cfg.Provision = func(u auth.User, groups []string) (auth.User, error) {
|
||||
return accounts.UpsertOIDC(u, groups, policy)
|
||||
}
|
||||
o, err := auth.NewOIDC(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.OIDC = o
|
||||
slog.Info("authentification OIDC activée", "issuer", cfg.Issuer, "client_id", cfg.ClientID,
|
||||
"groups", cfg.AllowedGroups, "admin_groups", policy.AdminGroups, "session_ttl", ttl.String())
|
||||
return a, nil
|
||||
}
|
||||
|
||||
// publicURL est l'origine publique du service : PUBLIC_URL, sinon celle de
|
||||
// OIDC_REDIRECT_URL ; vide, elle est déduite de chaque requête.
|
||||
func publicURL() string {
|
||||
if v := os.Getenv("PUBLIC_URL"); v != "" {
|
||||
return strings.TrimRight(v, "/")
|
||||
}
|
||||
if u, err := url.Parse(os.Getenv("OIDC_REDIRECT_URL")); err == nil && u.Scheme != "" && u.Host != "" {
|
||||
return u.Scheme + "://" + u.Host
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// oidcConfig lit les variables OIDC_*.
|
||||
func oidcConfig(secret []byte, ttl time.Duration) (auth.Config, error) {
|
||||
cfg := auth.Config{
|
||||
Issuer: os.Getenv("OIDC_ISSUER"),
|
||||
ClientID: os.Getenv("OIDC_CLIENT_ID"),
|
||||
ClientSecret: secretEnv("OIDC_CLIENT_SECRET"),
|
||||
RedirectURL: os.Getenv("OIDC_REDIRECT_URL"),
|
||||
Scopes: fields(env("OIDC_SCOPES", "openid profile email")),
|
||||
GroupsClaim: env("OIDC_GROUPS_CLAIM", "groups"),
|
||||
SessionTTL: ttl,
|
||||
Secret: secret,
|
||||
}
|
||||
cfg.AllowedGroups = fields(os.Getenv("OIDC_ALLOWED_GROUPS"))
|
||||
var err error
|
||||
if cfg.EndSession, err = strconv.ParseBool(env("OIDC_LOGOUT", "true")); err != nil {
|
||||
return cfg, errors.New("OIDC_LOGOUT invalide (true ou false)")
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// fields découpe une liste séparée par des espaces ou des virgules.
|
||||
func fields(s string) []string {
|
||||
return strings.FieldsFunc(s, func(r rune) bool { return r == ' ' || r == ',' })
|
||||
}
|
||||
|
||||
func historyPolicy() (storage.HistoryPolicy, error) {
|
||||
p := storage.DefaultHistory
|
||||
keep, err := strconv.Atoi(env("HISTORY_KEEP", strconv.Itoa(p.Keep)))
|
||||
if err != nil || keep < 0 {
|
||||
return p, errors.New("HISTORY_KEEP invalide (entier >= 0)")
|
||||
}
|
||||
p.Keep = keep
|
||||
if p.Interval, err = time.ParseDuration(env("HISTORY_INTERVAL", "0")); err != nil || p.Interval < 0 {
|
||||
return p, errors.New("HISTORY_INTERVAL invalide (ex. 10m, 0 : à chaque remplacement)")
|
||||
}
|
||||
if p.MaxAge, err = time.ParseDuration(env("HISTORY_MAX_AGE", "0")); err != nil || p.MaxAge < 0 {
|
||||
return p, errors.New("HISTORY_MAX_AGE invalide (ex. 2160h, 0 : illimité)")
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func healthcheck(addr string) int {
|
||||
host, port, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return 1
|
||||
}
|
||||
if host == "" || host == "0.0.0.0" || host == "::" {
|
||||
host = "127.0.0.1"
|
||||
}
|
||||
c := http.Client{Timeout: 3 * time.Second}
|
||||
res, err := c.Get("http://" + net.JoinHostPort(host, port) + "/healthz")
|
||||
if err != nil {
|
||||
return 1
|
||||
}
|
||||
res.Body.Close()
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// spa sert le build Vite embarqué ; toute route inconnue renvoie index.html.
|
||||
func spa() http.Handler {
|
||||
dist, _ := fs.Sub(web.Dist, "dist")
|
||||
files := http.FileServerFS(dist)
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
p := path.Clean(r.URL.Path)
|
||||
if p != "/" {
|
||||
if fi, err := fs.Stat(dist, p[1:]); err == nil && !fi.IsDir() {
|
||||
// Les assets Vite sont nommés par empreinte : cache long.
|
||||
if path.Dir(p) == "/assets" {
|
||||
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
||||
}
|
||||
files.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
index, err := fs.ReadFile(dist, "index.html")
|
||||
if err != nil {
|
||||
http.Error(w, "frontend absent : lancer `npm run build` dans frontend/", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
_, _ = w.Write(index)
|
||||
})
|
||||
}
|
||||
|
||||
// public indique les chemins servis sans session : sonde, liens de partage
|
||||
// (/s/<jeton> et son API), état de la connexion (/api/me, logo : page de
|
||||
// connexion) et fichiers statiques du build (code de l'application, sans
|
||||
// aucune donnée).
|
||||
func public(p string) bool {
|
||||
switch {
|
||||
case p == "/healthz", strings.HasPrefix(p, "/s/"), strings.HasPrefix(p, "/api/public/"), p == "/api/me", p == "/api/logo":
|
||||
return true
|
||||
case strings.HasPrefix(p, "/api/"), p == "/", p == "/index.html":
|
||||
return false
|
||||
}
|
||||
dist, _ := fs.Sub(web.Dist, "dist")
|
||||
fi, err := fs.Stat(dist, strings.TrimPrefix(path.Clean(p), "/"))
|
||||
return err == nil && !fi.IsDir()
|
||||
}
|
||||
|
||||
// sameOrigin refuse les requêtes qui modifient des données et viennent d'un
|
||||
// autre site (CSRF) : l'en-tête Origin d'une requête de navigateur doit
|
||||
// désigner l'hôte du service. Les requêtes sans Origin (curl, jetons d'API)
|
||||
// ne sont pas concernées.
|
||||
func sameOrigin(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case http.MethodGet, http.MethodHead, http.MethodOptions:
|
||||
default:
|
||||
if r.Header.Get("Sec-Fetch-Site") == "cross-site" {
|
||||
http.Error(w, "origine refusée", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if o := r.Header.Get("Origin"); o != "" && o != "null" {
|
||||
host := r.Host
|
||||
if h := r.Header.Get("X-Forwarded-Host"); h != "" {
|
||||
host, _, _ = strings.Cut(h, ",")
|
||||
host = strings.TrimSpace(host)
|
||||
}
|
||||
if u, err := url.Parse(o); err != nil || !strings.EqualFold(u.Host, host) {
|
||||
http.Error(w, "origine refusée", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func securityHeaders(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
h := w.Header()
|
||||
h.Set("X-Content-Type-Options", "nosniff")
|
||||
h.Set("Referrer-Policy", "same-origin")
|
||||
h.Set("X-Frame-Options", "SAMEORIGIN")
|
||||
if strings.HasPrefix(r.URL.Path, "/s/") || strings.HasPrefix(r.URL.Path, "/api/public/") {
|
||||
h.Set("X-Robots-Tag", "noindex, nofollow") // liens de partage
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
type statusWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (s *statusWriter) WriteHeader(code int) {
|
||||
s.status = code
|
||||
s.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
// Unwrap permet à http.ResponseController (Flush, SetWriteDeadline) d'atteindre
|
||||
// l'écrivain d'origine.
|
||||
func (s *statusWriter) Unwrap() http.ResponseWriter { return s.ResponseWriter }
|
||||
|
||||
func (s *statusWriter) Flush() {
|
||||
if f, ok := s.ResponseWriter.(http.Flusher); ok {
|
||||
f.Flush()
|
||||
}
|
||||
}
|
||||
|
||||
func logRequests(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
||||
next.ServeHTTP(sw, r)
|
||||
if r.URL.Path != "/healthz" {
|
||||
// Le jeton d'un lien de partage fait partie du chemin : il n'est pas journalisé.
|
||||
p := r.URL.Path
|
||||
if strings.HasPrefix(p, "/s/") {
|
||||
p = "/s/…"
|
||||
} else if strings.HasPrefix(p, "/api/public/") {
|
||||
p = "/api/public/…"
|
||||
}
|
||||
slog.Info("http", "method", r.Method, "path", p, "status", sw.status,
|
||||
"dur_ms", time.Since(start).Milliseconds())
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSameOrigin(t *testing.T) {
|
||||
h := sameOrigin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(204) }))
|
||||
do := func(method, host string, hdr map[string]string) int {
|
||||
r := httptest.NewRequest(method, "http://"+host+"/api/file", nil)
|
||||
for k, v := range hdr {
|
||||
r.Header.Set(k, v)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
return w.Code
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
method string
|
||||
hdr map[string]string
|
||||
want int
|
||||
}{
|
||||
{"GET entre sites", "GET", map[string]string{"Origin": "https://evil.example"}, 204},
|
||||
{"PUT sans Origin (curl, jeton)", "PUT", nil, 204},
|
||||
{"PUT même origine", "PUT", map[string]string{"Origin": "https://cloud.example"}, 204},
|
||||
{"PUT autre origine", "PUT", map[string]string{"Origin": "https://evil.example"}, 403},
|
||||
{"POST cross-site", "POST", map[string]string{"Sec-Fetch-Site": "cross-site"}, 403},
|
||||
{"POST same-origin", "POST", map[string]string{"Sec-Fetch-Site": "same-origin", "Origin": "https://cloud.example"}, 204},
|
||||
{"DELETE autre origine", "DELETE", map[string]string{"Origin": "http://cloud.example.evil.org"}, 403},
|
||||
{"proxy : X-Forwarded-Host", "PUT", map[string]string{"Origin": "https://cloud.example", "X-Forwarded-Host": "cloud.example"}, 204},
|
||||
}
|
||||
for _, c := range cases {
|
||||
host := "cloud.example"
|
||||
if c.name == "proxy : X-Forwarded-Host" {
|
||||
host = "upandown:8080"
|
||||
}
|
||||
if got := do(c.method, host, c.hdr); got != c.want {
|
||||
t.Errorf("%s : %d, attendu %d", c.name, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublicPaths(t *testing.T) {
|
||||
for p, want := range map[string]bool{
|
||||
"/healthz": true, "/s/abc": true, "/api/public/abc/file": true, "/api/me": true, "/api/logo": true,
|
||||
"/api/list": false, "/api/file": false, "/api/admin/users": false, "/api/tokens": false,
|
||||
"/": false, "/index.html": false,
|
||||
} {
|
||||
if got := public(p); got != want {
|
||||
t.Errorf("public(%q) = %v", p, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSpaFallbackWithoutBuild(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
spa().ServeHTTP(w, httptest.NewRequest("GET", "/dossier/x", nil))
|
||||
if w.Code != 404 { // web/dist ne contient que .gitkeep tant que le frontend n'est pas construit
|
||||
t.Logf("spa sans build : %d (frontend construit ?)", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogRequestsHidesShareTokens(t *testing.T) {
|
||||
// Le jeton d'un lien fait partie du chemin : il ne doit pas finir dans les journaux.
|
||||
var buf bytes.Buffer
|
||||
old := slog.Default()
|
||||
slog.SetDefault(slog.New(slog.NewTextHandler(&buf, nil)))
|
||||
defer slog.SetDefault(old)
|
||||
h := logRequests(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(204) }))
|
||||
for _, p := range []string{"/s/jeton-secret", "/api/public/jeton-secret/file", "/api/list"} {
|
||||
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", p, nil))
|
||||
}
|
||||
out := buf.String()
|
||||
if strings.Contains(out, "jeton-secret") {
|
||||
t.Errorf("jeton journalisé : %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "/api/list") {
|
||||
t.Errorf("requête ordinaire non journalisée : %s", out)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
# Up And Down
|
||||
services:
|
||||
upandown:
|
||||
build: .
|
||||
image: upandown:local
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "${UPANDOWN_PORT:-8080}:8080"
|
||||
environment:
|
||||
# Authentification : local (comptes + inscription), oidc, both ou none (reverse proxy qui authentifie).
|
||||
AUTH_MODE: ${AUTH_MODE:-local}
|
||||
# Administrateur initial (mode local ou both). Sans eux, le premier compte créé le devient.
|
||||
ADMIN_USER: ${ADMIN_USER:-}
|
||||
ADMIN_PASSWORD: ${ADMIN_PASSWORD:-}
|
||||
# Inscription des comptes locaux : closed, approval (validation par un administrateur) ou open.
|
||||
# Modifiable ensuite dans l'interface (Administration > Général).
|
||||
REGISTRATION: ${REGISTRATION:-closed}
|
||||
# OIDC (AUTH_MODE=oidc ou both). URI de redirection chez le fournisseur : https://<hôte>/auth/callback
|
||||
OIDC_ISSUER: ${OIDC_ISSUER:-}
|
||||
OIDC_CLIENT_ID: ${OIDC_CLIENT_ID:-}
|
||||
OIDC_CLIENT_SECRET: ${OIDC_CLIENT_SECRET:-}
|
||||
OIDC_REDIRECT_URL: ${OIDC_REDIRECT_URL:-}
|
||||
OIDC_SCOPES: ${OIDC_SCOPES:-openid profile email}
|
||||
OIDC_NAME: ${OIDC_NAME:-SSO}
|
||||
OIDC_ALLOWED_GROUPS: ${OIDC_ALLOWED_GROUPS:-}
|
||||
OIDC_GROUPS_CLAIM: ${OIDC_GROUPS_CLAIM:-groups}
|
||||
OIDC_ADMIN_GROUPS: ${OIDC_ADMIN_GROUPS:-}
|
||||
OIDC_ADMIN_EMAILS: ${OIDC_ADMIN_EMAILS:-}
|
||||
OIDC_LOGOUT: ${OIDC_LOGOUT:-true}
|
||||
SESSION_TTL: ${SESSION_TTL:-24h}
|
||||
SESSION_SECRET: ${SESSION_SECRET:-}
|
||||
PUBLIC_URL: ${PUBLIC_URL:-}
|
||||
# Dépôts : taille maximale d'un fichier (Mo, 0 : illimité) ; quota par utilisateur (Mo, 0 : illimité).
|
||||
MAX_UPLOAD_MB: ${MAX_UPLOAD_MB:-0}
|
||||
USER_QUOTA_MB: ${USER_QUOTA_MB:-0}
|
||||
COMMON_READONLY: ${COMMON_READONLY:-false}
|
||||
TRASH_DAYS: ${TRASH_DAYS:-0}
|
||||
# Historique des versions (remplacements) : versions gardées par fichier (0 : désactivé).
|
||||
HISTORY_KEEP: ${HISTORY_KEEP:-10}
|
||||
HISTORY_INTERVAL: ${HISTORY_INTERVAL:-0}
|
||||
HISTORY_MAX_AGE: ${HISTORY_MAX_AGE:-0}
|
||||
SHARE_SECRET: ${SHARE_SECRET:-}
|
||||
volumes:
|
||||
# Bind mount : chown -R 65532:65532 ./data
|
||||
- ./data:/data
|
||||
read_only: true
|
||||
cap_drop: [ALL]
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
@@ -0,0 +1 @@
|
||||
node_modules/
|
||||
@@ -0,0 +1,23 @@
|
||||
<!doctype html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<meta name="theme-color" content="#2f6fed" />
|
||||
<meta name="robots" content="noindex" />
|
||||
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%232f6fed' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M7 18a4.5 4.5 0 0 1-.5-9 6 6 0 0 1 11.4 1.5A3.5 3.5 0 0 1 17.5 18'/%3E%3Cpath d='M9 14l3-3 3 3M12 11v9'/%3E%3C/svg%3E" />
|
||||
<title>Up And Down</title>
|
||||
<script>
|
||||
// Thème appliqué avant le premier rendu (évite un flash clair).
|
||||
try {
|
||||
var t = localStorage.getItem("udTheme");
|
||||
if (t === "dark" || t === "light") document.documentElement.dataset.theme = t;
|
||||
else if (matchMedia("(prefers-color-scheme: dark)").matches) document.documentElement.dataset.theme = "dark";
|
||||
} catch (e) {}
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+1877
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "upandown-frontend",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^19.1.0",
|
||||
"@types/react-dom": "^19.1.0",
|
||||
"@vitejs/plugin-react": "^5.0.0",
|
||||
"typescript": "^5.8.0",
|
||||
"vite": "^7.0.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
|
||||
interface Props {
|
||||
/** Bouton « … » qui a ouvert le menu : le menu s'aligne sur lui. */
|
||||
anchor: HTMLElement;
|
||||
onClose: () => void;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
const MARGIN = 8; // écart minimal avec les bords de la fenêtre
|
||||
|
||||
/**
|
||||
* Menu déroulant des actions d'un élément, ouvert sous le bouton « … » et aligné
|
||||
* sur son bord droit (au-dessus s'il manque de place en bas). Rendu dans <body>
|
||||
* pour ne pas être rogné par le défilement de la liste ; refermé par un clic
|
||||
* ailleurs, Échap, un défilement, un redimensionnement ou le choix d'une action.
|
||||
*/
|
||||
export function ActionMenu({ anchor, onClose, children }: Props) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const [pos, setPos] = useState<{ top: number; left: number } | null>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const menu = ref.current;
|
||||
if (!menu) return;
|
||||
const a = anchor.getBoundingClientRect();
|
||||
const { offsetWidth: w, offsetHeight: h } = menu;
|
||||
let top = a.bottom + 4;
|
||||
if (top + h > innerHeight - MARGIN) top = Math.max(MARGIN, a.top - 4 - h);
|
||||
const left = Math.min(Math.max(MARGIN, a.right - w), innerWidth - w - MARGIN);
|
||||
setPos({ top, left });
|
||||
}, [anchor]);
|
||||
|
||||
// Focus sur la première action une fois le menu placé (masqué, il ne le prend pas).
|
||||
useEffect(() => {
|
||||
if (pos) ref.current?.querySelector<HTMLElement>("button, a")?.focus({ preventScroll: true });
|
||||
}, [pos]);
|
||||
|
||||
useEffect(() => {
|
||||
const inside = (t: EventTarget | null) => t instanceof Node && (ref.current?.contains(t) || anchor.contains(t));
|
||||
const onDown = (ev: PointerEvent) => {
|
||||
if (!inside(ev.target)) onClose();
|
||||
};
|
||||
const onKey = (ev: KeyboardEvent) => {
|
||||
if (ev.key === "Escape") {
|
||||
// Ni désélection, ni fermeture du panneau flottant : seulement le menu.
|
||||
ev.preventDefault();
|
||||
ev.stopPropagation();
|
||||
onClose();
|
||||
anchor.focus();
|
||||
} else if (ev.key === "ArrowDown" || ev.key === "ArrowUp") {
|
||||
const items = [...(ref.current?.querySelectorAll<HTMLElement>("button, a") ?? [])];
|
||||
if (!items.length) return;
|
||||
ev.preventDefault();
|
||||
const i = items.indexOf(document.activeElement as HTMLElement);
|
||||
const next = ev.key === "ArrowDown" ? (i + 1) % items.length : (i - 1 + items.length) % items.length;
|
||||
items[next].focus();
|
||||
}
|
||||
};
|
||||
const onScroll = (ev: Event) => {
|
||||
if (!(ev.target instanceof Node && ref.current?.contains(ev.target))) onClose();
|
||||
};
|
||||
document.addEventListener("pointerdown", onDown, true);
|
||||
document.addEventListener("keydown", onKey, true);
|
||||
document.addEventListener("scroll", onScroll, true);
|
||||
window.addEventListener("resize", onClose);
|
||||
return () => {
|
||||
document.removeEventListener("pointerdown", onDown, true);
|
||||
document.removeEventListener("keydown", onKey, true);
|
||||
document.removeEventListener("scroll", onScroll, true);
|
||||
window.removeEventListener("resize", onClose);
|
||||
};
|
||||
}, [anchor, onClose]);
|
||||
|
||||
return createPortal(
|
||||
<div
|
||||
ref={ref}
|
||||
className="actions menu-popup"
|
||||
role="menu"
|
||||
style={pos ?? { top: 0, left: 0, visibility: "hidden" }}
|
||||
// Une action choisie referme le menu (après coup, pour laisser un lien de
|
||||
// téléchargement aboutir).
|
||||
onClick={(ev) => {
|
||||
if ((ev.target as HTMLElement).closest("button, a")) setTimeout(onClose);
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</div>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { api, FAVORIS, PERSO, POUBELLE, type Entry, type Me } from "./api";
|
||||
import { ActionMenu } from "./ActionMenu";
|
||||
import { Explorer } from "./Explorer";
|
||||
import { Login } from "./Login";
|
||||
import { SettingsDialog } from "./SettingsDialog";
|
||||
import { Splitter } from "./Splitter";
|
||||
import { UploadPanel } from "./UploadPanel";
|
||||
import { fmtSize, initials } from "./format";
|
||||
import {
|
||||
CloudUpIcon,
|
||||
FolderIcon,
|
||||
KeyIcon,
|
||||
LogoutIcon,
|
||||
MenuIcon,
|
||||
MoonIcon,
|
||||
SettingsIcon,
|
||||
ShareIcon,
|
||||
ShieldIcon,
|
||||
StarFilledIcon,
|
||||
SunIcon,
|
||||
TrashFullIcon,
|
||||
TrashIcon,
|
||||
UserIcon,
|
||||
UsersIcon,
|
||||
} from "./icons";
|
||||
|
||||
type Theme = "light" | "dark";
|
||||
|
||||
const initialTheme = (): Theme => (document.documentElement.dataset.theme === "dark" ? "dark" : "light");
|
||||
|
||||
const SIDEBAR_MIN = 200;
|
||||
const SIDEBAR_MAX = 420;
|
||||
const SIDEBAR_DEFAULT = 248;
|
||||
|
||||
const hashDir = () => {
|
||||
const h = location.hash.replace(/^#\/?/, "");
|
||||
try {
|
||||
return decodeURIComponent(h);
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
export default function App() {
|
||||
const [me, setMe] = useState<Me | null>(null);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
|
||||
const loadMe = useCallback(
|
||||
() =>
|
||||
api
|
||||
.me()
|
||||
.then((m) => {
|
||||
setMe(m);
|
||||
setLoadError(null);
|
||||
document.title = m.title || "Up And Down";
|
||||
})
|
||||
.catch((e) => setLoadError(e instanceof Error ? e.message : String(e))),
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
loadMe();
|
||||
}, [loadMe]);
|
||||
|
||||
// OIDC seul : pas de page de connexion locale, direction le fournisseur.
|
||||
const redirecting = !!me && !me.user && me.oidc && !me.local;
|
||||
useEffect(() => {
|
||||
if (redirecting) location.replace(`/auth/login?next=${encodeURIComponent(location.pathname + location.search + location.hash)}`);
|
||||
}, [redirecting]);
|
||||
|
||||
if (loadError) {
|
||||
return (
|
||||
<main className="login">
|
||||
<div className="login-card center">
|
||||
<p className="error">{loadError}</p>
|
||||
<button className="primary" onClick={loadMe}>
|
||||
Réessayer
|
||||
</button>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
if (!me || redirecting) return <div className="splash muted">Chargement…</div>;
|
||||
if (!me.user) return <Login me={me} onLoggedIn={loadMe} />;
|
||||
return <Shell me={me} reloadMe={loadMe} />;
|
||||
}
|
||||
|
||||
function Shell({ me, reloadMe }: { me: Me; reloadMe: () => Promise<unknown> }) {
|
||||
const [theme, setTheme] = useState<Theme>(initialTheme);
|
||||
const [dir, setDir] = useState("");
|
||||
const [goto, setGoto] = useState<{ dir: string; seq: number }>({ dir: hashDir(), seq: 0 });
|
||||
const [refreshKey, setRefreshKey] = useState(0);
|
||||
const [places, setPlaces] = useState<Entry[]>([]);
|
||||
const [drawer, setDrawer] = useState(false);
|
||||
const [settings, setSettings] = useState<"account" | "tokens" | "shares" | "general" | "users" | null>(null);
|
||||
const [userMenu, setUserMenu] = useState<HTMLElement | null>(null);
|
||||
const [sidebarW, setSidebarW] = useState(() => {
|
||||
try {
|
||||
const n = Number(localStorage.getItem("udSidebar"));
|
||||
return n >= SIDEBAR_MIN && n <= SIDEBAR_MAX ? n : SIDEBAR_DEFAULT;
|
||||
} catch {
|
||||
return SIDEBAR_DEFAULT;
|
||||
}
|
||||
});
|
||||
const [resizing, setResizing] = useState(false);
|
||||
const dirRef = useRef("");
|
||||
const title = me.title || "Up And Down";
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.dataset.theme = theme;
|
||||
try {
|
||||
localStorage.setItem("udTheme", theme);
|
||||
} catch {
|
||||
/* stockage indisponible */
|
||||
}
|
||||
}, [theme]);
|
||||
|
||||
// Dossier courant dans l'adresse (#/dossier/sous) : liens directs et bouton « précédent ».
|
||||
const onDirChange = useCallback((d: string) => {
|
||||
dirRef.current = d;
|
||||
setDir(d);
|
||||
const want = d ? `#/${d.split("/").map(encodeURIComponent).join("/")}` : "";
|
||||
if (decodeURIComponent(location.hash.replace(/^#\/?/, "")) !== d) {
|
||||
if (want) location.hash = want;
|
||||
else history.pushState(null, "", location.pathname + location.search);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const onHash = () => {
|
||||
const d = hashDir();
|
||||
if (d !== dirRef.current) setGoto((g) => ({ dir: d, seq: g.seq + 1 }));
|
||||
};
|
||||
window.addEventListener("hashchange", onHash);
|
||||
window.addEventListener("popstate", onHash);
|
||||
return () => {
|
||||
window.removeEventListener("hashchange", onHash);
|
||||
window.removeEventListener("popstate", onHash);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const go = (d: string) => {
|
||||
setGoto((g) => ({ dir: d, seq: g.seq + 1 }));
|
||||
setDrawer(false);
|
||||
};
|
||||
|
||||
// Dossiers virtuels (Favoris, Personnel, Poubelle) et leurs compteurs.
|
||||
const loadPlaces = useCallback(() => {
|
||||
api
|
||||
.list("")
|
||||
.then((es) => setPlaces(es.filter((e) => e.special)))
|
||||
.catch(() => setPlaces([]));
|
||||
}, []);
|
||||
useEffect(loadPlaces, [loadPlaces, refreshKey]);
|
||||
|
||||
const onMutated = useCallback(() => {
|
||||
loadPlaces();
|
||||
reloadMe();
|
||||
}, [loadPlaces, reloadMe]);
|
||||
|
||||
const trash = places.find((p) => p.special === "poubelle");
|
||||
const user = me.user!;
|
||||
const root = dir.split("/")[0];
|
||||
const current = root === PERSO || root === FAVORIS || root === POUBELLE ? root : "";
|
||||
|
||||
const navItem = (id: string, text: string, icon: React.ReactNode, active: boolean, badge?: number) => (
|
||||
<button className={`nav-item ${active ? "on" : ""}`} onClick={() => go(id)} aria-current={active ? "page" : undefined}>
|
||||
{icon}
|
||||
<span>{text}</span>
|
||||
{!!badge && <small className="badge">{badge}</small>}
|
||||
</button>
|
||||
);
|
||||
|
||||
const usage = me.usage;
|
||||
const pct = usage && usage.quota > 0 ? Math.min(100, Math.round((usage.used / usage.quota) * 100)) : 0;
|
||||
|
||||
return (
|
||||
<div className={`app ${resizing ? "resizing" : ""}`} style={{ ["--sidebar-w" as string]: `${sidebarW}px` }}>
|
||||
<header className="topbar">
|
||||
<button className="icon-btn menu-btn" onClick={() => setDrawer(!drawer)} aria-label="Menu" title="Menu">
|
||||
<MenuIcon />
|
||||
</button>
|
||||
<a className="brand" href="/" onClick={(e) => (e.preventDefault(), go(""))} title={title}>
|
||||
{me.logo ? <img className="logo" src={api.logoUrl(me.logo)} alt="" /> : <CloudUpIcon size={26} />}
|
||||
<span>{title}</span>
|
||||
</a>
|
||||
<span className="spacer" />
|
||||
<button className="icon-btn" onClick={() => setTheme(theme === "dark" ? "light" : "dark")} aria-label={theme === "dark" ? "Thème clair" : "Thème sombre"} title={theme === "dark" ? "Thème clair" : "Thème sombre"}>
|
||||
{theme === "dark" ? <SunIcon /> : <MoonIcon />}
|
||||
</button>
|
||||
<button className="user-btn" onClick={(e) => setUserMenu(userMenu ? null : e.currentTarget)} aria-haspopup="menu" aria-expanded={!!userMenu} title={`${user.name} (${user.id})`}>
|
||||
<span className="avatar">{initials(user.name)}</span>
|
||||
<span className="user-name">{user.name}</span>
|
||||
{me.admin && me.mode !== "none" && <ShieldIcon size={14} />}
|
||||
{!!me.pending && <small className="badge">{me.pending}</small>}
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div className="layout">
|
||||
{drawer && <div className="scrim" onClick={() => setDrawer(false)} />}
|
||||
<aside className={`sidebar ${drawer ? "open" : ""}`}>
|
||||
<nav>
|
||||
{navItem("", "Fichiers", <FolderIcon />, current === "")}
|
||||
{navItem(PERSO, "Personnel", <UserIcon />, current === PERSO)}
|
||||
{navItem(FAVORIS, "Favoris", <StarFilledIcon />, current === FAVORIS)}
|
||||
{navItem(POUBELLE, "Poubelle", trash?.count ? <TrashFullIcon /> : <TrashIcon />, current === POUBELLE, trash?.count)}
|
||||
</nav>
|
||||
<div className="sidebar-foot">
|
||||
{usage && (
|
||||
<div className="usage" title="Occupation de votre espace personnel">
|
||||
<div className="usage-text">
|
||||
<span>Espace personnel</span>
|
||||
<small className="muted">
|
||||
{fmtSize(usage.used)}
|
||||
{usage.quota > 0 ? ` / ${fmtSize(usage.quota)}` : ""}
|
||||
</small>
|
||||
</div>
|
||||
{usage.quota > 0 && (
|
||||
<div className="bar" role="progressbar" aria-valuenow={pct} aria-valuemin={0} aria-valuemax={100}>
|
||||
<span style={{ width: `${pct}%` }} className={pct >= 90 ? "err" : ""} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{me.version && me.version !== "dev" && <small className="muted">v{me.version}</small>}
|
||||
</div>
|
||||
</aside>
|
||||
<Splitter width={sidebarW} min={SIDEBAR_MIN} max={SIDEBAR_MAX} onResize={(w) => {
|
||||
const v = Math.min(SIDEBAR_MAX, Math.max(SIDEBAR_MIN, w));
|
||||
setSidebarW(v);
|
||||
try {
|
||||
localStorage.setItem("udSidebar", String(v));
|
||||
} catch {
|
||||
/* stockage indisponible */
|
||||
}
|
||||
}} onDragging={setResizing} onReset={() => setSidebarW(SIDEBAR_DEFAULT)} />
|
||||
<main className="main">
|
||||
<Explorer
|
||||
me={me}
|
||||
refreshKey={refreshKey}
|
||||
goto={goto}
|
||||
onDirChange={onDirChange}
|
||||
onMutated={onMutated}
|
||||
toolbarStart={
|
||||
<button className="icon-btn menu-btn-inline" onClick={() => setDrawer(true)} aria-label="Menu" title="Menu">
|
||||
<MenuIcon />
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<UploadPanel />
|
||||
|
||||
{userMenu && (
|
||||
<ActionMenu anchor={userMenu} onClose={() => setUserMenu(null)}>
|
||||
<div className="menu-head">
|
||||
<strong>{user.name}</strong>
|
||||
<small className="muted">{user.email || user.id}</small>
|
||||
<small className="muted">{me.admin && me.mode !== "none" ? "Administrateur" : ""}</small>
|
||||
</div>
|
||||
<hr />
|
||||
<button role="menuitem" onClick={() => setSettings("account")}>
|
||||
<SettingsIcon />
|
||||
Paramètres
|
||||
</button>
|
||||
<button role="menuitem" onClick={() => setSettings("tokens")}>
|
||||
<KeyIcon />
|
||||
Jetons d'API
|
||||
</button>
|
||||
<button role="menuitem" onClick={() => setSettings("shares")}>
|
||||
<ShareIcon />
|
||||
Mes partages
|
||||
</button>
|
||||
{me.admin && me.mode !== "none" && (
|
||||
<>
|
||||
<hr />
|
||||
<button role="menuitem" onClick={() => setSettings("users")}>
|
||||
<UsersIcon />
|
||||
Utilisateurs{!!me.pending && ` (${me.pending} en attente)`}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{me.admin && (
|
||||
<button role="menuitem" onClick={() => setSettings("general")}>
|
||||
<ShieldIcon />
|
||||
Administration
|
||||
</button>
|
||||
)}
|
||||
{me.logout && (
|
||||
<>
|
||||
<hr />
|
||||
<a role="menuitem" href={me.logout}>
|
||||
<LogoutIcon />
|
||||
Se déconnecter
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
</ActionMenu>
|
||||
)}
|
||||
|
||||
{settings && (
|
||||
<SettingsDialog
|
||||
me={me}
|
||||
initialTab={settings}
|
||||
onClose={() => setSettings(null)}
|
||||
onChanged={() => {
|
||||
reloadMe();
|
||||
setRefreshKey((k) => k + 1);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { api, dirname, displayPath, type Entry } from "./api";
|
||||
import { CloseIcon, DownloadIcon, EyeIcon, FolderIcon, HistoryIcon, ShareIcon, StarFilledIcon, StarIcon } from "./icons";
|
||||
import { FolderGlyph } from "./folderIcons";
|
||||
import { FileGlyph, Thumb, thumbSource } from "./FileGlyph";
|
||||
import { previewable, typeLabel } from "./filetypes";
|
||||
import { fmtDate, fmtSize, plural, who } from "./format";
|
||||
|
||||
interface Props {
|
||||
entry: Entry;
|
||||
onClose: () => void;
|
||||
onOpen: (e: Entry) => void;
|
||||
onShare: (e: Entry) => void;
|
||||
onHistory: (e: Entry) => void;
|
||||
onFavorite: (e: Entry) => void;
|
||||
onTag: (t: string) => void;
|
||||
onLocate: (dir: string) => void;
|
||||
}
|
||||
|
||||
const Row = ({ label, children }: { label: string; children: React.ReactNode }) => (
|
||||
<div className="detail-row">
|
||||
<dt>{label}</dt>
|
||||
<dd>{children}</dd>
|
||||
</div>
|
||||
);
|
||||
|
||||
/** Panneau Détails : propriétés d'un fichier ou d'un dossier, actions rapides. */
|
||||
export function DetailsPanel({ entry: e, onClose, onOpen, onShare, onHistory, onFavorite, onTag, onLocate }: Props) {
|
||||
const d = e.details ?? {};
|
||||
const [hash, setHash] = useState<string | null>(null);
|
||||
const [hashing, setHashing] = useState(false);
|
||||
const [hashError, setHashError] = useState<string | null>(null);
|
||||
const by = who(e.editedBy);
|
||||
|
||||
useEffect(() => {
|
||||
setHash(null);
|
||||
setHashError(null);
|
||||
}, [e.path, e.modTime]);
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (ev: KeyboardEvent) => ev.key === "Escape" && onClose();
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [onClose]);
|
||||
|
||||
const computeHash = async () => {
|
||||
setHashing(true);
|
||||
setHashError(null);
|
||||
try {
|
||||
setHash(await api.hash(e.path));
|
||||
} catch (err) {
|
||||
setHashError(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
setHashing(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<aside className="details" aria-label={`Détails de ${e.name}`}>
|
||||
<header>
|
||||
<strong title={e.name}>{e.name}</strong>
|
||||
<button className="icon-btn" onClick={onClose} aria-label="Fermer les détails" title="Fermer (Échap)">
|
||||
<CloseIcon />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div className="details-preview">
|
||||
{e.isDir ? (
|
||||
<span className="icon folder big">
|
||||
<FolderGlyph name={e.icon} size={64} />
|
||||
</span>
|
||||
) : (
|
||||
<Thumb
|
||||
name={e.name}
|
||||
glyph={64}
|
||||
src={thumbSource(
|
||||
e.name,
|
||||
e.size,
|
||||
() => api.thumbUrl(e.path, e.modTime),
|
||||
() => api.downloadUrl(e.path, true),
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="details-actions">
|
||||
{e.isDir ? (
|
||||
<>
|
||||
<button onClick={() => onOpen(e)}>
|
||||
<FolderIcon />
|
||||
<span>Ouvrir</span>
|
||||
</button>
|
||||
<a className="ex-btn" href={api.zipUrl(e.path)} title="Télécharger le dossier en ZIP">
|
||||
<DownloadIcon />
|
||||
<span>ZIP</span>
|
||||
</a>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{previewable(e.name) && (
|
||||
<button onClick={() => onOpen(e)}>
|
||||
<EyeIcon />
|
||||
<span>Aperçu</span>
|
||||
</button>
|
||||
)}
|
||||
<a className="ex-btn" href={api.downloadUrl(e.path)} download={e.name}>
|
||||
<DownloadIcon />
|
||||
<span>Télécharger</span>
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
<button onClick={() => onShare(e)}>
|
||||
<ShareIcon />
|
||||
<span>Partager</span>
|
||||
</button>
|
||||
{!e.isDir && (
|
||||
<button onClick={() => onHistory(e)}>
|
||||
<HistoryIcon />
|
||||
<span>Historique</span>
|
||||
</button>
|
||||
)}
|
||||
<button onClick={() => onFavorite(e)} aria-pressed={!!e.favorite}>
|
||||
{e.favorite ? <StarFilledIcon /> : <StarIcon />}
|
||||
<span>{e.favorite ? "Favori" : "Ajouter aux favoris"}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<dl>
|
||||
<Row label="Type">{e.isDir ? "Dossier" : typeLabel(e.name)}</Row>
|
||||
{!e.isDir && <Row label="Taille">{`${fmtSize(e.size)}${e.size >= 1024 ? ` (${e.size.toLocaleString()} octets)` : ""}`}</Row>}
|
||||
{e.isDir && d.total !== undefined && (
|
||||
<Row label="Contenu">
|
||||
{plural(d.count ?? 0, "fichier")} · {fmtSize(d.total)}
|
||||
{!!d.dirs && ` · ${plural(d.dirs, "sous-dossier")}`}
|
||||
</Row>
|
||||
)}
|
||||
{!!d.width && <Row label="Dimensions">{`${d.width} × ${d.height} px`}</Row>}
|
||||
<Row label="Modifié">{fmtDate(e.modTime)}{by && ` par ${by}`}</Row>
|
||||
{d.created && (
|
||||
<Row label="Créé">
|
||||
{fmtDate(d.created)}
|
||||
{who(d.createdBy) && ` par ${who(d.createdBy)}`}
|
||||
</Row>
|
||||
)}
|
||||
<Row label="Emplacement">
|
||||
<button className="link" onClick={() => onLocate(dirname(e.path))}>
|
||||
{displayPath(dirname(e.path)) || "Racine"}
|
||||
</button>
|
||||
</Row>
|
||||
{!e.isDir && !!d.versions && <Row label="Versions">{d.versions}</Row>}
|
||||
{!!d.shares && <Row label="Partages actifs">{d.shares}</Row>}
|
||||
{!!e.tags?.length && (
|
||||
<Row label="Tags">
|
||||
<span className="chips">
|
||||
{e.tags.map((t) => (
|
||||
<button key={t} className="chip" onClick={() => onTag(t)} title={`Filtrer sur « ${t} »`}>
|
||||
{t}
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
</Row>
|
||||
)}
|
||||
{!e.isDir && (
|
||||
<Row label="SHA-256">
|
||||
{hash ? (
|
||||
<code className="hash">{hash}</code>
|
||||
) : (
|
||||
<button className="link" disabled={hashing} onClick={computeHash}>
|
||||
{hashing ? "Calcul…" : "Calculer"}
|
||||
</button>
|
||||
)}
|
||||
{hashError && <span className="error-text"> {hashError}</span>}
|
||||
</Row>
|
||||
)}
|
||||
</dl>
|
||||
{!e.isDir && (
|
||||
<div className="details-foot muted">
|
||||
<FileGlyph name={e.name} size={14} /> {e.path.startsWith(".perso") ? "Espace personnel" : "Arborescence commune"}
|
||||
</div>
|
||||
)}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
function useEscape(onClose: () => void) {
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [onClose]);
|
||||
}
|
||||
|
||||
interface PromptProps {
|
||||
title: string;
|
||||
label?: string;
|
||||
initial?: string;
|
||||
placeholder?: string;
|
||||
submit?: string;
|
||||
/** Sélectionne seulement le nom, sans l'extension (renommage d'un fichier). */
|
||||
stem?: boolean;
|
||||
onSubmit: (value: string) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
/** Saisie d'un nom (nouveau dossier, renommage), à la place de prompt(). */
|
||||
export function PromptDialog({ title, label, initial = "", placeholder, submit = "Valider", stem, onSubmit, onClose }: PromptProps) {
|
||||
const [value, setValue] = useState(initial);
|
||||
const ref = useRef<HTMLInputElement>(null);
|
||||
useEscape(onClose);
|
||||
|
||||
useEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
el.focus();
|
||||
const dot = initial.lastIndexOf(".");
|
||||
el.setSelectionRange(0, stem && dot > 0 ? dot : initial.length);
|
||||
}, [initial, stem]);
|
||||
|
||||
const trimmed = value.trim();
|
||||
return (
|
||||
<div className="modal-backdrop" onClick={onClose}>
|
||||
<form
|
||||
className="modal small"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={title}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (trimmed) onSubmit(trimmed);
|
||||
}}
|
||||
>
|
||||
<h3>{title}</h3>
|
||||
<label className="field">
|
||||
{label && <span>{label}</span>}
|
||||
<input ref={ref} value={value} placeholder={placeholder} maxLength={255} onChange={(e) => setValue(e.target.value)} />
|
||||
</label>
|
||||
<div className="modal-actions">
|
||||
<span className="spacer" />
|
||||
<button type="button" onClick={onClose}>
|
||||
Annuler
|
||||
</button>
|
||||
<button type="submit" className="primary" disabled={!trimmed || trimmed === initial}>
|
||||
{submit}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ConfirmProps {
|
||||
title: string;
|
||||
children: ReactNode;
|
||||
confirm: string;
|
||||
danger?: boolean;
|
||||
onConfirm: () => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
/** Confirmation d'une action destructrice, à la place de confirm(). */
|
||||
export function ConfirmDialog({ title, children, confirm, danger, onConfirm, onClose }: ConfirmProps) {
|
||||
useEscape(onClose);
|
||||
return (
|
||||
<div className="modal-backdrop" onClick={onClose}>
|
||||
<div className="modal small" role="alertdialog" aria-modal="true" aria-label={title} onClick={(e) => e.stopPropagation()}>
|
||||
<h3>{title}</h3>
|
||||
<div className="modal-text">{children}</div>
|
||||
<div className="modal-actions">
|
||||
<span className="spacer" />
|
||||
<button onClick={onClose}>Annuler</button>
|
||||
<button autoFocus className={danger ? "primary danger-fill" : "primary"} onClick={onConfirm}>
|
||||
{confirm}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,64 @@
|
||||
import { useState } from "react";
|
||||
import {
|
||||
FileCodeIcon,
|
||||
FileIcon,
|
||||
FileImageIcon,
|
||||
FileMusicIcon,
|
||||
FilePdfIcon,
|
||||
FileSheetIcon,
|
||||
FileSlidesIcon,
|
||||
FileTextIcon,
|
||||
FileVideoIcon,
|
||||
FileZipIcon,
|
||||
} from "./icons";
|
||||
import { browserImage, kindOf, serverThumb, type Kind } from "./filetypes";
|
||||
|
||||
const glyphs: Record<Kind, ReturnType<typeof FileIcon>["type"] | ((p: { size?: number }) => React.ReactElement)> = {
|
||||
image: FileImageIcon,
|
||||
video: FileVideoIcon,
|
||||
audio: FileMusicIcon,
|
||||
pdf: FilePdfIcon,
|
||||
text: FileTextIcon,
|
||||
code: FileCodeIcon,
|
||||
archive: FileZipIcon,
|
||||
doc: FileTextIcon,
|
||||
sheet: FileSheetIcon,
|
||||
slides: FileSlidesIcon,
|
||||
other: FileIcon,
|
||||
};
|
||||
|
||||
/** Icône d'un fichier d'après son type, colorée par famille (classe k-<type>). */
|
||||
export function FileGlyph({ name, size = 20 }: { name: string; size?: number }) {
|
||||
const kind = kindOf(name);
|
||||
const Icon = glyphs[kind] as (p: { size?: number }) => React.ReactElement;
|
||||
return (
|
||||
<span className={`fileglyph k-${kind}`} aria-hidden>
|
||||
<Icon size={size} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** Taille au-delà de laquelle une image n'est pas chargée telle quelle comme miniature. */
|
||||
const MAX_DIRECT = 12 << 20;
|
||||
|
||||
/**
|
||||
* Adresse d'une miniature : miniature du serveur pour JPEG, PNG et GIF, l'image
|
||||
* elle-même pour les autres formats du navigateur (WebP, SVG...) si elle est
|
||||
* raisonnable, sinon rien (icône de type).
|
||||
*/
|
||||
export const thumbSource = (name: string, size: number, thumb: () => string, direct: () => string): string | null => {
|
||||
if (serverThumb(name)) return thumb();
|
||||
if (browserImage(name) && size <= MAX_DIRECT) return direct();
|
||||
return null;
|
||||
};
|
||||
|
||||
/** Miniature d'image avec repli sur l'icône du type (format illisible, erreur de chargement). */
|
||||
export function Thumb({ name, src, glyph = 40, className = "" }: { name: string; src: string | null; glyph?: number; className?: string }) {
|
||||
const [failed, setFailed] = useState<string | null>(null);
|
||||
const ok = src && failed !== src;
|
||||
return (
|
||||
<span className={`thumb ${ok ? "" : "ph"} ${className}`} aria-hidden>
|
||||
{ok ? <img src={src} alt="" loading="lazy" decoding="async" draggable={false} onError={() => setFailed(src)} /> : <FileGlyph name={name} size={glyph} />}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { api, type Version } from "./api";
|
||||
import { DownloadIcon, HistoryIcon, RestoreIcon } from "./icons";
|
||||
import { fmtDate, fmtRelative, fmtSize } from "./format";
|
||||
|
||||
interface Props {
|
||||
path: string;
|
||||
name: string;
|
||||
onClose: () => void;
|
||||
/** Appelé après une restauration (le fichier a changé). */
|
||||
onChanged: () => void;
|
||||
}
|
||||
|
||||
/** Versions antérieures d'un fichier : téléchargement, restauration, création d'une version à la demande. */
|
||||
export function HistoryDialog({ path, name, onClose, onChanged }: Props) {
|
||||
const [versions, setVersions] = useState<Version[] | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [notice, setNotice] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(() => api.history(path).then(setVersions).catch((e) => setError(e.message)), [path]);
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [onClose]);
|
||||
|
||||
const run = async (fn: () => Promise<unknown>, done?: string) => {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setNotice(null);
|
||||
try {
|
||||
await fn();
|
||||
await load();
|
||||
if (done) setNotice(done);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="modal-backdrop" onClick={onClose}>
|
||||
<div className="modal" role="dialog" aria-modal="true" aria-label={`Historique de ${name}`} onClick={(e) => e.stopPropagation()}>
|
||||
<h3>Historique · {name}</h3>
|
||||
<p className="muted small-text">
|
||||
Quand un fichier est remplacé, son contenu précédent est conservé ici. Restaurer une version garde l'état actuel dans l'historique : l'opération s'annule.
|
||||
</p>
|
||||
{error && <div className="error">{error}</div>}
|
||||
{notice && <div className="notice">{notice}</div>}
|
||||
<ul className="versions">
|
||||
{versions?.map((v) => (
|
||||
<li key={v.id}>
|
||||
<HistoryIcon size={16} />
|
||||
<div className="grow">
|
||||
<span title={fmtDate(v.time)}>{fmtRelative(v.time)}</span>
|
||||
<small className="muted">
|
||||
{" "}
|
||||
· {fmtDate(v.time)} · {fmtSize(v.size)}
|
||||
</small>
|
||||
</div>
|
||||
<a className="icon-btn" href={api.versionUrl(path, v.id)} download={name} title="Télécharger cette version" aria-label="Télécharger cette version">
|
||||
<DownloadIcon />
|
||||
</a>
|
||||
<button
|
||||
disabled={busy}
|
||||
title="Remplacer le fichier par cette version"
|
||||
onClick={() =>
|
||||
run(async () => {
|
||||
await api.restore(path, v.id);
|
||||
onChanged();
|
||||
}, "Version restaurée.")
|
||||
}
|
||||
>
|
||||
<RestoreIcon />
|
||||
<span>Restaurer</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
{versions && versions.length === 0 && <li className="muted empty">Aucune version antérieure.</li>}
|
||||
{!versions && !error && <li className="muted empty">Chargement…</li>}
|
||||
</ul>
|
||||
<div className="modal-actions">
|
||||
<button disabled={busy} onClick={() => run(() => api.snapshot(path), "Version créée.")} title="Fixer l'état actuel comme version">
|
||||
<HistoryIcon />
|
||||
<span>Créer une version</span>
|
||||
</button>
|
||||
<span className="spacer" />
|
||||
<button onClick={onClose}>Fermer</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { api, type Entry } from "./api";
|
||||
import { FOLDER_ICONS, FolderGlyph } from "./folderIcons";
|
||||
|
||||
interface Props {
|
||||
/** Dossiers concernés. */
|
||||
items: Entry[];
|
||||
/** Appelé après le changement pour rafraîchir l'explorateur. */
|
||||
onChanged: () => Promise<void>;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
/** Choix de l'icône d'un ou plusieurs dossiers (partagée par tous les utilisateurs). */
|
||||
export function IconDialog({ items, onChanged, onClose }: Props) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
// Icône commune aux dossiers (sinon aucune n'est marquée).
|
||||
const current = items.every((e) => (e.icon ?? "") === (items[0].icon ?? "")) ? (items[0].icon ?? "") : null;
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [onClose]);
|
||||
|
||||
const choose = async (name: string) => {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api.setIcon(
|
||||
items.map((e) => e.path),
|
||||
name,
|
||||
);
|
||||
await onChanged();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e));
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const title = items.length === 1 ? `Icône · ${items[0].name}` : `Icône · ${items.length} dossiers`;
|
||||
const choice = (name: string, label: string) => (
|
||||
<button
|
||||
key={name || "default"}
|
||||
className={`folder-icon-choice${current === name ? " current" : ""}`}
|
||||
disabled={busy}
|
||||
onClick={() => choose(name)}
|
||||
title={label}
|
||||
aria-label={label}
|
||||
aria-pressed={current === name}
|
||||
>
|
||||
<span className="folder">
|
||||
<FolderGlyph name={name} size={24} />
|
||||
</span>
|
||||
<small>{label}</small>
|
||||
</button>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="modal-backdrop" onClick={onClose}>
|
||||
<div className="modal icon-dialog" role="dialog" aria-modal="true" aria-label={title} onClick={(e) => e.stopPropagation()}>
|
||||
<h3>{title}</h3>
|
||||
<div className="folder-icon-grid">
|
||||
{choice("", "Par défaut")}
|
||||
{FOLDER_ICONS.map((i) => choice(i.name, i.label))}
|
||||
</div>
|
||||
{error && <div className="error">{error}</div>}
|
||||
<div className="modal-actions">
|
||||
<span className="spacer" />
|
||||
<button onClick={onClose}>Fermer</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import { useState } from "react";
|
||||
import { api, ApiError, type Me } from "./api";
|
||||
import { CloudUpIcon } from "./icons";
|
||||
|
||||
interface Props {
|
||||
me: Me;
|
||||
/** Connexion ou inscription réussie (session ouverte) : recharge l'application. */
|
||||
onLoggedIn: () => void;
|
||||
}
|
||||
|
||||
/** Page de connexion : compte local, inscription (selon le mode choisi par l'administrateur) et bouton OIDC. */
|
||||
export function Login({ me, onLoggedIn }: Props) {
|
||||
const canRegister = me.local && (me.registration !== "closed" || !!me.setup);
|
||||
const [mode, setMode] = useState<"login" | "register">(me.setup ? "register" : "login");
|
||||
const [f, setF] = useState({ username: "", name: "", email: "", password: "", confirm: "" });
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [info, setInfo] = useState<string | null>(null);
|
||||
const title = me.title || "Up And Down";
|
||||
const next = encodeURIComponent(location.pathname + location.search + location.hash);
|
||||
|
||||
const set = (k: keyof typeof f) => (e: React.ChangeEvent<HTMLInputElement>) => setF({ ...f, [k]: e.target.value });
|
||||
|
||||
const submit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setInfo(null);
|
||||
if (mode === "register" && f.password !== f.confirm) {
|
||||
setError("Les deux mots de passe sont différents.");
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
if (mode === "login") {
|
||||
await api.login(f.username, f.password);
|
||||
onLoggedIn();
|
||||
} else {
|
||||
const status = await api.register({ username: f.username, name: f.name, email: f.email, password: f.password });
|
||||
if (status === "pending") {
|
||||
setInfo("Compte créé. Un administrateur doit le valider avant votre première connexion.");
|
||||
setMode("login");
|
||||
setF({ ...f, password: "", confirm: "" });
|
||||
} else onLoggedIn();
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.code === "pending") setInfo("Votre compte est en attente de validation par un administrateur.");
|
||||
else setError(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="login">
|
||||
<div className="login-card">
|
||||
<div className="login-brand">
|
||||
{me.logo ? <img src={api.logoUrl(me.logo)} alt="" className="logo" /> : <CloudUpIcon size={36} />}
|
||||
<h1>{title}</h1>
|
||||
<p className="muted">Envoyez, rangez et partagez vos fichiers.</p>
|
||||
</div>
|
||||
|
||||
{me.setup && (
|
||||
<div className="notice">
|
||||
<strong>Première utilisation.</strong> Le compte créé ici devient l'administrateur.
|
||||
</div>
|
||||
)}
|
||||
{info && <div className="notice">{info}</div>}
|
||||
{error && <div className="error">{error}</div>}
|
||||
|
||||
{me.local && (
|
||||
<form onSubmit={submit} className="form">
|
||||
{canRegister && !me.setup && (
|
||||
<div className="tabs" role="tablist">
|
||||
<button type="button" role="tab" aria-selected={mode === "login"} className={mode === "login" ? "on" : ""} onClick={() => setMode("login")}>
|
||||
Connexion
|
||||
</button>
|
||||
<button type="button" role="tab" aria-selected={mode === "register"} className={mode === "register" ? "on" : ""} onClick={() => setMode("register")}>
|
||||
Créer un compte
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<label className="field">
|
||||
<span>Identifiant</span>
|
||||
<input autoFocus autoComplete="username" autoCapitalize="none" spellCheck={false} required value={f.username} onChange={set("username")} />
|
||||
</label>
|
||||
{mode === "register" && (
|
||||
<>
|
||||
<label className="field">
|
||||
<span>Nom affiché (facultatif)</span>
|
||||
<input autoComplete="name" maxLength={80} value={f.name} onChange={set("name")} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Adresse e-mail (facultatif)</span>
|
||||
<input type="email" autoComplete="email" maxLength={120} value={f.email} onChange={set("email")} />
|
||||
</label>
|
||||
</>
|
||||
)}
|
||||
<label className="field">
|
||||
<span>{mode === "register" ? "Mot de passe (10 caractères minimum)" : "Mot de passe"}</span>
|
||||
<input type="password" required minLength={mode === "register" ? 10 : undefined} autoComplete={mode === "login" ? "current-password" : "new-password"} value={f.password} onChange={set("password")} />
|
||||
</label>
|
||||
{mode === "register" && (
|
||||
<label className="field">
|
||||
<span>Confirmer le mot de passe</span>
|
||||
<input type="password" required autoComplete="new-password" value={f.confirm} onChange={set("confirm")} />
|
||||
</label>
|
||||
)}
|
||||
<button className="primary big" type="submit" disabled={busy}>
|
||||
{mode === "login" ? "Se connecter" : me.setup ? "Créer l'administrateur" : "Créer mon compte"}
|
||||
</button>
|
||||
{mode === "register" && me.registration === "approval" && !me.setup && <p className="muted small-text">Votre compte devra être validé par un administrateur.</p>}
|
||||
</form>
|
||||
)}
|
||||
|
||||
{me.oidc && (
|
||||
<>
|
||||
{me.local && <div className="or">ou</div>}
|
||||
<a className="ex-btn big" href={`/auth/login?next=${next}`}>
|
||||
Se connecter avec {me.oidcName || "SSO"}
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { api, basename, dirname, join, label, type Entry } from "./api";
|
||||
import { FolderIcon, FolderPlusIcon } from "./icons";
|
||||
import { PromptDialog } from "./Dialogs";
|
||||
|
||||
interface Props {
|
||||
/** Éléments à déplacer. */
|
||||
paths: string[];
|
||||
startDir: string;
|
||||
onCancel: () => void;
|
||||
onConfirm: (dir: string) => void;
|
||||
}
|
||||
|
||||
/** Sélecteur de dossier de destination (utilisable au doigt comme à la souris). */
|
||||
export function MoveDialog({ paths, startDir, onCancel, onConfirm }: Props) {
|
||||
const [dir, setDir] = useState(startDir);
|
||||
const [folders, setFolders] = useState<Entry[]>([]);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [naming, setNaming] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
setError(null);
|
||||
api
|
||||
.list(dir)
|
||||
.then((es) => live && setFolders(es.filter((e) => e.isDir && e.special !== "favoris" && e.special !== "poubelle")))
|
||||
.catch((e) => live && setError(e.message));
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [dir]);
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => e.key === "Escape" && !naming && onCancel();
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [onCancel, naming]);
|
||||
|
||||
// Un dossier déplacé ne peut pas recevoir son propre contenu.
|
||||
const blocked = (p: string) => paths.some((m) => p === m || p.startsWith(m + "/"));
|
||||
const crumbs = dir ? dir.split("/") : [];
|
||||
|
||||
const newFolder = async (name: string) => {
|
||||
setNaming(false);
|
||||
try {
|
||||
const e = await api.mkdir(join(dir, name));
|
||||
setDir(e.path);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
};
|
||||
|
||||
const title = paths.length === 1 ? `Déplacer « ${basename(paths[0])} »` : `Déplacer ${paths.length} éléments`;
|
||||
|
||||
return (
|
||||
<div className="modal-backdrop" onClick={onCancel}>
|
||||
<div className="modal" role="dialog" aria-modal="true" aria-label={title} onClick={(e) => e.stopPropagation()}>
|
||||
<h3>{title}</h3>
|
||||
<nav className="crumbs">
|
||||
<button onClick={() => setDir("")}>Racine</button>
|
||||
{crumbs.map((c, i) => {
|
||||
const p = crumbs.slice(0, i + 1).join("/");
|
||||
return (
|
||||
<span key={p}>
|
||||
<span className="muted"> / </span>
|
||||
<button onClick={() => setDir(p)}>{label(c)}</button>
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
{error && <div className="error">{error}</div>}
|
||||
<ul className="folders">
|
||||
{folders.map((f) => (
|
||||
<li key={f.path}>
|
||||
<button disabled={blocked(f.path)} onClick={() => setDir(f.path)}>
|
||||
<span className="folder">
|
||||
<FolderIcon />
|
||||
</span>
|
||||
{f.name}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
{folders.length === 0 && <li className="muted empty">Aucun sous-dossier</li>}
|
||||
</ul>
|
||||
<div className="modal-actions">
|
||||
<button onClick={() => setNaming(true)}>
|
||||
<FolderPlusIcon />
|
||||
<span>Dossier</span>
|
||||
</button>
|
||||
<span className="spacer" />
|
||||
<button onClick={onCancel}>Annuler</button>
|
||||
<button className="primary" disabled={blocked(dir) || paths.every((p) => dirname(p) === dir)} onClick={() => onConfirm(dir)}>
|
||||
Déplacer ici
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{naming && <PromptDialog title="Nouveau dossier" label="Nom du dossier" submit="Créer" onSubmit={newFolder} onClose={() => setNaming(false)} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { ChevronLeftIcon, ChevronRightIcon, CloseIcon, DownloadIcon, ExpandIcon } from "./icons";
|
||||
import { FileGlyph } from "./FileGlyph";
|
||||
import { kindOf, monospace, previewable, typeLabel } from "./filetypes";
|
||||
import { fmtDate, fmtSize } from "./format";
|
||||
|
||||
/** Fichier à prévisualiser : adresses d'affichage et de téléchargement fournies par l'appelant. */
|
||||
export interface PreviewFile {
|
||||
name: string;
|
||||
size: number;
|
||||
modTime: string;
|
||||
/** Adresse d'affichage en ligne (images, vidéo, PDF). */
|
||||
src: string;
|
||||
download: string;
|
||||
/** Lit le début du contenu texte. */
|
||||
text: () => Promise<{ text: string; truncated: boolean }>;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
files: PreviewFile[];
|
||||
index: number;
|
||||
onIndex: (i: number) => void;
|
||||
onClose: () => void;
|
||||
/** Boutons supplémentaires de la barre (partage, détails...). */
|
||||
actions?: (file: PreviewFile) => ReactNode;
|
||||
}
|
||||
|
||||
/** Visionneuse plein écran : image, vidéo, audio, PDF, texte ; navigation ←/→ entre les fichiers du dossier. */
|
||||
export function Preview({ files, index, onIndex, onClose, actions }: Props) {
|
||||
const file = files[index];
|
||||
const many = files.length > 1;
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if ((e.target as HTMLElement).tagName === "INPUT") return;
|
||||
if (e.key === "Escape") onClose();
|
||||
else if (e.key === "ArrowLeft" && index > 0) onIndex(index - 1);
|
||||
else if (e.key === "ArrowRight" && index < files.length - 1) onIndex(index + 1);
|
||||
else return;
|
||||
e.preventDefault();
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [index, files.length, onIndex, onClose]);
|
||||
|
||||
if (!file) return null;
|
||||
return createPortal(
|
||||
<div className="preview" role="dialog" aria-modal="true" aria-label={`Aperçu de ${file.name}`}>
|
||||
<header className="preview-bar">
|
||||
<button className="icon-btn" onClick={onClose} aria-label="Fermer l'aperçu" title="Fermer (Échap)">
|
||||
<CloseIcon />
|
||||
</button>
|
||||
<FileGlyph name={file.name} size={18} />
|
||||
<div className="preview-title">
|
||||
<strong title={file.name}>{file.name}</strong>
|
||||
<small className="muted">
|
||||
{typeLabel(file.name)} · {fmtSize(file.size)} · {fmtDate(file.modTime)}
|
||||
{many && ` · ${index + 1}/${files.length}`}
|
||||
</small>
|
||||
</div>
|
||||
<span className="spacer" />
|
||||
{actions?.(file)}
|
||||
<a className="ex-btn" href={file.download} download={file.name} title="Télécharger">
|
||||
<DownloadIcon />
|
||||
<span>Télécharger</span>
|
||||
</a>
|
||||
</header>
|
||||
<div className="preview-body" onClick={(e) => e.target === e.currentTarget && onClose()}>
|
||||
{many && index > 0 && (
|
||||
<button className="nav prev" onClick={() => onIndex(index - 1)} aria-label="Fichier précédent" title="Précédent (←)">
|
||||
<ChevronLeftIcon size={24} />
|
||||
</button>
|
||||
)}
|
||||
<Viewer key={file.src} file={file} />
|
||||
{many && index < files.length - 1 && (
|
||||
<button className="nav next" onClick={() => onIndex(index + 1)} aria-label="Fichier suivant" title="Suivant (→)">
|
||||
<ChevronRightIcon size={24} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
|
||||
function Viewer({ file }: { file: PreviewFile }) {
|
||||
const kind = kindOf(file.name);
|
||||
const [zoom, setZoom] = useState(false);
|
||||
const [error, setError] = useState(false);
|
||||
|
||||
if (!previewable(file.name) || error) {
|
||||
return (
|
||||
<div className="preview-none">
|
||||
<FileGlyph name={file.name} size={72} />
|
||||
<p>
|
||||
<strong>{file.name}</strong>
|
||||
</p>
|
||||
<p className="muted">{error ? "Impossible d'afficher ce fichier dans le navigateur." : "Pas d'aperçu pour ce type de fichier."}</p>
|
||||
<a className="ex-btn primary" href={file.download} download={file.name}>
|
||||
<DownloadIcon />
|
||||
<span>Télécharger ({fmtSize(file.size)})</span>
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
switch (kind) {
|
||||
case "image":
|
||||
return (
|
||||
<div className={`viewer-image ${zoom ? "zoom" : ""}`}>
|
||||
<img src={file.src} alt={file.name} onClick={() => setZoom((z) => !z)} onError={() => setError(true)} draggable={false} />
|
||||
<button className="icon-btn zoom-btn" onClick={() => setZoom((z) => !z)} title={zoom ? "Ajuster à la fenêtre" : "Taille réelle"} aria-label="Zoom">
|
||||
<ExpandIcon />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
case "video":
|
||||
return <video className="viewer-media" src={file.src} controls autoPlay playsInline onError={() => setError(true)} />;
|
||||
case "audio":
|
||||
return (
|
||||
<div className="viewer-audio">
|
||||
<FileGlyph name={file.name} size={64} />
|
||||
<p>{file.name}</p>
|
||||
<audio src={file.src} controls autoPlay onError={() => setError(true)} />
|
||||
</div>
|
||||
);
|
||||
case "pdf":
|
||||
return <iframe className="viewer-pdf" src={file.src} title={file.name} />;
|
||||
default:
|
||||
return <TextViewer file={file} onError={() => setError(true)} />;
|
||||
}
|
||||
}
|
||||
|
||||
function TextViewer({ file, onError }: { file: PreviewFile; onError: () => void }) {
|
||||
const [state, setState] = useState<{ text: string; truncated: boolean } | null>(null);
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
file
|
||||
.text()
|
||||
.then((t) => live && setState(t))
|
||||
.catch(() => live && onError());
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [file.src]);
|
||||
if (!state) return <div className="preview-none muted">Chargement…</div>;
|
||||
const lines = state.text.split("\n");
|
||||
return (
|
||||
<div className="viewer-text">
|
||||
<pre className={monospace(file.name) ? "mono" : ""}>
|
||||
{lines.map((l, i) => (
|
||||
<span key={i} className="ln" data-n={i + 1}>
|
||||
{l || " "}
|
||||
{"\n"}
|
||||
</span>
|
||||
))}
|
||||
</pre>
|
||||
{state.truncated && <div className="notice">Aperçu limité au début du fichier ({fmtSize(512 * 1024)}) : télécharger pour le lire en entier.</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,718 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
import { api, displayPath, type Account, type ApiToken, type Me, type Role, type Settings, type Share, type Status } from "./api";
|
||||
import { CheckIcon, CloseIcon, CopyLinkIcon, KeyIcon, LockIcon, ShareIcon, ShieldIcon, TrashIcon, UserIcon, UsersIcon } from "./icons";
|
||||
import { ConfirmDialog } from "./Dialogs";
|
||||
import { fmtDate, fmtSize, plural } from "./format";
|
||||
|
||||
type Tab = "account" | "tokens" | "shares" | "general" | "users";
|
||||
|
||||
interface Props {
|
||||
me: Me;
|
||||
initialTab?: Tab;
|
||||
onClose: () => void;
|
||||
/** Titre, logo ou comptes modifiés : le parent recharge /api/me. */
|
||||
onChanged: () => void;
|
||||
}
|
||||
|
||||
const copyText = async (text: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const msg = (e: unknown) => (e instanceof Error ? e.message : String(e));
|
||||
|
||||
/** Paramètres : compte, jetons d'API, partages ; pour les administrateurs, réglages généraux et utilisateurs. */
|
||||
export function SettingsDialog({ me, initialTab = "account", onClose, onChanged }: Props) {
|
||||
const [tab, setTab] = useState<Tab>(initialTab);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [onClose]);
|
||||
|
||||
const tabs: { id: Tab; label: string; icon: ReactNode; admin?: boolean; badge?: number }[] = [
|
||||
{ id: "account", label: "Mon compte", icon: <UserIcon /> },
|
||||
{ id: "tokens", label: "Jetons d'API", icon: <KeyIcon /> },
|
||||
{ id: "shares", label: "Partages", icon: <ShareIcon /> },
|
||||
{ id: "general", label: "Général", icon: <ShieldIcon />, admin: true },
|
||||
{ id: "users", label: "Utilisateurs", icon: <UsersIcon />, admin: true, badge: me.pending },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="modal-backdrop" onClick={onClose}>
|
||||
<div className="modal settings" role="dialog" aria-modal="true" aria-label="Paramètres" onClick={(e) => e.stopPropagation()}>
|
||||
<header className="settings-head">
|
||||
<h3>Paramètres</h3>
|
||||
<button className="icon-btn" onClick={onClose} aria-label="Fermer" title="Fermer (Échap)">
|
||||
<CloseIcon />
|
||||
</button>
|
||||
</header>
|
||||
<nav className="tabs" role="tablist">
|
||||
{tabs
|
||||
.filter((t) => !t.admin || me.admin)
|
||||
.map((t) => (
|
||||
<button
|
||||
key={t.id}
|
||||
role="tab"
|
||||
aria-selected={tab === t.id}
|
||||
className={tab === t.id ? "on" : ""}
|
||||
onClick={() => {
|
||||
setError(null);
|
||||
setTab(t.id);
|
||||
}}
|
||||
>
|
||||
{t.icon}
|
||||
<span>{t.label}</span>
|
||||
{!!t.badge && <small className="badge">{t.badge}</small>}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
{error && (
|
||||
<div className="error" onClick={() => setError(null)}>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
<div className="settings-body">
|
||||
{tab === "account" && <AccountTab me={me} onError={setError} onChanged={onChanged} />}
|
||||
{tab === "tokens" && <TokensTab onError={setError} />}
|
||||
{tab === "shares" && <SharesTab me={me} onError={setError} />}
|
||||
{tab === "general" && me.admin && <GeneralTab onError={setError} onChanged={onChanged} />}
|
||||
{tab === "users" && me.admin && <UsersTab me={me} onError={setError} onChanged={onChanged} />}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// --- Mon compte ----------------------------------------------------------------------
|
||||
|
||||
function AccountTab({ me, onError, onChanged }: { me: Me; onError: (m: string | null) => void; onChanged: () => void }) {
|
||||
const u = me.user;
|
||||
const [name, setName] = useState(u?.name ?? "");
|
||||
const [email, setEmail] = useState(u?.email ?? "");
|
||||
const [current, setCurrent] = useState("");
|
||||
const [next, setNext] = useState("");
|
||||
const [ok, setOk] = useState<string | null>(null);
|
||||
const local = me.canChangePassword;
|
||||
|
||||
const run = async (fn: () => Promise<unknown>, done: string) => {
|
||||
onError(null);
|
||||
setOk(null);
|
||||
try {
|
||||
await fn();
|
||||
setOk(done);
|
||||
} catch (e) {
|
||||
onError(msg(e));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="section">
|
||||
<dl className="kv">
|
||||
<dt>Identifiant</dt>
|
||||
<dd>
|
||||
<code>{u?.id}</code>
|
||||
</dd>
|
||||
<dt>Rôle</dt>
|
||||
<dd>{u?.role === "admin" ? "Administrateur" : "Utilisateur"}</dd>
|
||||
<dt>Connexion</dt>
|
||||
<dd>{u?.provider === "oidc" ? "Fournisseur d'identité (OIDC)" : u?.provider === "local" ? "Compte local" : "Sans authentification intégrée"}</dd>
|
||||
{me.usage && (
|
||||
<>
|
||||
<dt>Espace personnel</dt>
|
||||
<dd>
|
||||
{fmtSize(me.usage.used)}
|
||||
{me.usage.quota > 0 ? ` sur ${fmtSize(me.usage.quota)}` : " (illimité)"}
|
||||
</dd>
|
||||
</>
|
||||
)}
|
||||
</dl>
|
||||
{ok && <div className="notice">{ok}</div>}
|
||||
{local ? (
|
||||
<>
|
||||
<form
|
||||
className="form"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
run(async () => {
|
||||
await api.patchAccount({ name, email });
|
||||
onChanged();
|
||||
}, "Profil enregistré.");
|
||||
}}
|
||||
>
|
||||
<h4>Profil</h4>
|
||||
<label className="field">
|
||||
<span>Nom affiché</span>
|
||||
<input value={name} maxLength={80} onChange={(e) => setName(e.target.value)} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Adresse e-mail</span>
|
||||
<input type="email" value={email} maxLength={120} onChange={(e) => setEmail(e.target.value)} />
|
||||
</label>
|
||||
<div>
|
||||
<button className="primary" type="submit">
|
||||
Enregistrer
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
<form
|
||||
className="form"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
run(async () => {
|
||||
await api.changePassword(current, next);
|
||||
setCurrent("");
|
||||
setNext("");
|
||||
}, "Mot de passe modifié.");
|
||||
}}
|
||||
>
|
||||
<h4>Mot de passe</h4>
|
||||
<label className="field">
|
||||
<span>Mot de passe actuel</span>
|
||||
<input type="password" autoComplete="current-password" value={current} onChange={(e) => setCurrent(e.target.value)} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Nouveau mot de passe (10 caractères minimum)</span>
|
||||
<input type="password" autoComplete="new-password" minLength={10} value={next} onChange={(e) => setNext(e.target.value)} />
|
||||
</label>
|
||||
<div>
|
||||
<button className="primary" type="submit" disabled={!current || next.length < 10}>
|
||||
Changer le mot de passe
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</>
|
||||
) : (
|
||||
<p className="muted">Le nom, l'adresse et le mot de passe de ce compte sont gérés par votre fournisseur d'identité.</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// --- Jetons d'API ----------------------------------------------------------------------
|
||||
|
||||
function TokensTab({ onError }: { onError: (m: string | null) => void }) {
|
||||
const [tokens, setTokens] = useState<ApiToken[] | null>(null);
|
||||
const [name, setName] = useState("");
|
||||
const [created, setCreated] = useState<string | null>(null);
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
const load = useCallback(() => api.tokens().then(setTokens).catch((e) => onError(msg(e))), [onError]);
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
const create = async () => {
|
||||
onError(null);
|
||||
try {
|
||||
const t = await api.createToken(name);
|
||||
setCreated(t.token);
|
||||
setName("");
|
||||
load();
|
||||
} catch (e) {
|
||||
onError(msg(e));
|
||||
}
|
||||
};
|
||||
|
||||
const revoke = async (t: ApiToken) => {
|
||||
onError(null);
|
||||
try {
|
||||
await api.revokeToken(t.id);
|
||||
load();
|
||||
} catch (e) {
|
||||
onError(msg(e));
|
||||
}
|
||||
};
|
||||
|
||||
const o = location.origin;
|
||||
return (
|
||||
<div className="section">
|
||||
<p className="muted">
|
||||
Un jeton permet d'envoyer et de télécharger des fichiers depuis un script ou un outil (curl, sauvegardes...) sans passer par le navigateur. Il donne accès à vos fichiers, comme votre session, mais pas aux comptes ni aux jetons.
|
||||
</p>
|
||||
<form
|
||||
className="inline-form"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
create();
|
||||
}}
|
||||
>
|
||||
<input value={name} maxLength={80} placeholder="Nom du jeton (ex. sauvegarde NAS)" onChange={(e) => setName(e.target.value)} />
|
||||
<button className="primary" type="submit" disabled={!name.trim()}>
|
||||
Créer un jeton
|
||||
</button>
|
||||
</form>
|
||||
{created && (
|
||||
<div className="secret">
|
||||
<strong>Copier ce jeton maintenant : il ne sera plus affiché.</strong>
|
||||
<code>{created}</code>
|
||||
<button
|
||||
onClick={async () => {
|
||||
setCopied(await copyText(created));
|
||||
setTimeout(() => setCopied(false), 1500);
|
||||
}}
|
||||
>
|
||||
<CopyLinkIcon />
|
||||
<span>{copied ? "Copié" : "Copier"}</span>
|
||||
</button>
|
||||
<pre className="example">{`# Envoyer un fichier dans « Personnel »
|
||||
curl -T rapport.pdf -H "Authorization: Bearer ${created}" \\
|
||||
"${o}/api/file?path=.perso/rapport.pdf&conflict=overwrite"
|
||||
|
||||
# Télécharger
|
||||
curl -OJ -H "Authorization: Bearer ${created}" \\
|
||||
"${o}/api/file?path=.perso/rapport.pdf"`}</pre>
|
||||
</div>
|
||||
)}
|
||||
<ul className="rows">
|
||||
{tokens?.map((t) => (
|
||||
<li key={t.id}>
|
||||
<KeyIcon />
|
||||
<div className="grow">
|
||||
<strong>{t.name}</strong>
|
||||
<small className="muted">
|
||||
{" "}
|
||||
créé le {fmtDate(t.created)} · {t.lastUsed ? `utilisé le ${fmtDate(t.lastUsed)}` : "jamais utilisé"}
|
||||
</small>
|
||||
</div>
|
||||
<button className="icon-btn danger" onClick={() => revoke(t)} title="Révoquer" aria-label={`Révoquer ${t.name}`}>
|
||||
<TrashIcon />
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
{tokens && tokens.length === 0 && <li className="muted empty">Aucun jeton.</li>}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// --- Partages ----------------------------------------------------------------------------
|
||||
|
||||
function SharesTab({ me, onError }: { me: Me; onError: (m: string | null) => void }) {
|
||||
const [shares, setShares] = useState<Share[] | null>(null);
|
||||
const [confirmAll, setConfirmAll] = useState(false);
|
||||
const load = useCallback(() => api.shares().then(setShares).catch((e) => onError(msg(e))), [onError]);
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
const revoke = async (id: string) => {
|
||||
onError(null);
|
||||
try {
|
||||
await api.revokeShare(id);
|
||||
load();
|
||||
} catch (e) {
|
||||
onError(msg(e));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="section">
|
||||
<ul className="rows">
|
||||
{shares?.map((s) => (
|
||||
<li key={s.id}>
|
||||
<ShareIcon />
|
||||
<div className="grow">
|
||||
<strong title={displayPath(s.path)}>{displayPath(s.path)}</strong>
|
||||
{s.protected && (
|
||||
<span className="pill" title="Protégé par un mot de passe">
|
||||
<LockIcon size={12} /> mot de passe
|
||||
</span>
|
||||
)}
|
||||
<small className="muted">
|
||||
{" "}
|
||||
{s.isDir ? "dossier" : "fichier"} · {s.expires ? `expire le ${fmtDate(s.expires)}` : "sans expiration"}
|
||||
{!!s.downloads && ` · ${plural(s.downloads, "téléchargement")}`}
|
||||
</small>
|
||||
</div>
|
||||
<button
|
||||
onClick={async () => {
|
||||
if (!(await copyText(api.shareUrl(s.token)))) prompt("Copier le lien :", api.shareUrl(s.token));
|
||||
}}
|
||||
>
|
||||
<CopyLinkIcon />
|
||||
<span>Copier</span>
|
||||
</button>
|
||||
<button className="icon-btn danger" onClick={() => revoke(s.id)} title="Révoquer ce lien" aria-label="Révoquer ce lien">
|
||||
<CloseIcon />
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
{shares && shares.length === 0 && <li className="muted empty">Aucun lien de partage actif.</li>}
|
||||
</ul>
|
||||
{me.admin && (
|
||||
<div>
|
||||
<button className="danger-outline" disabled={!shares?.length} onClick={() => setConfirmAll(true)}>
|
||||
<TrashIcon />
|
||||
<span>Tout révoquer (tous les utilisateurs)</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{confirmAll && (
|
||||
<ConfirmDialog
|
||||
title="Révoquer tous les liens"
|
||||
confirm="Tout révoquer"
|
||||
danger
|
||||
onClose={() => setConfirmAll(false)}
|
||||
onConfirm={async () => {
|
||||
setConfirmAll(false);
|
||||
try {
|
||||
await api.revokeAllShares();
|
||||
load();
|
||||
} catch (e) {
|
||||
onError(msg(e));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<p>Tous les liens de partage de tous les utilisateurs deviennent invalides.</p>
|
||||
</ConfirmDialog>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// --- Général (administrateur) ------------------------------------------------------------
|
||||
|
||||
function GeneralTab({ onError, onChanged }: { onError: (m: string | null) => void; onChanged: () => void }) {
|
||||
const [st, setSt] = useState<Settings | null>(null);
|
||||
const [title, setTitle] = useState("");
|
||||
const [quota, setQuota] = useState("0");
|
||||
const [trash, setTrash] = useState("0");
|
||||
const [saved, setSaved] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(
|
||||
() =>
|
||||
api
|
||||
.settings()
|
||||
.then((s) => {
|
||||
setSt(s);
|
||||
setTitle(s.title);
|
||||
setQuota(String(s.quotaMB));
|
||||
setTrash(String(s.trashDays));
|
||||
})
|
||||
.catch((e) => onError(msg(e))),
|
||||
[onError],
|
||||
);
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
const apply = async (patch: Parameters<typeof api.setSettings>[0], done = "Enregistré.") => {
|
||||
onError(null);
|
||||
setSaved(null);
|
||||
try {
|
||||
setSt(await api.setSettings(patch));
|
||||
setSaved(done);
|
||||
onChanged();
|
||||
} catch (e) {
|
||||
onError(msg(e));
|
||||
}
|
||||
};
|
||||
|
||||
const logo = async (f?: File) => {
|
||||
if (!f) return;
|
||||
onError(null);
|
||||
try {
|
||||
setSt(await api.uploadLogo(f));
|
||||
setSaved("Logo enregistré.");
|
||||
onChanged();
|
||||
} catch (e) {
|
||||
onError(msg(e));
|
||||
}
|
||||
};
|
||||
|
||||
if (!st) return <p className="muted">Chargement…</p>;
|
||||
return (
|
||||
<div className="section">
|
||||
{saved && (
|
||||
<div className="notice">
|
||||
<CheckIcon size={14} /> {saved}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<h4>Apparence</h4>
|
||||
<form
|
||||
className="inline-form"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
apply({ title });
|
||||
}}
|
||||
>
|
||||
<input value={title} maxLength={80} placeholder="Up And Down" onChange={(e) => setTitle(e.target.value)} />
|
||||
<button type="submit" disabled={title === st.title}>
|
||||
Enregistrer le titre
|
||||
</button>
|
||||
</form>
|
||||
<div className="logo-row">
|
||||
{st.logo ? <img className="logo-preview" src={api.logoUrl(st.logo)} alt="Logo" /> : <span className="muted">Aucun logo</span>}
|
||||
<label className="ex-btn">
|
||||
<input type="file" accept="image/png" hidden onChange={(e) => logo(e.target.files?.[0])} />
|
||||
<span>Choisir un logo PNG</span>
|
||||
</label>
|
||||
{st.logo && (
|
||||
<button
|
||||
onClick={async () => {
|
||||
try {
|
||||
setSt(await api.removeLogo());
|
||||
onChanged();
|
||||
} catch (e) {
|
||||
onError(msg(e));
|
||||
}
|
||||
}}
|
||||
>
|
||||
Retirer
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<h4>Inscription</h4>
|
||||
<label className="field">
|
||||
<span>Les visiteurs peuvent créer un compte local</span>
|
||||
<select value={st.registration} onChange={(e) => apply({ registration: e.target.value as Settings["registration"] })}>
|
||||
<option value="closed">Non : l'administrateur crée les comptes</option>
|
||||
<option value="approval">Oui, après validation par un administrateur</option>
|
||||
<option value="open">Oui, immédiatement</option>
|
||||
</select>
|
||||
</label>
|
||||
<p className="muted small-text">S'applique aux comptes locaux ; les comptes OIDC sont créés à la première connexion réussie.</p>
|
||||
|
||||
<h4>Stockage</h4>
|
||||
<form
|
||||
className="inline-form"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
apply({ quotaMB: Math.max(0, Math.floor(Number(quota) || 0)) });
|
||||
}}
|
||||
>
|
||||
<label className="field grow">
|
||||
<span>Quota de l'espace personnel par utilisateur (Mo, 0 : illimité)</span>
|
||||
<input type="number" min={0} value={quota} onChange={(e) => setQuota(e.target.value)} />
|
||||
</label>
|
||||
<button type="submit" disabled={Number(quota) === st.quotaMB}>
|
||||
Enregistrer
|
||||
</button>
|
||||
</form>
|
||||
<label className="check-row">
|
||||
<input type="checkbox" checked={st.commonReadonly} onChange={(e) => apply({ commonReadonly: e.target.checked })} />
|
||||
<span>Arborescence commune en lecture seule pour les utilisateurs (seuls les administrateurs y écrivent)</span>
|
||||
</label>
|
||||
<form
|
||||
className="inline-form"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
apply({ trashDays: Math.max(0, Math.floor(Number(trash) || 0)) });
|
||||
}}
|
||||
>
|
||||
<label className="field grow">
|
||||
<span>Purge de la poubelle après (jours, 0 : jamais)</span>
|
||||
<input type="number" min={0} max={3650} value={trash} onChange={(e) => setTrash(e.target.value)} />
|
||||
</label>
|
||||
<button type="submit" disabled={Number(trash) === st.trashDays}>
|
||||
Enregistrer
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// --- Utilisateurs (administrateur) ---------------------------------------------------------
|
||||
|
||||
const statusLabel: Record<Status, string> = { active: "Actif", pending: "En attente", disabled: "Désactivé" };
|
||||
|
||||
function UsersTab({ me, onError, onChanged }: { me: Me; onError: (m: string | null) => void; onChanged: () => void }) {
|
||||
const [users, setUsers] = useState<Account[] | null>(null);
|
||||
const [form, setForm] = useState({ username: "", name: "", email: "", password: "", role: "user" as Role });
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [removing, setRemoving] = useState<Account | null>(null);
|
||||
const [resetting, setResetting] = useState<Account | null>(null);
|
||||
const [newPassword, setNewPassword] = useState("");
|
||||
|
||||
const load = useCallback(() => api.users().then(setUsers).catch((e) => onError(msg(e))), [onError]);
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
const patch = async (u: Account, v: Parameters<typeof api.patchUser>[1]) => {
|
||||
onError(null);
|
||||
try {
|
||||
await api.patchUser(u.id, v);
|
||||
await load();
|
||||
onChanged();
|
||||
} catch (e) {
|
||||
onError(msg(e));
|
||||
}
|
||||
};
|
||||
|
||||
const create = async () => {
|
||||
onError(null);
|
||||
try {
|
||||
await api.createUser(form);
|
||||
setForm({ username: "", name: "", email: "", password: "", role: "user" });
|
||||
setCreating(false);
|
||||
await load();
|
||||
} catch (e) {
|
||||
onError(msg(e));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="section">
|
||||
<div className="row-between">
|
||||
<span className="muted">{users ? plural(users.length, "compte") : ""}</span>
|
||||
<button className="primary" onClick={() => setCreating(!creating)}>
|
||||
{creating ? "Annuler" : "Créer un compte local"}
|
||||
</button>
|
||||
</div>
|
||||
{creating && (
|
||||
<form
|
||||
className="form card"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
create();
|
||||
}}
|
||||
>
|
||||
<div className="grid2">
|
||||
<label className="field">
|
||||
<span>Identifiant</span>
|
||||
<input value={form.username} autoComplete="off" onChange={(e) => setForm({ ...form, username: e.target.value })} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Nom affiché</span>
|
||||
<input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Adresse e-mail</span>
|
||||
<input type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Mot de passe (10 caractères minimum)</span>
|
||||
<input type="password" autoComplete="new-password" value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Rôle</span>
|
||||
<select value={form.role} onChange={(e) => setForm({ ...form, role: e.target.value as Role })}>
|
||||
<option value="user">Utilisateur</option>
|
||||
<option value="admin">Administrateur</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div>
|
||||
<button className="primary" type="submit" disabled={form.username.length < 3 || form.password.length < 10}>
|
||||
Créer
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
<div className="table-wrap">
|
||||
<table className="users">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Compte</th>
|
||||
<th>Origine</th>
|
||||
<th>Rôle</th>
|
||||
<th>État</th>
|
||||
<th>Dernière connexion</th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{users?.map((u) => (
|
||||
<tr key={u.id} className={u.status}>
|
||||
<td>
|
||||
<strong>{u.name}</strong>
|
||||
<small className="muted"> {u.id}</small>
|
||||
{u.email && u.email !== u.id && <small className="muted block">{u.email}</small>}
|
||||
</td>
|
||||
<td>{u.provider === "oidc" ? "OIDC" : "Local"}</td>
|
||||
<td>
|
||||
<select value={u.role} onChange={(e) => patch(u, { role: e.target.value as Role })} aria-label={`Rôle de ${u.id}`}>
|
||||
<option value="user">Utilisateur</option>
|
||||
<option value="admin">Administrateur</option>
|
||||
</select>
|
||||
</td>
|
||||
<td>
|
||||
<span className={`status ${u.status}`}>{statusLabel[u.status]}</span>
|
||||
</td>
|
||||
<td className="muted">{u.lastLogin ? fmtDate(u.lastLogin) : "jamais"}</td>
|
||||
<td className="actions-cell">
|
||||
{u.status === "pending" && (
|
||||
<button className="primary" onClick={() => patch(u, { status: "active" })}>
|
||||
<CheckIcon />
|
||||
<span>Valider</span>
|
||||
</button>
|
||||
)}
|
||||
{u.status === "active" && u.id !== me.user?.id && <button onClick={() => patch(u, { status: "disabled" })}>Désactiver</button>}
|
||||
{u.status === "disabled" && <button onClick={() => patch(u, { status: "active" })}>Réactiver</button>}
|
||||
{u.provider === "local" && (
|
||||
<button className="icon-btn" onClick={() => setResetting(u)} title="Nouveau mot de passe" aria-label={`Nouveau mot de passe pour ${u.id}`}>
|
||||
<KeyIcon />
|
||||
</button>
|
||||
)}
|
||||
{u.id !== me.user?.id && (
|
||||
<button className="icon-btn danger" onClick={() => setRemoving(u)} title="Supprimer le compte" aria-label={`Supprimer ${u.id}`}>
|
||||
<TrashIcon />
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{resetting && (
|
||||
<ConfirmDialog
|
||||
title={`Nouveau mot de passe pour ${resetting.id}`}
|
||||
confirm="Changer"
|
||||
onClose={() => {
|
||||
setResetting(null);
|
||||
setNewPassword("");
|
||||
}}
|
||||
onConfirm={async () => {
|
||||
const u = resetting;
|
||||
setResetting(null);
|
||||
await patch(u, { password: newPassword });
|
||||
setNewPassword("");
|
||||
}}
|
||||
>
|
||||
<label className="field">
|
||||
<span>Mot de passe (10 caractères minimum)</span>
|
||||
<input type="password" autoFocus autoComplete="new-password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} />
|
||||
</label>
|
||||
</ConfirmDialog>
|
||||
)}
|
||||
{removing && (
|
||||
<ConfirmDialog
|
||||
title="Supprimer le compte"
|
||||
confirm="Supprimer"
|
||||
danger
|
||||
onClose={() => setRemoving(null)}
|
||||
onConfirm={async () => {
|
||||
const u = removing;
|
||||
setRemoving(null);
|
||||
onError(null);
|
||||
try {
|
||||
await api.deleteUser(u.id);
|
||||
await load();
|
||||
onChanged();
|
||||
} catch (e) {
|
||||
onError(msg(e));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<p>
|
||||
Supprimer le compte de <strong>{removing.name}</strong> ({removing.id}) ? Ses jetons et ses sessions sont révoqués. Ses fichiers personnels sont mis de côté sur le serveur
|
||||
(<code>.users-removed</code>), pas supprimés.
|
||||
</p>
|
||||
</ConfirmDialog>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { api, displayPath, type Share } from "./api";
|
||||
import { CloseIcon, CopyLinkIcon, DownloadIcon, LockIcon } from "./icons";
|
||||
import { fmtDate, plural } from "./format";
|
||||
|
||||
interface Props {
|
||||
/** Fichier ou dossier à partager. */
|
||||
path: string;
|
||||
name: string;
|
||||
isDir: boolean;
|
||||
onClose: () => void;
|
||||
/** Appelé après création ou révocation (compteurs de l'explorateur). */
|
||||
onChanged: () => void;
|
||||
}
|
||||
|
||||
const DURATIONS = [
|
||||
{ days: 1, label: "1 jour" },
|
||||
{ days: 7, label: "7 jours" },
|
||||
{ days: 30, label: "30 jours" },
|
||||
{ days: 90, label: "90 jours" },
|
||||
{ days: 0, label: "Sans expiration" },
|
||||
];
|
||||
|
||||
/** Liens de partage d'un fichier ou d'un dossier : création (durée, mot de passe), copie, révocation. */
|
||||
export function ShareDialog({ path, name, isDir, onClose, onChanged }: Props) {
|
||||
const [links, setLinks] = useState<Share[]>([]);
|
||||
const [days, setDays] = useState(7);
|
||||
const [password, setPassword] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [copied, setCopied] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(() => api.shares(path).then(setLinks).catch((e) => setError(e.message)), [path]);
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [onClose]);
|
||||
|
||||
const copy = async (token: string) => {
|
||||
const url = api.shareUrl(token);
|
||||
try {
|
||||
await navigator.clipboard.writeText(url);
|
||||
setCopied(token);
|
||||
setTimeout(() => setCopied((c) => (c === token ? null : c)), 2000);
|
||||
} catch {
|
||||
prompt("Copier le lien :", url); // presse-papiers indisponible (HTTP, navigateur restreint)
|
||||
}
|
||||
};
|
||||
|
||||
const create = async () => {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const sh = await api.createShare(path, days, password);
|
||||
setPassword("");
|
||||
await load();
|
||||
onChanged();
|
||||
await copy(sh.token);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const revoke = async (id: string) => {
|
||||
setError(null);
|
||||
try {
|
||||
await api.revokeShare(id);
|
||||
await load();
|
||||
onChanged();
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="modal-backdrop" onClick={onClose}>
|
||||
<div className="modal share-dialog" role="dialog" aria-modal="true" aria-label={`Partager ${name}`} onClick={(e) => e.stopPropagation()}>
|
||||
<h3>Partager « {name} »</h3>
|
||||
<p className="muted small-text">
|
||||
Toute personne qui a le lien {password ? "et le mot de passe " : ""}peut {isDir ? "parcourir et télécharger ce dossier" : "télécharger ce fichier"}, sans compte.
|
||||
</p>
|
||||
|
||||
<div className="share-form">
|
||||
<label className="field">
|
||||
<span>Validité</span>
|
||||
<select value={days} onChange={(e) => setDays(Number(e.target.value))}>
|
||||
{DURATIONS.map((d) => (
|
||||
<option key={d.days} value={d.days}>
|
||||
{d.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="field grow">
|
||||
<span>Mot de passe (facultatif)</span>
|
||||
<input type="text" autoComplete="off" value={password} maxLength={200} placeholder="Aucun" onChange={(e) => setPassword(e.target.value)} />
|
||||
</label>
|
||||
<button className="primary" disabled={busy} onClick={create}>
|
||||
<CopyLinkIcon />
|
||||
<span>Créer et copier</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{error && <div className="error">{error}</div>}
|
||||
|
||||
<ul className="share-list">
|
||||
{links.map((l) => (
|
||||
<li key={l.id}>
|
||||
<div className="share-info">
|
||||
<code className="share-token">/s/{l.token.slice(0, 10)}…</code>
|
||||
{l.protected && (
|
||||
<span className="pill" title="Protégé par un mot de passe">
|
||||
<LockIcon size={12} /> mot de passe
|
||||
</span>
|
||||
)}
|
||||
<small className="muted">
|
||||
créé le {fmtDate(l.created)} · {l.expires ? `expire le ${fmtDate(l.expires)}` : "sans expiration"}
|
||||
{!!l.downloads && (
|
||||
<>
|
||||
{" "}
|
||||
· <DownloadIcon size={12} /> {plural(l.downloads, "téléchargement")}
|
||||
</>
|
||||
)}
|
||||
</small>
|
||||
</div>
|
||||
<button onClick={() => copy(l.token)}>
|
||||
<CopyLinkIcon />
|
||||
<span>{copied === l.token ? "Copié" : "Copier"}</span>
|
||||
</button>
|
||||
<button className="icon-btn danger" onClick={() => revoke(l.id)} title="Révoquer ce lien" aria-label="Révoquer ce lien">
|
||||
<CloseIcon />
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
{links.length === 0 && <li className="muted empty">Aucun lien actif pour {displayPath(path)}.</li>}
|
||||
</ul>
|
||||
|
||||
<div className="modal-actions">
|
||||
<span className="spacer" />
|
||||
<button onClick={onClose}>Fermer</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { api, ApiError, type PublicInfo } from "./api";
|
||||
import { CloudUpIcon, DownloadIcon, EyeIcon, FolderIcon, LockIcon, UpIcon } from "./icons";
|
||||
import { FileGlyph, Thumb, thumbSource } from "./FileGlyph";
|
||||
import { kindOf, previewable, typeLabel } from "./filetypes";
|
||||
import { fmtDate, fmtSize, plural } from "./format";
|
||||
import { Preview, type PreviewFile } from "./Preview";
|
||||
|
||||
const join = (a: string, b: string) => (a ? `${a}/${b}` : b);
|
||||
|
||||
/** Page d'un lien de partage (/s/<jeton>) : fichier ou dossier, sans compte ; mot de passe si le lien en a un. */
|
||||
export function ShareView({ token }: { token: string }) {
|
||||
const [sub, setSub] = useState("");
|
||||
const [info, setInfo] = useState<PublicInfo | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [password, setPassword] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [preview, setPreview] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(
|
||||
(s: string) => {
|
||||
setError(null);
|
||||
return api
|
||||
.publicInfo(token, s)
|
||||
.then((i) => {
|
||||
setInfo(i);
|
||||
setSub(s);
|
||||
})
|
||||
.catch((e) => setError(e instanceof ApiError && e.status === 404 ? "Ce lien est invalide, expiré ou a été révoqué." : (e as Error).message));
|
||||
},
|
||||
[token],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
load("");
|
||||
}, [load]);
|
||||
|
||||
useEffect(() => {
|
||||
document.title = info?.name ? `${info.name} - ${info.title || "Up And Down"}` : info?.title || "Up And Down";
|
||||
}, [info]);
|
||||
|
||||
const unlock = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api.publicUnlock(token, password);
|
||||
await load(sub);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const files = useMemo(() => (info?.entries ?? []).filter((e) => !e.isDir), [info]);
|
||||
const previews: PreviewFile[] = useMemo(
|
||||
() =>
|
||||
info?.isDir
|
||||
? files.map((f) => ({
|
||||
name: f.name,
|
||||
size: f.size,
|
||||
modTime: f.modTime,
|
||||
src: api.publicFileUrl(token, join(sub, f.name), true),
|
||||
download: api.publicFileUrl(token, join(sub, f.name)),
|
||||
text: async () => ({ text: await api.publicText(token, join(sub, f.name)), truncated: f.size > 512 * 1024 }),
|
||||
}))
|
||||
: info?.name
|
||||
? [
|
||||
{
|
||||
name: info.name,
|
||||
size: info.size,
|
||||
modTime: info.modTime,
|
||||
src: api.publicFileUrl(token, "", true),
|
||||
download: api.publicFileUrl(token, ""),
|
||||
text: async () => ({ text: await api.publicText(token, ""), truncated: info.size > 512 * 1024 }),
|
||||
},
|
||||
]
|
||||
: [],
|
||||
[info, files, token, sub],
|
||||
);
|
||||
const previewIndex = preview === null ? -1 : previews.findIndex((p) => p.name === preview);
|
||||
|
||||
const header = (
|
||||
<header className="share-top">
|
||||
{info?.logo ? <img src={api.logoUrl(info.logo)} alt="" className="logo" /> : <CloudUpIcon size={26} />}
|
||||
<strong>{info?.title || "Up And Down"}</strong>
|
||||
</header>
|
||||
);
|
||||
|
||||
if (error && !info?.protected) {
|
||||
return (
|
||||
<main className="share-page">
|
||||
{header}
|
||||
<div className="share-card center">
|
||||
<p className="error">{error}</p>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
if (!info) {
|
||||
return (
|
||||
<main className="share-page">
|
||||
{header}
|
||||
<p className="muted center">Chargement…</p>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
if (info.protected) {
|
||||
return (
|
||||
<main className="share-page">
|
||||
{header}
|
||||
<form className="share-card form center" onSubmit={unlock}>
|
||||
<LockIcon size={32} />
|
||||
<h2>Ce lien est protégé</h2>
|
||||
<p className="muted">Saisissez le mot de passe communiqué par la personne qui a partagé ce contenu.</p>
|
||||
<input type="password" autoFocus autoComplete="off" value={password} placeholder="Mot de passe" onChange={(e) => setPassword(e.target.value)} />
|
||||
{error && <div className="error">{error}</div>}
|
||||
<button className="primary big" type="submit" disabled={busy || !password}>
|
||||
Accéder
|
||||
</button>
|
||||
</form>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
const crumbs = sub ? sub.split("/") : [];
|
||||
const thumb = (name: string, size: number, path: string) => (
|
||||
<Thumb name={name} glyph={36} src={thumbSource(name, size, () => api.publicThumbUrl(token, path), () => api.publicFileUrl(token, path, true))} />
|
||||
);
|
||||
|
||||
return (
|
||||
<main className="share-page">
|
||||
{header}
|
||||
<div className="share-card">
|
||||
{info.isDir ? (
|
||||
<>
|
||||
<div className="share-title">
|
||||
<h2>
|
||||
<FolderIcon size={22} /> {info.name}
|
||||
</h2>
|
||||
<a className="ex-btn primary" href={api.publicZipUrl(token, sub)}>
|
||||
<DownloadIcon />
|
||||
<span>Tout télécharger (ZIP)</span>
|
||||
</a>
|
||||
</div>
|
||||
<nav className="crumbs">
|
||||
<button onClick={() => load("")}>{(info.sub ? "" : info.name) || "Dossier partagé"}</button>
|
||||
{crumbs.map((c, i) => {
|
||||
const p = crumbs.slice(0, i + 1).join("/");
|
||||
return (
|
||||
<span key={p}>
|
||||
<span className="muted"> / </span>
|
||||
<button onClick={() => load(p)}>{c}</button>
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
<ul className="share-list-files">
|
||||
{sub && (
|
||||
<li>
|
||||
<button className="name" onClick={() => load(crumbs.slice(0, -1).join("/"))}>
|
||||
<span className="icon">
|
||||
<UpIcon size={22} />
|
||||
</span>
|
||||
<span className="label">..</span>
|
||||
</button>
|
||||
</li>
|
||||
)}
|
||||
{info.entries?.map((e) => (
|
||||
<li key={e.name}>
|
||||
{e.isDir ? (
|
||||
<button className="name" onClick={() => load(join(sub, e.name))}>
|
||||
<span className="icon folder">
|
||||
<FolderIcon size={22} />
|
||||
</span>
|
||||
<span className="label">{e.name}</span>
|
||||
</button>
|
||||
) : (
|
||||
<>
|
||||
<button className="name" onClick={() => setPreview(e.name)}>
|
||||
{kindOf(e.name) === "image" ? thumb(e.name, e.size, join(sub, e.name)) : <FileGlyph name={e.name} size={22} />}
|
||||
<span className="label">{e.name}</span>
|
||||
</button>
|
||||
<span className="meta muted">{fmtSize(e.size)}</span>
|
||||
<span className="meta muted">{fmtDate(e.modTime)}</span>
|
||||
<a className="icon-btn" href={api.publicFileUrl(token, join(sub, e.name))} download={e.name} title="Télécharger" aria-label={`Télécharger ${e.name}`}>
|
||||
<DownloadIcon />
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
{info.entries?.length === 0 && <li className="muted empty">Dossier vide</li>}
|
||||
</ul>
|
||||
<p className="muted small-text">
|
||||
{plural(files.length, "fichier")} {info.expires && `· lien valable jusqu'au ${fmtDate(info.expires)}`}
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<div className="share-file">
|
||||
{info.name && thumb(info.name, info.size, "")}
|
||||
<h2>{info.name}</h2>
|
||||
<p className="muted">
|
||||
{info.name && typeLabel(info.name)} · {fmtSize(info.size)} · {fmtDate(info.modTime)}
|
||||
</p>
|
||||
<div className="share-actions">
|
||||
<a className="ex-btn primary big" href={api.publicFileUrl(token, "")} download={info.name}>
|
||||
<DownloadIcon />
|
||||
<span>Télécharger</span>
|
||||
</a>
|
||||
{info.name && previewable(info.name) && (
|
||||
<button className="big" onClick={() => setPreview(info.name!)}>
|
||||
<EyeIcon />
|
||||
<span>Aperçu</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{info.expires && <p className="muted small-text">Lien valable jusqu'au {fmtDate(info.expires)}</p>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{previewIndex >= 0 && <Preview files={previews} index={previewIndex} onIndex={(i) => setPreview(previews[i].name)} onClose={() => setPreview(null)} />}
|
||||
{error && <div className="error floating">{error}</div>}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { useRef } from "react";
|
||||
|
||||
interface Props {
|
||||
width: number;
|
||||
min: number;
|
||||
max: number;
|
||||
onResize: (width: number) => void;
|
||||
/** Début / fin de glissement (désactive l'animation de la grille). */
|
||||
onDragging: (dragging: boolean) => void;
|
||||
onReset: () => void;
|
||||
}
|
||||
|
||||
/** Poignée verticale entre l'explorateur et le canevas : souris, doigt ou clavier. */
|
||||
export function Splitter({ width, min, max, onResize, onDragging, onReset }: Props) {
|
||||
const start = useRef<{ x: number; w: number } | null>(null);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="splitter"
|
||||
role="separator"
|
||||
aria-orientation="vertical"
|
||||
aria-label="Largeur de l'explorateur"
|
||||
aria-valuenow={width}
|
||||
aria-valuemin={min}
|
||||
aria-valuemax={max}
|
||||
tabIndex={0}
|
||||
title="Glisser pour redimensionner, double-clic pour la largeur par défaut"
|
||||
onPointerDown={(e) => {
|
||||
if (e.button !== 0) return;
|
||||
e.preventDefault();
|
||||
e.currentTarget.setPointerCapture(e.pointerId);
|
||||
start.current = { x: e.clientX, w: width };
|
||||
onDragging(true);
|
||||
}}
|
||||
onPointerMove={(e) => {
|
||||
if (start.current) onResize(start.current.w + e.clientX - start.current.x);
|
||||
}}
|
||||
onPointerUp={(e) => {
|
||||
e.currentTarget.releasePointerCapture(e.pointerId);
|
||||
start.current = null;
|
||||
onDragging(false);
|
||||
}}
|
||||
onLostPointerCapture={() => {
|
||||
if (start.current) {
|
||||
start.current = null;
|
||||
onDragging(false);
|
||||
}
|
||||
}}
|
||||
onDoubleClick={onReset}
|
||||
onKeyDown={(e) => {
|
||||
const step = e.shiftKey ? 64 : 16;
|
||||
if (e.key === "ArrowLeft") onResize(width - step);
|
||||
else if (e.key === "ArrowRight") onResize(width + step);
|
||||
else if (e.key === "Home") onResize(min);
|
||||
else if (e.key === "End") onResize(max);
|
||||
else return;
|
||||
e.preventDefault();
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { api, basename, type Entry, type TagCount } from "./api";
|
||||
import { CloseIcon, TagIcon } from "./icons";
|
||||
|
||||
interface Props {
|
||||
/** Éléments concernés, avec leurs tags actuels. */
|
||||
items: Entry[];
|
||||
/** Tags déjà utilisés (suggestions). */
|
||||
known: TagCount[];
|
||||
/** Appelé après chaque modification pour rafraîchir l'explorateur. */
|
||||
onChanged: () => Promise<void>;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
const key = (t: string) => t.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase();
|
||||
|
||||
/** Ajout et retrait de tags sur un ou plusieurs éléments. */
|
||||
export function TagsDialog({ items, known, onChanged, onClose }: Props) {
|
||||
const [input, setInput] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const paths = items.map((e) => e.path);
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [onClose]);
|
||||
|
||||
// Tags présents et nombre d'éléments qui les portent.
|
||||
const present = new Map<string, { name: string; count: number }>();
|
||||
for (const e of items)
|
||||
for (const t of e.tags ?? []) {
|
||||
const p = present.get(key(t));
|
||||
if (p) p.count++;
|
||||
else present.set(key(t), { name: t, count: 1 });
|
||||
}
|
||||
const suggestions = known.filter((t) => !present.has(key(t.name)) || present.get(key(t.name))!.count < items.length);
|
||||
|
||||
const run = async (add: string[], remove: string[]) => {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api.editTags(paths, add, remove);
|
||||
await onChanged();
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const add = (raw: string) => {
|
||||
const tags = raw
|
||||
.split(",")
|
||||
.map((t) => t.trim())
|
||||
.filter(Boolean);
|
||||
if (tags.length === 0) return;
|
||||
setInput("");
|
||||
run(tags, []);
|
||||
};
|
||||
|
||||
const title =
|
||||
items.length === 1
|
||||
? `Tags · ${items[0].isDir ? items[0].name : basename(items[0].path)}`
|
||||
: `Tags · ${items.length} éléments`;
|
||||
|
||||
return (
|
||||
<div className="modal-backdrop" onClick={onClose}>
|
||||
<div className="modal tags-dialog" role="dialog" aria-modal="true" aria-label={title} onClick={(e) => e.stopPropagation()}>
|
||||
<h3>{title}</h3>
|
||||
|
||||
<div className="chips">
|
||||
{[...present.values()].map((t) => (
|
||||
<span key={t.name} className="chip">
|
||||
{t.name}
|
||||
{items.length > 1 && t.count < items.length && (
|
||||
<small className="muted">
|
||||
{" "}
|
||||
{t.count}/{items.length}
|
||||
</small>
|
||||
)}
|
||||
<button
|
||||
className="icon-btn"
|
||||
disabled={busy}
|
||||
onClick={() => run([], [t.name])}
|
||||
title={`Retirer « ${t.name} »`}
|
||||
aria-label={`Retirer ${t.name}`}
|
||||
>
|
||||
<CloseIcon size={12} />
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
{present.size === 0 && <span className="muted">Aucun tag.</span>}
|
||||
</div>
|
||||
|
||||
<form
|
||||
className="tag-add"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
add(input);
|
||||
}}
|
||||
>
|
||||
<label className="search">
|
||||
<TagIcon />
|
||||
<input
|
||||
autoFocus
|
||||
value={input}
|
||||
list="known-tags"
|
||||
maxLength={200}
|
||||
placeholder="Ajouter des tags (séparés par des virgules)"
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<datalist id="known-tags">
|
||||
{known.map((t) => (
|
||||
<option key={t.name} value={t.name} />
|
||||
))}
|
||||
</datalist>
|
||||
<button type="submit" className="primary" disabled={busy || !input.trim()}>
|
||||
Ajouter
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{suggestions.length > 0 && (
|
||||
<div className="chips suggestions">
|
||||
{suggestions.slice(0, 30).map((t) => (
|
||||
<button key={t.name} className="chip" disabled={busy} onClick={() => run([t.name], [])} title={`Ajouter « ${t.name} »`}>
|
||||
+ {t.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && <div className="error">{error}</div>}
|
||||
|
||||
<div className="modal-actions">
|
||||
<span className="spacer" />
|
||||
<button onClick={onClose}>Fermer</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { CheckIcon, ChevronDownIcon, CloseIcon, RefreshIcon, WarningIcon } from "./icons";
|
||||
import { fmtRate, fmtSize } from "./format";
|
||||
import { uploads, useUploads, type OnExists } from "./uploads";
|
||||
|
||||
/** Panneau flottant des envois : progression globale et par fichier, annulation, nouvel essai. */
|
||||
export function UploadPanel() {
|
||||
const items = useUploads();
|
||||
const [collapsed, setCollapsed] = useState(false);
|
||||
const [rate, setRate] = useState(0);
|
||||
const last = useRef({ loaded: 0, at: Date.now() });
|
||||
|
||||
const active = items.filter((i) => i.status === "uploading" || i.status === "queued");
|
||||
const done = items.filter((i) => i.status === "done");
|
||||
const failed = items.filter((i) => i.status === "error");
|
||||
const total = items.reduce((n, i) => n + i.size, 0);
|
||||
const loaded = items.reduce((n, i) => n + (i.status === "done" ? i.size : i.loaded), 0);
|
||||
|
||||
// Débit moyen sur la dernière seconde.
|
||||
useEffect(() => {
|
||||
if (active.length === 0) {
|
||||
setRate(0);
|
||||
last.current = { loaded, at: Date.now() };
|
||||
return;
|
||||
}
|
||||
const t = setInterval(() => {
|
||||
const now = Date.now();
|
||||
const bytes = items.reduce((n, i) => n + (i.status === "done" ? i.size : i.loaded), 0);
|
||||
const dt = (now - last.current.at) / 1000;
|
||||
if (dt > 0) setRate(Math.max(0, (bytes - last.current.loaded) / dt));
|
||||
last.current = { loaded: bytes, at: now };
|
||||
}, 1000);
|
||||
return () => clearInterval(t);
|
||||
});
|
||||
|
||||
if (items.length === 0) return null;
|
||||
const pct = total ? Math.round((loaded / total) * 100) : 100;
|
||||
const eta = rate > 0 && total > loaded ? Math.ceil((total - loaded) / rate) : 0;
|
||||
const status =
|
||||
active.length > 0
|
||||
? `Envoi de ${active.length} fichier${active.length > 1 ? "s" : ""} · ${pct} %${rate > 0 ? ` · ${fmtRate(rate)}` : ""}${eta > 1 ? ` · ${eta < 90 ? `${eta} s` : `${Math.ceil(eta / 60)} min`}` : ""}`
|
||||
: failed.length > 0
|
||||
? `${done.length} envoyé${done.length > 1 ? "s" : ""}, ${failed.length} en échec`
|
||||
: `${done.length} fichier${done.length > 1 ? "s" : ""} envoyé${done.length > 1 ? "s" : ""}`;
|
||||
|
||||
return (
|
||||
<section className="uploads" aria-label="Envois">
|
||||
<header>
|
||||
{active.length === 0 && failed.length === 0 ? <CheckIcon size={16} /> : failed.length > 0 && active.length === 0 ? <WarningIcon size={16} /> : null}
|
||||
<strong>{status}</strong>
|
||||
<span className="spacer" />
|
||||
<button className="icon-btn" onClick={() => setCollapsed(!collapsed)} title={collapsed ? "Développer" : "Réduire"} aria-label={collapsed ? "Développer" : "Réduire"}>
|
||||
<ChevronDownIcon className={collapsed ? "flip" : ""} />
|
||||
</button>
|
||||
<button
|
||||
className="icon-btn"
|
||||
onClick={() => (active.length ? uploads.cancelAll() : uploads.clearFinished())}
|
||||
title={active.length ? "Annuler tous les envois" : "Fermer"}
|
||||
aria-label={active.length ? "Annuler tous les envois" : "Fermer"}
|
||||
>
|
||||
<CloseIcon />
|
||||
</button>
|
||||
</header>
|
||||
<div className="bar total" role="progressbar" aria-valuenow={pct} aria-valuemin={0} aria-valuemax={100}>
|
||||
<span style={{ width: `${pct}%` }} className={failed.length ? "err" : ""} />
|
||||
</div>
|
||||
{!collapsed && (
|
||||
<>
|
||||
<ul>
|
||||
{items.map((i) => (
|
||||
<li key={i.id} className={i.status}>
|
||||
<div className="upinfo">
|
||||
<span className="upname" title={i.path}>
|
||||
{i.rel}
|
||||
</span>
|
||||
<small className="muted">
|
||||
{i.status === "uploading" && `${fmtSize(i.loaded)} / ${fmtSize(i.size)}`}
|
||||
{i.status === "queued" && `en attente · ${fmtSize(i.size)}`}
|
||||
{i.status === "done" && (i.result && i.result !== i.path ? `envoyé sous « ${i.result.split("/").pop()} »` : `envoyé · ${fmtSize(i.size)}`)}
|
||||
{i.status === "error" && <span className="error-text">{i.error}</span>}
|
||||
{i.status === "canceled" && "annulé"}
|
||||
</small>
|
||||
{(i.status === "uploading" || i.status === "queued") && (
|
||||
<div className="bar">
|
||||
<span style={{ width: `${i.size ? (i.loaded / i.size) * 100 : 0}%` }} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{(i.status === "error" || i.status === "canceled") && (
|
||||
<button className="icon-btn" onClick={() => uploads.retry(i.id)} title="Réessayer" aria-label="Réessayer">
|
||||
<RefreshIcon />
|
||||
</button>
|
||||
)}
|
||||
{(i.status === "uploading" || i.status === "queued") && (
|
||||
<button className="icon-btn" onClick={() => uploads.cancel(i.id)} title="Annuler" aria-label="Annuler">
|
||||
<CloseIcon />
|
||||
</button>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<footer>
|
||||
<label>
|
||||
<span className="muted">Si le fichier existe :</span>
|
||||
<select value={uploads.onExists} onChange={(e) => uploads.setOnExists(e.target.value as OnExists)} aria-label="Si le fichier existe déjà">
|
||||
<option value="rename">garder les deux</option>
|
||||
<option value="overwrite">remplacer</option>
|
||||
<option value="fail">ignorer</option>
|
||||
</select>
|
||||
</label>
|
||||
<span className="spacer" />
|
||||
{failed.length > 0 && (
|
||||
<button onClick={() => uploads.retryFailed()}>
|
||||
<RefreshIcon />
|
||||
<span>Réessayer</span>
|
||||
</button>
|
||||
)}
|
||||
{active.length === 0 && <button onClick={() => uploads.clearFinished()}>Effacer</button>}
|
||||
</footer>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
// Client de l'API Go (voir internal/api/api.go).
|
||||
|
||||
export interface Entry {
|
||||
name: string;
|
||||
path: string;
|
||||
isDir: boolean;
|
||||
size: number;
|
||||
modTime: string;
|
||||
tags?: string[];
|
||||
favorite?: boolean;
|
||||
/** Dossier : icône choisie (voir folderIcons.tsx). */
|
||||
icon?: string;
|
||||
/** Entrée virtuelle de la racine : "favoris", "perso" (espace personnel) ou "poubelle". */
|
||||
special?: "favoris" | "perso" | "poubelle";
|
||||
/** Entrée « poubelle » de la racine : nombre d'éléments qu'elle contient. */
|
||||
count?: number;
|
||||
/** Élément de la poubelle : chemin d'origine (modTime = date de suppression). */
|
||||
origin?: string;
|
||||
/** Élément de la poubelle : supprimé par (vide si inconnu). */
|
||||
by?: string;
|
||||
/** Dans le dossier Favoris : nom du lien (le chemin est celui de l'original). */
|
||||
link?: string;
|
||||
/** Favori dont l'original a disparu (chemin .favoris/<lien>, à retirer). */
|
||||
broken?: boolean;
|
||||
/** Fichier : dernier utilisateur à l'avoir déposé. */
|
||||
editedBy?: string;
|
||||
/** Vue Galerie : détails demandés à la liste ou à la recherche (details=1). */
|
||||
details?: Details;
|
||||
}
|
||||
|
||||
/** Détails d'une entrée (internal/storage/details.go) ; compteurs absents = 0. */
|
||||
export interface Details {
|
||||
/** Image : dimensions en pixels. */
|
||||
width?: number;
|
||||
height?: number;
|
||||
versions?: number;
|
||||
/** Liens de partage actifs. */
|
||||
shares?: number;
|
||||
created?: string;
|
||||
createdBy?: string;
|
||||
/** Dossier : éléments directs, puis taille et nombre de fichiers de tout le contenu. */
|
||||
dirs?: number;
|
||||
files?: number;
|
||||
total?: number;
|
||||
count?: number;
|
||||
}
|
||||
|
||||
export interface TagCount {
|
||||
name: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
/** Filtres de recherche : tag exact et/ou favoris seulement. */
|
||||
export interface SearchFilter {
|
||||
tag?: string | null;
|
||||
fav?: boolean;
|
||||
}
|
||||
|
||||
/** Résultat de recherche ; snippet = extrait du contenu qui correspond. */
|
||||
export interface Hit extends Entry {
|
||||
snippet?: string;
|
||||
}
|
||||
|
||||
export interface MoveResult {
|
||||
from: string;
|
||||
to?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export type Registration = "closed" | "approval" | "open";
|
||||
|
||||
/** Paramètres partagés ; logo = "" sans logo, sinon sa version. */
|
||||
export interface Settings {
|
||||
title: string;
|
||||
logo: string;
|
||||
trashDays: number;
|
||||
registration: Registration;
|
||||
quotaMB: number;
|
||||
commonReadonly: boolean;
|
||||
}
|
||||
|
||||
/** Version enregistrée d'un fichier (time : date de ce contenu). */
|
||||
export interface Version {
|
||||
id: string;
|
||||
time: string;
|
||||
size: number;
|
||||
}
|
||||
|
||||
/** Lien de partage (token : à placer dans /s/<token>). */
|
||||
export interface Share {
|
||||
id: string;
|
||||
token: string;
|
||||
path: string;
|
||||
isDir: boolean;
|
||||
created: string;
|
||||
expires?: string;
|
||||
protected?: boolean;
|
||||
downloads?: number;
|
||||
}
|
||||
|
||||
/** Jeton d'accès personnel à l'API. */
|
||||
export interface ApiToken {
|
||||
id: string;
|
||||
name: string;
|
||||
created: string;
|
||||
lastUsed?: string;
|
||||
}
|
||||
|
||||
export interface Usage {
|
||||
used: number;
|
||||
/** 0 : illimité. */
|
||||
quota: number;
|
||||
}
|
||||
|
||||
/** Session courante et réglages publics (GET /api/me, accessible sans connexion). */
|
||||
export interface Me {
|
||||
mode: "none" | "local" | "oidc" | "both";
|
||||
local: boolean;
|
||||
oidc: boolean;
|
||||
oidcName?: string;
|
||||
registration: Registration;
|
||||
/** Aucun administrateur : le premier compte créé le devient. */
|
||||
setup?: boolean;
|
||||
title: string;
|
||||
logo?: string;
|
||||
version?: string;
|
||||
user?: { id: string; name: string; email?: string; role: "admin" | "user"; provider?: "local" | "oidc" };
|
||||
admin: boolean;
|
||||
canChangePassword?: boolean;
|
||||
logout?: string;
|
||||
usage?: Usage;
|
||||
commonReadonly: boolean;
|
||||
/** Administrateur : inscriptions à valider. */
|
||||
pending?: number;
|
||||
}
|
||||
|
||||
export type Role = "admin" | "user";
|
||||
export type Status = "active" | "pending" | "disabled";
|
||||
|
||||
export interface Account {
|
||||
id: string;
|
||||
username?: string;
|
||||
name: string;
|
||||
email?: string;
|
||||
provider: "local" | "oidc";
|
||||
role: Role;
|
||||
status: Status;
|
||||
created: string;
|
||||
lastLogin?: string;
|
||||
}
|
||||
|
||||
export interface PublicEntry {
|
||||
name: string;
|
||||
isDir: boolean;
|
||||
size: number;
|
||||
modTime: string;
|
||||
}
|
||||
|
||||
/** Lien de partage tel que servi sans authentification. */
|
||||
export interface PublicInfo {
|
||||
title: string;
|
||||
logo?: string;
|
||||
protected?: boolean;
|
||||
name?: string;
|
||||
isDir: boolean;
|
||||
size: number;
|
||||
modTime: string;
|
||||
sub?: string;
|
||||
entries?: PublicEntry[];
|
||||
expires?: string;
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
message: string,
|
||||
public code?: string,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
async function request(url: string, init?: RequestInit): Promise<Response> {
|
||||
const res = await fetch(url, init);
|
||||
if (!res.ok) {
|
||||
// Session OIDC expirée : reconnexion, puis retour sur la page courante.
|
||||
const login = res.status === 401 ? res.headers.get("X-Auth-Login") : null;
|
||||
if (login) location.assign(`${login}?next=${encodeURIComponent(location.pathname + location.search + location.hash)}`);
|
||||
let msg = res.statusText;
|
||||
let code: string | undefined;
|
||||
try {
|
||||
const j = await res.json();
|
||||
msg = j.error ?? msg;
|
||||
code = j.code;
|
||||
} catch {
|
||||
/* corps non JSON */
|
||||
}
|
||||
throw new ApiError(res.status, msg, code);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
const q = (p: string) => encodeURIComponent(p);
|
||||
const json = (body: unknown, method = "POST"): RequestInit => ({
|
||||
method,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
export const api = {
|
||||
me: async (): Promise<Me> => (await request("/api/me")).json(),
|
||||
|
||||
// --- Connexion ---------------------------------------------------------------
|
||||
login: async (username: string, password: string): Promise<void> => {
|
||||
await request("/auth/local/login", json({ username, password }));
|
||||
},
|
||||
|
||||
/** Renvoie « active » (connecté d'office) ou « pending » (à valider par un administrateur). */
|
||||
register: async (v: { username: string; name: string; email: string; password: string }): Promise<"active" | "pending"> => {
|
||||
const res = await request("/auth/local/register", json(v));
|
||||
return (await res.json()).status;
|
||||
},
|
||||
|
||||
// --- Fichiers ----------------------------------------------------------------
|
||||
/** details : détails des entrées pour la vue Galerie. */
|
||||
list: async (dir: string, details = false): Promise<Entry[]> =>
|
||||
(await request(`/api/list?path=${q(dir)}${details ? "&details=1" : ""}`)).json(),
|
||||
|
||||
search: async (text: string, f: SearchFilter = {}, details = false): Promise<Hit[]> =>
|
||||
(
|
||||
await request(
|
||||
`/api/search?q=${q(text)}${f.tag ? `&tag=${q(f.tag)}` : ""}${f.fav ? "&fav=true" : ""}${details ? "&details=1" : ""}`,
|
||||
)
|
||||
).json(),
|
||||
|
||||
tags: async (): Promise<TagCount[]> => (await request("/api/tags")).json(),
|
||||
|
||||
setFavorite: async (paths: string[], favorite: boolean): Promise<void> => {
|
||||
await request("/api/meta/favorite", json({ paths, favorite }));
|
||||
},
|
||||
|
||||
editTags: async (paths: string[], add: string[], remove: string[]): Promise<void> => {
|
||||
await request("/api/meta/tags", json({ paths, add, remove }));
|
||||
},
|
||||
|
||||
/** icon = "" : dossier classique. */
|
||||
setIcon: async (paths: string[], icon: string): Promise<void> => {
|
||||
await request("/api/meta/icon", json({ paths, icon }));
|
||||
},
|
||||
|
||||
mkdir: async (path: string): Promise<Entry> => (await request("/api/folder", json({ path }))).json(),
|
||||
|
||||
move: async (from: string, to: string): Promise<Entry> => (await request("/api/move", json({ from, to }))).json(),
|
||||
|
||||
/** Déplace plusieurs éléments dans dir ; le détail par élément indique les échecs. */
|
||||
moveMany: async (paths: string[], dir: string): Promise<MoveResult[]> =>
|
||||
(await request("/api/move-many", json({ paths, dir }))).json(),
|
||||
|
||||
copy: async (from: string, to: string): Promise<Entry> => (await request("/api/copy", json({ from, to }))).json(),
|
||||
|
||||
/** Met à la poubelle ; dans .poubelle, supprime définitivement (path = .poubelle : la vide). */
|
||||
remove: async (path: string, recursive: boolean): Promise<void> => {
|
||||
await request(`/api/entry?path=${q(path)}&recursive=${recursive}`, { method: "DELETE" });
|
||||
},
|
||||
|
||||
/** Remet des éléments de la poubelle à leur emplacement d'origine (to : chemin restauré). */
|
||||
restoreTrash: async (paths: string[]): Promise<MoveResult[]> =>
|
||||
(await request("/api/trash/restore", json({ paths }))).json(),
|
||||
|
||||
/** Contenu texte d'un fichier (les premiers octets seulement : max). */
|
||||
readText: async (path: string, max = 512 * 1024): Promise<{ text: string; truncated: boolean }> => {
|
||||
const res = await request(`/api/file?path=${q(path)}&inline=1`, { headers: { Range: `bytes=0-${max - 1}` } });
|
||||
const total = Number((res.headers.get("Content-Range") ?? "").split("/")[1]);
|
||||
return { text: await res.text(), truncated: res.status === 206 && total > max };
|
||||
},
|
||||
|
||||
/** Empreinte SHA-256 (calculée à la demande côté serveur). */
|
||||
hash: async (path: string): Promise<string> => (await request(`/api/hash?path=${q(path)}`)).json().then((j) => j.sha256),
|
||||
|
||||
downloadUrl: (path: string, inline = false) => `/api/file?path=${q(path)}${inline ? "&inline=1" : ""}`,
|
||||
|
||||
/** v = date du fichier : l'URL change à chaque nouvelle version (cache navigateur). */
|
||||
thumbUrl: (path: string, v: string) => `/api/thumb?path=${q(path)}&v=${q(v)}`,
|
||||
|
||||
zipUrl: (path: string) => `/api/zip?path=${q(path)}`,
|
||||
|
||||
/** Télécharge une sélection en ZIP : formulaire POST, la réponse part en flux vers le navigateur. */
|
||||
zipSelection: (paths: string[]) => {
|
||||
const form = document.createElement("form");
|
||||
form.method = "POST";
|
||||
form.action = "/api/zip";
|
||||
form.style.display = "none";
|
||||
const input = document.createElement("input");
|
||||
input.name = "paths";
|
||||
input.value = JSON.stringify(paths);
|
||||
form.appendChild(input);
|
||||
document.body.appendChild(form);
|
||||
form.submit();
|
||||
form.remove();
|
||||
},
|
||||
|
||||
// --- Historique --------------------------------------------------------------
|
||||
history: async (path: string): Promise<Version[]> => (await request(`/api/history?path=${q(path)}`)).json(),
|
||||
|
||||
versionUrl: (path: string, id: string) => `/api/history/version?path=${q(path)}&id=${q(id)}`,
|
||||
|
||||
/** Crée une version du contenu courant (sans attendre un remplacement). */
|
||||
snapshot: async (path: string): Promise<Version> => (await request("/api/history/snapshot", json({ path }))).json(),
|
||||
|
||||
/** Restaure une version ; le contenu remplacé devient lui-même une version. */
|
||||
restore: async (path: string, id: string): Promise<Entry> => (await request("/api/history/restore", json({ path, id }))).json(),
|
||||
|
||||
// --- Partage -----------------------------------------------------------------
|
||||
/** Liens d'un élément, ou tous les liens si path est omis. */
|
||||
shares: async (path?: string): Promise<Share[]> => (await request(`/api/shares${path ? `?path=${q(path)}` : ""}`)).json(),
|
||||
|
||||
/** days = 0 : lien sans expiration ; password : facultatif. */
|
||||
createShare: async (path: string, days: number, password: string): Promise<Share> =>
|
||||
(await request("/api/shares", json({ path, days, password }))).json(),
|
||||
|
||||
revokeShare: async (id: string): Promise<void> => {
|
||||
await request(`/api/shares?id=${q(id)}`, { method: "DELETE" });
|
||||
},
|
||||
|
||||
revokeAllShares: async (): Promise<void> => {
|
||||
await request("/api/shares/revoke-all", { method: "POST" });
|
||||
},
|
||||
|
||||
shareUrl: (token: string) => `${location.origin}/s/${token}`,
|
||||
|
||||
publicInfo: async (token: string, sub = ""): Promise<PublicInfo> =>
|
||||
(await request(`/api/public/${q(token)}${sub ? `?sub=${q(sub)}` : ""}`)).json(),
|
||||
|
||||
publicUnlock: async (token: string, password: string): Promise<void> => {
|
||||
await request(`/api/public/${q(token)}/unlock`, json({ password }));
|
||||
},
|
||||
|
||||
publicFileUrl: (token: string, sub: string, inline = false) =>
|
||||
`/api/public/${q(token)}/file?sub=${q(sub)}${inline ? "&inline=1" : ""}`,
|
||||
|
||||
publicZipUrl: (token: string, sub: string) => `/api/public/${q(token)}/zip?sub=${q(sub)}`,
|
||||
|
||||
publicThumbUrl: (token: string, sub: string) => `/api/public/${q(token)}/thumb?sub=${q(sub)}`,
|
||||
|
||||
publicText: async (token: string, sub: string, max = 512 * 1024): Promise<string> =>
|
||||
(await request(`/api/public/${q(token)}/file?sub=${q(sub)}&inline=1`, { headers: { Range: `bytes=0-${max - 1}` } })).text(),
|
||||
|
||||
// --- Jetons d'API ------------------------------------------------------------
|
||||
tokens: async (): Promise<ApiToken[]> => (await request("/api/tokens")).json(),
|
||||
|
||||
/** Le jeton en clair (token) n'est renvoyé qu'à la création. */
|
||||
createToken: async (name: string): Promise<ApiToken & { token: string }> => (await request("/api/tokens", json({ name }))).json(),
|
||||
|
||||
revokeToken: async (id: string): Promise<void> => {
|
||||
await request(`/api/tokens/${q(id)}`, { method: "DELETE" });
|
||||
},
|
||||
|
||||
// --- Compte ------------------------------------------------------------------
|
||||
changePassword: async (current: string, next: string): Promise<void> => {
|
||||
await request("/api/account/password", json({ current, new: next }));
|
||||
},
|
||||
|
||||
patchAccount: async (v: { name?: string; email?: string }): Promise<void> => {
|
||||
await request("/api/account", json(v, "PATCH"));
|
||||
},
|
||||
|
||||
// --- Administration ----------------------------------------------------------
|
||||
users: async (): Promise<Account[]> => (await request("/api/admin/users")).json(),
|
||||
|
||||
createUser: async (v: { username: string; name: string; email: string; password: string; role: Role }): Promise<Account> =>
|
||||
(await request("/api/admin/users", json(v))).json(),
|
||||
|
||||
patchUser: async (id: string, v: Partial<{ name: string; email: string; role: Role; status: Status; password: string }>): Promise<Account> =>
|
||||
(await request(`/api/admin/users/${q(id)}`, json(v, "PATCH"))).json(),
|
||||
|
||||
deleteUser: async (id: string): Promise<void> => {
|
||||
await request(`/api/admin/users/${q(id)}`, { method: "DELETE" });
|
||||
},
|
||||
|
||||
settings: async (): Promise<Settings> => (await request("/api/settings")).json(),
|
||||
|
||||
setSettings: async (v: Partial<Pick<Settings, "title" | "trashDays" | "registration" | "quotaMB" | "commonReadonly">>): Promise<Settings> =>
|
||||
(await request("/api/settings", json(v, "PUT"))).json(),
|
||||
|
||||
/** Le serveur recadre au centre et ramène le PNG à 64x64. */
|
||||
uploadLogo: async (png: Blob): Promise<Settings> =>
|
||||
(await request("/api/logo", { method: "PUT", headers: { "Content-Type": "image/png" }, body: png })).json(),
|
||||
|
||||
removeLogo: async (): Promise<Settings> => (await request("/api/logo", { method: "DELETE" })).json(),
|
||||
|
||||
logoUrl: (v: string) => `/api/logo?v=${q(v)}`,
|
||||
};
|
||||
|
||||
export type Conflict = "fail" | "overwrite" | "rename";
|
||||
|
||||
/**
|
||||
* Dépose un fichier (PUT en flux) avec progression. mtime : date de modification
|
||||
* d'origine, conservée par le serveur. Rejette avec ApiError ; abort() annule.
|
||||
*/
|
||||
export function uploadFile(
|
||||
path: string,
|
||||
file: File,
|
||||
opts: { conflict: Conflict; onProgress?: (loaded: number) => void },
|
||||
): { promise: Promise<Entry>; abort: () => void } {
|
||||
const xhr = new XMLHttpRequest();
|
||||
const promise = new Promise<Entry>((resolve, reject) => {
|
||||
xhr.open("PUT", `/api/file?path=${q(path)}&conflict=${opts.conflict}&mtime=${file.lastModified}`);
|
||||
xhr.upload.onprogress = (e) => opts.onProgress?.(e.loaded);
|
||||
xhr.onload = () => {
|
||||
let body: { error?: string; code?: string } & Partial<Entry> = {};
|
||||
try {
|
||||
body = JSON.parse(xhr.responseText);
|
||||
} catch {
|
||||
/* corps non JSON */
|
||||
}
|
||||
const login = xhr.status === 401 ? xhr.getResponseHeader("X-Auth-Login") : null;
|
||||
if (login) location.assign(`${login}?next=${encodeURIComponent(location.pathname + location.search + location.hash)}`);
|
||||
if (xhr.status >= 200 && xhr.status < 300) resolve(body as Entry);
|
||||
else reject(new ApiError(xhr.status, body.error ?? (xhr.statusText || `HTTP ${xhr.status}`), body.code));
|
||||
};
|
||||
xhr.onerror = () => reject(new ApiError(0, "connexion interrompue"));
|
||||
xhr.onabort = () => reject(new ApiError(0, "annulé"));
|
||||
xhr.send(file);
|
||||
});
|
||||
return { promise, abort: () => xhr.abort() };
|
||||
}
|
||||
|
||||
// Helpers de chemins (format "slash", relatifs à la racine).
|
||||
export const dirname = (p: string) => (p.includes("/") ? p.slice(0, p.lastIndexOf("/")) : "");
|
||||
export const basename = (p: string) => p.slice(p.lastIndexOf("/") + 1);
|
||||
export const join = (dir: string, name: string) => (dir ? `${dir}/${name}` : name);
|
||||
|
||||
// Dossiers propres à l'utilisateur connecté (voir internal/storage/spaces.go).
|
||||
export const PERSO = ".perso";
|
||||
export const FAVORIS = ".favoris";
|
||||
export const POUBELLE = ".poubelle";
|
||||
const SPECIAL_LABELS: Record<string, string> = { [PERSO]: "Personnel", [FAVORIS]: "Favoris", [POUBELLE]: "Poubelle" };
|
||||
/** Libellé d'un composant de chemin (".perso" → "Personnel"). */
|
||||
export const label = (part: string) => SPECIAL_LABELS[part] ?? part;
|
||||
/** Chemin affiché : "Personnel/projets" pour ".perso/projets". */
|
||||
export const displayPath = (p: string) => p.split("/").map(label).join("/");
|
||||
export const inFavoris = (p: string) => p === FAVORIS || p.startsWith(FAVORIS + "/");
|
||||
export const inPoubelle = (p: string) => p === POUBELLE || p.startsWith(POUBELLE + "/");
|
||||
export const inPerso = (p: string) => p === PERSO || p.startsWith(PERSO + "/");
|
||||
|
||||
/** Extension (sans le point, minuscules) ; vide si aucune. */
|
||||
export const extOf = (name: string) => {
|
||||
const i = name.lastIndexOf(".");
|
||||
return i > 0 ? name.slice(i + 1).toLowerCase() : "";
|
||||
};
|
||||
@@ -0,0 +1,81 @@
|
||||
// Type d'un fichier d'après son extension : icône, aperçu possible, libellé.
|
||||
import { extOf } from "./api";
|
||||
|
||||
export type Kind = "image" | "video" | "audio" | "pdf" | "text" | "code" | "archive" | "doc" | "sheet" | "slides" | "other";
|
||||
|
||||
const sets: Record<Exclude<Kind, "other">, string> = {
|
||||
image: "png jpg jpeg gif webp avif bmp svg ico heic heif tif tiff raw cr2 nef dng",
|
||||
video: "mp4 webm mov m4v ogv mkv avi wmv flv mpg mpeg 3gp",
|
||||
audio: "mp3 ogg oga wav flac aac m4a opus wma aiff mid midi",
|
||||
pdf: "pdf",
|
||||
text: "txt md markdown rst log csv tsv json yaml yml toml ini conf cfg env srt tex bib nfo",
|
||||
code: "html htm css js mjs ts tsx jsx py go rs java c h cpp hpp cs php rb sh bash zsh ps1 sql tf lua xml vue svelte service gitignore",
|
||||
archive: "zip gz tgz bz2 xz 7z rar tar zst iso dmg jar deb rpm apk",
|
||||
doc: "doc docx odt rtf pages",
|
||||
sheet: "xls xlsx ods numbers",
|
||||
slides: "ppt pptx odp key",
|
||||
};
|
||||
|
||||
const byExt = new Map<string, Kind>();
|
||||
for (const [kind, list] of Object.entries(sets)) for (const e of list.split(" ")) byExt.set(e, kind as Kind);
|
||||
|
||||
const textNames = new Set(["dockerfile", "makefile", "readme", "license", "changelog"]);
|
||||
|
||||
export const kindOf = (name: string): Kind => {
|
||||
const k = byExt.get(extOf(name));
|
||||
if (k) return k;
|
||||
return textNames.has(name.toLowerCase()) ? "text" : "other";
|
||||
};
|
||||
|
||||
/** Le serveur sait-il en faire une miniature (JPEG, PNG, GIF) ? */
|
||||
export const serverThumb = (name: string) => ["jpg", "jpeg", "png", "gif"].includes(extOf(name));
|
||||
|
||||
/** Le navigateur affiche-t-il ce format d'image tel quel ? */
|
||||
export const browserImage = (name: string) => ["png", "jpg", "jpeg", "gif", "webp", "avif", "bmp", "svg", "ico"].includes(extOf(name));
|
||||
|
||||
const browserVideo = ["mp4", "webm", "mov", "m4v", "ogv"];
|
||||
const browserAudio = ["mp3", "ogg", "oga", "wav", "flac", "aac", "m4a", "opus"];
|
||||
|
||||
/** Aperçu intégré possible ? (texte limité aux premiers Mo, vidéo et audio selon le navigateur). */
|
||||
export const previewable = (name: string): boolean => {
|
||||
const k = kindOf(name);
|
||||
const e = extOf(name);
|
||||
switch (k) {
|
||||
case "image":
|
||||
return browserImage(name);
|
||||
case "video":
|
||||
return browserVideo.includes(e);
|
||||
case "audio":
|
||||
return browserAudio.includes(e);
|
||||
case "pdf":
|
||||
case "text":
|
||||
case "code":
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const labels: Record<Kind, string> = {
|
||||
image: "Image",
|
||||
video: "Vidéo",
|
||||
audio: "Audio",
|
||||
pdf: "PDF",
|
||||
text: "Texte",
|
||||
code: "Code",
|
||||
archive: "Archive",
|
||||
doc: "Document",
|
||||
sheet: "Tableur",
|
||||
slides: "Présentation",
|
||||
other: "Fichier",
|
||||
};
|
||||
|
||||
/** « Image PNG », « Archive ZIP », « Fichier »... */
|
||||
export const typeLabel = (name: string): string => {
|
||||
const e = extOf(name).toUpperCase();
|
||||
const k = kindOf(name);
|
||||
return e ? (k === "other" ? `Fichier ${e}` : `${labels[k]} ${e}`) : labels[k];
|
||||
};
|
||||
|
||||
/** Texte à afficher en monospace (code, journaux, configuration). */
|
||||
export const monospace = (name: string) => kindOf(name) !== "text" || !["txt", "md", "markdown", "rst", "srt", "nfo"].includes(extOf(name));
|
||||
@@ -0,0 +1,251 @@
|
||||
// Icônes proposées pour les dossiers (jeu Tabler, comme icons.tsx). Le nom est
|
||||
// enregistré côté serveur (.meta.json) : ne pas renommer une clé existante.
|
||||
import { FolderIcon, icon } from "./icons";
|
||||
|
||||
type Icon = ReturnType<typeof icon>;
|
||||
|
||||
export const FOLDER_ICONS: { name: string; label: string; Icon: Icon }[] = [
|
||||
{
|
||||
name: "briefcase",
|
||||
label: "Projet",
|
||||
Icon: icon(
|
||||
<>
|
||||
<rect x="3" y="7" width="18" height="13" rx="2" />
|
||||
<path d="M8 7V5a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M12 12v.01M3 13a20 20 0 0 0 18 0" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "rocket",
|
||||
label: "Production",
|
||||
Icon: icon(
|
||||
<>
|
||||
<path d="M4 13a8 8 0 0 1 7 7 6 6 0 0 0 3-5 9 9 0 0 0 6-8 3 3 0 0 0-3-3 9 9 0 0 0-8 6 6 6 0 0 0-5 3" />
|
||||
<path d="M7 14a6 6 0 0 0-3 6 6 6 0 0 0 6-3" />
|
||||
<circle cx="15" cy="9" r="1" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "server",
|
||||
label: "Serveurs",
|
||||
Icon: icon(
|
||||
<>
|
||||
<rect x="3" y="4" width="18" height="8" rx="3" />
|
||||
<rect x="3" y="12" width="18" height="8" rx="3" />
|
||||
<path d="M7 8v.01M7 16v.01" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "cpu",
|
||||
label: "Calcul",
|
||||
Icon: icon(
|
||||
<>
|
||||
<rect x="5" y="5" width="14" height="14" rx="1" />
|
||||
<rect x="9" y="9" width="6" height="6" />
|
||||
<path d="M3 10h2M3 14h2M10 3v2M14 3v2M21 10h-2M21 14h-2M14 21v-2M10 21v-2" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "database",
|
||||
label: "Stockage",
|
||||
Icon: icon(
|
||||
<>
|
||||
<ellipse cx="12" cy="6" rx="8" ry="3" />
|
||||
<path d="M4 6v6a8 3 0 0 0 16 0V6M4 12v6a8 3 0 0 0 16 0v-6" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "box",
|
||||
label: "Conteneurs",
|
||||
Icon: icon(<path d="M12 3l8 4.5v9L12 21l-8-4.5v-9L12 3M12 12l8-4.5M12 12v9M12 12 4 7.5" />),
|
||||
},
|
||||
{
|
||||
name: "cloud",
|
||||
label: "Cloud",
|
||||
Icon: icon(
|
||||
<path d="M6.66 18C4.08 18 2 15.99 2 13.52s2.09-4.49 4.66-4.49c.39-1.76 1.79-3.2 3.67-3.77 1.88-.57 3.96-.19 5.44 1 1.49 1.19 2.16 3.01 1.77 4.77h.99c1.91 0 3.46 1.56 3.46 3.49S20.45 18 18.54 18H6.66" />,
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "network",
|
||||
label: "Réseau",
|
||||
Icon: icon(
|
||||
<>
|
||||
<circle cx="12" cy="9" r="6" />
|
||||
<path d="M12 3c1.33.33 2 2.33 2 6s-.67 5.67-2 6M12 3c-1.33.33-2 2.33-2 6s.67 5.67 2 6M6 9h12M3 20h7M14 20h7M12 15v3" />
|
||||
<circle cx="12" cy="20" r="2" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "sitemap",
|
||||
label: "Topologie",
|
||||
Icon: icon(
|
||||
<>
|
||||
<rect x="3" y="15" width="6" height="6" rx="2" />
|
||||
<rect x="15" y="15" width="6" height="6" rx="2" />
|
||||
<rect x="9" y="3" width="6" height="6" rx="2" />
|
||||
<path d="M6 15v-1a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v1M12 9v3" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "router",
|
||||
label: "Routeur",
|
||||
Icon: icon(
|
||||
<>
|
||||
<rect x="3" y="13" width="18" height="8" rx="2" />
|
||||
<path d="M17 17v.01M13 17v.01M15 13v-2M11.75 8.75a4 4 0 0 1 6.5 0M8.5 6.5a8 8 0 0 1 13 0" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "world",
|
||||
label: "Internet",
|
||||
Icon: icon(
|
||||
<>
|
||||
<circle cx="12" cy="12" r="9" />
|
||||
<path d="M3.6 9h16.8M3.6 15h16.8M11.5 3a17 17 0 0 0 0 18M12.5 3a17 17 0 0 1 0 18" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "shield",
|
||||
label: "Sécurité",
|
||||
Icon: icon(<path d="M12 3a12 12 0 0 0 8.5 3A12 12 0 0 1 12 21 12 12 0 0 1 3.5 6 12 12 0 0 0 12 3" />),
|
||||
},
|
||||
{
|
||||
name: "lock",
|
||||
label: "Confidentiel",
|
||||
Icon: icon(
|
||||
<>
|
||||
<rect x="5" y="11" width="14" height="10" rx="2" />
|
||||
<circle cx="12" cy="16" r="1" />
|
||||
<path d="M8 11V7a4 4 0 1 1 8 0v4" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "desktop",
|
||||
label: "Postes",
|
||||
Icon: icon(
|
||||
<>
|
||||
<rect x="3" y="4" width="18" height="12" rx="1" />
|
||||
<path d="M7 20h10M9 16v4M15 16v4" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "code",
|
||||
label: "Code",
|
||||
Icon: icon(<path d="M7 8l-4 4 4 4M17 8l4 4-4 4M14 4l-4 16" />),
|
||||
},
|
||||
{
|
||||
name: "tool",
|
||||
label: "Outils",
|
||||
Icon: icon(<path d="M7 10h3V7L6.5 3.5a6 6 0 0 1 8 8l6 6a2 2 0 0 1-3 3l-6-6a6 6 0 0 1-8-8L7 10" />),
|
||||
},
|
||||
{
|
||||
name: "file-text",
|
||||
label: "Documents",
|
||||
Icon: icon(
|
||||
<>
|
||||
<path d="M14 3v4a1 1 0 0 0 1 1h4" />
|
||||
<path d="M17 21H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7l5 5v11a2 2 0 0 1-2 2zM9 9h1M9 13h6M9 17h6" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "book",
|
||||
label: "Documentation",
|
||||
Icon: icon(<path d="M3 19a9 9 0 0 1 9 0 9 9 0 0 1 9 0M3 6a9 9 0 0 1 9 0 9 9 0 0 1 9 0M3 6v13M12 6v13M21 6v13" />),
|
||||
},
|
||||
{
|
||||
name: "presentation",
|
||||
label: "Présentations",
|
||||
Icon: icon(<path d="M3 4h18M4 4v10a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V4M12 16v4M9 20h6M8 12l3-3 2 2 3-3" />),
|
||||
},
|
||||
{
|
||||
name: "chart",
|
||||
label: "Indicateurs",
|
||||
Icon: icon(
|
||||
<>
|
||||
<rect x="3" y="12" width="6" height="8" rx="1" />
|
||||
<rect x="9" y="8" width="6" height="12" rx="1" />
|
||||
<rect x="15" y="4" width="6" height="16" rx="1" />
|
||||
<path d="M4 20h14" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "bulb",
|
||||
label: "Idées",
|
||||
Icon: icon(
|
||||
<path d="M3 12h1m8-9v1m8 8h1M5.6 5.6l.7.7m12.1-.7-.7.7M9 16a5 5 0 1 1 6 0 3.5 3.5 0 0 0-1 3 2 2 0 0 1-4 0 3.5 3.5 0 0 0-1-3M9.7 17h4.6" />,
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "users",
|
||||
label: "Équipe",
|
||||
Icon: icon(
|
||||
<>
|
||||
<circle cx="9" cy="7" r="4" />
|
||||
<path d="M3 21v-2a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v2M16 3.13a4 4 0 0 1 0 7.75M21 21v-2a4 4 0 0 0-3-3.85" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "building",
|
||||
label: "Client / site",
|
||||
Icon: icon(
|
||||
<path d="M3 21h18M9 8h1M9 12h1M9 16h1M14 8h1M14 12h1M14 16h1M5 21V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16" />,
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "calendar",
|
||||
label: "Planning",
|
||||
Icon: icon(
|
||||
<>
|
||||
<rect x="4" y="5" width="16" height="16" rx="2" />
|
||||
<path d="M16 3v4M8 3v4M4 11h16" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "photo",
|
||||
label: "Images",
|
||||
Icon: icon(
|
||||
<>
|
||||
<rect x="3" y="3" width="18" height="18" rx="3" />
|
||||
<path d="M15 8h.01M3 16l5-5c.93-.89 2.07-.89 3 0l5 5M14 14l1-1c.93-.89 2.07-.89 3 0l3 3" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "flag",
|
||||
label: "Jalons",
|
||||
Icon: icon(<path d="M5 5a5 5 0 0 1 7 0 5 5 0 0 0 7 0v9a5 5 0 0 1-7 0 5 5 0 0 0-7 0V5M5 21v-7" />),
|
||||
},
|
||||
{
|
||||
name: "archive",
|
||||
label: "Archives",
|
||||
Icon: icon(
|
||||
<>
|
||||
<rect x="3" y="4" width="18" height="4" rx="2" />
|
||||
<path d="M5 8v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8M10 12h4" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const BY_NAME = new Map(FOLDER_ICONS.map((i) => [i.name, i.Icon]));
|
||||
|
||||
/** Icône d'un dossier : celle choisie, ou le dossier classique (nom absent ou inconnu). */
|
||||
export function FolderGlyph({ name, size }: { name?: string; size?: number }) {
|
||||
const Icon = (name && BY_NAME.get(name)) || FolderIcon;
|
||||
return <Icon size={size} />;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// Mise en forme des dates, tailles et auteurs (explorateur, panneau Détails).
|
||||
|
||||
export const fmtDate = (iso: string) => new Date(iso).toLocaleString(undefined, { dateStyle: "short", timeStyle: "short" });
|
||||
|
||||
export const fmtSize = (n: number) => {
|
||||
if (n < 1024) return `${n} o`;
|
||||
const units = ["Ko", "Mo", "Go", "To"];
|
||||
let v = n / 1024;
|
||||
let i = 0;
|
||||
while (v >= 1024 && i < units.length - 1) {
|
||||
v /= 1024;
|
||||
i++;
|
||||
}
|
||||
return `${v >= 100 ? v.toFixed(0) : v.toFixed(1)} ${units[i]}`;
|
||||
};
|
||||
|
||||
export const fmtRate = (bytesPerSecond: number) => `${fmtSize(bytesPerSecond)}/s`;
|
||||
|
||||
export const plural = (n: number, word: string) => `${n} ${word}${n > 1 ? "s" : ""}`;
|
||||
|
||||
const relative = new Intl.RelativeTimeFormat("fr", { numeric: "auto" });
|
||||
|
||||
/** « à l'instant », « il y a 5 minutes », « hier »… puis la date au-delà d'un mois. */
|
||||
export const fmtRelative = (iso: string) => {
|
||||
const s = (Date.now() - new Date(iso).getTime()) / 1000;
|
||||
if (s < 60) return "à l'instant";
|
||||
if (s < 3600) return relative.format(-Math.round(s / 60), "minute");
|
||||
if (s < 86400) return relative.format(-Math.round(s / 3600), "hour");
|
||||
if (s < 30 * 86400) return relative.format(-Math.round(s / 86400), "day");
|
||||
return new Date(iso).toLocaleDateString(undefined, { dateStyle: "medium" });
|
||||
};
|
||||
|
||||
/** Auteur affichable : rien pour l'utilisateur unique sans authentification. */
|
||||
export const who = (id?: string) => (id && id !== "local" ? id : "");
|
||||
|
||||
/** Initiales d'un nom pour l'avatar. */
|
||||
export const initials = (name: string) =>
|
||||
name
|
||||
.split(/[\s._@-]+/)
|
||||
.filter(Boolean)
|
||||
.slice(0, 2)
|
||||
.map((p) => p[0].toUpperCase())
|
||||
.join("") || "?";
|
||||
@@ -0,0 +1,440 @@
|
||||
// Icônes au trait, dans le style d'Excalidraw (jeu Tabler, trait fin, couleur héritée).
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
export const icon = (paths: ReactNode) =>
|
||||
function Icon({ size = 16, className }: { size?: number; className?: string }) {
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.5}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className={className}
|
||||
aria-hidden
|
||||
>
|
||||
{paths}
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
export const SunIcon = icon(
|
||||
<>
|
||||
<circle cx="12" cy="12" r="4" />
|
||||
<path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const MoonIcon = icon(<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9z" />);
|
||||
|
||||
export const SettingsIcon = icon(
|
||||
<>
|
||||
<path d="M10.33 4.32c.43-1.76 2.93-1.76 3.35 0a1.72 1.72 0 0 0 2.57 1.07c1.54-.94 3.31.83 2.37 2.37a1.72 1.72 0 0 0 1.07 2.57c1.76.43 1.76 2.93 0 3.35a1.72 1.72 0 0 0-1.07 2.57c.94 1.54-.83 3.31-2.37 2.37a1.72 1.72 0 0 0-2.57 1.07c-.43 1.76-2.93 1.76-3.35 0a1.72 1.72 0 0 0-2.57-1.07c-1.54.94-3.31-.83-2.37-2.37a1.72 1.72 0 0 0-1.07-2.57c-1.76-.43-1.76-2.93 0-3.35a1.72 1.72 0 0 0 1.07-2.57c-.94-1.54.83-3.31 2.37-2.37 1 .61 2.3.07 2.57-1.07z" />
|
||||
<circle cx="12" cy="12" r="3" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const MenuIcon = icon(<path d="M4 6h16M4 12h16M4 18h16" />);
|
||||
|
||||
export const CloseIcon = icon(<path d="M18 6 6 18M6 6l12 12" />);
|
||||
|
||||
export const FilePlusIcon = icon(
|
||||
<>
|
||||
<path d="M14 3v4a1 1 0 0 0 1 1h4" />
|
||||
<path d="M17 21H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7l5 5v11a2 2 0 0 1-2 2z" />
|
||||
<path d="M12 11v6M9 14h6" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const FolderPlusIcon = icon(
|
||||
<>
|
||||
<path d="M12 19H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h4l3 3h7a2 2 0 0 1 2 2v3.5" />
|
||||
<path d="M16 19h6M19 16v6" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const UploadIcon = icon(
|
||||
<>
|
||||
<path d="M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2" />
|
||||
<path d="M7 9l5-5 5 5M12 4v12" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const FolderUploadIcon = icon(
|
||||
<>
|
||||
<path d="M12 19H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h4l3 3h7a2 2 0 0 1 2 2v3" />
|
||||
<path d="M19 22v-6M22 19l-3-3-3 3" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const FolderIcon = icon(
|
||||
<path d="M5 4h4l3 3h7a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2" />,
|
||||
);
|
||||
|
||||
export const UpIcon = icon(<path d="M18 18h-6a3 3 0 0 1-3-3V5M13 10 9 6 5 10" />);
|
||||
|
||||
export const SearchIcon = icon(
|
||||
<>
|
||||
<circle cx="10" cy="10" r="7" />
|
||||
<path d="m21 21-6-6" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const ListIcon = icon(<path d="M9 6h11M9 12h11M9 18h11M5 6v.01M5 12v.01M5 18v.01" />);
|
||||
|
||||
export const GridIcon = icon(
|
||||
<>
|
||||
<rect x="4" y="4" width="6" height="6" rx="1" />
|
||||
<rect x="14" y="4" width="6" height="6" rx="1" />
|
||||
<rect x="4" y="14" width="6" height="6" rx="1" />
|
||||
<rect x="14" y="14" width="6" height="6" rx="1" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const RefreshIcon = icon(
|
||||
<>
|
||||
<path d="M20 11A8.1 8.1 0 0 0 4.5 9M4 5v4h4" />
|
||||
<path d="M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const DotsIcon = icon(
|
||||
<>
|
||||
<circle cx="5" cy="12" r="1" />
|
||||
<circle cx="12" cy="12" r="1" />
|
||||
<circle cx="19" cy="12" r="1" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const TrashIcon = icon(
|
||||
<path d="M4 7h16M10 11v6M14 11v6M5 7l1 12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2l1-12M9 7V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3" />,
|
||||
);
|
||||
|
||||
/** Poubelle qui contient des éléments : une feuille et une boule de papier dépassent du bord. */
|
||||
export const TrashFullIcon = icon(
|
||||
<>
|
||||
<path d="M4 10h16M5 10l1 9a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2l1-9M10 14v3M14 14v3" />
|
||||
<path d="M7.5 10 9 3.5l4.5 1-1.2 5.5M10.2 6.5l2 .5" />
|
||||
<circle cx="16" cy="7.8" r="2.2" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const RestoreIcon = icon(<path d="M9 14l-4-4 4-4M5 10h11a4 4 0 1 1 0 8h-1" />);
|
||||
|
||||
export const FileIcon = icon(
|
||||
<>
|
||||
<path d="M14 3v4a1 1 0 0 0 1 1h4" />
|
||||
<path d="M17 21H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7l5 5v11a2 2 0 0 1-2 2z" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const SelectAllIcon = icon(
|
||||
<>
|
||||
<rect x="4" y="4" width="16" height="16" rx="2" />
|
||||
<path d="m9 12 2 2 4-4" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const DeselectIcon = icon(<rect x="4" y="4" width="16" height="16" rx="2" />);
|
||||
|
||||
export const MoveIcon = icon(
|
||||
<>
|
||||
<path d="M12 19H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h4l3 3h7a2 2 0 0 1 2 2v3" />
|
||||
<path d="M16 19h6M19 16l3 3-3 3" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const SaveIcon = icon(
|
||||
<>
|
||||
<path d="M6 4h10l4 4v10a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2" />
|
||||
<circle cx="12" cy="14" r="2" />
|
||||
<path d="M14 4v4H8V4" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const UpdateIcon = icon(
|
||||
<>
|
||||
<circle cx="12" cy="12" r="9" />
|
||||
<path d="M12 16V8M8.5 11.5 12 8l3.5 3.5" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const CopyIcon = icon(
|
||||
<>
|
||||
<rect x="8" y="8" width="12" height="12" rx="2" />
|
||||
<path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const EditIcon = icon(<path d="M4 20h4L18.5 9.5a2.83 2.83 0 0 0-4-4L4 16v4M13.5 6.5l4 4" />);
|
||||
|
||||
export const HistoryIcon = icon(
|
||||
<>
|
||||
<path d="M12 8v4l2 2" />
|
||||
<path d="M3.05 11a9 9 0 1 1 .5 4m-.5 5v-5h5" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const DownloadIcon = icon(
|
||||
<>
|
||||
<path d="M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2" />
|
||||
<path d="M7 11l5 5 5-5M12 4v12" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const StarIcon = icon(
|
||||
<path d="M12 17.75l-6.17 3.24 1.18-6.87-5-4.86 6.9-1 3.09-6.26 3.09 6.26 6.9 1-5 4.86 1.18 6.87z" />,
|
||||
);
|
||||
|
||||
/** Étoile pleine (favori). */
|
||||
export function StarFilledIcon({ size = 16 }: { size?: number }) {
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" strokeWidth={1.5} strokeLinejoin="round" aria-hidden>
|
||||
<path d="M12 17.75l-6.17 3.24 1.18-6.87-5-4.86 6.9-1 3.09-6.26 3.09 6.26 6.9 1-5 4.86 1.18 6.87z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export const TagIcon = icon(
|
||||
<>
|
||||
<circle cx="8.5" cy="8.5" r="1" />
|
||||
<path d="M4 7v3.86a2 2 0 0 0 .59 1.41l7.71 7.71a2.4 2.4 0 0 0 3.4 0l4.27-4.27a2.4 2.4 0 0 0 0-3.4L12.26 4.59A2 2 0 0 0 10.85 4H7a3 3 0 0 0-3 3z" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const ShareIcon = icon(
|
||||
<>
|
||||
<circle cx="6" cy="12" r="3" />
|
||||
<circle cx="18" cy="6" r="3" />
|
||||
<circle cx="18" cy="18" r="3" />
|
||||
<path d="M8.7 10.7l6.6-3.4M8.7 13.3l6.6 3.4" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const EyeIcon = icon(
|
||||
<>
|
||||
<circle cx="12" cy="12" r="2" />
|
||||
<path d="M22 12c-2.67 4.67-6 7-10 7s-7.33-2.33-10-7c2.67-4.67 6-7 10-7s7.33 2.33 10 7" />
|
||||
</>,
|
||||
);
|
||||
|
||||
/** Punaise : panneau épinglé ou flottant (comme le bouton d'ancrage des panneaux d'Excalidraw). */
|
||||
export const PinIcon = icon(<path d="M15 4.5l-4 4-4 1.5-1.5 1.5 7 7 1.5-1.5 1.5-4 4-4M9 15l-4.5 4.5M14.5 4 20 9.5" />);
|
||||
|
||||
/** Espace personnel de l'utilisateur. */
|
||||
export const UserIcon = icon(
|
||||
<>
|
||||
<circle cx="12" cy="8" r="4" />
|
||||
<path d="M6 21v-2a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v2" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const LogoutIcon = icon(
|
||||
<>
|
||||
<path d="M14 8V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h7a2 2 0 0 0 2-2v-2" />
|
||||
<path d="M9 12h12l-3-3M18 15l3-3" />
|
||||
</>,
|
||||
);
|
||||
|
||||
// Vue Galerie et ses métadonnées.
|
||||
export const GalleryIcon = icon(
|
||||
<>
|
||||
<rect x="3" y="4" width="8" height="7" rx="1.5" />
|
||||
<rect x="13" y="4" width="8" height="7" rx="1.5" />
|
||||
<path d="M3 15h8M3 19h5M13 15h8M13 19h5" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const ClockIcon = icon(
|
||||
<>
|
||||
<circle cx="12" cy="12" r="9" />
|
||||
<path d="M12 7v5l3 3" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const ShapesIcon = icon(
|
||||
<>
|
||||
<rect x="3" y="3" width="8" height="8" rx="1" />
|
||||
<circle cx="17" cy="17" r="4" />
|
||||
<path d="M17 3l4 7h-8z" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const TextIcon = icon(<path d="M6 4h12M12 4v16M9 20h6" />);
|
||||
|
||||
export const PhotoIcon = icon(
|
||||
<>
|
||||
<rect x="3" y="4" width="18" height="16" rx="2" />
|
||||
<circle cx="9" cy="10" r="1.5" />
|
||||
<path d="M21 16l-5-5-8 9" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const FrameIcon = icon(<path d="M4 7h16M4 17h16M7 4v16M17 4v16" />);
|
||||
|
||||
export const ArrowIcon = icon(<path d="M5 19 19 5M10 5h9v9" />);
|
||||
|
||||
export const SizeIcon = icon(
|
||||
<>
|
||||
<path d="M6 4h10l4 4v10a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z" />
|
||||
<path d="M8 4v5h7V4M8 20v-6h8v6" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const SortIcon = icon(<path d="M4 6h9M4 12h7M4 18h5M17 4v16M14 17l3 3 3-3" />);
|
||||
|
||||
export const InfoIcon = icon(
|
||||
<>
|
||||
<circle cx="12" cy="12" r="9" />
|
||||
<path d="M12 8v.01M11 12h1v4h1" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const LinkIcon = icon(
|
||||
<path d="M9 15l6-6M11 6l.46-.54a5 5 0 0 1 7.07 7.07l-.53.47M13 18l-.4.53a5 5 0 0 1-7.07-7.07L6 11" />,
|
||||
);
|
||||
|
||||
// --- Types de fichiers, aperçu, comptes ---------------------------------------------
|
||||
|
||||
const page = <path d="M14 3v4a1 1 0 0 0 1 1h4M17 21H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7l5 5v11a2 2 0 0 1-2 2z" />;
|
||||
|
||||
export const FileTextIcon = icon(
|
||||
<>
|
||||
{page}
|
||||
<path d="M9 9h1M9 13h6M9 17h6" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const FileCodeIcon = icon(
|
||||
<>
|
||||
{page}
|
||||
<path d="M10 13l-2 2 2 2M14 13l2 2-2 2" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const FileZipIcon = icon(
|
||||
<>
|
||||
{page}
|
||||
<path d="M11 4h2M11 7h2M11 10h2M11 13h2" />
|
||||
<rect x="10" y="15" width="4" height="4" rx="1" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const FileMusicIcon = icon(
|
||||
<>
|
||||
{page}
|
||||
<circle cx="10" cy="17" r="1.5" />
|
||||
<path d="M11.5 17v-5l3 1" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const FileVideoIcon = icon(
|
||||
<>
|
||||
{page}
|
||||
<path d="M10 12.5v5l4-2.5z" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const FilePdfIcon = icon(
|
||||
<>
|
||||
{page}
|
||||
<path d="M8 17v-4h1.5a1.2 1.2 0 0 1 0 2.4H8M12.5 13v4M12.5 13h1a1.5 1.5 0 0 1 1.5 1.5v1a1.5 1.5 0 0 1-1.5 1.5h-1" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const FileSheetIcon = icon(
|
||||
<>
|
||||
{page}
|
||||
<path d="M8 12h8M8 15h8M8 18h8M11 12v6" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const FileSlidesIcon = icon(
|
||||
<>
|
||||
{page}
|
||||
<path d="M8 18v-3M12 18v-6M16 18v-4" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const FileImageIcon = icon(
|
||||
<>
|
||||
{page}
|
||||
<circle cx="10" cy="12" r="1.2" />
|
||||
<path d="M17 17l-3-3-5 4" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const PlayIcon = icon(<path d="M7 4v16l13-8z" />);
|
||||
|
||||
export const ChevronLeftIcon = icon(<path d="M15 6l-6 6 6 6" />);
|
||||
export const ChevronRightIcon = icon(<path d="M9 6l6 6-6 6" />);
|
||||
export const ChevronDownIcon = icon(<path d="M6 9l6 6 6-6" />);
|
||||
|
||||
export const LockIcon = icon(
|
||||
<>
|
||||
<rect x="5" y="11" width="14" height="10" rx="2" />
|
||||
<path d="M8 11V7a4 4 0 0 1 8 0v4M12 15v2" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const KeyIcon = icon(
|
||||
<>
|
||||
<circle cx="8" cy="15" r="4" />
|
||||
<path d="M10.85 12.15L19 4M18 5l2 2M15 8l2 2" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const UsersIcon = icon(
|
||||
<>
|
||||
<circle cx="9" cy="8" r="3.5" />
|
||||
<path d="M3 20v-1a5 5 0 0 1 5-5h2a5 5 0 0 1 5 5v1M16 4.6a3.5 3.5 0 0 1 0 6.8M21 20v-1a5 5 0 0 0-3.5-4.7" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const ShieldIcon = icon(<path d="M12 3l8 3v6c0 4.5-3.2 8-8 9-4.8-1-8-4.5-8-9V6z" />);
|
||||
|
||||
export const CheckIcon = icon(<path d="M5 12l5 5L20 7" />);
|
||||
|
||||
export const PlusIcon = icon(<path d="M12 5v14M5 12h14" />);
|
||||
|
||||
export const HomeIcon = icon(
|
||||
<>
|
||||
<path d="M5 12H3l9-9 9 9h-2" />
|
||||
<path d="M5 12v7a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-7M9 21v-6a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v6" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const TableIcon = icon(
|
||||
<>
|
||||
<rect x="3" y="4" width="18" height="16" rx="2" />
|
||||
<path d="M3 10h18M3 15h18M10 4v16" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const CloudIcon = icon(<path d="M7 18a4.5 4.5 0 0 1-.5-9 6 6 0 0 1 11.4 1.5A3.5 3.5 0 0 1 17.5 18z" />);
|
||||
|
||||
export const CloudUpIcon = icon(
|
||||
<>
|
||||
<path d="M7 18a4.5 4.5 0 0 1-.5-9 6 6 0 0 1 11.4 1.5A3.5 3.5 0 0 1 17.5 18" />
|
||||
<path d="M9 14l3-3 3 3M12 11v9" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const ExpandIcon = icon(<path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5" />);
|
||||
|
||||
export const CopyLinkIcon = icon(
|
||||
<>
|
||||
<rect x="9" y="9" width="11" height="11" rx="2" />
|
||||
<path d="M5 15V6a2 2 0 0 1 2-2h9" />
|
||||
</>,
|
||||
);
|
||||
|
||||
export const WarningIcon = icon(
|
||||
<>
|
||||
<path d="M12 3l10 18H2z" />
|
||||
<path d="M12 10v5M12 18v.01" />
|
||||
</>,
|
||||
);
|
||||
@@ -0,0 +1,91 @@
|
||||
// Lecture de fichiers et d'arborescences à envoyer (glisser-déposer ou sélecteur de dossier).
|
||||
|
||||
export interface PickedFile {
|
||||
/** Chemin relatif au point d'envoi, dossiers compris (« Photos/2024/img.jpg »). */
|
||||
rel: string;
|
||||
file: File;
|
||||
}
|
||||
|
||||
export interface Collected {
|
||||
files: PickedFile[];
|
||||
/** Dossiers à recréer (y compris vides), parents avant enfants. */
|
||||
dirs: string[];
|
||||
/** Éléments ignorés : fichiers et dossiers cachés (.DS_Store, .git...). */
|
||||
ignored: string[];
|
||||
}
|
||||
|
||||
const hidden = (name: string) => name.startsWith(".");
|
||||
|
||||
/** Le glisser contient-il des fichiers venant du système ? */
|
||||
export const hasFiles = (dt: DataTransfer) => dt.types.includes("Files");
|
||||
|
||||
const readAll = (reader: FileSystemDirectoryReader) =>
|
||||
new Promise<FileSystemEntry[]>((resolve, reject) => {
|
||||
const out: FileSystemEntry[] = [];
|
||||
// readEntries rend les entrées par lots (100 sous Chrome) : boucler jusqu'au lot vide.
|
||||
const next = () =>
|
||||
reader.readEntries((batch) => {
|
||||
if (batch.length === 0) return resolve(out);
|
||||
out.push(...batch);
|
||||
next();
|
||||
}, reject);
|
||||
next();
|
||||
});
|
||||
|
||||
const fileOf = (entry: FileSystemFileEntry) => new Promise<File>((resolve, reject) => entry.file(resolve, reject));
|
||||
|
||||
async function walk(entry: FileSystemEntry, prefix: string, acc: Collected) {
|
||||
const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
|
||||
if (hidden(entry.name)) {
|
||||
acc.ignored.push(rel);
|
||||
return;
|
||||
}
|
||||
if (entry.isDirectory) {
|
||||
acc.dirs.push(rel);
|
||||
for (const child of await readAll((entry as FileSystemDirectoryEntry).createReader())) {
|
||||
await walk(child, rel, acc);
|
||||
}
|
||||
} else {
|
||||
acc.files.push({ rel, file: await fileOf(entry as FileSystemFileEntry) });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lit un dépôt (fichiers et dossiers). Les entrées doivent être capturées pendant
|
||||
* l'événement drop : le DataTransfer est vidé dès que le gestionnaire rend la main.
|
||||
*/
|
||||
export function collectDrop(dt: DataTransfer): Promise<Collected> {
|
||||
const entries = Array.from(dt.items)
|
||||
.filter((i) => i.kind === "file")
|
||||
.map((i) => i.webkitGetAsEntry?.())
|
||||
.filter((e): e is FileSystemEntry => !!e);
|
||||
const plain = entries.length ? [] : Array.from(dt.files); // navigateur sans webkitGetAsEntry
|
||||
return (async () => {
|
||||
const acc: Collected = { files: [], dirs: [], ignored: [] };
|
||||
for (const e of entries) await walk(e, "", acc);
|
||||
collectInto(plain, acc);
|
||||
return acc;
|
||||
})();
|
||||
}
|
||||
|
||||
/** Fichiers d'un <input type="file"> (chemins dans webkitRelativePath pour un dossier). */
|
||||
export function collectFiles(files: FileList | File[]): Collected {
|
||||
const acc: Collected = { files: [], dirs: [], ignored: [] };
|
||||
collectInto(Array.from(files), acc);
|
||||
return acc;
|
||||
}
|
||||
|
||||
function collectInto(files: File[], acc: Collected) {
|
||||
const dirs = new Set(acc.dirs);
|
||||
for (const file of files) {
|
||||
const rel = file.webkitRelativePath || file.name;
|
||||
const parts = rel.split("/");
|
||||
if (parts.some(hidden)) {
|
||||
acc.ignored.push(rel);
|
||||
continue;
|
||||
}
|
||||
for (let i = 1; i < parts.length; i++) dirs.add(parts.slice(0, i).join("/"));
|
||||
acc.files.push({ rel, file });
|
||||
}
|
||||
acc.dirs = [...dirs].sort((a, b) => a.split("/").length - b.split("/").length);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import "./styles.css";
|
||||
import App from "./App";
|
||||
import { ShareView } from "./ShareView";
|
||||
|
||||
// /s/<jeton> : lien de partage (sans compte).
|
||||
const share = location.pathname.match(/^\/s\/([^/]+)\/?$/);
|
||||
|
||||
createRoot(document.getElementById("root")!).render(<StrictMode>{share ? <ShareView token={decodeURIComponent(share[1])} /> : <App />}</StrictMode>);
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,182 @@
|
||||
// File d'envoi : plusieurs fichiers en parallèle, progression par fichier, annulation,
|
||||
// nouvel essai. L'état est un « store » externe lu par useSyncExternalStore.
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { api, ApiError, join, uploadFile, type Conflict } from "./api";
|
||||
import type { Collected } from "./importer";
|
||||
|
||||
export type UploadStatus = "queued" | "uploading" | "done" | "error" | "canceled";
|
||||
|
||||
export interface UploadItem {
|
||||
id: number;
|
||||
/** Chemin relatif affiché (« Photos/img.jpg »). */
|
||||
rel: string;
|
||||
/** Chemin de destination complet. */
|
||||
path: string;
|
||||
size: number;
|
||||
loaded: number;
|
||||
status: UploadStatus;
|
||||
error?: string;
|
||||
/** Chemin final (différent de path si le serveur a renommé). */
|
||||
result?: string;
|
||||
}
|
||||
|
||||
/** Que faire si un fichier du même nom existe ? */
|
||||
export type OnExists = Extract<Conflict, "rename" | "overwrite" | "fail">;
|
||||
|
||||
const CONCURRENCY = 3;
|
||||
|
||||
class UploadStore {
|
||||
private items: UploadItem[] = [];
|
||||
private snapshot: readonly UploadItem[] = [];
|
||||
private files = new Map<number, File>();
|
||||
private aborts = new Map<number, () => void>();
|
||||
private listeners = new Set<() => void>();
|
||||
private next = 1;
|
||||
private doneListeners = new Set<() => void>();
|
||||
|
||||
/** Comportement si le nom existe déjà (mémorisé par navigateur). */
|
||||
onExists: OnExists = (() => {
|
||||
try {
|
||||
const v = localStorage.getItem("uploadOnExists");
|
||||
return v === "overwrite" || v === "fail" ? v : "rename";
|
||||
} catch {
|
||||
return "rename";
|
||||
}
|
||||
})();
|
||||
|
||||
setOnExists(v: OnExists) {
|
||||
this.onExists = v;
|
||||
try {
|
||||
localStorage.setItem("uploadOnExists", v);
|
||||
} catch {
|
||||
/* stockage indisponible */
|
||||
}
|
||||
this.emit();
|
||||
}
|
||||
|
||||
subscribe = (fn: () => void) => {
|
||||
this.listeners.add(fn);
|
||||
return () => {
|
||||
this.listeners.delete(fn);
|
||||
};
|
||||
};
|
||||
|
||||
getSnapshot = () => this.snapshot;
|
||||
|
||||
/** Appelé quand des fichiers viennent d'être déposés (rafraîchit l'explorateur). */
|
||||
onDone(fn: () => void) {
|
||||
this.doneListeners.add(fn);
|
||||
return () => {
|
||||
this.doneListeners.delete(fn);
|
||||
};
|
||||
}
|
||||
|
||||
private emit() {
|
||||
this.snapshot = [...this.items];
|
||||
this.listeners.forEach((l) => l());
|
||||
}
|
||||
|
||||
/** Ajoute des fichiers (et les dossiers vides) à envoyer dans dir. */
|
||||
add(dir: string, picked: Collected) {
|
||||
// Dossiers d'abord (y compris vides) ; un dossier existant n'est pas une erreur.
|
||||
const mk = picked.dirs.map((d) => api.mkdir(join(dir, d)).catch((e) => (e instanceof ApiError && e.status === 409 ? undefined : Promise.reject(e))));
|
||||
Promise.allSettled(mk).then(() => this.doneListeners.forEach((l) => l()));
|
||||
for (const { rel, file } of picked.files) {
|
||||
const id = this.next++;
|
||||
this.files.set(id, file);
|
||||
this.items.push({ id, rel, path: join(dir, rel), size: file.size, loaded: 0, status: "queued" });
|
||||
}
|
||||
this.emit();
|
||||
this.pump();
|
||||
}
|
||||
|
||||
private pump() {
|
||||
let running = this.items.filter((i) => i.status === "uploading").length;
|
||||
for (const it of this.items) {
|
||||
if (running >= CONCURRENCY) break;
|
||||
if (it.status === "queued") {
|
||||
running++;
|
||||
this.start(it);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private start(it: UploadItem) {
|
||||
const file = this.files.get(it.id);
|
||||
if (!file) return;
|
||||
it.status = "uploading";
|
||||
it.loaded = 0;
|
||||
it.error = undefined;
|
||||
this.emit();
|
||||
const { promise, abort } = uploadFile(it.path, file, {
|
||||
conflict: this.onExists,
|
||||
onProgress: (loaded) => {
|
||||
it.loaded = loaded;
|
||||
this.emit();
|
||||
},
|
||||
});
|
||||
this.aborts.set(it.id, abort);
|
||||
promise
|
||||
.then((entry) => {
|
||||
it.status = "done";
|
||||
it.loaded = it.size;
|
||||
it.result = entry.path;
|
||||
this.files.delete(it.id);
|
||||
})
|
||||
.catch((e: unknown) => {
|
||||
const err = e instanceof ApiError ? e : null;
|
||||
if (err && err.status === 0 && err.message === "annulé") it.status = "canceled";
|
||||
else {
|
||||
it.status = "error";
|
||||
it.error = err?.status === 409 ? "existe déjà" : err?.status === 507 ? "quota de stockage dépassé" : err?.status === 413 ? "fichier trop volumineux" : err ? err.message : String(e);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
this.aborts.delete(it.id);
|
||||
this.emit();
|
||||
this.pump();
|
||||
if (!this.items.some((i) => i.status === "queued" || i.status === "uploading")) this.doneListeners.forEach((l) => l());
|
||||
});
|
||||
}
|
||||
|
||||
cancel(id: number) {
|
||||
const it = this.items.find((i) => i.id === id);
|
||||
if (!it) return;
|
||||
if (it.status === "uploading") this.aborts.get(id)?.();
|
||||
else if (it.status === "queued") {
|
||||
it.status = "canceled";
|
||||
this.files.delete(id);
|
||||
this.emit();
|
||||
}
|
||||
}
|
||||
|
||||
cancelAll() {
|
||||
for (const it of [...this.items]) this.cancel(it.id);
|
||||
}
|
||||
|
||||
retry(id: number) {
|
||||
const it = this.items.find((i) => i.id === id);
|
||||
if (it && (it.status === "error" || it.status === "canceled") && this.files.has(id)) {
|
||||
it.status = "queued";
|
||||
this.emit();
|
||||
this.pump();
|
||||
}
|
||||
}
|
||||
|
||||
retryFailed() {
|
||||
this.items.filter((i) => i.status === "error").forEach((i) => this.retry(i.id));
|
||||
}
|
||||
|
||||
/** Retire de la liste les envois terminés ou annulés. */
|
||||
clearFinished() {
|
||||
this.items = this.items.filter((i) => i.status === "queued" || i.status === "uploading" || i.status === "error");
|
||||
this.emit();
|
||||
}
|
||||
}
|
||||
|
||||
export const uploads = new UploadStore();
|
||||
|
||||
export function useUploads(): readonly UploadItem[] {
|
||||
return useSyncExternalStore(uploads.subscribe, uploads.getSnapshot);
|
||||
}
|
||||
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true,
|
||||
"isolatedModules": true,
|
||||
"allowImportingTsExtensions": false,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
// Le build est embarqué dans le binaire Go (web/dist).
|
||||
build: { outDir: "../web/dist", emptyOutDir: true },
|
||||
// `npm run dev` : l'API Go tourne sur :8080 (les routes /s, /auth et /api passent par le proxy).
|
||||
server: { proxy: { "/api": "http://localhost:8080", "/auth": "http://localhost:8080", "/s": "http://localhost:8080" } },
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/vblogio/upandown/internal/auth"
|
||||
)
|
||||
|
||||
func (h *Handler) adminUsers(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.admin(w, r) {
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, http.StatusOK, h.Accounts.List())
|
||||
}
|
||||
|
||||
func (h *Handler) adminCreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.admin(w, r) {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Username string `json:"username"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
Role string `json:"role"`
|
||||
}
|
||||
if !h.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
acc, err := h.Accounts.CreateLocal(auth.NewAccount{Username: req.Username, Name: req.Name, Email: req.Email,
|
||||
Password: req.Password, Role: req.Role, Status: auth.StatusActive})
|
||||
if err != nil {
|
||||
accountErr(w, err)
|
||||
return
|
||||
}
|
||||
slog.Info("compte créé", "user", acc.ID, "by", userID(r))
|
||||
writeJSON(w, http.StatusCreated, acc.Info())
|
||||
}
|
||||
|
||||
func (h *Handler) adminPatchUser(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.admin(w, r) {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Name *string `json:"name"`
|
||||
Email *string `json:"email"`
|
||||
Role *string `json:"role"`
|
||||
Status *string `json:"status"`
|
||||
Password *string `json:"password"`
|
||||
}
|
||||
if !h.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
acc, err := h.Accounts.Update(id, auth.Patch{Name: req.Name, Email: req.Email, Role: req.Role,
|
||||
Status: req.Status, Password: req.Password})
|
||||
if err != nil {
|
||||
accountErr(w, err)
|
||||
return
|
||||
}
|
||||
slog.Info("compte modifié", "user", id, "by", userID(r))
|
||||
writeJSON(w, http.StatusOK, acc.Info())
|
||||
}
|
||||
|
||||
func (h *Handler) adminDeleteUser(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.admin(w, r) {
|
||||
return
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
if id == userID(r) {
|
||||
writeErr(w, http.StatusBadRequest, "vous ne pouvez pas supprimer votre propre compte")
|
||||
return
|
||||
}
|
||||
if err := h.Accounts.Delete(id); err != nil {
|
||||
accountErr(w, err)
|
||||
return
|
||||
}
|
||||
if h.OnUserRemoved != nil {
|
||||
h.OnUserRemoved(id)
|
||||
}
|
||||
if err := h.Spaces.RetireUser(id); err != nil {
|
||||
slog.Warn("espace personnel non mis de côté", "user", id, "err", err)
|
||||
}
|
||||
slog.Info("compte supprimé", "user", id, "by", userID(r))
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
// Package api expose les fichiers en REST/JSON.
|
||||
//
|
||||
// GET /api/me session, fournisseurs et réglages publics (sans authentification)
|
||||
// GET /api/list?path=dir[&details=1] contenu d'un dossier (details : vue Galerie)
|
||||
// GET /api/search?q=texte[&tag=t][&fav=true][&details=1] recherche (noms, tags, texte des fichiers)
|
||||
// GET /api/tags tags utilisés et nombre d'éléments
|
||||
// POST /api/meta/favorite {"paths":[...],"favorite":true} favoris
|
||||
// POST /api/meta/tags {"paths":[...],"add":[...],"remove":[...]} tags
|
||||
// POST /api/meta/icon {"paths":[...],"icon":"server"} icône de dossiers ("" : défaut)
|
||||
// GET /api/file?path=a/b.pdf[&inline=1] téléchargement (Range, ETag) ; inline : affichage dans le navigateur si sûr
|
||||
// PUT /api/file?path=a/b.pdf[&conflict=fail|overwrite|rename][&mtime=ms] dépôt en flux
|
||||
// POST /api/folder {"path":"a/b"} création de dossier
|
||||
// POST /api/move {"from":"x","to":"y"} renommage / déplacement
|
||||
// POST /api/move-many {"paths":[...],"dir":"d"} déplacement multiple
|
||||
// POST /api/copy {"from":"x","to":"y"} duplication (fichier ou dossier)
|
||||
// DELETE /api/entry?path=x[&recursive=true] mise à la poubelle (suppression définitive
|
||||
// dans .poubelle ; path=.poubelle : la vide)
|
||||
// POST /api/trash/restore {"paths":[...]} restauration depuis la poubelle
|
||||
// GET /api/thumb?path=x miniature d'une image
|
||||
// GET /api/zip?path=x / POST (formulaire paths=[...]) archive ZIP en flux
|
||||
// GET /api/hash?path=x empreinte SHA-256 d'un fichier
|
||||
// GET /api/history?path=x versions d'un fichier
|
||||
// GET /api/history/version?path=x&id=v contenu d'une version
|
||||
// POST /api/history/snapshot {"path"} version du contenu courant
|
||||
// POST /api/history/restore {"path","id"} restauration
|
||||
// GET /api/shares[?path=x] liens de partage (d'un élément ou tous)
|
||||
// POST /api/shares {"path","days","password"} nouveau lien (days 0 : sans expiration)
|
||||
// DELETE /api/shares?id=x révocation d'un lien
|
||||
// POST /api/shares/revoke-all révocation de tous les liens (administrateur)
|
||||
// GET /api/public/{jeton}[?sub=d] lien de partage (sans authentification)
|
||||
// POST /api/public/{jeton}/unlock mot de passe d'un lien protégé
|
||||
// GET /api/public/{jeton}/file|zip|thumb contenu d'un lien de partage
|
||||
// GET /api/settings / PUT paramètres (écriture : administrateur)
|
||||
// GET /api/logo / PUT (image/png) / DELETE logo 64x64
|
||||
// POST /api/account/password changement du mot de passe (compte local)
|
||||
// PATCH /api/account nom et e-mail (compte local)
|
||||
// GET|POST /api/admin/users, PATCH|DELETE /api/admin/users/{id} comptes (administrateur)
|
||||
//
|
||||
// Les chemins sont vus par l'utilisateur connecté (storage.Space) : l'arborescence
|
||||
// commune, plus ".perso/..." (son espace personnel), ".favoris" (ses favoris,
|
||||
// liens symboliques vers les originaux ; DELETE .favoris/x retire le lien) et
|
||||
// ".poubelle" (éléments supprimés, de l'arborescence commune et de son espace).
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/vblogio/upandown/internal/auth"
|
||||
"github.com/vblogio/upandown/internal/storage"
|
||||
)
|
||||
|
||||
// Handler regroupe les routes de l'API.
|
||||
type Handler struct {
|
||||
Store *storage.Store // arborescence commune : paramètres, logo
|
||||
Spaces *storage.Spaces // fichiers : arborescence commune, espaces personnels, favoris
|
||||
|
||||
Auth *auth.Auth // nil : pas d'authentification intégrée
|
||||
Accounts *auth.Accounts // nil : pas de comptes (AUTH_MODE=none)
|
||||
|
||||
MaxJSON int64 // taille maximale d'un corps JSON (octets)
|
||||
Mode string // none, local, oidc ou both
|
||||
OIDCName string // libellé du bouton de connexion OIDC
|
||||
Version string
|
||||
|
||||
// SecureCookies : cookies de déverrouillage des liens marqués Secure même
|
||||
// en HTTP direct (URL publique en https).
|
||||
SecureCookies bool
|
||||
|
||||
// OnUserRemoved est appelé après la suppression d'un compte (jetons à révoquer).
|
||||
OnUserRemoved func(id string)
|
||||
|
||||
unlocks *auth.Limiter
|
||||
}
|
||||
|
||||
// Init prépare les limiteurs internes ; à appeler avant Register.
|
||||
func (h *Handler) Init() *Handler {
|
||||
if h.MaxJSON == 0 {
|
||||
h.MaxJSON = 1 << 20
|
||||
}
|
||||
h.unlocks = auth.NewLimiter(10, 15*time.Minute)
|
||||
return h
|
||||
}
|
||||
|
||||
// userID identifie l'utilisateur d'une requête : identifiant de son compte,
|
||||
// ou LocalUser sans authentification intégrée.
|
||||
func userID(r *http.Request) string {
|
||||
if u := auth.UserFrom(r.Context()); u != nil && u.ID != "" {
|
||||
return u.ID
|
||||
}
|
||||
return storage.LocalUser
|
||||
}
|
||||
|
||||
// UserID est la fonction d'identification utilisée aussi par les jetons.
|
||||
func UserID(r *http.Request) string { return userID(r) }
|
||||
|
||||
// isAdmin : sans authentification intégrée (AUTH_MODE=none), tout le monde
|
||||
// administre, le contrôle d'accès étant alors celui du reverse proxy. Sinon,
|
||||
// il faut une session de rôle administrateur.
|
||||
func (h *Handler) isAdmin(r *http.Request) bool {
|
||||
if h.Mode == "none" {
|
||||
return true
|
||||
}
|
||||
u := auth.UserFrom(r.Context())
|
||||
return u != nil && u.Role == auth.RoleAdmin
|
||||
}
|
||||
|
||||
// space renvoie la vue de l'utilisateur de la requête (espace personnel et favoris).
|
||||
func (h *Handler) space(w http.ResponseWriter, r *http.Request) (*storage.Space, bool) {
|
||||
u, err := h.Spaces.For(userID(r), h.isAdmin(r))
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return nil, false
|
||||
}
|
||||
return u, true
|
||||
}
|
||||
|
||||
// admin refuse les requêtes des non-administrateurs.
|
||||
func (h *Handler) admin(w http.ResponseWriter, r *http.Request) bool {
|
||||
if !h.isAdmin(r) {
|
||||
writeErr(w, http.StatusForbidden, "réservé aux administrateurs")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Register enregistre les routes sur mux (motifs Go 1.22+).
|
||||
func (h *Handler) Register(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/me", h.me)
|
||||
mux.HandleFunc("GET /api/list", h.list)
|
||||
mux.HandleFunc("GET /api/search", h.search)
|
||||
mux.HandleFunc("GET /api/tags", h.tags)
|
||||
mux.HandleFunc("POST /api/meta/favorite", h.setFavorite)
|
||||
mux.HandleFunc("POST /api/meta/tags", h.editTags)
|
||||
mux.HandleFunc("POST /api/meta/icon", h.setIcon)
|
||||
mux.HandleFunc("GET /api/file", h.download)
|
||||
mux.HandleFunc("PUT /api/file", h.upload)
|
||||
mux.HandleFunc("POST /api/folder", h.mkdir)
|
||||
mux.HandleFunc("POST /api/move", h.move)
|
||||
mux.HandleFunc("POST /api/move-many", h.moveMany)
|
||||
mux.HandleFunc("POST /api/copy", h.copy)
|
||||
mux.HandleFunc("DELETE /api/entry", h.delete)
|
||||
mux.HandleFunc("POST /api/trash/restore", h.restoreTrash)
|
||||
mux.HandleFunc("GET /api/thumb", h.thumb)
|
||||
mux.HandleFunc("GET /api/zip", h.zip)
|
||||
mux.HandleFunc("POST /api/zip", h.zip)
|
||||
mux.HandleFunc("GET /api/hash", h.hash)
|
||||
mux.HandleFunc("GET /api/history", h.history)
|
||||
mux.HandleFunc("GET /api/history/version", h.readVersion)
|
||||
mux.HandleFunc("POST /api/history/snapshot", h.snapshot)
|
||||
mux.HandleFunc("POST /api/history/restore", h.restore)
|
||||
mux.HandleFunc("GET /api/shares", h.shares)
|
||||
mux.HandleFunc("POST /api/shares", h.createShare)
|
||||
mux.HandleFunc("DELETE /api/shares", h.revokeShare)
|
||||
mux.HandleFunc("POST /api/shares/revoke-all", h.revokeAllShares)
|
||||
mux.HandleFunc("GET /api/public/{token}", h.publicInfo)
|
||||
mux.HandleFunc("POST /api/public/{token}/unlock", h.publicUnlock)
|
||||
mux.HandleFunc("GET /api/public/{token}/file", h.publicFile)
|
||||
mux.HandleFunc("GET /api/public/{token}/zip", h.publicZip)
|
||||
mux.HandleFunc("GET /api/public/{token}/thumb", h.publicThumb)
|
||||
mux.HandleFunc("GET /api/settings", h.readSettings)
|
||||
mux.HandleFunc("PUT /api/settings", h.writeSettings)
|
||||
mux.HandleFunc("GET /api/logo", h.readLogo)
|
||||
mux.HandleFunc("PUT /api/logo", h.writeLogo)
|
||||
mux.HandleFunc("DELETE /api/logo", h.deleteLogo)
|
||||
if h.Accounts != nil {
|
||||
mux.HandleFunc("POST /api/account/password", h.changePassword)
|
||||
mux.HandleFunc("PATCH /api/account", h.patchAccount)
|
||||
mux.HandleFunc("GET /api/admin/users", h.adminUsers)
|
||||
mux.HandleFunc("POST /api/admin/users", h.adminCreateUser)
|
||||
mux.HandleFunc("PATCH /api/admin/users/{id}", h.adminPatchUser)
|
||||
mux.HandleFunc("DELETE /api/admin/users/{id}", h.adminDeleteUser)
|
||||
}
|
||||
mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusNotFound, "route inconnue")
|
||||
})
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
func writeErr(w http.ResponseWriter, status int, msg string) {
|
||||
writeJSON(w, status, map[string]string{"error": msg})
|
||||
}
|
||||
|
||||
// fail traduit une erreur du Store en code HTTP.
|
||||
func fail(w http.ResponseWriter, err error) {
|
||||
var tooBig *http.MaxBytesError
|
||||
switch {
|
||||
case errors.Is(err, storage.ErrNotFound):
|
||||
writeErr(w, http.StatusNotFound, err.Error())
|
||||
case errors.Is(err, storage.ErrExists), errors.Is(err, storage.ErrNotEmpty):
|
||||
writeErr(w, http.StatusConflict, err.Error())
|
||||
case errors.Is(err, storage.ErrConflict):
|
||||
writeErr(w, http.StatusPreconditionFailed, err.Error())
|
||||
case errors.Is(err, storage.ErrInvalidPath), errors.Is(err, storage.ErrInvalidImage):
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
case errors.Is(err, storage.ErrForbidden):
|
||||
writeErr(w, http.StatusForbidden, err.Error())
|
||||
case errors.Is(err, storage.ErrQuota):
|
||||
writeErr(w, http.StatusInsufficientStorage, err.Error())
|
||||
case errors.Is(err, storage.ErrTooLarge), errors.As(err, &tooBig):
|
||||
writeErr(w, http.StatusRequestEntityTooLarge, "fichier trop volumineux")
|
||||
default:
|
||||
slog.Error("erreur interne", "err", err)
|
||||
writeErr(w, http.StatusInternalServerError, "erreur interne")
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) readBody(w http.ResponseWriter, r *http.Request) ([]byte, error) {
|
||||
return io.ReadAll(http.MaxBytesReader(w, r.Body, h.MaxJSON))
|
||||
}
|
||||
|
||||
func (h *Handler) decode(w http.ResponseWriter, r *http.Request, v any) bool {
|
||||
b, err := h.readBody(w, r)
|
||||
if err == nil {
|
||||
err = json.Unmarshal(b, v)
|
||||
}
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "requête JSON invalide")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func wantDetails(r *http.Request) bool {
|
||||
v := r.URL.Query().Get("details")
|
||||
return v == "1" || v == "true"
|
||||
}
|
||||
|
||||
func secure(r *http.Request) bool {
|
||||
return r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https")
|
||||
}
|
||||
@@ -0,0 +1,646 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/vblogio/upandown/internal/auth"
|
||||
"github.com/vblogio/upandown/internal/storage"
|
||||
"github.com/vblogio/upandown/internal/tokens"
|
||||
)
|
||||
|
||||
// fixture assemble le même graphe que cmd/server (mode local), sans ouvrir de port.
|
||||
type fixture struct {
|
||||
root string
|
||||
t *testing.T
|
||||
h http.Handler
|
||||
handler *Handler
|
||||
accounts *auth.Accounts
|
||||
tokens *tokens.Store
|
||||
spaces *storage.Spaces
|
||||
}
|
||||
|
||||
func newFixture(t *testing.T, mutate func(*storage.Store, *storage.Spaces)) *fixture {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
store, err := storage.New(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
spaces := storage.NewSpaces(store)
|
||||
if mutate != nil {
|
||||
mutate(store, spaces)
|
||||
}
|
||||
accounts, err := auth.OpenAccounts(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := (&Handler{Store: store, Spaces: spaces, Mode: "local", Accounts: accounts}).Init()
|
||||
a := auth.New(&auth.Auth{
|
||||
Accounts: accounts, Sessions: auth.NewSessions([]byte("0123456789abcdef0123456789abcdef"), time.Hour, false),
|
||||
Local: true,
|
||||
Registration: func() string {
|
||||
st, _ := store.ReadSettings()
|
||||
return st.Registration
|
||||
},
|
||||
})
|
||||
h.Auth = a
|
||||
mux := http.NewServeMux()
|
||||
a.Register(mux)
|
||||
h.Register(mux)
|
||||
tokenStore, err := tokens.Open(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ts := &tokens.Server{Store: tokenStore, UserID: UserID, Resolve: func(id string) (*auth.User, bool) {
|
||||
acc, ok := accounts.Get(id)
|
||||
if !ok || acc.Status != auth.StatusActive {
|
||||
return nil, false
|
||||
}
|
||||
u := acc.User()
|
||||
return &u, true
|
||||
}}
|
||||
ts.Register(mux)
|
||||
public := func(p string) bool {
|
||||
return strings.HasPrefix(p, "/api/public/") || p == "/api/me" || p == "/api/logo"
|
||||
}
|
||||
return &fixture{root: dir, t: t, h: ts.Middleware(a.Middleware(mux, public), mux), handler: h, accounts: accounts, tokens: tokenStore, spaces: spaces}
|
||||
}
|
||||
|
||||
type session struct {
|
||||
f *fixture
|
||||
cookies map[string]*http.Cookie
|
||||
bearer string
|
||||
}
|
||||
|
||||
func (f *fixture) session() *session { return &session{f: f, cookies: map[string]*http.Cookie{}} }
|
||||
|
||||
func (s *session) do(method, target string, body io.Reader, hdr ...string) *httptest.ResponseRecorder {
|
||||
s.f.t.Helper()
|
||||
r := httptest.NewRequest(method, target, body)
|
||||
for i := 0; i+1 < len(hdr); i += 2 {
|
||||
r.Header.Set(hdr[i], hdr[i+1])
|
||||
}
|
||||
for _, c := range s.cookies {
|
||||
r.AddCookie(c)
|
||||
}
|
||||
if s.bearer != "" {
|
||||
r.Header.Set("Authorization", "Bearer "+s.bearer)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
s.f.h.ServeHTTP(w, r)
|
||||
for _, c := range w.Result().Cookies() {
|
||||
if c.MaxAge < 0 {
|
||||
delete(s.cookies, c.Name)
|
||||
} else {
|
||||
s.cookies[c.Name] = c
|
||||
}
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
func (s *session) json(method, target string, v any) *httptest.ResponseRecorder {
|
||||
b, _ := json.Marshal(v)
|
||||
return s.do(method, target, bytes.NewReader(b), "Content-Type", "application/json")
|
||||
}
|
||||
|
||||
func (s *session) put(path, content string, query ...string) *httptest.ResponseRecorder {
|
||||
q := ""
|
||||
for _, x := range query {
|
||||
q += "&" + x
|
||||
}
|
||||
return s.do("PUT", "/api/file?path="+url.QueryEscape(path)+q, strings.NewReader(content))
|
||||
}
|
||||
|
||||
func (s *session) get(target string, hdr ...string) *httptest.ResponseRecorder {
|
||||
return s.do("GET", target, nil, hdr...)
|
||||
}
|
||||
|
||||
func decode[T any](t *testing.T, w *httptest.ResponseRecorder) T {
|
||||
t.Helper()
|
||||
var v T
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &v); err != nil {
|
||||
t.Fatalf("JSON illisible (%d) : %v : %s", w.Code, err, w.Body)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func want(t *testing.T, w *httptest.ResponseRecorder, code int) {
|
||||
t.Helper()
|
||||
if w.Code != code {
|
||||
t.Fatalf("code %d (attendu %d) : %s", w.Code, code, strings.TrimSpace(w.Body.String()))
|
||||
}
|
||||
}
|
||||
|
||||
// register crée un compte par l'inscription et renvoie sa session.
|
||||
func (f *fixture) register(name string) *session {
|
||||
f.t.Helper()
|
||||
s := f.session()
|
||||
w := s.json("POST", "/auth/local/register", map[string]string{"username": name, "password": "mot-de-passe-" + name})
|
||||
if w.Code != 201 && w.Code != 202 {
|
||||
f.t.Fatalf("inscription de %s : %d %s", name, w.Code, w.Body)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (f *fixture) login(name string) *session {
|
||||
f.t.Helper()
|
||||
s := f.session()
|
||||
want(f.t, s.json("POST", "/auth/local/login", map[string]string{"username": name, "password": "mot-de-passe-" + name}), 200)
|
||||
return s
|
||||
}
|
||||
|
||||
func makePNG(t *testing.T, w, h int) string {
|
||||
t.Helper()
|
||||
img := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||
for y := 0; y < h; y++ {
|
||||
for x := 0; x < w; x++ {
|
||||
img.Set(x, y, color.RGBA{uint8(x), uint8(y), 99, 255})
|
||||
}
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, img); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func TestAnonymousAndSetup(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
anon := f.session()
|
||||
want(t, anon.get("/api/list?path="), 401)
|
||||
want(t, anon.put("a.txt", "x"), 401)
|
||||
me := decode[meResponse](t, anon.get("/api/me"))
|
||||
if !me.Setup || me.User != nil || !me.Local || me.Registration != "closed" {
|
||||
t.Errorf("/api/me avant installation : %+v", me)
|
||||
}
|
||||
admin := f.register("alice")
|
||||
me = decode[meResponse](t, admin.get("/api/me"))
|
||||
if me.Setup || me.User == nil || me.User.ID != "alice" || !me.Admin || me.Usage == nil {
|
||||
t.Errorf("/api/me après installation : %+v", me)
|
||||
}
|
||||
// Inscriptions fermées : le second compte est refusé.
|
||||
w := f.session().json("POST", "/auth/local/register", map[string]string{"username": "bob", "password": "mot-de-passe-bob"})
|
||||
want(t, w, 403)
|
||||
}
|
||||
|
||||
func TestUploadDownloadRange(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
s := f.register("alice")
|
||||
want(t, s.put("docs/rapport.pdf", "%PDF-0123456789"), 200)
|
||||
w := s.get("/api/file?path=docs/rapport.pdf")
|
||||
want(t, w, 200)
|
||||
if w.Body.String() != "%PDF-0123456789" || !strings.HasPrefix(w.Header().Get("Content-Disposition"), "attachment;") {
|
||||
t.Errorf("téléchargement : %q %v", w.Body, w.Header())
|
||||
}
|
||||
w = s.get("/api/file?path=docs/rapport.pdf", "Range", "bytes=5-9")
|
||||
want(t, w, 206)
|
||||
if w.Body.String() != "01234" {
|
||||
t.Errorf("Range = %q", w.Body)
|
||||
}
|
||||
// Remplacement conditionnel par ETag, puis lecture conditionnelle.
|
||||
etag := s.get("/api/file?path=docs/rapport.pdf").Header().Get("ETag")
|
||||
want(t, s.get("/api/file?path=docs/rapport.pdf", "If-None-Match", etag), 304)
|
||||
// Conflit.
|
||||
want(t, s.put("docs/rapport.pdf", "autre"), 409)
|
||||
r := s.put("docs/rapport.pdf", "autre", "conflict=rename")
|
||||
want(t, r, 200)
|
||||
if e := decode[storage.Entry](t, r); e.Path != "docs/rapport (2).pdf" {
|
||||
t.Errorf("rename = %q", e.Path)
|
||||
}
|
||||
want(t, s.put("docs/rapport.pdf", "v2", "conflict=overwrite"), 200)
|
||||
want(t, s.put("docs/rapport.pdf", "v3", "conflict=n'importe-quoi"), 400)
|
||||
vs := decode[[]storage.Version](t, s.get("/api/history?path=docs/rapport.pdf"))
|
||||
if len(vs) != 1 {
|
||||
t.Fatalf("versions = %v", vs)
|
||||
}
|
||||
old := s.get("/api/history/version?path=docs/rapport.pdf&id=" + vs[0].ID)
|
||||
if old.Body.String() != "%PDF-0123456789" {
|
||||
t.Errorf("ancienne version = %q", old.Body)
|
||||
}
|
||||
want(t, s.json("POST", "/api/history/restore", map[string]string{"path": "docs/rapport.pdf", "id": vs[0].ID}), 200)
|
||||
if s.get("/api/file?path=docs/rapport.pdf").Body.String() != "%PDF-0123456789" {
|
||||
t.Error("restauration")
|
||||
}
|
||||
}
|
||||
|
||||
func TestActiveContentNeverRunsInOrigin(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
s := f.register("alice")
|
||||
want(t, s.put("page.html", "<script>alert(1)</script>"), 200)
|
||||
want(t, s.put("img.svg", `<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>`), 200)
|
||||
want(t, s.put("note.txt", "bonjour"), 200)
|
||||
want(t, s.put("photo.png", "\x89PNG"), 200)
|
||||
want(t, s.put("doc.pdf", "%PDF"), 200)
|
||||
want(t, s.put("inconnu.xyz", "?"), 200)
|
||||
|
||||
for _, name := range []string{"page.html", "img.svg", "inconnu.xyz"} {
|
||||
for _, inline := range []string{"", "&inline=1"} {
|
||||
w := s.get("/api/file?path=" + name + inline)
|
||||
ct := w.Header().Get("Content-Type")
|
||||
cd := w.Header().Get("Content-Disposition")
|
||||
if name == "img.svg" && inline != "" {
|
||||
// SVG affiché en ligne seulement avec un CSP qui interdit tout script.
|
||||
if !strings.Contains(w.Header().Get("Content-Security-Policy"), "sandbox") {
|
||||
t.Errorf("SVG inline sans sandbox")
|
||||
}
|
||||
continue
|
||||
}
|
||||
if strings.Contains(ct, "html") || strings.Contains(ct, "svg") {
|
||||
t.Errorf("%s%s servi en %s", name, inline, ct)
|
||||
}
|
||||
if name == "page.html" && inline != "" {
|
||||
if !strings.HasPrefix(ct, "text/plain") {
|
||||
t.Errorf("HTML inline : %s", ct)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !strings.HasPrefix(cd, "attachment") {
|
||||
t.Errorf("%s%s : %s", name, inline, cd)
|
||||
}
|
||||
}
|
||||
}
|
||||
if w := s.get("/api/file?path=note.txt&inline=1"); !strings.HasPrefix(w.Header().Get("Content-Disposition"), "inline") ||
|
||||
!strings.HasPrefix(w.Header().Get("Content-Type"), "text/plain") {
|
||||
t.Errorf("texte inline : %v", w.Header())
|
||||
}
|
||||
if w := s.get("/api/file?path=photo.png&inline=1"); w.Header().Get("Content-Type") != "image/png" || w.Header().Get("X-Content-Type-Options") != "nosniff" {
|
||||
t.Errorf("image inline : %v", w.Header())
|
||||
}
|
||||
// PDF en ligne sans CSP sandbox (sinon le lecteur PDF ne s'affiche pas).
|
||||
if w := s.get("/api/file?path=doc.pdf&inline=1"); w.Header().Get("Content-Type") != "application/pdf" || w.Header().Get("Content-Security-Policy") != "" {
|
||||
t.Errorf("pdf inline : %v", w.Header())
|
||||
}
|
||||
}
|
||||
|
||||
func TestContentDispositionEncoding(t *testing.T) {
|
||||
got := contentDisposition(false, `é"té\.pdf`)
|
||||
if !strings.Contains(got, `filename="_t_.pdf"`) && !strings.Contains(got, `filename="__t__.pdf"`) {
|
||||
// repli ASCII : les caractères non ASCII et les guillemets sont remplacés
|
||||
}
|
||||
if strings.Contains(got, `"té`) || !strings.Contains(got, "filename*=UTF-8''%C3%A9%22t%C3%A9%5C.pdf") {
|
||||
t.Errorf("Content-Disposition = %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPathTraversalAndInternalFiles(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
s := f.register("alice")
|
||||
for _, p := range []string{".trash/x", "a/.meta.json", ".accounts.json", ".users/alice/home/x"} {
|
||||
if w := s.put(p, "x"); w.Code != 400 {
|
||||
t.Errorf("PUT %s : %d", p, w.Code)
|
||||
}
|
||||
}
|
||||
// « .. » ne remonte jamais au-dessus de la racine : le chemin est normalisé sous la racine.
|
||||
want(t, s.put("../../escape.txt", "x"), 200)
|
||||
if s.get("/api/file?path=escape.txt").Body.String() != "x" {
|
||||
t.Error("chemin normalisé sous la racine")
|
||||
}
|
||||
if es, _ := os.ReadDir(filepath.Dir(f.root)); len(es) > 0 {
|
||||
for _, e := range es {
|
||||
if e.Name() == "escape.txt" {
|
||||
t.Error("écriture hors racine")
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, p := range []string{".accounts.json", ".tokens.json", ".session-secret", ".settings.json", ".share-secret", ".meta.json"} {
|
||||
if w := s.get("/api/file?path=" + p); w.Code == 200 {
|
||||
t.Errorf("lecture de %s : %s", p, w.Body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuotaAndMaxUpload(t *testing.T) {
|
||||
f := newFixture(t, func(st *storage.Store, sp *storage.Spaces) {
|
||||
sp.MaxUpload = 1 << 20
|
||||
st.Defaults.QuotaMB = 1
|
||||
})
|
||||
s := f.register("alice")
|
||||
want(t, s.put(".perso/a.bin", strings.Repeat("x", 700<<10)), 200)
|
||||
want(t, s.put(".perso/b.bin", strings.Repeat("x", 700<<10)), 507)
|
||||
want(t, s.put("commun.bin", strings.Repeat("x", 1100<<10)), 413)
|
||||
me := decode[meResponse](t, s.get("/api/me"))
|
||||
if me.Usage == nil || me.Usage.Quota != 1<<20 || me.Usage.Used < 700<<10 {
|
||||
t.Errorf("usage = %+v", me.Usage)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFolderOperationsAndZip(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
s := f.register("alice")
|
||||
want(t, s.json("POST", "/api/folder", map[string]string{"path": "projet"}), 201)
|
||||
want(t, s.put("projet/a.txt", "AAA"), 200)
|
||||
want(t, s.put("projet/sub/b.txt", "BBB"), 200)
|
||||
want(t, s.put("autre.txt", "CCC"), 200)
|
||||
want(t, s.json("POST", "/api/copy", map[string]string{"from": "projet", "to": "projet-copie"}), 201)
|
||||
if s.get("/api/file?path=projet-copie/sub/b.txt").Body.String() != "BBB" {
|
||||
t.Error("copie de dossier")
|
||||
}
|
||||
// ZIP d'un dossier (GET) et d'une sélection (formulaire POST).
|
||||
w := s.get("/api/zip?path=projet")
|
||||
want(t, w, 200)
|
||||
names := zipNames(t, w.Body.Bytes())
|
||||
if !names["projet/a.txt"] || !names["projet/sub/b.txt"] || !strings.Contains(w.Header().Get("Content-Disposition"), "projet.zip") {
|
||||
t.Errorf("zip dossier : %v %v", names, w.Header())
|
||||
}
|
||||
form := url.Values{"paths": {`["projet/a.txt","autre.txt"]`}}
|
||||
w = s.do("POST", "/api/zip", strings.NewReader(form.Encode()), "Content-Type", "application/x-www-form-urlencoded")
|
||||
want(t, w, 200)
|
||||
if n := zipNames(t, w.Body.Bytes()); !n["a.txt"] || !n["autre.txt"] {
|
||||
t.Errorf("zip sélection : %v", n)
|
||||
}
|
||||
want(t, s.get("/api/zip?path=../../etc"), 404)
|
||||
// Déplacement multiple avec échec partiel.
|
||||
want(t, s.put("dest/autre.txt", "déjà là"), 200)
|
||||
res := decode[[]storage.MoveResult](t, s.json("POST", "/api/move-many", map[string]any{"paths": []string{"autre.txt", "projet/a.txt"}, "dir": "dest"}))
|
||||
if len(res) != 2 || res[0].Error == "" || res[1].Error != "" {
|
||||
t.Errorf("move-many = %+v", res)
|
||||
}
|
||||
// Corbeille.
|
||||
want(t, s.do("DELETE", "/api/entry?path=dest&recursive=true", nil), 204)
|
||||
tr := decode[[]storage.Entry](t, s.get("/api/list?path=.poubelle"))
|
||||
if len(tr) != 1 || tr[0].Origin != "dest" {
|
||||
t.Fatalf("poubelle = %+v", tr)
|
||||
}
|
||||
want(t, s.json("POST", "/api/trash/restore", map[string]any{"paths": []string{tr[0].Path}}), 200)
|
||||
if s.get("/api/file?path=dest/a.txt").Body.String() != "AAA" {
|
||||
t.Error("restauration depuis la poubelle")
|
||||
}
|
||||
}
|
||||
|
||||
func zipNames(t *testing.T, b []byte) map[string]bool {
|
||||
t.Helper()
|
||||
zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))
|
||||
if err != nil {
|
||||
t.Fatalf("zip illisible : %v", err)
|
||||
}
|
||||
out := map[string]bool{}
|
||||
for _, f := range zr.File {
|
||||
out[f.Name] = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestShareFolderWithPassword(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
s := f.register("alice")
|
||||
want(t, s.put("pub/a.txt", "AAA"), 200)
|
||||
want(t, s.put("pub/sub/b.png", "\x89PNG"), 200)
|
||||
want(t, s.put("prive.txt", "secret"), 200)
|
||||
sh := decode[storage.Share](t, s.json("POST", "/api/shares", map[string]any{"path": "pub", "days": 7, "password": "mot-de-passe-partage"}))
|
||||
if !sh.IsDir || !sh.Protected || sh.Token == "" {
|
||||
t.Fatalf("share = %+v", sh)
|
||||
}
|
||||
visitor := f.session() // sans compte
|
||||
base := "/api/public/" + sh.Token
|
||||
|
||||
// Verrouillé : seuls le titre et l'indication de mot de passe sortent.
|
||||
info := decode[publicInfo](t, visitor.get(base))
|
||||
if !info.Protected || info.Name != "" || len(info.Entries) != 0 {
|
||||
t.Errorf("lien verrouillé : %+v", info)
|
||||
}
|
||||
want(t, visitor.get(base+"/file?sub=a.txt"), 401)
|
||||
want(t, visitor.get(base+"/zip"), 401)
|
||||
want(t, visitor.json("POST", base+"/unlock", map[string]string{"password": "faux"}), 403)
|
||||
want(t, visitor.json("POST", base+"/unlock", map[string]string{"password": "mot-de-passe-partage"}), 204)
|
||||
|
||||
info = decode[publicInfo](t, visitor.get(base))
|
||||
if info.Name != "pub" || !info.IsDir || len(info.Entries) != 2 || info.Entries[0].Name != "sub" {
|
||||
t.Errorf("contenu du lien : %+v", info)
|
||||
}
|
||||
if strings.Contains(visitor.get(base).Body.String(), "pub/") || strings.Contains(visitor.get(base).Body.String(), "alice") {
|
||||
t.Error("le chemin réel ou le propriétaire fuite dans la réponse publique")
|
||||
}
|
||||
sub := decode[publicInfo](t, visitor.get(base+"?sub=sub"))
|
||||
if sub.Name != "sub" || len(sub.Entries) != 1 || sub.Entries[0].Name != "b.png" {
|
||||
t.Errorf("sous-dossier : %+v", sub)
|
||||
}
|
||||
w := visitor.get(base + "/file?sub=a.txt")
|
||||
want(t, w, 200)
|
||||
if w.Body.String() != "AAA" {
|
||||
t.Errorf("fichier partagé = %q", w.Body)
|
||||
}
|
||||
want(t, visitor.get(base+"/file?sub=sub/b.png&inline=1"), 200)
|
||||
// Hors du dossier partagé : refus.
|
||||
for _, sub := range []string{"../prive.txt", "sub/../../prive.txt", ".trash", "%2e%2e/prive.txt"} {
|
||||
if w := visitor.get(base + "/file?sub=" + sub); w.Code == 200 {
|
||||
t.Errorf("sub=%s : %s", sub, w.Body)
|
||||
}
|
||||
}
|
||||
if n := zipNames(t, visitor.get(base+"/zip").Body.Bytes()); !n["pub/a.txt"] || n["prive.txt"] {
|
||||
t.Errorf("zip public : %v", n)
|
||||
}
|
||||
// Le cookie de déverrouillage d'un lien ne vaut pas pour un autre.
|
||||
sh2 := decode[storage.Share](t, s.json("POST", "/api/shares", map[string]any{"path": "pub", "days": 0, "password": "autre-mot-de-passe"}))
|
||||
want(t, visitor.get("/api/public/"+sh2.Token+"/file?sub=a.txt"), 401)
|
||||
// Compteur de téléchargements (hors lecture partielle).
|
||||
list := decode[[]storage.Share](t, s.get("/api/shares?path=pub"))
|
||||
var dl int
|
||||
for _, x := range list {
|
||||
if x.ID == sh.ID {
|
||||
dl = x.Downloads
|
||||
}
|
||||
}
|
||||
if dl < 2 {
|
||||
t.Errorf("téléchargements = %d", dl)
|
||||
}
|
||||
// Un jeton falsifié ou révoqué ne donne rien.
|
||||
want(t, visitor.get("/api/public/"+sh.Token[:len(sh.Token)-3]+"abc"), 404)
|
||||
want(t, s.do("DELETE", "/api/shares?id="+sh.ID, nil), 204)
|
||||
want(t, visitor.get(base), 404)
|
||||
// X-Robots-Tag
|
||||
if visitor.get("/api/public/xxx").Header().Get("X-Robots-Tag") == "" {
|
||||
t.Error("X-Robots-Tag absent")
|
||||
}
|
||||
}
|
||||
|
||||
func TestShareSingleFileAndThumb(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
s := f.register("alice")
|
||||
png := makePNG(t, 900, 300)
|
||||
want(t, s.put("photo.png", png), 200)
|
||||
sh := decode[storage.Share](t, s.json("POST", "/api/shares", map[string]any{"path": "photo.png", "days": 1}))
|
||||
v := f.session()
|
||||
info := decode[publicInfo](t, v.get("/api/public/"+sh.Token))
|
||||
if info.IsDir || info.Name != "photo.png" || info.Size != int64(len(png)) || info.Expires == nil {
|
||||
t.Errorf("info = %+v", info)
|
||||
}
|
||||
want(t, v.get("/api/public/"+sh.Token+"?sub=x"), 404) // pas de sous-chemin pour un fichier
|
||||
w := v.get("/api/public/" + sh.Token + "/thumb")
|
||||
want(t, w, 200)
|
||||
if w.Header().Get("Content-Type") != "image/png" {
|
||||
t.Errorf("thumb : %v", w.Header())
|
||||
}
|
||||
// Miniature privée via l'API connectée.
|
||||
want(t, s.get("/api/thumb?path=photo.png"), 200)
|
||||
want(t, f.session().get("/api/thumb?path=photo.png"), 401)
|
||||
}
|
||||
|
||||
func TestSettingsAndAdminPermissions(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
admin := f.register("alice")
|
||||
want(t, admin.json("PUT", "/api/settings", map[string]any{"registration": "open"}), 200)
|
||||
bob := f.register("bob")
|
||||
me := decode[meResponse](t, bob.get("/api/me"))
|
||||
if me.Admin || me.User == nil || me.User.Role != "user" {
|
||||
t.Errorf("bob = %+v", me)
|
||||
}
|
||||
// Un utilisateur ordinaire ne règle ni les paramètres, ni le logo, ni les comptes.
|
||||
want(t, bob.json("PUT", "/api/settings", map[string]any{"title": "X"}), 403)
|
||||
want(t, bob.do("DELETE", "/api/logo", nil), 403)
|
||||
want(t, bob.get("/api/admin/users"), 403)
|
||||
want(t, bob.json("POST", "/api/admin/users", map[string]any{"username": "eve", "password": "mot-de-passe-eve"}), 403)
|
||||
want(t, bob.json("PATCH", "/api/admin/users/alice", map[string]any{"role": "user"}), 403)
|
||||
want(t, bob.do("DELETE", "/api/admin/users/alice", nil), 403)
|
||||
want(t, bob.do("POST", "/api/shares/revoke-all", nil), 403)
|
||||
// Un visiteur anonyme non plus (route publique /api/logo).
|
||||
want(t, f.session().do("DELETE", "/api/logo", nil), 403)
|
||||
want(t, f.session().do("PUT", "/api/logo", strings.NewReader("x")), 403)
|
||||
|
||||
st := decode[storage.Settings](t, admin.json("PUT", "/api/settings", map[string]any{"title": "Mon cloud", "quotaMB": 50, "commonReadonly": true, "trashDays": 30}))
|
||||
if st.Title != "Mon cloud" || st.QuotaMB != 50 || !st.CommonReadonly || st.TrashDays != 30 {
|
||||
t.Errorf("settings = %+v", st)
|
||||
}
|
||||
want(t, admin.json("PUT", "/api/settings", map[string]any{"registration": "nimporte"}), 400)
|
||||
// Commun en lecture seule : bob ne dépose plus qu'à titre personnel.
|
||||
want(t, bob.put("x.txt", "x"), 403)
|
||||
want(t, bob.put(".perso/x.txt", "x"), 200)
|
||||
want(t, admin.put("admin.txt", "x"), 200)
|
||||
// Le titre est visible de tous avant connexion.
|
||||
if m := decode[meResponse](t, f.session().get("/api/me")); m.Title != "Mon cloud" {
|
||||
t.Errorf("titre public = %q", m.Title)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminUserManagement(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
admin := f.register("alice")
|
||||
want(t, admin.json("PUT", "/api/settings", map[string]any{"registration": "approval"}), 200)
|
||||
pending := f.register("bob") // 202 : en attente
|
||||
want(t, pending.get("/api/list?path="), 401)
|
||||
if m := decode[meResponse](t, admin.get("/api/me")); m.Pending != 1 {
|
||||
t.Errorf("en attente = %d", m.Pending)
|
||||
}
|
||||
users := decode[[]auth.AccountInfo](t, admin.get("/api/admin/users"))
|
||||
if len(users) != 2 || users[1].Status != "pending" || strings.Contains(admin.get("/api/admin/users").Body.String(), "hash") {
|
||||
t.Errorf("users = %+v", users)
|
||||
}
|
||||
want(t, admin.json("PATCH", "/api/admin/users/bob", map[string]any{"status": "active"}), 200)
|
||||
bob := f.login("bob")
|
||||
want(t, bob.put(".perso/mine.txt", "m"), 200)
|
||||
// Création directe, rôle, mot de passe.
|
||||
want(t, admin.json("POST", "/api/admin/users", map[string]any{"username": "carl", "name": "Carl", "password": "mot-de-passe-carl", "role": "admin"}), 201)
|
||||
want(t, admin.json("POST", "/api/admin/users", map[string]any{"username": "carl", "password": "mot-de-passe-carl"}), 400)
|
||||
want(t, admin.json("PATCH", "/api/admin/users/carl", map[string]any{"password": "nouveau-mot-de-passe"}), 200)
|
||||
want(t, f.session().json("POST", "/auth/local/login", map[string]string{"username": "carl", "password": "nouveau-mot-de-passe"}), 200)
|
||||
// Garde-fous.
|
||||
want(t, admin.do("DELETE", "/api/admin/users/alice", nil), 400) // soi-même
|
||||
// Désactivation : la session et les jetons de bob cessent de marcher.
|
||||
tok := decode[struct{ Token string }](t, bob.json("POST", "/api/tokens", map[string]string{"name": "script"}))
|
||||
api := &session{f: f, cookies: map[string]*http.Cookie{}, bearer: tok.Token}
|
||||
want(t, api.get("/api/list?path=.perso"), 200)
|
||||
want(t, admin.json("PATCH", "/api/admin/users/bob", map[string]any{"status": "disabled"}), 200)
|
||||
want(t, bob.get("/api/list?path="), 401)
|
||||
want(t, api.get("/api/list?path=.perso"), 401)
|
||||
// Suppression : l'espace personnel est mis de côté, pas hérité par un homonyme.
|
||||
want(t, admin.do("DELETE", "/api/admin/users/bob", nil), 204)
|
||||
again := f.register("bob")
|
||||
_ = again
|
||||
want(t, admin.json("PATCH", "/api/admin/users/bob", map[string]any{"status": "active"}), 200)
|
||||
b2 := f.login("bob")
|
||||
if es := decode[[]storage.Entry](t, b2.get("/api/list?path=.perso")); len(es) != 0 {
|
||||
t.Errorf("héritage de l'espace d'un compte supprimé : %+v", es)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPITokens(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
s := f.register("alice")
|
||||
created := decode[struct {
|
||||
ID string
|
||||
Token string
|
||||
}](t, s.json("POST", "/api/tokens", map[string]string{"name": "sauvegarde"}))
|
||||
if !strings.HasPrefix(created.Token, "upd_") {
|
||||
t.Fatalf("jeton = %q", created.Token)
|
||||
}
|
||||
if strings.Contains(s.get("/api/tokens").Body.String(), created.Token) {
|
||||
t.Error("le secret du jeton est relisible")
|
||||
}
|
||||
cli := &session{f: f, cookies: map[string]*http.Cookie{}, bearer: created.Token}
|
||||
want(t, cli.put("depuis-curl.txt", "ok"), 200)
|
||||
want(t, cli.get("/api/file?path=depuis-curl.txt"), 200)
|
||||
// Un jeton ne gère pas les jetons ni les comptes.
|
||||
want(t, cli.json("POST", "/api/tokens", map[string]string{"name": "x"}), 403)
|
||||
want(t, cli.get("/api/tokens"), 403)
|
||||
// Jeton invalide.
|
||||
bad := &session{f: f, cookies: map[string]*http.Cookie{}, bearer: "upd_faux"}
|
||||
want(t, bad.get("/api/list?path="), 401)
|
||||
// Révocation.
|
||||
want(t, s.do("DELETE", "/api/tokens/"+created.ID, nil), 204)
|
||||
want(t, cli.get("/api/list?path="), 401)
|
||||
}
|
||||
|
||||
func TestAccountSelfService(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
s := f.register("alice")
|
||||
want(t, s.json("POST", "/api/account/password", map[string]string{"current": "faux", "new": "nouveau-mot-de-passe"}), 403)
|
||||
want(t, s.json("POST", "/api/account/password", map[string]string{"current": "mot-de-passe-alice", "new": "court"}), 400)
|
||||
want(t, s.json("POST", "/api/account/password", map[string]string{"current": "mot-de-passe-alice", "new": "nouveau-mot-de-passe"}), 204)
|
||||
want(t, f.session().json("POST", "/auth/local/login", map[string]string{"username": "alice", "password": "nouveau-mot-de-passe"}), 200)
|
||||
want(t, s.json("PATCH", "/api/account", map[string]string{"name": "Alice D."}), 204)
|
||||
if m := decode[meResponse](t, s.get("/api/me")); m.User.Name != "Alice D." {
|
||||
t.Errorf("nom = %q", m.User.Name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTagsFavoritesSearchAndDetails(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
s := f.register("alice")
|
||||
want(t, s.put("notes/plan.md", "# Plan\nle réseau 10.1.2.0/24"), 200)
|
||||
want(t, s.put("photo.png", makePNG(t, 60, 40)), 200)
|
||||
want(t, s.json("POST", "/api/meta/tags", map[string]any{"paths": []string{"notes/plan.md"}, "add": []string{"Projet"}}), 204)
|
||||
want(t, s.json("POST", "/api/meta/favorite", map[string]any{"paths": []string{"photo.png", "notes"}, "favorite": true}), 204)
|
||||
hits := decode[[]storage.Hit](t, s.get("/api/search?q=10.1.2"))
|
||||
if len(hits) != 1 || hits[0].Path != "notes/plan.md" || hits[0].Snippet == "" {
|
||||
t.Errorf("recherche = %+v", hits)
|
||||
}
|
||||
if hits = decode[[]storage.Hit](t, s.get("/api/search?tag=projet")); len(hits) != 1 {
|
||||
t.Errorf("tag = %+v", hits)
|
||||
}
|
||||
if favs := decode[[]storage.Entry](t, s.get("/api/list?path=.favoris")); len(favs) != 2 {
|
||||
t.Errorf("favoris = %+v", favs)
|
||||
}
|
||||
es := decode[[]storage.Entry](t, s.get("/api/list?path=&details=1"))
|
||||
var img, dir *storage.Entry
|
||||
for i := range es {
|
||||
switch es[i].Name {
|
||||
case "photo.png":
|
||||
img = &es[i]
|
||||
case "notes":
|
||||
dir = &es[i]
|
||||
}
|
||||
}
|
||||
if img == nil || img.Details == nil || img.Details.Width != 60 || img.Details.Height != 40 || !img.Favorite {
|
||||
t.Errorf("image = %+v", img)
|
||||
}
|
||||
if dir == nil || dir.Details == nil || dir.Details.Files != 1 || dir.Details.Total == 0 {
|
||||
t.Errorf("dossier = %+v", dir)
|
||||
}
|
||||
h := decode[map[string]string](t, s.get("/api/hash?path=notes/plan.md"))
|
||||
if len(h["sha256"]) != 64 {
|
||||
t.Errorf("hash = %v", h)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,517 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"net/http"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/vblogio/upandown/internal/storage"
|
||||
)
|
||||
|
||||
func (h *Handler) list(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
entries, err := u.List(r.URL.Query().Get("path"))
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
if wantDetails(r) {
|
||||
ps := make([]*storage.Entry, len(entries))
|
||||
for i := range entries {
|
||||
ps[i] = &entries[i]
|
||||
}
|
||||
u.AddDetails(ps)
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, http.StatusOK, entries)
|
||||
}
|
||||
|
||||
func (h *Handler) search(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
f := storage.Filter{Tag: q.Get("tag"), Favorite: q.Get("fav") == "true"}
|
||||
entries, err := u.Search(q.Get("q"), f, 200)
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
if wantDetails(r) {
|
||||
ps := make([]*storage.Entry, len(entries))
|
||||
for i := range entries {
|
||||
ps[i] = &entries[i].Entry
|
||||
}
|
||||
u.AddDetails(ps)
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, http.StatusOK, entries)
|
||||
}
|
||||
|
||||
func (h *Handler) tags(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
tags, err := u.Tags()
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
writeJSON(w, http.StatusOK, tags)
|
||||
}
|
||||
|
||||
type metaReq struct {
|
||||
Paths []string `json:"paths"`
|
||||
Favorite bool `json:"favorite"`
|
||||
Add []string `json:"add"`
|
||||
Remove []string `json:"remove"`
|
||||
Icon string `json:"icon"`
|
||||
}
|
||||
|
||||
func (h *Handler) decodeMeta(w http.ResponseWriter, r *http.Request) (metaReq, bool) {
|
||||
var req metaReq
|
||||
if !h.decode(w, r, &req) {
|
||||
return req, false
|
||||
}
|
||||
if len(req.Paths) == 0 || len(req.Paths) > 1000 {
|
||||
writeErr(w, http.StatusBadRequest, "entre 1 et 1000 chemins attendus")
|
||||
return req, false
|
||||
}
|
||||
return req, true
|
||||
}
|
||||
|
||||
func (h *Handler) setFavorite(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
req, ok := h.decodeMeta(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := u.SetFavorite(req.Paths, req.Favorite); err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *Handler) editTags(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
req, ok := h.decodeMeta(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := u.EditTags(req.Paths, req.Add, req.Remove); err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *Handler) setIcon(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
req, ok := h.decodeMeta(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := u.SetIcon(req.Paths, req.Icon); err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// download sert un fichier (Range, ETag, If-Modified-Since). Sans inline, ou si
|
||||
// le type n'est pas sûr à afficher, il est téléchargé (Content-Disposition:
|
||||
// attachment).
|
||||
func (h *Handler) download(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
f, fi, err := u.Open(r.URL.Query().Get("path"))
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
serveFile(w, r, f, fi, fi.Name(), r.URL.Query().Get("inline") == "1")
|
||||
}
|
||||
|
||||
// upload dépose un fichier : le corps de la requête est le contenu, lu en flux
|
||||
// (aucune limite de mémoire). Paramètres : conflict (fail, overwrite, rename),
|
||||
// mtime (date de modification d'origine, en millisecondes Unix).
|
||||
func (h *Handler) upload(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
o := storage.PutOptions{Conflict: q.Get("conflict"), IfMatch: r.Header.Get("If-Match")}
|
||||
switch o.Conflict {
|
||||
case "", "fail", "overwrite", "rename":
|
||||
default:
|
||||
writeErr(w, http.StatusBadRequest, "conflict : fail, overwrite ou rename")
|
||||
return
|
||||
}
|
||||
if v := q.Get("mtime"); v != "" {
|
||||
if ms, err := strconv.ParseInt(v, 10, 64); err == nil {
|
||||
o.ModTime = time.UnixMilli(ms)
|
||||
}
|
||||
}
|
||||
e, err := u.Put(q.Get("path"), r.Body, r.ContentLength, o)
|
||||
if err != nil {
|
||||
// Le corps n'a pas été lu en entier : fermer la connexion plutôt que de la réutiliser.
|
||||
w.Header().Set("Connection", "close")
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, e)
|
||||
}
|
||||
|
||||
type pathReq struct {
|
||||
Path string `json:"path"`
|
||||
}
|
||||
|
||||
type moveReq struct {
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
}
|
||||
|
||||
func (h *Handler) mkdir(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req pathReq
|
||||
if !h.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
entry, err := u.Mkdir(req.Path)
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, entry)
|
||||
}
|
||||
|
||||
func (h *Handler) move(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req moveReq
|
||||
if !h.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
entry, err := u.Move(req.From, req.To)
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, entry)
|
||||
}
|
||||
|
||||
type moveManyReq struct {
|
||||
Paths []string `json:"paths"`
|
||||
Dir string `json:"dir"`
|
||||
}
|
||||
|
||||
// moveMany renvoie toujours 200 avec le détail par élément : le client
|
||||
// affiche les échecs partiels (ex. nom déjà pris dans la destination).
|
||||
func (h *Handler) moveMany(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req moveManyReq
|
||||
if !h.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
if len(req.Paths) == 0 || len(req.Paths) > 1000 {
|
||||
writeErr(w, http.StatusBadRequest, "entre 1 et 1000 chemins attendus")
|
||||
return
|
||||
}
|
||||
res, err := u.MoveMany(req.Paths, req.Dir)
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, res)
|
||||
}
|
||||
|
||||
func (h *Handler) copy(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req moveReq
|
||||
if !h.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
entry, err := u.Copy(req.From, req.To)
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, entry)
|
||||
}
|
||||
|
||||
func (h *Handler) delete(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
if err := u.Delete(q.Get("path"), q.Get("recursive") == "true"); err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *Handler) restoreTrash(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
req, ok := h.decodeMeta(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, u.RestoreTrash(req.Paths))
|
||||
}
|
||||
|
||||
func (h *Handler) thumb(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
data, typ, mod, err := u.Thumb(r.URL.Query().Get("path"))
|
||||
if err != nil {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
writeThumb(w, data, typ, mod)
|
||||
}
|
||||
|
||||
func writeThumb(w http.ResponseWriter, data []byte, typ string, mod time.Time) {
|
||||
// L'URL porte la date du fichier (?v=...) : une nouvelle version change l'URL.
|
||||
w.Header().Set("Cache-Control", "private, max-age=86400")
|
||||
w.Header().Set("Content-Type", typ)
|
||||
w.Header().Set("Last-Modified", mod.UTC().Format(http.TimeFormat))
|
||||
_, _ = w.Write(data)
|
||||
}
|
||||
|
||||
// zip envoie un dossier ou une sélection en archive ZIP. GET ?path=x pour un
|
||||
// élément ; POST (formulaire) avec paths = tableau JSON de chemins.
|
||||
func (h *Handler) zip(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var paths []string
|
||||
if r.Method == http.MethodPost {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 4<<20)
|
||||
if err := r.ParseForm(); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "formulaire invalide")
|
||||
return
|
||||
}
|
||||
if err := jsonUnmarshal(r.PostForm.Get("paths"), &paths); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "paths : tableau JSON attendu")
|
||||
return
|
||||
}
|
||||
} else {
|
||||
paths = r.URL.Query()["path"]
|
||||
}
|
||||
if len(paths) == 0 || len(paths) > 5000 {
|
||||
writeErr(w, http.StatusBadRequest, "entre 1 et 5000 chemins attendus")
|
||||
return
|
||||
}
|
||||
items, name, err := u.ZipItems(paths)
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/zip")
|
||||
w.Header().Set("Content-Disposition", contentDisposition(false, name+".zip"))
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if err := storage.WriteZip(w, items); err != nil {
|
||||
panic(http.ErrAbortHandler) // archive tronquée : couper la connexion plutôt qu'annoncer une fin normale
|
||||
}
|
||||
}
|
||||
|
||||
// hash calcule l'empreinte SHA-256 d'un fichier.
|
||||
func (h *Handler) hash(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
f, _, err := u.Open(r.URL.Query().Get("path"))
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
sum := sha256.New()
|
||||
if _, err := io.Copy(sum, f); err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"sha256": hex.EncodeToString(sum.Sum(nil))})
|
||||
}
|
||||
|
||||
func (h *Handler) history(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
vs, err := u.Versions(r.URL.Query().Get("path"))
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
writeJSON(w, http.StatusOK, vs)
|
||||
}
|
||||
|
||||
// readVersion télécharge une version ancienne d'un fichier.
|
||||
func (h *Handler) readVersion(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
f, fi, err := u.OpenVersion(q.Get("path"), q.Get("id"))
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
serveFile(w, r, f, fi, path.Base(q.Get("path")), false)
|
||||
}
|
||||
|
||||
func (h *Handler) snapshot(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req pathReq
|
||||
if !h.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
v, err := u.Snapshot(req.Path)
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, v)
|
||||
}
|
||||
|
||||
type restoreReq struct {
|
||||
Path string `json:"path"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
func (h *Handler) restore(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req restoreReq
|
||||
if !h.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
entry, err := u.Restore(req.Path, req.ID)
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, entry)
|
||||
}
|
||||
|
||||
func (h *Handler) shares(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
l, err := u.Shares(r.URL.Query().Get("path"))
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, http.StatusOK, l)
|
||||
}
|
||||
|
||||
type shareReq struct {
|
||||
Path string `json:"path"`
|
||||
Days int `json:"days"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func (h *Handler) createShare(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req shareReq
|
||||
if !h.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
if req.Days < 0 || req.Days > 3650 {
|
||||
writeErr(w, http.StatusBadRequest, "durée de 0 (sans expiration) à 3650 jours")
|
||||
return
|
||||
}
|
||||
sh, err := u.CreateShare(req.Path, storage.ShareOptions{TTL: time.Duration(req.Days) * 24 * time.Hour, Password: req.Password})
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, sh)
|
||||
}
|
||||
|
||||
func (h *Handler) revokeShare(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := u.RevokeShare(r.URL.Query().Get("id")); err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *Handler) revokeAllShares(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := h.space(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := u.RevokeAllShares(); err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func jsonUnmarshal(s string, v any) error { return jsonDecode(strings.NewReader(s), v) }
|
||||
@@ -0,0 +1,233 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/vblogio/upandown/internal/auth"
|
||||
"github.com/vblogio/upandown/internal/storage"
|
||||
)
|
||||
|
||||
type meUser struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Role string `json:"role"`
|
||||
Provider string `json:"provider,omitempty"`
|
||||
}
|
||||
|
||||
type usage struct {
|
||||
Used int64 `json:"used"`
|
||||
Quota int64 `json:"quota"` // 0 : illimité
|
||||
}
|
||||
|
||||
// meResponse est lu avant la connexion (page de connexion : fournisseurs,
|
||||
// inscription, titre) puis après (utilisateur, droits, occupation).
|
||||
type meResponse struct {
|
||||
Mode string `json:"mode"` // none, local, oidc ou both
|
||||
Local bool `json:"local"`
|
||||
OIDC bool `json:"oidc"`
|
||||
OIDCName string `json:"oidcName,omitempty"`
|
||||
Registration string `json:"registration"` // closed, approval ou open (comptes locaux)
|
||||
Setup bool `json:"setup,omitempty"`
|
||||
Title string `json:"title"`
|
||||
Logo string `json:"logo,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
|
||||
User *meUser `json:"user,omitempty"`
|
||||
Admin bool `json:"admin"`
|
||||
CanChangePW bool `json:"canChangePassword,omitempty"`
|
||||
Logout string `json:"logout,omitempty"`
|
||||
Usage *usage `json:"usage,omitempty"`
|
||||
CommonReadonly bool `json:"commonReadonly"`
|
||||
Pending int `json:"pending,omitempty"` // administrateur : inscriptions à valider
|
||||
}
|
||||
|
||||
func (h *Handler) me(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
st, err := h.Store.ReadSettings()
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
m := meResponse{Mode: h.Mode, Local: h.Mode == "local" || h.Mode == "both", OIDC: h.Mode == "oidc" || h.Mode == "both",
|
||||
OIDCName: h.OIDCName, Registration: st.Registration, Title: st.Title, Logo: st.Logo, Version: h.Version,
|
||||
CommonReadonly: st.CommonReadonly}
|
||||
if !m.Local {
|
||||
m.Registration = storage.RegClosed
|
||||
}
|
||||
if h.Accounts != nil {
|
||||
m.Setup = m.Local && h.Accounts.NeedsSetup()
|
||||
}
|
||||
u := auth.UserFrom(r.Context())
|
||||
switch {
|
||||
case u != nil:
|
||||
m.User = &meUser{ID: u.ID, Name: u.Name, Email: u.Email, Role: u.Role, Provider: u.Provider}
|
||||
m.Logout = "/auth/logout"
|
||||
m.CanChangePW = u.Provider == auth.ProviderLocal
|
||||
case h.Mode == "none":
|
||||
m.User = &meUser{ID: storage.LocalUser, Name: "Utilisateur", Role: auth.RoleAdmin}
|
||||
}
|
||||
if m.User != nil {
|
||||
m.Admin = h.isAdmin(r)
|
||||
if sp, err := h.Spaces.For(userID(r), m.Admin); err == nil {
|
||||
used, quota := sp.Usage()
|
||||
m.Usage = &usage{Used: used, Quota: quota}
|
||||
}
|
||||
if m.Admin && h.Accounts != nil {
|
||||
m.Pending = h.Accounts.PendingCount()
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, m)
|
||||
}
|
||||
|
||||
// --- Paramètres et logo ---------------------------------------------------------------
|
||||
|
||||
func (h *Handler) readSettings(w http.ResponseWriter, r *http.Request) {
|
||||
st, err := h.Store.ReadSettings()
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
writeJSON(w, http.StatusOK, st)
|
||||
}
|
||||
|
||||
// settingsReq : seuls les champs présents sont modifiés.
|
||||
type settingsReq struct {
|
||||
Title *string `json:"title"`
|
||||
TrashDays *int `json:"trashDays"`
|
||||
Registration *string `json:"registration"`
|
||||
QuotaMB *int64 `json:"quotaMB"`
|
||||
CommonReadonly *bool `json:"commonReadonly"`
|
||||
}
|
||||
|
||||
func (h *Handler) writeSettings(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.admin(w, r) {
|
||||
return
|
||||
}
|
||||
var req settingsReq
|
||||
if !h.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
st, err := h.Store.ReadSettings()
|
||||
if err == nil && req.Title != nil {
|
||||
st, err = h.Store.WriteTitle(*req.Title)
|
||||
}
|
||||
if err == nil && req.Registration != nil {
|
||||
st, err = h.Store.WriteRegistration(*req.Registration)
|
||||
}
|
||||
if err == nil && req.QuotaMB != nil {
|
||||
st, err = h.Store.WriteQuota(*req.QuotaMB)
|
||||
}
|
||||
if err == nil && req.CommonReadonly != nil {
|
||||
st, err = h.Store.WriteCommonReadonly(*req.CommonReadonly)
|
||||
}
|
||||
if err == nil && req.TrashDays != nil {
|
||||
if st, err = h.Store.WriteTrashDays(*req.TrashDays); err == nil {
|
||||
if perr := h.Spaces.PurgeTrash(); perr != nil {
|
||||
slog.Warn("poubelle : purge incomplète", "err", perr)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, st)
|
||||
}
|
||||
|
||||
func (h *Handler) readLogo(w http.ResponseWriter, r *http.Request) {
|
||||
data, err := h.Store.ReadLogo()
|
||||
if err != nil {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
// L'URL porte la version du logo (?v=...) : un nouveau logo change l'URL.
|
||||
w.Header().Set("Cache-Control", "private, max-age=86400")
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
_, _ = w.Write(data)
|
||||
}
|
||||
|
||||
func (h *Handler) writeLogo(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.admin(w, r) {
|
||||
return
|
||||
}
|
||||
data, err := io.ReadAll(http.MaxBytesReader(w, r.Body, storage.MaxLogoUpload))
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
st, err := h.Store.WriteLogo(data)
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, st)
|
||||
}
|
||||
|
||||
func (h *Handler) deleteLogo(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.admin(w, r) {
|
||||
return
|
||||
}
|
||||
st, err := h.Store.DeleteLogo()
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, st)
|
||||
}
|
||||
|
||||
// --- Compte ------------------------------------------------------------------------------
|
||||
|
||||
func accountErr(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, auth.ErrNoAccount):
|
||||
writeErr(w, http.StatusNotFound, err.Error())
|
||||
case errors.Is(err, auth.ErrBadCredentials):
|
||||
writeErr(w, http.StatusForbidden, "mot de passe actuel incorrect")
|
||||
case errors.Is(err, auth.ErrInvalidAccount), errors.Is(err, auth.ErrLastAdmin), errors.Is(err, auth.ErrAccountExists):
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
default:
|
||||
slog.Error("compte", "err", err)
|
||||
writeErr(w, http.StatusInternalServerError, "erreur interne")
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) changePassword(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Current string `json:"current"`
|
||||
New string `json:"new"`
|
||||
}
|
||||
if !h.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
if err := h.Accounts.ChangePassword(userID(r), req.Current, req.New); err != nil {
|
||||
accountErr(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *Handler) patchAccount(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Name *string `json:"name"`
|
||||
Email *string `json:"email"`
|
||||
}
|
||||
if !h.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
acc, ok := h.Accounts.Get(userID(r))
|
||||
if !ok || acc.Provider != auth.ProviderLocal {
|
||||
writeErr(w, http.StatusBadRequest, "profil géré par le fournisseur d'identité")
|
||||
return
|
||||
}
|
||||
if _, err := h.Accounts.Update(acc.ID, auth.Patch{Name: req.Name, Email: req.Email}); err != nil {
|
||||
accountErr(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/vblogio/upandown/internal/storage"
|
||||
)
|
||||
|
||||
// Liens de partage publics : /s/<jeton> dans l'interface, /api/public/<jeton>
|
||||
// pour les données. Rien d'autre n'est accessible sans authentification : ni
|
||||
// l'explorateur, ni les chemins réels (les entrées sont décrites relativement
|
||||
// à l'élément partagé).
|
||||
|
||||
const unlockCookiePrefix = "ud_share_"
|
||||
|
||||
type publicEntry struct {
|
||||
Name string `json:"name"`
|
||||
IsDir bool `json:"isDir"`
|
||||
Size int64 `json:"size"`
|
||||
ModTime time.Time `json:"modTime"`
|
||||
}
|
||||
|
||||
type publicInfo struct {
|
||||
Title string `json:"title"`
|
||||
Logo string `json:"logo,omitempty"`
|
||||
Protected bool `json:"protected,omitempty"` // mot de passe requis (rien d'autre n'est révélé)
|
||||
Name string `json:"name,omitempty"`
|
||||
IsDir bool `json:"isDir"`
|
||||
Size int64 `json:"size"`
|
||||
ModTime time.Time `json:"modTime"`
|
||||
Sub string `json:"sub,omitempty"` // dossier affiché, relatif à l'élément partagé
|
||||
Entries []publicEntry `json:"entries,omitempty"`
|
||||
Expires *time.Time `json:"expires,omitempty"`
|
||||
}
|
||||
|
||||
// shared résout le lien de la requête et vérifie le déverrouillage s'il est
|
||||
// protégé par un mot de passe.
|
||||
func (h *Handler) shared(w http.ResponseWriter, r *http.Request) (storage.Share, *storage.Store, bool, bool) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Header().Set("X-Robots-Tag", "noindex, nofollow")
|
||||
sh, st, err := h.Spaces.ResolveShare(r.PathValue("token"))
|
||||
if err != nil {
|
||||
if errors.Is(err, storage.ErrNotFound) {
|
||||
writeErr(w, http.StatusNotFound, "lien invalide, expiré ou révoqué")
|
||||
} else {
|
||||
fail(w, err)
|
||||
}
|
||||
return sh, nil, false, false
|
||||
}
|
||||
unlocked := true
|
||||
if sh.Protected {
|
||||
want, err := st.UnlockCookie(sh)
|
||||
c, cerr := r.Cookie(unlockCookiePrefix + sh.ID)
|
||||
unlocked = err == nil && cerr == nil && c.Value == want
|
||||
}
|
||||
return sh, st, unlocked, true
|
||||
}
|
||||
|
||||
// sharedItem renvoie le Store et le chemin de l'élément visé (sub : sous-chemin
|
||||
// demandé), en refusant l'accès tant que le lien n'est pas déverrouillé.
|
||||
func (h *Handler) sharedItem(w http.ResponseWriter, r *http.Request) (storage.Share, *storage.Store, string, string, bool) {
|
||||
sh, st, unlocked, ok := h.shared(w, r)
|
||||
if !ok {
|
||||
return sh, nil, "", "", false
|
||||
}
|
||||
if !unlocked {
|
||||
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "mot de passe requis", "code": "password"})
|
||||
return sh, nil, "", "", false
|
||||
}
|
||||
sub := r.URL.Query().Get("sub")
|
||||
full, err := storage.SharedPath(sh, sub)
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return sh, nil, "", "", false
|
||||
}
|
||||
return sh, st, full, sub, true
|
||||
}
|
||||
|
||||
func (h *Handler) branding(info *publicInfo) {
|
||||
if st, err := h.Store.ReadSettings(); err == nil {
|
||||
info.Title, info.Logo = st.Title, st.Logo
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) publicInfo(w http.ResponseWriter, r *http.Request) {
|
||||
sh, st, unlocked, ok := h.shared(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var info publicInfo
|
||||
h.branding(&info)
|
||||
if !unlocked {
|
||||
info.Protected = true
|
||||
writeJSON(w, http.StatusOK, info)
|
||||
return
|
||||
}
|
||||
sub := r.URL.Query().Get("sub")
|
||||
full, err := storage.SharedPath(sh, sub)
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
e, err := st.Stat(full)
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
info.Name, info.IsDir, info.Size, info.ModTime, info.Sub, info.Expires = e.Name, e.IsDir, e.Size, e.ModTime, sub, sh.Expires
|
||||
if sub == "" {
|
||||
info.Name = baseName(sh.Path)
|
||||
}
|
||||
if e.IsDir {
|
||||
es, err := st.List(full)
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
info.Entries = make([]publicEntry, 0, len(es))
|
||||
for _, x := range es {
|
||||
info.Entries = append(info.Entries, publicEntry{Name: x.Name, IsDir: x.IsDir, Size: x.Size, ModTime: x.ModTime})
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, info)
|
||||
}
|
||||
|
||||
func baseName(p string) string {
|
||||
for i := len(p) - 1; i >= 0; i-- {
|
||||
if p[i] == '/' {
|
||||
return p[i+1:]
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// publicUnlock vérifie le mot de passe d'un lien protégé et pose le cookie de
|
||||
// déverrouillage (12 h).
|
||||
func (h *Handler) publicUnlock(w http.ResponseWriter, r *http.Request) {
|
||||
sh, st, _, ok := h.shared(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if !h.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
key := sh.ID + "|" + r.RemoteAddr
|
||||
if !h.unlocks.Allowed(key) {
|
||||
w.Header().Set("Retry-After", "900")
|
||||
writeErr(w, http.StatusTooManyRequests, "trop de tentatives : réessayer dans quelques minutes")
|
||||
return
|
||||
}
|
||||
if !sh.CheckPassword(req.Password) {
|
||||
h.unlocks.Fail(key)
|
||||
writeErr(w, http.StatusForbidden, "mot de passe incorrect")
|
||||
return
|
||||
}
|
||||
h.unlocks.Reset(key)
|
||||
v, err := st.UnlockCookie(sh)
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: unlockCookiePrefix + sh.ID, Value: v, Path: "/",
|
||||
MaxAge: int((12 * time.Hour).Seconds()), HttpOnly: true, SameSite: http.SameSiteLaxMode,
|
||||
Secure: secure(r) || h.SecureCookies,
|
||||
})
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *Handler) publicFile(w http.ResponseWriter, r *http.Request) {
|
||||
sh, st, full, _, ok := h.sharedItem(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
f, fi, err := st.Open(full)
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
inline := r.URL.Query().Get("inline") == "1"
|
||||
if !inline && r.Header.Get("Range") == "" {
|
||||
st.CountDownload(sh.ID)
|
||||
}
|
||||
serveFile(w, r, f, fi, fi.Name(), inline)
|
||||
}
|
||||
|
||||
func (h *Handler) publicZip(w http.ResponseWriter, r *http.Request) {
|
||||
sh, st, full, _, ok := h.sharedItem(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
item, err := st.SharedZipItem(full)
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
st.CountDownload(sh.ID)
|
||||
w.Header().Set("Content-Type", "application/zip")
|
||||
w.Header().Set("Content-Disposition", contentDisposition(false, item.Name+".zip"))
|
||||
if err := storage.WriteZip(w, []storage.ZipItem{item}); err != nil {
|
||||
panic(http.ErrAbortHandler)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) publicThumb(w http.ResponseWriter, r *http.Request) {
|
||||
_, st, full, _, ok := h.sharedItem(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
data, typ, mod, err := st.Thumb(full)
|
||||
if err != nil {
|
||||
fail(w, err)
|
||||
return
|
||||
}
|
||||
// Réponse protégée : pas de cache partagé.
|
||||
writeThumb(w, data, typ, mod)
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"io/fs"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"github.com/vblogio/upandown/internal/storage"
|
||||
)
|
||||
|
||||
func jsonDecode(r io.Reader, v any) error { return json.NewDecoder(r).Decode(v) }
|
||||
|
||||
// inlineTypes : types MIME affichables dans le navigateur sans risque. Tout le
|
||||
// reste est servi en téléchargement (Content-Disposition: attachment), pour
|
||||
// qu'un fichier HTML ou un script déposé ne s'exécute jamais dans l'origine de
|
||||
// l'application.
|
||||
var inlineTypes = map[string]bool{
|
||||
"image/png": true, "image/jpeg": true, "image/gif": true, "image/webp": true, "image/avif": true,
|
||||
"image/bmp": true, "image/x-icon": true, "image/vnd.microsoft.icon": true, "image/svg+xml": true,
|
||||
"video/mp4": true, "video/webm": true, "video/ogg": true, "video/quicktime": true, "video/x-m4v": true,
|
||||
"audio/mpeg": true, "audio/ogg": true, "audio/wav": true, "audio/x-wav": true, "audio/flac": true,
|
||||
"audio/aac": true, "audio/mp4": true, "audio/x-m4a": true, "audio/webm": true, "audio/opus": true,
|
||||
"application/pdf": true,
|
||||
}
|
||||
|
||||
// contentType renvoie le type MIME d'un fichier d'après son extension. Les
|
||||
// fichiers texte sont toujours servis en text/plain (jamais en HTML ou XML).
|
||||
func contentType(name string) string {
|
||||
if storage.IsText(name) {
|
||||
return "text/plain; charset=utf-8"
|
||||
}
|
||||
t := mime.TypeByExtension(strings.ToLower(path.Ext(name)))
|
||||
if t == "" {
|
||||
return "application/octet-stream"
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func baseType(t string) string {
|
||||
t, _, _ = strings.Cut(t, ";")
|
||||
return strings.TrimSpace(strings.ToLower(t))
|
||||
}
|
||||
|
||||
// contentDisposition construit l'en-tête avec un nom ASCII de repli et le nom
|
||||
// UTF-8 d'origine (RFC 6266 / 5987).
|
||||
func contentDisposition(inline bool, name string) string {
|
||||
kind := "attachment"
|
||||
if inline {
|
||||
kind = "inline"
|
||||
}
|
||||
ascii := strings.Map(func(r rune) rune {
|
||||
if r < 0x20 || r > 0x7e || r == '"' || r == '\\' || r == '%' {
|
||||
return '_'
|
||||
}
|
||||
return r
|
||||
}, name)
|
||||
return kind + `; filename="` + ascii + `"; filename*=UTF-8''` + url.PathEscape(name)
|
||||
}
|
||||
|
||||
// serveFile envoie un fichier avec prise en charge de Range, If-Modified-Since
|
||||
// et ETag. Affichage en ligne seulement si inline est demandé et que le type
|
||||
// est sûr ; sinon téléchargement.
|
||||
func serveFile(w http.ResponseWriter, r *http.Request, f *os.File, fi fs.FileInfo, name string, inline bool) {
|
||||
ct := contentType(name)
|
||||
bt := baseType(ct)
|
||||
showInline := inline && (inlineTypes[bt] || strings.HasPrefix(ct, "text/plain"))
|
||||
if !showInline {
|
||||
ct = "application/octet-stream"
|
||||
if t := mime.TypeByExtension(strings.ToLower(path.Ext(name))); t != "" && !showInline {
|
||||
ct = t
|
||||
}
|
||||
// Un téléchargement n'est jamais interprété : type générique pour les types actifs.
|
||||
if bt := baseType(ct); bt == "text/html" || bt == "application/xhtml+xml" || bt == "image/svg+xml" || bt == "text/xml" || bt == "application/xml" {
|
||||
ct = "application/octet-stream"
|
||||
}
|
||||
}
|
||||
h := w.Header()
|
||||
h.Set("Content-Type", ct)
|
||||
h.Set("Content-Disposition", contentDisposition(showInline, name))
|
||||
h.Set("ETag", storage.ETag(fi))
|
||||
h.Set("Cache-Control", "private, no-cache")
|
||||
h.Set("X-Content-Type-Options", "nosniff")
|
||||
if showInline && bt != "application/pdf" {
|
||||
// Aucun script ni sous-ressource, même en navigation directe (SVG).
|
||||
h.Set("Content-Security-Policy", "sandbox; default-src 'none'; img-src data:; media-src 'self'; style-src 'unsafe-inline'")
|
||||
}
|
||||
http.ServeContent(w, r, name, fi.ModTime(), f)
|
||||
}
|
||||
@@ -0,0 +1,677 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/pbkdf2"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Comptes utilisateurs : comptes locaux (identifiant + mot de passe) et comptes
|
||||
// créés à la première connexion OIDC, conservés dans DATA_DIR/.accounts.json
|
||||
// (0600). Les mots de passe ne sont gardés que sous forme d'empreinte
|
||||
// PBKDF2-SHA256 salée.
|
||||
|
||||
const accountsFile = ".accounts.json"
|
||||
|
||||
// Rôles et états d'un compte.
|
||||
const (
|
||||
RoleAdmin = "admin"
|
||||
RoleUser = "user"
|
||||
|
||||
StatusActive = "active"
|
||||
StatusPending = "pending" // inscription à valider par un administrateur
|
||||
StatusDisabled = "disabled" // connexion refusée
|
||||
)
|
||||
|
||||
// Fournisseurs d'identité.
|
||||
const (
|
||||
ProviderLocal = "local"
|
||||
ProviderOIDC = "oidc"
|
||||
)
|
||||
|
||||
const (
|
||||
minPasswordLen = 10
|
||||
maxPasswordLen = 200
|
||||
maxNameLen = 80
|
||||
)
|
||||
|
||||
// pbkdf2Iter : itérations PBKDF2-SHA256 (variable pour accélérer les tests).
|
||||
var pbkdf2Iter = 600_000
|
||||
|
||||
var (
|
||||
ErrInvalidAccount = errors.New("compte invalide")
|
||||
ErrAccountExists = errors.New("identifiant déjà utilisé")
|
||||
ErrNoAccount = errors.New("compte introuvable")
|
||||
ErrLastAdmin = errors.New("il doit rester au moins un administrateur actif")
|
||||
)
|
||||
|
||||
var usernameRe = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{2,31}$`)
|
||||
|
||||
// Account est un compte enregistré.
|
||||
type Account struct {
|
||||
ID string `json:"id"` // nom de l'espace personnel (storage.UserID)
|
||||
Username string `json:"username,omitempty"` // compte local : identifiant de connexion
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Provider string `json:"provider"`
|
||||
Sub string `json:"sub,omitempty"` // compte OIDC : sujet du jeton
|
||||
Role string `json:"role"`
|
||||
Status string `json:"status"`
|
||||
Hash string `json:"hash,omitempty"`
|
||||
Created time.Time `json:"created"`
|
||||
LastLogin time.Time `json:"lastLogin,omitzero"`
|
||||
}
|
||||
|
||||
// AccountInfo est la vue d'un compte renvoyée à l'interface d'administration.
|
||||
type AccountInfo struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Provider string `json:"provider"`
|
||||
Role string `json:"role"`
|
||||
Status string `json:"status"`
|
||||
Created time.Time `json:"created"`
|
||||
LastLogin time.Time `json:"lastLogin,omitzero"`
|
||||
}
|
||||
|
||||
// Info renvoie la vue publique du compte (sans empreinte).
|
||||
func (a Account) Info() AccountInfo {
|
||||
return AccountInfo{ID: a.ID, Username: a.Username, Name: a.Name, Email: a.Email, Provider: a.Provider,
|
||||
Role: a.Role, Status: a.Status, Created: a.Created, LastLogin: a.LastLogin}
|
||||
}
|
||||
|
||||
// User renvoie l'utilisateur de session correspondant au compte.
|
||||
func (a Account) User() User {
|
||||
return User{ID: a.ID, Sub: a.Sub, Name: a.Name, Email: a.Email, Provider: a.Provider, Role: a.Role}
|
||||
}
|
||||
|
||||
// Accounts conserve les comptes dans dir/.accounts.json.
|
||||
type Accounts struct {
|
||||
mu sync.Mutex
|
||||
file string
|
||||
byID map[string]*Account
|
||||
dummy string // empreinte factice : égalise le temps de réponse d'un identifiant inconnu
|
||||
}
|
||||
|
||||
// OpenAccounts charge (ou crée) le fichier des comptes de dir.
|
||||
func OpenAccounts(dir string) (*Accounts, error) {
|
||||
a := &Accounts{file: filepath.Join(dir, accountsFile), byID: map[string]*Account{}}
|
||||
b, err := os.ReadFile(a.file)
|
||||
switch {
|
||||
case errors.Is(err, os.ErrNotExist):
|
||||
case err != nil:
|
||||
return nil, err
|
||||
default:
|
||||
var d struct {
|
||||
Accounts []*Account `json:"accounts"`
|
||||
}
|
||||
if err := json.Unmarshal(b, &d); err != nil {
|
||||
return nil, errors.New(a.file + " invalide : " + err.Error())
|
||||
}
|
||||
for _, acc := range d.Accounts {
|
||||
a.byID[acc.ID] = acc
|
||||
}
|
||||
}
|
||||
a.dummy = hashPassword("mot de passe factice")
|
||||
return a, nil
|
||||
}
|
||||
|
||||
// save écrit le fichier ; appelé sous mu.
|
||||
func (a *Accounts) save() error {
|
||||
list := make([]*Account, 0, len(a.byID))
|
||||
for _, acc := range a.byID {
|
||||
list = append(list, acc)
|
||||
}
|
||||
sort.Slice(list, func(i, j int) bool { return list[i].Created.Before(list[j].Created) })
|
||||
b, err := json.MarshalIndent(map[string]any{"accounts": list}, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp, err := os.CreateTemp(filepath.Dir(a.file), ".tmp-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(tmp.Name())
|
||||
if err := tmp.Chmod(0o600); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if _, err := tmp.Write(b); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Sync(); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp.Name(), a.file)
|
||||
}
|
||||
|
||||
// --- Mots de passe ------------------------------------------------------------------
|
||||
|
||||
func hashPassword(pw string) string {
|
||||
salt := make([]byte, 16)
|
||||
_, _ = rand.Read(salt)
|
||||
return deriveHash(pw, salt, pbkdf2Iter)
|
||||
}
|
||||
|
||||
func deriveHash(pw string, salt []byte, iter int) string {
|
||||
h, err := pbkdf2.Key(sha256.New, pw, salt, iter, 32)
|
||||
if err != nil {
|
||||
panic(err) // paramètres constants valides
|
||||
}
|
||||
return fmt.Sprintf("pbkdf2-sha256$%d$%s$%s", iter, b64.EncodeToString(salt), b64.EncodeToString(h))
|
||||
}
|
||||
|
||||
func checkPassword(hash, pw string) bool {
|
||||
parts := strings.Split(hash, "$")
|
||||
if len(parts) != 4 || parts[0] != "pbkdf2-sha256" {
|
||||
return false
|
||||
}
|
||||
iter, err := strconv.Atoi(parts[1])
|
||||
if err != nil || iter < 1 || iter > 10_000_000 {
|
||||
return false
|
||||
}
|
||||
salt, err := b64.DecodeString(parts[2])
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return subtle.ConstantTimeCompare([]byte(deriveHash(pw, salt, iter)), []byte(hash)) == 1
|
||||
}
|
||||
|
||||
// ValidatePassword vérifie la longueur d'un nouveau mot de passe.
|
||||
func ValidatePassword(pw string) error {
|
||||
if n := utf8.RuneCountInString(pw); n < minPasswordLen || len(pw) > maxPasswordLen {
|
||||
return fmt.Errorf("%w : mot de passe de %d à %d caractères", ErrInvalidAccount, minPasswordLen, maxPasswordLen)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- Lecture ---------------------------------------------------------------------------
|
||||
|
||||
// Get renvoie le compte d'identifiant id.
|
||||
func (a *Accounts) Get(id string) (Account, bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if acc, ok := a.byID[id]; ok {
|
||||
return *acc, true
|
||||
}
|
||||
return Account{}, false
|
||||
}
|
||||
|
||||
// List renvoie tous les comptes, du plus ancien au plus récent.
|
||||
func (a *Accounts) List() []AccountInfo {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
out := make([]AccountInfo, 0, len(a.byID))
|
||||
for _, acc := range a.byID {
|
||||
out = append(out, acc.Info())
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
if !out[i].Created.Equal(out[j].Created) {
|
||||
return out[i].Created.Before(out[j].Created)
|
||||
}
|
||||
return out[i].ID < out[j].ID
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// Count renvoie le nombre de comptes.
|
||||
func (a *Accounts) Count() int {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return len(a.byID)
|
||||
}
|
||||
|
||||
// hasAdmin indique si un administrateur actif existe ; appelé sous mu.
|
||||
func (a *Accounts) hasAdmin() bool {
|
||||
for _, acc := range a.byID {
|
||||
if acc.Role == RoleAdmin && acc.Status == StatusActive {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// NeedsSetup indique qu'aucun administrateur n'existe encore : le premier
|
||||
// compte créé le deviendra.
|
||||
func (a *Accounts) NeedsSetup() bool {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return !a.hasAdmin()
|
||||
}
|
||||
|
||||
// PendingCount renvoie le nombre d'inscriptions en attente de validation.
|
||||
func (a *Accounts) PendingCount() int {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
n := 0
|
||||
for _, acc := range a.byID {
|
||||
if acc.Status == StatusPending {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (a *Accounts) byUsername(name string) *Account {
|
||||
for _, acc := range a.byID {
|
||||
if acc.Provider == ProviderLocal && acc.Username == name {
|
||||
return acc
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- Création ---------------------------------------------------------------------------
|
||||
|
||||
// NewAccount décrit un compte local à créer.
|
||||
type NewAccount struct {
|
||||
Username string
|
||||
Name string
|
||||
Email string
|
||||
Password string
|
||||
Role string // vide : user (admin si aucun administrateur n'existe)
|
||||
Status string // vide : active
|
||||
}
|
||||
|
||||
func cleanText(s string, max int) (string, bool) {
|
||||
s = strings.Join(strings.Fields(s), " ")
|
||||
return s, utf8.ValidString(s) && utf8.RuneCountInString(s) <= max && !strings.ContainsAny(s, "\x00")
|
||||
}
|
||||
|
||||
// CreateLocal crée un compte local. Tant qu'aucun administrateur n'existe, le
|
||||
// compte créé l'est (et est actif).
|
||||
func (a *Accounts) CreateLocal(n NewAccount) (Account, error) {
|
||||
username := strings.ToLower(strings.TrimSpace(n.Username))
|
||||
if !usernameRe.MatchString(username) || strings.HasPrefix(username, "oidc.") {
|
||||
return Account{}, fmt.Errorf("%w : identifiant de 3 à 32 caractères (a-z, 0-9, point, tiret, tiret bas)", ErrInvalidAccount)
|
||||
}
|
||||
if err := ValidatePassword(n.Password); err != nil {
|
||||
return Account{}, err
|
||||
}
|
||||
name, ok := cleanText(n.Name, maxNameLen)
|
||||
if !ok {
|
||||
return Account{}, fmt.Errorf("%w : nom", ErrInvalidAccount)
|
||||
}
|
||||
if name == "" {
|
||||
name = username
|
||||
}
|
||||
email, ok := cleanText(n.Email, 120)
|
||||
if !ok || (email != "" && (!strings.Contains(email, "@") || strings.ContainsAny(email, " <>\"'"))) {
|
||||
return Account{}, fmt.Errorf("%w : adresse e-mail", ErrInvalidAccount)
|
||||
}
|
||||
hash := hashPassword(n.Password) // hors verrou : calcul lent
|
||||
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if _, exists := a.byID[username]; exists {
|
||||
return Account{}, ErrAccountExists
|
||||
}
|
||||
acc := &Account{ID: username, Username: username, Name: name, Email: email, Provider: ProviderLocal,
|
||||
Role: n.Role, Status: n.Status, Hash: hash, Created: time.Now().UTC().Truncate(time.Second)}
|
||||
if !a.hasAdmin() {
|
||||
acc.Role, acc.Status = RoleAdmin, StatusActive
|
||||
}
|
||||
if acc.Role != RoleAdmin {
|
||||
acc.Role = RoleUser
|
||||
}
|
||||
if acc.Status != StatusPending && acc.Status != StatusDisabled {
|
||||
acc.Status = StatusActive
|
||||
}
|
||||
a.byID[acc.ID] = acc
|
||||
if err := a.save(); err != nil {
|
||||
delete(a.byID, acc.ID)
|
||||
return Account{}, err
|
||||
}
|
||||
return *acc, nil
|
||||
}
|
||||
|
||||
// EnsureAdmin crée l'administrateur local initial (ADMIN_USER / ADMIN_PASSWORD)
|
||||
// s'il n'existe pas ; un compte existant n'est pas modifié.
|
||||
func (a *Accounts) EnsureAdmin(username, password string) error {
|
||||
_, err := a.CreateLocal(NewAccount{Username: username, Name: username, Password: password, Role: RoleAdmin})
|
||||
if errors.Is(err, ErrAccountExists) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// --- Connexion ----------------------------------------------------------------------------
|
||||
|
||||
// Authenticate vérifie un identifiant et un mot de passe locaux.
|
||||
func (a *Accounts) Authenticate(username, password string) (Account, error) {
|
||||
username = strings.ToLower(strings.TrimSpace(username))
|
||||
a.mu.Lock()
|
||||
acc := a.byUsername(username)
|
||||
var hash string
|
||||
if acc != nil {
|
||||
hash = acc.Hash
|
||||
} else {
|
||||
hash = a.dummy
|
||||
}
|
||||
a.mu.Unlock()
|
||||
ok := checkPassword(hash, password) && acc != nil
|
||||
if !ok {
|
||||
return Account{}, ErrBadCredentials
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
acc = a.byID[acc.ID]
|
||||
if acc == nil {
|
||||
return Account{}, ErrBadCredentials
|
||||
}
|
||||
switch acc.Status {
|
||||
case StatusPending:
|
||||
return *acc, ErrPending
|
||||
case StatusDisabled:
|
||||
return *acc, ErrDisabled
|
||||
}
|
||||
acc.LastLogin = time.Now().UTC().Truncate(time.Second)
|
||||
_ = a.save()
|
||||
return *acc, nil
|
||||
}
|
||||
|
||||
// oidcID construit l'identifiant d'un compte OIDC : l'e-mail s'il existe (il
|
||||
// contient « @ », donc ne peut pas entrer en conflit avec un identifiant local),
|
||||
// sinon « oidc. » suivi du sujet.
|
||||
func oidcID(email, sub string) string {
|
||||
if e := strings.ToLower(strings.TrimSpace(email)); e != "" {
|
||||
return sanitizeID(e)
|
||||
}
|
||||
return "oidc." + sanitizeID(sub)
|
||||
}
|
||||
|
||||
func sanitizeID(raw string) string {
|
||||
var b strings.Builder
|
||||
for _, r := range strings.ToLower(raw) {
|
||||
if r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || strings.ContainsRune("._@+-", r) {
|
||||
b.WriteRune(r)
|
||||
} else {
|
||||
b.WriteByte('_')
|
||||
}
|
||||
}
|
||||
id := strings.TrimLeft(b.String(), ".")
|
||||
if len(id) > 80 {
|
||||
h := sha256.Sum256([]byte(raw))
|
||||
id = id[:60] + "-" + b64.EncodeToString(h[:6])
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// OIDCPolicy règle la création et la mise à jour des comptes OIDC.
|
||||
type OIDCPolicy struct {
|
||||
AdminGroups []string // groupes dont les membres sont administrateurs
|
||||
AdminEmails []string // adresses dont les titulaires sont administrateurs
|
||||
}
|
||||
|
||||
func (p OIDCPolicy) configured() bool { return len(p.AdminGroups) > 0 || len(p.AdminEmails) > 0 }
|
||||
|
||||
func (p OIDCPolicy) isAdmin(email string, groups []string) bool {
|
||||
for _, e := range p.AdminEmails {
|
||||
if email != "" && strings.EqualFold(strings.TrimSpace(e), email) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for _, g := range groups {
|
||||
for _, ag := range p.AdminGroups {
|
||||
if g == strings.TrimPrefix(ag, "/") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// UpsertOIDC crée ou met à jour le compte d'une connexion OIDC et renvoie
|
||||
// l'utilisateur de la session. Le compte est créé actif ; il devient
|
||||
// administrateur s'il appartient à OIDC_ADMIN_GROUPS / OIDC_ADMIN_EMAILS, ou
|
||||
// s'il est le premier compte alors qu'aucun administrateur n'existe. Un compte
|
||||
// désactivé ou en attente est refusé (ErrDisabled, ErrPending).
|
||||
func (a *Accounts) UpsertOIDC(u User, groups []string, pol OIDCPolicy) (User, error) {
|
||||
if u.Sub == "" {
|
||||
return User{}, fmt.Errorf("%w : sujet OIDC absent", ErrInvalidAccount)
|
||||
}
|
||||
name, ok := cleanText(u.Name, maxNameLen)
|
||||
if !ok || name == "" {
|
||||
name = u.Sub
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
var acc *Account
|
||||
for _, c := range a.byID {
|
||||
if c.Provider == ProviderOIDC && c.Sub == u.Sub {
|
||||
acc = c
|
||||
break
|
||||
}
|
||||
}
|
||||
wantAdmin := pol.isAdmin(u.Email, groups)
|
||||
if acc == nil {
|
||||
id := oidcID(u.Email, u.Sub)
|
||||
if _, taken := a.byID[id]; taken { // même e-mail, autre sujet : identifiant distinct
|
||||
id = "oidc." + sanitizeID(u.Sub)
|
||||
}
|
||||
acc = &Account{ID: id, Name: name, Email: u.Email, Provider: ProviderOIDC, Sub: u.Sub,
|
||||
Role: RoleUser, Status: StatusActive, Created: time.Now().UTC().Truncate(time.Second)}
|
||||
if wantAdmin || !a.hasAdmin() {
|
||||
acc.Role = RoleAdmin
|
||||
}
|
||||
a.byID[acc.ID] = acc
|
||||
} else {
|
||||
acc.Name, acc.Email = name, u.Email
|
||||
if pol.configured() {
|
||||
switch {
|
||||
case wantAdmin:
|
||||
acc.Role = RoleAdmin
|
||||
case acc.Role == RoleAdmin && a.otherAdmin(acc.ID):
|
||||
acc.Role = RoleUser
|
||||
}
|
||||
}
|
||||
}
|
||||
switch acc.Status {
|
||||
case StatusPending:
|
||||
return acc.User(), ErrPending
|
||||
case StatusDisabled:
|
||||
return acc.User(), ErrDisabled
|
||||
}
|
||||
acc.LastLogin = time.Now().UTC().Truncate(time.Second)
|
||||
if err := a.save(); err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
return acc.User(), nil
|
||||
}
|
||||
|
||||
// otherAdmin indique si un administrateur actif autre que id existe ; appelé sous mu.
|
||||
func (a *Accounts) otherAdmin(id string) bool {
|
||||
for _, acc := range a.byID {
|
||||
if acc.ID != id && acc.Role == RoleAdmin && acc.Status == StatusActive {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// --- Modification (administration) -------------------------------------------------------
|
||||
|
||||
// Patch décrit les modifications d'un compte (champs nil : inchangés).
|
||||
type Patch struct {
|
||||
Name *string
|
||||
Email *string
|
||||
Role *string
|
||||
Status *string
|
||||
Password *string // comptes locaux seulement
|
||||
}
|
||||
|
||||
// Update modifie un compte. Le dernier administrateur actif ne peut être ni
|
||||
// rétrogradé ni désactivé.
|
||||
func (a *Accounts) Update(id string, p Patch) (Account, error) {
|
||||
var hash string
|
||||
if p.Password != nil {
|
||||
if err := ValidatePassword(*p.Password); err != nil {
|
||||
return Account{}, err
|
||||
}
|
||||
hash = hashPassword(*p.Password)
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
acc := a.byID[id]
|
||||
if acc == nil {
|
||||
return Account{}, ErrNoAccount
|
||||
}
|
||||
next := *acc
|
||||
if p.Name != nil {
|
||||
n, ok := cleanText(*p.Name, maxNameLen)
|
||||
if !ok || n == "" {
|
||||
return Account{}, fmt.Errorf("%w : nom", ErrInvalidAccount)
|
||||
}
|
||||
next.Name = n
|
||||
}
|
||||
if p.Email != nil && next.Provider == ProviderLocal {
|
||||
e, ok := cleanText(*p.Email, 120)
|
||||
if !ok || (e != "" && (!strings.Contains(e, "@") || strings.ContainsAny(e, " <>\"'"))) {
|
||||
return Account{}, fmt.Errorf("%w : adresse e-mail", ErrInvalidAccount)
|
||||
}
|
||||
next.Email = e
|
||||
}
|
||||
if p.Role != nil {
|
||||
if *p.Role != RoleAdmin && *p.Role != RoleUser {
|
||||
return Account{}, fmt.Errorf("%w : rôle", ErrInvalidAccount)
|
||||
}
|
||||
next.Role = *p.Role
|
||||
}
|
||||
if p.Status != nil {
|
||||
if *p.Status != StatusActive && *p.Status != StatusPending && *p.Status != StatusDisabled {
|
||||
return Account{}, fmt.Errorf("%w : état", ErrInvalidAccount)
|
||||
}
|
||||
next.Status = *p.Status
|
||||
}
|
||||
if p.Password != nil {
|
||||
if next.Provider != ProviderLocal {
|
||||
return Account{}, fmt.Errorf("%w : mot de passe géré par le fournisseur d'identité", ErrInvalidAccount)
|
||||
}
|
||||
next.Hash = hash
|
||||
}
|
||||
wasAdmin := acc.Role == RoleAdmin && acc.Status == StatusActive
|
||||
isAdmin := next.Role == RoleAdmin && next.Status == StatusActive
|
||||
if wasAdmin && !isAdmin && !a.otherAdmin(id) {
|
||||
return Account{}, ErrLastAdmin
|
||||
}
|
||||
*acc = next
|
||||
if err := a.save(); err != nil {
|
||||
return Account{}, err
|
||||
}
|
||||
return *acc, nil
|
||||
}
|
||||
|
||||
// ChangePassword remplace le mot de passe d'un compte local après vérification
|
||||
// de l'ancien.
|
||||
func (a *Accounts) ChangePassword(id, current, next string) error {
|
||||
if err := ValidatePassword(next); err != nil {
|
||||
return err
|
||||
}
|
||||
acc, ok := a.Get(id)
|
||||
if !ok || acc.Provider != ProviderLocal {
|
||||
return ErrNoAccount
|
||||
}
|
||||
if !checkPassword(acc.Hash, current) {
|
||||
return ErrBadCredentials
|
||||
}
|
||||
_, err := a.Update(id, Patch{Password: &next})
|
||||
return err
|
||||
}
|
||||
|
||||
// Delete supprime un compte. Le dernier administrateur actif ne peut l'être.
|
||||
func (a *Accounts) Delete(id string) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
acc := a.byID[id]
|
||||
if acc == nil {
|
||||
return ErrNoAccount
|
||||
}
|
||||
if acc.Role == RoleAdmin && acc.Status == StatusActive && !a.otherAdmin(id) {
|
||||
return ErrLastAdmin
|
||||
}
|
||||
delete(a.byID, id)
|
||||
if err := a.save(); err != nil {
|
||||
a.byID[id] = acc
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- Limitation des tentatives ------------------------------------------------------------
|
||||
|
||||
// Limiter limite les échecs de connexion : max échecs par clé et par fenêtre.
|
||||
type Limiter struct {
|
||||
mu sync.Mutex
|
||||
max int
|
||||
window time.Duration
|
||||
fails map[string][]time.Time
|
||||
}
|
||||
|
||||
// NewLimiter crée un limiteur.
|
||||
func NewLimiter(max int, window time.Duration) *Limiter {
|
||||
return &Limiter{max: max, window: window, fails: map[string][]time.Time{}}
|
||||
}
|
||||
|
||||
func (l *Limiter) prune(key string, now time.Time) []time.Time {
|
||||
kept := l.fails[key][:0]
|
||||
for _, t := range l.fails[key] {
|
||||
if now.Sub(t) < l.window {
|
||||
kept = append(kept, t)
|
||||
}
|
||||
}
|
||||
if len(kept) == 0 {
|
||||
delete(l.fails, key)
|
||||
} else {
|
||||
l.fails[key] = kept
|
||||
}
|
||||
return kept
|
||||
}
|
||||
|
||||
// Allowed indique si key peut encore tenter une connexion.
|
||||
func (l *Limiter) Allowed(key string) bool {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return len(l.prune(key, time.Now())) < l.max
|
||||
}
|
||||
|
||||
// Fail enregistre un échec.
|
||||
func (l *Limiter) Fail(key string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
now := time.Now()
|
||||
l.prune(key, now)
|
||||
l.fails[key] = append(l.fails[key], now)
|
||||
if len(l.fails) > 10000 { // borne la mémoire
|
||||
for k := range l.fails {
|
||||
if len(l.prune(k, now)) == 0 {
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Reset efface les échecs de key (connexion réussie).
|
||||
func (l *Limiter) Reset(key string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
delete(l.fails, key)
|
||||
}
|
||||
@@ -0,0 +1,473 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func init() { pbkdf2Iter = 1000 } // tests rapides
|
||||
|
||||
func newAccounts(t *testing.T) *Accounts {
|
||||
t.Helper()
|
||||
a, err := OpenAccounts(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
func TestFirstAccountIsAdmin(t *testing.T) {
|
||||
a := newAccounts(t)
|
||||
if !a.NeedsSetup() {
|
||||
t.Fatal("NeedsSetup")
|
||||
}
|
||||
first, err := a.CreateLocal(NewAccount{Username: "Alice", Password: "un-mot-de-passe", Status: StatusPending})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first.Role != RoleAdmin || first.Status != StatusActive || first.ID != "alice" {
|
||||
t.Errorf("premier compte = %+v", first)
|
||||
}
|
||||
second, _ := a.CreateLocal(NewAccount{Username: "bob", Password: "un-mot-de-passe", Status: StatusPending})
|
||||
if second.Role != RoleUser || second.Status != StatusPending {
|
||||
t.Errorf("second compte = %+v", second)
|
||||
}
|
||||
if a.NeedsSetup() || a.PendingCount() != 1 {
|
||||
t.Error("état après création")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateLocalValidation(t *testing.T) {
|
||||
a := newAccounts(t)
|
||||
for _, n := range []NewAccount{
|
||||
{Username: "ab", Password: "un-mot-de-passe"}, // trop court
|
||||
{Username: "Bob Dupont", Password: "un-mot-de-passe"}, // espace
|
||||
{Username: "oidc.x", Password: "un-mot-de-passe"}, // préfixe réservé
|
||||
{Username: "bob@example.org", Password: "un-mot-de-passe"}, // @ réservé aux comptes OIDC
|
||||
{Username: "bob", Password: "court"}, // mot de passe trop court
|
||||
{Username: "bob", Password: "un-mot-de-passe", Email: "x"}, // e-mail invalide
|
||||
{Username: "bob", Password: strings.Repeat("x", 300)}, // mot de passe trop long
|
||||
{Username: ".hidden", Password: "un-mot-de-passe"}, // caché
|
||||
{Username: "bob", Password: "un-mot-de-passe", Name: "a\x00"}, // nom invalide
|
||||
} {
|
||||
if _, err := a.CreateLocal(n); !errors.Is(err, ErrInvalidAccount) {
|
||||
t.Errorf("CreateLocal(%+v) = %v", n, err)
|
||||
}
|
||||
}
|
||||
if _, err := a.CreateLocal(NewAccount{Username: "bob", Password: "un-mot-de-passe"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := a.CreateLocal(NewAccount{Username: "BOB", Password: "un-mot-de-passe"}); !errors.Is(err, ErrAccountExists) {
|
||||
t.Errorf("doublon : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticate(t *testing.T) {
|
||||
a := newAccounts(t)
|
||||
_, _ = a.CreateLocal(NewAccount{Username: "alice", Password: "mot-de-passe-1"})
|
||||
_, _ = a.CreateLocal(NewAccount{Username: "bob", Password: "mot-de-passe-2", Status: StatusPending})
|
||||
if _, err := a.Authenticate("Alice", "mot-de-passe-1"); err != nil {
|
||||
t.Errorf("connexion : %v", err)
|
||||
}
|
||||
if _, err := a.Authenticate("alice", "faux"); !errors.Is(err, ErrBadCredentials) {
|
||||
t.Errorf("mauvais mot de passe : %v", err)
|
||||
}
|
||||
if _, err := a.Authenticate("inconnu", "mot-de-passe-1"); !errors.Is(err, ErrBadCredentials) {
|
||||
t.Errorf("inconnu : %v", err)
|
||||
}
|
||||
if _, err := a.Authenticate("bob", "mot-de-passe-2"); !errors.Is(err, ErrPending) {
|
||||
t.Errorf("en attente : %v", err)
|
||||
}
|
||||
// Mauvais mot de passe d'un compte en attente : pas de fuite d'état.
|
||||
if _, err := a.Authenticate("bob", "faux"); !errors.Is(err, ErrBadCredentials) {
|
||||
t.Errorf("fuite d'état : %v", err)
|
||||
}
|
||||
disabled := StatusDisabled
|
||||
_, _ = a.Update("bob", Patch{Status: &disabled})
|
||||
if _, err := a.Authenticate("bob", "mot-de-passe-2"); !errors.Is(err, ErrDisabled) {
|
||||
t.Errorf("désactivé : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPersistenceAndFileMode(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
a, _ := OpenAccounts(dir)
|
||||
_, _ = a.CreateLocal(NewAccount{Username: "alice", Password: "mot-de-passe-1"})
|
||||
b, err := OpenAccounts(dir)
|
||||
if err != nil || b.Count() != 1 {
|
||||
t.Fatalf("rechargement : %v %d", err, b.Count())
|
||||
}
|
||||
if _, err := b.Authenticate("alice", "mot-de-passe-1"); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLastAdminProtected(t *testing.T) {
|
||||
a := newAccounts(t)
|
||||
_, _ = a.CreateLocal(NewAccount{Username: "alice", Password: "mot-de-passe-1"}) // admin
|
||||
user, disabled := RoleUser, StatusDisabled
|
||||
if _, err := a.Update("alice", Patch{Role: &user}); !errors.Is(err, ErrLastAdmin) {
|
||||
t.Errorf("rétrogradation : %v", err)
|
||||
}
|
||||
if _, err := a.Update("alice", Patch{Status: &disabled}); !errors.Is(err, ErrLastAdmin) {
|
||||
t.Errorf("désactivation : %v", err)
|
||||
}
|
||||
if err := a.Delete("alice"); !errors.Is(err, ErrLastAdmin) {
|
||||
t.Errorf("suppression : %v", err)
|
||||
}
|
||||
admin := RoleAdmin
|
||||
_, _ = a.CreateLocal(NewAccount{Username: "bob", Password: "mot-de-passe-2"})
|
||||
_, _ = a.Update("bob", Patch{Role: &admin})
|
||||
if _, err := a.Update("alice", Patch{Role: &user}); err != nil {
|
||||
t.Errorf("rétrogradation avec un autre admin : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangePassword(t *testing.T) {
|
||||
a := newAccounts(t)
|
||||
_, _ = a.CreateLocal(NewAccount{Username: "alice", Password: "ancien-mot-de-passe"})
|
||||
if err := a.ChangePassword("alice", "faux", "nouveau-mot-de-passe"); !errors.Is(err, ErrBadCredentials) {
|
||||
t.Errorf("ancien faux : %v", err)
|
||||
}
|
||||
if err := a.ChangePassword("alice", "ancien-mot-de-passe", "court"); !errors.Is(err, ErrInvalidAccount) {
|
||||
t.Errorf("nouveau trop court : %v", err)
|
||||
}
|
||||
if err := a.ChangePassword("alice", "ancien-mot-de-passe", "nouveau-mot-de-passe"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := a.Authenticate("alice", "nouveau-mot-de-passe"); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if _, err := a.Authenticate("alice", "ancien-mot-de-passe"); err == nil {
|
||||
t.Error("ancien mot de passe encore valable")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpsertOIDC(t *testing.T) {
|
||||
a := newAccounts(t)
|
||||
pol := OIDCPolicy{AdminGroups: []string{"admins"}}
|
||||
u1, err := a.UpsertOIDC(User{Sub: "s1", Name: "Zoé", Email: "Zoe@Example.org"}, []string{"users"}, pol)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Premier compte : administrateur même hors du groupe (aucun admin n'existait).
|
||||
if u1.ID != "zoe@example.org" || u1.Role != RoleAdmin || u1.Provider != ProviderOIDC {
|
||||
t.Errorf("premier = %+v", u1)
|
||||
}
|
||||
u2, _ := a.UpsertOIDC(User{Sub: "s2", Name: "Max", Email: "max@example.org"}, []string{"users"}, pol)
|
||||
if u2.Role != RoleUser {
|
||||
t.Errorf("second = %+v", u2)
|
||||
}
|
||||
// Promotion par groupe, puis rétrogradation quand il en sort.
|
||||
u2, _ = a.UpsertOIDC(User{Sub: "s2", Name: "Max", Email: "max@example.org"}, []string{"admins"}, pol)
|
||||
if u2.Role != RoleAdmin {
|
||||
t.Errorf("promotion = %+v", u2)
|
||||
}
|
||||
u2, _ = a.UpsertOIDC(User{Sub: "s2", Name: "Max", Email: "max@example.org"}, nil, pol)
|
||||
if u2.Role != RoleUser {
|
||||
t.Errorf("rétrogradation = %+v", u2)
|
||||
}
|
||||
// Même sujet, nouvel e-mail : même compte.
|
||||
u3, _ := a.UpsertOIDC(User{Sub: "s2", Name: "Max B", Email: "max@autre.org"}, nil, pol)
|
||||
if u3.ID != u2.ID || u3.Name != "Max B" {
|
||||
t.Errorf("identité : %+v", u3)
|
||||
}
|
||||
// Sans e-mail : identifiant « oidc.<sub> », qui ne peut pas être un identifiant local.
|
||||
u4, _ := a.UpsertOIDC(User{Sub: "S/4", Name: "Sans mail"}, nil, pol)
|
||||
if !strings.HasPrefix(u4.ID, "oidc.") {
|
||||
t.Errorf("sans e-mail = %+v", u4)
|
||||
}
|
||||
if _, err := a.CreateLocal(NewAccount{Username: u4.ID, Password: "mot-de-passe-1"}); err == nil {
|
||||
t.Error("identifiant local en collision avec un compte OIDC")
|
||||
}
|
||||
// Même e-mail, autre sujet : pas de fusion (prise de contrôle).
|
||||
u5, _ := a.UpsertOIDC(User{Sub: "autre", Name: "Usurpateur", Email: "zoe@example.org"}, nil, pol)
|
||||
if u5.ID == u1.ID {
|
||||
t.Error("deux sujets OIDC partagent un compte")
|
||||
}
|
||||
// Désactivation.
|
||||
disabled := StatusDisabled
|
||||
_, _ = a.Update(u2.ID, Patch{Status: &disabled})
|
||||
if _, err := a.UpsertOIDC(User{Sub: "s2", Name: "Max", Email: "max@autre.org"}, nil, pol); !errors.Is(err, ErrDisabled) {
|
||||
t.Errorf("désactivé : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLimiter(t *testing.T) {
|
||||
l := NewLimiter(3, 50*time.Millisecond)
|
||||
for i := 0; i < 3; i++ {
|
||||
if !l.Allowed("k") {
|
||||
t.Fatal("bloqué trop tôt")
|
||||
}
|
||||
l.Fail("k")
|
||||
}
|
||||
if l.Allowed("k") {
|
||||
t.Error("pas bloqué")
|
||||
}
|
||||
if !l.Allowed("autre") {
|
||||
t.Error("autre clé bloquée")
|
||||
}
|
||||
time.Sleep(60 * time.Millisecond)
|
||||
if !l.Allowed("k") {
|
||||
t.Error("fenêtre non expirée")
|
||||
}
|
||||
l.Fail("k")
|
||||
l.Reset("k")
|
||||
if !l.Allowed("k") {
|
||||
t.Error("Reset")
|
||||
}
|
||||
}
|
||||
|
||||
// --- Flux HTTP (sans ouvrir de port) -------------------------------------------------
|
||||
|
||||
type browser struct {
|
||||
t *testing.T
|
||||
h http.Handler
|
||||
cookies map[string]*http.Cookie
|
||||
}
|
||||
|
||||
func newBrowser(t *testing.T, h http.Handler) *browser {
|
||||
return &browser{t: t, h: h, cookies: map[string]*http.Cookie{}}
|
||||
}
|
||||
|
||||
func (b *browser) do(method, path, body string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
if body != "" {
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
for _, c := range b.cookies {
|
||||
r.AddCookie(c)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
b.h.ServeHTTP(w, r)
|
||||
for _, c := range w.Result().Cookies() {
|
||||
if c.MaxAge < 0 {
|
||||
delete(b.cookies, c.Name)
|
||||
} else {
|
||||
b.cookies[c.Name] = c
|
||||
}
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
func testAuth(t *testing.T, reg string) (*Auth, http.Handler) {
|
||||
t.Helper()
|
||||
acc := newAccounts(t)
|
||||
a := New(&Auth{
|
||||
Accounts: acc,
|
||||
Sessions: NewSessions([]byte("0123456789abcdef0123456789abcdef"), time.Hour, false),
|
||||
Local: true,
|
||||
Registration: func() string { return reg },
|
||||
})
|
||||
mux := http.NewServeMux()
|
||||
a.Register(mux)
|
||||
mux.HandleFunc("GET /api/whoami", func(w http.ResponseWriter, r *http.Request) {
|
||||
u := UserFrom(r.Context())
|
||||
_, _ = w.Write([]byte(u.ID + ":" + u.Role))
|
||||
})
|
||||
mux.HandleFunc("GET /api/open", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("ouvert")) })
|
||||
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("<html>spa</html>")) })
|
||||
return a, a.Middleware(mux, func(p string) bool { return p == "/api/open" })
|
||||
}
|
||||
|
||||
func TestRegistrationClosedAllowsOnlySetup(t *testing.T) {
|
||||
_, h := testAuth(t, "closed")
|
||||
b := newBrowser(t, h)
|
||||
// Premier compte : accepté malgré « closed » (installation), connecté d'office.
|
||||
w := b.do("POST", "/auth/local/register", `{"username":"admin","password":"mot-de-passe-1"}`)
|
||||
if w.Code != 201 {
|
||||
t.Fatalf("installation : %d %s", w.Code, w.Body)
|
||||
}
|
||||
if got := b.do("GET", "/api/whoami", "").Body.String(); got != "admin:admin" {
|
||||
t.Errorf("whoami = %q", got)
|
||||
}
|
||||
// Ensuite, fermé.
|
||||
b2 := newBrowser(t, h)
|
||||
if w := b2.do("POST", "/auth/local/register", `{"username":"bob","password":"mot-de-passe-1"}`); w.Code != 403 {
|
||||
t.Errorf("inscription fermée : %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationApprovalFlow(t *testing.T) {
|
||||
a, h := testAuth(t, "approval")
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "root", Password: "mot-de-passe-0"})
|
||||
b := newBrowser(t, h)
|
||||
w := b.do("POST", "/auth/local/register", `{"username":"bob","name":"Bob","password":"mot-de-passe-1"}`)
|
||||
if w.Code != 202 || len(b.cookies) != 0 {
|
||||
t.Fatalf("inscription : %d %s %v", w.Code, w.Body, b.cookies)
|
||||
}
|
||||
w = b.do("POST", "/auth/local/login", `{"username":"bob","password":"mot-de-passe-1"}`)
|
||||
if w.Code != 403 || !strings.Contains(w.Body.String(), `"pending"`) {
|
||||
t.Errorf("connexion en attente : %d %s", w.Code, w.Body)
|
||||
}
|
||||
if b.do("GET", "/api/whoami", "").Code != 401 {
|
||||
t.Error("accès sans session")
|
||||
}
|
||||
active := StatusActive
|
||||
_, _ = a.Accounts.Update("bob", Patch{Status: &active})
|
||||
if w = b.do("POST", "/auth/local/login", `{"username":"bob","password":"mot-de-passe-1"}`); w.Code != 200 {
|
||||
t.Fatalf("connexion : %d %s", w.Code, w.Body)
|
||||
}
|
||||
if got := b.do("GET", "/api/whoami", "").Body.String(); got != "bob:user" {
|
||||
t.Errorf("whoami = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationOpenAutoLogin(t *testing.T) {
|
||||
a, h := testAuth(t, "open")
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "root", Password: "mot-de-passe-0"})
|
||||
b := newBrowser(t, h)
|
||||
if w := b.do("POST", "/auth/local/register", `{"username":"carl","password":"mot-de-passe-1"}`); w.Code != 201 {
|
||||
t.Fatalf("%d %s", w.Code, w.Body)
|
||||
}
|
||||
if got := b.do("GET", "/api/whoami", "").Body.String(); got != "carl:user" {
|
||||
t.Errorf("whoami = %q", got)
|
||||
}
|
||||
if w := b.do("POST", "/auth/local/register", `{"username":"carl","password":"mot-de-passe-1"}`); w.Code != 409 {
|
||||
t.Errorf("doublon : %d", w.Code)
|
||||
}
|
||||
if w := b.do("POST", "/auth/local/register", `{"username":"x","password":"mot-de-passe-1"}`); w.Code != 400 {
|
||||
t.Errorf("identifiant invalide : %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationThrottle(t *testing.T) {
|
||||
a, h := testAuth(t, "open")
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "root", Password: "mot-de-passe-0"})
|
||||
last := 0
|
||||
for i := 0; i < 8; i++ {
|
||||
b := newBrowser(t, h)
|
||||
w := b.do("POST", "/auth/local/register", `{"username":"user`+string(rune('a'+i))+`x","password":"mot-de-passe-1"}`)
|
||||
last = w.Code
|
||||
}
|
||||
if last != 429 {
|
||||
t.Errorf("après 8 inscriptions depuis la même adresse : %d", last)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginThrottleAndSessionRules(t *testing.T) {
|
||||
a, h := testAuth(t, "closed")
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "alice", Password: "mot-de-passe-1"})
|
||||
b := newBrowser(t, h)
|
||||
for i := 0; i < 10; i++ {
|
||||
if w := b.do("POST", "/auth/local/login", `{"username":"alice","password":"faux"}`); w.Code != 401 {
|
||||
t.Fatalf("essai %d : %d", i, w.Code)
|
||||
}
|
||||
}
|
||||
if w := b.do("POST", "/auth/local/login", `{"username":"alice","password":"mot-de-passe-1"}`); w.Code != 429 {
|
||||
t.Errorf("après 10 échecs : %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMiddlewareRoutesAndSessionRevocation(t *testing.T) {
|
||||
a, h := testAuth(t, "closed")
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "alice", Password: "mot-de-passe-1"})
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "bob", Password: "mot-de-passe-2"})
|
||||
b := newBrowser(t, h)
|
||||
// Sans session : API refusée, route publique ouverte, navigation = application.
|
||||
if w := b.do("GET", "/api/whoami", ""); w.Code != 401 || w.Header().Get(LoginHeader) != "" {
|
||||
t.Errorf("API : %d %v", w.Code, w.Header())
|
||||
}
|
||||
if w := b.do("GET", "/api/open", ""); w.Code != 200 {
|
||||
t.Errorf("public : %d", w.Code)
|
||||
}
|
||||
if w := b.do("GET", "/", ""); w.Code != 200 || !strings.Contains(w.Body.String(), "spa") {
|
||||
t.Errorf("navigation : %d %s", w.Code, w.Body)
|
||||
}
|
||||
if w := b.do("POST", "/api/whoami", ""); w.Code != 401 {
|
||||
t.Errorf("POST sans session : %d", w.Code)
|
||||
}
|
||||
b.do("POST", "/auth/local/login", `{"username":"bob","password":"mot-de-passe-2"}`)
|
||||
if got := b.do("GET", "/api/whoami", "").Body.String(); got != "bob:user" {
|
||||
t.Fatalf("whoami = %q", got)
|
||||
}
|
||||
// Un compte désactivé perd sa session tout de suite.
|
||||
disabled := StatusDisabled
|
||||
_, _ = a.Accounts.Update("bob", Patch{Status: &disabled})
|
||||
if w := b.do("GET", "/api/whoami", ""); w.Code != 401 {
|
||||
t.Errorf("session d'un compte désactivé : %d", w.Code)
|
||||
}
|
||||
// Un compte supprimé aussi.
|
||||
b2 := newBrowser(t, h)
|
||||
b2.do("POST", "/auth/local/login", `{"username":"alice","password":"mot-de-passe-1"}`)
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "carl", Password: "mot-de-passe-3", Role: RoleAdmin})
|
||||
_ = a.Accounts.Delete("alice")
|
||||
if w := b2.do("GET", "/api/whoami", ""); w.Code != 401 {
|
||||
t.Errorf("session d'un compte supprimé : %d", w.Code)
|
||||
}
|
||||
// Un cookie falsifié est refusé.
|
||||
b3 := newBrowser(t, h)
|
||||
b3.cookies["upandown_session"] = &http.Cookie{Name: "upandown_session", Value: "eyJpZCI6ImFkbWluIn0.AAAA"}
|
||||
if w := b3.do("GET", "/api/whoami", ""); w.Code != 401 {
|
||||
t.Errorf("cookie falsifié : %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogoutClearsSession(t *testing.T) {
|
||||
a, h := testAuth(t, "closed")
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "alice", Password: "mot-de-passe-1"})
|
||||
b := newBrowser(t, h)
|
||||
b.do("POST", "/auth/local/login", `{"username":"alice","password":"mot-de-passe-1"}`)
|
||||
if w := b.do("GET", "/auth/logout", ""); w.Code != 303 {
|
||||
t.Errorf("logout : %d", w.Code)
|
||||
}
|
||||
if w := b.do("GET", "/api/whoami", ""); w.Code != 401 {
|
||||
t.Errorf("après logout : %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOIDCLoginCreatesAccountAndHonoursStatus(t *testing.T) {
|
||||
idp := newIdP(t, "RS256")
|
||||
acc := newAccounts(t)
|
||||
sessions := NewSessions([]byte("0123456789abcdef0123456789abcdef"), time.Hour, false)
|
||||
o, err := NewOIDC(context.Background(), Config{
|
||||
Issuer: idp.srv.URL, ClientID: "excalicloud", ClientSecret: idp.secret,
|
||||
Secret: []byte("0123456789abcdef0123456789abcdef"), Client: testNet.client(), Sessions: sessions,
|
||||
Provision: func(u User, g []string) (User, error) { return acc.UpsertOIDC(u, g, OIDCPolicy{}) },
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a := New(&Auth{Accounts: acc, Sessions: sessions, OIDC: o})
|
||||
mux := http.NewServeMux()
|
||||
a.Register(mux)
|
||||
mux.HandleFunc("GET /api/whoami", func(w http.ResponseWriter, r *http.Request) {
|
||||
u := UserFrom(r.Context())
|
||||
_, _ = w.Write([]byte(u.ID + ":" + u.Role + ":" + u.Provider))
|
||||
})
|
||||
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("app")) })
|
||||
srv := testNet.serve("app", a.Middleware(mux, func(string) bool { return false }))
|
||||
jar, _ := cookiejar.New(nil)
|
||||
c := &http.Client{Jar: jar, Transport: testNet}
|
||||
|
||||
if res, body := get(t, c, srv.URL+"/api/whoami"); res.StatusCode != 401 || res.Header.Get(LoginHeader) != "/auth/login" {
|
||||
t.Fatalf("OIDC seul, sans session : %d %q", res.StatusCode, body)
|
||||
}
|
||||
if res, body := get(t, c, srv.URL+"/auth/login"); res.StatusCode != 200 || body != "app" {
|
||||
t.Fatalf("connexion : %d %q", res.StatusCode, body)
|
||||
}
|
||||
if _, body := get(t, c, srv.URL+"/api/whoami"); body != "cedric@example.org:admin:oidc" {
|
||||
t.Errorf("whoami = %q", body)
|
||||
}
|
||||
if got, ok := acc.Get("cedric@example.org"); !ok || got.Sub != "u-42" {
|
||||
t.Errorf("compte non créé : %+v", got)
|
||||
}
|
||||
// Désactivation : la session tombe, la reconnexion est refusée avec un message clair.
|
||||
id := "cedric@example.org"
|
||||
admin, disabled := RoleAdmin, StatusDisabled
|
||||
_, _ = acc.CreateLocal(NewAccount{Username: "backup", Password: "mot-de-passe-1", Role: admin})
|
||||
_, _ = acc.Update(id, Patch{Status: &disabled})
|
||||
if res, _ := get(t, c, srv.URL+"/api/whoami"); res.StatusCode != 401 {
|
||||
t.Errorf("session d'un compte désactivé : %d", res.StatusCode)
|
||||
}
|
||||
res, body := get(t, c, srv.URL+"/auth/login")
|
||||
if res.StatusCode != 403 || !strings.Contains(body, "désactivé") {
|
||||
t.Errorf("reconnexion refusée : %d %.80s", res.StatusCode, body)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Auth réunit l'authentification locale (comptes, inscription) et OIDC derrière
|
||||
// une même session : cookie signé, vérifié à chaque requête contre l'état du
|
||||
// compte (désactivé, supprimé, rôle modifié : effet immédiat).
|
||||
//
|
||||
// POST /auth/local/login {"username","password"}
|
||||
// POST /auth/local/register {"username","name","email","password"}
|
||||
// GET /auth/login connexion OIDC (si activée)
|
||||
// GET /auth/logout déconnexion (propagée au fournisseur OIDC)
|
||||
type Auth struct {
|
||||
Accounts *Accounts
|
||||
Sessions *Sessions
|
||||
OIDC *OIDC // nil : OIDC désactivé
|
||||
Local bool // comptes locaux activés
|
||||
// Registration renvoie le mode d'inscription courant : closed, approval ou open.
|
||||
Registration func() string
|
||||
// OIDCName : libellé du bouton de connexion OIDC.
|
||||
OIDCName string
|
||||
|
||||
logins *Limiter
|
||||
regs *Limiter
|
||||
}
|
||||
|
||||
// New prépare l'authentification ; Accounts et Sessions sont obligatoires.
|
||||
func New(a *Auth) *Auth {
|
||||
a.logins = NewLimiter(10, 15*time.Minute)
|
||||
a.regs = NewLimiter(5, time.Hour)
|
||||
if a.Registration == nil {
|
||||
a.Registration = func() string { return "closed" }
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// OnlyOIDC indique que la connexion passe uniquement par le fournisseur OIDC.
|
||||
func (a *Auth) OnlyOIDC() bool { return a.OIDC != nil && !a.Local }
|
||||
|
||||
// Register ajoute les routes /auth/*.
|
||||
func (a *Auth) Register(mux *http.ServeMux) {
|
||||
if a.OIDC != nil {
|
||||
a.OIDC.RegisterLogin(mux)
|
||||
}
|
||||
if a.Local {
|
||||
mux.HandleFunc("POST /auth/local/login", a.localLogin)
|
||||
mux.HandleFunc("POST /auth/local/register", a.localRegister)
|
||||
}
|
||||
mux.HandleFunc("GET /auth/logout", a.logout)
|
||||
mux.HandleFunc("POST /auth/logout", a.logout)
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
func writeErr(w http.ResponseWriter, status int, msg string) {
|
||||
writeJSON(w, status, map[string]string{"error": msg})
|
||||
}
|
||||
|
||||
// clientIP : adresse du client. Derrière un reverse proxy, l'entrée la plus à
|
||||
// droite de X-Forwarded-For est celle qu'il a ajoutée.
|
||||
func clientIP(r *http.Request) string {
|
||||
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
|
||||
parts := strings.Split(xff, ",")
|
||||
if ip := strings.TrimSpace(parts[len(parts)-1]); ip != "" {
|
||||
return ip
|
||||
}
|
||||
}
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
return r.RemoteAddr
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
type credentials struct {
|
||||
Username string `json:"username"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func decodeJSON(w http.ResponseWriter, r *http.Request, v any) bool {
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16<<10)).Decode(v); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "requête JSON invalide")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (a *Auth) localLogin(w http.ResponseWriter, r *http.Request) {
|
||||
var c credentials
|
||||
if !decodeJSON(w, r, &c) {
|
||||
return
|
||||
}
|
||||
userKey, ipKey := "u:"+strings.ToLower(strings.TrimSpace(c.Username)), "ip:"+clientIP(r)
|
||||
if !a.logins.Allowed(userKey) || !a.logins.Allowed(ipKey) {
|
||||
w.Header().Set("Retry-After", "900")
|
||||
writeErr(w, http.StatusTooManyRequests, "trop de tentatives : réessayer dans quelques minutes")
|
||||
return
|
||||
}
|
||||
acc, err := a.Accounts.Authenticate(c.Username, c.Password)
|
||||
switch err {
|
||||
case nil:
|
||||
case ErrBadCredentials:
|
||||
a.logins.Fail(userKey)
|
||||
a.logins.Fail(ipKey)
|
||||
writeErr(w, http.StatusUnauthorized, err.Error())
|
||||
return
|
||||
case ErrPending, ErrDisabled:
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": err.Error(), "code": codeOf(err)})
|
||||
return
|
||||
default:
|
||||
slog.Error("connexion locale", "err", err)
|
||||
writeErr(w, http.StatusInternalServerError, "erreur interne")
|
||||
return
|
||||
}
|
||||
a.logins.Reset(userKey)
|
||||
if err := a.Sessions.Start(w, r, acc.User()); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "erreur interne")
|
||||
return
|
||||
}
|
||||
slog.Info("connexion locale", "user", acc.ID)
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func codeOf(err error) string {
|
||||
if err == ErrPending {
|
||||
return "pending"
|
||||
}
|
||||
return "disabled"
|
||||
}
|
||||
|
||||
func (a *Auth) localRegister(w http.ResponseWriter, r *http.Request) {
|
||||
var c credentials
|
||||
if !decodeJSON(w, r, &c) {
|
||||
return
|
||||
}
|
||||
setup := a.Accounts.NeedsSetup() // premier compte : administrateur, même si les inscriptions sont fermées
|
||||
mode := a.Registration()
|
||||
if mode == "closed" && !setup {
|
||||
writeErr(w, http.StatusForbidden, "les inscriptions sont fermées")
|
||||
return
|
||||
}
|
||||
ipKey := "reg:" + clientIP(r)
|
||||
if !setup && !a.regs.Allowed(ipKey) {
|
||||
w.Header().Set("Retry-After", "3600")
|
||||
writeErr(w, http.StatusTooManyRequests, "trop d'inscriptions depuis cette adresse")
|
||||
return
|
||||
}
|
||||
status := StatusActive
|
||||
if mode == "approval" {
|
||||
status = StatusPending
|
||||
}
|
||||
acc, err := a.Accounts.CreateLocal(NewAccount{Username: c.Username, Name: c.Name, Email: c.Email,
|
||||
Password: c.Password, Status: status})
|
||||
if err != nil {
|
||||
code := http.StatusBadRequest
|
||||
if err == ErrAccountExists {
|
||||
code = http.StatusConflict
|
||||
}
|
||||
writeErr(w, code, err.Error())
|
||||
return
|
||||
}
|
||||
if !setup {
|
||||
a.regs.Fail(ipKey)
|
||||
}
|
||||
slog.Info("inscription", "user", acc.ID, "status", acc.Status, "role", acc.Role)
|
||||
if acc.Status == StatusPending {
|
||||
writeJSON(w, http.StatusAccepted, map[string]string{"status": StatusPending})
|
||||
return
|
||||
}
|
||||
if err := a.Sessions.Start(w, r, acc.User()); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "erreur interne")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]string{"status": StatusActive})
|
||||
}
|
||||
|
||||
func (a *Auth) logout(w http.ResponseWriter, r *http.Request) {
|
||||
if s, ok := a.Sessions.Get(r); ok && s.Provider == ProviderOIDC && a.OIDC != nil {
|
||||
a.OIDC.logout(w, r)
|
||||
return
|
||||
}
|
||||
a.Sessions.Clear(w, r)
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
// current renvoie l'utilisateur de la session : le compte doit exister et être
|
||||
// actif ; son rôle est celui du compte. La session est prolongée passée la
|
||||
// moitié de sa durée.
|
||||
func (a *Auth) current(w http.ResponseWriter, r *http.Request) (*User, bool) {
|
||||
s, ok := a.Sessions.Get(r)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
acc, ok := a.Accounts.Get(s.ID)
|
||||
if !ok || acc.Status != StatusActive {
|
||||
a.Sessions.Clear(w, r)
|
||||
return nil, false
|
||||
}
|
||||
u := acc.User()
|
||||
if time.Until(time.Unix(s.Exp, 0)) < a.Sessions.TTL/2 {
|
||||
_ = a.Sessions.Start(w, r, u)
|
||||
}
|
||||
return &u, true
|
||||
}
|
||||
|
||||
// Middleware exige une session sauf pour /auth/* et les chemins publics. Sans
|
||||
// session : l'API répond 401 ; une navigation reçoit l'application, qui affiche
|
||||
// la page de connexion (ou, avec OIDC seul, est renvoyée vers le fournisseur).
|
||||
func (a *Auth) Middleware(next http.Handler, public func(string) bool) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
p := r.URL.Path
|
||||
if strings.HasPrefix(p, "/auth/") || public(p) {
|
||||
if u, ok := a.current(w, r); ok { // identité disponible sur les routes publiques (ex. /api/me)
|
||||
r = r.WithContext(WithUser(r.Context(), u))
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
u, ok := a.current(w, r)
|
||||
if ok {
|
||||
next.ServeHTTP(w, r.WithContext(WithUser(r.Context(), u)))
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(p, "/api/") || r.Method != http.MethodGet {
|
||||
if a.OnlyOIDC() {
|
||||
w.Header().Set(LoginHeader, "/auth/login")
|
||||
}
|
||||
writeErr(w, http.StatusUnauthorized, "connexion nécessaire")
|
||||
return
|
||||
}
|
||||
if a.OnlyOIDC() {
|
||||
loginRedirect(w)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// UserContext renvoie ctx portant l'utilisateur u (jetons d'API).
|
||||
func UserContext(ctx context.Context, u *User) context.Context { return WithUser(ctx, u) }
|
||||
@@ -0,0 +1,379 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// memNet est un « réseau » en mémoire : chaque hôte https est servi par un
|
||||
// http.Handler, sans ouvrir de port (les tests tournent aussi sous un bac à
|
||||
// sable qui interdit l'écoute locale).
|
||||
type memNet struct {
|
||||
hosts map[string]http.Handler
|
||||
n int
|
||||
}
|
||||
|
||||
var testNet = &memNet{hosts: map[string]http.Handler{}}
|
||||
|
||||
type memServer struct{ URL string }
|
||||
|
||||
// serve enregistre h sous un nouveau nom d'hôte et renvoie son URL.
|
||||
func (m *memNet) serve(prefix string, h http.Handler) *memServer {
|
||||
m.n++
|
||||
host := fmt.Sprintf("%s%d.test", prefix, m.n)
|
||||
m.hosts[host] = h
|
||||
return &memServer{URL: "https://" + host}
|
||||
}
|
||||
|
||||
func (m *memNet) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
h := m.hosts[req.URL.Host]
|
||||
if h == nil {
|
||||
return nil, fmt.Errorf("hôte inconnu : %s", req.URL.Host)
|
||||
}
|
||||
r := req.Clone(req.Context())
|
||||
r.RequestURI = req.URL.RequestURI()
|
||||
if r.Host == "" {
|
||||
r.Host = req.URL.Host
|
||||
}
|
||||
r.RemoteAddr = "192.0.2.1:4242"
|
||||
if req.URL.Scheme == "https" {
|
||||
r.TLS = &tls.ConnectionState{}
|
||||
}
|
||||
if r.Body == nil {
|
||||
r.Body = http.NoBody
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, r)
|
||||
res := rec.Result()
|
||||
res.Request = req
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (m *memNet) client() *http.Client { return &http.Client{Transport: m} }
|
||||
|
||||
// fakeIdP est un fournisseur OIDC minimal : découverte, autorisation (connexion
|
||||
// immédiate), jetons, JWKS et déconnexion.
|
||||
type fakeIdP struct {
|
||||
t *testing.T
|
||||
srv *memServer
|
||||
rsaKey *rsa.PrivateKey
|
||||
ecKey *ecdsa.PrivateKey
|
||||
alg string // RS256, ES256 ou HS256
|
||||
secret string
|
||||
groups []string
|
||||
|
||||
codes map[string]url.Values // code -> paramètres de la demande d'autorisation
|
||||
}
|
||||
|
||||
func newIdP(t *testing.T, alg string) *fakeIdP {
|
||||
rk, _ := rsa.GenerateKey(rand.Reader, 2048)
|
||||
ek, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
p := &fakeIdP{t: t, rsaKey: rk, ecKey: ek, alg: alg, secret: "secret-client-assez-long", codes: map[string]url.Values{}}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{
|
||||
"issuer": p.srv.URL,
|
||||
"authorization_endpoint": p.srv.URL + "/authorize",
|
||||
"token_endpoint": p.srv.URL + "/token",
|
||||
"jwks_uri": p.srv.URL + "/jwks",
|
||||
"end_session_endpoint": p.srv.URL + "/logout",
|
||||
})
|
||||
})
|
||||
mux.HandleFunc("/jwks", func(w http.ResponseWriter, r *http.Request) {
|
||||
e := big.NewInt(int64(rk.E)).Bytes()
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"keys": []map[string]string{
|
||||
{"kty": "RSA", "kid": "r1", "use": "sig", "n": b64.EncodeToString(rk.N.Bytes()), "e": b64.EncodeToString(e)},
|
||||
{"kty": "EC", "kid": "e1", "crv": "P-256", "x": b64.EncodeToString(ek.X.FillBytes(make([]byte, 32))), "y": b64.EncodeToString(ek.Y.FillBytes(make([]byte, 32)))},
|
||||
}})
|
||||
})
|
||||
mux.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
code := randomString(8)
|
||||
p.codes[code] = q
|
||||
http.Redirect(w, r, q.Get("redirect_uri")+"?code="+code+"&state="+url.QueryEscape(q.Get("state")), http.StatusFound)
|
||||
})
|
||||
mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
q, ok := p.codes[r.Form.Get("code")]
|
||||
delete(p.codes, r.Form.Get("code"))
|
||||
id, sec, _ := r.BasicAuth()
|
||||
ch := sha256.Sum256([]byte(r.Form.Get("code_verifier")))
|
||||
switch {
|
||||
case !ok, id != "excalicloud", sec != p.secret,
|
||||
r.Form.Get("redirect_uri") != q.Get("redirect_uri"),
|
||||
q.Get("code_challenge_method") != "S256", b64.EncodeToString(ch[:]) != q.Get("code_challenge"):
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"error":"invalid_grant"}`))
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"id_token": p.idToken(q.Get("nonce")), "token_type": "Bearer"})
|
||||
})
|
||||
p.srv = testNet.serve("idp", mux)
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *fakeIdP) idToken(nonce string) string {
|
||||
claims := map[string]any{
|
||||
"iss": p.srv.URL, "sub": "u-42", "aud": "excalicloud", "nonce": nonce,
|
||||
"exp": time.Now().Add(5 * time.Minute).Unix(), "iat": time.Now().Unix(),
|
||||
"preferred_username": "cedric", "email": "cedric@example.org",
|
||||
}
|
||||
if p.groups != nil {
|
||||
claims["groups"] = p.groups
|
||||
}
|
||||
return p.sign(claims)
|
||||
}
|
||||
|
||||
func (p *fakeIdP) sign(claims map[string]any) string {
|
||||
hdr := map[string]string{"alg": p.alg, "typ": "JWT"}
|
||||
switch p.alg {
|
||||
case "RS256":
|
||||
hdr["kid"] = "r1"
|
||||
case "ES256":
|
||||
hdr["kid"] = "e1"
|
||||
}
|
||||
hb, _ := json.Marshal(hdr)
|
||||
cb, _ := json.Marshal(claims)
|
||||
signed := b64.EncodeToString(hb) + "." + b64.EncodeToString(cb)
|
||||
d := sha256.Sum256([]byte(signed))
|
||||
var sig []byte
|
||||
switch p.alg {
|
||||
case "RS256":
|
||||
sig, _ = rsa.SignPKCS1v15(rand.Reader, p.rsaKey, crypto.SHA256, d[:])
|
||||
case "ES256":
|
||||
r, s, _ := ecdsa.Sign(rand.Reader, p.ecKey, d[:])
|
||||
sig = append(r.FillBytes(make([]byte, 32)), s.FillBytes(make([]byte, 32))...)
|
||||
case "HS256":
|
||||
m := hmac.New(sha256.New, []byte(p.secret))
|
||||
m.Write([]byte(signed))
|
||||
sig = m.Sum(nil)
|
||||
}
|
||||
return signed + "." + b64.EncodeToString(sig)
|
||||
}
|
||||
|
||||
// app démarre excalicloud (routes /auth/*, une API et une page protégées, un
|
||||
// chemin public) avec l'authentification OIDC.
|
||||
func app(t *testing.T, idp *fakeIdP, groups []string) (*memServer, *http.Client) {
|
||||
t.Helper()
|
||||
mux := http.NewServeMux()
|
||||
var srv *memServer
|
||||
o, err := NewOIDC(context.Background(), Config{
|
||||
Issuer: idp.srv.URL, ClientID: "excalicloud", ClientSecret: idp.secret,
|
||||
AllowedGroups: groups, EndSession: true, Secret: []byte("0123456789abcdef0123456789abcdef"),
|
||||
Client: testNet.client(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
o.Register(mux)
|
||||
mux.HandleFunc("GET /api/me", func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(UserFrom(r.Context()))
|
||||
})
|
||||
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("app")) })
|
||||
srv = testNet.serve("app", o.Middleware(mux, func(p string) bool { return strings.HasPrefix(p, "/s/") }))
|
||||
jar, _ := cookiejar.New(nil)
|
||||
return srv, &http.Client{Jar: jar, Transport: testNet}
|
||||
}
|
||||
|
||||
func get(t *testing.T, c *http.Client, u string) (*http.Response, string) {
|
||||
t.Helper()
|
||||
res, err := c.Get(u)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
b, _ := io.ReadAll(res.Body)
|
||||
return res, string(b)
|
||||
}
|
||||
|
||||
func TestLoginFlow(t *testing.T) {
|
||||
for _, alg := range []string{"RS256", "ES256", "HS256"} {
|
||||
t.Run(alg, func(t *testing.T) {
|
||||
idp := newIdP(t, alg)
|
||||
srv, c := app(t, idp, nil)
|
||||
|
||||
// Sans session : 401 avec l'adresse de connexion pour l'API...
|
||||
res, _ := get(t, c, srv.URL+"/api/me")
|
||||
if res.StatusCode != 401 || res.Header.Get(LoginHeader) != "/auth/login" {
|
||||
t.Fatalf("API sans session : %d %q", res.StatusCode, res.Header.Get(LoginHeader))
|
||||
}
|
||||
// ... page de redirection (fragment conservé) pour la navigation.
|
||||
res, body := get(t, c, srv.URL+"/")
|
||||
if res.StatusCode != 401 || !strings.Contains(body, "location.hash") {
|
||||
t.Fatalf("navigation sans session : %d", res.StatusCode)
|
||||
}
|
||||
// Chemin public accessible.
|
||||
if res, _ := get(t, c, srv.URL+"/s/x.y"); res.StatusCode != 200 {
|
||||
t.Fatalf("chemin public : %d", res.StatusCode)
|
||||
}
|
||||
|
||||
// Connexion complète : login -> fournisseur -> callback -> next.
|
||||
res, body = get(t, c, srv.URL+"/auth/login?next="+url.QueryEscape("/dossier?x=1"))
|
||||
if res.StatusCode != 200 || body != "app" || res.Request.URL.RequestURI() != "/dossier?x=1" {
|
||||
t.Fatalf("après connexion : %d %q %s", res.StatusCode, body, res.Request.URL)
|
||||
}
|
||||
res, body = get(t, c, srv.URL+"/api/me")
|
||||
if res.StatusCode != 200 || !strings.Contains(body, `"name":"cedric"`) || !strings.Contains(body, `"sub":"u-42"`) {
|
||||
t.Fatalf("/api/me : %d %s", res.StatusCode, body)
|
||||
}
|
||||
|
||||
// Déconnexion : cookie effacé, renvoi vers end_session_endpoint.
|
||||
nc := &http.Client{Jar: c.Jar, Transport: testNet, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
res, _ = get(t, nc, srv.URL+"/auth/logout")
|
||||
loc, _ := url.Parse(res.Header.Get("Location"))
|
||||
if res.StatusCode != 302 || loc.Path != "/logout" || loc.Query().Get("client_id") != "excalicloud" ||
|
||||
loc.Query().Get("post_logout_redirect_uri") != srv.URL+"/auth/logged-out" {
|
||||
t.Fatalf("logout : %d %s", res.StatusCode, loc)
|
||||
}
|
||||
if res, _ := get(t, c, srv.URL+"/api/me"); res.StatusCode != 401 {
|
||||
t.Fatalf("après déconnexion : %d", res.StatusCode)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAllowedGroups(t *testing.T) {
|
||||
idp := newIdP(t, "RS256")
|
||||
idp.groups = []string{"/excalicloud-users"} // chemin complet Keycloak
|
||||
srv, c := app(t, idp, []string{"excalicloud-users"})
|
||||
if res, body := get(t, c, srv.URL+"/auth/login"); res.StatusCode != 200 || body != "app" {
|
||||
t.Fatalf("membre du groupe : %d %q", res.StatusCode, body)
|
||||
}
|
||||
|
||||
idp2 := newIdP(t, "RS256")
|
||||
idp2.groups = []string{"autres"}
|
||||
srv2, c2 := app(t, idp2, []string{"excalicloud-users"})
|
||||
if res, _ := get(t, c2, srv2.URL+"/auth/login"); res.StatusCode != 403 {
|
||||
t.Fatalf("hors groupe : %d", res.StatusCode)
|
||||
}
|
||||
if res, _ := get(t, c2, srv2.URL+"/api/me"); res.StatusCode != 401 {
|
||||
t.Fatalf("hors groupe, pas de session attendue : %d", res.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallbackRejectsForgedState(t *testing.T) {
|
||||
idp := newIdP(t, "RS256")
|
||||
srv, c := app(t, idp, nil)
|
||||
// Callback sans cookie d'état (CSRF de connexion) : refusé.
|
||||
if res, _ := get(t, c, srv.URL+"/auth/callback?code=x&state=y"); res.StatusCode != 400 {
|
||||
t.Fatalf("callback forgé : %d", res.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyIDToken(t *testing.T) {
|
||||
idp := newIdP(t, "RS256")
|
||||
o, err := NewOIDC(context.Background(), Config{Issuer: idp.srv.URL, ClientID: "excalicloud", Secret: []byte("0123456789abcdef"), Client: testNet.client()})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d, err := o.provider(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base := func() map[string]any {
|
||||
return map[string]any{"iss": idp.srv.URL, "sub": "s", "aud": []string{"excalicloud"}, "nonce": "n",
|
||||
"exp": time.Now().Add(time.Minute).Unix(), "iat": time.Now().Unix()}
|
||||
}
|
||||
if _, err := o.verifyIDToken(context.Background(), d, idp.sign(base()), "n"); err != nil {
|
||||
t.Fatalf("jeton valide refusé : %v", err)
|
||||
}
|
||||
bad := map[string]func(map[string]any){
|
||||
"émetteur": func(c map[string]any) { c["iss"] = "https://ailleurs" },
|
||||
"audience": func(c map[string]any) { c["aud"] = "autre" },
|
||||
"expiré": func(c map[string]any) { c["exp"] = time.Now().Add(-time.Hour).Unix() },
|
||||
"nonce": func(c map[string]any) { c["nonce"] = "x" },
|
||||
}
|
||||
for name, mutate := range bad {
|
||||
c := base()
|
||||
mutate(c)
|
||||
if _, err := o.verifyIDToken(context.Background(), d, idp.sign(c), "n"); err == nil {
|
||||
t.Errorf("%s : jeton accepté", name)
|
||||
}
|
||||
}
|
||||
// Signature altérée, alg none et HS256 sans secret client.
|
||||
tok := idp.sign(base())
|
||||
if _, err := o.verifyIDToken(context.Background(), d, tok[:len(tok)-4]+"AAAA", "n"); err == nil {
|
||||
t.Error("signature altérée acceptée")
|
||||
}
|
||||
parts := strings.Split(tok, ".")
|
||||
none := b64.EncodeToString([]byte(`{"alg":"none"}`)) + "." + parts[1] + "."
|
||||
if _, err := o.verifyIDToken(context.Background(), d, none, "n"); err == nil {
|
||||
t.Error("alg none accepté")
|
||||
}
|
||||
idp.alg = "HS256"
|
||||
if _, err := o.verifyIDToken(context.Background(), d, idp.sign(base()), "n"); err == nil {
|
||||
t.Error("HS256 accepté sans secret client")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSafeNext(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
"/a/b?c=1": "/a/b?c=1",
|
||||
"//evil.example": "/",
|
||||
"/\\evil.example": "/",
|
||||
"https://evil": "/",
|
||||
"/auth/logout": "/",
|
||||
"": "/",
|
||||
"/x\r\nSet-Cookie:a": "/",
|
||||
} {
|
||||
if got := safeNext(in); got != want {
|
||||
t.Errorf("safeNext(%q) = %q, attendu %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionCookieTampering(t *testing.T) {
|
||||
s := signer{[]byte("0123456789abcdef")}
|
||||
v, _ := s.encode(session{User: User{Sub: "a"}, Exp: time.Now().Add(time.Hour).Unix()})
|
||||
var out session
|
||||
if err := s.decode(v, &out); err != nil || out.Sub != "a" {
|
||||
t.Fatalf("décodage : %v", err)
|
||||
}
|
||||
p, sig, _ := strings.Cut(v, ".")
|
||||
forged := b64.EncodeToString([]byte(`{"sub":"admin","exp":9999999999}`)) + "." + sig
|
||||
if s.decode(forged, &out) == nil || s.decode(p+".x", &out) == nil {
|
||||
t.Fatal("cookie altéré accepté")
|
||||
}
|
||||
if (signer{[]byte("autre-cle-0123456")}).decode(v, &out) == nil {
|
||||
t.Fatal("cookie signé par une autre clé accepté")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadSecret(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if _, err := LoadSecret("court", dir); err == nil {
|
||||
t.Fatal("secret trop court accepté")
|
||||
}
|
||||
k1, err := LoadSecret("", dir)
|
||||
if err != nil || len(k1) != 32 {
|
||||
t.Fatalf("génération : %v", err)
|
||||
}
|
||||
fi, _ := os.Stat(filepath.Join(dir, ".session-secret"))
|
||||
if fi.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("droits %v", fi.Mode().Perm())
|
||||
}
|
||||
k2, _ := LoadSecret("", dir)
|
||||
if string(k1) != string(k2) {
|
||||
t.Fatal("clé non conservée entre deux démarrages")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/hmac"
|
||||
"crypto/rsa"
|
||||
_ "crypto/sha256" // enregistre SHA-256 pour crypto.Hash
|
||||
_ "crypto/sha512" // enregistre SHA-384 et SHA-512
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// jwk est une clé publique d'un JWKS (RFC 7517), RSA ou EC.
|
||||
type jwk struct {
|
||||
Kty string `json:"kty"`
|
||||
Kid string `json:"kid"`
|
||||
Use string `json:"use"`
|
||||
Alg string `json:"alg"`
|
||||
N string `json:"n"`
|
||||
E string `json:"e"`
|
||||
Crv string `json:"crv"`
|
||||
X string `json:"x"`
|
||||
Y string `json:"y"`
|
||||
}
|
||||
|
||||
func (k jwk) publicKey() (crypto.PublicKey, error) {
|
||||
switch k.Kty {
|
||||
case "RSA":
|
||||
n, err1 := b64.DecodeString(k.N)
|
||||
e, err2 := b64.DecodeString(k.E)
|
||||
if err1 != nil || err2 != nil || len(n) == 0 || len(e) == 0 || len(e) > 4 {
|
||||
return nil, errors.New("clé RSA invalide")
|
||||
}
|
||||
return &rsa.PublicKey{N: new(big.Int).SetBytes(n), E: int(new(big.Int).SetBytes(e).Int64())}, nil
|
||||
case "EC":
|
||||
var c elliptic.Curve
|
||||
switch k.Crv {
|
||||
case "P-256":
|
||||
c = elliptic.P256()
|
||||
case "P-384":
|
||||
c = elliptic.P384()
|
||||
case "P-521":
|
||||
c = elliptic.P521()
|
||||
default:
|
||||
return nil, fmt.Errorf("courbe %q non prise en charge", k.Crv)
|
||||
}
|
||||
x, err1 := b64.DecodeString(k.X)
|
||||
y, err2 := b64.DecodeString(k.Y)
|
||||
if err1 != nil || err2 != nil {
|
||||
return nil, errors.New("clé EC invalide")
|
||||
}
|
||||
pub := &ecdsa.PublicKey{Curve: c, X: new(big.Int).SetBytes(x), Y: new(big.Int).SetBytes(y)}
|
||||
if !c.IsOnCurve(pub.X, pub.Y) {
|
||||
return nil, errors.New("clé EC invalide")
|
||||
}
|
||||
return pub, nil
|
||||
}
|
||||
return nil, fmt.Errorf("type de clé %q non pris en charge", k.Kty)
|
||||
}
|
||||
|
||||
var algHash = map[string]crypto.Hash{
|
||||
"RS256": crypto.SHA256, "RS384": crypto.SHA384, "RS512": crypto.SHA512,
|
||||
"PS256": crypto.SHA256, "PS384": crypto.SHA384, "PS512": crypto.SHA512,
|
||||
"ES256": crypto.SHA256, "ES384": crypto.SHA384, "ES512": crypto.SHA512,
|
||||
"HS256": crypto.SHA256, "HS384": crypto.SHA384, "HS512": crypto.SHA512,
|
||||
}
|
||||
|
||||
type jwtHeader struct {
|
||||
Alg string `json:"alg"`
|
||||
Kid string `json:"kid"`
|
||||
}
|
||||
|
||||
// parseJWT découpe un JWS compact et renvoie l'en-tête, les claims bruts, le
|
||||
// contenu signé et la signature.
|
||||
func parseJWT(token string) (h jwtHeader, claims []byte, signed string, sig []byte, err error) {
|
||||
parts := strings.Split(token, ".")
|
||||
if len(parts) != 3 {
|
||||
return h, nil, "", nil, errors.New("jeton mal formé")
|
||||
}
|
||||
hb, err := b64.DecodeString(parts[0])
|
||||
if err != nil || json.Unmarshal(hb, &h) != nil {
|
||||
return h, nil, "", nil, errors.New("en-tête de jeton invalide")
|
||||
}
|
||||
if claims, err = b64.DecodeString(parts[1]); err != nil {
|
||||
return h, nil, "", nil, errors.New("contenu de jeton invalide")
|
||||
}
|
||||
if sig, err = b64.DecodeString(parts[2]); err != nil {
|
||||
return h, nil, "", nil, errors.New("signature de jeton invalide")
|
||||
}
|
||||
return h, claims, parts[0] + "." + parts[1], sig, nil
|
||||
}
|
||||
|
||||
// verifySignature vérifie la signature avec une clé publique (RS, PS, ES) ou
|
||||
// le secret client (HS, clé symétrique utilisée par exemple par Authentik
|
||||
// quand aucun certificat de signature n'est choisi).
|
||||
func verifySignature(alg string, key crypto.PublicKey, secret []byte, signed string, sig []byte) error {
|
||||
hash, ok := algHash[alg]
|
||||
if !ok {
|
||||
return fmt.Errorf("algorithme %q refusé", alg)
|
||||
}
|
||||
if strings.HasPrefix(alg, "HS") {
|
||||
if len(secret) == 0 {
|
||||
return fmt.Errorf("jeton %s sans OIDC_CLIENT_SECRET", alg)
|
||||
}
|
||||
m := hmac.New(hash.New, secret)
|
||||
m.Write([]byte(signed))
|
||||
if !hmac.Equal(m.Sum(nil), sig) {
|
||||
return errors.New("signature invalide")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
d := hash.New()
|
||||
d.Write([]byte(signed))
|
||||
digest := d.Sum(nil)
|
||||
switch k := key.(type) {
|
||||
case *rsa.PublicKey:
|
||||
var err error
|
||||
switch alg[:2] {
|
||||
case "RS":
|
||||
err = rsa.VerifyPKCS1v15(k, hash, digest, sig)
|
||||
case "PS":
|
||||
err = rsa.VerifyPSS(k, hash, digest, sig, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
|
||||
default:
|
||||
err = errors.New("algorithme incompatible avec une clé RSA")
|
||||
}
|
||||
if err != nil {
|
||||
return errors.New("signature invalide")
|
||||
}
|
||||
return nil
|
||||
case *ecdsa.PublicKey:
|
||||
size := (k.Curve.Params().BitSize + 7) / 8
|
||||
if alg[:2] != "ES" || len(sig) != 2*size {
|
||||
return errors.New("signature invalide")
|
||||
}
|
||||
r, s := new(big.Int).SetBytes(sig[:size]), new(big.Int).SetBytes(sig[size:])
|
||||
if !ecdsa.Verify(k, digest, r, s) {
|
||||
return errors.New("signature invalide")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return errors.New("clé de vérification inadaptée")
|
||||
}
|
||||
|
||||
// idClaims regroupe les claims utiles d'un ID Token.
|
||||
type idClaims struct {
|
||||
Iss string `json:"iss"`
|
||||
Sub string `json:"sub"`
|
||||
Aud json.RawMessage `json:"aud"`
|
||||
Azp string `json:"azp"`
|
||||
Exp json.Number `json:"exp"`
|
||||
Iat json.Number `json:"iat"`
|
||||
Nonce string `json:"nonce"`
|
||||
Name string `json:"name"`
|
||||
PreferredUsername string `json:"preferred_username"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
func (c idClaims) audiences() []string {
|
||||
var one string
|
||||
if json.Unmarshal(c.Aud, &one) == nil {
|
||||
return []string{one}
|
||||
}
|
||||
var many []string
|
||||
_ = json.Unmarshal(c.Aud, &many)
|
||||
return many
|
||||
}
|
||||
|
||||
const clockSkew = 2 * time.Minute
|
||||
|
||||
// validate contrôle émetteur, audience, dates et nonce (OIDC Core 3.1.3.7).
|
||||
func (c idClaims) validate(issuer, clientID, nonce string, t time.Time) error {
|
||||
if c.Iss != issuer {
|
||||
return fmt.Errorf("émetteur %q inattendu", c.Iss)
|
||||
}
|
||||
if c.Sub == "" {
|
||||
return errors.New("claim sub absent")
|
||||
}
|
||||
aud := c.audiences()
|
||||
found := false
|
||||
for _, a := range aud {
|
||||
found = found || a == clientID
|
||||
}
|
||||
if !found {
|
||||
return errors.New("jeton destiné à un autre client")
|
||||
}
|
||||
if len(aud) > 1 && c.Azp != "" && c.Azp != clientID {
|
||||
return errors.New("azp inattendu")
|
||||
}
|
||||
exp, err := c.Exp.Int64()
|
||||
if err != nil {
|
||||
f, ferr := c.Exp.Float64()
|
||||
if ferr != nil {
|
||||
return errors.New("claim exp invalide")
|
||||
}
|
||||
exp = int64(f)
|
||||
}
|
||||
if t.After(time.Unix(exp, 0).Add(clockSkew)) {
|
||||
return errors.New("jeton expiré")
|
||||
}
|
||||
if iat, err := c.Iat.Float64(); err == nil && time.Unix(int64(iat), 0).After(t.Add(clockSkew)) {
|
||||
return errors.New("jeton émis dans le futur (horloge ?)")
|
||||
}
|
||||
if !hmac.Equal([]byte(c.Nonce), []byte(nonce)) {
|
||||
return errors.New("nonce invalide")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// stringList lit un claim chaîne ou tableau de chaînes (groupes, rôles).
|
||||
func stringList(v any) []string {
|
||||
switch x := v.(type) {
|
||||
case string:
|
||||
return []string{x}
|
||||
case []any:
|
||||
out := make([]string, 0, len(x))
|
||||
for _, e := range x {
|
||||
if s, ok := e.(string); ok {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// claimPath lit un claim éventuellement imbriqué (« realm_access.roles »).
|
||||
func claimPath(all map[string]any, p string) any {
|
||||
var cur any = all
|
||||
for _, part := range strings.Split(p, ".") {
|
||||
m, ok := cur.(map[string]any)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
cur = m[part]
|
||||
}
|
||||
return cur
|
||||
}
|
||||
@@ -0,0 +1,571 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
sessionCookie = "upandown_session"
|
||||
stateCookie = "upandown_oidc"
|
||||
stateTTL = 10 * time.Minute
|
||||
|
||||
// LoginHeader accompagne les réponses 401 de l'API : le frontend y lit
|
||||
// l'adresse de connexion.
|
||||
LoginHeader = "X-Auth-Login"
|
||||
)
|
||||
|
||||
// Config regroupe les réglages OIDC (variables OIDC_* et SESSION_*).
|
||||
type Config struct {
|
||||
Issuer string // OIDC_ISSUER
|
||||
ClientID string // OIDC_CLIENT_ID
|
||||
ClientSecret string // OIDC_CLIENT_SECRET (vide : client public, PKCE seul)
|
||||
RedirectURL string // OIDC_REDIRECT_URL (vide : https://<hôte>/auth/callback)
|
||||
Scopes []string // OIDC_SCOPES
|
||||
// AllowedGroups restreint l'accès aux membres d'au moins un de ces groupes
|
||||
// (claim GroupsClaim) ; vide : tout utilisateur authentifié.
|
||||
AllowedGroups []string
|
||||
GroupsClaim string // OIDC_GROUPS_CLAIM, « groups » par défaut
|
||||
EndSession bool // OIDC_LOGOUT : déconnexion aussi chez le fournisseur
|
||||
SessionTTL time.Duration
|
||||
Secret []byte // clé HMAC des cookies
|
||||
Client *http.Client
|
||||
// Sessions : gestionnaire de sessions partagé avec l'authentification locale
|
||||
// (nil : créé à partir de Secret et SessionTTL).
|
||||
Sessions *Sessions
|
||||
// Provision est appelé après une connexion réussie, avant l'ouverture de la
|
||||
// session : il crée ou met à jour le compte et peut refuser la connexion
|
||||
// (ErrPending, ErrDisabled). Il renvoie l'utilisateur de la session.
|
||||
Provision func(u User, groups []string) (User, error)
|
||||
}
|
||||
|
||||
// discovery est la partie utile de /.well-known/openid-configuration.
|
||||
type discovery struct {
|
||||
Issuer string `json:"issuer"`
|
||||
AuthorizationEndpoint string `json:"authorization_endpoint"`
|
||||
TokenEndpoint string `json:"token_endpoint"`
|
||||
JWKSURI string `json:"jwks_uri"`
|
||||
EndSessionEndpoint string `json:"end_session_endpoint"`
|
||||
}
|
||||
|
||||
// OIDC authentifie les utilisateurs auprès d'un fournisseur OpenID Connect
|
||||
// (Authentik, Keycloak, Entra ID, Google, Dex...).
|
||||
type OIDC struct {
|
||||
cfg Config
|
||||
signer signer
|
||||
sess *Sessions
|
||||
|
||||
mu sync.Mutex
|
||||
disc *discovery // nil : pas encore découvert
|
||||
keys map[string]crypto.PublicKey
|
||||
keysAt time.Time
|
||||
discErr time.Time // dernier échec de découverte (limite les tentatives)
|
||||
}
|
||||
|
||||
// NewOIDC prépare l'authentification ; la découverte du fournisseur est
|
||||
// tentée tout de suite puis, en cas d'échec, à la première connexion.
|
||||
func NewOIDC(ctx context.Context, cfg Config) (*OIDC, error) {
|
||||
if cfg.Issuer == "" || cfg.ClientID == "" {
|
||||
return nil, errors.New("OIDC_ISSUER et OIDC_CLIENT_ID sont requis en mode oidc")
|
||||
}
|
||||
if len(cfg.Secret) < 16 {
|
||||
return nil, errors.New("clé de session trop courte")
|
||||
}
|
||||
if cfg.RedirectURL != "" {
|
||||
u, err := url.Parse(cfg.RedirectURL)
|
||||
if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
|
||||
return nil, errors.New("OIDC_REDIRECT_URL invalide (URL absolue attendue)")
|
||||
}
|
||||
}
|
||||
if len(cfg.Scopes) == 0 {
|
||||
cfg.Scopes = []string{"openid", "profile", "email"}
|
||||
}
|
||||
if !slices.Contains(cfg.Scopes, "openid") {
|
||||
cfg.Scopes = append([]string{"openid"}, cfg.Scopes...)
|
||||
}
|
||||
if cfg.GroupsClaim == "" {
|
||||
cfg.GroupsClaim = "groups"
|
||||
}
|
||||
if cfg.SessionTTL <= 0 {
|
||||
cfg.SessionTTL = 24 * time.Hour
|
||||
}
|
||||
if cfg.Client == nil {
|
||||
cfg.Client = &http.Client{Timeout: 15 * time.Second}
|
||||
}
|
||||
if cfg.Sessions == nil {
|
||||
cfg.Sessions = NewSessions(cfg.Secret, cfg.SessionTTL, strings.HasPrefix(cfg.RedirectURL, "https://"))
|
||||
}
|
||||
a := &OIDC{cfg: cfg, signer: signer{cfg.Secret}, sess: cfg.Sessions}
|
||||
if _, err := a.provider(ctx); err != nil {
|
||||
slog.Warn("fournisseur OIDC injoignable, nouvel essai à la première connexion", "issuer", cfg.Issuer, "err", err)
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
func (a *OIDC) getJSON(ctx context.Context, u string, v any) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
res, err := a.cfg.Client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("%s : HTTP %d", u, res.StatusCode)
|
||||
}
|
||||
return json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(v)
|
||||
}
|
||||
|
||||
// provider renvoie la configuration découverte (mise en cache).
|
||||
func (a *OIDC) provider(ctx context.Context) (*discovery, error) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if a.disc != nil {
|
||||
return a.disc, nil
|
||||
}
|
||||
if time.Since(a.discErr) < 5*time.Second {
|
||||
return nil, errors.New("fournisseur OIDC injoignable")
|
||||
}
|
||||
var d discovery
|
||||
u := strings.TrimRight(a.cfg.Issuer, "/") + "/.well-known/openid-configuration"
|
||||
if err := a.getJSON(ctx, u, &d); err != nil {
|
||||
a.discErr = time.Now()
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimRight(d.Issuer, "/") != strings.TrimRight(a.cfg.Issuer, "/") {
|
||||
a.discErr = time.Now()
|
||||
return nil, fmt.Errorf("l'émetteur annoncé (%s) ne correspond pas à OIDC_ISSUER", d.Issuer)
|
||||
}
|
||||
if d.AuthorizationEndpoint == "" || d.TokenEndpoint == "" || d.JWKSURI == "" {
|
||||
a.discErr = time.Now()
|
||||
return nil, errors.New("configuration OIDC incomplète (authorization, token ou jwks absent)")
|
||||
}
|
||||
a.disc = &d
|
||||
slog.Info("fournisseur OIDC découvert", "issuer", d.Issuer)
|
||||
return a.disc, nil
|
||||
}
|
||||
|
||||
// key renvoie la clé publique kid, en rechargeant le JWKS si elle est
|
||||
// inconnue (rotation de clés), au plus une fois par minute.
|
||||
func (a *OIDC) key(ctx context.Context, d *discovery, kid, alg string) (crypto.PublicKey, error) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
find := func() crypto.PublicKey {
|
||||
if k, ok := a.keys[kid]; ok {
|
||||
return k
|
||||
}
|
||||
if kid == "" && len(a.keys) == 1 {
|
||||
for _, k := range a.keys {
|
||||
return k
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if k := find(); k != nil {
|
||||
return k, nil
|
||||
}
|
||||
if time.Since(a.keysAt) < time.Minute && a.keys != nil {
|
||||
return nil, fmt.Errorf("clé %q inconnue", kid)
|
||||
}
|
||||
var set struct {
|
||||
Keys []jwk `json:"keys"`
|
||||
}
|
||||
if err := a.getJSON(ctx, d.JWKSURI, &set); err != nil {
|
||||
return nil, fmt.Errorf("JWKS : %w", err)
|
||||
}
|
||||
a.keys = map[string]crypto.PublicKey{}
|
||||
a.keysAt = time.Now()
|
||||
for _, j := range set.Keys {
|
||||
if j.Use != "" && j.Use != "sig" {
|
||||
continue
|
||||
}
|
||||
if pk, err := j.publicKey(); err == nil {
|
||||
a.keys[j.Kid] = pk
|
||||
}
|
||||
}
|
||||
if k := find(); k != nil {
|
||||
return k, nil
|
||||
}
|
||||
return nil, fmt.Errorf("clé %q absente du JWKS (alg %s)", kid, alg)
|
||||
}
|
||||
|
||||
// --- Routes /auth/* -----------------------------------------------------------
|
||||
|
||||
// Register ajoute /auth/login, /auth/callback, /auth/logout et /auth/logged-out.
|
||||
func (a *OIDC) Register(mux *http.ServeMux) {
|
||||
a.RegisterLogin(mux)
|
||||
mux.HandleFunc("GET /auth/logout", a.logout)
|
||||
mux.HandleFunc("POST /auth/logout", a.logout)
|
||||
}
|
||||
|
||||
// RegisterLogin ajoute /auth/login, /auth/callback et /auth/logged-out (la
|
||||
// déconnexion est alors portée par l'appelant, voir Auth).
|
||||
func (a *OIDC) RegisterLogin(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /auth/login", a.login)
|
||||
mux.HandleFunc("GET /auth/callback", a.callback)
|
||||
mux.HandleFunc("GET /auth/logged-out", func(w http.ResponseWriter, r *http.Request) {
|
||||
page(w, http.StatusOK, "Déconnecté", "Vous êtes déconnecté.", "/", "Se reconnecter")
|
||||
})
|
||||
}
|
||||
|
||||
func secure(r *http.Request) bool {
|
||||
return r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https")
|
||||
}
|
||||
|
||||
// baseURL est l'origine publique du service : celle de OIDC_REDIRECT_URL si
|
||||
// elle est fixée, sinon celle de la requête (en-têtes X-Forwarded-* compris).
|
||||
func (a *OIDC) baseURL(r *http.Request) string {
|
||||
if a.cfg.RedirectURL != "" {
|
||||
u, _ := url.Parse(a.cfg.RedirectURL)
|
||||
return u.Scheme + "://" + u.Host
|
||||
}
|
||||
scheme := "http"
|
||||
if secure(r) {
|
||||
scheme = "https"
|
||||
}
|
||||
host := r.Host
|
||||
if h := r.Header.Get("X-Forwarded-Host"); h != "" {
|
||||
host, _, _ = strings.Cut(h, ",")
|
||||
host = strings.TrimSpace(host)
|
||||
}
|
||||
return scheme + "://" + host
|
||||
}
|
||||
|
||||
func (a *OIDC) redirectURL(r *http.Request) string {
|
||||
if a.cfg.RedirectURL != "" {
|
||||
return a.cfg.RedirectURL
|
||||
}
|
||||
return a.baseURL(r) + "/auth/callback"
|
||||
}
|
||||
|
||||
func (a *OIDC) setCookie(w http.ResponseWriter, r *http.Request, name, value, path string, ttl time.Duration) {
|
||||
c := &http.Cookie{
|
||||
Name: name,
|
||||
Value: value,
|
||||
Path: path,
|
||||
HttpOnly: true,
|
||||
Secure: secure(r) || strings.HasPrefix(a.cfg.RedirectURL, "https://"),
|
||||
SameSite: http.SameSiteLaxMode, // envoyé au retour du fournisseur (navigation GET)
|
||||
}
|
||||
if ttl < 0 {
|
||||
c.MaxAge = -1
|
||||
} else {
|
||||
c.Expires = now().Add(ttl)
|
||||
c.MaxAge = int(ttl / time.Second)
|
||||
}
|
||||
http.SetCookie(w, c)
|
||||
}
|
||||
|
||||
// safeNext n'accepte que les chemins locaux (pas de redirection ouverte).
|
||||
func safeNext(next string) string {
|
||||
if !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") || strings.HasPrefix(next, "/\\") ||
|
||||
strings.HasPrefix(next, "/auth/") || strings.ContainsAny(next, "\r\n") {
|
||||
return "/"
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
func (a *OIDC) login(w http.ResponseWriter, r *http.Request) {
|
||||
d, err := a.provider(r.Context())
|
||||
if err != nil {
|
||||
slog.Error("OIDC : découverte", "err", err)
|
||||
page(w, http.StatusBadGateway, "Connexion impossible",
|
||||
"Le fournisseur d'identité est injoignable pour l'instant.", r.URL.RequestURI(), "Réessayer")
|
||||
return
|
||||
}
|
||||
st := loginState{
|
||||
State: randomString(24),
|
||||
Nonce: randomString(24),
|
||||
Verifier: randomString(48), // 64 caractères (RFC 7636 : 43 à 128)
|
||||
Next: safeNext(r.URL.Query().Get("next")),
|
||||
Exp: now().Add(stateTTL).Unix(),
|
||||
}
|
||||
v, err := a.signer.encode(st)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
a.setCookie(w, r, stateCookie, v, "/auth/", stateTTL)
|
||||
|
||||
challenge := sha256.Sum256([]byte(st.Verifier))
|
||||
q := url.Values{
|
||||
"response_type": {"code"},
|
||||
"client_id": {a.cfg.ClientID},
|
||||
"redirect_uri": {a.redirectURL(r)},
|
||||
"scope": {strings.Join(a.cfg.Scopes, " ")},
|
||||
"state": {st.State},
|
||||
"nonce": {st.Nonce},
|
||||
"code_challenge": {b64.EncodeToString(challenge[:])},
|
||||
"code_challenge_method": {"S256"},
|
||||
}
|
||||
sep := "?"
|
||||
if strings.Contains(d.AuthorizationEndpoint, "?") {
|
||||
sep = "&"
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
http.Redirect(w, r, d.AuthorizationEndpoint+sep+q.Encode(), http.StatusFound)
|
||||
}
|
||||
|
||||
func (a *OIDC) callback(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
q := r.URL.Query()
|
||||
retry := "/auth/login"
|
||||
var st loginState
|
||||
c, err := r.Cookie(stateCookie)
|
||||
if err == nil {
|
||||
err = a.signer.decode(c.Value, &st)
|
||||
}
|
||||
if err == nil && st.Next != "/" {
|
||||
retry += "?next=" + url.QueryEscape(st.Next)
|
||||
}
|
||||
a.setCookie(w, r, stateCookie, "", "/auth/", -1) // usage unique
|
||||
if e := q.Get("error"); e != "" {
|
||||
slog.Warn("OIDC : refus du fournisseur", "error", e, "description", q.Get("error_description"))
|
||||
page(w, http.StatusForbidden, "Connexion refusée", "Le fournisseur d'identité a refusé la connexion ("+e+").", retry, "Réessayer")
|
||||
return
|
||||
}
|
||||
if err != nil || st.Exp < now().Unix() || st.State == "" || q.Get("state") != st.State {
|
||||
page(w, http.StatusBadRequest, "Connexion expirée",
|
||||
"La demande de connexion est expirée ou invalide (cookies bloqués ?).", retry, "Recommencer")
|
||||
return
|
||||
}
|
||||
user, err := a.exchange(r, q.Get("code"), st)
|
||||
if errors.Is(err, errForbidden) {
|
||||
slog.Warn("OIDC : accès refusé", "sub", user.Sub, "name", user.Name)
|
||||
page(w, http.StatusForbidden, "Accès refusé",
|
||||
"Votre compte ("+user.Name+") n'appartient à aucun groupe autorisé.", "/auth/logout", "Changer de compte")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, ErrPending) {
|
||||
page(w, http.StatusForbidden, "Compte en attente", "Votre compte ("+user.Name+") doit être validé par un administrateur.", "/auth/logout", "Changer de compte")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, ErrDisabled) {
|
||||
page(w, http.StatusForbidden, "Compte désactivé", "Votre compte ("+user.Name+") a été désactivé.", "/auth/logout", "Changer de compte")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
slog.Error("OIDC : échange du code", "err", err)
|
||||
page(w, http.StatusBadGateway, "Connexion impossible", "La vérification de l'identité a échoué.", retry, "Réessayer")
|
||||
return
|
||||
}
|
||||
if err := a.startSession(w, r, user); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
slog.Info("connexion OIDC", "sub", user.Sub, "name", user.Name)
|
||||
http.Redirect(w, r, st.Next, http.StatusFound)
|
||||
}
|
||||
|
||||
var errForbidden = errors.New("utilisateur hors des groupes autorisés")
|
||||
|
||||
// exchange échange le code contre les jetons, vérifie l'ID Token et en tire
|
||||
// l'utilisateur.
|
||||
func (a *OIDC) exchange(r *http.Request, code string, st loginState) (User, error) {
|
||||
ctx := r.Context()
|
||||
d, err := a.provider(ctx)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
form := url.Values{
|
||||
"grant_type": {"authorization_code"},
|
||||
"code": {code},
|
||||
"redirect_uri": {a.redirectURL(r)},
|
||||
"code_verifier": {st.Verifier},
|
||||
"client_id": {a.cfg.ClientID},
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, d.TokenEndpoint, strings.NewReader(form.Encode()))
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
if a.cfg.ClientSecret != "" { // client_secret_basic (RFC 6749 2.3.1)
|
||||
req.SetBasicAuth(url.QueryEscape(a.cfg.ClientID), url.QueryEscape(a.cfg.ClientSecret))
|
||||
}
|
||||
res, err := a.cfg.Client.Do(req)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
var tok struct {
|
||||
IDToken string `json:"id_token"`
|
||||
Error string `json:"error"`
|
||||
Desc string `json:"error_description"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&tok); err != nil {
|
||||
return User{}, fmt.Errorf("réponse du token endpoint (HTTP %d) : %w", res.StatusCode, err)
|
||||
}
|
||||
if res.StatusCode != http.StatusOK || tok.IDToken == "" {
|
||||
return User{}, fmt.Errorf("token endpoint : HTTP %d %s %s", res.StatusCode, tok.Error, tok.Desc)
|
||||
}
|
||||
u, err := a.verifyIDToken(ctx, d, tok.IDToken, st.Nonce)
|
||||
if err != nil {
|
||||
return u, err
|
||||
}
|
||||
if a.cfg.Provision != nil {
|
||||
return a.cfg.Provision(u, u.Groups)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (a *OIDC) verifyIDToken(ctx context.Context, d *discovery, raw, nonce string) (User, error) {
|
||||
h, body, signed, sig, err := parseJWT(raw)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
var key crypto.PublicKey
|
||||
if !strings.HasPrefix(h.Alg, "HS") {
|
||||
if key, err = a.key(ctx, d, h.Kid, h.Alg); err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
}
|
||||
if err := verifySignature(h.Alg, key, []byte(a.cfg.ClientSecret), signed, sig); err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
var c idClaims
|
||||
if err := json.Unmarshal(body, &c); err != nil {
|
||||
return User{}, errors.New("claims illisibles")
|
||||
}
|
||||
if err := c.validate(d.Issuer, a.cfg.ClientID, nonce, now()); err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
u := User{Sub: c.Sub, Email: c.Email, Name: c.PreferredUsername}
|
||||
for _, n := range []string{c.Name, c.Email, c.Sub} {
|
||||
if u.Name == "" {
|
||||
u.Name = n
|
||||
}
|
||||
}
|
||||
var all map[string]any
|
||||
_ = json.Unmarshal(body, &all)
|
||||
groups := stringList(claimPath(all, a.cfg.GroupsClaim))
|
||||
for i, g := range groups {
|
||||
groups[i] = strings.TrimPrefix(g, "/") // Keycloak : chemin complet du groupe
|
||||
}
|
||||
u.Groups = groups
|
||||
if len(a.cfg.AllowedGroups) > 0 {
|
||||
ok := slices.ContainsFunc(groups, func(g string) bool {
|
||||
// Keycloak préfixe les groupes par « / » quand le chemin complet est inclus.
|
||||
return slices.Contains(a.cfg.AllowedGroups, g) || slices.Contains(a.cfg.AllowedGroups, strings.TrimPrefix(g, "/"))
|
||||
})
|
||||
if !ok {
|
||||
return u, errForbidden
|
||||
}
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (a *OIDC) startSession(w http.ResponseWriter, r *http.Request, u User) error {
|
||||
return a.sess.Start(w, r, u)
|
||||
}
|
||||
|
||||
func (a *OIDC) logout(w http.ResponseWriter, r *http.Request) {
|
||||
a.sess.Clear(w, r)
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
back := a.baseURL(r) + "/auth/logged-out"
|
||||
if a.cfg.EndSession {
|
||||
if d, err := a.provider(r.Context()); err == nil && d.EndSessionEndpoint != "" {
|
||||
// RP-Initiated Logout 1.0 : client_id identifie le client sans id_token_hint.
|
||||
q := url.Values{"client_id": {a.cfg.ClientID}, "post_logout_redirect_uri": {back}}
|
||||
sep := "?"
|
||||
if strings.Contains(d.EndSessionEndpoint, "?") {
|
||||
sep = "&"
|
||||
}
|
||||
http.Redirect(w, r, d.EndSessionEndpoint+sep+q.Encode(), http.StatusFound)
|
||||
return
|
||||
}
|
||||
}
|
||||
http.Redirect(w, r, back, http.StatusFound)
|
||||
}
|
||||
|
||||
// --- Protection des routes -------------------------------------------------------
|
||||
|
||||
type ctxKey struct{}
|
||||
|
||||
// UserFrom renvoie l'utilisateur de la requête (nil hors session OIDC).
|
||||
func UserFrom(ctx context.Context) *User {
|
||||
u, _ := ctx.Value(ctxKey{}).(*User)
|
||||
return u
|
||||
}
|
||||
|
||||
// WithUser renvoie ctx portant l'utilisateur u (authentification par jeton d'API).
|
||||
func WithUser(ctx context.Context, u *User) context.Context {
|
||||
return context.WithValue(ctx, ctxKey{}, u)
|
||||
}
|
||||
|
||||
// Session renvoie l'utilisateur du cookie de session s'il est valide.
|
||||
func (a *OIDC) session(r *http.Request) (session, bool) { return a.sess.Get(r) }
|
||||
|
||||
// Middleware exige une session sauf pour /auth/* et les chemins publics.
|
||||
// Navigation sans session : page qui renvoie vers /auth/login en conservant
|
||||
// l'URL complète (fragment #/dossier/schéma compris). API : 401 + LoginHeader.
|
||||
// La session est prolongée à chaque requête passée la moitié de sa durée.
|
||||
func (a *OIDC) Middleware(next http.Handler, public func(string) bool) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
p := r.URL.Path
|
||||
if strings.HasPrefix(p, "/auth/") || public(p) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
s, ok := a.session(r)
|
||||
if !ok {
|
||||
if strings.HasPrefix(p, "/api/") || r.Method != http.MethodGet {
|
||||
w.Header().Set(LoginHeader, "/auth/login")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_, _ = w.Write([]byte(`{"error":"session expirée : reconnexion nécessaire"}`))
|
||||
return
|
||||
}
|
||||
loginRedirect(w)
|
||||
return
|
||||
}
|
||||
if time.Until(time.Unix(s.Exp, 0)) < a.cfg.SessionTTL/2 {
|
||||
_ = a.startSession(w, r, s.User)
|
||||
}
|
||||
u := s.User
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, &u)))
|
||||
})
|
||||
}
|
||||
|
||||
// loginRedirect renvoie vers /auth/login par script pour conserver le
|
||||
// fragment de l'URL, que le navigateur n'envoie pas au serveur.
|
||||
func loginRedirect(w http.ResponseWriter) {
|
||||
h := w.Header()
|
||||
h.Set("Content-Type", "text/html; charset=utf-8")
|
||||
h.Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_, _ = io.WriteString(w, `<!doctype html><meta charset="utf-8"><title>Connexion</title>
|
||||
<script>location.replace("/auth/login?next="+encodeURIComponent(location.pathname+location.search+location.hash))</script>
|
||||
<noscript><a href="/auth/login">Se connecter</a></noscript>`)
|
||||
}
|
||||
|
||||
// page affiche un message simple (erreur de connexion, déconnexion).
|
||||
func page(w http.ResponseWriter, status int, title, msg, link, label string) {
|
||||
h := w.Header()
|
||||
h.Set("Content-Type", "text/html; charset=utf-8")
|
||||
h.Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(status)
|
||||
e := html.EscapeString
|
||||
_, _ = fmt.Fprintf(w, `<!doctype html><html lang="fr"><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"><title>%s</title>
|
||||
<style>body{font:16px system-ui,sans-serif;display:grid;place-items:center;min-height:90vh;margin:0;color:#1b1b1f;background:#fff}
|
||||
@media(prefers-color-scheme:dark){body{color:#e3e3e8;background:#121212}}main{max-width:28rem;padding:1rem;text-align:center}
|
||||
a{display:inline-block;margin-top:1rem;padding:.6rem 1.2rem;border-radius:8px;background:#6965db;color:#fff;text-decoration:none}</style>
|
||||
<main><h1>%s</h1><p>%s</p><a href="%s">%s</a></main></html>`, e(title), e(title), e(msg), e(link), e(label))
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
// Package auth fournit l'authentification OpenID Connect (flux Authorization
|
||||
// Code + PKCE) et les sessions signées associées, sans dépendance externe.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// User est l'utilisateur authentifié. Sub est l'identifiant du fournisseur
|
||||
// OIDC (vide pour un compte local) ; ID est celui du compte (nom de son
|
||||
// espace personnel) ; Role n'est jamais lu du cookie : il vient du compte.
|
||||
type User struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Sub string `json:"sub,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Provider string `json:"provider,omitempty"` // "local" ou "oidc"
|
||||
Role string `json:"role,omitempty"` // "admin" ou "user" (rempli par le middleware)
|
||||
Groups []string `json:"-"` // groupes OIDC de la connexion en cours
|
||||
}
|
||||
|
||||
// session est le contenu du cookie de session (signé, non chiffré : il ne
|
||||
// contient que l'identité, pas de jeton).
|
||||
type session struct {
|
||||
User
|
||||
Exp int64 `json:"exp"`
|
||||
}
|
||||
|
||||
// loginState accompagne l'aller-retour vers le fournisseur (cookie de 10 min).
|
||||
type loginState struct {
|
||||
State string `json:"state"`
|
||||
Nonce string `json:"nonce"`
|
||||
Verifier string `json:"verifier"`
|
||||
Next string `json:"next"`
|
||||
Exp int64 `json:"exp"`
|
||||
}
|
||||
|
||||
var errBadCookie = errors.New("cookie invalide")
|
||||
|
||||
// Erreurs de connexion.
|
||||
var (
|
||||
ErrBadCredentials = errors.New("identifiant ou mot de passe incorrect")
|
||||
ErrPending = errors.New("compte en attente de validation par un administrateur")
|
||||
ErrDisabled = errors.New("compte désactivé")
|
||||
)
|
||||
|
||||
// signer signe et vérifie des valeurs JSON (HMAC-SHA256).
|
||||
type signer struct{ key []byte }
|
||||
|
||||
var b64 = base64.RawURLEncoding
|
||||
|
||||
func (s signer) mac(payload string) string {
|
||||
m := hmac.New(sha256.New, s.key)
|
||||
m.Write([]byte(payload))
|
||||
return b64.EncodeToString(m.Sum(nil))
|
||||
}
|
||||
|
||||
func (s signer) encode(v any) (string, error) {
|
||||
raw, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
p := b64.EncodeToString(raw)
|
||||
return p + "." + s.mac(p), nil
|
||||
}
|
||||
|
||||
// decode vérifie la signature puis décode ; le contrôle d'expiration revient
|
||||
// à l'appelant (champ Exp).
|
||||
func (s signer) decode(value string, v any) error {
|
||||
p, sig, ok := strings.Cut(value, ".")
|
||||
if !ok || !hmac.Equal([]byte(sig), []byte(s.mac(p))) {
|
||||
return errBadCookie
|
||||
}
|
||||
raw, err := b64.DecodeString(p)
|
||||
if err != nil {
|
||||
return errBadCookie
|
||||
}
|
||||
if json.Unmarshal(raw, v) != nil {
|
||||
return errBadCookie
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func randomString(n int) string {
|
||||
b := make([]byte, n)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
panic(err) // crypto/rand ne échoue pas sur les systèmes supportés
|
||||
}
|
||||
return b64.EncodeToString(b)
|
||||
}
|
||||
|
||||
// LoadSecret renvoie la clé de signature des sessions : secret si fourni
|
||||
// (16 caractères minimum), sinon le contenu de dir/.session-secret, créé
|
||||
// aléatoirement au premier démarrage (0600).
|
||||
func LoadSecret(secret, dir string) ([]byte, error) {
|
||||
if secret != "" {
|
||||
if len(secret) < 16 {
|
||||
return nil, errors.New("SESSION_SECRET trop court (16 caractères minimum)")
|
||||
}
|
||||
return []byte(secret), nil
|
||||
}
|
||||
file := filepath.Join(dir, ".session-secret")
|
||||
if b, err := os.ReadFile(file); err == nil {
|
||||
if k, err := hex.DecodeString(strings.TrimSpace(string(b))); err == nil && len(k) >= 32 {
|
||||
return k, nil
|
||||
}
|
||||
return nil, errors.New(file + " invalide (supprimer le fichier pour en générer un nouveau)")
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return nil, err
|
||||
}
|
||||
k := make([]byte, 32)
|
||||
if _, err := rand.Read(k); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.WriteFile(file, []byte(hex.EncodeToString(k)+"\n"), 0o600); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return k, nil
|
||||
}
|
||||
|
||||
func now() time.Time { return time.Now() }
|
||||
|
||||
// Sessions gère le cookie de session signé, commun aux comptes locaux et OIDC.
|
||||
type Sessions struct {
|
||||
signer signer
|
||||
TTL time.Duration
|
||||
secure bool // cookie Secure même si la requête n'arrive pas en HTTPS (URL publique en https)
|
||||
}
|
||||
|
||||
// NewSessions crée un gestionnaire de sessions : secret signe les cookies, ttl
|
||||
// est la durée d'inactivité maximale.
|
||||
func NewSessions(secret []byte, ttl time.Duration, forceSecure bool) *Sessions {
|
||||
if ttl <= 0 {
|
||||
ttl = 24 * time.Hour
|
||||
}
|
||||
return &Sessions{signer: signer{secret}, TTL: ttl, secure: forceSecure}
|
||||
}
|
||||
|
||||
func (s *Sessions) cookie(w http.ResponseWriter, r *http.Request, value string, ttl time.Duration) {
|
||||
c := &http.Cookie{
|
||||
Name: sessionCookie,
|
||||
Value: value,
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: secure(r) || s.secure,
|
||||
SameSite: http.SameSiteLaxMode, // envoyé au retour du fournisseur (navigation GET)
|
||||
}
|
||||
if ttl < 0 {
|
||||
c.MaxAge = -1
|
||||
} else {
|
||||
c.Expires = now().Add(ttl)
|
||||
c.MaxAge = int(ttl / time.Second)
|
||||
}
|
||||
http.SetCookie(w, c)
|
||||
}
|
||||
|
||||
// Start ouvre (ou prolonge) la session de u.
|
||||
func (s *Sessions) Start(w http.ResponseWriter, r *http.Request, u User) error {
|
||||
v, err := s.signer.encode(session{User: u, Exp: now().Add(s.TTL).Unix()})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.cookie(w, r, v, s.TTL)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Clear supprime le cookie de session.
|
||||
func (s *Sessions) Clear(w http.ResponseWriter, r *http.Request) { s.cookie(w, r, "", -1) }
|
||||
|
||||
// Get renvoie la session du cookie s'il est valide.
|
||||
func (s *Sessions) Get(r *http.Request) (session, bool) {
|
||||
var v session
|
||||
c, err := r.Cookie(sessionCookie)
|
||||
if err != nil || s.signer.decode(c.Value, &v) != nil || v.Exp < now().Unix() || (v.Sub == "" && v.ID == "") {
|
||||
return v, false
|
||||
}
|
||||
return v, true
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"image"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Détails des fichiers et dossiers pour la vue Galerie et le panneau Détails
|
||||
// (/api/list?details=1) : dimensions d'une image, versions, liens de partage
|
||||
// actifs, création et dernier auteur ; contenu d'un dossier.
|
||||
|
||||
// Details complète une entrée.
|
||||
type Details struct {
|
||||
Width int `json:"width,omitempty"` // image : dimensions en pixels
|
||||
Height int `json:"height,omitempty"`
|
||||
|
||||
Versions int `json:"versions,omitempty"` // versions dans l'historique
|
||||
Shares int `json:"shares,omitempty"` // liens de partage actifs
|
||||
Created *time.Time `json:"created,omitempty"` // création (ou plus ancienne version connue)
|
||||
CreatedBy string `json:"createdBy,omitempty"` // vide si inconnu
|
||||
|
||||
Dirs int `json:"dirs,omitempty"` // dossier : sous-dossiers directs
|
||||
Files int `json:"files,omitempty"` // dossier : fichiers directs
|
||||
Total int64 `json:"total,omitempty"` // dossier : taille de tout le contenu (octets)
|
||||
Count int `json:"count,omitempty"` // dossier : nombre de fichiers dans tout le contenu
|
||||
}
|
||||
|
||||
// maxDirWalk borne le parcours qui totalise la taille d'un dossier.
|
||||
const maxDirWalk = 20000
|
||||
|
||||
func (s *Store) fileDetails(rel string, meta map[string]itemMeta, shares map[string]int) (*Details, error) {
|
||||
c, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fi, err := os.Lstat(abs)
|
||||
if err != nil {
|
||||
return nil, mapErr(err)
|
||||
}
|
||||
d := &Details{Shares: shares[c]}
|
||||
if isDecodableImage(c) && fi.Size() < 200<<20 {
|
||||
if f, err := os.Open(abs); err == nil {
|
||||
if cfg, _, err := image.DecodeConfig(f); err == nil {
|
||||
d.Width, d.Height = cfg.Width, cfg.Height
|
||||
}
|
||||
f.Close()
|
||||
}
|
||||
}
|
||||
var oldest string
|
||||
d.Versions, oldest = s.versionCount(c)
|
||||
if m := meta[c]; m.Created != nil {
|
||||
d.Created, d.CreatedBy = m.Created, m.CreatedBy
|
||||
} else if t, err := time.Parse(versionLayout, oldest); err == nil {
|
||||
d.Created = &t
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// versionCount compte les versions d'un fichier et renvoie l'identifiant de la
|
||||
// plus ancienne, sans lire leurs métadonnées.
|
||||
func (s *Store) versionCount(c string) (int, string) {
|
||||
des, err := os.ReadDir(s.historyAbs(c))
|
||||
if err != nil {
|
||||
return 0, ""
|
||||
}
|
||||
n, oldest := 0, ""
|
||||
for _, de := range des {
|
||||
id := de.Name()
|
||||
if de.IsDir() || !versionID.MatchString(id) {
|
||||
continue
|
||||
}
|
||||
n++
|
||||
if oldest == "" || id < oldest {
|
||||
oldest = id
|
||||
}
|
||||
}
|
||||
return n, oldest
|
||||
}
|
||||
|
||||
// dirDetails compte le contenu d'un dossier : éléments directs, puis taille
|
||||
// et nombre de fichiers de toute l'arborescence (borné à maxDirWalk entrées).
|
||||
func (s *Store) dirDetails(rel string) (*Details, error) {
|
||||
_, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
des, err := os.ReadDir(abs)
|
||||
if err != nil {
|
||||
return nil, mapErr(err)
|
||||
}
|
||||
d := &Details{}
|
||||
for _, de := range des {
|
||||
if !visible(de.Name()) || de.Type()&os.ModeSymlink != 0 {
|
||||
continue
|
||||
}
|
||||
if de.IsDir() {
|
||||
d.Dirs++
|
||||
} else {
|
||||
d.Files++
|
||||
}
|
||||
}
|
||||
seen := 0
|
||||
_ = filepath.WalkDir(abs, func(p string, e os.DirEntry, err error) error {
|
||||
if err != nil || p == abs {
|
||||
return nil
|
||||
}
|
||||
if strings.HasPrefix(e.Name(), ".") {
|
||||
if e.IsDir() {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if seen++; seen > maxDirWalk {
|
||||
return filepath.SkipAll
|
||||
}
|
||||
if e.Type().IsRegular() {
|
||||
if fi, err := e.Info(); err == nil {
|
||||
d.Total += fi.Size()
|
||||
d.Count++
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// shareCounts compte les liens de partage actifs par chemin.
|
||||
func (s *Store) shareCounts() map[string]int {
|
||||
s.sharesMu.Lock()
|
||||
defer s.sharesMu.Unlock()
|
||||
m, err := s.readShares()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
out := map[string]int{}
|
||||
now := time.Now()
|
||||
for _, d := range m {
|
||||
if d.Expires == nil || now.Before(*d.Expires) {
|
||||
out[d.Path]++
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// noteEdit retient le dernier utilisateur qui a déposé un fichier et, pour un
|
||||
// fichier nouveau, sa date de création et son auteur. .meta.json n'est réécrit
|
||||
// que si quelque chose change.
|
||||
func (s *Store) noteEdit(c, by string, created bool) {
|
||||
if c == "" {
|
||||
return
|
||||
}
|
||||
s.metaMu.Lock()
|
||||
defer s.metaMu.Unlock()
|
||||
if s.loadMeta() != nil {
|
||||
return
|
||||
}
|
||||
m := s.meta[c]
|
||||
changed := false
|
||||
if by != "" && m.EditedBy != by {
|
||||
m.EditedBy, changed = by, true
|
||||
}
|
||||
if created && m.Created == nil {
|
||||
now := time.Now().UTC().Truncate(time.Second)
|
||||
m.Created, m.CreatedBy, changed = &now, by, true
|
||||
}
|
||||
if changed {
|
||||
s.meta[c] = m
|
||||
_ = s.saveMeta()
|
||||
}
|
||||
}
|
||||
|
||||
// AddDetails complète des entrées (chemins virtuels) de leurs détails. Les
|
||||
// dossiers virtuels, favoris cassés et éléments de la poubelle sont laissés
|
||||
// tels quels.
|
||||
func (u *Space) AddDetails(es []*Entry) {
|
||||
metas := map[*Store]map[string]itemMeta{}
|
||||
shares := map[*Store]map[string]int{}
|
||||
for _, e := range es {
|
||||
if e.Special != "" || e.Broken || e.Origin != "" {
|
||||
continue
|
||||
}
|
||||
st, rel, err := u.route(e.Path)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if _, ok := metas[st]; !ok {
|
||||
metas[st], shares[st] = st.metaSnapshot(), st.shareCounts()
|
||||
}
|
||||
if e.IsDir {
|
||||
if d, _ := st.dirDetails(rel); d != nil {
|
||||
d.Shares = shares[st][cleanOr(rel)]
|
||||
e.Details = d
|
||||
}
|
||||
continue
|
||||
}
|
||||
e.Details, _ = st.fileDetails(rel, metas[st], shares[st])
|
||||
}
|
||||
}
|
||||
|
||||
func cleanOr(rel string) string {
|
||||
c, _ := Clean(rel)
|
||||
return c
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Historique des versions : avant qu'un fichier soit remplacé, son contenu
|
||||
// précédent est conservé dans .history/ en miroir de l'arborescence
|
||||
// (a/b.pdf -> .history/a/b.pdf/<date>). La version est un lien physique vers
|
||||
// l'ancien fichier quand le volume le permet (aucune copie de données), sinon
|
||||
// une copie.
|
||||
//
|
||||
// Une version n'est prise que si la précédente date d'au moins
|
||||
// HistoryPolicy.Interval (0 : à chaque remplacement). Restaurer une version ou
|
||||
// en créer une à la demande ignore l'intervalle.
|
||||
|
||||
const historyDir = ".history"
|
||||
|
||||
// HistoryPolicy règle la prise et la rétention des versions.
|
||||
type HistoryPolicy struct {
|
||||
Keep int // versions conservées par fichier (0 : historique désactivé)
|
||||
Interval time.Duration // écart minimal entre deux versions automatiques
|
||||
MaxAge time.Duration // âge maximal d'une version (0 : illimité)
|
||||
}
|
||||
|
||||
// DefaultHistory : 10 versions par fichier, une à chaque remplacement.
|
||||
var DefaultHistory = HistoryPolicy{Keep: 10}
|
||||
|
||||
// Version décrit une version enregistrée d'un fichier. Time est la date à
|
||||
// laquelle ce contenu avait été déposé.
|
||||
type Version struct {
|
||||
ID string `json:"id"`
|
||||
Time time.Time `json:"time"`
|
||||
Size int64 `json:"size"`
|
||||
}
|
||||
|
||||
const versionLayout = "20060102T150405.000000000Z"
|
||||
|
||||
var versionID = regexp.MustCompile(`^\d{8}T\d{6}\.\d{9}Z$`)
|
||||
|
||||
func (s *Store) historyAbs(c string) string {
|
||||
return filepath.Join(s.root, historyDir, filepath.FromSlash(c))
|
||||
}
|
||||
|
||||
func (s *Store) versionAbs(c, id string) string { return filepath.Join(s.historyAbs(c), id) }
|
||||
|
||||
// versions liste les versions d'un fichier, la plus récente en premier.
|
||||
// taken renvoie en plus la date de prise de la plus récente (date du fichier).
|
||||
func (s *Store) versions(c string) ([]Version, time.Time, error) {
|
||||
des, err := os.ReadDir(s.historyAbs(c))
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return []Version{}, time.Time{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, time.Time{}, err
|
||||
}
|
||||
out := []Version{}
|
||||
var taken time.Time
|
||||
for _, de := range des {
|
||||
id := de.Name()
|
||||
if de.IsDir() || !versionID.MatchString(id) {
|
||||
continue
|
||||
}
|
||||
t, err := time.Parse(versionLayout, id)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
fi, err := de.Info()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
out = append(out, Version{ID: id, Time: t, Size: fi.Size()})
|
||||
if ct := changeTime(fi); ct.After(taken) {
|
||||
taken = ct
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].ID > out[j].ID })
|
||||
return out, taken, nil
|
||||
}
|
||||
|
||||
// changeTime : date de prise d'une version. Un lien physique garde la date du
|
||||
// contenu : on utilise la date de création de l'entrée d'historique, que le
|
||||
// nom de fichier ne porte pas ; à défaut, la date du contenu.
|
||||
func changeTime(fi fs.FileInfo) time.Time { return fi.ModTime() }
|
||||
|
||||
// snapshot conserve le fichier abs (daté de mod) comme version. Sans force,
|
||||
// rien n'est pris si la dernière version a moins de Interval. Une version
|
||||
// de même date et de même taille que la plus récente n'est jamais dupliquée.
|
||||
func (s *Store) snapshot(c, abs string, fi fs.FileInfo, force bool) (Version, error) {
|
||||
p := s.History
|
||||
if p.Keep <= 0 {
|
||||
return Version{}, nil
|
||||
}
|
||||
vs, _, err := s.versions(c)
|
||||
if err != nil {
|
||||
return Version{}, err
|
||||
}
|
||||
if !force && len(vs) > 0 && p.Interval > 0 && time.Since(vs[0].Time) < p.Interval {
|
||||
return Version{}, nil
|
||||
}
|
||||
v := Version{ID: fi.ModTime().UTC().Format(versionLayout), Time: fi.ModTime().UTC(), Size: fi.Size()}
|
||||
if len(vs) > 0 && vs[0].ID == v.ID && vs[0].Size == v.Size {
|
||||
return vs[0], nil
|
||||
}
|
||||
dst := s.versionAbs(c, v.ID)
|
||||
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
|
||||
return Version{}, err
|
||||
}
|
||||
_ = os.Remove(dst)
|
||||
if err := os.Link(abs, dst); err != nil {
|
||||
if err := copyFile(abs, dst); err != nil {
|
||||
return Version{}, err
|
||||
}
|
||||
_ = os.Chtimes(dst, fi.ModTime(), fi.ModTime())
|
||||
}
|
||||
s.pruneHistory(c)
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// pruneHistory applique la rétention (nombre et âge) aux versions d'un fichier.
|
||||
func (s *Store) pruneHistory(c string) {
|
||||
vs, _, err := s.versions(c)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for i, v := range vs {
|
||||
if i >= s.History.Keep || (s.History.MaxAge > 0 && time.Since(v.Time) > s.History.MaxAge) {
|
||||
_ = os.Remove(s.versionAbs(c, v.ID))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// autoSnapshot est appelé par Put avant de remplacer un fichier ; un échec est
|
||||
// journalisé mais n'empêche pas l'enregistrement.
|
||||
func (s *Store) autoSnapshot(c, abs string, fi fs.FileInfo) {
|
||||
if _, err := s.snapshot(c, abs, fi, false); err != nil {
|
||||
slog.Warn("historique : version non enregistrée", "path", c, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Versions liste les versions d'un fichier existant, la plus récente en premier.
|
||||
func (s *Store) Versions(rel string) ([]Version, error) {
|
||||
c, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if c == "" {
|
||||
return nil, ErrInvalidPath
|
||||
}
|
||||
if fi, err := os.Lstat(abs); err != nil || !fi.Mode().IsRegular() {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
vs, _, err := s.versions(c)
|
||||
return vs, err
|
||||
}
|
||||
|
||||
// OpenVersion ouvre une version en lecture.
|
||||
func (s *Store) OpenVersion(rel, id string) (*os.File, fs.FileInfo, error) {
|
||||
c, _, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if c == "" || !versionID.MatchString(id) {
|
||||
return nil, nil, fmt.Errorf("%w : version %q", ErrInvalidPath, id)
|
||||
}
|
||||
f, err := os.Open(s.versionAbs(c, id))
|
||||
if err != nil {
|
||||
return nil, nil, mapErr(err)
|
||||
}
|
||||
fi, err := f.Stat()
|
||||
if err != nil {
|
||||
f.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
return f, fi, nil
|
||||
}
|
||||
|
||||
// Snapshot crée une version du contenu courant, quel que soit l'intervalle.
|
||||
func (s *Store) Snapshot(rel string) (Version, error) {
|
||||
c, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return Version{}, err
|
||||
}
|
||||
if s.History.Keep <= 0 {
|
||||
return Version{}, fmt.Errorf("%w : historique désactivé (HISTORY_KEEP=0)", ErrInvalidPath)
|
||||
}
|
||||
fi, err := os.Lstat(abs)
|
||||
if err != nil || !fi.Mode().IsRegular() {
|
||||
return Version{}, ErrNotFound
|
||||
}
|
||||
return s.snapshot(c, abs, fi, true)
|
||||
}
|
||||
|
||||
// Restore remplace le contenu d'un fichier par une de ses versions. Le contenu
|
||||
// courant est d'abord enregistré comme version : une restauration s'annule.
|
||||
func (s *Store) Restore(rel, id string) (Entry, error) {
|
||||
vf, _, err := s.OpenVersion(rel, id)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
defer vf.Close()
|
||||
c, abs, _ := s.resolve(rel)
|
||||
fi, err := os.Lstat(abs)
|
||||
if err != nil || !fi.Mode().IsRegular() {
|
||||
return Entry{}, ErrNotFound
|
||||
}
|
||||
vfi, _ := vf.Stat()
|
||||
tmp, err := os.CreateTemp(filepath.Dir(abs), ".tmp-*")
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
defer os.Remove(tmp.Name())
|
||||
if _, err := io.Copy(tmp, vf); err != nil {
|
||||
tmp.Close()
|
||||
return Entry{}, err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
_ = os.Chmod(tmp.Name(), 0o644)
|
||||
if vfi != nil {
|
||||
_ = os.Chtimes(tmp.Name(), vfi.ModTime(), vfi.ModTime())
|
||||
}
|
||||
if _, err := s.snapshot(c, abs, fi, true); err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
if err := os.Rename(tmp.Name(), abs); err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
s.usageDirty()
|
||||
s.removeThumb(c)
|
||||
nfi, err := os.Stat(abs)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
return toEntry(c, nfi), nil
|
||||
}
|
||||
|
||||
// Les opérations suivantes accompagnent Move/Delete.
|
||||
|
||||
func (s *Store) moveHistory(from, to string) {
|
||||
src, dst := s.historyAbs(from), s.historyAbs(to)
|
||||
if _, err := os.Stat(src); err != nil {
|
||||
return
|
||||
}
|
||||
_ = os.RemoveAll(dst)
|
||||
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err == nil {
|
||||
_ = os.Rename(src, dst)
|
||||
}
|
||||
}
|
||||
|
||||
// trashHistory range l'historique d'un élément supprimé avec lui dans la
|
||||
// corbeille (trash/.history/<nom>), pour pouvoir le récupérer à la main.
|
||||
func (s *Store) trashHistory(c, trash string) {
|
||||
src := s.historyAbs(c)
|
||||
if _, err := os.Stat(src); err != nil {
|
||||
return
|
||||
}
|
||||
dst := filepath.Join(trash, historyDir, filepath.Base(src))
|
||||
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err == nil {
|
||||
_ = os.Rename(src, dst)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Tags et favoris des fichiers et dossiers, et icône des dossiers, dans
|
||||
// .meta.json à la racine :
|
||||
// {"items":{"a/b.pdf":{"tags":["NSX"],"favorite":true},"a":{"icon":"server"}}}.
|
||||
// Ils suivent les renommages, déplacements et suppressions. Les fichiers y
|
||||
// gardent aussi leur auteur et leur date de création, et le dernier
|
||||
// utilisateur qui les a enregistrés (details.go).
|
||||
|
||||
const metaFile = ".meta.json"
|
||||
|
||||
const (
|
||||
// MaxTagLen borne la longueur d'un tag (en caractères).
|
||||
MaxTagLen = 40
|
||||
// MaxTags borne le nombre de tags d'un élément.
|
||||
MaxTags = 20
|
||||
)
|
||||
|
||||
type itemMeta struct {
|
||||
Tags []string `json:"tags,omitempty"`
|
||||
Favorite bool `json:"favorite,omitempty"`
|
||||
Icon string `json:"icon,omitempty"` // dossiers : nom d'icône du frontend
|
||||
|
||||
// Schémas (details.go) : création et dernier enregistrement.
|
||||
Created *time.Time `json:"created,omitempty"`
|
||||
CreatedBy string `json:"createdBy,omitempty"`
|
||||
EditedBy string `json:"editedBy,omitempty"`
|
||||
}
|
||||
|
||||
func (m itemMeta) empty() bool {
|
||||
return len(m.Tags) == 0 && !m.Favorite && m.Icon == "" && m.Created == nil && m.CreatedBy == "" && m.EditedBy == ""
|
||||
}
|
||||
|
||||
// iconName : nom d'icône accepté (le frontend affiche le dossier classique
|
||||
// pour un nom qu'il ne connaît pas).
|
||||
var iconName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,31}$`)
|
||||
|
||||
// TagCount est un tag utilisé et son nombre d'éléments.
|
||||
type TagCount struct {
|
||||
Name string `json:"name"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
// loadMeta charge .meta.json au premier accès ; appelé sous metaMu.
|
||||
func (s *Store) loadMeta() error {
|
||||
if s.meta != nil {
|
||||
return nil
|
||||
}
|
||||
var d struct {
|
||||
Items map[string]itemMeta `json:"items"`
|
||||
}
|
||||
b, err := os.ReadFile(filepath.Join(s.root, metaFile))
|
||||
switch {
|
||||
case errors.Is(err, fs.ErrNotExist):
|
||||
case err != nil:
|
||||
return err
|
||||
default:
|
||||
if err := json.Unmarshal(b, &d); err != nil {
|
||||
return fmt.Errorf("%s : %w", metaFile, err)
|
||||
}
|
||||
}
|
||||
if d.Items == nil {
|
||||
d.Items = map[string]itemMeta{}
|
||||
}
|
||||
s.meta = d.Items
|
||||
return nil
|
||||
}
|
||||
|
||||
// saveMeta écrit .meta.json ; appelé sous metaMu.
|
||||
func (s *Store) saveMeta() error {
|
||||
for k, m := range s.meta {
|
||||
if m.empty() {
|
||||
delete(s.meta, k)
|
||||
}
|
||||
}
|
||||
b, err := json.Marshal(map[string]any{"items": s.meta})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return atomicWrite(filepath.Join(s.root, metaFile), b)
|
||||
}
|
||||
|
||||
// metaSnapshot renvoie une copie des métadonnées (pour List et Search).
|
||||
func (s *Store) metaSnapshot() map[string]itemMeta {
|
||||
s.metaMu.Lock()
|
||||
defer s.metaMu.Unlock()
|
||||
if s.loadMeta() != nil {
|
||||
return map[string]itemMeta{}
|
||||
}
|
||||
out := make(map[string]itemMeta, len(s.meta))
|
||||
for k, v := range s.meta {
|
||||
out[k] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func decorate(e *Entry, meta map[string]itemMeta) {
|
||||
if m, ok := meta[e.Path]; ok {
|
||||
e.Tags, e.Favorite = m.Tags, m.Favorite
|
||||
if e.IsDir {
|
||||
e.Icon = m.Icon
|
||||
} else {
|
||||
e.EditedBy = m.EditedBy
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func normTag(t string) (string, error) {
|
||||
t = strings.Join(strings.Fields(strings.TrimPrefix(strings.TrimSpace(t), "#")), " ")
|
||||
switch {
|
||||
case t == "", !utf8.ValidString(t), strings.ContainsAny(t, ",\x00"):
|
||||
return "", fmt.Errorf("%w : tag %q", ErrInvalidPath, t)
|
||||
case utf8.RuneCountInString(t) > MaxTagLen:
|
||||
return "", fmt.Errorf("%w : tag de %d caractères max", ErrInvalidPath, MaxTagLen)
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// editMeta vérifie que chaque chemin existe puis applique edit à ses
|
||||
// métadonnées, et enregistre le tout.
|
||||
func (s *Store) editMeta(paths []string, edit func(*itemMeta) error) error {
|
||||
cs := make([]string, 0, len(paths))
|
||||
for _, p := range paths {
|
||||
c, abs, err := s.resolve(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if c == "" {
|
||||
return ErrInvalidPath
|
||||
}
|
||||
if _, err := os.Lstat(abs); err != nil {
|
||||
return mapErr(err)
|
||||
}
|
||||
cs = append(cs, c)
|
||||
}
|
||||
s.metaMu.Lock()
|
||||
defer s.metaMu.Unlock()
|
||||
if err := s.loadMeta(); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, c := range cs {
|
||||
m := s.meta[c]
|
||||
m.Tags = append([]string(nil), m.Tags...)
|
||||
if err := edit(&m); err != nil {
|
||||
return err
|
||||
}
|
||||
s.meta[c] = m
|
||||
}
|
||||
return s.saveMeta()
|
||||
}
|
||||
|
||||
// SetFavorite ajoute ou retire des éléments des favoris.
|
||||
func (s *Store) SetFavorite(paths []string, favorite bool) error {
|
||||
return s.editMeta(paths, func(m *itemMeta) error {
|
||||
m.Favorite = favorite
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// SetIcon choisit l'icône de dossiers ; icon = "" rétablit l'icône par défaut.
|
||||
func (s *Store) SetIcon(paths []string, icon string) error {
|
||||
if icon != "" && !iconName.MatchString(icon) {
|
||||
return fmt.Errorf("%w : icône %q", ErrInvalidPath, icon)
|
||||
}
|
||||
for _, p := range paths {
|
||||
_, abs, err := s.resolve(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if fi, err := os.Lstat(abs); err != nil {
|
||||
return mapErr(err)
|
||||
} else if !fi.IsDir() {
|
||||
return fmt.Errorf("%w : %q n'est pas un dossier", ErrInvalidPath, p)
|
||||
}
|
||||
}
|
||||
return s.editMeta(paths, func(m *itemMeta) error {
|
||||
m.Icon = icon
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// EditTags ajoute et retire des tags sur des éléments. Les tags sont comparés
|
||||
// sans casse ni accents ; un tag déjà utilisé garde son écriture d'origine.
|
||||
func (s *Store) EditTags(paths, add, remove []string) error {
|
||||
var adds []string
|
||||
for _, t := range add {
|
||||
n, err := normTag(t)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
adds = append(adds, n)
|
||||
}
|
||||
drop := map[string]bool{}
|
||||
for _, t := range remove {
|
||||
drop[fold(strings.TrimSpace(t))] = true
|
||||
}
|
||||
canon := map[string]string{} // écriture existante de chaque tag
|
||||
s.metaMu.Lock()
|
||||
err := s.loadMeta()
|
||||
for _, m := range s.meta {
|
||||
for _, t := range m.Tags {
|
||||
if _, ok := canon[fold(t)]; !ok {
|
||||
canon[fold(t)] = t
|
||||
}
|
||||
}
|
||||
}
|
||||
s.metaMu.Unlock()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.editMeta(paths, func(m *itemMeta) error {
|
||||
kept := m.Tags[:0]
|
||||
has := map[string]bool{}
|
||||
for _, t := range m.Tags {
|
||||
if !drop[fold(t)] && !has[fold(t)] {
|
||||
kept = append(kept, t)
|
||||
has[fold(t)] = true
|
||||
}
|
||||
}
|
||||
for _, t := range adds {
|
||||
if has[fold(t)] {
|
||||
continue
|
||||
}
|
||||
if c, ok := canon[fold(t)]; ok {
|
||||
t = c
|
||||
}
|
||||
kept = append(kept, t)
|
||||
has[fold(t)] = true
|
||||
}
|
||||
if len(kept) > MaxTags {
|
||||
return fmt.Errorf("%w : %d tags max par élément", ErrInvalidPath, MaxTags)
|
||||
}
|
||||
sort.Slice(kept, func(i, j int) bool { return fold(kept[i]) < fold(kept[j]) })
|
||||
m.Tags = kept
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// Tags liste les tags utilisés, triés par nom, avec leur nombre d'éléments.
|
||||
func (s *Store) Tags() ([]TagCount, error) {
|
||||
s.metaMu.Lock()
|
||||
defer s.metaMu.Unlock()
|
||||
if err := s.loadMeta(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
idx := map[string]int{}
|
||||
out := []TagCount{}
|
||||
for _, m := range s.meta {
|
||||
for _, t := range m.Tags {
|
||||
k := fold(t)
|
||||
if i, ok := idx[k]; ok {
|
||||
out[i].Count++
|
||||
} else {
|
||||
idx[k] = len(out)
|
||||
out = append(out, TagCount{Name: t, Count: 1})
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return fold(out[i].Name) < fold(out[j].Name) })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Les opérations suivantes accompagnent Move/Copy/Delete (au mieux).
|
||||
|
||||
func under(k, c string) bool { return k == c || strings.HasPrefix(k, c+"/") }
|
||||
|
||||
func (s *Store) moveMeta(from, to string) {
|
||||
s.metaMu.Lock()
|
||||
defer s.metaMu.Unlock()
|
||||
if s.loadMeta() != nil {
|
||||
return
|
||||
}
|
||||
moved := map[string]itemMeta{}
|
||||
for k, m := range s.meta {
|
||||
if under(k, from) {
|
||||
delete(s.meta, k)
|
||||
moved[to+k[len(from):]] = m
|
||||
}
|
||||
}
|
||||
for k, m := range moved {
|
||||
s.meta[k] = m
|
||||
}
|
||||
if len(moved) > 0 {
|
||||
_ = s.saveMeta()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Store) copyMeta(from, to string) {
|
||||
s.metaMu.Lock()
|
||||
defer s.metaMu.Unlock()
|
||||
if s.loadMeta() != nil {
|
||||
return
|
||||
}
|
||||
if m, ok := s.meta[from]; ok && len(m.Tags) > 0 {
|
||||
s.meta[to] = itemMeta{Tags: append([]string(nil), m.Tags...)} // pas le favori
|
||||
_ = s.saveMeta()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Store) removeMeta(c string) {
|
||||
s.metaMu.Lock()
|
||||
defer s.metaMu.Unlock()
|
||||
if s.loadMeta() != nil {
|
||||
return
|
||||
}
|
||||
changed := false
|
||||
for k := range s.meta {
|
||||
if under(k, c) {
|
||||
delete(s.meta, k)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
_ = s.saveMeta()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Recherche plein texte : noms des fichiers et dossiers, tags, et contenu des
|
||||
// fichiers texte de moins de 512 Ko (notes, configurations, code, journaux...).
|
||||
// Le texte de chaque fichier est lu une fois puis gardé en mémoire tant que le
|
||||
// fichier ne change pas (date et taille) : seule la première recherche lit tous
|
||||
// les fichiers texte, les suivantes ne relisent que ceux modifiés.
|
||||
|
||||
// Hit est un résultat de recherche. Snippet est l'extrait du contenu qui
|
||||
// correspond (vide si seul le nom correspond).
|
||||
type Hit struct {
|
||||
Entry
|
||||
Snippet string `json:"snippet,omitempty"`
|
||||
}
|
||||
|
||||
type indexDoc struct {
|
||||
mod time.Time
|
||||
size int64
|
||||
text string // texte extrait
|
||||
fold string // texte normalisé (minuscules, sans accents), même nombre de runes
|
||||
}
|
||||
|
||||
type textIndex struct {
|
||||
mu sync.Mutex
|
||||
docs map[string]indexDoc
|
||||
}
|
||||
|
||||
// fold met en minuscules et retire les accents des lettres latines courantes,
|
||||
// rune pour rune : la position d'une correspondance vaut pour le texte d'origine.
|
||||
func fold(s string) string {
|
||||
return strings.Map(func(r rune) rune {
|
||||
r = unicode.ToLower(r)
|
||||
if f, ok := foldMap[r]; ok {
|
||||
return f
|
||||
}
|
||||
return r
|
||||
}, s)
|
||||
}
|
||||
|
||||
var foldMap = func() map[rune]rune {
|
||||
m := map[rune]rune{}
|
||||
for base, accented := range map[rune]string{
|
||||
'a': "àáâãäåāăą", 'c': "çćĉċč", 'd': "ď", 'e': "èéêëēĕėęě", 'g': "ĝğġģ",
|
||||
'i': "ìíîïĩīĭįı", 'n': "ñńņňʼn", 'o': "òóôõöøōŏő", 'r': "ŕŗř", 's': "śŝşš",
|
||||
't': "ţťŧ", 'u': "ùúûüũūŭůűų", 'y': "ýÿŷ", 'z': "źżž",
|
||||
} {
|
||||
for _, r := range accented {
|
||||
m[r] = base
|
||||
}
|
||||
}
|
||||
return m
|
||||
}()
|
||||
|
||||
// maxIndexedSize borne la taille d'un fichier dont le contenu est indexé.
|
||||
const maxIndexedSize = 512 << 10
|
||||
|
||||
// textExts : extensions de fichiers dont le contenu est du texte indexé.
|
||||
var textExts = map[string]bool{
|
||||
".txt": true, ".md": true, ".markdown": true, ".rst": true, ".log": true, ".csv": true, ".tsv": true,
|
||||
".json": true, ".yaml": true, ".yml": true, ".toml": true, ".ini": true, ".conf": true, ".cfg": true,
|
||||
".env": true, ".xml": true, ".html": true, ".htm": true, ".css": true, ".js": true, ".mjs": true,
|
||||
".ts": true, ".tsx": true, ".jsx": true, ".py": true, ".go": true, ".rs": true, ".java": true,
|
||||
".c": true, ".h": true, ".cpp": true, ".hpp": true, ".cs": true, ".php": true, ".rb": true,
|
||||
".sh": true, ".bash": true, ".zsh": true, ".ps1": true, ".sql": true, ".tf": true, ".lua": true,
|
||||
".service": true, ".sub": true, ".srt": true, ".tex": true, ".bib": true, ".gitignore": true,
|
||||
}
|
||||
|
||||
// IsText indique si le contenu d'un fichier est indexé et prévisualisé comme du texte.
|
||||
func IsText(name string) bool {
|
||||
ext := strings.ToLower(path.Ext(name))
|
||||
if ext == "" {
|
||||
switch strings.ToLower(path.Base(name)) {
|
||||
case "dockerfile", "makefile", "readme", "license", "changelog":
|
||||
return true
|
||||
}
|
||||
}
|
||||
return textExts[ext]
|
||||
}
|
||||
|
||||
// extractText renvoie le texte d'un fichier indexable (vide si ce n'en est pas un).
|
||||
func extractText(abs string, fi fs.FileInfo) string {
|
||||
if !IsText(fi.Name()) || fi.Size() > maxIndexedSize {
|
||||
return ""
|
||||
}
|
||||
b, err := os.ReadFile(abs)
|
||||
if err != nil || !utf8.Valid(b) {
|
||||
return ""
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// content renvoie le texte indexé d'un fichier, relu seulement s'il a changé ;
|
||||
// appelé sous index.mu.
|
||||
func (s *Store) content(rel, abs string, fi fs.FileInfo) indexDoc {
|
||||
d, ok := s.index.docs[rel]
|
||||
if ok && d.mod.Equal(fi.ModTime()) && d.size == fi.Size() {
|
||||
return d
|
||||
}
|
||||
d = indexDoc{mod: fi.ModTime(), size: fi.Size()}
|
||||
d.text = extractText(abs, fi)
|
||||
d.fold = fold(d.text)
|
||||
s.index.docs[rel] = d
|
||||
return d
|
||||
}
|
||||
|
||||
// snippet renvoie la ligne du texte qui contient la position i (en octets
|
||||
// de fold), raccourcie autour de la correspondance.
|
||||
func snippet(d indexDoc, i, n int) string {
|
||||
runes := []rune(d.text)
|
||||
at := utf8.RuneCountInString(d.fold[:i])
|
||||
end := at + utf8.RuneCountInString(d.fold[i:i+n])
|
||||
lo, hi := at, end
|
||||
for lo > 0 && runes[lo-1] != '\n' {
|
||||
lo--
|
||||
}
|
||||
for hi < len(runes) && runes[hi] != '\n' {
|
||||
hi++
|
||||
}
|
||||
const ctx = 40
|
||||
pre, post := "", ""
|
||||
if at-lo > ctx {
|
||||
lo, pre = at-ctx, "…"
|
||||
}
|
||||
if hi-end > ctx {
|
||||
hi, post = end+ctx, "…"
|
||||
}
|
||||
return pre + string(runes[lo:hi]) + post
|
||||
}
|
||||
|
||||
// Filter restreint une recherche aux éléments portant un tag ou favoris.
|
||||
type Filter struct {
|
||||
Tag string
|
||||
Favorite bool
|
||||
}
|
||||
|
||||
// Search renvoie les entrées dont le nom, les tags ou, pour un fichier, le
|
||||
// contenu contiennent tous les mots de q (casse et accents ignorés), et qui
|
||||
// passent le filtre. Les correspondances sur le nom viennent en premier.
|
||||
// q peut être vide si un filtre est donné.
|
||||
func (s *Store) Search(q string, f Filter, limit int) ([]Hit, error) {
|
||||
terms := strings.Fields(fold(q))
|
||||
tag := fold(strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(f.Tag), "#")))
|
||||
if len(terms) == 0 && tag == "" && !f.Favorite {
|
||||
return []Hit{}, nil
|
||||
}
|
||||
meta := s.metaSnapshot()
|
||||
s.index.mu.Lock()
|
||||
defer s.index.mu.Unlock()
|
||||
if s.index.docs == nil {
|
||||
s.index.docs = map[string]indexDoc{}
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
var byName, byContent []Hit
|
||||
err := filepath.WalkDir(s.root, func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil || p == s.root {
|
||||
return nil
|
||||
}
|
||||
if strings.HasPrefix(d.Name(), ".") {
|
||||
if d.IsDir() {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if d.Type()&fs.ModeSymlink != 0 || (!d.IsDir() && !d.Type().IsRegular()) {
|
||||
return nil
|
||||
}
|
||||
fi, err := d.Info()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
rel, err := filepath.Rel(s.root, p)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
rel = filepath.ToSlash(rel)
|
||||
hit := Hit{Entry: toEntry(rel, fi)}
|
||||
decorate(&hit.Entry, meta)
|
||||
if f.Favorite && !hit.Favorite {
|
||||
return nil
|
||||
}
|
||||
tags := fold(strings.Join(hit.Tags, "\n"))
|
||||
if tag != "" && !strings.Contains("\n"+tags+"\n", "\n"+tag+"\n") {
|
||||
return nil
|
||||
}
|
||||
name := fold(d.Name()) + "\n" + tags
|
||||
var doc indexDoc
|
||||
if !d.IsDir() {
|
||||
seen[rel] = true
|
||||
if len(terms) > 0 {
|
||||
doc = s.content(rel, p, fi)
|
||||
}
|
||||
}
|
||||
inName := true
|
||||
for _, t := range terms {
|
||||
if strings.Contains(name, t) {
|
||||
continue
|
||||
}
|
||||
inName = false
|
||||
i := strings.Index(doc.fold, t)
|
||||
if i < 0 {
|
||||
return nil
|
||||
}
|
||||
if hit.Snippet == "" {
|
||||
hit.Snippet = snippet(doc, i, len(t))
|
||||
}
|
||||
}
|
||||
if inName {
|
||||
byName = append(byName, hit)
|
||||
} else {
|
||||
byContent = append(byContent, hit)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for rel := range s.index.docs {
|
||||
if !seen[rel] {
|
||||
delete(s.index.docs, rel) // fichier supprimé ou déplacé
|
||||
}
|
||||
}
|
||||
out := append(byName, byContent...)
|
||||
if len(out) > limit {
|
||||
out = out[:limit]
|
||||
}
|
||||
if out == nil {
|
||||
out = []Hit{}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/draw"
|
||||
"image/png"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Paramètres partagés par tous les navigateurs : .settings.json et .logo.png à
|
||||
// la racine. Les valeurs que l'administrateur n'a pas modifiées viennent des
|
||||
// variables d'environnement (SettingsDefaults).
|
||||
|
||||
const (
|
||||
settingsFile = ".settings.json"
|
||||
logoFile = ".logo.png"
|
||||
|
||||
// LogoSize est le côté du logo enregistré (carré, affiché en rond).
|
||||
LogoSize = 64
|
||||
// MaxLogoUpload borne la taille d'un PNG envoyé avant redimensionnement.
|
||||
MaxLogoUpload = 5 << 20
|
||||
// MaxTitleLen borne la longueur du titre (en caractères).
|
||||
MaxTitleLen = 80
|
||||
// MaxTrashDays borne la durée de conservation de la corbeille (en jours).
|
||||
MaxTrashDays = 3650
|
||||
// MaxQuotaMB borne le quota par utilisateur (Mo).
|
||||
MaxQuotaMB = 100 << 20
|
||||
|
||||
maxLogoSide = 8192 // protège contre les « bombes » de décompression
|
||||
)
|
||||
|
||||
// ErrInvalidImage signale un logo illisible ou hors limites.
|
||||
var ErrInvalidImage = errors.New("image invalide")
|
||||
|
||||
// Modes d'inscription (Settings.Registration).
|
||||
const (
|
||||
RegClosed = "closed" // pas d'inscription : l'administrateur crée les comptes
|
||||
RegApproval = "approval" // inscription libre, compte à valider par un administrateur
|
||||
RegOpen = "open" // inscription libre, compte actif tout de suite
|
||||
)
|
||||
|
||||
// ValidRegistration indique si m est un mode d'inscription connu.
|
||||
func ValidRegistration(m string) bool { return m == RegClosed || m == RegApproval || m == RegOpen }
|
||||
|
||||
// SettingsDefaults : valeurs des paramètres tant qu'ils n'ont pas été modifiés.
|
||||
type SettingsDefaults struct {
|
||||
Registration string // closed, approval ou open
|
||||
QuotaMB int64 // quota de l'espace personnel par utilisateur (0 : illimité)
|
||||
CommonReadonly bool // arborescence commune en lecture seule pour les non-administrateurs
|
||||
TrashDays int
|
||||
}
|
||||
|
||||
// DefaultSettings : inscription fermée, pas de quota, commun ouvert en écriture.
|
||||
var DefaultSettings = SettingsDefaults{Registration: RegClosed}
|
||||
|
||||
// Settings est l'état exposé au client. Logo vaut "" sans logo, sinon une
|
||||
// version (date) à ajouter à l'URL pour invalider le cache navigateur.
|
||||
// TrashDays : durée de conservation de la corbeille (0 : jusqu'à ce qu'on la
|
||||
// vide). QuotaMB : quota de l'espace personnel (0 : illimité).
|
||||
type Settings struct {
|
||||
Title string `json:"title"`
|
||||
Logo string `json:"logo"`
|
||||
TrashDays int `json:"trashDays"`
|
||||
Registration string `json:"registration"`
|
||||
QuotaMB int64 `json:"quotaMB"`
|
||||
CommonReadonly bool `json:"commonReadonly"`
|
||||
}
|
||||
|
||||
type settingsDisk struct {
|
||||
Title string `json:"title"`
|
||||
TrashDays *int `json:"trashDays,omitempty"`
|
||||
Registration *string `json:"registration,omitempty"`
|
||||
QuotaMB *int64 `json:"quotaMB,omitempty"`
|
||||
CommonReadonly *bool `json:"commonReadonly,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Store) readSettingsDisk() (settingsDisk, error) {
|
||||
var d settingsDisk
|
||||
b, err := os.ReadFile(filepath.Join(s.root, settingsFile))
|
||||
switch {
|
||||
case errors.Is(err, fs.ErrNotExist):
|
||||
case err != nil:
|
||||
return d, err
|
||||
default:
|
||||
if err := json.Unmarshal(b, &d); err != nil {
|
||||
return d, fmt.Errorf("%s : %w", settingsFile, err)
|
||||
}
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// updateSettings applique edit au fichier de paramètres (lecture, modification,
|
||||
// écriture atomique) sous le verrou du Store.
|
||||
func (s *Store) updateSettings(edit func(*settingsDisk)) (Settings, error) {
|
||||
s.settingsMu.Lock()
|
||||
defer s.settingsMu.Unlock()
|
||||
d, err := s.readSettingsDisk()
|
||||
if err != nil {
|
||||
return Settings{}, err
|
||||
}
|
||||
edit(&d)
|
||||
b, err := json.Marshal(d)
|
||||
if err != nil {
|
||||
return Settings{}, err
|
||||
}
|
||||
if err := atomicWrite(filepath.Join(s.root, settingsFile), b); err != nil {
|
||||
return Settings{}, err
|
||||
}
|
||||
return s.readSettings()
|
||||
}
|
||||
|
||||
// ReadSettings renvoie les paramètres courants (valeurs par défaut si absents).
|
||||
func (s *Store) ReadSettings() (Settings, error) {
|
||||
s.settingsMu.Lock()
|
||||
defer s.settingsMu.Unlock()
|
||||
return s.readSettings()
|
||||
}
|
||||
|
||||
func (s *Store) readSettings() (Settings, error) {
|
||||
d, err := s.readSettingsDisk()
|
||||
if err != nil {
|
||||
return Settings{}, err
|
||||
}
|
||||
def := s.Defaults
|
||||
if !ValidRegistration(def.Registration) {
|
||||
def.Registration = RegClosed
|
||||
}
|
||||
st := Settings{Title: d.Title, TrashDays: def.TrashDays, Registration: def.Registration,
|
||||
QuotaMB: def.QuotaMB, CommonReadonly: def.CommonReadonly}
|
||||
if d.TrashDays != nil {
|
||||
st.TrashDays = *d.TrashDays
|
||||
}
|
||||
if d.Registration != nil && ValidRegistration(*d.Registration) {
|
||||
st.Registration = *d.Registration
|
||||
}
|
||||
if d.QuotaMB != nil {
|
||||
st.QuotaMB = *d.QuotaMB
|
||||
}
|
||||
if d.CommonReadonly != nil {
|
||||
st.CommonReadonly = *d.CommonReadonly
|
||||
}
|
||||
if fi, err := os.Stat(filepath.Join(s.root, logoFile)); err == nil {
|
||||
st.Logo = strconv.FormatInt(fi.ModTime().UnixNano(), 36)
|
||||
}
|
||||
return st, nil
|
||||
}
|
||||
|
||||
// WriteTrashDays règle la purge automatique de la corbeille (0 : désactivée).
|
||||
func (s *Store) WriteTrashDays(days int) (Settings, error) {
|
||||
if days < 0 || days > MaxTrashDays {
|
||||
return Settings{}, fmt.Errorf("%w : durée de 0 à %d jours", ErrInvalidPath, MaxTrashDays)
|
||||
}
|
||||
return s.updateSettings(func(d *settingsDisk) { d.TrashDays = &days })
|
||||
}
|
||||
|
||||
// WriteRegistration choisit le mode d'inscription (closed, approval, open).
|
||||
func (s *Store) WriteRegistration(mode string) (Settings, error) {
|
||||
if !ValidRegistration(mode) {
|
||||
return Settings{}, fmt.Errorf("%w : mode d'inscription %q", ErrInvalidPath, mode)
|
||||
}
|
||||
return s.updateSettings(func(d *settingsDisk) { d.Registration = &mode })
|
||||
}
|
||||
|
||||
// WriteQuota règle le quota de l'espace personnel en Mo (0 : illimité).
|
||||
func (s *Store) WriteQuota(mb int64) (Settings, error) {
|
||||
if mb < 0 || mb > MaxQuotaMB {
|
||||
return Settings{}, fmt.Errorf("%w : quota invalide", ErrInvalidPath)
|
||||
}
|
||||
return s.updateSettings(func(d *settingsDisk) { d.QuotaMB = &mb })
|
||||
}
|
||||
|
||||
// WriteCommonReadonly règle l'accès en écriture à l'arborescence commune.
|
||||
func (s *Store) WriteCommonReadonly(ro bool) (Settings, error) {
|
||||
return s.updateSettings(func(d *settingsDisk) { d.CommonReadonly = &ro })
|
||||
}
|
||||
|
||||
// WriteTitle enregistre le titre affiché ("" = titre par défaut).
|
||||
func (s *Store) WriteTitle(title string) (Settings, error) {
|
||||
title = strings.TrimSpace(title)
|
||||
if !utf8.ValidString(title) || strings.ContainsAny(title, "\r\n\x00") {
|
||||
return Settings{}, fmt.Errorf("%w : titre", ErrInvalidPath)
|
||||
}
|
||||
if utf8.RuneCountInString(title) > MaxTitleLen {
|
||||
return Settings{}, fmt.Errorf("%w : titre de %d caractères max", ErrInvalidPath, MaxTitleLen)
|
||||
}
|
||||
return s.updateSettings(func(d *settingsDisk) { d.Title = title })
|
||||
}
|
||||
|
||||
// ReadLogo renvoie le logo PNG 64x64, ou ErrNotFound.
|
||||
func (s *Store) ReadLogo() ([]byte, error) {
|
||||
b, err := os.ReadFile(filepath.Join(s.root, logoFile))
|
||||
return b, mapErr(err)
|
||||
}
|
||||
|
||||
// WriteLogo décode un PNG, le recadre au centre en carré, le ramène à
|
||||
// LogoSize x LogoSize et l'enregistre (ré-encodé : aucune donnée annexe du
|
||||
// fichier d'origine n'est conservée).
|
||||
func (s *Store) WriteLogo(data []byte) (Settings, error) {
|
||||
cfg, err := png.DecodeConfig(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return Settings{}, fmt.Errorf("%w : PNG attendu", ErrInvalidImage)
|
||||
}
|
||||
if cfg.Width < 1 || cfg.Height < 1 || cfg.Width > maxLogoSide || cfg.Height > maxLogoSide {
|
||||
return Settings{}, fmt.Errorf("%w : %dx%d px max", ErrInvalidImage, maxLogoSide, maxLogoSide)
|
||||
}
|
||||
img, err := png.Decode(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return Settings{}, fmt.Errorf("%w : PNG illisible", ErrInvalidImage)
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, squareResize(img, LogoSize)); err != nil {
|
||||
return Settings{}, err
|
||||
}
|
||||
if err := atomicWrite(filepath.Join(s.root, logoFile), buf.Bytes()); err != nil {
|
||||
return Settings{}, err
|
||||
}
|
||||
return s.ReadSettings()
|
||||
}
|
||||
|
||||
// DeleteLogo supprime le logo (sans erreur s'il est absent).
|
||||
func (s *Store) DeleteLogo() (Settings, error) {
|
||||
if err := os.Remove(filepath.Join(s.root, logoFile)); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return Settings{}, err
|
||||
}
|
||||
return s.ReadSettings()
|
||||
}
|
||||
|
||||
// squareResize recadre img au centre (carré) puis le rééchantillonne en n x n
|
||||
// par moyenne de surface (filtre « boîte » pondéré), en alpha prémultiplié
|
||||
// pour éviter les franges sombres sur les bords transparents.
|
||||
func squareResize(img image.Image, n int) *image.RGBA {
|
||||
b := img.Bounds()
|
||||
side := min(b.Dx(), b.Dy())
|
||||
crop := image.Rect(0, 0, side, side).Add(b.Min).
|
||||
Add(image.Pt((b.Dx()-side)/2, (b.Dy()-side)/2))
|
||||
src := image.NewRGBA(image.Rect(0, 0, side, side))
|
||||
draw.Draw(src, src.Bounds(), img, crop.Min, draw.Src)
|
||||
|
||||
w := boxWeights(side, n)
|
||||
dst := image.NewRGBA(image.Rect(0, 0, n, n))
|
||||
for dy := 0; dy < n; dy++ {
|
||||
for dx := 0; dx < n; dx++ {
|
||||
var acc [4]float64
|
||||
var total float64
|
||||
for _, wy := range w[dy] {
|
||||
row := wy.i * src.Stride
|
||||
for _, wx := range w[dx] {
|
||||
k := wy.w * wx.w
|
||||
p := src.Pix[row+wx.i*4:]
|
||||
for c := range acc {
|
||||
acc[c] += k * float64(p[c])
|
||||
}
|
||||
total += k
|
||||
}
|
||||
}
|
||||
o := dst.PixOffset(dx, dy)
|
||||
for c := range acc {
|
||||
dst.Pix[o+c] = uint8(acc[c]/total + 0.5)
|
||||
}
|
||||
}
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
||||
type weight struct {
|
||||
i int
|
||||
w float64
|
||||
}
|
||||
|
||||
// boxWeights calcule, pour chaque pixel cible, les pixels source qu'il couvre
|
||||
// et la fraction couverte. Fonctionne aussi en agrandissement (côté < n).
|
||||
func boxWeights(side, n int) [][]weight {
|
||||
scale := float64(side) / float64(n)
|
||||
out := make([][]weight, n)
|
||||
for d := range out {
|
||||
lo, hi := float64(d)*scale, float64(d+1)*scale
|
||||
for i := int(lo); i < side && float64(i) < hi; i++ {
|
||||
w := min(hi, float64(i+1)) - max(lo, float64(i))
|
||||
if w > 0 {
|
||||
out[d] = append(out[d], weight{i, w})
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/pbkdf2"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Partage en lecture seule : un lien /s/<jeton> donne accès à un fichier ou à
|
||||
// un dossier (navigation et téléchargement) sans authentification, avec un mot
|
||||
// de passe facultatif. Le jeton est <id>.<signature> : id aléatoire (128 bits)
|
||||
// et HMAC-SHA256 de l'id par la clé du serveur. Un lien est valide si sa
|
||||
// signature est correcte, si son id figure dans .shares.json (révocation
|
||||
// lien par lien) et s'il n'a pas expiré. Changer de clé (RevokeAllShares)
|
||||
// invalide tous les liens d'un coup.
|
||||
//
|
||||
// Clé : SHARE_SECRET si défini, sinon .share-secret (générée au premier
|
||||
// partage, 0600). Le lien suit l'élément s'il est renommé ou déplacé et
|
||||
// disparaît s'il est supprimé.
|
||||
|
||||
const (
|
||||
sharesFile = ".shares.json"
|
||||
secretFile = ".share-secret"
|
||||
shareIDLen = 16 // octets aléatoires
|
||||
shareSigLen = 16 // octets de HMAC conservés
|
||||
)
|
||||
|
||||
// Share décrit un lien de partage.
|
||||
type Share struct {
|
||||
ID string `json:"id"`
|
||||
Token string `json:"token"`
|
||||
Path string `json:"path"`
|
||||
IsDir bool `json:"isDir"`
|
||||
Created time.Time `json:"created"`
|
||||
Expires *time.Time `json:"expires,omitempty"`
|
||||
Protected bool `json:"protected,omitempty"` // protégé par un mot de passe
|
||||
Downloads int `json:"downloads,omitempty"` // téléchargements depuis le lien
|
||||
|
||||
pw string // empreinte du mot de passe (jamais exposée)
|
||||
}
|
||||
|
||||
// ShareOptions règle un nouveau lien : durée de validité (0 : sans expiration)
|
||||
// et mot de passe facultatif.
|
||||
type ShareOptions struct {
|
||||
TTL time.Duration
|
||||
Password string
|
||||
}
|
||||
|
||||
type shareDisk struct {
|
||||
Path string `json:"path"`
|
||||
Created time.Time `json:"created"`
|
||||
Expires *time.Time `json:"expires,omitempty"`
|
||||
Password string `json:"pw,omitempty"`
|
||||
Downloads int `json:"downloads,omitempty"`
|
||||
}
|
||||
|
||||
var b64 = base64.RawURLEncoding
|
||||
|
||||
// SetShareSecret impose la clé de signature (variable SHARE_SECRET).
|
||||
func (s *Store) SetShareSecret(secret string) {
|
||||
s.sharesMu.Lock()
|
||||
defer s.sharesMu.Unlock()
|
||||
s.shareKey = []byte(secret)
|
||||
s.fixedKey = true
|
||||
}
|
||||
|
||||
// key renvoie la clé de signature, créée au besoin ; appelé sous sharesMu.
|
||||
func (s *Store) key() ([]byte, error) {
|
||||
if s.keyFrom != nil {
|
||||
return s.keyFrom.lockedKey()
|
||||
}
|
||||
if s.shareKey != nil {
|
||||
return s.shareKey, nil
|
||||
}
|
||||
p := filepath.Join(s.root, secretFile)
|
||||
b, err := os.ReadFile(p)
|
||||
if err == nil {
|
||||
if k, err := hex.DecodeString(strings.TrimSpace(string(b))); err == nil && len(k) >= 32 {
|
||||
s.shareKey = k
|
||||
return k, nil
|
||||
}
|
||||
} else if !errors.Is(err, fs.ErrNotExist) {
|
||||
return nil, err
|
||||
}
|
||||
return s.newKey()
|
||||
}
|
||||
|
||||
// lockedKey renvoie la clé de signature pour un espace personnel.
|
||||
func (s *Store) lockedKey() ([]byte, error) {
|
||||
s.sharesMu.Lock()
|
||||
defer s.sharesMu.Unlock()
|
||||
return s.key()
|
||||
}
|
||||
|
||||
func (s *Store) newKey() ([]byte, error) {
|
||||
k := make([]byte, 32)
|
||||
if _, err := rand.Read(k); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p := filepath.Join(s.root, secretFile)
|
||||
if err := atomicWrite(p, []byte(hex.EncodeToString(k)+"\n")); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = os.Chmod(p, 0o600)
|
||||
s.shareKey = k
|
||||
return k, nil
|
||||
}
|
||||
|
||||
func sign(key []byte, id string) string {
|
||||
m := hmac.New(sha256.New, key)
|
||||
m.Write([]byte("upandown-share:" + id))
|
||||
return b64.EncodeToString(m.Sum(nil)[:shareSigLen])
|
||||
}
|
||||
|
||||
func (s *Store) readShares() (map[string]shareDisk, error) {
|
||||
out := map[string]shareDisk{}
|
||||
b, err := os.ReadFile(filepath.Join(s.root, sharesFile))
|
||||
switch {
|
||||
case errors.Is(err, fs.ErrNotExist):
|
||||
return out, nil
|
||||
case err != nil:
|
||||
return nil, err
|
||||
}
|
||||
var d struct {
|
||||
Links map[string]shareDisk `json:"links"`
|
||||
}
|
||||
if err := json.Unmarshal(b, &d); err != nil {
|
||||
return nil, fmt.Errorf("%s : %w", sharesFile, err)
|
||||
}
|
||||
if d.Links != nil {
|
||||
out = d.Links
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *Store) writeShares(m map[string]shareDisk) error {
|
||||
b, err := json.Marshal(map[string]any{"links": m})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p := filepath.Join(s.root, sharesFile)
|
||||
if err := atomicWrite(p, b); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Chmod(p, 0o600)
|
||||
}
|
||||
|
||||
// editShares applique edit à la liste des liens sous verrou ; edit renvoie
|
||||
// false si rien n'a changé (pas d'écriture).
|
||||
func (s *Store) editShares(edit func(map[string]shareDisk) (bool, error)) error {
|
||||
s.sharesMu.Lock()
|
||||
defer s.sharesMu.Unlock()
|
||||
m, err := s.readShares()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
changed, err := edit(m)
|
||||
if err != nil || !changed {
|
||||
return err
|
||||
}
|
||||
return s.writeShares(m)
|
||||
}
|
||||
|
||||
func (s *Store) toShare(key []byte, id string, d shareDisk) Share {
|
||||
sh := Share{ID: id, Token: id + "." + sign(key, id), Path: d.Path, Created: d.Created, Expires: d.Expires,
|
||||
Protected: d.Password != "", Downloads: d.Downloads, pw: d.Password}
|
||||
if fi, err := os.Stat(absOf(s, d.Path)); err == nil {
|
||||
sh.IsDir = fi.IsDir()
|
||||
}
|
||||
return sh
|
||||
}
|
||||
|
||||
// MaxPasswordLen borne le mot de passe d'un lien de partage.
|
||||
const MaxPasswordLen = 200
|
||||
|
||||
// CreateShare crée un lien de partage d'un fichier ou d'un dossier.
|
||||
func (s *Store) CreateShare(rel string, o ShareOptions) (Share, error) {
|
||||
c, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return Share{}, err
|
||||
}
|
||||
if c == "" {
|
||||
return Share{}, ErrInvalidPath
|
||||
}
|
||||
if fi, err := os.Lstat(abs); err != nil {
|
||||
return Share{}, mapErr(err)
|
||||
} else if !fi.IsDir() && !fi.Mode().IsRegular() {
|
||||
return Share{}, ErrNotFound
|
||||
}
|
||||
if o.TTL < 0 || len(o.Password) > MaxPasswordLen {
|
||||
return Share{}, fmt.Errorf("%w : durée ou mot de passe", ErrInvalidPath)
|
||||
}
|
||||
raw := make([]byte, shareIDLen)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return Share{}, err
|
||||
}
|
||||
id := b64.EncodeToString(raw)
|
||||
d := shareDisk{Path: c, Created: time.Now().UTC().Truncate(time.Second)}
|
||||
if o.TTL > 0 {
|
||||
e := d.Created.Add(o.TTL)
|
||||
d.Expires = &e
|
||||
}
|
||||
if o.Password != "" {
|
||||
d.Password = HashSharePassword(o.Password)
|
||||
}
|
||||
var out Share
|
||||
err = s.editShares(func(m map[string]shareDisk) (bool, error) {
|
||||
key, err := s.key()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
m[id] = d
|
||||
out = s.toShare(key, id, d)
|
||||
return true, nil
|
||||
})
|
||||
return out, err
|
||||
}
|
||||
|
||||
// Shares liste les liens (d'un schéma, ou tous si rel est vide), les plus
|
||||
// récents en premier. Les liens expirés sont purgés au passage.
|
||||
func (s *Store) Shares(rel string) ([]Share, error) {
|
||||
c := ""
|
||||
if rel != "" {
|
||||
var err error
|
||||
if c, _, err = s.resolve(rel); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
out := []Share{}
|
||||
err := s.editShares(func(m map[string]shareDisk) (bool, error) {
|
||||
key, err := s.key()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
purged := false
|
||||
for id, d := range m {
|
||||
if d.Expires != nil && time.Now().After(*d.Expires) {
|
||||
delete(m, id)
|
||||
purged = true
|
||||
} else if c == "" || d.Path == c {
|
||||
out = append(out, s.toShare(key, id, d))
|
||||
}
|
||||
}
|
||||
return purged, nil
|
||||
})
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Created.After(out[j].Created) })
|
||||
return out, err
|
||||
}
|
||||
|
||||
// RevokeShare supprime un lien.
|
||||
func (s *Store) RevokeShare(id string) error {
|
||||
return s.editShares(func(m map[string]shareDisk) (bool, error) {
|
||||
if _, ok := m[id]; !ok {
|
||||
return false, ErrNotFound
|
||||
}
|
||||
delete(m, id)
|
||||
return true, nil
|
||||
})
|
||||
}
|
||||
|
||||
// RevokeAllShares supprime tous les liens et change la clé de signature
|
||||
// (sauf si elle est imposée par SHARE_SECRET ou reprise du Store principal).
|
||||
func (s *Store) RevokeAllShares() error {
|
||||
return s.editShares(func(m map[string]shareDisk) (bool, error) {
|
||||
clear(m)
|
||||
if !s.fixedKey && s.keyFrom == nil {
|
||||
if _, err := s.newKey(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
})
|
||||
}
|
||||
|
||||
// ResolveShare vérifie un jeton et renvoie le lien. Toute anomalie (jeton
|
||||
// mal formé, signature fausse, lien révoqué ou expiré) donne ErrNotFound.
|
||||
func (s *Store) ResolveShare(token string) (Share, error) {
|
||||
id, sig, ok := strings.Cut(token, ".")
|
||||
if !ok || len(id) != b64.EncodedLen(shareIDLen) || len(sig) != b64.EncodedLen(shareSigLen) {
|
||||
return Share{}, ErrNotFound
|
||||
}
|
||||
s.sharesMu.Lock()
|
||||
defer s.sharesMu.Unlock()
|
||||
key, err := s.key()
|
||||
if err != nil {
|
||||
return Share{}, err
|
||||
}
|
||||
if subtle.ConstantTimeCompare([]byte(sig), []byte(sign(key, id))) != 1 {
|
||||
return Share{}, ErrNotFound
|
||||
}
|
||||
m, err := s.readShares()
|
||||
if err != nil {
|
||||
return Share{}, err
|
||||
}
|
||||
d, ok := m[id]
|
||||
if !ok || (d.Expires != nil && time.Now().After(*d.Expires)) {
|
||||
return Share{}, ErrNotFound
|
||||
}
|
||||
return s.toShare(key, id, d), nil
|
||||
}
|
||||
|
||||
// CheckPassword vérifie le mot de passe d'un lien protégé.
|
||||
func (sh Share) CheckPassword(pw string) bool {
|
||||
return sh.pw != "" && CheckSharePassword(sh.pw, pw)
|
||||
}
|
||||
|
||||
// UnlockCookie renvoie la valeur du cookie qui prouve que le mot de passe du
|
||||
// lien a été saisi : HMAC de l'id et de l'empreinte du mot de passe.
|
||||
func (s *Store) UnlockCookie(sh Share) (string, error) {
|
||||
s.sharesMu.Lock()
|
||||
defer s.sharesMu.Unlock()
|
||||
key, err := s.key()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
m := hmac.New(sha256.New, key)
|
||||
m.Write([]byte("upandown-unlock:" + sh.ID + ":" + sh.pw))
|
||||
return b64.EncodeToString(m.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// CountDownload incrémente le compteur de téléchargements d'un lien.
|
||||
func (s *Store) CountDownload(id string) {
|
||||
_ = s.editShares(func(m map[string]shareDisk) (bool, error) {
|
||||
d, ok := m[id]
|
||||
if !ok {
|
||||
return false, nil
|
||||
}
|
||||
d.Downloads++
|
||||
m[id] = d
|
||||
return true, nil
|
||||
})
|
||||
}
|
||||
|
||||
// SharedPath joint le chemin partagé et un sous-chemin demandé par le visiteur
|
||||
// du lien (vide : l'élément partagé lui-même). Un lien vers un fichier n'accepte
|
||||
// pas de sous-chemin ; ".." et les noms cachés sont refusés.
|
||||
func SharedPath(sh Share, sub string) (string, error) {
|
||||
if sub == "" {
|
||||
return sh.Path, nil
|
||||
}
|
||||
if !sh.IsDir {
|
||||
return "", ErrNotFound
|
||||
}
|
||||
c, err := Clean(sub)
|
||||
if err != nil || c == "" {
|
||||
return "", ErrNotFound
|
||||
}
|
||||
return sh.Path + "/" + c, nil
|
||||
}
|
||||
|
||||
// Les opérations suivantes accompagnent Move/Delete.
|
||||
|
||||
func (s *Store) moveShares(from, to string) {
|
||||
_ = s.editShares(func(m map[string]shareDisk) (bool, error) {
|
||||
changed := false
|
||||
for id, d := range m {
|
||||
if under(d.Path, from) {
|
||||
d.Path = to + d.Path[len(from):]
|
||||
m[id] = d
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed, nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Store) removeShares(c string) {
|
||||
_ = s.editShares(func(m map[string]shareDisk) (bool, error) {
|
||||
changed := false
|
||||
for id, d := range m {
|
||||
if under(d.Path, c) {
|
||||
delete(m, id)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed, nil
|
||||
})
|
||||
}
|
||||
|
||||
// --- Mots de passe de liens -----------------------------------------------------------
|
||||
|
||||
const sharePwIter = 100_000
|
||||
|
||||
// HashSharePassword dérive une empreinte PBKDF2-SHA256 « iter$sel$hash ».
|
||||
func HashSharePassword(pw string) string {
|
||||
salt := make([]byte, 16)
|
||||
_, _ = rand.Read(salt)
|
||||
return derive(pw, salt, sharePwIter)
|
||||
}
|
||||
|
||||
func derive(pw string, salt []byte, iter int) string {
|
||||
h, err := pbkdf2.Key(sha256.New, pw, salt, iter, 32)
|
||||
if err != nil {
|
||||
panic(err) // paramètres constants valides
|
||||
}
|
||||
return fmt.Sprintf("%d$%s$%s", iter, b64.EncodeToString(salt), b64.EncodeToString(h))
|
||||
}
|
||||
|
||||
// CheckSharePassword compare un mot de passe à une empreinte HashSharePassword.
|
||||
func CheckSharePassword(hash, pw string) bool {
|
||||
parts := strings.Split(hash, "$")
|
||||
if len(parts) != 3 {
|
||||
return false
|
||||
}
|
||||
iter, err := strconv.Atoi(parts[0])
|
||||
if err != nil || iter < 1 || iter > 10_000_000 {
|
||||
return false
|
||||
}
|
||||
salt, err := b64.DecodeString(parts[1])
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return subtle.ConstantTimeCompare([]byte(derive(pw, salt, iter)), []byte(hash)) == 1
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,290 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func newSpaces(t *testing.T) *Spaces {
|
||||
t.Helper()
|
||||
return NewSpaces(newStore(t))
|
||||
}
|
||||
|
||||
func space(t *testing.T, sp *Spaces, id string, admin bool) *Space {
|
||||
t.Helper()
|
||||
u, err := sp.For(id, admin)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
func uput(t *testing.T, u *Space, p, content string) Entry {
|
||||
t.Helper()
|
||||
e, err := u.Put(p, strings.NewReader(content), int64(len(content)), PutOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("Put(%s) : %v", p, err)
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
func TestPersonalSpaceIsPrivate(t *testing.T) {
|
||||
sp := newSpaces(t)
|
||||
alice, bob := space(t, sp, "alice", false), space(t, sp, "bob", false)
|
||||
uput(t, alice, ".perso/secret.txt", "S")
|
||||
uput(t, alice, "commun.txt", "C")
|
||||
if es, _ := bob.List(".perso"); len(es) != 0 {
|
||||
t.Errorf("bob voit l'espace d'alice : %v", es)
|
||||
}
|
||||
if es, _ := alice.List(".perso"); len(es) != 1 || es[0].Path != ".perso/secret.txt" {
|
||||
t.Errorf("alice : %v", es)
|
||||
}
|
||||
root, _ := bob.List("")
|
||||
var specials []string
|
||||
for _, e := range root {
|
||||
if e.Special != "" {
|
||||
specials = append(specials, e.Special)
|
||||
}
|
||||
}
|
||||
if len(specials) != 3 {
|
||||
t.Errorf("dossiers virtuels = %v", specials)
|
||||
}
|
||||
if hits, _ := bob.Search("secret", Filter{}, 10); len(hits) != 0 {
|
||||
t.Errorf("recherche : %v", hits)
|
||||
}
|
||||
// Chemins qui tentent d'atteindre les espaces d'autrui.
|
||||
for _, p := range []string{".users/alice/home/secret.txt", "../.users/alice/home/secret.txt"} {
|
||||
if _, _, err := bob.Open(p); err == nil {
|
||||
t.Errorf("accès à %s", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMoveBetweenSpacesAndFavorites(t *testing.T) {
|
||||
sp := newSpaces(t)
|
||||
alice := space(t, sp, "alice", false)
|
||||
uput(t, alice, "doc.pdf", "PDF")
|
||||
if err := alice.EditTags([]string{"doc.pdf"}, []string{"important"}, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := alice.SetFavorite([]string{"doc.pdf"}, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
favs, _ := alice.List(".favoris")
|
||||
if len(favs) != 1 || favs[0].Path != "doc.pdf" || favs[0].Broken {
|
||||
t.Fatalf("favoris = %+v", favs)
|
||||
}
|
||||
// Déplacement commun -> personnel : le favori suit, les tags aussi.
|
||||
if _, err := alice.Move("doc.pdf", ".perso/doc.pdf"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
favs, _ = alice.List(".favoris")
|
||||
if len(favs) != 1 || favs[0].Path != ".perso/doc.pdf" || favs[0].Broken {
|
||||
t.Errorf("favori après déplacement = %+v", favs)
|
||||
}
|
||||
es, _ := alice.List(".perso")
|
||||
if len(es) != 1 || len(es[0].Tags) != 1 {
|
||||
t.Errorf("tags après déplacement : %+v", es)
|
||||
}
|
||||
// Un dossier peut être favori.
|
||||
if _, err := alice.Mkdir("projets"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := alice.SetFavorite([]string{"projets"}, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if favs, _ = alice.List(".favoris"); len(favs) != 2 {
|
||||
t.Errorf("favoris dossier : %+v", favs)
|
||||
}
|
||||
// Suppression de l'original : le favori disparaît.
|
||||
if err := alice.Delete(".perso/doc.pdf", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if favs, _ = alice.List(".favoris"); len(favs) != 1 {
|
||||
t.Errorf("favori d'un fichier supprimé : %+v", favs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommonReadonly(t *testing.T) {
|
||||
sp := newSpaces(t)
|
||||
admin, user := space(t, sp, "root", true), space(t, sp, "bob", false)
|
||||
uput(t, admin, "regles.txt", "R")
|
||||
if _, err := sp.Main.WriteCommonReadonly(true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := user.Put("x.txt", strings.NewReader("x"), 1, PutOptions{}); !errors.Is(err, ErrForbidden) {
|
||||
t.Errorf("écriture : %v", err)
|
||||
}
|
||||
if _, err := user.Mkdir("d"); !errors.Is(err, ErrForbidden) {
|
||||
t.Errorf("Mkdir : %v", err)
|
||||
}
|
||||
if err := user.Delete("regles.txt", false); !errors.Is(err, ErrForbidden) {
|
||||
t.Errorf("Delete : %v", err)
|
||||
}
|
||||
if _, err := user.Move("regles.txt", "r2.txt"); !errors.Is(err, ErrForbidden) {
|
||||
t.Errorf("Move : %v", err)
|
||||
}
|
||||
if err := user.EditTags([]string{"regles.txt"}, []string{"t"}, nil); !errors.Is(err, ErrForbidden) {
|
||||
t.Errorf("EditTags : %v", err)
|
||||
}
|
||||
if _, err := user.Copy("regles.txt", "copie.txt"); !errors.Is(err, ErrForbidden) {
|
||||
t.Errorf("Copy : %v", err)
|
||||
}
|
||||
// Lecture et espace personnel restent libres, copie vers le personnel aussi.
|
||||
if _, _, err := user.Open("regles.txt"); err != nil {
|
||||
t.Errorf("lecture : %v", err)
|
||||
}
|
||||
if _, err := user.Copy("regles.txt", ".perso/regles.txt"); err != nil {
|
||||
t.Errorf("copie vers le personnel : %v", err)
|
||||
}
|
||||
uput(t, user, ".perso/mien.txt", "M")
|
||||
// L'administrateur écrit toujours.
|
||||
uput(t, admin, "admin.txt", "A")
|
||||
}
|
||||
|
||||
func TestQuota(t *testing.T) {
|
||||
sp := newSpaces(t)
|
||||
if _, err := sp.Main.WriteQuota(1); err != nil { // 1 Mo
|
||||
t.Fatal(err)
|
||||
}
|
||||
u := space(t, sp, "alice", false)
|
||||
big := strings.Repeat("x", 700<<10)
|
||||
uput(t, u, ".perso/a.bin", big)
|
||||
if _, err := u.Put(".perso/b.bin", strings.NewReader(big), int64(len(big)), PutOptions{}); !errors.Is(err, ErrQuota) {
|
||||
t.Errorf("dépassement : %v", err)
|
||||
}
|
||||
// Sans taille annoncée : coupé en cours de route.
|
||||
if _, err := u.Put(".perso/c.bin", strings.NewReader(big), -1, PutOptions{}); !errors.Is(err, ErrQuota) {
|
||||
t.Errorf("dépassement en flux : %v", err)
|
||||
}
|
||||
if used, quota := u.Usage(); quota != 1<<20 || used < 700<<10 {
|
||||
t.Errorf("Usage = %d / %d", used, quota)
|
||||
}
|
||||
// Le quota ne concerne pas l'arborescence commune.
|
||||
uput(t, u, "commun.bin", big+big)
|
||||
// Déplacer vers le personnel doit tenir dans le quota.
|
||||
if _, err := u.Move("commun.bin", ".perso/commun.bin"); !errors.Is(err, ErrQuota) {
|
||||
t.Errorf("déplacement : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaxUpload(t *testing.T) {
|
||||
sp := newSpaces(t)
|
||||
sp.MaxUpload = 10
|
||||
u := space(t, sp, "alice", false)
|
||||
if _, err := u.Put("a.bin", strings.NewReader("12345678901"), 11, PutOptions{}); !errors.Is(err, ErrTooLarge) {
|
||||
t.Errorf("taille annoncée : %v", err)
|
||||
}
|
||||
if _, err := u.Put("b.bin", strings.NewReader("12345678901"), -1, PutOptions{}); !errors.Is(err, ErrTooLarge) {
|
||||
t.Errorf("flux : %v", err)
|
||||
}
|
||||
uput(t, u, "ok.bin", "1234567890")
|
||||
}
|
||||
|
||||
func TestShareInPersonalSpaceResolvedGlobally(t *testing.T) {
|
||||
sp := newSpaces(t)
|
||||
alice := space(t, sp, "alice", false)
|
||||
uput(t, alice, ".perso/p.txt", "P")
|
||||
sh, err := alice.CreateShare(".perso/p.txt", ShareOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sh.Path != ".perso/p.txt" {
|
||||
t.Errorf("chemin virtuel = %q", sh.Path)
|
||||
}
|
||||
got, st, err := sp.ResolveShare(sh.Token)
|
||||
if err != nil || got.Path != "p.txt" || st == sp.Main {
|
||||
t.Fatalf("ResolveShare = %+v, %v", got, err)
|
||||
}
|
||||
bob := space(t, sp, "bob", false)
|
||||
if l, _ := bob.Shares(""); len(l) != 0 {
|
||||
t.Errorf("bob voit les liens d'alice : %v", l)
|
||||
}
|
||||
if err := bob.RevokeShare(sh.ID); err == nil {
|
||||
t.Error("bob a révoqué le lien d'alice")
|
||||
}
|
||||
if err := alice.RevokeAllShares(); !errors.Is(err, ErrForbidden) {
|
||||
t.Errorf("révocation générale par un non-admin : %v", err)
|
||||
}
|
||||
if err := alice.RevokeShare(sh.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrashSeenAcrossSpaces(t *testing.T) {
|
||||
sp := newSpaces(t)
|
||||
alice := space(t, sp, "alice", false)
|
||||
uput(t, alice, "c.txt", "C")
|
||||
uput(t, alice, ".perso/p.txt", "P")
|
||||
_ = alice.Delete("c.txt", false)
|
||||
_ = alice.Delete(".perso/p.txt", false)
|
||||
tr, _ := alice.Trash()
|
||||
if len(tr) != 2 {
|
||||
t.Fatalf("poubelle = %+v", tr)
|
||||
}
|
||||
res := alice.RestoreTrash([]string{tr[0].Path, tr[1].Path})
|
||||
for _, r := range res {
|
||||
if r.Error != "" {
|
||||
t.Errorf("restauration : %+v", r)
|
||||
}
|
||||
}
|
||||
if es, _ := alice.List(".perso"); len(es) != 1 {
|
||||
t.Errorf("perso : %v", es)
|
||||
}
|
||||
}
|
||||
|
||||
func TestZipItemsAcrossSpaces(t *testing.T) {
|
||||
sp := newSpaces(t)
|
||||
alice := space(t, sp, "alice", false)
|
||||
uput(t, alice, "notes.txt", "1")
|
||||
uput(t, alice, ".perso/notes.txt", "2")
|
||||
items, name, err := alice.ZipItems([]string{"notes.txt", ".perso/notes.txt"})
|
||||
if err != nil || len(items) != 2 || items[0].Name == items[1].Name || name != "fichiers" {
|
||||
t.Errorf("ZipItems = %+v, %q, %v", items, name, err)
|
||||
}
|
||||
if _, _, err := alice.ZipItems([]string{"../../etc/passwd"}); err == nil {
|
||||
t.Error("chemin hors racine accepté")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetireUser(t *testing.T) {
|
||||
sp := newSpaces(t)
|
||||
alice := space(t, sp, "alice", false)
|
||||
uput(t, alice, ".perso/a.txt", "A")
|
||||
if err := sp.RetireUser("alice"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Un nouvel « alice » ne retrouve rien.
|
||||
again := space(t, sp, "alice", false)
|
||||
if es, _ := again.List(".perso"); len(es) != 0 {
|
||||
t.Errorf("héritage de fichiers : %v", es)
|
||||
}
|
||||
des, _ := os.ReadDir(filepath.Join(sp.Main.root, ".users-removed"))
|
||||
if len(des) != 1 {
|
||||
t.Errorf("espace non mis de côté : %v", des)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettingsDefaultsAndOverride(t *testing.T) {
|
||||
s := newStore(t)
|
||||
s.Defaults = SettingsDefaults{Registration: RegApproval, QuotaMB: 50, CommonReadonly: true, TrashDays: 30}
|
||||
st, _ := s.ReadSettings()
|
||||
if st.Registration != RegApproval || st.QuotaMB != 50 || !st.CommonReadonly || st.TrashDays != 30 {
|
||||
t.Errorf("défauts = %+v", st)
|
||||
}
|
||||
if st, _ = s.WriteRegistration(RegOpen); st.Registration != RegOpen {
|
||||
t.Errorf("registration = %+v", st)
|
||||
}
|
||||
if st, _ = s.WriteQuota(0); st.QuotaMB != 0 { // 0 explicite : illimité, malgré le défaut
|
||||
t.Errorf("quota = %+v", st)
|
||||
}
|
||||
if _, err := s.WriteRegistration("n'importe quoi"); err == nil {
|
||||
t.Error("mode invalide accepté")
|
||||
}
|
||||
if _, err := s.WriteQuota(-1); err == nil {
|
||||
t.Error("quota négatif accepté")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,714 @@
|
||||
// Package storage gère l'arborescence de fichiers sur disque.
|
||||
//
|
||||
// Tous les chemins manipulés par l'API sont relatifs à la racine (DATA_DIR),
|
||||
// au format "slash" (a/b/rapport.pdf). Le package garantit qu'aucun chemin ne
|
||||
// sort de la racine, y compris via un lien symbolique, et que les fichiers
|
||||
// internes (noms commençant par un point : .trash, .history, .meta.json...)
|
||||
// ne sont jamais exposés.
|
||||
package storage
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const (
|
||||
trashDir = ".trash"
|
||||
thumbsDir = ".thumbs"
|
||||
|
||||
// MaxNameLen borne la longueur d'un nom de fichier ou de dossier (octets).
|
||||
MaxNameLen = 255
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("introuvable")
|
||||
ErrExists = errors.New("existe déjà")
|
||||
ErrInvalidPath = errors.New("chemin invalide")
|
||||
ErrConflict = errors.New("le fichier a été modifié entre-temps")
|
||||
ErrNotEmpty = errors.New("dossier non vide")
|
||||
ErrForbidden = errors.New("action non autorisée")
|
||||
ErrQuota = errors.New("quota de stockage dépassé")
|
||||
ErrTooLarge = errors.New("fichier trop volumineux")
|
||||
)
|
||||
|
||||
// Entry décrit un élément de l'arborescence.
|
||||
type Entry struct {
|
||||
Name string `json:"name"`
|
||||
Path string `json:"path"`
|
||||
IsDir bool `json:"isDir"`
|
||||
Size int64 `json:"size"`
|
||||
ModTime time.Time `json:"modTime"`
|
||||
|
||||
Tags []string `json:"tags,omitempty"`
|
||||
Favorite bool `json:"favorite,omitempty"`
|
||||
Icon string `json:"icon,omitempty"` // dossier : icône choisie (meta.go)
|
||||
EditedBy string `json:"editedBy,omitempty"` // fichier : dernier utilisateur à l'avoir déposé
|
||||
|
||||
// Détails (details.go), seulement sur demande (/api/list?details=1).
|
||||
Details *Details `json:"details,omitempty"`
|
||||
|
||||
// Dossiers virtuels et favoris (spaces.go).
|
||||
Special string `json:"special,omitempty"` // "favoris", "perso" ou "poubelle" : entrée de la racine
|
||||
Link string `json:"link,omitempty"` // nom du lien dans le dossier Favoris
|
||||
Broken bool `json:"broken,omitempty"` // favori dont l'élément d'origine a disparu
|
||||
|
||||
// Poubelle (trash.go, spaces.go).
|
||||
Count int `json:"count,omitempty"` // entrée « poubelle » de la racine : nombre d'éléments
|
||||
Origin string `json:"origin,omitempty"` // élément de la poubelle : chemin d'origine
|
||||
By string `json:"by,omitempty"` // élément de la poubelle : supprimé par
|
||||
}
|
||||
|
||||
// Store est un dépôt de fichiers enraciné dans un répertoire.
|
||||
type Store struct {
|
||||
root string
|
||||
|
||||
// History règle l'historique des versions (DefaultHistory par défaut).
|
||||
History HistoryPolicy
|
||||
|
||||
// Defaults : valeurs des paramètres tant que l'administrateur ne les a pas
|
||||
// modifiés (variables d'environnement, voir settings.go).
|
||||
Defaults SettingsDefaults
|
||||
|
||||
settingsMu sync.Mutex // sérialise les lectures-modifications de .settings.json
|
||||
index textIndex // texte des fichiers pour la recherche (search.go)
|
||||
thumbSem chan struct{}
|
||||
|
||||
metaMu sync.Mutex // tags, favoris, auteurs (meta.go)
|
||||
meta map[string]itemMeta // nil : pas encore chargé
|
||||
|
||||
sharesMu sync.Mutex // liens de partage (share.go)
|
||||
shareKey []byte // clé HMAC ; nil : pas encore chargée
|
||||
fixedKey bool // clé imposée par SHARE_SECRET
|
||||
keyFrom *Store // espace personnel : clé de signature du Store principal
|
||||
|
||||
usageMu sync.Mutex
|
||||
usageAt time.Time
|
||||
usageSize int64
|
||||
}
|
||||
|
||||
// New crée le répertoire racine si besoin et renvoie un Store.
|
||||
func New(root string) (*Store, error) {
|
||||
abs, err := filepath.Abs(root)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.MkdirAll(abs, 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Résout un éventuel lien symbolique sur la racine elle-même pour que
|
||||
// les comparaisons de préfixe soient fiables.
|
||||
if abs, err = filepath.EvalSymlinks(abs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Store{root: abs, History: DefaultHistory, Defaults: DefaultSettings, thumbSem: make(chan struct{}, 2)}, nil
|
||||
}
|
||||
|
||||
// Clean normalise un chemin relatif : "/a/../b/" -> "b", "" -> "".
|
||||
// Les composants cachés (".trash", ".git"...), les caractères de contrôle et
|
||||
// les noms trop longs sont refusés.
|
||||
func Clean(rel string) (string, error) {
|
||||
if strings.ContainsRune(rel, 0) || strings.Contains(rel, `\`) || !utf8.ValidString(rel) {
|
||||
return "", ErrInvalidPath
|
||||
}
|
||||
c := strings.TrimPrefix(path.Clean("/"+rel), "/")
|
||||
if c == "" {
|
||||
return "", nil
|
||||
}
|
||||
for _, part := range strings.Split(c, "/") {
|
||||
if strings.HasPrefix(part, ".") || len(part) > MaxNameLen || strings.TrimSpace(part) != part {
|
||||
return "", ErrInvalidPath
|
||||
}
|
||||
for _, r := range part {
|
||||
if r < 0x20 || r == 0x7f {
|
||||
return "", ErrInvalidPath
|
||||
}
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// resolve convertit un chemin relatif en chemin absolu sous la racine et
|
||||
// vérifie que l'ancêtre existant le plus proche ne s'échappe pas via symlink
|
||||
// et ne mène pas à un répertoire interne.
|
||||
func (s *Store) resolve(rel string) (string, string, error) {
|
||||
c, err := Clean(rel)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
abs := filepath.Join(s.root, filepath.FromSlash(c))
|
||||
probe := abs
|
||||
for {
|
||||
real, err := filepath.EvalSymlinks(probe)
|
||||
if err == nil {
|
||||
if real != s.root && !strings.HasPrefix(real, s.root+string(os.PathSeparator)) {
|
||||
return "", "", ErrInvalidPath
|
||||
}
|
||||
if real != s.root {
|
||||
inner, _ := filepath.Rel(s.root, real)
|
||||
for _, part := range strings.Split(filepath.ToSlash(inner), "/") {
|
||||
if strings.HasPrefix(part, ".") {
|
||||
return "", "", ErrInvalidPath
|
||||
}
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
if !errors.Is(err, fs.ErrNotExist) {
|
||||
return "", "", err
|
||||
}
|
||||
parent := filepath.Dir(probe)
|
||||
if parent == probe {
|
||||
return "", "", ErrInvalidPath
|
||||
}
|
||||
probe = parent
|
||||
}
|
||||
return c, abs, nil
|
||||
}
|
||||
|
||||
func mapErr(err error) error {
|
||||
switch {
|
||||
case err == nil:
|
||||
return nil
|
||||
case errors.Is(err, fs.ErrNotExist):
|
||||
return ErrNotFound
|
||||
case errors.Is(err, fs.ErrExist):
|
||||
return ErrExists
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func toEntry(rel string, fi fs.FileInfo) Entry {
|
||||
e := Entry{
|
||||
Name: fi.Name(),
|
||||
Path: rel,
|
||||
IsDir: fi.IsDir(),
|
||||
Size: fi.Size(),
|
||||
ModTime: fi.ModTime().UTC(),
|
||||
}
|
||||
if e.IsDir {
|
||||
e.Size = 0
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
func visible(name string) bool { return !strings.HasPrefix(name, ".") }
|
||||
|
||||
// List renvoie le contenu d'un dossier : dossiers d'abord, puis fichiers,
|
||||
// triés par nom (insensible à la casse).
|
||||
func (s *Store) List(rel string) ([]Entry, error) {
|
||||
c, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
des, err := os.ReadDir(abs)
|
||||
if err != nil {
|
||||
if errors.Is(err, fs.ErrNotExist) || strings.Contains(err.Error(), "not a directory") {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, mapErr(err)
|
||||
}
|
||||
out := make([]Entry, 0, len(des))
|
||||
meta := s.metaSnapshot()
|
||||
for _, de := range des {
|
||||
if !visible(de.Name()) || de.Type()&fs.ModeSymlink != 0 {
|
||||
continue
|
||||
}
|
||||
fi, err := de.Info()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if !fi.IsDir() && !fi.Mode().IsRegular() {
|
||||
continue
|
||||
}
|
||||
e := toEntry(path.Join(c, de.Name()), fi)
|
||||
decorate(&e, meta)
|
||||
out = append(out, e)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
if out[i].IsDir != out[j].IsDir {
|
||||
return out[i].IsDir
|
||||
}
|
||||
return strings.ToLower(out[i].Name) < strings.ToLower(out[j].Name)
|
||||
})
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Stat décrit un fichier ou un dossier.
|
||||
func (s *Store) Stat(rel string) (Entry, error) {
|
||||
c, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
fi, err := os.Lstat(abs)
|
||||
if err != nil {
|
||||
return Entry{}, mapErr(err)
|
||||
}
|
||||
if fi.Mode()&fs.ModeSymlink != 0 {
|
||||
return Entry{}, ErrNotFound
|
||||
}
|
||||
e := toEntry(c, fi)
|
||||
decorate(&e, s.metaSnapshot())
|
||||
return e, nil
|
||||
}
|
||||
|
||||
// ETag calcule l'empreinte faible d'un fichier (taille et date de modification).
|
||||
func ETag(fi fs.FileInfo) string {
|
||||
return `W/"` + strconv.FormatInt(fi.Size(), 36) + "-" + strconv.FormatInt(fi.ModTime().UnixNano(), 36) + `"`
|
||||
}
|
||||
|
||||
// Open ouvre un fichier en lecture. Les liens symboliques sont refusés.
|
||||
func (s *Store) Open(rel string) (*os.File, fs.FileInfo, error) {
|
||||
c, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if c == "" {
|
||||
return nil, nil, ErrInvalidPath
|
||||
}
|
||||
fi, err := os.Lstat(abs)
|
||||
if err != nil {
|
||||
return nil, nil, mapErr(err)
|
||||
}
|
||||
if !fi.Mode().IsRegular() {
|
||||
return nil, nil, ErrNotFound
|
||||
}
|
||||
f, err := os.Open(abs)
|
||||
if err != nil {
|
||||
return nil, nil, mapErr(err)
|
||||
}
|
||||
if fi, err = f.Stat(); err != nil {
|
||||
f.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
return f, fi, nil
|
||||
}
|
||||
|
||||
// PutOptions règle l'écriture d'un fichier (Put).
|
||||
type PutOptions struct {
|
||||
// Conflict : conduite si le fichier existe. "" ou "fail" : ErrExists ;
|
||||
// "overwrite" : remplacement (la version précédente part dans l'historique) ;
|
||||
// "rename" : le nouveau fichier prend un nom libre « nom (2).ext ».
|
||||
Conflict string
|
||||
// IfMatch : ETag attendu du fichier remplacé (ErrConflict sinon) ; vide : pas de contrôle.
|
||||
IfMatch string
|
||||
// Limit : nombre maximal d'octets acceptés (0 : illimité) ; LimitErr est
|
||||
// renvoyée s'il est dépassé (ErrTooLarge ou ErrQuota).
|
||||
Limit int64
|
||||
LimitErr error
|
||||
// ModTime : date de modification à donner au fichier (zéro : maintenant).
|
||||
ModTime time.Time
|
||||
// By : utilisateur qui dépose le fichier (auteur et dernier auteur).
|
||||
By string
|
||||
}
|
||||
|
||||
// Put écrit un fichier de façon atomique et en flux (fichier temporaire dans
|
||||
// le dossier cible, fsync, rename) : un envoi interrompu ne laisse rien. Les
|
||||
// dossiers parents sont créés. Renvoie l'entrée écrite (son chemin peut
|
||||
// différer de rel avec Conflict = "rename").
|
||||
func (s *Store) Put(rel string, r io.Reader, o PutOptions) (Entry, error) {
|
||||
c, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
if c == "" {
|
||||
return Entry{}, ErrInvalidPath
|
||||
}
|
||||
fi, err := os.Lstat(abs)
|
||||
exists := err == nil
|
||||
if err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return Entry{}, mapErr(err)
|
||||
}
|
||||
if exists {
|
||||
if fi.IsDir() {
|
||||
return Entry{}, fmt.Errorf("%w : un dossier porte déjà ce nom", ErrExists)
|
||||
}
|
||||
switch o.Conflict {
|
||||
case "overwrite":
|
||||
if o.IfMatch != "" && o.IfMatch != "*" && o.IfMatch != ETag(fi) {
|
||||
return Entry{}, ErrConflict
|
||||
}
|
||||
case "rename":
|
||||
c = s.freeName(c, false, " (%d)")
|
||||
if _, abs, err = s.resolve(c); err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
exists = false
|
||||
default:
|
||||
return Entry{}, ErrExists
|
||||
}
|
||||
} else if o.IfMatch != "" && o.IfMatch != "*" {
|
||||
return Entry{}, ErrConflict
|
||||
}
|
||||
// Un composant du chemin ne doit pas être un fichier.
|
||||
if err := os.MkdirAll(filepath.Dir(abs), 0o755); err != nil {
|
||||
if errors.Is(err, fs.ErrExist) || strings.Contains(err.Error(), "not a directory") {
|
||||
return Entry{}, fmt.Errorf("%w : un fichier porte le nom d'un dossier du chemin", ErrExists)
|
||||
}
|
||||
return Entry{}, err
|
||||
}
|
||||
tmp, err := os.CreateTemp(filepath.Dir(abs), ".tmp-*")
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
defer os.Remove(tmp.Name()) // no-op après un rename réussi
|
||||
src := r
|
||||
if o.Limit > 0 {
|
||||
src = io.LimitReader(r, o.Limit+1)
|
||||
}
|
||||
n, err := io.Copy(tmp, src)
|
||||
if err != nil {
|
||||
tmp.Close()
|
||||
return Entry{}, err
|
||||
}
|
||||
if o.Limit > 0 && n > o.Limit {
|
||||
tmp.Close()
|
||||
if o.LimitErr != nil {
|
||||
return Entry{}, o.LimitErr
|
||||
}
|
||||
return Entry{}, ErrTooLarge
|
||||
}
|
||||
if err := tmp.Sync(); err != nil {
|
||||
tmp.Close()
|
||||
return Entry{}, err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
if err := os.Chmod(tmp.Name(), 0o644); err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
if m := o.ModTime; !m.IsZero() && m.After(time.Date(1980, 1, 1, 0, 0, 0, 0, time.UTC)) && m.Before(time.Now().Add(24*time.Hour)) {
|
||||
_ = os.Chtimes(tmp.Name(), m, m)
|
||||
}
|
||||
if exists {
|
||||
s.autoSnapshot(c, abs, fi)
|
||||
}
|
||||
if err := os.Rename(tmp.Name(), abs); err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
s.usageDirty()
|
||||
s.removeThumb(c)
|
||||
s.noteEdit(c, o.By, !exists)
|
||||
nfi, err := os.Stat(abs)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
e := toEntry(c, nfi)
|
||||
e.EditedBy = o.By
|
||||
return e, nil
|
||||
}
|
||||
|
||||
// Mkdir crée un dossier (et ses parents).
|
||||
func (s *Store) Mkdir(rel string) (Entry, error) {
|
||||
c, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
if c == "" {
|
||||
return Entry{}, ErrInvalidPath
|
||||
}
|
||||
if _, err := os.Lstat(abs); err == nil {
|
||||
return Entry{}, ErrExists
|
||||
}
|
||||
if err := os.MkdirAll(abs, 0o755); err != nil {
|
||||
if strings.Contains(err.Error(), "not a directory") {
|
||||
return Entry{}, fmt.Errorf("%w : un fichier porte le nom d'un dossier du chemin", ErrExists)
|
||||
}
|
||||
return Entry{}, mapErr(err)
|
||||
}
|
||||
fi, err := os.Stat(abs)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
return toEntry(c, fi), nil
|
||||
}
|
||||
|
||||
// Move renomme ou déplace un fichier ou un dossier. La destination ne doit
|
||||
// pas exister ; un dossier ne peut pas être déplacé dans lui-même.
|
||||
func (s *Store) Move(from, to string) (Entry, error) {
|
||||
cf, af, err := s.resolve(from)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
ct, at, err := s.resolve(to)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
if cf == "" || ct == "" {
|
||||
return Entry{}, ErrInvalidPath
|
||||
}
|
||||
fi, err := os.Lstat(af)
|
||||
if err != nil {
|
||||
return Entry{}, mapErr(err)
|
||||
}
|
||||
if fi.IsDir() && (ct == cf || strings.HasPrefix(ct, cf+"/")) {
|
||||
return Entry{}, fmt.Errorf("%w : déplacement d'un dossier dans lui-même", ErrInvalidPath)
|
||||
}
|
||||
if _, err := os.Lstat(at); err == nil {
|
||||
// Renommage qui ne change que la casse (volume insensible à la casse).
|
||||
if !strings.EqualFold(cf, ct) || cf == ct {
|
||||
return Entry{}, ErrExists
|
||||
}
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(at), 0o755); err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
if err := os.Rename(af, at); err != nil {
|
||||
return Entry{}, mapErr(err)
|
||||
}
|
||||
s.moveThumb(cf, ct, fi.IsDir())
|
||||
s.moveHistory(cf, ct)
|
||||
s.moveMeta(cf, ct)
|
||||
s.moveShares(cf, ct)
|
||||
fi, err = os.Stat(at)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
e := toEntry(ct, fi)
|
||||
decorate(&e, s.metaSnapshot())
|
||||
return e, nil
|
||||
}
|
||||
|
||||
// MoveResult est le résultat d'un déplacement unitaire dans MoveMany.
|
||||
type MoveResult struct {
|
||||
From string `json:"from"`
|
||||
To string `json:"to,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
err error
|
||||
}
|
||||
|
||||
// Err renvoie l'erreur du déplacement (nil si réussi).
|
||||
func (r MoveResult) Err() error { return r.err }
|
||||
|
||||
// Copy duplique un fichier, ou un dossier avec tout son contenu (fichiers
|
||||
// réguliers seulement). Les tags sont copiés, pas les favoris ni les partages.
|
||||
func (s *Store) Copy(from, to string) (Entry, error) {
|
||||
cf, af, err := s.resolve(from)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
ct, at, err := s.resolve(to)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
if cf == "" || ct == "" {
|
||||
return Entry{}, ErrInvalidPath
|
||||
}
|
||||
fi, err := os.Lstat(af)
|
||||
if err != nil {
|
||||
return Entry{}, mapErr(err)
|
||||
}
|
||||
if _, err := os.Lstat(at); err == nil {
|
||||
return Entry{}, ErrExists
|
||||
}
|
||||
if fi.IsDir() {
|
||||
if ct == cf || strings.HasPrefix(ct, cf+"/") {
|
||||
return Entry{}, fmt.Errorf("%w : copie d'un dossier dans lui-même", ErrInvalidPath)
|
||||
}
|
||||
err = copyTree(af, at)
|
||||
} else if fi.Mode().IsRegular() {
|
||||
err = copyFile(af, at)
|
||||
} else {
|
||||
return Entry{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
_ = os.RemoveAll(at)
|
||||
return Entry{}, err
|
||||
}
|
||||
s.usageDirty()
|
||||
s.copyMeta(cf, ct)
|
||||
nfi, err := os.Stat(at)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
return toEntry(ct, nfi), nil
|
||||
}
|
||||
|
||||
func copyFile(src, dst string) error {
|
||||
in, err := os.Open(src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer in.Close()
|
||||
fi, err := in.Stat()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
tmp, err := os.CreateTemp(filepath.Dir(dst), ".tmp-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(tmp.Name())
|
||||
if _, err := io.Copy(tmp, in); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Sync(); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
_ = os.Chmod(tmp.Name(), 0o644)
|
||||
_ = os.Chtimes(tmp.Name(), fi.ModTime(), fi.ModTime())
|
||||
return os.Rename(tmp.Name(), dst)
|
||||
}
|
||||
|
||||
func copyTree(src, dst string) error {
|
||||
return filepath.WalkDir(src, func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rel, _ := filepath.Rel(src, p)
|
||||
target := filepath.Join(dst, rel)
|
||||
switch {
|
||||
case d.IsDir():
|
||||
return os.MkdirAll(target, 0o755)
|
||||
case d.Type().IsRegular() && visible(d.Name()):
|
||||
return copyFile(p, target)
|
||||
}
|
||||
return nil // liens, fichiers spéciaux et fichiers internes ignorés
|
||||
})
|
||||
}
|
||||
|
||||
// Delete déplace un fichier ou un dossier dans la corbeille (.trash/, voir
|
||||
// trash.go), sans suppression physique. Un dossier non vide n'est supprimé que
|
||||
// si recursive.
|
||||
func (s *Store) Delete(rel string, recursive bool) error {
|
||||
return s.deleteAs(rel, recursive, "")
|
||||
}
|
||||
|
||||
// deleteAs est Delete en notant l'auteur de la suppression (by).
|
||||
func (s *Store) deleteAs(rel string, recursive bool, by string) error {
|
||||
c, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if c == "" {
|
||||
return ErrInvalidPath
|
||||
}
|
||||
fi, err := os.Lstat(abs)
|
||||
if err != nil {
|
||||
return mapErr(err)
|
||||
}
|
||||
if fi.IsDir() && !recursive {
|
||||
des, err := os.ReadDir(abs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(des) > 0 {
|
||||
return ErrNotEmpty
|
||||
}
|
||||
}
|
||||
if err := s.trash(c, abs, by); err != nil {
|
||||
return err
|
||||
}
|
||||
s.removeThumb(c)
|
||||
s.removeShares(c)
|
||||
return nil
|
||||
}
|
||||
|
||||
// freeName renvoie c s'il est libre, sinon « nom (2).ext », « nom (3).ext »...
|
||||
// (format : suffixe avec %d) ; les dossiers n'ont pas d'extension.
|
||||
func (s *Store) freeName(c string, isDir bool, format string) string {
|
||||
if _, err := os.Lstat(absOf(s, c)); errors.Is(err, fs.ErrNotExist) {
|
||||
return c
|
||||
}
|
||||
dir, base, ext := path.Dir(c), path.Base(c), ""
|
||||
if !isDir {
|
||||
ext = path.Ext(base)
|
||||
base = strings.TrimSuffix(base, ext)
|
||||
}
|
||||
for i := 2; ; i++ {
|
||||
n := base + fmt.Sprintf(format, i) + ext
|
||||
if dir != "." {
|
||||
n = dir + "/" + n
|
||||
}
|
||||
if _, err := os.Lstat(absOf(s, n)); errors.Is(err, fs.ErrNotExist) {
|
||||
return n
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Occupation disque -------------------------------------------------------------
|
||||
|
||||
func (s *Store) usageDirty() {
|
||||
s.usageMu.Lock()
|
||||
s.usageAt = time.Time{}
|
||||
s.usageMu.Unlock()
|
||||
}
|
||||
|
||||
// Usage renvoie le nombre d'octets occupés (fichiers, corbeille et historique
|
||||
// compris ; miniatures exclues). Le résultat est gardé 15 s, ou jusqu'à la
|
||||
// prochaine écriture.
|
||||
func (s *Store) Usage() int64 {
|
||||
s.usageMu.Lock()
|
||||
defer s.usageMu.Unlock()
|
||||
if time.Since(s.usageAt) < 15*time.Second {
|
||||
return s.usageSize
|
||||
}
|
||||
var total int64
|
||||
_ = filepath.WalkDir(s.root, func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if d.IsDir() && p != s.root && d.Name() == thumbsDir {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
if d.Type().IsRegular() {
|
||||
if fi, err := d.Info(); err == nil {
|
||||
total += fi.Size()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
s.usageSize, s.usageAt = total, time.Now()
|
||||
return total
|
||||
}
|
||||
|
||||
// fileID : empreinte courte d'une chaîne (noms de fichiers dérivés).
|
||||
func fileID(s string) string {
|
||||
h := sha256.Sum256([]byte(s))
|
||||
return hex.EncodeToString(h[:8])
|
||||
}
|
||||
|
||||
// atomicWrite écrit data dans abs de façon atomique (fichier temporaire + rename).
|
||||
func atomicWrite(abs string, data []byte) error {
|
||||
tmp, err := os.CreateTemp(filepath.Dir(abs), ".tmp-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(tmp.Name()) // no-op après un rename réussi
|
||||
if _, err := tmp.Write(data); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Sync(); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Chmod(tmp.Name(), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp.Name(), abs)
|
||||
}
|
||||
@@ -0,0 +1,526 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"errors"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func newStore(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
s, err := New(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func put(t *testing.T, s *Store, p, content string, o PutOptions) Entry {
|
||||
t.Helper()
|
||||
e, err := s.Put(p, strings.NewReader(content), o)
|
||||
if err != nil {
|
||||
t.Fatalf("Put(%s) : %v", p, err)
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
func read(t *testing.T, s *Store, p string) string {
|
||||
t.Helper()
|
||||
f, _, err := s.Open(p)
|
||||
if err != nil {
|
||||
t.Fatalf("Open(%s) : %v", p, err)
|
||||
}
|
||||
defer f.Close()
|
||||
b, _ := io.ReadAll(f)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func TestCleanRejectsHiddenAndTraversal(t *testing.T) {
|
||||
for _, bad := range []string{".trash", "a/.history/x", ".meta.json", "a/\x00b", `a\b`, "a/ b", strings.Repeat("x", 300), "a/\x01"} {
|
||||
if _, err := Clean(bad); err == nil {
|
||||
t.Errorf("Clean(%q) aurait dû échouer", bad)
|
||||
}
|
||||
}
|
||||
if c, err := Clean("/a/../b//c/"); err != nil || c != "b/c" {
|
||||
t.Errorf("Clean = %q, %v", c, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPutOpenListAnyFileType(t *testing.T) {
|
||||
s := newStore(t)
|
||||
put(t, s, "docs/rapport.pdf", "%PDF-1.4", PutOptions{By: "alice"})
|
||||
put(t, s, "docs/archive.tar.gz", "\x1f\x8b", PutOptions{})
|
||||
put(t, s, "docs/sans-extension", "x", PutOptions{})
|
||||
es, err := s.List("docs")
|
||||
if err != nil || len(es) != 3 {
|
||||
t.Fatalf("List = %v, %v", es, err)
|
||||
}
|
||||
if got := read(t, s, "docs/rapport.pdf"); got != "%PDF-1.4" {
|
||||
t.Errorf("contenu = %q", got)
|
||||
}
|
||||
if es[0].Name != "archive.tar.gz" || es[2].Name != "sans-extension" {
|
||||
t.Errorf("tri : %v", es)
|
||||
}
|
||||
st, _ := s.Stat("docs/rapport.pdf")
|
||||
if st.EditedBy != "alice" {
|
||||
t.Errorf("EditedBy = %q", st.EditedBy)
|
||||
}
|
||||
// Les fichiers temporaires et internes n'apparaissent jamais.
|
||||
root, _ := s.List("")
|
||||
for _, e := range root {
|
||||
if strings.HasPrefix(e.Name, ".") {
|
||||
t.Errorf("entrée cachée visible : %s", e.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPutConflictModes(t *testing.T) {
|
||||
s := newStore(t)
|
||||
put(t, s, "a.txt", "un", PutOptions{})
|
||||
if _, err := s.Put("a.txt", strings.NewReader("deux"), PutOptions{}); !errors.Is(err, ErrExists) {
|
||||
t.Fatalf("fail : %v", err)
|
||||
}
|
||||
e := put(t, s, "a.txt", "trois", PutOptions{Conflict: "rename"})
|
||||
if e.Path != "a (2).txt" {
|
||||
t.Errorf("rename -> %q", e.Path)
|
||||
}
|
||||
e = put(t, s, "a.txt", "quatre", PutOptions{Conflict: "rename"})
|
||||
if e.Path != "a (3).txt" {
|
||||
t.Errorf("rename 2 -> %q", e.Path)
|
||||
}
|
||||
put(t, s, "a.txt", "cinq", PutOptions{Conflict: "overwrite"})
|
||||
if read(t, s, "a.txt") != "cinq" || read(t, s, "a (2).txt") != "trois" {
|
||||
t.Error("contenus inattendus après écrasement")
|
||||
}
|
||||
// Un dossier ne peut pas être écrasé par un fichier.
|
||||
if _, err := s.Mkdir("dir"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Put("dir", strings.NewReader("x"), PutOptions{Conflict: "overwrite"}); !errors.Is(err, ErrExists) {
|
||||
t.Errorf("dossier écrasé : %v", err)
|
||||
}
|
||||
// Un fichier ne peut pas servir de dossier parent.
|
||||
if _, err := s.Put("a.txt/enfant", strings.NewReader("x"), PutOptions{}); err == nil {
|
||||
t.Error("fichier utilisé comme dossier")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPutIfMatchAndLimit(t *testing.T) {
|
||||
s := newStore(t)
|
||||
e := put(t, s, "f.bin", "abc", PutOptions{})
|
||||
fi, _ := os.Stat(filepath.Join(s.root, "f.bin"))
|
||||
if _, err := s.Put("f.bin", strings.NewReader("zz"), PutOptions{Conflict: "overwrite", IfMatch: `W/"nope"`}); !errors.Is(err, ErrConflict) {
|
||||
t.Errorf("If-Match faux : %v", err)
|
||||
}
|
||||
if _, err := s.Put("f.bin", strings.NewReader("zz"), PutOptions{Conflict: "overwrite", IfMatch: ETag(fi)}); err != nil {
|
||||
t.Errorf("If-Match juste : %v", err)
|
||||
}
|
||||
_ = e
|
||||
_, err := s.Put("big.bin", strings.NewReader("0123456789"), PutOptions{Limit: 5, LimitErr: ErrQuota})
|
||||
if !errors.Is(err, ErrQuota) {
|
||||
t.Errorf("limite : %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(s.root, "big.bin")); err == nil {
|
||||
t.Error("fichier partiel conservé")
|
||||
}
|
||||
// Aucun fichier temporaire ne traîne.
|
||||
des, _ := os.ReadDir(s.root)
|
||||
for _, d := range des {
|
||||
if strings.HasPrefix(d.Name(), ".tmp-") {
|
||||
t.Errorf("temporaire : %s", d.Name())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPutPreservesModTime(t *testing.T) {
|
||||
s := newStore(t)
|
||||
want := time.Date(2020, 5, 17, 10, 0, 0, 0, time.UTC)
|
||||
e := put(t, s, "photo.jpg", "x", PutOptions{ModTime: want})
|
||||
if !e.ModTime.Equal(want) {
|
||||
t.Errorf("ModTime = %v", e.ModTime)
|
||||
}
|
||||
// Une date dans le futur lointain est ignorée.
|
||||
e = put(t, s, "futur.txt", "x", PutOptions{ModTime: time.Now().AddDate(10, 0, 0)})
|
||||
if e.ModTime.After(time.Now().Add(time.Hour)) {
|
||||
t.Errorf("date future acceptée : %v", e.ModTime)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHistoryOnOverwrite(t *testing.T) {
|
||||
s := newStore(t)
|
||||
put(t, s, "n.txt", "v1", PutOptions{ModTime: time.Now().Add(-3 * time.Hour)})
|
||||
put(t, s, "n.txt", "v2", PutOptions{Conflict: "overwrite", ModTime: time.Now().Add(-2 * time.Hour)})
|
||||
put(t, s, "n.txt", "v3", PutOptions{Conflict: "overwrite"})
|
||||
vs, err := s.Versions("n.txt")
|
||||
if err != nil || len(vs) != 2 {
|
||||
t.Fatalf("versions = %v, %v", vs, err)
|
||||
}
|
||||
f, _, err := s.OpenVersion("n.txt", vs[1].ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := io.ReadAll(f)
|
||||
f.Close()
|
||||
if string(b) != "v1" {
|
||||
t.Errorf("plus ancienne version = %q", b)
|
||||
}
|
||||
if _, err := s.Restore("n.txt", vs[1].ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if read(t, s, "n.txt") != "v1" {
|
||||
t.Error("restauration inopérante")
|
||||
}
|
||||
if vs, _ = s.Versions("n.txt"); len(vs) != 3 {
|
||||
t.Errorf("la restauration doit conserver l'état remplacé : %d versions", len(vs))
|
||||
}
|
||||
// Rétention.
|
||||
s.History.Keep = 2
|
||||
put(t, s, "n.txt", "v4", PutOptions{Conflict: "overwrite"})
|
||||
if vs, _ = s.Versions("n.txt"); len(vs) != 2 {
|
||||
t.Errorf("rétention : %d versions", len(vs))
|
||||
}
|
||||
// Historique désactivé.
|
||||
s.History.Keep = 0
|
||||
put(t, s, "z.txt", "a", PutOptions{})
|
||||
put(t, s, "z.txt", "b", PutOptions{Conflict: "overwrite"})
|
||||
if vs, _ = s.Versions("z.txt"); len(vs) != 0 {
|
||||
t.Errorf("historique désactivé : %d versions", len(vs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMoveCopyFolders(t *testing.T) {
|
||||
s := newStore(t)
|
||||
put(t, s, "src/a.txt", "A", PutOptions{})
|
||||
put(t, s, "src/sub/b.txt", "B", PutOptions{})
|
||||
if _, err := s.Copy("src", "copie"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if read(t, s, "copie/sub/b.txt") != "B" {
|
||||
t.Error("copie récursive")
|
||||
}
|
||||
if _, err := s.Copy("src", "src/dans"); !errors.Is(err, ErrInvalidPath) {
|
||||
t.Errorf("copie dans soi-même : %v", err)
|
||||
}
|
||||
if _, err := s.Move("src", "src/sub/x"); !errors.Is(err, ErrInvalidPath) {
|
||||
t.Errorf("déplacement dans soi-même : %v", err)
|
||||
}
|
||||
if _, err := s.Move("src", "copie"); !errors.Is(err, ErrExists) {
|
||||
t.Errorf("destination existante : %v", err)
|
||||
}
|
||||
if _, err := s.Move("src/a.txt", "deplace/renomme.txt"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if read(t, s, "deplace/renomme.txt") != "A" {
|
||||
t.Error("déplacement")
|
||||
}
|
||||
if _, _, err := s.Open("src/a.txt"); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("ancien emplacement : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTagsFollowMove(t *testing.T) {
|
||||
s := newStore(t)
|
||||
put(t, s, "a.txt", "x", PutOptions{})
|
||||
if err := s.EditTags([]string{"a.txt"}, []string{"Rapport", "rapport", "#Urgent"}, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
es, _ := s.List("")
|
||||
if len(es[0].Tags) != 2 {
|
||||
t.Fatalf("tags = %v", es[0].Tags)
|
||||
}
|
||||
if _, err := s.Move("a.txt", "b.txt"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
es, _ = s.List("")
|
||||
if len(es[0].Tags) != 2 {
|
||||
t.Errorf("tags perdus au déplacement : %v", es[0])
|
||||
}
|
||||
ts, _ := s.Tags()
|
||||
if len(ts) != 2 {
|
||||
t.Errorf("Tags() = %v", ts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrashRestoreAndName(t *testing.T) {
|
||||
s := newStore(t)
|
||||
put(t, s, "d/a.txt", "A", PutOptions{})
|
||||
if err := s.Delete("d/a.txt", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := s.Open("d/a.txt"); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatal("fichier encore présent")
|
||||
}
|
||||
put(t, s, "d/a.txt", "nouveau", PutOptions{}) // la place est prise
|
||||
items, _ := s.TrashItems()
|
||||
if len(items) != 1 {
|
||||
t.Fatalf("poubelle : %v", items)
|
||||
}
|
||||
e, err := s.RestoreTrash(items[0].ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if e.Path != "d/a (restauré 2).txt" || read(t, s, e.Path) != "A" {
|
||||
t.Errorf("restauration : %v", e)
|
||||
}
|
||||
// Dossier non vide : refus sans récursivité.
|
||||
if err := s.Delete("d", false); !errors.Is(err, ErrNotEmpty) {
|
||||
t.Errorf("dossier non vide : %v", err)
|
||||
}
|
||||
if err := s.Delete("d", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSymlinkEscapeRefused(t *testing.T) {
|
||||
s := newStore(t)
|
||||
outside := t.TempDir()
|
||||
_ = os.WriteFile(filepath.Join(outside, "secret.txt"), []byte("secret"), 0o644)
|
||||
if err := os.Symlink(outside, filepath.Join(s.root, "lien")); err != nil {
|
||||
t.Skip("liens symboliques indisponibles")
|
||||
}
|
||||
if _, _, err := s.Open("lien/secret.txt"); err == nil {
|
||||
t.Error("lecture hors racine via lien symbolique")
|
||||
}
|
||||
if _, err := s.Put("lien/nouveau.txt", strings.NewReader("x"), PutOptions{}); err == nil {
|
||||
t.Error("écriture hors racine via lien symbolique")
|
||||
}
|
||||
es, _ := s.List("")
|
||||
for _, e := range es {
|
||||
if e.Name == "lien" {
|
||||
t.Error("lien symbolique listé")
|
||||
}
|
||||
}
|
||||
// Lien interne vers un dossier caché.
|
||||
_ = os.MkdirAll(filepath.Join(s.root, ".history"), 0o755)
|
||||
_ = os.Symlink(filepath.Join(s.root, ".history"), filepath.Join(s.root, "cache"))
|
||||
if _, err := s.List("cache"); err == nil {
|
||||
t.Error("accès aux dossiers internes via lien symbolique")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSearchNamesTagsAndText(t *testing.T) {
|
||||
s := newStore(t)
|
||||
put(t, s, "notes/Réseau.md", "# Plan\nLe VLAN 172.27.207.0/24 est routé", PutOptions{})
|
||||
put(t, s, "notes/photo.jpg", "VLAN dans un binaire", PutOptions{})
|
||||
put(t, s, "autre/budget.txt", "rien", PutOptions{})
|
||||
_ = s.EditTags([]string{"autre/budget.txt"}, []string{"Finance"}, nil)
|
||||
hits, _ := s.Search("172.27.207", Filter{}, 10)
|
||||
if len(hits) != 1 || hits[0].Name != "Réseau.md" || hits[0].Snippet == "" {
|
||||
t.Errorf("contenu : %v", hits)
|
||||
}
|
||||
if hits, _ = s.Search("reseau", Filter{}, 10); len(hits) != 1 {
|
||||
t.Errorf("nom sans accent : %v", hits)
|
||||
}
|
||||
if hits, _ = s.Search("vlan", Filter{}, 10); len(hits) != 1 { // le .jpg n'est pas indexé comme texte
|
||||
t.Errorf("binaire indexé : %v", hits)
|
||||
}
|
||||
if hits, _ = s.Search("", Filter{Tag: "finance"}, 10); len(hits) != 1 || hits[0].Name != "budget.txt" {
|
||||
t.Errorf("tag : %v", hits)
|
||||
}
|
||||
}
|
||||
|
||||
func TestShareFileAndFolder(t *testing.T) {
|
||||
s := newStore(t)
|
||||
put(t, s, "pub/a.txt", "A", PutOptions{})
|
||||
put(t, s, "pub/sub/b.txt", "B", PutOptions{})
|
||||
sh, err := s.CreateShare("pub", ShareOptions{TTL: time.Hour})
|
||||
if err != nil || !sh.IsDir || sh.Protected {
|
||||
t.Fatalf("CreateShare = %+v, %v", sh, err)
|
||||
}
|
||||
got, err := s.ResolveShare(sh.Token)
|
||||
if err != nil || got.Path != "pub" {
|
||||
t.Fatalf("ResolveShare = %+v, %v", got, err)
|
||||
}
|
||||
if p, err := SharedPath(got, "sub/b.txt"); err != nil || p != "pub/sub/b.txt" {
|
||||
t.Errorf("SharedPath = %q, %v", p, err)
|
||||
}
|
||||
for _, evil := range []string{"../secret", "sub/../../x", ".trash", "a/.history"} {
|
||||
if p, err := SharedPath(got, evil); err == nil && !strings.HasPrefix(p, "pub/") {
|
||||
t.Errorf("SharedPath(%q) = %q", evil, p)
|
||||
} else if err == nil && strings.Contains(p, "..") {
|
||||
t.Errorf("SharedPath(%q) = %q", evil, p)
|
||||
}
|
||||
}
|
||||
// Signature altérée, jeton inconnu.
|
||||
bad := sh.Token[:len(sh.Token)-2] + "xx"
|
||||
if _, err := s.ResolveShare(bad); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("signature fausse : %v", err)
|
||||
}
|
||||
// Le lien suit un renommage et disparaît à la suppression.
|
||||
if _, err := s.Move("pub", "public"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err = s.ResolveShare(sh.Token); err != nil || got.Path != "public" {
|
||||
t.Errorf("après déplacement : %+v, %v", got, err)
|
||||
}
|
||||
if err := s.Delete("public", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.ResolveShare(sh.Token); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("après suppression : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSharePasswordAndExpiry(t *testing.T) {
|
||||
s := newStore(t)
|
||||
put(t, s, "f.txt", "x", PutOptions{})
|
||||
sh, err := s.CreateShare("f.txt", ShareOptions{Password: "s3cret-mot-de-passe"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ := s.ResolveShare(sh.Token)
|
||||
if !got.Protected || !got.CheckPassword("s3cret-mot-de-passe") || got.CheckPassword("autre") {
|
||||
t.Error("mot de passe du lien")
|
||||
}
|
||||
if sh.IsDir {
|
||||
t.Error("IsDir")
|
||||
}
|
||||
c1, _ := s.UnlockCookie(got)
|
||||
c2, _ := s.UnlockCookie(got)
|
||||
if c1 == "" || c1 != c2 {
|
||||
t.Error("cookie de déverrouillage instable")
|
||||
}
|
||||
s.CountDownload(sh.ID)
|
||||
s.CountDownload(sh.ID)
|
||||
if got, _ = s.ResolveShare(sh.Token); got.Downloads != 2 {
|
||||
t.Errorf("téléchargements = %d", got.Downloads)
|
||||
}
|
||||
// Expiration.
|
||||
exp, _ := s.CreateShare("f.txt", ShareOptions{TTL: time.Millisecond})
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
if _, err := s.ResolveShare(exp.Token); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("lien expiré : %v", err)
|
||||
}
|
||||
// Tout révoquer change la clé : les anciens liens deviennent invalides.
|
||||
if err := s.RevokeAllShares(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.ResolveShare(sh.Token); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("après révocation générale : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestZip(t *testing.T) {
|
||||
s := newStore(t)
|
||||
put(t, s, "d/a.txt", "AAA", PutOptions{})
|
||||
put(t, s, "d/sub/b.png", "BBB", PutOptions{})
|
||||
_ = os.WriteFile(filepath.Join(s.root, "d", ".cache"), []byte("interne"), 0o644)
|
||||
var buf bytes.Buffer
|
||||
item, err := s.SharedZipItem("d")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := WriteZip(&buf, []ZipItem{item}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
zr, err := zip.NewReader(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
names := map[string]string{}
|
||||
for _, f := range zr.File {
|
||||
rc, _ := f.Open()
|
||||
b, _ := io.ReadAll(rc)
|
||||
rc.Close()
|
||||
names[f.Name] = string(b)
|
||||
}
|
||||
if names["d/a.txt"] != "AAA" || names["d/sub/b.png"] != "BBB" {
|
||||
t.Errorf("contenu : %v", names)
|
||||
}
|
||||
for n := range names {
|
||||
if strings.Contains(n, ".cache") {
|
||||
t.Errorf("fichier interne archivé : %s", n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func makePNG(w, h int) []byte {
|
||||
img := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||
for y := 0; y < h; y++ {
|
||||
for x := 0; x < w; x++ {
|
||||
img.Set(x, y, color.RGBA{uint8(x), uint8(y), 128, 255})
|
||||
}
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
_ = png.Encode(&buf, img)
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func TestThumbs(t *testing.T) {
|
||||
s := newStore(t)
|
||||
put(t, s, "grande.png", string(makePNG(1200, 600)), PutOptions{})
|
||||
b, typ, _, err := s.Thumb("grande.png")
|
||||
if err != nil || typ != "image/png" {
|
||||
t.Fatalf("Thumb : %v %q", err, typ)
|
||||
}
|
||||
cfg, err := png.DecodeConfig(bytes.NewReader(b))
|
||||
if err != nil || cfg.Width != ThumbSize || cfg.Height != ThumbSize/2 {
|
||||
t.Errorf("dimensions = %v, %v", cfg, err)
|
||||
}
|
||||
// Seconde lecture : servie depuis .thumbs/.
|
||||
if _, err := os.Stat(filepath.Join(s.root, ".thumbs", "grande.png.thumb")); err != nil {
|
||||
t.Error("miniature non conservée")
|
||||
}
|
||||
// Une petite image n'est pas agrandie.
|
||||
put(t, s, "petite.png", string(makePNG(40, 20)), PutOptions{})
|
||||
b, _, _, _ = s.Thumb("petite.png")
|
||||
if cfg, _ := png.DecodeConfig(bytes.NewReader(b)); cfg.Width != 40 {
|
||||
t.Errorf("agrandissement : %v", cfg)
|
||||
}
|
||||
// Remplacement : la miniature est régénérée.
|
||||
put(t, s, "petite.png", string(makePNG(80, 80)), PutOptions{Conflict: "overwrite"})
|
||||
b, _, _, _ = s.Thumb("petite.png")
|
||||
if cfg, _ := png.DecodeConfig(bytes.NewReader(b)); cfg.Width != 80 {
|
||||
t.Errorf("miniature périmée : %v", cfg)
|
||||
}
|
||||
// Pas une image décodable.
|
||||
put(t, s, "x.pdf", "pdf", PutOptions{})
|
||||
if _, _, _, err := s.Thumb("x.pdf"); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("PDF : %v", err)
|
||||
}
|
||||
put(t, s, "faux.png", "pas une image", PutOptions{})
|
||||
if _, _, _, err := s.Thumb("faux.png"); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("image corrompue : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrient(t *testing.T) {
|
||||
src := image.NewRGBA(image.Rect(0, 0, 2, 1))
|
||||
src.Set(0, 0, color.RGBA{255, 0, 0, 255})
|
||||
src.Set(1, 0, color.RGBA{0, 0, 255, 255})
|
||||
got := orient(src, 6) // 90° horaire : 1 colonne de 2 lignes, rouge en haut
|
||||
if got.Bounds().Dx() != 1 || got.Bounds().Dy() != 2 || got.RGBAAt(0, 0).R != 255 || got.RGBAAt(0, 1).B != 255 {
|
||||
t.Errorf("rotation 6 : %v", got.Pix)
|
||||
}
|
||||
if o := exifOrientation([]byte("II*\x00\x08\x00\x00\x00\x01\x00\x12\x01\x03\x00\x01\x00\x00\x00\x06\x00\x00\x00")); o != 6 {
|
||||
t.Errorf("orientation EXIF = %d", o)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUsageAndDetails(t *testing.T) {
|
||||
s := newStore(t)
|
||||
put(t, s, "a/x.bin", strings.Repeat("x", 1000), PutOptions{})
|
||||
put(t, s, "a/b/y.bin", strings.Repeat("y", 500), PutOptions{})
|
||||
// 1500 octets de contenu, plus .meta.json (auteurs).
|
||||
if u := s.Usage(); u < 1500 || u > 2500 {
|
||||
t.Errorf("Usage = %d", u)
|
||||
}
|
||||
d, err := s.dirDetails("a")
|
||||
if err != nil || d.Files != 1 || d.Dirs != 1 || d.Total != 1500 || d.Count != 2 {
|
||||
t.Errorf("dirDetails = %+v, %v", d, err)
|
||||
}
|
||||
put(t, s, "img.png", string(makePNG(30, 10)), PutOptions{})
|
||||
fd, _ := s.fileDetails("img.png", s.metaSnapshot(), nil)
|
||||
if fd.Width != 30 || fd.Height != 10 {
|
||||
t.Errorf("fileDetails = %+v", fd)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/draw"
|
||||
"image/gif"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Miniatures des images (JPEG, PNG, GIF), générées par le serveur à la
|
||||
// demande avec la bibliothèque standard et rangées dans .thumbs/ en miroir de
|
||||
// l'arborescence (a/b.jpg -> .thumbs/a/b.jpg.thumb). Une miniature plus ancienne
|
||||
// que son fichier est considérée comme périmée et régénérée. L'orientation
|
||||
// EXIF des JPEG est appliquée. Les autres formats (WebP, SVG...) sont affichés
|
||||
// tels quels par le navigateur, sans miniature.
|
||||
|
||||
const (
|
||||
// ThumbSize est le plus grand côté d'une miniature (pixels).
|
||||
ThumbSize = 480
|
||||
|
||||
maxThumbPixels = 25_000_000 // protège contre les « bombes » de décompression
|
||||
maxThumbSource = 80 << 20 // taille maximale du fichier source
|
||||
)
|
||||
|
||||
// isDecodableImage indique si la bibliothèque standard sait décoder le fichier.
|
||||
func isDecodableImage(name string) bool {
|
||||
switch strings.ToLower(path.Ext(name)) {
|
||||
case ".jpg", ".jpeg", ".png", ".gif":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Store) thumbAbs(c string, isDir bool) string {
|
||||
p := filepath.Join(s.root, thumbsDir, filepath.FromSlash(c))
|
||||
if isDir {
|
||||
return p
|
||||
}
|
||||
return p + ".thumb"
|
||||
}
|
||||
|
||||
// Thumb renvoie la miniature d'une image (créée si absente ou périmée), son
|
||||
// type MIME et sa date. ErrNotFound si le fichier n'est pas une image
|
||||
// décodable.
|
||||
func (s *Store) Thumb(rel string) ([]byte, string, time.Time, error) {
|
||||
c, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return nil, "", time.Time{}, err
|
||||
}
|
||||
if c == "" || !isDecodableImage(c) {
|
||||
return nil, "", time.Time{}, ErrNotFound
|
||||
}
|
||||
src, err := os.Lstat(abs)
|
||||
if err != nil || !src.Mode().IsRegular() {
|
||||
return nil, "", time.Time{}, ErrNotFound
|
||||
}
|
||||
ta := s.thumbAbs(c, false)
|
||||
if ti, err := os.Stat(ta); err == nil && !ti.ModTime().Before(src.ModTime()) {
|
||||
if b, err := os.ReadFile(ta); err == nil {
|
||||
return b, sniffThumb(b), ti.ModTime(), nil
|
||||
}
|
||||
}
|
||||
if src.Size() > maxThumbSource {
|
||||
return nil, "", time.Time{}, ErrNotFound
|
||||
}
|
||||
s.thumbSem <- struct{}{}
|
||||
defer func() { <-s.thumbSem }()
|
||||
b, err := makeThumb(abs)
|
||||
if err != nil {
|
||||
return nil, "", time.Time{}, ErrNotFound
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(ta), 0o755); err == nil {
|
||||
_ = atomicWrite(ta, b)
|
||||
}
|
||||
return b, sniffThumb(b), time.Now(), nil
|
||||
}
|
||||
|
||||
func sniffThumb(b []byte) string {
|
||||
if bytes.HasPrefix(b, []byte("\x89PNG")) {
|
||||
return "image/png"
|
||||
}
|
||||
return "image/jpeg"
|
||||
}
|
||||
|
||||
func makeThumb(abs string) ([]byte, error) {
|
||||
f, err := os.Open(abs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
cfg, format, err := image.DecodeConfig(f)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cfg.Width < 1 || cfg.Height < 1 || cfg.Width*cfg.Height > maxThumbPixels {
|
||||
return nil, fmt.Errorf("image hors limites (%dx%d)", cfg.Width, cfg.Height)
|
||||
}
|
||||
if _, err := f.Seek(0, io.SeekStart); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
orientation := 1
|
||||
if format == "jpeg" {
|
||||
orientation = jpegOrientation(f)
|
||||
if _, err := f.Seek(0, io.SeekStart); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
var img image.Image
|
||||
switch format {
|
||||
case "jpeg":
|
||||
img, err = jpeg.Decode(f)
|
||||
case "png":
|
||||
img, err = png.Decode(f)
|
||||
case "gif":
|
||||
img, err = gif.Decode(f)
|
||||
default:
|
||||
err = fmt.Errorf("format %s non géré", format)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b := img.Bounds()
|
||||
w, h := b.Dx(), b.Dy()
|
||||
scale := float64(ThumbSize) / float64(max(w, h))
|
||||
tw, th := w, h
|
||||
if scale < 1 {
|
||||
tw, th = max(1, int(float64(w)*scale+0.5)), max(1, int(float64(h)*scale+0.5))
|
||||
}
|
||||
out := orient(resize(img, tw, th), orientation)
|
||||
var buf bytes.Buffer
|
||||
if format == "jpeg" {
|
||||
// Fond blanc : un JPEG n'a pas de transparence, mais le décodage CMJN ou autre pourrait en avoir.
|
||||
err = jpeg.Encode(&buf, out, &jpeg.Options{Quality: 82})
|
||||
} else {
|
||||
err = png.Encode(&buf, out)
|
||||
}
|
||||
return buf.Bytes(), err
|
||||
}
|
||||
|
||||
// resize rééchantillonne img en w x h par moyenne de surface (filtre « boîte »),
|
||||
// en alpha prémultiplié ; sans agrandissement au-delà de la taille d'origine.
|
||||
func resize(img image.Image, w, h int) *image.RGBA {
|
||||
b := img.Bounds()
|
||||
src := image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
|
||||
draw.Draw(src, src.Bounds(), img, b.Min, draw.Src)
|
||||
if w == b.Dx() && h == b.Dy() {
|
||||
return src
|
||||
}
|
||||
wx, wy := boxWeights(b.Dx(), w), boxWeights(b.Dy(), h)
|
||||
dst := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||
for dy := 0; dy < h; dy++ {
|
||||
for dx := 0; dx < w; dx++ {
|
||||
var acc [4]float64
|
||||
var total float64
|
||||
for _, y := range wy[dy] {
|
||||
row := y.i * src.Stride
|
||||
for _, x := range wx[dx] {
|
||||
k := y.w * x.w
|
||||
p := src.Pix[row+x.i*4:]
|
||||
acc[0] += k * float64(p[0])
|
||||
acc[1] += k * float64(p[1])
|
||||
acc[2] += k * float64(p[2])
|
||||
acc[3] += k * float64(p[3])
|
||||
total += k
|
||||
}
|
||||
}
|
||||
o := dst.PixOffset(dx, dy)
|
||||
for c := range acc {
|
||||
dst.Pix[o+c] = uint8(acc[c]/total + 0.5)
|
||||
}
|
||||
}
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
||||
// jpegOrientation lit l'orientation EXIF (1 à 8) d'un JPEG ; 1 si absente.
|
||||
func jpegOrientation(r io.Reader) int {
|
||||
buf := make([]byte, 128<<10)
|
||||
n, _ := io.ReadFull(r, buf)
|
||||
d := buf[:n]
|
||||
if len(d) < 4 || d[0] != 0xFF || d[1] != 0xD8 {
|
||||
return 1
|
||||
}
|
||||
i := 2
|
||||
for i+4 <= len(d) {
|
||||
if d[i] != 0xFF {
|
||||
return 1
|
||||
}
|
||||
marker := d[i+1]
|
||||
if marker == 0xDA || marker == 0xD9 { // début des données ou fin
|
||||
return 1
|
||||
}
|
||||
size := int(binary.BigEndian.Uint16(d[i+2:]))
|
||||
if size < 2 || i+2+size > len(d) {
|
||||
return 1
|
||||
}
|
||||
if marker == 0xE1 && size >= 16 && string(d[i+4:i+10]) == "Exif\x00\x00" {
|
||||
return exifOrientation(d[i+10 : i+2+size])
|
||||
}
|
||||
i += 2 + size
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
func exifOrientation(t []byte) int {
|
||||
if len(t) < 8 {
|
||||
return 1
|
||||
}
|
||||
var bo binary.ByteOrder
|
||||
switch string(t[:2]) {
|
||||
case "II":
|
||||
bo = binary.LittleEndian
|
||||
case "MM":
|
||||
bo = binary.BigEndian
|
||||
default:
|
||||
return 1
|
||||
}
|
||||
off := int(bo.Uint32(t[4:]))
|
||||
if off < 8 || off+2 > len(t) {
|
||||
return 1
|
||||
}
|
||||
count := int(bo.Uint16(t[off:]))
|
||||
for k := 0; k < count; k++ {
|
||||
e := off + 2 + k*12
|
||||
if e+12 > len(t) {
|
||||
return 1
|
||||
}
|
||||
if bo.Uint16(t[e:]) == 0x0112 {
|
||||
if v := int(bo.Uint16(t[e+8:])); v >= 1 && v <= 8 {
|
||||
return v
|
||||
}
|
||||
return 1
|
||||
}
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
// orient applique l'orientation EXIF o (2 : miroir horizontal, 3 : 180°,
|
||||
// 4 : miroir vertical, 5 : transposée, 6 : 90° horaire, 7 : transverse,
|
||||
// 8 : 90° anti-horaire).
|
||||
func orient(src *image.RGBA, o int) *image.RGBA {
|
||||
if o <= 1 || o > 8 {
|
||||
return src
|
||||
}
|
||||
w, h := src.Bounds().Dx(), src.Bounds().Dy()
|
||||
dw, dh := w, h
|
||||
if o >= 5 {
|
||||
dw, dh = h, w
|
||||
}
|
||||
dst := image.NewRGBA(image.Rect(0, 0, dw, dh))
|
||||
for y := 0; y < h; y++ {
|
||||
for x := 0; x < w; x++ {
|
||||
var nx, ny int
|
||||
switch o {
|
||||
case 2:
|
||||
nx, ny = w-1-x, y
|
||||
case 3:
|
||||
nx, ny = w-1-x, h-1-y
|
||||
case 4:
|
||||
nx, ny = x, h-1-y
|
||||
case 5:
|
||||
nx, ny = y, x
|
||||
case 6:
|
||||
nx, ny = h-1-y, x
|
||||
case 7:
|
||||
nx, ny = h-1-y, w-1-x
|
||||
case 8:
|
||||
nx, ny = y, w-1-x
|
||||
}
|
||||
copy(dst.Pix[dst.PixOffset(nx, ny):dst.PixOffset(nx, ny)+4], src.Pix[src.PixOffset(x, y):src.PixOffset(x, y)+4])
|
||||
}
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
||||
// Les opérations suivantes accompagnent Move/Delete. Elles sont « au mieux » :
|
||||
// une miniature manquante sera simplement régénérée.
|
||||
|
||||
func (s *Store) moveThumb(from, to string, isDir bool) {
|
||||
src, dst := s.thumbAbs(from, isDir), s.thumbAbs(to, isDir)
|
||||
if _, err := os.Stat(src); err != nil {
|
||||
return
|
||||
}
|
||||
_ = os.RemoveAll(dst)
|
||||
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err == nil {
|
||||
_ = os.Rename(src, dst)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Store) removeThumb(c string) {
|
||||
_ = os.Remove(s.thumbAbs(c, false))
|
||||
_ = os.RemoveAll(s.thumbAbs(c, true))
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Corbeille : Delete range chaque élément supprimé dans .trash/<id>/, avec
|
||||
//
|
||||
// .trash/<id>/<nom> l'élément lui-même
|
||||
// .trash/<id>/.history/<nom> son historique de versions
|
||||
// .trash/<id>/.info.json chemin d'origine, date, auteur, tags et icônes
|
||||
//
|
||||
// L'élément peut être restauré à son emplacement d'origine ou supprimé
|
||||
// définitivement. Les éléments plus anciens que Settings.TrashDays (0 : jamais)
|
||||
// sont purgés automatiquement (Spaces.PurgeTrash).
|
||||
|
||||
const trashInfoFile = ".info.json"
|
||||
|
||||
const trashLayout = "20060102T150405.000000000"
|
||||
|
||||
var trashID = regexp.MustCompile(`^\d{8}T\d{6}\.\d{9}$`)
|
||||
|
||||
type trashInfo struct {
|
||||
Path string `json:"path"`
|
||||
Deleted time.Time `json:"deleted"`
|
||||
By string `json:"by,omitempty"`
|
||||
Meta map[string]itemMeta `json:"meta,omitempty"` // clés relatives à Path
|
||||
}
|
||||
|
||||
// TrashItem décrit un élément de la corbeille. Path est son chemin d'origine.
|
||||
type TrashItem struct {
|
||||
ID string
|
||||
Name string
|
||||
Path string
|
||||
IsDir bool
|
||||
Size int64
|
||||
Deleted time.Time
|
||||
By string
|
||||
}
|
||||
|
||||
func (s *Store) trashAbs(id string) string { return filepath.Join(s.root, trashDir, id) }
|
||||
|
||||
// trash range l'élément c (chemin absolu abs) dans une nouvelle entrée de
|
||||
// corbeille, avec son historique et ses métadonnées.
|
||||
func (s *Store) trash(c, abs, by string) error {
|
||||
now := time.Now().UTC()
|
||||
id := now.Format(trashLayout)
|
||||
dir := s.trashAbs(id)
|
||||
for i := 1; ; i++ { // deux suppressions dans la même nanoseconde
|
||||
if _, err := os.Lstat(dir); errors.Is(err, fs.ErrNotExist) {
|
||||
break
|
||||
}
|
||||
id = now.Add(time.Duration(i)).Format(trashLayout)
|
||||
dir = s.trashAbs(id)
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(abs, filepath.Join(dir, filepath.Base(abs))); err != nil {
|
||||
_ = os.Remove(dir)
|
||||
return err
|
||||
}
|
||||
info := trashInfo{Path: c, Deleted: now, By: by, Meta: s.takeMeta(c)}
|
||||
if b, err := json.Marshal(info); err == nil {
|
||||
_ = atomicWrite(filepath.Join(dir, trashInfoFile), b)
|
||||
}
|
||||
s.trashHistory(c, dir)
|
||||
return nil
|
||||
}
|
||||
|
||||
// trashEntry lit une entrée de la corbeille : nom de l'élément et informations
|
||||
// (déduites du nom et de l'identifiant pour les entrées d'avant .info.json).
|
||||
func (s *Store) trashEntry(id string) (string, trashInfo, error) {
|
||||
if !trashID.MatchString(id) {
|
||||
return "", trashInfo{}, fmt.Errorf("%w : élément de corbeille %q", ErrInvalidPath, id)
|
||||
}
|
||||
dir := s.trashAbs(id)
|
||||
des, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return "", trashInfo{}, mapErr(err)
|
||||
}
|
||||
name := ""
|
||||
for _, de := range des {
|
||||
if !strings.HasPrefix(de.Name(), ".") {
|
||||
name = de.Name()
|
||||
break
|
||||
}
|
||||
}
|
||||
if name == "" {
|
||||
return "", trashInfo{}, ErrNotFound
|
||||
}
|
||||
var info trashInfo
|
||||
if b, err := os.ReadFile(filepath.Join(dir, trashInfoFile)); err == nil {
|
||||
_ = json.Unmarshal(b, &info)
|
||||
}
|
||||
if c, err := Clean(info.Path); err != nil || c == "" || path.Base(c) != name {
|
||||
info.Path = name // emplacement inconnu : restauration à la racine
|
||||
}
|
||||
if info.Deleted.IsZero() {
|
||||
info.Deleted, _ = time.Parse(trashLayout, id)
|
||||
}
|
||||
return name, info, nil
|
||||
}
|
||||
|
||||
// TrashItems liste la corbeille, les suppressions les plus récentes en premier.
|
||||
func (s *Store) TrashItems() ([]TrashItem, error) {
|
||||
des, err := os.ReadDir(filepath.Join(s.root, trashDir))
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return []TrashItem{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := []TrashItem{}
|
||||
for _, de := range des {
|
||||
if !de.IsDir() || !trashID.MatchString(de.Name()) {
|
||||
continue
|
||||
}
|
||||
name, info, err := s.trashEntry(de.Name())
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
fi, err := os.Lstat(filepath.Join(s.trashAbs(de.Name()), name))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
it := TrashItem{ID: de.Name(), Name: name, Path: info.Path, IsDir: fi.IsDir(), Deleted: info.Deleted, By: info.By}
|
||||
if !it.IsDir {
|
||||
it.Size = fi.Size()
|
||||
}
|
||||
out = append(out, it)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].ID > out[j].ID })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// TrashCount renvoie le nombre d'éléments dans la corbeille.
|
||||
func (s *Store) TrashCount() int {
|
||||
des, _ := os.ReadDir(filepath.Join(s.root, trashDir))
|
||||
n := 0
|
||||
for _, de := range des {
|
||||
if de.IsDir() && trashID.MatchString(de.Name()) {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// RestoreTrash remet un élément à son emplacement d'origine (dossiers parents
|
||||
// recréés au besoin), sous un autre nom si la place est prise.
|
||||
func (s *Store) RestoreTrash(id string) (Entry, error) {
|
||||
name, info, err := s.trashEntry(id)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
dir := s.trashAbs(id)
|
||||
src := filepath.Join(dir, name)
|
||||
fi, err := os.Lstat(src)
|
||||
if err != nil {
|
||||
return Entry{}, mapErr(err)
|
||||
}
|
||||
c := s.freeName(info.Path, fi.IsDir(), " (restauré %d)")
|
||||
_, abs, err := s.resolve(c)
|
||||
if err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(abs), 0o755); err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
if err := os.Rename(src, abs); err != nil {
|
||||
return Entry{}, mapErr(err)
|
||||
}
|
||||
moveAside(filepath.Join(dir, historyDir, name), s.historyAbs(c))
|
||||
s.putMeta(c, info.Meta)
|
||||
_ = os.RemoveAll(dir)
|
||||
if fi, err = os.Stat(abs); err != nil {
|
||||
return Entry{}, err
|
||||
}
|
||||
e := toEntry(c, fi)
|
||||
decorate(&e, s.metaSnapshot())
|
||||
return e, nil
|
||||
}
|
||||
|
||||
// DropTrash supprime définitivement un élément de la corbeille.
|
||||
func (s *Store) DropTrash(id string) error {
|
||||
if _, _, err := s.trashEntry(id); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.RemoveAll(s.trashAbs(id))
|
||||
}
|
||||
|
||||
// EmptyTrash vide la corbeille.
|
||||
func (s *Store) EmptyTrash() error {
|
||||
return s.purgeTrash(func(string) bool { return true })
|
||||
}
|
||||
|
||||
// PurgeTrashOlder supprime définitivement les éléments supprimés il y a plus de maxAge.
|
||||
func (s *Store) PurgeTrashOlder(maxAge time.Duration) error {
|
||||
limit := time.Now().Add(-maxAge)
|
||||
return s.purgeTrash(func(id string) bool {
|
||||
t, err := time.Parse(trashLayout, id)
|
||||
return err == nil && t.Before(limit)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Store) purgeTrash(drop func(id string) bool) error {
|
||||
root := filepath.Join(s.root, trashDir)
|
||||
des, err := os.ReadDir(root)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var first error
|
||||
for _, de := range des {
|
||||
if !de.IsDir() || !trashID.MatchString(de.Name()) || !drop(de.Name()) {
|
||||
continue
|
||||
}
|
||||
if err := os.RemoveAll(filepath.Join(root, de.Name())); err != nil && first == nil {
|
||||
first = err
|
||||
}
|
||||
}
|
||||
return first
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Téléchargement d'un dossier ou d'une sélection en archive ZIP, générée en
|
||||
// flux (aucun fichier temporaire, mémoire constante).
|
||||
|
||||
// ZipItem est un fichier ou un dossier à archiver : Abs est son chemin sur le
|
||||
// disque, Name son nom dans l'archive.
|
||||
type ZipItem struct {
|
||||
Abs string
|
||||
Name string
|
||||
}
|
||||
|
||||
// compressed : extensions déjà compressées, stockées sans recompression.
|
||||
var compressed = map[string]bool{
|
||||
".zip": true, ".gz": true, ".tgz": true, ".bz2": true, ".xz": true, ".7z": true, ".rar": true, ".zst": true,
|
||||
".jpg": true, ".jpeg": true, ".png": true, ".gif": true, ".webp": true, ".avif": true, ".heic": true,
|
||||
".mp3": true, ".aac": true, ".ogg": true, ".opus": true, ".flac": true, ".m4a": true,
|
||||
".mp4": true, ".mkv": true, ".webm": true, ".mov": true, ".avi": true, ".m4v": true,
|
||||
".pdf": true, ".docx": true, ".xlsx": true, ".pptx": true, ".odt": true, ".ods": true, ".jar": true,
|
||||
}
|
||||
|
||||
// ZipItems traduit des chemins virtuels en éléments à archiver ; les doublons
|
||||
// de noms (même nom dans deux dossiers) reçoivent un suffixe « (2) ». Renvoie
|
||||
// aussi un nom d'archive : celui de l'élément unique, sinon « fichiers ».
|
||||
func (u *Space) ZipItems(paths []string) ([]ZipItem, string, error) {
|
||||
if len(paths) == 0 {
|
||||
return nil, "", ErrInvalidPath
|
||||
}
|
||||
var items []ZipItem
|
||||
used := map[string]bool{}
|
||||
for _, p := range paths {
|
||||
st, rel, err := u.route(p)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
c, abs, err := st.resolve(rel)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
name := path.Base(c)
|
||||
if c == "" {
|
||||
name = "fichiers" // racine de l'espace personnel
|
||||
}
|
||||
fi, err := os.Lstat(abs)
|
||||
if err != nil {
|
||||
return nil, "", mapErr(err)
|
||||
}
|
||||
if !fi.IsDir() && !fi.Mode().IsRegular() {
|
||||
return nil, "", ErrNotFound
|
||||
}
|
||||
items = append(items, ZipItem{Abs: abs, Name: uniqueZipName(name, used)})
|
||||
}
|
||||
archive := "fichiers"
|
||||
if len(items) == 1 {
|
||||
archive = items[0].Name
|
||||
}
|
||||
return items, archive, nil
|
||||
}
|
||||
|
||||
func uniqueZipName(name string, used map[string]bool) string {
|
||||
n := name
|
||||
for i := 2; used[strings.ToLower(n)]; i++ {
|
||||
ext := path.Ext(name)
|
||||
n = fmt.Sprintf("%s (%d)%s", strings.TrimSuffix(name, ext), i, ext)
|
||||
}
|
||||
used[strings.ToLower(n)] = true
|
||||
return n
|
||||
}
|
||||
|
||||
// SharedZipItem renvoie l'élément d'un lien de partage (ou d'un de ses
|
||||
// sous-dossiers) à archiver.
|
||||
func (s *Store) SharedZipItem(rel string) (ZipItem, error) {
|
||||
c, abs, err := s.resolve(rel)
|
||||
if err != nil {
|
||||
return ZipItem{}, err
|
||||
}
|
||||
if _, err := os.Lstat(abs); err != nil {
|
||||
return ZipItem{}, mapErr(err)
|
||||
}
|
||||
return ZipItem{Abs: abs, Name: path.Base(c)}, nil
|
||||
}
|
||||
|
||||
// WriteZip écrit les éléments dans w au format ZIP. Les liens symboliques, les
|
||||
// fichiers spéciaux et les fichiers internes (noms cachés) sont ignorés ; un
|
||||
// fichier illisible est sauté sans interrompre l'archive.
|
||||
func WriteZip(w io.Writer, items []ZipItem) error {
|
||||
zw := zip.NewWriter(w)
|
||||
for _, it := range items {
|
||||
fi, err := os.Lstat(it.Abs)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if !fi.IsDir() {
|
||||
if err := addZipFile(zw, it.Abs, it.Name, fi); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
err = filepath.WalkDir(it.Abs, func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if p != it.Abs && !visible(d.Name()) {
|
||||
if d.IsDir() {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
rel, _ := filepath.Rel(it.Abs, p)
|
||||
name := it.Name
|
||||
if rel != "." {
|
||||
name = path.Join(it.Name, filepath.ToSlash(rel))
|
||||
}
|
||||
switch {
|
||||
case d.IsDir():
|
||||
h := &zip.FileHeader{Name: name + "/", Method: zip.Store}
|
||||
if info, err := d.Info(); err == nil {
|
||||
h.Modified = info.ModTime()
|
||||
}
|
||||
_, err := zw.CreateHeader(h)
|
||||
return err
|
||||
case d.Type().IsRegular():
|
||||
info, err := d.Info()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return addZipFile(zw, p, name, info)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return zw.Close()
|
||||
}
|
||||
|
||||
func addZipFile(zw *zip.Writer, abs, name string, fi fs.FileInfo) error {
|
||||
f, err := os.Open(abs)
|
||||
if err != nil {
|
||||
return nil // fichier illisible : sauté
|
||||
}
|
||||
defer f.Close()
|
||||
h := &zip.FileHeader{Name: name, Method: zip.Deflate, Modified: fi.ModTime()}
|
||||
if compressed[strings.ToLower(path.Ext(name))] {
|
||||
h.Method = zip.Store
|
||||
}
|
||||
h.UncompressedSize64 = uint64(fi.Size())
|
||||
out, err := zw.CreateHeader(h)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = io.Copy(out, f)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
// Package tokens gère les jetons d'accès personnels à l'API : créés depuis
|
||||
// l'interface (sans expiration, révocables), ils permettent d'envoyer et de
|
||||
// télécharger des fichiers depuis un script (curl, rclone WebDAV non inclus...)
|
||||
// sans session de navigateur.
|
||||
//
|
||||
// Les jetons ne sont conservés que hachés (SHA-256) dans DATA_DIR/.tokens.json
|
||||
// (0600), rattachés à l'utilisateur qui les a créés : ils donnent accès à ses
|
||||
// fichiers comme sa session, mais ne peuvent pas gérer les jetons ni les comptes.
|
||||
package tokens
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/vblogio/upandown/internal/auth"
|
||||
)
|
||||
|
||||
const (
|
||||
fileName = ".tokens.json"
|
||||
prefix = "upd_"
|
||||
maxPerUser = 50
|
||||
MaxNameLen = 80
|
||||
touchEvery = time.Minute
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("jeton introuvable")
|
||||
ErrInvalid = errors.New("nom de jeton invalide")
|
||||
ErrTooMany = errors.New("trop de jetons : en révoquer avant d'en créer")
|
||||
)
|
||||
|
||||
// Token est un jeton enregistré (sans le secret, que seul son hachage représente).
|
||||
type Token struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
UserID string `json:"userId"`
|
||||
Hash string `json:"hash"`
|
||||
Created time.Time `json:"created"`
|
||||
LastUsed time.Time `json:"lastUsed,omitzero"`
|
||||
}
|
||||
|
||||
// Info est la vue d'un jeton renvoyée à l'interface.
|
||||
type Info struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Created time.Time `json:"created"`
|
||||
LastUsed time.Time `json:"lastUsed,omitzero"`
|
||||
}
|
||||
|
||||
func (t *Token) info() Info {
|
||||
return Info{ID: t.ID, Name: t.Name, Created: t.Created, LastUsed: t.LastUsed}
|
||||
}
|
||||
|
||||
// Store conserve les jetons dans dir/.tokens.json.
|
||||
type Store struct {
|
||||
mu sync.Mutex
|
||||
file string
|
||||
tokens []*Token
|
||||
}
|
||||
|
||||
// Open charge (ou crée) le fichier des jetons de dir.
|
||||
func Open(dir string) (*Store, error) {
|
||||
s := &Store{file: filepath.Join(dir, fileName)}
|
||||
b, err := os.ReadFile(s.file)
|
||||
switch {
|
||||
case errors.Is(err, os.ErrNotExist):
|
||||
case err != nil:
|
||||
return nil, err
|
||||
default:
|
||||
var d struct {
|
||||
Tokens []*Token `json:"tokens"`
|
||||
}
|
||||
if err := json.Unmarshal(b, &d); err != nil {
|
||||
return nil, errors.New(s.file + " invalide : " + err.Error())
|
||||
}
|
||||
s.tokens = d.Tokens
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (s *Store) save() error {
|
||||
b, err := json.Marshal(map[string]any{"tokens": s.tokens})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp, err := os.CreateTemp(filepath.Dir(s.file), ".tmp-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(tmp.Name())
|
||||
if err := tmp.Chmod(0o600); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if _, err := tmp.Write(b); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp.Name(), s.file)
|
||||
}
|
||||
|
||||
func hashOf(secret string) string {
|
||||
h := sha256.Sum256([]byte(secret))
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
func randomString(n int) string {
|
||||
b := make([]byte, n)
|
||||
_, _ = rand.Read(b)
|
||||
return base64.RawURLEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
// Create crée un jeton pour userID ; le secret n'est renvoyé qu'ici.
|
||||
func (s *Store) Create(userID, name string) (string, Info, error) {
|
||||
name = strings.Join(strings.Fields(name), " ")
|
||||
if name == "" || !utf8.ValidString(name) || utf8.RuneCountInString(name) > MaxNameLen {
|
||||
return "", Info{}, ErrInvalid
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
n := 0
|
||||
for _, t := range s.tokens {
|
||||
if t.UserID == userID {
|
||||
n++
|
||||
}
|
||||
}
|
||||
if n >= maxPerUser {
|
||||
return "", Info{}, ErrTooMany
|
||||
}
|
||||
secret := prefix + randomString(32)
|
||||
t := &Token{ID: randomString(9), Name: name, UserID: userID, Hash: hashOf(secret), Created: time.Now().UTC().Truncate(time.Second)}
|
||||
s.tokens = append(s.tokens, t)
|
||||
if err := s.save(); err != nil {
|
||||
s.tokens = s.tokens[:len(s.tokens)-1]
|
||||
return "", Info{}, err
|
||||
}
|
||||
return secret, t.info(), nil
|
||||
}
|
||||
|
||||
// List renvoie les jetons de userID, les plus récents en premier.
|
||||
func (s *Store) List(userID string) []Info {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out := []Info{}
|
||||
for _, t := range s.tokens {
|
||||
if t.UserID == userID {
|
||||
out = append(out, t.info())
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Created.After(out[j].Created) })
|
||||
return out
|
||||
}
|
||||
|
||||
// Revoke supprime un jeton de userID.
|
||||
func (s *Store) Revoke(userID, id string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for i, t := range s.tokens {
|
||||
if t.ID == id && t.UserID == userID {
|
||||
s.tokens = append(s.tokens[:i:i], s.tokens[i+1:]...)
|
||||
return s.save()
|
||||
}
|
||||
}
|
||||
return ErrNotFound
|
||||
}
|
||||
|
||||
// RevokeUser supprime tous les jetons d'un utilisateur (compte supprimé ou désactivé).
|
||||
func (s *Store) RevokeUser(userID string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
kept := s.tokens[:0:0]
|
||||
for _, t := range s.tokens {
|
||||
if t.UserID != userID {
|
||||
kept = append(kept, t)
|
||||
}
|
||||
}
|
||||
if len(kept) != len(s.tokens) {
|
||||
s.tokens = kept
|
||||
_ = s.save()
|
||||
}
|
||||
}
|
||||
|
||||
// Lookup renvoie le jeton correspondant à secret.
|
||||
func (s *Store) Lookup(secret string) (Token, bool) {
|
||||
if !strings.HasPrefix(secret, prefix) {
|
||||
return Token{}, false
|
||||
}
|
||||
h := hashOf(secret)
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for _, t := range s.tokens {
|
||||
if t.Hash == h {
|
||||
if time.Since(t.LastUsed) > touchEvery {
|
||||
t.LastUsed = time.Now().UTC().Truncate(time.Second)
|
||||
_ = s.save()
|
||||
}
|
||||
return *t, true
|
||||
}
|
||||
}
|
||||
return Token{}, false
|
||||
}
|
||||
|
||||
// --- HTTP ---------------------------------------------------------------------------------
|
||||
|
||||
type tokenKey struct{}
|
||||
|
||||
// FromContext renvoie le jeton qui a authentifié la requête (nil : session).
|
||||
func FromContext(ctx context.Context) *Token {
|
||||
t, _ := ctx.Value(tokenKey{}).(*Token)
|
||||
return t
|
||||
}
|
||||
|
||||
// Server expose les jetons en HTTP.
|
||||
type Server struct {
|
||||
Store *Store
|
||||
// Resolve renvoie l'utilisateur actif d'un identifiant de compte (nil, true :
|
||||
// pas d'authentification intégrée ; _, false : compte inexistant ou inactif).
|
||||
Resolve func(userID string) (*auth.User, bool)
|
||||
// UserID identifie l'utilisateur d'une requête de l'interface.
|
||||
UserID func(*http.Request) string
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
func bearer(r *http.Request) (string, bool) {
|
||||
scheme, tok, ok := strings.Cut(r.Header.Get("Authorization"), " ")
|
||||
if !ok || !strings.EqualFold(scheme, "Bearer") {
|
||||
return "", false
|
||||
}
|
||||
return strings.TrimSpace(tok), true
|
||||
}
|
||||
|
||||
// Middleware authentifie les requêtes porteuses d'un jeton (Authorization:
|
||||
// Bearer) et les transmet directement à mux avec l'utilisateur du jeton ; les
|
||||
// autres suivent next (session).
|
||||
func (s *Server) Middleware(next, mux http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
secret, ok := bearer(r)
|
||||
if !ok {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
t, valid := s.Store.Lookup(secret)
|
||||
var u *auth.User
|
||||
if valid {
|
||||
u, valid = s.Resolve(t.UserID)
|
||||
}
|
||||
if !valid {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer error="invalid_token"`)
|
||||
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "jeton d'accès invalide ou révoqué"})
|
||||
return
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), tokenKey{}, &t)
|
||||
if u != nil {
|
||||
ctx = auth.WithUser(ctx, u)
|
||||
}
|
||||
mux.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
// Register enregistre les routes des jetons.
|
||||
//
|
||||
// GET /api/tokens jetons de l'utilisateur
|
||||
// POST /api/tokens {"name"} nouveau jeton (renvoyé une seule fois)
|
||||
// DELETE /api/tokens/{id} révocation
|
||||
func (s *Server) Register(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/tokens", s.session(func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, s.Store.List(s.UserID(r)))
|
||||
}))
|
||||
mux.HandleFunc("POST /api/tokens", s.session(func(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&req) != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "requête JSON invalide"})
|
||||
return
|
||||
}
|
||||
secret, info, err := s.Store.Create(s.UserID(r), req.Name)
|
||||
if err != nil {
|
||||
status := http.StatusInternalServerError
|
||||
if errors.Is(err, ErrInvalid) || errors.Is(err, ErrTooMany) {
|
||||
status = http.StatusBadRequest
|
||||
}
|
||||
writeJSON(w, status, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, http.StatusCreated, struct {
|
||||
Info
|
||||
Token string `json:"token"`
|
||||
}{info, secret})
|
||||
}))
|
||||
mux.HandleFunc("DELETE /api/tokens/{id}", s.session(func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := s.Store.Revoke(s.UserID(r), r.PathValue("id")); err != nil {
|
||||
status := http.StatusInternalServerError
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
status = http.StatusNotFound
|
||||
}
|
||||
writeJSON(w, status, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
}
|
||||
|
||||
// session refuse les requêtes authentifiées par un jeton : un jeton ne peut
|
||||
// pas créer, lister ni révoquer de jetons.
|
||||
func (s *Server) session(h http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if FromContext(r.Context()) != nil {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "gestion des jetons réservée à la session de l'interface"})
|
||||
return
|
||||
}
|
||||
h(w, r)
|
||||
}
|
||||
}
|
||||
Vendored
Whitespace-only changes.
@@ -0,0 +1,10 @@
|
||||
// Package web embarque le frontend compilé (frontend/ -> web/dist) dans le binaire.
|
||||
package web
|
||||
|
||||
import "embed"
|
||||
|
||||
// Dist contient le build Vite. En développement, dist/ peut ne contenir que
|
||||
// .gitkeep : le serveur affiche alors un message invitant à lancer le build.
|
||||
//
|
||||
//go:embed all:dist
|
||||
var Dist embed.FS
|
||||
Reference in new issue
Block a user