Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8d3a47bd91 | |||
| 073f2cf9ca | |||
| 36bfeb057e | |||
| 7a3c119f36 | |||
| 813dfd952c | |||
| 693e6736de | |||
| 33295a7aaf | |||
| 755cba6b78 | |||
| fe2a3e66c7 | |||
| b070b74929 | |||
| c9670ca309 | |||
| 5c1c2a8591 | |||
| 9a4bb5efa1 | |||
| d6c110fc3b |
22
.github/workflows/ci.yml
vendored
22
.github/workflows/ci.yml
vendored
@@ -41,20 +41,26 @@ jobs:
|
|||||||
cache: npm
|
cache: npm
|
||||||
- run: npm ci
|
- run: npm ci
|
||||||
- run: npm run build
|
- run: npm run build
|
||||||
# @arboretum/shared (dépendance runtime non publiée) est embarquée dans le tarball
|
# @arboretum/shared (paquet workspace NON publié) est INLINÉ dans dist/_shared au prepack
|
||||||
# via bundleDependencies (matérialisée au prepack). On packe donc UN SEUL tarball
|
# (scripts/inline-shared.mjs) : le tarball est 100 % autonome — aucun node_modules embarqué,
|
||||||
# et on l'installe seul, comme un vrai consommateur depuis le registre.
|
# aucune bundleDependency, aucun symlink. On packe en mode workspace (-w), EXACTEMENT comme
|
||||||
|
# le fait « npm publish » dans release.yml, puis on l'installe seul comme un vrai consommateur.
|
||||||
- name: Pack tarball
|
- name: Pack tarball
|
||||||
run: |
|
run: |
|
||||||
mkdir -p /tmp/tarballs
|
rm -rf /tmp/tarballs && mkdir -p /tmp/tarballs
|
||||||
npm pack -w @johanleroy/git-arboretum --pack-destination /tmp/tarballs
|
npm pack -w @johanleroy/git-arboretum --pack-destination /tmp/tarballs
|
||||||
ls -l /tmp/tarballs
|
ls -l /tmp/tarballs
|
||||||
- name: Assert @arboretum/shared is bundled in the tarball
|
- name: Assert the package is self-contained (@arboretum/shared inlined)
|
||||||
run: |
|
run: |
|
||||||
tgz=$(ls /tmp/tarballs/*.tgz)
|
tgz=$(ls /tmp/tarballs/*.tgz)
|
||||||
tar -tzf "$tgz" | grep -q 'node_modules/@arboretum/shared/dist/index.js' \
|
rm -rf /tmp/inspect && mkdir -p /tmp/inspect && tar -xzf "$tgz" -C /tmp/inspect
|
||||||
|| { echo "ERREUR: @arboretum/shared non embarqué dans $tgz"; exit 1; }
|
test -f /tmp/inspect/package/dist/_shared/index.js \
|
||||||
echo "OK: bundleDependency @arboretum/shared présente dans $tgz"
|
|| { echo "ERREUR: dist/_shared/index.js absent de $tgz — inline-shared n'a pas tourné ?"; exit 1; }
|
||||||
|
if grep -rq '@arboretum/shared' /tmp/inspect/package/dist; then
|
||||||
|
echo "ERREUR: import bare '@arboretum/shared' encore présent dans le JS publié"
|
||||||
|
grep -rn '@arboretum/shared' /tmp/inspect/package/dist; exit 1
|
||||||
|
fi
|
||||||
|
echo "OK: paquet autonome — shared inliné dans dist/_shared, aucun import externe"
|
||||||
- name: Install tarball in an empty project
|
- name: Install tarball in an empty project
|
||||||
run: |
|
run: |
|
||||||
mkdir /tmp/smoke
|
mkdir /tmp/smoke
|
||||||
|
|||||||
37
.github/workflows/release.yml
vendored
37
.github/workflows/release.yml
vendored
@@ -35,8 +35,39 @@ jobs:
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
echo "OK: tag $tag == version $pkg"
|
echo "OK: tag $tag == version $pkg"
|
||||||
- run: npm publish -w @johanleroy/git-arboretum
|
# Publication idempotente : le signal faisant autorité d'une version déjà présente est le
|
||||||
|
# 409 « already exists » renvoyé par npm publish lui-même (npm view est non fiable contre le
|
||||||
|
# registre npm de Gitea — faux négatif masqué par >/dev/null). On tente toujours le publish ;
|
||||||
|
# un 409 = succès idempotent, tout autre échec reste fatal. Le shell Actions tourne en
|
||||||
|
# `bash -eo pipefail` : on isole l'échec attendu dans la condition d'un `if` pour ne pas
|
||||||
|
# déclencher `set -e`. Le secret du registre est mappé sur NODE_AUTH_TOKEN lu par le .npmrc
|
||||||
|
# de setup-node.
|
||||||
|
- name: Publish (idempotent — tolère un 409 « already exists »)
|
||||||
|
run: |
|
||||||
|
if out="$(npm publish -w @johanleroy/git-arboretum 2>&1)"; then
|
||||||
|
printf '%s\n' "$out"
|
||||||
|
echo "Publication réussie."
|
||||||
|
else
|
||||||
|
code=$?
|
||||||
|
printf '%s\n' "$out"
|
||||||
|
if printf '%s' "$out" | grep -qiE 'E409|409 Conflict|already exists'; then
|
||||||
|
echo "::notice::Version déjà présente sur le registre (409) — publication idempotente, étape ignorée."
|
||||||
|
else
|
||||||
|
echo "::error::Échec de la publication (code $code)."
|
||||||
|
exit "$code"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
env:
|
env:
|
||||||
# Mapper le secret du registre (PAT Gitea write:package, ou le token auto
|
|
||||||
# GITEA_TOKEN s'il a ce scope) sur NODE_AUTH_TOKEN lu par le .npmrc de setup-node.
|
|
||||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||||
|
# SBOM (transparence supply-chain entreprise) : généré pour le paquet publié et exposé en
|
||||||
|
# artefact. C'est un bonus : un échec de génération/upload ne doit jamais faire rougir une
|
||||||
|
# release dont le publish a réussi → continue-on-error.
|
||||||
|
# upload-artifact@v3 : Gitea Actions (GHES-like) ne supporte pas @v4 (@actions/artifact v2+).
|
||||||
|
- name: Generate SBOM (CycloneDX)
|
||||||
|
continue-on-error: true
|
||||||
|
run: npx --yes @cyclonedx/cyclonedx-npm --omit dev --output-format JSON --output-file sbom.json -w @johanleroy/git-arboretum || npx --yes @cyclonedx/cyclonedx-npm --omit dev --output-format JSON --output-file sbom.json
|
||||||
|
- uses: actions/upload-artifact@v3
|
||||||
|
continue-on-error: true
|
||||||
|
with:
|
||||||
|
name: sbom
|
||||||
|
path: sbom.json
|
||||||
|
|||||||
10
README.fr.md
10
README.fr.md
@@ -209,9 +209,13 @@ Un terminal web, c'est de l'exécution de code à distance *par conception*. Les
|
|||||||
- Se bind sur `127.0.0.1` par défaut ; refuse les binds non-loopback sans flag explicite.
|
- Se bind sur `127.0.0.1` par défaut ; refuse les binds non-loopback sans flag explicite.
|
||||||
- Authentifie **chaque** requête `/api/**` **et** chaque upgrade `/ws` avec des tokens révocables, et applique un **check `Origin` strict** (le cookie `SameSite=Strict` ne couvre pas les upgrades WebSocket — c'est le garde-fou anti cross-site hijacking).
|
- Authentifie **chaque** requête `/api/**` **et** chaque upgrade `/ws` avec des tokens révocables, et applique un **check `Origin` strict** (le cookie `SameSite=Strict` ne couvre pas les upgrades WebSocket — c'est le garde-fou anti cross-site hijacking).
|
||||||
- Les tokens sont stockés **hashés** (sha256) et comparés en temps constant ; le bootstrap token n'est affiché qu'une seule fois. Le cookie de session est un payload signé HMAC, `HttpOnly` et `SameSite=Strict`, et reçoit automatiquement le flag `Secure` quand la requête arrive en HTTPS (p. ex. derrière Tailscale Serve). Le login est rate-limité avec backoff exponentiel.
|
- Les tokens sont stockés **hashés** (sha256) et comparés en temps constant ; le bootstrap token n'est affiché qu'une seule fois. Le cookie de session est un payload signé HMAC, `HttpOnly` et `SameSite=Strict`, et reçoit automatiquement le flag `Secure` quand la requête arrive en HTTPS (p. ex. derrière Tailscale Serve). Le login est rate-limité avec backoff exponentiel.
|
||||||
|
- Envoie des en-têtes HTTP durcis (CSP, `X-Frame-Options`, `nosniff`, `Referrer-Policy`, HSTS conditionnel, `no-store` sur l'API), restreint le dossier de données à `0o700` et la base à `0o600`, et **chiffre les secrets sensibles au repos** (AES-256-GCM).
|
||||||
|
- Tient un **journal d'audit** des opérations sensibles et offre l'**export/effacement RGPD** des données (Réglages → Sécurité & conformité).
|
||||||
|
|
||||||
Tailscale Serve est **la** façon d'atteindre Arboretum depuis d'autres appareils — pas seulement une recommandation : HTTPS valide, identité tailnet, aucun port ouvert. Le flag `--i-know-this-exposes-a-terminal` est une trappe de secours, pas un mode de déploiement ; n'exposez jamais Arboretum directement sur internet.
|
Tailscale Serve est **la** façon d'atteindre Arboretum depuis d'autres appareils — pas seulement une recommandation : HTTPS valide, identité tailnet, aucun port ouvert. Le flag `--i-know-this-exposes-a-terminal` est une trappe de secours, pas un mode de déploiement ; n'exposez jamais Arboretum directement sur internet.
|
||||||
|
|
||||||
|
Voir [`SECURITY.md`](SECURITY.md) pour le modèle de menace complet et [`docs/ENTERPRISE_DEPLOYMENT.md`](docs/ENTERPRISE_DEPLOYMENT.md) pour le durcissement en environnement réglementé.
|
||||||
|
|
||||||
## Ce qui le distingue
|
## Ce qui le distingue
|
||||||
|
|
||||||
| | Arboretum | GitKraken Agent Mode / Conductor / Nimbalyst | Happy / CloudCLI | Anthropic Remote Control |
|
| | Arboretum | GitKraken Agent Mode / Conductor / Nimbalyst | Happy / CloudCLI | Anthropic Remote Control |
|
||||||
@@ -251,6 +255,12 @@ node packages/server/scripts/acceptance-p4.mjs # Web Push + commande WS `answe
|
|||||||
node packages/server/scripts/acceptance-p5.mjs # groupes de travail : CRUD + broadcast WS + CASCADE
|
node packages/server/scripts/acceptance-p5.mjs # groupes de travail : CRUD + broadcast WS + CASCADE
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Soutenir le projet
|
||||||
|
|
||||||
|
Arboretum est un projet personnel libre et auto-financé. S'il vous fait gagner du temps, vous pouvez soutenir son développement :
|
||||||
|
|
||||||
|
[](https://buymeacoffee.com/johanleroy)
|
||||||
|
|
||||||
## Licence
|
## Licence
|
||||||
|
|
||||||
MIT — voir [LICENSE](LICENSE).
|
MIT — voir [LICENSE](LICENSE).
|
||||||
|
|||||||
10
README.md
10
README.md
@@ -209,9 +209,13 @@ A web terminal is remote code execution *by design*. Arboretum's guardrails are
|
|||||||
- Binds to `127.0.0.1` by default; refuses non-loopback binds without an explicit flag.
|
- Binds to `127.0.0.1` by default; refuses non-loopback binds without an explicit flag.
|
||||||
- Authenticates **every** `/api/**` request **and** every `/ws` upgrade with revocable tokens, and applies a **strict `Origin` check** (the `SameSite=Strict` cookie does not cover WebSocket upgrades — this is the anti cross-site hijacking guard).
|
- Authenticates **every** `/api/**` request **and** every `/ws` upgrade with revocable tokens, and applies a **strict `Origin` check** (the `SameSite=Strict` cookie does not cover WebSocket upgrades — this is the anti cross-site hijacking guard).
|
||||||
- Tokens are stored **hashed** (sha256) and compared in constant time; the bootstrap token is shown only once. The session cookie is an HMAC-signed payload, `HttpOnly` and `SameSite=Strict`, and it automatically gains the `Secure` flag when the request arrives over HTTPS (e.g. behind Tailscale Serve). Login is rate-limited with exponential backoff.
|
- Tokens are stored **hashed** (sha256) and compared in constant time; the bootstrap token is shown only once. The session cookie is an HMAC-signed payload, `HttpOnly` and `SameSite=Strict`, and it automatically gains the `Secure` flag when the request arrives over HTTPS (e.g. behind Tailscale Serve). Login is rate-limited with exponential backoff.
|
||||||
|
- Sends hardened HTTP headers (CSP, `X-Frame-Options`, `nosniff`, `Referrer-Policy`, conditional HSTS, `no-store` on the API), restricts the data directory to `0o700` and the database to `0o600`, and **encrypts sensitive secrets at rest** (AES-256-GCM).
|
||||||
|
- Keeps an **audit log** of sensitive operations and offers **GDPR** data export/erasure (Settings → Security & compliance).
|
||||||
|
|
||||||
Tailscale Serve is **the** way to reach Arboretum from other devices — not just a recommendation: valid HTTPS, tailnet identity, no open ports. The `--i-know-this-exposes-a-terminal` flag is an escape hatch, not a deployment mode; never expose Arboretum directly to the internet.
|
Tailscale Serve is **the** way to reach Arboretum from other devices — not just a recommendation: valid HTTPS, tailnet identity, no open ports. The `--i-know-this-exposes-a-terminal` flag is an escape hatch, not a deployment mode; never expose Arboretum directly to the internet.
|
||||||
|
|
||||||
|
See [`SECURITY.md`](SECURITY.md) for the full threat model and [`docs/ENTERPRISE_DEPLOYMENT.md`](docs/ENTERPRISE_DEPLOYMENT.md) for hardening in regulated environments.
|
||||||
|
|
||||||
## What makes it different
|
## What makes it different
|
||||||
|
|
||||||
| | Arboretum | GitKraken Agent Mode / Conductor / Nimbalyst | Happy / CloudCLI | Anthropic Remote Control |
|
| | Arboretum | GitKraken Agent Mode / Conductor / Nimbalyst | Happy / CloudCLI | Anthropic Remote Control |
|
||||||
@@ -251,6 +255,12 @@ node packages/server/scripts/acceptance-p4.mjs # Web Push + WS `answer` comman
|
|||||||
node packages/server/scripts/acceptance-p5.mjs # work groups: CRUD + WS broadcast + CASCADE
|
node packages/server/scripts/acceptance-p5.mjs # work groups: CRUD + WS broadcast + CASCADE
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Support
|
||||||
|
|
||||||
|
Arboretum is a free, self-funded side project. If it saves you time, you can support its development:
|
||||||
|
|
||||||
|
[](https://buymeacoffee.com/johanleroy)
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
MIT — see [LICENSE](LICENSE).
|
MIT — see [LICENSE](LICENSE).
|
||||||
|
|||||||
61
SECURITY.md
Normal file
61
SECURITY.md
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
# Security Policy
|
||||||
|
|
||||||
|
Arboretum is a self-hosted daemon that serves a web dashboard to drive git worktrees and the
|
||||||
|
Claude Code sessions running on them. **A web terminal is remote code execution by design** — that
|
||||||
|
is the product, not a bug. Arboretum's security model is therefore built on *structural* guards
|
||||||
|
(loopback-only binding, authenticated access, strict Origin checks) far more than on cryptography
|
||||||
|
alone.
|
||||||
|
|
||||||
|
This document describes the threat model, the controls that are implemented, the deliberate
|
||||||
|
trade-offs, and how to report a vulnerability. For hardening a deployment in a regulated
|
||||||
|
environment, see [`docs/ENTERPRISE_DEPLOYMENT.md`](docs/ENTERPRISE_DEPLOYMENT.md).
|
||||||
|
|
||||||
|
## Threat model
|
||||||
|
|
||||||
|
- **Single-user by design.** Arboretum runs on the owner's machine and is meant for one operator.
|
||||||
|
There is no multi-tenant isolation and no RBAC — and none is claimed.
|
||||||
|
- **Loopback by default.** The server binds `127.0.0.1`; `config.ts` *refuses* any non-loopback bind
|
||||||
|
unless you pass `--i-know-this-exposes-a-terminal`. Remote access is expected via **Tailscale Serve**
|
||||||
|
(TLS + tailnet identity), never by opening a port.
|
||||||
|
- **The terminal is RCE.** Anyone who can authenticate can run code. The controls below exist to make
|
||||||
|
sure only the authenticated operator reaches it, and that the surrounding surface (cookies, headers,
|
||||||
|
data at rest) is hardened.
|
||||||
|
|
||||||
|
## Implemented controls
|
||||||
|
|
||||||
|
| Area | Control | Where |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Network | Loopback-only default; non-loopback refused without explicit flag | `packages/server/src/config.ts` |
|
||||||
|
| AuthN | Global guard on **all** `/api/**` and `/ws` (only login is public, and rate-limited) | `packages/server/src/app.ts` |
|
||||||
|
| AuthN | Tokens stored **hashed** (SHA-256), compared in constant time; bootstrap token shown once | `packages/server/src/auth/service.ts` |
|
||||||
|
| Sessions | Cookie is an HMAC-SHA256 signed payload, `HttpOnly` + `SameSite=Strict`, `Secure` when HTTPS | `packages/server/src/routes/auth.ts` |
|
||||||
|
| CSRF / WS | Strict `Origin` check on every `/api/**` and `/ws` request (anti cross-site WS hijacking) | `packages/server/src/app.ts` |
|
||||||
|
| CSRF | Mutations carrying a body must be `application/json` | `packages/server/src/app.ts` |
|
||||||
|
| Rate limit | Global login rate limit with exponential backoff (not per-IP — Tailscale fronts everything as 127.0.0.1) | `packages/server/src/auth/service.ts` |
|
||||||
|
| HTTP headers | CSP, `X-Frame-Options: DENY`, `X-Content-Type-Options: nosniff`, `Referrer-Policy`, `Permissions-Policy`, conditional HSTS, `Cache-Control: no-store` on API; `Server` header stripped | `packages/server/src/app.ts` |
|
||||||
|
| Injection | All SQL is parameterized; all git calls use `execFile` (no shell); path-traversal guards | `packages/server/src/**` |
|
||||||
|
| Data at rest | DB file/dir forced to `0o600`/`0o700`; sensitive secrets (server secret, VAPID private key) encrypted with AES-256-GCM | `packages/server/src/db/index.ts`, `core/secret-box.ts` |
|
||||||
|
| Audit | Persistent audit log of sensitive mutations (tokens, settings, secrets, push, groups) | `packages/server/src/core/audit-log.ts` |
|
||||||
|
| Privacy | GDPR export (`/api/v1/data/export`) and erasure (`/api/v1/data/delete-my-data`) | `packages/server/src/routes/data.ts` |
|
||||||
|
| Install | Runs as a **user** service (systemd user unit / launchd LaunchAgent), never root | `packages/server/src/cli/install.ts` |
|
||||||
|
|
||||||
|
## Deliberate trade-offs
|
||||||
|
|
||||||
|
- **Long-lived API tokens.** Tokens do not expire by age (CLI automation stability) but can be revoked
|
||||||
|
instantly, and `last_used_at` is tracked. Review and rotate tokens periodically.
|
||||||
|
- **Encryption-at-rest key management.** With no `ARBORETUM_SECRET_KEY` set, the encryption key lives in
|
||||||
|
`dataDir/secret.key` (`0o600`) next to the database — this protects a leaked database *copy* (backup,
|
||||||
|
WAL) but not a full `dataDir` compromise. For strong protection, set `ARBORETUM_SECRET_KEY` and store it
|
||||||
|
separately from database backups. Full-DB SQLCipher is intentionally avoided (it breaks the `npx`
|
||||||
|
prebuilt portability).
|
||||||
|
- **No multi-user model.** If you need multiple operators with isolation, Arboretum is not the right tool.
|
||||||
|
|
||||||
|
## Reporting a vulnerability
|
||||||
|
|
||||||
|
Please report security issues **privately** — do not open a public issue.
|
||||||
|
|
||||||
|
- Email: **security@johanleroy.fr** (or `contact@johanleroy.fr`).
|
||||||
|
- Include a description, affected version, and reproduction steps.
|
||||||
|
- Expect an acknowledgement within **7 days** and a coordinated disclosure window of up to **90 days**.
|
||||||
|
|
||||||
|
Thank you for helping keep Arboretum users safe.
|
||||||
95
docs/ENTERPRISE_DEPLOYMENT.md
Normal file
95
docs/ENTERPRISE_DEPLOYMENT.md
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
# Enterprise deployment guide
|
||||||
|
|
||||||
|
This guide complements [`../SECURITY.md`](../SECURITY.md) with the operational steps a regulated or
|
||||||
|
security-conscious organization needs to deploy Arboretum with confidence.
|
||||||
|
|
||||||
|
## 1. Remote access: Tailscale Serve (recommended)
|
||||||
|
|
||||||
|
Never open a public port. Keep the default `127.0.0.1` bind and put Arboretum behind Tailscale Serve:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# on the host running arboretum (default bind 127.0.0.1:7317)
|
||||||
|
tailscale serve --bg 7317
|
||||||
|
```
|
||||||
|
|
||||||
|
This gives you TLS, a stable `*.ts.net` hostname, and tailnet identity. Then add that origin to the
|
||||||
|
allow-list so the strict Origin check accepts it:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
arboretum --allow-origin https://my-host.tailnet.ts.net
|
||||||
|
```
|
||||||
|
|
||||||
|
The `--i-know-this-exposes-a-terminal` flag exists only as an escape hatch for non-loopback binds; it
|
||||||
|
is **never** a deployment mode and is never injected automatically by `arboretum install`.
|
||||||
|
|
||||||
|
## 2. Encryption at rest
|
||||||
|
|
||||||
|
Sensitive secrets (the HMAC server secret and the VAPID private key) are encrypted with AES-256-GCM
|
||||||
|
before being stored in SQLite. Token values are never stored — only their SHA-256 hashes.
|
||||||
|
|
||||||
|
For **strong** protection (key not co-located with the database), provide a passphrase via the
|
||||||
|
environment instead of the on-disk key file:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ARBORETUM_SECRET_KEY='<a long random passphrase from your secrets manager>' arboretum
|
||||||
|
```
|
||||||
|
|
||||||
|
- Store this passphrase in your secrets manager / KMS, **separately** from database backups.
|
||||||
|
- Without it, the key is auto-generated in `dataDir/secret.key` (`0o600`). This still protects a leaked
|
||||||
|
database copy, but not a full `dataDir` compromise.
|
||||||
|
- Rotating the passphrase requires re-encrypting existing values; the simplest path is to revoke and
|
||||||
|
recreate the bootstrap token after rotation.
|
||||||
|
|
||||||
|
## 3. Filesystem permissions
|
||||||
|
|
||||||
|
On startup Arboretum forces `dataDir` to `0o700` and the database files (`*.db`, `-wal`, `-shm`) to
|
||||||
|
`0o600`. Verify after first run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
stat -c '%a %n' ~/.local/share/arboretum ~/.local/share/arboretum/*.db
|
||||||
|
# expect: 700 …/arboretum and 600 …/arboretum.db
|
||||||
|
```
|
||||||
|
|
||||||
|
Keep `$HOME` private (standard `0o700`). If you relocate data with `--db` or `XDG_DATA_HOME`, make sure
|
||||||
|
the target directory is not world-readable.
|
||||||
|
|
||||||
|
## 4. Audit logging
|
||||||
|
|
||||||
|
All sensitive mutations are recorded in an append-only `audit_logs` table: token create/revoke, login
|
||||||
|
success/failure, settings changes, secret generation, push subscribe/unsubscribe, group CRUD, and data
|
||||||
|
erasure. Query it via the API (paginated):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -s -H "Authorization: Bearer $TOKEN" \
|
||||||
|
'http://127.0.0.1:7317/api/v1/audit-logs?limit=100'
|
||||||
|
```
|
||||||
|
|
||||||
|
The audit log never contains secret values — only non-sensitive metadata (ids, labels, counters). It is
|
||||||
|
also visible in the dashboard under **Settings → Security & compliance**.
|
||||||
|
|
||||||
|
## 5. GDPR (data subject requests)
|
||||||
|
|
||||||
|
- **Export**: `GET /api/v1/data/export` returns every record tied to the authenticated token (token
|
||||||
|
metadata, push subscriptions, session history, settings) as JSON. Also available as a one-click
|
||||||
|
download in **Settings → Security & compliance**.
|
||||||
|
- **Erasure**: `POST /api/v1/data/delete-my-data` is a two-step call — the first response returns a
|
||||||
|
`confirm` code that must be POSTed back to execute. It purges the token's push subscriptions and
|
||||||
|
revokes the token (unless it is the last active one).
|
||||||
|
|
||||||
|
## 6. Backups & retention
|
||||||
|
|
||||||
|
- Back up the SQLite database (`arboretum.db`) with the WAL checkpointed. Treat backups as sensitive.
|
||||||
|
- If you use `ARBORETUM_SECRET_KEY`, back the key up **separately** — a database backup is useless (and
|
||||||
|
safe) without it, which is the point.
|
||||||
|
- Session history is retained until the database is reset. To start clean, stop the service and remove
|
||||||
|
the database file.
|
||||||
|
|
||||||
|
## 7. Logging hygiene
|
||||||
|
|
||||||
|
The log level is controlled by `ARBORETUM_LOG` (default `info`). Do **not** run `debug`/`trace` in
|
||||||
|
production: verbose levels may log request metadata. Keep `info` or higher.
|
||||||
|
|
||||||
|
## 8. Supply chain
|
||||||
|
|
||||||
|
Each published release ships with a CycloneDX SBOM (`sbom.json`) generated in CI, so you can scan the
|
||||||
|
dependency tree for known vulnerabilities before deploying.
|
||||||
192
package-lock.json
generated
192
package-lock.json
generated
@@ -720,9 +720,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@fastify/static": {
|
"node_modules/@fastify/static": {
|
||||||
"version": "8.3.0",
|
"version": "9.1.3",
|
||||||
"resolved": "https://registry.npmjs.org/@fastify/static/-/static-8.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@fastify/static/-/static-9.1.3.tgz",
|
||||||
"integrity": "sha512-yKxviR5PH1OKNnisIzZKmgZSus0r2OZb8qCSbqmw34aolT4g3UlzYfeBRym+HJ1J471CR8e2ldNub4PubD1coA==",
|
"integrity": "sha512-aXrYtsiryLhRxRNaxNqsn7FUISeb7rB9q4eHUPIot5aeQBLNahnz1m6thzm7JWC1poSGXS9XrX8DvuMivp2hkQ==",
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
"type": "github",
|
"type": "github",
|
||||||
@@ -737,10 +737,10 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@fastify/accept-negotiator": "^2.0.0",
|
"@fastify/accept-negotiator": "^2.0.0",
|
||||||
"@fastify/send": "^4.0.0",
|
"@fastify/send": "^4.0.0",
|
||||||
"content-disposition": "^0.5.4",
|
"content-disposition": "^1.0.1",
|
||||||
"fastify-plugin": "^5.0.0",
|
"fastify-plugin": "^5.0.0",
|
||||||
"fastq": "^1.17.1",
|
"fastq": "^1.17.1",
|
||||||
"glob": "^11.0.0"
|
"glob": "^13.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@fastify/websocket": {
|
"node_modules/@fastify/websocket": {
|
||||||
@@ -839,15 +839,6 @@
|
|||||||
"url": "https://github.com/sponsors/kazupon"
|
"url": "https://github.com/sponsors/kazupon"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@isaacs/cliui": {
|
|
||||||
"version": "9.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-9.0.0.tgz",
|
|
||||||
"integrity": "sha512-AokJm4tuBHillT+FpMtxQ60n8ObyXBatq7jD2/JA9dxbDDokKQm8KMht5ibGzLVU9IJDIKK4TPKgMHEYMn3lMg==",
|
|
||||||
"license": "BlueOak-1.0.0",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=18"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@johanleroy/git-arboretum": {
|
"node_modules/@johanleroy/git-arboretum": {
|
||||||
"resolved": "packages/server",
|
"resolved": "packages/server",
|
||||||
"link": true
|
"link": true
|
||||||
@@ -914,6 +905,15 @@
|
|||||||
"@jridgewell/sourcemap-codec": "^1.4.14"
|
"@jridgewell/sourcemap-codec": "^1.4.14"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@lucide/vue": {
|
||||||
|
"version": "1.21.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@lucide/vue/-/vue-1.21.0.tgz",
|
||||||
|
"integrity": "sha512-eoFn3tppjKAc12ZqdnRSMFdtwQ1ZMRQFb6SV1Eub6Y8kU28ccnqKeSFdnur9hMg8gIbosU2Y3WFJr/J/xS/IlQ==",
|
||||||
|
"license": "ISC",
|
||||||
|
"peerDependencies": {
|
||||||
|
"vue": ">=3.0.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@lukeed/ms": {
|
"node_modules/@lukeed/ms": {
|
||||||
"version": "2.0.2",
|
"version": "2.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/@lukeed/ms/-/ms-2.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/@lukeed/ms/-/ms-2.0.2.tgz",
|
||||||
@@ -2542,15 +2542,16 @@
|
|||||||
"peer": true
|
"peer": true
|
||||||
},
|
},
|
||||||
"node_modules/content-disposition": {
|
"node_modules/content-disposition": {
|
||||||
"version": "0.5.4",
|
"version": "1.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
|
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",
|
||||||
"integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==",
|
"integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
|
||||||
"safe-buffer": "5.2.1"
|
|
||||||
},
|
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">= 0.6"
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/express"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/cookie": {
|
"node_modules/cookie": {
|
||||||
@@ -2581,20 +2582,6 @@
|
|||||||
"url": "https://github.com/sponsors/mesqueeb"
|
"url": "https://github.com/sponsors/mesqueeb"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/cross-spawn": {
|
|
||||||
"version": "7.0.6",
|
|
||||||
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
|
||||||
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"path-key": "^3.1.0",
|
|
||||||
"shebang-command": "^2.0.0",
|
|
||||||
"which": "^2.0.1"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 8"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/csstype": {
|
"node_modules/csstype": {
|
||||||
"version": "3.2.3",
|
"version": "3.2.3",
|
||||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
|
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
|
||||||
@@ -2970,22 +2957,6 @@
|
|||||||
"node": ">=20"
|
"node": ">=20"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/foreground-child": {
|
|
||||||
"version": "3.3.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz",
|
|
||||||
"integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==",
|
|
||||||
"license": "ISC",
|
|
||||||
"dependencies": {
|
|
||||||
"cross-spawn": "^7.0.6",
|
|
||||||
"signal-exit": "^4.0.1"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=14"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/isaacs"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/fs-constants": {
|
"node_modules/fs-constants": {
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",
|
||||||
@@ -3014,24 +2985,17 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/glob": {
|
"node_modules/glob": {
|
||||||
"version": "11.1.0",
|
"version": "13.0.6",
|
||||||
"resolved": "https://registry.npmjs.org/glob/-/glob-11.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz",
|
||||||
"integrity": "sha512-vuNwKSaKiqm7g0THUBu2x7ckSs3XJLXE+2ssL7/MfTGPLLcrJQ/4Uq1CjPTtO5cCIiRxqvN6Twy1qOwhL0Xjcw==",
|
"integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==",
|
||||||
"deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me",
|
|
||||||
"license": "BlueOak-1.0.0",
|
"license": "BlueOak-1.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"foreground-child": "^3.3.1",
|
"minimatch": "^10.2.2",
|
||||||
"jackspeak": "^4.1.1",
|
"minipass": "^7.1.3",
|
||||||
"minimatch": "^10.1.1",
|
"path-scurry": "^2.0.2"
|
||||||
"minipass": "^7.1.2",
|
|
||||||
"package-json-from-dist": "^1.0.0",
|
|
||||||
"path-scurry": "^2.0.0"
|
|
||||||
},
|
|
||||||
"bin": {
|
|
||||||
"glob": "dist/esm/bin.mjs"
|
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "20 || >=22"
|
"node": "18 || 20 || >=22"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://github.com/sponsors/isaacs"
|
"url": "https://github.com/sponsors/isaacs"
|
||||||
@@ -3145,27 +3109,6 @@
|
|||||||
"url": "https://github.com/sponsors/mesqueeb"
|
"url": "https://github.com/sponsors/mesqueeb"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/isexe": {
|
|
||||||
"version": "2.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
|
|
||||||
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
|
|
||||||
"license": "ISC"
|
|
||||||
},
|
|
||||||
"node_modules/jackspeak": {
|
|
||||||
"version": "4.2.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-4.2.3.tgz",
|
|
||||||
"integrity": "sha512-ykkVRwrYvFm1nb2AJfKKYPr0emF6IiXDYUaFx4Zn9ZuIH7MrzEZ3sD5RlqGXNRpHtvUHJyOnCEFxOlNDtGo7wg==",
|
|
||||||
"license": "BlueOak-1.0.0",
|
|
||||||
"dependencies": {
|
|
||||||
"@isaacs/cliui": "^9.0.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": "20 || >=22"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/isaacs"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/jiti": {
|
"node_modules/jiti": {
|
||||||
"version": "2.7.0",
|
"version": "2.7.0",
|
||||||
"resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz",
|
"resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz",
|
||||||
@@ -3711,12 +3654,6 @@
|
|||||||
"wrappy": "1"
|
"wrappy": "1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/package-json-from-dist": {
|
|
||||||
"version": "1.0.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz",
|
|
||||||
"integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==",
|
|
||||||
"license": "BlueOak-1.0.0"
|
|
||||||
},
|
|
||||||
"node_modules/path-browserify": {
|
"node_modules/path-browserify": {
|
||||||
"version": "1.0.1",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz",
|
||||||
@@ -3724,15 +3661,6 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/path-key": {
|
|
||||||
"version": "3.1.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
|
|
||||||
"integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=8"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/path-scurry": {
|
"node_modules/path-scurry": {
|
||||||
"version": "2.0.2",
|
"version": "2.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz",
|
||||||
@@ -4184,27 +4112,6 @@
|
|||||||
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
|
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
|
||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
},
|
},
|
||||||
"node_modules/shebang-command": {
|
|
||||||
"version": "2.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
|
|
||||||
"integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"shebang-regex": "^3.0.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=8"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/shebang-regex": {
|
|
||||||
"version": "3.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
|
|
||||||
"integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=8"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/siginfo": {
|
"node_modules/siginfo": {
|
||||||
"version": "2.0.0",
|
"version": "2.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
|
||||||
@@ -4212,18 +4119,6 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
},
|
},
|
||||||
"node_modules/signal-exit": {
|
|
||||||
"version": "4.1.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",
|
|
||||||
"integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==",
|
|
||||||
"license": "ISC",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=14"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/isaacs"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/simple-concat": {
|
"node_modules/simple-concat": {
|
||||||
"version": "1.0.1",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz",
|
||||||
@@ -4899,21 +4794,6 @@
|
|||||||
"node": ">= 16"
|
"node": ">= 16"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/which": {
|
|
||||||
"version": "2.0.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
|
|
||||||
"integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
|
|
||||||
"license": "ISC",
|
|
||||||
"dependencies": {
|
|
||||||
"isexe": "^2.0.0"
|
|
||||||
},
|
|
||||||
"bin": {
|
|
||||||
"node-which": "bin/node-which"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 8"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/why-is-node-running": {
|
"node_modules/why-is-node-running": {
|
||||||
"version": "2.3.0",
|
"version": "2.3.0",
|
||||||
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
|
||||||
@@ -4960,15 +4840,11 @@
|
|||||||
},
|
},
|
||||||
"packages/server": {
|
"packages/server": {
|
||||||
"name": "@johanleroy/git-arboretum",
|
"name": "@johanleroy/git-arboretum",
|
||||||
"version": "1.1.0",
|
"version": "1.4.1",
|
||||||
"bundleDependencies": [
|
|
||||||
"@arboretum/shared"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@arboretum/shared": "0.1.0",
|
|
||||||
"@fastify/cookie": "^11.0.0",
|
"@fastify/cookie": "^11.0.0",
|
||||||
"@fastify/static": "^8.0.0",
|
"@fastify/static": "^9.0.0",
|
||||||
"@fastify/websocket": "^11.0.0",
|
"@fastify/websocket": "^11.0.0",
|
||||||
"@homebridge/node-pty-prebuilt-multiarch": "^0.13.0",
|
"@homebridge/node-pty-prebuilt-multiarch": "^0.13.0",
|
||||||
"@xterm/headless": "^6.0.0",
|
"@xterm/headless": "^6.0.0",
|
||||||
@@ -4979,11 +4855,16 @@
|
|||||||
"arboretum": "dist/index.js"
|
"arboretum": "dist/index.js"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@arboretum/shared": "0.1.0",
|
||||||
"@types/web-push": "^3.6.4",
|
"@types/web-push": "^3.6.4",
|
||||||
"@types/ws": "^8.5.0"
|
"@types/ws": "^8.5.0"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=22.16"
|
"node": ">=22.16"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "buymeacoffee",
|
||||||
|
"url": "https://buymeacoffee.com/johanleroy"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"packages/shared": {
|
"packages/shared": {
|
||||||
@@ -4995,6 +4876,7 @@
|
|||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@arboretum/shared": "*",
|
"@arboretum/shared": "*",
|
||||||
|
"@lucide/vue": "^1.21.0",
|
||||||
"@xterm/addon-fit": "^0.11.0",
|
"@xterm/addon-fit": "^0.11.0",
|
||||||
"@xterm/addon-webgl": "^0.19.0",
|
"@xterm/addon-webgl": "^0.19.0",
|
||||||
"@xterm/xterm": "^6.0.0",
|
"@xterm/xterm": "^6.0.0",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@johanleroy/git-arboretum",
|
"name": "@johanleroy/git-arboretum",
|
||||||
"version": "1.1.0",
|
"version": "1.4.1",
|
||||||
"description": "Self-hosted web dashboard for git worktrees and the Claude Code sessions running on them",
|
"description": "Self-hosted web dashboard for git worktrees and the Claude Code sessions running on them",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
@@ -14,6 +14,10 @@
|
|||||||
"bugs": {
|
"bugs": {
|
||||||
"url": "https://git.lidge.fr/johanleroy/arboretum/issues"
|
"url": "https://git.lidge.fr/johanleroy/arboretum/issues"
|
||||||
},
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "buymeacoffee",
|
||||||
|
"url": "https://buymeacoffee.com/johanleroy"
|
||||||
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"git",
|
"git",
|
||||||
"worktree",
|
"worktree",
|
||||||
@@ -44,16 +48,12 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc -b",
|
"build": "tsc -b",
|
||||||
"dev": "tsc -b --watch & node --watch dist/index.js",
|
"dev": "tsc -b --watch & node --watch dist/index.js",
|
||||||
"prepack": "node scripts/copy-web.mjs && node scripts/vendor-shared.mjs && node scripts/copy-meta.mjs",
|
"prepack": "node scripts/copy-web.mjs && node scripts/inline-shared.mjs && node scripts/copy-meta.mjs",
|
||||||
"test": "vitest run"
|
"test": "vitest run"
|
||||||
},
|
},
|
||||||
"bundleDependencies": [
|
|
||||||
"@arboretum/shared"
|
|
||||||
],
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@arboretum/shared": "0.1.0",
|
|
||||||
"@fastify/cookie": "^11.0.0",
|
"@fastify/cookie": "^11.0.0",
|
||||||
"@fastify/static": "^8.0.0",
|
"@fastify/static": "^9.0.0",
|
||||||
"@fastify/websocket": "^11.0.0",
|
"@fastify/websocket": "^11.0.0",
|
||||||
"@homebridge/node-pty-prebuilt-multiarch": "^0.13.0",
|
"@homebridge/node-pty-prebuilt-multiarch": "^0.13.0",
|
||||||
"@xterm/headless": "^6.0.0",
|
"@xterm/headless": "^6.0.0",
|
||||||
@@ -61,6 +61,7 @@
|
|||||||
"web-push": "^3.6.7"
|
"web-push": "^3.6.7"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@arboretum/shared": "0.1.0",
|
||||||
"@types/web-push": "^3.6.4",
|
"@types/web-push": "^3.6.4",
|
||||||
"@types/ws": "^8.5.0"
|
"@types/ws": "^8.5.0"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ const check = (name, ok, detail = '') => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-'));
|
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-'));
|
||||||
const srv = spawn('node', [join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db')], {
|
const srv = spawn('node', [join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--no-discover'], {
|
||||||
env: { ...process.env, ARBORETUM_LOG: 'warn' },
|
env: { ...process.env, ARBORETUM_LOG: 'warn' },
|
||||||
stdio: ['ignore', 'pipe', 'pipe'],
|
stdio: ['ignore', 'pipe', 'pipe'],
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ writeFileSync(
|
|||||||
|
|
||||||
const srv = spawn(
|
const srv = spawn(
|
||||||
'node',
|
'node',
|
||||||
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', claudeHome],
|
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', claudeHome, '--no-discover'],
|
||||||
{ env: { ...process.env, ARBORETUM_LOG: 'warn', PATH: `${fakeBin}:${process.env.PATH}` }, stdio: ['ignore', 'pipe', 'pipe'] },
|
{ env: { ...process.env, ARBORETUM_LOG: 'warn', PATH: `${fakeBin}:${process.env.PATH}` }, stdio: ['ignore', 'pipe', 'pipe'] },
|
||||||
);
|
);
|
||||||
let srvOut = '';
|
let srvOut = '';
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ git('commit', '-m', 'init');
|
|||||||
|
|
||||||
const srv = spawn(
|
const srv = spawn(
|
||||||
'node',
|
'node',
|
||||||
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', join(tmp, 'claude')],
|
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', join(tmp, 'claude'), '--no-discover'],
|
||||||
{ env: { ...process.env, ARBORETUM_LOG: 'warn' }, stdio: ['ignore', 'pipe', 'pipe'] },
|
{ env: { ...process.env, ARBORETUM_LOG: 'warn' }, stdio: ['ignore', 'pipe', 'pipe'] },
|
||||||
);
|
);
|
||||||
let srvOut = '';
|
let srvOut = '';
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p4-'));
|
|||||||
|
|
||||||
const srv = spawn(
|
const srv = spawn(
|
||||||
'node',
|
'node',
|
||||||
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', join(tmp, 'claude')],
|
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', join(tmp, 'claude'), '--no-discover'],
|
||||||
{ env: { ...process.env, ARBORETUM_LOG: 'warn' }, stdio: ['ignore', 'pipe', 'pipe'] },
|
{ env: { ...process.env, ARBORETUM_LOG: 'warn' }, stdio: ['ignore', 'pipe', 'pipe'] },
|
||||||
);
|
);
|
||||||
let srvOut = '';
|
let srvOut = '';
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ git('commit', '-m', 'init');
|
|||||||
|
|
||||||
const srv = spawn(
|
const srv = spawn(
|
||||||
'node',
|
'node',
|
||||||
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', join(tmp, 'claude')],
|
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', join(tmp, 'claude'), '--no-discover'],
|
||||||
{ env: { ...process.env, ARBORETUM_LOG: 'warn' }, stdio: ['ignore', 'pipe', 'pipe'] },
|
{ env: { ...process.env, ARBORETUM_LOG: 'warn' }, stdio: ['ignore', 'pipe', 'pipe'] },
|
||||||
);
|
);
|
||||||
let srvOut = '';
|
let srvOut = '';
|
||||||
|
|||||||
71
packages/server/scripts/inline-shared.mjs
Normal file
71
packages/server/scripts/inline-shared.mjs
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Inline @arboretum/shared (paquet workspace NON publié) directement dans le dist du serveur,
|
||||||
|
// pour que le tarball npm soit 100 % autonome. Branché sur le hook "prepack".
|
||||||
|
//
|
||||||
|
// Pourquoi PAS bundleDependencies : embarquer une dépendance qui est aussi un *workspace* via
|
||||||
|
// bundleDependencies est instable selon l'environnement npm (mode -w, exécution en root sur un
|
||||||
|
// runner CI, version d'arborist) — npm voit le nœud comme un lien workspace et n'embarque parfois
|
||||||
|
// AUCUN fichier ("bundled files: 0"), produisant un paquet cassé chez le consommateur. On élimine
|
||||||
|
// donc toute magie de bundling : on copie le JS compilé de shared dans dist/_shared et on réécrit
|
||||||
|
// l'import bare '@arboretum/shared' du serveur vers ce chemin relatif. Zéro node_modules embarqué,
|
||||||
|
// zéro symlink, résultat identique partout.
|
||||||
|
import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||||
|
import { join, dirname, relative, sep } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
const serverDist = join(serverDir, 'dist');
|
||||||
|
const sharedDist = join(serverDir, '..', 'shared', 'dist');
|
||||||
|
const inlineDir = join(serverDist, '_shared');
|
||||||
|
|
||||||
|
for (const [label, p] of [['dist serveur', serverDist], ['dist shared', sharedDist]]) {
|
||||||
|
if (!existsSync(p)) {
|
||||||
|
console.error(`inline-shared: ${label} introuvable (${p}) — lance "npm run build" avant le pack.`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1) Copier le JS compilé de shared dans dist/_shared (uniquement *.js : seul le runtime compte ;
|
||||||
|
// les .d.ts/.map ne sont de toute façon pas publiés via le glob `files`). index.js réexporte
|
||||||
|
// ./protocol.js et ./api.js en relatif → la copie complète préserve la résolution interne.
|
||||||
|
rmSync(inlineDir, { recursive: true, force: true });
|
||||||
|
mkdirSync(inlineDir, { recursive: true });
|
||||||
|
let copied = 0;
|
||||||
|
for (const name of readdirSync(sharedDist)) {
|
||||||
|
if (name.endsWith('.js')) {
|
||||||
|
cpSync(join(sharedDist, name), join(inlineDir, name));
|
||||||
|
copied++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (copied === 0) {
|
||||||
|
console.error(`inline-shared: aucun .js dans ${sharedDist} — shared n'est pas compilé.`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2) Réécrire l'import bare '@arboretum/shared' de chaque .js du serveur vers le chemin relatif
|
||||||
|
// (POSIX) pointant sur dist/_shared/index.js, calculé par fichier (profondeur variable).
|
||||||
|
const walk = (dir) =>
|
||||||
|
readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
|
||||||
|
const p = join(dir, e.name);
|
||||||
|
if (e.isDirectory()) return p === inlineDir ? [] : walk(p); // ne pas se réécrire soi-même
|
||||||
|
return e.name.endsWith('.js') ? [p] : [];
|
||||||
|
});
|
||||||
|
|
||||||
|
let rewritten = 0;
|
||||||
|
for (const file of walk(serverDist)) {
|
||||||
|
const src = readFileSync(file, 'utf8');
|
||||||
|
if (!src.includes('@arboretum/shared')) continue;
|
||||||
|
let rel = relative(dirname(file), join(inlineDir, 'index.js')).split(sep).join('/');
|
||||||
|
if (!rel.startsWith('.')) rel = `./${rel}`;
|
||||||
|
const out = src.replaceAll(`'@arboretum/shared'`, `'${rel}'`).replaceAll(`"@arboretum/shared"`, `"${rel}"`);
|
||||||
|
if (out !== src) {
|
||||||
|
writeFileSync(file, out);
|
||||||
|
rewritten++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (rewritten === 0) {
|
||||||
|
console.error(`inline-shared: aucun import '@arboretum/shared' réécrit dans ${serverDist} — build manquant ?`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`inline-shared: ${copied} fichier(s) shared -> dist/_shared, import réécrit dans ${rewritten} fichier(s) serveur`);
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
#!/usr/bin/env node
|
|
||||||
// Embarque @arboretum/shared (dépendance runtime non publiée) DANS le tarball npm.
|
|
||||||
// Branché sur le hook "prepack", aux côtés de bundleDependencies dans package.json.
|
|
||||||
//
|
|
||||||
// Pourquoi un vrai dossier et pas le symlink workspace : sous npm workspaces, shared
|
|
||||||
// est seulement symlinké dans le node_modules racine ; `npm pack` n'embarque une
|
|
||||||
// bundleDependency que si elle existe comme VRAI dossier dans le node_modules du
|
|
||||||
// paquet packé (packages/server/node_modules/@arboretum/shared). On le matérialise ici.
|
|
||||||
import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
||||||
import { join, dirname } from 'node:path';
|
|
||||||
import { fileURLToPath } from 'node:url';
|
|
||||||
|
|
||||||
const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
|
|
||||||
const sharedDir = join(serverDir, '..', 'shared');
|
|
||||||
const sharedDist = join(sharedDir, 'dist');
|
|
||||||
const target = join(serverDir, 'node_modules', '@arboretum', 'shared');
|
|
||||||
|
|
||||||
if (!existsSync(sharedDist)) {
|
|
||||||
console.error(
|
|
||||||
`vendor-shared: ${sharedDist} introuvable — lance "npm run build" (shared doit être compilé) avant le pack.`,
|
|
||||||
);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
// package.json minimal et déterministe : on reprend les champs de résolution réels de
|
|
||||||
// shared (version incluse, pour rester synchro), sans scripts ni files inutiles au runtime.
|
|
||||||
const shared = JSON.parse(readFileSync(join(sharedDir, 'package.json'), 'utf8'));
|
|
||||||
const minimal = {
|
|
||||||
name: shared.name,
|
|
||||||
version: shared.version,
|
|
||||||
type: shared.type,
|
|
||||||
main: shared.main,
|
|
||||||
types: shared.types,
|
|
||||||
exports: shared.exports,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Idempotent : on repart d'un dossier propre à chaque pack.
|
|
||||||
rmSync(target, { recursive: true, force: true });
|
|
||||||
mkdirSync(target, { recursive: true });
|
|
||||||
writeFileSync(join(target, 'package.json'), JSON.stringify(minimal, null, 2) + '\n');
|
|
||||||
cpSync(sharedDist, join(target, 'dist'), { recursive: true });
|
|
||||||
|
|
||||||
console.log(`vendor-shared: embarqué ${shared.name}@${shared.version} -> ${target}`);
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import Fastify, { type FastifyInstance, type FastifyRequest } from 'fastify';
|
import Fastify, { type FastifyError, type FastifyInstance, type FastifyRequest } from 'fastify';
|
||||||
import fastifyCookie from '@fastify/cookie';
|
import fastifyCookie from '@fastify/cookie';
|
||||||
import fastifyWebsocket from '@fastify/websocket';
|
import fastifyWebsocket from '@fastify/websocket';
|
||||||
import fastifyStatic from '@fastify/static';
|
import fastifyStatic from '@fastify/static';
|
||||||
@@ -11,16 +11,49 @@ import { AuthService, LoginRateLimiter, type AuthContext } from './auth/service.
|
|||||||
import { PtyManager } from './core/pty-manager.js';
|
import { PtyManager } from './core/pty-manager.js';
|
||||||
import { DiscoveryService } from './core/discovery-service.js';
|
import { DiscoveryService } from './core/discovery-service.js';
|
||||||
import { WorktreeManager } from './core/worktree-manager.js';
|
import { WorktreeManager } from './core/worktree-manager.js';
|
||||||
|
import { RepoDiscoveryService } from './core/repo-discovery.js';
|
||||||
import { GroupManager } from './core/group-manager.js';
|
import { GroupManager } from './core/group-manager.js';
|
||||||
import { PushService } from './core/push-service.js';
|
import { PushService } from './core/push-service.js';
|
||||||
|
import { loadSecretBox } from './core/secret-box.js';
|
||||||
import { registerAuthRoutes } from './routes/auth.js';
|
import { registerAuthRoutes } from './routes/auth.js';
|
||||||
import { registerSessionRoutes } from './routes/sessions.js';
|
import { registerSessionRoutes } from './routes/sessions.js';
|
||||||
import { registerRepoRoutes } from './routes/repos.js';
|
import { registerRepoRoutes } from './routes/repos.js';
|
||||||
import { registerGroupRoutes } from './routes/groups.js';
|
import { registerGroupRoutes } from './routes/groups.js';
|
||||||
import { registerWorktreeRoutes } from './routes/worktrees.js';
|
import { registerWorktreeRoutes } from './routes/worktrees.js';
|
||||||
import { registerPushRoutes } from './routes/push.js';
|
import { registerPushRoutes } from './routes/push.js';
|
||||||
|
import { registerSettingsRoutes } from './routes/settings.js';
|
||||||
import { registerFsRoutes } from './routes/fs.js';
|
import { registerFsRoutes } from './routes/fs.js';
|
||||||
|
import { registerAuditRoutes } from './routes/audit.js';
|
||||||
|
import { registerDataRoutes } from './routes/data.js';
|
||||||
import { registerWsGateway } from './ws/gateway.js';
|
import { registerWsGateway } from './ws/gateway.js';
|
||||||
|
import { isHttpsRequest } from './routes/auth.js';
|
||||||
|
|
||||||
|
// En-têtes de sécurité posés sur TOUTES les réponses (defense-in-depth + conformité scanners
|
||||||
|
// entreprise). Le terminal web reste du RCE par conception : ces en-têtes durcissent la SPA et
|
||||||
|
// le transport, ils ne remplacent pas le modèle loopback + auth + Origin.
|
||||||
|
const SECURITY_HEADERS: Record<string, string> = {
|
||||||
|
'X-Content-Type-Options': 'nosniff',
|
||||||
|
'X-Frame-Options': 'DENY',
|
||||||
|
'Referrer-Policy': 'no-referrer',
|
||||||
|
'Cross-Origin-Opener-Policy': 'same-origin',
|
||||||
|
'Permissions-Policy': 'geolocation=(), microphone=(), camera=(), payment=()',
|
||||||
|
// CSP calibrée pour la SPA : Tailwind/xterm injectent du style inline ; le WebSocket impose
|
||||||
|
// ws:/wss: en connect-src ; le service worker push impose worker-src 'self'.
|
||||||
|
'Content-Security-Policy': [
|
||||||
|
"default-src 'self'",
|
||||||
|
"script-src 'self'",
|
||||||
|
"style-src 'self' 'unsafe-inline'",
|
||||||
|
"img-src 'self' data:",
|
||||||
|
"font-src 'self' data:",
|
||||||
|
"connect-src 'self' ws: wss:",
|
||||||
|
"worker-src 'self'",
|
||||||
|
"manifest-src 'self'",
|
||||||
|
"frame-ancestors 'none'",
|
||||||
|
"base-uri 'self'",
|
||||||
|
"object-src 'none'",
|
||||||
|
"form-action 'self'",
|
||||||
|
].join('; '),
|
||||||
|
};
|
||||||
|
|
||||||
declare module 'fastify' {
|
declare module 'fastify' {
|
||||||
interface FastifyRequest {
|
interface FastifyRequest {
|
||||||
@@ -36,6 +69,7 @@ export interface AppBundle {
|
|||||||
auth: AuthService;
|
auth: AuthService;
|
||||||
manager: PtyManager;
|
manager: PtyManager;
|
||||||
discovery: DiscoveryService;
|
discovery: DiscoveryService;
|
||||||
|
repoDiscovery: RepoDiscoveryService;
|
||||||
worktrees: WorktreeManager;
|
worktrees: WorktreeManager;
|
||||||
groups: GroupManager;
|
groups: GroupManager;
|
||||||
push: PushService;
|
push: PushService;
|
||||||
@@ -43,9 +77,11 @@ export interface AppBundle {
|
|||||||
|
|
||||||
export function buildApp(config: Config, db: Db, serverVersion: string): AppBundle {
|
export function buildApp(config: Config, db: Db, serverVersion: string): AppBundle {
|
||||||
const app = Fastify({ logger: { level: process.env.ARBORETUM_LOG ?? 'info' } });
|
const app = Fastify({ logger: { level: process.env.ARBORETUM_LOG ?? 'info' } });
|
||||||
const auth = new AuthService(db);
|
// Chiffrement au repos des secrets (server_secret, clé privée VAPID) dans la base.
|
||||||
|
const box = loadSecretBox(config.dataDir);
|
||||||
|
const auth = new AuthService(db, box);
|
||||||
const limiter = new LoginRateLimiter();
|
const limiter = new LoginRateLimiter();
|
||||||
const push = new PushService(db, config.vapidContact);
|
const push = new PushService(db, config.vapidContact, undefined, box);
|
||||||
const manager = new PtyManager(db, config.claudeSessionsDir, push);
|
const manager = new PtyManager(db, config.claudeSessionsDir, push);
|
||||||
const discovery = new DiscoveryService({
|
const discovery = new DiscoveryService({
|
||||||
ptyManager: manager,
|
ptyManager: manager,
|
||||||
@@ -53,8 +89,47 @@ export function buildApp(config: Config, db: Db, serverVersion: string): AppBund
|
|||||||
sessionsDir: config.claudeSessionsDir,
|
sessionsDir: config.claudeSessionsDir,
|
||||||
});
|
});
|
||||||
const worktrees = new WorktreeManager(db, manager, discovery);
|
const worktrees = new WorktreeManager(db, manager, discovery);
|
||||||
|
// Démarré dans runDaemon() (jamais ici) → le scan ne tourne pas pendant les tests qui appellent buildApp.
|
||||||
|
const repoDiscovery = new RepoDiscoveryService(db, worktrees);
|
||||||
const groups = new GroupManager(db);
|
const groups = new GroupManager(db);
|
||||||
|
|
||||||
|
// En-têtes de sécurité sur toute réponse + no-store sur les réponses sensibles (API/WS).
|
||||||
|
// onSend DOIT retourner le payload (sinon Fastify vide la réponse).
|
||||||
|
app.addHook('onSend', async (req, reply, payload) => {
|
||||||
|
reply.removeHeader('Server'); // anti-fingerprinting (no-op si absent)
|
||||||
|
for (const [k, v] of Object.entries(SECURITY_HEADERS)) reply.header(k, v);
|
||||||
|
if (isHttpsRequest(req)) {
|
||||||
|
reply.header('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
|
||||||
|
}
|
||||||
|
if (req.url.startsWith('/api/') || req.url.startsWith('/ws')) {
|
||||||
|
reply.header('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0');
|
||||||
|
}
|
||||||
|
return payload;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Garde CSRF defense-in-depth : une mutation porteuse d'un corps DOIT être en application/json
|
||||||
|
// (bloque les soumissions de formulaire cross-site en text/plain, que Fastify parserait sinon).
|
||||||
|
app.addHook('preHandler', async (req, reply) => {
|
||||||
|
if (!['POST', 'PATCH', 'PUT', 'DELETE'].includes(req.method)) return;
|
||||||
|
const len = req.headers['content-length'];
|
||||||
|
if (!len || len === '0') return; // pas de corps : rien à valider
|
||||||
|
const ct = (req.headers['content-type'] ?? '').toLowerCase();
|
||||||
|
if (!ct.startsWith('application/json')) {
|
||||||
|
return reply.status(415).send({ error: { code: 'UNSUPPORTED_MEDIA_TYPE', message: 'Content-Type must be application/json' } });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Handler d'erreur : ne jamais fuiter de stack/chemin au client ; détail complet côté logs.
|
||||||
|
app.setErrorHandler((err: FastifyError, req, reply) => {
|
||||||
|
const status = err.statusCode && err.statusCode >= 400 && err.statusCode < 600 ? err.statusCode : 500;
|
||||||
|
if (status >= 500) {
|
||||||
|
req.log.error({ err }, 'unhandled error');
|
||||||
|
return reply.status(status).send({ error: { code: 'INTERNAL', message: 'Internal Server Error' } });
|
||||||
|
}
|
||||||
|
// erreurs client (4xx) : code générique, message court non sensible.
|
||||||
|
return reply.status(status).send({ error: { code: err.code ?? 'BAD_REQUEST', message: err.message } });
|
||||||
|
});
|
||||||
|
|
||||||
void app.register(fastifyCookie);
|
void app.register(fastifyCookie);
|
||||||
void app.register(fastifyWebsocket, {
|
void app.register(fastifyWebsocket, {
|
||||||
options: { maxPayload: 1024 * 1024 },
|
options: { maxPayload: 1024 * 1024 },
|
||||||
@@ -92,13 +167,16 @@ export function buildApp(config: Config, db: Db, serverVersion: string): AppBund
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
registerAuthRoutes(app, auth, limiter, serverVersion);
|
registerAuthRoutes(app, auth, limiter, serverVersion, db);
|
||||||
registerSessionRoutes(app, manager, discovery);
|
registerSessionRoutes(app, manager, discovery);
|
||||||
registerRepoRoutes(app, worktrees);
|
registerRepoRoutes(app, worktrees, db);
|
||||||
registerGroupRoutes(app, groups);
|
registerGroupRoutes(app, groups, db);
|
||||||
registerWorktreeRoutes(app, worktrees);
|
registerWorktreeRoutes(app, worktrees);
|
||||||
registerPushRoutes(app, push);
|
registerPushRoutes(app, push, db);
|
||||||
|
registerSettingsRoutes(app, db, config, serverVersion, push);
|
||||||
registerFsRoutes(app);
|
registerFsRoutes(app);
|
||||||
|
registerAuditRoutes(app, db);
|
||||||
|
registerDataRoutes(app, db, auth);
|
||||||
// La route websocket doit être déclarée APRÈS le chargement du plugin (contexte
|
// La route websocket doit être déclarée APRÈS le chargement du plugin (contexte
|
||||||
// encapsulé) — sinon le handler reçoit la signature REST (request, reply).
|
// encapsulé) — sinon le handler reçoit la signature REST (request, reply).
|
||||||
void app.register(async (scoped) => {
|
void app.register(async (scoped) => {
|
||||||
@@ -117,5 +195,5 @@ export function buildApp(config: Config, db: Db, serverVersion: string): AppBund
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return { app, auth, manager, discovery, worktrees, groups, push };
|
return { app, auth, manager, discovery, repoDiscovery, worktrees, groups, push };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
|
import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
|
||||||
import { type Db, getSetting, setSetting } from '../db/index.js';
|
import { type Db, getSetting, setSetting } from '../db/index.js';
|
||||||
|
import type { SecretBox } from '../core/secret-box.js';
|
||||||
|
import { recordAudit } from '../core/audit-log.js';
|
||||||
|
|
||||||
const COOKIE_NAME = 'arb_session';
|
const COOKIE_NAME = 'arb_session';
|
||||||
const COOKIE_TTL_MS = 30 * 24 * 3600 * 1000;
|
const COOKIE_TTL_MS = 30 * 24 * 3600 * 1000;
|
||||||
@@ -12,11 +14,21 @@ export interface AuthContext {
|
|||||||
export class AuthService {
|
export class AuthService {
|
||||||
private readonly secret: Buffer;
|
private readonly secret: Buffer;
|
||||||
|
|
||||||
constructor(private readonly db: Db) {
|
constructor(
|
||||||
let secretHex = getSetting(db, 'server_secret');
|
private readonly db: Db,
|
||||||
if (!secretHex) {
|
box?: SecretBox,
|
||||||
|
) {
|
||||||
|
// server_secret chiffré au repos quand un SecretBox est fourni (prod). Migration douce :
|
||||||
|
// une valeur en clair pré-existante est re-chiffrée à la lecture.
|
||||||
|
const stored = getSetting(db, 'server_secret');
|
||||||
|
let secretHex: string;
|
||||||
|
if (!stored) {
|
||||||
secretHex = randomBytes(32).toString('hex');
|
secretHex = randomBytes(32).toString('hex');
|
||||||
setSetting(db, 'server_secret', secretHex);
|
setSetting(db, 'server_secret', box ? box.encrypt(secretHex) : secretHex);
|
||||||
|
recordAudit(db, { actor: 'system', action: 'secret.generate', resourceId: 'server_secret' });
|
||||||
|
} else {
|
||||||
|
secretHex = box ? box.decrypt(stored) : stored;
|
||||||
|
if (box && !box.isEncrypted(stored)) setSetting(db, 'server_secret', box.encrypt(secretHex));
|
||||||
}
|
}
|
||||||
this.secret = Buffer.from(secretHex, 'hex');
|
this.secret = Buffer.from(secretHex, 'hex');
|
||||||
}
|
}
|
||||||
@@ -35,11 +47,60 @@ export class AuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
createToken(label: string): string {
|
createToken(label: string): string {
|
||||||
|
return this.createTokenRecord(label).token;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Comme createToken mais renvoie aussi l'id (pour l'API de gestion des tokens). */
|
||||||
|
createTokenRecord(label: string): { id: string; token: string } {
|
||||||
|
const id = randomUUID();
|
||||||
const raw = `arb_${randomBytes(24).toString('hex')}`;
|
const raw = `arb_${randomBytes(24).toString('hex')}`;
|
||||||
this.db
|
this.db
|
||||||
.prepare('INSERT INTO auth_tokens (id, label, token_hash, created_at) VALUES (?, ?, ?, ?)')
|
.prepare('INSERT INTO auth_tokens (id, label, token_hash, created_at) VALUES (?, ?, ?, ?)')
|
||||||
.run(randomUUID(), label, sha256(raw), new Date().toISOString());
|
.run(id, label, sha256(raw), new Date().toISOString());
|
||||||
return raw;
|
return { id, token: raw };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Tokens actifs (non révoqués), du plus ancien au plus récent. Ne renvoie JAMAIS le hash. */
|
||||||
|
listTokens(): Array<{ id: string; label: string; createdAt: string; lastUsedAt: string | null }> {
|
||||||
|
return this.db
|
||||||
|
.prepare(
|
||||||
|
'SELECT id, label, created_at AS createdAt, last_used_at AS lastUsedAt FROM auth_tokens WHERE revoked_at IS NULL ORDER BY created_at',
|
||||||
|
)
|
||||||
|
.all() as Array<{ id: string; label: string; createdAt: string; lastUsedAt: string | null }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Nombre de tokens actifs (non révoqués). */
|
||||||
|
countActiveTokens(): number {
|
||||||
|
return (this.db.prepare('SELECT COUNT(*) AS n FROM auth_tokens WHERE revoked_at IS NULL').get() as { n: number }).n;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Révoque un token. Refuse de révoquer le DERNIER token actif (sinon lock-out total) → 'last'.
|
||||||
|
* 'ok' = révoqué ; 'not_found' = id inconnu ou déjà révoqué.
|
||||||
|
*/
|
||||||
|
revokeToken(id: string): 'ok' | 'last' | 'not_found' {
|
||||||
|
// Transaction : le check « dernier token » et l'UPDATE doivent être atomiques (garde
|
||||||
|
// anti lock-out robuste, même si un refactor futur introduisait de la concurrence).
|
||||||
|
this.db.exec('BEGIN IMMEDIATE');
|
||||||
|
try {
|
||||||
|
const row = this.db.prepare('SELECT id FROM auth_tokens WHERE id = ? AND revoked_at IS NULL').get(id) as
|
||||||
|
| { id: string }
|
||||||
|
| undefined;
|
||||||
|
let result: 'ok' | 'last' | 'not_found';
|
||||||
|
if (!row) {
|
||||||
|
result = 'not_found';
|
||||||
|
} else if (this.countActiveTokens() <= 1) {
|
||||||
|
result = 'last';
|
||||||
|
} else {
|
||||||
|
this.db.prepare('UPDATE auth_tokens SET revoked_at = ? WHERE id = ?').run(new Date().toISOString(), id);
|
||||||
|
result = 'ok';
|
||||||
|
}
|
||||||
|
this.db.exec('COMMIT');
|
||||||
|
return result;
|
||||||
|
} catch (err) {
|
||||||
|
this.db.exec('ROLLBACK');
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
verifyRawToken(raw: string): AuthContext | null {
|
verifyRawToken(raw: string): AuthContext | null {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { parseArgs } from 'node:util';
|
import { parseArgs } from 'node:util';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import { homedir } from 'node:os';
|
import { homedir } from 'node:os';
|
||||||
import { mkdirSync } from 'node:fs';
|
import { chmodSync, mkdirSync } from 'node:fs';
|
||||||
|
|
||||||
export interface Config {
|
export interface Config {
|
||||||
port: number;
|
port: number;
|
||||||
@@ -17,6 +17,8 @@ export interface Config {
|
|||||||
claudeSessionsDir: string;
|
claudeSessionsDir: string;
|
||||||
/** sujet VAPID des notifications Web Push (mailto: ou URL). */
|
/** sujet VAPID des notifications Web Push (mailto: ou URL). */
|
||||||
vapidContact: string;
|
vapidContact: string;
|
||||||
|
/** découverte auto des repos au démarrage + périodique (désactivable via --no-discover). */
|
||||||
|
autoDiscover: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function loadConfig(argv = process.argv.slice(2)): Config {
|
export function loadConfig(argv = process.argv.slice(2)): Config {
|
||||||
@@ -33,6 +35,8 @@ export function loadConfig(argv = process.argv.slice(2)): Config {
|
|||||||
'claude-home': { type: 'string' },
|
'claude-home': { type: 'string' },
|
||||||
// sujet VAPID des notifications push (contact requis par la spec Web Push).
|
// sujet VAPID des notifications push (contact requis par la spec Web Push).
|
||||||
'vapid-contact': { type: 'string' },
|
'vapid-contact': { type: 'string' },
|
||||||
|
// désactive la découverte auto des repos (boot + périodique) — utilisé par les tests d'acceptation.
|
||||||
|
'no-discover': { type: 'boolean', default: false },
|
||||||
},
|
},
|
||||||
strict: true,
|
strict: true,
|
||||||
});
|
});
|
||||||
@@ -49,6 +53,14 @@ export function loadConfig(argv = process.argv.slice(2)): Config {
|
|||||||
|
|
||||||
const dataDir = join(process.env.XDG_DATA_HOME ?? join(homedir(), '.local', 'share'), 'arboretum');
|
const dataDir = join(process.env.XDG_DATA_HOME ?? join(homedir(), '.local', 'share'), 'arboretum');
|
||||||
mkdirSync(dataDir, { recursive: true });
|
mkdirSync(dataDir, { recursive: true });
|
||||||
|
// La DB contient des secrets (server_secret, clé privée VAPID, hashs de tokens) : le dossier de
|
||||||
|
// données ne doit jamais être lisible par d'autres utilisateurs du système. chmod best-effort
|
||||||
|
// (peut échouer sur certains FS Windows/montés ; le démarrage avertit alors sans bloquer).
|
||||||
|
try {
|
||||||
|
chmodSync(dataDir, 0o700);
|
||||||
|
} catch {
|
||||||
|
/* FS sans permissions POSIX : ignoré, cf. avertissement dans db.openDb */
|
||||||
|
}
|
||||||
const claudeHome = values['claude-home'] ?? join(homedir(), '.claude');
|
const claudeHome = values['claude-home'] ?? join(homedir(), '.claude');
|
||||||
return {
|
return {
|
||||||
port: Number(values.port),
|
port: Number(values.port),
|
||||||
@@ -60,5 +72,6 @@ export function loadConfig(argv = process.argv.slice(2)): Config {
|
|||||||
claudeProjectsDir: join(claudeHome, 'projects'),
|
claudeProjectsDir: join(claudeHome, 'projects'),
|
||||||
claudeSessionsDir: join(claudeHome, 'sessions'),
|
claudeSessionsDir: join(claudeHome, 'sessions'),
|
||||||
vapidContact: values['vapid-contact'] ?? 'mailto:arboretum@localhost',
|
vapidContact: values['vapid-contact'] ?? 'mailto:arboretum@localhost',
|
||||||
|
autoDiscover: !(values['no-discover'] ?? false),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
65
packages/server/src/core/audit-log.ts
Normal file
65
packages/server/src/core/audit-log.ts
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
// Journal d'audit : trace persistante des opérations sensibles (création/révocation de tokens,
|
||||||
|
// changements de réglages, génération de secrets, abonnements push, CRUD groupes). Exigence de
|
||||||
|
// conformité entreprise (GDPR/SOX/ISO 27001). Règle ABSOLUE : ne JAMAIS journaliser un secret en
|
||||||
|
// clair — `details` ne contient que des métadonnées non sensibles (ids, labels, compteurs).
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import type { AuditLogEntry } from '@arboretum/shared';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
|
||||||
|
export type AuditResult = 'ok' | 'denied' | 'error';
|
||||||
|
|
||||||
|
export interface AuditEntry {
|
||||||
|
/** tokenId de l'acteur, ou 'system' (opérations automatiques), ou 'anonymous' (avant auth). */
|
||||||
|
actor: string;
|
||||||
|
/** verbe.objet, ex. 'token.create', 'settings.update', 'login.failure'. */
|
||||||
|
action: string;
|
||||||
|
resourceId?: string | null;
|
||||||
|
details?: Record<string, unknown> | null;
|
||||||
|
result?: AuditResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Enregistre une entrée d'audit. Best-effort : une erreur d'écriture ne casse jamais l'opération métier. */
|
||||||
|
export function recordAudit(db: Db, e: AuditEntry): void {
|
||||||
|
try {
|
||||||
|
db.prepare(
|
||||||
|
'INSERT INTO audit_logs (id, ts, actor, action, resource_id, details, result) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||||
|
).run(
|
||||||
|
randomUUID(),
|
||||||
|
new Date().toISOString(),
|
||||||
|
e.actor,
|
||||||
|
e.action,
|
||||||
|
e.resourceId ?? null,
|
||||||
|
e.details ? JSON.stringify(e.details) : null,
|
||||||
|
e.result ?? 'ok',
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
/* l'audit ne doit jamais faire échouer l'action auditée */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Liste paginée par date décroissante (curseur `before` = ts strictement inférieur). */
|
||||||
|
export function listAudit(db: Db, opts: { limit: number; before?: string | null }): AuditLogEntry[] {
|
||||||
|
const limit = Math.min(Math.max(Math.trunc(opts.limit) || 50, 1), 200);
|
||||||
|
const rows = (
|
||||||
|
opts.before
|
||||||
|
? db
|
||||||
|
.prepare(
|
||||||
|
'SELECT id, ts, actor, action, resource_id AS resourceId, details, result FROM audit_logs WHERE ts < ? ORDER BY ts DESC LIMIT ?',
|
||||||
|
)
|
||||||
|
.all(opts.before, limit)
|
||||||
|
: db
|
||||||
|
.prepare(
|
||||||
|
'SELECT id, ts, actor, action, resource_id AS resourceId, details, result FROM audit_logs ORDER BY ts DESC LIMIT ?',
|
||||||
|
)
|
||||||
|
.all(limit)
|
||||||
|
) as Array<{ id: string; ts: string; actor: string; action: string; resourceId: string | null; details: string | null; result: string }>;
|
||||||
|
return rows.map((r) => ({ ...r, details: r.details ? safeParse(r.details) : null }));
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeParse(s: string): unknown {
|
||||||
|
try {
|
||||||
|
return JSON.parse(s);
|
||||||
|
} catch {
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,8 @@
|
|||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
import { createRequire } from 'node:module';
|
import { createRequire } from 'node:module';
|
||||||
import { type Db, getSetting, setSetting } from '../db/index.js';
|
import { type Db, getSetting, setSetting } from '../db/index.js';
|
||||||
|
import type { SecretBox } from './secret-box.js';
|
||||||
|
import { recordAudit } from './audit-log.js';
|
||||||
|
|
||||||
// web-push est publié en CommonJS : on le charge via require (verbatimModuleSyntax + NodeNext),
|
// web-push est publié en CommonJS : on le charge via require (verbatimModuleSyntax + NodeNext),
|
||||||
// typé par l'import type — même pattern que @xterm/headless dans screen-reader.ts.
|
// typé par l'import type — même pattern que @xterm/headless dans screen-reader.ts.
|
||||||
@@ -47,16 +49,22 @@ export class PushService {
|
|||||||
private readonly db: Db,
|
private readonly db: Db,
|
||||||
private readonly contact: string = 'mailto:arboretum@localhost',
|
private readonly contact: string = 'mailto:arboretum@localhost',
|
||||||
sender?: PushSender,
|
sender?: PushSender,
|
||||||
|
box?: SecretBox,
|
||||||
) {
|
) {
|
||||||
this.send = sender ?? ((sub, payload, options) => webpush.sendNotification(sub, payload, options as Parameters<typeof webpush.sendNotification>[2]));
|
this.send = sender ?? ((sub, payload, options) => webpush.sendNotification(sub, payload, options as Parameters<typeof webpush.sendNotification>[2]));
|
||||||
let pub = getSetting(db, 'vapid_public');
|
let pub = getSetting(db, 'vapid_public'); // clé publique : jamais chiffrée (sûre à exposer)
|
||||||
let priv = getSetting(db, 'vapid_private');
|
const storedPriv = getSetting(db, 'vapid_private');
|
||||||
|
let priv = storedPriv ? (box ? box.decrypt(storedPriv) : storedPriv) : null;
|
||||||
if (!pub || !priv) {
|
if (!pub || !priv) {
|
||||||
const keys = webpush.generateVAPIDKeys();
|
const keys = webpush.generateVAPIDKeys();
|
||||||
pub = keys.publicKey;
|
pub = keys.publicKey;
|
||||||
priv = keys.privateKey;
|
priv = keys.privateKey;
|
||||||
setSetting(db, 'vapid_public', pub);
|
setSetting(db, 'vapid_public', pub);
|
||||||
setSetting(db, 'vapid_private', priv);
|
setSetting(db, 'vapid_private', box ? box.encrypt(priv) : priv);
|
||||||
|
recordAudit(db, { actor: 'system', action: 'secret.generate', resourceId: 'vapid' });
|
||||||
|
} else if (box && storedPriv && !box.isEncrypted(storedPriv)) {
|
||||||
|
// migration douce : clé privée pré-existante en clair → re-chiffrée.
|
||||||
|
setSetting(db, 'vapid_private', box.encrypt(priv));
|
||||||
}
|
}
|
||||||
this.vapidPublic = pub;
|
this.vapidPublic = pub;
|
||||||
this.vapidPrivate = priv;
|
this.vapidPrivate = priv;
|
||||||
|
|||||||
42
packages/server/src/core/repo-discovery.ts
Normal file
42
packages/server/src/core/repo-discovery.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
// Planificateur de la découverte auto des repos : scan au démarrage + re-scan périodique.
|
||||||
|
// Calqué sur DiscoveryService (sessions) — start()/stop() avec timer .unref(). Démarré depuis
|
||||||
|
// runDaemon() UNIQUEMENT (jamais buildApp), ce qui isole naturellement les tests vitest du scan.
|
||||||
|
// Lui-même sans état : il lit les racines/l'intervalle dans `settings` et délègue à WorktreeManager.
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
import type { WorktreeManager } from './worktree-manager.js';
|
||||||
|
import { readScanIntervalMin, readScanRoots } from './scan-settings.js';
|
||||||
|
|
||||||
|
export class RepoDiscoveryService {
|
||||||
|
private timer: NodeJS.Timeout | null = null;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly db: Db,
|
||||||
|
private readonly worktrees: WorktreeManager,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
start(): void {
|
||||||
|
if (this.timer) return;
|
||||||
|
void this.refresh(); // scan initial asynchrone : ne bloque pas le boot
|
||||||
|
const intervalMin = readScanIntervalMin(this.db);
|
||||||
|
if (intervalMin > 0) {
|
||||||
|
this.timer = setInterval(() => void this.refresh(), intervalMin * 60_000);
|
||||||
|
this.timer.unref(); // ne maintient pas le process en vie
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stop(): void {
|
||||||
|
if (this.timer) {
|
||||||
|
clearInterval(this.timer);
|
||||||
|
this.timer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Relit les racines (changement effectif sans redémarrage) et lance un scan. Ne lève jamais. */
|
||||||
|
private async refresh(): Promise<void> {
|
||||||
|
try {
|
||||||
|
await this.worktrees.discoverRepos({ roots: readScanRoots(this.db) });
|
||||||
|
} catch {
|
||||||
|
/* scan tolérant : une erreur ne doit pas tuer le timer */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
97
packages/server/src/core/repo-scanner.ts
Normal file
97
packages/server/src/core/repo-scanner.ts
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
// Découverte auto des dépôts git : marche bornée du système de fichiers à la recherche de `.git`.
|
||||||
|
// Fonction PURE et tolérante (ne lève jamais) — testable isolément comme parseWorktreePorcelain.
|
||||||
|
// N'appelle JAMAIS git (détection par présence de `.git`) : la validation réelle (isRepo) et la
|
||||||
|
// résolution de default_branch se font paresseusement à l'enregistrement, pas par dépôt scanné.
|
||||||
|
import { readdir } from 'node:fs/promises';
|
||||||
|
import { existsSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
|
||||||
|
export interface ScanLimits {
|
||||||
|
/** profondeur maximale de descente sous chaque racine (la racine = 0). */
|
||||||
|
maxDepth: number;
|
||||||
|
/** nombre maximal de repos retournés (garde-fou anti-explosion d'un FS pathologique). */
|
||||||
|
maxRepos: number;
|
||||||
|
/** noms de dossiers à ne jamais ouvrir (en plus des dotdirs, toujours exclus). */
|
||||||
|
excludeDirs?: Set<string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Dossiers jamais explorés : grosses arborescences sans repos racine, ou bruit de build. */
|
||||||
|
export const DEFAULT_EXCLUDE_DIRS = new Set<string>([
|
||||||
|
'node_modules',
|
||||||
|
'vendor',
|
||||||
|
'target',
|
||||||
|
'dist',
|
||||||
|
'build',
|
||||||
|
'.cache',
|
||||||
|
'venv',
|
||||||
|
'.venv',
|
||||||
|
'__pycache__',
|
||||||
|
]);
|
||||||
|
|
||||||
|
interface Frame {
|
||||||
|
dir: string;
|
||||||
|
depth: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parcours itératif (pile explicite, jamais de récursion non bornée) des `roots`.
|
||||||
|
* Règles :
|
||||||
|
* - un dossier contenant `.git` (fichier OU dossier → couvre les worktrees liés) est un repo :
|
||||||
|
* on l'enregistre ; en profondeur on NE descend PAS dedans (sous-modules/worktrees imbriqués
|
||||||
|
* ignorés). EXCEPTION : une racine fournie (depth 0) qui est elle-même un repo est aussi un
|
||||||
|
* conteneur — on l'enregistre ET on continue de descendre pour trouver les repos internes ;
|
||||||
|
* - on n'empile que les vrais sous-dossiers (`d.isDirectory()`), donc les symlinks ne sont PAS
|
||||||
|
* suivis (anti-cycle + anti-sortie de racine), et on saute dotdirs + excludeDirs ;
|
||||||
|
* - bornes : `maxDepth`, `maxRepos`, et un éventuel `signal` (timeout global) ;
|
||||||
|
* - tolérance : un `readdir` qui échoue (EACCES/ENOENT) est ignoré, le scan continue ;
|
||||||
|
* - racine inexistante/illisible : ignorée silencieusement.
|
||||||
|
* Retourne les chemins absolus dédupliqués des racines de repos, et `truncated` si une borne a coupé.
|
||||||
|
*/
|
||||||
|
export async function scanForRepos(
|
||||||
|
roots: string[],
|
||||||
|
limits: ScanLimits,
|
||||||
|
signal?: AbortSignal,
|
||||||
|
): Promise<{ paths: string[]; truncated: boolean }> {
|
||||||
|
const excludes = limits.excludeDirs ?? DEFAULT_EXCLUDE_DIRS;
|
||||||
|
const found = new Set<string>();
|
||||||
|
const seen = new Set<string>(); // ceinture-bretelles anti-cycle (chemins déjà visités)
|
||||||
|
let truncated = false;
|
||||||
|
|
||||||
|
// pile partagée entre toutes les racines : un seul plafond global maxRepos.
|
||||||
|
const stack: Frame[] = [];
|
||||||
|
for (const root of roots) stack.push({ dir: root, depth: 0 });
|
||||||
|
|
||||||
|
while (stack.length > 0) {
|
||||||
|
if (signal?.aborted || found.size >= limits.maxRepos) {
|
||||||
|
truncated = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const { dir, depth } = stack.pop() as Frame;
|
||||||
|
if (seen.has(dir)) continue;
|
||||||
|
seen.add(dir);
|
||||||
|
|
||||||
|
// Un dossier avec `.git` est un repo. En PROFONDEUR (depth > 0) c'est une feuille : on
|
||||||
|
// l'enregistre sans descendre (on n'ouvre pas les sous-modules/worktrees imbriqués). Mais une
|
||||||
|
// RACINE fournie explicitement (depth 0) est un CONTENEUR de scan : si elle est elle-même un
|
||||||
|
// repo on l'enregistre, puis on CONTINUE de descendre pour découvrir les dépôts qu'elle contient.
|
||||||
|
if (existsSync(join(dir, '.git'))) {
|
||||||
|
found.add(dir);
|
||||||
|
if (depth > 0) continue;
|
||||||
|
}
|
||||||
|
if (depth >= limits.maxDepth) continue;
|
||||||
|
|
||||||
|
let entries;
|
||||||
|
try {
|
||||||
|
entries = await readdir(dir, { withFileTypes: true });
|
||||||
|
} catch {
|
||||||
|
continue; // EACCES/ENOENT/… : dossier ignoré, on poursuit
|
||||||
|
}
|
||||||
|
for (const e of entries) {
|
||||||
|
if (!e.isDirectory()) continue; // symlinks non suivis (isDirectory() est false pour un lien)
|
||||||
|
if (e.name.startsWith('.') || excludes.has(e.name)) continue;
|
||||||
|
stack.push({ dir: join(dir, e.name), depth: depth + 1 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { paths: [...found], truncated };
|
||||||
|
}
|
||||||
66
packages/server/src/core/scan-settings.ts
Normal file
66
packages/server/src/core/scan-settings.ts
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
// Réglages de la découverte auto des repos, persistés dans la table `settings` (clé/valeur).
|
||||||
|
// Frontière de sécurité : ces clés sont NON sensibles et n'entrent dans l'allow-list du PATCH
|
||||||
|
// /api/v1/settings que via les validateurs ci-dessous. Aucun secret ne transite par ici.
|
||||||
|
import { getSetting } from '../db/index.js';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
import { isSafeAbsolutePath } from './git.js';
|
||||||
|
|
||||||
|
export const SCAN_ROOTS_KEY = 'scan_roots';
|
||||||
|
export const SCAN_INTERVAL_KEY = 'scan_interval_min';
|
||||||
|
|
||||||
|
/** Intervalle par défaut du re-scan périodique (minutes). 0 = désactivé. */
|
||||||
|
export const DEFAULT_SCAN_INTERVAL_MIN = 5;
|
||||||
|
/** Borne haute de l'intervalle (24 h) et nombre maximal de racines. */
|
||||||
|
export const MAX_SCAN_INTERVAL_MIN = 1440;
|
||||||
|
export const MAX_SCAN_ROOTS = 16;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Racines à scanner. Défaut : AUCUNE racine → aucun scan (clean install).
|
||||||
|
* L'utilisateur ajoute ses racines via Réglages → Découverte. Lecture tolérante (JSON malformé → []).
|
||||||
|
*/
|
||||||
|
export function readScanRoots(db: Db): string[] {
|
||||||
|
const raw = getSetting(db, SCAN_ROOTS_KEY);
|
||||||
|
if (!raw) return [];
|
||||||
|
return normalizeScanRoots(safeParse(raw)) ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Intervalle périodique en minutes (0 = désactivé). Défaut DEFAULT_SCAN_INTERVAL_MIN. */
|
||||||
|
export function readScanIntervalMin(db: Db): number {
|
||||||
|
const raw = getSetting(db, SCAN_INTERVAL_KEY);
|
||||||
|
if (raw === null) return DEFAULT_SCAN_INTERVAL_MIN;
|
||||||
|
const n = Number(raw);
|
||||||
|
return Number.isInteger(n) && n >= 0 && n <= MAX_SCAN_INTERVAL_MIN ? n : DEFAULT_SCAN_INTERVAL_MIN;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valide/normalise une liste de racines : tableau de chemins absolus normalisés (isSafeAbsolutePath),
|
||||||
|
* jamais `/` (scan catastrophique), dédupliqués, ≤ MAX_SCAN_ROOTS. Retourne null si invalide (⇒ 400).
|
||||||
|
* Une liste vide est valide (revient au défaut côté lecture).
|
||||||
|
*/
|
||||||
|
export function normalizeScanRoots(raw: unknown): string[] | null {
|
||||||
|
if (!Array.isArray(raw)) return null;
|
||||||
|
if (raw.length > MAX_SCAN_ROOTS) return null;
|
||||||
|
const out: string[] = [];
|
||||||
|
for (const item of raw) {
|
||||||
|
if (typeof item !== 'string') return null;
|
||||||
|
const p = item.trim();
|
||||||
|
if (!isSafeAbsolutePath(p) || p === '/') return null;
|
||||||
|
if (!out.includes(p)) out.push(p);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Valide un intervalle (entier 0–MAX_SCAN_INTERVAL_MIN). Retourne null si invalide. */
|
||||||
|
export function normalizeScanIntervalMin(raw: unknown): number | null {
|
||||||
|
if (typeof raw !== 'number' || !Number.isInteger(raw)) return null;
|
||||||
|
if (raw < 0 || raw > MAX_SCAN_INTERVAL_MIN) return null;
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeParse(raw: string): unknown {
|
||||||
|
try {
|
||||||
|
return JSON.parse(raw);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
69
packages/server/src/core/secret-box.ts
Normal file
69
packages/server/src/core/secret-box.ts
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
// Chiffrement au repos des secrets applicatifs (server_secret HMAC, clé privée VAPID) stockés dans
|
||||||
|
// la table `settings`. node:sqlite (DatabaseSync) ne supporte pas sqlcipher → on chiffre au niveau
|
||||||
|
// applicatif les VALEURS sensibles, en AES-256-GCM (authentifié), avant insertion.
|
||||||
|
//
|
||||||
|
// Gestion de clé (par ordre de priorité) :
|
||||||
|
// 1. ARBORETUM_SECRET_KEY (variable d'env) → vraie protection : la clé ne vit pas sur le disque,
|
||||||
|
// donc une fuite de la base seule (backup, WAL) ne révèle pas les secrets ;
|
||||||
|
// 2. sinon, fichier clé `dataDir/secret.key` (0o600), généré au 1er démarrage. Protection partielle :
|
||||||
|
// couvre la fuite de la base seule, PAS celle du dossier de données complet (clé + base ensemble).
|
||||||
|
// Compromis assumé et documenté (docs/ENTERPRISE_DEPLOYMENT.md) : pour une protection forte, fournir
|
||||||
|
// ARBORETUM_SECRET_KEY et sauvegarder cette clé séparément des backups de la base.
|
||||||
|
import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from 'node:crypto';
|
||||||
|
import { chmodSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
|
||||||
|
const PREFIX = 'v1:'; // versionne le format ; absence de préfixe = valeur en clair (legacy → migration douce)
|
||||||
|
const SCRYPT_SALT = 'arboretum-secret-box-v1'; // sel fixe : l'entropie vient de la passphrase fournie
|
||||||
|
|
||||||
|
export class SecretBox {
|
||||||
|
constructor(private readonly key: Buffer) {}
|
||||||
|
|
||||||
|
/** Chiffre en `v1:<iv>:<tag>:<ciphertext>` (hex). */
|
||||||
|
encrypt(plaintext: string): string {
|
||||||
|
const iv = randomBytes(12);
|
||||||
|
const cipher = createCipheriv('aes-256-gcm', this.key, iv);
|
||||||
|
const ct = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
|
||||||
|
const tag = cipher.getAuthTag();
|
||||||
|
return `${PREFIX}${iv.toString('hex')}:${tag.toString('hex')}:${ct.toString('hex')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Déchiffre une valeur `v1:` ; une valeur sans préfixe est retournée telle quelle (clair legacy). */
|
||||||
|
decrypt(stored: string): string {
|
||||||
|
if (!this.isEncrypted(stored)) return stored;
|
||||||
|
const [, ivHex, tagHex, ctHex] = stored.split(':');
|
||||||
|
if (!ivHex || !tagHex || !ctHex) throw new Error('secret-box: format chiffré invalide');
|
||||||
|
const decipher = createDecipheriv('aes-256-gcm', this.key, Buffer.from(ivHex, 'hex'));
|
||||||
|
decipher.setAuthTag(Buffer.from(tagHex, 'hex'));
|
||||||
|
return Buffer.concat([decipher.update(Buffer.from(ctHex, 'hex')), decipher.final()]).toString('utf8');
|
||||||
|
}
|
||||||
|
|
||||||
|
isEncrypted(stored: string): boolean {
|
||||||
|
return stored.startsWith(PREFIX);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Construit le SecretBox de production : clé dérivée d'ARBORETUM_SECRET_KEY si fournie, sinon
|
||||||
|
* d'un fichier clé `dataDir/secret.key` (0o600) généré au besoin.
|
||||||
|
*/
|
||||||
|
export function loadSecretBox(dataDir: string): SecretBox {
|
||||||
|
const passphrase = process.env.ARBORETUM_SECRET_KEY;
|
||||||
|
if (passphrase && passphrase.length > 0) {
|
||||||
|
return new SecretBox(scryptSync(passphrase, SCRYPT_SALT, 32));
|
||||||
|
}
|
||||||
|
const keyPath = join(dataDir, 'secret.key');
|
||||||
|
let keyHex: string;
|
||||||
|
if (existsSync(keyPath)) {
|
||||||
|
keyHex = readFileSync(keyPath, 'utf8').trim();
|
||||||
|
} else {
|
||||||
|
keyHex = randomBytes(32).toString('hex');
|
||||||
|
writeFileSync(keyPath, keyHex + '\n', { mode: 0o600 });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
chmodSync(keyPath, 0o600);
|
||||||
|
} catch {
|
||||||
|
/* FS sans permissions POSIX : ignoré */
|
||||||
|
}
|
||||||
|
return new SecretBox(Buffer.from(keyHex, 'hex'));
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ import { randomUUID } from 'node:crypto';
|
|||||||
import { basename, dirname, join, resolve } from 'node:path';
|
import { basename, dirname, join, resolve } from 'node:path';
|
||||||
import { existsSync } from 'node:fs';
|
import { existsSync } from 'node:fs';
|
||||||
import type {
|
import type {
|
||||||
|
DiscoverReposResponse,
|
||||||
HookRunResult,
|
HookRunResult,
|
||||||
PostCreateHook,
|
PostCreateHook,
|
||||||
RepoSummary,
|
RepoSummary,
|
||||||
@@ -17,6 +18,7 @@ import type {
|
|||||||
import type { Db } from '../db/index.js';
|
import type { Db } from '../db/index.js';
|
||||||
import type { PtyManager } from './pty-manager.js';
|
import type { PtyManager } from './pty-manager.js';
|
||||||
import { DiscoveryService, mergeSessions } from './discovery-service.js';
|
import { DiscoveryService, mergeSessions } from './discovery-service.js';
|
||||||
|
import { scanForRepos } from './repo-scanner.js';
|
||||||
import { preTrustProject } from './claude-trust.js';
|
import { preTrustProject } from './claude-trust.js';
|
||||||
import {
|
import {
|
||||||
addWorktree,
|
addWorktree,
|
||||||
@@ -35,6 +37,10 @@ import {
|
|||||||
const FACTS_TTL_MS = 2500;
|
const FACTS_TTL_MS = 2500;
|
||||||
const HOOK_TIMEOUT_MS = 5 * 60_000;
|
const HOOK_TIMEOUT_MS = 5 * 60_000;
|
||||||
const HOOK_OUTPUT_MAX = 64 * 1024;
|
const HOOK_OUTPUT_MAX = 64 * 1024;
|
||||||
|
// Bornes du scan de découverte (anti-explosion sur un home volumineux).
|
||||||
|
const SCAN_MAX_DEPTH = 6;
|
||||||
|
const SCAN_MAX_REPOS = 2000;
|
||||||
|
const SCAN_TIMEOUT_MS = 30_000;
|
||||||
|
|
||||||
interface RepoRow {
|
interface RepoRow {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -44,6 +50,7 @@ interface RepoRow {
|
|||||||
post_create_hooks: string;
|
post_create_hooks: string;
|
||||||
pre_trust: number;
|
pre_trust: number;
|
||||||
created_at: string;
|
created_at: string;
|
||||||
|
hidden: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface WorktreeManagerEvents {
|
export interface WorktreeManagerEvents {
|
||||||
@@ -96,6 +103,8 @@ function runHook(cwd: string, hook: PostCreateHook): Promise<HookRunResult> {
|
|||||||
export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||||
private readonly factsCache = new Map<string, { facts: Array<{ w: ParsedWorktree; status: WorktreeGitStatus }>; at: number }>();
|
private readonly factsCache = new Map<string, { facts: Array<{ w: ParsedWorktree; status: WorktreeGitStatus }>; at: number }>();
|
||||||
private readonly locks = new Map<string, Promise<unknown>>();
|
private readonly locks = new Map<string, Promise<unknown>>();
|
||||||
|
/** Scan de découverte en cours : coalesce boot + bouton + périodique sur un seul scan. */
|
||||||
|
private scanInFlight: Promise<DiscoverReposResponse> | null = null;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly db: Db,
|
private readonly db: Db,
|
||||||
@@ -121,6 +130,7 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
|||||||
preTrust: row.pre_trust === 1,
|
preTrust: row.pre_trust === 1,
|
||||||
createdAt: row.created_at,
|
createdAt: row.created_at,
|
||||||
valid: await isRepo(row.path),
|
valid: await isRepo(row.path),
|
||||||
|
hidden: row.hidden === 1,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,24 +153,35 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
|||||||
post_create_hooks: JSON.stringify(opts.postCreateHooks ?? []),
|
post_create_hooks: JSON.stringify(opts.postCreateHooks ?? []),
|
||||||
pre_trust: opts.preTrust ? 1 : 0,
|
pre_trust: opts.preTrust ? 1 : 0,
|
||||||
created_at: new Date().toISOString(),
|
created_at: new Date().toISOString(),
|
||||||
|
hidden: 0,
|
||||||
};
|
};
|
||||||
|
try {
|
||||||
this.db
|
this.db
|
||||||
.prepare('INSERT INTO repos (id, path, label, default_branch, post_create_hooks, pre_trust, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)')
|
.prepare('INSERT INTO repos (id, path, label, default_branch, post_create_hooks, pre_trust, created_at, hidden) VALUES (?, ?, ?, ?, ?, ?, ?, ?)')
|
||||||
.run(row.id, row.path, row.label, row.default_branch, row.post_create_hooks, row.pre_trust, row.created_at);
|
.run(row.id, row.path, row.label, row.default_branch, row.post_create_hooks, row.pre_trust, row.created_at, row.hidden);
|
||||||
|
} catch (err) {
|
||||||
|
// Course possible avec un scan concurrent qui aurait inséré le même path entre le SELECT
|
||||||
|
// d'unicité et cet INSERT (contrainte UNIQUE sur path) → on rend le même 409 explicite.
|
||||||
|
if (String((err as { code?: string }).code).includes('CONSTRAINT')) {
|
||||||
|
throw httpError(409, 'ALREADY_REGISTERED', 'This repository is already registered');
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
const summary = await this.rowToSummary(row);
|
const summary = await this.rowToSummary(row);
|
||||||
this.emit('repo_update', summary);
|
this.emit('repo_update', summary);
|
||||||
return summary;
|
return summary;
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateRepo(id: string, patch: { label?: string; postCreateHooks?: PostCreateHook[]; preTrust?: boolean }): Promise<RepoSummary> {
|
async updateRepo(id: string, patch: { label?: string; postCreateHooks?: PostCreateHook[]; preTrust?: boolean; hidden?: boolean }): Promise<RepoSummary> {
|
||||||
const row = this.getRepoRow(id);
|
const row = this.getRepoRow(id);
|
||||||
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
|
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
|
||||||
if (patch.label !== undefined) row.label = patch.label.trim() || row.label;
|
if (patch.label !== undefined) row.label = patch.label.trim() || row.label;
|
||||||
if (patch.postCreateHooks !== undefined) row.post_create_hooks = JSON.stringify(patch.postCreateHooks);
|
if (patch.postCreateHooks !== undefined) row.post_create_hooks = JSON.stringify(patch.postCreateHooks);
|
||||||
if (patch.preTrust !== undefined) row.pre_trust = patch.preTrust ? 1 : 0;
|
if (patch.preTrust !== undefined) row.pre_trust = patch.preTrust ? 1 : 0;
|
||||||
|
if (patch.hidden !== undefined) row.hidden = patch.hidden ? 1 : 0;
|
||||||
this.db
|
this.db
|
||||||
.prepare('UPDATE repos SET label = ?, post_create_hooks = ?, pre_trust = ? WHERE id = ?')
|
.prepare('UPDATE repos SET label = ?, post_create_hooks = ?, pre_trust = ?, hidden = ? WHERE id = ?')
|
||||||
.run(row.label, row.post_create_hooks, row.pre_trust, id);
|
.run(row.label, row.post_create_hooks, row.pre_trust, row.hidden, id);
|
||||||
const summary = await this.rowToSummary(row);
|
const summary = await this.rowToSummary(row);
|
||||||
this.emit('repo_update', summary);
|
this.emit('repo_update', summary);
|
||||||
return summary;
|
return summary;
|
||||||
@@ -174,6 +195,53 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Découvre les repos git sous `roots` et auto-enregistre les NOUVEAUX (path absent de la DB).
|
||||||
|
* Idempotent et anti-résurrection : un path déjà présent — visible OU masqué — n'est jamais
|
||||||
|
* réécrit (INSERT ... ON CONFLICT DO NOTHING). Les scans concurrents sont coalescés. Tolérant :
|
||||||
|
* ne lève pas (le scanner avale les erreurs FS). N'appelle aucun git pendant le scan
|
||||||
|
* (default_branch=NULL, résolu paresseusement par rowToSummary à l'affichage).
|
||||||
|
*/
|
||||||
|
discoverRepos(opts: { roots: string[]; maxDepth?: number; maxRepos?: number }): Promise<DiscoverReposResponse> {
|
||||||
|
if (this.scanInFlight) return this.scanInFlight;
|
||||||
|
this.scanInFlight = this.runDiscovery(opts).finally(() => {
|
||||||
|
this.scanInFlight = null;
|
||||||
|
});
|
||||||
|
return this.scanInFlight;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async runDiscovery(opts: { roots: string[]; maxDepth?: number; maxRepos?: number }): Promise<DiscoverReposResponse> {
|
||||||
|
const t0 = Date.now();
|
||||||
|
const { paths, truncated } = await scanForRepos(
|
||||||
|
opts.roots,
|
||||||
|
{ maxDepth: opts.maxDepth ?? SCAN_MAX_DEPTH, maxRepos: opts.maxRepos ?? SCAN_MAX_REPOS },
|
||||||
|
AbortSignal.timeout(SCAN_TIMEOUT_MS),
|
||||||
|
);
|
||||||
|
const insert = this.db.prepare(
|
||||||
|
`INSERT INTO repos (id, path, label, default_branch, post_create_hooks, pre_trust, created_at, hidden)
|
||||||
|
VALUES (?, ?, ?, NULL, '[]', 0, ?, 0) ON CONFLICT(path) DO NOTHING`,
|
||||||
|
);
|
||||||
|
let added = 0;
|
||||||
|
for (const path of paths) {
|
||||||
|
const row: RepoRow = {
|
||||||
|
id: randomUUID(),
|
||||||
|
path,
|
||||||
|
label: basename(path),
|
||||||
|
default_branch: null,
|
||||||
|
post_create_hooks: '[]',
|
||||||
|
pre_trust: 0,
|
||||||
|
created_at: new Date().toISOString(),
|
||||||
|
hidden: 0,
|
||||||
|
};
|
||||||
|
const res = insert.run(row.id, row.path, row.label, row.created_at);
|
||||||
|
if (res.changes === 1) {
|
||||||
|
added++;
|
||||||
|
this.emit('repo_update', await this.rowToSummary(row)); // nouveaux uniquement
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { scanned: paths.length, added, durationMs: Date.now() - t0, truncated };
|
||||||
|
}
|
||||||
|
|
||||||
// ---- worktrees ----
|
// ---- worktrees ----
|
||||||
|
|
||||||
/** Sessions (managées + découvertes) dont le cwd correspond à ce chemin de worktree. */
|
/** Sessions (managées + découvertes) dont le cwd correspond à ce chemin de worktree. */
|
||||||
@@ -214,8 +282,13 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async listAllWorktrees(): Promise<WorktreeSummary[]> {
|
async listAllWorktrees(): Promise<WorktreeSummary[]> {
|
||||||
const rows = this.db.prepare('SELECT id FROM repos ORDER BY created_at ASC').all() as Array<{ id: string }>;
|
// Les repos masqués sont exclus du dashboard : inutile de calculer leurs worktrees (sous-process
|
||||||
const lists = await Promise.all(rows.map((r) => this.listRepoWorktrees(r.id)));
|
// git par repo). Le front charge paresseusement ceux d'un repo masqué via listRepoWorktrees
|
||||||
|
// quand l'utilisateur active « afficher les masqués ».
|
||||||
|
const rows = this.db.prepare('SELECT id FROM repos WHERE hidden = 0 ORDER BY created_at ASC').all() as Array<{ id: string }>;
|
||||||
|
// Tolérance par repo : avec la découverte auto, un repo douteux (git en échec, chemin disparu,
|
||||||
|
// permission) ne doit JAMAIS faire planter tout l'endpoint — il ne contribue alors aucun worktree.
|
||||||
|
const lists = await Promise.all(rows.map((r) => this.listRepoWorktrees(r.id).catch(() => [])));
|
||||||
return lists.flat();
|
return lists.flat();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { DatabaseSync } from 'node:sqlite';
|
import { DatabaseSync } from 'node:sqlite';
|
||||||
|
import { chmodSync, existsSync } from 'node:fs';
|
||||||
|
|
||||||
const MIGRATIONS: Array<{ id: number; sql: string }> = [
|
const MIGRATIONS: Array<{ id: number; sql: string }> = [
|
||||||
{
|
{
|
||||||
@@ -93,6 +94,30 @@ const MIGRATIONS: Array<{ id: number; sql: string }> = [
|
|||||||
CREATE INDEX idx_group_repos_repo ON group_repos(repo_id);
|
CREATE INDEX idx_group_repos_repo ON group_repos(repo_id);
|
||||||
`,
|
`,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
// Découverte auto : un repo masqué reste en DB (exclu du dashboard) pour qu'un
|
||||||
|
// re-scan ne le ressuscite pas. hidden=1 = masqué.
|
||||||
|
id: 6,
|
||||||
|
sql: `ALTER TABLE repos ADD COLUMN hidden INTEGER NOT NULL DEFAULT 0;`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// Journal d'audit (conformité entreprise : GDPR/SOX/ISO 27001). Trace les mutations
|
||||||
|
// sensibles (tokens, réglages, secrets, abonnements push, groupes). Ne contient JAMAIS
|
||||||
|
// de secret en clair — `details` est un JSON de métadonnées non sensibles.
|
||||||
|
id: 7,
|
||||||
|
sql: `
|
||||||
|
CREATE TABLE audit_logs (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
ts TEXT NOT NULL,
|
||||||
|
actor TEXT NOT NULL,
|
||||||
|
action TEXT NOT NULL,
|
||||||
|
resource_id TEXT,
|
||||||
|
details TEXT,
|
||||||
|
result TEXT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_audit_ts ON audit_logs(ts);
|
||||||
|
`,
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
export type Db = DatabaseSync;
|
export type Db = DatabaseSync;
|
||||||
@@ -101,10 +126,27 @@ export function openDb(path: string): Db {
|
|||||||
const db = new DatabaseSync(path);
|
const db = new DatabaseSync(path);
|
||||||
db.exec('PRAGMA journal_mode = WAL');
|
db.exec('PRAGMA journal_mode = WAL');
|
||||||
db.exec('PRAGMA foreign_keys = ON');
|
db.exec('PRAGMA foreign_keys = ON');
|
||||||
|
hardenDbPermissions(path);
|
||||||
migrate(db);
|
migrate(db);
|
||||||
return db;
|
return db;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Restreint la base (et ses fichiers WAL/SHM) à 0o600 — proprio uniquement. La base contient des
|
||||||
|
* secrets (server_secret, clé privée VAPID, hashs de tokens) : elle ne doit jamais être lisible par
|
||||||
|
* d'autres utilisateurs du système. Best-effort : ignoré sur les FS sans permissions POSIX.
|
||||||
|
*/
|
||||||
|
function hardenDbPermissions(path: string): void {
|
||||||
|
if (path === ':memory:') return;
|
||||||
|
for (const p of [path, `${path}-wal`, `${path}-shm`]) {
|
||||||
|
try {
|
||||||
|
if (existsSync(p)) chmodSync(p, 0o600);
|
||||||
|
} catch {
|
||||||
|
/* FS sans permissions POSIX (Windows / montage) : ignoré */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function migrate(db: DatabaseSync): void {
|
function migrate(db: DatabaseSync): void {
|
||||||
db.exec('CREATE TABLE IF NOT EXISTS schema_migrations (id INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)');
|
db.exec('CREATE TABLE IF NOT EXISTS schema_migrations (id INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)');
|
||||||
const applied = new Set(
|
const applied = new Set(
|
||||||
|
|||||||
@@ -14,11 +14,12 @@ const pkg = JSON.parse(
|
|||||||
/** Démarre le daemon : écoute HTTP, scan des sessions, drain propre au SIGTERM/SIGINT. */
|
/** Démarre le daemon : écoute HTTP, scan des sessions, drain propre au SIGTERM/SIGINT. */
|
||||||
export async function runDaemon(config: Config): Promise<void> {
|
export async function runDaemon(config: Config): Promise<void> {
|
||||||
const db = openDb(config.dbPath);
|
const db = openDb(config.dbPath);
|
||||||
const { app, auth, manager, discovery } = buildApp(config, db, pkg.version);
|
const { app, auth, manager, discovery, repoDiscovery } = buildApp(config, db, pkg.version);
|
||||||
|
|
||||||
const bootstrapToken = auth.ensureBootstrapToken();
|
const bootstrapToken = auth.ensureBootstrapToken();
|
||||||
await app.listen({ port: config.port, host: config.bind });
|
await app.listen({ port: config.port, host: config.bind });
|
||||||
discovery.start(); // scan initial + rafraîchissement périodique des sessions découvertes
|
discovery.start(); // scan initial + rafraîchissement périodique des sessions découvertes
|
||||||
|
if (config.autoDiscover) repoDiscovery.start(); // découverte auto des repos : scan au boot + re-scan périodique
|
||||||
|
|
||||||
const url = `http://${config.bind === '0.0.0.0' ? '127.0.0.1' : config.bind}:${config.port}`;
|
const url = `http://${config.bind === '0.0.0.0' ? '127.0.0.1' : config.bind}:${config.port}`;
|
||||||
app.log.info(`Arboretum v${pkg.version} — ${url}`);
|
app.log.info(`Arboretum v${pkg.version} — ${url}`);
|
||||||
@@ -35,6 +36,7 @@ export async function runDaemon(config: Config): Promise<void> {
|
|||||||
shuttingDown = true;
|
shuttingDown = true;
|
||||||
app.log.info(`${signal} received — draining sessions then exiting`);
|
app.log.info(`${signal} received — draining sessions then exiting`);
|
||||||
discovery.stop();
|
discovery.stop();
|
||||||
|
repoDiscovery.stop();
|
||||||
manager.shutdown();
|
manager.shutdown();
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
void app.close().then(() => process.exit(0));
|
void app.close().then(() => process.exit(0));
|
||||||
|
|||||||
17
packages/server/src/routes/audit.ts
Normal file
17
packages/server/src/routes/audit.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
// Consultation du journal d'audit (onglet Réglages / outils de conformité). Lecture seule, sous
|
||||||
|
// l'auth globale. Pagination par curseur `before` (ts décroissant).
|
||||||
|
import type { FastifyInstance } from 'fastify';
|
||||||
|
import type { AuditLogsResponse } from '@arboretum/shared';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
import { listAudit } from '../core/audit-log.js';
|
||||||
|
|
||||||
|
export function registerAuditRoutes(app: FastifyInstance, db: Db): void {
|
||||||
|
app.get('/api/v1/audit-logs', async (req): Promise<AuditLogsResponse> => {
|
||||||
|
const q = req.query as { limit?: string; before?: string };
|
||||||
|
const limit = Math.min(Math.max(Math.trunc(Number(q.limit) || 50), 1), 200);
|
||||||
|
const entries = listAudit(db, { limit, before: q.before ?? null });
|
||||||
|
// s'il reste potentiellement des entrées (page pleine), expose le curseur suivant.
|
||||||
|
const nextBefore = entries.length === limit ? entries[entries.length - 1]!.ts : null;
|
||||||
|
return { entries, nextBefore };
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,11 +1,20 @@
|
|||||||
import type { FastifyInstance, FastifyRequest } from 'fastify';
|
import type { FastifyInstance, FastifyRequest } from 'fastify';
|
||||||
import type { LoginRequest, LoginResponse, MeResponse } from '@arboretum/shared';
|
import type {
|
||||||
|
CreateTokenRequest,
|
||||||
|
CreateTokenResponse,
|
||||||
|
LoginRequest,
|
||||||
|
LoginResponse,
|
||||||
|
MeResponse,
|
||||||
|
TokensListResponse,
|
||||||
|
} from '@arboretum/shared';
|
||||||
import type { AuthService, LoginRateLimiter } from '../auth/service.js';
|
import type { AuthService, LoginRateLimiter } from '../auth/service.js';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
import { recordAudit } from '../core/audit-log.js';
|
||||||
|
|
||||||
// Tailscale Serve / un reverse-proxy TLS posent x-forwarded-proto. On ne sert jamais
|
// Tailscale Serve / un reverse-proxy TLS posent x-forwarded-proto. On ne sert jamais
|
||||||
// en TLS direct : `secure` n'est posé que derrière un front HTTPS, jamais en localhost http
|
// en TLS direct : `secure` n'est posé que derrière un front HTTPS, jamais en localhost http
|
||||||
// (sinon le navigateur refuserait le cookie sur http://127.0.0.1 et le login local casserait).
|
// (sinon le navigateur refuserait le cookie sur http://127.0.0.1 et le login local casserait).
|
||||||
function isHttpsRequest(req: FastifyRequest): boolean {
|
export function isHttpsRequest(req: FastifyRequest): boolean {
|
||||||
const xfp = req.headers['x-forwarded-proto'];
|
const xfp = req.headers['x-forwarded-proto'];
|
||||||
const proto = (Array.isArray(xfp) ? xfp[0] : xfp)?.split(',')[0]?.trim();
|
const proto = (Array.isArray(xfp) ? xfp[0] : xfp)?.split(',')[0]?.trim();
|
||||||
return proto === 'https';
|
return proto === 'https';
|
||||||
@@ -16,6 +25,7 @@ export function registerAuthRoutes(
|
|||||||
auth: AuthService,
|
auth: AuthService,
|
||||||
limiter: LoginRateLimiter,
|
limiter: LoginRateLimiter,
|
||||||
serverVersion: string,
|
serverVersion: string,
|
||||||
|
db: Db,
|
||||||
): void {
|
): void {
|
||||||
app.post('/api/v1/auth/login', { config: { public: true } }, async (req, reply) => {
|
app.post('/api/v1/auth/login', { config: { public: true } }, async (req, reply) => {
|
||||||
const wait = limiter.check();
|
const wait = limiter.check();
|
||||||
@@ -26,9 +36,11 @@ export function registerAuthRoutes(
|
|||||||
const ctx = typeof body?.token === 'string' ? auth.verifyRawToken(body.token) : null;
|
const ctx = typeof body?.token === 'string' ? auth.verifyRawToken(body.token) : null;
|
||||||
if (!ctx) {
|
if (!ctx) {
|
||||||
limiter.recordFailure();
|
limiter.recordFailure();
|
||||||
|
recordAudit(db, { actor: 'anonymous', action: 'login.failure', result: 'denied' });
|
||||||
return reply.status(401).send({ error: { code: 'BAD_TOKEN', message: 'Invalid token' } });
|
return reply.status(401).send({ error: { code: 'BAD_TOKEN', message: 'Invalid token' } });
|
||||||
}
|
}
|
||||||
limiter.recordSuccess();
|
limiter.recordSuccess();
|
||||||
|
recordAudit(db, { actor: ctx.tokenId, action: 'login.success' });
|
||||||
void reply.setCookie(auth.cookieName, auth.issueCookie(ctx), {
|
void reply.setCookie(auth.cookieName, auth.issueCookie(ctx), {
|
||||||
path: '/',
|
path: '/',
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
@@ -41,7 +53,12 @@ export function registerAuthRoutes(
|
|||||||
});
|
});
|
||||||
|
|
||||||
app.get('/api/v1/auth/me', async (req, reply) => {
|
app.get('/api/v1/auth/me', async (req, reply) => {
|
||||||
const res: MeResponse = { ok: true, tokenLabel: req.authContext?.label ?? 'unknown', serverVersion };
|
const res: MeResponse = {
|
||||||
|
ok: true,
|
||||||
|
tokenId: req.authContext?.tokenId ?? '',
|
||||||
|
tokenLabel: req.authContext?.label ?? 'unknown',
|
||||||
|
serverVersion,
|
||||||
|
};
|
||||||
return reply.send(res);
|
return reply.send(res);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -50,4 +67,39 @@ export function registerAuthRoutes(
|
|||||||
void reply.clearCookie(auth.cookieName, { path: '/', secure: isHttpsRequest(req) });
|
void reply.clearCookie(auth.cookieName, { path: '/', secure: isHttpsRequest(req) });
|
||||||
return reply.send({ ok: true });
|
return reply.send({ ok: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ---- Gestion des tokens d'accès (onglet Réglages) ----
|
||||||
|
// Sous l'auth globale (preValidation). On ne renvoie jamais le hash ; la valeur en clair
|
||||||
|
// d'un nouveau token n'est exposée qu'une seule fois, à la création.
|
||||||
|
app.get('/api/v1/auth/tokens', async (req): Promise<TokensListResponse> => {
|
||||||
|
const current = req.authContext?.tokenId;
|
||||||
|
return { tokens: auth.listTokens().map((t) => ({ ...t, current: t.id === current })) };
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post('/api/v1/auth/tokens', async (req, reply) => {
|
||||||
|
const body = req.body as Partial<CreateTokenRequest> | null;
|
||||||
|
const label = typeof body?.label === 'string' ? body.label.trim() : '';
|
||||||
|
if (label.length < 1 || label.length > 64) {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'label must be 1–64 characters' } });
|
||||||
|
}
|
||||||
|
const { id, token } = auth.createTokenRecord(label);
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'token.create', resourceId: id, details: { label } });
|
||||||
|
return reply.status(201).send({ id, label, token } satisfies CreateTokenResponse);
|
||||||
|
});
|
||||||
|
|
||||||
|
app.delete('/api/v1/auth/tokens/:id', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const result = auth.revokeToken(id);
|
||||||
|
const actor = req.authContext?.tokenId ?? 'unknown';
|
||||||
|
if (result === 'not_found') {
|
||||||
|
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No active token with this id' } });
|
||||||
|
}
|
||||||
|
if (result === 'last') {
|
||||||
|
recordAudit(db, { actor, action: 'token.revoke', resourceId: id, result: 'denied', details: { reason: 'last_active_token' } });
|
||||||
|
return reply.status(409).send({ error: { code: 'LAST_TOKEN', message: 'Cannot revoke the last active token' } });
|
||||||
|
}
|
||||||
|
recordAudit(db, { actor, action: 'token.revoke', resourceId: id });
|
||||||
|
// 200 + corps JSON (pas 204) : le mini-client REST du front parse toujours la réponse.
|
||||||
|
return reply.send({ ok: true });
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
54
packages/server/src/routes/data.ts
Normal file
54
packages/server/src/routes/data.ts
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
// RGPD (droits d'accès & d'effacement) : export et suppression des données rattachées au token
|
||||||
|
// authentifié. Modèle mono-utilisateur → le détenteur du token EST le sujet des données. Sous l'auth
|
||||||
|
// globale. La suppression se fait en deux temps (code de confirmation) pour éviter les clics accidentels.
|
||||||
|
import { createHash } from 'node:crypto';
|
||||||
|
import type { FastifyInstance } from 'fastify';
|
||||||
|
import type { DataExportResponse, DeleteMyDataRequest, DeleteMyDataResponse } from '@arboretum/shared';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
import type { AuthService } from '../auth/service.js';
|
||||||
|
import { readScanIntervalMin, readScanRoots } from '../core/scan-settings.js';
|
||||||
|
import { recordAudit } from '../core/audit-log.js';
|
||||||
|
|
||||||
|
export function registerDataRoutes(app: FastifyInstance, db: Db, auth: AuthService): void {
|
||||||
|
app.get('/api/v1/data/export', async (req): Promise<DataExportResponse> => {
|
||||||
|
const current = req.authContext!.tokenId;
|
||||||
|
const tokens = auth.listTokens().map((t) => ({ ...t, current: t.id === current }));
|
||||||
|
const pushSubscriptions = db
|
||||||
|
.prepare(
|
||||||
|
'SELECT endpoint, user_agent AS userAgent, created_at AS createdAt, last_ok_at AS lastOkAt FROM push_subscriptions WHERE token_id = ?',
|
||||||
|
)
|
||||||
|
.all(current) as DataExportResponse['pushSubscriptions'];
|
||||||
|
const sessions = db
|
||||||
|
.prepare(
|
||||||
|
'SELECT id, cwd, command, title, created_at AS createdAt, ended_at AS endedAt, exit_code AS exitCode FROM sessions ORDER BY created_at',
|
||||||
|
)
|
||||||
|
.all() as DataExportResponse['sessions'];
|
||||||
|
return {
|
||||||
|
exportedAt: new Date().toISOString(),
|
||||||
|
tokens,
|
||||||
|
pushSubscriptions,
|
||||||
|
sessions,
|
||||||
|
settings: { scanRoots: readScanRoots(db), scanIntervalMin: readScanIntervalMin(db) },
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post('/api/v1/data/delete-my-data', async (req, reply) => {
|
||||||
|
const current = req.authContext!.tokenId;
|
||||||
|
// code déterministe lié au token (sans état serveur) : renvoyé au 1er appel, exigé au 2nd.
|
||||||
|
const code = createHash('sha256').update(`delete:${current}`).digest('hex').slice(0, 12);
|
||||||
|
const body = (req.body as DeleteMyDataRequest | null) ?? {};
|
||||||
|
const subsCount = (db.prepare('SELECT COUNT(*) AS n FROM push_subscriptions WHERE token_id = ?').get(current) as { n: number }).n;
|
||||||
|
|
||||||
|
if (body.confirm !== code) {
|
||||||
|
const res: DeleteMyDataResponse = { status: 'pending', confirm: code, summary: { pushSubscriptions: subsCount, tokenRevoked: false } };
|
||||||
|
return reply.send(res);
|
||||||
|
}
|
||||||
|
|
||||||
|
db.prepare('DELETE FROM push_subscriptions WHERE token_id = ?').run(current);
|
||||||
|
// révoque le token courant (sauf si c'est le dernier actif → garde anti lock-out conservée).
|
||||||
|
const revoked = auth.revokeToken(current) === 'ok';
|
||||||
|
recordAudit(db, { actor: current, action: 'data.delete', details: { pushSubscriptions: subsCount, tokenRevoked: revoked } });
|
||||||
|
const res: DeleteMyDataResponse = { status: 'done', summary: { pushSubscriptions: subsCount, tokenRevoked: revoked } };
|
||||||
|
return reply.send(res);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -7,9 +7,11 @@ import type {
|
|||||||
UpdateGroupRequest,
|
UpdateGroupRequest,
|
||||||
} from '@arboretum/shared';
|
} from '@arboretum/shared';
|
||||||
import type { GroupManager } from '../core/group-manager.js';
|
import type { GroupManager } from '../core/group-manager.js';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
import { recordAudit } from '../core/audit-log.js';
|
||||||
import { sendManagerError } from './repos.js';
|
import { sendManagerError } from './repos.js';
|
||||||
|
|
||||||
export function registerGroupRoutes(app: FastifyInstance, gm: GroupManager): void {
|
export function registerGroupRoutes(app: FastifyInstance, gm: GroupManager, db: Db): void {
|
||||||
app.get('/api/v1/groups', async (): Promise<GroupsListResponse> => ({ groups: gm.listGroups() }));
|
app.get('/api/v1/groups', async (): Promise<GroupsListResponse> => ({ groups: gm.listGroups() }));
|
||||||
|
|
||||||
app.get('/api/v1/groups/:id', async (req, reply) => {
|
app.get('/api/v1/groups/:id', async (req, reply) => {
|
||||||
@@ -33,6 +35,7 @@ export function registerGroupRoutes(app: FastifyInstance, gm: GroupManager): voi
|
|||||||
...(body.color !== undefined ? { color: body.color } : {}),
|
...(body.color !== undefined ? { color: body.color } : {}),
|
||||||
...(Array.isArray(body.repoIds) ? { repoIds: body.repoIds } : {}),
|
...(Array.isArray(body.repoIds) ? { repoIds: body.repoIds } : {}),
|
||||||
});
|
});
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'group.create', resourceId: group.id, details: { label: group.label } });
|
||||||
return reply.status(201).send({ group } satisfies GroupResponse);
|
return reply.status(201).send({ group } satisfies GroupResponse);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return sendManagerError(reply, err);
|
return sendManagerError(reply, err);
|
||||||
@@ -48,6 +51,7 @@ export function registerGroupRoutes(app: FastifyInstance, gm: GroupManager): voi
|
|||||||
...(body.description !== undefined ? { description: body.description } : {}),
|
...(body.description !== undefined ? { description: body.description } : {}),
|
||||||
...(body.color !== undefined ? { color: body.color } : {}),
|
...(body.color !== undefined ? { color: body.color } : {}),
|
||||||
});
|
});
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'group.update', resourceId: id });
|
||||||
return reply.send({ group } satisfies GroupResponse);
|
return reply.send({ group } satisfies GroupResponse);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return sendManagerError(reply, err);
|
return sendManagerError(reply, err);
|
||||||
@@ -59,6 +63,7 @@ export function registerGroupRoutes(app: FastifyInstance, gm: GroupManager): voi
|
|||||||
if (!gm.deleteGroup(id)) {
|
if (!gm.deleteGroup(id)) {
|
||||||
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No group with this id' } });
|
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No group with this id' } });
|
||||||
}
|
}
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'group.delete', resourceId: id });
|
||||||
return reply.send({ ok: true });
|
return reply.send({ ok: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -3,8 +3,10 @@
|
|||||||
import type { FastifyInstance } from 'fastify';
|
import type { FastifyInstance } from 'fastify';
|
||||||
import type { PushSubscribeRequest, PushUnsubscribeRequest, VapidKeyResponse } from '@arboretum/shared';
|
import type { PushSubscribeRequest, PushUnsubscribeRequest, VapidKeyResponse } from '@arboretum/shared';
|
||||||
import type { PushService } from '../core/push-service.js';
|
import type { PushService } from '../core/push-service.js';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
import { recordAudit } from '../core/audit-log.js';
|
||||||
|
|
||||||
export function registerPushRoutes(app: FastifyInstance, push: PushService): void {
|
export function registerPushRoutes(app: FastifyInstance, push: PushService, db: Db): void {
|
||||||
app.get('/api/v1/push/vapid-public-key', async (): Promise<VapidKeyResponse> => ({ key: push.publicKey() }));
|
app.get('/api/v1/push/vapid-public-key', async (): Promise<VapidKeyResponse> => ({ key: push.publicKey() }));
|
||||||
|
|
||||||
app.post('/api/v1/push/subscribe', async (req, reply) => {
|
app.post('/api/v1/push/subscribe', async (req, reply) => {
|
||||||
@@ -15,6 +17,7 @@ export function registerPushRoutes(app: FastifyInstance, push: PushService): voi
|
|||||||
// garanti non-null : la route est protégée par le preValidation global.
|
// garanti non-null : la route est protégée par le preValidation global.
|
||||||
const tokenId = req.authContext!.tokenId;
|
const tokenId = req.authContext!.tokenId;
|
||||||
push.subscribe(tokenId, { endpoint: body.endpoint, keys: { p256dh: body.keys.p256dh, auth: body.keys.auth } }, req.headers['user-agent'] ?? null);
|
push.subscribe(tokenId, { endpoint: body.endpoint, keys: { p256dh: body.keys.p256dh, auth: body.keys.auth } }, req.headers['user-agent'] ?? null);
|
||||||
|
recordAudit(db, { actor: tokenId, action: 'push.subscribe' });
|
||||||
return reply.status(201).send({ ok: true });
|
return reply.status(201).send({ ok: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -24,6 +27,7 @@ export function registerPushRoutes(app: FastifyInstance, push: PushService): voi
|
|||||||
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'endpoint is required' } });
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'endpoint is required' } });
|
||||||
}
|
}
|
||||||
push.unsubscribe(body.endpoint);
|
push.unsubscribe(body.endpoint);
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'push.unsubscribe' });
|
||||||
return reply.send({ ok: true });
|
return reply.send({ ok: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import type { FastifyInstance, FastifyReply } from 'fastify';
|
import type { FastifyInstance, FastifyReply } from 'fastify';
|
||||||
import type { CreateRepoRequest, RepoResponse, ReposListResponse, UpdateRepoRequest } from '@arboretum/shared';
|
import type { CreateRepoRequest, DiscoverReposResponse, RepoResponse, ReposListResponse, UpdateRepoRequest } from '@arboretum/shared';
|
||||||
import type { WorktreeManager } from '../core/worktree-manager.js';
|
import type { WorktreeManager } from '../core/worktree-manager.js';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
import { readScanRoots } from '../core/scan-settings.js';
|
||||||
|
|
||||||
/** Mappe une erreur du manager (statusCode + code) vers une réponse REST normalisée. */
|
/** Mappe une erreur du manager (statusCode + code) vers une réponse REST normalisée. */
|
||||||
export function sendManagerError(reply: FastifyReply, err: unknown): FastifyReply {
|
export function sendManagerError(reply: FastifyReply, err: unknown): FastifyReply {
|
||||||
@@ -8,9 +10,19 @@ export function sendManagerError(reply: FastifyReply, err: unknown): FastifyRepl
|
|||||||
return reply.status(e.statusCode ?? 500).send({ error: { code: e.code ?? 'INTERNAL', message: e.message ?? 'Internal error' } });
|
return reply.status(e.statusCode ?? 500).send({ error: { code: e.code ?? 'INTERNAL', message: e.message ?? 'Internal error' } });
|
||||||
}
|
}
|
||||||
|
|
||||||
export function registerRepoRoutes(app: FastifyInstance, wt: WorktreeManager): void {
|
export function registerRepoRoutes(app: FastifyInstance, wt: WorktreeManager, db: Db): void {
|
||||||
app.get('/api/v1/repos', async (): Promise<ReposListResponse> => ({ repos: await wt.listRepos() }));
|
app.get('/api/v1/repos', async (): Promise<ReposListResponse> => ({ repos: await wt.listRepos() }));
|
||||||
|
|
||||||
|
// Scan manuel : découvre et auto-enregistre les repos sous les racines configurées (settings).
|
||||||
|
app.post('/api/v1/repos/discover', async (_req, reply) => {
|
||||||
|
try {
|
||||||
|
const res: DiscoverReposResponse = await wt.discoverRepos({ roots: readScanRoots(db) });
|
||||||
|
return reply.send(res);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
app.post('/api/v1/repos', async (req, reply) => {
|
app.post('/api/v1/repos', async (req, reply) => {
|
||||||
const body = req.body as Partial<CreateRepoRequest> | null;
|
const body = req.body as Partial<CreateRepoRequest> | null;
|
||||||
if (!body || typeof body.path !== 'string') {
|
if (!body || typeof body.path !== 'string') {
|
||||||
@@ -38,6 +50,7 @@ export function registerRepoRoutes(app: FastifyInstance, wt: WorktreeManager): v
|
|||||||
...(body.label !== undefined ? { label: body.label } : {}),
|
...(body.label !== undefined ? { label: body.label } : {}),
|
||||||
...(body.postCreateHooks !== undefined ? { postCreateHooks: body.postCreateHooks } : {}),
|
...(body.postCreateHooks !== undefined ? { postCreateHooks: body.postCreateHooks } : {}),
|
||||||
...(body.preTrust !== undefined ? { preTrust: body.preTrust } : {}),
|
...(body.preTrust !== undefined ? { preTrust: body.preTrust } : {}),
|
||||||
|
...(typeof body.hidden === 'boolean' ? { hidden: body.hidden } : {}),
|
||||||
});
|
});
|
||||||
const res: RepoResponse = { repo };
|
const res: RepoResponse = { repo };
|
||||||
return reply.send(res);
|
return reply.send(res);
|
||||||
|
|||||||
69
packages/server/src/routes/settings.ts
Normal file
69
packages/server/src/routes/settings.ts
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
// Réglages exposés à l'UI (onglet Réglages). Frontière de sécurité CENTRALE : la table `settings`
|
||||||
|
// contient aussi des SECRETS (server_secret, vapid_private). Ces routes n'exposent QUE des champs
|
||||||
|
// non sensibles et n'écrivent QUE des clés explicitement allow-listées — jamais les secrets.
|
||||||
|
import type { FastifyInstance } from 'fastify';
|
||||||
|
import type { ServerInfo, SettingsResponse, UpdateSettingsRequest } from '@arboretum/shared';
|
||||||
|
import type { Config } from '../config.js';
|
||||||
|
import { type Db, setSetting } from '../db/index.js';
|
||||||
|
import type { PushService } from '../core/push-service.js';
|
||||||
|
import { recordAudit } from '../core/audit-log.js';
|
||||||
|
import {
|
||||||
|
SCAN_INTERVAL_KEY,
|
||||||
|
SCAN_ROOTS_KEY,
|
||||||
|
normalizeScanIntervalMin,
|
||||||
|
normalizeScanRoots,
|
||||||
|
readScanIntervalMin,
|
||||||
|
readScanRoots,
|
||||||
|
} from '../core/scan-settings.js';
|
||||||
|
|
||||||
|
// Réglages modifiables via l'API (allow-list stricte). Les secrets ne figurent JAMAIS ici.
|
||||||
|
export function registerSettingsRoutes(
|
||||||
|
app: FastifyInstance,
|
||||||
|
db: Db,
|
||||||
|
config: Config,
|
||||||
|
serverVersion: string,
|
||||||
|
push: PushService,
|
||||||
|
): void {
|
||||||
|
const serverInfo = (): ServerInfo => ({
|
||||||
|
version: serverVersion,
|
||||||
|
port: config.port,
|
||||||
|
bind: config.bind,
|
||||||
|
allowedOrigins: config.allowedOrigins,
|
||||||
|
dataDir: config.dataDir,
|
||||||
|
vapidPublicKey: push.publicKey() || null,
|
||||||
|
vapidContact: config.vapidContact,
|
||||||
|
});
|
||||||
|
const snapshot = (): SettingsResponse => ({
|
||||||
|
settings: {
|
||||||
|
scanRoots: readScanRoots(db),
|
||||||
|
scanIntervalMin: readScanIntervalMin(db),
|
||||||
|
},
|
||||||
|
server: serverInfo(),
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get('/api/v1/settings', async (): Promise<SettingsResponse> => snapshot());
|
||||||
|
|
||||||
|
app.patch('/api/v1/settings', async (req, reply) => {
|
||||||
|
const body = (req.body as Partial<UpdateSettingsRequest> | null) ?? {};
|
||||||
|
if ('scanRoots' in body) {
|
||||||
|
const roots = normalizeScanRoots(body.scanRoots);
|
||||||
|
if (!roots) {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'scanRoots must be an array of ≤16 absolute, normalized paths (never "/")' } });
|
||||||
|
}
|
||||||
|
setSetting(db, SCAN_ROOTS_KEY, JSON.stringify(roots));
|
||||||
|
}
|
||||||
|
if ('scanIntervalMin' in body) {
|
||||||
|
const interval = normalizeScanIntervalMin(body.scanIntervalMin);
|
||||||
|
if (interval === null) {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'scanIntervalMin must be an integer between 0 and 1440' } });
|
||||||
|
}
|
||||||
|
setSetting(db, SCAN_INTERVAL_KEY, String(interval));
|
||||||
|
}
|
||||||
|
recordAudit(db, {
|
||||||
|
actor: req.authContext?.tokenId ?? 'unknown',
|
||||||
|
action: 'settings.update',
|
||||||
|
details: { keys: Object.keys(body) },
|
||||||
|
});
|
||||||
|
return reply.send(snapshot());
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ import { openDb, type Db } from '../src/db/index.js';
|
|||||||
import { munge } from '../src/core/jsonl-discovery.js';
|
import { munge } from '../src/core/jsonl-discovery.js';
|
||||||
import { readProcStart } from '../src/core/session-registry.js';
|
import { readProcStart } from '../src/core/session-registry.js';
|
||||||
import type { Config } from '../src/config.js';
|
import type { Config } from '../src/config.js';
|
||||||
|
import type { DiscoverReposResponse, RepoResponse, ReposListResponse } from '@arboretum/shared';
|
||||||
|
|
||||||
// resolveClaudeBin() fait `which claude` : on le stub pour ne pas dépendre d'un claude réel en PATH.
|
// resolveClaudeBin() fait `which claude` : on le stub pour ne pas dépendre d'un claude réel en PATH.
|
||||||
vi.mock('node:child_process', () => ({ execFileSync: () => '/usr/bin/claude\n' }));
|
vi.mock('node:child_process', () => ({ execFileSync: () => '/usr/bin/claude\n' }));
|
||||||
@@ -127,7 +128,8 @@ describe('app e2e — auth, origin et sessions', () => {
|
|||||||
cookies: { arb_session: cookieValue },
|
cookies: { arb_session: cookieValue },
|
||||||
});
|
});
|
||||||
expect(me.statusCode).toBe(200);
|
expect(me.statusCode).toBe(200);
|
||||||
expect(me.json()).toEqual({ ok: true, tokenLabel: 'initial', serverVersion: '0.0.0-test' });
|
expect(me.json()).toMatchObject({ ok: true, tokenLabel: 'initial', serverVersion: '0.0.0-test' });
|
||||||
|
expect(typeof (me.json() as { tokenId: string }).tokenId).toBe('string');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('cookie altéré → 401', async () => {
|
it('cookie altéré → 401', async () => {
|
||||||
@@ -353,3 +355,59 @@ describe('app e2e — découverte, resume & fork (P2)', () => {
|
|||||||
expect(fork.statusCode).toBe(201);
|
expect(fork.statusCode).toBe(201);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('app e2e — découverte auto des repos & masquage', () => {
|
||||||
|
let t: TestApp;
|
||||||
|
let scanRoot: string;
|
||||||
|
const bearer = (): Record<string, string> => ({ authorization: `Bearer ${t.token}` });
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
t = makeApp('repos-discover');
|
||||||
|
// un « repo » côté scanner = un dossier avec .git (le scanner ne lance pas git).
|
||||||
|
scanRoot = join(dir, 'scan-root');
|
||||||
|
mkdirSync(join(scanRoot, 'alpha', '.git'), { recursive: true });
|
||||||
|
mkdirSync(join(scanRoot, 'beta', '.git'), { recursive: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('POST /repos/discover enregistre les repos sous les racines configurées', async () => {
|
||||||
|
// configure la racine de scan via l'allow-list settings, désactive le périodique
|
||||||
|
const patch = await t.bundle.app.inject({
|
||||||
|
method: 'PATCH',
|
||||||
|
url: '/api/v1/settings',
|
||||||
|
headers: bearer(),
|
||||||
|
payload: { scanRoots: [scanRoot], scanIntervalMin: 0 },
|
||||||
|
});
|
||||||
|
expect(patch.statusCode).toBe(200);
|
||||||
|
|
||||||
|
const disc = await t.bundle.app.inject({ method: 'POST', url: '/api/v1/repos/discover', headers: bearer() });
|
||||||
|
expect(disc.statusCode).toBe(200);
|
||||||
|
const body = disc.json() as DiscoverReposResponse;
|
||||||
|
expect(body.added).toBe(2);
|
||||||
|
expect(body.scanned).toBe(2);
|
||||||
|
|
||||||
|
const list = await t.bundle.app.inject({ method: 'GET', url: '/api/v1/repos', headers: bearer() });
|
||||||
|
const repos = (list.json() as ReposListResponse).repos;
|
||||||
|
expect(repos.map((r) => r.label).sort()).toEqual(['alpha', 'beta']);
|
||||||
|
expect(repos.every((r) => r.hidden === false)).toBe(true);
|
||||||
|
|
||||||
|
// re-scan : idempotent (aucun nouveau)
|
||||||
|
const disc2 = await t.bundle.app.inject({ method: 'POST', url: '/api/v1/repos/discover', headers: bearer() });
|
||||||
|
expect((disc2.json() as DiscoverReposResponse).added).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('PATCH /repos/:id { hidden } masque le repo', async () => {
|
||||||
|
const list = await t.bundle.app.inject({ method: 'GET', url: '/api/v1/repos', headers: bearer() });
|
||||||
|
const repo = (list.json() as ReposListResponse).repos[0];
|
||||||
|
const patch = await t.bundle.app.inject({
|
||||||
|
method: 'PATCH',
|
||||||
|
url: `/api/v1/repos/${repo.id}`,
|
||||||
|
headers: bearer(),
|
||||||
|
payload: { hidden: true },
|
||||||
|
});
|
||||||
|
expect(patch.statusCode).toBe(200);
|
||||||
|
expect((patch.json() as RepoResponse).repo.hidden).toBe(true);
|
||||||
|
// toujours listé (les masqués restent récupérables) mais avec hidden=true
|
||||||
|
const after = await t.bundle.app.inject({ method: 'GET', url: '/api/v1/repos', headers: bearer() });
|
||||||
|
expect((after.json() as ReposListResponse).repos.find((r) => r.id === repo.id)?.hidden).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
164
packages/server/test/audit-data-routes.test.ts
Normal file
164
packages/server/test/audit-data-routes.test.ts
Normal file
@@ -0,0 +1,164 @@
|
|||||||
|
// Lot 5 — sécurité enterprise : en-têtes de sécurité, journal d'audit, RGPD (export/suppression),
|
||||||
|
// garde Content-Type. Vérifie le câblage de bout en bout via buildApp + token bootstrap.
|
||||||
|
import { mkdtempSync, rmSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { buildApp, type AppBundle } from '../src/app.js';
|
||||||
|
import { openDb, type Db } from '../src/db/index.js';
|
||||||
|
import type { Config } from '../src/config.js';
|
||||||
|
import type { AuditLogsResponse, DataExportResponse, DeleteMyDataResponse } from '@arboretum/shared';
|
||||||
|
|
||||||
|
vi.mock('node:child_process', () => ({ execFileSync: () => '/usr/bin/claude\n' }));
|
||||||
|
vi.mock('@homebridge/node-pty-prebuilt-multiarch', () => {
|
||||||
|
class FakePty {
|
||||||
|
pid = 424242;
|
||||||
|
write = vi.fn();
|
||||||
|
resize = vi.fn();
|
||||||
|
pause = vi.fn();
|
||||||
|
resume = vi.fn();
|
||||||
|
kill = vi.fn();
|
||||||
|
onData(): { dispose: () => void } {
|
||||||
|
return { dispose: () => {} };
|
||||||
|
}
|
||||||
|
onExit(): { dispose: () => void } {
|
||||||
|
return { dispose: () => {} };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { default: { spawn: (): FakePty => new FakePty() } };
|
||||||
|
});
|
||||||
|
|
||||||
|
process.env.ARBORETUM_LOG = 'silent';
|
||||||
|
|
||||||
|
let dir: string;
|
||||||
|
let bundle: AppBundle;
|
||||||
|
let db: Db;
|
||||||
|
let token: string;
|
||||||
|
const auth = (): { authorization: string } => ({ authorization: `Bearer ${token}` });
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
dir = mkdtempSync(join(tmpdir(), 'arboretum-audit-'));
|
||||||
|
const dbPath = join(dir, 'audit.db');
|
||||||
|
db = openDb(dbPath);
|
||||||
|
const config: Config = {
|
||||||
|
port: 9998,
|
||||||
|
bind: '127.0.0.1',
|
||||||
|
dbPath,
|
||||||
|
dataDir: dir,
|
||||||
|
allowedOrigins: ['https://host.tailnet.ts.net'],
|
||||||
|
printToken: false,
|
||||||
|
claudeProjectsDir: join(dir, 'claude', 'projects'),
|
||||||
|
claudeSessionsDir: join(dir, 'claude', 'sessions'),
|
||||||
|
vapidContact: 'mailto:test@localhost',
|
||||||
|
autoDiscover: false,
|
||||||
|
};
|
||||||
|
bundle = buildApp(config, db, '1.2.3-test');
|
||||||
|
const t = bundle.auth.ensureBootstrapToken();
|
||||||
|
if (!t) throw new Error('bootstrap token attendu');
|
||||||
|
token = t;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await bundle.app.close();
|
||||||
|
db.close();
|
||||||
|
rmSync(dir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('En-têtes de sécurité', () => {
|
||||||
|
it('pose les en-têtes durs + no-store sur /api, sans header Server', async () => {
|
||||||
|
const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/me', headers: auth() });
|
||||||
|
expect(res.statusCode).toBe(200);
|
||||||
|
expect(res.headers['x-content-type-options']).toBe('nosniff');
|
||||||
|
expect(res.headers['x-frame-options']).toBe('DENY');
|
||||||
|
expect(res.headers['referrer-policy']).toBe('no-referrer');
|
||||||
|
expect(res.headers['content-security-policy']).toContain("default-src 'self'");
|
||||||
|
expect(res.headers['content-security-policy']).toContain("frame-ancestors 'none'");
|
||||||
|
expect(String(res.headers['cache-control'])).toContain('no-store');
|
||||||
|
expect(res.headers['server']).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('pose HSTS uniquement derrière HTTPS (x-forwarded-proto)', async () => {
|
||||||
|
const http = await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/me', headers: auth() });
|
||||||
|
expect(http.headers['strict-transport-security']).toBeUndefined();
|
||||||
|
const https = await bundle.app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/auth/me',
|
||||||
|
headers: { ...auth(), 'x-forwarded-proto': 'https' },
|
||||||
|
});
|
||||||
|
expect(String(https.headers['strict-transport-security'])).toContain('max-age=');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejette une mutation avec corps non-JSON (415)', async () => {
|
||||||
|
const res = await bundle.app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/auth/tokens',
|
||||||
|
headers: { ...auth(), 'content-type': 'text/plain' },
|
||||||
|
payload: 'label=pwned',
|
||||||
|
});
|
||||||
|
expect(res.statusCode).toBe(415);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Journal d’audit', () => {
|
||||||
|
it('journalise la création de token et l’expose via GET /audit-logs', async () => {
|
||||||
|
const create = await bundle.app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/auth/tokens',
|
||||||
|
headers: auth(),
|
||||||
|
payload: { label: 'ci-extra' },
|
||||||
|
});
|
||||||
|
expect(create.statusCode).toBe(201);
|
||||||
|
|
||||||
|
const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/audit-logs', headers: auth() });
|
||||||
|
expect(res.statusCode).toBe(200);
|
||||||
|
const body = res.json() as AuditLogsResponse;
|
||||||
|
const actions = body.entries.map((e) => e.action);
|
||||||
|
expect(actions).toContain('token.create');
|
||||||
|
expect(actions).toContain('secret.generate'); // généré au bootstrap (system)
|
||||||
|
// aucune VALEUR secrète en clair : pas de chaîne hex de 64 caractères (server_secret / clé).
|
||||||
|
// (les ids sont des UUID avec tirets → non concernés ; 'server_secret' est un nom de ressource.)
|
||||||
|
expect(res.body).not.toMatch(/[a-f0-9]{64}/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('journalise les échecs de login (actor anonymous)', async () => {
|
||||||
|
await bundle.app.inject({ method: 'POST', url: '/api/v1/auth/login', payload: { token: 'arb_invalid_xxx' } });
|
||||||
|
const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/audit-logs?limit=200', headers: auth() });
|
||||||
|
const body = res.json() as AuditLogsResponse;
|
||||||
|
expect(body.entries.some((e) => e.action === 'login.failure' && e.actor === 'anonymous')).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('RGPD', () => {
|
||||||
|
it('exporte les données du token authentifié', async () => {
|
||||||
|
const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/data/export', headers: auth() });
|
||||||
|
expect(res.statusCode).toBe(200);
|
||||||
|
const body = res.json() as DataExportResponse;
|
||||||
|
expect(Array.isArray(body.tokens)).toBe(true);
|
||||||
|
expect(body.tokens.some((t) => t.current)).toBe(true);
|
||||||
|
expect(Array.isArray(body.pushSubscriptions)).toBe(true);
|
||||||
|
expect(Array.isArray(body.sessions)).toBe(true);
|
||||||
|
expect(body.settings).toHaveProperty('scanRoots');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('supprime en deux temps (pending → confirm → done) et révoque le token', async () => {
|
||||||
|
const pending = await bundle.app.inject({ method: 'POST', url: '/api/v1/data/delete-my-data', headers: auth(), payload: {} });
|
||||||
|
const p = pending.json() as DeleteMyDataResponse;
|
||||||
|
expect(p.status).toBe('pending');
|
||||||
|
expect(p.confirm).toBeTruthy();
|
||||||
|
|
||||||
|
// un 2e token existe (créé plus haut) → révoquer le token courant est autorisé.
|
||||||
|
const done = await bundle.app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/data/delete-my-data',
|
||||||
|
headers: auth(),
|
||||||
|
payload: { confirm: p.confirm },
|
||||||
|
});
|
||||||
|
const d = done.json() as DeleteMyDataResponse;
|
||||||
|
expect(d.status).toBe('done');
|
||||||
|
expect(d.summary.tokenRevoked).toBe(true);
|
||||||
|
|
||||||
|
// le token courant est désormais révoqué → 401.
|
||||||
|
const after = await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/me', headers: auth() });
|
||||||
|
expect(after.statusCode).toBe(401);
|
||||||
|
});
|
||||||
|
});
|
||||||
143
packages/server/test/auth-tokens.test.ts
Normal file
143
packages/server/test/auth-tokens.test.ts
Normal file
@@ -0,0 +1,143 @@
|
|||||||
|
// Gestion des tokens d'accès via l'API REST (onglet Réglages) : create → list → revoke,
|
||||||
|
// flag « courant », jamais de hash exposé, garde anti lock-out sur le dernier token.
|
||||||
|
import { mkdtempSync, rmSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { buildApp, type AppBundle } from '../src/app.js';
|
||||||
|
import { openDb, type Db } from '../src/db/index.js';
|
||||||
|
import type { Config } from '../src/config.js';
|
||||||
|
import type { CreateTokenResponse, MeResponse, TokensListResponse } from '@arboretum/shared';
|
||||||
|
|
||||||
|
// Mêmes stubs que les autres tests de routes : pas de vrai claude ni de vrai PTY.
|
||||||
|
vi.mock('node:child_process', () => ({ execFileSync: () => '/usr/bin/claude\n' }));
|
||||||
|
vi.mock('@homebridge/node-pty-prebuilt-multiarch', () => {
|
||||||
|
class FakePty {
|
||||||
|
pid = 424242;
|
||||||
|
write = vi.fn();
|
||||||
|
resize = vi.fn();
|
||||||
|
pause = vi.fn();
|
||||||
|
resume = vi.fn();
|
||||||
|
kill = vi.fn();
|
||||||
|
onData(): { dispose: () => void } {
|
||||||
|
return { dispose: () => {} };
|
||||||
|
}
|
||||||
|
onExit(): { dispose: () => void } {
|
||||||
|
return { dispose: () => {} };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { default: { spawn: (): FakePty => new FakePty() } };
|
||||||
|
});
|
||||||
|
|
||||||
|
process.env.ARBORETUM_LOG = 'silent';
|
||||||
|
|
||||||
|
let dir: string;
|
||||||
|
let bundle: AppBundle;
|
||||||
|
let db: Db;
|
||||||
|
let token: string;
|
||||||
|
|
||||||
|
const auth = (): { authorization: string } => ({ authorization: `Bearer ${token}` });
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
dir = mkdtempSync(join(tmpdir(), 'arboretum-tokens-'));
|
||||||
|
const dbPath = join(dir, 'tokens.db');
|
||||||
|
db = openDb(dbPath);
|
||||||
|
const config: Config = {
|
||||||
|
port: 7317,
|
||||||
|
bind: '127.0.0.1',
|
||||||
|
dbPath,
|
||||||
|
dataDir: dir,
|
||||||
|
allowedOrigins: [],
|
||||||
|
printToken: false,
|
||||||
|
claudeProjectsDir: join(dir, 'claude', 'projects'),
|
||||||
|
claudeSessionsDir: join(dir, 'claude', 'sessions'),
|
||||||
|
vapidContact: 'mailto:test@localhost',
|
||||||
|
};
|
||||||
|
bundle = buildApp(config, db, '0.0.0-test');
|
||||||
|
const t = bundle.auth.ensureBootstrapToken();
|
||||||
|
if (!t) throw new Error('bootstrap token attendu sur une base vierge');
|
||||||
|
token = t;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await bundle.app.close();
|
||||||
|
db.close();
|
||||||
|
rmSync(dir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('routes de gestion des tokens', () => {
|
||||||
|
it('GET /auth/me expose le tokenId courant', async () => {
|
||||||
|
const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/me', headers: auth() });
|
||||||
|
expect(res.statusCode).toBe(200);
|
||||||
|
const me = res.json() as MeResponse;
|
||||||
|
expect(typeof me.tokenId).toBe('string');
|
||||||
|
expect(me.tokenId.length).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('liste le token initial et le marque « courant », sans jamais exposer de hash', async () => {
|
||||||
|
const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/tokens', headers: auth() });
|
||||||
|
expect(res.statusCode).toBe(200);
|
||||||
|
const body = res.json() as TokensListResponse;
|
||||||
|
expect(body.tokens).toHaveLength(1);
|
||||||
|
expect(body.tokens[0]?.label).toBe('initial');
|
||||||
|
expect(body.tokens[0]?.current).toBe(true);
|
||||||
|
// aucune fuite de hash / valeur en clair
|
||||||
|
expect(JSON.stringify(body)).not.toMatch(/token_hash|tokenHash/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('crée un token (valeur en clair renvoyée une fois), puis utilisable pour s’authentifier', async () => {
|
||||||
|
const res = await bundle.app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/auth/tokens',
|
||||||
|
headers: auth(),
|
||||||
|
payload: { label: 'laptop' },
|
||||||
|
});
|
||||||
|
expect(res.statusCode).toBe(201);
|
||||||
|
const created = res.json() as CreateTokenResponse;
|
||||||
|
expect(created.label).toBe('laptop');
|
||||||
|
expect(created.token).toMatch(/^arb_[0-9a-f]{48}$/);
|
||||||
|
|
||||||
|
// le nouveau token authentifie réellement
|
||||||
|
const me = await bundle.app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/auth/me',
|
||||||
|
headers: { authorization: `Bearer ${created.token}` },
|
||||||
|
});
|
||||||
|
expect((me.json() as MeResponse).tokenLabel).toBe('laptop');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejette un label vide ou trop long (400)', async () => {
|
||||||
|
const empty = await bundle.app.inject({ method: 'POST', url: '/api/v1/auth/tokens', headers: auth(), payload: { label: ' ' } });
|
||||||
|
expect(empty.statusCode).toBe(400);
|
||||||
|
const tooLong = await bundle.app.inject({ method: 'POST', url: '/api/v1/auth/tokens', headers: auth(), payload: { label: 'x'.repeat(65) } });
|
||||||
|
expect(tooLong.statusCode).toBe(400);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('révoque un token non courant (204), qui disparaît de la liste et n’authentifie plus', async () => {
|
||||||
|
const before = (await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/tokens', headers: auth() })).json() as TokensListResponse;
|
||||||
|
const victim = before.tokens.find((t) => !t.current);
|
||||||
|
expect(victim).toBeDefined();
|
||||||
|
const del = await bundle.app.inject({ method: 'DELETE', url: `/api/v1/auth/tokens/${victim!.id}`, headers: auth() });
|
||||||
|
expect(del.statusCode).toBe(200);
|
||||||
|
const after = (await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/tokens', headers: auth() })).json() as TokensListResponse;
|
||||||
|
expect(after.tokens.find((t) => t.id === victim!.id)).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('404 sur un id inconnu', async () => {
|
||||||
|
const res = await bundle.app.inject({ method: 'DELETE', url: '/api/v1/auth/tokens/nope-xyz', headers: auth() });
|
||||||
|
expect(res.statusCode).toBe(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('409 LAST_TOKEN : refuse de révoquer le dernier token actif', async () => {
|
||||||
|
const list = (await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/tokens', headers: auth() })).json() as TokensListResponse;
|
||||||
|
expect(list.tokens).toHaveLength(1); // seul le token courant subsiste
|
||||||
|
const res = await bundle.app.inject({ method: 'DELETE', url: `/api/v1/auth/tokens/${list.tokens[0]!.id}`, headers: auth() });
|
||||||
|
expect(res.statusCode).toBe(409);
|
||||||
|
expect(res.json()).toMatchObject({ error: { code: 'LAST_TOKEN' } });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sans authentification → 401', async () => {
|
||||||
|
const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/tokens' });
|
||||||
|
expect(res.statusCode).toBe(401);
|
||||||
|
});
|
||||||
|
});
|
||||||
14
packages/server/test/fixtures/dialogs/ask2.raw
vendored
14
packages/server/test/fixtures/dialogs/ask2.raw
vendored
@@ -19,7 +19,7 @@
|
|||||||
[2GClaude[9GCode'll[17Gbe[20Gable[25Gto[28Gread,[34Gedit,[40Gand[44Gexecute[52Gfiles[58Ghere.
|
[2GClaude[9GCode'll[17Gbe[20Gable[25Gto[28Gread,[34Gedit,[40Gand[44Gexecute[52Gfiles[58Ghere.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[2G]8;id=zaxmda;https://code.claude.com/docs/en/security[38;2;153;153;153mSecurity guide[39m]8;;
|
[2G]8;id=zaxmda;https://code.claude.com/docs/en/security[38;2;153;153;153mSecurity guide[39m]8;;
|
||||||
|
|
||||||
|
|
||||||
@@ -321,13 +321,13 @@
|
|||||||
[2C[3A[?25h[?2026l[?2026h[?25l[2D[3B
|
[2C[3A[?25h[?2026l[?2026h[?25l[2D[3B
|
||||||
[2C[6A[38;2;255;183;101mSim[8G[38;2;255;153;51mrin[14G[38;2;153;153;153m(2s · [38;2;177;177;177mthinking with xhigh effort[38;2;153;153;153m)[39m
|
[2C[6A[38;2;255;183;101mSim[8G[38;2;255;153;51mrin[14G[38;2;153;153;153m(2s · [38;2;177;177;177mthinking with xhigh effort[38;2;153;153;153m)[39m
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[2C[3A[?25h[?2026l[?2026h[?25l[2D[3B
|
[2C[3A[?25h[?2026l[?2026h[?25l[2D[3B
|
||||||
[19C[6A[38;2;173;173;173mthinking with xhigh effort[39m
|
[19C[6A[38;2;173;173;173mthinking with xhigh effort[39m
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -343,7 +343,7 @@
|
|||||||
|
|
||||||
|
|
||||||
[2C[3A[?25h[?2026l[?2026h[?25l[2D[3B
|
[2C[3A[?25h[?2026l[?2026h[?25l[2D[3B
|
||||||
[19C[6A[38;2;161;161;161mthinking with xhigh effort[39m
|
[19C[6A[38;2;161;161;161mthinking with xhigh effort[39m
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -359,7 +359,7 @@
|
|||||||
|
|
||||||
|
|
||||||
[2C[3A[?25h[?2026l[?2026h[?25l[2D[3B
|
[2C[3A[?25h[?2026l[?2026h[?25l[2D[3B
|
||||||
[21C[6A[38;2;153;153;153m57[34Gthinking with xhigh effort[39m
|
[21C[6A[38;2;153;153;153m57[34Gthinking with xhigh effort[39m
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -566,7 +566,7 @@
|
|||||||
|
|
||||||
[3G[38;2;153;153;153mesc[7Gto[10Ginterrupt[21G[38;2;255;204;0mYou've[28Gused[33G96%[37Gof[40Gyour[45Gsession[53Glimit[59G·[61Gresets[68G7pm[72G(America/Lima)[87G·[89G/usage-credits[104Gto[107Grequest[115Gmore[39m
|
[3G[38;2;153;153;153mesc[7Gto[10Ginterrupt[21G[38;2;255;204;0mYou've[28Gused[33G96%[37Gof[40Gyour[45Gsession[53Glimit[59G·[61Gresets[68G7pm[72G(America/Lima)[87G·[89G/usage-credits[104Gto[107Grequest[115Gmore[39m
|
||||||
|
|
||||||
[2C[3A[?25h[?2026l[?2026h[?25l[2D[3B
|
[2C[3A[?25h[?2026l[?2026h[?25l[2D[3B
|
||||||
[4C[6A[38;2;255;153;51mn[8G[38;2;255;183;101mn[39m
|
[4C[6A[38;2;255;153;51mn[8G[38;2;255;183;101mn[39m
|
||||||
|
|
||||||
|
|
||||||
@@ -19,7 +19,7 @@
|
|||||||
[2GClaude[9GCode'll[17Gbe[20Gable[25Gto[28Gread,[34Gedit,[40Gand[44Gexecute[52Gfiles[58Ghere.
|
[2GClaude[9GCode'll[17Gbe[20Gable[25Gto[28Gread,[34Gedit,[40Gand[44Gexecute[52Gfiles[58Ghere.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[2G]8;id=zaxmda;https://code.claude.com/docs/en/security[38;2;153;153;153mSecurity guide[39m]8;;
|
[2G]8;id=zaxmda;https://code.claude.com/docs/en/security[38;2;153;153;153mSecurity guide[39m]8;;
|
||||||
|
|
||||||
|
|
||||||
@@ -475,7 +475,7 @@
|
|||||||
[14C[6A[38;2;153;153;153m4[35Gthought for 1s)[39m[K
|
[14C[6A[38;2;153;153;153m4[35Gthought for 1s)[39m[K
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,7 @@
|
|||||||
[2GClaude[9GCode'll[17Gbe[20Gable[25Gto[28Gread,[34Gedit,[40Gand[44Gexecute[52Gfiles[58Ghere.
|
[2GClaude[9GCode'll[17Gbe[20Gable[25Gto[28Gread,[34Gedit,[40Gand[44Gexecute[52Gfiles[58Ghere.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[2G]8;id=zaxmda;https://code.claude.com/docs/en/security[38;2;153;153;153mSecurity guide[39m]8;;
|
[2G]8;id=zaxmda;https://code.claude.com/docs/en/security[38;2;153;153;153mSecurity guide[39m]8;;
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,7 @@
|
|||||||
[2GClaude[9GCode'll[17Gbe[20Gable[25Gto[28Gread,[34Gedit,[40Gand[44Gexecute[52Gfiles[58Ghere.
|
[2GClaude[9GCode'll[17Gbe[20Gable[25Gto[28Gread,[34Gedit,[40Gand[44Gexecute[52Gfiles[58Ghere.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[2G]8;id=zaxmda;https://code.claude.com/docs/en/security[38;2;153;153;153mSecurity guide[39m]8;;
|
[2G]8;id=zaxmda;https://code.claude.com/docs/en/security[38;2;153;153;153mSecurity guide[39m]8;;
|
||||||
|
|
||||||
|
|
||||||
@@ -218,13 +218,13 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
[2C[3A[?25h[?2026l[?2026h[?25l[2D[3B
|
[2C[3A[?25h[?2026l[?2026h[?25l[2D[3B
|
||||||
[6A[38;2;255;153;51m✻[39m
|
[6A[38;2;255;153;51m✻[39m
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[2C[3A[?25h[?2026l[?2026h[?25l[2D[3B
|
[2C[3A[?25h[?2026l[?2026h[?25l[2D[3B
|
||||||
[6A[38;2;255;153;51m✽[39m
|
[6A[38;2;255;153;51m✽[39m
|
||||||
@@ -242,7 +242,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
[2C[3A[?25h[?2026l[?2026h[?25l[2D[3B
|
[2C[3A[?25h[?2026l[?2026h[?25l[2D[3B
|
||||||
[12C[6A[38;2;153;153;153m(1s · thinking with xhigh effort)[39m
|
[12C[6A[38;2;153;153;153m(1s · thinking with xhigh effort)[39m
|
||||||
|
|
||||||
|
|
||||||
@@ -251,7 +251,7 @@
|
|||||||
|
|
||||||
|
|
||||||
[2C[3A[?25h[?2026l[?2026h[?25l[2D[3B
|
[2C[3A[?25h[?2026l[?2026h[?25l[2D[3B
|
||||||
[5C[6A[38;2;255;183;101mo[9G[38;2;255;153;51mn[14G[38;2;153;153;153m2[19G[38;2;169;169;169mthinking with xhigh effort[39m
|
[5C[6A[38;2;255;183;101mo[9G[38;2;255;153;51mn[14G[38;2;153;153;153m2[19G[38;2;169;169;169mthinking with xhigh effort[39m
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -416,7 +416,7 @@
|
|||||||
[2B[38;2;153;153;153m❯ [39m[K
|
[2B[38;2;153;153;153m❯ [39m[K
|
||||||
|
|
||||||
[38;2;136;136;136m────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[39m
|
[38;2;136;136;136m────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[39m
|
||||||
|
|
||||||
[3G[38;2;153;153;153mesc[7Gto[10Ginterrupt[21G[38;2;255;204;0mYou've[28Gused[33G91%[37Gof[40Gyour[45Gsession[53Glimit[59G·[61Gresets[68G7pm[72G(America/Lima)[87G·[89G/usage-credits[104Gto[107Grequest[115Gmore[39m
|
[3G[38;2;153;153;153mesc[7Gto[10Ginterrupt[21G[38;2;255;204;0mYou've[28Gused[33G91%[37Gof[40Gyour[45Gsession[53Glimit[59G·[61Gresets[68G7pm[72G(America/Lima)[87G·[89G/usage-credits[104Gto[107Grequest[115Gmore[39m
|
||||||
|
|
||||||
[2C[3A[?25h[?2026l[?2026h[?25l[2D[3B
|
[2C[3A[?25h[?2026l[?2026h[?25l[2D[3B
|
||||||
@@ -430,16 +430,16 @@
|
|||||||
[2C[3A[?25h[?2026l[?2026h[?25l[2D[3B
|
[2C[3A[?25h[?2026l[?2026h[?25l[2D[3B
|
||||||
[6A[38;2;255;153;51m*[10Gng[39m
|
[6A[38;2;255;153;51m*[10Gng[39m
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[2C[3A[?25h[?2026l[?2026h[?25l[2D[3B
|
[2C[3A[?25h[?2026l[?2026h[?25l[2D[3B
|
||||||
[11C[6A[38;2;255;153;51m…[39m
|
[11C[6A[38;2;255;153;51m…[39m
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,7 @@
|
|||||||
[2GClaude[9GCode'll[17Gbe[20Gable[25Gto[28Gread,[34Gedit,[40Gand[44Gexecute[52Gfiles[58Ghere.
|
[2GClaude[9GCode'll[17Gbe[20Gable[25Gto[28Gread,[34Gedit,[40Gand[44Gexecute[52Gfiles[58Ghere.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[2G]8;id=zaxmda;https://code.claude.com/docs/en/security[38;2;153;153;153mSecurity guide[39m]8;;
|
[2G]8;id=zaxmda;https://code.claude.com/docs/en/security[38;2;153;153;153mSecurity guide[39m]8;;
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ function writeJsonl(projectsDir: string, cwd: string, sid: string, lines: object
|
|||||||
describe('munge', () => {
|
describe('munge', () => {
|
||||||
it('reproduit le nom de dossier ~/.claude/projects', () => {
|
it('reproduit le nom de dossier ~/.claude/projects', () => {
|
||||||
expect(munge('/home/x/My Project!')).toBe('-home-x-My-Project-');
|
expect(munge('/home/x/My Project!')).toBe('-home-x-My-Project-');
|
||||||
expect(munge('/home/johan/WebstormProjects/arboretum')).toBe('-home-johan-WebstormProjects-arboretum');
|
expect(munge('/home/user/projects/demo')).toBe('-home-user-projects-demo');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
104
packages/server/test/repo-scanner.test.ts
Normal file
104
packages/server/test/repo-scanner.test.ts
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
import { describe, expect, it, afterEach } from 'vitest';
|
||||||
|
import { mkdtempSync, mkdirSync, rmSync, symlinkSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { scanForRepos } from '../src/core/repo-scanner.js';
|
||||||
|
|
||||||
|
const dirs: string[] = [];
|
||||||
|
afterEach(() => {
|
||||||
|
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
function tmpRoot(): string {
|
||||||
|
const d = mkdtempSync(join(tmpdir(), 'arb-scan-'));
|
||||||
|
dirs.push(d);
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
// un « repo » pour le scanner = un dossier contenant `.git` (le scanner ne lance jamais git).
|
||||||
|
function makeRepo(...segs: string[]): void {
|
||||||
|
mkdirSync(join(...segs, '.git'), { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
const limits = { maxDepth: 6, maxRepos: 2000 };
|
||||||
|
|
||||||
|
describe('scanForRepos', () => {
|
||||||
|
it('trouve un repo simple', async () => {
|
||||||
|
const root = tmpRoot();
|
||||||
|
makeRepo(root, 'proj');
|
||||||
|
const { paths, truncated } = await scanForRepos([root], limits);
|
||||||
|
expect(paths).toEqual([join(root, 'proj')]);
|
||||||
|
expect(truncated).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ne descend pas dans un repo trouvé (sous-repo ignoré)', async () => {
|
||||||
|
const root = tmpRoot();
|
||||||
|
makeRepo(root, 'a');
|
||||||
|
makeRepo(root, 'a', 'sub'); // imbriqué : doit être ignoré
|
||||||
|
const { paths } = await scanForRepos([root], limits);
|
||||||
|
expect(paths).toEqual([join(root, 'a')]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('descend dans une racine qui est elle-même un repo (workspace + sous-repos)', async () => {
|
||||||
|
const root = tmpRoot();
|
||||||
|
makeRepo(root); // la racine fournie contient elle-même un .git (cas WebstormProjects)
|
||||||
|
makeRepo(root, 'a');
|
||||||
|
makeRepo(root, 'b');
|
||||||
|
const { paths } = await scanForRepos([root], limits);
|
||||||
|
// la racine ET ses dépôts internes sont découverts (la racine n'arrête pas le scan)
|
||||||
|
expect([...paths].sort()).toEqual([root, join(root, 'a'), join(root, 'b')].sort());
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignore node_modules et les dotdirs', async () => {
|
||||||
|
const root = tmpRoot();
|
||||||
|
makeRepo(root, 'node_modules', 'pkg');
|
||||||
|
makeRepo(root, '.hidden', 'x');
|
||||||
|
makeRepo(root, 'real');
|
||||||
|
const { paths } = await scanForRepos([root], limits);
|
||||||
|
expect(paths).toEqual([join(root, 'real')]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('respecte maxDepth', async () => {
|
||||||
|
const root = tmpRoot();
|
||||||
|
makeRepo(root, 'a', 'b', 'c', 'deep'); // repo à profondeur 4
|
||||||
|
const shallow = await scanForRepos([root], { maxDepth: 2, maxRepos: 2000 });
|
||||||
|
expect(shallow.paths).toEqual([]);
|
||||||
|
const deep = await scanForRepos([root], { maxDepth: 4, maxRepos: 2000 });
|
||||||
|
expect(deep.paths).toEqual([join(root, 'a', 'b', 'c', 'deep')]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ne suit pas les symlinks (cycle terminé, pas de doublon)', async () => {
|
||||||
|
const root = tmpRoot();
|
||||||
|
makeRepo(root, 'proj');
|
||||||
|
try {
|
||||||
|
symlinkSync(root, join(root, 'loop')); // cycle vers la racine
|
||||||
|
} catch {
|
||||||
|
/* symlink non autorisé sous certains CI : le test reste valide sans le lien */
|
||||||
|
}
|
||||||
|
const { paths } = await scanForRepos([root], limits);
|
||||||
|
expect(paths).toEqual([join(root, 'proj')]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('tronque à maxRepos', async () => {
|
||||||
|
const root = tmpRoot();
|
||||||
|
makeRepo(root, 'r1');
|
||||||
|
makeRepo(root, 'r2');
|
||||||
|
makeRepo(root, 'r3');
|
||||||
|
const { paths, truncated } = await scanForRepos([root], { maxDepth: 6, maxRepos: 2 });
|
||||||
|
expect(truncated).toBe(true);
|
||||||
|
expect(paths.length).toBeLessThanOrEqual(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignore une racine inexistante sans lever', async () => {
|
||||||
|
const { paths } = await scanForRepos(['/nope/does/not/exist'], limits);
|
||||||
|
expect(paths).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('scanne plusieurs racines', async () => {
|
||||||
|
const r1 = tmpRoot();
|
||||||
|
const r2 = tmpRoot();
|
||||||
|
makeRepo(r1, 'one');
|
||||||
|
makeRepo(r2, 'two');
|
||||||
|
const { paths } = await scanForRepos([r1, r2], limits);
|
||||||
|
expect([...paths].sort()).toEqual([join(r1, 'one'), join(r2, 'two')].sort());
|
||||||
|
});
|
||||||
|
});
|
||||||
37
packages/server/test/secret-box.test.ts
Normal file
37
packages/server/test/secret-box.test.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { randomBytes } from 'node:crypto';
|
||||||
|
import { SecretBox } from '../src/core/secret-box.js';
|
||||||
|
|
||||||
|
const box = (): SecretBox => new SecretBox(randomBytes(32));
|
||||||
|
|
||||||
|
describe('SecretBox', () => {
|
||||||
|
it('chiffre puis déchiffre (round-trip)', () => {
|
||||||
|
const b = box();
|
||||||
|
const secret = 'deadbeef'.repeat(8);
|
||||||
|
const enc = b.encrypt(secret);
|
||||||
|
expect(enc.startsWith('v1:')).toBe(true);
|
||||||
|
expect(enc).not.toContain(secret); // le clair n'apparaît pas
|
||||||
|
expect(b.decrypt(enc)).toBe(secret);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('produit un chiffré différent à chaque fois (IV aléatoire)', () => {
|
||||||
|
const b = box();
|
||||||
|
expect(b.encrypt('x')).not.toBe(b.encrypt('x'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('retourne tel quel une valeur en clair (legacy) et la détecte', () => {
|
||||||
|
const b = box();
|
||||||
|
expect(b.isEncrypted('plain-secret')).toBe(false);
|
||||||
|
expect(b.decrypt('plain-secret')).toBe('plain-secret');
|
||||||
|
expect(b.isEncrypted(b.encrypt('x'))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('échoue si la clé ne correspond pas (GCM authentifié)', () => {
|
||||||
|
const enc = box().encrypt('secret');
|
||||||
|
expect(() => box().decrypt(enc)).toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('échoue sur un format chiffré corrompu', () => {
|
||||||
|
expect(() => box().decrypt('v1:zzz')).toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
139
packages/server/test/settings-routes.test.ts
Normal file
139
packages/server/test/settings-routes.test.ts
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
// Routes Réglages : GET expose la config non sensible (jamais les secrets), PATCH n'écrit que
|
||||||
|
// l'allow-list (découverte des dépôts) et ignore toute clé hors allow-list.
|
||||||
|
import { mkdtempSync, rmSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { buildApp, type AppBundle } from '../src/app.js';
|
||||||
|
import { getSetting, openDb, type Db } from '../src/db/index.js';
|
||||||
|
import type { Config } from '../src/config.js';
|
||||||
|
import type { SettingsResponse } from '@arboretum/shared';
|
||||||
|
|
||||||
|
vi.mock('node:child_process', () => ({ execFileSync: () => '/usr/bin/claude\n' }));
|
||||||
|
vi.mock('@homebridge/node-pty-prebuilt-multiarch', () => {
|
||||||
|
class FakePty {
|
||||||
|
pid = 424242;
|
||||||
|
write = vi.fn();
|
||||||
|
resize = vi.fn();
|
||||||
|
pause = vi.fn();
|
||||||
|
resume = vi.fn();
|
||||||
|
kill = vi.fn();
|
||||||
|
onData(): { dispose: () => void } {
|
||||||
|
return { dispose: () => {} };
|
||||||
|
}
|
||||||
|
onExit(): { dispose: () => void } {
|
||||||
|
return { dispose: () => {} };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { default: { spawn: (): FakePty => new FakePty() } };
|
||||||
|
});
|
||||||
|
|
||||||
|
process.env.ARBORETUM_LOG = 'silent';
|
||||||
|
|
||||||
|
let dir: string;
|
||||||
|
let bundle: AppBundle;
|
||||||
|
let db: Db;
|
||||||
|
let token: string;
|
||||||
|
|
||||||
|
const auth = (): { authorization: string } => ({ authorization: `Bearer ${token}` });
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
dir = mkdtempSync(join(tmpdir(), 'arboretum-settings-'));
|
||||||
|
const dbPath = join(dir, 'settings.db');
|
||||||
|
db = openDb(dbPath);
|
||||||
|
const config: Config = {
|
||||||
|
port: 9999,
|
||||||
|
bind: '127.0.0.1',
|
||||||
|
dbPath,
|
||||||
|
dataDir: dir,
|
||||||
|
allowedOrigins: ['https://host.tailnet.ts.net'],
|
||||||
|
printToken: false,
|
||||||
|
claudeProjectsDir: join(dir, 'claude', 'projects'),
|
||||||
|
claudeSessionsDir: join(dir, 'claude', 'sessions'),
|
||||||
|
vapidContact: 'mailto:test@localhost',
|
||||||
|
};
|
||||||
|
bundle = buildApp(config, db, '1.2.3-test');
|
||||||
|
const t = bundle.auth.ensureBootstrapToken();
|
||||||
|
if (!t) throw new Error('bootstrap token attendu');
|
||||||
|
token = t;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await bundle.app.close();
|
||||||
|
db.close();
|
||||||
|
rmSync(dir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /api/v1/settings', () => {
|
||||||
|
it('renvoie la config serveur non sensible et aucune racine de scan par défaut', async () => {
|
||||||
|
const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/settings', headers: auth() });
|
||||||
|
expect(res.statusCode).toBe(200);
|
||||||
|
const body = res.json() as SettingsResponse;
|
||||||
|
expect(body.server.version).toBe('1.2.3-test');
|
||||||
|
expect(body.server.port).toBe(9999);
|
||||||
|
expect(body.server.bind).toBe('127.0.0.1');
|
||||||
|
expect(body.server.allowedOrigins).toEqual(['https://host.tailnet.ts.net']);
|
||||||
|
expect(body.server.vapidPublicKey).toBeTruthy(); // clé publique = sûre à exposer
|
||||||
|
// défauts de découverte : AUCUNE racine (clean install → pas de scan) + intervalle 5 min
|
||||||
|
expect(body.settings.scanRoots).toEqual([]);
|
||||||
|
expect(body.settings.scanIntervalMin).toBe(5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('n’expose AUCUN secret (server_secret, clé privée VAPID)', async () => {
|
||||||
|
const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/settings', headers: auth() });
|
||||||
|
const raw = res.body;
|
||||||
|
const secret = getSetting(db, 'server_secret');
|
||||||
|
const vapidPrivate = getSetting(db, 'vapid_private');
|
||||||
|
expect(secret).toBeTruthy();
|
||||||
|
expect(raw).not.toContain(secret as string);
|
||||||
|
expect(raw).not.toContain(vapidPrivate as string);
|
||||||
|
expect(raw).not.toMatch(/server_secret|vapid_private|privateKey/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('PATCH /api/v1/settings — sécurité', () => {
|
||||||
|
it('ignore toute clé hors allow-list (ne touche pas aux secrets)', async () => {
|
||||||
|
const before = getSetting(db, 'server_secret');
|
||||||
|
await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { server_secret: 'pwned', vapid_private: 'pwned' } });
|
||||||
|
expect(getSetting(db, 'server_secret')).toBe(before); // inchangé
|
||||||
|
expect(getSetting(db, 'vapid_private')).not.toBe('pwned');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sans authentification → 401', async () => {
|
||||||
|
const res = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', payload: { scanRoots: ['/home/u/work'] } });
|
||||||
|
expect(res.statusCode).toBe(401);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('PATCH /api/v1/settings — découverte des dépôts', () => {
|
||||||
|
it('enregistre des scanRoots et un intervalle valides et les renvoie', async () => {
|
||||||
|
const res = await bundle.app.inject({
|
||||||
|
method: 'PATCH',
|
||||||
|
url: '/api/v1/settings',
|
||||||
|
headers: auth(),
|
||||||
|
payload: { scanRoots: ['/home/u/work', '/srv/code'], scanIntervalMin: 10 },
|
||||||
|
});
|
||||||
|
expect(res.statusCode).toBe(200);
|
||||||
|
const body = res.json() as SettingsResponse;
|
||||||
|
expect(body.settings.scanRoots).toEqual(['/home/u/work', '/srv/code']);
|
||||||
|
expect(body.settings.scanIntervalMin).toBe(10);
|
||||||
|
// persisté
|
||||||
|
const get = await bundle.app.inject({ method: 'GET', url: '/api/v1/settings', headers: auth() });
|
||||||
|
expect((get.json() as SettingsResponse).settings.scanRoots).toEqual(['/home/u/work', '/srv/code']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejette des racines non absolues, "/", avec ".." ou en surnombre (400)', async () => {
|
||||||
|
const bads: unknown[] = [['relative/path'], ['/'], ['/a/../b'], Array.from({ length: 17 }, (_, i) => `/r${i}`)];
|
||||||
|
for (const scanRoots of bads) {
|
||||||
|
const res = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { scanRoots } });
|
||||||
|
expect(res.statusCode).toBe(400);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejette un intervalle hors borne (400)', async () => {
|
||||||
|
const res = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { scanIntervalMin: 5000 } });
|
||||||
|
expect(res.statusCode).toBe(400);
|
||||||
|
const neg = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { scanIntervalMin: -1 } });
|
||||||
|
expect(neg.statusCode).toBe(400);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';
|
import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';
|
||||||
import { execFileSync } from 'node:child_process';
|
import { execFileSync } from 'node:child_process';
|
||||||
import { mkdtempSync, writeFileSync, rmSync, existsSync } from 'node:fs';
|
import { mkdtempSync, mkdirSync, writeFileSync, rmSync, existsSync } from 'node:fs';
|
||||||
import { tmpdir } from 'node:os';
|
import { tmpdir } from 'node:os';
|
||||||
import { join, basename, dirname, resolve } from 'node:path';
|
import { join, basename, dirname, resolve } from 'node:path';
|
||||||
import type { WorktreeSummary } from '@arboretum/shared';
|
import type { RepoSummary, WorktreeSummary } from '@arboretum/shared';
|
||||||
import { WorktreeManager } from '../src/core/worktree-manager.js';
|
import { WorktreeManager } from '../src/core/worktree-manager.js';
|
||||||
import { PtyManager } from '../src/core/pty-manager.js';
|
import { PtyManager } from '../src/core/pty-manager.js';
|
||||||
import { DiscoveryService } from '../src/core/discovery-service.js';
|
import { DiscoveryService } from '../src/core/discovery-service.js';
|
||||||
@@ -34,9 +34,7 @@ afterEach(() => {
|
|||||||
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
|
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
function makeTmpRepo(): string {
|
function gitInit(dir: string): void {
|
||||||
const dir = mkdtempSync(join(tmpdir(), 'arb-wtm-'));
|
|
||||||
dirs.push(dir);
|
|
||||||
const run = (...args: string[]): void => void execFileSync('git', args, { cwd: dir, stdio: 'pipe' });
|
const run = (...args: string[]): void => void execFileSync('git', args, { cwd: dir, stdio: 'pipe' });
|
||||||
run('init', '-b', 'main');
|
run('init', '-b', 'main');
|
||||||
run('config', 'user.email', 'test@arboretum.dev');
|
run('config', 'user.email', 'test@arboretum.dev');
|
||||||
@@ -44,9 +42,21 @@ function makeTmpRepo(): string {
|
|||||||
writeFileSync(join(dir, 'README.md'), '# test\n');
|
writeFileSync(join(dir, 'README.md'), '# test\n');
|
||||||
run('add', '-A');
|
run('add', '-A');
|
||||||
run('commit', '-m', 'init');
|
run('commit', '-m', 'init');
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeTmpRepo(): string {
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'arb-wtm-'));
|
||||||
|
dirs.push(dir);
|
||||||
|
gitInit(dir);
|
||||||
return dir;
|
return dir;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Crée un vrai repo git à un chemin donné (sous une racine de scan contrôlée). */
|
||||||
|
function makeRepoAt(path: string): void {
|
||||||
|
mkdirSync(path, { recursive: true });
|
||||||
|
gitInit(path);
|
||||||
|
}
|
||||||
|
|
||||||
describe('WorktreeManager', () => {
|
describe('WorktreeManager', () => {
|
||||||
let db: Db;
|
let db: Db;
|
||||||
let pty: PtyManager;
|
let pty: PtyManager;
|
||||||
@@ -144,4 +154,79 @@ describe('WorktreeManager', () => {
|
|||||||
pty.spawn({ cwd: wtPath, command: 'bash' });
|
pty.spawn({ cwd: wtPath, command: 'bash' });
|
||||||
await expect(wt.deleteWorktree(r.id, wtPath, false)).rejects.toMatchObject({ statusCode: 409, code: 'SESSION_LIVE_IN_WORKTREE' });
|
await expect(wt.deleteWorktree(r.id, wtPath, false)).rejects.toMatchObject({ statusCode: 409, code: 'SESSION_LIVE_IN_WORKTREE' });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('addRepo renvoie hidden:false ; updateRepo({hidden}) bascule et émet repo_update', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
const r = await wt.addRepo({ path: repo });
|
||||||
|
expect(r.hidden).toBe(false);
|
||||||
|
const updates: RepoSummary[] = [];
|
||||||
|
wt.on('repo_update', (s) => updates.push(s));
|
||||||
|
const u = await wt.updateRepo(r.id, { hidden: true });
|
||||||
|
expect(u.hidden).toBe(true);
|
||||||
|
expect(updates.some((s) => s.id === r.id && s.hidden)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('listAllWorktrees exclut les repos masqués', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
const r = await wt.addRepo({ path: repo });
|
||||||
|
expect((await wt.listAllWorktrees()).length).toBeGreaterThan(0); // main worktree présent
|
||||||
|
await wt.updateRepo(r.id, { hidden: true });
|
||||||
|
expect(await wt.listAllWorktrees()).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('discoverRepos : auto-ajoute les nouveaux, idempotent, masqué non ressuscité, supprimé re-découvrable', async () => {
|
||||||
|
const root = mkdtempSync(join(tmpdir(), 'arb-scan-'));
|
||||||
|
dirs.push(root);
|
||||||
|
makeRepoAt(join(root, 'a'));
|
||||||
|
makeRepoAt(join(root, 'b'));
|
||||||
|
|
||||||
|
const updates: RepoSummary[] = [];
|
||||||
|
wt.on('repo_update', (s) => updates.push(s));
|
||||||
|
|
||||||
|
const res = await wt.discoverRepos({ roots: [root], maxDepth: 2 });
|
||||||
|
expect(res.added).toBe(2);
|
||||||
|
expect(res.scanned).toBe(2);
|
||||||
|
expect(await wt.listRepos()).toHaveLength(2);
|
||||||
|
expect(updates).toHaveLength(2); // un repo_update par nouveau
|
||||||
|
|
||||||
|
// re-scan : idempotent (aucun ajout, aucune émission)
|
||||||
|
updates.length = 0;
|
||||||
|
const res2 = await wt.discoverRepos({ roots: [root], maxDepth: 2 });
|
||||||
|
expect(res2.added).toBe(0);
|
||||||
|
expect(updates).toHaveLength(0);
|
||||||
|
expect(await wt.listRepos()).toHaveLength(2);
|
||||||
|
|
||||||
|
// masquer 'a' puis re-scan : reste masqué, jamais ré-ajouté (invariant central)
|
||||||
|
const repoA = (await wt.listRepos()).find((r) => resolve(r.path) === resolve(join(root, 'a')));
|
||||||
|
await wt.updateRepo(repoA!.id, { hidden: true });
|
||||||
|
updates.length = 0;
|
||||||
|
const res3 = await wt.discoverRepos({ roots: [root], maxDepth: 2 });
|
||||||
|
expect(res3.added).toBe(0);
|
||||||
|
expect((await wt.listRepos()).find((r) => r.id === repoA!.id)?.hidden).toBe(true);
|
||||||
|
|
||||||
|
// supprimer 'b' puis re-scan : re-découvert (volontaire)
|
||||||
|
const repoB = (await wt.listRepos()).find((r) => resolve(r.path) === resolve(join(root, 'b')));
|
||||||
|
wt.removeRepo(repoB!.id);
|
||||||
|
expect(await wt.listRepos()).toHaveLength(1);
|
||||||
|
const res4 = await wt.discoverRepos({ roots: [root], maxDepth: 2 });
|
||||||
|
expect(res4.added).toBe(1);
|
||||||
|
expect(await wt.listRepos()).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('discoverRepos : repo disparu du disque conservé en DB (valid=false), non re-trouvé', async () => {
|
||||||
|
const root = mkdtempSync(join(tmpdir(), 'arb-scan-'));
|
||||||
|
dirs.push(root);
|
||||||
|
makeRepoAt(join(root, 'gone'));
|
||||||
|
await wt.discoverRepos({ roots: [root], maxDepth: 2 });
|
||||||
|
expect(await wt.listRepos()).toHaveLength(1);
|
||||||
|
|
||||||
|
rmSync(join(root, 'gone'), { recursive: true, force: true }); // disparaît du disque
|
||||||
|
const res = await wt.discoverRepos({ roots: [root], maxDepth: 2 });
|
||||||
|
expect(res.added).toBe(0); // plus trouvé par le scan
|
||||||
|
const repos = await wt.listRepos();
|
||||||
|
expect(repos).toHaveLength(1); // mais la ligne est conservée (pas de suppression auto)
|
||||||
|
expect(repos[0].valid).toBe(false);
|
||||||
|
// robustesse : un repo dont le chemin a disparu ne fait pas planter /worktrees (git échoue → [])
|
||||||
|
await expect(wt.listAllWorktrees()).resolves.toEqual([]);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -14,10 +14,34 @@ export interface LoginResponse {
|
|||||||
}
|
}
|
||||||
export interface MeResponse {
|
export interface MeResponse {
|
||||||
ok: true;
|
ok: true;
|
||||||
|
/** id du token de la session courante — sert à marquer « courant » dans la liste des tokens. */
|
||||||
|
tokenId: string;
|
||||||
tokenLabel: string;
|
tokenLabel: string;
|
||||||
serverVersion: string;
|
serverVersion: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- Gestion des tokens d'accès (onglet Réglages) ----
|
||||||
|
export interface TokenInfo {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
createdAt: string;
|
||||||
|
lastUsedAt: string | null;
|
||||||
|
/** true pour le token de la session courante. */
|
||||||
|
current: boolean;
|
||||||
|
}
|
||||||
|
export interface TokensListResponse {
|
||||||
|
tokens: TokenInfo[];
|
||||||
|
}
|
||||||
|
export interface CreateTokenRequest {
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
export interface CreateTokenResponse {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
/** valeur en clair — affichée une seule fois, jamais re-récupérable. */
|
||||||
|
token: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface CreateSessionRequest {
|
export interface CreateSessionRequest {
|
||||||
cwd: string;
|
cwd: string;
|
||||||
/** binaire à lancer — défaut "claude" ; "bash" sert aux tests d'acceptation sans quota */
|
/** binaire à lancer — défaut "claude" ; "bash" sert aux tests d'acceptation sans quota */
|
||||||
@@ -52,6 +76,19 @@ export interface UpdateRepoRequest {
|
|||||||
label?: string;
|
label?: string;
|
||||||
postCreateHooks?: PostCreateHook[];
|
postCreateHooks?: PostCreateHook[];
|
||||||
preTrust?: boolean;
|
preTrust?: boolean;
|
||||||
|
/** true = masquer le repo (exclu du dashboard, conservé en DB) ; false = ré-afficher. */
|
||||||
|
hidden?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Résultat d'un scan de découverte (POST /api/v1/repos/discover). */
|
||||||
|
export interface DiscoverReposResponse {
|
||||||
|
/** dossiers-repos trouvés sur disque. */
|
||||||
|
scanned: number;
|
||||||
|
/** repos réellement insérés (nouveaux, non déjà enregistrés). */
|
||||||
|
added: number;
|
||||||
|
durationMs: number;
|
||||||
|
/** true si la limite (maxRepos / timeout) a été atteinte avant la fin du scan. */
|
||||||
|
truncated: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface WorktreesListResponse {
|
export interface WorktreesListResponse {
|
||||||
@@ -146,3 +183,72 @@ export interface PushSubscribeRequest {
|
|||||||
export interface PushUnsubscribeRequest {
|
export interface PushUnsubscribeRequest {
|
||||||
endpoint: string;
|
endpoint: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- Réglages & info serveur (onglet Réglages) ----
|
||||||
|
/** Config runtime non sensible du daemon — lecture seule (changée via flags CLI + redémarrage). */
|
||||||
|
export interface ServerInfo {
|
||||||
|
version: string;
|
||||||
|
port: number;
|
||||||
|
bind: string;
|
||||||
|
allowedOrigins: string[];
|
||||||
|
dataDir: string;
|
||||||
|
/** clé publique VAPID (sûre à exposer) ; null si push indisponible. */
|
||||||
|
vapidPublicKey: string | null;
|
||||||
|
vapidContact: string;
|
||||||
|
}
|
||||||
|
export interface SettingsResponse {
|
||||||
|
/** réglages modifiables à chaud (allow-list serveur — jamais les secrets). */
|
||||||
|
settings: {
|
||||||
|
/** racines absolues scannées pour la découverte auto des repos (défaut : aucune → pas de scan). */
|
||||||
|
scanRoots: string[];
|
||||||
|
/** intervalle du re-scan périodique en minutes ; 0 = périodique désactivé. */
|
||||||
|
scanIntervalMin: number;
|
||||||
|
};
|
||||||
|
server: ServerInfo;
|
||||||
|
}
|
||||||
|
export interface UpdateSettingsRequest {
|
||||||
|
/** racines absolues à scanner (chemins normalisés, ≤ 16) ; remplace la liste. */
|
||||||
|
scanRoots?: string[];
|
||||||
|
/** intervalle du re-scan périodique en minutes (0–1440 ; 0 désactive). */
|
||||||
|
scanIntervalMin?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Journal d'audit (conformité entreprise) ----
|
||||||
|
export interface AuditLogEntry {
|
||||||
|
id: string;
|
||||||
|
/** horodatage ISO 8601 */
|
||||||
|
ts: string;
|
||||||
|
/** tokenId de l'acteur, 'system' (auto) ou 'anonymous' (avant auth) */
|
||||||
|
actor: string;
|
||||||
|
/** verbe.objet, ex. 'token.create', 'settings.update' */
|
||||||
|
action: string;
|
||||||
|
resourceId: string | null;
|
||||||
|
/** métadonnées non sensibles (jamais de secret) */
|
||||||
|
details: unknown;
|
||||||
|
result: string;
|
||||||
|
}
|
||||||
|
export interface AuditLogsResponse {
|
||||||
|
entries: AuditLogEntry[];
|
||||||
|
/** curseur de pagination (ts à passer en `before`) ; null si fin de liste. */
|
||||||
|
nextBefore: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- RGPD : export / suppression des données liées au token authentifié ----
|
||||||
|
export interface DataExportResponse {
|
||||||
|
exportedAt: string;
|
||||||
|
tokens: Array<{ id: string; label: string; createdAt: string; lastUsedAt: string | null; current: boolean }>;
|
||||||
|
pushSubscriptions: Array<{ endpoint: string; userAgent: string | null; createdAt: string; lastOkAt: string | null }>;
|
||||||
|
sessions: Array<{ id: string; cwd: string; command: string; title: string | null; createdAt: string; endedAt: string | null; exitCode: number | null }>;
|
||||||
|
settings: { scanRoots: string[]; scanIntervalMin: number };
|
||||||
|
}
|
||||||
|
export interface DeleteMyDataRequest {
|
||||||
|
/** code de confirmation renvoyé par un premier appel sans `confirm` ; doit être renvoyé pour exécuter. */
|
||||||
|
confirm?: string;
|
||||||
|
}
|
||||||
|
export interface DeleteMyDataResponse {
|
||||||
|
/** 'pending' = confirmation requise (renvoie `confirm`) ; 'done' = suppression effectuée. */
|
||||||
|
status: 'pending' | 'done';
|
||||||
|
confirm?: string;
|
||||||
|
/** récapitulatif de ce qui sera/a été supprimé. */
|
||||||
|
summary: { pushSubscriptions: number; tokenRevoked: boolean };
|
||||||
|
}
|
||||||
|
|||||||
@@ -136,6 +136,8 @@ export interface RepoSummary {
|
|||||||
createdAt: string;
|
createdAt: string;
|
||||||
/** false si le chemin n'est plus un repo git accessible. */
|
/** false si le chemin n'est plus un repo git accessible. */
|
||||||
valid: boolean;
|
valid: boolean;
|
||||||
|
/** true = masqué du dashboard (conservé en DB → non ré-ajouté au re-scan). */
|
||||||
|
hidden: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface WorktreeGitStatus {
|
export interface WorktreeGitStatus {
|
||||||
|
|||||||
@@ -10,6 +10,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@arboretum/shared": "*",
|
"@arboretum/shared": "*",
|
||||||
|
"@lucide/vue": "^1.21.0",
|
||||||
"@xterm/addon-fit": "^0.11.0",
|
"@xterm/addon-fit": "^0.11.0",
|
||||||
"@xterm/addon-webgl": "^0.19.0",
|
"@xterm/addon-webgl": "^0.19.0",
|
||||||
"@xterm/xterm": "^6.0.0",
|
"@xterm/xterm": "^6.0.0",
|
||||||
|
|||||||
@@ -1,20 +1,25 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="flex h-full flex-col">
|
<div class="flex h-dvh flex-col">
|
||||||
<div
|
<WsBanner v-if="wsReconnecting" />
|
||||||
v-if="wsReconnecting"
|
<AppShell v-if="layout !== 'bare'" :fullbleed="layout === 'fullbleed'">
|
||||||
class="border-b border-amber-900/50 bg-amber-950/80 px-4 py-1.5 text-center text-xs text-amber-300"
|
<RouterView />
|
||||||
>
|
</AppShell>
|
||||||
{{ t('ws.reconnecting') }}
|
<RouterView v-else class="min-h-0 flex-1" />
|
||||||
</div>
|
<ToastContainer />
|
||||||
<RouterView class="min-h-0 flex-1" />
|
<CommandPalette />
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed } from 'vue';
|
import { computed } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useRoute } from 'vue-router';
|
||||||
import { wsClient } from './lib/ws-client';
|
import { wsClient } from './lib/ws-client';
|
||||||
|
import WsBanner from './components/layout/WsBanner.vue';
|
||||||
|
import AppShell from './components/layout/AppShell.vue';
|
||||||
|
import ToastContainer from './components/ToastContainer.vue';
|
||||||
|
import CommandPalette from './components/CommandPalette.vue';
|
||||||
|
|
||||||
const { t } = useI18n();
|
const route = useRoute();
|
||||||
|
const layout = computed(() => route.meta.layout ?? 'shell');
|
||||||
const wsReconnecting = computed(() => wsClient.status.value === 'reconnecting');
|
const wsReconnecting = computed(() => wsClient.status.value === 'reconnecting');
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
37
packages/web/src/components/AttentionSection.vue
Normal file
37
packages/web/src/components/AttentionSection.vue
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
<template>
|
||||||
|
<section v-if="waiting.length" class="flex flex-col gap-2 rounded-xl border border-amber-900/50 bg-amber-950/20 p-3">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<AlertTriangle :size="16" class="text-amber-400" />
|
||||||
|
<h2 class="text-sm font-semibold text-amber-200">{{ t('attention.title') }}</h2>
|
||||||
|
<BaseBadge tone="amber">{{ t('attention.count', waiting.length) }}</BaseBadge>
|
||||||
|
</div>
|
||||||
|
<div v-for="s in waiting" :key="s.id" class="flex flex-col gap-1">
|
||||||
|
<RouterLink
|
||||||
|
:to="{ name: 'session', params: { id: s.id } }"
|
||||||
|
class="truncate font-mono text-xs text-amber-300/80 transition-colors hover:text-amber-200"
|
||||||
|
:title="s.cwd"
|
||||||
|
>
|
||||||
|
{{ s.cwd }}
|
||||||
|
</RouterLink>
|
||||||
|
<DialogPrompt :session="s" />
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
// Vue « À traiter » : regroupe en tête les sessions bloquées sur un dialogue (cœur de la
|
||||||
|
// supervision mobile). Réutilise DialogPrompt pour répondre sans ouvrir le terminal.
|
||||||
|
import { computed } from 'vue';
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { AlertTriangle } from '@lucide/vue';
|
||||||
|
import { useSessionsStore } from '../stores/sessions';
|
||||||
|
import DialogPrompt from './DialogPrompt.vue';
|
||||||
|
import BaseBadge from './ui/BaseBadge.vue';
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
const sessions = useSessionsStore();
|
||||||
|
|
||||||
|
const waiting = computed(() =>
|
||||||
|
sessions.sessions.filter((s) => s.live && s.activity === 'waiting' && s.dialog),
|
||||||
|
);
|
||||||
|
</script>
|
||||||
169
packages/web/src/components/CommandPalette.vue
Normal file
169
packages/web/src/components/CommandPalette.vue
Normal file
@@ -0,0 +1,169 @@
|
|||||||
|
<template>
|
||||||
|
<Teleport to="body">
|
||||||
|
<div v-if="open" class="fixed inset-0 z-[60] flex items-start justify-center p-4 pt-[10vh]" role="dialog" aria-modal="true">
|
||||||
|
<div class="absolute inset-0 bg-black/60" @click="close" />
|
||||||
|
<div class="relative flex max-h-[70vh] w-full max-w-lg flex-col overflow-hidden rounded-xl border border-zinc-700 bg-zinc-900 shadow-pop">
|
||||||
|
<div class="flex items-center gap-2 border-b border-zinc-800 px-3">
|
||||||
|
<Search :size="16" class="text-zinc-500" />
|
||||||
|
<input
|
||||||
|
ref="inputEl"
|
||||||
|
v-model="query"
|
||||||
|
type="text"
|
||||||
|
class="w-full bg-transparent py-3 text-sm text-zinc-100 outline-none placeholder:text-zinc-600"
|
||||||
|
:placeholder="t('palette.placeholder')"
|
||||||
|
:aria-activedescendant="activeId ? `cmd-${activeId}` : undefined"
|
||||||
|
role="combobox"
|
||||||
|
aria-controls="cmd-listbox"
|
||||||
|
aria-expanded="true"
|
||||||
|
@keydown.down.prevent="move(1)"
|
||||||
|
@keydown.up.prevent="move(-1)"
|
||||||
|
@keydown.enter.prevent="run(results[activeIndex])"
|
||||||
|
@keydown.esc.prevent="close"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ul v-if="results.length" id="cmd-listbox" role="listbox" class="min-h-0 flex-1 overflow-y-auto p-1.5">
|
||||||
|
<li
|
||||||
|
v-for="(item, i) in results"
|
||||||
|
:id="`cmd-${item.id}`"
|
||||||
|
:key="item.id"
|
||||||
|
role="option"
|
||||||
|
:aria-selected="i === activeIndex"
|
||||||
|
class="flex cursor-pointer items-center gap-2 rounded-lg px-2.5 py-2"
|
||||||
|
:class="i === activeIndex ? 'bg-zinc-800' : 'hover:bg-zinc-800/50'"
|
||||||
|
@mousemove="activeIndex = i"
|
||||||
|
@click="run(item)"
|
||||||
|
>
|
||||||
|
<component :is="item.icon" :size="15" class="shrink-0 text-zinc-500" />
|
||||||
|
<span class="min-w-0 flex-1">
|
||||||
|
<span class="block truncate text-sm text-zinc-100">{{ item.label }}</span>
|
||||||
|
<span v-if="item.sublabel" class="block truncate font-mono text-[11px] text-zinc-500">{{ item.sublabel }}</span>
|
||||||
|
</span>
|
||||||
|
<span class="shrink-0 text-[10px] uppercase tracking-wide text-zinc-600">{{ t(`palette.types.${item.type}`) }}</span>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<p v-else class="px-3 py-6 text-center text-sm text-zinc-500">{{ t('palette.empty') }}</p>
|
||||||
|
|
||||||
|
<div class="border-t border-zinc-800 px-3 py-1.5 text-[11px] text-zinc-600">{{ t('palette.hint') }}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Teleport>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, nextTick, onMounted, onUnmounted, ref, watch, type Component } from 'vue';
|
||||||
|
import { useRouter, type RouteLocationRaw } from 'vue-router';
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { Search, GitBranch, TerminalSquare, Boxes, Plus, FolderPlus } from '@lucide/vue';
|
||||||
|
import { useSessionsStore } from '../stores/sessions';
|
||||||
|
import { useWorktreesStore } from '../stores/worktrees';
|
||||||
|
import { useGroupsStore } from '../stores/groups';
|
||||||
|
import { useCommandPalette } from '../composables/useCommandPalette';
|
||||||
|
|
||||||
|
interface PaletteItem {
|
||||||
|
id: string;
|
||||||
|
type: 'repo' | 'worktree' | 'session' | 'group' | 'action';
|
||||||
|
label: string;
|
||||||
|
sublabel?: string;
|
||||||
|
icon: Component;
|
||||||
|
keywords: string;
|
||||||
|
to?: RouteLocationRaw;
|
||||||
|
run?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
const router = useRouter();
|
||||||
|
const { open, close, toggle } = useCommandPalette();
|
||||||
|
const sessions = useSessionsStore();
|
||||||
|
const worktrees = useWorktreesStore();
|
||||||
|
const groups = useGroupsStore();
|
||||||
|
|
||||||
|
const query = ref('');
|
||||||
|
const activeIndex = ref(0);
|
||||||
|
const inputEl = ref<HTMLInputElement | null>(null);
|
||||||
|
|
||||||
|
const basename = (p: string): string => p.split('/').filter(Boolean).pop() ?? p;
|
||||||
|
|
||||||
|
const items = computed<PaletteItem[]>(() => {
|
||||||
|
const out: PaletteItem[] = [];
|
||||||
|
for (const r of worktrees.repos) {
|
||||||
|
out.push({ id: `repo-${r.id}`, type: 'repo', label: r.label, sublabel: r.path, icon: GitBranch as Component, keywords: `${r.label} ${r.path}`.toLowerCase(), to: { name: 'dashboard' } });
|
||||||
|
}
|
||||||
|
for (const w of worktrees.worktrees) {
|
||||||
|
const target: RouteLocationRaw = w.sessions[0]
|
||||||
|
? { name: 'session', params: { id: w.sessions[0].id } }
|
||||||
|
: { name: 'dashboard' };
|
||||||
|
out.push({ id: `wt-${w.path}`, type: 'worktree', label: w.branch ?? basename(w.path), sublabel: w.path, icon: GitBranch as Component, keywords: `${w.branch ?? ''} ${w.path}`.toLowerCase(), to: target });
|
||||||
|
}
|
||||||
|
for (const s of sessions.sessions) {
|
||||||
|
out.push({ id: `ses-${s.id}`, type: 'session', label: s.title ?? basename(s.cwd), sublabel: s.cwd, icon: TerminalSquare as Component, keywords: `${s.title ?? ''} ${s.cwd} ${s.command}`.toLowerCase(), to: { name: 'session', params: { id: s.id } } });
|
||||||
|
}
|
||||||
|
for (const g of groups.groups) {
|
||||||
|
out.push({ id: `grp-${g.id}`, type: 'group', label: g.label, ...(g.description ? { sublabel: g.description } : {}), icon: Boxes as Component, keywords: `${g.label} ${g.description ?? ''}`.toLowerCase(), to: { name: 'group', params: { id: g.id } } });
|
||||||
|
}
|
||||||
|
// actions globales
|
||||||
|
out.push({ id: 'act-newSession', type: 'action', label: t('palette.actions.newSession'), icon: Plus as Component, keywords: t('palette.actions.newSession').toLowerCase(), to: { name: 'sessions' } });
|
||||||
|
out.push({ id: 'act-addRepo', type: 'action', label: t('palette.actions.addRepo'), icon: FolderPlus as Component, keywords: t('palette.actions.addRepo').toLowerCase(), to: { name: 'dashboard' } });
|
||||||
|
out.push({ id: 'act-newGroup', type: 'action', label: t('palette.actions.newGroup'), icon: Boxes as Component, keywords: t('palette.actions.newGroup').toLowerCase(), to: { name: 'groups' } });
|
||||||
|
return out;
|
||||||
|
});
|
||||||
|
|
||||||
|
// fuzzy minimal : tous les tokens présents (AND), score = somme des positions (plus tôt = mieux).
|
||||||
|
const results = computed<PaletteItem[]>(() => {
|
||||||
|
const tokens = query.value.trim().toLowerCase().split(/\s+/).filter(Boolean);
|
||||||
|
if (tokens.length === 0) return items.value.slice(0, 30);
|
||||||
|
const scored: { item: PaletteItem; score: number }[] = [];
|
||||||
|
for (const item of items.value) {
|
||||||
|
let score = 0;
|
||||||
|
let ok = true;
|
||||||
|
for (const tok of tokens) {
|
||||||
|
const idx = item.keywords.indexOf(tok);
|
||||||
|
if (idx < 0) {
|
||||||
|
ok = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
score += idx;
|
||||||
|
}
|
||||||
|
if (ok) scored.push({ item, score });
|
||||||
|
}
|
||||||
|
return scored.sort((a, b) => a.score - b.score).slice(0, 30).map((s) => s.item);
|
||||||
|
});
|
||||||
|
|
||||||
|
watch(results, () => {
|
||||||
|
if (activeIndex.value >= results.value.length) activeIndex.value = 0;
|
||||||
|
});
|
||||||
|
|
||||||
|
const activeId = computed(() => results.value[activeIndex.value]?.id);
|
||||||
|
|
||||||
|
function move(delta: number): void {
|
||||||
|
const n = results.value.length;
|
||||||
|
if (n === 0) return;
|
||||||
|
activeIndex.value = (activeIndex.value + delta + n) % n;
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(item: PaletteItem | undefined): void {
|
||||||
|
if (!item) return;
|
||||||
|
close();
|
||||||
|
if (item.run) item.run();
|
||||||
|
else if (item.to) void router.push(item.to);
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(open, async (v) => {
|
||||||
|
if (v) {
|
||||||
|
query.value = '';
|
||||||
|
activeIndex.value = 0;
|
||||||
|
await nextTick();
|
||||||
|
inputEl.value?.focus();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// raccourci global ⌘K / Ctrl+K — en phase de capture pour passer devant xterm (SessionView).
|
||||||
|
function onKey(e: KeyboardEvent): void {
|
||||||
|
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
|
||||||
|
e.preventDefault();
|
||||||
|
toggle();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
onMounted(() => window.addEventListener('keydown', onKey, { capture: true }));
|
||||||
|
onUnmounted(() => window.removeEventListener('keydown', onKey, { capture: true }));
|
||||||
|
</script>
|
||||||
87
packages/web/src/components/ListToolbar.vue
Normal file
87
packages/web/src/components/ListToolbar.vue
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
<div class="flex flex-col gap-2 sm:flex-row sm:items-center">
|
||||||
|
<!-- recherche -->
|
||||||
|
<div class="relative flex-1">
|
||||||
|
<Search :size="15" class="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-zinc-500" />
|
||||||
|
<input
|
||||||
|
v-model="searchModel"
|
||||||
|
type="search"
|
||||||
|
class="input pl-8"
|
||||||
|
:placeholder="t(searchPlaceholderKey ?? 'controls.searchPlaceholder')"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- tri : clé + direction -->
|
||||||
|
<div class="flex items-center gap-1.5">
|
||||||
|
<label class="sr-only" :for="sortId">{{ t('controls.sortBy') }}</label>
|
||||||
|
<select :id="sortId" class="input w-auto" :value="controls.sortKey.value" @change="onSortChange">
|
||||||
|
<option v-for="def in controls.sortDefs" :key="def.key" :value="def.key">{{ t(def.labelKey) }}</option>
|
||||||
|
</select>
|
||||||
|
<BaseButton
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
icon-only
|
||||||
|
:icon="controls.sortDir.value === 'asc' ? ArrowUp : ArrowDown"
|
||||||
|
:aria-label="t(controls.sortDir.value === 'asc' ? 'sort.asc' : 'sort.desc')"
|
||||||
|
@click="controls.setSort(controls.sortKey.value)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- chips de filtre + compteur (le compteur s'affiche même sans filtres) -->
|
||||||
|
<div class="flex flex-wrap items-center gap-1.5">
|
||||||
|
<template v-for="def in controls.filterDefs.value" :key="def.key">
|
||||||
|
<button
|
||||||
|
v-for="opt in def.options"
|
||||||
|
:key="def.key + ':' + opt.value"
|
||||||
|
type="button"
|
||||||
|
class="rounded-full border px-2 py-0.5 text-xs transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-500/50"
|
||||||
|
:class="isActive(def.key, opt.value)
|
||||||
|
? 'border-sky-700 bg-sky-950/40 text-sky-300'
|
||||||
|
: 'border-zinc-700 text-zinc-400 hover:border-zinc-600 hover:text-zinc-200'"
|
||||||
|
@click="controls.toggleFilter(def.key, opt.value)"
|
||||||
|
>
|
||||||
|
{{ opt.labelKey ? t(opt.labelKey) : opt.label }}
|
||||||
|
</button>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<BaseButton
|
||||||
|
v-if="controls.activeFilterCount.value > 0 || controls.search.value"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
:icon="X"
|
||||||
|
@click="controls.clearAll()"
|
||||||
|
>
|
||||||
|
{{ t('controls.clearAll') }}
|
||||||
|
</BaseButton>
|
||||||
|
|
||||||
|
<span class="ml-auto text-xs text-zinc-500">{{ t('controls.results', controls.total.value) }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts" generic="T">
|
||||||
|
import { computed, useId } from 'vue';
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { Search, ArrowUp, ArrowDown, X } from '@lucide/vue';
|
||||||
|
import BaseButton from './ui/BaseButton.vue';
|
||||||
|
import type { ListToolbarControls } from '../composables/useListControls';
|
||||||
|
|
||||||
|
const props = defineProps<{ controls: ListToolbarControls<T>; searchPlaceholderKey?: string }>();
|
||||||
|
const { t } = useI18n();
|
||||||
|
const sortId = useId();
|
||||||
|
|
||||||
|
const searchModel = computed({
|
||||||
|
get: () => props.controls.search.value,
|
||||||
|
set: (v: string) => props.controls.setSearch(v),
|
||||||
|
});
|
||||||
|
|
||||||
|
function onSortChange(e: Event): void {
|
||||||
|
props.controls.setSort((e.target as HTMLSelectElement).value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isActive(key: string, value: string): boolean {
|
||||||
|
return props.controls.filters.value[key]?.has(value) ?? false;
|
||||||
|
}
|
||||||
|
</script>
|
||||||
47
packages/web/src/components/Pagination.vue
Normal file
47
packages/web/src/components/Pagination.vue
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
<template>
|
||||||
|
<div v-if="pageCount > 1 || pageSize !== defaultSize" class="flex flex-wrap items-center justify-between gap-2 text-xs text-zinc-500">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<label class="flex items-center gap-1.5">
|
||||||
|
{{ t('pagination.perPage') }}
|
||||||
|
<select class="input w-auto py-1" :value="pageSize" @change="onSize">
|
||||||
|
<option v-for="opt in pageSizeOptions" :key="opt" :value="opt">{{ opt === 0 ? t('pagination.all') : opt }}</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div v-if="pageCount > 1" class="flex items-center gap-2">
|
||||||
|
<BaseButton variant="ghost" size="sm" :icon="ChevronLeft" :disabled="page <= 1" @click="emit('update:page', page - 1)">
|
||||||
|
{{ t('pagination.prev') }}
|
||||||
|
</BaseButton>
|
||||||
|
<span>{{ t('pagination.pageOf', { page, pageCount }) }}</span>
|
||||||
|
<BaseButton variant="ghost" size="sm" :disabled="page >= pageCount" @click="emit('update:page', page + 1)">
|
||||||
|
{{ t('pagination.next') }}
|
||||||
|
<ChevronRight :size="15" />
|
||||||
|
</BaseButton>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { ChevronLeft, ChevronRight } from '@lucide/vue';
|
||||||
|
import BaseButton from './ui/BaseButton.vue';
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
|
||||||
|
withDefaults(
|
||||||
|
defineProps<{
|
||||||
|
page: number;
|
||||||
|
pageCount: number;
|
||||||
|
pageSize: number;
|
||||||
|
pageSizeOptions?: number[];
|
||||||
|
defaultSize?: number;
|
||||||
|
}>(),
|
||||||
|
{ pageSizeOptions: () => [25, 50, 100, 0], defaultSize: 25 },
|
||||||
|
);
|
||||||
|
|
||||||
|
const emit = defineEmits<{ 'update:page': [number]; 'update:pageSize': [number] }>();
|
||||||
|
|
||||||
|
function onSize(e: Event): void {
|
||||||
|
emit('update:pageSize', Number((e.target as HTMLSelectElement).value));
|
||||||
|
}
|
||||||
|
</script>
|
||||||
@@ -1,20 +1,27 @@
|
|||||||
<template>
|
<template>
|
||||||
<section class="flex flex-col gap-2 rounded-lg border border-zinc-800 bg-zinc-900/50 p-3">
|
<section class="card flex flex-col gap-2">
|
||||||
<header class="flex items-center gap-2">
|
<header class="flex flex-wrap items-center gap-2">
|
||||||
<h2 class="font-semibold text-zinc-100">{{ repo.label }}</h2>
|
<h2 class="font-semibold text-zinc-100">{{ repo.label }}</h2>
|
||||||
<span v-if="!repo.valid" class="badge bg-red-950 text-red-400">{{ t('repos.invalid') }}</span>
|
<BaseBadge v-if="!repo.valid" tone="red">{{ t('repos.invalid') }}</BaseBadge>
|
||||||
<span class="truncate font-mono text-xs text-zinc-500" :title="repo.path">{{ repo.path }}</span>
|
<span class="truncate font-mono text-xs text-zinc-500" :title="repo.path">{{ repo.path }}</span>
|
||||||
<div class="ml-auto flex items-center gap-2">
|
<div class="ml-auto flex items-center gap-2">
|
||||||
<button class="btn text-xs" @click="creating = !creating">{{ t('worktrees.new') }}</button>
|
<BaseButton size="sm" :icon="Plus" @click="creating = !creating">{{ t('worktrees.new') }}</BaseButton>
|
||||||
<button class="btn text-xs" :disabled="busy" @click="onPrune">{{ t('worktrees.prune') }}</button>
|
<BaseButton size="sm" :icon="Scissors" :loading="busy" @click="onPrune">{{ t('worktrees.prune') }}</BaseButton>
|
||||||
<button class="btn-danger text-xs" @click="onRemove">{{ t('repos.remove') }}</button>
|
<BaseButton
|
||||||
|
size="sm"
|
||||||
|
icon-only
|
||||||
|
:icon="repo.hidden ? Eye : EyeOff"
|
||||||
|
:aria-label="repo.hidden ? t('repos.show') : t('repos.hide')"
|
||||||
|
@click="onToggleHidden"
|
||||||
|
/>
|
||||||
|
<BaseButton variant="danger" size="sm" icon-only :icon="Trash2" :aria-label="t('repos.remove')" @click="onRemove" />
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<form v-if="creating" class="flex flex-wrap items-end gap-2 rounded border border-zinc-800 bg-zinc-950/40 p-2" @submit.prevent="onCreate">
|
<form v-if="creating" class="card-inset flex flex-wrap items-end gap-2" @submit.prevent="onCreate">
|
||||||
<label class="flex flex-1 flex-col gap-1 text-xs text-zinc-400">
|
<label class="flex flex-1 flex-col gap-1 text-xs text-zinc-400">
|
||||||
{{ t('worktrees.branch') }}
|
{{ t('worktrees.branch') }}
|
||||||
<input v-model="branch" class="input font-mono" :placeholder="repo.defaultBranch ? `feature/…` : 'feature/…'" required />
|
<input v-model="branch" class="input font-mono" placeholder="feature/…" required />
|
||||||
</label>
|
</label>
|
||||||
<label class="flex flex-col gap-1 text-xs text-zinc-400">
|
<label class="flex flex-col gap-1 text-xs text-zinc-400">
|
||||||
{{ t('worktrees.start') }}
|
{{ t('worktrees.start') }}
|
||||||
@@ -25,14 +32,15 @@
|
|||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
<label class="flex items-center gap-1 text-xs text-zinc-400"><input v-model="newBranch" type="checkbox" /> {{ t('worktrees.newBranch') }}</label>
|
<label class="flex items-center gap-1 text-xs text-zinc-400"><input v-model="newBranch" type="checkbox" /> {{ t('worktrees.newBranch') }}</label>
|
||||||
<button type="submit" class="btn-primary text-xs" :disabled="busy || branch.trim() === ''">
|
<BaseButton type="submit" variant="primary" size="sm" :loading="busy" :disabled="branch.trim() === ''">
|
||||||
{{ busy ? t('worktrees.creating') : t('worktrees.create') }}
|
{{ t('worktrees.create') }}
|
||||||
</button>
|
</BaseButton>
|
||||||
</form>
|
</form>
|
||||||
<p v-if="error" class="text-sm text-red-400">{{ error }}</p>
|
<p v-if="error" class="text-sm text-red-400">{{ error }}</p>
|
||||||
|
|
||||||
<div class="flex flex-col gap-1.5">
|
<div class="flex flex-col gap-1.5">
|
||||||
<WorktreeCard v-for="w in worktrees" :key="w.path" :worktree="w" />
|
<WorktreeCard v-for="w in worktrees" :key="w.path" :worktree="w" />
|
||||||
|
<p v-if="worktrees.length === 0" class="px-1 text-xs text-zinc-600">{{ t('worktrees.noSession') }}</p>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</template>
|
</template>
|
||||||
@@ -40,15 +48,23 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, ref } from 'vue';
|
import { computed, ref } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { Eye, EyeOff, Plus, Scissors, Trash2 } from '@lucide/vue';
|
||||||
import type { RepoSummary } from '@arboretum/shared';
|
import type { RepoSummary } from '@arboretum/shared';
|
||||||
import { useWorktreesStore } from '../stores/worktrees';
|
import { useWorktreesStore } from '../stores/worktrees';
|
||||||
|
import { useWorktreeView } from '../composables/useWorktreeView';
|
||||||
|
import { useToastsStore } from '../stores/toasts';
|
||||||
import WorktreeCard from './WorktreeCard.vue';
|
import WorktreeCard from './WorktreeCard.vue';
|
||||||
|
import BaseButton from './ui/BaseButton.vue';
|
||||||
|
import BaseBadge from './ui/BaseBadge.vue';
|
||||||
|
|
||||||
const props = defineProps<{ repo: RepoSummary }>();
|
const props = defineProps<{ repo: RepoSummary }>();
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const store = useWorktreesStore();
|
const store = useWorktreesStore();
|
||||||
|
const view = useWorktreeView();
|
||||||
|
const toasts = useToastsStore();
|
||||||
|
|
||||||
const worktrees = computed(() => store.worktreesForRepo(props.repo.id));
|
// applique le tri/filtre/recherche partagé (toolbar du dashboard) aux worktrees de ce repo.
|
||||||
|
const worktrees = computed(() => view.apply(store.worktreesForRepo(props.repo.id)));
|
||||||
const creating = ref(false);
|
const creating = ref(false);
|
||||||
const branch = ref('');
|
const branch = ref('');
|
||||||
const newBranch = ref(true);
|
const newBranch = ref(true);
|
||||||
@@ -63,6 +79,7 @@ async function onCreate(): Promise<void> {
|
|||||||
await store.createWorktree(props.repo.id, { branch: branch.value.trim(), newBranch: newBranch.value, startSession: startSession.value });
|
await store.createWorktree(props.repo.id, { branch: branch.value.trim(), newBranch: newBranch.value, startSession: startSession.value });
|
||||||
branch.value = '';
|
branch.value = '';
|
||||||
creating.value = false;
|
creating.value = false;
|
||||||
|
toasts.success(t('toast.worktreeCreated'));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
error.value = err instanceof Error ? err.message : String(err);
|
error.value = err instanceof Error ? err.message : String(err);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -75,19 +92,28 @@ async function onPrune(): Promise<void> {
|
|||||||
error.value = null;
|
error.value = null;
|
||||||
try {
|
try {
|
||||||
await store.prune(props.repo.id);
|
await store.prune(props.repo.id);
|
||||||
|
toasts.success(t('toast.pruned'));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
error.value = err instanceof Error ? err.message : String(err);
|
toasts.error(err);
|
||||||
} finally {
|
} finally {
|
||||||
busy.value = false;
|
busy.value = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onRemove(): Promise<void> {
|
async function onRemove(): Promise<void> {
|
||||||
error.value = null;
|
|
||||||
try {
|
try {
|
||||||
await store.removeRepo(props.repo.id);
|
await store.removeRepo(props.repo.id);
|
||||||
|
toasts.success(t('toast.repoRemoved'));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
error.value = err instanceof Error ? err.message : String(err);
|
toasts.error(err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onToggleHidden(): Promise<void> {
|
||||||
|
try {
|
||||||
|
await store.setHidden(props.repo.id, !props.repo.hidden);
|
||||||
|
} catch (err) {
|
||||||
|
toasts.error(err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
60
packages/web/src/components/ToastContainer.vue
Normal file
60
packages/web/src/components/ToastContainer.vue
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
<template>
|
||||||
|
<div class="pointer-events-none fixed inset-x-0 bottom-0 z-50 flex flex-col items-end gap-2 p-4 sm:bottom-4 sm:right-4 sm:left-auto sm:p-0">
|
||||||
|
<TransitionGroup name="toast">
|
||||||
|
<div
|
||||||
|
v-for="toast in store.toasts"
|
||||||
|
:key="toast.id"
|
||||||
|
class="pointer-events-auto flex w-full max-w-sm items-start gap-2 rounded-lg border px-3 py-2 shadow-pop"
|
||||||
|
:class="toneClass(toast.kind)"
|
||||||
|
:role="toast.kind === 'error' ? 'alert' : 'status'"
|
||||||
|
:aria-live="toast.kind === 'error' ? 'assertive' : 'polite'"
|
||||||
|
>
|
||||||
|
<component :is="icon(toast.kind)" :size="16" class="mt-0.5 shrink-0" />
|
||||||
|
<span class="min-w-0 flex-1 break-words text-sm">{{ toast.message }}</span>
|
||||||
|
<button
|
||||||
|
class="shrink-0 rounded p-0.5 opacity-70 transition-opacity hover:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400/50"
|
||||||
|
:aria-label="t('toast.dismiss')"
|
||||||
|
@click="store.dismiss(toast.id)"
|
||||||
|
>
|
||||||
|
<X :size="14" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</TransitionGroup>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { CheckCircle2, AlertTriangle, Info, X } from '@lucide/vue';
|
||||||
|
import { useToastsStore, type ToastKind } from '../stores/toasts';
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
const store = useToastsStore();
|
||||||
|
|
||||||
|
function toneClass(kind: ToastKind): string {
|
||||||
|
if (kind === 'success') return 'border-emerald-800 bg-emerald-950 text-emerald-200';
|
||||||
|
if (kind === 'error') return 'border-red-800 bg-red-950 text-red-200';
|
||||||
|
return 'border-zinc-700 bg-zinc-900 text-zinc-200';
|
||||||
|
}
|
||||||
|
function icon(kind: ToastKind) {
|
||||||
|
return kind === 'success' ? CheckCircle2 : kind === 'error' ? AlertTriangle : Info;
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.toast-enter-active,
|
||||||
|
.toast-leave-active {
|
||||||
|
transition: opacity 0.18s ease, transform 0.18s ease;
|
||||||
|
}
|
||||||
|
.toast-enter-from,
|
||||||
|
.toast-leave-to {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(8px);
|
||||||
|
}
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.toast-enter-active,
|
||||||
|
.toast-leave-active {
|
||||||
|
transition: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
53
packages/web/src/components/layout/AppShell.vue
Normal file
53
packages/web/src/components/layout/AppShell.vue
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
<template>
|
||||||
|
<div class="flex min-h-0 w-full flex-1 overflow-hidden">
|
||||||
|
<AppSidebar />
|
||||||
|
<div class="flex min-h-0 min-w-0 flex-1 flex-col">
|
||||||
|
<main v-if="fullbleed" class="flex min-h-0 flex-1 flex-col pb-14 md:pb-0">
|
||||||
|
<slot />
|
||||||
|
</main>
|
||||||
|
<main v-else class="flex-1 overflow-y-auto pb-14 md:pb-0">
|
||||||
|
<div class="mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-4 md:py-6">
|
||||||
|
<slot />
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
<MobileTabBar />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
// Coquille des vues authentifiées. Propriétaire unique du chargement initial et des abonnements
|
||||||
|
// temps réel (sessions/worktrees/groups) pour toute la durée de la session : fiabilise le badge
|
||||||
|
// de navigation, la palette ⌘K et la section « À traiter » quelle que soit la vue active.
|
||||||
|
import { onMounted, onUnmounted } from 'vue';
|
||||||
|
import { useSessionsStore } from '../../stores/sessions';
|
||||||
|
import { useWorktreesStore } from '../../stores/worktrees';
|
||||||
|
import { useGroupsStore } from '../../stores/groups';
|
||||||
|
import { useSettingsStore } from '../../stores/settings';
|
||||||
|
import AppSidebar from './AppSidebar.vue';
|
||||||
|
import MobileTabBar from './MobileTabBar.vue';
|
||||||
|
|
||||||
|
defineProps<{ fullbleed?: boolean }>();
|
||||||
|
|
||||||
|
const sessions = useSessionsStore();
|
||||||
|
const worktrees = useWorktreesStore();
|
||||||
|
const groups = useGroupsStore();
|
||||||
|
const settings = useSettingsStore();
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
void worktrees.fetchAll();
|
||||||
|
void sessions.fetchSessions();
|
||||||
|
void groups.fetchGroups();
|
||||||
|
void settings.fetch(); // alimente l'icône de nav Gitea et la vue Réglages
|
||||||
|
|
||||||
|
worktrees.startRealtime();
|
||||||
|
sessions.startRealtime();
|
||||||
|
groups.startRealtime();
|
||||||
|
});
|
||||||
|
|
||||||
|
onUnmounted(() => {
|
||||||
|
worktrees.stopRealtime();
|
||||||
|
sessions.stopRealtime();
|
||||||
|
groups.stopRealtime();
|
||||||
|
});
|
||||||
|
</script>
|
||||||
57
packages/web/src/components/layout/AppShellFooter.vue
Normal file
57
packages/web/src/components/layout/AppShellFooter.vue
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
<p v-if="pushErrorText" class="text-xs text-amber-400">{{ pushErrorText }}</p>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<LanguageSwitcher />
|
||||||
|
<BaseButton
|
||||||
|
v-if="push.supported"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
icon-only
|
||||||
|
:icon="push.enabled ? Bell : BellOff"
|
||||||
|
:class="push.enabled ? 'text-emerald-300' : ''"
|
||||||
|
:disabled="push.busy"
|
||||||
|
:title="pushErrorText || undefined"
|
||||||
|
:aria-label="push.enabled ? t('push.disable') : t('push.enable')"
|
||||||
|
@click="push.toggle()"
|
||||||
|
/>
|
||||||
|
<BaseButton
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
icon-only
|
||||||
|
:icon="LogOut"
|
||||||
|
class="ml-auto"
|
||||||
|
:aria-label="t('common.logout')"
|
||||||
|
@click="logout"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<span v-if="auth.serverVersion" class="text-[11px] text-zinc-600">v{{ auth.serverVersion }}</span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted } from 'vue';
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { Bell, BellOff, LogOut } from '@lucide/vue';
|
||||||
|
import { useAuthStore } from '../../stores/auth';
|
||||||
|
import { usePushStore } from '../../stores/push';
|
||||||
|
import { useSession } from '../../composables/useSession';
|
||||||
|
import BaseButton from '../ui/BaseButton.vue';
|
||||||
|
import LanguageSwitcher from '../LanguageSwitcher.vue';
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
const auth = useAuthStore();
|
||||||
|
const push = usePushStore();
|
||||||
|
const { logout } = useSession();
|
||||||
|
|
||||||
|
// 'denied'/'unsupported' sont des clés i18n ; tout autre message d'erreur est affiché tel quel.
|
||||||
|
const pushErrorText = computed(() => {
|
||||||
|
const e = push.error;
|
||||||
|
if (!e) return '';
|
||||||
|
return e === 'denied' || e === 'unsupported' ? t(`push.${e}`) : e;
|
||||||
|
});
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
void push.refresh();
|
||||||
|
});
|
||||||
|
</script>
|
||||||
58
packages/web/src/components/layout/AppSidebar.vue
Normal file
58
packages/web/src/components/layout/AppSidebar.vue
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
<template>
|
||||||
|
<aside class="hidden w-56 shrink-0 flex-col border-r border-zinc-800/80 bg-zinc-900/40 md:flex">
|
||||||
|
<RouterLink :to="{ name: 'dashboard' }" class="flex items-center gap-2 px-4 py-3.5">
|
||||||
|
<img src="/icon.svg" class="h-7 w-7" alt="" />
|
||||||
|
<span class="text-base font-semibold text-zinc-100">{{ t('common.appName') }}</span>
|
||||||
|
</RouterLink>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="mx-2 mb-2 flex items-center gap-2 rounded-lg border border-zinc-800 bg-zinc-950/40 px-2.5 py-1.5 text-sm text-zinc-500 transition-colors hover:border-zinc-700 hover:text-zinc-300 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-500/50"
|
||||||
|
@click="palette.show()"
|
||||||
|
>
|
||||||
|
<Search :size="15" />
|
||||||
|
<span class="flex-1 text-left">{{ t('common.search') }}</span>
|
||||||
|
<kbd class="rounded border border-zinc-700 px-1 text-[10px] text-zinc-500">⌘K</kbd>
|
||||||
|
</button>
|
||||||
|
<nav class="flex flex-1 flex-col gap-1 px-2">
|
||||||
|
<NavItem
|
||||||
|
v-for="item in primary"
|
||||||
|
:key="item.key"
|
||||||
|
:to="item.to"
|
||||||
|
:icon="item.icon"
|
||||||
|
:label="item.label"
|
||||||
|
:badge="item.badge"
|
||||||
|
:active="isActive(item.match)"
|
||||||
|
orientation="row"
|
||||||
|
/>
|
||||||
|
</nav>
|
||||||
|
<nav class="flex flex-col gap-1 px-2 pb-1">
|
||||||
|
<NavItem
|
||||||
|
v-for="item in secondary"
|
||||||
|
:key="item.key"
|
||||||
|
:to="item.to"
|
||||||
|
:href="item.href"
|
||||||
|
:icon="item.icon"
|
||||||
|
:label="item.label"
|
||||||
|
:badge="item.badge"
|
||||||
|
:active="isActive(item.match)"
|
||||||
|
orientation="row"
|
||||||
|
/>
|
||||||
|
</nav>
|
||||||
|
<div class="border-t border-zinc-800/80 p-3">
|
||||||
|
<AppShellFooter />
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { Search } from '@lucide/vue';
|
||||||
|
import { useNav } from '../../composables/useNav';
|
||||||
|
import { useCommandPalette } from '../../composables/useCommandPalette';
|
||||||
|
import NavItem from './NavItem.vue';
|
||||||
|
import AppShellFooter from './AppShellFooter.vue';
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
const { primary, secondary, isActive } = useNav();
|
||||||
|
const palette = useCommandPalette();
|
||||||
|
</script>
|
||||||
43
packages/web/src/components/layout/MobileTabBar.vue
Normal file
43
packages/web/src/components/layout/MobileTabBar.vue
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
<template>
|
||||||
|
<nav
|
||||||
|
class="fixed inset-x-0 bottom-0 z-40 flex border-t border-zinc-800 bg-zinc-950/95 backdrop-blur md:hidden"
|
||||||
|
style="padding-bottom: env(safe-area-inset-bottom)"
|
||||||
|
>
|
||||||
|
<NavItem
|
||||||
|
v-for="item in primary"
|
||||||
|
:key="item.key"
|
||||||
|
:to="item.to"
|
||||||
|
:icon="item.icon"
|
||||||
|
:label="item.label"
|
||||||
|
:badge="item.badge"
|
||||||
|
:active="isActive(item.match)"
|
||||||
|
orientation="col"
|
||||||
|
class="flex-1"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex flex-1 flex-col items-center gap-0.5 py-2 text-zinc-500 transition-colors hover:text-zinc-300 focus-visible:outline-none"
|
||||||
|
:class="moreActive ? 'text-emerald-400' : ''"
|
||||||
|
@click="showMore = true"
|
||||||
|
>
|
||||||
|
<Menu :size="20" :stroke-width="1.75" />
|
||||||
|
<span class="text-[10px]">{{ t('nav.more') }}</span>
|
||||||
|
</button>
|
||||||
|
<MoreSheet v-if="showMore" @close="showMore = false" />
|
||||||
|
</nav>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue';
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { Menu } from '@lucide/vue';
|
||||||
|
import { useNav } from '../../composables/useNav';
|
||||||
|
import NavItem from './NavItem.vue';
|
||||||
|
import MoreSheet from './MoreSheet.vue';
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
const { primary, secondary, isActive } = useNav();
|
||||||
|
const showMore = ref(false);
|
||||||
|
// « More » est actif quand la route courante appartient aux items secondaires (Réglages/Aide).
|
||||||
|
const moreActive = computed(() => secondary.value.some((i) => isActive(i.match)));
|
||||||
|
</script>
|
||||||
42
packages/web/src/components/layout/MoreSheet.vue
Normal file
42
packages/web/src/components/layout/MoreSheet.vue
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
<template>
|
||||||
|
<Teleport to="body">
|
||||||
|
<div class="fixed inset-0 z-50 md:hidden" role="dialog" aria-modal="true">
|
||||||
|
<div class="absolute inset-0 bg-black/60" @click="emit('close')" />
|
||||||
|
<div
|
||||||
|
class="absolute inset-x-0 bottom-0 rounded-t-2xl border-t border-zinc-800 bg-zinc-900 p-4 shadow-pop"
|
||||||
|
style="padding-bottom: calc(1rem + env(safe-area-inset-bottom))"
|
||||||
|
>
|
||||||
|
<div class="mx-auto mb-3 h-1 w-10 rounded-full bg-zinc-700" />
|
||||||
|
<nav class="mb-3 flex flex-col gap-1">
|
||||||
|
<NavItem
|
||||||
|
v-for="item in secondary"
|
||||||
|
:key="item.key"
|
||||||
|
:to="item.to"
|
||||||
|
:href="item.href"
|
||||||
|
:icon="item.icon"
|
||||||
|
:label="item.label"
|
||||||
|
:active="isActive(item.match)"
|
||||||
|
orientation="row"
|
||||||
|
@click="emit('close')"
|
||||||
|
/>
|
||||||
|
</nav>
|
||||||
|
<div class="border-t border-zinc-800/80 pt-3">
|
||||||
|
<AppShellFooter />
|
||||||
|
</div>
|
||||||
|
<BaseButton class="mt-3 w-full" @click="emit('close')">{{ t('common.close') }}</BaseButton>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Teleport>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { useNav } from '../../composables/useNav';
|
||||||
|
import NavItem from './NavItem.vue';
|
||||||
|
import AppShellFooter from './AppShellFooter.vue';
|
||||||
|
import BaseButton from '../ui/BaseButton.vue';
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
const { secondary, isActive } = useNav();
|
||||||
|
const emit = defineEmits<{ close: [] }>();
|
||||||
|
</script>
|
||||||
58
packages/web/src/components/layout/NavItem.vue
Normal file
58
packages/web/src/components/layout/NavItem.vue
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
<template>
|
||||||
|
<!-- RouterLink pour une route interne ; <a target=_blank> pour un lien externe (ex. Gitea). -->
|
||||||
|
<component
|
||||||
|
:is="href ? 'a' : RouterLink"
|
||||||
|
:to="href ? undefined : to"
|
||||||
|
:href="href"
|
||||||
|
:target="href ? '_blank' : undefined"
|
||||||
|
:rel="href ? 'noopener noreferrer' : undefined"
|
||||||
|
:aria-current="!href && active ? 'page' : undefined"
|
||||||
|
:class="orientation === 'col' ? colClass : rowClass"
|
||||||
|
>
|
||||||
|
<span class="relative">
|
||||||
|
<component :is="icon" :size="orientation === 'col' ? 20 : 18" :stroke-width="1.75" />
|
||||||
|
<span
|
||||||
|
v-if="badge"
|
||||||
|
class="absolute -right-1.5 -top-1.5 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-amber-500 px-1 text-[9px] font-semibold text-amber-950"
|
||||||
|
>
|
||||||
|
{{ badge }}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
<span :class="orientation === 'col' ? 'text-[10px]' : 'flex-1'">{{ label }}</span>
|
||||||
|
<span
|
||||||
|
v-if="badge && orientation === 'row'"
|
||||||
|
class="rounded-full bg-amber-500/20 px-1.5 text-[11px] font-semibold text-amber-300"
|
||||||
|
>
|
||||||
|
{{ badge }}
|
||||||
|
</span>
|
||||||
|
</component>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, type Component } from 'vue';
|
||||||
|
import { RouterLink, type RouteLocationRaw } from 'vue-router';
|
||||||
|
|
||||||
|
const props = withDefaults(
|
||||||
|
defineProps<{
|
||||||
|
// `| undefined` requis par exactOptionalPropertyTypes : les items de nav passent `to`/`href`
|
||||||
|
// potentiellement undefined (l'un ou l'autre selon route interne vs lien externe).
|
||||||
|
to?: RouteLocationRaw | undefined;
|
||||||
|
href?: string | undefined;
|
||||||
|
icon: Component;
|
||||||
|
label: string;
|
||||||
|
badge?: number;
|
||||||
|
active?: boolean;
|
||||||
|
orientation?: 'row' | 'col';
|
||||||
|
}>(),
|
||||||
|
{ orientation: 'row' },
|
||||||
|
);
|
||||||
|
|
||||||
|
const rowClass = computed(() => [
|
||||||
|
'flex items-center gap-2.5 rounded-lg px-3 py-2 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-500/70',
|
||||||
|
props.active ? 'bg-zinc-800 text-zinc-100' : 'text-zinc-400 hover:bg-zinc-800/50 hover:text-zinc-200',
|
||||||
|
]);
|
||||||
|
const colClass = computed(() => [
|
||||||
|
'flex flex-1 flex-col items-center gap-0.5 py-2 transition-colors focus-visible:outline-none',
|
||||||
|
props.active ? 'text-emerald-400' : 'text-zinc-500 hover:text-zinc-300',
|
||||||
|
]);
|
||||||
|
</script>
|
||||||
21
packages/web/src/components/layout/PageHeader.vue
Normal file
21
packages/web/src/components/layout/PageHeader.vue
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
<template>
|
||||||
|
<header class="flex flex-wrap items-center gap-x-3 gap-y-2">
|
||||||
|
<div class="flex min-w-0 items-center gap-2">
|
||||||
|
<slot name="title">
|
||||||
|
<h1 class="truncate text-lg font-semibold text-zinc-100">{{ title }}</h1>
|
||||||
|
</slot>
|
||||||
|
<span v-if="subtitle" class="truncate font-mono text-xs text-zinc-500" :title="subtitle">{{ subtitle }}</span>
|
||||||
|
</div>
|
||||||
|
<div v-if="$slots.default" class="ml-auto flex flex-wrap items-center gap-2">
|
||||||
|
<slot />
|
||||||
|
</div>
|
||||||
|
<div v-if="$slots.search" class="w-full">
|
||||||
|
<slot name="search" />
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
// En-tête de contenu : titre (ou slot #title pour un titre riche) + slot d'actions + slot recherche.
|
||||||
|
defineProps<{ title?: string; subtitle?: string }>();
|
||||||
|
</script>
|
||||||
11
packages/web/src/components/layout/WsBanner.vue
Normal file
11
packages/web/src/components/layout/WsBanner.vue
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
<template>
|
||||||
|
<div class="border-b border-amber-900/50 bg-amber-950/80 px-4 py-1.5 text-center text-xs text-amber-300">
|
||||||
|
{{ t('ws.reconnecting') }}
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
</script>
|
||||||
33
packages/web/src/components/settings/ServerRow.vue
Normal file
33
packages/web/src/components/settings/ServerRow.vue
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
<template>
|
||||||
|
<!-- Ligne de config serveur en lecture seule : label + valeur (+ flag CLI) + copier. -->
|
||||||
|
<div class="flex flex-wrap items-center gap-x-3 gap-y-0.5 py-2">
|
||||||
|
<dt class="w-40 shrink-0 text-sm text-zinc-400">{{ label }}</dt>
|
||||||
|
<dd class="flex min-w-0 flex-1 items-center gap-2">
|
||||||
|
<span :class="['min-w-0 flex-1 break-all text-sm text-zinc-200', mono ? 'font-mono text-xs' : '']">{{ value }}</span>
|
||||||
|
<span v-if="flag" class="hidden shrink-0 font-mono text-[11px] text-zinc-600 sm:inline" :title="t('settings.flagHint', { flag })">{{ flag }}</span>
|
||||||
|
<BaseButton size="sm" variant="ghost" icon-only :icon="copied ? Check : Copy" :aria-label="t('settings.copy')" @click="copy" />
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref } from 'vue';
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { Check, Copy } from '@lucide/vue';
|
||||||
|
import BaseButton from '../ui/BaseButton.vue';
|
||||||
|
|
||||||
|
const props = defineProps<{ label: string; value: string; flag?: string; mono?: boolean }>();
|
||||||
|
const { t } = useI18n();
|
||||||
|
|
||||||
|
const copied = ref(false);
|
||||||
|
// Auto-contenu : on ne confirme (✓) qu'après la résolution réelle de l'écriture presse-papiers.
|
||||||
|
async function copy(): Promise<void> {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(props.value);
|
||||||
|
copied.value = true;
|
||||||
|
setTimeout(() => (copied.value = false), 1500);
|
||||||
|
} catch {
|
||||||
|
/* presse-papiers indisponible (http non sécurisé) : silencieux */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
35
packages/web/src/components/ui/BaseBadge.vue
Normal file
35
packages/web/src/components/ui/BaseBadge.vue
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
<template>
|
||||||
|
<span class="badge" :class="toneClass">
|
||||||
|
<span v-if="dot" class="inline-block h-1.5 w-1.5 rounded-full" :class="dotClass" />
|
||||||
|
<slot />
|
||||||
|
</span>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
// Pastille d'état : centralise les paires bg/text répétées (zinc/emerald/amber/sky/red).
|
||||||
|
import { computed } from 'vue';
|
||||||
|
|
||||||
|
type Tone = 'zinc' | 'emerald' | 'amber' | 'sky' | 'red';
|
||||||
|
|
||||||
|
const props = withDefaults(defineProps<{ tone?: Tone; dot?: boolean; pulse?: boolean }>(), {
|
||||||
|
tone: 'zinc',
|
||||||
|
});
|
||||||
|
|
||||||
|
const TONES: Record<Tone, string> = {
|
||||||
|
zinc: 'bg-zinc-800 text-zinc-400',
|
||||||
|
emerald: 'bg-emerald-950 text-emerald-400',
|
||||||
|
amber: 'bg-amber-950 text-amber-300',
|
||||||
|
sky: 'bg-sky-950 text-sky-300',
|
||||||
|
red: 'bg-red-950 text-red-400',
|
||||||
|
};
|
||||||
|
const DOTS: Record<Tone, string> = {
|
||||||
|
zinc: 'bg-zinc-500',
|
||||||
|
emerald: 'bg-emerald-400',
|
||||||
|
amber: 'bg-amber-300',
|
||||||
|
sky: 'bg-sky-300',
|
||||||
|
red: 'bg-red-400',
|
||||||
|
};
|
||||||
|
|
||||||
|
const toneClass = computed(() => TONES[props.tone]);
|
||||||
|
const dotClass = computed(() => [DOTS[props.tone], props.pulse ? 'animate-pulse' : '']);
|
||||||
|
</script>
|
||||||
80
packages/web/src/components/ui/BaseButton.vue
Normal file
80
packages/web/src/components/ui/BaseButton.vue
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
<template>
|
||||||
|
<component
|
||||||
|
:is="tag"
|
||||||
|
:class="classes"
|
||||||
|
v-bind="mergedAttrs"
|
||||||
|
@click="onClick"
|
||||||
|
>
|
||||||
|
<Loader2 v-if="loading" :size="iconSize" class="animate-spin" />
|
||||||
|
<component :is="icon" v-else-if="icon" :size="iconSize" />
|
||||||
|
<slot />
|
||||||
|
</component>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
// Bouton unifié : variantes + tailles + état loading + anneau de focus cohérent.
|
||||||
|
// Rend un <RouterLink> quand `to` est fourni (et actionnable), sinon un <button>.
|
||||||
|
import { computed, useAttrs, type Component } from 'vue';
|
||||||
|
import { RouterLink, type RouteLocationRaw } from 'vue-router';
|
||||||
|
import { Loader2 } from '@lucide/vue';
|
||||||
|
|
||||||
|
defineOptions({ inheritAttrs: false });
|
||||||
|
|
||||||
|
const props = withDefaults(
|
||||||
|
defineProps<{
|
||||||
|
variant?: 'primary' | 'secondary' | 'ghost' | 'danger';
|
||||||
|
size?: 'sm' | 'md';
|
||||||
|
loading?: boolean;
|
||||||
|
disabled?: boolean;
|
||||||
|
iconOnly?: boolean;
|
||||||
|
icon?: Component;
|
||||||
|
to?: RouteLocationRaw;
|
||||||
|
type?: 'button' | 'submit';
|
||||||
|
}>(),
|
||||||
|
{ variant: 'secondary', size: 'md', type: 'button' },
|
||||||
|
);
|
||||||
|
|
||||||
|
const emit = defineEmits<{ click: [MouseEvent] }>();
|
||||||
|
const attrs = useAttrs();
|
||||||
|
|
||||||
|
const isDisabled = computed(() => props.disabled || props.loading);
|
||||||
|
const asLink = computed(() => props.to !== undefined && !isDisabled.value);
|
||||||
|
const tag = computed(() => (asLink.value ? RouterLink : 'button'));
|
||||||
|
const iconSize = computed(() => (props.size === 'sm' ? 15 : 16));
|
||||||
|
|
||||||
|
const BASE =
|
||||||
|
'inline-flex items-center justify-center gap-1.5 rounded-lg font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-offset-zinc-950 disabled:cursor-not-allowed disabled:opacity-50';
|
||||||
|
|
||||||
|
const VARIANTS: Record<NonNullable<typeof props.variant>, string> = {
|
||||||
|
primary: 'bg-emerald-600 text-white hover:bg-emerald-500 focus-visible:ring-emerald-500/70',
|
||||||
|
secondary: 'border border-zinc-700 bg-zinc-800 text-zinc-200 hover:bg-zinc-700 focus-visible:ring-emerald-500/70',
|
||||||
|
ghost: 'text-zinc-300 hover:bg-zinc-800/60 focus-visible:ring-emerald-500/70',
|
||||||
|
danger: 'border border-red-900 bg-red-950 text-red-300 hover:bg-red-900 focus-visible:ring-red-500/70',
|
||||||
|
};
|
||||||
|
|
||||||
|
const SIZES = {
|
||||||
|
sm: { text: 'h-8 px-2.5 text-xs', icon: 'h-8 w-8' },
|
||||||
|
md: { text: 'h-9 px-3 text-sm', icon: 'h-9 w-9' },
|
||||||
|
};
|
||||||
|
|
||||||
|
const classes = computed(() => {
|
||||||
|
const size = SIZES[props.size];
|
||||||
|
return [BASE, VARIANTS[props.variant], props.iconOnly ? size.icon : size.text];
|
||||||
|
});
|
||||||
|
|
||||||
|
// Attributs natifs propres au tag rendu (button : type/disabled/aria-busy ; lien : to).
|
||||||
|
const nativeProps = computed(() => {
|
||||||
|
if (asLink.value) return { to: props.to };
|
||||||
|
return { type: props.type, disabled: isDisabled.value, 'aria-busy': props.loading || undefined };
|
||||||
|
});
|
||||||
|
// useAttrs (class/aria-label/etc. du parent) + props natifs.
|
||||||
|
const mergedAttrs = computed(() => ({ ...attrs, ...nativeProps.value }));
|
||||||
|
|
||||||
|
function onClick(e: MouseEvent): void {
|
||||||
|
if (isDisabled.value) {
|
||||||
|
e.preventDefault();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
emit('click', e);
|
||||||
|
}
|
||||||
|
</script>
|
||||||
17
packages/web/src/components/ui/EmptyState.vue
Normal file
17
packages/web/src/components/ui/EmptyState.vue
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
<template>
|
||||||
|
<div class="flex flex-col items-center gap-2 rounded-xl border border-dashed border-zinc-800 px-6 py-10 text-center">
|
||||||
|
<component :is="icon" v-if="icon" :size="32" class="text-zinc-600" :stroke-width="1.5" />
|
||||||
|
<p class="text-sm font-medium text-zinc-300">{{ title }}</p>
|
||||||
|
<p v-if="hint" class="max-w-sm text-xs text-zinc-500">{{ hint }}</p>
|
||||||
|
<div v-if="$slots.action" class="mt-1">
|
||||||
|
<slot name="action" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
// État vide soigné (icône + titre + indice + CTA) — remplace les <p text-zinc-500> plats.
|
||||||
|
import type { Component } from 'vue';
|
||||||
|
|
||||||
|
defineProps<{ icon?: Component; title: string; hint?: string }>();
|
||||||
|
</script>
|
||||||
31
packages/web/src/components/ui/GiteaIcon.vue
Normal file
31
packages/web/src/components/ui/GiteaIcon.vue
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
<template>
|
||||||
|
<!-- Lucide n'a pas d'icône Gitea : motif « tasse de thé fumante » (git + tea), trait cohérent
|
||||||
|
avec les icônes Lucide (currentColor, coins arrondis). stroke-width hérité via fallthrough. -->
|
||||||
|
<svg
|
||||||
|
:width="size"
|
||||||
|
:height="size"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
stroke-width="1.75"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<!-- vapeur = mini-branche git -->
|
||||||
|
<path d="M9 5.5V4" />
|
||||||
|
<path d="M13 5.5V3" />
|
||||||
|
<circle cx="9" cy="3" r="0.6" fill="currentColor" stroke="none" />
|
||||||
|
<circle cx="13" cy="2.5" r="0.6" fill="currentColor" stroke="none" />
|
||||||
|
<!-- tasse -->
|
||||||
|
<path d="M4 8h12v4a5 5 0 0 1-5 5H9a5 5 0 0 1-5-5z" />
|
||||||
|
<!-- anse -->
|
||||||
|
<path d="M16 9h1.5a2.5 2.5 0 0 1 0 5H16" />
|
||||||
|
<!-- soucoupe -->
|
||||||
|
<path d="M5 20h10" />
|
||||||
|
</svg>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
withDefaults(defineProps<{ size?: number }>(), { size: 18 });
|
||||||
|
</script>
|
||||||
30
packages/web/src/components/ui/SegmentedControl.vue
Normal file
30
packages/web/src/components/ui/SegmentedControl.vue
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
<template>
|
||||||
|
<div class="inline-flex rounded-lg border border-zinc-800 bg-zinc-950/40 p-0.5">
|
||||||
|
<button
|
||||||
|
v-for="opt in options"
|
||||||
|
:key="opt.value"
|
||||||
|
type="button"
|
||||||
|
class="inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-500/70"
|
||||||
|
:class="opt.value === modelValue ? 'bg-zinc-800 text-zinc-100' : 'text-zinc-400 hover:text-zinc-200'"
|
||||||
|
:aria-pressed="opt.value === modelValue"
|
||||||
|
@click="emit('update:modelValue', opt.value)"
|
||||||
|
>
|
||||||
|
<component :is="opt.icon" v-if="opt.icon" :size="15" />
|
||||||
|
<span v-if="opt.label">{{ opt.label }}</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
// Bascule segmentée (ex. liste / grille) : remplace le toggle bricolé inline.
|
||||||
|
import type { Component } from 'vue';
|
||||||
|
|
||||||
|
export interface SegmentOption {
|
||||||
|
value: string;
|
||||||
|
label?: string;
|
||||||
|
icon?: Component;
|
||||||
|
}
|
||||||
|
|
||||||
|
defineProps<{ modelValue: string; options: SegmentOption[] }>();
|
||||||
|
const emit = defineEmits<{ 'update:modelValue': [string] }>();
|
||||||
|
</script>
|
||||||
15
packages/web/src/components/ui/SkeletonRow.vue
Normal file
15
packages/web/src/components/ui/SkeletonRow.vue
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
<div
|
||||||
|
v-for="i in count"
|
||||||
|
:key="i"
|
||||||
|
class="animate-pulse rounded-xl border border-zinc-800 bg-zinc-900/40 motion-reduce:animate-none"
|
||||||
|
:style="{ height: `${height}px` }"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
// Squelette de chargement : garde la hauteur stable, évite le layout shift.
|
||||||
|
withDefaults(defineProps<{ count?: number; height?: number }>(), { count: 3, height: 64 });
|
||||||
|
</script>
|
||||||
161
packages/web/src/composables/listDefs.ts
Normal file
161
packages/web/src/composables/listDefs.ts
Normal file
@@ -0,0 +1,161 @@
|
|||||||
|
import type { GroupSummary, RepoSummary, SessionSummary, WorktreeSummary } from '@arboretum/shared';
|
||||||
|
import type { FilterDef, SortDef } from './useListControls';
|
||||||
|
|
||||||
|
// ---- état canonique d'une session (réutilise la logique de SessionStateBadge) ----
|
||||||
|
type CanonState = 'waiting' | 'busy' | 'idle' | null;
|
||||||
|
const canonState = (s: SessionSummary): CanonState => (s.activity ?? s.registryStatus ?? null);
|
||||||
|
|
||||||
|
/** Rang d'actionnabilité : waiting(0) < busy(1) < idle(2) < live(3) < resumable(4) < exited(5). */
|
||||||
|
export function sessionStateRank(s: SessionSummary): number {
|
||||||
|
if (s.live) {
|
||||||
|
const st = canonState(s);
|
||||||
|
return st === 'waiting' ? 0 : st === 'busy' ? 1 : st === 'idle' ? 2 : 3;
|
||||||
|
}
|
||||||
|
return s.resumable ? 4 : 5;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Une session correspond-elle à une valeur d'état de filtre ? */
|
||||||
|
function sessionMatchesState(s: SessionSummary, value: string): boolean {
|
||||||
|
switch (value) {
|
||||||
|
case 'live':
|
||||||
|
return s.live;
|
||||||
|
case 'waiting':
|
||||||
|
case 'busy':
|
||||||
|
case 'idle':
|
||||||
|
return s.live && canonState(s) === value;
|
||||||
|
case 'exited':
|
||||||
|
return !s.live && !s.resumable;
|
||||||
|
case 'resumable':
|
||||||
|
return !s.live && s.resumable;
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- sessions ----
|
||||||
|
export function sessionSorts(): SortDef<SessionSummary>[] {
|
||||||
|
return [
|
||||||
|
{ key: 'state', labelKey: 'sort.session.state', compare: (a, b) => sessionStateRank(a) - sessionStateRank(b), defaultDir: 'asc' },
|
||||||
|
{ key: 'recent', labelKey: 'sort.session.recent', compare: (a, b) => a.createdAt.localeCompare(b.createdAt), defaultDir: 'desc' },
|
||||||
|
{ key: 'clients', labelKey: 'sort.session.clients', compare: (a, b) => a.clients - b.clients, defaultDir: 'desc' },
|
||||||
|
{ key: 'cwd', labelKey: 'sort.session.cwd', compare: (a, b) => a.cwd.localeCompare(b.cwd), defaultDir: 'asc' },
|
||||||
|
{ key: 'command', labelKey: 'sort.session.command', compare: (a, b) => a.command.localeCompare(b.command), defaultDir: 'asc' },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sessionFilters(repos: readonly RepoSummary[]): FilterDef<SessionSummary>[] {
|
||||||
|
const STATES = ['live', 'waiting', 'busy', 'idle', 'exited', 'resumable'];
|
||||||
|
// corrélation session→repo par préfixe de chemin (cwd sous repo.path).
|
||||||
|
const repoPaths = repos.map((r) => ({ id: r.id, path: r.path }));
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
key: 'state',
|
||||||
|
labelKey: 'filter.state.label',
|
||||||
|
options: STATES.map((v) => ({ value: v, labelKey: `filter.state.${v}` })),
|
||||||
|
predicate: (s, active) => [...active].some((v) => sessionMatchesState(s, v)),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'command',
|
||||||
|
labelKey: 'filter.command.label',
|
||||||
|
options: [
|
||||||
|
{ value: 'claude', label: 'claude' },
|
||||||
|
{ value: 'bash', label: 'bash' },
|
||||||
|
],
|
||||||
|
predicate: (s, active) => active.has(s.command),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'source',
|
||||||
|
labelKey: 'filter.source.label',
|
||||||
|
options: [
|
||||||
|
{ value: 'managed', labelKey: 'filter.source.managed' },
|
||||||
|
{ value: 'discovered', labelKey: 'filter.source.discovered' },
|
||||||
|
],
|
||||||
|
predicate: (s, active) => active.has(s.source),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'repo',
|
||||||
|
labelKey: 'filter.repo.label',
|
||||||
|
options: repos.map((r) => ({ value: r.id, label: r.label })),
|
||||||
|
predicate: (s, active) =>
|
||||||
|
repoPaths.some((r) => active.has(r.id) && (s.cwd === r.path || s.cwd.startsWith(r.path + '/'))),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- worktrees ----
|
||||||
|
function worktreeActivityRank(w: WorktreeSummary): number {
|
||||||
|
if (w.sessions.length === 0) return 99;
|
||||||
|
return Math.min(...w.sessions.map(sessionStateRank));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function worktreeSorts(): SortDef<WorktreeSummary>[] {
|
||||||
|
return [
|
||||||
|
{ key: 'main', labelKey: 'sort.worktree.main', compare: (a, b) => Number(b.isMain) - Number(a.isMain), defaultDir: 'asc' },
|
||||||
|
{ key: 'branch', labelKey: 'sort.worktree.branch', compare: (a, b) => (a.branch ?? '').localeCompare(b.branch ?? ''), defaultDir: 'asc' },
|
||||||
|
{ key: 'dirty', labelKey: 'sort.worktree.dirty', compare: (a, b) => a.git.dirtyCount - b.git.dirtyCount, defaultDir: 'desc' },
|
||||||
|
{ key: 'ahead', labelKey: 'sort.worktree.ahead', compare: (a, b) => a.git.ahead - b.git.ahead, defaultDir: 'desc' },
|
||||||
|
{ key: 'behind', labelKey: 'sort.worktree.behind', compare: (a, b) => a.git.behind - b.git.behind, defaultDir: 'desc' },
|
||||||
|
{ key: 'activity', labelKey: 'sort.worktree.activity', compare: (a, b) => worktreeActivityRank(a) - worktreeActivityRank(b), defaultDir: 'asc' },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function worktreeFilters(): FilterDef<WorktreeSummary>[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
key: 'dirtiness',
|
||||||
|
labelKey: 'filter.worktree.dirtiness',
|
||||||
|
options: [
|
||||||
|
{ value: 'dirty', labelKey: 'filter.worktree.dirty' },
|
||||||
|
{ value: 'clean', labelKey: 'filter.worktree.clean' },
|
||||||
|
],
|
||||||
|
predicate: (w, active) =>
|
||||||
|
(active.has('dirty') && w.git.dirtyCount > 0) || (active.has('clean') && w.git.dirtyCount === 0),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'session',
|
||||||
|
labelKey: 'filter.worktree.session',
|
||||||
|
options: [
|
||||||
|
{ value: 'with', labelKey: 'filter.worktree.with' },
|
||||||
|
{ value: 'without', labelKey: 'filter.worktree.without' },
|
||||||
|
],
|
||||||
|
predicate: (w, active) =>
|
||||||
|
(active.has('with') && w.sessions.length > 0) || (active.has('without') && w.sessions.length === 0),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'flags',
|
||||||
|
labelKey: 'filter.worktree.flags',
|
||||||
|
options: [
|
||||||
|
{ value: 'locked', labelKey: 'filter.worktree.locked' },
|
||||||
|
{ value: 'prunable', labelKey: 'filter.worktree.prunable' },
|
||||||
|
],
|
||||||
|
predicate: (w, active) => (active.has('locked') && w.locked) || (active.has('prunable') && w.prunable),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- repos ----
|
||||||
|
export interface RepoSortCtx {
|
||||||
|
worktreeCount: (repoId: string) => number;
|
||||||
|
activeCount: (repoId: string) => number;
|
||||||
|
}
|
||||||
|
export function repoSorts(ctx: RepoSortCtx): SortDef<RepoSummary>[] {
|
||||||
|
return [
|
||||||
|
{ key: 'label', labelKey: 'sort.repo.label', compare: (a, b) => a.label.localeCompare(b.label), defaultDir: 'asc' },
|
||||||
|
{ key: 'created', labelKey: 'sort.repo.created', compare: (a, b) => a.createdAt.localeCompare(b.createdAt), defaultDir: 'desc' },
|
||||||
|
{ key: 'worktrees', labelKey: 'sort.repo.worktrees', compare: (a, b) => ctx.worktreeCount(a.id) - ctx.worktreeCount(b.id), defaultDir: 'desc' },
|
||||||
|
{ key: 'activity', labelKey: 'sort.repo.activity', compare: (a, b) => ctx.activeCount(a.id) - ctx.activeCount(b.id), defaultDir: 'desc' },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- groupes ----
|
||||||
|
export interface GroupSortCtx {
|
||||||
|
activeCount: (groupId: string) => number;
|
||||||
|
}
|
||||||
|
export function groupSorts(ctx: GroupSortCtx): SortDef<GroupSummary>[] {
|
||||||
|
return [
|
||||||
|
{ key: 'label', labelKey: 'sort.group.label', compare: (a, b) => a.label.localeCompare(b.label), defaultDir: 'asc' },
|
||||||
|
{ key: 'created', labelKey: 'sort.group.created', compare: (a, b) => a.createdAt.localeCompare(b.createdAt), defaultDir: 'desc' },
|
||||||
|
{ key: 'repos', labelKey: 'sort.group.repos', compare: (a, b) => a.repoIds.length - b.repoIds.length, defaultDir: 'desc' },
|
||||||
|
{ key: 'activeSessions', labelKey: 'sort.group.activeSessions', compare: (a, b) => ctx.activeCount(a.id) - ctx.activeCount(b.id), defaultDir: 'desc' },
|
||||||
|
];
|
||||||
|
}
|
||||||
20
packages/web/src/composables/useCommandPalette.ts
Normal file
20
packages/web/src/composables/useCommandPalette.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import { ref } from 'vue';
|
||||||
|
|
||||||
|
// Singleton module-level : l'ouverture est pilotée par le raccourci global ⌘K et par
|
||||||
|
// d'éventuels boutons (ex. sidebar). Un seul CommandPalette est monté dans App.vue.
|
||||||
|
const open = ref(false);
|
||||||
|
|
||||||
|
export function useCommandPalette() {
|
||||||
|
return {
|
||||||
|
open,
|
||||||
|
toggle: (): void => {
|
||||||
|
open.value = !open.value;
|
||||||
|
},
|
||||||
|
show: (): void => {
|
||||||
|
open.value = true;
|
||||||
|
},
|
||||||
|
close: (): void => {
|
||||||
|
open.value = false;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
22
packages/web/src/composables/useDebouncedRef.ts
Normal file
22
packages/web/src/composables/useDebouncedRef.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import { ref, watch, onUnmounted, getCurrentInstance, type Ref } from 'vue';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renvoie un miroir débouncé d'un ref source. Le ref source reste instantané (idéal pour un
|
||||||
|
* v-model d'input) ; le miroir ne se met à jour qu'après `delay` ms de stabilité — c'est lui
|
||||||
|
* que le pipeline de tri/filtre consomme, pour ne pas recalculer à chaque frappe.
|
||||||
|
*/
|
||||||
|
export function useDebouncedRef<T>(source: Ref<T>, delay = 150): Ref<T> {
|
||||||
|
const debounced = ref(source.value) as Ref<T>;
|
||||||
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
|
||||||
|
watch(source, (v) => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
timer = setTimeout(() => {
|
||||||
|
debounced.value = v;
|
||||||
|
}, delay);
|
||||||
|
});
|
||||||
|
|
||||||
|
if (getCurrentInstance()) onUnmounted(() => clearTimeout(timer));
|
||||||
|
|
||||||
|
return debounced;
|
||||||
|
}
|
||||||
290
packages/web/src/composables/useListControls.ts
Normal file
290
packages/web/src/composables/useListControls.ts
Normal file
@@ -0,0 +1,290 @@
|
|||||||
|
import { computed, ref, watch, type ComputedRef, type Ref } from 'vue';
|
||||||
|
import { useRoute, useRouter } from 'vue-router';
|
||||||
|
import { useDebouncedRef } from './useDebouncedRef';
|
||||||
|
|
||||||
|
export type SortDir = 'asc' | 'desc';
|
||||||
|
|
||||||
|
/** Comparateur d'une clé de tri, toujours écrit en ASC ; la direction est appliquée par le composable. */
|
||||||
|
export interface SortDef<T> {
|
||||||
|
key: string;
|
||||||
|
labelKey: string;
|
||||||
|
compare: (a: T, b: T) => number;
|
||||||
|
defaultDir?: SortDir;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FilterOption {
|
||||||
|
value: string;
|
||||||
|
labelKey?: string;
|
||||||
|
label?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Un filtre activable par une ou plusieurs valeurs (OR intra-filtre, AND inter-filtres). */
|
||||||
|
export interface FilterDef<T> {
|
||||||
|
key: string;
|
||||||
|
labelKey: string;
|
||||||
|
options: FilterOption[];
|
||||||
|
predicate: (item: T, active: Set<string>) => boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ListControlsOptions<T> {
|
||||||
|
source: () => readonly T[];
|
||||||
|
sorts: SortDef<T>[];
|
||||||
|
/** Tableau statique ou getter (pour des options dérivées d'un store chargé en asynchrone). */
|
||||||
|
filters?: FilterDef<T>[] | (() => FilterDef<T>[]);
|
||||||
|
searchAccessor?: (item: T) => string;
|
||||||
|
defaultSortKey?: string;
|
||||||
|
defaultPageSize?: number; // 0 = tout afficher
|
||||||
|
/** Si fourni, l'état est synchronisé dans l'URL sous des params préfixés (liens partageables). */
|
||||||
|
urlKey?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sous-ensemble consommé par ListToolbar (sans pagination) — implémentable aussi par un store partagé. */
|
||||||
|
export interface ListToolbarControls<T> {
|
||||||
|
search: Ref<string>;
|
||||||
|
sortKey: Ref<string>;
|
||||||
|
sortDir: Ref<SortDir>;
|
||||||
|
filters: Ref<Record<string, Set<string>>>;
|
||||||
|
total: ComputedRef<number>;
|
||||||
|
activeFilterCount: ComputedRef<number>;
|
||||||
|
setSearch(v: string): void;
|
||||||
|
setSort(key: string): void;
|
||||||
|
toggleFilter(key: string, value: string): void;
|
||||||
|
clearAll(): void;
|
||||||
|
sortDefs: SortDef<T>[];
|
||||||
|
filterDefs: ComputedRef<FilterDef<T>[]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ListControls<T> extends ListToolbarControls<T> {
|
||||||
|
page: Ref<number>;
|
||||||
|
pageSize: Ref<number>;
|
||||||
|
processed: ComputedRef<T[]>;
|
||||||
|
pageCount: ComputedRef<number>;
|
||||||
|
setPage(p: number): void;
|
||||||
|
setPageSize(n: number): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useListControls<T>(opts: ListControlsOptions<T>): ListControls<T> {
|
||||||
|
const sortDefs = opts.sorts;
|
||||||
|
const filterDefs = computed<FilterDef<T>[]>(() =>
|
||||||
|
typeof opts.filters === 'function' ? opts.filters() : (opts.filters ?? []),
|
||||||
|
);
|
||||||
|
const defaultSortKey = opts.defaultSortKey ?? sortDefs[0]?.key ?? '';
|
||||||
|
const defaultPageSize = opts.defaultPageSize ?? 25;
|
||||||
|
|
||||||
|
const search = ref('');
|
||||||
|
const sortKey = ref(defaultSortKey);
|
||||||
|
const sortDir = ref<SortDir>(sortDefs.find((s) => s.key === defaultSortKey)?.defaultDir ?? 'asc');
|
||||||
|
const filters = ref<Record<string, Set<string>>>({});
|
||||||
|
const page = ref(1);
|
||||||
|
const pageSize = ref(defaultPageSize);
|
||||||
|
|
||||||
|
const debouncedSearch = useDebouncedRef(search, 150);
|
||||||
|
|
||||||
|
// ---- pipeline : filtres → recherche → tri → pagination (computed purs, aucune mutation de store) ----
|
||||||
|
const filtered = computed<T[]>(() => {
|
||||||
|
let items = [...opts.source()];
|
||||||
|
for (const def of filterDefs.value) {
|
||||||
|
const active = filters.value[def.key];
|
||||||
|
if (active && active.size > 0) items = items.filter((it) => def.predicate(it, active));
|
||||||
|
}
|
||||||
|
const q = debouncedSearch.value.trim().toLowerCase();
|
||||||
|
if (q && opts.searchAccessor) {
|
||||||
|
items = items.filter((it) => opts.searchAccessor!(it).toLowerCase().includes(q));
|
||||||
|
}
|
||||||
|
return items;
|
||||||
|
});
|
||||||
|
|
||||||
|
const sorted = computed<T[]>(() => {
|
||||||
|
const def = sortDefs.find((s) => s.key === sortKey.value) ?? sortDefs[0];
|
||||||
|
if (!def) return filtered.value;
|
||||||
|
const dir = sortDir.value === 'desc' ? -1 : 1;
|
||||||
|
return [...filtered.value].sort((a, b) => def.compare(a, b) * dir);
|
||||||
|
});
|
||||||
|
|
||||||
|
const total = computed(() => filtered.value.length);
|
||||||
|
const pageCount = computed(() => (pageSize.value === 0 ? 1 : Math.max(1, Math.ceil(total.value / pageSize.value))));
|
||||||
|
const processed = computed<T[]>(() => {
|
||||||
|
if (pageSize.value === 0) return sorted.value;
|
||||||
|
const start = (page.value - 1) * pageSize.value;
|
||||||
|
return sorted.value.slice(start, start + pageSize.value);
|
||||||
|
});
|
||||||
|
const activeFilterCount = computed(() =>
|
||||||
|
Object.values(filters.value).reduce((n, set) => n + set.size, 0),
|
||||||
|
);
|
||||||
|
|
||||||
|
// ramène la page dans les bornes quand un filtre réduit le total.
|
||||||
|
watch(pageCount, (count) => {
|
||||||
|
if (page.value > count) page.value = count;
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- setters (toute action utilisateur revient page 1) ----
|
||||||
|
function setSort(key: string): void {
|
||||||
|
if (sortKey.value === key) {
|
||||||
|
sortDir.value = sortDir.value === 'asc' ? 'desc' : 'asc';
|
||||||
|
} else {
|
||||||
|
sortKey.value = key;
|
||||||
|
sortDir.value = sortDefs.find((s) => s.key === key)?.defaultDir ?? 'asc';
|
||||||
|
}
|
||||||
|
page.value = 1;
|
||||||
|
}
|
||||||
|
function toggleFilter(key: string, value: string): void {
|
||||||
|
const next = { ...filters.value };
|
||||||
|
const set = new Set(next[key] ?? []);
|
||||||
|
if (set.has(value)) set.delete(value);
|
||||||
|
else set.add(value);
|
||||||
|
if (set.size === 0) delete next[key];
|
||||||
|
else next[key] = set;
|
||||||
|
filters.value = next;
|
||||||
|
page.value = 1;
|
||||||
|
}
|
||||||
|
function clearAll(): void {
|
||||||
|
search.value = '';
|
||||||
|
filters.value = {};
|
||||||
|
page.value = 1;
|
||||||
|
}
|
||||||
|
function setPage(p: number): void {
|
||||||
|
page.value = Math.min(Math.max(1, p), pageCount.value);
|
||||||
|
}
|
||||||
|
function setPageSize(n: number): void {
|
||||||
|
pageSize.value = n;
|
||||||
|
page.value = 1;
|
||||||
|
}
|
||||||
|
// saisie utilisateur : retour page 1 de façon synchrone (l'hydratation URL écrit search.value
|
||||||
|
// directement, sans passer par ici → ne réinitialise pas une page fournie par l'URL).
|
||||||
|
function setSearch(v: string): void {
|
||||||
|
search.value = v;
|
||||||
|
page.value = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// suspend l'écriture état→URL pendant l'application des params depuis l'URL.
|
||||||
|
let hydrating = false;
|
||||||
|
|
||||||
|
// ---- synchro URL (optionnelle) ----
|
||||||
|
if (opts.urlKey) {
|
||||||
|
const k = opts.urlKey;
|
||||||
|
const P = {
|
||||||
|
q: `${k}_q`,
|
||||||
|
sort: `${k}_sort`,
|
||||||
|
dir: `${k}_dir`,
|
||||||
|
filter: `${k}_filter`,
|
||||||
|
page: `${k}_page`,
|
||||||
|
size: `${k}_size`,
|
||||||
|
};
|
||||||
|
const route = useRoute();
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
// sérialise les filtres de façon canonique : key:v1,v2;key2:v3 (clés/valeurs triées).
|
||||||
|
const serializeFilters = (f: Record<string, Set<string>>): string =>
|
||||||
|
Object.entries(f)
|
||||||
|
.filter(([, set]) => set.size > 0)
|
||||||
|
.sort(([a], [b]) => a.localeCompare(b))
|
||||||
|
.map(([key, set]) => `${key}:${[...set].sort().join(',')}`)
|
||||||
|
.join(';');
|
||||||
|
|
||||||
|
// params possédés par cette liste (non-défauts uniquement → URLs propres).
|
||||||
|
function ownedParams(): Record<string, string> {
|
||||||
|
const out: Record<string, string> = {};
|
||||||
|
if (search.value.trim()) out[P.q] = search.value.trim();
|
||||||
|
if (sortKey.value !== defaultSortKey) out[P.sort] = sortKey.value;
|
||||||
|
const baseDir = sortDefs.find((s) => s.key === sortKey.value)?.defaultDir ?? 'asc';
|
||||||
|
if (sortDir.value !== baseDir) out[P.dir] = sortDir.value;
|
||||||
|
const fser = serializeFilters(filters.value);
|
||||||
|
if (fser) out[P.filter] = fser;
|
||||||
|
if (page.value > 1) out[P.page] = String(page.value);
|
||||||
|
if (pageSize.value !== defaultPageSize) out[P.size] = String(pageSize.value);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
const canonical = (o: Record<string, string>): string =>
|
||||||
|
Object.keys(o).sort().map((key) => `${key}=${o[key]}`).join('&');
|
||||||
|
|
||||||
|
function readOwned(query: Record<string, unknown>): Record<string, string> {
|
||||||
|
const out: Record<string, string> = {};
|
||||||
|
for (const key of Object.values(P)) {
|
||||||
|
const v = query[key];
|
||||||
|
if (typeof v === 'string' && v) out[key] = v;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyFromQuery(query: Record<string, unknown>): void {
|
||||||
|
hydrating = true;
|
||||||
|
const str = (key: string): string => (typeof query[key] === 'string' ? (query[key] as string) : '');
|
||||||
|
search.value = str(P.q);
|
||||||
|
sortKey.value = sortDefs.some((s) => s.key === str(P.sort)) ? str(P.sort) : defaultSortKey;
|
||||||
|
const dir = str(P.dir);
|
||||||
|
sortDir.value = dir === 'asc' || dir === 'desc' ? dir : sortDefs.find((s) => s.key === sortKey.value)?.defaultDir ?? 'asc';
|
||||||
|
const parsedFilters: Record<string, Set<string>> = {};
|
||||||
|
const fser = str(P.filter);
|
||||||
|
if (fser) {
|
||||||
|
for (const part of fser.split(';')) {
|
||||||
|
const [fk, vals] = part.split(':');
|
||||||
|
if (!fk || !vals) continue;
|
||||||
|
const def = filterDefs.value.find((d) => d.key === fk);
|
||||||
|
if (!def) continue;
|
||||||
|
const allowed = new Set(def.options.map((o) => o.value));
|
||||||
|
const set = new Set(vals.split(',').filter((v) => allowed.has(v)));
|
||||||
|
if (set.size) parsedFilters[fk] = set;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
filters.value = parsedFilters;
|
||||||
|
const sz = Number(str(P.size));
|
||||||
|
pageSize.value = Number.isFinite(sz) && sz >= 0 ? sz : defaultPageSize;
|
||||||
|
const pg = Number(str(P.page));
|
||||||
|
page.value = Number.isFinite(pg) && pg >= 1 ? pg : 1;
|
||||||
|
// libère le garde après le flush des watchers déclenchés par les assignations ci-dessus.
|
||||||
|
void Promise.resolve().then(() => {
|
||||||
|
hydrating = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// URL → état (init + navigations arrière/avant) ; ignore si déjà en phase avec l'état courant.
|
||||||
|
watch(
|
||||||
|
() => route.query,
|
||||||
|
(query) => {
|
||||||
|
if (canonical(readOwned(query)) === canonical(ownedParams())) return;
|
||||||
|
applyFromQuery(query);
|
||||||
|
},
|
||||||
|
{ immediate: true, deep: true },
|
||||||
|
);
|
||||||
|
|
||||||
|
// état → URL : remplace (pas d'entrée d'historique), préserve les params non possédés.
|
||||||
|
watch(
|
||||||
|
[search, sortKey, sortDir, filters, page, pageSize],
|
||||||
|
() => {
|
||||||
|
if (hydrating) return;
|
||||||
|
const owned = ownedParams();
|
||||||
|
const preserved: Record<string, unknown> = {};
|
||||||
|
for (const [key, v] of Object.entries(route.query)) {
|
||||||
|
if (!Object.values(P).includes(key)) preserved[key] = v;
|
||||||
|
}
|
||||||
|
const next = { ...preserved, ...owned };
|
||||||
|
// no-op si la query possédée est inchangée (anti-boucle / anti-spam).
|
||||||
|
if (canonical(readOwned(route.query)) === canonical(owned)) return;
|
||||||
|
void router.replace({ query: next as Record<string, string> });
|
||||||
|
},
|
||||||
|
{ deep: true },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
search,
|
||||||
|
sortKey,
|
||||||
|
sortDir,
|
||||||
|
filters,
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
processed,
|
||||||
|
total,
|
||||||
|
pageCount,
|
||||||
|
activeFilterCount,
|
||||||
|
setSearch,
|
||||||
|
setSort,
|
||||||
|
toggleFilter,
|
||||||
|
clearAll,
|
||||||
|
setPage,
|
||||||
|
setPageSize,
|
||||||
|
sortDefs,
|
||||||
|
filterDefs,
|
||||||
|
};
|
||||||
|
}
|
||||||
50
packages/web/src/composables/useNav.ts
Normal file
50
packages/web/src/composables/useNav.ts
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
import { computed, type Component } from 'vue';
|
||||||
|
import { useRoute, type RouteLocationRaw } from 'vue-router';
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { Boxes, Coffee, GitBranch, LifeBuoy, Settings, TerminalSquare } from '@lucide/vue';
|
||||||
|
import { useSessionsStore } from '../stores/sessions';
|
||||||
|
import GiteaIcon from '../components/ui/GiteaIcon.vue';
|
||||||
|
import { BUYMEACOFFEE_URL, REPO_SOURCE_URL } from '../lib/constants';
|
||||||
|
|
||||||
|
export interface NavEntry {
|
||||||
|
key: string;
|
||||||
|
/** route interne (exclusif avec `href`). */
|
||||||
|
to?: RouteLocationRaw;
|
||||||
|
/** lien externe ouvert dans un nouvel onglet (exclusif avec `to`). */
|
||||||
|
href?: string;
|
||||||
|
icon: Component;
|
||||||
|
label: string;
|
||||||
|
match: string[]; // noms de routes considérés actifs pour cet item
|
||||||
|
badge: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Définition unique de la navigation, partagée par la sidebar et la barre d'onglets. */
|
||||||
|
export function useNav() {
|
||||||
|
const { t } = useI18n();
|
||||||
|
const route = useRoute();
|
||||||
|
const sessions = useSessionsStore();
|
||||||
|
|
||||||
|
// sessions vivantes bloquées sur un dialogue (le cœur de la supervision mobile).
|
||||||
|
const waitingCount = computed(
|
||||||
|
() => sessions.sessions.filter((s) => s.live && s.activity === 'waiting').length,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Onglets principaux : barre du bas mobile + haut de sidebar.
|
||||||
|
const primary = computed<NavEntry[]>(() => [
|
||||||
|
{ key: 'worktrees', to: { name: 'dashboard' }, icon: GitBranch, label: t('nav.worktrees'), match: ['dashboard'], badge: 0 },
|
||||||
|
{ key: 'sessions', to: { name: 'sessions' }, icon: TerminalSquare, label: t('nav.sessions'), match: ['sessions', 'session'], badge: waitingCount.value },
|
||||||
|
{ key: 'groups', to: { name: 'groups' }, icon: Boxes, label: t('nav.groups'), match: ['groups', 'group'], badge: 0 },
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Onglets secondaires : réglages, aide, et lien externe « Code source » (en dur, toujours présent).
|
||||||
|
const secondary = computed<NavEntry[]>(() => [
|
||||||
|
{ key: 'settings', to: { name: 'settings' }, icon: Settings, label: t('nav.settings'), match: ['settings'], badge: 0 },
|
||||||
|
{ key: 'help', to: { name: 'help' }, icon: LifeBuoy, label: t('nav.help'), match: ['help'], badge: 0 },
|
||||||
|
{ key: 'gitea', href: REPO_SOURCE_URL, icon: GiteaIcon, label: t('nav.gitea'), match: [], badge: 0 },
|
||||||
|
{ key: 'buymeacoffee', href: BUYMEACOFFEE_URL, icon: Coffee, label: t('nav.buymeacoffee'), match: [], badge: 0 },
|
||||||
|
]);
|
||||||
|
|
||||||
|
const isActive = (match: string[]): boolean => match.includes(String(route.name));
|
||||||
|
|
||||||
|
return { primary, secondary, isActive, waitingCount };
|
||||||
|
}
|
||||||
19
packages/web/src/composables/useSession.ts
Normal file
19
packages/web/src/composables/useSession.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { useRouter } from 'vue-router';
|
||||||
|
import { useAuthStore } from '../stores/auth';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Déconnexion centralisée. `auth.logout()` ferme la WebSocket ; la redirection vers /login
|
||||||
|
* démonte l'AppShell, qui stoppe alors les abonnements temps réel (source unique). Corrige
|
||||||
|
* l'incohérence où certaines vues ne stoppaient pas tous les flux au logout.
|
||||||
|
*/
|
||||||
|
export function useSession() {
|
||||||
|
const auth = useAuthStore();
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
async function logout(): Promise<void> {
|
||||||
|
await auth.logout();
|
||||||
|
await router.replace({ name: 'login' });
|
||||||
|
}
|
||||||
|
|
||||||
|
return { logout };
|
||||||
|
}
|
||||||
103
packages/web/src/composables/useWorktreeView.ts
Normal file
103
packages/web/src/composables/useWorktreeView.ts
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
import { computed, ref } from 'vue';
|
||||||
|
import type { WorktreeSummary } from '@arboretum/shared';
|
||||||
|
import type { ListToolbarControls, SortDir } from './useListControls';
|
||||||
|
import { useDebouncedRef } from './useDebouncedRef';
|
||||||
|
import { worktreeSorts, worktreeFilters } from './listDefs';
|
||||||
|
import { useWorktreesStore } from '../stores/worktrees';
|
||||||
|
|
||||||
|
export interface WorktreeView extends ListToolbarControls<WorktreeSummary> {
|
||||||
|
apply: (list: readonly WorktreeSummary[]) => WorktreeSummary[];
|
||||||
|
isActive: () => boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* État de tri/filtre/recherche des worktrees, PARTAGÉ entre toutes les RepoSection du dashboard
|
||||||
|
* (une seule toolbar pilote toutes les sections). Singleton module-level — et non un store Pinia,
|
||||||
|
* car Pinia déballe les refs, ce que ListToolbar attend justement comme refs. Pas de pagination
|
||||||
|
* (liste groupée par repo) ; `apply()` filtre+trie le sous-ensemble d'un repo donné.
|
||||||
|
*/
|
||||||
|
let instance: WorktreeView | null = null;
|
||||||
|
|
||||||
|
function create(): WorktreeView {
|
||||||
|
const search = ref('');
|
||||||
|
const debounced = useDebouncedRef(search, 150);
|
||||||
|
const sortKey = ref('main');
|
||||||
|
const sortDir = ref<SortDir>('asc');
|
||||||
|
const filters = ref<Record<string, Set<string>>>({});
|
||||||
|
|
||||||
|
const sortDefs = worktreeSorts();
|
||||||
|
const filterDefList = worktreeFilters();
|
||||||
|
const filterDefs = computed(() => filterDefList);
|
||||||
|
|
||||||
|
const accessor = (w: WorktreeSummary): string => `${w.branch ?? ''} ${w.path}`.toLowerCase();
|
||||||
|
|
||||||
|
function apply(list: readonly WorktreeSummary[]): WorktreeSummary[] {
|
||||||
|
let items = [...list];
|
||||||
|
for (const def of filterDefList) {
|
||||||
|
const active = filters.value[def.key];
|
||||||
|
if (active && active.size > 0) items = items.filter((it) => def.predicate(it, active));
|
||||||
|
}
|
||||||
|
const q = debounced.value.trim().toLowerCase();
|
||||||
|
if (q) items = items.filter((w) => accessor(w).includes(q));
|
||||||
|
const def = sortDefs.find((s) => s.key === sortKey.value) ?? sortDefs[0];
|
||||||
|
if (def) {
|
||||||
|
const dir = sortDir.value === 'desc' ? -1 : 1;
|
||||||
|
items.sort((a, b) => def.compare(a, b) * dir);
|
||||||
|
}
|
||||||
|
return items;
|
||||||
|
}
|
||||||
|
|
||||||
|
const isActive = (): boolean => debounced.value.trim() !== '' || Object.keys(filters.value).length > 0;
|
||||||
|
|
||||||
|
// total (compteur de la toolbar) : worktrees correspondants, tous repos confondus.
|
||||||
|
const total = computed(() => apply(useWorktreesStore().worktrees).length);
|
||||||
|
const activeFilterCount = computed(() =>
|
||||||
|
Object.values(filters.value).reduce((n, set) => n + set.size, 0),
|
||||||
|
);
|
||||||
|
|
||||||
|
function setSearch(v: string): void {
|
||||||
|
search.value = v;
|
||||||
|
}
|
||||||
|
function setSort(key: string): void {
|
||||||
|
if (sortKey.value === key) sortDir.value = sortDir.value === 'asc' ? 'desc' : 'asc';
|
||||||
|
else {
|
||||||
|
sortKey.value = key;
|
||||||
|
sortDir.value = sortDefs.find((s) => s.key === key)?.defaultDir ?? 'asc';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function toggleFilter(key: string, value: string): void {
|
||||||
|
const next = { ...filters.value };
|
||||||
|
const set = new Set(next[key] ?? []);
|
||||||
|
if (set.has(value)) set.delete(value);
|
||||||
|
else set.add(value);
|
||||||
|
if (set.size === 0) delete next[key];
|
||||||
|
else next[key] = set;
|
||||||
|
filters.value = next;
|
||||||
|
}
|
||||||
|
function clearAll(): void {
|
||||||
|
search.value = '';
|
||||||
|
filters.value = {};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
search,
|
||||||
|
sortKey,
|
||||||
|
sortDir,
|
||||||
|
filters,
|
||||||
|
total,
|
||||||
|
activeFilterCount,
|
||||||
|
setSearch,
|
||||||
|
setSort,
|
||||||
|
toggleFilter,
|
||||||
|
clearAll,
|
||||||
|
sortDefs,
|
||||||
|
filterDefs,
|
||||||
|
apply,
|
||||||
|
isActive,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useWorktreeView(): WorktreeView {
|
||||||
|
instance ??= create();
|
||||||
|
return instance;
|
||||||
|
}
|
||||||
@@ -5,6 +5,12 @@ export default {
|
|||||||
cancel: 'Cancel',
|
cancel: 'Cancel',
|
||||||
logout: 'Log out',
|
logout: 'Log out',
|
||||||
language: 'Language',
|
language: 'Language',
|
||||||
|
refresh: 'Refresh',
|
||||||
|
back: 'Back',
|
||||||
|
search: 'Search',
|
||||||
|
settings: 'Settings',
|
||||||
|
close: 'Close',
|
||||||
|
retry: 'Retry',
|
||||||
},
|
},
|
||||||
login: {
|
login: {
|
||||||
title: 'Sign in with your access token',
|
title: 'Sign in with your access token',
|
||||||
@@ -116,8 +122,13 @@ export default {
|
|||||||
remove: 'Remove',
|
remove: 'Remove',
|
||||||
pathLabel: 'Repository path',
|
pathLabel: 'Repository path',
|
||||||
pathPlaceholder: '/absolute/path/to/repo',
|
pathPlaceholder: '/absolute/path/to/repo',
|
||||||
empty: 'No repository registered yet — add one above.',
|
empty: 'No repository registered yet — add one above, or scan for repos.',
|
||||||
invalid: 'unavailable',
|
invalid: 'unavailable',
|
||||||
|
scan: 'Scan',
|
||||||
|
scanResult: 'No new repository found | 1 new repository added | {n} new repositories added',
|
||||||
|
hide: 'Hide',
|
||||||
|
show: 'Show',
|
||||||
|
showHidden: 'Show hidden ({n})',
|
||||||
},
|
},
|
||||||
worktrees: {
|
worktrees: {
|
||||||
new: 'New worktree',
|
new: 'New worktree',
|
||||||
@@ -163,4 +174,206 @@ export default {
|
|||||||
ws: {
|
ws: {
|
||||||
reconnecting: 'Connection lost — reconnecting…',
|
reconnecting: 'Connection lost — reconnecting…',
|
||||||
},
|
},
|
||||||
|
nav: {
|
||||||
|
worktrees: 'Worktrees',
|
||||||
|
sessions: 'Sessions',
|
||||||
|
groups: 'Groups',
|
||||||
|
settings: 'Settings',
|
||||||
|
help: 'Help',
|
||||||
|
more: 'More',
|
||||||
|
gitea: 'Source code',
|
||||||
|
buymeacoffee: 'Buy me a coffee',
|
||||||
|
waiting: 'waiting',
|
||||||
|
},
|
||||||
|
controls: {
|
||||||
|
searchPlaceholder: 'Search…',
|
||||||
|
results: 'no result | 1 result | {n} results',
|
||||||
|
sortBy: 'Sort by',
|
||||||
|
filters: 'Filters',
|
||||||
|
clearAll: 'Clear',
|
||||||
|
},
|
||||||
|
sort: {
|
||||||
|
asc: 'Ascending',
|
||||||
|
desc: 'Descending',
|
||||||
|
session: {
|
||||||
|
state: 'State',
|
||||||
|
recent: 'Most recent',
|
||||||
|
clients: 'Clients',
|
||||||
|
cwd: 'Directory',
|
||||||
|
command: 'Command',
|
||||||
|
},
|
||||||
|
worktree: {
|
||||||
|
main: 'Main first',
|
||||||
|
branch: 'Branch',
|
||||||
|
dirty: 'Changes',
|
||||||
|
ahead: 'Ahead',
|
||||||
|
behind: 'Behind',
|
||||||
|
activity: 'Activity',
|
||||||
|
},
|
||||||
|
repo: {
|
||||||
|
label: 'Name',
|
||||||
|
created: 'Created',
|
||||||
|
worktrees: 'Worktrees',
|
||||||
|
activity: 'Activity',
|
||||||
|
},
|
||||||
|
group: {
|
||||||
|
label: 'Name',
|
||||||
|
created: 'Created',
|
||||||
|
repos: 'Repositories',
|
||||||
|
activeSessions: 'Active sessions',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
filter: {
|
||||||
|
state: {
|
||||||
|
label: 'State',
|
||||||
|
live: 'Live',
|
||||||
|
waiting: 'Waiting',
|
||||||
|
busy: 'Busy',
|
||||||
|
idle: 'Idle',
|
||||||
|
exited: 'Exited',
|
||||||
|
resumable: 'Resumable',
|
||||||
|
},
|
||||||
|
command: {
|
||||||
|
label: 'Command',
|
||||||
|
},
|
||||||
|
source: {
|
||||||
|
label: 'Source',
|
||||||
|
managed: 'Managed',
|
||||||
|
discovered: 'Discovered',
|
||||||
|
},
|
||||||
|
repo: {
|
||||||
|
label: 'Repository',
|
||||||
|
},
|
||||||
|
worktree: {
|
||||||
|
dirtiness: 'Changes',
|
||||||
|
dirty: 'Dirty',
|
||||||
|
clean: 'Clean',
|
||||||
|
session: 'Session',
|
||||||
|
with: 'With session',
|
||||||
|
without: 'Without session',
|
||||||
|
flags: 'Flags',
|
||||||
|
locked: 'Locked',
|
||||||
|
prunable: 'Prunable',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
pagination: {
|
||||||
|
prev: 'Previous',
|
||||||
|
next: 'Next',
|
||||||
|
pageOf: 'Page {page} / {pageCount}',
|
||||||
|
perPage: 'Per page',
|
||||||
|
all: 'All',
|
||||||
|
},
|
||||||
|
palette: {
|
||||||
|
placeholder: 'Jump to repo, worktree, session, group…',
|
||||||
|
empty: 'No match',
|
||||||
|
hint: '↑↓ navigate · ↵ open · esc close',
|
||||||
|
types: {
|
||||||
|
repo: 'Repo',
|
||||||
|
worktree: 'Worktree',
|
||||||
|
session: 'Session',
|
||||||
|
group: 'Group',
|
||||||
|
action: 'Action',
|
||||||
|
},
|
||||||
|
actions: {
|
||||||
|
newSession: 'New session',
|
||||||
|
addRepo: 'Add repo',
|
||||||
|
newGroup: 'New group',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
toast: {
|
||||||
|
sessionCreated: 'Session started',
|
||||||
|
sessionKilled: 'Session killed',
|
||||||
|
sessionResumed: 'Session resumed',
|
||||||
|
sessionForked: 'Session forked',
|
||||||
|
repoAdded: 'Repository added',
|
||||||
|
repoRemoved: 'Repository removed',
|
||||||
|
worktreeCreated: 'Worktree created',
|
||||||
|
worktreeDeleted: 'Worktree deleted',
|
||||||
|
pruned: 'Worktrees pruned',
|
||||||
|
groupCreated: 'Group created',
|
||||||
|
groupUpdated: 'Group updated',
|
||||||
|
groupDeleted: 'Group deleted',
|
||||||
|
genericError: 'Something went wrong',
|
||||||
|
dismiss: 'Dismiss',
|
||||||
|
},
|
||||||
|
attention: {
|
||||||
|
title: 'Needs attention',
|
||||||
|
count: 'no session waiting | 1 session waiting | {n} sessions waiting',
|
||||||
|
empty: 'Nothing waiting',
|
||||||
|
},
|
||||||
|
settings: {
|
||||||
|
title: 'Settings',
|
||||||
|
// Préférences
|
||||||
|
preferences: 'Preferences',
|
||||||
|
preferencesHint: 'These apply to this browser only.',
|
||||||
|
language: 'Language',
|
||||||
|
notifications: 'Notifications',
|
||||||
|
notificationsEnabled: 'Enabled — you will be notified when a session needs input.',
|
||||||
|
notificationsDisabled: 'Disabled.',
|
||||||
|
enableNotifications: 'Enable notifications',
|
||||||
|
disableNotifications: 'Disable notifications',
|
||||||
|
testNotification: 'Send a test',
|
||||||
|
testSent: 'Test notification sent',
|
||||||
|
pushUnsupported: 'Push needs HTTPS (e.g. Tailscale Serve); on iOS, install the app to your home screen first.',
|
||||||
|
// Accès & sécurité
|
||||||
|
security: 'Access & security',
|
||||||
|
securityHint: 'Tokens grant full access to this server. Create one per device and revoke any you no longer use.',
|
||||||
|
tokens: 'Access tokens',
|
||||||
|
newTokenLabel: 'Label',
|
||||||
|
newTokenPlaceholder: 'e.g. phone, laptop',
|
||||||
|
createToken: 'Create token',
|
||||||
|
tokenCreated: 'Token created',
|
||||||
|
copyTokenHint: 'Copy this token now — for security it will never be shown again.',
|
||||||
|
copy: 'Copy',
|
||||||
|
copied: 'Copied',
|
||||||
|
current: 'current',
|
||||||
|
created: 'Created {date}',
|
||||||
|
lastUsed: 'last used {date}',
|
||||||
|
neverUsed: 'never used',
|
||||||
|
revoke: 'Revoke',
|
||||||
|
confirmRevoke: 'Confirm revoke',
|
||||||
|
tokenRevoked: 'Token revoked',
|
||||||
|
lastTokenError: 'You cannot revoke the last active token — create another one first.',
|
||||||
|
save: 'Save',
|
||||||
|
saved: 'Saved',
|
||||||
|
// Sécurité & conformité
|
||||||
|
compliance: 'Security & compliance',
|
||||||
|
complianceHint: 'Export or erase the data tied to your token (GDPR), and review the audit log of sensitive operations.',
|
||||||
|
exportData: 'Export my data',
|
||||||
|
refreshAudit: 'Audit log',
|
||||||
|
deleteData: 'Erase my data',
|
||||||
|
deleteConfirm: 'Erase the data tied to your token (push subscriptions) and revoke this token? This cannot be undone.',
|
||||||
|
deleteDone: 'Your data has been erased.',
|
||||||
|
// Découverte des dépôts
|
||||||
|
discovery: 'Repository discovery',
|
||||||
|
discoveryHint: 'Arboretum scans these folders for git repositories and registers them automatically. Hidden repos are kept and never re-added.',
|
||||||
|
scanRoots: 'Scan folders',
|
||||||
|
scanRootsEmpty: 'No folder configured — your home directory is used by default.',
|
||||||
|
addRoot: 'Add folder',
|
||||||
|
removeRoot: 'Remove',
|
||||||
|
scanInterval: 'Re-scan interval (minutes)',
|
||||||
|
scanIntervalHint: '0 disables periodic scanning. Changes apply on the next daemon restart.',
|
||||||
|
// Serveur (lecture seule)
|
||||||
|
server: 'Server',
|
||||||
|
serverHint: 'Set at startup via CLI flags — changing them requires restarting the daemon.',
|
||||||
|
version: 'Version',
|
||||||
|
port: 'Port',
|
||||||
|
bind: 'Bind address',
|
||||||
|
allowedOrigins: 'Allowed origins',
|
||||||
|
dataDir: 'Data directory',
|
||||||
|
vapidPublicKey: 'VAPID public key',
|
||||||
|
vapidContact: 'VAPID contact',
|
||||||
|
none: 'none',
|
||||||
|
flagHint: 'CLI flag: {flag}',
|
||||||
|
// Support
|
||||||
|
support: 'Support',
|
||||||
|
supportHint: 'Arboretum is a free, self-funded side project. If it saves you time, you can support its development.',
|
||||||
|
supportCta: 'Buy me a coffee',
|
||||||
|
},
|
||||||
|
help: {
|
||||||
|
title: 'Help',
|
||||||
|
intro: 'Everything Arboretum can do, and how to use it.',
|
||||||
|
searchPlaceholder: 'Search help…',
|
||||||
|
noMatch: 'No matching topic',
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -7,6 +7,12 @@ const fr: typeof en = {
|
|||||||
cancel: 'Annuler',
|
cancel: 'Annuler',
|
||||||
logout: 'Se déconnecter',
|
logout: 'Se déconnecter',
|
||||||
language: 'Langue',
|
language: 'Langue',
|
||||||
|
refresh: 'Rafraîchir',
|
||||||
|
back: 'Retour',
|
||||||
|
search: 'Rechercher',
|
||||||
|
settings: 'Réglages',
|
||||||
|
close: 'Fermer',
|
||||||
|
retry: 'Réessayer',
|
||||||
},
|
},
|
||||||
login: {
|
login: {
|
||||||
title: 'Connectez-vous avec votre jeton d’accès',
|
title: 'Connectez-vous avec votre jeton d’accès',
|
||||||
@@ -118,8 +124,13 @@ const fr: typeof en = {
|
|||||||
remove: 'Retirer',
|
remove: 'Retirer',
|
||||||
pathLabel: 'Chemin du dépôt',
|
pathLabel: 'Chemin du dépôt',
|
||||||
pathPlaceholder: '/chemin/absolu/du/repo',
|
pathPlaceholder: '/chemin/absolu/du/repo',
|
||||||
empty: 'Aucun dépôt enregistré — ajoutez-en un ci-dessus.',
|
empty: 'Aucun dépôt enregistré — ajoutez-en un ci-dessus, ou lancez un scan.',
|
||||||
invalid: 'indisponible',
|
invalid: 'indisponible',
|
||||||
|
scan: 'Scanner',
|
||||||
|
scanResult: 'Aucun nouveau dépôt trouvé | 1 nouveau dépôt ajouté | {n} nouveaux dépôts ajoutés',
|
||||||
|
hide: 'Masquer',
|
||||||
|
show: 'Afficher',
|
||||||
|
showHidden: 'Afficher les masqués ({n})',
|
||||||
},
|
},
|
||||||
worktrees: {
|
worktrees: {
|
||||||
new: 'Nouveau worktree',
|
new: 'Nouveau worktree',
|
||||||
@@ -166,6 +177,208 @@ const fr: typeof en = {
|
|||||||
ws: {
|
ws: {
|
||||||
reconnecting: 'Connexion perdue — reconnexion…',
|
reconnecting: 'Connexion perdue — reconnexion…',
|
||||||
},
|
},
|
||||||
|
nav: {
|
||||||
|
worktrees: 'Worktrees',
|
||||||
|
sessions: 'Sessions',
|
||||||
|
groups: 'Groupes',
|
||||||
|
settings: 'Réglages',
|
||||||
|
help: 'Aide',
|
||||||
|
more: 'Plus',
|
||||||
|
gitea: 'Code source',
|
||||||
|
buymeacoffee: 'Offrez-moi un café',
|
||||||
|
waiting: 'en attente',
|
||||||
|
},
|
||||||
|
controls: {
|
||||||
|
searchPlaceholder: 'Rechercher…',
|
||||||
|
results: 'aucun résultat | 1 résultat | {n} résultats',
|
||||||
|
sortBy: 'Trier par',
|
||||||
|
filters: 'Filtres',
|
||||||
|
clearAll: 'Effacer',
|
||||||
|
},
|
||||||
|
sort: {
|
||||||
|
asc: 'Croissant',
|
||||||
|
desc: 'Décroissant',
|
||||||
|
session: {
|
||||||
|
state: 'État',
|
||||||
|
recent: 'Plus récentes',
|
||||||
|
clients: 'Clients',
|
||||||
|
cwd: 'Répertoire',
|
||||||
|
command: 'Commande',
|
||||||
|
},
|
||||||
|
worktree: {
|
||||||
|
main: 'Principal d’abord',
|
||||||
|
branch: 'Branche',
|
||||||
|
dirty: 'Modifications',
|
||||||
|
ahead: 'En avance',
|
||||||
|
behind: 'En retard',
|
||||||
|
activity: 'Activité',
|
||||||
|
},
|
||||||
|
repo: {
|
||||||
|
label: 'Nom',
|
||||||
|
created: 'Créé le',
|
||||||
|
worktrees: 'Worktrees',
|
||||||
|
activity: 'Activité',
|
||||||
|
},
|
||||||
|
group: {
|
||||||
|
label: 'Nom',
|
||||||
|
created: 'Créé le',
|
||||||
|
repos: 'Dépôts',
|
||||||
|
activeSessions: 'Sessions actives',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
filter: {
|
||||||
|
state: {
|
||||||
|
label: 'État',
|
||||||
|
live: 'Active',
|
||||||
|
waiting: 'En attente',
|
||||||
|
busy: 'Occupée',
|
||||||
|
idle: 'Au repos',
|
||||||
|
exited: 'Terminée',
|
||||||
|
resumable: 'Reprenable',
|
||||||
|
},
|
||||||
|
command: {
|
||||||
|
label: 'Commande',
|
||||||
|
},
|
||||||
|
source: {
|
||||||
|
label: 'Source',
|
||||||
|
managed: 'Gérée',
|
||||||
|
discovered: 'Découverte',
|
||||||
|
},
|
||||||
|
repo: {
|
||||||
|
label: 'Dépôt',
|
||||||
|
},
|
||||||
|
worktree: {
|
||||||
|
dirtiness: 'Modifications',
|
||||||
|
dirty: 'Modifié',
|
||||||
|
clean: 'Propre',
|
||||||
|
session: 'Session',
|
||||||
|
with: 'Avec session',
|
||||||
|
without: 'Sans session',
|
||||||
|
flags: 'Drapeaux',
|
||||||
|
locked: 'Verrouillé',
|
||||||
|
prunable: 'Élaguable',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
pagination: {
|
||||||
|
prev: 'Précédent',
|
||||||
|
next: 'Suivant',
|
||||||
|
pageOf: 'Page {page} / {pageCount}',
|
||||||
|
perPage: 'Par page',
|
||||||
|
all: 'Tout',
|
||||||
|
},
|
||||||
|
palette: {
|
||||||
|
placeholder: 'Aller à un dépôt, worktree, session, groupe…',
|
||||||
|
empty: 'Aucun résultat',
|
||||||
|
hint: '↑↓ naviguer · ↵ ouvrir · échap fermer',
|
||||||
|
types: {
|
||||||
|
repo: 'Dépôt',
|
||||||
|
worktree: 'Worktree',
|
||||||
|
session: 'Session',
|
||||||
|
group: 'Groupe',
|
||||||
|
action: 'Action',
|
||||||
|
},
|
||||||
|
actions: {
|
||||||
|
newSession: 'Nouvelle session',
|
||||||
|
addRepo: 'Ajouter un dépôt',
|
||||||
|
newGroup: 'Nouveau groupe',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
toast: {
|
||||||
|
sessionCreated: 'Session démarrée',
|
||||||
|
sessionKilled: 'Session tuée',
|
||||||
|
sessionResumed: 'Session reprise',
|
||||||
|
sessionForked: 'Session dupliquée',
|
||||||
|
repoAdded: 'Dépôt ajouté',
|
||||||
|
repoRemoved: 'Dépôt retiré',
|
||||||
|
worktreeCreated: 'Worktree créé',
|
||||||
|
worktreeDeleted: 'Worktree supprimé',
|
||||||
|
pruned: 'Worktrees élagués',
|
||||||
|
groupCreated: 'Groupe créé',
|
||||||
|
groupUpdated: 'Groupe mis à jour',
|
||||||
|
groupDeleted: 'Groupe supprimé',
|
||||||
|
genericError: 'Une erreur est survenue',
|
||||||
|
dismiss: 'Fermer',
|
||||||
|
},
|
||||||
|
attention: {
|
||||||
|
title: 'À traiter',
|
||||||
|
count: 'aucune session en attente | 1 session en attente | {n} sessions en attente',
|
||||||
|
empty: 'Rien à traiter',
|
||||||
|
},
|
||||||
|
settings: {
|
||||||
|
title: 'Réglages',
|
||||||
|
// Préférences
|
||||||
|
preferences: 'Préférences',
|
||||||
|
preferencesHint: 'Ces réglages ne s’appliquent qu’à ce navigateur.',
|
||||||
|
language: 'Langue',
|
||||||
|
notifications: 'Notifications',
|
||||||
|
notificationsEnabled: 'Activées — vous serez notifié lorsqu’une session attend une réponse.',
|
||||||
|
notificationsDisabled: 'Désactivées.',
|
||||||
|
enableNotifications: 'Activer les notifications',
|
||||||
|
disableNotifications: 'Désactiver les notifications',
|
||||||
|
testNotification: 'Envoyer un test',
|
||||||
|
testSent: 'Notification de test envoyée',
|
||||||
|
pushUnsupported: 'Le push exige HTTPS (ex. Tailscale Serve) ; sur iOS, installez d’abord l’app sur l’écran d’accueil.',
|
||||||
|
// Accès & sécurité
|
||||||
|
security: 'Accès & sécurité',
|
||||||
|
securityHint: 'Les jetons donnent un accès complet à ce serveur. Créez-en un par appareil et révoquez ceux que vous n’utilisez plus.',
|
||||||
|
tokens: 'Jetons d’accès',
|
||||||
|
newTokenLabel: 'Libellé',
|
||||||
|
newTokenPlaceholder: 'ex. téléphone, portable',
|
||||||
|
createToken: 'Créer un jeton',
|
||||||
|
tokenCreated: 'Jeton créé',
|
||||||
|
copyTokenHint: 'Copiez ce jeton maintenant — par sécurité il ne sera plus jamais affiché.',
|
||||||
|
copy: 'Copier',
|
||||||
|
copied: 'Copié',
|
||||||
|
current: 'courant',
|
||||||
|
created: 'Créé le {date}',
|
||||||
|
lastUsed: 'utilisé le {date}',
|
||||||
|
neverUsed: 'jamais utilisé',
|
||||||
|
revoke: 'Révoquer',
|
||||||
|
confirmRevoke: 'Confirmer la révocation',
|
||||||
|
tokenRevoked: 'Jeton révoqué',
|
||||||
|
lastTokenError: 'Impossible de révoquer le dernier jeton actif — créez-en un autre d’abord.',
|
||||||
|
save: 'Enregistrer',
|
||||||
|
saved: 'Enregistré',
|
||||||
|
// Sécurité & conformité
|
||||||
|
compliance: 'Sécurité & conformité',
|
||||||
|
complianceHint: 'Exportez ou effacez les données liées à votre jeton (RGPD), et consultez le journal d’audit des opérations sensibles.',
|
||||||
|
exportData: 'Exporter mes données',
|
||||||
|
refreshAudit: 'Journal d’audit',
|
||||||
|
deleteData: 'Effacer mes données',
|
||||||
|
deleteConfirm: 'Effacer les données liées à votre jeton (abonnements push) et révoquer ce jeton ? Action irréversible.',
|
||||||
|
deleteDone: 'Vos données ont été effacées.',
|
||||||
|
// Découverte des dépôts
|
||||||
|
discovery: 'Découverte des dépôts',
|
||||||
|
discoveryHint: 'Arboretum scanne ces dossiers à la recherche de dépôts git et les enregistre automatiquement. Les dépôts masqués sont conservés et jamais ré-ajoutés.',
|
||||||
|
scanRoots: 'Dossiers à scanner',
|
||||||
|
scanRootsEmpty: 'Aucun dossier configuré — votre dossier personnel est utilisé par défaut.',
|
||||||
|
addRoot: 'Ajouter un dossier',
|
||||||
|
removeRoot: 'Retirer',
|
||||||
|
scanInterval: 'Intervalle de re-scan (minutes)',
|
||||||
|
scanIntervalHint: '0 désactive le scan périodique. Les changements prennent effet au prochain redémarrage du daemon.',
|
||||||
|
// Serveur (lecture seule)
|
||||||
|
server: 'Serveur',
|
||||||
|
serverHint: 'Définis au démarrage via des flags CLI — les modifier nécessite de redémarrer le daemon.',
|
||||||
|
version: 'Version',
|
||||||
|
port: 'Port',
|
||||||
|
bind: 'Adresse de liaison',
|
||||||
|
allowedOrigins: 'Origines autorisées',
|
||||||
|
dataDir: 'Répertoire de données',
|
||||||
|
vapidPublicKey: 'Clé publique VAPID',
|
||||||
|
vapidContact: 'Contact VAPID',
|
||||||
|
none: 'aucune',
|
||||||
|
flagHint: 'Flag CLI : {flag}',
|
||||||
|
// Soutien
|
||||||
|
support: 'Soutenir le projet',
|
||||||
|
supportHint: 'Arboretum est un projet personnel libre et auto-financé. S’il vous fait gagner du temps, vous pouvez soutenir son développement.',
|
||||||
|
supportCta: 'Offrez-moi un café',
|
||||||
|
},
|
||||||
|
help: {
|
||||||
|
title: 'Aide',
|
||||||
|
intro: 'Tout ce qu’Arboretum sait faire, et comment l’utiliser.',
|
||||||
|
searchPlaceholder: 'Rechercher dans l’aide…',
|
||||||
|
noMatch: 'Aucun sujet correspondant',
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export default fr;
|
export default fr;
|
||||||
|
|||||||
14
packages/web/src/lib/constants.ts
Normal file
14
packages/web/src/lib/constants.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
// Constantes globales du front.
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lien « Code source » affiché en permanence dans la navigation secondaire.
|
||||||
|
* En dur (pas un réglage) : pointe vers le dépôt source d'Arboretum, identique pour
|
||||||
|
* tous les utilisateurs de la solution.
|
||||||
|
*/
|
||||||
|
export const REPO_SOURCE_URL = 'https://git.lidge.fr/johanleroy/arboretum';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lien « Buy me a coffee » affiché dans la navigation et la page Réglages.
|
||||||
|
* En dur (pas un réglage) : page de don personnelle, identique pour tous.
|
||||||
|
*/
|
||||||
|
export const BUYMEACOFFEE_URL = 'https://buymeacoffee.com/johanleroy';
|
||||||
@@ -1,15 +1,25 @@
|
|||||||
import { createRouter, createWebHistory } from 'vue-router';
|
import { createRouter, createWebHistory } from 'vue-router';
|
||||||
import { useAuthStore } from '../stores/auth';
|
import { useAuthStore } from '../stores/auth';
|
||||||
|
|
||||||
|
// Type du layout choisi par App.vue : 'bare' (login, sans coquille),
|
||||||
|
// 'shell' (sidebar + contenu centré), 'fullbleed' (terminal plein écran dans la coquille).
|
||||||
|
declare module 'vue-router' {
|
||||||
|
interface RouteMeta {
|
||||||
|
layout?: 'bare' | 'shell' | 'fullbleed';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export const router = createRouter({
|
export const router = createRouter({
|
||||||
history: createWebHistory(),
|
history: createWebHistory(),
|
||||||
routes: [
|
routes: [
|
||||||
{ path: '/login', name: 'login', component: () => import('../views/LoginView.vue') },
|
{ path: '/login', name: 'login', component: () => import('../views/LoginView.vue'), meta: { layout: 'bare' } },
|
||||||
{ path: '/', name: 'dashboard', component: () => import('../views/DashboardView.vue') },
|
{ path: '/', name: 'dashboard', component: () => import('../views/DashboardView.vue'), meta: { layout: 'shell' } },
|
||||||
{ path: '/sessions', name: 'sessions', component: () => import('../views/SessionsListView.vue') },
|
{ path: '/sessions', name: 'sessions', component: () => import('../views/SessionsListView.vue'), meta: { layout: 'shell' } },
|
||||||
{ path: '/sessions/:id', name: 'session', component: () => import('../views/SessionView.vue') },
|
{ path: '/sessions/:id', name: 'session', component: () => import('../views/SessionView.vue'), meta: { layout: 'fullbleed' } },
|
||||||
{ path: '/groups', name: 'groups', component: () => import('../views/GroupsListView.vue') },
|
{ path: '/groups', name: 'groups', component: () => import('../views/GroupsListView.vue'), meta: { layout: 'shell' } },
|
||||||
{ path: '/groups/:id', name: 'group', component: () => import('../views/GroupView.vue') },
|
{ path: '/groups/:id', name: 'group', component: () => import('../views/GroupView.vue'), meta: { layout: 'shell' } },
|
||||||
|
{ path: '/settings', name: 'settings', component: () => import('../views/SettingsView.vue'), meta: { layout: 'shell' } },
|
||||||
|
{ path: '/help', name: 'help', component: () => import('../views/HelpView.vue'), meta: { layout: 'shell' } },
|
||||||
{ path: '/:pathMatch(.*)*', redirect: '/' },
|
{ path: '/:pathMatch(.*)*', redirect: '/' },
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|||||||
36
packages/web/src/stores/settings.ts
Normal file
36
packages/web/src/stores/settings.ts
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
import { defineStore } from 'pinia';
|
||||||
|
import { ref } from 'vue';
|
||||||
|
import type { ServerInfo, SettingsResponse, UpdateSettingsRequest } from '@arboretum/shared';
|
||||||
|
import { api } from '../lib/api';
|
||||||
|
|
||||||
|
// Réglages serveur (découverte des dépôts, infos serveur).
|
||||||
|
// Les préférences purement client (langue) restent gérées par l'i18n/localStorage.
|
||||||
|
export const useSettingsStore = defineStore('settings', () => {
|
||||||
|
const server = ref<ServerInfo | null>(null);
|
||||||
|
const scanRoots = ref<string[]>([]);
|
||||||
|
const scanIntervalMin = ref(0);
|
||||||
|
const loaded = ref(false);
|
||||||
|
const saving = ref(false);
|
||||||
|
|
||||||
|
function apply(res: SettingsResponse): void {
|
||||||
|
server.value = res.server;
|
||||||
|
scanRoots.value = res.settings.scanRoots;
|
||||||
|
scanIntervalMin.value = res.settings.scanIntervalMin;
|
||||||
|
loaded.value = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetch(): Promise<void> {
|
||||||
|
apply(await api.get<SettingsResponse>('/api/v1/settings'));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function save(patch: UpdateSettingsRequest): Promise<void> {
|
||||||
|
saving.value = true;
|
||||||
|
try {
|
||||||
|
apply(await api.patch<SettingsResponse>('/api/v1/settings', patch));
|
||||||
|
} finally {
|
||||||
|
saving.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { server, scanRoots, scanIntervalMin, loaded, saving, fetch, save };
|
||||||
|
});
|
||||||
45
packages/web/src/stores/toasts.ts
Normal file
45
packages/web/src/stores/toasts.ts
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
import { defineStore } from 'pinia';
|
||||||
|
import { ref } from 'vue';
|
||||||
|
|
||||||
|
export type ToastKind = 'success' | 'error' | 'info';
|
||||||
|
|
||||||
|
export interface Toast {
|
||||||
|
id: number;
|
||||||
|
kind: ToastKind;
|
||||||
|
message: string;
|
||||||
|
timeout: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** File de notifications éphémères. Aucun couplage : les vues appellent success/error/info. */
|
||||||
|
export const useToastsStore = defineStore('toasts', () => {
|
||||||
|
const toasts = ref<Toast[]>([]);
|
||||||
|
let seq = 0;
|
||||||
|
const timers = new Map<number, ReturnType<typeof setTimeout>>();
|
||||||
|
|
||||||
|
function dismiss(id: number): void {
|
||||||
|
toasts.value = toasts.value.filter((t) => t.id !== id);
|
||||||
|
const timer = timers.get(id);
|
||||||
|
if (timer) {
|
||||||
|
clearTimeout(timer);
|
||||||
|
timers.delete(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function push(kind: ToastKind, message: string, timeout = 4000): number {
|
||||||
|
const id = ++seq;
|
||||||
|
toasts.value = [...toasts.value, { id, kind, message, timeout }];
|
||||||
|
if (timeout > 0) timers.set(id, setTimeout(() => dismiss(id), timeout));
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
const success = (message: string): number => push('success', message);
|
||||||
|
const info = (message: string): number => push('info', message);
|
||||||
|
|
||||||
|
/** Normalise n'importe quelle erreur (ApiError/Error/inconnu) en message lisible. Sticky par défaut. */
|
||||||
|
function error(err: unknown, timeout = 0): number {
|
||||||
|
const message = err instanceof Error ? err.message : String(err);
|
||||||
|
return push('error', message, timeout);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { toasts, push, success, info, error, dismiss };
|
||||||
|
});
|
||||||
@@ -3,6 +3,7 @@ import { ref } from 'vue';
|
|||||||
import type {
|
import type {
|
||||||
CreateWorktreeRequest,
|
CreateWorktreeRequest,
|
||||||
CreateWorktreeResponse,
|
CreateWorktreeResponse,
|
||||||
|
DiscoverReposResponse,
|
||||||
RepoResponse,
|
RepoResponse,
|
||||||
ReposListResponse,
|
ReposListResponse,
|
||||||
RepoSummary,
|
RepoSummary,
|
||||||
@@ -84,6 +85,19 @@ export const useWorktreesStore = defineStore('worktrees', () => {
|
|||||||
removeRepoLocal(id);
|
removeRepoLocal(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Masque/ré-affiche un repo (persiste `hidden` côté serveur ; émis aussi par WS). */
|
||||||
|
async function setHidden(id: string, hidden: boolean): Promise<void> {
|
||||||
|
const res = await api.patch<RepoResponse>(`/api/v1/repos/${id}`, { hidden });
|
||||||
|
upsertRepo(res.repo);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lance un scan de découverte ; les nouveaux repos arrivent par WS, on resynchronise par sûreté. */
|
||||||
|
async function discover(): Promise<DiscoverReposResponse> {
|
||||||
|
const res = await api.post<DiscoverReposResponse>('/api/v1/repos/discover');
|
||||||
|
await fetchAll();
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
async function createWorktree(repoId: string, req: CreateWorktreeRequest): Promise<CreateWorktreeResponse> {
|
async function createWorktree(repoId: string, req: CreateWorktreeRequest): Promise<CreateWorktreeResponse> {
|
||||||
const res = await api.post<CreateWorktreeResponse>(`/api/v1/repos/${repoId}/worktrees`, req);
|
const res = await api.post<CreateWorktreeResponse>(`/api/v1/repos/${repoId}/worktrees`, req);
|
||||||
upsertWorktree(res.worktree);
|
upsertWorktree(res.worktree);
|
||||||
@@ -117,6 +131,9 @@ export const useWorktreesStore = defineStore('worktrees', () => {
|
|||||||
fetchAll,
|
fetchAll,
|
||||||
addRepo,
|
addRepo,
|
||||||
removeRepo,
|
removeRepo,
|
||||||
|
setHidden,
|
||||||
|
discover,
|
||||||
|
refreshRepoWorktrees,
|
||||||
createWorktree,
|
createWorktree,
|
||||||
deleteWorktree,
|
deleteWorktree,
|
||||||
prune,
|
prune,
|
||||||
|
|||||||
@@ -1,5 +1,11 @@
|
|||||||
@import 'tailwindcss';
|
@import 'tailwindcss';
|
||||||
|
|
||||||
|
/* Tokens additifs (la palette zinc/emerald/amber/sky/red reste celle de Tailwind). */
|
||||||
|
@theme {
|
||||||
|
--shadow-card: 0 1px 2px 0 rgb(0 0 0 / 0.4);
|
||||||
|
--shadow-pop: 0 12px 32px -12px rgb(0 0 0 / 0.7);
|
||||||
|
}
|
||||||
|
|
||||||
html,
|
html,
|
||||||
body,
|
body,
|
||||||
#app {
|
#app {
|
||||||
@@ -12,20 +18,45 @@ body {
|
|||||||
-webkit-font-smoothing: antialiased;
|
-webkit-font-smoothing: antialiased;
|
||||||
}
|
}
|
||||||
|
|
||||||
@layer components {
|
@layer base {
|
||||||
.input {
|
/* Tailwind v4 ne met plus cursor:pointer sur les boutons → on le rétablit
|
||||||
@apply w-full rounded-md border border-zinc-700 bg-zinc-950 px-2.5 py-1.5 text-sm text-zinc-100 outline-none transition-colors placeholder:text-zinc-600 focus:border-zinc-400;
|
(sauf désactivés, qui gardent le curseur par défaut / not-allowed). */
|
||||||
}
|
button:not(:disabled),
|
||||||
.btn {
|
[role='button']:not([aria-disabled='true']) {
|
||||||
@apply inline-flex items-center justify-center gap-1.5 rounded-md border border-zinc-700 bg-zinc-800 px-3 py-1.5 text-sm font-medium text-zinc-200 transition-colors hover:bg-zinc-700 disabled:cursor-not-allowed disabled:opacity-50;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
.btn-primary {
|
}
|
||||||
@apply inline-flex items-center justify-center gap-1.5 rounded-md bg-emerald-600 px-3 py-1.5 text-sm font-medium text-white transition-colors hover:bg-emerald-500 disabled:cursor-not-allowed disabled:opacity-50;
|
|
||||||
}
|
@layer components {
|
||||||
.btn-danger {
|
/* Champs : rayon unifié + anneau de focus visible (absent auparavant). */
|
||||||
@apply inline-flex items-center justify-center gap-1.5 rounded-md border border-red-900 bg-red-950 px-3 py-1.5 text-sm font-medium text-red-300 transition-colors hover:bg-red-900 disabled:cursor-not-allowed disabled:opacity-50;
|
.input {
|
||||||
}
|
@apply w-full rounded-lg border border-zinc-700 bg-zinc-950 px-2.5 py-1.5 text-sm text-zinc-100 outline-none transition-colors placeholder:text-zinc-600 focus-visible:border-zinc-500 focus-visible:ring-2 focus-visible:ring-emerald-500/40;
|
||||||
.badge {
|
}
|
||||||
@apply inline-flex items-center rounded px-1.5 py-0.5 text-[11px] font-medium;
|
|
||||||
|
/* Boutons : socle CSS pour les usages hors composant (ex. RouterLink class="btn").
|
||||||
|
Le composant BaseButton réplique ces variantes et ajoute tailles / loading / focus. */
|
||||||
|
.btn {
|
||||||
|
@apply inline-flex items-center justify-center gap-1.5 rounded-lg border border-zinc-700 bg-zinc-800 px-3 py-1.5 text-sm font-medium text-zinc-200 transition-colors hover:bg-zinc-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-500/70 focus-visible:ring-offset-2 focus-visible:ring-offset-zinc-950 disabled:cursor-not-allowed disabled:opacity-50;
|
||||||
|
}
|
||||||
|
.btn-primary {
|
||||||
|
@apply inline-flex items-center justify-center gap-1.5 rounded-lg bg-emerald-600 px-3 py-1.5 text-sm font-medium text-white transition-colors hover:bg-emerald-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-500/70 focus-visible:ring-offset-2 focus-visible:ring-offset-zinc-950 disabled:cursor-not-allowed disabled:opacity-50;
|
||||||
|
}
|
||||||
|
.btn-danger {
|
||||||
|
@apply inline-flex items-center justify-center gap-1.5 rounded-lg border border-red-900 bg-red-950 px-3 py-1.5 text-sm font-medium text-red-300 transition-colors hover:bg-red-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-red-500/70 focus-visible:ring-offset-2 focus-visible:ring-offset-zinc-950 disabled:cursor-not-allowed disabled:opacity-50;
|
||||||
|
}
|
||||||
|
.btn-ghost {
|
||||||
|
@apply inline-flex items-center justify-center gap-1.5 rounded-lg px-3 py-1.5 text-sm font-medium text-zinc-300 transition-colors hover:bg-zinc-800/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-500/70 focus-visible:ring-offset-2 focus-visible:ring-offset-zinc-950 disabled:cursor-not-allowed disabled:opacity-50;
|
||||||
|
}
|
||||||
|
|
||||||
|
.badge {
|
||||||
|
@apply inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[11px] font-medium;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Cartes : factorise le motif répété dans les listes/sections/formulaires. */
|
||||||
|
.card {
|
||||||
|
@apply rounded-xl border border-zinc-800 bg-zinc-900/50 p-3;
|
||||||
|
}
|
||||||
|
.card-inset {
|
||||||
|
@apply rounded-lg border border-zinc-800 bg-zinc-950/40 p-2;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,38 +1,26 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="overflow-y-auto">
|
<PageHeader :title="t('nav.worktrees')">
|
||||||
<div class="mx-auto flex max-w-3xl flex-col gap-4 px-4 py-6">
|
<BaseButton variant="ghost" size="sm" :icon="ScanSearch" :loading="scanning" @click="onDiscover">
|
||||||
<header class="flex items-center gap-3">
|
{{ t('repos.scan') }}
|
||||||
<h1 class="text-lg font-semibold text-zinc-100">{{ t('dashboard.title') }}</h1>
|
</BaseButton>
|
||||||
<span v-if="auth.serverVersion" class="text-xs text-zinc-600">v{{ auth.serverVersion }}</span>
|
<BaseButton variant="ghost" size="sm" :icon="RefreshCw" :loading="store.loading" @click="refresh">
|
||||||
<div class="ml-auto flex items-center gap-2">
|
{{ t('common.refresh') }}
|
||||||
<RouterLink :to="{ name: 'groups' }" class="btn">{{ t('dashboard.groups') }}</RouterLink>
|
</BaseButton>
|
||||||
<RouterLink :to="{ name: 'sessions' }" class="btn">{{ t('dashboard.allSessions') }}</RouterLink>
|
</PageHeader>
|
||||||
<button class="btn" :disabled="store.loading" @click="store.fetchAll()">{{ t('sessions.refresh') }}</button>
|
|
||||||
<button
|
|
||||||
v-if="push.supported"
|
|
||||||
class="btn"
|
|
||||||
:class="push.enabled ? 'border-emerald-700 text-emerald-300' : ''"
|
|
||||||
:disabled="push.busy"
|
|
||||||
:title="pushErrorText"
|
|
||||||
@click="push.toggle()"
|
|
||||||
>
|
|
||||||
{{ push.enabled ? t('push.disable') : t('push.enable') }}
|
|
||||||
</button>
|
|
||||||
<LanguageSwitcher />
|
|
||||||
<button class="btn" @click="onLogout">{{ t('common.logout') }}</button>
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
<p v-if="pushErrorText" class="text-xs text-amber-400">{{ pushErrorText }}</p>
|
|
||||||
|
|
||||||
<form class="flex flex-col gap-2 rounded-lg border border-zinc-800 bg-zinc-900/50 p-3 sm:flex-row sm:items-end" @submit.prevent="onAddRepo">
|
<AttentionSection />
|
||||||
|
|
||||||
|
<form class="card flex flex-col gap-2 sm:flex-row sm:items-end" @submit.prevent="onAddRepo">
|
||||||
<label class="flex flex-1 flex-col gap-1 text-xs text-zinc-400">
|
<label class="flex flex-1 flex-col gap-1 text-xs text-zinc-400">
|
||||||
{{ t('repos.pathLabel') }}
|
{{ t('repos.pathLabel') }}
|
||||||
<input v-model="newPath" type="text" class="input font-mono" :placeholder="t('repos.pathPlaceholder')" required />
|
<input v-model="newPath" type="text" class="input font-mono" :placeholder="t('repos.pathPlaceholder')" required />
|
||||||
</label>
|
</label>
|
||||||
<button type="button" class="btn whitespace-nowrap" @click="showPicker = !showPicker">{{ t('fs.browse') }}</button>
|
<BaseButton type="button" :icon="FolderOpen" class="whitespace-nowrap" @click="showPicker = !showPicker">
|
||||||
<button type="submit" class="btn-primary whitespace-nowrap" :disabled="adding || newPath.trim() === ''">
|
{{ t('fs.browse') }}
|
||||||
{{ adding ? t('repos.adding') : t('repos.add') }}
|
</BaseButton>
|
||||||
</button>
|
<BaseButton type="submit" variant="primary" :icon="Plus" class="whitespace-nowrap" :loading="adding" :disabled="newPath.trim() === ''">
|
||||||
|
{{ t('repos.add') }}
|
||||||
|
</BaseButton>
|
||||||
</form>
|
</form>
|
||||||
<DirectoryPicker
|
<DirectoryPicker
|
||||||
v-if="showPicker"
|
v-if="showPicker"
|
||||||
@@ -41,80 +29,129 @@
|
|||||||
@select="onPickPath"
|
@select="onPickPath"
|
||||||
@close="showPicker = false"
|
@close="showPicker = false"
|
||||||
/>
|
/>
|
||||||
<p v-if="addError" class="text-sm text-red-400">{{ addError }}</p>
|
|
||||||
|
|
||||||
<p v-if="store.loadError" class="text-sm text-red-400">{{ store.loadError }}</p>
|
<SkeletonRow v-if="store.loading && store.repos.length === 0" />
|
||||||
<p v-else-if="store.loading && store.repos.length === 0" class="text-sm text-zinc-500">{{ t('common.loading') }}</p>
|
<EmptyState v-else-if="store.repos.length === 0" :icon="GitBranch" :title="t('repos.empty')" />
|
||||||
<p v-else-if="store.repos.length === 0" class="text-sm text-zinc-500">{{ t('repos.empty') }}</p>
|
|
||||||
|
|
||||||
<RepoSection v-for="repo in store.repos" :key="repo.id" :repo="repo" />
|
<template v-else>
|
||||||
</div>
|
<!-- une seule toolbar pilote le tri/filtre des worktrees de toutes les sections -->
|
||||||
</div>
|
<ListToolbar :controls="view" search-placeholder-key="controls.searchPlaceholder" />
|
||||||
|
<label v-if="hiddenCount > 0" class="flex items-center gap-2 px-1 text-xs text-zinc-400">
|
||||||
|
<input v-model="showHidden" type="checkbox" /> {{ t('repos.showHidden', { n: hiddenCount }) }}
|
||||||
|
</label>
|
||||||
|
<EmptyState v-if="visibleRepos.length === 0" :icon="Search" :title="t('controls.results', 0)" />
|
||||||
|
<RepoSection v-for="repo in pagedRepos" :key="repo.id" :repo="repo" />
|
||||||
|
<Pagination
|
||||||
|
:page="repoPage"
|
||||||
|
:page-count="repoPageCount"
|
||||||
|
:page-size="repoPageSize"
|
||||||
|
:page-size-options="[10, 25, 50, 0]"
|
||||||
|
:default-size="10"
|
||||||
|
@update:page="repoPage = $event"
|
||||||
|
@update:page-size="onRepoPageSize"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onMounted, ref } from 'vue';
|
import { computed, ref, watch } from 'vue';
|
||||||
import { useRouter } from 'vue-router';
|
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { useAuthStore } from '../stores/auth';
|
import { GitBranch, RefreshCw, FolderOpen, Plus, Search, ScanSearch } from '@lucide/vue';
|
||||||
import { useWorktreesStore } from '../stores/worktrees';
|
import { useWorktreesStore } from '../stores/worktrees';
|
||||||
import { useSessionsStore } from '../stores/sessions';
|
import { useToastsStore } from '../stores/toasts';
|
||||||
import { usePushStore } from '../stores/push';
|
import { useWorktreeView } from '../composables/useWorktreeView';
|
||||||
import LanguageSwitcher from '../components/LanguageSwitcher.vue';
|
import PageHeader from '../components/layout/PageHeader.vue';
|
||||||
|
import BaseButton from '../components/ui/BaseButton.vue';
|
||||||
|
import EmptyState from '../components/ui/EmptyState.vue';
|
||||||
|
import SkeletonRow from '../components/ui/SkeletonRow.vue';
|
||||||
|
import ListToolbar from '../components/ListToolbar.vue';
|
||||||
|
import Pagination from '../components/Pagination.vue';
|
||||||
|
import AttentionSection from '../components/AttentionSection.vue';
|
||||||
import RepoSection from '../components/RepoSection.vue';
|
import RepoSection from '../components/RepoSection.vue';
|
||||||
import DirectoryPicker from '../components/DirectoryPicker.vue';
|
import DirectoryPicker from '../components/DirectoryPicker.vue';
|
||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const router = useRouter();
|
|
||||||
const auth = useAuthStore();
|
|
||||||
const store = useWorktreesStore();
|
const store = useWorktreesStore();
|
||||||
const sessions = useSessionsStore();
|
const toasts = useToastsStore();
|
||||||
const push = usePushStore();
|
const view = useWorktreeView();
|
||||||
|
|
||||||
const newPath = ref('');
|
const newPath = ref('');
|
||||||
const showPicker = ref(false);
|
const showPicker = ref(false);
|
||||||
const adding = ref(false);
|
const adding = ref(false);
|
||||||
const addError = ref<string | null>(null);
|
const scanning = ref(false);
|
||||||
|
const showHidden = ref(false);
|
||||||
|
|
||||||
|
const hiddenCount = computed(() => store.repos.filter((r) => r.hidden).length);
|
||||||
|
|
||||||
|
// repos visibles : les masqués sont exclus sauf si « afficher les masqués » est coché. Triés par libellé ;
|
||||||
|
// puis masqués quand un filtre/recherche worktree actif ne laisse rien dans le repo.
|
||||||
|
const sortedRepos = computed(() =>
|
||||||
|
[...store.repos]
|
||||||
|
.filter((r) => showHidden.value || !r.hidden)
|
||||||
|
.sort((a, b) => a.label.localeCompare(b.label)),
|
||||||
|
);
|
||||||
|
const visibleRepos = computed(() =>
|
||||||
|
view.isActive()
|
||||||
|
? sortedRepos.value.filter((r) => view.apply(store.worktreesForRepo(r.id)).length > 0)
|
||||||
|
: sortedRepos.value,
|
||||||
|
);
|
||||||
|
|
||||||
|
// GET /worktrees exclut les repos masqués (perf) → charger paresseusement leurs worktrees au dévoilement.
|
||||||
|
watch(showHidden, (on) => {
|
||||||
|
if (on) for (const r of store.repos.filter((x) => x.hidden)) void store.refreshRepoWorktrees(r.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
// pagination des repos (rarement nombreux → masquée par défaut).
|
||||||
|
const repoPage = ref(1);
|
||||||
|
const repoPageSize = ref(10);
|
||||||
|
const repoPageCount = computed(() =>
|
||||||
|
repoPageSize.value === 0 ? 1 : Math.max(1, Math.ceil(visibleRepos.value.length / repoPageSize.value)),
|
||||||
|
);
|
||||||
|
const pagedRepos = computed(() => {
|
||||||
|
if (repoPageSize.value === 0) return visibleRepos.value;
|
||||||
|
const start = (repoPage.value - 1) * repoPageSize.value;
|
||||||
|
return visibleRepos.value.slice(start, start + repoPageSize.value);
|
||||||
|
});
|
||||||
|
watch(repoPageCount, (count) => {
|
||||||
|
if (repoPage.value > count) repoPage.value = count;
|
||||||
|
});
|
||||||
|
|
||||||
|
function onRepoPageSize(n: number): void {
|
||||||
|
repoPageSize.value = n;
|
||||||
|
repoPage.value = 1;
|
||||||
|
}
|
||||||
|
|
||||||
function onPickPath(path: string): void {
|
function onPickPath(path: string): void {
|
||||||
newPath.value = path;
|
newPath.value = path;
|
||||||
showPicker.value = false;
|
showPicker.value = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 'denied'/'unsupported' sont des clés i18n ; tout autre message d'erreur est affiché tel quel.
|
function refresh(): void {
|
||||||
const pushErrorText = computed(() => {
|
|
||||||
const e = push.error;
|
|
||||||
if (!e) return '';
|
|
||||||
return e === 'denied' || e === 'unsupported' ? t(`push.${e}`) : e;
|
|
||||||
});
|
|
||||||
|
|
||||||
onMounted(() => {
|
|
||||||
void store.fetchAll();
|
void store.fetchAll();
|
||||||
store.startRealtime();
|
}
|
||||||
// les sessions alimentent la corrélation worktree↔session (cwd) côté serveur ; on charge et on
|
|
||||||
// suit leurs mises à jour temps réel pour que les badges d'état (busy/waiting/idle) restent live.
|
async function onDiscover(): Promise<void> {
|
||||||
void sessions.fetchSessions();
|
scanning.value = true;
|
||||||
sessions.startRealtime();
|
try {
|
||||||
void push.refresh();
|
const res = await store.discover();
|
||||||
});
|
toasts.success(t('repos.scanResult', res.added));
|
||||||
|
} catch (err) {
|
||||||
|
toasts.error(err);
|
||||||
|
} finally {
|
||||||
|
scanning.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function onAddRepo(): Promise<void> {
|
async function onAddRepo(): Promise<void> {
|
||||||
adding.value = true;
|
adding.value = true;
|
||||||
addError.value = null;
|
|
||||||
try {
|
try {
|
||||||
await store.addRepo(newPath.value.trim());
|
await store.addRepo(newPath.value.trim());
|
||||||
newPath.value = '';
|
newPath.value = '';
|
||||||
|
toasts.success(t('toast.repoAdded'));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
addError.value = err instanceof Error ? err.message : String(err);
|
toasts.error(err);
|
||||||
} finally {
|
} finally {
|
||||||
adding.value = false;
|
adding.value = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onLogout(): Promise<void> {
|
|
||||||
store.stopRealtime();
|
|
||||||
sessions.stopRealtime();
|
|
||||||
await auth.logout();
|
|
||||||
await router.replace({ name: 'login' });
|
|
||||||
}
|
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -1,42 +1,42 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="overflow-y-auto">
|
<PageHeader>
|
||||||
<div class="mx-auto flex max-w-3xl flex-col gap-4 px-4 py-6">
|
<template #title>
|
||||||
<header class="flex flex-wrap items-center gap-3">
|
<BaseButton variant="ghost" size="sm" icon-only :icon="ChevronLeft" :to="{ name: 'groups' }" :aria-label="t('common.back')" />
|
||||||
<RouterLink :to="{ name: 'groups' }" class="text-sm text-zinc-400 hover:text-zinc-200">← {{ t('groups.title') }}</RouterLink>
|
<h1 v-if="group" class="flex items-center gap-2 truncate text-lg font-semibold text-zinc-100">
|
||||||
<h1 v-if="group" class="flex items-center gap-2 text-lg font-semibold text-zinc-100">
|
<span class="h-3 w-3 shrink-0 rounded-full" :style="{ backgroundColor: group.color ?? '#52525b' }" />
|
||||||
<span class="h-3 w-3 rounded-full" :style="{ backgroundColor: group.color ?? '#52525b' }" />
|
|
||||||
{{ group.label }}
|
{{ group.label }}
|
||||||
</h1>
|
</h1>
|
||||||
<div class="ml-auto flex flex-wrap items-center gap-2">
|
<span v-else class="text-sm text-zinc-500">{{ t('common.loading') }}</span>
|
||||||
<button v-if="group" class="btn text-xs" :class="editingRepos ? 'border-sky-700 text-sky-300' : ''" @click="editingRepos = !editingRepos">
|
</template>
|
||||||
|
|
||||||
|
<template v-if="group">
|
||||||
|
<BaseButton
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
:icon="Pencil"
|
||||||
|
:class="editingRepos ? 'text-sky-300' : ''"
|
||||||
|
@click="editingRepos = !editingRepos"
|
||||||
|
>
|
||||||
{{ editingRepos ? t('groups.editDone') : t('groups.edit') }}
|
{{ editingRepos ? t('groups.editDone') : t('groups.edit') }}
|
||||||
</button>
|
</BaseButton>
|
||||||
<button class="btn text-xs" :disabled="groupRepos.length === 0" @click="showFeatureModal = true">{{ t('groups.newFeature') }}</button>
|
<BaseButton size="sm" :icon="Combine" :disabled="groupRepos.length === 0" @click="showFeatureModal = true">
|
||||||
<div class="flex overflow-hidden rounded border border-zinc-800">
|
{{ t('groups.newFeature') }}
|
||||||
<button class="px-2 py-1 text-xs" :class="view === 'list' ? 'bg-zinc-800 text-zinc-100' : 'text-zinc-400'" @click="view = 'list'">
|
</BaseButton>
|
||||||
{{ t('groups.viewList') }}
|
<SegmentedControl v-model="view" :options="viewOptions" />
|
||||||
</button>
|
<BaseButton variant="ghost" size="sm" :icon="RefreshCw" :loading="worktrees.loading" @click="refresh" />
|
||||||
<button class="px-2 py-1 text-xs" :class="view === 'grid' ? 'bg-zinc-800 text-zinc-100' : 'text-zinc-400'" @click="view = 'grid'">
|
</template>
|
||||||
{{ t('groups.viewGrid') }}
|
</PageHeader>
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<button class="btn text-xs" :disabled="worktrees.loading" @click="refresh">{{ t('sessions.refresh') }}</button>
|
|
||||||
<LanguageSwitcher />
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<p v-if="!group" class="text-sm text-zinc-500">{{ t('common.loading') }}</p>
|
<template v-if="group">
|
||||||
|
|
||||||
<template v-else>
|
|
||||||
<!-- édition de la composition : ajouter/retirer des repos déjà enregistrés -->
|
<!-- édition de la composition : ajouter/retirer des repos déjà enregistrés -->
|
||||||
<div v-if="editingRepos" class="flex flex-col gap-1 rounded-lg border border-zinc-800 bg-zinc-900/50 p-3 text-xs text-zinc-400">
|
<div v-if="editingRepos" class="card flex flex-col gap-1 text-xs text-zinc-400">
|
||||||
{{ t('groups.reposLabel') }}
|
{{ t('groups.reposLabel') }}
|
||||||
<p v-if="worktrees.repos.length === 0" class="text-zinc-600">{{ t('groups.noReposRegistered') }}</p>
|
<p v-if="worktrees.repos.length === 0" class="text-zinc-600">{{ t('groups.noReposRegistered') }}</p>
|
||||||
<div v-else class="flex flex-wrap gap-2">
|
<div v-else class="flex flex-wrap gap-2">
|
||||||
<label
|
<label
|
||||||
v-for="repo in worktrees.repos"
|
v-for="repo in worktrees.repos"
|
||||||
:key="repo.id"
|
:key="repo.id"
|
||||||
class="flex items-center gap-1.5 rounded border border-zinc-800 bg-zinc-950/40 px-2 py-1"
|
class="flex items-center gap-1.5 rounded-lg border border-zinc-800 bg-zinc-950/40 px-2 py-1"
|
||||||
>
|
>
|
||||||
<input type="checkbox" :checked="group.repoIds.includes(repo.id)" @change="toggleRepo(repo.id)" />
|
<input type="checkbox" :checked="group.repoIds.includes(repo.id)" @change="toggleRepo(repo.id)" />
|
||||||
<span class="text-zinc-300">{{ repo.label }}</span>
|
<span class="text-zinc-300">{{ repo.label }}</span>
|
||||||
@@ -46,40 +46,49 @@
|
|||||||
|
|
||||||
<!-- mode liste : réutilise RepoSection (worktrees + sessions + dialogues inline) -->
|
<!-- mode liste : réutilise RepoSection (worktrees + sessions + dialogues inline) -->
|
||||||
<template v-if="view === 'list'">
|
<template v-if="view === 'list'">
|
||||||
<p v-if="groupRepos.length === 0 && missingRepoIds.length === 0" class="text-sm text-zinc-500">{{ t('groups.noReposInGroup') }}</p>
|
<EmptyState
|
||||||
|
v-if="groupRepos.length === 0 && missingRepoIds.length === 0"
|
||||||
|
:icon="Boxes"
|
||||||
|
:title="t('groups.noReposInGroup')"
|
||||||
|
/>
|
||||||
<RepoSection v-for="repo in groupRepos" :key="repo.id" :repo="repo" />
|
<RepoSection v-for="repo in groupRepos" :key="repo.id" :repo="repo" />
|
||||||
<div
|
<div
|
||||||
v-for="id in missingRepoIds"
|
v-for="id in missingRepoIds"
|
||||||
:key="id"
|
:key="id"
|
||||||
class="flex items-center gap-2 rounded-lg border border-amber-900/50 bg-amber-950/20 p-3 text-sm text-amber-300"
|
class="flex items-center gap-2 rounded-xl border border-amber-900/50 bg-amber-950/20 p-3 text-sm text-amber-300"
|
||||||
>
|
>
|
||||||
<span class="flex-1">{{ t('groups.missingRepo') }} <span class="font-mono text-xs text-amber-500/70">{{ id }}</span></span>
|
<span class="flex-1">{{ t('groups.missingRepo') }} <span class="font-mono text-xs text-amber-500/70">{{ id }}</span></span>
|
||||||
<button class="btn text-xs" @click="removeRepo(id)">{{ t('groups.removeFromGroup') }}</button>
|
<BaseButton size="sm" @click="removeRepo(id)">{{ t('groups.removeFromGroup') }}</BaseButton>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<!-- mode grille : terminaux côte à côte -->
|
<!-- mode grille : toolbar (tri waiting-first + recherche) en amont du cap dur de TerminalGrid -->
|
||||||
<TerminalGrid v-else :sessions="activeGroupSessions" />
|
<template v-else>
|
||||||
|
<ListToolbar v-if="activeGroupSessions.length" :controls="gridControls" />
|
||||||
|
<TerminalGrid :sessions="gridControls.processed.value" />
|
||||||
|
</template>
|
||||||
</template>
|
</template>
|
||||||
</div>
|
|
||||||
|
|
||||||
<CrossRepoFeatureModal
|
<CrossRepoFeatureModal v-if="showFeatureModal && group" :repos="groupRepos" @close="showFeatureModal = false" />
|
||||||
v-if="showFeatureModal && group"
|
|
||||||
:repos="groupRepos"
|
|
||||||
@close="showFeatureModal = false"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onMounted, onUnmounted, ref } from 'vue';
|
import { computed, ref } from 'vue';
|
||||||
import { useRoute } from 'vue-router';
|
import { useRoute } from 'vue-router';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { ChevronLeft, Pencil, Combine, RefreshCw, List, LayoutGrid, Boxes } from '@lucide/vue';
|
||||||
import type { SessionSummary } from '@arboretum/shared';
|
import type { SessionSummary } from '@arboretum/shared';
|
||||||
import { useGroupsStore } from '../stores/groups';
|
import { useGroupsStore } from '../stores/groups';
|
||||||
import { useWorktreesStore } from '../stores/worktrees';
|
import { useWorktreesStore } from '../stores/worktrees';
|
||||||
import { useSessionsStore } from '../stores/sessions';
|
import { useSessionsStore } from '../stores/sessions';
|
||||||
import LanguageSwitcher from '../components/LanguageSwitcher.vue';
|
import { useToastsStore } from '../stores/toasts';
|
||||||
|
import { useListControls } from '../composables/useListControls';
|
||||||
|
import { sessionSorts } from '../composables/listDefs';
|
||||||
|
import PageHeader from '../components/layout/PageHeader.vue';
|
||||||
|
import BaseButton from '../components/ui/BaseButton.vue';
|
||||||
|
import EmptyState from '../components/ui/EmptyState.vue';
|
||||||
|
import SegmentedControl from '../components/ui/SegmentedControl.vue';
|
||||||
|
import ListToolbar from '../components/ListToolbar.vue';
|
||||||
import RepoSection from '../components/RepoSection.vue';
|
import RepoSection from '../components/RepoSection.vue';
|
||||||
import TerminalGrid from '../components/TerminalGrid.vue';
|
import TerminalGrid from '../components/TerminalGrid.vue';
|
||||||
import CrossRepoFeatureModal from '../components/CrossRepoFeatureModal.vue';
|
import CrossRepoFeatureModal from '../components/CrossRepoFeatureModal.vue';
|
||||||
@@ -89,13 +98,19 @@ const route = useRoute();
|
|||||||
const groups = useGroupsStore();
|
const groups = useGroupsStore();
|
||||||
const worktrees = useWorktreesStore();
|
const worktrees = useWorktreesStore();
|
||||||
const sessions = useSessionsStore();
|
const sessions = useSessionsStore();
|
||||||
|
const toasts = useToastsStore();
|
||||||
|
|
||||||
const groupId = computed(() => String(route.params.id));
|
const groupId = computed(() => String(route.params.id));
|
||||||
const group = computed(() => groups.byId(groupId.value));
|
const group = computed(() => groups.byId(groupId.value));
|
||||||
const view = ref<'list' | 'grid'>('list');
|
const view = ref('list');
|
||||||
const editingRepos = ref(false);
|
const editingRepos = ref(false);
|
||||||
const showFeatureModal = ref(false);
|
const showFeatureModal = ref(false);
|
||||||
|
|
||||||
|
const viewOptions = computed(() => [
|
||||||
|
{ value: 'list', label: t('groups.viewList'), icon: List },
|
||||||
|
{ value: 'grid', label: t('groups.viewGrid'), icon: LayoutGrid },
|
||||||
|
]);
|
||||||
|
|
||||||
const groupRepos = computed(() => groups.reposInGroup(groupId.value));
|
const groupRepos = computed(() => groups.reposInGroup(groupId.value));
|
||||||
|
|
||||||
// repoIds du groupe absents du store worktrees (repo supprimé mais membership pas encore purgée côté UI).
|
// repoIds du groupe absents du store worktrees (repo supprimé mais membership pas encore purgée côté UI).
|
||||||
@@ -116,19 +131,12 @@ const activeGroupSessions = computed<SessionSummary[]>(() => {
|
|||||||
return [...byId.values()];
|
return [...byId.values()];
|
||||||
});
|
});
|
||||||
|
|
||||||
onMounted(() => {
|
// mode grille : tri (waiting d'abord) + recherche, sans pagination ; TerminalGrid conserve son cap dur.
|
||||||
void groups.fetchGroups();
|
const gridControls = useListControls<SessionSummary>({
|
||||||
void worktrees.fetchAll();
|
source: () => activeGroupSessions.value,
|
||||||
void sessions.fetchSessions();
|
sorts: sessionSorts(),
|
||||||
groups.startRealtime();
|
searchAccessor: (s) => `${s.cwd} ${s.title ?? ''}`,
|
||||||
worktrees.startRealtime();
|
defaultPageSize: 0,
|
||||||
sessions.startRealtime();
|
|
||||||
});
|
|
||||||
|
|
||||||
onUnmounted(() => {
|
|
||||||
groups.stopRealtime();
|
|
||||||
worktrees.stopRealtime();
|
|
||||||
sessions.stopRealtime();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
async function refresh(): Promise<void> {
|
async function refresh(): Promise<void> {
|
||||||
@@ -138,12 +146,23 @@ async function refresh(): Promise<void> {
|
|||||||
async function toggleRepo(repoId: string): Promise<void> {
|
async function toggleRepo(repoId: string): Promise<void> {
|
||||||
const g = group.value;
|
const g = group.value;
|
||||||
if (!g) return;
|
if (!g) return;
|
||||||
|
try {
|
||||||
if (g.repoIds.includes(repoId)) await groups.removeRepoFromGroup(g.id, repoId);
|
if (g.repoIds.includes(repoId)) await groups.removeRepoFromGroup(g.id, repoId);
|
||||||
else await groups.addRepoToGroup(g.id, repoId);
|
else await groups.addRepoToGroup(g.id, repoId);
|
||||||
|
toasts.success(t('toast.groupUpdated'));
|
||||||
|
} catch (err) {
|
||||||
|
toasts.error(err);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function removeRepo(repoId: string): Promise<void> {
|
async function removeRepo(repoId: string): Promise<void> {
|
||||||
const g = group.value;
|
const g = group.value;
|
||||||
if (g) await groups.removeRepoFromGroup(g.id, repoId);
|
if (!g) return;
|
||||||
|
try {
|
||||||
|
await groups.removeRepoFromGroup(g.id, repoId);
|
||||||
|
toasts.success(t('toast.groupUpdated'));
|
||||||
|
} catch (err) {
|
||||||
|
toasts.error(err);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -1,18 +1,12 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="overflow-y-auto">
|
<PageHeader :title="t('nav.groups')">
|
||||||
<div class="mx-auto flex max-w-3xl flex-col gap-4 px-4 py-6">
|
<BaseButton variant="ghost" size="sm" :icon="RefreshCw" :loading="groups.loading" @click="refresh">
|
||||||
<header class="flex items-center gap-3">
|
{{ t('common.refresh') }}
|
||||||
<h1 class="text-lg font-semibold text-zinc-100">{{ t('groups.title') }}</h1>
|
</BaseButton>
|
||||||
<div class="ml-auto flex items-center gap-2">
|
</PageHeader>
|
||||||
<RouterLink :to="{ name: 'dashboard' }" class="btn">{{ t('groups.dashboard') }}</RouterLink>
|
|
||||||
<button class="btn" :disabled="groups.loading" @click="refresh">{{ t('sessions.refresh') }}</button>
|
|
||||||
<LanguageSwitcher />
|
|
||||||
<button class="btn" @click="onLogout">{{ t('common.logout') }}</button>
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<!-- création d'un groupe : nom + sélection des repos déjà enregistrés -->
|
<!-- création d'un groupe : nom + sélection des repos déjà enregistrés -->
|
||||||
<form class="flex flex-col gap-2 rounded-lg border border-zinc-800 bg-zinc-900/50 p-3" @submit.prevent="onCreate">
|
<form class="card flex flex-col gap-2" @submit.prevent="onCreate">
|
||||||
<label class="flex flex-col gap-1 text-xs text-zinc-400">
|
<label class="flex flex-col gap-1 text-xs text-zinc-400">
|
||||||
{{ t('groups.nameLabel') }}
|
{{ t('groups.nameLabel') }}
|
||||||
<input v-model="newLabel" type="text" class="input" :placeholder="t('groups.namePlaceholder')" required />
|
<input v-model="newLabel" type="text" class="input" :placeholder="t('groups.namePlaceholder')" required />
|
||||||
@@ -24,35 +18,29 @@
|
|||||||
<label
|
<label
|
||||||
v-for="repo in worktrees.repos"
|
v-for="repo in worktrees.repos"
|
||||||
:key="repo.id"
|
:key="repo.id"
|
||||||
class="flex items-center gap-1.5 rounded border border-zinc-800 bg-zinc-950/40 px-2 py-1"
|
class="flex items-center gap-1.5 rounded-lg border border-zinc-800 bg-zinc-950/40 px-2 py-1"
|
||||||
>
|
>
|
||||||
<input v-model="selectedRepoIds" type="checkbox" :value="repo.id" />
|
<input v-model="selectedRepoIds" type="checkbox" :value="repo.id" />
|
||||||
<span class="text-zinc-300">{{ repo.label }}</span>
|
<span class="text-zinc-300">{{ repo.label }}</span>
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex items-center gap-2">
|
<div>
|
||||||
<button type="submit" class="btn-primary" :disabled="creating || newLabel.trim() === ''">
|
<BaseButton type="submit" variant="primary" :icon="Plus" :loading="creating" :disabled="newLabel.trim() === ''">
|
||||||
{{ creating ? t('groups.creating') : t('groups.new') }}
|
{{ t('groups.new') }}
|
||||||
</button>
|
</BaseButton>
|
||||||
<span v-if="createError" class="text-sm text-red-400">{{ createError }}</span>
|
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<p v-if="groups.loadError" class="text-sm text-red-400">{{ groups.loadError }}</p>
|
<SkeletonRow v-if="groups.loading && groups.groups.length === 0" />
|
||||||
<p v-else-if="groups.loading && groups.groups.length === 0" class="text-sm text-zinc-500">{{ t('common.loading') }}</p>
|
<EmptyState v-else-if="groups.groups.length === 0" :icon="Boxes" :title="t('groups.empty')" />
|
||||||
<p v-else-if="groups.groups.length === 0" class="text-sm text-zinc-500">{{ t('groups.empty') }}</p>
|
|
||||||
|
|
||||||
<div class="flex flex-col gap-2">
|
<template v-else>
|
||||||
<article
|
<ListToolbar :controls="controls" />
|
||||||
v-for="group in groups.groups"
|
<EmptyState v-if="controls.total.value === 0" :icon="Search" :title="t('controls.results', 0)" />
|
||||||
:key="group.id"
|
<div v-else class="flex flex-col gap-2">
|
||||||
class="flex items-center gap-3 rounded-lg border border-zinc-800 bg-zinc-900/50 p-3"
|
<article v-for="group in controls.processed.value" :key="group.id" class="card flex items-center gap-3">
|
||||||
>
|
<span class="h-3 w-3 shrink-0 rounded-full" :style="{ backgroundColor: group.color ?? '#52525b' }" />
|
||||||
<span
|
|
||||||
class="h-3 w-3 shrink-0 rounded-full"
|
|
||||||
:style="{ backgroundColor: group.color ?? '#52525b' }"
|
|
||||||
/>
|
|
||||||
<div class="min-w-0 flex-1">
|
<div class="min-w-0 flex-1">
|
||||||
<RouterLink :to="{ name: 'group', params: { id: group.id } }" class="font-semibold text-zinc-100 hover:underline">
|
<RouterLink :to="{ name: 'group', params: { id: group.id } }" class="font-semibold text-zinc-100 hover:underline">
|
||||||
{{ group.label }}
|
{{ group.label }}
|
||||||
@@ -60,44 +48,65 @@
|
|||||||
<p v-if="group.description" class="truncate text-xs text-zinc-500">{{ group.description }}</p>
|
<p v-if="group.description" class="truncate text-xs text-zinc-500">{{ group.description }}</p>
|
||||||
</div>
|
</div>
|
||||||
<span class="text-xs text-zinc-500">{{ t('groups.repoCount', group.repoIds.length) }}</span>
|
<span class="text-xs text-zinc-500">{{ t('groups.repoCount', group.repoIds.length) }}</span>
|
||||||
<span v-if="activeCount(group.id) > 0" class="badge bg-emerald-950 text-emerald-400">
|
<BaseBadge v-if="activeCount(group.id) > 0" tone="emerald">
|
||||||
{{ t('groups.sessionsActive', activeCount(group.id)) }}
|
{{ t('groups.sessionsActive', activeCount(group.id)) }}
|
||||||
</span>
|
</BaseBadge>
|
||||||
<div class="flex items-center gap-2">
|
<div class="flex items-center gap-2">
|
||||||
<RouterLink :to="{ name: 'group', params: { id: group.id } }" class="btn text-xs">{{ t('groups.open') }}</RouterLink>
|
<BaseButton size="sm" :to="{ name: 'group', params: { id: group.id } }">{{ t('groups.open') }}</BaseButton>
|
||||||
<template v-if="confirmingDelete === group.id">
|
<template v-if="confirmingDelete === group.id">
|
||||||
<button class="btn-danger text-xs" @click="onDelete(group.id)">{{ t('groups.confirmDelete') }}</button>
|
<BaseButton variant="danger" size="sm" :icon="Trash2" @click="onDelete(group.id)">{{ t('groups.confirmDelete') }}</BaseButton>
|
||||||
<button class="btn text-xs" @click="confirmingDelete = null">{{ t('common.cancel') }}</button>
|
<BaseButton variant="ghost" size="sm" @click="confirmingDelete = null">{{ t('common.cancel') }}</BaseButton>
|
||||||
</template>
|
</template>
|
||||||
<button v-else class="btn-danger text-xs" @click="confirmingDelete = group.id">{{ t('groups.remove') }}</button>
|
<BaseButton v-else variant="danger" size="sm" :icon="Trash2" @click="confirmingDelete = group.id">{{ t('groups.remove') }}</BaseButton>
|
||||||
</div>
|
</div>
|
||||||
</article>
|
</article>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<Pagination
|
||||||
</div>
|
:page="controls.page.value"
|
||||||
|
:page-count="controls.pageCount.value"
|
||||||
|
:page-size="controls.pageSize.value"
|
||||||
|
:page-size-options="[25, 50, 100, 0]"
|
||||||
|
:default-size="50"
|
||||||
|
@update:page="controls.setPage"
|
||||||
|
@update:page-size="controls.setPageSize"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { onMounted, onUnmounted, ref } from 'vue';
|
import { ref } from 'vue';
|
||||||
import { useRouter } from 'vue-router';
|
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { useAuthStore } from '../stores/auth';
|
import type { GroupSummary } from '@arboretum/shared';
|
||||||
|
import { RefreshCw, Plus, Trash2, Boxes, Search } from '@lucide/vue';
|
||||||
import { useGroupsStore } from '../stores/groups';
|
import { useGroupsStore } from '../stores/groups';
|
||||||
import { useWorktreesStore } from '../stores/worktrees';
|
import { useWorktreesStore } from '../stores/worktrees';
|
||||||
import { useSessionsStore } from '../stores/sessions';
|
import { useToastsStore } from '../stores/toasts';
|
||||||
import LanguageSwitcher from '../components/LanguageSwitcher.vue';
|
import { useListControls } from '../composables/useListControls';
|
||||||
|
import { groupSorts } from '../composables/listDefs';
|
||||||
|
import PageHeader from '../components/layout/PageHeader.vue';
|
||||||
|
import BaseButton from '../components/ui/BaseButton.vue';
|
||||||
|
import BaseBadge from '../components/ui/BaseBadge.vue';
|
||||||
|
import EmptyState from '../components/ui/EmptyState.vue';
|
||||||
|
import SkeletonRow from '../components/ui/SkeletonRow.vue';
|
||||||
|
import ListToolbar from '../components/ListToolbar.vue';
|
||||||
|
import Pagination from '../components/Pagination.vue';
|
||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const router = useRouter();
|
|
||||||
const auth = useAuthStore();
|
|
||||||
const groups = useGroupsStore();
|
const groups = useGroupsStore();
|
||||||
const worktrees = useWorktreesStore();
|
const worktrees = useWorktreesStore();
|
||||||
const sessions = useSessionsStore();
|
const toasts = useToastsStore();
|
||||||
|
|
||||||
|
const controls = useListControls<GroupSummary>({
|
||||||
|
source: () => groups.groups,
|
||||||
|
sorts: groupSorts({ activeCount: (id) => groups.sessionsInGroup(id).filter((s) => s.live).length }),
|
||||||
|
searchAccessor: (g) => `${g.label} ${g.description ?? ''}`,
|
||||||
|
defaultPageSize: 50,
|
||||||
|
urlKey: 'groups',
|
||||||
|
});
|
||||||
|
|
||||||
const newLabel = ref('');
|
const newLabel = ref('');
|
||||||
const selectedRepoIds = ref<string[]>([]);
|
const selectedRepoIds = ref<string[]>([]);
|
||||||
const creating = ref(false);
|
const creating = ref(false);
|
||||||
const createError = ref<string | null>(null);
|
|
||||||
const confirmingDelete = ref<string | null>(null);
|
const confirmingDelete = ref<string | null>(null);
|
||||||
|
|
||||||
// nombre de sessions vivantes corrélées aux repos du groupe (badge d'aperçu).
|
// nombre de sessions vivantes corrélées aux repos du groupe (badge d'aperçu).
|
||||||
@@ -105,34 +114,19 @@ function activeCount(groupId: string): number {
|
|||||||
return groups.sessionsInGroup(groupId).filter((s) => s.live).length;
|
return groups.sessionsInGroup(groupId).filter((s) => s.live).length;
|
||||||
}
|
}
|
||||||
|
|
||||||
onMounted(() => {
|
function refresh(): void {
|
||||||
void groups.fetchGroups();
|
void Promise.all([groups.fetchGroups(), worktrees.fetchAll()]);
|
||||||
void worktrees.fetchAll();
|
|
||||||
void sessions.fetchSessions();
|
|
||||||
groups.startRealtime();
|
|
||||||
worktrees.startRealtime();
|
|
||||||
sessions.startRealtime();
|
|
||||||
});
|
|
||||||
|
|
||||||
onUnmounted(() => {
|
|
||||||
groups.stopRealtime();
|
|
||||||
worktrees.stopRealtime();
|
|
||||||
sessions.stopRealtime();
|
|
||||||
});
|
|
||||||
|
|
||||||
async function refresh(): Promise<void> {
|
|
||||||
await Promise.all([groups.fetchGroups(), worktrees.fetchAll(), sessions.fetchSessions()]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onCreate(): Promise<void> {
|
async function onCreate(): Promise<void> {
|
||||||
creating.value = true;
|
creating.value = true;
|
||||||
createError.value = null;
|
|
||||||
try {
|
try {
|
||||||
await groups.createGroup({ label: newLabel.value.trim(), repoIds: [...selectedRepoIds.value] });
|
await groups.createGroup({ label: newLabel.value.trim(), repoIds: [...selectedRepoIds.value] });
|
||||||
newLabel.value = '';
|
newLabel.value = '';
|
||||||
selectedRepoIds.value = [];
|
selectedRepoIds.value = [];
|
||||||
|
toasts.success(t('toast.groupCreated'));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
createError.value = err instanceof Error ? err.message : String(err);
|
toasts.error(err);
|
||||||
} finally {
|
} finally {
|
||||||
creating.value = false;
|
creating.value = false;
|
||||||
}
|
}
|
||||||
@@ -142,16 +136,9 @@ async function onDelete(id: string): Promise<void> {
|
|||||||
confirmingDelete.value = null;
|
confirmingDelete.value = null;
|
||||||
try {
|
try {
|
||||||
await groups.deleteGroup(id);
|
await groups.deleteGroup(id);
|
||||||
|
toasts.success(t('toast.groupDeleted'));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
createError.value = err instanceof Error ? err.message : String(err);
|
toasts.error(err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onLogout(): Promise<void> {
|
|
||||||
groups.stopRealtime();
|
|
||||||
worktrees.stopRealtime();
|
|
||||||
sessions.stopRealtime();
|
|
||||||
await auth.logout();
|
|
||||||
await router.replace({ name: 'login' });
|
|
||||||
}
|
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
68
packages/web/src/views/HelpView.vue
Normal file
68
packages/web/src/views/HelpView.vue
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<PageHeader :title="t('help.title')">
|
||||||
|
<template #search>
|
||||||
|
<div class="relative">
|
||||||
|
<Search :size="15" class="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-zinc-500" />
|
||||||
|
<input v-model="query" class="input pl-8" :placeholder="t('help.searchPlaceholder')" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</PageHeader>
|
||||||
|
<p class="text-sm text-zinc-400">{{ t('help.intro') }}</p>
|
||||||
|
|
||||||
|
<section v-for="section in filtered" :key="section.id" class="card flex flex-col gap-3">
|
||||||
|
<header class="flex items-center gap-2">
|
||||||
|
<component :is="iconFor(section.id)" :size="18" class="text-emerald-400" :stroke-width="1.75" />
|
||||||
|
<h2 class="text-sm font-semibold text-zinc-100">{{ section.title }}</h2>
|
||||||
|
</header>
|
||||||
|
<p class="text-xs text-zinc-500">{{ section.blurb }}</p>
|
||||||
|
<dl class="flex flex-col gap-2">
|
||||||
|
<div v-for="(item, i) in section.items" :key="i" class="card-inset">
|
||||||
|
<dt class="text-sm font-medium text-zinc-200">{{ item.title }}</dt>
|
||||||
|
<dd class="mt-0.5 text-sm leading-relaxed text-zinc-400">{{ item.body }}</dd>
|
||||||
|
</div>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<EmptyState v-if="!filtered.length" :icon="SearchX" :title="t('help.noMatch')" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref, type Component } from 'vue';
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { Boxes, Command, GitBranch, KeyRound, Puzzle, Search, SearchX, Settings, Smartphone, TerminalSquare } from '@lucide/vue';
|
||||||
|
import type { AppLocale } from '../i18n';
|
||||||
|
import { helpSections, type HelpSection } from './help-content';
|
||||||
|
import PageHeader from '../components/layout/PageHeader.vue';
|
||||||
|
import EmptyState from '../components/ui/EmptyState.vue';
|
||||||
|
|
||||||
|
const { t, locale } = useI18n();
|
||||||
|
const query = ref('');
|
||||||
|
|
||||||
|
const ICONS: Record<string, Component> = {
|
||||||
|
gettingStarted: KeyRound,
|
||||||
|
worktrees: GitBranch,
|
||||||
|
sessions: TerminalSquare,
|
||||||
|
mobile: Smartphone,
|
||||||
|
groups: Boxes,
|
||||||
|
productivity: Command,
|
||||||
|
settings: Settings,
|
||||||
|
integrations: Puzzle,
|
||||||
|
};
|
||||||
|
const iconFor = (id: string): Component => ICONS[id] ?? KeyRound;
|
||||||
|
|
||||||
|
const sections = computed<HelpSection[]>(() => helpSections[locale.value as AppLocale] ?? helpSections.en);
|
||||||
|
|
||||||
|
const filtered = computed<HelpSection[]>(() => {
|
||||||
|
const q = query.value.trim().toLowerCase();
|
||||||
|
if (!q) return sections.value;
|
||||||
|
return sections.value
|
||||||
|
.map((s) => {
|
||||||
|
const sectionMatches = (s.title + ' ' + s.blurb).toLowerCase().includes(q);
|
||||||
|
const items = sectionMatches ? s.items : s.items.filter((it) => (it.title + ' ' + it.body).toLowerCase().includes(q));
|
||||||
|
return items.length ? { ...s, items } : null;
|
||||||
|
})
|
||||||
|
.filter((s): s is HelpSection => s !== null);
|
||||||
|
});
|
||||||
|
</script>
|
||||||
@@ -25,9 +25,9 @@
|
|||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
<p v-if="error" class="text-sm text-red-400">{{ error }}</p>
|
<p v-if="error" class="text-sm text-red-400">{{ error }}</p>
|
||||||
<button type="submit" class="btn-primary" :disabled="submitting || token.trim() === ''">
|
<BaseButton type="submit" variant="primary" :loading="submitting" :disabled="token.trim() === ''">
|
||||||
{{ submitting ? t('login.submitting') : t('login.submit') }}
|
{{ submitting ? t('login.submitting') : t('login.submit') }}
|
||||||
</button>
|
</BaseButton>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
@@ -39,6 +39,7 @@ import { useI18n } from 'vue-i18n';
|
|||||||
import { useAuthStore } from '../stores/auth';
|
import { useAuthStore } from '../stores/auth';
|
||||||
import { ApiError } from '../lib/api';
|
import { ApiError } from '../lib/api';
|
||||||
import LanguageSwitcher from '../components/LanguageSwitcher.vue';
|
import LanguageSwitcher from '../components/LanguageSwitcher.vue';
|
||||||
|
import BaseButton from '../components/ui/BaseButton.vue';
|
||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const route = useRoute();
|
const route = useRoute();
|
||||||
|
|||||||
@@ -8,9 +8,6 @@
|
|||||||
<span class="truncate font-mono text-xs text-zinc-500" :title="session?.cwd ?? sessionId">
|
<span class="truncate font-mono text-xs text-zinc-500" :title="session?.cwd ?? sessionId">
|
||||||
{{ session?.cwd ?? sessionId }}
|
{{ session?.cwd ?? sessionId }}
|
||||||
</span>
|
</span>
|
||||||
<div class="ml-auto">
|
|
||||||
<LanguageSwitcher />
|
|
||||||
</div>
|
|
||||||
</header>
|
</header>
|
||||||
<DialogPrompt v-if="session && session.activity === 'waiting'" :session="session" class="m-2" />
|
<DialogPrompt v-if="session && session.activity === 'waiting'" :session="session" class="m-2" />
|
||||||
<TerminalView v-if="attachable" :key="`${sessionId}:${mode}`" :session-id="sessionId" :mode="mode" class="flex-1" />
|
<TerminalView v-if="attachable" :key="`${sessionId}:${mode}`" :session-id="sessionId" :mode="mode" class="flex-1" />
|
||||||
@@ -28,7 +25,6 @@ import { useI18n } from 'vue-i18n';
|
|||||||
import { useSessionsStore } from '../stores/sessions';
|
import { useSessionsStore } from '../stores/sessions';
|
||||||
import TerminalView from '../components/TerminalView.vue';
|
import TerminalView from '../components/TerminalView.vue';
|
||||||
import DialogPrompt from '../components/DialogPrompt.vue';
|
import DialogPrompt from '../components/DialogPrompt.vue';
|
||||||
import LanguageSwitcher from '../components/LanguageSwitcher.vue';
|
|
||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const route = useRoute();
|
const route = useRoute();
|
||||||
@@ -41,8 +37,7 @@ const session = computed(() => store.sessions.find((s) => s.id === sessionId.val
|
|||||||
const attachable = computed(() => session.value?.attachable ?? true);
|
const attachable = computed(() => session.value?.attachable ?? true);
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
// navigation directe : la liste n'est pas encore chargée (en-tête cwd/commande)
|
// navigation directe : garantit l'en-tête (cwd/commande) même si l'AppShell n'a pas encore chargé.
|
||||||
if (store.sessions.length === 0) void store.fetchSessions();
|
if (store.sessions.length === 0) void store.fetchSessions();
|
||||||
store.startRealtime();
|
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -1,32 +1,14 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="overflow-y-auto">
|
<PageHeader :title="t('nav.sessions')">
|
||||||
<div class="mx-auto flex max-w-3xl flex-col gap-4 px-4 py-6">
|
<BaseButton variant="ghost" size="sm" :icon="RefreshCw" :loading="store.loading" @click="store.fetchSessions()">
|
||||||
<header class="flex items-center gap-3">
|
{{ t('common.refresh') }}
|
||||||
<h1 class="text-lg font-semibold text-zinc-100">{{ t('sessions.title') }}</h1>
|
</BaseButton>
|
||||||
<span v-if="auth.serverVersion" class="text-xs text-zinc-600">v{{ auth.serverVersion }}</span>
|
</PageHeader>
|
||||||
<div class="ml-auto flex items-center gap-2">
|
|
||||||
<RouterLink :to="{ name: 'dashboard' }" class="btn">{{ t('dashboard.title') }}</RouterLink>
|
|
||||||
<button class="btn" :disabled="store.loading" @click="store.fetchSessions()">
|
|
||||||
{{ t('sessions.refresh') }}
|
|
||||||
</button>
|
|
||||||
<LanguageSwitcher />
|
|
||||||
<button class="btn" @click="onLogout">{{ t('common.logout') }}</button>
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<form
|
<form class="card flex flex-col gap-2 sm:flex-row sm:items-end" @submit.prevent="onCreate">
|
||||||
class="flex flex-col gap-2 rounded-lg border border-zinc-800 bg-zinc-900/50 p-3 sm:flex-row sm:items-end"
|
|
||||||
@submit.prevent="onCreate"
|
|
||||||
>
|
|
||||||
<label class="flex flex-1 flex-col gap-1 text-xs text-zinc-400">
|
<label class="flex flex-1 flex-col gap-1 text-xs text-zinc-400">
|
||||||
{{ t('sessions.cwdLabel') }}
|
{{ t('sessions.cwdLabel') }}
|
||||||
<input
|
<input v-model="newCwd" type="text" class="input font-mono" :placeholder="t('sessions.cwdPlaceholder')" required />
|
||||||
v-model="newCwd"
|
|
||||||
type="text"
|
|
||||||
class="input font-mono"
|
|
||||||
:placeholder="t('sessions.cwdPlaceholder')"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</label>
|
</label>
|
||||||
<label class="flex flex-col gap-1 text-xs text-zinc-400">
|
<label class="flex flex-col gap-1 text-xs text-zinc-400">
|
||||||
{{ t('sessions.commandLabel') }}
|
{{ t('sessions.commandLabel') }}
|
||||||
@@ -35,10 +17,12 @@
|
|||||||
<option value="bash">bash</option>
|
<option value="bash">bash</option>
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
<button type="button" class="btn whitespace-nowrap" @click="showPicker = !showPicker">{{ t('fs.browse') }}</button>
|
<BaseButton type="button" :icon="FolderOpen" class="whitespace-nowrap" @click="showPicker = !showPicker">
|
||||||
<button type="submit" class="btn-primary whitespace-nowrap" :disabled="creating || newCwd.trim() === ''">
|
{{ t('fs.browse') }}
|
||||||
{{ creating ? t('sessions.creating') : t('sessions.newSession') }}
|
</BaseButton>
|
||||||
</button>
|
<BaseButton type="submit" variant="primary" :icon="Plus" class="whitespace-nowrap" :loading="creating" :disabled="newCwd.trim() === ''">
|
||||||
|
{{ t('sessions.newSession') }}
|
||||||
|
</BaseButton>
|
||||||
</form>
|
</form>
|
||||||
<DirectoryPicker
|
<DirectoryPicker
|
||||||
v-if="showPicker"
|
v-if="showPicker"
|
||||||
@@ -47,26 +31,18 @@
|
|||||||
@select="onPickCwd"
|
@select="onPickCwd"
|
||||||
@close="showPicker = false"
|
@close="showPicker = false"
|
||||||
/>
|
/>
|
||||||
<p v-if="createError" class="text-sm text-red-400">{{ createError }}</p>
|
|
||||||
<p v-if="actionError" class="text-sm text-red-400">{{ actionError }}</p>
|
|
||||||
|
|
||||||
<p v-if="store.loadError" class="text-sm text-red-400">{{ store.loadError }}</p>
|
<SkeletonRow v-if="store.loading && store.sessions.length === 0" />
|
||||||
<p v-else-if="store.loading && store.sessions.length === 0" class="text-sm text-zinc-500">
|
<EmptyState v-else-if="store.sessions.length === 0" :icon="TerminalSquare" :title="t('sessions.empty')" />
|
||||||
{{ t('common.loading') }}
|
|
||||||
</p>
|
|
||||||
<p v-else-if="store.sessions.length === 0" class="text-sm text-zinc-500">{{ t('sessions.empty') }}</p>
|
|
||||||
|
|
||||||
<ul class="flex flex-col gap-2">
|
<template v-else>
|
||||||
<li
|
<ListToolbar :controls="controls" />
|
||||||
v-for="s in store.sessions"
|
<EmptyState v-if="controls.total.value === 0" :icon="Search" :title="t('controls.results', 0)" />
|
||||||
:key="s.id"
|
<ul v-else class="flex flex-col gap-2">
|
||||||
class="flex flex-col gap-2 rounded-lg border border-zinc-800 bg-zinc-900/50 p-3"
|
<li v-for="s in controls.processed.value" :key="s.id" class="card flex flex-col gap-2">
|
||||||
>
|
|
||||||
<div class="flex items-center gap-2">
|
<div class="flex items-center gap-2">
|
||||||
<span class="badge bg-zinc-800 font-mono text-zinc-300">{{ s.command }}</span>
|
<span class="badge bg-zinc-800 font-mono text-zinc-300">{{ s.command }}</span>
|
||||||
<span v-if="s.source === 'discovered'" class="badge bg-sky-950 text-sky-400">
|
<BaseBadge v-if="s.source === 'discovered'" tone="sky">{{ t('sessions.sourceDiscovered') }}</BaseBadge>
|
||||||
{{ t('sessions.sourceDiscovered') }}
|
|
||||||
</span>
|
|
||||||
<SessionStateBadge :session="s" />
|
<SessionStateBadge :session="s" />
|
||||||
<span class="ml-auto text-xs text-zinc-500">{{ formatDate(s.createdAt) }}</span>
|
<span class="ml-auto text-xs text-zinc-500">{{ formatDate(s.createdAt) }}</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -79,67 +55,85 @@
|
|||||||
<div class="ml-auto flex items-center gap-2">
|
<div class="ml-auto flex items-center gap-2">
|
||||||
<!-- session managée vivante : terminal complet -->
|
<!-- session managée vivante : terminal complet -->
|
||||||
<template v-if="s.attachable">
|
<template v-if="s.attachable">
|
||||||
<RouterLink :to="{ name: 'session', params: { id: s.id } }" class="btn">{{ t('sessions.open') }}</RouterLink>
|
<BaseButton size="sm" :icon="SquareTerminal" :to="{ name: 'session', params: { id: s.id } }">{{ t('sessions.open') }}</BaseButton>
|
||||||
<RouterLink :to="{ name: 'session', params: { id: s.id }, query: { mode: 'observer' } }" class="btn">
|
<BaseButton size="sm" :icon="Eye" :to="{ name: 'session', params: { id: s.id }, query: { mode: 'observer' } }">{{ t('sessions.observe') }}</BaseButton>
|
||||||
{{ t('sessions.observe') }}
|
|
||||||
</RouterLink>
|
|
||||||
<template v-if="killArmedId === s.id">
|
<template v-if="killArmedId === s.id">
|
||||||
<button class="btn-danger" :disabled="killing" @click="onConfirmKill(s.id)">
|
<BaseButton variant="danger" size="sm" :icon="Trash2" :loading="killing" @click="onConfirmKill(s.id)">{{ t('sessions.confirmKill') }}</BaseButton>
|
||||||
{{ t('sessions.confirmKill') }}
|
<BaseButton variant="ghost" size="sm" @click="killArmedId = null">{{ t('common.cancel') }}</BaseButton>
|
||||||
</button>
|
|
||||||
<button class="btn" @click="killArmedId = null">{{ t('common.cancel') }}</button>
|
|
||||||
</template>
|
</template>
|
||||||
<button v-else class="btn-danger" @click="killArmedId = s.id">{{ t('sessions.kill') }}</button>
|
<BaseButton v-else variant="danger" size="sm" :icon="Trash2" @click="killArmedId = s.id">{{ t('sessions.kill') }}</BaseButton>
|
||||||
</template>
|
</template>
|
||||||
<!-- session externe vivante : pas d'attache (PTY non détenu) → vue read-only ou fork -->
|
<!-- session externe vivante : pas d'attache (PTY non détenu) → vue read-only ou fork -->
|
||||||
<template v-else-if="s.live">
|
<template v-else-if="s.live">
|
||||||
<RouterLink :to="{ name: 'session', params: { id: s.id } }" class="btn">{{ t('sessions.view') }}</RouterLink>
|
<BaseButton size="sm" :icon="Eye" :to="{ name: 'session', params: { id: s.id } }">{{ t('sessions.view') }}</BaseButton>
|
||||||
<button class="btn" :disabled="actingId === s.id" @click="onFork(s.id)">{{ t('sessions.fork') }}</button>
|
<BaseButton size="sm" :icon="GitFork" :loading="actingId === s.id" @click="onFork(s.id)">{{ t('sessions.fork') }}</BaseButton>
|
||||||
</template>
|
</template>
|
||||||
<!-- session morte reprenable : resume direct ou fork -->
|
<!-- session morte reprenable : resume direct ou fork -->
|
||||||
<template v-else-if="s.resumable">
|
<template v-else-if="s.resumable">
|
||||||
<button class="btn-primary" :disabled="actingId === s.id" @click="onResume(s.id)">
|
<BaseButton variant="primary" size="sm" :icon="Play" :loading="actingId === s.id" @click="onResume(s.id)">{{ t('sessions.resume') }}</BaseButton>
|
||||||
{{ t('sessions.resume') }}
|
<BaseButton size="sm" :icon="GitFork" :loading="actingId === s.id" @click="onFork(s.id)">{{ t('sessions.fork') }}</BaseButton>
|
||||||
</button>
|
|
||||||
<button class="btn" :disabled="actingId === s.id" @click="onFork(s.id)">{{ t('sessions.fork') }}</button>
|
|
||||||
</template>
|
</template>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
<Pagination
|
||||||
</div>
|
:page="controls.page.value"
|
||||||
|
:page-count="controls.pageCount.value"
|
||||||
|
:page-size="controls.pageSize.value"
|
||||||
|
@update:page="controls.setPage"
|
||||||
|
@update:page-size="controls.setPageSize"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { onMounted, ref } from 'vue';
|
import { onMounted, ref } from 'vue';
|
||||||
import { useRouter } from 'vue-router';
|
import { useRouter } from 'vue-router';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { useAuthStore } from '../stores/auth';
|
import type { SessionSummary } from '@arboretum/shared';
|
||||||
|
import { RefreshCw, FolderOpen, Plus, TerminalSquare, SquareTerminal, Eye, Trash2, GitFork, Play, Search } from '@lucide/vue';
|
||||||
import { useSessionsStore } from '../stores/sessions';
|
import { useSessionsStore } from '../stores/sessions';
|
||||||
import LanguageSwitcher from '../components/LanguageSwitcher.vue';
|
import { useWorktreesStore } from '../stores/worktrees';
|
||||||
|
import { useToastsStore } from '../stores/toasts';
|
||||||
|
import { useListControls } from '../composables/useListControls';
|
||||||
|
import { sessionSorts, sessionFilters } from '../composables/listDefs';
|
||||||
|
import PageHeader from '../components/layout/PageHeader.vue';
|
||||||
|
import BaseButton from '../components/ui/BaseButton.vue';
|
||||||
|
import BaseBadge from '../components/ui/BaseBadge.vue';
|
||||||
|
import EmptyState from '../components/ui/EmptyState.vue';
|
||||||
|
import SkeletonRow from '../components/ui/SkeletonRow.vue';
|
||||||
|
import ListToolbar from '../components/ListToolbar.vue';
|
||||||
|
import Pagination from '../components/Pagination.vue';
|
||||||
import SessionStateBadge from '../components/SessionStateBadge.vue';
|
import SessionStateBadge from '../components/SessionStateBadge.vue';
|
||||||
import DialogPrompt from '../components/DialogPrompt.vue';
|
import DialogPrompt from '../components/DialogPrompt.vue';
|
||||||
import DirectoryPicker from '../components/DirectoryPicker.vue';
|
import DirectoryPicker from '../components/DirectoryPicker.vue';
|
||||||
|
|
||||||
const { t, locale } = useI18n();
|
const { t, locale } = useI18n();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const auth = useAuthStore();
|
|
||||||
const store = useSessionsStore();
|
const store = useSessionsStore();
|
||||||
|
const worktrees = useWorktreesStore();
|
||||||
|
const toasts = useToastsStore();
|
||||||
|
|
||||||
|
const controls = useListControls<SessionSummary>({
|
||||||
|
source: () => store.sessions,
|
||||||
|
sorts: sessionSorts(),
|
||||||
|
filters: () => sessionFilters(worktrees.repos),
|
||||||
|
searchAccessor: (s) => `${s.cwd} ${s.title ?? ''}`,
|
||||||
|
urlKey: 'sessions',
|
||||||
|
});
|
||||||
|
|
||||||
const newCwd = ref('');
|
const newCwd = ref('');
|
||||||
const newCommand = ref<'claude' | 'bash'>('claude');
|
const newCommand = ref<'claude' | 'bash'>('claude');
|
||||||
const showPicker = ref(false);
|
const showPicker = ref(false);
|
||||||
const creating = ref(false);
|
const creating = ref(false);
|
||||||
const createError = ref<string | null>(null);
|
|
||||||
const killArmedId = ref<string | null>(null);
|
const killArmedId = ref<string | null>(null);
|
||||||
const killing = ref(false);
|
const killing = ref(false);
|
||||||
const actingId = ref<string | null>(null);
|
const actingId = ref<string | null>(null);
|
||||||
const actionError = ref<string | null>(null);
|
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
void store.fetchSessions();
|
// navigation directe : garantit la liste même si l'AppShell n'a pas encore chargé.
|
||||||
store.startRealtime();
|
if (store.sessions.length === 0) void store.fetchSessions();
|
||||||
});
|
});
|
||||||
|
|
||||||
function formatDate(iso: string): string {
|
function formatDate(iso: string): string {
|
||||||
@@ -153,13 +147,13 @@ function onPickCwd(path: string): void {
|
|||||||
|
|
||||||
async function onCreate(): Promise<void> {
|
async function onCreate(): Promise<void> {
|
||||||
creating.value = true;
|
creating.value = true;
|
||||||
createError.value = null;
|
|
||||||
try {
|
try {
|
||||||
const session = await store.createSession(newCwd.value.trim(), newCommand.value);
|
const session = await store.createSession(newCwd.value.trim(), newCommand.value);
|
||||||
newCwd.value = '';
|
newCwd.value = '';
|
||||||
|
toasts.success(t('toast.sessionCreated'));
|
||||||
await router.push({ name: 'session', params: { id: session.id } });
|
await router.push({ name: 'session', params: { id: session.id } });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
createError.value = err instanceof Error ? err.message : String(err);
|
toasts.error(err);
|
||||||
} finally {
|
} finally {
|
||||||
creating.value = false;
|
creating.value = false;
|
||||||
}
|
}
|
||||||
@@ -167,12 +161,12 @@ async function onCreate(): Promise<void> {
|
|||||||
|
|
||||||
async function onResume(id: string): Promise<void> {
|
async function onResume(id: string): Promise<void> {
|
||||||
actingId.value = id;
|
actingId.value = id;
|
||||||
actionError.value = null;
|
|
||||||
try {
|
try {
|
||||||
const session = await store.resumeSession(id);
|
const session = await store.resumeSession(id);
|
||||||
|
toasts.success(t('toast.sessionResumed'));
|
||||||
await router.push({ name: 'session', params: { id: session.id } });
|
await router.push({ name: 'session', params: { id: session.id } });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
actionError.value = err instanceof Error ? err.message : String(err);
|
toasts.error(err);
|
||||||
} finally {
|
} finally {
|
||||||
actingId.value = null;
|
actingId.value = null;
|
||||||
}
|
}
|
||||||
@@ -180,12 +174,12 @@ async function onResume(id: string): Promise<void> {
|
|||||||
|
|
||||||
async function onFork(id: string): Promise<void> {
|
async function onFork(id: string): Promise<void> {
|
||||||
actingId.value = id;
|
actingId.value = id;
|
||||||
actionError.value = null;
|
|
||||||
try {
|
try {
|
||||||
const session = await store.forkSession(id);
|
const session = await store.forkSession(id);
|
||||||
|
toasts.success(t('toast.sessionForked'));
|
||||||
await router.push({ name: 'session', params: { id: session.id } });
|
await router.push({ name: 'session', params: { id: session.id } });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
actionError.value = err instanceof Error ? err.message : String(err);
|
toasts.error(err);
|
||||||
} finally {
|
} finally {
|
||||||
actingId.value = null;
|
actingId.value = null;
|
||||||
}
|
}
|
||||||
@@ -195,6 +189,7 @@ async function onConfirmKill(id: string): Promise<void> {
|
|||||||
killing.value = true;
|
killing.value = true;
|
||||||
try {
|
try {
|
||||||
await store.killSession(id);
|
await store.killSession(id);
|
||||||
|
toasts.success(t('toast.sessionKilled'));
|
||||||
} catch {
|
} catch {
|
||||||
// l'état réel arrive par session_exit ; un échec (déjà morte) est sans gravité
|
// l'état réel arrive par session_exit ; un échec (déjà morte) est sans gravité
|
||||||
} finally {
|
} finally {
|
||||||
@@ -202,10 +197,4 @@ async function onConfirmKill(id: string): Promise<void> {
|
|||||||
killArmedId.value = null;
|
killArmedId.value = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onLogout(): Promise<void> {
|
|
||||||
store.stopRealtime();
|
|
||||||
await auth.logout();
|
|
||||||
await router.replace({ name: 'login' });
|
|
||||||
}
|
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
383
packages/web/src/views/SettingsView.vue
Normal file
383
packages/web/src/views/SettingsView.vue
Normal file
@@ -0,0 +1,383 @@
|
|||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<PageHeader :title="t('settings.title')" />
|
||||||
|
|
||||||
|
<!-- Préférences (client) -->
|
||||||
|
<section class="card flex flex-col gap-3">
|
||||||
|
<h2 class="flex items-center gap-2 text-sm font-semibold text-zinc-100">
|
||||||
|
<SlidersHorizontal :size="16" /> {{ t('settings.preferences') }}
|
||||||
|
</h2>
|
||||||
|
<p class="text-xs text-zinc-500">{{ t('settings.preferencesHint') }}</p>
|
||||||
|
|
||||||
|
<div class="flex items-center justify-between gap-3">
|
||||||
|
<span class="text-sm text-zinc-300">{{ t('settings.language') }}</span>
|
||||||
|
<LanguageSwitcher />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex flex-col gap-2 border-t border-zinc-800/80 pt-3">
|
||||||
|
<div class="flex items-center justify-between gap-3">
|
||||||
|
<div class="min-w-0">
|
||||||
|
<p class="text-sm text-zinc-300">{{ t('settings.notifications') }}</p>
|
||||||
|
<p class="text-xs text-zinc-500">
|
||||||
|
{{ push.supported ? (push.enabled ? t('settings.notificationsEnabled') : t('settings.notificationsDisabled')) : t('settings.pushUnsupported') }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<BaseButton
|
||||||
|
v-if="push.supported"
|
||||||
|
:variant="push.enabled ? 'secondary' : 'primary'"
|
||||||
|
size="sm"
|
||||||
|
:icon="push.enabled ? BellOff : Bell"
|
||||||
|
:loading="push.busy"
|
||||||
|
@click="push.toggle()"
|
||||||
|
>
|
||||||
|
{{ push.enabled ? t('settings.disableNotifications') : t('settings.enableNotifications') }}
|
||||||
|
</BaseButton>
|
||||||
|
</div>
|
||||||
|
<div v-if="push.enabled">
|
||||||
|
<BaseButton variant="ghost" size="sm" :icon="Send" :loading="testing" @click="sendTest">
|
||||||
|
{{ t('settings.testNotification') }}
|
||||||
|
</BaseButton>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- Accès & sécurité : tokens -->
|
||||||
|
<section class="card flex flex-col gap-3">
|
||||||
|
<h2 class="flex items-center gap-2 text-sm font-semibold text-zinc-100">
|
||||||
|
<Shield :size="16" /> {{ t('settings.security') }}
|
||||||
|
</h2>
|
||||||
|
<p class="text-xs text-zinc-500">{{ t('settings.securityHint') }}</p>
|
||||||
|
|
||||||
|
<!-- Création -->
|
||||||
|
<form class="flex flex-wrap items-end gap-2" @submit.prevent="createToken">
|
||||||
|
<label class="flex min-w-40 flex-1 flex-col gap-1">
|
||||||
|
<span class="text-xs text-zinc-400">{{ t('settings.newTokenLabel') }}</span>
|
||||||
|
<input v-model="newLabel" class="input" :placeholder="t('settings.newTokenPlaceholder')" maxlength="64" />
|
||||||
|
</label>
|
||||||
|
<BaseButton type="submit" variant="primary" :icon="Plus" :loading="creating" :disabled="!newLabel.trim()">
|
||||||
|
{{ t('settings.createToken') }}
|
||||||
|
</BaseButton>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<!-- Valeur en clair (une seule fois) -->
|
||||||
|
<div v-if="createdToken" class="card-inset flex flex-col gap-2 border-emerald-800/60 bg-emerald-950/20">
|
||||||
|
<p class="text-xs text-emerald-300">{{ t('settings.copyTokenHint') }}</p>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<code class="min-w-0 flex-1 truncate rounded bg-zinc-950 px-2 py-1 font-mono text-xs text-zinc-100">{{ createdToken.token }}</code>
|
||||||
|
<BaseButton size="sm" :icon="copiedNew ? Check : Copy" @click="copy(createdToken.token, 'new')">
|
||||||
|
{{ copiedNew ? t('settings.copied') : t('settings.copy') }}
|
||||||
|
</BaseButton>
|
||||||
|
<BaseButton size="sm" variant="ghost" icon-only :icon="X" :aria-label="t('common.close')" @click="createdToken = null" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Liste -->
|
||||||
|
<ul class="flex flex-col gap-2">
|
||||||
|
<li
|
||||||
|
v-for="tok in tokens"
|
||||||
|
:key="tok.id"
|
||||||
|
class="card-inset flex flex-wrap items-center gap-x-3 gap-y-1"
|
||||||
|
>
|
||||||
|
<KeyRound :size="15" class="shrink-0 text-zinc-500" />
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<p class="flex items-center gap-2 truncate text-sm text-zinc-200">
|
||||||
|
{{ tok.label }}
|
||||||
|
<span v-if="tok.current" class="badge bg-emerald-500/15 text-emerald-300">{{ t('settings.current') }}</span>
|
||||||
|
</p>
|
||||||
|
<p class="text-[11px] text-zinc-500">
|
||||||
|
{{ t('settings.created', { date: fmt(tok.createdAt) }) }} ·
|
||||||
|
{{ tok.lastUsedAt ? t('settings.lastUsed', { date: fmt(tok.lastUsedAt) }) : t('settings.neverUsed') }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<BaseButton
|
||||||
|
v-if="!tok.current"
|
||||||
|
size="sm"
|
||||||
|
:variant="confirmId === tok.id ? 'danger' : 'ghost'"
|
||||||
|
:icon="Trash2"
|
||||||
|
@click="revoke(tok)"
|
||||||
|
>
|
||||||
|
{{ confirmId === tok.id ? t('settings.confirmRevoke') : t('settings.revoke') }}
|
||||||
|
</BaseButton>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- Découverte des dépôts -->
|
||||||
|
<section class="card flex flex-col gap-3">
|
||||||
|
<h2 class="flex items-center gap-2 text-sm font-semibold text-zinc-100">
|
||||||
|
<ScanSearch :size="16" /> {{ t('settings.discovery') }}
|
||||||
|
</h2>
|
||||||
|
<p class="text-xs text-zinc-500">{{ t('settings.discoveryHint') }}</p>
|
||||||
|
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
<span class="text-xs text-zinc-400">{{ t('settings.scanRoots') }}</span>
|
||||||
|
<p v-if="rootsDraft.length === 0" class="text-xs text-zinc-600">{{ t('settings.scanRootsEmpty') }}</p>
|
||||||
|
<ul v-else class="flex flex-col gap-1">
|
||||||
|
<li v-for="(root, i) in rootsDraft" :key="root" class="card-inset flex items-center gap-2">
|
||||||
|
<span class="min-w-0 flex-1 truncate font-mono text-xs text-zinc-200" :title="root">{{ root }}</span>
|
||||||
|
<BaseButton size="sm" variant="ghost" icon-only :icon="X" :aria-label="t('settings.removeRoot')" @click="rootsDraft.splice(i, 1)" />
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<div>
|
||||||
|
<BaseButton size="sm" :icon="FolderOpen" @click="showRootPicker = !showRootPicker">{{ t('settings.addRoot') }}</BaseButton>
|
||||||
|
</div>
|
||||||
|
<DirectoryPicker v-if="showRootPicker" mode="dir" @select="onAddRoot" @close="showRootPicker = false" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<label class="flex flex-col gap-1">
|
||||||
|
<span class="text-xs text-zinc-400">{{ t('settings.scanInterval') }}</span>
|
||||||
|
<input v-model.number="intervalDraft" type="number" min="0" max="1440" class="input w-32" />
|
||||||
|
<span class="text-xs text-zinc-500">{{ t('settings.scanIntervalHint') }}</span>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<BaseButton variant="primary" :loading="settings.saving" :disabled="!discoveryDirty" @click="saveDiscovery">
|
||||||
|
{{ t('settings.save') }}
|
||||||
|
</BaseButton>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- Sécurité & conformité -->
|
||||||
|
<section class="card flex flex-col gap-3">
|
||||||
|
<h2 class="flex items-center gap-2 text-sm font-semibold text-zinc-100">
|
||||||
|
<Shield :size="16" /> {{ t('settings.compliance') }}
|
||||||
|
</h2>
|
||||||
|
<p class="text-xs text-zinc-500">{{ t('settings.complianceHint') }}</p>
|
||||||
|
<div class="flex flex-wrap gap-2">
|
||||||
|
<BaseButton size="sm" :icon="Download" :loading="exporting" @click="exportData">{{ t('settings.exportData') }}</BaseButton>
|
||||||
|
<BaseButton variant="ghost" size="sm" :icon="RefreshCw" :loading="auditing" @click="loadAudit">{{ t('settings.refreshAudit') }}</BaseButton>
|
||||||
|
<BaseButton variant="ghost" size="sm" :icon="Trash2" @click="deleteMyData">{{ t('settings.deleteData') }}</BaseButton>
|
||||||
|
</div>
|
||||||
|
<ul v-if="audit.length" class="flex flex-col divide-y divide-zinc-800/80 text-xs">
|
||||||
|
<li v-for="e in audit" :key="e.id" class="flex items-center justify-between gap-3 py-1.5">
|
||||||
|
<span class="font-mono text-zinc-300">{{ e.action }}</span>
|
||||||
|
<span class="truncate text-zinc-500">{{ e.actor }}</span>
|
||||||
|
<span class="shrink-0 text-zinc-600">{{ new Date(e.ts).toLocaleString() }}</span>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- Serveur (lecture seule) -->
|
||||||
|
<section class="card flex flex-col gap-3">
|
||||||
|
<h2 class="flex items-center gap-2 text-sm font-semibold text-zinc-100">
|
||||||
|
<Server :size="16" /> {{ t('settings.server') }}
|
||||||
|
</h2>
|
||||||
|
<p class="text-xs text-zinc-500">{{ t('settings.serverHint') }}</p>
|
||||||
|
<dl v-if="settings.server" class="flex flex-col divide-y divide-zinc-800/80">
|
||||||
|
<ServerRow :label="t('settings.version')" :value="settings.server.version" />
|
||||||
|
<ServerRow :label="t('settings.port')" :value="String(settings.server.port)" flag="--port" />
|
||||||
|
<ServerRow :label="t('settings.bind')" :value="settings.server.bind" flag="--bind" />
|
||||||
|
<ServerRow
|
||||||
|
:label="t('settings.allowedOrigins')"
|
||||||
|
:value="settings.server.allowedOrigins.length ? settings.server.allowedOrigins.join(', ') : t('settings.none')"
|
||||||
|
flag="--allow-origin"
|
||||||
|
/>
|
||||||
|
<ServerRow :label="t('settings.dataDir')" :value="settings.server.dataDir" />
|
||||||
|
<ServerRow :label="t('settings.vapidContact')" :value="settings.server.vapidContact" flag="--vapid-contact" />
|
||||||
|
<ServerRow :label="t('settings.vapidPublicKey')" :value="settings.server.vapidPublicKey ?? t('settings.none')" mono />
|
||||||
|
</dl>
|
||||||
|
<SkeletonRow v-else />
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- Support -->
|
||||||
|
<section class="card flex flex-col gap-3">
|
||||||
|
<h2 class="flex items-center gap-2 text-sm font-semibold text-zinc-100">
|
||||||
|
<Coffee :size="16" /> {{ t('settings.support') }}
|
||||||
|
</h2>
|
||||||
|
<p class="text-xs text-zinc-500">{{ t('settings.supportHint') }}</p>
|
||||||
|
<div>
|
||||||
|
<a
|
||||||
|
:href="BUYMEACOFFEE_URL"
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
class="inline-flex h-9 items-center justify-center gap-1.5 rounded-lg border border-zinc-700 bg-zinc-800 px-3 text-sm font-medium text-zinc-200 transition-colors hover:bg-zinc-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-500/70 focus-visible:ring-offset-2 focus-visible:ring-offset-zinc-950"
|
||||||
|
>
|
||||||
|
<Coffee :size="16" /> {{ t('settings.supportCta') }}
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, ref } from 'vue';
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { Bell, BellOff, Check, Coffee, Copy, Download, FolderOpen, KeyRound, Plus, RefreshCw, ScanSearch, Send, Server, Shield, SlidersHorizontal, Trash2, X } from '@lucide/vue';
|
||||||
|
import type {
|
||||||
|
AuditLogEntry,
|
||||||
|
AuditLogsResponse,
|
||||||
|
CreateTokenResponse,
|
||||||
|
DataExportResponse,
|
||||||
|
DeleteMyDataResponse,
|
||||||
|
TokenInfo,
|
||||||
|
TokensListResponse,
|
||||||
|
} from '@arboretum/shared';
|
||||||
|
import { api, ApiError } from '../lib/api';
|
||||||
|
import { BUYMEACOFFEE_URL } from '../lib/constants';
|
||||||
|
import { useSettingsStore } from '../stores/settings';
|
||||||
|
import { usePushStore } from '../stores/push';
|
||||||
|
import { useToastsStore } from '../stores/toasts';
|
||||||
|
import PageHeader from '../components/layout/PageHeader.vue';
|
||||||
|
import LanguageSwitcher from '../components/LanguageSwitcher.vue';
|
||||||
|
import BaseButton from '../components/ui/BaseButton.vue';
|
||||||
|
import SkeletonRow from '../components/ui/SkeletonRow.vue';
|
||||||
|
import ServerRow from '../components/settings/ServerRow.vue';
|
||||||
|
import DirectoryPicker from '../components/DirectoryPicker.vue';
|
||||||
|
|
||||||
|
const { t, locale } = useI18n();
|
||||||
|
const settings = useSettingsStore();
|
||||||
|
const push = usePushStore();
|
||||||
|
const toasts = useToastsStore();
|
||||||
|
|
||||||
|
// ---- Préférences ----
|
||||||
|
const testing = ref(false);
|
||||||
|
async function sendTest(): Promise<void> {
|
||||||
|
testing.value = true;
|
||||||
|
try {
|
||||||
|
await api.post('/api/v1/push/test');
|
||||||
|
toasts.success(t('settings.testSent'));
|
||||||
|
} catch (e) {
|
||||||
|
toasts.error(e);
|
||||||
|
} finally {
|
||||||
|
testing.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Tokens ----
|
||||||
|
const tokens = ref<TokenInfo[]>([]);
|
||||||
|
const newLabel = ref('');
|
||||||
|
const creating = ref(false);
|
||||||
|
const createdToken = ref<CreateTokenResponse | null>(null);
|
||||||
|
const confirmId = ref<string | null>(null);
|
||||||
|
const copiedNew = ref(false);
|
||||||
|
|
||||||
|
const fmt = (iso: string): string => new Date(iso).toLocaleString(locale.value);
|
||||||
|
|
||||||
|
async function loadTokens(): Promise<void> {
|
||||||
|
tokens.value = (await api.get<TokensListResponse>('/api/v1/auth/tokens')).tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createToken(): Promise<void> {
|
||||||
|
const label = newLabel.value.trim();
|
||||||
|
if (!label) return;
|
||||||
|
creating.value = true;
|
||||||
|
try {
|
||||||
|
createdToken.value = await api.post<CreateTokenResponse>('/api/v1/auth/tokens', { label });
|
||||||
|
newLabel.value = '';
|
||||||
|
toasts.success(t('settings.tokenCreated'));
|
||||||
|
await loadTokens();
|
||||||
|
} catch (e) {
|
||||||
|
toasts.error(e);
|
||||||
|
} finally {
|
||||||
|
creating.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function revoke(tok: TokenInfo): Promise<void> {
|
||||||
|
if (confirmId.value !== tok.id) {
|
||||||
|
confirmId.value = tok.id;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
confirmId.value = null;
|
||||||
|
try {
|
||||||
|
await api.delete(`/api/v1/auth/tokens/${tok.id}`);
|
||||||
|
toasts.success(t('settings.tokenRevoked'));
|
||||||
|
await loadTokens();
|
||||||
|
} catch (e) {
|
||||||
|
toasts.error(e instanceof ApiError && e.code === 'LAST_TOKEN' ? t('settings.lastTokenError') : e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copy(text: string, target?: 'new'): Promise<void> {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(text);
|
||||||
|
if (target === 'new') {
|
||||||
|
copiedNew.value = true;
|
||||||
|
setTimeout(() => (copiedNew.value = false), 1500);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* presse-papiers indisponible (http non sécurisé) : silencieux */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Découverte des dépôts ----
|
||||||
|
const rootsDraft = ref<string[]>([]);
|
||||||
|
const intervalDraft = ref(0);
|
||||||
|
const showRootPicker = ref(false);
|
||||||
|
const discoveryDirty = computed(
|
||||||
|
() =>
|
||||||
|
intervalDraft.value !== settings.scanIntervalMin ||
|
||||||
|
rootsDraft.value.length !== settings.scanRoots.length ||
|
||||||
|
rootsDraft.value.some((r, i) => r !== settings.scanRoots[i]),
|
||||||
|
);
|
||||||
|
function syncDiscoveryDraft(): void {
|
||||||
|
rootsDraft.value = [...settings.scanRoots];
|
||||||
|
intervalDraft.value = settings.scanIntervalMin;
|
||||||
|
}
|
||||||
|
function onAddRoot(path: string): void {
|
||||||
|
if (!rootsDraft.value.includes(path)) rootsDraft.value.push(path);
|
||||||
|
showRootPicker.value = false;
|
||||||
|
}
|
||||||
|
async function saveDiscovery(): Promise<void> {
|
||||||
|
try {
|
||||||
|
await settings.save({ scanRoots: rootsDraft.value, scanIntervalMin: intervalDraft.value });
|
||||||
|
syncDiscoveryDraft();
|
||||||
|
toasts.success(t('settings.saved'));
|
||||||
|
} catch (e) {
|
||||||
|
toasts.error(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Sécurité & conformité (audit / RGPD) ----
|
||||||
|
const audit = ref<AuditLogEntry[]>([]);
|
||||||
|
const auditing = ref(false);
|
||||||
|
const exporting = ref(false);
|
||||||
|
|
||||||
|
async function loadAudit(): Promise<void> {
|
||||||
|
auditing.value = true;
|
||||||
|
try {
|
||||||
|
audit.value = (await api.get<AuditLogsResponse>('/api/v1/audit-logs?limit=20')).entries;
|
||||||
|
} catch (e) {
|
||||||
|
toasts.error(e);
|
||||||
|
} finally {
|
||||||
|
auditing.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function exportData(): Promise<void> {
|
||||||
|
exporting.value = true;
|
||||||
|
try {
|
||||||
|
const data = await api.get<DataExportResponse>('/api/v1/data/export');
|
||||||
|
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = url;
|
||||||
|
a.download = 'arboretum-data-export.json';
|
||||||
|
a.click();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
} catch (e) {
|
||||||
|
toasts.error(e);
|
||||||
|
} finally {
|
||||||
|
exporting.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteMyData(): Promise<void> {
|
||||||
|
if (!window.confirm(t('settings.deleteConfirm'))) return;
|
||||||
|
try {
|
||||||
|
const pending = await api.post<DeleteMyDataResponse>('/api/v1/data/delete-my-data', {});
|
||||||
|
if (pending.status !== 'pending' || !pending.confirm) return;
|
||||||
|
const done = await api.post<DeleteMyDataResponse>('/api/v1/data/delete-my-data', { confirm: pending.confirm });
|
||||||
|
toasts.success(t('settings.deleteDone'));
|
||||||
|
if (done.summary.tokenRevoked) window.location.reload(); // token courant révoqué → re-login
|
||||||
|
} catch (e) {
|
||||||
|
toasts.error(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
await Promise.all([loadTokens(), settings.loaded ? Promise.resolve() : settings.fetch()]);
|
||||||
|
syncDiscoveryDraft();
|
||||||
|
void push.refresh();
|
||||||
|
});
|
||||||
|
</script>
|
||||||
352
packages/web/src/views/help-content.ts
Normal file
352
packages/web/src/views/help-content.ts
Normal file
@@ -0,0 +1,352 @@
|
|||||||
|
// Contenu de l'onglet Aide, bilingue. Texte long-format → gardé hors des fichiers i18n
|
||||||
|
// (en.ts/fr.ts) pour ne pas les alourdir. HelpView mappe chaque `id` vers une icône Lucide.
|
||||||
|
import type { AppLocale } from '../i18n';
|
||||||
|
|
||||||
|
export interface HelpItem {
|
||||||
|
title: string;
|
||||||
|
body: string;
|
||||||
|
}
|
||||||
|
export interface HelpSection {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
blurb: string;
|
||||||
|
items: HelpItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const en: HelpSection[] = [
|
||||||
|
{
|
||||||
|
id: 'gettingStarted',
|
||||||
|
title: 'Getting started & access',
|
||||||
|
blurb:
|
||||||
|
'Arboretum is a single daemon that serves this dashboard to drive your git worktrees and the Claude Code sessions running on them, from any device.',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
title: 'Sign in with a token',
|
||||||
|
body: 'On first start the daemon prints a one-time access token. Paste it on the login screen. You can create extra tokens (one per device) and revoke old ones in Settings → Access & security.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Remote access via Tailscale Serve',
|
||||||
|
body: 'The daemon binds to 127.0.0.1. To reach it from your phone, run tailscale serve --bg 7317 and start Arboretum with --allow-origin https://<machine>.<tailnet>.ts.net. The HTTPS that Tailscale provides is also what makes Web Push work.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Install as an app (PWA)',
|
||||||
|
body: 'On mobile, open Arboretum and choose Add to Home Screen. On iOS this install step is required before notifications can work.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'worktrees',
|
||||||
|
title: 'Repositories & worktrees',
|
||||||
|
blurb: 'Register your git repos, then spin up an isolated worktree per branch — each can auto-start a session.',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
title: 'Add a repository',
|
||||||
|
body: 'On the Worktrees page, type or browse to the absolute path of a git repo and add it. Per-repo post-create hooks (e.g. npm ci) run automatically on new worktrees.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Create a worktree',
|
||||||
|
body: 'In a repo section, click New worktree, enter a branch (optionally create it), and optionally start a claude or bash session in it. Hooks run automatically.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Read worktree state',
|
||||||
|
body: 'Each card shows the branch, ahead/behind counts, dirty file count and flags (main, locked, prunable), plus the live state of any linked session.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Delete & prune',
|
||||||
|
body: 'Delete a worktree from its card (force-delete if dirty or locked), or prune all orphaned worktrees at the repo level.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'sessions',
|
||||||
|
title: 'Sessions & the web terminal',
|
||||||
|
blurb: 'Run, observe, resume and answer Claude Code (or bash) sessions in a full xterm terminal, right in the browser.',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
title: 'Start a session',
|
||||||
|
body: 'On the Sessions page, set a working directory and a command (claude or bash) and launch. Open it to get an interactive terminal.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Discovered sessions',
|
||||||
|
body: 'Sessions you start in your own terminal are detected automatically and tagged as discovered. Observe them read-only, or resume/fork them once stopped.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Resume & fork',
|
||||||
|
body: 'Resume restarts a stopped session in its original working directory, with full scrollback replayed. Fork creates a fresh independent copy with the same command and cwd.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Observe vs interact',
|
||||||
|
body: 'Anyone opening a live session can type; open it as an observer for read-only monitoring that never slows the session down.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Fine-grained state',
|
||||||
|
body: 'Managed Claude sessions report waiting / busy / idle in real time. Waiting sessions are surfaced first and can trigger notifications.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Kill a session',
|
||||||
|
body: 'Kill a live session from its row (confirm to avoid accidents); it receives SIGTERM, then SIGKILL after a short grace delay.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'mobile',
|
||||||
|
title: 'Mobile supervision',
|
||||||
|
blurb: 'Keep sessions moving from your phone, without opening a terminal.',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
title: 'Needs attention',
|
||||||
|
body: 'A banner at the top of the dashboard lists every session blocked on a dialog, with inline answer buttons.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Answer dialogs',
|
||||||
|
body: 'When Claude asks for trust, a permission or a choice, pick an option (or Deny) right from the card — no terminal needed.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Web Push notifications',
|
||||||
|
body: 'Enable notifications in Settings (or the footer bell). You get a push when a session starts waiting; tap it to answer. Requires HTTPS; on iOS, install the app first.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'groups',
|
||||||
|
title: 'Work groups',
|
||||||
|
blurb: 'Bundle related repos (API, web, shared lib…) and operate on them together.',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
title: 'Create a group',
|
||||||
|
body: 'On the Groups page, name a group and pick its repos. Membership is lightweight and editable anytime.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'List vs terminal grid',
|
||||||
|
body: 'A group view shows all its repos worktrees and sessions as a list, or switch to the terminal grid to watch several live sessions side by side.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Cross-repo feature',
|
||||||
|
body: 'Create the same worktree (and an optional session) across every repo of the group in one action; partial failures can be retried per repo.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'productivity',
|
||||||
|
title: 'Productivity',
|
||||||
|
blurb: 'Find anything fast and tailor each list.',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
title: 'Command palette',
|
||||||
|
body: 'Press ⌘K (or Ctrl+K) to fuzzy-jump to any repo, worktree, session or group, or to run a quick action.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Sort, filter & search',
|
||||||
|
body: 'Every list has a toolbar to sort, filter (state, command, source, flags…) and search. Your choices persist in the URL, so links are shareable.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Pagination',
|
||||||
|
body: 'Long lists are paginated with a configurable page size; choose All to show everything at once.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Language',
|
||||||
|
body: 'Switch the interface between English and French anytime, from Settings or the footer.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'settings',
|
||||||
|
title: 'Settings & security',
|
||||||
|
blurb: 'Configure the app and manage who can reach the daemon.',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
title: 'Notifications',
|
||||||
|
body: 'Enable or disable Web Push and send a test notification from Settings → Preferences.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Access tokens',
|
||||||
|
body: 'Create a token per device and revoke any you no longer trust. A new token value is shown only once — copy it immediately. The last active token cannot be revoked, to avoid locking yourself out.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Server info',
|
||||||
|
body: 'Settings → Server shows the running version and the startup configuration (port, bind, allowed origins, data directory, VAPID). These are set via CLI flags and need a daemon restart to change.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'integrations',
|
||||||
|
title: 'Integrations',
|
||||||
|
blurb: 'Shortcuts to the tools around your repos.',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
title: 'Source code',
|
||||||
|
body: 'The “Source code” icon in the navigation always links to the Arboretum source repository on Gitea.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const fr: HelpSection[] = [
|
||||||
|
{
|
||||||
|
id: 'gettingStarted',
|
||||||
|
title: 'Prise en main & accès',
|
||||||
|
blurb:
|
||||||
|
'Arboretum est un daemon unique qui sert ce dashboard pour piloter vos worktrees git et les sessions Claude Code qui tournent dessus, depuis n’importe quel appareil.',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
title: 'Se connecter avec un jeton',
|
||||||
|
body: 'Au premier démarrage, le daemon affiche un jeton d’accès à usage unique. Collez-le sur l’écran de connexion. Vous pouvez créer des jetons supplémentaires (un par appareil) et révoquer les anciens dans Réglages → Accès & sécurité.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Accès distant via Tailscale Serve',
|
||||||
|
body: 'Le daemon écoute sur 127.0.0.1. Pour y accéder depuis votre téléphone, lancez tailscale serve --bg 7317 et démarrez Arboretum avec --allow-origin https://<machine>.<tailnet>.ts.net. Le HTTPS fourni par Tailscale est aussi ce qui permet au Web Push de fonctionner.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Installer comme une app (PWA)',
|
||||||
|
body: 'Sur mobile, ouvrez Arboretum et choisissez Ajouter à l’écran d’accueil. Sur iOS, cette installation est requise avant que les notifications puissent fonctionner.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'worktrees',
|
||||||
|
title: 'Dépôts & worktrees',
|
||||||
|
blurb: 'Enregistrez vos dépôts git, puis créez un worktree isolé par branche — chacun peut démarrer une session automatiquement.',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
title: 'Ajouter un dépôt',
|
||||||
|
body: 'Sur la page Worktrees, saisissez (ou parcourez) le chemin absolu d’un dépôt git et ajoutez-le. Les hooks post-création par dépôt (ex. npm ci) s’exécutent automatiquement sur les nouveaux worktrees.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Créer un worktree',
|
||||||
|
body: 'Dans une section de dépôt, cliquez sur Nouveau worktree, saisissez une branche (à créer éventuellement) et démarrez si besoin une session claude ou bash. Les hooks s’exécutent automatiquement.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Lire l’état d’un worktree',
|
||||||
|
body: 'Chaque carte affiche la branche, l’avance/le retard, le nombre de fichiers modifiés et des indicateurs (main, verrouillé, élagable), ainsi que l’état en direct de la session liée.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Supprimer & élaguer',
|
||||||
|
body: 'Supprimez un worktree depuis sa carte (suppression forcée s’il est sale ou verrouillé), ou élaguez tous les worktrees orphelins au niveau du dépôt.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'sessions',
|
||||||
|
title: 'Sessions & terminal web',
|
||||||
|
blurb: 'Lancez, observez, reprenez et répondez aux sessions Claude Code (ou bash) dans un vrai terminal xterm, directement dans le navigateur.',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
title: 'Démarrer une session',
|
||||||
|
body: 'Sur la page Sessions, indiquez un répertoire de travail et une commande (claude ou bash) puis lancez. Ouvrez-la pour obtenir un terminal interactif.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Sessions découvertes',
|
||||||
|
body: 'Les sessions lancées dans votre propre terminal sont détectées automatiquement et marquées « découvertes ». Observez-les en lecture seule, ou reprenez/forkez-les une fois arrêtées.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Reprendre & forker',
|
||||||
|
body: 'Reprendre relance une session arrêtée dans son répertoire d’origine, avec tout l’historique rejoué. Forker crée une copie indépendante neuve avec la même commande et le même cwd.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Observer ou interagir',
|
||||||
|
body: 'Quiconque ouvre une session vivante peut écrire ; ouvrez-la en observateur pour une supervision en lecture seule qui ne ralentit jamais la session.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'États fins',
|
||||||
|
body: 'Les sessions Claude gérées rapportent en temps réel les états en attente / occupé / inactif. Les sessions en attente sont remontées en premier et peuvent déclencher des notifications.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Arrêter une session',
|
||||||
|
body: 'Arrêtez une session vivante depuis sa ligne (confirmation pour éviter les accidents) ; elle reçoit SIGTERM, puis SIGKILL après un court délai de grâce.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'mobile',
|
||||||
|
title: 'Supervision mobile',
|
||||||
|
blurb: 'Faites avancer vos sessions depuis votre téléphone, sans ouvrir de terminal.',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
title: 'À traiter',
|
||||||
|
body: 'Une bannière en haut du dashboard liste toutes les sessions bloquées sur un dialogue, avec des boutons de réponse en ligne.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Répondre aux dialogues',
|
||||||
|
body: 'Quand Claude demande une confiance, une permission ou un choix, sélectionnez une option (ou Refuser) directement depuis la carte — sans terminal.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Notifications Web Push',
|
||||||
|
body: 'Activez les notifications dans Réglages (ou via la cloche du pied de page). Vous recevez un push quand une session passe en attente ; touchez-le pour répondre. Exige HTTPS ; sur iOS, installez d’abord l’app.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'groups',
|
||||||
|
title: 'Groupes de travail',
|
||||||
|
blurb: 'Regroupez des dépôts liés (API, web, lib partagée…) et agissez dessus ensemble.',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
title: 'Créer un groupe',
|
||||||
|
body: 'Sur la page Groupes, nommez un groupe et choisissez ses dépôts. L’appartenance est légère et modifiable à tout moment.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Liste ou grille de terminaux',
|
||||||
|
body: 'La vue d’un groupe affiche les worktrees et sessions de tous ses dépôts en liste, ou basculez sur la grille de terminaux pour suivre plusieurs sessions vivantes côte à côte.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Feature cross-repo',
|
||||||
|
body: 'Créez le même worktree (et une session optionnelle) dans chaque dépôt du groupe en une seule action ; les échecs partiels sont rejouables dépôt par dépôt.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'productivity',
|
||||||
|
title: 'Productivité',
|
||||||
|
blurb: 'Trouvez tout rapidement et adaptez chaque liste.',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
title: 'Palette de commandes',
|
||||||
|
body: 'Appuyez sur ⌘K (ou Ctrl+K) pour sauter en recherche floue vers n’importe quel dépôt, worktree, session ou groupe, ou lancer une action rapide.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Trier, filtrer & rechercher',
|
||||||
|
body: 'Chaque liste a une barre d’outils pour trier, filtrer (état, commande, source, indicateurs…) et rechercher. Vos choix persistent dans l’URL, donc les liens sont partageables.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Pagination',
|
||||||
|
body: 'Les longues listes sont paginées avec une taille de page configurable ; choisissez Tout pour afficher l’ensemble.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Langue',
|
||||||
|
body: 'Basculez l’interface entre l’anglais et le français à tout moment, depuis les Réglages ou le pied de page.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'settings',
|
||||||
|
title: 'Réglages & sécurité',
|
||||||
|
blurb: 'Configurez l’application et gérez qui peut atteindre le daemon.',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
title: 'Notifications',
|
||||||
|
body: 'Activez ou désactivez le Web Push et envoyez une notification de test depuis Réglages → Préférences.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Jetons d’accès',
|
||||||
|
body: 'Créez un jeton par appareil et révoquez ceux en lesquels vous n’avez plus confiance. La valeur d’un nouveau jeton n’est affichée qu’une seule fois — copiez-la immédiatement. Le dernier jeton actif ne peut pas être révoqué, pour éviter de vous verrouiller dehors.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Infos serveur',
|
||||||
|
body: 'Réglages → Serveur affiche la version en cours et la configuration de démarrage (port, bind, origines autorisées, répertoire de données, VAPID). Ces valeurs se définissent via des flags CLI et nécessitent un redémarrage du daemon.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'integrations',
|
||||||
|
title: 'Intégrations',
|
||||||
|
blurb: 'Des raccourcis vers les outils autour de vos dépôts.',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
title: 'Code source',
|
||||||
|
body: 'L’icône « Code source » de la navigation pointe toujours vers le dépôt source d’Arboretum sur Gitea.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export const helpSections: Record<AppLocale, HelpSection[]> = { en, fr };
|
||||||
87
packages/web/test/use-list-controls.test.ts
Normal file
87
packages/web/test/use-list-controls.test.ts
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { ref } from 'vue';
|
||||||
|
import { useListControls, type FilterDef, type SortDef } from '../src/composables/useListControls';
|
||||||
|
|
||||||
|
interface Item {
|
||||||
|
n: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const sorts: SortDef<Item>[] = [
|
||||||
|
{ key: 'n', labelKey: 'n', compare: (a, b) => a.n - b.n, defaultDir: 'asc' },
|
||||||
|
];
|
||||||
|
const filters: FilterDef<Item>[] = [
|
||||||
|
{
|
||||||
|
key: 'parity',
|
||||||
|
labelKey: 'parity',
|
||||||
|
options: [
|
||||||
|
{ value: 'even', label: 'even' },
|
||||||
|
{ value: 'odd', label: 'odd' },
|
||||||
|
],
|
||||||
|
predicate: (it, active) =>
|
||||||
|
(active.has('even') && it.n % 2 === 0) || (active.has('odd') && it.n % 2 === 1),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
function make() {
|
||||||
|
const source = ref<Item[]>([{ n: 5 }, { n: 2 }, { n: 4 }, { n: 1 }, { n: 3 }]);
|
||||||
|
const c = useListControls<Item>({ source: () => source.value, sorts, filters, defaultPageSize: 2 });
|
||||||
|
return { source, c };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('useListControls', () => {
|
||||||
|
it('trie en ascendant par défaut', () => {
|
||||||
|
const { c } = make();
|
||||||
|
expect(c.processed.value.map((i) => i.n)).toEqual([1, 2]); // page 1, taille 2
|
||||||
|
expect(c.total.value).toBe(5);
|
||||||
|
expect(c.pageCount.value).toBe(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('inverse la direction au re-clic de la même clé', () => {
|
||||||
|
const { c } = make();
|
||||||
|
c.setSort('n'); // même clé → desc
|
||||||
|
expect(c.sortDir.value).toBe('desc');
|
||||||
|
expect(c.processed.value.map((i) => i.n)).toEqual([5, 4]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('pagine et borne la page', () => {
|
||||||
|
const { c } = make();
|
||||||
|
c.setPage(3);
|
||||||
|
expect(c.processed.value.map((i) => i.n)).toEqual([5]);
|
||||||
|
c.setPage(99);
|
||||||
|
expect(c.page.value).toBe(3); // borné à pageCount
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filtre (OR intra-filtre) et revient page 1', () => {
|
||||||
|
const { c } = make();
|
||||||
|
c.setPage(2);
|
||||||
|
c.toggleFilter('parity', 'even');
|
||||||
|
expect(c.page.value).toBe(1);
|
||||||
|
expect(c.total.value).toBe(2); // 2 et 4
|
||||||
|
expect(c.processed.value.map((i) => i.n)).toEqual([2, 4]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('setSearch revient page 1, mais écrire search.value directement (hydratation) ne touche pas la page', () => {
|
||||||
|
const { c } = make();
|
||||||
|
c.setPage(3);
|
||||||
|
// hydratation URL : on écrit le ref directement → la page fournie par l'URL est préservée
|
||||||
|
c.search.value = '';
|
||||||
|
expect(c.page.value).toBe(3);
|
||||||
|
// saisie utilisateur via setSearch → retour page 1
|
||||||
|
c.setSearch('x');
|
||||||
|
expect(c.page.value).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('pageSize 0 affiche tout', () => {
|
||||||
|
const { c } = make();
|
||||||
|
c.setPageSize(0);
|
||||||
|
expect(c.pageCount.value).toBe(1);
|
||||||
|
expect(c.processed.value.map((i) => i.n)).toEqual([1, 2, 3, 4, 5]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reste réactif aux mutations de la source (upsert temps réel)', () => {
|
||||||
|
const { source, c } = make();
|
||||||
|
source.value = [...source.value, { n: 0 }];
|
||||||
|
expect(c.total.value).toBe(6);
|
||||||
|
expect(c.processed.value.map((i) => i.n)).toEqual([0, 1]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
# Spike S4 — Découverte JSONL + registre — VERDICT : ✅ GO
|
# Spike S4 — Découverte JSONL + registre — VERDICT : ✅ GO
|
||||||
|
|
||||||
Exécuté le 2026-06-11 sur la machine de Johan (CLI 2.1.170/2.1.173 actifs, transcripts 2.1.139 → 2.1.173). Script : `scan.mjs`, résultats bruts : `result.json`.
|
Exécuté sur un poste de dev (CLI 2.1.170/2.1.173 actifs, transcripts 2.1.139 → 2.1.173). Script : `scan.mjs`.
|
||||||
|
|
||||||
## Critères Go
|
## Critères Go
|
||||||
|
|
||||||
|
|||||||
@@ -1,141 +0,0 @@
|
|||||||
{
|
|
||||||
"scan": {
|
|
||||||
"files": 1318,
|
|
||||||
"bytes": 470368918,
|
|
||||||
"ok": 1316,
|
|
||||||
"noCwd": 2,
|
|
||||||
"noSessionId": 0,
|
|
||||||
"empty": 0,
|
|
||||||
"errors": 0,
|
|
||||||
"mb": "449",
|
|
||||||
"scanMs": "1368",
|
|
||||||
"okPct": "99.8 %"
|
|
||||||
},
|
|
||||||
"mungeValidation": {
|
|
||||||
"mungeMatch": 1316,
|
|
||||||
"mungeMismatch": 0,
|
|
||||||
"mismatchSamples": []
|
|
||||||
},
|
|
||||||
"lineTypes": {
|
|
||||||
"user": 1315,
|
|
||||||
"last-prompt": 1313,
|
|
||||||
"attachment": 1308,
|
|
||||||
"assistant": 1204,
|
|
||||||
"queue-operation": 1001,
|
|
||||||
"ai-title": 470,
|
|
||||||
"file-history-snapshot": 431,
|
|
||||||
"system": 398,
|
|
||||||
"permission-mode": 387,
|
|
||||||
"agent-name": 228,
|
|
||||||
"mode": 219,
|
|
||||||
"bridge-session": 6
|
|
||||||
},
|
|
||||||
"versions": {
|
|
||||||
"2.1.139": 16,
|
|
||||||
"2.1.140": 86,
|
|
||||||
"2.1.142": 19,
|
|
||||||
"2.1.143": 113,
|
|
||||||
"2.1.144": 58,
|
|
||||||
"2.1.145": 81,
|
|
||||||
"2.1.146": 43,
|
|
||||||
"2.1.150": 137,
|
|
||||||
"2.1.152": 59,
|
|
||||||
"2.1.153": 18,
|
|
||||||
"2.1.156": 80,
|
|
||||||
"2.1.159": 77,
|
|
||||||
"2.1.160": 58,
|
|
||||||
"2.1.161": 102,
|
|
||||||
"2.1.162": 60,
|
|
||||||
"2.1.163": 3,
|
|
||||||
"2.1.165": 20,
|
|
||||||
"2.1.166": 6,
|
|
||||||
"2.1.168": 83,
|
|
||||||
"2.1.169": 74,
|
|
||||||
"2.1.170": 90,
|
|
||||||
"2.1.173": 33
|
|
||||||
},
|
|
||||||
"registry": {
|
|
||||||
"count": 3,
|
|
||||||
"entries": [
|
|
||||||
{
|
|
||||||
"file": "1061541.json",
|
|
||||||
"pid": 1061541,
|
|
||||||
"sessionId": "026cc229-c1cd-4327-9c53-68406794e870",
|
|
||||||
"cwd": "/home/johan/WebstormProjects",
|
|
||||||
"status": "busy",
|
|
||||||
"waitingFor": null,
|
|
||||||
"kind": "interactive",
|
|
||||||
"version": "2.1.170",
|
|
||||||
"peerProtocol": 1,
|
|
||||||
"updatedAt": 1781192047718,
|
|
||||||
"alive": true,
|
|
||||||
"procStartOk": true
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"file": "1701999.json",
|
|
||||||
"pid": 1701999,
|
|
||||||
"sessionId": "8733906c-832a-4e74-aab7-7d8b2f5eb9d2",
|
|
||||||
"cwd": "/home/johan/WebstormProjects",
|
|
||||||
"status": "idle",
|
|
||||||
"waitingFor": null,
|
|
||||||
"kind": "interactive",
|
|
||||||
"version": "2.1.173",
|
|
||||||
"peerProtocol": 1,
|
|
||||||
"updatedAt": 1781191339305,
|
|
||||||
"alive": true,
|
|
||||||
"procStartOk": true
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"file": "597768.json",
|
|
||||||
"pid": 597768,
|
|
||||||
"sessionId": "95f8eaf3-feeb-4fbe-8848-fa7a994c8d7f",
|
|
||||||
"cwd": "/home/johan/WebstormProjects",
|
|
||||||
"status": "busy",
|
|
||||||
"waitingFor": null,
|
|
||||||
"kind": "interactive",
|
|
||||||
"version": "2.1.170",
|
|
||||||
"peerProtocol": 1,
|
|
||||||
"updatedAt": 1781192263383,
|
|
||||||
"alive": true,
|
|
||||||
"procStartOk": true
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"attachment": {
|
|
||||||
"inWebstormProjects": 573,
|
|
||||||
"outside": 743,
|
|
||||||
"topDirs": {
|
|
||||||
"(racine)": 323,
|
|
||||||
"beehelp_prospect": 133,
|
|
||||||
"techos_web": 31,
|
|
||||||
"beehelp_api": 27,
|
|
||||||
"techos_api": 23,
|
|
||||||
"beehelp_web": 15,
|
|
||||||
"teknoroot-simulator-web": 5,
|
|
||||||
"beehelp_claude_marketplace": 3,
|
|
||||||
"beehelp_lambdas": 2,
|
|
||||||
"teknoroot-simulator-api": 2,
|
|
||||||
"Beehelp_iac": 1,
|
|
||||||
"Techos_V1_outdated": 1,
|
|
||||||
"bee-tiptap-resolver": 1,
|
|
||||||
"beehelp_api-wt-qualiobee-docs": 1,
|
|
||||||
"beehelp_api-wt": 1
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"failuresSample": [
|
|
||||||
{
|
|
||||||
"fp": "/home/johan/.claude/projects/-home-johan-WebstormProjects-beehelp-api/0811ca37-c488-45aa-8a9e-5ecd6c87dfeb.jsonl",
|
|
||||||
"why": "pas de cwd",
|
|
||||||
"types": [
|
|
||||||
"queue-operation"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fp": "/home/johan/.claude/projects/-tmp/59e9a9f8-a5f2-4773-b1f6-72fa8b9514a9.jsonl",
|
|
||||||
"why": "pas de cwd",
|
|
||||||
"types": [
|
|
||||||
"queue-operation"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user