Compare commits
44 Commits
v1.0.1
...
06a400acc7
| Author | SHA1 | Date | |
|---|---|---|---|
| 06a400acc7 | |||
| a1fd00b046 | |||
| 057c2d55ed | |||
| cf7eb05aca | |||
| 663ae7ace1 | |||
| 5ebe3a0f37 | |||
| eb843be9c1 | |||
| f4fb6c3b52 | |||
| e84c6a7f6d | |||
| dacff2b98f | |||
| bf9c6ba8f3 | |||
| d02c1dabd4 | |||
| 86cdc1f597 | |||
| 1b57c3801c | |||
| 4e3b1f5604 | |||
| afe39ac072 | |||
| 5166b14d5c | |||
| 8036de2f0d | |||
| 08539f4ca6 | |||
| 915fdf185d | |||
| ea7b2fd278 | |||
| 4e1c5b2c33 | |||
| c6ea9f7930 | |||
| ca6700d6ce | |||
| dcb6cd1ec7 | |||
| 3b251c8174 | |||
| 8d3a47bd91 | |||
| 073f2cf9ca | |||
| 36bfeb057e | |||
| 7a3c119f36 | |||
| 813dfd952c | |||
| 693e6736de | |||
| 33295a7aaf | |||
| 755cba6b78 | |||
| fe2a3e66c7 | |||
| b070b74929 | |||
| c9670ca309 | |||
| 5c1c2a8591 | |||
| 9a4bb5efa1 | |||
| d6c110fc3b | |||
| c1390bfe06 | |||
| e38b3a5d5e | |||
| e6999011d1 | |||
| f446a3dda1 |
@@ -27,6 +27,7 @@ jobs:
|
|||||||
- run: npm ci
|
- run: npm ci
|
||||||
- run: npm run typecheck
|
- run: npm run typecheck
|
||||||
- run: npm run build
|
- run: npm run build
|
||||||
|
- run: npm run build:site
|
||||||
- run: npx vitest run
|
- run: npx vitest run
|
||||||
|
|
||||||
pack-smoke:
|
pack-smoke:
|
||||||
@@ -41,20 +42,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
|
||||||
55
.gitea/workflows/prod.yml
Normal file
55
.gitea/workflows/prod.yml
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
name: Deploy site (production)
|
||||||
|
|
||||||
|
# Déploie le site vitrine (packages/site) sur Plesk via FTPS (lftp), à l'identique
|
||||||
|
# de lidge_web / tracksniff-web. Ne se déclenche que sur un changement du site.
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
paths:
|
||||||
|
- 'packages/site/**'
|
||||||
|
- '.gitea/workflows/prod.yml'
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: deploy-site
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-and-deploy:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
container:
|
||||||
|
image: node:22-bookworm
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
# Install scopé au workspace du site : pas de build des deps natives du
|
||||||
|
# serveur (node-pty / node:sqlite) qui n'ont rien à faire ici.
|
||||||
|
- name: Install deps (@arboretum/site)
|
||||||
|
run: npm install -w @arboretum/site --no-audit --no-fund
|
||||||
|
|
||||||
|
- name: Build site
|
||||||
|
run: npm run build:site
|
||||||
|
|
||||||
|
- name: Check build output
|
||||||
|
run: ls -la packages/site/dist
|
||||||
|
|
||||||
|
- name: Deploy via FTPS (lftp)
|
||||||
|
run: |
|
||||||
|
if [ -z "$REMOTE_PATH" ]; then
|
||||||
|
echo "::error::Secret SITE_REMOTE_PATH manquant (chemin docroot du vhost git-arboretum.com)."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
apt-get update && apt-get install -y lftp
|
||||||
|
lftp -c "
|
||||||
|
open -u \"$FTP_USER\",\"$FTP_PASSWORD\" \"$FTP_HOST\"
|
||||||
|
set ssl:verify-certificate no
|
||||||
|
mirror -R --delete --verbose packages/site/dist \"$REMOTE_PATH\"
|
||||||
|
"
|
||||||
|
env:
|
||||||
|
FTP_HOST: ${{ secrets.FTP_HOST }}
|
||||||
|
FTP_USER: ${{ secrets.FTP_USER }}
|
||||||
|
FTP_PASSWORD: ${{ secrets.FTP_PASSWORD }}
|
||||||
|
# Chemin docroot du vhost git-arboretum.com sur Plesk (ex. /httpdocs/arboretum/public).
|
||||||
|
REMOTE_PATH: ${{ secrets.SITE_REMOTE_PATH }}
|
||||||
73
.gitea/workflows/release.yml
Normal file
73
.gitea/workflows/release.yml
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
# Publication du paquet @johanleroy/git-arboretum sur le registre npm du Gitea,
|
||||||
|
# déclenchée UNIQUEMENT par un tag vX.Y.Z (jamais sur un push de branche).
|
||||||
|
name: Release
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags: ['v*']
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
publish:
|
||||||
|
name: Publish to Gitea npm registry
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 22
|
||||||
|
registry-url: 'https://git.lidge.fr/api/packages/johanleroy/npm/'
|
||||||
|
scope: '@johanleroy'
|
||||||
|
cache: npm
|
||||||
|
- run: npm ci
|
||||||
|
- run: npm run build
|
||||||
|
# Garde-fou : le tag (sans le "v") doit correspondre à la version du paquet.
|
||||||
|
# GITHUB_REF_NAME est une variable d'env du runner (pas d'interpolation ${{ }} dans le shell).
|
||||||
|
- name: Verify tag matches package version
|
||||||
|
run: |
|
||||||
|
pkg=$(node -p "require('./packages/server/package.json').version")
|
||||||
|
tag="${GITHUB_REF_NAME#v}"
|
||||||
|
if [ "$pkg" != "$tag" ]; then
|
||||||
|
echo "ERREUR: tag '$tag' != version paquet '$pkg'"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "OK: tag $tag == version $pkg"
|
||||||
|
# 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:
|
||||||
|
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
|
||||||
74
.gitea/workflows/vscode-release.yml
Normal file
74
.gitea/workflows/vscode-release.yml
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
# Packaging du VSIX de l'extension VS Code, déclenché UNIQUEMENT par un tag vscode-vX.Y.Z
|
||||||
|
# (séparé de la release du daemon, qui écoute les tags v*). Le .vsix est exposé en artefact du run
|
||||||
|
# (toujours) et, en best-effort, attaché à la release Gitea correspondante.
|
||||||
|
name: VSCode Release
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags: ['vscode-v*']
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
package:
|
||||||
|
name: Package VSIX
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 22
|
||||||
|
cache: npm
|
||||||
|
- run: npm ci
|
||||||
|
# Garde-fou : le tag (sans "vscode-v") doit correspondre à la version du manifeste de l'extension.
|
||||||
|
- name: Verify tag matches extension version
|
||||||
|
run: |
|
||||||
|
pkg=$(node -p "require('./packages/vscode/package.json').version")
|
||||||
|
tag="${GITHUB_REF_NAME#vscode-v}"
|
||||||
|
if [ "$pkg" != "$tag" ]; then
|
||||||
|
echo "ERREUR: tag '$tag' != version extension '$pkg'"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "OK: tag $tag == version $pkg"
|
||||||
|
# Build du shared puis bundle esbuild de l'extension (typecheck inclus), puis packaging VSIX.
|
||||||
|
# --no-dependencies : tout est bundlé dans dist/extension.js → pas de node_modules dans le VSIX.
|
||||||
|
- name: Build & package
|
||||||
|
run: |
|
||||||
|
npm run build:vscode
|
||||||
|
version=$(node -p "require('./packages/vscode/package.json').version")
|
||||||
|
cd packages/vscode
|
||||||
|
npx --yes @vscode/vsce package --no-dependencies -o "git-arboretum-${version}.vsix"
|
||||||
|
# Artefact du run : canal de distribution fiable, indépendant de l'API release.
|
||||||
|
# upload-artifact@v3 : Gitea Actions ne supporte pas @v4 (@actions/artifact v2+).
|
||||||
|
- uses: actions/upload-artifact@v3
|
||||||
|
with:
|
||||||
|
name: vsix
|
||||||
|
path: packages/vscode/*.vsix
|
||||||
|
# Best-effort : attache le VSIX à la release Gitea du tag (crée la release si absente).
|
||||||
|
# Réutilise le secret NPM_TOKEN (même token Gitea que la publication du daemon — droits
|
||||||
|
# repository suffisants pour l'API release). Sans lui, l'étape est ignorée sans faire échouer
|
||||||
|
# le job (continue-on-error) ; le VSIX reste disponible en artefact.
|
||||||
|
- name: Attach VSIX to Gitea release
|
||||||
|
continue-on-error: true
|
||||||
|
env:
|
||||||
|
RELEASE_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||||
|
run: |
|
||||||
|
if [ -z "$RELEASE_TOKEN" ]; then
|
||||||
|
echo "::notice::NPM_TOKEN absent — VSIX disponible en artefact uniquement."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
api="${GITHUB_SERVER_URL}/api/v1/repos/${GITHUB_REPOSITORY}"
|
||||||
|
auth="Authorization: token ${RELEASE_TOKEN}"
|
||||||
|
version=$(node -p "require('./packages/vscode/package.json').version")
|
||||||
|
vsix="packages/vscode/git-arboretum-${version}.vsix"
|
||||||
|
# id de release du tag, sinon création
|
||||||
|
rid=$(curl -fsSL -H "$auth" "${api}/releases/tags/${GITHUB_REF_NAME}" | node -p "JSON.parse(require('fs').readFileSync(0,'utf8')).id || ''" || true)
|
||||||
|
if [ -z "$rid" ]; then
|
||||||
|
rid=$(curl -fsSL -X POST -H "$auth" -H 'Content-Type: application/json' \
|
||||||
|
-d "{\"tag_name\":\"${GITHUB_REF_NAME}\",\"name\":\"Arboretum VSCode ${version}\"}" \
|
||||||
|
"${api}/releases" | node -p "JSON.parse(require('fs').readFileSync(0,'utf8')).id || ''")
|
||||||
|
fi
|
||||||
|
curl -fsSL -X POST -H "$auth" -F "attachment=@${vsix}" \
|
||||||
|
"${api}/releases/${rid}/assets?name=git-arboretum-${version}.vsix"
|
||||||
|
echo "VSIX attaché à la release ${GITHUB_REF_NAME}."
|
||||||
42
.github/workflows/release.yml
vendored
42
.github/workflows/release.yml
vendored
@@ -1,42 +0,0 @@
|
|||||||
# Publication du paquet @johanleroy/git-arboretum sur le registre npm du Gitea,
|
|
||||||
# déclenchée UNIQUEMENT par un tag vX.Y.Z (jamais sur un push de branche).
|
|
||||||
name: Release
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
tags: ['v*']
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
packages: write
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
publish:
|
|
||||||
name: Publish to Gitea npm registry
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version: 22
|
|
||||||
registry-url: 'https://git.lidge.fr/api/packages/johanleroy/npm/'
|
|
||||||
scope: '@johanleroy'
|
|
||||||
cache: npm
|
|
||||||
- run: npm ci
|
|
||||||
- run: npm run build
|
|
||||||
# Garde-fou : le tag (sans le "v") doit correspondre à la version du paquet.
|
|
||||||
# GITHUB_REF_NAME est une variable d'env du runner (pas d'interpolation ${{ }} dans le shell).
|
|
||||||
- name: Verify tag matches package version
|
|
||||||
run: |
|
|
||||||
pkg=$(node -p "require('./packages/server/package.json').version")
|
|
||||||
tag="${GITHUB_REF_NAME#v}"
|
|
||||||
if [ "$pkg" != "$tag" ]; then
|
|
||||||
echo "ERREUR: tag '$tag' != version paquet '$pkg'"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
echo "OK: tag $tag == version $pkg"
|
|
||||||
- run: npm publish -w @johanleroy/git-arboretum
|
|
||||||
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 }}
|
|
||||||
100
README.fr.md
100
README.fr.md
@@ -10,7 +10,7 @@
|
|||||||
<a href="README.md">English</a> · <strong>Français</strong>
|
<a href="README.md">English</a> · <strong>Français</strong>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
**Statut : MVP.** Le dashboard worktree-first, la découverte et la reprise de sessions, le cycle de vie des worktrees multi-repo, les états de session en temps réel, le terminal web et la supervision mobile (PWA installable, Web Push quand une session vous attend, valider/refuser sans ouvrir de terminal) sont implémentés et testés.
|
**Statut : MVP.** Le dashboard worktree-first, la découverte et la reprise de sessions, le cycle de vie des worktrees multi-repo, le démarrage de sessions sur votre branche principale ou n'importe quel worktree, les états de session en temps réel, le terminal web, la supervision mobile (PWA installable, Web Push quand une session vous attend, répondre à une demande sans ouvrir de terminal) et les groupes de travail (piloter plusieurs repos liés depuis une seule session Claude) sont implémentés et testés.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -28,9 +28,11 @@ Un unique daemon Node.js que vous lancez sur votre machine de dev (`npx @johanle
|
|||||||
|
|
||||||
- **Dashboard worktree-first, multi-repo** — chaque worktree de chaque repo enregistré, avec son état git (branche, ahead/behind, fichiers modifiés) *et* l'état de sa session Claude Code (busy / en attente d'entrée / idle / reprenable).
|
- **Dashboard worktree-first, multi-repo** — chaque worktree de chaque repo enregistré, avec son état git (branche, ahead/behind, fichiers modifiés) *et* l'état de sa session Claude Code (busy / en attente d'entrée / idle / reprenable).
|
||||||
- **Cycle de vie complet des worktrees** — créer (avec des hooks post-création par repo : `npm ci`, copie de `.env`…), adopter des worktrees créés à la main, supprimer avec garde-fous, élaguer les orphelins.
|
- **Cycle de vie complet des worktrees** — créer (avec des hooks post-création par repo : `npm ci`, copie de `.env`…), adopter des worktrees créés à la main, supprimer avec garde-fous, élaguer les orphelins.
|
||||||
- **Découverte & reprise de sessions** — les sessions lancées dans votre propre terminal apparaissent automatiquement ; reprenez les sessions mortes, observez ou forkez les vivantes. Ne corrompt jamais une session vivante.
|
- **Découverte & reprise de sessions** — les sessions lancées dans votre propre terminal apparaissent automatiquement ; reprenez les sessions mortes, observez ou forkez les vivantes. Ne corrompt jamais une session vivante. Masquez les anciennes qui encombrent la liste (un clic efface tout l'historique externe ; elles restent reprenables).
|
||||||
- **Terminal web** — terminal xterm.js complet vers chaque session managée, qui survit aux déconnexions du navigateur.
|
- **Terminal web** — terminal xterm.js complet vers chaque session managée, qui survit aux déconnexions du navigateur ; vraiment plein écran, avec l'invite ancrée en bas et tout l'historique défilable au-dessus.
|
||||||
- **Supervision depuis votre téléphone** — PWA installable avec notifications push quand une session vous attend ; validez ou refusez une demande sans ouvrir de terminal.
|
- **Supervision depuis votre téléphone** — PWA installable avec notifications push quand une session vous attend ; répondez à une demande (ses options, ou refusez) sans ouvrir de terminal.
|
||||||
|
- **Groupes de travail** — regroupez des repos liés (ex. une API, son frontend web et sa doc) dans un groupe nommé, puis lancez **une seule session Claude qui les couvre tous à la fois** (via le flag `--add-dir` du CLI) : une conversation unique avec un contexte partagé travaillant à travers chaque repo, plus une vue unifiée de tous leurs worktrees et une grille multi-terminaux côte à côte. Une session de groupe peut d'abord créer le même worktree de branche dans chaque repo, ou tourner directement sur les checkouts principaux.
|
||||||
|
- **Extension VS Code** — une extension native (pas un webview) qui amène l'arbre en direct, les terminaux de session natifs, les alertes d'attente et les actions git directement dans votre éditeur. Voir [Extension VS Code](#extension-vs-code).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -42,6 +44,11 @@ Un unique daemon Node.js que vous lancez sur votre machine de dev (`npx @johanle
|
|||||||
|
|
||||||
## Démarrage rapide
|
## Démarrage rapide
|
||||||
|
|
||||||
|
Deux chemins, selon ce que vous voulez :
|
||||||
|
|
||||||
|
- **Juste l'utiliser (la plupart des gens).** Arboretum est un paquet npm publié — vous **n'avez pas besoin de cloner ce dépôt**. Pointez npm vers le registre et lancez-le (ci-dessous). À faire sur la machine où tournent vos sessions Claude Code.
|
||||||
|
- **Lancer depuis les sources.** Ne clonez le dépôt que pour développer Arboretum ou lancer une version non publiée.
|
||||||
|
|
||||||
### Le lancer (recommandé)
|
### Le lancer (recommandé)
|
||||||
|
|
||||||
Arboretum est publié sur un registre npm Gitea auto-hébergé. Pointez le scope `@johanleroy` dessus une fois par machine — ajoutez à `~/.npmrc` :
|
Arboretum est publié sur un registre npm Gitea auto-hébergé. Pointez le scope `@johanleroy` dessus une fois par machine — ajoutez à `~/.npmrc` :
|
||||||
@@ -70,8 +77,17 @@ Au premier démarrage, Arboretum affiche un **token d'accès** unique et l'URL
|
|||||||
|
|
||||||
Ouvrez l'URL, collez le token pour vous connecter, et c'est parti. Le token est stocké **hashé** — il n'est affiché qu'une seule fois, alors gardez-le en lieu sûr (un gestionnaire de mots de passe). Vous pourrez gérer vos tokens plus tard depuis les **Réglages**.
|
Ouvrez l'URL, collez le token pour vous connecter, et c'est parti. Le token est stocké **hashé** — il n'est affiché qu'une seule fois, alors gardez-le en lieu sûr (un gestionnaire de mots de passe). Vous pourrez gérer vos tokens plus tard depuis les **Réglages**.
|
||||||
|
|
||||||
|
`npx` télécharge et lance la dernière version publiée à chaque fois. Pour l'installer une bonne fois — et obtenir la commande `arboretum` sur votre `PATH`, dont se sert le [service d'arrière-plan](#le-faire-tourner-en-service-darrière-plan) —, installez-le plutôt globalement :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm i -g @johanleroy/git-arboretum
|
||||||
|
arboretum # identique à la commande npx, depuis le binaire installé
|
||||||
|
```
|
||||||
|
|
||||||
### Lancer depuis les sources
|
### Lancer depuis les sources
|
||||||
|
|
||||||
|
Nécessaire uniquement pour **développer** Arboretum ou lancer une version non publiée — pas pour simplement l'utiliser. Clonez le dépôt, installez les dépendances, buildez, puis démarrez le daemon :
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://git.lidge.fr/johanleroy/arboretum.git
|
git clone https://git.lidge.fr/johanleroy/arboretum.git
|
||||||
cd arboretum
|
cd arboretum
|
||||||
@@ -85,9 +101,27 @@ node packages/server/dist/index.js
|
|||||||
|
|
||||||
1. **Ajoutez un dépôt.** Depuis le dashboard, enregistrez un repo git local par son chemin. Configurez éventuellement des **hooks post-création** (ex. `npm ci`, `cp ../.env .env`) exécutés automatiquement à chaque création d'un nouveau worktree pour ce repo.
|
1. **Ajoutez un dépôt.** Depuis le dashboard, enregistrez un repo git local par son chemin. Configurez éventuellement des **hooks post-création** (ex. `npm ci`, `cp ../.env .env`) exécutés automatiquement à chaque création d'un nouveau worktree pour ce repo.
|
||||||
2. **Créez ou adoptez des worktrees.** Créez un nouveau worktree + branche en un clic (les hooks s'exécutent pour vous), ou adoptez un worktree créé à la main. Chaque worktree affiche sa branche, son ahead/behind et son nombre de fichiers modifiés.
|
2. **Créez ou adoptez des worktrees.** Créez un nouveau worktree + branche en un clic (les hooks s'exécutent pour vous), ou adoptez un worktree créé à la main. Chaque worktree affiche sa branche, son ahead/behind et son nombre de fichiers modifiés.
|
||||||
3. **Démarrez ou reprenez une session.** Lancez une session Claude Code sur un worktree, ou reprenez-en une démarrée dans votre terminal — Arboretum découvre les sessions existantes automatiquement et les reprend toujours dans leur répertoire de travail d'origine.
|
3. **Démarrez ou reprenez une session.** Lancez une session Claude Code sur la branche principale du repo ou n'importe quel worktree, ou reprenez-en une démarrée dans votre terminal — Arboretum découvre les sessions existantes automatiquement et les reprend toujours dans leur répertoire de travail d'origine.
|
||||||
4. **Suivez les états en direct.** Chaque session indique si elle est *busy*, *en attente de votre entrée* ou *idle*. Ouvrez le **terminal web** pour interagir directement ; il survit aux déconnexions du navigateur (fermer l'onglet ne tue pas la session).
|
4. **Suivez les états en direct.** Chaque session indique si elle est *busy*, *en attente de votre entrée* ou *idle*. Ouvrez le **terminal web** pour interagir directement ; il survit aux déconnexions du navigateur (fermer l'onglet ne tue pas la session).
|
||||||
5. **Supervisez depuis votre téléphone.** Installez la PWA, et quand une session bascule en *attente*, vous recevez une notification push. Validez ou refusez la demande directement depuis l'interface de notification — sans terminal.
|
5. **Supervisez depuis votre téléphone.** Installez la PWA, et quand une session bascule en *attente*, vous recevez une notification push. Répondez à la demande — choisissez l'une de ses options ou refusez-la — directement depuis le dashboard, sans terminal.
|
||||||
|
|
||||||
|
## Extension VS Code
|
||||||
|
|
||||||
|
Vous préférez rester dans votre éditeur ? Arboretum fournit une **extension VS Code native** (`packages/vscode`) — pas un webview. Elle se connecte au même daemon et l'expose avec les primitives natives de VS Code :
|
||||||
|
|
||||||
|
- Un arbre **Repositories** et **Groups** en direct (repos → worktrees → sessions) dans l'Activity Bar, mis à jour en temps réel via le WebSocket du daemon.
|
||||||
|
- **Terminaux natifs** : attachez-vous (ou observez) n'importe quelle session dans un vrai terminal VS Code — vous bénéficiez du rendu, du scrollback et du copier-coller de VS Code gratuitement.
|
||||||
|
- Un compteur en **status bar** et des **notifications** natives quand une session attend, avec réponses Oui/Non sans ouvrir de terminal.
|
||||||
|
- Les mutations git (créer un worktree, commit, push, promouvoir) et la **conscience du workspace** — le worktree de votre dossier ouvert est mis en évidence, avec « démarrer une session / créer un worktree ici » en un clic.
|
||||||
|
|
||||||
|
Elle est distribuée en **VSIX privé**. Buildez-la et packagez-la depuis le monorepo :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run build:vscode
|
||||||
|
cd packages/vscode && npx @vscode/vsce package --no-dependencies # → git-arboretum-0.1.0.vsix
|
||||||
|
```
|
||||||
|
|
||||||
|
Puis installez-la via **Extensions : Installer à partir d'un VSIX…** (ou `code --install-extension git-arboretum-0.1.0.vsix`), lancez **Arboretum: Sign In** et collez un token. Détails complets dans [`packages/vscode/README.md`](packages/vscode/README.md).
|
||||||
|
|
||||||
## Accès distant depuis votre téléphone
|
## Accès distant depuis votre téléphone
|
||||||
|
|
||||||
@@ -110,7 +144,26 @@ Ouvrez `https://<machine>.<tailnet>.ts.net` depuis n'importe quel appareil de vo
|
|||||||
|
|
||||||
## Le faire tourner en service d'arrière-plan
|
## Le faire tourner en service d'arrière-plan
|
||||||
|
|
||||||
Pour un daemon qui survit à la déconnexion et redémarre au boot, lancez-le via un **service systemd utilisateur**. Installez une version figée globalement (`npm i -g @johanleroy/git-arboretum`), puis créez `~/.config/systemd/user/arboretum.service` :
|
Le plus rapide pour faire tourner Arboretum en service qui survit à la déconnexion et redémarre au boot, c'est l'installeur intégré. Installez une version figée globalement, puis lancez `install` — il détecte votre OS, écrit le fichier de service, le démarre et affiche le token unique :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm i -g @johanleroy/git-arboretum
|
||||||
|
arboretum install --allow-origin https://MACHINE.TAILNET.ts.net
|
||||||
|
```
|
||||||
|
|
||||||
|
Cela met en place un **service systemd utilisateur** sous Linux (`~/.config/systemd/user/arboretum.service`) ou un **LaunchAgent launchd** sous macOS (`~/Library/LaunchAgents/fr.lidge.arboretum.plist`). Tous les flags du daemon (`--port`, `--allow-origin`, `--db`, …) sont propagés au service. Gérez-le avec :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
arboretum status # état du service (+ où lire les logs)
|
||||||
|
arboretum uninstall # arrête et supprime le service
|
||||||
|
```
|
||||||
|
|
||||||
|
Les logs vivent dans `journalctl --user -u arboretum -f` (Linux) ou `~/Library/Logs/arboretum/` (macOS). Lancez d'abord `arboretum install --dry-run …` pour afficher le unit/plist et les commandes exactes sans rien modifier.
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Vous préférez configurer systemd à la main ? (Linux)</summary>
|
||||||
|
|
||||||
|
Créez `~/.config/systemd/user/arboretum.service` :
|
||||||
|
|
||||||
```ini
|
```ini
|
||||||
[Unit]
|
[Unit]
|
||||||
@@ -137,12 +190,15 @@ systemctl --user enable --now arboretum
|
|||||||
loginctl enable-linger "$USER" # démarre le service au boot, sans session ouverte
|
loginctl enable-linger "$USER" # démarre le service au boot, sans session ouverte
|
||||||
journalctl --user -u arboretum -f # logs
|
journalctl --user -u arboretum -f # logs
|
||||||
```
|
```
|
||||||
|
</details>
|
||||||
|
|
||||||
> Le **token d'accès** unique n'est affiché qu'au tout premier démarrage (base vierge). En service, récupérez-le depuis `journalctl`, ou faites un lancement manuel avant d'activer le service. Le token est hashé et n'est jamais réaffiché.
|
> Le **token d'accès** unique est affiché par `arboretum install` (et au tout premier lancement manuel sur base vierge). Le token est hashé et n'est jamais réaffiché — conservez-le en lieu sûr.
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
Toutes les options sont des flags CLI :
|
Commandes : `arboretum` démarre le daemon (par défaut), `arboretum serve` en est un alias explicite, `arboretum install` / `uninstall` / `status` gèrent le service d'arrière-plan, et `arboretum help` affiche l'aide.
|
||||||
|
|
||||||
|
Les options du daemon sont des flags CLI :
|
||||||
|
|
||||||
| Flag | Défaut | Description |
|
| Flag | Défaut | Description |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
@@ -154,6 +210,15 @@ Toutes les options sont des flags CLI :
|
|||||||
| `--print-token` | `false` | Indication sur le réaffichage du token (les tokens sont hashés et ne peuvent pas être réaffichés). |
|
| `--print-token` | `false` | Indication sur le réaffichage du token (les tokens sont hashés et ne peuvent pas être réaffichés). |
|
||||||
| `--i-know-this-exposes-a-terminal` | `false` | Reconnaître le bind sur une adresse non-loopback. **À éviter** — préférez Tailscale Serve. |
|
| `--i-know-this-exposes-a-terminal` | `false` | Reconnaître le bind sur une adresse non-loopback. **À éviter** — préférez Tailscale Serve. |
|
||||||
|
|
||||||
|
`arboretum install` accepte tous les flags du daemon ci-dessus (propagés tels quels au service), plus :
|
||||||
|
|
||||||
|
| Flag | Description |
|
||||||
|
|---|---|
|
||||||
|
| `--bin-path <path>` | Utilise ce binaire dans le service au lieu de `node` + le script embarqué. |
|
||||||
|
| `--label <id>` | Label launchd (macOS uniquement, défaut `fr.lidge.arboretum`). |
|
||||||
|
| `--dry-run` | Affiche le unit/plist et les commandes sans rien appliquer. |
|
||||||
|
| `--no-enable` | Écrit le fichier de service sans l'activer/le démarrer. |
|
||||||
|
|
||||||
L'état (la base SQLite) vit dans `$XDG_DATA_HOME/arboretum` (par défaut `~/.local/share/arboretum`).
|
L'état (la base SQLite) vit dans `$XDG_DATA_HOME/arboretum` (par défaut `~/.local/share/arboretum`).
|
||||||
|
|
||||||
## Modèle de sécurité
|
## Modèle de sécurité
|
||||||
@@ -162,9 +227,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. 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é).
|
||||||
|
|
||||||
La façon recommandée d'atteindre Arboretum depuis d'autres appareils est Tailscale Serve (HTTPS valide, identité tailnet, aucun port ouvert). Ne l'exposez jamais 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
|
||||||
|
|
||||||
@@ -185,7 +254,7 @@ Arboretum enveloppe le CLI Claude Code **interactif** dans un PTY — la même c
|
|||||||
|
|
||||||
## Développement
|
## Développement
|
||||||
|
|
||||||
Arboretum est un monorepo npm workspaces : `@arboretum/shared` (protocole WS/REST, source de vérité), `@johanleroy/git-arboretum` (le daemon Fastify, le paquet publié) et `@arboretum/web` (la SPA Vue 3).
|
Arboretum est un monorepo npm workspaces : `@arboretum/shared` (protocole WS/REST, source de vérité), `@johanleroy/git-arboretum` (le daemon Fastify, le paquet publié), `@arboretum/web` (la SPA Vue 3) et `git-arboretum` (l'extension VS Code — buildée séparément avec `npm run build:vscode`).
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm run build # build shared → server → web (l'ordre compte)
|
npm run build # build shared → server → web (l'ordre compte)
|
||||||
@@ -202,8 +271,15 @@ node packages/server/scripts/acceptance-p1.mjs # cœur : daemon + client WS r
|
|||||||
node packages/server/scripts/acceptance-p2.mjs # découverte & reprise de sessions
|
node packages/server/scripts/acceptance-p2.mjs # découverte & reprise de sessions
|
||||||
node packages/server/scripts/acceptance-p3.mjs # worktrees & corrélation de sessions
|
node packages/server/scripts/acceptance-p3.mjs # worktrees & corrélation de sessions
|
||||||
node packages/server/scripts/acceptance-p4.mjs # Web Push + commande WS `answer`
|
node packages/server/scripts/acceptance-p4.mjs # Web Push + commande WS `answer`
|
||||||
|
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).
|
||||||
|
|||||||
100
README.md
100
README.md
@@ -10,7 +10,7 @@
|
|||||||
<strong>English</strong> · <a href="README.fr.md">Français</a>
|
<strong>English</strong> · <a href="README.fr.md">Français</a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
**Status: MVP.** The worktree-first dashboard, session discovery & resume, multi-repo worktree lifecycle, live session states, the web terminal, and mobile supervision (installable PWA, Web Push when a session needs you, approve/deny without opening a terminal) are implemented and tested.
|
**Status: MVP.** The worktree-first dashboard, session discovery & resume, multi-repo worktree lifecycle, sessions on your main branch or any worktree, live session states, the web terminal, mobile supervision (installable PWA, Web Push when a session needs you, answer a prompt without opening a terminal), and work groups (drive several related repos from a single Claude session) are implemented and tested.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -28,9 +28,11 @@ A single Node.js daemon you run on your dev machine (`npx @johanleroy/git-arbore
|
|||||||
|
|
||||||
- **Worktree-first, multi-repo dashboard** — every worktree of every registered repo, with its git state (branch, ahead/behind, dirty files) *and* the state of its Claude Code session (busy / waiting for input / idle / resumable).
|
- **Worktree-first, multi-repo dashboard** — every worktree of every registered repo, with its git state (branch, ahead/behind, dirty files) *and* the state of its Claude Code session (busy / waiting for input / idle / resumable).
|
||||||
- **Full worktree lifecycle** — create (with per-repo post-create hooks: `npm ci`, copy `.env`…), adopt worktrees created by hand, delete with guardrails, prune orphans.
|
- **Full worktree lifecycle** — create (with per-repo post-create hooks: `npm ci`, copy `.env`…), adopt worktrees created by hand, delete with guardrails, prune orphans.
|
||||||
- **Session discovery & resume** — sessions you launched in your own terminal show up automatically; resume dead ones, observe or fork live ones. Never corrupts a live session.
|
- **Session discovery & resume** — sessions you launched in your own terminal show up automatically; resume dead ones, observe or fork live ones. Never corrupts a live session. Hide the old ones that clutter the list (one click clears the whole external history; they stay resumable).
|
||||||
- **Web terminal** — full xterm.js terminal to every managed session, surviving browser disconnects.
|
- **Web terminal** — full xterm.js terminal to every managed session, surviving browser disconnects; truly fullscreen, with the prompt pinned to the bottom and full scrollback above.
|
||||||
- **Supervision from your phone** — installable PWA with push notifications when a session needs you; approve/deny a prompt without opening a terminal.
|
- **Supervision from your phone** — installable PWA with push notifications when a session needs you; answer a prompt (its options, or deny) without opening a terminal.
|
||||||
|
- **Work groups** — bundle related repos (e.g. an API, its web frontend and its docs) into a named group, then launch **one Claude session that spans all of them at once** (via the CLI's `--add-dir`): a single conversation with one shared context working across every repo, plus a unified view of all their worktrees and a side-by-side multi-terminal grid. Group sessions can either create the same branch worktree in each repo first, or run straight on the main checkouts.
|
||||||
|
- **VS Code extension** — a native extension (not a webview) that brings the live tree, native session terminals, waiting alerts and git actions right into your editor. See [VS Code extension](#vs-code-extension).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -42,6 +44,11 @@ A single Node.js daemon you run on your dev machine (`npx @johanleroy/git-arbore
|
|||||||
|
|
||||||
## Quick start
|
## Quick start
|
||||||
|
|
||||||
|
Two paths, depending on what you want:
|
||||||
|
|
||||||
|
- **Just use it (most people).** Arboretum is a published npm package — you **don't need to clone this repo**. Point npm at the registry and run it (below). Do this on the machine where your Claude Code sessions run.
|
||||||
|
- **Run from source.** Clone the repo only to hack on Arboretum or run an unreleased build.
|
||||||
|
|
||||||
### Run it (recommended)
|
### Run it (recommended)
|
||||||
|
|
||||||
Arboretum is published to a self-hosted Gitea npm registry. Point the `@johanleroy` scope at it once per machine — add to `~/.npmrc`:
|
Arboretum is published to a self-hosted Gitea npm registry. Point the `@johanleroy` scope at it once per machine — add to `~/.npmrc`:
|
||||||
@@ -70,8 +77,17 @@ On first start, Arboretum prints a one-time **access token** and the URL to open
|
|||||||
|
|
||||||
Open the URL, paste the token to log in, and you're in. The token is stored **hashed** — it is shown only once, so save it somewhere safe (a password manager). You can manage tokens later from **Settings**.
|
Open the URL, paste the token to log in, and you're in. The token is stored **hashed** — it is shown only once, so save it somewhere safe (a password manager). You can manage tokens later from **Settings**.
|
||||||
|
|
||||||
|
`npx` fetches and runs the latest published version each time. To install it once — and get the `arboretum` command on your `PATH`, which the [background service](#running-it-as-a-background-service) relies on — install it globally instead:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm i -g @johanleroy/git-arboretum
|
||||||
|
arboretum # identical to the npx command, from the installed binary
|
||||||
|
```
|
||||||
|
|
||||||
### Run from source
|
### Run from source
|
||||||
|
|
||||||
|
Only needed to **develop** Arboretum or run an unreleased build — not required just to use it. Clone the repo, install dependencies, build, then start the daemon:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://git.lidge.fr/johanleroy/arboretum.git
|
git clone https://git.lidge.fr/johanleroy/arboretum.git
|
||||||
cd arboretum
|
cd arboretum
|
||||||
@@ -85,9 +101,27 @@ node packages/server/dist/index.js
|
|||||||
|
|
||||||
1. **Add a repository.** From the dashboard, register a local git repo by its path. Optionally configure **post-create hooks** (e.g. `npm ci`, `cp ../.env .env`) that run automatically every time you create a new worktree for that repo.
|
1. **Add a repository.** From the dashboard, register a local git repo by its path. Optionally configure **post-create hooks** (e.g. `npm ci`, `cp ../.env .env`) that run automatically every time you create a new worktree for that repo.
|
||||||
2. **Create or adopt worktrees.** Spin up a new worktree + branch in one click (hooks run for you), or adopt a worktree you created by hand. Each worktree shows its branch, ahead/behind, and dirty-file count.
|
2. **Create or adopt worktrees.** Spin up a new worktree + branch in one click (hooks run for you), or adopt a worktree you created by hand. Each worktree shows its branch, ahead/behind, and dirty-file count.
|
||||||
3. **Start or resume a session.** Launch a Claude Code session on a worktree, or resume one that was started in your terminal — Arboretum discovers existing sessions automatically and always resumes them in their original working directory.
|
3. **Start or resume a session.** Launch a Claude Code session on the repo's main branch or any worktree, or resume one that was started in your terminal — Arboretum discovers existing sessions automatically and always resumes them in their original working directory.
|
||||||
4. **Watch the live states.** Each session reports whether it's *busy*, *waiting for your input*, or *idle*. Open the **web terminal** to interact directly; it survives browser disconnects (closing the tab does not kill the session).
|
4. **Watch the live states.** Each session reports whether it's *busy*, *waiting for your input*, or *idle*. Open the **web terminal** to interact directly; it survives browser disconnects (closing the tab does not kill the session).
|
||||||
5. **Supervise from your phone.** Install the PWA, and when a session flips to *waiting* you get a push notification. Approve or deny the prompt straight from the notification UI — no terminal required.
|
5. **Supervise from your phone.** Install the PWA, and when a session flips to *waiting* you get a push notification. Answer the prompt — pick one of its options or deny it — straight from the dashboard, no terminal required.
|
||||||
|
|
||||||
|
## VS Code extension
|
||||||
|
|
||||||
|
Prefer to stay in your editor? Arboretum ships a **native VS Code extension** (`packages/vscode`) — not a webview. It connects to the same daemon and surfaces it with VS Code's own primitives:
|
||||||
|
|
||||||
|
- A live **Repositories** and **Groups** tree (repos → worktrees → sessions) in the Activity Bar, updated in real time over the daemon's WebSocket.
|
||||||
|
- **Native terminals**: attach to (or observe) any session in a real VS Code terminal — you get VS Code's rendering, scrollback and copy/paste for free.
|
||||||
|
- A **status-bar** counter and native **notifications** when a session is waiting, with Yes/No answers without opening a terminal.
|
||||||
|
- Git mutations (create worktree, commit, push, promote) and **workspace awareness** — the worktree for your open folder is highlighted, with one-click "start session / create worktree here".
|
||||||
|
|
||||||
|
It is distributed as a **private VSIX**. Build and package it from the monorepo:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run build:vscode
|
||||||
|
cd packages/vscode && npx @vscode/vsce package --no-dependencies # → git-arboretum-0.1.0.vsix
|
||||||
|
```
|
||||||
|
|
||||||
|
Then install it via **Extensions: Install from VSIX…** (or `code --install-extension git-arboretum-0.1.0.vsix`), run **Arboretum: Sign In** and paste a token. Full details in [`packages/vscode/README.md`](packages/vscode/README.md).
|
||||||
|
|
||||||
## Remote access from your phone
|
## Remote access from your phone
|
||||||
|
|
||||||
@@ -110,7 +144,26 @@ Open `https://<machine>.<tailnet>.ts.net` from any device on your tailnet. **Web
|
|||||||
|
|
||||||
## Running it as a background service
|
## Running it as a background service
|
||||||
|
|
||||||
For a daemon that survives logout and restarts on boot, run it under a **systemd user service**. Install a pinned version globally (`npm i -g @johanleroy/git-arboretum`), then create `~/.config/systemd/user/arboretum.service`:
|
The quickest way to run Arboretum as a service that survives logout and restarts on boot is the built-in installer. Install a pinned version globally, then run `install` — it detects your OS, writes the service file, starts it, and prints the one-time token:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm i -g @johanleroy/git-arboretum
|
||||||
|
arboretum install --allow-origin https://MACHINE.TAILNET.ts.net
|
||||||
|
```
|
||||||
|
|
||||||
|
This sets up a **systemd user service** on Linux (`~/.config/systemd/user/arboretum.service`) or a **launchd LaunchAgent** on macOS (`~/Library/LaunchAgents/fr.lidge.arboretum.plist`). Every daemon flag (`--port`, `--allow-origin`, `--db`, …) is propagated to the service. Manage it with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
arboretum status # service status (+ where to read logs)
|
||||||
|
arboretum uninstall # stop and remove the service
|
||||||
|
```
|
||||||
|
|
||||||
|
Logs live in `journalctl --user -u arboretum -f` (Linux) or `~/Library/Logs/arboretum/` (macOS). Run `arboretum install --dry-run …` first to print the unit/plist and the exact commands without touching anything.
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Prefer to set up systemd by hand? (Linux)</summary>
|
||||||
|
|
||||||
|
Create `~/.config/systemd/user/arboretum.service`:
|
||||||
|
|
||||||
```ini
|
```ini
|
||||||
[Unit]
|
[Unit]
|
||||||
@@ -137,12 +190,15 @@ systemctl --user enable --now arboretum
|
|||||||
loginctl enable-linger "$USER" # start the service at boot, without an open session
|
loginctl enable-linger "$USER" # start the service at boot, without an open session
|
||||||
journalctl --user -u arboretum -f # logs
|
journalctl --user -u arboretum -f # logs
|
||||||
```
|
```
|
||||||
|
</details>
|
||||||
|
|
||||||
> The one-time **access token is printed only on the very first run** (empty database). When running as a service, capture it from `journalctl`, or do one manual run before enabling the service. The token is hashed and never shown again.
|
> The one-time **access token is printed by `arboretum install`** (and on the very first manual run with an empty database). The token is hashed and never shown again — store it safely.
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
All options are CLI flags:
|
Commands: `arboretum` starts the daemon (the default), `arboretum serve` is an explicit alias, `arboretum install` / `uninstall` / `status` manage the background service, and `arboretum help` prints usage.
|
||||||
|
|
||||||
|
Daemon options are CLI flags:
|
||||||
|
|
||||||
| Flag | Default | Description |
|
| Flag | Default | Description |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
@@ -154,6 +210,15 @@ All options are CLI flags:
|
|||||||
| `--print-token` | `false` | Hint about token re-printing (tokens are hashed and cannot be re-shown). |
|
| `--print-token` | `false` | Hint about token re-printing (tokens are hashed and cannot be re-shown). |
|
||||||
| `--i-know-this-exposes-a-terminal` | `false` | Acknowledge binding to a non-loopback address. **Avoid** — prefer Tailscale Serve. |
|
| `--i-know-this-exposes-a-terminal` | `false` | Acknowledge binding to a non-loopback address. **Avoid** — prefer Tailscale Serve. |
|
||||||
|
|
||||||
|
`arboretum install` accepts every daemon flag above (propagated verbatim to the service) plus:
|
||||||
|
|
||||||
|
| Flag | Description |
|
||||||
|
|---|---|
|
||||||
|
| `--bin-path <path>` | Use this binary in the service instead of `node` + the bundled script. |
|
||||||
|
| `--label <id>` | launchd label (macOS only, default `fr.lidge.arboretum`). |
|
||||||
|
| `--dry-run` | Print the unit/plist and commands without applying anything. |
|
||||||
|
| `--no-enable` | Write the service file but do not enable/start it. |
|
||||||
|
|
||||||
State (the SQLite database) lives in `$XDG_DATA_HOME/arboretum` (default `~/.local/share/arboretum`).
|
State (the SQLite database) lives in `$XDG_DATA_HOME/arboretum` (default `~/.local/share/arboretum`).
|
||||||
|
|
||||||
## Security model
|
## Security model
|
||||||
@@ -162,9 +227,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. 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).
|
||||||
|
|
||||||
The recommended way to reach Arboretum from other devices is Tailscale Serve (valid HTTPS, tailnet identity, no open ports). Never expose it 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
|
||||||
|
|
||||||
@@ -185,7 +254,7 @@ Arboretum wraps the **interactive** Claude Code CLI in a PTY — the same thing
|
|||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
Arboretum is an npm-workspaces monorepo: `@arboretum/shared` (WS/REST protocol, source of truth), `@johanleroy/git-arboretum` (the Fastify daemon, the published package), and `@arboretum/web` (the Vue 3 SPA).
|
Arboretum is an npm-workspaces monorepo: `@arboretum/shared` (WS/REST protocol, source of truth), `@johanleroy/git-arboretum` (the Fastify daemon, the published package), `@arboretum/web` (the Vue 3 SPA), and `git-arboretum` (the VS Code extension — built separately with `npm run build:vscode`).
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm run build # build shared → server → web (order matters)
|
npm run build # build shared → server → web (order matters)
|
||||||
@@ -202,8 +271,15 @@ node packages/server/scripts/acceptance-p1.mjs # core: daemon + real WS client
|
|||||||
node packages/server/scripts/acceptance-p2.mjs # session discovery & resume
|
node packages/server/scripts/acceptance-p2.mjs # session discovery & resume
|
||||||
node packages/server/scripts/acceptance-p3.mjs # worktrees & session correlation
|
node packages/server/scripts/acceptance-p3.mjs # worktrees & session correlation
|
||||||
node packages/server/scripts/acceptance-p4.mjs # Web Push + WS `answer` command
|
node packages/server/scripts/acceptance-p4.mjs # Web Push + WS `answer` command
|
||||||
|
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.
|
||||||
3701
package-lock.json
generated
3701
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -15,7 +15,12 @@
|
|||||||
"pack": "npm run build && npm pack -w @johanleroy/git-arboretum",
|
"pack": "npm run build && npm pack -w @johanleroy/git-arboretum",
|
||||||
"test": "vitest run",
|
"test": "vitest run",
|
||||||
"dev:server": "npm run dev -w @johanleroy/git-arboretum",
|
"dev:server": "npm run dev -w @johanleroy/git-arboretum",
|
||||||
"dev:web": "npm run dev -w @arboretum/web"
|
"dev:web": "npm run dev -w @arboretum/web",
|
||||||
|
"build:site": "npm run build -w @arboretum/site",
|
||||||
|
"dev:site": "npm run dev -w @arboretum/site",
|
||||||
|
"preview:site": "npm run preview -w @arboretum/site",
|
||||||
|
"build:vscode": "npm run build -w @arboretum/shared -w git-arboretum",
|
||||||
|
"dev:vscode": "npm run dev -w git-arboretum"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "^22.10.0",
|
"@types/node": "^22.10.0",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@johanleroy/git-arboretum",
|
"name": "@johanleroy/git-arboretum",
|
||||||
"version": "1.0.1",
|
"version": "1.9.0",
|
||||||
"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 = '';
|
||||||
@@ -144,6 +144,37 @@ try {
|
|||||||
const out = c.state.outputs.get(att?.channel) ?? '';
|
const out = c.state.outputs.get(att?.channel) ?? '';
|
||||||
check('resume lance `--resume sid-dead` dans le bon cwd', out.includes('args=[--resume sid-dead]') && out.includes(`cwd=${workDir}`), out.replace(/\s+/g, ' ').slice(0, 120));
|
check('resume lance `--resume sid-dead` dans le bon cwd', out.includes('args=[--resume sid-dead]') && out.includes(`cwd=${workDir}`), out.replace(/\s+/g, ' ').slice(0, 120));
|
||||||
|
|
||||||
|
// --- Régression « Reprendre » : reprise d'une session MANAGÉE morte par son UUID Arboretum ---
|
||||||
|
// (le bouton web envoie l'UUID managé, pas le claudeSessionId ; le serveur doit le résoudre en DB).
|
||||||
|
const createManaged = await fetch(`${ORIGIN}/api/v1/sessions`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json', Origin: ORIGIN, Cookie: cookie },
|
||||||
|
body: JSON.stringify({ cwd: workDir, command: 'claude' }),
|
||||||
|
});
|
||||||
|
const managed = (await createManaged.json()).session;
|
||||||
|
check('création session managée claude → 201 (pid)', createManaged.status === 201 && managed?.pid > 0);
|
||||||
|
|
||||||
|
// Simule la capture du claudeSessionId : entrée registre pour le pid du PTY managé (pollée toutes les 400ms).
|
||||||
|
writeFileSync(
|
||||||
|
join(sessions, `${managed.pid}.json`),
|
||||||
|
JSON.stringify({ pid: managed.pid, sessionId: 'sid-managed', cwd: workDir, status: 'idle' }),
|
||||||
|
);
|
||||||
|
const captured = await c.waitMsg(
|
||||||
|
(m) => m.type === 'session_update' && m.session?.id === managed.id && m.session?.claudeSessionId === 'sid-managed',
|
||||||
|
);
|
||||||
|
check('claudeSessionId capturé depuis le registre (session managée)', !!captured);
|
||||||
|
|
||||||
|
// Fermeture (kill) puis reprise par UUID managé → 201 dans le cwd d'origine (avant le fix : 404).
|
||||||
|
const killManaged = await fetch(`${ORIGIN}/api/v1/sessions/${managed.id}`, { method: 'DELETE', headers: { Origin: ORIGIN, Cookie: cookie } });
|
||||||
|
check('kill session managée → 200', killManaged.status === 200);
|
||||||
|
await sleep(400); // laisse handleExit persister ended_at
|
||||||
|
const resumeManaged = await postJson(`/api/v1/sessions/${managed.id}/resume`, cookie);
|
||||||
|
const resumedManaged = (await resumeManaged.json()).session;
|
||||||
|
check(
|
||||||
|
'resume d’une session MANAGÉE morte par UUID → 201',
|
||||||
|
resumeManaged.status === 201 && resumedManaged?.command === 'claude' && resumedManaged?.source === 'managed' && resumedManaged?.cwd === workDir,
|
||||||
|
);
|
||||||
|
|
||||||
// Broadcast : une nouvelle session découverte est poussée via session_update au rafraîchissement périodique.
|
// Broadcast : une nouvelle session découverte est poussée via session_update au rafraîchissement périodique.
|
||||||
writeJsonl(workDir, 'sid-new');
|
writeJsonl(workDir, 'sid-new');
|
||||||
const pushed = await c.waitMsg((m) => m.type === 'session_update' && m.session?.id === 'sid-new', 13000);
|
const pushed = await c.waitMsg((m) => m.type === 'session_update' && m.session?.id === 'sid-new', 13000);
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Vrai daemon + vrai repo git tmp. Couvre : enregistrement repo, création worktree avec hook
|
// Vrai daemon + vrai repo git tmp. Couvre : enregistrement repo, création worktree avec hook
|
||||||
// post-create, broadcast WS worktree_update, corrélation worktree↔session (bash), suppression.
|
// post-create, broadcast WS worktree_update, corrélation worktree↔session (bash), suppression.
|
||||||
import { spawn, execFileSync } from 'node:child_process';
|
import { spawn, execFileSync } from 'node:child_process';
|
||||||
import { mkdtempSync, rmSync, existsSync } from 'node:fs';
|
import { mkdtempSync, rmSync, existsSync, writeFileSync } from 'node:fs';
|
||||||
import { tmpdir } from 'node:os';
|
import { tmpdir } from 'node:os';
|
||||||
import { join, dirname, basename } from 'node:path';
|
import { join, dirname, basename } from 'node:path';
|
||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from 'node:url';
|
||||||
@@ -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 = '';
|
||||||
@@ -119,6 +119,24 @@ try {
|
|||||||
const feat = wlist1.worktrees.find((w) => w.branch === 'feat');
|
const feat = wlist1.worktrees.find((w) => w.branch === 'feat');
|
||||||
check('corrélation worktree ↔ session (cwd)', feat?.sessions?.some((s) => s.command === 'bash' && s.live));
|
check('corrélation worktree ↔ session (cwd)', feat?.sessions?.some((s) => s.command === 'bash' && s.live));
|
||||||
|
|
||||||
|
// Session sur le checkout principal (« bosser sur la branche principale ») avec création de branche.
|
||||||
|
const mainSess = await j(`/api/v1/repos/${repoSummary.id}/session`, 'POST', cookie, { command: 'bash', branch: 'mainfeat', newBranch: true });
|
||||||
|
const mainBody = await mainSess.json();
|
||||||
|
check('POST repo session → 201 (bash)', mainSess.status === 201 && mainBody.session?.command === 'bash');
|
||||||
|
check('session de branche principale : cwd = checkout principal', mainBody.session?.cwd === repoSummary.path);
|
||||||
|
const mainPush = await c.waitMsg((m) => m.type === 'worktree_update' && m.worktree?.isMain && m.worktree?.branch === 'mainfeat');
|
||||||
|
check('broadcast worktree_update (branche principale basculée)', !!mainPush);
|
||||||
|
await sleep(300);
|
||||||
|
const wlistM = await (await j('/api/v1/worktrees', 'GET', cookie)).json();
|
||||||
|
const mainWt = wlistM.worktrees.find((w) => w.isMain);
|
||||||
|
check('session corrélée au checkout principal', mainWt?.branch === 'mainfeat' && mainWt.sessions.some((s) => s.id === mainBody.session.id));
|
||||||
|
|
||||||
|
// Refus 409 quand le checkout principal est sale.
|
||||||
|
writeFileSync(join(repo, 'scratch.txt'), 'wip\n');
|
||||||
|
const dirtyRefused = await j(`/api/v1/repos/${repoSummary.id}/session`, 'POST', cookie, { command: 'bash', branch: 'other', newBranch: true });
|
||||||
|
check('repo session sur checkout sale → 409', dirtyRefused.status === 409);
|
||||||
|
rmSync(join(repo, 'scratch.txt'), { force: true });
|
||||||
|
|
||||||
// Suppression forcée (une session vit dans le worktree).
|
// Suppression forcée (une session vit dans le worktree).
|
||||||
const refused = await j(`/api/v1/repos/${repoSummary.id}/worktrees?path=${encodeURIComponent(wtPath)}&force=false`, 'DELETE', cookie);
|
const refused = await j(`/api/v1/repos/${repoSummary.id}/worktrees?path=${encodeURIComponent(wtPath)}&force=false`, 'DELETE', cookie);
|
||||||
check('delete sans force (session live) → 409', refused.status === 409);
|
check('delete sans force (session live) → 409', refused.status === 409);
|
||||||
|
|||||||
@@ -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 = '';
|
||||||
|
|||||||
216
packages/server/scripts/acceptance-p5.mjs
Normal file
216
packages/server/scripts/acceptance-p5.mjs
Normal file
@@ -0,0 +1,216 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Acceptation P5 (sans navigateur, sans quota Claude) : groupes de travail.
|
||||||
|
// Vrai daemon + vrai repo git tmp. Couvre : CRUD groupe via REST, broadcast WS group_update/
|
||||||
|
// group_removed sur le topic 'groups', ajout/retrait de repo, et purge CASCADE de la membership
|
||||||
|
// quand le repo est supprimé (PRAGMA foreign_keys = ON).
|
||||||
|
import { spawn, execFileSync } from 'node:child_process';
|
||||||
|
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join, dirname } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const WebSocket = require('ws');
|
||||||
|
|
||||||
|
const PORT = 7545;
|
||||||
|
const ORIGIN = `http://127.0.0.1:${PORT}`;
|
||||||
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
const results = [];
|
||||||
|
const check = (name, ok, detail = '') => {
|
||||||
|
results.push({ name, ok, detail });
|
||||||
|
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? ` — ${detail}` : ''}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p5-'));
|
||||||
|
function initRepo(path) {
|
||||||
|
execFileSync('mkdir', ['-p', path]);
|
||||||
|
const git = (...args) => execFileSync('git', args, { cwd: path, stdio: 'pipe' });
|
||||||
|
git('init', '-b', 'main');
|
||||||
|
git('config', 'user.email', 'test@arboretum.dev');
|
||||||
|
git('config', 'user.name', 'Test');
|
||||||
|
execFileSync('bash', ['-lc', 'echo "# demo" > README.md'], { cwd: path });
|
||||||
|
git('add', '-A');
|
||||||
|
git('commit', '-m', 'init');
|
||||||
|
}
|
||||||
|
const repo = join(tmp, 'demo-repo');
|
||||||
|
const repo2 = join(tmp, 'demo-repo-2');
|
||||||
|
initRepo(repo);
|
||||||
|
initRepo(repo2);
|
||||||
|
|
||||||
|
const srv = spawn(
|
||||||
|
'node',
|
||||||
|
[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'] },
|
||||||
|
);
|
||||||
|
let srvOut = '';
|
||||||
|
srv.stdout.on('data', (d) => (srvOut += d));
|
||||||
|
srv.stderr.on('data', (d) => (srvOut += d));
|
||||||
|
|
||||||
|
function wsClient(cookie) {
|
||||||
|
const ws = new WebSocket(`ws://127.0.0.1:${PORT}/ws`, { headers: { Origin: ORIGIN, Cookie: cookie } });
|
||||||
|
const state = { msgs: [] };
|
||||||
|
ws.on('message', (data, isBinary) => {
|
||||||
|
if (!isBinary) state.msgs.push(JSON.parse(String(data)));
|
||||||
|
});
|
||||||
|
const waitMsg = async (pred, timeout = 8000) => {
|
||||||
|
const t0 = Date.now();
|
||||||
|
while (Date.now() - t0 < timeout) {
|
||||||
|
const m = state.msgs.find(pred);
|
||||||
|
if (m) return m;
|
||||||
|
await sleep(50);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
return { ws, state, waitMsg, send: (m) => ws.send(JSON.stringify(m)) };
|
||||||
|
}
|
||||||
|
|
||||||
|
const j = (path, method, cookie, body) =>
|
||||||
|
fetch(`${ORIGIN}${path}`, {
|
||||||
|
method,
|
||||||
|
headers: { Origin: ORIGIN, Cookie: cookie, ...(body ? { 'Content-Type': 'application/json' } : {}) },
|
||||||
|
...(body ? { body: JSON.stringify(body) } : {}),
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await sleep(1500);
|
||||||
|
const token = /arb_[0-9a-f]+/.exec(srvOut)?.[0];
|
||||||
|
check('boot + token bootstrap', !!token);
|
||||||
|
|
||||||
|
const login = await fetch(`${ORIGIN}/api/v1/auth/login`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json', Origin: ORIGIN },
|
||||||
|
body: JSON.stringify({ token }),
|
||||||
|
});
|
||||||
|
const cookie = login.headers.get('set-cookie')?.split(';')[0] ?? '';
|
||||||
|
check('login → cookie', login.status === 200);
|
||||||
|
|
||||||
|
const c = wsClient(cookie);
|
||||||
|
await new Promise((res, rej) => (c.ws.on('open', res), c.ws.on('error', rej)));
|
||||||
|
c.send({ type: 'hello', protocol: 1 });
|
||||||
|
await c.waitMsg((m) => m.type === 'hello_ok');
|
||||||
|
c.send({ type: 'sub', topics: ['sessions', 'worktrees', 'groups'] });
|
||||||
|
|
||||||
|
// Enregistrement d'un repo (cible de la membership).
|
||||||
|
const addRepo = await j('/api/v1/repos', 'POST', cookie, { path: repo });
|
||||||
|
const repoSummary = (await addRepo.json()).repo;
|
||||||
|
check('POST /repos → 201', addRepo.status === 201 && repoSummary?.valid === true);
|
||||||
|
|
||||||
|
// Création d'un groupe vide via REST → broadcast WS group_update.
|
||||||
|
const created = await j('/api/v1/groups', 'POST', cookie, { label: 'Sprint 42', color: '#4f46e5' });
|
||||||
|
const group = (await created.json()).group;
|
||||||
|
check('POST /groups → 201', created.status === 201 && group?.label === 'Sprint 42' && group?.repoIds.length === 0);
|
||||||
|
const pushedCreate = await c.waitMsg((m) => m.type === 'group_update' && m.group?.id === group.id);
|
||||||
|
check('broadcast WS group_update (création)', !!pushedCreate);
|
||||||
|
|
||||||
|
const list = await (await j('/api/v1/groups', 'GET', cookie)).json();
|
||||||
|
check('GET /groups → groupe présent', list.groups?.some((g) => g.id === group.id));
|
||||||
|
|
||||||
|
// Ajout du repo au groupe → group_update avec repoIds peuplé.
|
||||||
|
const added = await j(`/api/v1/groups/${group.id}/repos`, 'POST', cookie, { repoId: repoSummary.id });
|
||||||
|
const addedBody = await added.json();
|
||||||
|
check('POST /groups/:id/repos → repoIds', added.status === 200 && addedBody.group?.repoIds.includes(repoSummary.id));
|
||||||
|
const pushedAdd = await c.waitMsg((m) => m.type === 'group_update' && m.group?.repoIds?.includes(repoSummary.id));
|
||||||
|
check('broadcast WS group_update (ajout repo)', !!pushedAdd);
|
||||||
|
|
||||||
|
// ---- P6 : session de groupe multi-repo (UNE session couvrant tous les repos via --add-dir) ----
|
||||||
|
// Enregistre un 2e repo, l'ajoute au groupe, puis lance UNE session de groupe (bash, sans quota).
|
||||||
|
const addRepo2 = await j('/api/v1/repos', 'POST', cookie, { path: repo2 });
|
||||||
|
const repo2Summary = (await addRepo2.json()).repo;
|
||||||
|
check('POST /repos (2e repo) → 201', addRepo2.status === 201 && repo2Summary?.valid === true);
|
||||||
|
await j(`/api/v1/groups/${group.id}/repos`, 'POST', cookie, { repoId: repo2Summary.id });
|
||||||
|
|
||||||
|
// Mode « checkouts principaux » (pas de branch) : couvre le worktree principal de chaque repo.
|
||||||
|
const gsRes = await j(`/api/v1/groups/${group.id}/session`, 'POST', cookie, { command: 'bash' });
|
||||||
|
const gsBody = await gsRes.json();
|
||||||
|
const gsession = gsBody.session;
|
||||||
|
check('POST /groups/:id/session → 201', gsRes.status === 201 && !!gsession);
|
||||||
|
check('session de groupe : 2 répertoires couverts', Array.isArray(gsBody.dirs) && gsBody.dirs.length === 2);
|
||||||
|
// cwd = parent commun des repos (P6), chaque repo relié en --add-dir → 2 addedDirs.
|
||||||
|
check('session de groupe : cwd = parent commun des repos', gsession?.cwd === tmp);
|
||||||
|
check('session de groupe : addedDirs = les 2 repos', (gsession?.addedDirs?.length ?? 0) === 2);
|
||||||
|
check('session de groupe : groupId posé', gsession?.groupId === group.id);
|
||||||
|
check('session de groupe : cwd parent + 2 repos addedDirs = 3 chemins distincts', new Set([gsession?.cwd, ...(gsession?.addedDirs ?? [])]).size === 3);
|
||||||
|
|
||||||
|
// La session apparaît dans la liste globale avec son groupId.
|
||||||
|
const sessList = await (await j('/api/v1/sessions', 'GET', cookie)).json();
|
||||||
|
const listed = sessList.sessions?.find((s) => s.id === gsession.id);
|
||||||
|
check('GET /sessions : session de groupe présente avec groupId', listed?.groupId === group.id);
|
||||||
|
|
||||||
|
// broadcast WS session_update reçu pour la session de groupe.
|
||||||
|
const pushedSession = await c.waitMsg((m) => m.type === 'session_update' && m.session?.id === gsession.id);
|
||||||
|
check('broadcast WS session_update (session de groupe)', !!pushedSession);
|
||||||
|
|
||||||
|
// ---- Worktree de groupe sur une NOUVELLE branche (scénario corrigé : mode auto, plus de -b raté) ----
|
||||||
|
const wtA = await j(`/api/v1/repos/${repoSummary.id}/worktrees`, 'POST', cookie, { branch: 'feature/cross', mode: 'auto', startSession: null });
|
||||||
|
const wtABody = await wtA.json();
|
||||||
|
check('POST /repos/:id/worktrees (branche neuve) → 201 + action=created', wtA.status === 201 && wtABody.action === 'created');
|
||||||
|
const wtB = await j(`/api/v1/repos/${repo2Summary.id}/worktrees`, 'POST', cookie, { branch: 'feature/cross', mode: 'auto', startSession: null });
|
||||||
|
check('POST /repos (2e repo) worktree branche neuve → 201', wtB.status === 201);
|
||||||
|
|
||||||
|
// GET /branches : la nouvelle branche apparaît (alimente le sélecteur de base côté UI).
|
||||||
|
const branchesA = await (await j(`/api/v1/repos/${repoSummary.id}/branches`, 'GET', cookie)).json();
|
||||||
|
check('GET /repos/:id/branches : feature/cross présente', Array.isArray(branchesA.local) && branchesA.local.includes('feature/cross'));
|
||||||
|
|
||||||
|
// session de groupe SUR cette branche → résout les worktrees créés (le cas qui échouait avant).
|
||||||
|
const gsBranch = await j(`/api/v1/groups/${group.id}/session`, 'POST', cookie, { command: 'bash', branch: 'feature/cross' });
|
||||||
|
const gsBranchBody = await gsBranch.json();
|
||||||
|
check('POST /groups/:id/session (branche) → 201 + 2 dirs', gsBranch.status === 201 && gsBranchBody.dirs?.length === 2);
|
||||||
|
await j(`/api/v1/sessions/${gsBranchBody.session.id}`, 'DELETE', cookie);
|
||||||
|
|
||||||
|
// commit : fichier neuf dans le worktree de repo1 puis commit via l'endpoint.
|
||||||
|
writeFileSync(join(wtABody.worktree.path, 'cross.txt'), 'wip\n');
|
||||||
|
const commitRes = await j(`/api/v1/repos/${repoSummary.id}/worktrees/commit`, 'POST', cookie, { path: wtABody.worktree.path, message: 'wip cross' });
|
||||||
|
check('POST /worktrees/commit → 200 + dirty=0', commitRes.status === 200 && (await commitRes.json()).worktree?.git?.dirtyCount === 0);
|
||||||
|
|
||||||
|
// promotion « en principal » : feature/cross devient le checkout principal de repo1, worktree supprimé.
|
||||||
|
const promRes = await j(`/api/v1/repos/${repoSummary.id}/worktrees/promote`, 'POST', cookie, { path: wtABody.worktree.path });
|
||||||
|
check('POST /worktrees/promote → 200', promRes.status === 200);
|
||||||
|
const wtsAfter = await (await j(`/api/v1/repos/${repoSummary.id}/worktrees`, 'GET', cookie)).json();
|
||||||
|
check('promotion : checkout principal désormais sur feature/cross', wtsAfter.worktrees?.find((w) => w.isMain)?.branch === 'feature/cross');
|
||||||
|
|
||||||
|
// groupe sans worktree résolu (branche inexistante) → 400.
|
||||||
|
const gsBad = await j(`/api/v1/groups/${group.id}/session`, 'POST', cookie, { command: 'bash', branch: 'no/such/branch' });
|
||||||
|
check('POST /groups/:id/session branche absente → 400', gsBad.status === 400);
|
||||||
|
|
||||||
|
// Arrêt de la session de groupe + nettoyage du 2e repo (CASCADE retire repo2 de la membership).
|
||||||
|
const killSession = await j(`/api/v1/sessions/${gsession.id}`, 'DELETE', cookie);
|
||||||
|
check('DELETE session de groupe → 200', killSession.status === 200);
|
||||||
|
await j(`/api/v1/repos/${repo2Summary.id}`, 'DELETE', cookie);
|
||||||
|
|
||||||
|
// Renommage via PATCH.
|
||||||
|
const patched = await j(`/api/v1/groups/${group.id}`, 'PATCH', cookie, { label: 'Renamed' });
|
||||||
|
check('PATCH /groups/:id → 200 (renommé)', patched.status === 200 && (await patched.json()).group?.label === 'Renamed');
|
||||||
|
|
||||||
|
// repoId inexistant → 404.
|
||||||
|
const bad = await j(`/api/v1/groups/${group.id}/repos`, 'POST', cookie, { repoId: 'does-not-exist' });
|
||||||
|
check('POST repo inexistant → 404', bad.status === 404);
|
||||||
|
|
||||||
|
// Suppression du repo → CASCADE purge la membership.
|
||||||
|
const delRepo = await j(`/api/v1/repos/${repoSummary.id}`, 'DELETE', cookie);
|
||||||
|
check('DELETE /repos/:id → 200', delRepo.status === 200);
|
||||||
|
await sleep(200);
|
||||||
|
const afterCascade = await (await j(`/api/v1/groups/${group.id}`, 'GET', cookie)).json();
|
||||||
|
check('CASCADE : membership purgée à la suppression du repo', afterCascade.group?.repoIds.length === 0);
|
||||||
|
|
||||||
|
// Suppression du groupe → broadcast WS group_removed.
|
||||||
|
const delGroup = await j(`/api/v1/groups/${group.id}`, 'DELETE', cookie);
|
||||||
|
check('DELETE /groups/:id → 200', delGroup.status === 200);
|
||||||
|
const removed = await c.waitMsg((m) => m.type === 'group_removed' && m.groupId === group.id);
|
||||||
|
check('broadcast WS group_removed', !!removed);
|
||||||
|
const delAgain = await j(`/api/v1/groups/${group.id}`, 'DELETE', cookie);
|
||||||
|
check('DELETE groupe inconnu → 404', delAgain.status === 404);
|
||||||
|
|
||||||
|
c.ws.close();
|
||||||
|
} catch (err) {
|
||||||
|
check('exception', false, String(err));
|
||||||
|
} finally {
|
||||||
|
srv.kill('SIGTERM');
|
||||||
|
await sleep(1500);
|
||||||
|
check('arrêt propre du daemon (SIGTERM)', srv.exitCode === 0 || srv.signalCode === null || srv.exitCode === null);
|
||||||
|
rmSync(tmp, { recursive: true, force: true });
|
||||||
|
const failed = results.filter((r) => !r.ok);
|
||||||
|
console.log(failed.length === 0 ? '\nACCEPTANCE P5: ALL GREEN' : `\nACCEPTANCE P5: ${failed.length} FAILURE(S)`);
|
||||||
|
process.exit(failed.length === 0 ? 0 : 1);
|
||||||
|
}
|
||||||
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,14 +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 { 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 { 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 {
|
||||||
@@ -34,22 +69,67 @@ export interface AppBundle {
|
|||||||
auth: AuthService;
|
auth: AuthService;
|
||||||
manager: PtyManager;
|
manager: PtyManager;
|
||||||
discovery: DiscoveryService;
|
discovery: DiscoveryService;
|
||||||
|
repoDiscovery: RepoDiscoveryService;
|
||||||
worktrees: WorktreeManager;
|
worktrees: WorktreeManager;
|
||||||
|
groups: GroupManager;
|
||||||
push: PushService;
|
push: PushService;
|
||||||
}
|
}
|
||||||
|
|
||||||
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({
|
||||||
|
db,
|
||||||
ptyManager: manager,
|
ptyManager: manager,
|
||||||
projectsDir: config.claudeProjectsDir,
|
projectsDir: config.claudeProjectsDir,
|
||||||
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);
|
||||||
|
|
||||||
|
// 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, {
|
||||||
@@ -88,16 +168,20 @@ 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, db);
|
||||||
registerRepoRoutes(app, worktrees);
|
registerRepoRoutes(app, worktrees, db);
|
||||||
registerWorktreeRoutes(app, worktrees);
|
registerGroupRoutes(app, groups, db, worktrees, manager);
|
||||||
registerPushRoutes(app, push);
|
registerWorktreeRoutes(app, worktrees, db);
|
||||||
|
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) => {
|
||||||
registerWsGateway(scoped, manager, discovery, worktrees, serverVersion);
|
registerWsGateway(scoped, manager, discovery, worktrees, groups, serverVersion);
|
||||||
});
|
});
|
||||||
|
|
||||||
// SPA buildée embarquée dans le paquet npm (public/) — absente en dev (vite dev sert le front)
|
// SPA buildée embarquée dans le paquet npm (public/) — absente en dev (vite dev sert le front)
|
||||||
@@ -112,5 +196,5 @@ export function buildApp(config: Config, db: Db, serverVersion: string): AppBund
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return { app, auth, manager, discovery, worktrees, 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 {
|
||||||
|
|||||||
363
packages/server/src/cli/install.ts
Normal file
363
packages/server/src/cli/install.ts
Normal file
@@ -0,0 +1,363 @@
|
|||||||
|
import { parseArgs } from 'node:util';
|
||||||
|
import { spawnSync } from 'node:child_process';
|
||||||
|
import { mkdirSync, writeFileSync, rmSync, existsSync } from 'node:fs';
|
||||||
|
import { homedir } from 'node:os';
|
||||||
|
import { join, dirname } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { loadConfig } from '../config.js';
|
||||||
|
import { openDb } from '../db/index.js';
|
||||||
|
import { AuthService } from '../auth/service.js';
|
||||||
|
|
||||||
|
// Nom de l'unit systemd (Linux) et label launchd par défaut (macOS, surchargeable via --label).
|
||||||
|
const SERVICE_NAME = 'arboretum';
|
||||||
|
const LAUNCHD_LABEL = 'fr.lidge.arboretum';
|
||||||
|
|
||||||
|
export type SupportedPlatform = 'linux' | 'darwin';
|
||||||
|
|
||||||
|
export interface InstallFlags {
|
||||||
|
port?: string | undefined;
|
||||||
|
bind?: string | undefined;
|
||||||
|
allowOrigin: string[];
|
||||||
|
db?: string | undefined;
|
||||||
|
vapidContact?: string | undefined;
|
||||||
|
claudeHome?: string | undefined;
|
||||||
|
binPath?: string | undefined;
|
||||||
|
label: string;
|
||||||
|
dryRun: boolean;
|
||||||
|
noEnable: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Fonctions pures (génération de contenu / chemins) ────────────────────────────────
|
||||||
|
|
||||||
|
/** macOS (launchd) et Linux (systemd) uniquement ; sinon throw avec un message pédagogique. */
|
||||||
|
export function detectPlatform(platform: NodeJS.Platform = process.platform): SupportedPlatform {
|
||||||
|
if (platform === 'linux' || platform === 'darwin') return platform;
|
||||||
|
throw new Error(
|
||||||
|
`Automatic service installation is supported on Linux (systemd) and macOS (launchd) only.\n` +
|
||||||
|
`On ${platform}, run \`arboretum\` manually or set up your own supervisor.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseInstallArgs(argv: string[]): InstallFlags {
|
||||||
|
const { values } = parseArgs({
|
||||||
|
args: argv,
|
||||||
|
options: {
|
||||||
|
port: { type: 'string' },
|
||||||
|
bind: { type: 'string' },
|
||||||
|
'allow-origin': { type: 'string', multiple: true },
|
||||||
|
db: { type: 'string' },
|
||||||
|
'vapid-contact': { type: 'string' },
|
||||||
|
'claude-home': { type: 'string' },
|
||||||
|
'bin-path': { type: 'string' },
|
||||||
|
label: { type: 'string' },
|
||||||
|
'dry-run': { type: 'boolean', default: false },
|
||||||
|
'no-enable': { type: 'boolean', default: false },
|
||||||
|
},
|
||||||
|
strict: true,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
port: values.port,
|
||||||
|
bind: values.bind,
|
||||||
|
allowOrigin: values['allow-origin'] ?? [],
|
||||||
|
db: values.db,
|
||||||
|
vapidContact: values['vapid-contact'],
|
||||||
|
claudeHome: values['claude-home'],
|
||||||
|
binPath: values['bin-path'],
|
||||||
|
label: values.label ?? LAUNCHD_LABEL,
|
||||||
|
dryRun: values['dry-run'] ?? false,
|
||||||
|
noEnable: values['no-enable'] ?? false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Flags propagés au service : UNIQUEMENT ceux fournis par l'utilisateur (ordre stable,
|
||||||
|
* ExecStart déterministe). On n'ajoute JAMAIS --i-know-this-exposes-a-terminal automatiquement
|
||||||
|
* (cf. modèle de sécurité : un service exposé doit être un choix conscient et explicite).
|
||||||
|
*/
|
||||||
|
export function buildServiceArgs(flags: InstallFlags): string[] {
|
||||||
|
const args: string[] = [];
|
||||||
|
if (flags.port) args.push('--port', flags.port);
|
||||||
|
if (flags.bind) args.push('--bind', flags.bind);
|
||||||
|
for (const origin of flags.allowOrigin) args.push('--allow-origin', origin);
|
||||||
|
if (flags.db) args.push('--db', flags.db);
|
||||||
|
if (flags.vapidContact) args.push('--vapid-contact', flags.vapidContact);
|
||||||
|
if (flags.claudeHome) args.push('--claude-home', flags.claudeHome);
|
||||||
|
return args;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Le `dist/index.js` réellement installé (depuis dist/cli/install.js). */
|
||||||
|
export function resolveScriptPath(): string {
|
||||||
|
return fileURLToPath(new URL('../index.js', import.meta.url));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cible exécutable du service. Par défaut node + script (immunisé contre un PATH minimal sous
|
||||||
|
* systemd/launchd) ; --bin-path force le wrapper `arboretum` global (suit les upgrades npm i -g).
|
||||||
|
*/
|
||||||
|
export function resolveBin(flags: Pick<InstallFlags, 'binPath'>): { exec: string; args: string[] } {
|
||||||
|
if (flags.binPath) return { exec: flags.binPath, args: [] };
|
||||||
|
return { exec: process.execPath, args: [resolveScriptPath()] };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function systemdUnitPath(): string {
|
||||||
|
const configHome = process.env.XDG_CONFIG_HOME ?? join(homedir(), '.config');
|
||||||
|
return join(configHome, 'systemd', 'user', `${SERVICE_NAME}.service`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function launchAgentPlistPath(label: string): string {
|
||||||
|
return join(homedir(), 'Library', 'LaunchAgents', `${label}.plist`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function launchdLogPaths(): { dir: string; out: string; err: string } {
|
||||||
|
const dir = join(homedir(), 'Library', 'Logs', 'arboretum');
|
||||||
|
return { dir, out: join(dir, 'out.log'), err: join(dir, 'err.log') };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function xmlEscape(s: string): string {
|
||||||
|
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||||
|
}
|
||||||
|
|
||||||
|
// systemd accepte les doubles quotes dans ExecStart ; on ne quote que les tokens à espaces.
|
||||||
|
function quoteIfNeeded(token: string): string {
|
||||||
|
return /\s/.test(token) ? `"${token}"` : token;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function renderSystemdUnit(input: { exec: string; scriptArgs: string[] }): string {
|
||||||
|
const execStart = [input.exec, ...input.scriptArgs].map(quoteIfNeeded).join(' ');
|
||||||
|
// KillSignal=SIGTERM + TimeoutStopSec=10 collent au drain de runDaemon (SIGTERM → drain 1s → close).
|
||||||
|
return `[Unit]
|
||||||
|
Description=Arboretum — git worktree & Claude Code dashboard
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
ExecStart=${execStart}
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=5
|
||||||
|
KillSignal=SIGTERM
|
||||||
|
TimeoutStopSec=10
|
||||||
|
Environment=NODE_ENV=production
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=default.target
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function renderLaunchAgentPlist(input: {
|
||||||
|
label: string;
|
||||||
|
programArguments: string[];
|
||||||
|
stdoutPath: string;
|
||||||
|
stderrPath: string;
|
||||||
|
}): string {
|
||||||
|
const args = input.programArguments.map((a) => ` <string>${xmlEscape(a)}</string>`).join('\n');
|
||||||
|
// KeepAlive/SuccessfulExit=false ≈ Restart=on-failure (ne relance pas après un drain volontaire).
|
||||||
|
return `<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<key>Label</key>
|
||||||
|
<string>${xmlEscape(input.label)}</string>
|
||||||
|
<key>ProgramArguments</key>
|
||||||
|
<array>
|
||||||
|
${args}
|
||||||
|
</array>
|
||||||
|
<key>RunAtLoad</key>
|
||||||
|
<true/>
|
||||||
|
<key>KeepAlive</key>
|
||||||
|
<dict>
|
||||||
|
<key>SuccessfulExit</key>
|
||||||
|
<false/>
|
||||||
|
</dict>
|
||||||
|
<key>StandardOutPath</key>
|
||||||
|
<string>${xmlEscape(input.stdoutPath)}</string>
|
||||||
|
<key>StandardErrorPath</key>
|
||||||
|
<string>${xmlEscape(input.stderrPath)}</string>
|
||||||
|
<key>EnvironmentVariables</key>
|
||||||
|
<dict>
|
||||||
|
<key>NODE_ENV</key>
|
||||||
|
<string>production</string>
|
||||||
|
</dict>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function printTokenBanner(token: string, url: string): void {
|
||||||
|
console.log('\n┌──────────────────────────────────────────────────────────────────┐');
|
||||||
|
console.log('│ First start — your access token (shown once, store it safely): │');
|
||||||
|
console.log('└──────────────────────────────────────────────────────────────────┘');
|
||||||
|
console.log(`\n ${token}\n`);
|
||||||
|
console.log(` Login at: ${url}/\n`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function printUsage(version: string): void {
|
||||||
|
console.log(`Arboretum v${version} — git worktree & Claude Code dashboard
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
arboretum [flags] Start the daemon (default)
|
||||||
|
arboretum serve [flags] Start the daemon (explicit alias)
|
||||||
|
arboretum install [flags] Install & start a user service (systemd on Linux, launchd on macOS)
|
||||||
|
arboretum uninstall Stop & remove the user service
|
||||||
|
arboretum status Show the service status
|
||||||
|
arboretum help Show this help
|
||||||
|
|
||||||
|
Daemon flags:
|
||||||
|
--port <n> Port to listen on (default 7317)
|
||||||
|
--bind <addr> Bind address (default 127.0.0.1)
|
||||||
|
--allow-origin <url> Additional allowed Origin (repeatable)
|
||||||
|
--db <path> SQLite database path
|
||||||
|
--vapid-contact <mailto|url> VAPID contact subject for Web Push
|
||||||
|
--i-know-this-exposes-a-terminal Acknowledge a non-loopback bind (avoid — prefer Tailscale Serve)
|
||||||
|
|
||||||
|
Install flags (daemon flags above are propagated to the service):
|
||||||
|
--bin-path <path> Use this binary in the service instead of node + script
|
||||||
|
--label <id> launchd label (macOS only, default ${LAUNCHD_LABEL})
|
||||||
|
--dry-run Print the unit/plist and commands without applying anything
|
||||||
|
--no-enable Write the service file but do not enable/start it
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Effets de bord (fs + exec) ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function run(cmd: string, args: string[], opts?: { check?: boolean }): number {
|
||||||
|
const res = spawnSync(cmd, args, { stdio: 'inherit' });
|
||||||
|
if (res.error) {
|
||||||
|
if ((res.error as NodeJS.ErrnoException).code === 'ENOENT') {
|
||||||
|
throw new Error(`Command not found: ${cmd}. Is it installed and on your PATH?`);
|
||||||
|
}
|
||||||
|
throw res.error;
|
||||||
|
}
|
||||||
|
const code = res.status ?? 0;
|
||||||
|
if (opts?.check && code !== 0) {
|
||||||
|
throw new Error(`Command failed (exit ${code}): ${cmd} ${args.join(' ')}`);
|
||||||
|
}
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bootstrap du token avec EXACTEMENT les flags du service (même db). Valide aussi le bind
|
||||||
|
* (garde-fou de loadConfig). Affiche le token une fois, puis ferme la db avant que le service
|
||||||
|
* ne l'ouvre. Skippé en --dry-run par l'appelant.
|
||||||
|
*/
|
||||||
|
function bootstrapToken(serviceArgs: string[]): void {
|
||||||
|
const config = loadConfig(serviceArgs);
|
||||||
|
const url = `http://${config.bind === '0.0.0.0' ? '127.0.0.1' : config.bind}:${config.port}`;
|
||||||
|
const db = openDb(config.dbPath);
|
||||||
|
try {
|
||||||
|
const token = new AuthService(db).ensureBootstrapToken();
|
||||||
|
if (token) printTokenBanner(token, url);
|
||||||
|
else console.log('\nAn access token already exists in this database — manage tokens from Settings.\n');
|
||||||
|
} finally {
|
||||||
|
db.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function runInstall(argv: string[]): Promise<void> {
|
||||||
|
const platform = detectPlatform();
|
||||||
|
const flags = parseInstallArgs(argv);
|
||||||
|
const serviceArgs = buildServiceArgs(flags);
|
||||||
|
const { exec, args: binArgs } = resolveBin(flags);
|
||||||
|
const scriptArgs = [...binArgs, ...serviceArgs];
|
||||||
|
|
||||||
|
if (platform === 'linux') {
|
||||||
|
const unit = renderSystemdUnit({ exec, scriptArgs });
|
||||||
|
const unitPath = systemdUnitPath();
|
||||||
|
if (flags.dryRun) {
|
||||||
|
console.log(`# ${unitPath}\n${unit}\n# commands:`);
|
||||||
|
console.log('systemctl --user daemon-reload');
|
||||||
|
if (!flags.noEnable) {
|
||||||
|
console.log(`systemctl --user enable --now ${SERVICE_NAME}`);
|
||||||
|
console.log(`loginctl enable-linger ${process.env.USER ?? '$USER'}`);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
bootstrapToken(serviceArgs);
|
||||||
|
mkdirSync(dirname(unitPath), { recursive: true });
|
||||||
|
writeFileSync(unitPath, unit);
|
||||||
|
console.log(`Wrote ${unitPath}`);
|
||||||
|
run('systemctl', ['--user', 'daemon-reload'], { check: true });
|
||||||
|
if (!flags.noEnable) {
|
||||||
|
run('systemctl', ['--user', 'enable', '--now', SERVICE_NAME], { check: true });
|
||||||
|
// enable-linger best-effort : absent en CI / sans session loginctl, non bloquant.
|
||||||
|
if (run('loginctl', ['enable-linger', process.env.USER ?? '']) !== 0) {
|
||||||
|
console.warn('Warning: could not enable linger — the service may not start at boot.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.log(`\nArboretum service installed. Logs: journalctl --user -u ${SERVICE_NAME} -f`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// macOS (launchd)
|
||||||
|
const logs = launchdLogPaths();
|
||||||
|
const programArguments = [exec, ...scriptArgs];
|
||||||
|
const plist = renderLaunchAgentPlist({
|
||||||
|
label: flags.label,
|
||||||
|
programArguments,
|
||||||
|
stdoutPath: logs.out,
|
||||||
|
stderrPath: logs.err,
|
||||||
|
});
|
||||||
|
const plistPath = launchAgentPlistPath(flags.label);
|
||||||
|
const uid = process.getuid?.() ?? 0;
|
||||||
|
const target = `gui/${uid}/${flags.label}`;
|
||||||
|
if (flags.dryRun) {
|
||||||
|
console.log(`# ${plistPath}\n${plist}\n# commands:`);
|
||||||
|
console.log(`launchctl bootout ${target} # best-effort`);
|
||||||
|
if (!flags.noEnable) {
|
||||||
|
console.log(`launchctl bootstrap gui/${uid} ${plistPath}`);
|
||||||
|
console.log(`launchctl enable ${target}`);
|
||||||
|
console.log(`launchctl kickstart -k ${target}`);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
bootstrapToken(serviceArgs);
|
||||||
|
mkdirSync(dirname(plistPath), { recursive: true });
|
||||||
|
mkdirSync(logs.dir, { recursive: true });
|
||||||
|
writeFileSync(plistPath, plist);
|
||||||
|
console.log(`Wrote ${plistPath}`);
|
||||||
|
if (!flags.noEnable) {
|
||||||
|
run('launchctl', ['bootout', target]); // best-effort : ignore "not loaded" (rend bootstrap idempotent)
|
||||||
|
run('launchctl', ['bootstrap', `gui/${uid}`, plistPath], { check: true });
|
||||||
|
run('launchctl', ['enable', target]);
|
||||||
|
run('launchctl', ['kickstart', '-k', target]);
|
||||||
|
}
|
||||||
|
console.log(`\nArboretum service installed. Logs: ${logs.out}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function runUninstall(argv: string[]): Promise<void> {
|
||||||
|
const platform = detectPlatform();
|
||||||
|
const flags = parseInstallArgs(argv);
|
||||||
|
if (platform === 'linux') {
|
||||||
|
const unitPath = systemdUnitPath();
|
||||||
|
run('systemctl', ['--user', 'disable', '--now', SERVICE_NAME]); // best-effort
|
||||||
|
if (existsSync(unitPath)) {
|
||||||
|
rmSync(unitPath);
|
||||||
|
console.log(`Removed ${unitPath}`);
|
||||||
|
}
|
||||||
|
run('systemctl', ['--user', 'daemon-reload']);
|
||||||
|
console.log('Arboretum service removed.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const plistPath = launchAgentPlistPath(flags.label);
|
||||||
|
const uid = process.getuid?.() ?? 0;
|
||||||
|
run('launchctl', ['bootout', `gui/${uid}/${flags.label}`]); // best-effort
|
||||||
|
if (existsSync(plistPath)) {
|
||||||
|
rmSync(plistPath);
|
||||||
|
console.log(`Removed ${plistPath}`);
|
||||||
|
}
|
||||||
|
console.log('Arboretum service removed.');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function runStatus(argv: string[]): Promise<void> {
|
||||||
|
const platform = detectPlatform();
|
||||||
|
const flags = parseInstallArgs(argv);
|
||||||
|
if (platform === 'linux') {
|
||||||
|
const code = run('systemctl', ['--user', 'status', SERVICE_NAME, '--no-pager']);
|
||||||
|
console.log(`\nLogs: journalctl --user -u ${SERVICE_NAME} -f`);
|
||||||
|
process.exitCode = code;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const uid = process.getuid?.() ?? 0;
|
||||||
|
const code = run('launchctl', ['print', `gui/${uid}/${flags.label}`]);
|
||||||
|
console.log(`\nLogs: ${launchdLogPaths().out}`);
|
||||||
|
process.exitCode = code;
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,6 +10,8 @@ export interface SpawnOptions {
|
|||||||
command: 'claude' | 'bash';
|
command: 'claude' | 'bash';
|
||||||
/** reprise d'une session existante (P2) : `--resume <id>`, `--fork-session` si fork. */
|
/** reprise d'une session existante (P2) : `--resume <id>`, `--fork-session` si fork. */
|
||||||
resume?: { claudeSessionId: string; fork?: boolean };
|
resume?: { claudeSessionId: string; fork?: boolean };
|
||||||
|
/** répertoires supplémentaires à relier dans une seule session (P6) : `--add-dir <path>` répété. */
|
||||||
|
addDirs?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
let cachedClaudeBin: string | null = null;
|
let cachedClaudeBin: string | null = null;
|
||||||
@@ -42,5 +44,7 @@ export function buildSpawnSpec(opts: SpawnOptions): SpawnSpec {
|
|||||||
args.push('--resume', opts.resume.claudeSessionId);
|
args.push('--resume', opts.resume.claudeSessionId);
|
||||||
if (opts.resume.fork) args.push('--fork-session');
|
if (opts.resume.fork) args.push('--fork-session');
|
||||||
}
|
}
|
||||||
|
// Session de groupe : relie plusieurs repos/worktrees dans une seule session (P6).
|
||||||
|
for (const dir of opts.addDirs ?? []) args.push('--add-dir', dir);
|
||||||
return { file: resolveClaudeBin(), args, env };
|
return { file: resolveClaudeBin(), args, env };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { join } from 'node:path';
|
|||||||
import type { SessionSummary } from '@arboretum/shared';
|
import type { SessionSummary } from '@arboretum/shared';
|
||||||
import { scanProjects, type DiscoveredJsonl } from './jsonl-discovery.js';
|
import { scanProjects, type DiscoveredJsonl } from './jsonl-discovery.js';
|
||||||
import { readRegistry, type RegistryEntry } from './session-registry.js';
|
import { readRegistry, type RegistryEntry } from './session-registry.js';
|
||||||
|
import { listHiddenSessionIds, type Db } from '../db/index.js';
|
||||||
import type { PtyManager } from './pty-manager.js';
|
import type { PtyManager } from './pty-manager.js';
|
||||||
|
|
||||||
const DEFAULT_REFRESH_MS = 10_000;
|
const DEFAULT_REFRESH_MS = 10_000;
|
||||||
@@ -17,6 +18,7 @@ export interface DiscoveryServiceEvents {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface DiscoveryOptions {
|
export interface DiscoveryOptions {
|
||||||
|
db: Db;
|
||||||
ptyManager: PtyManager;
|
ptyManager: PtyManager;
|
||||||
projectsDir?: string;
|
projectsDir?: string;
|
||||||
sessionsDir?: string;
|
sessionsDir?: string;
|
||||||
@@ -24,6 +26,7 @@ export interface DiscoveryOptions {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class DiscoveryService extends EventEmitter<DiscoveryServiceEvents> {
|
export class DiscoveryService extends EventEmitter<DiscoveryServiceEvents> {
|
||||||
|
private readonly db: Db;
|
||||||
private readonly projectsDir: string;
|
private readonly projectsDir: string;
|
||||||
private readonly sessionsDir: string;
|
private readonly sessionsDir: string;
|
||||||
private readonly ptyManager: PtyManager;
|
private readonly ptyManager: PtyManager;
|
||||||
@@ -35,6 +38,7 @@ export class DiscoveryService extends EventEmitter<DiscoveryServiceEvents> {
|
|||||||
|
|
||||||
constructor(opts: DiscoveryOptions) {
|
constructor(opts: DiscoveryOptions) {
|
||||||
super();
|
super();
|
||||||
|
this.db = opts.db;
|
||||||
this.ptyManager = opts.ptyManager;
|
this.ptyManager = opts.ptyManager;
|
||||||
this.projectsDir = opts.projectsDir ?? join(homedir(), '.claude', 'projects');
|
this.projectsDir = opts.projectsDir ?? join(homedir(), '.claude', 'projects');
|
||||||
this.sessionsDir = opts.sessionsDir ?? join(homedir(), '.claude', 'sessions');
|
this.sessionsDir = opts.sessionsDir ?? join(homedir(), '.claude', 'sessions');
|
||||||
@@ -81,6 +85,9 @@ export class DiscoveryService extends EventEmitter<DiscoveryServiceEvents> {
|
|||||||
if (r.claudeSessionId) regBySid.set(r.claudeSessionId, r);
|
if (r.claudeSessionId) regBySid.set(r.claudeSessionId, r);
|
||||||
}
|
}
|
||||||
const known = this.ptyManager.knownClaudeSessionIds();
|
const known = this.ptyManager.knownClaudeSessionIds();
|
||||||
|
// Sessions masquées par l'utilisateur : on les garde dans le cache (resume/fork possibles) mais
|
||||||
|
// marquées `hidden` → la route /sessions les exclut par défaut.
|
||||||
|
const hiddenIds = listHiddenSessionIds(this.db);
|
||||||
|
|
||||||
// Dédoublonnage des JSONL par claudeSessionId (on retient le plus récent).
|
// Dédoublonnage des JSONL par claudeSessionId (on retient le plus récent).
|
||||||
const latest = new Map<string, DiscoveredJsonl>();
|
const latest = new Map<string, DiscoveredJsonl>();
|
||||||
@@ -113,6 +120,7 @@ export class DiscoveryService extends EventEmitter<DiscoveryServiceEvents> {
|
|||||||
resumable: !live, // morte → --resume direct ; vivante → fork/observe (jamais resume : corruption)
|
resumable: !live, // morte → --resume direct ; vivante → fork/observe (jamais resume : corruption)
|
||||||
attachable: false, // Arboretum ne tient pas le PTY d'une session externe
|
attachable: false, // Arboretum ne tient pas le PTY d'une session externe
|
||||||
registryStatus: r?.status ?? null,
|
registryStatus: r?.status ?? null,
|
||||||
|
hidden: hiddenIds.has(d.claudeSessionId),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,9 +2,11 @@
|
|||||||
// les chemins/refs utilisateur. Fonctions pures sans état, prenant un cwd déjà validé par l'appelant.
|
// les chemins/refs utilisateur. Fonctions pures sans état, prenant un cwd déjà validé par l'appelant.
|
||||||
import { execFile } from 'node:child_process';
|
import { execFile } from 'node:child_process';
|
||||||
import { resolve, sep } from 'node:path';
|
import { resolve, sep } from 'node:path';
|
||||||
import type { WorktreeGitStatus } from '@arboretum/shared';
|
import type { WorktreeGitStatus, WorktreeBranchAction, WorktreeBranchMode } from '@arboretum/shared';
|
||||||
|
|
||||||
const GIT_TIMEOUT_MS = 10_000;
|
const GIT_TIMEOUT_MS = 10_000;
|
||||||
|
// `push` peut dialoguer avec un remote (réseau) : on lui laisse une marge bien plus large.
|
||||||
|
const GIT_PUSH_TIMEOUT_MS = 120_000;
|
||||||
const GIT_MAX_BUFFER = 8 * 1024 * 1024;
|
const GIT_MAX_BUFFER = 8 * 1024 * 1024;
|
||||||
|
|
||||||
interface GitError extends Error {
|
interface GitError extends Error {
|
||||||
@@ -12,14 +14,14 @@ interface GitError extends Error {
|
|||||||
code?: number | string;
|
code?: number | string;
|
||||||
}
|
}
|
||||||
|
|
||||||
function git(cwd: string, args: string[]): Promise<string> {
|
function git(cwd: string, args: string[], timeoutMs: number = GIT_TIMEOUT_MS): Promise<string> {
|
||||||
return new Promise((resolveP, reject) => {
|
return new Promise((resolveP, reject) => {
|
||||||
execFile(
|
execFile(
|
||||||
'git',
|
'git',
|
||||||
args,
|
args,
|
||||||
{
|
{
|
||||||
cwd,
|
cwd,
|
||||||
timeout: GIT_TIMEOUT_MS,
|
timeout: timeoutMs,
|
||||||
maxBuffer: GIT_MAX_BUFFER,
|
maxBuffer: GIT_MAX_BUFFER,
|
||||||
// GIT_OPTIONAL_LOCKS=0 : pas de prise de verrou par `status` (perf + concurrence avec une
|
// GIT_OPTIONAL_LOCKS=0 : pas de prise de verrou par `status` (perf + concurrence avec une
|
||||||
// session claude active) ; LC_ALL=C : sortie stable pour le parsing.
|
// session claude active) ; LC_ALL=C : sortie stable pour le parsing.
|
||||||
@@ -140,6 +142,52 @@ export async function defaultBranch(repoPath: string): Promise<string | null> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Branche courante (nom court) du checkout en `repoPath`, ou null si HEAD détaché. */
|
||||||
|
export async function currentBranch(repoPath: string): Promise<string | null> {
|
||||||
|
try {
|
||||||
|
const b = (await git(repoPath, ['rev-parse', '--abbrev-ref', 'HEAD'])).trim();
|
||||||
|
return b === 'HEAD' ? null : b;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Existence d'une branche, en local (`refs/heads`) et/ou suivie du remote (`refs/remotes/origin`). */
|
||||||
|
export async function branchExists(repoPath: string, branch: string): Promise<{ local: boolean; remote: boolean }> {
|
||||||
|
const verify = async (ref: string): Promise<boolean> => {
|
||||||
|
try {
|
||||||
|
await git(repoPath, ['rev-parse', '--verify', '--quiet', ref]);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const [local, remote] = await Promise.all([verify(`refs/heads/${branch}`), verify(`refs/remotes/origin/${branch}`)]);
|
||||||
|
return { local, remote };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Branches locales + suivies de `origin` (noms courts) + branche par défaut — pour un sélecteur de base. */
|
||||||
|
export async function listBranches(repoPath: string): Promise<{ local: string[]; remote: string[]; default: string | null }> {
|
||||||
|
const local: string[] = [];
|
||||||
|
const remote: string[] = [];
|
||||||
|
try {
|
||||||
|
const out = await git(repoPath, ['for-each-ref', '--format=%(refname:short)', 'refs/heads', 'refs/remotes/origin']);
|
||||||
|
for (const line of out.split('\n')) {
|
||||||
|
const name = line.trim();
|
||||||
|
if (!name) continue;
|
||||||
|
if (name.startsWith('origin/')) {
|
||||||
|
const short = name.slice('origin/'.length);
|
||||||
|
if (short && short !== 'HEAD') remote.push(short);
|
||||||
|
} else {
|
||||||
|
local.push(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* dépôt sans refs encore (premier commit absent) → listes vides */
|
||||||
|
}
|
||||||
|
return { local, remote, default: await defaultBranch(repoPath) };
|
||||||
|
}
|
||||||
|
|
||||||
export async function listWorktrees(repoPath: string): Promise<ParsedWorktree[]> {
|
export async function listWorktrees(repoPath: string): Promise<ParsedWorktree[]> {
|
||||||
return parseWorktreePorcelain(await git(repoPath, ['worktree', 'list', '--porcelain']));
|
return parseWorktreePorcelain(await git(repoPath, ['worktree', 'list', '--porcelain']));
|
||||||
}
|
}
|
||||||
@@ -175,19 +223,79 @@ export async function worktreeStatus(worktreePath: string): Promise<WorktreeGitS
|
|||||||
return { ahead, behind, dirtyCount, upstream };
|
return { ahead, behind, dirtyCount, upstream };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Point de départ d'une branche créée : `baseRef` explicite, sinon la branche par défaut du dépôt
|
||||||
|
* (locale ou suivie de `origin`), sinon undefined (git part alors du HEAD courant). */
|
||||||
|
async function resolveStartPoint(repoPath: string, baseRef?: string): Promise<string | undefined> {
|
||||||
|
if (baseRef) return baseRef;
|
||||||
|
const def = await defaultBranch(repoPath);
|
||||||
|
if (!def) return undefined;
|
||||||
|
const { local, remote } = await branchExists(repoPath, def);
|
||||||
|
if (local) return def;
|
||||||
|
if (remote) return `origin/${def}`;
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Crée un worktree en résolvant la branche selon `mode` (voir `WorktreeBranchMode`). Renvoie l'action
|
||||||
|
* effective. En mode `auto`, on choisit checkout / suivi-remote / création selon l'existence réelle de
|
||||||
|
* la branche — indispensable pour les groupes hétérogènes (branche présente dans certains dépôts seulement).
|
||||||
|
*/
|
||||||
export async function addWorktree(
|
export async function addWorktree(
|
||||||
repoPath: string,
|
repoPath: string,
|
||||||
opts: { path: string; branch: string; newBranch: boolean; baseRef?: string },
|
opts: { path: string; branch: string; mode: WorktreeBranchMode; baseRef?: string },
|
||||||
): Promise<void> {
|
): Promise<WorktreeBranchAction> {
|
||||||
|
const { local, remote } = await branchExists(repoPath, opts.branch);
|
||||||
|
let action: WorktreeBranchAction;
|
||||||
|
if (opts.mode === 'create') action = 'created';
|
||||||
|
else if (opts.mode === 'checkout') action = local ? 'reused' : 'tracked';
|
||||||
|
else action = local ? 'reused' : remote ? 'tracked' : 'created'; // auto
|
||||||
|
|
||||||
const args = ['worktree', 'add'];
|
const args = ['worktree', 'add'];
|
||||||
if (opts.newBranch) args.push('-b', opts.branch);
|
if (action === 'reused') {
|
||||||
args.push('--', opts.path);
|
args.push('--', opts.path, opts.branch);
|
||||||
if (opts.newBranch) {
|
} else if (action === 'tracked') {
|
||||||
if (opts.baseRef) args.push(opts.baseRef);
|
args.push('--track', '-b', opts.branch, '--', opts.path, `origin/${opts.branch}`);
|
||||||
} else {
|
} else {
|
||||||
args.push(opts.branch);
|
const start = await resolveStartPoint(repoPath, opts.baseRef);
|
||||||
|
args.push('-b', opts.branch, '--', opts.path);
|
||||||
|
if (start) args.push(start);
|
||||||
}
|
}
|
||||||
await git(repoPath, args);
|
await git(repoPath, args);
|
||||||
|
return action;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `git add -A` puis commit. L'appelant garantit qu'il y a quelque chose à committer. */
|
||||||
|
export async function commitAll(repoPath: string, message: string): Promise<void> {
|
||||||
|
await git(repoPath, ['add', '-A']);
|
||||||
|
await git(repoPath, ['commit', '-m', message]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pousse la branche courante. Si aucun upstream n'est configuré : `git push -u origin <branche>`. */
|
||||||
|
export async function push(repoPath: string): Promise<void> {
|
||||||
|
let hasUpstream = false;
|
||||||
|
try {
|
||||||
|
await git(repoPath, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']);
|
||||||
|
hasUpstream = true;
|
||||||
|
} catch {
|
||||||
|
hasUpstream = false;
|
||||||
|
}
|
||||||
|
if (hasUpstream) {
|
||||||
|
await git(repoPath, ['push'], GIT_PUSH_TIMEOUT_MS);
|
||||||
|
} else {
|
||||||
|
const branch = await currentBranch(repoPath);
|
||||||
|
if (!branch) throw new Error('cannot push a detached HEAD');
|
||||||
|
await git(repoPath, ['push', '-u', 'origin', branch], GIT_PUSH_TIMEOUT_MS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Crée/bascule une branche dans le checkout (worktree) en `repoPath` — utilisé pour démarrer une
|
||||||
|
* session sur la branche principale sans worktree dédié. `create` → `git switch -c <branch>` (échoue
|
||||||
|
* si la branche existe) ; sinon `git switch <branch>` (branche existante). Pas de `--` : l'argument
|
||||||
|
* est une réf (pas un pathspec) et le nom est déjà filtré en amont par `isValidBranchName` (anti-flag).
|
||||||
|
*/
|
||||||
|
export async function switchBranch(repoPath: string, opts: { branch: string; create: boolean }): Promise<void> {
|
||||||
|
await git(repoPath, opts.create ? ['switch', '-c', opts.branch] : ['switch', opts.branch]);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function removeWorktree(repoPath: string, worktreePath: string, force: boolean): Promise<void> {
|
export async function removeWorktree(repoPath: string, worktreePath: string, force: boolean): Promise<void> {
|
||||||
|
|||||||
203
packages/server/src/core/group-manager.ts
Normal file
203
packages/server/src/core/group-manager.ts
Normal file
@@ -0,0 +1,203 @@
|
|||||||
|
// Gestion des groupes de travail (P5) : un groupe = collection nommée de repos (many-to-many).
|
||||||
|
// Membership légère et persistée ; les worktrees/sessions du groupe ne sont PAS stockés ici —
|
||||||
|
// ils restent servis par WorktreeManager/PtyManager et filtrés côté client par repoId.
|
||||||
|
// Tout est synchrone : aucune I/O git/fs, node:sqlite est synchrone.
|
||||||
|
import { EventEmitter } from 'node:events';
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import type { GroupSummary } from '@arboretum/shared';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
|
||||||
|
const LABEL_MAX = 100;
|
||||||
|
const DESCRIPTION_MAX = 2000;
|
||||||
|
const COLOR_RE = /^#[0-9a-fA-F]{6}$/;
|
||||||
|
|
||||||
|
interface GroupRow {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
description: string | null;
|
||||||
|
color: string | null;
|
||||||
|
position: number;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GroupManagerEvents {
|
||||||
|
group_update: [GroupSummary];
|
||||||
|
group_removed: [string];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Erreur portant un statusCode + code pour mapping HTTP direct par les routes (cf. sendManagerError). */
|
||||||
|
function httpError(statusCode: number, code: string, message: string): Error {
|
||||||
|
return Object.assign(new Error(message), { statusCode, code });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Valide un label : non vide après trim, borné. */
|
||||||
|
function normLabel(label: unknown): string {
|
||||||
|
if (typeof label !== 'string') throw httpError(400, 'BAD_REQUEST', 'label is required');
|
||||||
|
const v = label.trim();
|
||||||
|
if (v === '') throw httpError(400, 'BAD_REQUEST', 'label must not be empty');
|
||||||
|
if (v.length > LABEL_MAX) throw httpError(400, 'BAD_REQUEST', `label must be at most ${LABEL_MAX} characters`);
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Normalise une description : vide/absente → null, bornée sinon. */
|
||||||
|
function normDescription(description: string | null | undefined): string | null {
|
||||||
|
if (description === null || description === undefined) return null;
|
||||||
|
const v = description.trim();
|
||||||
|
if (v === '') return null;
|
||||||
|
if (v.length > DESCRIPTION_MAX) throw httpError(400, 'BAD_REQUEST', `description must be at most ${DESCRIPTION_MAX} characters`);
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Normalise une couleur : vide/absente → null, doit être un hex `#rrggbb` sinon. */
|
||||||
|
function normColor(color: string | null | undefined): string | null {
|
||||||
|
if (color === null || color === undefined) return null;
|
||||||
|
const v = color.trim();
|
||||||
|
if (v === '') return null;
|
||||||
|
if (!COLOR_RE.test(v)) throw httpError(400, 'BAD_REQUEST', 'color must be a hex string like #4f46e5');
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class GroupManager extends EventEmitter<GroupManagerEvents> {
|
||||||
|
constructor(private readonly db: Db) {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
private getGroupRow(id: string): GroupRow | null {
|
||||||
|
return (this.db.prepare('SELECT * FROM groups WHERE id = ?').get(id) as unknown as GroupRow | undefined) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private repoIdsFor(groupId: string): string[] {
|
||||||
|
const rows = this.db
|
||||||
|
.prepare('SELECT repo_id FROM group_repos WHERE group_id = ? ORDER BY position ASC, created_at ASC')
|
||||||
|
.all(groupId) as Array<{ repo_id: string }>;
|
||||||
|
return rows.map((r) => r.repo_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
private rowToSummary(row: GroupRow): GroupSummary {
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
label: row.label,
|
||||||
|
description: row.description,
|
||||||
|
color: row.color,
|
||||||
|
repoIds: this.repoIdsFor(row.id),
|
||||||
|
createdAt: row.created_at,
|
||||||
|
updatedAt: row.updated_at,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Garde-fou : le repo doit exister (meilleur message que de laisser la FK lever une contrainte opaque). */
|
||||||
|
private assertRepoExists(repoId: string): void {
|
||||||
|
if (typeof repoId !== 'string' || repoId === '') throw httpError(400, 'BAD_REQUEST', 'repoId is required');
|
||||||
|
const exists = this.db.prepare('SELECT 1 FROM repos WHERE id = ?').get(repoId);
|
||||||
|
if (!exists) throw httpError(404, 'REPO_NOT_FOUND', 'No repo with this id');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Position d'insertion suivante dans un groupe (append en queue). */
|
||||||
|
private nextPosition(groupId: string): number {
|
||||||
|
const row = this.db.prepare('SELECT COALESCE(MAX(position), -1) + 1 AS pos FROM group_repos WHERE group_id = ?').get(groupId) as {
|
||||||
|
pos: number;
|
||||||
|
};
|
||||||
|
return row.pos;
|
||||||
|
}
|
||||||
|
|
||||||
|
listGroups(): GroupSummary[] {
|
||||||
|
const rows = this.db.prepare('SELECT * FROM groups ORDER BY position ASC, created_at ASC').all() as unknown as GroupRow[];
|
||||||
|
return rows.map((r) => this.rowToSummary(r));
|
||||||
|
}
|
||||||
|
|
||||||
|
getGroup(id: string): GroupSummary {
|
||||||
|
const row = this.getGroupRow(id);
|
||||||
|
if (!row) throw httpError(404, 'NOT_FOUND', 'No group with this id');
|
||||||
|
return this.rowToSummary(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
createGroup(opts: { label: string; description?: string; color?: string; repoIds?: string[] }): GroupSummary {
|
||||||
|
const label = normLabel(opts.label);
|
||||||
|
const description = normDescription(opts.description);
|
||||||
|
const color = normColor(opts.color);
|
||||||
|
const repoIds = opts.repoIds ?? [];
|
||||||
|
if (!Array.isArray(repoIds)) throw httpError(400, 'BAD_REQUEST', 'repoIds must be an array');
|
||||||
|
for (const repoId of repoIds) this.assertRepoExists(repoId);
|
||||||
|
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
const id = randomUUID();
|
||||||
|
const position = this.db.prepare('SELECT COALESCE(MAX(position), -1) + 1 AS pos FROM groups').get() as { pos: number };
|
||||||
|
|
||||||
|
this.db.exec('BEGIN');
|
||||||
|
try {
|
||||||
|
this.db
|
||||||
|
.prepare('INSERT INTO groups (id, label, description, color, position, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)')
|
||||||
|
.run(id, label, description, color, position.pos, now, now);
|
||||||
|
const insertRepo = this.db.prepare('INSERT OR IGNORE INTO group_repos (group_id, repo_id, position, created_at) VALUES (?, ?, ?, ?)');
|
||||||
|
let pos = 0;
|
||||||
|
const seen = new Set<string>();
|
||||||
|
for (const repoId of repoIds) {
|
||||||
|
if (seen.has(repoId)) continue;
|
||||||
|
seen.add(repoId);
|
||||||
|
insertRepo.run(id, repoId, pos++, now);
|
||||||
|
}
|
||||||
|
this.db.exec('COMMIT');
|
||||||
|
} catch (err) {
|
||||||
|
this.db.exec('ROLLBACK');
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
|
const summary = this.getGroup(id);
|
||||||
|
this.emit('group_update', summary);
|
||||||
|
return summary;
|
||||||
|
}
|
||||||
|
|
||||||
|
updateGroup(id: string, patch: { label?: string; description?: string | null; color?: string | null }): GroupSummary {
|
||||||
|
const row = this.getGroupRow(id);
|
||||||
|
if (!row) throw httpError(404, 'NOT_FOUND', 'No group with this id');
|
||||||
|
if (patch.label !== undefined) row.label = normLabel(patch.label);
|
||||||
|
if (patch.description !== undefined) row.description = normDescription(patch.description);
|
||||||
|
if (patch.color !== undefined) row.color = normColor(patch.color);
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
this.db
|
||||||
|
.prepare('UPDATE groups SET label = ?, description = ?, color = ?, updated_at = ? WHERE id = ?')
|
||||||
|
.run(row.label, row.description, row.color, now, id);
|
||||||
|
const summary = this.getGroup(id);
|
||||||
|
this.emit('group_update', summary);
|
||||||
|
return summary;
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteGroup(id: string): boolean {
|
||||||
|
// CASCADE (PRAGMA foreign_keys = ON) purge group_repos.
|
||||||
|
const res = this.db.prepare('DELETE FROM groups WHERE id = ?').run(id);
|
||||||
|
if (res.changes === 0) return false;
|
||||||
|
// Les sessions de groupe (P6) ne sont pas en FK : on désorpheline leur group_id manuellement.
|
||||||
|
this.db.prepare('UPDATE sessions SET group_id = NULL WHERE group_id = ?').run(id);
|
||||||
|
this.emit('group_removed', id);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
addRepo(groupId: string, repoId: string): GroupSummary {
|
||||||
|
if (!this.getGroupRow(groupId)) throw httpError(404, 'NOT_FOUND', 'No group with this id');
|
||||||
|
this.assertRepoExists(repoId);
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
// INSERT OR IGNORE → idempotent (PRIMARY KEY (group_id, repo_id)).
|
||||||
|
this.db
|
||||||
|
.prepare('INSERT OR IGNORE INTO group_repos (group_id, repo_id, position, created_at) VALUES (?, ?, ?, ?)')
|
||||||
|
.run(groupId, repoId, this.nextPosition(groupId), now);
|
||||||
|
this.touch(groupId, now);
|
||||||
|
const summary = this.getGroup(groupId);
|
||||||
|
this.emit('group_update', summary);
|
||||||
|
return summary;
|
||||||
|
}
|
||||||
|
|
||||||
|
removeRepo(groupId: string, repoId: string): GroupSummary {
|
||||||
|
if (!this.getGroupRow(groupId)) throw httpError(404, 'NOT_FOUND', 'No group with this id');
|
||||||
|
// DELETE no-op si absent → idempotent.
|
||||||
|
this.db.prepare('DELETE FROM group_repos WHERE group_id = ? AND repo_id = ?').run(groupId, repoId);
|
||||||
|
this.touch(groupId, new Date().toISOString());
|
||||||
|
const summary = this.getGroup(groupId);
|
||||||
|
this.emit('group_update', summary);
|
||||||
|
return summary;
|
||||||
|
}
|
||||||
|
|
||||||
|
private touch(groupId: string, now: string): void {
|
||||||
|
this.db.prepare('UPDATE groups SET updated_at = ? WHERE id = ?').run(now, groupId);
|
||||||
|
}
|
||||||
|
}
|
||||||
37
packages/server/src/core/group-session.ts
Normal file
37
packages/server/src/core/group-session.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import { parse, resolve, sep } from 'node:path';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Plus long ancêtre commun d'un ensemble de chemins absolus (par segments, jamais par préfixe
|
||||||
|
* de chaîne — `/a/bc` n'est PAS un ancêtre de `/a/bcd`). Pour un seul chemin, renvoie ce chemin.
|
||||||
|
*/
|
||||||
|
export function commonAncestorDir(paths: string[]): string {
|
||||||
|
const first = paths[0];
|
||||||
|
if (first === undefined) throw new Error('commonAncestorDir: empty input');
|
||||||
|
const firstSegs = resolve(first).split(sep);
|
||||||
|
let common = firstSegs.length;
|
||||||
|
for (let i = 1; i < paths.length; i++) {
|
||||||
|
const segs = resolve(paths[i]!).split(sep);
|
||||||
|
let k = 0;
|
||||||
|
while (k < common && k < segs.length && segs[k] === firstSegs[k]) k++;
|
||||||
|
common = k;
|
||||||
|
}
|
||||||
|
const joined = firstSegs.slice(0, common).join(sep);
|
||||||
|
// `['', 'a', 'b'].slice(0,1).join('/')` === '' → racine POSIX ; rétablir le séparateur racine.
|
||||||
|
return joined === '' ? parse(resolve(first)).root : joined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Politique de répertoire de travail d'une session de groupe (P6) : le `cwd` est le PARENT COMMUN
|
||||||
|
* des répertoires couverts (racine neutre, chemins relatifs cross-repo naturels), chaque répertoire
|
||||||
|
* étant ensuite relié via `--add-dir` (le dédoublonnage + filtrage du cwd est fait par `PtyManager`).
|
||||||
|
* Garde-fou : si le parent commun est la racine du FS (repos éparpillés sur des racines différentes),
|
||||||
|
* on retombe sur le premier répertoire pour ne pas accorder à Claude la permission sur tout le disque.
|
||||||
|
*/
|
||||||
|
export function resolveGroupCwd(dirs: string[]): { cwd: string; addDirs: string[] } {
|
||||||
|
const first = dirs[0];
|
||||||
|
if (first === undefined) throw new Error('resolveGroupCwd: empty input');
|
||||||
|
const ancestor = commonAncestorDir(dirs);
|
||||||
|
const root = parse(resolve(first)).root;
|
||||||
|
const cwd = ancestor === root ? first : ancestor;
|
||||||
|
return { cwd, addDirs: dirs };
|
||||||
|
}
|
||||||
@@ -12,7 +12,9 @@ import { SessionActivityTracker } from './claude-adapter.js';
|
|||||||
import type { PushService } from './push-service.js';
|
import type { PushService } from './push-service.js';
|
||||||
import type { Db } from '../db/index.js';
|
import type { Db } from '../db/index.js';
|
||||||
|
|
||||||
const RING_CAPACITY = 2 * 1024 * 1024;
|
// 4 Mo : conserve assez d'historique pour que le replay (REPLAY_TAIL_BYTES = 1 Mo) reste largement
|
||||||
|
// dans le ring et qu'on puisse remonter une conversation Claude après ré-attache.
|
||||||
|
const RING_CAPACITY = 4 * 1024 * 1024;
|
||||||
const KILL_GRACE_MS = 5000;
|
const KILL_GRACE_MS = 5000;
|
||||||
/** Délai avant envoi d'une notif push sur passage en `waiting` : annulé si la session repart (faux positif). */
|
/** Délai avant envoi d'une notif push sur passage en `waiting` : annulé si la session repart (faux positif). */
|
||||||
const NOTIFY_DEBOUNCE_MS = 1500;
|
const NOTIFY_DEBOUNCE_MS = 1500;
|
||||||
@@ -20,6 +22,17 @@ const NOTIFY_DEBOUNCE_MS = 1500;
|
|||||||
const CLAUDE_ID_POLL_MS = 400;
|
const CLAUDE_ID_POLL_MS = 400;
|
||||||
const CLAUDE_ID_TIMEOUT_MS = 60_000;
|
const CLAUDE_ID_TIMEOUT_MS = 60_000;
|
||||||
|
|
||||||
|
/** Parse la colonne `added_dirs` (JSON array de chemins) de façon défensive ; [] si NULL/invalide. */
|
||||||
|
function parseAddedDirs(raw: string | null): string[] {
|
||||||
|
if (!raw) return [];
|
||||||
|
try {
|
||||||
|
const v = JSON.parse(raw);
|
||||||
|
return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [];
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Lien entre un client WS attaché et une session. La gateway fournit les callbacks d'envoi. */
|
/** Lien entre un client WS attaché et une session. La gateway fournit les callbacks d'envoi. */
|
||||||
export interface ClientBinding {
|
export interface ClientBinding {
|
||||||
channel: number;
|
channel: number;
|
||||||
@@ -48,6 +61,10 @@ interface ManagedSession {
|
|||||||
killTimer: NodeJS.Timeout | null;
|
killTimer: NodeJS.Timeout | null;
|
||||||
/** ID interne du CLI claude, résolu via le registre après spawn (null pour bash / pas encore prêt). */
|
/** ID interne du CLI claude, résolu via le registre après spawn (null pour bash / pas encore prêt). */
|
||||||
claudeSessionId: string | null;
|
claudeSessionId: string | null;
|
||||||
|
/** répertoires supplémentaires reliés dans la session (--add-dir) ; [] pour une session mono-repo (P6). */
|
||||||
|
addedDirs: string[];
|
||||||
|
/** groupe propriétaire d'une session de groupe multi-repo ; null sinon (P6). */
|
||||||
|
groupId: string | null;
|
||||||
/** détection d'état fin (busy/waiting/idle + dialogue) ; null pour bash (P3-B). */
|
/** détection d'état fin (busy/waiting/idle + dialogue) ; null pour bash (P3-B). */
|
||||||
tracker: SessionActivityTracker | null;
|
tracker: SessionActivityTracker | null;
|
||||||
/** dernière activité notifiée (détection du front montant vers `waiting` pour le push P4-B). */
|
/** dernière activité notifiée (détection du front montant vers `waiting` pour le push P4-B). */
|
||||||
@@ -72,14 +89,33 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
|||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
|
||||||
spawn(opts: { cwd: string; command?: 'claude' | 'bash'; resume?: { claudeSessionId: string; fork?: boolean } }): SessionSummary {
|
spawn(opts: {
|
||||||
|
cwd: string;
|
||||||
|
command?: 'claude' | 'bash';
|
||||||
|
resume?: { claudeSessionId: string; fork?: boolean };
|
||||||
|
/** répertoires supplémentaires à relier (session de groupe multi-repo, P6). */
|
||||||
|
addDirs?: string[];
|
||||||
|
/** groupe propriétaire (session de groupe, P6). */
|
||||||
|
groupId?: string;
|
||||||
|
}): SessionSummary {
|
||||||
const cwd = opts.cwd;
|
const cwd = opts.cwd;
|
||||||
if (!existsSync(cwd) || !statSync(cwd).isDirectory()) {
|
if (!existsSync(cwd) || !statSync(cwd).isDirectory()) {
|
||||||
throw Object.assign(new Error(`Not a directory: ${cwd}`), { statusCode: 400 });
|
throw Object.assign(new Error(`Not a directory: ${cwd}`), { statusCode: 400 });
|
||||||
}
|
}
|
||||||
|
// Dédoublonne et écarte le cwd primaire ; valide chaque répertoire supplémentaire (comme le cwd).
|
||||||
|
const addedDirs = [...new Set(opts.addDirs ?? [])].filter((d) => d !== cwd);
|
||||||
|
for (const dir of addedDirs) {
|
||||||
|
if (!existsSync(dir) || !statSync(dir).isDirectory()) {
|
||||||
|
throw Object.assign(new Error(`Not a directory: ${dir}`), { statusCode: 400 });
|
||||||
|
}
|
||||||
|
}
|
||||||
// Un resume/fork est toujours une session claude (le cwd d'origine est garanti par l'appelant — S1).
|
// Un resume/fork est toujours une session claude (le cwd d'origine est garanti par l'appelant — S1).
|
||||||
const command = opts.resume ? 'claude' : (opts.command ?? 'claude');
|
const command = opts.resume ? 'claude' : (opts.command ?? 'claude');
|
||||||
const spec = buildSpawnSpec({ command, ...(opts.resume ? { resume: opts.resume } : {}) });
|
const spec = buildSpawnSpec({
|
||||||
|
command,
|
||||||
|
...(opts.resume ? { resume: opts.resume } : {}),
|
||||||
|
...(addedDirs.length ? { addDirs: addedDirs } : {}),
|
||||||
|
});
|
||||||
const id = randomUUID();
|
const id = randomUUID();
|
||||||
const proc = pty.spawn(spec.file, spec.args, {
|
const proc = pty.spawn(spec.file, spec.args, {
|
||||||
name: 'xterm-256color',
|
name: 'xterm-256color',
|
||||||
@@ -101,6 +137,8 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
|||||||
exited: null,
|
exited: null,
|
||||||
killTimer: null,
|
killTimer: null,
|
||||||
claudeSessionId: null,
|
claudeSessionId: null,
|
||||||
|
addedDirs,
|
||||||
|
groupId: opts.groupId ?? null,
|
||||||
tracker: null,
|
tracker: null,
|
||||||
prevActivity: null,
|
prevActivity: null,
|
||||||
notifyTimer: null,
|
notifyTimer: null,
|
||||||
@@ -116,8 +154,16 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
|||||||
}
|
}
|
||||||
this.live.set(id, session);
|
this.live.set(id, session);
|
||||||
this.db
|
this.db
|
||||||
.prepare('INSERT INTO sessions (id, cwd, command, created_at, resumed_from) VALUES (?, ?, ?, ?, ?)')
|
.prepare('INSERT INTO sessions (id, cwd, command, created_at, resumed_from, added_dirs, group_id) VALUES (?, ?, ?, ?, ?, ?, ?)')
|
||||||
.run(id, cwd, command, session.createdAt, opts.resume?.claudeSessionId ?? null);
|
.run(
|
||||||
|
id,
|
||||||
|
cwd,
|
||||||
|
command,
|
||||||
|
session.createdAt,
|
||||||
|
opts.resume?.claudeSessionId ?? null,
|
||||||
|
addedDirs.length ? JSON.stringify(addedDirs) : null,
|
||||||
|
session.groupId,
|
||||||
|
);
|
||||||
|
|
||||||
proc.onData((data) => this.handleOutput(session, Buffer.from(data, 'utf8')));
|
proc.onData((data) => this.handleOutput(session, Buffer.from(data, 'utf8')));
|
||||||
proc.onExit(({ exitCode, signal }) => this.handleExit(session, exitCode, signal ?? null));
|
proc.onExit(({ exitCode, signal }) => this.handleExit(session, exitCode, signal ?? null));
|
||||||
@@ -145,6 +191,36 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
|||||||
setTimeout(tick, CLAUDE_ID_POLL_MS).unref();
|
setTimeout(tick, CLAUDE_ID_POLL_MS).unref();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Contexte de session de groupe (P6) à réinjecter au resume : derniers `added_dirs`/`group_id`
|
||||||
|
* persistés pour ce claudeSessionId. Permet à `--resume` de re-relier les mêmes répertoires.
|
||||||
|
*/
|
||||||
|
groupSessionContext(claudeSessionId: string): { addedDirs: string[]; groupId: string | null } | null {
|
||||||
|
const row = this.db
|
||||||
|
.prepare('SELECT added_dirs, group_id FROM sessions WHERE claude_session_id = ? AND added_dirs IS NOT NULL ORDER BY created_at DESC LIMIT 1')
|
||||||
|
.get(claudeSessionId) as { added_dirs: string | null; group_id: string | null } | undefined;
|
||||||
|
if (!row) return null;
|
||||||
|
return { addedDirs: parseAddedDirs(row.added_dirs), groupId: row.group_id };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cible de reprise d'une session managée MORTE (P2/P6), résolue par UUID Arboretum : son cwd
|
||||||
|
* d'origine, son claudeSessionId et son contexte de groupe, lus en DB. null si l'id ne correspond
|
||||||
|
* pas à une session managée morte, reprenable (claude + claudeSessionId connu).
|
||||||
|
* Complète `DiscoveryService.getDiscovered`, qui ne couvre QUE les sessions claude EXTERNES
|
||||||
|
* (une managée connue est justement exclue de la découverte).
|
||||||
|
*/
|
||||||
|
resumeTargetById(id: string): { cwd: string; claudeSessionId: string; addedDirs: string[]; groupId: string | null } | null {
|
||||||
|
if (this.live.has(id)) return null; // vivante : pas de resume direct (fork via le même chemin)
|
||||||
|
const row = this.db
|
||||||
|
.prepare(
|
||||||
|
"SELECT cwd, claude_session_id, added_dirs, group_id FROM sessions WHERE id = ? AND ended_at IS NOT NULL AND claude_session_id IS NOT NULL AND command = 'claude'",
|
||||||
|
)
|
||||||
|
.get(id) as { cwd: string; claude_session_id: string; added_dirs: string | null; group_id: string | null } | undefined;
|
||||||
|
if (!row) return null;
|
||||||
|
return { cwd: row.cwd, claudeSessionId: row.claude_session_id, addedDirs: parseAddedDirs(row.added_dirs), groupId: row.group_id };
|
||||||
|
}
|
||||||
|
|
||||||
/** Session managée VIVANTE portant ce claudeSessionId (garde-fou anti-resume d'une session vivante). */
|
/** Session managée VIVANTE portant ce claudeSessionId (garde-fou anti-resume d'une session vivante). */
|
||||||
findLiveByClaudeSessionId(claudeSessionId: string): SessionSummary | null {
|
findLiveByClaudeSessionId(claudeSessionId: string): SessionSummary | null {
|
||||||
for (const s of this.live.values()) {
|
for (const s of this.live.values()) {
|
||||||
@@ -170,29 +246,34 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
|||||||
const liveSummaries = [...this.live.values()].map((s) => this.summarize(s));
|
const liveSummaries = [...this.live.values()].map((s) => this.summarize(s));
|
||||||
const liveIds = new Set(this.live.keys());
|
const liveIds = new Set(this.live.keys());
|
||||||
const rows = this.db
|
const rows = this.db
|
||||||
.prepare('SELECT id, cwd, command, title, created_at, ended_at, exit_code, claude_session_id FROM sessions ORDER BY created_at DESC LIMIT 100')
|
.prepare('SELECT id, cwd, command, title, created_at, ended_at, exit_code, claude_session_id, added_dirs, group_id FROM sessions ORDER BY created_at DESC LIMIT 100')
|
||||||
.all() as Array<{ id: string; cwd: string; command: string; title: string | null; created_at: string; ended_at: string | null; exit_code: number | null; claude_session_id: string | null }>;
|
.all() as Array<{ id: string; cwd: string; command: string; title: string | null; created_at: string; ended_at: string | null; exit_code: number | null; claude_session_id: string | null; added_dirs: string | null; group_id: string | null }>;
|
||||||
const historical: SessionSummary[] = rows
|
const historical: SessionSummary[] = rows
|
||||||
.filter((r) => !liveIds.has(r.id))
|
.filter((r) => !liveIds.has(r.id))
|
||||||
.map((r) => ({
|
.map((r) => {
|
||||||
|
const addedDirs = parseAddedDirs(r.added_dirs);
|
||||||
|
return {
|
||||||
id: r.id,
|
id: r.id,
|
||||||
cwd: r.cwd,
|
cwd: r.cwd,
|
||||||
command: r.command,
|
command: r.command,
|
||||||
title: r.title,
|
title: r.title,
|
||||||
status: 'exited',
|
status: 'exited' as const,
|
||||||
live: false,
|
live: false,
|
||||||
createdAt: r.created_at,
|
createdAt: r.created_at,
|
||||||
endedAt: r.ended_at,
|
endedAt: r.ended_at,
|
||||||
exitCode: r.exit_code,
|
exitCode: r.exit_code,
|
||||||
clients: 0,
|
clients: 0,
|
||||||
source: 'managed',
|
source: 'managed' as const,
|
||||||
claudeSessionId: r.claude_session_id,
|
claudeSessionId: r.claude_session_id,
|
||||||
pid: null,
|
pid: null,
|
||||||
// une session claude morte avec un claudeSessionId connu est reprenable (--resume direct).
|
// une session claude morte avec un claudeSessionId connu est reprenable (--resume direct).
|
||||||
resumable: r.command === 'claude' && r.claude_session_id != null,
|
resumable: r.command === 'claude' && r.claude_session_id != null,
|
||||||
attachable: false,
|
attachable: false,
|
||||||
registryStatus: null,
|
registryStatus: null,
|
||||||
}));
|
...(addedDirs.length ? { addedDirs } : {}),
|
||||||
|
groupId: r.group_id,
|
||||||
|
};
|
||||||
|
});
|
||||||
return [...liveSummaries, ...historical];
|
return [...liveSummaries, ...historical];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -427,6 +508,8 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
|||||||
activity: act?.activity ?? null,
|
activity: act?.activity ?? null,
|
||||||
waitingFor: act?.waitingFor ?? null,
|
waitingFor: act?.waitingFor ?? null,
|
||||||
dialog: act?.dialog ?? null,
|
dialog: act?.dialog ?? null,
|
||||||
|
...(s.addedDirs.length ? { addedDirs: s.addedDirs } : {}),
|
||||||
|
groupId: s.groupId,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,27 +7,35 @@ 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,
|
||||||
SessionSummary,
|
SessionSummary,
|
||||||
|
WorktreeBranchAction,
|
||||||
|
WorktreeBranchMode,
|
||||||
WorktreeGitStatus,
|
WorktreeGitStatus,
|
||||||
WorktreeSummary,
|
WorktreeSummary,
|
||||||
} from '@arboretum/shared';
|
} from '@arboretum/shared';
|
||||||
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,
|
||||||
|
commitAll,
|
||||||
defaultBranch,
|
defaultBranch,
|
||||||
isDirtyWorktreeError,
|
isDirtyWorktreeError,
|
||||||
isRepo,
|
isRepo,
|
||||||
isSafeAbsolutePath,
|
isSafeAbsolutePath,
|
||||||
isValidBranchName,
|
isValidBranchName,
|
||||||
|
listBranches,
|
||||||
listWorktrees,
|
listWorktrees,
|
||||||
pruneWorktrees,
|
pruneWorktrees,
|
||||||
|
push,
|
||||||
removeWorktree,
|
removeWorktree,
|
||||||
|
switchBranch,
|
||||||
worktreeStatus,
|
worktreeStatus,
|
||||||
type ParsedWorktree,
|
type ParsedWorktree,
|
||||||
} from './git.js';
|
} from './git.js';
|
||||||
@@ -35,6 +43,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 +56,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 +109,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 +136,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 +159,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,12 +201,67 @@ 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. */
|
/**
|
||||||
private sessionsForCwd(path: string): SessionSummary[] {
|
* Sessions (managées + découvertes) dont le cwd correspond à ce chemin de worktree.
|
||||||
|
* Les sessions explicitement masquées (`hidden`) sont exclues — cohérent avec `/api/v1/sessions`
|
||||||
|
* (sans quoi le masquage était ignoré dans les fiches worktree). Le tri managées/externes est laissé
|
||||||
|
* au client (interrupteur « afficher les externes »), qui dispose du champ `source`. La garde de
|
||||||
|
* suppression réclame en revanche TOUTES les sessions vivantes (`includeHidden`) pour rester sûre.
|
||||||
|
*/
|
||||||
|
private sessionsForCwd(path: string, opts?: { includeHidden?: boolean }): SessionSummary[] {
|
||||||
const rp = resolve(path);
|
const rp = resolve(path);
|
||||||
return mergeSessions(this.ptyManager.list(), this.discovery.list()).filter((s) => resolve(s.cwd) === rp);
|
return mergeSessions(this.ptyManager.list(), this.discovery.list())
|
||||||
|
.filter((s) => resolve(s.cwd) === rp)
|
||||||
|
.filter((s) => opts?.includeHidden || !s.hidden);
|
||||||
}
|
}
|
||||||
|
|
||||||
private toSummary(repoId: string, repoPath: string, w: ParsedWorktree, status: WorktreeGitStatus): WorktreeSummary {
|
private toSummary(repoId: string, repoPath: string, w: ParsedWorktree, status: WorktreeGitStatus): WorktreeSummary {
|
||||||
@@ -214,8 +296,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();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -248,8 +335,8 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
|||||||
|
|
||||||
async createWorktree(
|
async createWorktree(
|
||||||
repoId: string,
|
repoId: string,
|
||||||
req: { branch: string; newBranch: boolean; baseRef?: string; path?: string; runHooks?: boolean; preTrust?: boolean; startSession?: 'claude' | 'bash' | null },
|
req: { branch: string; mode?: WorktreeBranchMode; baseRef?: string; path?: string; runHooks?: boolean; preTrust?: boolean; startSession?: 'claude' | 'bash' | null },
|
||||||
): Promise<{ worktree: WorktreeSummary; hookResults: HookRunResult[]; session: SessionSummary | null }> {
|
): Promise<{ worktree: WorktreeSummary; hookResults: HookRunResult[]; session: SessionSummary | null; action: WorktreeBranchAction }> {
|
||||||
const row = this.getRepoRow(repoId);
|
const row = this.getRepoRow(repoId);
|
||||||
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 (!isValidBranchName(req.branch)) throw httpError(400, 'BAD_BRANCH', `Invalid branch name: ${req.branch}`);
|
if (!isValidBranchName(req.branch)) throw httpError(400, 'BAD_BRANCH', `Invalid branch name: ${req.branch}`);
|
||||||
@@ -258,8 +345,9 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
|||||||
if (existsSync(path)) throw httpError(409, 'PATH_EXISTS', `Path already exists: ${path}`);
|
if (existsSync(path)) throw httpError(409, 'PATH_EXISTS', `Path already exists: ${path}`);
|
||||||
|
|
||||||
return this.withLock(repoId, async () => {
|
return this.withLock(repoId, async () => {
|
||||||
|
let action: WorktreeBranchAction;
|
||||||
try {
|
try {
|
||||||
await addWorktree(row.path, { path, branch: req.branch, newBranch: req.newBranch, ...(req.baseRef ? { baseRef: req.baseRef } : {}) });
|
action = await addWorktree(row.path, { path, branch: req.branch, mode: req.mode ?? 'auto', ...(req.baseRef ? { baseRef: req.baseRef } : {}) });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw httpError(400, 'WORKTREE_ADD_FAILED', (err as Error).message);
|
throw httpError(400, 'WORKTREE_ADD_FAILED', (err as Error).message);
|
||||||
}
|
}
|
||||||
@@ -278,7 +366,128 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
|||||||
if (req.startSession) session = this.ptyManager.spawn({ cwd: path, command: req.startSession });
|
if (req.startSession) session = this.ptyManager.spawn({ cwd: path, command: req.startSession });
|
||||||
|
|
||||||
const worktree = (await this.emitWorktree(row, path)) ?? this.toSummary(row.id, row.path, { path, head: null, branch: req.branch, detached: false, locked: false, prunable: false, bare: false }, { ahead: 0, behind: 0, dirtyCount: 0, upstream: null });
|
const worktree = (await this.emitWorktree(row, path)) ?? this.toSummary(row.id, row.path, { path, head: null, branch: req.branch, detached: false, locked: false, prunable: false, bare: false }, { ahead: 0, behind: 0, dirtyCount: 0, upstream: null });
|
||||||
return { worktree, hookResults, session };
|
return { worktree, hookResults, session, action };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Branches locales/remote + branche par défaut d'un repo — alimente le sélecteur de base côté UI. */
|
||||||
|
async listRepoBranches(repoId: string): Promise<{ local: string[]; remote: string[]; default: string | null }> {
|
||||||
|
const row = this.getRepoRow(repoId);
|
||||||
|
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
|
||||||
|
return listBranches(row.path);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `git add -A` + commit dans le worktree visé (le checkout principal est un worktree valide ici). */
|
||||||
|
async commitWorktree(repoId: string, path: string, message: string): Promise<WorktreeSummary> {
|
||||||
|
const row = this.getRepoRow(repoId);
|
||||||
|
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
|
||||||
|
const w = await this.findWorktree(row, path);
|
||||||
|
if (!w) throw httpError(404, 'NOT_FOUND', 'No such worktree under this repo');
|
||||||
|
return this.withLock(repoId, async () => {
|
||||||
|
if ((await worktreeStatus(w.path)).dirtyCount === 0) {
|
||||||
|
throw httpError(409, 'NOTHING_TO_COMMIT', 'Nothing to commit — working tree is clean');
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await commitAll(w.path, message);
|
||||||
|
} catch (err) {
|
||||||
|
throw httpError(400, 'COMMIT_FAILED', (err as Error).message);
|
||||||
|
}
|
||||||
|
this.factsCache.delete(repoId);
|
||||||
|
return (await this.emitWorktree(row, w.path)) as WorktreeSummary;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pousse la branche du worktree visé (upstream auto si absent). */
|
||||||
|
async pushWorktree(repoId: string, path: string): Promise<WorktreeSummary> {
|
||||||
|
const row = this.getRepoRow(repoId);
|
||||||
|
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
|
||||||
|
const w = await this.findWorktree(row, path);
|
||||||
|
if (!w) throw httpError(404, 'NOT_FOUND', 'No such worktree under this repo');
|
||||||
|
return this.withLock(repoId, async () => {
|
||||||
|
try {
|
||||||
|
await push(w.path);
|
||||||
|
} catch (err) {
|
||||||
|
throw httpError(400, 'PUSH_FAILED', (err as Error).message);
|
||||||
|
}
|
||||||
|
this.factsCache.delete(repoId);
|
||||||
|
return (await this.emitWorktree(row, w.path)) as WorktreeSummary;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* « Passer en principal » : la branche du worktree devient le checkout principal du dépôt. Une branche
|
||||||
|
* ne pouvant être extraite qu'à un seul endroit, on retire d'abord le worktree (libère la branche) puis
|
||||||
|
* on bascule le checkout principal dessus. Sans merge ni conflit possible. L'ancienne branche principale
|
||||||
|
* est conservée (jamais supprimée). Garde-fous d'arbre sale outrepassables par `force`.
|
||||||
|
*/
|
||||||
|
async promoteWorktree(repoId: string, path: string, force = false): Promise<WorktreeSummary | null> {
|
||||||
|
const row = this.getRepoRow(repoId);
|
||||||
|
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
|
||||||
|
const w = await this.findWorktree(row, path);
|
||||||
|
if (!w) throw httpError(404, 'NOT_FOUND', 'No such worktree under this repo');
|
||||||
|
if (resolve(w.path) === resolve(row.path)) throw httpError(400, 'IS_MAIN_WORKTREE', 'This is already the main checkout');
|
||||||
|
if (!w.branch || w.detached) throw httpError(400, 'DETACHED_WORKTREE', 'Worktree has no branch to promote (detached HEAD)');
|
||||||
|
const branch = w.branch;
|
||||||
|
return this.withLock(repoId, async () => {
|
||||||
|
if (!force) {
|
||||||
|
if ((await worktreeStatus(w.path)).dirtyCount > 0) {
|
||||||
|
throw httpError(409, 'WORKTREE_DIRTY', 'Worktree has uncommitted changes — commit or pass force');
|
||||||
|
}
|
||||||
|
if ((await worktreeStatus(row.path)).dirtyCount > 0) {
|
||||||
|
throw httpError(409, 'DIRTY_TREE', 'Main checkout has uncommitted changes — commit/stash or pass force');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await removeWorktree(row.path, w.path, force);
|
||||||
|
} catch (err) {
|
||||||
|
if (!force && isDirtyWorktreeError(err)) {
|
||||||
|
throw httpError(409, 'WORKTREE_DIRTY', 'Worktree has uncommitted changes — pass force to promote anyway');
|
||||||
|
}
|
||||||
|
throw httpError(500, 'WORKTREE_REMOVE_FAILED', (err as Error).message);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await switchBranch(row.path, { branch, create: false });
|
||||||
|
} catch (err) {
|
||||||
|
throw httpError(500, 'SWITCH_FAILED', (err as Error).message);
|
||||||
|
}
|
||||||
|
this.factsCache.delete(repoId);
|
||||||
|
this.emit('worktree_removed', { repoId, path: w.path });
|
||||||
|
return this.emitWorktree(row, row.path); // le checkout principal est désormais sur `branch`
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lance UNE session dans le checkout principal du repo (`repo.path`) — pour « bosser sur la branche
|
||||||
|
* principale » sans créer de worktree. Si `branch` est fourni, crée/bascule d'abord cette branche
|
||||||
|
* dans ce checkout (`git switch[-c]`), refusé si l'arbre est sale (on n'écrase pas un HEAD modifié).
|
||||||
|
* Volontairement SANS hooks ni pré-trust (contraste avec createWorktree) : le checkout principal
|
||||||
|
* est le dépôt réel de l'utilisateur, déjà configuré/approuvé. Sérialisé par repo (withLock).
|
||||||
|
*/
|
||||||
|
async startMainSession(
|
||||||
|
repoId: string,
|
||||||
|
req: { command?: 'claude' | 'bash'; branch?: string; newBranch?: boolean },
|
||||||
|
): Promise<{ session: SessionSummary; worktree: WorktreeSummary | null }> {
|
||||||
|
const row = this.getRepoRow(repoId);
|
||||||
|
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
|
||||||
|
const branch = req.branch?.trim() || undefined;
|
||||||
|
if (branch !== undefined && !isValidBranchName(branch)) throw httpError(400, 'BAD_BRANCH', `Invalid branch name: ${branch}`);
|
||||||
|
|
||||||
|
return this.withLock(repoId, async () => {
|
||||||
|
if (branch !== undefined) {
|
||||||
|
// garde-fou : ne pas basculer le HEAD du checkout principal s'il a des changements non sauvegardés.
|
||||||
|
if ((await worktreeStatus(row.path)).dirtyCount > 0) {
|
||||||
|
throw httpError(409, 'DIRTY_TREE', 'Main checkout has uncommitted changes — commit or stash before switching branch');
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await switchBranch(row.path, { branch, create: req.newBranch ?? true });
|
||||||
|
} catch (err) {
|
||||||
|
throw httpError(400, 'SWITCH_FAILED', (err as Error).message);
|
||||||
|
}
|
||||||
|
this.factsCache.delete(repoId);
|
||||||
|
}
|
||||||
|
const session = this.ptyManager.spawn({ cwd: row.path, command: req.command ?? 'claude' });
|
||||||
|
const worktree = await this.emitWorktree(row, row.path);
|
||||||
|
return { session, worktree };
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -306,7 +515,7 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
|||||||
if (!w) throw httpError(404, 'NOT_FOUND', 'No such worktree under this repo');
|
if (!w) throw httpError(404, 'NOT_FOUND', 'No such worktree under this repo');
|
||||||
if (resolve(w.path) === resolve(row.path)) throw httpError(400, 'IS_MAIN_WORKTREE', 'Cannot remove the main worktree');
|
if (resolve(w.path) === resolve(row.path)) throw httpError(400, 'IS_MAIN_WORKTREE', 'Cannot remove the main worktree');
|
||||||
// garde-fou : une session vivante tourne dans ce worktree → exiger une confirmation explicite.
|
// garde-fou : une session vivante tourne dans ce worktree → exiger une confirmation explicite.
|
||||||
if (!force && this.sessionsForCwd(w.path).some((s) => s.live)) {
|
if (!force && this.sessionsForCwd(w.path, { includeHidden: true }).some((s) => s.live)) {
|
||||||
throw httpError(409, 'SESSION_LIVE_IN_WORKTREE', 'A live session runs in this worktree — pass force to delete anyway');
|
throw httpError(409, 'SESSION_LIVE_IN_WORKTREE', 'A live session runs in this worktree — pass force to delete anyway');
|
||||||
}
|
}
|
||||||
return this.withLock(repoId, async () => {
|
return this.withLock(repoId, async () => {
|
||||||
|
|||||||
@@ -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 }> = [
|
||||||
{
|
{
|
||||||
@@ -68,6 +69,79 @@ const MIGRATIONS: Array<{ id: number; sql: string }> = [
|
|||||||
CREATE INDEX idx_push_subs_token ON push_subscriptions(token_id);
|
CREATE INDEX idx_push_subs_token ON push_subscriptions(token_id);
|
||||||
`,
|
`,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
// P5 — groupes de travail. Un groupe = collection de repos (many-to-many).
|
||||||
|
// Worktrees/sessions NON persistés ici : servis par WorktreeManager/PtyManager
|
||||||
|
// et filtrés côté client par repoId. CASCADE s'appuie sur PRAGMA foreign_keys = ON (cf. openDb).
|
||||||
|
id: 5,
|
||||||
|
sql: `
|
||||||
|
CREATE TABLE groups (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
label TEXT NOT NULL,
|
||||||
|
description TEXT,
|
||||||
|
color TEXT,
|
||||||
|
position INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE group_repos (
|
||||||
|
group_id TEXT NOT NULL REFERENCES groups(id) ON DELETE CASCADE,
|
||||||
|
repo_id TEXT NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
|
||||||
|
position INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (group_id, 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);
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// P6 — session de groupe multi-repo. Une session peut couvrir plusieurs répertoires (--add-dir)
|
||||||
|
// et appartenir à un groupe. `added_dirs` : JSON array de chemins absolus (NULL si mono-repo).
|
||||||
|
// `group_id` : pas de FK (ALTER ADD COLUMN sqlite n'en pose pas) ; nettoyé à la suppression du groupe.
|
||||||
|
id: 8,
|
||||||
|
sql: `
|
||||||
|
ALTER TABLE sessions ADD COLUMN added_dirs TEXT;
|
||||||
|
ALTER TABLE sessions ADD COLUMN group_id TEXT;
|
||||||
|
CREATE INDEX idx_sessions_group_id ON sessions(group_id);
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// Masquage des sessions Claude découvertes (lancées en CLI hors Arboretum) qui polluent la liste.
|
||||||
|
// Calqué sur repos.hidden (#6) : la session masquée reste connue (resume/fork possibles) mais est
|
||||||
|
// exclue de la liste par défaut, et un re-scan ne la ressuscite pas. Clé = claudeSessionId (stable,
|
||||||
|
// partagé entre une découverte et sa reprise managée).
|
||||||
|
id: 9,
|
||||||
|
sql: `
|
||||||
|
CREATE TABLE hidden_sessions (
|
||||||
|
claude_session_id TEXT PRIMARY KEY,
|
||||||
|
hidden_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
`,
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
export type Db = DatabaseSync;
|
export type Db = DatabaseSync;
|
||||||
@@ -76,10 +150,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(
|
||||||
@@ -107,3 +198,23 @@ export function getSetting(db: Db, key: string): string | null {
|
|||||||
export function setSetting(db: Db, key: string, value: string): void {
|
export function setSetting(db: Db, key: string, value: string): void {
|
||||||
db.prepare('INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value').run(key, value);
|
db.prepare('INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value').run(key, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- Sessions masquées (par claudeSessionId) ----
|
||||||
|
|
||||||
|
/** Ensemble des claudeSessionId masqués par l'utilisateur. */
|
||||||
|
export function listHiddenSessionIds(db: Db): Set<string> {
|
||||||
|
const rows = db.prepare('SELECT claude_session_id FROM hidden_sessions').all() as Array<{ claude_session_id: string }>;
|
||||||
|
return new Set(rows.map((r) => r.claude_session_id));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Masque une session (idempotent). */
|
||||||
|
export function hideSession(db: Db, claudeSessionId: string): void {
|
||||||
|
db.prepare(
|
||||||
|
'INSERT INTO hidden_sessions (claude_session_id, hidden_at) VALUES (?, ?) ON CONFLICT(claude_session_id) DO NOTHING',
|
||||||
|
).run(claudeSessionId, new Date().toISOString());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ré-affiche une session masquée (idempotent). */
|
||||||
|
export function unhideSession(db: Db, claudeSessionId: string): void {
|
||||||
|
db.prepare('DELETE FROM hidden_sessions WHERE claude_session_id = ?').run(claudeSessionId);
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,32 +2,30 @@
|
|||||||
import { readFileSync } from 'node:fs';
|
import { readFileSync } from 'node:fs';
|
||||||
import { join, dirname } from 'node:path';
|
import { join, dirname } from 'node:path';
|
||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from 'node:url';
|
||||||
import { loadConfig } from './config.js';
|
import { loadConfig, type Config } from './config.js';
|
||||||
import { openDb } from './db/index.js';
|
import { openDb } from './db/index.js';
|
||||||
import { buildApp } from './app.js';
|
import { buildApp } from './app.js';
|
||||||
|
import { runInstall, runUninstall, runStatus, printUsage, printTokenBanner } from './cli/install.js';
|
||||||
|
|
||||||
const pkg = JSON.parse(
|
const pkg = JSON.parse(
|
||||||
readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'package.json'), 'utf8'),
|
readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'package.json'), 'utf8'),
|
||||||
) as { version: string };
|
) as { version: string };
|
||||||
|
|
||||||
async function main(): Promise<void> {
|
/** Démarre le daemon : écoute HTTP, scan des sessions, drain propre au SIGTERM/SIGINT. */
|
||||||
const config = loadConfig();
|
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}`);
|
||||||
if (bootstrapToken) {
|
if (bootstrapToken) {
|
||||||
// Affiché une seule fois : le hash seul est stocké.
|
// Affiché une seule fois : le hash seul est stocké.
|
||||||
console.log('\n┌──────────────────────────────────────────────────────────────────┐');
|
printTokenBanner(bootstrapToken, url);
|
||||||
console.log('│ First start — your access token (shown once, store it safely): │');
|
|
||||||
console.log('└──────────────────────────────────────────────────────────────────┘');
|
|
||||||
console.log(`\n ${bootstrapToken}\n`);
|
|
||||||
console.log(` Login at: ${url}/\n`);
|
|
||||||
} else if (config.printToken) {
|
} else if (config.printToken) {
|
||||||
console.log('Tokens are stored hashed and cannot be re-printed. Create a new one from Settings (or reset the db).');
|
console.log('Tokens are stored hashed and cannot be re-printed. Create a new one from Settings (or reset the db).');
|
||||||
}
|
}
|
||||||
@@ -38,6 +36,7 @@ async function main(): 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));
|
||||||
@@ -47,6 +46,36 @@ async function main(): Promise<void> {
|
|||||||
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Routeur de sous-commandes. On inspecte argv[0] AVANT loadConfig (parseArgs strict throw sur
|
||||||
|
// un positionnel inconnu). Aucune sous-commande (ou un flag en tête) → daemon : rétrocompat stricte
|
||||||
|
// de `arboretum`, `arboretum --port 8080`, `npx @johanleroy/git-arboretum --allow-origin …`.
|
||||||
|
async function main(): Promise<void> {
|
||||||
|
const argv = process.argv.slice(2);
|
||||||
|
const cmd = argv[0];
|
||||||
|
switch (cmd) {
|
||||||
|
case 'install':
|
||||||
|
return runInstall(argv.slice(1));
|
||||||
|
case 'uninstall':
|
||||||
|
return runUninstall(argv.slice(1));
|
||||||
|
case 'status':
|
||||||
|
return runStatus(argv.slice(1));
|
||||||
|
case 'serve':
|
||||||
|
return runDaemon(loadConfig(argv.slice(1)));
|
||||||
|
case 'help':
|
||||||
|
case '--help':
|
||||||
|
case '-h':
|
||||||
|
printUsage(pkg.version);
|
||||||
|
return;
|
||||||
|
default:
|
||||||
|
if (cmd && !cmd.startsWith('-')) {
|
||||||
|
console.error(`Unknown command: ${cmd}\n`);
|
||||||
|
printUsage(pkg.version);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
return runDaemon(loadConfig(argv));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
main().catch((err) => {
|
main().catch((err) => {
|
||||||
console.error(err instanceof Error ? err.message : err);
|
console.error(err instanceof Error ? err.message : err);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
|
|||||||
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,12 +1,31 @@
|
|||||||
import type { FastifyInstance } 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
|
||||||
|
// 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).
|
||||||
|
export function isHttpsRequest(req: FastifyRequest): boolean {
|
||||||
|
const xfp = req.headers['x-forwarded-proto'];
|
||||||
|
const proto = (Array.isArray(xfp) ? xfp[0] : xfp)?.split(',')[0]?.trim();
|
||||||
|
return proto === 'https';
|
||||||
|
}
|
||||||
|
|
||||||
export function registerAuthRoutes(
|
export function registerAuthRoutes(
|
||||||
app: FastifyInstance,
|
app: FastifyInstance,
|
||||||
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();
|
||||||
@@ -17,13 +36,16 @@ 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,
|
||||||
sameSite: 'strict',
|
sameSite: 'strict',
|
||||||
|
secure: isHttpsRequest(req),
|
||||||
maxAge: 30 * 24 * 3600,
|
maxAge: 30 * 24 * 3600,
|
||||||
});
|
});
|
||||||
const res: LoginResponse = { ok: true, label: ctx.label };
|
const res: LoginResponse = { ok: true, label: ctx.label };
|
||||||
@@ -31,12 +53,53 @@ 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);
|
||||||
});
|
});
|
||||||
|
|
||||||
app.post('/api/v1/auth/logout', async (_req, reply) => {
|
app.post('/api/v1/auth/logout', async (req, reply) => {
|
||||||
void reply.clearCookie(auth.cookieName, { path: '/' });
|
// Les attributs doivent matcher ceux posés au login pour que le navigateur efface bien le cookie.
|
||||||
|
void reply.clearCookie(auth.cookieName, { path: '/', secure: isHttpsRequest(req) });
|
||||||
|
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 });
|
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);
|
||||||
|
});
|
||||||
|
}
|
||||||
162
packages/server/src/routes/groups.ts
Normal file
162
packages/server/src/routes/groups.ts
Normal file
@@ -0,0 +1,162 @@
|
|||||||
|
import type { FastifyInstance } from 'fastify';
|
||||||
|
import type {
|
||||||
|
AddRepoRequest,
|
||||||
|
CreateGroupRequest,
|
||||||
|
CreateGroupSessionRequest,
|
||||||
|
GroupResponse,
|
||||||
|
GroupSessionResponse,
|
||||||
|
GroupsListResponse,
|
||||||
|
UpdateGroupRequest,
|
||||||
|
} from '@arboretum/shared';
|
||||||
|
import type { GroupManager } from '../core/group-manager.js';
|
||||||
|
import type { WorktreeManager } from '../core/worktree-manager.js';
|
||||||
|
import type { PtyManager } from '../core/pty-manager.js';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
import { recordAudit } from '../core/audit-log.js';
|
||||||
|
import { resolveGroupCwd } from '../core/group-session.js';
|
||||||
|
import { sendManagerError } from './repos.js';
|
||||||
|
|
||||||
|
export function registerGroupRoutes(
|
||||||
|
app: FastifyInstance,
|
||||||
|
gm: GroupManager,
|
||||||
|
db: Db,
|
||||||
|
wt: WorktreeManager,
|
||||||
|
manager: PtyManager,
|
||||||
|
): void {
|
||||||
|
app.get('/api/v1/groups', async (): Promise<GroupsListResponse> => ({ groups: gm.listGroups() }));
|
||||||
|
|
||||||
|
app.get('/api/v1/groups/:id', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
try {
|
||||||
|
return reply.send({ group: gm.getGroup(id) } satisfies GroupResponse);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post('/api/v1/groups', async (req, reply) => {
|
||||||
|
const body = req.body as Partial<CreateGroupRequest> | null;
|
||||||
|
if (!body || typeof body.label !== 'string') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'label is required' } });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const group = gm.createGroup({
|
||||||
|
label: body.label,
|
||||||
|
...(body.description !== undefined ? { description: body.description } : {}),
|
||||||
|
...(body.color !== undefined ? { color: body.color } : {}),
|
||||||
|
...(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);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.patch('/api/v1/groups/:id', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const body = (req.body as Partial<UpdateGroupRequest> | null) ?? {};
|
||||||
|
try {
|
||||||
|
const group = gm.updateGroup(id, {
|
||||||
|
...(body.label !== undefined ? { label: body.label } : {}),
|
||||||
|
...(body.description !== undefined ? { description: body.description } : {}),
|
||||||
|
...(body.color !== undefined ? { color: body.color } : {}),
|
||||||
|
});
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'group.update', resourceId: id });
|
||||||
|
return reply.send({ group } satisfies GroupResponse);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.delete('/api/v1/groups/:id', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
if (!gm.deleteGroup(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 });
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post('/api/v1/groups/:id/repos', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const body = req.body as Partial<AddRepoRequest> | null;
|
||||||
|
if (!body || typeof body.repoId !== 'string') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'repoId is required' } });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return reply.send({ group: gm.addRepo(id, body.repoId) } satisfies GroupResponse);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.delete('/api/v1/groups/:id/repos/:repoId', async (req, reply) => {
|
||||||
|
const { id, repoId } = req.params as { id: string; repoId: string };
|
||||||
|
try {
|
||||||
|
return reply.send({ group: gm.removeRepo(id, repoId) } satisfies GroupResponse);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Session de groupe (P6) : UNE session Claude couvrant tous les repos du groupe (--add-dir).
|
||||||
|
// Les répertoires sont résolus côté serveur depuis les propres worktrees du groupe — le client
|
||||||
|
// ne passe jamais de chemin brut. `branch` présent → worktree de cette branche par repo ;
|
||||||
|
// absent → le worktree principal de chaque repo.
|
||||||
|
app.post('/api/v1/groups/:id/session', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const body = (req.body as Partial<CreateGroupSessionRequest> | null) ?? {};
|
||||||
|
const command = body.command ?? 'claude';
|
||||||
|
if (command !== 'claude' && command !== 'bash') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'command must be claude or bash' } });
|
||||||
|
}
|
||||||
|
const branch = typeof body.branch === 'string' && body.branch.trim() !== '' ? body.branch.trim() : null;
|
||||||
|
|
||||||
|
let group;
|
||||||
|
try {
|
||||||
|
group = gm.getGroup(id);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
|
||||||
|
const dirs: string[] = [];
|
||||||
|
const skipped: Array<{ repoId: string; reason: string }> = [];
|
||||||
|
for (const repoId of group.repoIds) {
|
||||||
|
let worktrees;
|
||||||
|
try {
|
||||||
|
worktrees = await wt.listRepoWorktrees(repoId);
|
||||||
|
} catch (err) {
|
||||||
|
skipped.push({ repoId, reason: err instanceof Error ? err.message : String(err) });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const match = branch ? worktrees.find((w) => w.branch === branch) : worktrees.find((w) => w.isMain);
|
||||||
|
if (!match) {
|
||||||
|
skipped.push({ repoId, reason: branch ? `no worktree on branch ${branch}` : 'no main worktree' });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!dirs.includes(match.path)) dirs.push(match.path);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dirs.length === 0) {
|
||||||
|
const detail = branch ? `no repo has a worktree on branch "${branch}" (create it first)` : 'no repo has a resolvable main checkout';
|
||||||
|
return reply.status(400).send({ error: { code: 'NO_RESOLVABLE_WORKTREE', message: `Cannot start group session: ${detail}` } });
|
||||||
|
}
|
||||||
|
// cwd = parent commun des repos couverts, chacun relié en --add-dir (P6). Voir resolveGroupCwd.
|
||||||
|
const { cwd, addDirs } = resolveGroupCwd(dirs);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const session = manager.spawn({ cwd, addDirs, command, groupId: id });
|
||||||
|
recordAudit(db, {
|
||||||
|
actor: req.authContext?.tokenId ?? 'unknown',
|
||||||
|
action: 'group.session.create',
|
||||||
|
resourceId: id,
|
||||||
|
details: { command, dirs: dirs.length, ...(branch ? { branch } : {}) },
|
||||||
|
});
|
||||||
|
return reply.status(201).send({ session, dirs, skipped } satisfies GroupSessionResponse);
|
||||||
|
} catch (err) {
|
||||||
|
const statusCode = (err as { statusCode?: number }).statusCode ?? 500;
|
||||||
|
return reply.status(statusCode).send({ error: { code: 'SPAWN_FAILED', message: (err as Error).message } });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
|||||||
@@ -1,13 +1,24 @@
|
|||||||
import type { FastifyInstance } from 'fastify';
|
import type { FastifyInstance } from 'fastify';
|
||||||
import type { CreateSessionRequest, SessionResponse, SessionsListResponse } from '@arboretum/shared';
|
import type { CreateSessionRequest, HideDiscoveredResponse, SessionResponse, SessionsListResponse } from '@arboretum/shared';
|
||||||
import type { PtyManager } from '../core/pty-manager.js';
|
import type { PtyManager } from '../core/pty-manager.js';
|
||||||
import { mergeSessions, type DiscoveryService } from '../core/discovery-service.js';
|
import { mergeSessions, type DiscoveryService } from '../core/discovery-service.js';
|
||||||
|
import { hideSession, unhideSession, type Db } from '../db/index.js';
|
||||||
|
import { recordAudit } from '../core/audit-log.js';
|
||||||
|
|
||||||
export function registerSessionRoutes(app: FastifyInstance, manager: PtyManager, discovery: DiscoveryService): void {
|
export function registerSessionRoutes(app: FastifyInstance, manager: PtyManager, discovery: DiscoveryService, db: Db): void {
|
||||||
app.get('/api/v1/sessions', async (): Promise<SessionsListResponse> => {
|
app.get('/api/v1/sessions', async (req): Promise<SessionsListResponse> => {
|
||||||
return { sessions: mergeSessions(manager.list(), discovery.list()) };
|
const includeHidden = (req.query as { includeHidden?: string }).includeHidden === 'true';
|
||||||
|
const all = mergeSessions(manager.list(), discovery.list());
|
||||||
|
return { sessions: includeHidden ? all : all.filter((s) => !s.hidden) };
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Résout le claudeSessionId d'un :id de session (managée par UUID, ou découverte dont l'id EST le sid).
|
||||||
|
const resolveClaudeSid = (id: string): string | null => {
|
||||||
|
const managed = manager.resumeTargetById(id);
|
||||||
|
if (managed?.claudeSessionId) return managed.claudeSessionId;
|
||||||
|
return discovery.getDiscovered(id) ? id : null;
|
||||||
|
};
|
||||||
|
|
||||||
app.post('/api/v1/sessions', async (req, reply) => {
|
app.post('/api/v1/sessions', async (req, reply) => {
|
||||||
const body = req.body as Partial<CreateSessionRequest> | null;
|
const body = req.body as Partial<CreateSessionRequest> | null;
|
||||||
if (!body || typeof body.cwd !== 'string' || !body.cwd.startsWith('/')) {
|
if (!body || typeof body.cwd !== 'string' || !body.cwd.startsWith('/')) {
|
||||||
@@ -26,20 +37,32 @@ export function registerSessionRoutes(app: FastifyInstance, manager: PtyManager,
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Reprise d'une session morte : nouveau PTY managé `--resume <id>` DANS SON CWD D'ORIGINE (spike S1).
|
// Reprise d'une session morte : nouveau PTY managé `--resume <claudeSessionId>` DANS SON CWD D'ORIGINE
|
||||||
// Le cwd n'est jamais fourni par le client : il est lu sur disque via la découverte.
|
// (spike S1). Le cwd n'est JAMAIS fourni par le client. Deux origines d'id possibles :
|
||||||
|
// - session managée morte (id = UUID Arboretum) → cwd + claudeSessionId + groupe lus en DB ;
|
||||||
|
// - session claude EXTERNE découverte (id = claudeSessionId) → cwd lu sur disque.
|
||||||
app.post('/api/v1/sessions/:id/resume', async (req, reply) => {
|
app.post('/api/v1/sessions/:id/resume', async (req, reply) => {
|
||||||
const { id } = req.params as { id: string };
|
const { id } = req.params as { id: string };
|
||||||
const discovered = discovery.getDiscovered(id);
|
const managed = manager.resumeTargetById(id);
|
||||||
if (!discovered) {
|
const discovered = managed ? null : discovery.getDiscovered(id);
|
||||||
|
if (!managed && !discovered) {
|
||||||
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No resumable session with this id' } });
|
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No resumable session with this id' } });
|
||||||
}
|
}
|
||||||
|
const cwd = managed ? managed.cwd : discovered!.cwd;
|
||||||
|
const claudeSessionId = managed ? managed.claudeSessionId : id;
|
||||||
// Garde-fou anti-corruption : jamais de resume direct d'une session vivante (vérif FRAÎCHE).
|
// Garde-fou anti-corruption : jamais de resume direct d'une session vivante (vérif FRAÎCHE).
|
||||||
if (discovery.isClaudeSessionLive(id) || manager.findLiveByClaudeSessionId(id)) {
|
if (discovery.isClaudeSessionLive(claudeSessionId) || manager.findLiveByClaudeSessionId(claudeSessionId)) {
|
||||||
return reply.status(409).send({ error: { code: 'SESSION_LIVE', message: 'Session is live — fork it instead' } });
|
return reply.status(409).send({ error: { code: 'SESSION_LIVE', message: 'Session is live — fork it instead' } });
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const session = manager.spawn({ cwd: discovered.cwd, resume: { claudeSessionId: id } });
|
// Session de groupe (P6) : re-relie les mêmes répertoires (--add-dir) et son groupe au resume.
|
||||||
|
const ctx = managed ? { addedDirs: managed.addedDirs, groupId: managed.groupId } : manager.groupSessionContext(claudeSessionId);
|
||||||
|
const session = manager.spawn({
|
||||||
|
cwd,
|
||||||
|
resume: { claudeSessionId },
|
||||||
|
...(ctx?.addedDirs.length ? { addDirs: ctx.addedDirs } : {}),
|
||||||
|
...(ctx?.groupId ? { groupId: ctx.groupId } : {}),
|
||||||
|
});
|
||||||
const res: SessionResponse = { session };
|
const res: SessionResponse = { session };
|
||||||
return reply.status(201).send(res);
|
return reply.status(201).send(res);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -49,14 +72,18 @@ export function registerSessionRoutes(app: FastifyInstance, manager: PtyManager,
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Fork : duplique une session (vivante ou morte) sans la corrompre (`--resume <id> --fork-session`).
|
// Fork : duplique une session (vivante ou morte) sans la corrompre (`--resume <id> --fork-session`).
|
||||||
|
// Même résolution d'id que /resume (managée morte par UUID, sinon externe découverte par claudeSessionId).
|
||||||
app.post('/api/v1/sessions/:id/fork', async (req, reply) => {
|
app.post('/api/v1/sessions/:id/fork', async (req, reply) => {
|
||||||
const { id } = req.params as { id: string };
|
const { id } = req.params as { id: string };
|
||||||
const discovered = discovery.getDiscovered(id);
|
const managed = manager.resumeTargetById(id);
|
||||||
if (!discovered) {
|
const discovered = managed ? null : discovery.getDiscovered(id);
|
||||||
|
if (!managed && !discovered) {
|
||||||
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No session with this id to fork' } });
|
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No session with this id to fork' } });
|
||||||
}
|
}
|
||||||
|
const cwd = managed ? managed.cwd : discovered!.cwd;
|
||||||
|
const claudeSessionId = managed ? managed.claudeSessionId : id;
|
||||||
try {
|
try {
|
||||||
const session = manager.spawn({ cwd: discovered.cwd, resume: { claudeSessionId: id, fork: true } });
|
const session = manager.spawn({ cwd, resume: { claudeSessionId, fork: true } });
|
||||||
const res: SessionResponse = { session };
|
const res: SessionResponse = { session };
|
||||||
return reply.status(201).send(res);
|
return reply.status(201).send(res);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -65,6 +92,49 @@ export function registerSessionRoutes(app: FastifyInstance, manager: PtyManager,
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Masque une session découverte (ou managée morte) : exclue de la liste sauf ?includeHidden=true.
|
||||||
|
// Reste reprenable/forkable — c'est un filtre d'affichage, pas une suppression.
|
||||||
|
app.post('/api/v1/sessions/:id/hide', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const sid = resolveClaudeSid(id);
|
||||||
|
if (!sid) {
|
||||||
|
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No session with this id to hide' } });
|
||||||
|
}
|
||||||
|
hideSession(db, sid);
|
||||||
|
await discovery.refresh(); // rediffuse l'état (hidden) aux clients
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'session.hide', resourceId: sid });
|
||||||
|
return reply.send({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
// Ré-affiche une session masquée.
|
||||||
|
app.delete('/api/v1/sessions/:id/hide', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const sid = resolveClaudeSid(id);
|
||||||
|
if (!sid) {
|
||||||
|
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No session with this id to unhide' } });
|
||||||
|
}
|
||||||
|
unhideSession(db, sid);
|
||||||
|
await discovery.refresh();
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'session.unhide', resourceId: sid });
|
||||||
|
return reply.send({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
// Masquage de masse : nettoie d'un coup tout l'historique externe actuellement visible. Les futures
|
||||||
|
// sessions externes réapparaîtront (sinon --no-discover). Renvoie le nombre de sessions masquées.
|
||||||
|
app.post('/api/v1/sessions/hide-discovered', async (req, reply) => {
|
||||||
|
const sids = discovery
|
||||||
|
.list()
|
||||||
|
.filter((s) => !s.hidden && s.claudeSessionId)
|
||||||
|
.map((s) => s.claudeSessionId as string);
|
||||||
|
for (const sid of sids) hideSession(db, sid);
|
||||||
|
await discovery.refresh();
|
||||||
|
if (sids.length > 0) {
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'session.hideDiscovered', resourceId: null, details: { count: sids.length } });
|
||||||
|
}
|
||||||
|
const res: HideDiscoveredResponse = { hidden: sids.length };
|
||||||
|
return reply.send(res);
|
||||||
|
});
|
||||||
|
|
||||||
app.delete('/api/v1/sessions/:id', async (req, reply) => {
|
app.delete('/api/v1/sessions/:id', async (req, reply) => {
|
||||||
const { id } = req.params as { id: string };
|
const { id } = req.params as { id: string };
|
||||||
if (!manager.kill(id)) {
|
if (!manager.kill(id)) {
|
||||||
|
|||||||
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());
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,15 +1,32 @@
|
|||||||
import type { FastifyInstance } from 'fastify';
|
import type { FastifyInstance } from 'fastify';
|
||||||
import type {
|
import type {
|
||||||
AdoptWorktreeRequest,
|
AdoptWorktreeRequest,
|
||||||
|
CommitWorktreeRequest,
|
||||||
CreateWorktreeRequest,
|
CreateWorktreeRequest,
|
||||||
CreateWorktreeResponse,
|
CreateWorktreeResponse,
|
||||||
|
PromoteWorktreeRequest,
|
||||||
|
PushWorktreeRequest,
|
||||||
|
RepoBranchesResponse,
|
||||||
|
SessionResponse,
|
||||||
|
StartRepoSessionRequest,
|
||||||
|
WorktreeBranchMode,
|
||||||
WorktreeResponse,
|
WorktreeResponse,
|
||||||
WorktreesListResponse,
|
WorktreesListResponse,
|
||||||
} from '@arboretum/shared';
|
} 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 { recordAudit } from '../core/audit-log.js';
|
||||||
import { sendManagerError } from './repos.js';
|
import { sendManagerError } from './repos.js';
|
||||||
|
|
||||||
export function registerWorktreeRoutes(app: FastifyInstance, wt: WorktreeManager): void {
|
/** Mappe l'API (mode prioritaire ; `newBranch` déprécié) vers la stratégie de résolution de branche. */
|
||||||
|
function resolveMode(body: { mode?: unknown; newBranch?: unknown }): WorktreeBranchMode {
|
||||||
|
if (body.mode === 'auto' || body.mode === 'create' || body.mode === 'checkout') return body.mode;
|
||||||
|
if (body.newBranch === true) return 'create';
|
||||||
|
if (body.newBranch === false) return 'checkout';
|
||||||
|
return 'auto';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function registerWorktreeRoutes(app: FastifyInstance, wt: WorktreeManager, db: Db): void {
|
||||||
app.get('/api/v1/worktrees', async (): Promise<WorktreesListResponse> => ({ worktrees: await wt.listAllWorktrees() }));
|
app.get('/api/v1/worktrees', async (): Promise<WorktreesListResponse> => ({ worktrees: await wt.listAllWorktrees() }));
|
||||||
|
|
||||||
app.get('/api/v1/repos/:id/worktrees', async (req): Promise<WorktreesListResponse> => {
|
app.get('/api/v1/repos/:id/worktrees', async (req): Promise<WorktreesListResponse> => {
|
||||||
@@ -29,7 +46,7 @@ export function registerWorktreeRoutes(app: FastifyInstance, wt: WorktreeManager
|
|||||||
try {
|
try {
|
||||||
const out = await wt.createWorktree(id, {
|
const out = await wt.createWorktree(id, {
|
||||||
branch: body.branch,
|
branch: body.branch,
|
||||||
newBranch: body.newBranch !== false, // défaut : créer la branche
|
mode: resolveMode(body), // défaut : auto (détecte créer / checkout / suivi remote)
|
||||||
...(body.baseRef !== undefined ? { baseRef: body.baseRef } : {}),
|
...(body.baseRef !== undefined ? { baseRef: body.baseRef } : {}),
|
||||||
...(body.path !== undefined ? { path: body.path } : {}),
|
...(body.path !== undefined ? { path: body.path } : {}),
|
||||||
...(body.runHooks !== undefined ? { runHooks: body.runHooks } : {}),
|
...(body.runHooks !== undefined ? { runHooks: body.runHooks } : {}),
|
||||||
@@ -43,6 +60,44 @@ export function registerWorktreeRoutes(app: FastifyInstance, wt: WorktreeManager
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Branches du repo (locales + suivies de origin + défaut) — alimente le sélecteur de base côté UI.
|
||||||
|
app.get('/api/v1/repos/:id/branches', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
try {
|
||||||
|
const out = await wt.listRepoBranches(id);
|
||||||
|
return reply.send(out satisfies RepoBranchesResponse);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Session sur le checkout principal (« bosser sur la branche principale » sans worktree),
|
||||||
|
// avec création/bascule de branche optionnelle côté serveur.
|
||||||
|
app.post('/api/v1/repos/:id/session', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const body = (req.body as Partial<StartRepoSessionRequest> | null) ?? {};
|
||||||
|
if (body.command != null && body.command !== 'claude' && body.command !== 'bash') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'command must be claude or bash' } });
|
||||||
|
}
|
||||||
|
if (body.branch != null && typeof body.branch !== 'string') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'branch must be a string' } });
|
||||||
|
}
|
||||||
|
if (body.newBranch != null && typeof body.newBranch !== 'boolean') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'newBranch must be a boolean' } });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const out = await wt.startMainSession(id, {
|
||||||
|
...(body.command !== undefined ? { command: body.command } : {}),
|
||||||
|
...(body.branch !== undefined ? { branch: body.branch } : {}),
|
||||||
|
...(body.newBranch !== undefined ? { newBranch: body.newBranch } : {}),
|
||||||
|
});
|
||||||
|
const res: SessionResponse = { session: out.session };
|
||||||
|
return reply.status(201).send(res);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
app.post('/api/v1/repos/:id/worktrees/adopt', async (req, reply) => {
|
app.post('/api/v1/repos/:id/worktrees/adopt', async (req, reply) => {
|
||||||
const { id } = req.params as { id: string };
|
const { id } = req.params as { id: string };
|
||||||
const body = req.body as Partial<AdoptWorktreeRequest> | null;
|
const body = req.body as Partial<AdoptWorktreeRequest> | null;
|
||||||
@@ -72,6 +127,57 @@ export function registerWorktreeRoutes(app: FastifyInstance, wt: WorktreeManager
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Commit (git add -A + commit) dans un worktree (ou le checkout principal).
|
||||||
|
app.post('/api/v1/repos/:id/worktrees/commit', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const body = req.body as Partial<CommitWorktreeRequest> | null;
|
||||||
|
if (!body || typeof body.path !== 'string') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path is required' } });
|
||||||
|
}
|
||||||
|
if (typeof body.message !== 'string' || body.message.trim() === '') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'message is required' } });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const worktree = await wt.commitWorktree(id, body.path, body.message.trim());
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'worktree.commit', resourceId: id, details: { path: body.path } });
|
||||||
|
return reply.send({ worktree } satisfies WorktreeResponse);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Push de la branche d'un worktree (upstream auto si absent).
|
||||||
|
app.post('/api/v1/repos/:id/worktrees/push', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const body = req.body as Partial<PushWorktreeRequest> | null;
|
||||||
|
if (!body || typeof body.path !== 'string') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path is required' } });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const worktree = await wt.pushWorktree(id, body.path);
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'worktree.push', resourceId: id, details: { path: body.path } });
|
||||||
|
return reply.send({ worktree } satisfies WorktreeResponse);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Promotion « en principal » : la branche du worktree devient le checkout principal (worktree supprimé).
|
||||||
|
app.post('/api/v1/repos/:id/worktrees/promote', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const body = req.body as Partial<PromoteWorktreeRequest> | null;
|
||||||
|
if (!body || typeof body.path !== 'string') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path is required' } });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const worktree = await wt.promoteWorktree(id, body.path, body.force === true);
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'worktree.promote', resourceId: id, details: { path: body.path } });
|
||||||
|
return reply.send({ worktree });
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
app.delete('/api/v1/repos/:id/worktrees', async (req, reply) => {
|
app.delete('/api/v1/repos/:id/worktrees', async (req, reply) => {
|
||||||
const { id } = req.params as { id: string };
|
const { id } = req.params as { id: string };
|
||||||
const query = req.query as { path?: string; force?: string };
|
const query = req.query as { path?: string; force?: string };
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
PROTOCOL_VERSION,
|
PROTOCOL_VERSION,
|
||||||
encodeBinaryFrame,
|
encodeBinaryFrame,
|
||||||
parseClientMessage,
|
parseClientMessage,
|
||||||
|
type GroupSummary,
|
||||||
type RepoSummary,
|
type RepoSummary,
|
||||||
type ServerMessage,
|
type ServerMessage,
|
||||||
type SessionSummary,
|
type SessionSummary,
|
||||||
@@ -13,6 +14,7 @@ import {
|
|||||||
import type { ClientBinding, PtyManager } from '../core/pty-manager.js';
|
import type { ClientBinding, PtyManager } from '../core/pty-manager.js';
|
||||||
import type { DiscoveryService } from '../core/discovery-service.js';
|
import type { DiscoveryService } from '../core/discovery-service.js';
|
||||||
import type { WorktreeManager } from '../core/worktree-manager.js';
|
import type { WorktreeManager } from '../core/worktree-manager.js';
|
||||||
|
import type { GroupManager } from '../core/group-manager.js';
|
||||||
|
|
||||||
const HEARTBEAT_MS = 30_000;
|
const HEARTBEAT_MS = 30_000;
|
||||||
|
|
||||||
@@ -26,6 +28,7 @@ export function registerWsGateway(
|
|||||||
manager: PtyManager,
|
manager: PtyManager,
|
||||||
discovery: DiscoveryService,
|
discovery: DiscoveryService,
|
||||||
worktrees: WorktreeManager,
|
worktrees: WorktreeManager,
|
||||||
|
groups: GroupManager,
|
||||||
serverVersion: string,
|
serverVersion: string,
|
||||||
): void {
|
): void {
|
||||||
app.get('/ws', { websocket: true }, (socket: WebSocket, req) => {
|
app.get('/ws', { websocket: true }, (socket: WebSocket, req) => {
|
||||||
@@ -35,6 +38,7 @@ export function registerWsGateway(
|
|||||||
let helloDone = false;
|
let helloDone = false;
|
||||||
let subscribedSessions = false;
|
let subscribedSessions = false;
|
||||||
let subscribedWorktrees = false;
|
let subscribedWorktrees = false;
|
||||||
|
let subscribedGroups = false;
|
||||||
let alive = true;
|
let alive = true;
|
||||||
|
|
||||||
const send = (msg: ServerMessage): void => {
|
const send = (msg: ServerMessage): void => {
|
||||||
@@ -66,6 +70,12 @@ export function registerWsGateway(
|
|||||||
const onWorktreeRemoved = (e: { repoId: string; path: string }): void => {
|
const onWorktreeRemoved = (e: { repoId: string; path: string }): void => {
|
||||||
if (subscribedWorktrees) send({ type: 'worktree_removed', ...e });
|
if (subscribedWorktrees) send({ type: 'worktree_removed', ...e });
|
||||||
};
|
};
|
||||||
|
const onGroupUpdate = (group: GroupSummary): void => {
|
||||||
|
if (subscribedGroups) send({ type: 'group_update', group });
|
||||||
|
};
|
||||||
|
const onGroupRemoved = (groupId: string): void => {
|
||||||
|
if (subscribedGroups) send({ type: 'group_removed', groupId });
|
||||||
|
};
|
||||||
manager.on('session_update', onSessionUpdate);
|
manager.on('session_update', onSessionUpdate);
|
||||||
manager.on('session_exit', onSessionExit);
|
manager.on('session_exit', onSessionExit);
|
||||||
discovery.on('discovery_update', onDiscoveryUpdate);
|
discovery.on('discovery_update', onDiscoveryUpdate);
|
||||||
@@ -73,6 +83,8 @@ export function registerWsGateway(
|
|||||||
worktrees.on('repo_removed', onRepoRemoved);
|
worktrees.on('repo_removed', onRepoRemoved);
|
||||||
worktrees.on('worktree_update', onWorktreeUpdate);
|
worktrees.on('worktree_update', onWorktreeUpdate);
|
||||||
worktrees.on('worktree_removed', onWorktreeRemoved);
|
worktrees.on('worktree_removed', onWorktreeRemoved);
|
||||||
|
groups.on('group_update', onGroupUpdate);
|
||||||
|
groups.on('group_removed', onGroupRemoved);
|
||||||
|
|
||||||
const heartbeat = setInterval(() => {
|
const heartbeat = setInterval(() => {
|
||||||
if (!alive) {
|
if (!alive) {
|
||||||
@@ -111,6 +123,7 @@ export function registerWsGateway(
|
|||||||
case 'sub': {
|
case 'sub': {
|
||||||
subscribedSessions = msg.topics.includes('sessions');
|
subscribedSessions = msg.topics.includes('sessions');
|
||||||
subscribedWorktrees = msg.topics.includes('worktrees');
|
subscribedWorktrees = msg.topics.includes('worktrees');
|
||||||
|
subscribedGroups = msg.topics.includes('groups');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
case 'attach': {
|
case 'attach': {
|
||||||
@@ -202,6 +215,8 @@ export function registerWsGateway(
|
|||||||
worktrees.off('repo_removed', onRepoRemoved);
|
worktrees.off('repo_removed', onRepoRemoved);
|
||||||
worktrees.off('worktree_update', onWorktreeUpdate);
|
worktrees.off('worktree_update', onWorktreeUpdate);
|
||||||
worktrees.off('worktree_removed', onWorktreeRemoved);
|
worktrees.off('worktree_removed', onWorktreeRemoved);
|
||||||
|
groups.off('group_update', onGroupUpdate);
|
||||||
|
groups.off('group_removed', onGroupRemoved);
|
||||||
for (const [, st] of channels) manager.detach(st.sessionId, st.binding);
|
for (const [, st] of channels) manager.detach(st.sessionId, st.binding);
|
||||||
channels.clear();
|
channels.clear();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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' }));
|
||||||
@@ -91,9 +92,25 @@ describe('app e2e — auth, origin et sessions', () => {
|
|||||||
expect(cookie).toBeDefined();
|
expect(cookie).toBeDefined();
|
||||||
expect(cookie?.httpOnly).toBe(true);
|
expect(cookie?.httpOnly).toBe(true);
|
||||||
expect(cookie?.sameSite).toBe('Strict');
|
expect(cookie?.sameSite).toBe('Strict');
|
||||||
|
// Login local (http, pas de x-forwarded-proto) → pas de Secure, sinon le cookie casserait en localhost.
|
||||||
|
expect(cookie?.secure).toBeFalsy();
|
||||||
cookieValue = cookie!.value;
|
cookieValue = cookie!.value;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('cookie Secure posé derrière un front HTTPS (x-forwarded-proto)', async () => {
|
||||||
|
const res = await t.bundle.app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/auth/login',
|
||||||
|
headers: { 'x-forwarded-proto': 'https' },
|
||||||
|
payload: { token: t.token },
|
||||||
|
});
|
||||||
|
expect(res.statusCode).toBe(200);
|
||||||
|
const cookie = res.cookies.find((c) => c.name === 'arb_session');
|
||||||
|
expect(cookie?.secure).toBe(true);
|
||||||
|
expect(cookie?.httpOnly).toBe(true);
|
||||||
|
expect(cookie?.sameSite).toBe('Strict');
|
||||||
|
});
|
||||||
|
|
||||||
it('routes API sans auth → 401', async () => {
|
it('routes API sans auth → 401', async () => {
|
||||||
for (const url of ['/api/v1/sessions', '/api/v1/auth/me']) {
|
for (const url of ['/api/v1/sessions', '/api/v1/auth/me']) {
|
||||||
const res = await t.bundle.app.inject({ method: 'GET', url });
|
const res = await t.bundle.app.inject({ method: 'GET', url });
|
||||||
@@ -111,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 () => {
|
||||||
@@ -130,6 +148,20 @@ describe('app e2e — auth, origin et sessions', () => {
|
|||||||
expect(res.json()).toEqual({ sessions: [] });
|
expect(res.json()).toEqual({ sessions: [] });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('masquage des sessions : hide-discovered (vide), includeHidden, hide d’un id inconnu → 404', async () => {
|
||||||
|
const headers = { authorization: `Bearer ${t.token}` };
|
||||||
|
const mass = await t.bundle.app.inject({ method: 'POST', url: '/api/v1/sessions/hide-discovered', headers });
|
||||||
|
expect(mass.statusCode).toBe(200);
|
||||||
|
expect(mass.json()).toEqual({ hidden: 0 });
|
||||||
|
|
||||||
|
const withHidden = await t.bundle.app.inject({ method: 'GET', url: '/api/v1/sessions?includeHidden=true', headers });
|
||||||
|
expect(withHidden.statusCode).toBe(200);
|
||||||
|
expect(withHidden.json()).toEqual({ sessions: [] });
|
||||||
|
|
||||||
|
const unknown = await t.bundle.app.inject({ method: 'POST', url: '/api/v1/sessions/nope/hide', headers });
|
||||||
|
expect(unknown.statusCode).toBe(404);
|
||||||
|
});
|
||||||
|
|
||||||
it('Origin interdite → 403 même avec un Bearer valide, et même sur la route publique de login', async () => {
|
it('Origin interdite → 403 même avec un Bearer valide, et même sur la route publique de login', async () => {
|
||||||
const res = await t.bundle.app.inject({
|
const res = await t.bundle.app.inject({
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
@@ -337,3 +369,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);
|
||||||
|
});
|
||||||
|
});
|
||||||
29
packages/server/test/claude-launcher.test.ts
Normal file
29
packages/server/test/claude-launcher.test.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
import { buildSpawnSpec } from '../src/core/claude-launcher.js';
|
||||||
|
|
||||||
|
// 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' }));
|
||||||
|
|
||||||
|
describe('buildSpawnSpec — session de groupe multi-repo (P6)', () => {
|
||||||
|
it('émet un --add-dir par répertoire supplémentaire (claude)', () => {
|
||||||
|
const spec = buildSpawnSpec({ command: 'claude', addDirs: ['/a', '/b', '/c'] });
|
||||||
|
expect(spec.file).toBe('/usr/bin/claude');
|
||||||
|
expect(spec.args).toEqual(['--add-dir', '/a', '--add-dir', '/b', '--add-dir', '/c']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('combine --resume et --add-dir (reprise d’une session de groupe)', () => {
|
||||||
|
const spec = buildSpawnSpec({ command: 'claude', resume: { claudeSessionId: 'sid' }, addDirs: ['/x'] });
|
||||||
|
expect(spec.args).toEqual(['--resume', 'sid', '--add-dir', '/x']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('aucun --add-dir quand addDirs est vide/absent', () => {
|
||||||
|
expect(buildSpawnSpec({ command: 'claude' }).args).toEqual([]);
|
||||||
|
expect(buildSpawnSpec({ command: 'claude', addDirs: [] }).args).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignore addDirs pour bash (pas de --add-dir)', () => {
|
||||||
|
const spec = buildSpawnSpec({ command: 'bash', addDirs: ['/a', '/b'] });
|
||||||
|
expect(spec.file).toBe('bash');
|
||||||
|
expect(spec.args).toEqual(['--norc']);
|
||||||
|
});
|
||||||
|
});
|
||||||
166
packages/server/test/cli-install.test.ts
Normal file
166
packages/server/test/cli-install.test.ts
Normal file
@@ -0,0 +1,166 @@
|
|||||||
|
import { afterEach, describe, expect, it } from 'vitest';
|
||||||
|
import { homedir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import {
|
||||||
|
detectPlatform,
|
||||||
|
parseInstallArgs,
|
||||||
|
buildServiceArgs,
|
||||||
|
resolveBin,
|
||||||
|
resolveScriptPath,
|
||||||
|
renderSystemdUnit,
|
||||||
|
renderLaunchAgentPlist,
|
||||||
|
xmlEscape,
|
||||||
|
systemdUnitPath,
|
||||||
|
launchAgentPlistPath,
|
||||||
|
} from '../src/cli/install.js';
|
||||||
|
|
||||||
|
describe('cli install — detectPlatform', () => {
|
||||||
|
it('accepte linux et darwin', () => {
|
||||||
|
expect(detectPlatform('linux')).toBe('linux');
|
||||||
|
expect(detectPlatform('darwin')).toBe('darwin');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejette les autres plateformes avec un message clair', () => {
|
||||||
|
expect(() => detectPlatform('win32')).toThrow(/Linux \(systemd\) and macOS \(launchd\)/);
|
||||||
|
expect(() => detectPlatform('freebsd')).toThrow(/freebsd/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('cli install — buildServiceArgs', () => {
|
||||||
|
it('aucun flag → aucun argument (le service garde les défauts loopback)', () => {
|
||||||
|
expect(buildServiceArgs(parseInstallArgs([]))).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('propage --port et --allow-origin (répétable) dans un ordre stable', () => {
|
||||||
|
const flags = parseInstallArgs(['--port', '8080', '--allow-origin', 'a', '--allow-origin', 'b']);
|
||||||
|
expect(buildServiceArgs(flags)).toEqual(['--port', '8080', '--allow-origin', 'a', '--allow-origin', 'b']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("n'injecte JAMAIS --i-know-this-exposes-a-terminal (modèle de sécurité)", () => {
|
||||||
|
const flags = parseInstallArgs(['--bind', '0.0.0.0', '--port', '7317']);
|
||||||
|
expect(buildServiceArgs(flags)).not.toContain('--i-know-this-exposes-a-terminal');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ne propage pas les flags propres à l'install (bin-path, label, dry-run, no-enable)", () => {
|
||||||
|
const flags = parseInstallArgs(['--bin-path', '/usr/local/bin/arboretum', '--label', 'x', '--dry-run', '--no-enable']);
|
||||||
|
expect(buildServiceArgs(flags)).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('cli install — resolveBin', () => {
|
||||||
|
it('par défaut : node (process.execPath) + dist/index.js', () => {
|
||||||
|
const { exec, args } = resolveBin({});
|
||||||
|
expect(exec).toBe(process.execPath);
|
||||||
|
expect(args).toHaveLength(1);
|
||||||
|
expect(args[0]).toBe(resolveScriptPath());
|
||||||
|
expect(args[0]).toMatch(/index\.(js|ts)$/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('--bin-path force le wrapper, sans argument de script', () => {
|
||||||
|
expect(resolveBin({ binPath: '/usr/local/bin/arboretum' })).toEqual({
|
||||||
|
exec: '/usr/local/bin/arboretum',
|
||||||
|
args: [],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('cli install — renderSystemdUnit', () => {
|
||||||
|
it('contient le ExecStart calculé et les directives clés', () => {
|
||||||
|
const unit = renderSystemdUnit({ exec: '/usr/bin/node', scriptArgs: ['/opt/arboretum/index.js', '--port', '7317'] });
|
||||||
|
expect(unit).toContain('ExecStart=/usr/bin/node /opt/arboretum/index.js --port 7317');
|
||||||
|
expect(unit).toContain('Restart=on-failure');
|
||||||
|
expect(unit).toContain('KillSignal=SIGTERM');
|
||||||
|
expect(unit).toContain('TimeoutStopSec=10');
|
||||||
|
expect(unit).toContain('WantedBy=default.target');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('quote les tokens contenant un espace', () => {
|
||||||
|
const unit = renderSystemdUnit({ exec: '/path with space/node', scriptArgs: ['/s.js'] });
|
||||||
|
expect(unit).toContain('ExecStart="/path with space/node" /s.js');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('snapshot du unit pour un jeu de flags fixe', () => {
|
||||||
|
const unit = renderSystemdUnit({
|
||||||
|
exec: '/usr/bin/node',
|
||||||
|
scriptArgs: ['/opt/arboretum/index.js', '--port', '7317', '--allow-origin', 'https://m.ts.net'],
|
||||||
|
});
|
||||||
|
expect(unit).toMatchInlineSnapshot(`
|
||||||
|
"[Unit]
|
||||||
|
Description=Arboretum — git worktree & Claude Code dashboard
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
ExecStart=/usr/bin/node /opt/arboretum/index.js --port 7317 --allow-origin https://m.ts.net
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=5
|
||||||
|
KillSignal=SIGTERM
|
||||||
|
TimeoutStopSec=10
|
||||||
|
Environment=NODE_ENV=production
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=default.target
|
||||||
|
"
|
||||||
|
`);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('cli install — renderLaunchAgentPlist', () => {
|
||||||
|
const base = {
|
||||||
|
label: 'fr.lidge.arboretum',
|
||||||
|
programArguments: ['/usr/bin/node', '/opt/index.js', '--port', '7317'],
|
||||||
|
stdoutPath: '/Users/me/Library/Logs/arboretum/out.log',
|
||||||
|
stderrPath: '/Users/me/Library/Logs/arboretum/err.log',
|
||||||
|
};
|
||||||
|
|
||||||
|
it('contient le label, les ProgramArguments ordonnés et les clés launchd', () => {
|
||||||
|
const plist = renderLaunchAgentPlist(base);
|
||||||
|
expect(plist).toContain('<string>fr.lidge.arboretum</string>');
|
||||||
|
const idxNode = plist.indexOf('<string>/usr/bin/node</string>');
|
||||||
|
const idxScript = plist.indexOf('<string>/opt/index.js</string>');
|
||||||
|
expect(idxNode).toBeGreaterThan(0);
|
||||||
|
expect(idxScript).toBeGreaterThan(idxNode);
|
||||||
|
expect(plist).toContain('<key>RunAtLoad</key>');
|
||||||
|
expect(plist).toContain('<key>KeepAlive</key>');
|
||||||
|
expect(plist).toContain('<key>StandardOutPath</key>');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('échappe les caractères XML dans les arguments (URL avec &)', () => {
|
||||||
|
const plist = renderLaunchAgentPlist({
|
||||||
|
...base,
|
||||||
|
programArguments: ['/usr/bin/node', '/opt/index.js', '--allow-origin', 'https://a?b&c=d'],
|
||||||
|
});
|
||||||
|
expect(plist).toContain('https://a?b&c=d');
|
||||||
|
expect(plist).not.toContain('b&c=d');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('cli install — xmlEscape', () => {
|
||||||
|
it('échappe &, < et >', () => {
|
||||||
|
expect(xmlEscape('a & b < c > d')).toBe('a & b < c > d');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('cli install — chemins', () => {
|
||||||
|
const savedXdg = process.env.XDG_CONFIG_HOME;
|
||||||
|
afterEach(() => {
|
||||||
|
if (savedXdg === undefined) delete process.env.XDG_CONFIG_HOME;
|
||||||
|
else process.env.XDG_CONFIG_HOME = savedXdg;
|
||||||
|
});
|
||||||
|
|
||||||
|
it('systemdUnitPath respecte XDG_CONFIG_HOME', () => {
|
||||||
|
process.env.XDG_CONFIG_HOME = '/tmp/xdg';
|
||||||
|
expect(systemdUnitPath()).toBe('/tmp/xdg/systemd/user/arboretum.service');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('systemdUnitPath retombe sur ~/.config sans XDG_CONFIG_HOME', () => {
|
||||||
|
delete process.env.XDG_CONFIG_HOME;
|
||||||
|
expect(systemdUnitPath()).toBe(join(homedir(), '.config', 'systemd', 'user', 'arboretum.service'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('launchAgentPlistPath place le plist dans ~/Library/LaunchAgents', () => {
|
||||||
|
expect(launchAgentPlistPath('fr.lidge.arboretum')).toBe(
|
||||||
|
join(homedir(), 'Library', 'LaunchAgents', 'fr.lidge.arboretum.plist'),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -7,7 +7,7 @@ import { DiscoveryService, mergeSessions } from '../src/core/discovery-service.j
|
|||||||
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 { PtyManager } from '../src/core/pty-manager.js';
|
import { PtyManager } from '../src/core/pty-manager.js';
|
||||||
import { openDb, type Db } from '../src/db/index.js';
|
import { openDb, hideSession, unhideSession, listHiddenSessionIds, type Db } from '../src/db/index.js';
|
||||||
|
|
||||||
function writeJsonl(projectsDir: string, cwd: string, sid: string): void {
|
function writeJsonl(projectsDir: string, cwd: string, sid: string): void {
|
||||||
const dir = join(projectsDir, munge(cwd));
|
const dir = join(projectsDir, munge(cwd));
|
||||||
@@ -30,7 +30,7 @@ describe('DiscoveryService', () => {
|
|||||||
sessionsDir = mkdtempSync(join(tmpdir(), 'arb-sess-'));
|
sessionsDir = mkdtempSync(join(tmpdir(), 'arb-sess-'));
|
||||||
db = openDb(':memory:');
|
db = openDb(':memory:');
|
||||||
manager = new PtyManager(db, sessionsDir);
|
manager = new PtyManager(db, sessionsDir);
|
||||||
svc = new DiscoveryService({ ptyManager: manager, projectsDir, sessionsDir });
|
svc = new DiscoveryService({ db, ptyManager: manager, projectsDir, sessionsDir });
|
||||||
});
|
});
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
svc.stop();
|
svc.stop();
|
||||||
@@ -71,6 +71,29 @@ describe('DiscoveryService', () => {
|
|||||||
expect(svc.list().find((x) => x.id === 'managed-sid')).toBeUndefined();
|
expect(svc.list().find((x) => x.id === 'managed-sid')).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('marque hidden une session masquée mais la garde résoluble (resume/fork)', async () => {
|
||||||
|
writeJsonl(projectsDir, '/home/u/old', 'old-sid');
|
||||||
|
hideSession(db, 'old-sid');
|
||||||
|
await svc.refresh();
|
||||||
|
const s = svc.list().find((x) => x.id === 'old-sid');
|
||||||
|
expect(s?.hidden).toBe(true);
|
||||||
|
// toujours connue : la reprise/le fork doivent rester possibles
|
||||||
|
expect(svc.getDiscovered('old-sid')?.cwd).toBe('/home/u/old');
|
||||||
|
// ré-affichage
|
||||||
|
unhideSession(db, 'old-sid');
|
||||||
|
await svc.refresh();
|
||||||
|
expect(svc.list().find((x) => x.id === 'old-sid')?.hidden).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hideSession est idempotent et listHiddenSessionIds reflète l’état', () => {
|
||||||
|
hideSession(db, 'a');
|
||||||
|
hideSession(db, 'a');
|
||||||
|
hideSession(db, 'b');
|
||||||
|
expect(listHiddenSessionIds(db)).toEqual(new Set(['a', 'b']));
|
||||||
|
unhideSession(db, 'a');
|
||||||
|
expect(listHiddenSessionIds(db)).toEqual(new Set(['b']));
|
||||||
|
});
|
||||||
|
|
||||||
it('émet discovery_update sur changement uniquement', async () => {
|
it('émet discovery_update sur changement uniquement', async () => {
|
||||||
writeJsonl(projectsDir, '/home/u/x', 'sid-x');
|
writeJsonl(projectsDir, '/home/u/x', 'sid-x');
|
||||||
const seen: SessionSummary[] = [];
|
const seen: SessionSummary[] = [];
|
||||||
|
|||||||
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,12 @@ import {
|
|||||||
addWorktree,
|
addWorktree,
|
||||||
removeWorktree,
|
removeWorktree,
|
||||||
pruneWorktrees,
|
pruneWorktrees,
|
||||||
|
switchBranch,
|
||||||
isDirtyWorktreeError,
|
isDirtyWorktreeError,
|
||||||
|
branchExists,
|
||||||
|
currentBranch,
|
||||||
|
listBranches,
|
||||||
|
commitAll,
|
||||||
} from '../src/core/git.js';
|
} from '../src/core/git.js';
|
||||||
|
|
||||||
const dirs: string[] = [];
|
const dirs: string[] = [];
|
||||||
@@ -95,7 +100,7 @@ describe('opérations git (repo tmp réel)', () => {
|
|||||||
const repo = makeTmpRepo();
|
const repo = makeTmpRepo();
|
||||||
const wtPath = join(dirname(repo), `${basename(repo)}-wt-feat`);
|
const wtPath = join(dirname(repo), `${basename(repo)}-wt-feat`);
|
||||||
dirs.push(wtPath);
|
dirs.push(wtPath);
|
||||||
await addWorktree(repo, { path: wtPath, branch: 'feat', newBranch: true });
|
await addWorktree(repo, { path: wtPath, branch: 'feat', mode: 'create' });
|
||||||
|
|
||||||
const list = await listWorktrees(repo);
|
const list = await listWorktrees(repo);
|
||||||
const wt = list.find((w) => resolve(w.path) === resolve(wtPath));
|
const wt = list.find((w) => resolve(w.path) === resolve(wtPath));
|
||||||
@@ -118,12 +123,74 @@ describe('opérations git (repo tmp réel)', () => {
|
|||||||
expect((await listWorktrees(repo)).some((w) => resolve(w.path) === resolve(wtPath))).toBe(false);
|
expect((await listWorktrees(repo)).some((w) => resolve(w.path) === resolve(wtPath))).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('switchBranch : create=true crée une branche, create=false bascule sur une existante', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
const cur = (): string => execFileSync('git', ['branch', '--show-current'], { cwd: repo }).toString().trim();
|
||||||
|
|
||||||
|
await switchBranch(repo, { branch: 'feature/new', create: true });
|
||||||
|
expect(cur()).toBe('feature/new');
|
||||||
|
|
||||||
|
await switchBranch(repo, { branch: 'main', create: false });
|
||||||
|
expect(cur()).toBe('main');
|
||||||
|
|
||||||
|
// créer une branche déjà existante échoue (git refuse).
|
||||||
|
await expect(switchBranch(repo, { branch: 'feature/new', create: true })).rejects.toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
it('prune retire un worktree dont le dossier a disparu', async () => {
|
it('prune retire un worktree dont le dossier a disparu', async () => {
|
||||||
const repo = makeTmpRepo();
|
const repo = makeTmpRepo();
|
||||||
const wtPath = join(dirname(repo), `${basename(repo)}-wt-gone`);
|
const wtPath = join(dirname(repo), `${basename(repo)}-wt-gone`);
|
||||||
await addWorktree(repo, { path: wtPath, branch: 'gone', newBranch: true });
|
await addWorktree(repo, { path: wtPath, branch: 'gone', mode: 'create' });
|
||||||
rmSync(wtPath, { recursive: true, force: true }); // suppression "à la main"
|
rmSync(wtPath, { recursive: true, force: true }); // suppression "à la main"
|
||||||
await pruneWorktrees(repo);
|
await pruneWorktrees(repo);
|
||||||
expect((await listWorktrees(repo)).some((w) => resolve(w.path) === resolve(wtPath))).toBe(false);
|
expect((await listWorktrees(repo)).some((w) => resolve(w.path) === resolve(wtPath))).toBe(false);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('branche : existence, liste, courante, commit', () => {
|
||||||
|
it('branchExists / currentBranch / listBranches', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
expect(await currentBranch(repo)).toBe('main');
|
||||||
|
expect(await branchExists(repo, 'main')).toEqual({ local: true, remote: false });
|
||||||
|
expect(await branchExists(repo, 'nope')).toEqual({ local: false, remote: false });
|
||||||
|
|
||||||
|
execFileSync('git', ['branch', 'dev'], { cwd: repo });
|
||||||
|
const b = await listBranches(repo);
|
||||||
|
expect(b.local).toContain('main');
|
||||||
|
expect(b.local).toContain('dev');
|
||||||
|
expect(b.remote).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('commitAll : add -A + commit, fait baisser dirtyCount à 0', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
writeFileSync(join(repo, 'new.txt'), 'hello\n');
|
||||||
|
expect((await worktreeStatus(repo)).dirtyCount).toBeGreaterThan(0);
|
||||||
|
await commitAll(repo, 'add new.txt');
|
||||||
|
expect((await worktreeStatus(repo)).dirtyCount).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('addWorktree : résolution auto (créer / réutiliser)', () => {
|
||||||
|
it('auto crée la branche si absente, la réutilise si présente', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
// branche absente → création (renvoie "created")
|
||||||
|
const wt1 = join(dirname(repo), `${basename(repo)}-wt-feat`);
|
||||||
|
dirs.push(wt1);
|
||||||
|
expect(await addWorktree(repo, { path: wt1, branch: 'feat', mode: 'auto' })).toBe('created');
|
||||||
|
expect((await listWorktrees(repo)).find((w) => resolve(w.path) === resolve(wt1))?.branch).toBe('feat');
|
||||||
|
|
||||||
|
// la même branche existe désormais ; un AUTRE worktree dessus → checkout (renvoie "reused")
|
||||||
|
await removeWorktree(repo, wt1, true); // libère la branche
|
||||||
|
const wt2 = join(dirname(repo), `${basename(repo)}-wt-feat2`);
|
||||||
|
dirs.push(wt2);
|
||||||
|
expect(await addWorktree(repo, { path: wt2, branch: 'feat', mode: 'auto' })).toBe('reused');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('mode create échoue si la branche existe déjà', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
execFileSync('git', ['branch', 'dup'], { cwd: repo });
|
||||||
|
const wt = join(dirname(repo), `${basename(repo)}-wt-dup`);
|
||||||
|
dirs.push(wt);
|
||||||
|
await expect(addWorktree(repo, { path: wt, branch: 'dup', mode: 'create' })).rejects.toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
45
packages/server/test/group-cwd.test.ts
Normal file
45
packages/server/test/group-cwd.test.ts
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { commonAncestorDir, resolveGroupCwd } from '../src/core/group-session.js';
|
||||||
|
|
||||||
|
describe('commonAncestorDir', () => {
|
||||||
|
it('renvoie le chemin lui-même pour un seul répertoire', () => {
|
||||||
|
expect(commonAncestorDir(['/home/johan/WebstormProjects/arboretum'])).toBe('/home/johan/WebstormProjects/arboretum');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renvoie le parent commun de deux siblings', () => {
|
||||||
|
expect(commonAncestorDir(['/p/a', '/p/b'])).toBe('/p');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('gère un répertoire ancêtre d’un autre', () => {
|
||||||
|
expect(commonAncestorDir(['/p/a', '/p/a/b'])).toBe('/p/a');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('compare par segments, pas par préfixe de chaîne', () => {
|
||||||
|
// /a/bc n'est PAS un ancêtre de /a/bcd : ancêtre commun = /a
|
||||||
|
expect(commonAncestorDir(['/a/bc', '/a/bcd'])).toBe('/a');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renvoie la racine quand aucun segment n’est commun', () => {
|
||||||
|
expect(commonAncestorDir(['/x/a', '/y/b'])).toBe('/');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('resolveGroupCwd', () => {
|
||||||
|
it('mono-repo : cwd = le repo, addDirs sera filtré à vide par PtyManager', () => {
|
||||||
|
const { cwd, addDirs } = resolveGroupCwd(['/p/a']);
|
||||||
|
expect(cwd).toBe('/p/a');
|
||||||
|
expect(addDirs).toEqual(['/p/a']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('multi-repos sous un parent commun : cwd = parent, addDirs = tous les repos', () => {
|
||||||
|
const dirs = ['/home/johan/WebstormProjects/beehelp_lambdas', '/home/johan/WebstormProjects/beehelp_api'];
|
||||||
|
const { cwd, addDirs } = resolveGroupCwd(dirs);
|
||||||
|
expect(cwd).toBe('/home/johan/WebstormProjects');
|
||||||
|
expect(addDirs).toEqual(dirs);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('garde-fou : repos sur des racines différentes → retombe sur le premier répertoire', () => {
|
||||||
|
const { cwd } = resolveGroupCwd(['/x/a', '/y/b']);
|
||||||
|
expect(cwd).toBe('/x/a');
|
||||||
|
});
|
||||||
|
});
|
||||||
111
packages/server/test/group-manager.test.ts
Normal file
111
packages/server/test/group-manager.test.ts
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
import { describe, expect, it, beforeEach, vi } from 'vitest';
|
||||||
|
import { GroupManager } from '../src/core/group-manager.js';
|
||||||
|
import { openDb, type Db } from '../src/db/index.js';
|
||||||
|
|
||||||
|
/** Insère un repo minimal directement (le GroupManager n'a besoin que de repos.id). */
|
||||||
|
function insertRepo(db: Db, id: string, path: string): void {
|
||||||
|
db.prepare(
|
||||||
|
"INSERT INTO repos (id, path, label, default_branch, post_create_hooks, pre_trust, created_at) VALUES (?, ?, ?, NULL, '[]', 0, ?)",
|
||||||
|
).run(id, path, id, new Date().toISOString());
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('GroupManager', () => {
|
||||||
|
let db: Db;
|
||||||
|
let gm: GroupManager;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
db = openDb(':memory:');
|
||||||
|
insertRepo(db, 'repo-a', '/tmp/a');
|
||||||
|
insertRepo(db, 'repo-b', '/tmp/b');
|
||||||
|
gm = new GroupManager(db);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('createGroup : groupe vide, persisté, événement group_update émis', () => {
|
||||||
|
const spy = vi.fn();
|
||||||
|
gm.on('group_update', spy);
|
||||||
|
const g = gm.createGroup({ label: 'Sprint 42' });
|
||||||
|
expect(g).toMatchObject({ label: 'Sprint 42', description: null, color: null, repoIds: [] });
|
||||||
|
expect(gm.listGroups()).toHaveLength(1);
|
||||||
|
expect(spy).toHaveBeenCalledWith(expect.objectContaining({ id: g.id }));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('createGroup : repoIds initiaux ordonnés et dédoublonnés', () => {
|
||||||
|
const g = gm.createGroup({ label: 'Eco', repoIds: ['repo-b', 'repo-a', 'repo-b'] });
|
||||||
|
expect(g.repoIds).toEqual(['repo-b', 'repo-a']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('createGroup : repoId inexistant → 404', () => {
|
||||||
|
expect(() => gm.createGroup({ label: 'X', repoIds: ['nope'] })).toThrow(
|
||||||
|
expect.objectContaining({ statusCode: 404, code: 'REPO_NOT_FOUND' }),
|
||||||
|
);
|
||||||
|
expect(gm.listGroups()).toHaveLength(0); // rollback de la transaction
|
||||||
|
});
|
||||||
|
|
||||||
|
it('createGroup : validations (label vide / trop long, couleur invalide)', () => {
|
||||||
|
expect(() => gm.createGroup({ label: ' ' })).toThrow(expect.objectContaining({ statusCode: 400 }));
|
||||||
|
expect(() => gm.createGroup({ label: 'x'.repeat(101) })).toThrow(expect.objectContaining({ statusCode: 400 }));
|
||||||
|
expect(() => gm.createGroup({ label: 'X', color: 'red' })).toThrow(expect.objectContaining({ statusCode: 400 }));
|
||||||
|
expect(gm.createGroup({ label: 'X', color: '#4f46e5' }).color).toBe('#4f46e5');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('getGroup : id inconnu → 404', () => {
|
||||||
|
expect(() => gm.getGroup('nope')).toThrow(expect.objectContaining({ statusCode: 404, code: 'NOT_FOUND' }));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('updateGroup : modifie label/description/color et bump updatedAt', () => {
|
||||||
|
const g = gm.createGroup({ label: 'A' });
|
||||||
|
const updated = gm.updateGroup(g.id, { label: 'B', description: 'hello', color: '#000000' });
|
||||||
|
expect(updated).toMatchObject({ label: 'B', description: 'hello', color: '#000000' });
|
||||||
|
expect(gm.updateGroup(g.id, { description: '' }).description).toBeNull(); // '' → null
|
||||||
|
});
|
||||||
|
|
||||||
|
it('addRepo : idempotent (PRIMARY KEY), émet group_update', () => {
|
||||||
|
const g = gm.createGroup({ label: 'A' });
|
||||||
|
const spy = vi.fn();
|
||||||
|
gm.on('group_update', spy);
|
||||||
|
expect(gm.addRepo(g.id, 'repo-a').repoIds).toEqual(['repo-a']);
|
||||||
|
expect(gm.addRepo(g.id, 'repo-a').repoIds).toEqual(['repo-a']); // pas de doublon
|
||||||
|
expect(gm.addRepo(g.id, 'repo-b').repoIds).toEqual(['repo-a', 'repo-b']);
|
||||||
|
expect(spy).toHaveBeenCalledTimes(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('addRepo : groupe ou repo inexistant → 404', () => {
|
||||||
|
const g = gm.createGroup({ label: 'A' });
|
||||||
|
expect(() => gm.addRepo('nope', 'repo-a')).toThrow(expect.objectContaining({ statusCode: 404, code: 'NOT_FOUND' }));
|
||||||
|
expect(() => gm.addRepo(g.id, 'nope')).toThrow(expect.objectContaining({ statusCode: 404, code: 'REPO_NOT_FOUND' }));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('removeRepo : idempotent (retrait d’un repo absent = no-op)', () => {
|
||||||
|
const g = gm.createGroup({ label: 'A', repoIds: ['repo-a'] });
|
||||||
|
expect(gm.removeRepo(g.id, 'repo-a').repoIds).toEqual([]);
|
||||||
|
expect(gm.removeRepo(g.id, 'repo-a').repoIds).toEqual([]); // déjà absent → succès
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deleteGroup : true + group_removed ; id inconnu → false', () => {
|
||||||
|
const g = gm.createGroup({ label: 'A' });
|
||||||
|
const spy = vi.fn();
|
||||||
|
gm.on('group_removed', spy);
|
||||||
|
expect(gm.deleteGroup(g.id)).toBe(true);
|
||||||
|
expect(spy).toHaveBeenCalledWith(g.id);
|
||||||
|
expect(gm.deleteGroup(g.id)).toBe(false);
|
||||||
|
expect(gm.listGroups()).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('CASCADE : supprimer un repo purge la membership (PRAGMA foreign_keys = ON)', () => {
|
||||||
|
const g = gm.createGroup({ label: 'A', repoIds: ['repo-a', 'repo-b'] });
|
||||||
|
expect(gm.getGroup(g.id).repoIds).toEqual(['repo-a', 'repo-b']);
|
||||||
|
db.prepare('DELETE FROM repos WHERE id = ?').run('repo-a');
|
||||||
|
expect(gm.getGroup(g.id).repoIds).toEqual(['repo-b']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deleteGroup : désorpheline le group_id des sessions de groupe (P6)', () => {
|
||||||
|
const g = gm.createGroup({ label: 'A' });
|
||||||
|
// session de groupe liée à g (insérée directement, comme le ferait PtyManager.spawn).
|
||||||
|
db.prepare(
|
||||||
|
'INSERT INTO sessions (id, cwd, command, created_at, group_id) VALUES (?, ?, ?, ?, ?)',
|
||||||
|
).run('sess-1', '/tmp/a', 'claude', new Date().toISOString(), g.id);
|
||||||
|
expect(gm.deleteGroup(g.id)).toBe(true);
|
||||||
|
const row = db.prepare('SELECT group_id FROM sessions WHERE id = ?').get('sess-1') as { group_id: string | null };
|
||||||
|
expect(row.group_id).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -187,6 +187,34 @@ describe('PtyManager (pty mocké)', () => {
|
|||||||
expect(listed).toMatchObject({ live: false, resumable: true, claudeSessionId: 'sid-known' });
|
expect(listed).toMatchObject({ live: false, resumable: true, claudeSessionId: 'sid-known' });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('resumeTargetById : session claude morte → cwd + claudeSessionId + groupe ; null sinon', () => {
|
||||||
|
const d1 = mkdtempSync(join(tmpdir(), 'arb-rt-'));
|
||||||
|
try {
|
||||||
|
const summary = manager.spawn({ cwd, command: 'claude', addDirs: [d1], groupId: 'grpR' });
|
||||||
|
db.prepare('UPDATE sessions SET claude_session_id = ? WHERE id = ?').run('cs-resume', summary.id);
|
||||||
|
// vivante → null (resume direct interdit ; fork passe par le même chemin)
|
||||||
|
expect(manager.resumeTargetById(summary.id)).toBeNull();
|
||||||
|
lastPty().emitExit(0);
|
||||||
|
// morte avec claudeSessionId connu → cible complète
|
||||||
|
expect(manager.resumeTargetById(summary.id)).toEqual({
|
||||||
|
cwd,
|
||||||
|
claudeSessionId: 'cs-resume',
|
||||||
|
addedDirs: [d1],
|
||||||
|
groupId: 'grpR',
|
||||||
|
});
|
||||||
|
// id inconnu → null
|
||||||
|
expect(manager.resumeTargetById('nope')).toBeNull();
|
||||||
|
} finally {
|
||||||
|
rmSync(d1, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resumeTargetById : session bash morte (sans claudeSessionId) → null', () => {
|
||||||
|
const { summary, pty } = spawnBash();
|
||||||
|
pty.emitExit(0);
|
||||||
|
expect(manager.resumeTargetById(summary.id)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
it('capture le claudeSessionId via le registre (poll par pid) → findLiveByClaudeSessionId', () => {
|
it('capture le claudeSessionId via le registre (poll par pid) → findLiveByClaudeSessionId', () => {
|
||||||
vi.useFakeTimers();
|
vi.useFakeTimers();
|
||||||
const sessDir = mkdtempSync(join(tmpdir(), 'arb-sess-'));
|
const sessDir = mkdtempSync(join(tmpdir(), 'arb-sess-'));
|
||||||
@@ -215,7 +243,11 @@ describe('PtyManager (pty mocké)', () => {
|
|||||||
|
|
||||||
it('resync à l’attach = queue du ring (REPLAY_TAIL_BYTES max)', () => {
|
it('resync à l’attach = queue du ring (REPLAY_TAIL_BYTES max)', () => {
|
||||||
const { summary, pty } = spawnBash();
|
const { summary, pty } = spawnBash();
|
||||||
const chunks = ['A', 'B', 'C'].map((c) => c.repeat(100 * 1024));
|
// on écrit volontairement PLUS que REPLAY_TAIL_BYTES (mais < RING_CAPACITY) pour vérifier
|
||||||
|
// le plafonnement de la queue rejouée. Tailles dérivées de la constante → robuste aux bumps.
|
||||||
|
const chunkSize = 256 * 1024;
|
||||||
|
const chunkCount = Math.ceil(REPLAY_TAIL_BYTES / chunkSize) + 2;
|
||||||
|
const chunks = Array.from({ length: chunkCount }, (_, i) => String.fromCharCode(65 + (i % 26)).repeat(chunkSize));
|
||||||
for (const c of chunks) pty.emitData(c);
|
for (const c of chunks) pty.emitData(c);
|
||||||
|
|
||||||
const b = makeBinding('interactive');
|
const b = makeBinding('interactive');
|
||||||
@@ -574,4 +606,53 @@ describe('PtyManager (pty mocké)', () => {
|
|||||||
expect(manager.attach(summary.id, makeBinding('interactive'), 80, 24)).toEqual({ ok: false, code: 'NOT_FOUND' });
|
expect(manager.attach(summary.id, makeBinding('interactive'), 80, 24)).toEqual({ ok: false, code: 'NOT_FOUND' });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('session de groupe multi-repo (P6)', () => {
|
||||||
|
it('spawn avec addDirs : --add-dir au pty, addedDirs + groupId résumés et persistés', () => {
|
||||||
|
const d1 = mkdtempSync(join(tmpdir(), 'arb-g1-'));
|
||||||
|
const d2 = mkdtempSync(join(tmpdir(), 'arb-g2-'));
|
||||||
|
try {
|
||||||
|
const summary = manager.spawn({ cwd, command: 'claude', addDirs: [d1, d2], groupId: 'grp1' });
|
||||||
|
expect(lastPty().args).toEqual(['--add-dir', d1, '--add-dir', d2]);
|
||||||
|
expect(summary.addedDirs).toEqual([d1, d2]);
|
||||||
|
expect(summary.groupId).toBe('grp1');
|
||||||
|
const row = db.prepare('SELECT added_dirs, group_id FROM sessions WHERE id = ?').get(summary.id) as {
|
||||||
|
added_dirs: string | null;
|
||||||
|
group_id: string | null;
|
||||||
|
};
|
||||||
|
expect(JSON.parse(row.added_dirs as string)).toEqual([d1, d2]);
|
||||||
|
expect(row.group_id).toBe('grp1');
|
||||||
|
} finally {
|
||||||
|
rmSync(d1, { recursive: true, force: true });
|
||||||
|
rmSync(d2, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('dédoublonne et écarte le cwd primaire des addDirs', () => {
|
||||||
|
const d1 = mkdtempSync(join(tmpdir(), 'arb-g4-'));
|
||||||
|
try {
|
||||||
|
const summary = manager.spawn({ cwd, command: 'claude', addDirs: [d1, d1, cwd] });
|
||||||
|
expect(summary.addedDirs).toEqual([d1]);
|
||||||
|
} finally {
|
||||||
|
rmSync(d1, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejette un addDir inexistant (400)', () => {
|
||||||
|
expect(() => manager.spawn({ cwd, command: 'bash', addDirs: ['/no/such/dir/xyz-arb'] })).toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('groupSessionContext renvoie les addedDirs/groupId persistés (resume)', () => {
|
||||||
|
const d1 = mkdtempSync(join(tmpdir(), 'arb-g5-'));
|
||||||
|
try {
|
||||||
|
const summary = manager.spawn({ cwd, command: 'claude', addDirs: [d1], groupId: 'grpX' });
|
||||||
|
// simule la capture du claudeSessionId (normalement résolue via le registre)
|
||||||
|
db.prepare('UPDATE sessions SET claude_session_id = ? WHERE id = ?').run('cs-1', summary.id);
|
||||||
|
expect(manager.groupSessionContext('cs-1')).toEqual({ addedDirs: [d1], groupId: 'grpX' });
|
||||||
|
expect(manager.groupSessionContext('unknown')).toBeNull();
|
||||||
|
} finally {
|
||||||
|
rmSync(d1, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
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;
|
||||||
@@ -59,7 +69,7 @@ describe('WorktreeManager', () => {
|
|||||||
claudeHome = mkdtempSync(join(tmpdir(), 'arb-ch-'));
|
claudeHome = mkdtempSync(join(tmpdir(), 'arb-ch-'));
|
||||||
dirs.push(claudeHome);
|
dirs.push(claudeHome);
|
||||||
pty = new PtyManager(db, join(claudeHome, 'sessions'));
|
pty = new PtyManager(db, join(claudeHome, 'sessions'));
|
||||||
discovery = new DiscoveryService({ ptyManager: pty, projectsDir: join(claudeHome, 'projects'), sessionsDir: join(claudeHome, 'sessions') });
|
discovery = new DiscoveryService({ db, ptyManager: pty, projectsDir: join(claudeHome, 'projects'), sessionsDir: join(claudeHome, 'sessions') });
|
||||||
wt = new WorktreeManager(db, pty, discovery);
|
wt = new WorktreeManager(db, pty, discovery);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -87,7 +97,8 @@ describe('WorktreeManager', () => {
|
|||||||
|
|
||||||
const wtPath = join(dirname(repo), `${basename(repo)}-wt-feat`);
|
const wtPath = join(dirname(repo), `${basename(repo)}-wt-feat`);
|
||||||
dirs.push(wtPath);
|
dirs.push(wtPath);
|
||||||
const out = await wt.createWorktree(r.id, { branch: 'feat', newBranch: true, runHooks: true });
|
const out = await wt.createWorktree(r.id, { branch: 'feat', mode: 'create', runHooks: true });
|
||||||
|
expect(out.action).toBe('created');
|
||||||
|
|
||||||
expect(resolve(out.worktree.path)).toBe(resolve(wtPath));
|
expect(resolve(out.worktree.path)).toBe(resolve(wtPath));
|
||||||
expect(out.worktree.branch).toBe('feat');
|
expect(out.worktree.branch).toBe('feat');
|
||||||
@@ -103,7 +114,47 @@ describe('WorktreeManager', () => {
|
|||||||
it('createWorktree : branche invalide → 400', async () => {
|
it('createWorktree : branche invalide → 400', async () => {
|
||||||
const repo = makeTmpRepo();
|
const repo = makeTmpRepo();
|
||||||
const r = await wt.addRepo({ path: repo });
|
const r = await wt.addRepo({ path: repo });
|
||||||
await expect(wt.createWorktree(r.id, { branch: '../evil', newBranch: true })).rejects.toMatchObject({ statusCode: 400 });
|
await expect(wt.createWorktree(r.id, { branch: '../evil', mode: 'create' })).rejects.toMatchObject({ statusCode: 400 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('startMainSession : session dans le checkout principal (branche actuelle, sans mutation git)', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
const r = await wt.addRepo({ path: repo });
|
||||||
|
const out = await wt.startMainSession(r.id, { command: 'bash' });
|
||||||
|
expect(resolve(out.session.cwd)).toBe(resolve(repo));
|
||||||
|
expect(out.session).toMatchObject({ command: 'bash', live: true });
|
||||||
|
// pas de bascule de branche → toujours sur main.
|
||||||
|
expect(execFileSync('git', ['branch', '--show-current'], { cwd: repo }).toString().trim()).toBe('main');
|
||||||
|
const main = (await wt.listRepoWorktrees(r.id, true)).find((w) => w.isMain);
|
||||||
|
expect(main?.sessions.some((s) => s.id === out.session.id)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('startMainSession : newBranch crée et bascule la branche dans le checkout principal + event', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
const r = await wt.addRepo({ path: repo });
|
||||||
|
const events: Array<{ worktree: WorktreeSummary }> = [];
|
||||||
|
wt.on('worktree_update', (e) => events.push(e));
|
||||||
|
const out = await wt.startMainSession(r.id, { command: 'bash', branch: 'feature/x', newBranch: true });
|
||||||
|
expect(execFileSync('git', ['branch', '--show-current'], { cwd: repo }).toString().trim()).toBe('feature/x');
|
||||||
|
expect(out.worktree?.branch).toBe('feature/x');
|
||||||
|
expect(events.some((e) => e.worktree.isMain && e.worktree.branch === 'feature/x')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('startMainSession : checkout principal sale → 409 DIRTY_TREE (pas de bascule)', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
const r = await wt.addRepo({ path: repo });
|
||||||
|
writeFileSync(join(repo, 'scratch.txt'), 'wip\n'); // arbre sale
|
||||||
|
await expect(wt.startMainSession(r.id, { command: 'bash', branch: 'feature/y', newBranch: true })).rejects.toMatchObject({
|
||||||
|
statusCode: 409,
|
||||||
|
code: 'DIRTY_TREE',
|
||||||
|
});
|
||||||
|
expect(execFileSync('git', ['branch', '--show-current'], { cwd: repo }).toString().trim()).toBe('main');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('startMainSession : branche invalide → 400', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
const r = await wt.addRepo({ path: repo });
|
||||||
|
await expect(wt.startMainSession(r.id, { command: 'bash', branch: '../evil', newBranch: true })).rejects.toMatchObject({ statusCode: 400 });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('deleteWorktree : main refusé (400), dirty refusé (409) puis force OK', async () => {
|
it('deleteWorktree : main refusé (400), dirty refusé (409) puis force OK', async () => {
|
||||||
@@ -113,7 +164,7 @@ describe('WorktreeManager', () => {
|
|||||||
|
|
||||||
const wtPath = join(dirname(repo), `${basename(repo)}-wt-x`);
|
const wtPath = join(dirname(repo), `${basename(repo)}-wt-x`);
|
||||||
dirs.push(wtPath);
|
dirs.push(wtPath);
|
||||||
await wt.createWorktree(r.id, { branch: 'x', newBranch: true, runHooks: false });
|
await wt.createWorktree(r.id, { branch: 'x', mode: 'create', runHooks: false });
|
||||||
writeFileSync(join(wtPath, 'scratch.txt'), 'wip\n'); // worktree sale
|
writeFileSync(join(wtPath, 'scratch.txt'), 'wip\n'); // worktree sale
|
||||||
|
|
||||||
await expect(wt.deleteWorktree(r.id, wtPath, false)).rejects.toMatchObject({ statusCode: 409, code: 'WORKTREE_DIRTY' });
|
await expect(wt.deleteWorktree(r.id, wtPath, false)).rejects.toMatchObject({ statusCode: 409, code: 'WORKTREE_DIRTY' });
|
||||||
@@ -126,7 +177,7 @@ describe('WorktreeManager', () => {
|
|||||||
const r = await wt.addRepo({ path: repo });
|
const r = await wt.addRepo({ path: repo });
|
||||||
const wtPath = join(dirname(repo), `${basename(repo)}-wt-sess`);
|
const wtPath = join(dirname(repo), `${basename(repo)}-wt-sess`);
|
||||||
dirs.push(wtPath);
|
dirs.push(wtPath);
|
||||||
await wt.createWorktree(r.id, { branch: 'sess', newBranch: true, runHooks: false });
|
await wt.createWorktree(r.id, { branch: 'sess', mode: 'create', runHooks: false });
|
||||||
|
|
||||||
pty.spawn({ cwd: wtPath, command: 'bash' });
|
pty.spawn({ cwd: wtPath, command: 'bash' });
|
||||||
const list = await wt.listRepoWorktrees(r.id, true);
|
const list = await wt.listRepoWorktrees(r.id, true);
|
||||||
@@ -140,8 +191,121 @@ describe('WorktreeManager', () => {
|
|||||||
const r = await wt.addRepo({ path: repo });
|
const r = await wt.addRepo({ path: repo });
|
||||||
const wtPath = join(dirname(repo), `${basename(repo)}-wt-busy`);
|
const wtPath = join(dirname(repo), `${basename(repo)}-wt-busy`);
|
||||||
dirs.push(wtPath);
|
dirs.push(wtPath);
|
||||||
await wt.createWorktree(r.id, { branch: 'busy', newBranch: true, runHooks: false });
|
await wt.createWorktree(r.id, { branch: 'busy', mode: 'create', runHooks: false });
|
||||||
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('listRepoBranches : renvoie les branches locales (dont main)', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
const r = await wt.addRepo({ path: repo });
|
||||||
|
const b = await wt.listRepoBranches(r.id);
|
||||||
|
expect(b.local).toContain('main');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('commitWorktree : arbre propre → 409 NOTHING_TO_COMMIT ; arbre sale → commit (dirty=0)', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
const r = await wt.addRepo({ path: repo });
|
||||||
|
await expect(wt.commitWorktree(r.id, repo, 'noop')).rejects.toMatchObject({ statusCode: 409, code: 'NOTHING_TO_COMMIT' });
|
||||||
|
writeFileSync(join(repo, 'f.txt'), 'x\n');
|
||||||
|
const w = await wt.commitWorktree(r.id, repo, 'add f');
|
||||||
|
expect(w.git.dirtyCount).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('promoteWorktree : la branche du worktree devient le checkout principal, worktree supprimé, ancienne branche conservée', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
const r = await wt.addRepo({ path: repo });
|
||||||
|
const wtPath = join(dirname(repo), `${basename(repo)}-wt-prom`);
|
||||||
|
dirs.push(wtPath);
|
||||||
|
await wt.createWorktree(r.id, { branch: 'prom', mode: 'create', runHooks: false });
|
||||||
|
|
||||||
|
await wt.promoteWorktree(r.id, wtPath);
|
||||||
|
|
||||||
|
expect(execFileSync('git', ['branch', '--show-current'], { cwd: repo }).toString().trim()).toBe('prom');
|
||||||
|
expect((await wt.listRepoWorktrees(r.id, true)).some((w) => resolve(w.path) === resolve(wtPath))).toBe(false);
|
||||||
|
const branches = await wt.listRepoBranches(r.id);
|
||||||
|
expect(branches.local).toContain('main'); // ancienne branche principale conservée
|
||||||
|
expect(branches.local).toContain('prom');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('promoteWorktree : checkout principal refusé (400 IS_MAIN_WORKTREE)', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
const r = await wt.addRepo({ path: repo });
|
||||||
|
await expect(wt.promoteWorktree(r.id, repo)).rejects.toMatchObject({ statusCode: 400, code: 'IS_MAIN_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([]);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// Types REST partagés (préfixe /api/v1).
|
// Types REST partagés (préfixe /api/v1).
|
||||||
import type { PostCreateHook, RepoSummary, SessionSummary, WorktreeSummary } from './protocol.js';
|
import type { GroupSummary, PostCreateHook, RepoSummary, SessionSummary, WorktreeSummary } from './protocol.js';
|
||||||
|
|
||||||
export interface ApiError {
|
export interface ApiError {
|
||||||
error: { code: string; message: string; details?: unknown };
|
error: { code: string; message: string; details?: unknown };
|
||||||
@@ -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 */
|
||||||
@@ -29,6 +53,11 @@ export interface SessionsListResponse {
|
|||||||
export interface SessionResponse {
|
export interface SessionResponse {
|
||||||
session: SessionSummary;
|
session: SessionSummary;
|
||||||
}
|
}
|
||||||
|
/** POST /sessions/hide-discovered — masque tout l'historique de sessions externes visible. */
|
||||||
|
export interface HideDiscoveredResponse {
|
||||||
|
/** nombre de sessions effectivement masquées. */
|
||||||
|
hidden: number;
|
||||||
|
}
|
||||||
|
|
||||||
// POST /sessions/:id/resume et /sessions/:id/fork (P2) : aucun corps — cwd et command
|
// POST /sessions/:id/resume et /sessions/:id/fork (P2) : aucun corps — cwd et command
|
||||||
// sont TOUJOURS dérivés du :id (lu sur disque), jamais fournis par le client (cf. spike S1).
|
// sont TOUJOURS dérivés du :id (lu sur disque), jamais fournis par le client (cf. spike S1).
|
||||||
@@ -52,6 +81,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 {
|
||||||
@@ -67,11 +109,25 @@ export interface HookRunResult {
|
|||||||
output: string;
|
output: string;
|
||||||
durationMs: number;
|
durationMs: number;
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* Stratégie de résolution de la branche d'un nouveau worktree :
|
||||||
|
* - `auto` (défaut) : détecte l'existence de la branche — checkout si elle existe en local, suivi de
|
||||||
|
* `origin/<branch>` si elle n'existe que sur le remote, sinon création (`-b`). Robuste pour les
|
||||||
|
* groupes hétérogènes où la branche peut déjà exister dans certains dépôts mais pas d'autres.
|
||||||
|
* - `create` : force la création (`-b`), échoue si la branche existe déjà.
|
||||||
|
* - `checkout` : force le checkout d'une branche existante, échoue si elle est absente.
|
||||||
|
*/
|
||||||
|
export type WorktreeBranchMode = 'auto' | 'create' | 'checkout';
|
||||||
|
/** Action réellement effectuée par la résolution `auto` (feedback UI). */
|
||||||
|
export type WorktreeBranchAction = 'created' | 'reused' | 'tracked';
|
||||||
|
|
||||||
export interface CreateWorktreeRequest {
|
export interface CreateWorktreeRequest {
|
||||||
branch: string;
|
branch: string;
|
||||||
/** true : créer la branche (`-b`) ; false : checkout d'une branche existante. */
|
/** stratégie de résolution de la branche (défaut : `auto`). Voir {@link WorktreeBranchMode}. */
|
||||||
newBranch: boolean;
|
mode?: WorktreeBranchMode;
|
||||||
/** point de départ de la nouvelle branche (défaut : HEAD courant du repo). */
|
/** @deprecated remplacé par `mode` ; mappé : true→create, false→checkout, absent→auto. */
|
||||||
|
newBranch?: boolean;
|
||||||
|
/** point de départ d'une branche créée (défaut : branche par défaut du dépôt, sinon HEAD). */
|
||||||
baseRef?: string;
|
baseRef?: string;
|
||||||
/** chemin cible du worktree (défaut : `<parent>/<repo>-wt-<branch>`). */
|
/** chemin cible du worktree (défaut : `<parent>/<repo>-wt-<branch>`). */
|
||||||
path?: string;
|
path?: string;
|
||||||
@@ -84,6 +140,35 @@ export interface CreateWorktreeResponse {
|
|||||||
worktree: WorktreeSummary;
|
worktree: WorktreeSummary;
|
||||||
hookResults: HookRunResult[];
|
hookResults: HookRunResult[];
|
||||||
session: SessionSummary | null;
|
session: SessionSummary | null;
|
||||||
|
/** action effective de la résolution de branche (créée / réutilisée / suivie du remote). */
|
||||||
|
action: WorktreeBranchAction;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** GET /api/v1/repos/:id/branches — branches locales/remote pour alimenter un sélecteur de base. */
|
||||||
|
export interface RepoBranchesResponse {
|
||||||
|
local: string[];
|
||||||
|
remote: string[];
|
||||||
|
/** branche par défaut du dépôt (origin/HEAD), ou null si indéterminée. */
|
||||||
|
default: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** POST /api/v1/repos/:id/worktrees/commit — `git add -A` puis commit dans le worktree visé. */
|
||||||
|
export interface CommitWorktreeRequest {
|
||||||
|
path: string;
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
/** POST /api/v1/repos/:id/worktrees/push — pousse la branche du worktree (upstream auto si absent). */
|
||||||
|
export interface PushWorktreeRequest {
|
||||||
|
path: string;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* POST /api/v1/repos/:id/worktrees/promote — « passer en principal » : la branche du worktree devient
|
||||||
|
* le checkout principal du dépôt (le worktree est supprimé, l'ancienne branche principale est conservée).
|
||||||
|
*/
|
||||||
|
export interface PromoteWorktreeRequest {
|
||||||
|
path: string;
|
||||||
|
/** outrepasse les garde-fous d'arbre sale (worktree/checkout principal). */
|
||||||
|
force?: boolean;
|
||||||
}
|
}
|
||||||
export interface AdoptWorktreeRequest {
|
export interface AdoptWorktreeRequest {
|
||||||
path: string;
|
path: string;
|
||||||
@@ -91,6 +176,60 @@ export interface AdoptWorktreeRequest {
|
|||||||
preTrust?: boolean;
|
preTrust?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /api/v1/repos/:id/session — lance UNE session dans le checkout principal du repo
|
||||||
|
* (`repo.path`) pour « bosser sur la branche principale » sans créer de worktree.
|
||||||
|
* Réponse : `SessionResponse`.
|
||||||
|
*/
|
||||||
|
export interface StartRepoSessionRequest {
|
||||||
|
/** binaire à lancer — défaut "claude" ; "bash" sert aux tests sans quota. */
|
||||||
|
command?: 'claude' | 'bash';
|
||||||
|
/** si fourni : crée/bascule cette branche dans le checkout principal avant la session. */
|
||||||
|
branch?: string;
|
||||||
|
/** true (défaut quand `branch` fourni) : `git switch -c` ; false : bascule sur une branche existante. */
|
||||||
|
newBranch?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Groupes de travail (P5) ----
|
||||||
|
export interface GroupsListResponse {
|
||||||
|
groups: GroupSummary[];
|
||||||
|
}
|
||||||
|
export interface GroupResponse {
|
||||||
|
group: GroupSummary;
|
||||||
|
}
|
||||||
|
export interface CreateGroupRequest {
|
||||||
|
label: string;
|
||||||
|
description?: string;
|
||||||
|
color?: string;
|
||||||
|
/** ids de repos initiaux (défaut : []). */
|
||||||
|
repoIds?: string[];
|
||||||
|
}
|
||||||
|
export interface UpdateGroupRequest {
|
||||||
|
label?: string;
|
||||||
|
/** null pour effacer. */
|
||||||
|
description?: string | null;
|
||||||
|
color?: string | null;
|
||||||
|
}
|
||||||
|
export interface AddRepoRequest {
|
||||||
|
repoId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Session de groupe multi-repo (P6) ----
|
||||||
|
/** Lance UNE session Claude couvrant tous les repos du groupe (via `--add-dir`). */
|
||||||
|
export interface CreateGroupSessionRequest {
|
||||||
|
/** défaut : claude. */
|
||||||
|
command?: 'claude' | 'bash';
|
||||||
|
/** présent → couvre le worktree de cette branche dans chaque repo ; absent → les checkouts principaux. */
|
||||||
|
branch?: string;
|
||||||
|
}
|
||||||
|
export interface GroupSessionResponse {
|
||||||
|
session: SessionSummary;
|
||||||
|
/** répertoires effectivement couverts par la session (cwd primaire en tête). */
|
||||||
|
dirs: string[];
|
||||||
|
/** repos du groupe pour lesquels aucun worktree n'a pu être résolu. */
|
||||||
|
skipped: Array<{ repoId: string; reason: string }>;
|
||||||
|
}
|
||||||
|
|
||||||
// ---- Navigateur de répertoires (sélecteur de dossier côté web) ----
|
// ---- Navigateur de répertoires (sélecteur de dossier côté web) ----
|
||||||
export interface FsEntry {
|
export interface FsEntry {
|
||||||
name: string;
|
name: string;
|
||||||
@@ -122,3 +261,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 };
|
||||||
|
}
|
||||||
|
|||||||
@@ -51,8 +51,12 @@ export const FLOW = {
|
|||||||
LAGGING_BYTES: 2 * 1024 * 1024,
|
LAGGING_BYTES: 2 * 1024 * 1024,
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
/** Replay à l'attach : reset terminal + queue du ring (l'écran TUI se repeint en continu) */
|
/**
|
||||||
export const REPLAY_TAIL_BYTES = 256 * 1024;
|
* Replay à l'attach : reset terminal + queue du ring (l'écran TUI se repeint en continu).
|
||||||
|
* 1 Mo (≈ 10–15k lignes) pour permettre de remonter une vraie conversation Claude dans le terminal ;
|
||||||
|
* reste < LAGGING_BYTES (pas de faux lagging) et bien dans RING_CAPACITY.
|
||||||
|
*/
|
||||||
|
export const REPLAY_TAIL_BYTES = 1024 * 1024;
|
||||||
|
|
||||||
// ---- États de session (sous-ensemble P1 ; étendu en P3) ----
|
// ---- États de session (sous-ensemble P1 ; étendu en P3) ----
|
||||||
export type SessionRuntimeStatus =
|
export type SessionRuntimeStatus =
|
||||||
@@ -113,6 +117,14 @@ export interface SessionSummary {
|
|||||||
waitingFor?: string | null;
|
waitingFor?: string | null;
|
||||||
/** dialogue typé en cours (présent quand activity === 'waiting'). */
|
/** dialogue typé en cours (présent quand activity === 'waiting'). */
|
||||||
dialog?: SessionDialog | null;
|
dialog?: SessionDialog | null;
|
||||||
|
// ---- P6 : session de groupe multi-repo (additif) ----
|
||||||
|
/** répertoires supplémentaires couverts via `--add-dir` ; absent/[] pour une session mono-repo. */
|
||||||
|
addedDirs?: string[];
|
||||||
|
/** groupe propriétaire d'une session de groupe (couvre plusieurs repos) ; null/absent sinon. */
|
||||||
|
groupId?: string | null;
|
||||||
|
// ---- Masquage (additif) ----
|
||||||
|
/** true = session découverte masquée par l'utilisateur (exclue de la liste sauf includeHidden). */
|
||||||
|
hidden?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- Worktrees & repos (P3) ----
|
// ---- Worktrees & repos (P3) ----
|
||||||
@@ -136,6 +148,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 {
|
||||||
@@ -160,6 +174,22 @@ export interface WorktreeSummary {
|
|||||||
sessions: SessionSummary[];
|
sessions: SessionSummary[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- Groupes de travail (P5) ----
|
||||||
|
// Un groupe regroupe plusieurs repos pour piloter des sessions Claude en simultané sur
|
||||||
|
// plusieurs worktrees. Membership légère : seule la liste d'ids de repos est persistée ;
|
||||||
|
// les repos/worktrees/sessions du groupe sont dérivés par filtrage sur `repoId` côté client.
|
||||||
|
export interface GroupSummary {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
description: string | null;
|
||||||
|
/** couleur d'accent UI (hex `#rrggbb`) ou null. */
|
||||||
|
color: string | null;
|
||||||
|
/** ids de repos membres, ordonnés par leur position dans le groupe. */
|
||||||
|
repoIds: string[];
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
// ---- Messages client → serveur ----
|
// ---- Messages client → serveur ----
|
||||||
export type ClientMessage =
|
export type ClientMessage =
|
||||||
| { type: 'hello'; protocol: number }
|
| { type: 'hello'; protocol: number }
|
||||||
@@ -172,7 +202,7 @@ export type ClientMessage =
|
|||||||
| { type: 'answer'; channel: number; action: 'select' | 'confirm' | 'deny'; optionN?: number }
|
| { type: 'answer'; channel: number; action: 'select' | 'confirm' | 'deny'; optionN?: number }
|
||||||
| { type: 'resize'; channel: number; cols: number; rows: number }
|
| { type: 'resize'; channel: number; cols: number; rows: number }
|
||||||
| { type: 'ack'; channel: number; bytes: number }
|
| { type: 'ack'; channel: number; bytes: number }
|
||||||
| { type: 'sub'; topics: Array<'sessions' | 'worktrees'> }
|
| { type: 'sub'; topics: Array<'sessions' | 'worktrees' | 'groups'> }
|
||||||
| { type: 'ping' };
|
| { type: 'ping' };
|
||||||
|
|
||||||
// ---- Messages serveur → client ----
|
// ---- Messages serveur → client ----
|
||||||
@@ -187,6 +217,8 @@ export type ServerMessage =
|
|||||||
| { type: 'repo_removed'; repoId: string }
|
| { type: 'repo_removed'; repoId: string }
|
||||||
| { type: 'worktree_update'; repoId: string; worktree: WorktreeSummary }
|
| { type: 'worktree_update'; repoId: string; worktree: WorktreeSummary }
|
||||||
| { type: 'worktree_removed'; repoId: string; path: string }
|
| { type: 'worktree_removed'; repoId: string; path: string }
|
||||||
|
| { type: 'group_update'; group: GroupSummary }
|
||||||
|
| { type: 'group_removed'; groupId: string }
|
||||||
| { type: 'error'; code: ErrorCode; message: string; channel?: number }
|
| { type: 'error'; code: ErrorCode; message: string; channel?: number }
|
||||||
| { type: 'pong' };
|
| { type: 'pong' };
|
||||||
|
|
||||||
@@ -244,8 +276,8 @@ export function parseClientMessage(raw: string): ClientMessage | null {
|
|||||||
? { type: 'ack', channel: m.channel, bytes: m.bytes }
|
? { type: 'ack', channel: m.channel, bytes: m.bytes }
|
||||||
: null;
|
: null;
|
||||||
case 'sub':
|
case 'sub':
|
||||||
return Array.isArray(m.topics) && m.topics.every((t) => t === 'sessions' || t === 'worktrees')
|
return Array.isArray(m.topics) && m.topics.every((t) => t === 'sessions' || t === 'worktrees' || t === 'groups')
|
||||||
? { type: 'sub', topics: m.topics as Array<'sessions' | 'worktrees'> }
|
? { type: 'sub', topics: m.topics as Array<'sessions' | 'worktrees' | 'groups'> }
|
||||||
: null;
|
: null;
|
||||||
case 'ping':
|
case 'ping':
|
||||||
return { type: 'ping' };
|
return { type: 'ping' };
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ function assertInvariants(msg: ClientMessage): void {
|
|||||||
expect(msg.bytes).toBeGreaterThanOrEqual(0);
|
expect(msg.bytes).toBeGreaterThanOrEqual(0);
|
||||||
break;
|
break;
|
||||||
case 'sub':
|
case 'sub':
|
||||||
expect(msg.topics.every((t) => t === 'sessions')).toBe(true);
|
expect(msg.topics.every((t) => t === 'sessions' || t === 'worktrees' || t === 'groups')).toBe(true);
|
||||||
break;
|
break;
|
||||||
case 'ping':
|
case 'ping':
|
||||||
break;
|
break;
|
||||||
@@ -117,9 +117,14 @@ describe('parseClientMessage — cas valides', () => {
|
|||||||
expect(parseClientMessage('{"type":"ack","channel":1,"bytes":0}')).toEqual({ type: 'ack', channel: 1, bytes: 0 });
|
expect(parseClientMessage('{"type":"ack","channel":1,"bytes":0}')).toEqual({ type: 'ack', channel: 1, bytes: 0 });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('sub avec topics sessions/worktrees (et tableau vide accepté)', () => {
|
it('sub avec topics sessions/worktrees/groups (et tableau vide accepté)', () => {
|
||||||
expect(parseClientMessage('{"type":"sub","topics":["sessions"]}')).toEqual({ type: 'sub', topics: ['sessions'] });
|
expect(parseClientMessage('{"type":"sub","topics":["sessions"]}')).toEqual({ type: 'sub', topics: ['sessions'] });
|
||||||
expect(parseClientMessage('{"type":"sub","topics":["sessions","worktrees"]}')).toEqual({ type: 'sub', topics: ['sessions', 'worktrees'] });
|
expect(parseClientMessage('{"type":"sub","topics":["sessions","worktrees"]}')).toEqual({ type: 'sub', topics: ['sessions', 'worktrees'] });
|
||||||
|
expect(parseClientMessage('{"type":"sub","topics":["groups"]}')).toEqual({ type: 'sub', topics: ['groups'] });
|
||||||
|
expect(parseClientMessage('{"type":"sub","topics":["sessions","worktrees","groups"]}')).toEqual({
|
||||||
|
type: 'sub',
|
||||||
|
topics: ['sessions', 'worktrees', 'groups'],
|
||||||
|
});
|
||||||
expect(parseClientMessage('{"type":"sub","topics":[]}')).toEqual({ type: 'sub', topics: [] });
|
expect(parseClientMessage('{"type":"sub","topics":[]}')).toEqual({ type: 'sub', topics: [] });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
53
packages/site/index.html
Normal file
53
packages/site/index.html
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en" style="background-color: #09090b">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<meta name="color-scheme" content="dark" />
|
||||||
|
<meta name="theme-color" content="#09090b" />
|
||||||
|
|
||||||
|
<title>Arboretum — Mission control for your AI coding agents</title>
|
||||||
|
<meta
|
||||||
|
name="description"
|
||||||
|
content="Arboretum is a local-first daemon you launch with npx that serves a web dashboard to run and supervise many Claude Code sessions across git worktrees — from any device, even your phone."
|
||||||
|
/>
|
||||||
|
<link rel="canonical" href="https://git-arboretum.com/" />
|
||||||
|
|
||||||
|
<!-- Open Graph / Twitter -->
|
||||||
|
<meta property="og:type" content="website" />
|
||||||
|
<meta property="og:url" content="https://git-arboretum.com/" />
|
||||||
|
<meta property="og:title" content="Arboretum — Mission control for your AI coding agents" />
|
||||||
|
<meta
|
||||||
|
property="og:description"
|
||||||
|
content="Run and supervise many Claude Code sessions across every git worktree — from any device, even your phone."
|
||||||
|
/>
|
||||||
|
<meta property="og:site_name" content="Arboretum" />
|
||||||
|
<meta property="og:image" content="https://git-arboretum.com/assets/og-cover.png" />
|
||||||
|
<meta property="og:image:width" content="1200" />
|
||||||
|
<meta property="og:image:height" content="630" />
|
||||||
|
<meta property="og:image:alt" content="Arboretum — mission control for your AI coding agents" />
|
||||||
|
<meta name="twitter:card" content="summary_large_image" />
|
||||||
|
<meta name="twitter:title" content="Arboretum — Mission control for your AI coding agents" />
|
||||||
|
<meta
|
||||||
|
name="twitter:description"
|
||||||
|
content="Run and supervise many Claude Code sessions across every git worktree — from any device, even your phone."
|
||||||
|
/>
|
||||||
|
<meta name="twitter:image" content="https://git-arboretum.com/assets/og-cover.png" />
|
||||||
|
|
||||||
|
<!-- Icons -->
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/icon.svg" />
|
||||||
|
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
|
||||||
|
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||||
|
<!-- Polices JetBrains Mono self-host via @fontsource (importées dans src/main.ts). -->
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app"></div>
|
||||||
|
<noscript>
|
||||||
|
<div style="padding: 24px; font-family: system-ui, sans-serif; color: #f4f4f5; text-align: center">
|
||||||
|
Arboretum — mission control for your AI coding agents.
|
||||||
|
<a href="https://git.lidge.fr/johanleroy/arboretum" style="color: #34d399">View on Gitea</a>.
|
||||||
|
</div>
|
||||||
|
</noscript>
|
||||||
|
<script type="module" src="/src/main.ts"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
24
packages/site/package.json
Normal file
24
packages/site/package.json
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"name": "@arboretum/site",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.1.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "vue-tsc --noEmit && vite build",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"vue": "^3.5.38",
|
||||||
|
"vue-i18n": "^11.4.5"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@fontsource/jetbrains-mono": "^5.1.0",
|
||||||
|
"@tailwindcss/vite": "^4.3.0",
|
||||||
|
"@vitejs/plugin-vue": "^6.0.7",
|
||||||
|
"tailwindcss": "^4.3.0",
|
||||||
|
"typescript": "^5.7.0",
|
||||||
|
"vite": "^8.0.16",
|
||||||
|
"vue-tsc": "^3.3.4"
|
||||||
|
}
|
||||||
|
}
|
||||||
16
packages/site/public/.htaccess
Normal file
16
packages/site/public/.htaccess
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
# git-arboretum.com — site vitrine statique (Vue 3 / Vite).
|
||||||
|
#
|
||||||
|
# Google PageSpeed (mod_pagespeed) renvoie un corps HTML VIDE sur ce domaine Plesk
|
||||||
|
# (la home répond 200 mais 0 octet → page blanche), alors que les assets statiques
|
||||||
|
# passent. Les bundles Vite sont déjà minifiés, hashés et gzippés : PageSpeed
|
||||||
|
# n'apporte rien ici et casse le rendu. On le désactive pour ce vhost.
|
||||||
|
#
|
||||||
|
# NB : si l'hébergement interdit ces directives en .htaccess (AllowOverride
|
||||||
|
# restrictif), Apache renverra une 500 → dans ce cas, supprimer ce fichier et
|
||||||
|
# désactiver PageSpeed depuis Plesk (Apache & nginx Settings).
|
||||||
|
<IfModule pagespeed_module>
|
||||||
|
ModPagespeed off
|
||||||
|
</IfModule>
|
||||||
|
<IfModule ngx_pagespeed_module>
|
||||||
|
pagespeed off;
|
||||||
|
</IfModule>
|
||||||
BIN
packages/site/public/apple-touch-icon.png
Normal file
BIN
packages/site/public/apple-touch-icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
BIN
packages/site/public/assets/arboretum-mark.png
Normal file
BIN
packages/site/public/assets/arboretum-mark.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 28 KiB |
BIN
packages/site/public/assets/og-cover.png
Normal file
BIN
packages/site/public/assets/og-cover.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 75 KiB |
BIN
packages/site/public/favicon.ico
Normal file
BIN
packages/site/public/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 5.5 KiB |
46
packages/site/public/icon.svg
Normal file
46
packages/site/public/icon.svg
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512" role="img" aria-label="Arboretum">
|
||||||
|
<defs>
|
||||||
|
<!-- glow néon : flou doux derrière les traits et les nœuds -->
|
||||||
|
<filter id="glow" x="-30%" y="-30%" width="160%" height="160%">
|
||||||
|
<feGaussianBlur stdDeviation="6" result="b"/>
|
||||||
|
<feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
|
||||||
|
</filter>
|
||||||
|
<linearGradient id="branch" x1="256" y1="430" x2="256" y2="90" gradientUnits="userSpaceOnUse">
|
||||||
|
<stop offset="0" stop-color="#10b981"/>
|
||||||
|
<stop offset="1" stop-color="#34d399"/>
|
||||||
|
</linearGradient>
|
||||||
|
</defs>
|
||||||
|
|
||||||
|
<rect width="512" height="512" fill="#09090b"/>
|
||||||
|
|
||||||
|
<!-- branches / circuit (tronc + fourches symétriques), tracées dans la zone sûre maskable -->
|
||||||
|
<g fill="none" stroke="url(#branch)" stroke-width="17" stroke-linecap="round" stroke-linejoin="round" filter="url(#glow)">
|
||||||
|
<!-- tronc : du nœud sommet jusqu'à la base avec le curseur >_ -->
|
||||||
|
<path d="M256 96 V392"/>
|
||||||
|
<!-- paire haute -->
|
||||||
|
<path d="M256 232 L150 232 V150"/>
|
||||||
|
<path d="M256 232 L362 232 V150"/>
|
||||||
|
<!-- paire médiane -->
|
||||||
|
<path d="M256 300 L104 300 V214"/>
|
||||||
|
<path d="M256 300 L408 300 V214"/>
|
||||||
|
<!-- paire basse -->
|
||||||
|
<path d="M256 356 L150 356 V300"/>
|
||||||
|
<path d="M256 356 L362 356 V300"/>
|
||||||
|
<!-- base : invite de commande >_ -->
|
||||||
|
<path d="M232 404 L246 418 L232 432" stroke-width="14"/>
|
||||||
|
<path d="M258 434 H286" stroke-width="14"/>
|
||||||
|
</g>
|
||||||
|
|
||||||
|
<!-- nœuds (sessions) : anneaux cyan lumineux, centre sombre -->
|
||||||
|
<g filter="url(#glow)">
|
||||||
|
<g fill="#09090b" stroke="#22d3ee" stroke-width="9">
|
||||||
|
<circle cx="256" cy="96" r="20"/>
|
||||||
|
<circle cx="150" cy="150" r="16"/>
|
||||||
|
<circle cx="362" cy="150" r="16"/>
|
||||||
|
<circle cx="104" cy="214" r="16"/>
|
||||||
|
<circle cx="408" cy="214" r="16"/>
|
||||||
|
<circle cx="150" cy="300" r="16"/>
|
||||||
|
<circle cx="362" cy="300" r="16"/>
|
||||||
|
</g>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 1.9 KiB |
4
packages/site/public/robots.txt
Normal file
4
packages/site/public/robots.txt
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
User-agent: *
|
||||||
|
Allow: /
|
||||||
|
|
||||||
|
Sitemap: https://git-arboretum.com/sitemap.xml
|
||||||
9
packages/site/public/sitemap.xml
Normal file
9
packages/site/public/sitemap.xml
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||||
|
<url>
|
||||||
|
<loc>https://git-arboretum.com/</loc>
|
||||||
|
<lastmod>2026-06-19</lastmod>
|
||||||
|
<changefreq>monthly</changefreq>
|
||||||
|
<priority>1.0</priority>
|
||||||
|
</url>
|
||||||
|
</urlset>
|
||||||
74
packages/site/src/App.vue
Normal file
74
packages/site/src/App.vue
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { watch } from 'vue';
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import AppHeader from './components/AppHeader.vue';
|
||||||
|
import HeroSection from './components/HeroSection.vue';
|
||||||
|
import ProblemSection from './components/ProblemSection.vue';
|
||||||
|
import FeaturesSection from './components/FeaturesSection.vue';
|
||||||
|
import ShowcaseSection from './components/ShowcaseSection.vue';
|
||||||
|
import WorkGroupsSection from './components/WorkGroupsSection.vue';
|
||||||
|
import HowItWorksSection from './components/HowItWorksSection.vue';
|
||||||
|
import SecuritySection from './components/SecuritySection.vue';
|
||||||
|
import FaqSection from './components/FaqSection.vue';
|
||||||
|
import FinalCta from './components/FinalCta.vue';
|
||||||
|
import AppFooter from './components/AppFooter.vue';
|
||||||
|
|
||||||
|
const { locale } = useI18n();
|
||||||
|
|
||||||
|
// Tient l'attribut <html lang> synchronisé avec la langue active.
|
||||||
|
watch(
|
||||||
|
locale,
|
||||||
|
(l) => {
|
||||||
|
document.documentElement.lang = l;
|
||||||
|
},
|
||||||
|
{ immediate: true },
|
||||||
|
);
|
||||||
|
|
||||||
|
// Grain de fond + halo emerald (décoratifs) — portés tels quels du design.
|
||||||
|
const grainStyle = {
|
||||||
|
position: 'fixed',
|
||||||
|
inset: '0',
|
||||||
|
zIndex: 0,
|
||||||
|
pointerEvents: 'none',
|
||||||
|
backgroundImage: 'radial-gradient(rgba(255,255,255,.025) 1px,transparent 1.4px)',
|
||||||
|
backgroundSize: '34px 34px',
|
||||||
|
WebkitMaskImage: 'radial-gradient(ellipse 120% 70% at 50% -4%,#000,transparent 70%)',
|
||||||
|
maskImage: 'radial-gradient(ellipse 120% 70% at 50% -4%,#000,transparent 70%)',
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const glowStyle = {
|
||||||
|
position: 'fixed',
|
||||||
|
top: '-26%',
|
||||||
|
left: '50%',
|
||||||
|
transform: 'translateX(-50%)',
|
||||||
|
width: '1100px',
|
||||||
|
height: '680px',
|
||||||
|
zIndex: 0,
|
||||||
|
pointerEvents: 'none',
|
||||||
|
background: 'radial-gradient(50% 50% at 50% 50%,rgba(16,185,129,.12),transparent 64%)',
|
||||||
|
filter: 'blur(18px)',
|
||||||
|
} as const;
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="relative overflow-x-hidden">
|
||||||
|
<div aria-hidden="true" :style="grainStyle"></div>
|
||||||
|
<div aria-hidden="true" :style="glowStyle"></div>
|
||||||
|
|
||||||
|
<AppHeader />
|
||||||
|
|
||||||
|
<main id="top" class="relative z-[1]">
|
||||||
|
<HeroSection />
|
||||||
|
<ProblemSection />
|
||||||
|
<FeaturesSection />
|
||||||
|
<ShowcaseSection />
|
||||||
|
<WorkGroupsSection />
|
||||||
|
<HowItWorksSection />
|
||||||
|
<SecuritySection />
|
||||||
|
<FaqSection />
|
||||||
|
<FinalCta />
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<AppFooter />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
50
packages/site/src/components/AppFooter.vue
Normal file
50
packages/site/src/components/AppFooter.vue
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { INSTALL_COMMAND } from '../composables/useCopy';
|
||||||
|
import { REPO, LICENSE, COFFEE } from '../lib/links';
|
||||||
|
import IconGitea from './icons/IconGitea.vue';
|
||||||
|
import CopyButton from './CopyButton.vue';
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<footer class="relative z-[1] border-t border-[#1c1c1f]">
|
||||||
|
<div class="mx-auto flex max-w-[1200px] flex-wrap items-center justify-between gap-5 px-6 py-[34px]">
|
||||||
|
<div class="flex items-center gap-[11px]">
|
||||||
|
<img
|
||||||
|
src="/assets/arboretum-mark.png"
|
||||||
|
alt=""
|
||||||
|
width="22"
|
||||||
|
height="22"
|
||||||
|
class="h-[22px] w-[22px] object-contain"
|
||||||
|
style="filter: grayscale(1) brightness(1.5); opacity: 0.4"
|
||||||
|
/>
|
||||||
|
<span class="font-mono text-sm text-zinc-300">git-arboretum.com</span>
|
||||||
|
<span class="ml-1 text-[13px] text-zinc-600">— {{ t('footTag') }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-[22px] text-sm">
|
||||||
|
<a :href="REPO" target="_blank" rel="noopener" class="inline-flex items-center gap-1.5 text-zinc-400 no-underline transition-colors hover:text-emerald-400">
|
||||||
|
<IconGitea :size="15" />
|
||||||
|
Gitea
|
||||||
|
</a>
|
||||||
|
<a :href="LICENSE" target="_blank" rel="noopener" class="text-zinc-400 no-underline transition-colors hover:text-emerald-400">
|
||||||
|
{{ t('license') }}
|
||||||
|
</a>
|
||||||
|
<a
|
||||||
|
:href="COFFEE"
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener"
|
||||||
|
class="inline-flex items-center gap-1.5 text-zinc-400 no-underline transition-colors hover:text-amber-400 focus-visible:rounded-md focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-amber-400/70"
|
||||||
|
>
|
||||||
|
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 2v2" /><path d="M14 2v2" /><path d="M5 8h13a1 1 0 0 1 1 1v2a4 4 0 0 1-4 4H8a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1Z" /><path d="M6 15a4 4 0 0 0 4 4h2a4 4 0 0 0 4-4" /><path d="M19 9h1.5a2.5 2.5 0 0 1 0 5H18" /></svg>
|
||||||
|
{{ t('coffee') }}
|
||||||
|
</a>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<code class="font-mono text-[12.5px] text-zinc-600">{{ INSTALL_COMMAND }}</code>
|
||||||
|
<CopyButton variant="icon" :text="INSTALL_COMMAND" :label="t('copyCommand')" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</footer>
|
||||||
|
</template>
|
||||||
59
packages/site/src/components/AppHeader.vue
Normal file
59
packages/site/src/components/AppHeader.vue
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { REPO } from '../lib/links';
|
||||||
|
import LangToggle from './LangToggle.vue';
|
||||||
|
import IconGitea from './icons/IconGitea.vue';
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
|
||||||
|
const navLinks = [
|
||||||
|
{ href: '#features', key: 'navFeatures' },
|
||||||
|
{ href: '#how', key: 'navHow' },
|
||||||
|
{ href: '#security', key: 'navSecurity' },
|
||||||
|
{ href: '#faq', key: 'navFaq' },
|
||||||
|
] as const;
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<header
|
||||||
|
class="sticky top-0 z-50 border-b border-[#1c1c1f] bg-[rgba(9,9,11,0.72)] backdrop-blur-[14px]"
|
||||||
|
>
|
||||||
|
<div class="mx-auto flex h-16 max-w-[1200px] items-center justify-between gap-6 px-6">
|
||||||
|
<a href="#top" class="flex items-center gap-2.5 text-zinc-100 no-underline">
|
||||||
|
<img
|
||||||
|
src="/assets/arboretum-mark.png"
|
||||||
|
alt="Arboretum"
|
||||||
|
width="28"
|
||||||
|
height="28"
|
||||||
|
class="block h-7 w-7 object-contain"
|
||||||
|
/>
|
||||||
|
<span class="font-mono text-[17px] font-semibold tracking-[-0.01em]">Arboretum</span>
|
||||||
|
</a>
|
||||||
|
|
||||||
|
<nav class="hidden items-center gap-[30px] min-[900px]:flex">
|
||||||
|
<a
|
||||||
|
v-for="link in navLinks"
|
||||||
|
:key="link.href"
|
||||||
|
:href="link.href"
|
||||||
|
class="text-[14.5px] text-zinc-400 no-underline transition-colors hover:text-zinc-100"
|
||||||
|
>
|
||||||
|
{{ t(link.key) }}
|
||||||
|
</a>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<div class="flex items-center gap-3.5">
|
||||||
|
<LangToggle />
|
||||||
|
<a
|
||||||
|
:href="REPO"
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener"
|
||||||
|
aria-label="Gitea"
|
||||||
|
class="inline-flex items-center gap-[7px] rounded-lg border border-zinc-800 px-[13px] py-[7px] text-[13.5px] font-medium text-zinc-300 no-underline transition-colors hover:border-emerald-500/50 hover:text-emerald-400 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-500/70"
|
||||||
|
>
|
||||||
|
<IconGitea :size="16" />
|
||||||
|
Gitea
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
</template>
|
||||||
57
packages/site/src/components/CopyButton.vue
Normal file
57
packages/site/src/components/CopyButton.vue
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { useCopy } from '../composables/useCopy';
|
||||||
|
import IconCopy from './icons/IconCopy.vue';
|
||||||
|
import IconCheck from './icons/IconCheck.vue';
|
||||||
|
|
||||||
|
// Bouton « copier » réutilisable, avec retour visuel (icône ✓ + label) pendant 1800 ms.
|
||||||
|
// Deux variantes :
|
||||||
|
// - 'bar' : bouton étiqueté intégré aux barres de commande (hero, CTA final).
|
||||||
|
// - 'icon' : bouton compact icône seule, pour les blocs de code (étapes, footer).
|
||||||
|
withDefaults(
|
||||||
|
defineProps<{
|
||||||
|
text: string;
|
||||||
|
variant?: 'bar' | 'icon';
|
||||||
|
label?: string; // aria-label décrivant ce qui est copié
|
||||||
|
barClass?: string; // padding/ajustements de la variante 'bar'
|
||||||
|
}>(),
|
||||||
|
{ variant: 'bar', label: '', barClass: 'px-[15px]' },
|
||||||
|
);
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
const { copied, copy } = useCopy();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<button
|
||||||
|
v-if="variant === 'bar'"
|
||||||
|
type="button"
|
||||||
|
:aria-label="label || t('copy')"
|
||||||
|
:class="[
|
||||||
|
'inline-flex flex-none items-center gap-[7px] border-l border-zinc-800 bg-zinc-900 font-mono text-[13px] font-semibold transition-colors hover:bg-zinc-800 hover:text-emerald-400 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-emerald-500/70',
|
||||||
|
barClass,
|
||||||
|
copied ? 'text-emerald-400' : 'text-zinc-300',
|
||||||
|
]"
|
||||||
|
@click="copy(text)"
|
||||||
|
>
|
||||||
|
<component :is="copied ? IconCheck : IconCopy" :size="15" />
|
||||||
|
<span aria-live="polite">{{ copied ? t('copied') : t('copy') }}</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
v-else
|
||||||
|
type="button"
|
||||||
|
:aria-label="label || t('copy')"
|
||||||
|
:title="copied ? t('copied') : label || t('copy')"
|
||||||
|
:class="[
|
||||||
|
'inline-flex flex-none items-center justify-center rounded-md border p-1.5 transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-500/70',
|
||||||
|
copied
|
||||||
|
? 'border-emerald-500/40 bg-zinc-800 text-emerald-400'
|
||||||
|
: 'border-zinc-800 bg-zinc-900/80 text-zinc-400 hover:border-emerald-500/40 hover:bg-zinc-800 hover:text-emerald-400',
|
||||||
|
]"
|
||||||
|
@click="copy(text)"
|
||||||
|
>
|
||||||
|
<component :is="copied ? IconCheck : IconCopy" :size="14" />
|
||||||
|
<span aria-live="polite" class="sr-only">{{ copied ? t('copied') : t('copy') }}</span>
|
||||||
|
</button>
|
||||||
|
</template>
|
||||||
52
packages/site/src/components/FaqSection.vue
Normal file
52
packages/site/src/components/FaqSection.vue
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue';
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { FAQS } from '../i18n/content';
|
||||||
|
import type { AppLocale } from '../i18n';
|
||||||
|
|
||||||
|
const { t, locale } = useI18n();
|
||||||
|
const open = ref(0);
|
||||||
|
const items = computed(() => FAQS[locale.value as AppLocale]);
|
||||||
|
|
||||||
|
function toggle(i: number): void {
|
||||||
|
open.value = open.value === i ? -1 : i;
|
||||||
|
}
|
||||||
|
|
||||||
|
function panelStyle(i: number) {
|
||||||
|
return {
|
||||||
|
maxHeight: open.value === i ? '300px' : '0px',
|
||||||
|
opacity: open.value === i ? 1 : 0,
|
||||||
|
overflow: 'hidden',
|
||||||
|
transition: 'max-height .4s ease, opacity .35s ease',
|
||||||
|
} as const;
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section id="faq" class="mx-auto max-w-[780px] scroll-mt-[84px] px-6 pb-[100px]">
|
||||||
|
<div v-reveal class="mb-[38px] text-center">
|
||||||
|
<div class="mb-3.5 font-mono text-xs uppercase tracking-[0.14em] text-emerald-400">{{ t('navFaq') }}</div>
|
||||||
|
<h2 class="m-0 text-[clamp(28px,3.4vw,40px)] font-semibold tracking-[-0.025em] text-zinc-50">{{ t('faqTitle') }}</h2>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-reveal>
|
||||||
|
<div v-for="(f, i) in items" :key="i" class="border-t" :class="open === i ? 'border-emerald-400/40' : 'border-zinc-800'">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
:aria-expanded="open === i"
|
||||||
|
:aria-controls="`faq-panel-${i}`"
|
||||||
|
class="flex w-full cursor-pointer items-center justify-between gap-4 border-none bg-transparent px-1 py-5 text-left text-[clamp(16px,2vw,18px)] font-medium text-zinc-50 focus-visible:rounded-md focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-500/70"
|
||||||
|
@click="toggle(i)"
|
||||||
|
>
|
||||||
|
<span>{{ f.q }}</span>
|
||||||
|
<span class="flex flex-none text-emerald-400 transition-transform duration-300" :class="open === i ? 'rotate-180' : ''">
|
||||||
|
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#34d399" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6" /></svg>
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
<div :id="`faq-panel-${i}`" :style="panelStyle(i)" :inert="open !== i" :aria-hidden="open !== i">
|
||||||
|
<p class="m-0 max-w-[640px] px-1 pb-5 text-[15.5px] leading-[1.6] text-zinc-400">{{ f.a }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
17
packages/site/src/components/FeatureCard.vue
Normal file
17
packages/site/src/components/FeatureCard.vue
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
defineProps<{ title: string }>();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div
|
||||||
|
class="rounded-xl border border-zinc-800 bg-zinc-900/50 p-6 transition-[transform,border-color] duration-[180ms] ease-in-out hover:-translate-y-[3px] hover:border-emerald-400/40"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
class="mb-4 inline-flex h-[42px] w-[42px] items-center justify-center rounded-[10px] bg-emerald-500/10 text-emerald-400"
|
||||||
|
>
|
||||||
|
<slot name="icon" />
|
||||||
|
</div>
|
||||||
|
<h3 class="m-0 mb-[7px] text-lg font-semibold text-zinc-50">{{ title }}</h3>
|
||||||
|
<p class="m-0 text-[14.5px] leading-[1.55] text-zinc-400"><slot /></p>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
83
packages/site/src/components/FeaturesSection.vue
Normal file
83
packages/site/src/components/FeaturesSection.vue
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import FeatureCard from './FeatureCard.vue';
|
||||||
|
const { t } = useI18n();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section id="features" class="mx-auto max-w-[1200px] scroll-mt-[84px] px-6 pb-[100px]">
|
||||||
|
<div v-reveal class="mb-[46px] text-center">
|
||||||
|
<div class="mb-3.5 font-mono text-xs uppercase tracking-[0.14em] text-emerald-400">{{ t('featKicker') }}</div>
|
||||||
|
<h2 class="m-0 text-[clamp(28px,3.4vw,40px)] font-semibold tracking-[-0.025em] text-zinc-50">
|
||||||
|
{{ t('featTitle') }}
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-reveal class="grid grid-cols-[repeat(auto-fit,minmax(264px,1fr))] gap-4">
|
||||||
|
<FeatureCard :title="t('feat1Title')">
|
||||||
|
<template #icon>
|
||||||
|
<svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="6" y1="3" x2="6" y2="15" /><circle cx="18" cy="6" r="3" /><circle cx="6" cy="18" r="3" /><path d="M18 9a9 9 0 0 1-9 9" /></svg>
|
||||||
|
</template>
|
||||||
|
{{ t('feat1Desc') }}
|
||||||
|
</FeatureCard>
|
||||||
|
|
||||||
|
<FeatureCard :title="t('feat2Title')">
|
||||||
|
<template #icon>
|
||||||
|
<svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect width="7" height="7" x="3" y="3" rx="1" /><rect width="7" height="7" x="14" y="3" rx="1" /><rect width="7" height="7" x="14" y="14" rx="1" /><rect width="7" height="7" x="3" y="14" rx="1" /></svg>
|
||||||
|
</template>
|
||||||
|
{{ t('feat2Desc') }}
|
||||||
|
</FeatureCard>
|
||||||
|
|
||||||
|
<FeatureCard :title="t('feat3Title')">
|
||||||
|
<template #icon>
|
||||||
|
<svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M22 12h-4l-3 9L9 3l-3 9H2" /></svg>
|
||||||
|
</template>
|
||||||
|
<span class="text-sky-300">{{ t('busy') }}</span> ·
|
||||||
|
<span class="text-amber-300">{{ t('waiting') }}</span> ·
|
||||||
|
<span class="text-emerald-400">{{ t('idle') }}</span> — {{ t('feat3Desc') }}
|
||||||
|
</FeatureCard>
|
||||||
|
|
||||||
|
<FeatureCard :title="t('feat4Title')">
|
||||||
|
<template #icon>
|
||||||
|
<svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect width="14" height="20" x="5" y="2" rx="2.5" /><path d="M12 18h.01" /></svg>
|
||||||
|
</template>
|
||||||
|
{{ t('feat4Desc') }}
|
||||||
|
</FeatureCard>
|
||||||
|
|
||||||
|
<FeatureCard :title="t('feat5Title')">
|
||||||
|
<template #icon>
|
||||||
|
<svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10.27 21a1.94 1.94 0 0 0 3.46 0" /><path d="M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326" /></svg>
|
||||||
|
</template>
|
||||||
|
{{ t('feat5Desc') }}
|
||||||
|
</FeatureCard>
|
||||||
|
|
||||||
|
<FeatureCard :title="t('feat6Title')">
|
||||||
|
<template #icon>
|
||||||
|
<svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" /></svg>
|
||||||
|
</template>
|
||||||
|
{{ t('feat6Desc') }}
|
||||||
|
</FeatureCard>
|
||||||
|
|
||||||
|
<FeatureCard :title="t('feat7Title')">
|
||||||
|
<template #icon>
|
||||||
|
<svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z" /><path d="m7 16.5-4.74-2.85" /><path d="m7 16.5 5-3" /><path d="M7 16.5v5.17" /><path d="M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z" /><path d="m17 16.5 4.74-2.85" /><path d="M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z" /></svg>
|
||||||
|
</template>
|
||||||
|
{{ t('feat7Desc') }}
|
||||||
|
</FeatureCard>
|
||||||
|
|
||||||
|
<FeatureCard :title="t('feat8Title')">
|
||||||
|
<template #icon>
|
||||||
|
<svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z" /></svg>
|
||||||
|
</template>
|
||||||
|
{{ t('feat8Desc') }}
|
||||||
|
</FeatureCard>
|
||||||
|
|
||||||
|
<FeatureCard :title="t('feat9Title')">
|
||||||
|
<template #icon>
|
||||||
|
<svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="16 18 22 12 16 6" /><polyline points="8 6 2 12 8 18" /></svg>
|
||||||
|
</template>
|
||||||
|
{{ t('feat9Desc') }}
|
||||||
|
</FeatureCard>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
52
packages/site/src/components/FinalCta.vue
Normal file
52
packages/site/src/components/FinalCta.vue
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { INSTALL_COMMAND } from '../composables/useCopy';
|
||||||
|
import { REPO } from '../lib/links';
|
||||||
|
import IconGitea from './icons/IconGitea.vue';
|
||||||
|
import CopyButton from './CopyButton.vue';
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section class="mx-auto max-w-[1200px] px-6 pb-[100px]">
|
||||||
|
<div
|
||||||
|
v-reveal
|
||||||
|
class="rounded-[20px] border border-zinc-800 px-6 py-[clamp(36px,5vw,64px)] text-center"
|
||||||
|
style="background: radial-gradient(120% 140% at 50% 0%, rgba(16, 185, 129, 0.1), transparent 60%), #0c0c0e"
|
||||||
|
>
|
||||||
|
<img
|
||||||
|
src="/assets/arboretum-mark.png"
|
||||||
|
alt=""
|
||||||
|
width="52"
|
||||||
|
height="52"
|
||||||
|
class="mx-auto mb-5 block h-[52px] w-[52px] object-contain"
|
||||||
|
/>
|
||||||
|
<h2 class="m-0 mb-3.5 text-[clamp(30px,4vw,46px)] font-bold leading-[1.08] tracking-[-0.03em] text-zinc-50">
|
||||||
|
{{ t('ctaTitle') }}
|
||||||
|
</h2>
|
||||||
|
<p class="mx-auto mb-7 max-w-[480px] text-[17px] text-zinc-400">{{ t('ctaBody') }}</p>
|
||||||
|
|
||||||
|
<div
|
||||||
|
class="mx-auto flex max-w-[460px] items-stretch overflow-hidden rounded-[10px] border border-zinc-800 bg-zinc-950"
|
||||||
|
>
|
||||||
|
<div class="flex min-w-0 flex-1 items-center gap-2.5 overflow-x-auto whitespace-nowrap px-4 font-mono text-sm">
|
||||||
|
<span class="text-emerald-400">$</span><span class="text-zinc-200">{{ INSTALL_COMMAND }}</span>
|
||||||
|
</div>
|
||||||
|
<CopyButton variant="bar" :text="INSTALL_COMMAND" :label="t('copyCommand')" bar-class="px-4" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-[18px]">
|
||||||
|
<a
|
||||||
|
:href="REPO"
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener"
|
||||||
|
class="inline-flex items-center gap-2 text-[14.5px] text-zinc-400 no-underline transition-colors hover:text-emerald-400"
|
||||||
|
>
|
||||||
|
<IconGitea :size="16" />
|
||||||
|
{{ t('ctaSource') }}
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
218
packages/site/src/components/HeroMockup.vue
Normal file
218
packages/site/src/components/HeroMockup.vue
Normal file
@@ -0,0 +1,218 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from 'vue';
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { useHeroTimeline, type SessionState } from '../composables/useHeroTimeline';
|
||||||
|
import { DLG_OPTS } from '../i18n/content';
|
||||||
|
import type { AppLocale } from '../i18n';
|
||||||
|
import IconGitea from './icons/IconGitea.vue';
|
||||||
|
|
||||||
|
const { t, locale } = useI18n();
|
||||||
|
const { anim } = useHeroTimeline('hero-stage');
|
||||||
|
|
||||||
|
// Couleurs des lignes de terminal par type (porté de renderVals.C).
|
||||||
|
const LINE_COLORS: Record<string, string> = {
|
||||||
|
cmd: '#52525b',
|
||||||
|
tool: '#a1a1aa',
|
||||||
|
edit: '#34d399',
|
||||||
|
add: '#34d399',
|
||||||
|
del: '#f87171',
|
||||||
|
ok: '#34d399',
|
||||||
|
warn: '#fcd34d',
|
||||||
|
run: '#7dd3fc',
|
||||||
|
};
|
||||||
|
|
||||||
|
// Couleurs alignées sur SessionStateBadge de l'app (zinc/emerald/amber/sky de Tailwind).
|
||||||
|
const PILL: Record<SessionState, { bg: string; fg: string; dot: string; pulse: string }> = {
|
||||||
|
idle: { bg: '#022c22', fg: '#34d399', dot: '#34d399', pulse: '' },
|
||||||
|
busy: { bg: '#082f49', fg: '#7dd3fc', dot: '#7dd3fc', pulse: 'pulseSky 2s ease-in-out infinite' },
|
||||||
|
waiting: { bg: '#451a03', fg: '#fcd34d', dot: '#fcd34d', pulse: 'pulseAmber 2.2s ease-in-out infinite' },
|
||||||
|
};
|
||||||
|
|
||||||
|
const pill = computed(() => PILL[anim.value.sess]);
|
||||||
|
const sessText = computed(() => t(anim.value.sess));
|
||||||
|
|
||||||
|
const termLines = computed(() =>
|
||||||
|
anim.value.lines.map((l) => ({ text: l.text, color: LINE_COLORS[l.k] ?? '#d4d4d8' })),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Options du dialogue de permission — reproduit DialogPrompt (boutons numérotés + Deny).
|
||||||
|
const dlgOptions = computed(() =>
|
||||||
|
DLG_OPTS[locale.value as AppLocale].map((txt, i) => ({
|
||||||
|
num: anim.value.ans === i ? '✓' : String(i + 1),
|
||||||
|
text: txt,
|
||||||
|
highlighted: anim.value.hl === i,
|
||||||
|
answered: anim.value.ans === i,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div id="hero-stage" class="relative min-w-[300px] flex-[1_1_480px]">
|
||||||
|
<div
|
||||||
|
class="relative overflow-hidden rounded-[14px] border border-zinc-800 bg-zinc-950 shadow-hero"
|
||||||
|
>
|
||||||
|
<!-- barre de fenêtre -->
|
||||||
|
<div class="flex items-center gap-2 border-b border-[#1c1c1f] bg-[#0c0c0e] px-[14px] py-[11px]">
|
||||||
|
<span class="h-2.5 w-2.5 rounded-full bg-zinc-700"></span>
|
||||||
|
<span class="h-2.5 w-2.5 rounded-full bg-zinc-700"></span>
|
||||||
|
<span class="h-2.5 w-2.5 rounded-full bg-zinc-700"></span>
|
||||||
|
<span class="ml-2 font-mono text-[11.5px] text-zinc-600">arboretum · localhost:7317</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex min-h-[440px]">
|
||||||
|
<!-- sidebar (fidèle à AppSidebar : Worktrees / Sessions / Groups, puis Réglages / Aide / Gitea / Café) -->
|
||||||
|
<div
|
||||||
|
class="flex w-[190px] flex-none flex-col border-r border-[#1c1c1f] bg-zinc-900/40 px-2 py-3"
|
||||||
|
>
|
||||||
|
<div class="flex items-center gap-2 px-2 pb-3">
|
||||||
|
<img
|
||||||
|
src="/assets/arboretum-mark.png"
|
||||||
|
alt=""
|
||||||
|
width="22"
|
||||||
|
height="22"
|
||||||
|
class="h-[22px] w-[22px] object-contain"
|
||||||
|
/>
|
||||||
|
<span class="text-[14px] font-semibold text-zinc-100">Arboretum</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
class="mb-2 flex items-center gap-2 rounded-lg border border-zinc-800 bg-zinc-950/40 px-2.5 py-1.5"
|
||||||
|
>
|
||||||
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#52525b" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="8" /><path d="m21 21-4.3-4.3" /></svg>
|
||||||
|
<span class="flex-1 text-[12px] text-zinc-500">{{ t('mSearch') }}</span>
|
||||||
|
<span class="rounded border border-zinc-700 px-[5px] py-px font-mono text-[10px] text-zinc-500">⌘K</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- nav primaire -->
|
||||||
|
<div class="flex flex-col gap-1">
|
||||||
|
<div class="flex items-center gap-2.5 rounded-lg bg-zinc-800 px-2.5 py-1.5 text-zinc-100">
|
||||||
|
<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="6" x2="6" y1="3" y2="15" /><circle cx="18" cy="6" r="3" /><circle cx="6" cy="18" r="3" /><path d="M18 9a9 9 0 0 1-9 9" /></svg>
|
||||||
|
<span class="flex-1 text-[12.5px] font-medium">{{ t('mWorktrees') }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-zinc-400">
|
||||||
|
<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m7 11 2-2-2-2" /><path d="M11 13h4" /><rect width="18" height="18" x="3" y="3" rx="2" ry="2" /></svg>
|
||||||
|
<span class="flex-1 text-[12.5px] font-medium">{{ t('mSessions') }}</span>
|
||||||
|
<span
|
||||||
|
v-show="anim.att > 0"
|
||||||
|
class="rounded-full bg-amber-500/20 px-1.5 text-[11px] font-semibold text-amber-300"
|
||||||
|
>{{ anim.att }}</span
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-zinc-400">
|
||||||
|
<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z" /><path d="M7 16.5 12 13.5" /><path d="M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z" /><path d="m17 16.5 4.74-2.85" /><path d="M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0z" /></svg>
|
||||||
|
<span class="flex-1 text-[12.5px] font-medium">{{ t('mGroups') }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex-1"></div>
|
||||||
|
|
||||||
|
<!-- nav secondaire -->
|
||||||
|
<div class="flex flex-col gap-1">
|
||||||
|
<div class="flex items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-zinc-400">
|
||||||
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z" /><circle cx="12" cy="12" r="3" /></svg>
|
||||||
|
<span class="flex-1 text-[12.5px] font-medium">{{ t('mSettings') }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-zinc-400">
|
||||||
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10" /><path d="m4.93 4.93 4.24 4.24" /><path d="m14.83 9.17 4.24-4.24" /><path d="m14.83 14.83 4.24 4.24" /><path d="m9.17 14.83-4.24 4.24" /><circle cx="12" cy="12" r="4" /></svg>
|
||||||
|
<span class="flex-1 text-[12.5px] font-medium">{{ t('mHelp') }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-zinc-400">
|
||||||
|
<IconGitea :size="16" />
|
||||||
|
<span class="flex-1 text-[12.5px] font-medium">{{ t('mGitea') }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-zinc-400">
|
||||||
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 2v2" /><path d="M14 2v2" /><path d="M16 8a1 1 0 0 1 1 1v8a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1h14a4 4 0 1 1 0 8h-1" /><path d="M6 2v2" /></svg>
|
||||||
|
<span class="flex-1 text-[12.5px] font-medium">{{ t('coffee') }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- pied : langue · notifications · déconnexion + version (fidèle à AppShellFooter) -->
|
||||||
|
<div class="mt-2 flex items-center gap-2 border-t border-[#1c1c1f] px-1 pt-2.5">
|
||||||
|
<span class="rounded border border-zinc-700 px-1.5 py-px font-mono text-[10px] text-zinc-400">{{ locale.toUpperCase() }}</span>
|
||||||
|
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#34d399" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10.268 21a2 2 0 0 0 3.464 0" /><path d="M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326" /></svg>
|
||||||
|
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#71717a" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" /><polyline points="16 17 21 12 16 7" /><line x1="21" x2="9" y1="12" y2="12" /></svg>
|
||||||
|
<span class="ml-auto font-mono text-[10px] text-zinc-600">v1.6.0</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- main -->
|
||||||
|
<div class="flex min-w-0 flex-1 flex-col gap-[11px] p-[13px]">
|
||||||
|
<!-- terminal pane -->
|
||||||
|
<div
|
||||||
|
class="flex min-h-0 flex-1 flex-col overflow-hidden rounded-[10px] border border-zinc-800 bg-zinc-950"
|
||||||
|
>
|
||||||
|
<div class="flex items-center justify-between border-b border-[#1c1c1f] px-[11px] py-2">
|
||||||
|
<span class="font-mono text-[11.5px] text-zinc-300">api · feat/auth</span>
|
||||||
|
<span
|
||||||
|
class="inline-flex items-center gap-1.5 rounded px-2 py-[3px] font-mono text-[11px]"
|
||||||
|
:style="{ background: pill.bg, color: pill.fg }"
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
class="h-1.5 w-1.5 flex-none rounded-full"
|
||||||
|
:style="{ background: pill.dot, animation: pill.pulse }"
|
||||||
|
></span>
|
||||||
|
{{ sessText }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
class="flex min-h-[150px] flex-1 flex-col justify-end overflow-hidden p-[11px] font-mono text-xs leading-[1.7] text-zinc-300"
|
||||||
|
>
|
||||||
|
<div v-for="(ln, i) in termLines" :key="i" :style="{ color: ln.color, whiteSpace: 'pre' }">
|
||||||
|
{{ ln.text }}
|
||||||
|
</div>
|
||||||
|
<div v-if="anim.cur">
|
||||||
|
<span class="text-emerald-400">$</span>
|
||||||
|
<span class="ml-1 inline-block h-[13px] w-[7px] animate-blink align-middle bg-zinc-200"></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- dialogue de permission (fidèle à DialogPrompt : badge type + question + options + Deny) -->
|
||||||
|
<div
|
||||||
|
v-if="anim.dlg"
|
||||||
|
class="animate-dlg-in rounded-lg border border-amber-900/60 bg-amber-950/30 p-[11px]"
|
||||||
|
>
|
||||||
|
<div class="mb-2 flex items-center gap-2">
|
||||||
|
<span class="inline-flex items-center rounded bg-amber-900 px-1.5 py-0.5 text-[11px] font-medium text-amber-200">{{ t('mPermission') }}</span>
|
||||||
|
<span class="text-[12.5px] text-amber-100">{{ t('dlgQ') }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-wrap gap-[6px]">
|
||||||
|
<span
|
||||||
|
v-for="(op, i) in dlgOptions"
|
||||||
|
:key="i"
|
||||||
|
class="inline-flex items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs font-medium transition-colors"
|
||||||
|
:class="op.answered
|
||||||
|
? 'border-emerald-500/70 bg-emerald-950/50 text-emerald-300'
|
||||||
|
: op.highlighted
|
||||||
|
? 'border-amber-400 bg-amber-950/50 text-amber-200'
|
||||||
|
: 'border-zinc-700 bg-zinc-800 text-zinc-200'"
|
||||||
|
>
|
||||||
|
<span class="font-mono" :class="op.answered ? 'text-emerald-400' : 'text-amber-400'">{{ op.num }}</span>
|
||||||
|
{{ op.text }}
|
||||||
|
</span>
|
||||||
|
<span class="inline-flex items-center rounded-lg border border-red-900 bg-red-950 px-2.5 py-1.5 text-xs font-medium text-red-300">{{ t('mDeny') }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- toast push -->
|
||||||
|
<div
|
||||||
|
v-if="anim.toast"
|
||||||
|
class="animate-toast-in absolute bottom-[14px] right-[14px] flex w-[248px] items-start gap-2.5 rounded-[11px] border border-[rgba(120,53,15,0.5)] bg-[#0c0c0e] p-3 shadow-toast"
|
||||||
|
>
|
||||||
|
<span class="inline-flex h-[30px] w-[30px] flex-none items-center justify-center rounded-lg bg-emerald-500/15">
|
||||||
|
<img src="/assets/arboretum-mark.png" alt="" width="18" height="18" class="h-[18px] w-[18px] object-contain" />
|
||||||
|
</span>
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<span class="font-mono text-[11px] text-emerald-400">Arboretum</span>
|
||||||
|
<span class="text-[10px] text-zinc-600">now</span>
|
||||||
|
</div>
|
||||||
|
<div class="mt-[3px] text-[13px] font-semibold text-zinc-100">{{ t('toastTitle') }}</div>
|
||||||
|
<div class="mt-px text-[11.5px] leading-[1.4] text-zinc-400">{{ t('toastBody') }}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
71
packages/site/src/components/HeroSection.vue
Normal file
71
packages/site/src/components/HeroSection.vue
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { INSTALL_COMMAND } from '../composables/useCopy';
|
||||||
|
import { REPO } from '../lib/links';
|
||||||
|
import HeroMockup from './HeroMockup.vue';
|
||||||
|
import IconGitea from './icons/IconGitea.vue';
|
||||||
|
import CopyButton from './CopyButton.vue';
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section class="mx-auto flex max-w-[1200px] flex-wrap items-center gap-12 px-6 pb-16 pt-[72px]">
|
||||||
|
<div class="min-w-[300px] flex-[1_1_430px]">
|
||||||
|
<div class="mb-[22px] flex items-center gap-[13px]">
|
||||||
|
<img
|
||||||
|
src="/assets/arboretum-mark.png"
|
||||||
|
alt=""
|
||||||
|
width="46"
|
||||||
|
height="46"
|
||||||
|
class="block h-[46px] w-[46px] object-contain"
|
||||||
|
/>
|
||||||
|
<span
|
||||||
|
class="inline-flex items-center gap-2 rounded-full border border-emerald-500/30 bg-emerald-500/[0.07] px-[11px] py-[5px] font-mono text-[11.5px] uppercase tracking-[0.1em] text-emerald-400"
|
||||||
|
>
|
||||||
|
<span class="h-1.5 w-1.5 rounded-full bg-emerald-400 shadow-[0_0_8px_#34d399]"></span>
|
||||||
|
{{ t('heroBadge') }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h1 class="m-0 text-[clamp(40px,5.6vw,64px)] font-bold leading-[1.04] tracking-[-0.035em] text-zinc-50">
|
||||||
|
{{ t('heroTitle') }}
|
||||||
|
</h1>
|
||||||
|
<p class="mt-[22px] max-w-[520px] text-[clamp(17px,1.7vw,20px)] leading-[1.55] text-zinc-400">
|
||||||
|
{{ t('heroSub') }}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div
|
||||||
|
class="mt-[30px] flex max-w-[480px] items-stretch overflow-hidden rounded-[10px] border border-zinc-800 bg-zinc-950/60"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
class="flex min-w-0 flex-1 items-center gap-2.5 overflow-x-auto whitespace-nowrap px-[15px] font-mono text-sm"
|
||||||
|
>
|
||||||
|
<span class="text-emerald-400">$</span><span class="text-zinc-200">{{ INSTALL_COMMAND }}</span>
|
||||||
|
</div>
|
||||||
|
<CopyButton variant="bar" :text="INSTALL_COMMAND" :label="t('copyCommand')" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-6 flex flex-wrap gap-[13px]">
|
||||||
|
<a
|
||||||
|
href="#how"
|
||||||
|
class="inline-flex items-center gap-[9px] rounded-[9px] bg-emerald-600 px-6 py-[13px] text-[15.5px] font-semibold text-white no-underline transition-[background,transform] duration-150 ease-in-out hover:-translate-y-px hover:bg-emerald-500 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-500/70"
|
||||||
|
>
|
||||||
|
{{ t('getStarted') }}
|
||||||
|
<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14" /><path d="m12 5 7 7-7 7" /></svg>
|
||||||
|
</a>
|
||||||
|
<a
|
||||||
|
:href="REPO"
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener"
|
||||||
|
class="inline-flex items-center gap-[9px] rounded-[9px] border border-zinc-800 px-[22px] py-[13px] text-[15.5px] font-medium text-zinc-100 no-underline transition-colors hover:border-emerald-500/45 hover:text-emerald-400 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-500/70"
|
||||||
|
>
|
||||||
|
<IconGitea :size="17" />
|
||||||
|
{{ t('gitea') }}
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<HeroMockup />
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
53
packages/site/src/components/HowItWorksSection.vue
Normal file
53
packages/site/src/components/HowItWorksSection.vue
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { INSTALL_COMMAND } from '../composables/useCopy';
|
||||||
|
import CopyButton from './CopyButton.vue';
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
// Port par défaut réel du daemon (cf. packages/server/src/config.ts).
|
||||||
|
const LOCAL_URL = 'http://localhost:7317';
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section id="how" class="mx-auto max-w-[1200px] scroll-mt-[84px] px-6 pb-[100px]">
|
||||||
|
<div v-reveal class="mb-[46px] text-center">
|
||||||
|
<div class="mb-3.5 font-mono text-xs uppercase tracking-[0.14em] text-emerald-400">{{ t('howKicker') }}</div>
|
||||||
|
<h2 class="m-0 text-[clamp(28px,3.4vw,40px)] font-semibold tracking-[-0.025em] text-zinc-50">{{ t('howTitle') }}</h2>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-reveal class="grid grid-cols-[repeat(auto-fit,minmax(280px,1fr))] gap-4">
|
||||||
|
<div class="rounded-xl border border-zinc-800 bg-zinc-900/50 p-[26px]">
|
||||||
|
<div class="mb-[18px] font-mono text-[13px] text-emerald-400">01</div>
|
||||||
|
<h3 class="m-0 mb-2.5 text-lg font-semibold text-zinc-50">{{ t('step1Title') }}</h3>
|
||||||
|
<p class="m-0 mb-4 text-[14.5px] leading-[1.55] text-zinc-400">{{ t('step1Desc') }}</p>
|
||||||
|
<div class="flex items-center gap-2 rounded-lg border border-zinc-800 bg-zinc-950 p-[11px]">
|
||||||
|
<code class="min-w-0 flex-1 overflow-x-auto whitespace-nowrap font-mono text-[12.5px] text-zinc-200">
|
||||||
|
<span class="text-emerald-400">$ </span>{{ INSTALL_COMMAND }}
|
||||||
|
</code>
|
||||||
|
<CopyButton variant="icon" :text="INSTALL_COMMAND" :label="t('copyCommand')" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="rounded-xl border border-zinc-800 bg-zinc-900/50 p-[26px]">
|
||||||
|
<div class="mb-[18px] font-mono text-[13px] text-emerald-400">02</div>
|
||||||
|
<h3 class="m-0 mb-2.5 text-lg font-semibold text-zinc-50">{{ t('step2Title') }}</h3>
|
||||||
|
<p class="m-0 mb-4 text-[14.5px] leading-[1.55] text-zinc-400">{{ t('step2Desc') }}</p>
|
||||||
|
<div class="flex items-center gap-2 rounded-lg border border-zinc-800 bg-zinc-950 p-[11px]">
|
||||||
|
<code class="min-w-0 flex-1 overflow-x-auto whitespace-nowrap font-mono text-[12.5px] text-sky-300">
|
||||||
|
→ {{ LOCAL_URL }}
|
||||||
|
</code>
|
||||||
|
<CopyButton variant="icon" :text="LOCAL_URL" :label="t('copyUrl')" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="rounded-xl border border-zinc-800 bg-zinc-900/50 p-[26px]">
|
||||||
|
<div class="mb-[18px] font-mono text-[13px] text-emerald-400">03</div>
|
||||||
|
<h3 class="m-0 mb-2.5 text-lg font-semibold text-zinc-50">{{ t('step3Title') }}</h3>
|
||||||
|
<p class="m-0 mb-4 text-[14.5px] leading-[1.55] text-zinc-400">{{ t('step3Desc') }}</p>
|
||||||
|
<div class="flex flex-wrap gap-1.5">
|
||||||
|
<span class="rounded-md bg-emerald-500/10 px-[9px] py-1 font-mono text-[11px] text-emerald-400">{{ t('idle') }}</span>
|
||||||
|
<span class="rounded-md bg-[rgba(8,47,73,0.7)] px-[9px] py-1 font-mono text-[11px] text-sky-300">{{ t('busy') }}</span>
|
||||||
|
<span class="rounded-md bg-[rgba(69,26,3,0.6)] px-[9px] py-1 font-mono text-[11px] text-amber-300">{{ t('waiting') }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
37
packages/site/src/components/LangToggle.vue
Normal file
37
packages/site/src/components/LangToggle.vue
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { setLocale, type AppLocale } from '../i18n';
|
||||||
|
|
||||||
|
const { locale } = useI18n();
|
||||||
|
|
||||||
|
function set(l: AppLocale): void {
|
||||||
|
setLocale(l);
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div
|
||||||
|
role="group"
|
||||||
|
aria-label="Language"
|
||||||
|
class="flex items-center overflow-hidden rounded-lg border border-zinc-800 bg-zinc-950/40"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
:aria-pressed="locale === 'en'"
|
||||||
|
class="cursor-pointer border-none px-[11px] py-1.5 font-mono text-xs font-semibold focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-emerald-500/70"
|
||||||
|
:class="locale === 'en' ? 'bg-zinc-800 text-emerald-400' : 'bg-transparent text-zinc-500'"
|
||||||
|
@click="set('en')"
|
||||||
|
>
|
||||||
|
EN
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
:aria-pressed="locale === 'fr'"
|
||||||
|
class="cursor-pointer border-none px-[11px] py-1.5 font-mono text-xs font-semibold focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-emerald-500/70"
|
||||||
|
:class="locale === 'fr' ? 'bg-zinc-800 text-emerald-400' : 'bg-transparent text-zinc-500'"
|
||||||
|
@click="set('fr')"
|
||||||
|
>
|
||||||
|
FR
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
14
packages/site/src/components/ProblemSection.vue
Normal file
14
packages/site/src/components/ProblemSection.vue
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
const { t } = useI18n();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section v-reveal class="mx-auto max-w-[920px] px-6 pb-[92px] pt-12 text-center">
|
||||||
|
<div class="mb-4 font-mono text-xs uppercase tracking-[0.14em] text-emerald-400">{{ t('probKicker') }}</div>
|
||||||
|
<h2 class="m-0 text-[clamp(28px,3.6vw,42px)] font-semibold leading-[1.18] tracking-[-0.025em] text-zinc-50">
|
||||||
|
{{ t('probTitle') }}
|
||||||
|
</h2>
|
||||||
|
<p class="mx-auto mt-[22px] max-w-[640px] text-[clamp(17px,1.6vw,19px)] text-zinc-400">{{ t('probBody') }}</p>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
47
packages/site/src/components/SecuritySection.vue
Normal file
47
packages/site/src/components/SecuritySection.vue
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
const { t } = useI18n();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section id="security" class="mx-auto max-w-[1200px] scroll-mt-[84px] px-6 pb-[100px]">
|
||||||
|
<div
|
||||||
|
v-reveal
|
||||||
|
class="rounded-[18px] border border-emerald-500/[0.18] p-[clamp(28px,4vw,48px)]"
|
||||||
|
style="background: linear-gradient(180deg, rgba(16, 185, 129, 0.05), rgba(16, 185, 129, 0))"
|
||||||
|
>
|
||||||
|
<div class="mb-[30px] flex flex-wrap items-end justify-between gap-3.5">
|
||||||
|
<div>
|
||||||
|
<div class="mb-3 font-mono text-xs uppercase tracking-[0.14em] text-emerald-400">{{ t('secKicker') }}</div>
|
||||||
|
<h2 class="m-0 text-[clamp(26px,3.2vw,38px)] font-semibold leading-[1.12] tracking-[-0.025em] text-zinc-50">
|
||||||
|
{{ t('secTitle') }}
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
<p class="m-0 max-w-[380px] text-[15.5px] leading-[1.55] text-zinc-400">{{ t('secIntro') }}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid grid-cols-[repeat(auto-fit,minmax(200px,1fr))] gap-3.5">
|
||||||
|
<div class="flex flex-col gap-2.5 rounded-[11px] border border-zinc-800 bg-[#0c0c0e] p-[18px]">
|
||||||
|
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#34d399" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect width="18" height="11" x="3" y="11" rx="2" /><path d="M7 11V7a5 5 0 0 1 10 0v4" /></svg>
|
||||||
|
<div class="text-[15px] font-semibold text-zinc-50">{{ t('sec1Title') }}</div>
|
||||||
|
<div class="text-[13.5px] leading-[1.5] text-zinc-400">{{ t('sec1Desc') }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-col gap-2.5 rounded-[11px] border border-zinc-800 bg-[#0c0c0e] p-[18px]">
|
||||||
|
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#34d399" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4" /><path d="m21 2-9.6 9.6" /><circle cx="7.5" cy="15.5" r="5.5" /></svg>
|
||||||
|
<div class="text-[15px] font-semibold text-zinc-50">{{ t('sec2Title') }}</div>
|
||||||
|
<div class="text-[13.5px] leading-[1.5] text-zinc-400">{{ t('sec2Desc') }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-col gap-2.5 rounded-[11px] border border-zinc-800 bg-[#0c0c0e] p-[18px]">
|
||||||
|
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#34d399" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z" /><path d="m9 12 2 2 4-4" /></svg>
|
||||||
|
<div class="text-[15px] font-semibold text-zinc-50">{{ t('sec3Title') }}</div>
|
||||||
|
<div class="text-[13.5px] leading-[1.5] text-zinc-400">{{ t('sec3Desc') }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-col gap-2.5 rounded-[11px] border border-zinc-800 bg-[#0c0c0e] p-[18px]">
|
||||||
|
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#34d399" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12.55a11 11 0 0 1 14.08 0" /><path d="M1.42 9a16 16 0 0 1 21.16 0" /><path d="M8.53 16.11a6 6 0 0 1 6.95 0" /><path d="M12 20h.01" /></svg>
|
||||||
|
<div class="text-[15px] font-semibold text-zinc-50">{{ t('sec4Title') }}</div>
|
||||||
|
<div class="text-[13.5px] leading-[1.5] text-zinc-400">{{ t('sec4Desc') }}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
257
packages/site/src/components/ShowcaseSection.vue
Normal file
257
packages/site/src/components/ShowcaseSection.vue
Normal file
@@ -0,0 +1,257 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from 'vue';
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { DLG_OPTS } from '../i18n/content';
|
||||||
|
import type { AppLocale } from '../i18n';
|
||||||
|
|
||||||
|
const { t, locale } = useI18n();
|
||||||
|
|
||||||
|
// Options du dialogue (réutilisées pour le rail « À traiter » et la vue mobile).
|
||||||
|
const dlgOpts = computed(() => DLG_OPTS[locale.value as AppLocale]);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section id="showcase" class="mx-auto flex max-w-[1200px] scroll-mt-[84px] flex-col gap-[92px] px-6">
|
||||||
|
<!-- a) dashboard worktree-first : rail « À traiter » + section de repo (fidèle à AttentionSection + RepoSection) -->
|
||||||
|
<div v-reveal class="flex flex-wrap items-center gap-12">
|
||||||
|
<div class="min-w-[280px] flex-[1_1_360px]">
|
||||||
|
<div class="mb-3 font-mono text-xs uppercase tracking-[0.12em] text-emerald-400">{{ t('scAKicker') }}</div>
|
||||||
|
<h2 class="m-0 mb-4 text-[clamp(26px,3vw,34px)] font-semibold leading-[1.15] tracking-[-0.025em] text-zinc-50">
|
||||||
|
{{ t('scATitle') }}
|
||||||
|
</h2>
|
||||||
|
<p class="m-0 text-[16.5px] leading-[1.6] text-zinc-400">{{ t('scABody') }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="flex min-w-[280px] flex-[1_1_440px] flex-col gap-3">
|
||||||
|
<!-- rail « À traiter » -->
|
||||||
|
<div class="flex flex-col gap-2 rounded-xl border border-amber-900/50 bg-amber-950/20 p-3 shadow-card">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#fbbf24" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z" /><path d="M12 9v4" /><path d="M12 17h.01" /></svg>
|
||||||
|
<h3 class="text-sm font-semibold text-amber-200">{{ t('mAttn') }}</h3>
|
||||||
|
<span class="rounded-full bg-amber-500/20 px-1.5 text-[11px] font-semibold text-amber-300">1</span>
|
||||||
|
</div>
|
||||||
|
<span class="truncate font-mono text-xs text-amber-300/80">~/code/arboretum/api</span>
|
||||||
|
<!-- DialogPrompt -->
|
||||||
|
<div class="rounded-lg border border-amber-900/60 bg-amber-950/30 p-2.5">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<span class="inline-flex items-center rounded bg-amber-900 px-1.5 py-0.5 text-[11px] font-medium text-amber-200">{{ t('mPermission') }}</span>
|
||||||
|
<span class="text-[12.5px] text-amber-100">{{ t('dlgQ') }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="mt-2 flex flex-wrap gap-1.5">
|
||||||
|
<span
|
||||||
|
v-for="(op, i) in dlgOpts"
|
||||||
|
:key="i"
|
||||||
|
class="inline-flex items-center gap-1.5 rounded-lg border border-zinc-700 bg-zinc-800 px-2.5 py-1.5 text-xs font-medium text-zinc-200"
|
||||||
|
>
|
||||||
|
<span class="font-mono text-amber-400">{{ i + 1 }}</span> {{ op }}
|
||||||
|
</span>
|
||||||
|
<span class="inline-flex items-center rounded-lg border border-red-900 bg-red-950 px-2.5 py-1.5 text-xs font-medium text-red-300">{{ t('mDeny') }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- section de repo : worktrees + état de session -->
|
||||||
|
<div class="flex flex-col gap-2 rounded-xl border border-zinc-800 bg-zinc-900/50 p-3 shadow-card">
|
||||||
|
<header class="flex flex-wrap items-center gap-2">
|
||||||
|
<h3 class="font-semibold text-zinc-100">arboretum</h3>
|
||||||
|
<span class="truncate font-mono text-xs text-zinc-500">~/code/arboretum</span>
|
||||||
|
<span class="ml-auto inline-flex items-center gap-1.5 rounded-lg border border-zinc-700 bg-zinc-800 px-2 py-1 text-xs font-medium text-zinc-200">
|
||||||
|
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14" /><path d="M12 5v14" /></svg>
|
||||||
|
{{ t('mStart') }}
|
||||||
|
</span>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<!-- worktree : branche principale, session au repos -->
|
||||||
|
<div class="rounded border border-zinc-800 bg-zinc-900/40 p-2">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<span class="font-mono text-sm text-zinc-200">main</span>
|
||||||
|
<span class="inline-flex items-center rounded bg-zinc-800 px-1.5 py-0.5 text-[11px] font-medium text-zinc-400">{{ t('mMain') }}</span>
|
||||||
|
<span class="ml-auto text-xs text-zinc-600">{{ t('mClean') }}</span>
|
||||||
|
</div>
|
||||||
|
<p class="truncate font-mono text-xs text-zinc-500">~/code/arboretum</p>
|
||||||
|
<div class="mt-1 flex items-center gap-2">
|
||||||
|
<span class="inline-flex items-center gap-1 rounded bg-zinc-800/60 px-1.5 py-0.5">
|
||||||
|
<span class="inline-flex items-center gap-1 rounded bg-emerald-950 px-1.5 py-0.5 text-[11px] font-medium text-emerald-400">
|
||||||
|
<span class="h-1.5 w-1.5 rounded-full bg-emerald-400"></span>{{ t('idle') }}
|
||||||
|
</span>
|
||||||
|
<span class="font-mono text-[11px] text-zinc-400">claude</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- worktree : branche de feature, session occupée -->
|
||||||
|
<div class="rounded border border-zinc-800 bg-zinc-900/40 p-2">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<span class="font-mono text-sm text-zinc-200">feat/auth</span>
|
||||||
|
<span class="ml-auto flex items-center gap-2 text-xs text-zinc-500">
|
||||||
|
<span>↑2</span>
|
||||||
|
<span class="text-amber-400">● {{ t('mDirty') }}</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<p class="truncate font-mono text-xs text-zinc-500">~/code/arboretum/.wt/feat-auth</p>
|
||||||
|
<div class="mt-1 flex items-center gap-2">
|
||||||
|
<span class="inline-flex items-center gap-1 rounded bg-zinc-800/60 px-1.5 py-0.5">
|
||||||
|
<span class="inline-flex items-center gap-1 rounded bg-sky-950 px-1.5 py-0.5 text-[11px] font-medium text-sky-300">
|
||||||
|
<span class="h-1.5 w-1.5 animate-pulse-sky rounded-full bg-sky-300"></span>{{ t('busy') }}
|
||||||
|
</span>
|
||||||
|
<span class="font-mono text-[11px] text-zinc-400">claude</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<!-- actions git de la carte : commit / push (fidèle au WorktreeCard) -->
|
||||||
|
<div class="mt-1 flex items-center gap-1.5">
|
||||||
|
<span class="inline-flex items-center rounded border border-zinc-700 bg-zinc-800 px-1.5 py-0.5 text-[11px] font-medium text-zinc-300">{{ t('mCommit') }}</span>
|
||||||
|
<span class="inline-flex items-center rounded border border-zinc-700 bg-zinc-800 px-1.5 py-0.5 text-[11px] font-medium text-zinc-300">{{ t('mPush') }} ↑2</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- b) grille multi-terminaux (fidèle à TerminalCell : badge d'état + titre repo · branche + commande) -->
|
||||||
|
<div v-reveal class="flex flex-wrap-reverse items-center gap-12">
|
||||||
|
<div class="min-w-[280px] flex-[1_1_440px]">
|
||||||
|
<div class="grid grid-cols-2 gap-2.5 overflow-hidden rounded-xl border border-zinc-800 bg-[#0c0c0e] p-3 shadow-card">
|
||||||
|
<div class="overflow-hidden rounded-lg border border-zinc-800 bg-[#09090b]">
|
||||||
|
<div class="flex items-center gap-2 border-b border-zinc-800 px-2 py-1.5">
|
||||||
|
<span class="inline-flex items-center gap-1 rounded bg-sky-950 px-1.5 py-0.5 text-[10px] font-medium text-sky-300"><span class="h-1.5 w-1.5 animate-pulse-sky rounded-full bg-sky-300"></span>{{ t('busy') }}</span>
|
||||||
|
<span class="truncate font-mono text-[11px] text-zinc-300">api · feat/auth</span>
|
||||||
|
<span class="ml-auto shrink-0 font-mono text-[11px] text-zinc-500">claude</span>
|
||||||
|
</div>
|
||||||
|
<div class="p-[11px] font-mono text-[11px] leading-[1.75] text-zinc-300">
|
||||||
|
<div class="text-emerald-400">● Edit session.ts</div>
|
||||||
|
<div class="text-emerald-400">+ const token = sign(...)</div>
|
||||||
|
<div class="text-red-400">- legacy cookie auth</div>
|
||||||
|
<div class="text-zinc-500">refactoring guards…</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="overflow-hidden rounded-lg border border-zinc-800 bg-[#09090b]">
|
||||||
|
<div class="flex items-center gap-2 border-b border-zinc-800 px-2 py-1.5">
|
||||||
|
<span class="inline-flex items-center gap-1 rounded bg-emerald-950 px-1.5 py-0.5 text-[10px] font-medium text-emerald-400"><span class="h-1.5 w-1.5 rounded-full bg-emerald-400"></span>{{ t('idle') }}</span>
|
||||||
|
<span class="truncate font-mono text-[11px] text-zinc-300">web · fix/cart</span>
|
||||||
|
<span class="ml-auto shrink-0 font-mono text-[11px] text-zinc-500">claude</span>
|
||||||
|
</div>
|
||||||
|
<div class="p-[11px] font-mono text-[11px] leading-[1.75] text-zinc-300">
|
||||||
|
<div class="text-emerald-400">✓ all tests passing</div>
|
||||||
|
<div class="text-zinc-500">24 passed, 0 failed</div>
|
||||||
|
<div>
|
||||||
|
<span class="text-emerald-400">$</span>
|
||||||
|
<span class="ml-1 inline-block h-[11px] w-1.5 animate-blink align-middle bg-zinc-200"></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="overflow-hidden rounded-lg border border-zinc-800 bg-[#09090b]">
|
||||||
|
<div class="flex items-center gap-2 border-b border-zinc-800 px-2 py-1.5">
|
||||||
|
<span class="inline-flex items-center gap-1 rounded bg-sky-950 px-1.5 py-0.5 text-[10px] font-medium text-sky-300"><span class="h-1.5 w-1.5 animate-pulse-sky rounded-full bg-sky-300"></span>{{ t('busy') }}</span>
|
||||||
|
<span class="truncate font-mono text-[11px] text-zinc-300">db · refactor</span>
|
||||||
|
<span class="ml-auto shrink-0 font-mono text-[11px] text-zinc-500">claude</span>
|
||||||
|
</div>
|
||||||
|
<div class="p-[11px] font-mono text-[11px] leading-[1.75] text-zinc-300">
|
||||||
|
<div class="text-emerald-400">● Write migration</div>
|
||||||
|
<div class="text-zinc-500">0003_add_index.sql</div>
|
||||||
|
<div class="text-zinc-500">applying to schema…</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="overflow-hidden rounded-lg border border-zinc-800 bg-[#09090b]">
|
||||||
|
<div class="flex items-center gap-2 border-b border-zinc-800 px-2 py-1.5">
|
||||||
|
<span class="inline-flex items-center gap-1 rounded bg-amber-950 px-1.5 py-0.5 text-[10px] font-medium text-amber-300"><span class="h-1.5 w-1.5 animate-pulse-amber rounded-full bg-amber-300"></span>{{ t('waiting') }}</span>
|
||||||
|
<span class="truncate font-mono text-[11px] text-zinc-300">docs · api</span>
|
||||||
|
<span class="ml-auto shrink-0 font-mono text-[11px] text-zinc-500">claude</span>
|
||||||
|
</div>
|
||||||
|
<div class="p-[11px] font-mono text-[11px] leading-[1.75] text-zinc-300">
|
||||||
|
<div class="text-emerald-400">● Read README.md</div>
|
||||||
|
<div class="text-amber-300">Permission required</div>
|
||||||
|
<div class="text-zinc-500">waiting for input…</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="min-w-[280px] flex-[1_1_360px]">
|
||||||
|
<div class="mb-3 font-mono text-xs uppercase tracking-[0.12em] text-emerald-400">{{ t('scBKicker') }}</div>
|
||||||
|
<h2 class="m-0 mb-4 text-[clamp(26px,3vw,34px)] font-semibold leading-[1.15] tracking-[-0.025em] text-zinc-50">
|
||||||
|
{{ t('scBTitle') }}
|
||||||
|
</h2>
|
||||||
|
<p class="m-0 text-[16.5px] leading-[1.6] text-zinc-400">{{ t('scBBody') }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- c) mobile : push + réponse au dialogue (fidèle à DialogPrompt) + barre d'onglets -->
|
||||||
|
<div v-reveal class="flex flex-wrap items-center gap-12">
|
||||||
|
<div class="min-w-[280px] flex-[1_1_380px]">
|
||||||
|
<div class="mb-3 font-mono text-xs uppercase tracking-[0.12em] text-emerald-400">{{ t('scCKicker') }}</div>
|
||||||
|
<h2 class="m-0 mb-4 text-[clamp(26px,3vw,34px)] font-semibold leading-[1.15] tracking-[-0.025em] text-zinc-50">
|
||||||
|
{{ t('scCTitle') }}
|
||||||
|
</h2>
|
||||||
|
<p class="m-0 text-[16.5px] leading-[1.6] text-zinc-400">{{ t('scCBody') }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="flex min-w-[280px] flex-[1_1_320px] justify-center">
|
||||||
|
<div class="relative w-[300px] overflow-hidden rounded-[40px] border-[9px] border-zinc-900 bg-zinc-950 shadow-phone">
|
||||||
|
<div class="flex h-[30px] items-center justify-center">
|
||||||
|
<div class="h-1.5 w-[90px] rounded-full bg-zinc-800"></div>
|
||||||
|
</div>
|
||||||
|
<div class="px-3 pb-[64px]">
|
||||||
|
<!-- toast push -->
|
||||||
|
<div class="flex items-start gap-[11px] rounded-[15px] border border-[rgba(120,53,15,0.5)] bg-[#0c0c0e] p-[13px] shadow-toast-sm">
|
||||||
|
<span class="inline-flex h-[30px] w-[30px] flex-none items-center justify-center rounded-lg bg-emerald-500/[0.14]">
|
||||||
|
<img src="/assets/arboretum-mark.png" alt="" width="18" height="18" class="h-[18px] w-[18px] object-contain" />
|
||||||
|
</span>
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<span class="font-mono text-[11px] text-emerald-400">Arboretum</span>
|
||||||
|
<span class="text-[10px] text-zinc-600">now</span>
|
||||||
|
</div>
|
||||||
|
<div class="mt-[3px] text-[13.5px] font-semibold text-zinc-50">{{ t('toastTitle') }}</div>
|
||||||
|
<div class="text-xs leading-[1.45] text-zinc-400">{{ t('toastBody') }}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- carte « À traiter » + DialogPrompt -->
|
||||||
|
<div class="mt-[14px] flex flex-col gap-2 rounded-[15px] border border-amber-900/50 bg-amber-950/20 p-2.5">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#fbbf24" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z" /><path d="M12 9v4" /><path d="M12 17h.01" /></svg>
|
||||||
|
<span class="text-[13px] font-semibold text-amber-200">{{ t('mAttn') }}</span>
|
||||||
|
<span class="rounded-full bg-amber-500/20 px-1.5 text-[11px] font-semibold text-amber-300">1</span>
|
||||||
|
</div>
|
||||||
|
<span class="font-mono text-[11px] text-amber-300/80">api · feat/auth</span>
|
||||||
|
<div class="rounded-lg border border-amber-900/60 bg-amber-950/30 p-2.5">
|
||||||
|
<span class="inline-flex items-center rounded bg-amber-900 px-1.5 py-0.5 text-[11px] font-medium text-amber-200">{{ t('mPermission') }}</span>
|
||||||
|
<div class="mt-1.5 text-[13px] leading-[1.4] text-amber-100">{{ t('dlgQ') }}</div>
|
||||||
|
<div class="mt-2 flex flex-col gap-1.5">
|
||||||
|
<span
|
||||||
|
v-for="(op, i) in dlgOpts"
|
||||||
|
:key="i"
|
||||||
|
class="flex items-center gap-2 rounded-lg border border-zinc-700 bg-zinc-800 px-2.5 py-2 text-[13px] font-medium text-zinc-200"
|
||||||
|
>
|
||||||
|
<span class="font-mono text-amber-400">{{ i + 1 }}</span> {{ op }}
|
||||||
|
</span>
|
||||||
|
<span class="rounded-lg border border-red-900 bg-red-950 px-2.5 py-2 text-center text-[13px] font-medium text-red-300">{{ t('mDeny') }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- barre d'onglets mobile (fidèle à MobileTabBar) -->
|
||||||
|
<div class="absolute inset-x-0 bottom-0 flex border-t border-zinc-800 bg-zinc-950/95 backdrop-blur">
|
||||||
|
<div class="flex flex-1 flex-col items-center gap-0.5 py-2 text-zinc-500">
|
||||||
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="6" x2="6" y1="3" y2="15" /><circle cx="18" cy="6" r="3" /><circle cx="6" cy="18" r="3" /><path d="M18 9a9 9 0 0 1-9 9" /></svg>
|
||||||
|
<span class="text-[10px]">{{ t('mWorktrees') }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="relative flex flex-1 flex-col items-center gap-0.5 py-2 text-emerald-400">
|
||||||
|
<span class="relative">
|
||||||
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m7 11 2-2-2-2" /><path d="M11 13h4" /><rect width="18" height="18" x="3" y="3" rx="2" ry="2" /></svg>
|
||||||
|
<span 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">1</span>
|
||||||
|
</span>
|
||||||
|
<span class="text-[10px]">{{ t('mSessions') }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-1 flex-col items-center gap-0.5 py-2 text-zinc-500">
|
||||||
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z" /><path d="M7 16.5 12 13.5" /><path d="M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z" /><path d="m17 16.5 4.74-2.85" /><path d="M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0z" /></svg>
|
||||||
|
<span class="text-[10px]">{{ t('mGroups') }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-1 flex-col items-center gap-0.5 py-2 text-zinc-500">
|
||||||
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="4" x2="20" y1="12" y2="12" /><line x1="4" x2="20" y1="6" y2="6" /><line x1="4" x2="20" y1="18" y2="18" /></svg>
|
||||||
|
<span class="text-[10px]">{{ t('mMore') }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
55
packages/site/src/components/WorkGroupsSection.vue
Normal file
55
packages/site/src/components/WorkGroupsSection.vue
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
const { t } = useI18n();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section class="mx-auto max-w-[1200px] scroll-mt-[84px] px-6 py-[92px]">
|
||||||
|
<div
|
||||||
|
v-reveal
|
||||||
|
class="flex flex-wrap items-center gap-12 rounded-[18px] border border-zinc-800 p-[clamp(28px,4vw,52px)]"
|
||||||
|
style="background: linear-gradient(180deg, rgba(24, 24, 27, 0.55), rgba(12, 12, 14, 0.55))"
|
||||||
|
>
|
||||||
|
<div class="min-w-[280px] flex-[1_1_360px]">
|
||||||
|
<div class="mb-3 font-mono text-xs uppercase tracking-[0.12em] text-emerald-400">{{ t('grpKicker') }}</div>
|
||||||
|
<h2 class="m-0 mb-4 text-[clamp(26px,3vw,36px)] font-semibold leading-[1.15] tracking-[-0.025em] text-zinc-50">
|
||||||
|
{{ t('grpTitle') }}
|
||||||
|
</h2>
|
||||||
|
<p class="m-0 text-[16.5px] leading-[1.6] text-zinc-400">{{ t('grpBody') }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="flex min-w-[280px] flex-[1_1_360px] justify-center">
|
||||||
|
<div class="flex w-full max-w-[380px] items-center">
|
||||||
|
<div class="flex flex-none flex-col items-center gap-2">
|
||||||
|
<div
|
||||||
|
class="inline-flex h-[62px] w-[62px] items-center justify-center rounded-[15px] border border-emerald-500/35 bg-emerald-500/[0.12] text-emerald-400"
|
||||||
|
>
|
||||||
|
<svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z" /><path d="M7 16.5 12 13.5" /><path d="M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z" /><path d="m17 16.5 4.74-2.85" /><path d="M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0z" /></svg>
|
||||||
|
</div>
|
||||||
|
<span class="font-mono text-[11px] text-zinc-300">{{ t('grpHub') }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="relative h-[96px] flex-1">
|
||||||
|
<svg width="100%" height="100%" viewBox="0 0 100 96" preserveAspectRatio="none" class="absolute inset-0" aria-hidden="true">
|
||||||
|
<path d="M0 48 H40 V14 H100" fill="none" stroke="rgba(16,185,129,.45)" stroke-width="1.4" />
|
||||||
|
<path d="M0 48 H40 V48 H100" fill="none" stroke="rgba(16,185,129,.45)" stroke-width="1.4" />
|
||||||
|
<path d="M0 48 H40 V82 H100" fill="none" stroke="rgba(16,185,129,.45)" stroke-width="1.4" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-none flex-col gap-2.5">
|
||||||
|
<div class="flex items-center gap-2 rounded-lg border border-zinc-800 bg-[#0c0c0e] px-3 py-2">
|
||||||
|
<span class="h-1.5 w-1.5 rounded-full bg-sky-300"></span>
|
||||||
|
<span class="font-mono text-[11px] text-zinc-300">api</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-2 rounded-lg border border-zinc-800 bg-[#0c0c0e] px-3 py-2">
|
||||||
|
<span class="h-1.5 w-1.5 rounded-full bg-sky-300"></span>
|
||||||
|
<span class="font-mono text-[11px] text-zinc-300">web</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-2 rounded-lg border border-zinc-800 bg-[#0c0c0e] px-3 py-2">
|
||||||
|
<span class="h-1.5 w-1.5 rounded-full bg-sky-300"></span>
|
||||||
|
<span class="font-mono text-[11px] text-zinc-300">sdk</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
19
packages/site/src/components/icons/IconCheck.vue
Normal file
19
packages/site/src/components/icons/IconCheck.vue
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
withDefaults(defineProps<{ size?: number }>(), { size: 15 });
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<svg
|
||||||
|
:width="size"
|
||||||
|
:height="size"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
stroke-width="2.2"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<path d="M20 6 9 17l-5-5" />
|
||||||
|
</svg>
|
||||||
|
</template>
|
||||||
20
packages/site/src/components/icons/IconCopy.vue
Normal file
20
packages/site/src/components/icons/IconCopy.vue
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
withDefaults(defineProps<{ size?: number }>(), { size: 15 });
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<svg
|
||||||
|
:width="size"
|
||||||
|
:height="size"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
stroke-width="1.9"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<rect width="13" height="13" x="9" y="9" rx="2" />
|
||||||
|
<path d="M5 15c-1.1 0-2-.9-2-2V5c0-1.1.9-2 2-2h8c1.1 0 2 .9 2 2" />
|
||||||
|
</svg>
|
||||||
|
</template>
|
||||||
22
packages/site/src/components/icons/IconGitea.vue
Normal file
22
packages/site/src/components/icons/IconGitea.vue
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
withDefaults(defineProps<{ size?: number }>(), { size: 16 });
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<svg
|
||||||
|
:width="size"
|
||||||
|
:height="size"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
stroke-width="1.7"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<path d="M4 10h12v4a4 4 0 0 1-4 4H8a4 4 0 0 1-4-4z" />
|
||||||
|
<path d="M16 11h2.5a2.5 2.5 0 0 1 0 5H16" />
|
||||||
|
<path d="M7 3c-.5.8.5 1.6 0 2.5" />
|
||||||
|
<path d="M11 3c-.5.8.5 1.6 0 2.5" />
|
||||||
|
</svg>
|
||||||
|
</template>
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user