Compare commits
76 Commits
v1.2.0
...
ef21b03d9c
| Author | SHA1 | Date | |
|---|---|---|---|
| ef21b03d9c | |||
| 0532331795 | |||
| 1299b1b349 | |||
| ccbc1b9e4e | |||
| c9811fc0ca | |||
| 82682b0a37 | |||
| ae7ede6684 | |||
| de066abb54 | |||
| 4798732856 | |||
| d287c3c1d1 | |||
| 6741b2d47c | |||
| 5302bf29ae | |||
| f62404234b | |||
| c96d929c7a | |||
| 6acd4a16fd | |||
| cf60fa3a56 | |||
| 9a496abd00 | |||
| 65ef616867 | |||
| 985531a986 | |||
| d4e3ab47cd | |||
| 8a8fac75e6 | |||
| ac4d098b53 | |||
| 08695a707d | |||
| e8d10b7ec0 | |||
| 92670a796a | |||
| 75efecf93f | |||
| c8dd539571 | |||
| be43911dc0 | |||
| 062bb64d41 | |||
| a67871b9b9 | |||
| 69123eaf0e | |||
| 0f126cf911 | |||
| b5236b41c8 | |||
| 2506dfb1f3 | |||
| 7d618c30d5 | |||
| 529c136199 | |||
| 7fc1f6f747 | |||
| 8b9060e0c0 | |||
| 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 |
101
.gitea/workflows/ci.yml
Normal file
101
.gitea/workflows/ci.yml
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
# CI Arboretum : build + tests sur Node 22/24, puis smoke de packaging npx.
|
||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
name: Build & test (Node ${{ matrix.node }})
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
node: [22, 24]
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: ${{ matrix.node }}
|
||||||
|
cache: npm
|
||||||
|
- run: npm ci
|
||||||
|
- run: npm run typecheck
|
||||||
|
- run: npm run build
|
||||||
|
- run: npm run build:site
|
||||||
|
- run: npx vitest run
|
||||||
|
|
||||||
|
pack-smoke:
|
||||||
|
name: Pack & boot smoke (Node 22)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: test
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 22
|
||||||
|
cache: npm
|
||||||
|
- run: npm ci
|
||||||
|
- run: npm run build
|
||||||
|
# @arboretum/shared (paquet workspace NON publié) est INLINÉ dans dist/_shared au prepack
|
||||||
|
# (scripts/inline-shared.mjs) : le tarball est 100 % autonome : aucun node_modules embarqué,
|
||||||
|
# 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
|
||||||
|
run: |
|
||||||
|
rm -rf /tmp/tarballs && mkdir -p /tmp/tarballs
|
||||||
|
npm pack -w @johanleroy/git-arboretum --pack-destination /tmp/tarballs
|
||||||
|
ls -l /tmp/tarballs
|
||||||
|
- name: Assert the package is self-contained (@arboretum/shared inlined)
|
||||||
|
run: |
|
||||||
|
tgz=$(ls /tmp/tarballs/*.tgz)
|
||||||
|
rm -rf /tmp/inspect && mkdir -p /tmp/inspect && tar -xzf "$tgz" -C /tmp/inspect
|
||||||
|
test -f /tmp/inspect/package/dist/_shared/index.js \
|
||||||
|
|| { 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
|
||||||
|
run: |
|
||||||
|
mkdir /tmp/smoke
|
||||||
|
cd /tmp/smoke
|
||||||
|
npm init -y
|
||||||
|
npm i /tmp/tarballs/*.tgz
|
||||||
|
- name: Boot smoke (expect 401 on /api/v1/sessions)
|
||||||
|
run: |
|
||||||
|
cd /tmp/smoke
|
||||||
|
timeout 30 node_modules/.bin/arboretum --port 7999 --db ./t.db &
|
||||||
|
server_pid=$!
|
||||||
|
code=000
|
||||||
|
for i in $(seq 1 20); do
|
||||||
|
sleep 0.5
|
||||||
|
code=$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:7999/api/v1/sessions || true)
|
||||||
|
if [ "$code" = "401" ]; then break; fi
|
||||||
|
done
|
||||||
|
echo "GET /api/v1/sessions -> HTTP $code"
|
||||||
|
kill "$server_pid" 2>/dev/null || true
|
||||||
|
test "$code" = "401"
|
||||||
|
|
||||||
|
lint-dashes:
|
||||||
|
# Interdit tout tiret cadratin (U+2014) ou demi-cadratin (U+2013) dans les fichiers suivis.
|
||||||
|
# Utiliser a la place : point median, deux-points, virgule, ou tiret simple pour les plages.
|
||||||
|
# Exclusions : logo binaire + captures brutes du terminal (fidelite des fixtures de dialogue).
|
||||||
|
name: No em/en dashes
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Fail on U+2014 / U+2013 (outside allow-list)
|
||||||
|
run: |
|
||||||
|
if git grep -nP '[\x{2014}\x{2013}]' -- . \
|
||||||
|
':(exclude)brand/arboretum-logo-source.png' \
|
||||||
|
':(exclude)packages/server/test/fixtures/dialogs/*.raw'; then
|
||||||
|
echo "::error::Tiret cadratin/demi-cadratin trouve. Utiliser point median, deux-points, virgule ou tiret simple (plages)."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
78
.gitea/workflows/desktop-release.yml
Normal file
78
.gitea/workflows/desktop-release.yml
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
# Packaging de l'app de bureau Electron, déclenché UNIQUEMENT par un tag desktop-vX.Y.Z (séparé de
|
||||||
|
# la release du daemon qui écoute v*, et du VSIX qui écoute vscode-v*). Linux (AppImage + deb) est
|
||||||
|
# automatisé ici ; Windows et macOS se buildent sur ces OS (voir packages/desktop/README.md) et
|
||||||
|
# leurs artefacts sont attachés manuellement à la release.
|
||||||
|
name: Desktop Release
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags: ['desktop-v*']
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
env:
|
||||||
|
NODE_VERSION: '22.21.1'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
linux:
|
||||||
|
name: Build Linux (AppImage + deb)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: ${{ env.NODE_VERSION }}
|
||||||
|
cache: npm
|
||||||
|
# Garde-fou : le tag (sans "desktop-v") doit correspondre à la version du paquet desktop.
|
||||||
|
- name: Verify tag matches desktop version
|
||||||
|
run: |
|
||||||
|
pkg=$(node -p "require('./packages/desktop/package.json').version")
|
||||||
|
tag="${GITHUB_REF_NAME#desktop-v}"
|
||||||
|
if [ "$pkg" != "$tag" ]; then
|
||||||
|
echo "ERREUR: tag '$tag' != version desktop '$pkg'"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "OK: tag $tag == version $pkg"
|
||||||
|
# Deps racine (build/pack du daemon) puis deps du paquet desktop (hors workspaces racine).
|
||||||
|
- run: npm ci
|
||||||
|
- name: Install desktop deps
|
||||||
|
run: cd packages/desktop && npm ci
|
||||||
|
# Build complet : shell + daemon empaqueté + Node standalone + AppImage/deb (electron-builder).
|
||||||
|
- name: Build installers
|
||||||
|
run: cd packages/desktop && npm run dist:linux
|
||||||
|
# Artefacts du run : canal fiable, indépendant de l'API release.
|
||||||
|
- uses: actions/upload-artifact@v3
|
||||||
|
with:
|
||||||
|
name: desktop-linux
|
||||||
|
path: |
|
||||||
|
packages/desktop/release/*.AppImage
|
||||||
|
packages/desktop/release/*.deb
|
||||||
|
packages/desktop/release/latest-linux.yml
|
||||||
|
# Best-effort : attache les installeurs (+ latest-linux.yml pour l'auto-update) à la release
|
||||||
|
# Gitea du tag (crée la release si absente). Réutilise NPM_TOKEN (même token Gitea).
|
||||||
|
- name: Attach installers to Gitea release
|
||||||
|
continue-on-error: true
|
||||||
|
env:
|
||||||
|
RELEASE_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||||
|
run: |
|
||||||
|
if [ -z "$RELEASE_TOKEN" ]; then
|
||||||
|
echo "::notice::NPM_TOKEN absent : installeurs disponibles 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/desktop/package.json').version")
|
||||||
|
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 Desktop ${version}\"}" \
|
||||||
|
"${api}/releases" | node -p "JSON.parse(require('fs').readFileSync(0,'utf8')).id || ''")
|
||||||
|
fi
|
||||||
|
for f in packages/desktop/release/*.AppImage packages/desktop/release/*.deb packages/desktop/release/latest-linux.yml; do
|
||||||
|
[ -f "$f" ] || continue
|
||||||
|
name=$(basename "$f")
|
||||||
|
echo "attaching $name"
|
||||||
|
curl -fsSL -X POST -H "$auth" -F "attachment=@${f}" "${api}/releases/${rid}/assets?name=${name}"
|
||||||
|
done
|
||||||
|
echo "Installeurs Linux attachés à la release ${GITHUB_REF_NAME}."
|
||||||
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 }}
|
||||||
75
.gitea/workflows/release.yml
Normal file
75
.gitea/workflows/release.yml
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
# 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:
|
||||||
|
# `v[0-9]*` (et non `v*`) : sinon ce workflow capture aussi les tags `vscode-v*` de l'extension
|
||||||
|
# : il stripperait alors `v` (→ `scode-v0.1.0`) et échouerait contre la version du daemon.
|
||||||
|
tags: ['v[0-9]*']
|
||||||
|
|
||||||
|
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}."
|
||||||
77
.github/workflows/ci.yml
vendored
77
.github/workflows/ci.yml
vendored
@@ -1,77 +0,0 @@
|
|||||||
# CI Arboretum : build + tests sur Node 22/24, puis smoke de packaging npx.
|
|
||||||
name: CI
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [main]
|
|
||||||
pull_request:
|
|
||||||
branches: [main]
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
test:
|
|
||||||
name: Build & test (Node ${{ matrix.node }})
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
node: [22, 24]
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version: ${{ matrix.node }}
|
|
||||||
cache: npm
|
|
||||||
- run: npm ci
|
|
||||||
- run: npm run typecheck
|
|
||||||
- run: npm run build
|
|
||||||
- run: npx vitest run
|
|
||||||
|
|
||||||
pack-smoke:
|
|
||||||
name: Pack & boot smoke (Node 22)
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: test
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version: 22
|
|
||||||
cache: npm
|
|
||||||
- run: npm ci
|
|
||||||
- run: npm run build
|
|
||||||
# @arboretum/shared (dépendance runtime non publiée) est embarquée dans le tarball
|
|
||||||
# via bundleDependencies (matérialisée au prepack). On packe donc UN SEUL tarball
|
|
||||||
# et on l'installe seul, comme un vrai consommateur depuis le registre.
|
|
||||||
- name: Pack tarball
|
|
||||||
run: |
|
|
||||||
mkdir -p /tmp/tarballs
|
|
||||||
npm pack -w @johanleroy/git-arboretum --pack-destination /tmp/tarballs
|
|
||||||
ls -l /tmp/tarballs
|
|
||||||
- name: Assert @arboretum/shared is bundled in the tarball
|
|
||||||
run: |
|
|
||||||
tgz=$(ls /tmp/tarballs/*.tgz)
|
|
||||||
tar -tzf "$tgz" | grep -q 'node_modules/@arboretum/shared/dist/index.js' \
|
|
||||||
|| { echo "ERREUR: @arboretum/shared non embarqué dans $tgz"; exit 1; }
|
|
||||||
echo "OK: bundleDependency @arboretum/shared présente dans $tgz"
|
|
||||||
- name: Install tarball in an empty project
|
|
||||||
run: |
|
|
||||||
mkdir /tmp/smoke
|
|
||||||
cd /tmp/smoke
|
|
||||||
npm init -y
|
|
||||||
npm i /tmp/tarballs/*.tgz
|
|
||||||
- name: Boot smoke (expect 401 on /api/v1/sessions)
|
|
||||||
run: |
|
|
||||||
cd /tmp/smoke
|
|
||||||
timeout 30 node_modules/.bin/arboretum --port 7999 --db ./t.db &
|
|
||||||
server_pid=$!
|
|
||||||
code=000
|
|
||||||
for i in $(seq 1 20); do
|
|
||||||
sleep 0.5
|
|
||||||
code=$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:7999/api/v1/sessions || true)
|
|
||||||
if [ "$code" = "401" ]; then break; fi
|
|
||||||
done
|
|
||||||
echo "GET /api/v1/sessions -> HTTP $code"
|
|
||||||
kill "$server_pid" 2>/dev/null || true
|
|
||||||
test "$code" = "401"
|
|
||||||
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 }}
|
|
||||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -26,7 +26,7 @@ coverage/
|
|||||||
.vscode/
|
.vscode/
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
|
||||||
# Claude Code / agent tooling (local only — do not commit)
|
# Claude Code / agent tooling (local only, do not commit)
|
||||||
CLAUDE.md
|
CLAUDE.md
|
||||||
.claude/
|
.claude/
|
||||||
.remember/
|
.remember/
|
||||||
|
|||||||
139
README.fr.md
139
README.fr.md
@@ -3,14 +3,16 @@
|
|||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
Un dashboard web auto-hébergé pour vos worktrees git et les sessions Claude Code qui tournent dessus — depuis n'importe quel appareil.
|
Un IDE IA multi-projet auto-hébergé pour vos worktrees git et les sessions Claude Code qui tournent dessus : une app de bureau native et une interface web, depuis n'importe quel appareil.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<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, la supervision mobile (PWA installable, Web Push quand une session vous attend, valider/refuser sans ouvrir de terminal) et les groupes de travail (piloter plusieurs repos liés à la fois) 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.
|
||||||
|
|
||||||
|
La dernière étape transforme Arboretum en véritable **IDE IA multi-projet** : un espace de travail unique (route `/ide`, la vue par défaut sur desktop) qui réunit **tous** vos projets ouverts à la fois, fini l'IDE par projet. Un arbre unique à gauche (projet, puis checkout principal et worktrees, puis session Claude), un éditeur Monaco à onglets au centre (plusieurs fichiers de projets différents côte à côte, diffs inline), les terminaux Claude en dock bas, et des panneaux Git / Sessions / Groupes via une barre d'activité. Il est fourni à la fois en **app de bureau native** (Linux, Windows, macOS) et en interface web, adossé à un watcher de système de fichiers en temps réel, au staging sélectif / discard / amend / fetch / pull, à l'archivage automatique des sessions, à la synchronisation des réglages en temps réel, et à des services git distants chiffrés (GitHub / GitLab / Gitea) avec clone HTTPS.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -24,39 +26,43 @@ Travailler avec des agents de code IA a changé notre usage de git : une feature
|
|||||||
|
|
||||||
## Ce que fait Arboretum
|
## Ce que fait Arboretum
|
||||||
|
|
||||||
Un unique daemon Node.js que vous lancez sur votre machine de dev (`npx @johanleroy/git-arboretum`), servant une interface web utilisable depuis votre ordinateur, téléphone ou tablette :
|
Un unique daemon Node.js que vous lancez sur votre machine de dev (en app de bureau native, ou via `npx @johanleroy/git-arboretum`), servant une interface utilisable depuis votre ordinateur, téléphone ou tablette :
|
||||||
|
|
||||||
- **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.
|
- **IDE multi-projet** : un espace de travail pour tous les projets ouverts à la fois (pas de fenêtre par projet). Un arbre unique (projet, worktrees, sessions Claude), un éditeur Monaco à onglets (plusieurs fichiers de projets différents côte à côte, avec diffs inline par fichier), un dock bas de terminaux de session, et des panneaux Git / Sessions / Groupes. Éditez les fichiers, indexez les changements sélectivement, committez (ou amendez), fetch/pull et push, au même endroit. Un watcher de système de fichiers en temps réel garde la vue à jour au fil des éditions de l'agent. Disponible en app de bureau native et dans le navigateur.
|
||||||
- **Groupes de travail** — regroupez des repos liés (ex. une API, son frontend web et une lib partagée) dans un groupe nommé pour travailler sur tous à la fois : une vue unifiée de leurs worktrees et sessions, une grille multi-terminaux côte à côte, et une action « feature cross-repo » en un clic qui crée le même worktree de branche (et au besoin une session Claude) dans chaque repo du groupe.
|
- **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.
|
||||||
|
- **Services git distants** : connectez vos comptes GitHub, GitLab ou Gitea (personal access token ou app password), stockés **chiffrés au repos** (AES-256-GCM) ; parcourez vos dépôts distants et clonez-les en HTTPS avec progression en direct, directement depuis le dashboard.
|
||||||
|
- **Archivage automatique** : les sessions terminées sont archivées automatiquement après une fenêtre de rétention configurable (30 jours par défaut), pour que la liste reste centrée sur ce qui est vivant tandis que l'historique reste à un clic.
|
||||||
|
- **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).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Prérequis
|
## Prérequis
|
||||||
|
|
||||||
- **Node.js ≥ 22.16** — requis, pas seulement recommandé. Arboretum persiste son état avec `node:sqlite` (`DatabaseSync`), natif et stable seulement à partir de cette version. (`.nvmrc` fixe `22`.)
|
- **Node.js ≥ 22.16** pour l'usage `npx` / depuis les sources : requis, pas seulement recommandé. Arboretum persiste son état avec `node:sqlite` (`DatabaseSync`), natif et stable seulement à partir de cette version. (`.nvmrc` fixe `22`.) L'**app de bureau embarque son propre runtime Node**, donc ses utilisateurs finaux n'ont pas besoin d'installer Node.
|
||||||
- **Le CLI `claude`** sur votre `PATH` si vous voulez qu'Arboretum lance et gère des sessions Claude Code. Arboretum enveloppe le CLI interactif que vous utilisez déjà — installez-le et authentifiez-le comme d'habitude.
|
- **Le CLI `claude`** sur votre `PATH` si vous voulez qu'Arboretum lance et gère des sessions Claude Code. Arboretum enveloppe le CLI interactif que vous utilisez déjà, installez-le et authentifiez-le comme d'habitude.
|
||||||
- Un **dépôt git** (ou plusieurs) que vous voulez gérer.
|
- Un **dépôt git** (ou plusieurs) que vous voulez gérer.
|
||||||
|
|
||||||
## Démarrage rapide
|
## Démarrage rapide
|
||||||
|
|
||||||
Deux chemins, selon ce que vous voulez :
|
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.
|
- **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.
|
- **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` :
|
||||||
|
|
||||||
```
|
```
|
||||||
@johanleroy:registry=https://git.lidge.fr/api/packages/johanleroy/npm/
|
@johanleroy:registry=https://git.lidge.fr/api/packages/johanleroy/npm/
|
||||||
```
|
```
|
||||||
|
|
||||||
Aucun token nécessaire — le paquet est en lecture publique. Puis lancez-le depuis n'importe où :
|
Aucun token nécessaire, le paquet est en lecture publique. Puis lancez-le depuis n'importe où :
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npx @johanleroy/git-arboretum
|
npx @johanleroy/git-arboretum
|
||||||
@@ -66,7 +72,7 @@ Au premier démarrage, Arboretum affiche un **token d'accès** unique et l'URL
|
|||||||
|
|
||||||
```
|
```
|
||||||
┌──────────────────────────────────────────────────────────────────┐
|
┌──────────────────────────────────────────────────────────────────┐
|
||||||
│ First start — your access token (shown once, store it safely): │
|
│ First start · your access token (shown once, store it safely): │
|
||||||
└──────────────────────────────────────────────────────────────────┘
|
└──────────────────────────────────────────────────────────────────┘
|
||||||
|
|
||||||
<votre-token-ici>
|
<votre-token-ici>
|
||||||
@@ -74,9 +80,9 @@ Au premier démarrage, Arboretum affiche un **token d'accès** unique et l'URL
|
|||||||
Login at: http://127.0.0.1:7317/
|
Login at: http://127.0.0.1:7317/
|
||||||
```
|
```
|
||||||
|
|
||||||
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 :
|
`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
|
```bash
|
||||||
npm i -g @johanleroy/git-arboretum
|
npm i -g @johanleroy/git-arboretum
|
||||||
@@ -85,7 +91,7 @@ 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 :
|
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
|
||||||
@@ -96,17 +102,58 @@ npm run build # build shared → server → web (l'ordre compte)
|
|||||||
node packages/server/dist/index.js
|
node packages/server/dist/index.js
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Application de bureau
|
||||||
|
|
||||||
|
Vous préférez une app native au daemon-dans-un-terminal ? Arboretum fournit une **app de bureau Electron** (`packages/desktop`) pour **Linux, Windows et macOS**. Elle lance le daemon en process enfant et ouvre son interface dans une fenêtre native, déjà connectée (aucun écran de login), et elle **embarque son propre runtime Node** : pas besoin d'avoir Node installé pour l'utiliser.
|
||||||
|
|
||||||
|
- **Installer.** Les installeurs sont publiés sur la [page des releases](https://git.lidge.fr/johanleroy/arboretum/releases) dès qu'une release desktop est taguée : un AppImage et un `.deb` sous Linux, un installeur NSIS (et un build portable) sous Windows, un `.dmg` sous macOS. Vous préférez les builder vous-même ? Voir [`packages/desktop/README.md`](packages/desktop/README.md).
|
||||||
|
- **Premier lancement.** L'app n'est pas encore signée : sous **Windows**, SmartScreen affiche « éditeur inconnu », choisissez « Informations complémentaires » puis « Exécuter quand même » ; sous **macOS**, Gatekeeper la bloque, clic droit sur l'app puis « Ouvrir » (ou lancez `xattr -dr com.apple.quarantine /Applications/Arboretum.app`).
|
||||||
|
- **Vit dans le tray.** Fermer la fenêtre garde Arboretum actif dans la barre système ; quittez depuis le menu du tray, où vous pouvez aussi activer le lancement au login. L'auto-update est intégré sous Windows et Linux (les mises à jour macOS restent manuelles tant que l'app n'est pas signée).
|
||||||
|
|
||||||
|
L'app de bureau n'est qu'une coquille autour du même daemon et de la même interface web : tout ce qui suit (espace de travail, git, sessions) fonctionne à l'identique.
|
||||||
|
|
||||||
## Utiliser Arboretum
|
## Utiliser Arboretum
|
||||||
|
|
||||||
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.
|
||||||
|
|
||||||
|
## L'IDE, espace de travail & opérations git
|
||||||
|
|
||||||
|
Au-delà de la supervision, Arboretum est un véritable **IDE multi-projet** (route `/ide`, la vue par défaut sur desktop). Il réunit tous les projets ouverts à la fois, pour ne plus jongler avec une fenêtre d'IDE par projet :
|
||||||
|
|
||||||
|
- **Arbre de projets unifié.** Un arbre unique à gauche liste chaque projet enregistré, son checkout principal et ses worktrees, et la session Claude corrélée à chacun. Dépliez un worktree pour parcourir ses fichiers inline. Une barre d'activité bascule le panneau gauche entre Explorateur, Git, Sessions et Groupes.
|
||||||
|
- **Éditeur à onglets.** Ouvrez des fichiers dans un **éditeur Monaco** à onglets, plusieurs fichiers de **projets différents** côte à côte, coloration syntaxique, détection du langage, enregistrement avec détection de conflit. Chaque onglet bascule entre éditeur et **diff par fichier** inline (arbre de travail ou index, ajouts/suppressions colorés, diffs binaires et énormes refusés).
|
||||||
|
- **Dock de terminaux.** Les terminaux de session Claude vivent dans un dock bas, un onglet par session ; ouvrez-en plusieurs à la fois (à travers les projets), répondez à une demande en attente directement là. Les terminaux survivent aux changements d'onglet et aux déconnexions du navigateur.
|
||||||
|
- **Panneau Git.** Indexez ou désindexez des fichiers individuels, jetez des changements, écrivez un message et **committez** (tout ou seulement l'indexé), **amendez** le dernier commit (refusé une fois poussé), puis **fetch**, **pull** (fast-forward ou rebase) et **push**. Les compteurs indexés / non indexés / conflits détaillés et le dernier commit restent à jour via un **watcher de système de fichiers en temps réel** : la vue s'actualise dès qu'une session Claude touche un fichier.
|
||||||
|
- **Deep links & mobile.** `/workspace/:repoId/:wt` ouvre toujours un worktree précis directement dans l'IDE (utilisé par l'extension VS Code). Sur mobile, l'IDE dégrade en panneau unique, et le dashboard des worktrees et les vues de session restent la PWA de supervision installable.
|
||||||
|
|
||||||
|
Comme toute action git dans Arboretum, ces opérations s'exécutent **en tant que vous** (le daemon tourne sous votre compte), cohérent avec le modèle de sécurité : un terminal web, c'est de l'exécution de code à distance par conception.
|
||||||
|
|
||||||
|
## 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, **fetch / pull**) avec un **statut git détaillé** dans l'arbre (indexés / non indexés / conflits et dernier commit), 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.
|
||||||
|
- **Ouvrir dans l'IDE web** : sautez de n'importe quel worktree directement vers sa vue `/workspace` complète dans le navigateur. L'extension reste un gestionnaire de worktrees visuel et léger ; l'édition lourde vit dans l'IDE web.
|
||||||
|
|
||||||
|
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.2.0.vsix
|
||||||
|
```
|
||||||
|
|
||||||
|
Puis installez-la via **Extensions : Installer à partir d'un VSIX…** (ou `code --install-extension git-arboretum-0.2.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
|
||||||
|
|
||||||
Arboretum se bind sur `127.0.0.1` par défaut et **refuse** de se binder sur une adresse non-loopback sans dérogation explicite. La façon recommandée (et sûre) de l'atteindre depuis d'autres appareils est **[Tailscale Serve](https://tailscale.com/kb/1242/tailscale-serve)** — HTTPS valide, identité tailnet, aucun port ouvert :
|
Arboretum se bind sur `127.0.0.1` par défaut et **refuse** de se binder sur une adresse non-loopback sans dérogation explicite. La façon recommandée (et sûre) de l'atteindre depuis d'autres appareils est **[Tailscale Serve](https://tailscale.com/kb/1242/tailscale-serve)**, HTTPS valide, identité tailnet, aucun port ouvert :
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Expose le daemon local en HTTPS dans votre tailnet
|
# Expose le daemon local en HTTPS dans votre tailnet
|
||||||
@@ -125,7 +172,7 @@ 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
|
||||||
|
|
||||||
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 :
|
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
|
```bash
|
||||||
npm i -g @johanleroy/git-arboretum
|
npm i -g @johanleroy/git-arboretum
|
||||||
@@ -148,7 +195,7 @@ Créez `~/.config/systemd/user/arboretum.service` :
|
|||||||
|
|
||||||
```ini
|
```ini
|
||||||
[Unit]
|
[Unit]
|
||||||
Description=Arboretum — git worktree & Claude Code dashboard
|
Description=Arboretum · git worktree & Claude Code dashboard
|
||||||
After=network-online.target
|
After=network-online.target
|
||||||
Wants=network-online.target
|
Wants=network-online.target
|
||||||
|
|
||||||
@@ -173,7 +220,7 @@ journalctl --user -u arboretum -f # logs
|
|||||||
```
|
```
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
> 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.
|
> 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
|
||||||
|
|
||||||
@@ -185,11 +232,11 @@ Les options du daemon sont des flags CLI :
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `--port <n>` | `7317` | Port d'écoute. |
|
| `--port <n>` | `7317` | Port d'écoute. |
|
||||||
| `--bind <addr>` | `127.0.0.1` | Adresse de bind. Une adresse non-loopback est refusée sauf si `--i-know-this-exposes-a-terminal` est défini. |
|
| `--bind <addr>` | `127.0.0.1` | Adresse de bind. Une adresse non-loopback est refusée sauf si `--i-know-this-exposes-a-terminal` est défini. |
|
||||||
| `--allow-origin <url>` | — | Origine `Origin` autorisée supplémentaire (répétable). Nécessaire pour l'accès Tailscale/HTTPS. |
|
| `--allow-origin <url>` | aucun | Origine `Origin` autorisée supplémentaire (répétable). Nécessaire pour l'accès Tailscale/HTTPS. |
|
||||||
| `--db <path>` | `<data>/arboretum.db` | Chemin de la base SQLite. |
|
| `--db <path>` | `<data>/arboretum.db` | Chemin de la base SQLite. |
|
||||||
| `--vapid-contact <mailto/url>` | `mailto:arboretum@localhost` | Sujet de contact VAPID pour le Web Push. |
|
| `--vapid-contact <mailto/url>` | `mailto:arboretum@localhost` | Sujet de contact VAPID pour le Web Push. |
|
||||||
| `--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 :
|
`arboretum install` accepte tous les flags du daemon ci-dessus (propagés tels quels au service), plus :
|
||||||
|
|
||||||
@@ -202,15 +249,29 @@ Les options du daemon sont des flags CLI :
|
|||||||
|
|
||||||
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`).
|
||||||
|
|
||||||
|
Les réglages au-delà des flags CLI (les répertoires qu'Arboretum scanne pour trouver des repos et à quelle fréquence, le chemin et le home du binaire `claude`, et les fenêtres de rétention / purge des sessions) vivent dans les **Réglages** de l'UI. Ils sont diffusés via le WebSocket, donc chaque navigateur connecté reflète un changement en temps réel, sans rechargement.
|
||||||
|
|
||||||
|
## Services git distants & clone
|
||||||
|
|
||||||
|
Arboretum peut se connecter à vos fournisseurs d'hébergement git pour parcourir et cloner des dépôts sans quitter le dashboard :
|
||||||
|
|
||||||
|
- **Fournisseurs & auth.** GitHub, GitLab et Gitea, authentifiés par un **personal access token** ou un **app password** (clés SSH et OAuth prévus). Ajoutez une connexion depuis **Réglages → Services git**, donnez-lui un libellé, et testez-la sur place : Arboretum rapporte `ok`, `auth failed`, `rate limited` ou `unreachable`.
|
||||||
|
- **Les secrets restent secrets.** Les identifiants sont **chiffrés au repos** (AES-256-GCM, `SecretBox`) et **jamais** renvoyés en clair par l'API REST : les réponses ne portent qu'un indice `…last4` et un drapeau « a un secret ».
|
||||||
|
- **Parcourir & cloner.** Listez les dépôts qu'une connexion peut voir, choisissez-en un, et clonez-le en HTTPS vers la destination de votre choix. Le clone tourne comme une opération suivie, avec **progression et phase** poussées en direct via le WebSocket, et le nouveau repo est enregistré automatiquement une fois terminé.
|
||||||
|
|
||||||
## Modèle de sécurité
|
## Modèle de sécurité
|
||||||
|
|
||||||
Un terminal web, c'est de l'exécution de code à distance *par conception*. Les garde-fous d'Arboretum sont structurants :
|
Un terminal web, c'est de l'exécution de code à distance *par conception*. Les garde-fous d'Arboretum sont structurants :
|
||||||
|
|
||||||
- Se bind sur `127.0.0.1` par défaut ; refuse les binds non-loopback sans flag explicite.
|
- Se bind sur `127.0.0.1` par défaut ; refuse les binds non-loopback sans flag explicite.
|
||||||
- Authentifie **chaque** requête `/api/**` **et** chaque upgrade `/ws` avec des tokens révocables, et applique un **check `Origin` strict** (le cookie `SameSite=Strict` ne couvre pas les upgrades WebSocket — c'est le garde-fou anti cross-site hijacking).
|
- Authentifie **chaque** requête `/api/**` **et** chaque upgrade `/ws` avec des tokens révocables, et applique un **check `Origin` strict** (le cookie `SameSite=Strict` ne couvre pas les upgrades WebSocket : c'est le garde-fou anti cross-site hijacking).
|
||||||
- Les tokens sont stockés **hashés** (sha256) et comparés en temps constant ; le bootstrap token n'est affiché qu'une seule fois. Le cookie de session est un payload signé HMAC, `HttpOnly` et `SameSite=Strict`, et reçoit automatiquement le flag `Secure` quand la requête arrive en HTTPS (p. ex. derrière Tailscale Serve). Le login est rate-limité avec backoff exponentiel.
|
- Les tokens sont stockés **hashés** (sha256) et comparés en temps constant ; le bootstrap token n'est affiché qu'une seule fois. Le cookie de session est un payload signé HMAC, `HttpOnly` et `SameSite=Strict`, et reçoit automatiquement le flag `Secure` quand la requête arrive en HTTPS (p. ex. derrière Tailscale Serve). Le login est rate-limité avec backoff exponentiel.
|
||||||
|
- Envoie des en-têtes HTTP durcis (CSP, `X-Frame-Options`, `nosniff`, `Referrer-Policy`, HSTS conditionnel, `no-store` sur l'API), restreint le dossier de données à `0o700` et la base à `0o600`, et **chiffre les secrets sensibles au repos** (AES-256-GCM).
|
||||||
|
- Tient un **journal d'audit** des opérations sensibles et offre l'**export/effacement RGPD** des données (Réglages → Sécurité & conformité).
|
||||||
|
|
||||||
Tailscale Serve est **la** façon d'atteindre Arboretum depuis d'autres appareils — pas seulement une recommandation : HTTPS valide, identité tailnet, aucun port ouvert. Le flag `--i-know-this-exposes-a-terminal` est une trappe de secours, pas un mode de déploiement ; n'exposez jamais Arboretum directement sur internet.
|
Tailscale Serve est **la** façon d'atteindre Arboretum depuis d'autres appareils, pas seulement une recommandation : HTTPS valide, identité tailnet, aucun port ouvert. Le flag `--i-know-this-exposes-a-terminal` est une trappe de secours, pas un mode de déploiement ; n'exposez jamais Arboretum directement sur internet.
|
||||||
|
|
||||||
|
Voir [`SECURITY.md`](SECURITY.md) pour le modèle de menace complet et [`docs/ENTERPRISE_DEPLOYMENT.md`](docs/ENTERPRISE_DEPLOYMENT.md) pour le durcissement en environnement réglementé.
|
||||||
|
|
||||||
## Ce qui le distingue
|
## Ce qui le distingue
|
||||||
|
|
||||||
@@ -219,7 +280,7 @@ Tailscale Serve est **la** façon d'atteindre Arboretum depuis d'autres appareil
|
|||||||
| Interface web, tout appareil | ✅ | ❌ apps desktop | ✅ | ✅ |
|
| Interface web, tout appareil | ✅ | ❌ apps desktop | ✅ | ✅ |
|
||||||
| Gestion visuelle des worktrees (multi-repo) | ✅ | ✅ (mono-repo, desktop) | ❌ | ❌ |
|
| Gestion visuelle des worktrees (multi-repo) | ✅ | ✅ (mono-repo, desktop) | ❌ | ❌ |
|
||||||
| Découvre & reprend les sessions de terminal *existantes* | ✅ | ❌ | partiel | ❌ |
|
| Découvre & reprend les sessions de terminal *existantes* | ✅ | ❌ | partiel | ❌ |
|
||||||
| 100 % auto-hébergé — zéro trafic via des serveurs tiers | ✅ | ✅ | serveur relais | ❌ relayé via Anthropic |
|
| 100 % auto-hébergé, zéro trafic via des serveurs tiers | ✅ | ✅ | serveur relais | ❌ relayé via Anthropic |
|
||||||
| Linux-first | ✅ | variable | ✅ | l'app desktop n'a pas de build Linux |
|
| Linux-first | ✅ | variable | ✅ | l'app desktop n'a pas de build Linux |
|
||||||
| Open source | MIT | ❌ / partiel | MIT / AGPL | ❌ |
|
| Open source | MIT | ❌ / partiel | MIT / AGPL | ❌ |
|
||||||
|
|
||||||
@@ -227,11 +288,11 @@ Le Remote Control d'Anthropic est excellent pour piloter *une* session depuis vo
|
|||||||
|
|
||||||
## Une note sur l'usage de Claude
|
## Une note sur l'usage de Claude
|
||||||
|
|
||||||
Arboretum enveloppe le CLI Claude Code **interactif** dans un PTY — la même chose que vous lancez dans votre terminal, affichée dans votre navigateur. Il n'utilise pas l'Agent SDK ni le mode headless. Les politiques d'usage d'Anthropic autour de l'usage programmatique peuvent évoluer ; Arboretum suivra les sorties du CLI et documentera tout impact de façon transparente.
|
Arboretum enveloppe le CLI Claude Code **interactif** dans un PTY : la même chose que vous lancez dans votre terminal, affichée dans votre navigateur. Il n'utilise pas l'Agent SDK ni le mode headless. Les politiques d'usage d'Anthropic autour de l'usage programmatique peuvent évoluer ; Arboretum suivra les sorties du CLI et documentera tout impact de façon transparente.
|
||||||
|
|
||||||
## 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)
|
||||||
@@ -249,8 +310,22 @@ node packages/server/scripts/acceptance-p2.mjs # découverte & reprise de sess
|
|||||||
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
|
node packages/server/scripts/acceptance-p5.mjs # groupes de travail : CRUD + broadcast WS + CASCADE
|
||||||
|
node packages/server/scripts/acceptance-p7.mjs # moteur git, API fichiers & watcher FS temps réel
|
||||||
|
node packages/server/scripts/acceptance-p8.mjs # IDE workspace : changes / diff / staging / commit
|
||||||
|
node packages/server/scripts/acceptance-p9.mjs # commit/push avancé : staging sélectif, amend, fetch/pull
|
||||||
|
node packages/server/scripts/acceptance-p10.mjs # archivage automatique des sessions
|
||||||
|
node packages/server/scripts/acceptance-p11.mjs # synchronisation des réglages en temps réel
|
||||||
|
node packages/server/scripts/acceptance-p12.mjs # services git distants + clone HTTPS
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Le protocole s'est enrichi (de façon additive, sans bump de version) pour porter ces nouveautés : messages client `watch` / `unwatch` et signal ciblé `worktree_changes` (P7), plus les broadcasts `session_archived` (P10), `settings_update` (P11) et `clone_update` (P12). Côté serveur, le tout s'appuie sur `core/git.ts` (le moteur git pur), `core/fs-watcher.ts` (chokidar), `core/git-credentials.ts` + `core/clone-manager.ts` (identifiants chiffrés & clone), et les services d'archivage de sessions et de réglages.
|
||||||
|
|
||||||
|
## 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).
|
||||||
|
|||||||
139
README.md
139
README.md
@@ -3,14 +3,16 @@
|
|||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
A self-hosted web dashboard for your git worktrees and the Claude Code sessions running on them — from any device.
|
A self-hosted, multi-project AI IDE for your git worktrees and the Claude Code sessions running on them: a native desktop app and a web UI, from any device.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<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), and work groups (run several related repos at once) 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.
|
||||||
|
|
||||||
|
The latest milestone turns Arboretum into a real **multi-project AI IDE**: a single workspace (route `/ide`, the default view on desktop) that holds **all** your open projects at once, no more one IDE window per project. A single left tree (project, then main checkout and worktrees, then Claude session), a tabbed Monaco editor at the center (several files from different projects side by side, inline diffs), Claude terminals in a bottom dock, and Git / Sessions / Groups panels via an activity bar. It ships both as a **native desktop app** (Linux, Windows, macOS) and the same web UI, backed by a real-time file-system watcher, selective staging / discard / amend / fetch / pull, automatic session archival, real-time settings sync, and encrypted remote git services (GitHub / GitLab / Gitea) with HTTPS clone.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -24,39 +26,43 @@ Working with AI coding agents changed how we use git: one feature = one worktree
|
|||||||
|
|
||||||
## What Arboretum does
|
## What Arboretum does
|
||||||
|
|
||||||
A single Node.js daemon you run on your dev machine (`npx @johanleroy/git-arboretum`), serving a web UI usable from your desktop, phone or tablet:
|
A single Node.js daemon you run on your dev machine (as a native desktop app, or via `npx @johanleroy/git-arboretum`), serving a UI usable from your desktop, phone or tablet:
|
||||||
|
|
||||||
- **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.
|
- **Multi-project IDE**: one workspace for every open project at once (no per-project window). A single tree (project, worktrees, Claude sessions), a tabbed Monaco editor (several files from different projects side by side, with inline per-file diffs), a bottom dock of session terminals, and Git / Sessions / Groups panels. Edit files, stage changes selectively, commit (or amend), fetch/pull and push, all in one place. A real-time file-system watcher keeps the view live as the agent edits. Available as a native desktop app and in the browser.
|
||||||
- **Work groups** — bundle related repos (e.g. an API, its web frontend and a shared library) into a named group to work on them at once: a unified view of all their worktrees and sessions, a side-by-side multi-terminal grid, and a one-click "cross-repo feature" that creates the same branch worktree (and optionally a Claude session) across every repo in the group.
|
- **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.
|
||||||
|
- **Remote git services**: connect your GitHub, GitLab or Gitea accounts (personal access token or app password), stored **encrypted at rest** (AES-256-GCM); browse your remote repositories and clone them over HTTPS with live progress, straight from the dashboard.
|
||||||
|
- **Automatic archival**: finished sessions are archived automatically after a configurable retention window (30 days by default), so the list stays focused on what's live while the history is one toggle away.
|
||||||
|
- **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).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
- **Node.js ≥ 22.16** — required, not just recommended. Arboretum persists state with `node:sqlite` (`DatabaseSync`), which is native and stable only from this version. (`.nvmrc` pins `22`.)
|
- **Node.js ≥ 22.16** for the `npx` / from-source usage: required, not just recommended. Arboretum persists state with `node:sqlite` (`DatabaseSync`), which is native and stable only from this version. (`.nvmrc` pins `22`.) The **desktop app bundles its own Node runtime**, so its end users do not need to install Node.
|
||||||
- **The `claude` CLI** on your `PATH` if you want Arboretum to launch and manage Claude Code sessions. Arboretum wraps the interactive CLI you already use — install and authenticate it as usual.
|
- **The `claude` CLI** on your `PATH` if you want Arboretum to launch and manage Claude Code sessions. Arboretum wraps the interactive CLI you already use, install and authenticate it as usual.
|
||||||
- A **git** repository (or several) you want to manage.
|
- A **git** repository (or several) you want to manage.
|
||||||
|
|
||||||
## Quick start
|
## Quick start
|
||||||
|
|
||||||
Two paths, depending on what you want:
|
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.
|
- **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 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`:
|
||||||
|
|
||||||
```
|
```
|
||||||
@johanleroy:registry=https://git.lidge.fr/api/packages/johanleroy/npm/
|
@johanleroy:registry=https://git.lidge.fr/api/packages/johanleroy/npm/
|
||||||
```
|
```
|
||||||
|
|
||||||
No token needed — the package is publicly readable. Then run it from anywhere:
|
No token needed, the package is publicly readable. Then run it from anywhere:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npx @johanleroy/git-arboretum
|
npx @johanleroy/git-arboretum
|
||||||
@@ -66,7 +72,7 @@ On first start, Arboretum prints a one-time **access token** and the URL to open
|
|||||||
|
|
||||||
```
|
```
|
||||||
┌──────────────────────────────────────────────────────────────────┐
|
┌──────────────────────────────────────────────────────────────────┐
|
||||||
│ First start — your access token (shown once, store it safely): │
|
│ First start · your access token (shown once, store it safely): │
|
||||||
└──────────────────────────────────────────────────────────────────┘
|
└──────────────────────────────────────────────────────────────────┘
|
||||||
|
|
||||||
<your-token-here>
|
<your-token-here>
|
||||||
@@ -74,9 +80,9 @@ On first start, Arboretum prints a one-time **access token** and the URL to open
|
|||||||
Login at: http://127.0.0.1:7317/
|
Login at: http://127.0.0.1:7317/
|
||||||
```
|
```
|
||||||
|
|
||||||
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:
|
`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
|
```bash
|
||||||
npm i -g @johanleroy/git-arboretum
|
npm i -g @johanleroy/git-arboretum
|
||||||
@@ -85,7 +91,7 @@ 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:
|
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
|
||||||
@@ -96,17 +102,58 @@ npm run build # builds shared → server → web (order matters)
|
|||||||
node packages/server/dist/index.js
|
node packages/server/dist/index.js
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Desktop app
|
||||||
|
|
||||||
|
Prefer a native app to the daemon-in-a-terminal? Arboretum ships an **Electron desktop app** (`packages/desktop`) for **Linux, Windows and macOS**. It runs the daemon as a child process and opens its UI in a native window, already signed in (no login screen), and it **bundles its own Node runtime**, so you do not need Node installed to use it.
|
||||||
|
|
||||||
|
- **Install.** Installers are published on the [releases page](https://git.lidge.fr/johanleroy/arboretum/releases) when a desktop release is tagged: an AppImage and a `.deb` on Linux, an NSIS installer (and a portable build) on Windows, a `.dmg` on macOS. Prefer to build them yourself? See [`packages/desktop/README.md`](packages/desktop/README.md).
|
||||||
|
- **First launch.** The app is not code-signed yet: on **Windows**, SmartScreen shows "unknown publisher", choose "More info" then "Run anyway"; on **macOS**, Gatekeeper blocks it, right-click the app then "Open" (or run `xattr -dr com.apple.quarantine /Applications/Arboretum.app`).
|
||||||
|
- **Lives in the tray.** Closing the window keeps Arboretum running in the system tray; quit from the tray menu, where you can also toggle launch-at-login. Auto-update is built in on Windows and Linux (macOS updates are manual while unsigned).
|
||||||
|
|
||||||
|
The desktop app is just a shell around the same daemon and web UI, so everything below (workspace, git, sessions) works identically.
|
||||||
|
|
||||||
## Using Arboretum
|
## Using Arboretum
|
||||||
|
|
||||||
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.
|
||||||
|
|
||||||
|
## The IDE, workspace & git operations
|
||||||
|
|
||||||
|
Beyond supervising, Arboretum is a full **multi-project IDE** (route `/ide`, the default view on desktop). It holds every open project at once, so you never juggle one IDE window per project:
|
||||||
|
|
||||||
|
- **Unified project tree.** A single left tree lists every registered project, its main checkout and worktrees, and the Claude session correlated with each. Expand a worktree to browse its files inline. An activity bar switches the left panel between Explorer, Git, Sessions and Groups.
|
||||||
|
- **Tabbed editor.** Open files in a **Monaco editor** with tabs, several files from **different projects** side by side, syntax highlighting, language detection, save with conflict detection. Each tab toggles between editor and an inline **per-file diff** (working tree or index, additions/deletions colour-coded, binary and huge diffs refused).
|
||||||
|
- **Terminal dock.** Claude session terminals live in a bottom dock with one tab per session; open several at once (across projects), answer a waiting prompt right there. Terminals survive tab switches and browser disconnects.
|
||||||
|
- **Git panel.** Stage or unstage individual files, discard changes, write a message and **commit** (everything or just what's staged), **amend** the last commit (refused once pushed), then **fetch**, **pull** (fast-forward or rebase) and **push**. Detailed staged / unstaged / conflict counts and the last commit stay current via a **real-time file-system watcher**, so the view updates the moment a Claude session touches a file.
|
||||||
|
- **Deep links & mobile.** `/workspace/:repoId/:wt` still opens a specific worktree straight in the IDE (used by the VS Code extension). On mobile the IDE degrades to a single panel, and the worktree dashboard and session views remain the installable supervision PWA.
|
||||||
|
|
||||||
|
Like every git action in Arboretum, these run **as you** (the daemon runs under your account), consistent with the security model: a web terminal is remote code execution by design.
|
||||||
|
|
||||||
|
## 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, **fetch / pull**) with **detailed git status** in the tree (staged / unstaged / conflicts and the last commit), and **workspace awareness**: the worktree for your open folder is highlighted, with one-click "start session / create worktree here".
|
||||||
|
- **Open in the web IDE**: jump from any worktree straight to its full `/workspace` view in the browser. The extension stays a lightweight, visual worktree manager; the heavy editing lives in the web IDE.
|
||||||
|
|
||||||
|
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.2.0.vsix
|
||||||
|
```
|
||||||
|
|
||||||
|
Then install it via **Extensions: Install from VSIX…** (or `code --install-extension git-arboretum-0.2.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
|
||||||
|
|
||||||
Arboretum binds to `127.0.0.1` by default and **refuses** to bind to a non-loopback address without an explicit override. The recommended (and safe) way to reach it from other devices is **[Tailscale Serve](https://tailscale.com/kb/1242/tailscale-serve)** — valid HTTPS, tailnet identity, no open ports:
|
Arboretum binds to `127.0.0.1` by default and **refuses** to bind to a non-loopback address without an explicit override. The recommended (and safe) way to reach it from other devices is **[Tailscale Serve](https://tailscale.com/kb/1242/tailscale-serve)**, valid HTTPS, tailnet identity, no open ports:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Expose the local daemon over HTTPS inside your tailnet
|
# Expose the local daemon over HTTPS inside your tailnet
|
||||||
@@ -125,7 +172,7 @@ 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
|
||||||
|
|
||||||
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:
|
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
|
```bash
|
||||||
npm i -g @johanleroy/git-arboretum
|
npm i -g @johanleroy/git-arboretum
|
||||||
@@ -148,7 +195,7 @@ Create `~/.config/systemd/user/arboretum.service`:
|
|||||||
|
|
||||||
```ini
|
```ini
|
||||||
[Unit]
|
[Unit]
|
||||||
Description=Arboretum — git worktree & Claude Code dashboard
|
Description=Arboretum · git worktree & Claude Code dashboard
|
||||||
After=network-online.target
|
After=network-online.target
|
||||||
Wants=network-online.target
|
Wants=network-online.target
|
||||||
|
|
||||||
@@ -173,7 +220,7 @@ journalctl --user -u arboretum -f # logs
|
|||||||
```
|
```
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
> 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.
|
> 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
|
||||||
|
|
||||||
@@ -185,11 +232,11 @@ Daemon options are CLI flags:
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `--port <n>` | `7317` | Port to listen on. |
|
| `--port <n>` | `7317` | Port to listen on. |
|
||||||
| `--bind <addr>` | `127.0.0.1` | Bind address. Non-loopback is refused unless `--i-know-this-exposes-a-terminal` is set. |
|
| `--bind <addr>` | `127.0.0.1` | Bind address. Non-loopback is refused unless `--i-know-this-exposes-a-terminal` is set. |
|
||||||
| `--allow-origin <url>` | — | Additional allowed `Origin` (repeatable). Needed for Tailscale/HTTPS access. |
|
| `--allow-origin <url>` | none | Additional allowed `Origin` (repeatable). Needed for Tailscale/HTTPS access. |
|
||||||
| `--db <path>` | `<data>/arboretum.db` | SQLite database path. |
|
| `--db <path>` | `<data>/arboretum.db` | SQLite database path. |
|
||||||
| `--vapid-contact <mailto/url>` | `mailto:arboretum@localhost` | VAPID contact subject for Web Push. |
|
| `--vapid-contact <mailto/url>` | `mailto:arboretum@localhost` | VAPID contact subject for Web Push. |
|
||||||
| `--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:
|
`arboretum install` accepts every daemon flag above (propagated verbatim to the service) plus:
|
||||||
|
|
||||||
@@ -202,15 +249,29 @@ Daemon options are CLI flags:
|
|||||||
|
|
||||||
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`).
|
||||||
|
|
||||||
|
Settings beyond CLI flags (the directories Arboretum scans for repos and how often, the `claude` binary path and home, and the session retention / purge windows) live in **Settings** in the UI. They are broadcast over the WebSocket, so every connected browser reflects a change in real time, no reload needed.
|
||||||
|
|
||||||
|
## Remote git services & clone
|
||||||
|
|
||||||
|
Arboretum can connect to your git hosting providers so you can browse and clone repositories without leaving the dashboard:
|
||||||
|
|
||||||
|
- **Providers & auth.** GitHub, GitLab and Gitea, authenticated with a **personal access token** or an **app password** (SSH keys and OAuth are planned). Add a connection from **Settings → Git services**, give it a label, and test it in place: Arboretum reports `ok`, `auth failed`, `rate limited` or `unreachable`.
|
||||||
|
- **Secrets stay secret.** Credentials are **encrypted at rest** (AES-256-GCM, `SecretBox`) and **never** returned in clear by the REST API: responses carry only a `…last4` hint and a "has secret" flag.
|
||||||
|
- **Browse & clone.** List the repositories a connection can see, pick one, and clone it over HTTPS into a destination of your choice. The clone runs as a tracked operation with live **progress and phase** pushed over the WebSocket, and the new repo is registered automatically when it completes.
|
||||||
|
|
||||||
## Security model
|
## Security model
|
||||||
|
|
||||||
A web terminal is remote code execution *by design*. Arboretum's guardrails are structural:
|
A web terminal is remote code execution *by design*. Arboretum's guardrails are structural:
|
||||||
|
|
||||||
- Binds to `127.0.0.1` by default; refuses non-loopback binds without an explicit flag.
|
- Binds to `127.0.0.1` by default; refuses non-loopback binds without an explicit flag.
|
||||||
- Authenticates **every** `/api/**` request **and** every `/ws` upgrade with revocable tokens, and applies a **strict `Origin` check** (the `SameSite=Strict` cookie does not cover WebSocket upgrades — this is the anti cross-site hijacking guard).
|
- Authenticates **every** `/api/**` request **and** every `/ws` upgrade with revocable tokens, and applies a **strict `Origin` check** (the `SameSite=Strict` cookie does not cover WebSocket upgrades: this is the anti cross-site hijacking guard).
|
||||||
- Tokens are stored **hashed** (sha256) and compared in constant time; the bootstrap token is shown only once. The session cookie is an HMAC-signed payload, `HttpOnly` and `SameSite=Strict`, and it automatically gains the `Secure` flag when the request arrives over HTTPS (e.g. behind Tailscale Serve). Login is rate-limited with exponential backoff.
|
- Tokens are stored **hashed** (sha256) and compared in constant time; the bootstrap token is shown only once. The session cookie is an HMAC-signed payload, `HttpOnly` and `SameSite=Strict`, and it automatically gains the `Secure` flag when the request arrives over HTTPS (e.g. behind Tailscale Serve). Login is rate-limited with exponential backoff.
|
||||||
|
- Sends hardened HTTP headers (CSP, `X-Frame-Options`, `nosniff`, `Referrer-Policy`, conditional HSTS, `no-store` on the API), restricts the data directory to `0o700` and the database to `0o600`, and **encrypts sensitive secrets at rest** (AES-256-GCM).
|
||||||
|
- Keeps an **audit log** of sensitive operations and offers **GDPR** data export/erasure (Settings → Security & compliance).
|
||||||
|
|
||||||
Tailscale Serve is **the** way to reach Arboretum from other devices — not just a recommendation: valid HTTPS, tailnet identity, no open ports. The `--i-know-this-exposes-a-terminal` flag is an escape hatch, not a deployment mode; never expose Arboretum directly to the internet.
|
Tailscale Serve is **the** way to reach Arboretum from other devices, not just a recommendation: valid HTTPS, tailnet identity, no open ports. The `--i-know-this-exposes-a-terminal` flag is an escape hatch, not a deployment mode; never expose Arboretum directly to the internet.
|
||||||
|
|
||||||
|
See [`SECURITY.md`](SECURITY.md) for the full threat model and [`docs/ENTERPRISE_DEPLOYMENT.md`](docs/ENTERPRISE_DEPLOYMENT.md) for hardening in regulated environments.
|
||||||
|
|
||||||
## What makes it different
|
## What makes it different
|
||||||
|
|
||||||
@@ -219,7 +280,7 @@ Tailscale Serve is **the** way to reach Arboretum from other devices — not jus
|
|||||||
| Web UI, any device | ✅ | ❌ desktop apps | ✅ | ✅ |
|
| Web UI, any device | ✅ | ❌ desktop apps | ✅ | ✅ |
|
||||||
| Visual worktree management (multi-repo) | ✅ | ✅ (single repo, desktop) | ❌ | ❌ |
|
| Visual worktree management (multi-repo) | ✅ | ✅ (single repo, desktop) | ❌ | ❌ |
|
||||||
| Discovers & resumes *existing* terminal sessions | ✅ | ❌ | partial | ❌ |
|
| Discovers & resumes *existing* terminal sessions | ✅ | ❌ | partial | ❌ |
|
||||||
| 100% self-hosted — zero traffic through third-party servers | ✅ | ✅ | relay server | ❌ relayed through Anthropic |
|
| 100% self-hosted, zero traffic through third-party servers | ✅ | ✅ | relay server | ❌ relayed through Anthropic |
|
||||||
| Linux-first | ✅ | varies | ✅ | Desktop app has no Linux build |
|
| Linux-first | ✅ | varies | ✅ | Desktop app has no Linux build |
|
||||||
| Open source | MIT | ❌ / partial | MIT / AGPL | ❌ |
|
| Open source | MIT | ❌ / partial | MIT / AGPL | ❌ |
|
||||||
|
|
||||||
@@ -227,11 +288,11 @@ Anthropic's Remote Control is great at piloting *one* session from your phone. A
|
|||||||
|
|
||||||
## A note on Claude usage
|
## A note on Claude usage
|
||||||
|
|
||||||
Arboretum wraps the **interactive** Claude Code CLI in a PTY — the same thing you run in your terminal, displayed in your browser. It does not use the Agent SDK or headless mode. Anthropic's usage policies around programmatic use may evolve; Arboretum will track CLI releases and document any impact transparently.
|
Arboretum wraps the **interactive** Claude Code CLI in a PTY: the same thing you run in your terminal, displayed in your browser. It does not use the Agent SDK or headless mode. Anthropic's usage policies around programmatic use may evolve; Arboretum will track CLI releases and document any impact transparently.
|
||||||
|
|
||||||
## 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)
|
||||||
@@ -249,8 +310,22 @@ 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
|
node packages/server/scripts/acceptance-p5.mjs # work groups: CRUD + WS broadcast + CASCADE
|
||||||
|
node packages/server/scripts/acceptance-p7.mjs # git engine, file API & real-time FS watcher
|
||||||
|
node packages/server/scripts/acceptance-p8.mjs # workspace IDE: changes / diff / staging / commit
|
||||||
|
node packages/server/scripts/acceptance-p9.mjs # advanced commit/push: selective staging, amend, fetch/pull
|
||||||
|
node packages/server/scripts/acceptance-p10.mjs # automatic session archival
|
||||||
|
node packages/server/scripts/acceptance-p11.mjs # real-time settings sync
|
||||||
|
node packages/server/scripts/acceptance-p12.mjs # remote git services + HTTPS clone
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The protocol grew (additively, no version bump) to carry the new surface: client `watch` / `unwatch` messages and the targeted `worktree_changes` signal (P7), plus `session_archived` (P10), `settings_update` (P11) and `clone_update` (P12) broadcasts. Server-side, the work is backed by `core/git.ts` (the pure git engine), `core/fs-watcher.ts` (chokidar), `core/git-credentials.ts` + `core/clone-manager.ts` (encrypted credentials & clone), and the session-archive and settings services.
|
||||||
|
|
||||||
|
## 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.
|
||||||
@@ -7,8 +7,8 @@ branches, cyan session nodes, a `>_` prompt at the base) on a dark background.
|
|||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `arboretum-logo-source.png` | Master artwork (opaque dark background). Keep; everything else derives from it. |
|
| `arboretum-logo-source.png` | Master artwork (opaque dark background). Keep; everything else derives from it. |
|
||||||
| `arboretum-logo.png` | Full logo, **transparent**. Best on dark surfaces (the wordmark is light). |
|
| `arboretum-logo.png` | Full logo, **transparent**. Best on dark surfaces (the wordmark is light). |
|
||||||
| `arboretum-logo-on-dark.png` | Full logo on the app background `#09090b`. Safe on any theme — used in the README. |
|
| `arboretum-logo-on-dark.png` | Full logo on the app background `#09090b`. Safe on any theme, used in the README. |
|
||||||
| `arboretum-mark.png` | Square, **transparent**, tree only (no wordmark). Ideal **Gitea repo avatar** — reads on both light and dark. |
|
| `arboretum-mark.png` | Square, **transparent**, tree only (no wordmark). Ideal **Gitea repo avatar**, reads on both light and dark. |
|
||||||
|
|
||||||
The transparent versions are extracted by luminance (alpha ∝ brightness), the clean
|
The transparent versions are extracted by luminance (alpha ∝ brightness), the clean
|
||||||
way to lift glow-on-black artwork: the dark background becomes fully transparent, the
|
way to lift glow-on-black artwork: the dark background becomes fully transparent, the
|
||||||
@@ -26,11 +26,11 @@ when the surrounding background might be light.
|
|||||||
|
|
||||||
The web-facing assets live in `packages/web/public/` and are wired into the SPA:
|
The web-facing assets live in `packages/web/public/` and are wired into the SPA:
|
||||||
|
|
||||||
- `icon.svg` — scalable favicon, redrawn to match the brand (vector, glow, `>_`).
|
- `icon.svg`: scalable favicon, redrawn to match the brand (vector, glow, `>_`).
|
||||||
- `icon-192.png` / `icon-512.png` — maskable PWA icons (tree on `#09090b`, content in the safe zone).
|
- `icon-192.png` / `icon-512.png`: maskable PWA icons (tree on `#09090b`, content in the safe zone).
|
||||||
- `apple-touch-icon.png` — iOS home-screen icon (180×180).
|
- `apple-touch-icon.png`: iOS home-screen icon (180×180).
|
||||||
- `favicon.ico` — multi-size favicon (16/32/48), transparent.
|
- `favicon.ico`: multi-size favicon (16/32/48), transparent.
|
||||||
- `logo.png` — transparent full logo for in-app use.
|
- `logo.png`: transparent full logo for in-app use.
|
||||||
|
|
||||||
## Regenerate
|
## Regenerate
|
||||||
|
|
||||||
|
|||||||
@@ -5,11 +5,11 @@ Source : un PNG « néon sur fond sombre » (arbre-circuit + texte « Arboretum
|
|||||||
On extrait l'alpha par luminance (méthode propre pour ce type d'artwork glow-on-black) :
|
On extrait l'alpha par luminance (méthode propre pour ce type d'artwork glow-on-black) :
|
||||||
chaque pixel reçoit une transparence proportionnelle à sa luminosité, ce qui rend le
|
chaque pixel reçoit une transparence proportionnelle à sa luminosité, ce qui rend le
|
||||||
fond sombre totalement transparent, garde le cœur des traits opaque et conserve le halo
|
fond sombre totalement transparent, garde le cœur des traits opaque et conserve le halo
|
||||||
en semi-transparent — donc lisible sur n'importe quel fond.
|
en semi-transparent, donc lisible sur n'importe quel fond.
|
||||||
|
|
||||||
Sorties :
|
Sorties :
|
||||||
brand/arboretum-logo.png logo complet transparent (haute déf) — Gitea / README
|
brand/arboretum-logo.png logo complet transparent (haute déf) : Gitea / README
|
||||||
brand/arboretum-mark.png marque carrée transparente (arbre seul) — avatar Gitea
|
brand/arboretum-mark.png marque carrée transparente (arbre seul) : avatar Gitea
|
||||||
brand/arboretum-logo-on-dark.png logo complet sur fond #09090b (fallback fond clair)
|
brand/arboretum-logo-on-dark.png logo complet sur fond #09090b (fallback fond clair)
|
||||||
packages/web/public/logo.png logo complet transparent, optimisé pour l'UI
|
packages/web/public/logo.png logo complet transparent, optimisé pour l'UI
|
||||||
packages/web/public/icon-192.png icône PWA maskable (arbre, fond #09090b)
|
packages/web/public/icon-192.png icône PWA maskable (arbre, fond #09090b)
|
||||||
@@ -24,7 +24,7 @@ import numpy as np
|
|||||||
from PIL import Image
|
from PIL import Image
|
||||||
|
|
||||||
SRC = sys.argv[1] if len(sys.argv) > 1 else "brand/arboretum-logo-source.png"
|
SRC = sys.argv[1] if len(sys.argv) > 1 else "brand/arboretum-logo-source.png"
|
||||||
BG = (9, 9, 11) # #09090b — couleur de fond du dashboard (manifest background_color/theme_color)
|
BG = (9, 9, 11) # #09090b : couleur de fond du dashboard (manifest background_color/theme_color)
|
||||||
|
|
||||||
# Découpe verticale arbre / texte (mesurée sur la source)
|
# Découpe verticale arbre / texte (mesurée sur la source)
|
||||||
TREE_Y = (130, 930) # arbre + curseur >_
|
TREE_Y = (130, 930) # arbre + curseur >_
|
||||||
|
|||||||
101
docs/ENTERPRISE_DEPLOYMENT.md
Normal file
101
docs/ENTERPRISE_DEPLOYMENT.md
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
|
> **Desktop app.** The Electron desktop app (`packages/desktop`) is an additive, self-contained
|
||||||
|
> client: it runs its own local daemon (child process) bound to `127.0.0.1` and shows the same web
|
||||||
|
> UI. It does not change the server deployment below; a shared or service daemon (systemd/launchd,
|
||||||
|
> reached over Tailscale Serve) is deployed exactly as described here, independently of whether
|
||||||
|
> developers also use the desktop app on their own machines.
|
||||||
|
|
||||||
|
## 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.
|
||||||
3755
package-lock.json
generated
3755
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
13
package.json
13
package.json
@@ -4,7 +4,11 @@
|
|||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"workspaces": [
|
"workspaces": [
|
||||||
"packages/*"
|
"packages/shared",
|
||||||
|
"packages/server",
|
||||||
|
"packages/web",
|
||||||
|
"packages/site",
|
||||||
|
"packages/vscode"
|
||||||
],
|
],
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=22.16"
|
"node": ">=22.16"
|
||||||
@@ -15,7 +19,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",
|
||||||
|
|||||||
4
packages/desktop/.gitignore
vendored
Normal file
4
packages/desktop/.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
build/
|
||||||
|
release/
|
||||||
79
packages/desktop/README.md
Normal file
79
packages/desktop/README.md
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
# Arboretum Desktop
|
||||||
|
|
||||||
|
Native desktop shell (Electron) for Arboretum. It runs the existing daemon as a child process and
|
||||||
|
shows its web UI in a window, already authenticated (no login screen). The heavy lifting stays in
|
||||||
|
the daemon; this package is a thin shell (window lifecycle, daemon supervision, auto auth).
|
||||||
|
|
||||||
|
This package is intentionally **outside the root npm workspaces** so the daemon CI stays light. It
|
||||||
|
has its own `package-lock.json` and is built on a developer machine (or a dedicated CI runner),
|
||||||
|
not by the main `npm run build`.
|
||||||
|
|
||||||
|
## How it works
|
||||||
|
|
||||||
|
1. The shell picks a data directory under the OS user-data path and spawns the bundled Node runtime
|
||||||
|
running the packaged daemon (`build/server/package/dist/index.js`) with `ARBORETUM_EMIT_TOKEN_FD=3`.
|
||||||
|
2. The daemon mints a fresh token and writes `{token, url}` on file descriptor 3 (private stdio pipe).
|
||||||
|
3. The shell posts that token to `/api/v1/auth/login` from the window's session (server to server),
|
||||||
|
which drops the `arb_session` cookie into the session jar, then loads the SPA on `127.0.0.1`.
|
||||||
|
4. On quit, the daemon child gets `SIGTERM` (then `SIGKILL` after a grace delay).
|
||||||
|
|
||||||
|
A standalone Node runtime (pinned, >= 22.16) is bundled instead of reusing Electron's Node, so
|
||||||
|
`node:sqlite` works without a flag and the `node-pty` prebuild keeps the `node.` ABI prefix.
|
||||||
|
|
||||||
|
## Prerequisites (all platforms)
|
||||||
|
|
||||||
|
- Node >= 22.16 to build.
|
||||||
|
- `git` on PATH at runtime (worktree operations). `claude` is discovered on PATH or via the
|
||||||
|
in-app Claude CLI setting; it is not bundled.
|
||||||
|
|
||||||
|
## Develop
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd packages/desktop
|
||||||
|
npm install # ELECTRON_SKIP_BINARY_DOWNLOAD=1 to skip the Electron binary if you only typecheck
|
||||||
|
npm run dev # bundles main/preload, then `electron .` against the repo's built daemon
|
||||||
|
```
|
||||||
|
|
||||||
|
`npm run dev` runs the daemon from the repo (`packages/server/dist`, so run `npm run build` at the
|
||||||
|
repo root first) using the system `node`.
|
||||||
|
|
||||||
|
## Build installers
|
||||||
|
|
||||||
|
Each command builds the shell, prepares the daemon (`npm pack` + runtime deps with the right
|
||||||
|
`node-pty` prebuild) and a standalone Node runtime, then runs electron-builder.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run dist:linux # AppImage + .deb (on Linux)
|
||||||
|
npm run dist:win # NSIS + portable (on Windows)
|
||||||
|
npm run dist:mac # dmg + zip (on macOS)
|
||||||
|
```
|
||||||
|
|
||||||
|
Artifacts land in `packages/desktop/release/`.
|
||||||
|
|
||||||
|
### Linux
|
||||||
|
|
||||||
|
Fully supported. `dist:linux` runs on a Linux host or the Gitea CI runner.
|
||||||
|
|
||||||
|
### Windows
|
||||||
|
|
||||||
|
Build on a Windows host (recommended): the `node-pty` win32 native binary and the installer
|
||||||
|
(`makensis`) are most reliable there. Cross-building from Linux via Wine is a best-effort fallback.
|
||||||
|
The app uses ConPTY (Windows 10 1809+). The installer is not code-signed yet, so SmartScreen shows
|
||||||
|
"unknown publisher": choose "More info" then "Run anyway".
|
||||||
|
|
||||||
|
### macOS (best-effort)
|
||||||
|
|
||||||
|
Build on a Mac (`dmg`/`zip` cannot be produced elsewhere). The app is **not** signed or notarized,
|
||||||
|
so Gatekeeper blocks the first launch: right-click the app then "Open", or run
|
||||||
|
`xattr -dr com.apple.quarantine /Applications/Arboretum.app`.
|
||||||
|
|
||||||
|
## Auto-update
|
||||||
|
|
||||||
|
electron-builder emits `latest*.yml` next to the artifacts; `electron-updater` (wired in a later
|
||||||
|
change) points at the Gitea release assets. Auto-update works for Windows (NSIS) and Linux
|
||||||
|
(AppImage); macOS updates are manual while the app is unsigned.
|
||||||
|
|
||||||
|
## Icon
|
||||||
|
|
||||||
|
`resources/icon.png` (square, >= 512px) is the single source; electron-builder derives every
|
||||||
|
platform icon from it.
|
||||||
60
packages/desktop/electron-builder.yml
Normal file
60
packages/desktop/electron-builder.yml
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
appId: fr.lidge.arboretum
|
||||||
|
productName: Arboretum
|
||||||
|
copyright: Copyright Johan Leroy
|
||||||
|
|
||||||
|
directories:
|
||||||
|
output: release
|
||||||
|
buildResources: resources
|
||||||
|
|
||||||
|
# Le bundle esbuild (dist/) va dans l'ASAR ; le daemon et le runtime Node restent des fichiers
|
||||||
|
# reels sur disque (extraResources, hors ASAR) : les binaires natifs (.node de node-pty) se
|
||||||
|
# chargent proprement, ce qu'un .asar interdirait.
|
||||||
|
files:
|
||||||
|
- dist/**/*
|
||||||
|
- "!**/*.map"
|
||||||
|
asar: true
|
||||||
|
|
||||||
|
extraResources:
|
||||||
|
- from: build/server
|
||||||
|
to: server
|
||||||
|
- from: build/node
|
||||||
|
to: node
|
||||||
|
- from: resources/icon.png
|
||||||
|
to: icon.png
|
||||||
|
|
||||||
|
# Icône : electron-builder dérive toutes les tailles/formats par OS depuis resources/icon.png
|
||||||
|
# (buildResources), pas besoin de .ico/.icns séparés.
|
||||||
|
linux:
|
||||||
|
target: [AppImage, deb]
|
||||||
|
category: Development
|
||||||
|
artifactName: ${productName}-${version}-${arch}.${ext}
|
||||||
|
|
||||||
|
deb:
|
||||||
|
# git est requis pour les operations de worktree ; claude n'est pas dans les depots (documente).
|
||||||
|
depends: [git]
|
||||||
|
|
||||||
|
win:
|
||||||
|
target:
|
||||||
|
- target: nsis
|
||||||
|
arch: [x64]
|
||||||
|
- target: portable
|
||||||
|
arch: [x64]
|
||||||
|
artifactName: ${productName}-${version}-${arch}.${ext}
|
||||||
|
|
||||||
|
nsis:
|
||||||
|
oneClick: false
|
||||||
|
perMachine: false
|
||||||
|
allowToChangeInstallationDirectory: true
|
||||||
|
|
||||||
|
mac:
|
||||||
|
target: [dmg, zip]
|
||||||
|
category: public.app-category.developer-tools
|
||||||
|
# macOS best-effort : non signe (documente : clic droit -> Ouvrir, ou xattr -dr com.apple.quarantine)
|
||||||
|
identity: null
|
||||||
|
hardenedRuntime: false
|
||||||
|
|
||||||
|
# Auto-update (electron-updater, cable en C5) : provider generic pointant sur les assets de release
|
||||||
|
# Gitea. Genere latest*.yml a cote des artefacts.
|
||||||
|
publish:
|
||||||
|
provider: generic
|
||||||
|
url: https://git.lidge.fr/johanleroy/arboretum/releases/download/desktop-latest
|
||||||
24
packages/desktop/esbuild.mjs
Normal file
24
packages/desktop/esbuild.mjs
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
// Bundle du process principal + preload en CJS (comme l'extension VS Code). `electron` reste
|
||||||
|
// externe (fourni par le runtime Electron) ; les modules node natifs sont externes par platform:node.
|
||||||
|
import esbuild from 'esbuild';
|
||||||
|
|
||||||
|
const watch = process.argv.includes('--watch');
|
||||||
|
|
||||||
|
const options = {
|
||||||
|
entryPoints: { main: 'src/main/main.ts', preload: 'src/preload/preload.ts' },
|
||||||
|
outdir: 'dist',
|
||||||
|
bundle: true,
|
||||||
|
platform: 'node',
|
||||||
|
format: 'cjs',
|
||||||
|
target: 'node18',
|
||||||
|
sourcemap: true,
|
||||||
|
external: ['electron'],
|
||||||
|
logLevel: 'info',
|
||||||
|
};
|
||||||
|
|
||||||
|
if (watch) {
|
||||||
|
const ctx = await esbuild.context(options);
|
||||||
|
await ctx.watch();
|
||||||
|
} else {
|
||||||
|
await esbuild.build(options);
|
||||||
|
}
|
||||||
5835
packages/desktop/package-lock.json
generated
Normal file
5835
packages/desktop/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
26
packages/desktop/package.json
Normal file
26
packages/desktop/package.json
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"name": "@arboretum/desktop",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.1.0",
|
||||||
|
"description": "Arboretum desktop app: Electron shell that runs the daemon and shows its web UI",
|
||||||
|
"main": "dist/main.js",
|
||||||
|
"type": "commonjs",
|
||||||
|
"scripts": {
|
||||||
|
"typecheck": "tsc -p . --noEmit",
|
||||||
|
"build": "npm run typecheck && node esbuild.mjs",
|
||||||
|
"dev": "node esbuild.mjs && electron .",
|
||||||
|
"prepare:server": "node scripts/prepare-server.mjs",
|
||||||
|
"prepare:node": "node scripts/fetch-node.mjs",
|
||||||
|
"dist:linux": "npm run build && npm run prepare:server -- --platform=linux && npm run prepare:node -- --platform=linux && electron-builder --linux",
|
||||||
|
"dist:win": "npm run build && npm run prepare:server -- --platform=win32 && npm run prepare:node -- --platform=win32 && electron-builder --win",
|
||||||
|
"dist:mac": "npm run build && npm run prepare:server -- --platform=darwin && npm run prepare:node -- --platform=darwin && electron-builder --mac"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^22.10.0",
|
||||||
|
"electron": "^33.0.0",
|
||||||
|
"electron-builder": "^25.1.0",
|
||||||
|
"electron-updater": "^6.3.0",
|
||||||
|
"esbuild": "^0.21.0",
|
||||||
|
"typescript": "^5.7.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
BIN
packages/desktop/resources/icon.png
Normal file
BIN
packages/desktop/resources/icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 184 KiB |
49
packages/desktop/scripts/fetch-node.mjs
Normal file
49
packages/desktop/scripts/fetch-node.mjs
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
// Télécharge un runtime Node standalone (>= 22.16, épinglé) dans build/node, avec vérification
|
||||||
|
// SHA256. Le daemon tourne SUR ce Node (pas celui d'Electron) pour garantir node:sqlite sans flag
|
||||||
|
// et l'ABI node-pty attendue (prefixe `node.`). Options : --platform / --arch (défaut : hôte).
|
||||||
|
import { execFileSync } from 'node:child_process';
|
||||||
|
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
||||||
|
import { createHash } from 'node:crypto';
|
||||||
|
import { join, dirname } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const NODE_VERSION = '22.21.1';
|
||||||
|
const HERE = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const BUILD = join(HERE, '..', 'build');
|
||||||
|
const NODE_DIR = join(BUILD, 'node');
|
||||||
|
|
||||||
|
const args = process.argv.slice(2);
|
||||||
|
const arg = (name, def) => args.find((a) => a.startsWith(`--${name}=`))?.split('=')[1] ?? def;
|
||||||
|
const platform = arg('platform', process.platform);
|
||||||
|
const arch = arg('arch', process.arch);
|
||||||
|
|
||||||
|
const OS = { linux: 'linux', darwin: 'darwin', win32: 'win' }[platform];
|
||||||
|
if (!OS) throw new Error(`plateforme non supportee: ${platform}`);
|
||||||
|
const ext = platform === 'win32' ? 'zip' : 'tar.xz';
|
||||||
|
const name = `node-v${NODE_VERSION}-${OS}-${arch}`;
|
||||||
|
const base = `https://nodejs.org/dist/v${NODE_VERSION}`;
|
||||||
|
|
||||||
|
async function get(url) {
|
||||||
|
const res = await fetch(url);
|
||||||
|
if (!res.ok) throw new Error(`GET ${url} -> ${res.status}`);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
rmSync(NODE_DIR, { recursive: true, force: true });
|
||||||
|
mkdirSync(NODE_DIR, { recursive: true });
|
||||||
|
|
||||||
|
const tarball = Buffer.from(await (await get(`${base}/${name}.${ext}`)).arrayBuffer());
|
||||||
|
const shasums = await (await get(`${base}/SHASUMS256.txt`)).text();
|
||||||
|
const expected = shasums.split('\n').find((l) => l.endsWith(`${name}.${ext}`))?.split(/\s+/)[0];
|
||||||
|
const actual = createHash('sha256').update(tarball).digest('hex');
|
||||||
|
if (!expected) throw new Error(`SHA introuvable pour ${name}.${ext}`);
|
||||||
|
if (expected !== actual) throw new Error(`SHA256 mismatch pour ${name}.${ext}`);
|
||||||
|
|
||||||
|
const archive = join(BUILD, `${name}.${ext}`);
|
||||||
|
writeFileSync(archive, tarball);
|
||||||
|
if (ext === 'zip') execFileSync('unzip', ['-q', archive, '-d', BUILD], { stdio: 'inherit' });
|
||||||
|
else execFileSync('tar', ['-xJf', archive, '-C', BUILD], { stdio: 'inherit' });
|
||||||
|
// aplatir node-vX-os-arch/ -> build/node/
|
||||||
|
execFileSync('bash', ['-c', `cp -R "${join(BUILD, name)}/." "${NODE_DIR}/" && rm -rf "${join(BUILD, name)}" "${archive}"`], { stdio: 'inherit' });
|
||||||
|
|
||||||
|
console.log(`fetch-node: Node ${NODE_VERSION} (${OS}-${arch}) -> build/node`);
|
||||||
56
packages/desktop/scripts/prepare-server.mjs
Normal file
56
packages/desktop/scripts/prepare-server.mjs
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
// Prépare le daemon pour l'empaquetage Electron : réutilise INTÉGRALEMENT le pipeline npm du paquet
|
||||||
|
// publié (hooks prepack copy-web / inline-shared / copy-meta), donc aucune divergence de code.
|
||||||
|
// 1) build (shared + server + web) puis `npm pack` -> tarball 100 % autonome
|
||||||
|
// 2) extraction dans build/server/package
|
||||||
|
// 3) `npm install --omit=dev` -> deps runtime (node-pty avec le prebuild de la plateforme cible)
|
||||||
|
// Options : --platform=win32|darwin|linux et --arch=x64|arm64 pour un prebuild node-pty croisé
|
||||||
|
// (via npm_config_platform / npm_config_arch au moment du npm install).
|
||||||
|
import { execFileSync } from 'node:child_process';
|
||||||
|
import { mkdirSync, rmSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||||
|
import { join, dirname } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const HERE = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const DESKTOP = join(HERE, '..');
|
||||||
|
const REPO = join(DESKTOP, '..', '..');
|
||||||
|
const SERVER_DIR = join(DESKTOP, 'build', 'server');
|
||||||
|
|
||||||
|
const args = process.argv.slice(2);
|
||||||
|
const arg = (name) => args.find((a) => a.startsWith(`--${name}=`))?.split('=')[1];
|
||||||
|
const platform = arg('platform');
|
||||||
|
const arch = arg('arch');
|
||||||
|
|
||||||
|
const run = (cmd, cmdArgs, cwd, env) =>
|
||||||
|
execFileSync(cmd, cmdArgs, { cwd, stdio: 'inherit', env: { ...process.env, ...env } });
|
||||||
|
|
||||||
|
rmSync(SERVER_DIR, { recursive: true, force: true });
|
||||||
|
mkdirSync(SERVER_DIR, { recursive: true });
|
||||||
|
|
||||||
|
// 1) build + pack (le tarball embarque dist + _shared inliné + public via prepack).
|
||||||
|
// Rebuild FORCÉ de shared+server : le prepack (inline-shared) mute le dist du serveur en place
|
||||||
|
// (imports réécrits vers ./_shared) ; un tsc -b incrémental ne le régénère pas au run suivant,
|
||||||
|
// d'où un pack qui échoue. --force garantit un dist propre à imports bare avant chaque pack.
|
||||||
|
run('npx', ['tsc', '-b', '--force', 'packages/shared', 'packages/server'], REPO);
|
||||||
|
run('npm', ['run', 'build', '-w', '@arboretum/web'], REPO);
|
||||||
|
run('npm', ['pack', '-w', '@johanleroy/git-arboretum', '--pack-destination', SERVER_DIR], REPO);
|
||||||
|
|
||||||
|
// 2) extraire le tarball -> build/server/package
|
||||||
|
const tgz = readdirSync(SERVER_DIR).find((f) => f.endsWith('.tgz'));
|
||||||
|
if (!tgz) throw new Error('tarball introuvable apres npm pack');
|
||||||
|
run('tar', ['-xzf', join(SERVER_DIR, tgz), '-C', SERVER_DIR]);
|
||||||
|
rmSync(join(SERVER_DIR, tgz));
|
||||||
|
|
||||||
|
// 3) deps runtime (node-pty prebuild). Cross-compile via npm_config_platform/arch si demandé.
|
||||||
|
const pkgDir = join(SERVER_DIR, 'package');
|
||||||
|
// Retirer les devDependencies du paquet extrait : inutiles au runtime, et @arboretum/shared
|
||||||
|
// (workspace non publié, déjà inliné dans dist/_shared) n'existe sur aucun registre -> 404.
|
||||||
|
const pkgJsonPath = join(pkgDir, 'package.json');
|
||||||
|
const pj = JSON.parse(readFileSync(pkgJsonPath, 'utf8'));
|
||||||
|
delete pj.devDependencies;
|
||||||
|
writeFileSync(pkgJsonPath, `${JSON.stringify(pj, null, 2)}\n`);
|
||||||
|
const env = {};
|
||||||
|
if (platform) env.npm_config_platform = platform;
|
||||||
|
if (arch) env.npm_config_arch = arch;
|
||||||
|
run('npm', ['install', '--omit=dev', '--no-audit', '--no-fund'], pkgDir, env);
|
||||||
|
|
||||||
|
console.log(`prepare-server: build/server/package pret${platform ? ` (${platform}-${arch ?? 'host'})` : ''}`);
|
||||||
16
packages/desktop/src/main/auth.ts
Normal file
16
packages/desktop/src/main/auth.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
import { session } from 'electron';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pose le cookie de session dans la partition du renderer, sans écran de login : login
|
||||||
|
* server-to-server depuis la session Electron cible (le Set-Cookie atterrit dans son jar), avec le
|
||||||
|
* token frais reçu au handshake. Le token ne transite jamais par le renderer.
|
||||||
|
*/
|
||||||
|
export async function seedSessionCookie(partition: string, url: string, token: string): Promise<void> {
|
||||||
|
const ses = session.fromPartition(partition);
|
||||||
|
const res = await ses.fetch(`${url}/api/v1/auth/login`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
body: JSON.stringify({ token }),
|
||||||
|
});
|
||||||
|
if (!res.ok) throw new Error(`daemon login failed (HTTP ${res.status})`);
|
||||||
|
}
|
||||||
44
packages/desktop/src/main/autostart.ts
Normal file
44
packages/desktop/src/main/autostart.ts
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import { app } from 'electron';
|
||||||
|
import { existsSync, mkdirSync, unlinkSync, writeFileSync } from 'node:fs';
|
||||||
|
import { dirname, join } from 'node:path';
|
||||||
|
import { homedir } from 'node:os';
|
||||||
|
|
||||||
|
// Lancement au login. Windows/macOS : API Electron (login items). Linux : fichier .desktop dans
|
||||||
|
// ~/.config/autostart (pas d'API Electron fiable pour l'autostart Linux).
|
||||||
|
|
||||||
|
function desktopFile(): string {
|
||||||
|
return join(homedir(), '.config', 'autostart', 'arboretum.desktop');
|
||||||
|
}
|
||||||
|
|
||||||
|
function desktopEntry(): string {
|
||||||
|
const exec = process.env.APPIMAGE ?? app.getPath('exe');
|
||||||
|
return `[Desktop Entry]
|
||||||
|
Type=Application
|
||||||
|
Name=Arboretum
|
||||||
|
Exec=${exec}
|
||||||
|
Terminal=false
|
||||||
|
X-GNOME-Autostart-enabled=true
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isAutoStartEnabled(): boolean {
|
||||||
|
if (process.platform === 'linux') return existsSync(desktopFile());
|
||||||
|
return app.getLoginItemSettings().openAtLogin;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setAutoStart(enabled: boolean): void {
|
||||||
|
if (process.platform === 'linux') {
|
||||||
|
if (enabled) {
|
||||||
|
mkdirSync(dirname(desktopFile()), { recursive: true });
|
||||||
|
writeFileSync(desktopFile(), desktopEntry());
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
unlinkSync(desktopFile());
|
||||||
|
} catch {
|
||||||
|
/* déjà absent */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
app.setLoginItemSettings({ openAtLogin: enabled });
|
||||||
|
}
|
||||||
90
packages/desktop/src/main/daemon.ts
Normal file
90
packages/desktop/src/main/daemon.ts
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
import { spawn, type ChildProcess } from 'node:child_process';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { resolveNodeBin, resolveServerEntry } from './paths';
|
||||||
|
import { buildChildEnv } from './env';
|
||||||
|
|
||||||
|
export interface DaemonHandle {
|
||||||
|
url: string;
|
||||||
|
token: string;
|
||||||
|
stop(): Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Handshake {
|
||||||
|
token: string;
|
||||||
|
url: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lance le daemon en process enfant (Node bundlé) et attend son handshake sur le fd 3
|
||||||
|
* (ARBORETUM_EMIT_TOKEN_FD=3 côté serveur) : la réception du JSON {token,url} prouve que le
|
||||||
|
* serveur écoute (le handshake est écrit après app.listen). Arrêt propre : SIGTERM puis SIGKILL.
|
||||||
|
*/
|
||||||
|
export function startDaemon(opts: {
|
||||||
|
dataDir: string;
|
||||||
|
port: number;
|
||||||
|
onLog?: (line: string) => void;
|
||||||
|
onExit?: (code: number | null) => void;
|
||||||
|
}): Promise<DaemonHandle> {
|
||||||
|
const node = resolveNodeBin();
|
||||||
|
const entry = resolveServerEntry();
|
||||||
|
const dbPath = join(opts.dataDir, 'arboretum.db');
|
||||||
|
const env = buildChildEnv({ XDG_DATA_HOME: opts.dataDir, ARBORETUM_EMIT_TOKEN_FD: '3' });
|
||||||
|
|
||||||
|
const child: ChildProcess = spawn(node, [entry, '--port', String(opts.port), '--db', dbPath], {
|
||||||
|
env,
|
||||||
|
stdio: ['ignore', 'pipe', 'pipe', 'pipe'],
|
||||||
|
});
|
||||||
|
|
||||||
|
child.stdout?.on('data', (d: Buffer) => opts.onLog?.(d.toString()));
|
||||||
|
child.stderr?.on('data', (d: Buffer) => opts.onLog?.(d.toString()));
|
||||||
|
|
||||||
|
let stopped = false;
|
||||||
|
const stop = (): Promise<void> =>
|
||||||
|
new Promise((resolve) => {
|
||||||
|
if (stopped || child.exitCode !== null) return resolve();
|
||||||
|
stopped = true;
|
||||||
|
const killTimer = setTimeout(() => child.kill('SIGKILL'), 3000);
|
||||||
|
child.once('exit', () => {
|
||||||
|
clearTimeout(killTimer);
|
||||||
|
resolve();
|
||||||
|
});
|
||||||
|
child.kill('SIGTERM');
|
||||||
|
});
|
||||||
|
|
||||||
|
return new Promise<DaemonHandle>((resolve, reject) => {
|
||||||
|
let buf = '';
|
||||||
|
let settled = false;
|
||||||
|
const fd3 = child.stdio[3] as NodeJS.ReadableStream | null;
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
if (settled) return;
|
||||||
|
settled = true;
|
||||||
|
void stop();
|
||||||
|
reject(new Error('daemon handshake timeout'));
|
||||||
|
}, 30000);
|
||||||
|
|
||||||
|
child.once('exit', (code) => {
|
||||||
|
opts.onExit?.(code);
|
||||||
|
if (!settled) {
|
||||||
|
settled = true;
|
||||||
|
clearTimeout(timer);
|
||||||
|
reject(new Error(`daemon exited before handshake (code ${code ?? 'null'})`));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
fd3?.on('data', (chunk: Buffer) => {
|
||||||
|
if (settled) return;
|
||||||
|
buf += chunk.toString();
|
||||||
|
const nl = buf.indexOf('\n');
|
||||||
|
if (nl < 0) return;
|
||||||
|
settled = true;
|
||||||
|
clearTimeout(timer);
|
||||||
|
try {
|
||||||
|
const hs = JSON.parse(buf.slice(0, nl)) as Handshake;
|
||||||
|
resolve({ url: hs.url, token: hs.token, stop });
|
||||||
|
} catch (err) {
|
||||||
|
void stop();
|
||||||
|
reject(err instanceof Error ? err : new Error(String(err)));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
15
packages/desktop/src/main/env.ts
Normal file
15
packages/desktop/src/main/env.ts
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import { delimiter, join } from 'node:path';
|
||||||
|
import { homedir } from 'node:os';
|
||||||
|
|
||||||
|
// Env de l'enfant daemon. Une app GUI démarre souvent avec un PATH minimal (sans ~/.local/bin,
|
||||||
|
// /usr/local/bin, /opt/homebrew/bin) : on l'enrichit pour que le daemon retrouve `git` et le CLI
|
||||||
|
// `claude`. Le réglage `claude_bin_path` (UI) reste le filet de secours.
|
||||||
|
export function buildChildEnv(extra: Record<string, string>): NodeJS.ProcessEnv {
|
||||||
|
const env: NodeJS.ProcessEnv = { ...process.env, ...extra };
|
||||||
|
if (process.platform !== 'win32') {
|
||||||
|
const extras = ['/usr/local/bin', '/opt/homebrew/bin', join(homedir(), '.local', 'bin'), '/usr/bin', '/bin'];
|
||||||
|
const current = env.PATH ? env.PATH.split(delimiter) : [];
|
||||||
|
env.PATH = [...new Set([...extras, ...current])].join(delimiter);
|
||||||
|
}
|
||||||
|
return env;
|
||||||
|
}
|
||||||
127
packages/desktop/src/main/main.ts
Normal file
127
packages/desktop/src/main/main.ts
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
import { app, BrowserWindow, session, shell, type BrowserWindowConstructorOptions, type Tray } from 'electron';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { startDaemon, type DaemonHandle } from './daemon';
|
||||||
|
import { seedSessionCookie } from './auth';
|
||||||
|
import { loadWindowState, saveWindowState } from './window-state';
|
||||||
|
import { createTray } from './tray';
|
||||||
|
import { initUpdater } from './updater';
|
||||||
|
|
||||||
|
const PARTITION = 'persist:arboretum';
|
||||||
|
const PORT = 7317;
|
||||||
|
|
||||||
|
let daemon: DaemonHandle | null = null;
|
||||||
|
let win: BrowserWindow | null = null;
|
||||||
|
let tray: Tray | null = null;
|
||||||
|
let isQuitting = false;
|
||||||
|
let shuttingDown = false;
|
||||||
|
|
||||||
|
// Instance unique : deux instances = deux daemons/ports en conflit.
|
||||||
|
if (!app.requestSingleInstanceLock()) {
|
||||||
|
app.quit();
|
||||||
|
} else {
|
||||||
|
app.on('second-instance', showWindow);
|
||||||
|
app.whenReady().then(bootstrap).catch((err: unknown) => {
|
||||||
|
console.error('[arboretum-desktop] bootstrap failed:', err);
|
||||||
|
app.quit();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function bootstrap(): Promise<void> {
|
||||||
|
const dataDir = join(app.getPath('userData'), 'daemon');
|
||||||
|
daemon = await startDaemon({ dataDir, port: PORT, onLog: (l) => process.stdout.write(l) });
|
||||||
|
await seedSessionCookie(PARTITION, daemon.url, daemon.token);
|
||||||
|
createWindow(daemon.url);
|
||||||
|
tray = createTray({ show: showWindow, quit: quitApp });
|
||||||
|
initUpdater();
|
||||||
|
}
|
||||||
|
|
||||||
|
function showWindow(): void {
|
||||||
|
if (!win) return;
|
||||||
|
if (win.isMinimized()) win.restore();
|
||||||
|
win.show();
|
||||||
|
win.focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
function quitApp(): void {
|
||||||
|
isQuitting = true;
|
||||||
|
app.quit();
|
||||||
|
}
|
||||||
|
|
||||||
|
function createWindow(url: string): void {
|
||||||
|
const state = loadWindowState();
|
||||||
|
const opts: BrowserWindowConstructorOptions = {
|
||||||
|
width: state.width,
|
||||||
|
height: state.height,
|
||||||
|
backgroundColor: '#09090b',
|
||||||
|
webPreferences: {
|
||||||
|
partition: PARTITION,
|
||||||
|
contextIsolation: true,
|
||||||
|
sandbox: true,
|
||||||
|
nodeIntegration: false,
|
||||||
|
preload: join(__dirname, 'preload.js'),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
if (state.x !== undefined) opts.x = state.x;
|
||||||
|
if (state.y !== undefined) opts.y = state.y;
|
||||||
|
|
||||||
|
win = new BrowserWindow(opts);
|
||||||
|
if (state.maximized) win.maximize();
|
||||||
|
|
||||||
|
// Liens externes -> navigateur système ; toute navigation hors origine locale est déviée.
|
||||||
|
win.webContents.setWindowOpenHandler(({ url: u }) => {
|
||||||
|
void shell.openExternal(u);
|
||||||
|
return { action: 'deny' };
|
||||||
|
});
|
||||||
|
win.webContents.on('will-navigate', (e, u) => {
|
||||||
|
if (!u.startsWith(url)) {
|
||||||
|
e.preventDefault();
|
||||||
|
void shell.openExternal(u);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Permissions : n'autoriser que les notifications (cohérent avec la Permissions-Policy serveur).
|
||||||
|
session.fromPartition(PARTITION).setPermissionRequestHandler((_wc, permission, cb) => cb(permission === 'notifications'));
|
||||||
|
|
||||||
|
const persist = (): void => {
|
||||||
|
if (!win) return;
|
||||||
|
const b = win.getBounds();
|
||||||
|
saveWindowState({ width: b.width, height: b.height, x: b.x, y: b.y, maximized: win.isMaximized() });
|
||||||
|
};
|
||||||
|
|
||||||
|
// Fermer la fenêtre = réduire dans le tray (l'app continue en arrière-plan) ; quitter réellement
|
||||||
|
// se fait via le menu du tray ou le menu applicatif.
|
||||||
|
win.on('close', (e) => {
|
||||||
|
persist();
|
||||||
|
if (!isQuitting) {
|
||||||
|
e.preventDefault();
|
||||||
|
win?.hide();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
win.on('closed', () => {
|
||||||
|
win = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
void win.loadURL(`${url}/`);
|
||||||
|
}
|
||||||
|
|
||||||
|
app.on('before-quit', (e) => {
|
||||||
|
// Ne pas quitter avant l'arrêt propre du daemon enfant.
|
||||||
|
isQuitting = true;
|
||||||
|
if (daemon && !shuttingDown) {
|
||||||
|
e.preventDefault();
|
||||||
|
void shutdown();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
async function shutdown(): Promise<void> {
|
||||||
|
if (shuttingDown) return;
|
||||||
|
shuttingDown = true;
|
||||||
|
try {
|
||||||
|
await daemon?.stop();
|
||||||
|
} finally {
|
||||||
|
daemon = null;
|
||||||
|
tray?.destroy();
|
||||||
|
tray = null;
|
||||||
|
app.quit();
|
||||||
|
}
|
||||||
|
}
|
||||||
26
packages/desktop/src/main/paths.ts
Normal file
26
packages/desktop/src/main/paths.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import { app } from 'electron';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
|
||||||
|
// Résolution des chemins runtime : dev (depuis le repo) vs packagé (extraResources).
|
||||||
|
// __dirname pointe sur dist/ (bundle esbuild) une fois construit.
|
||||||
|
|
||||||
|
/** Entrée du serveur daemon (son dist/index.js). */
|
||||||
|
export function resolveServerEntry(): string {
|
||||||
|
if (app.isPackaged) {
|
||||||
|
// packagé : le tarball du daemon est extrait sous resources/server/package/
|
||||||
|
return join(process.resourcesPath, 'server', 'package', 'dist', 'index.js');
|
||||||
|
}
|
||||||
|
// dev : packages/desktop/dist/main.js -> packages/server/dist/index.js
|
||||||
|
return join(__dirname, '..', '..', 'server', 'dist', 'index.js');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Binaire Node qui exécute le daemon (>= 22.16 : node:sqlite + ABI node-pty maîtrisé). */
|
||||||
|
export function resolveNodeBin(): string {
|
||||||
|
if (app.isPackaged) {
|
||||||
|
return process.platform === 'win32'
|
||||||
|
? join(process.resourcesPath, 'node', 'node.exe')
|
||||||
|
: join(process.resourcesPath, 'node', 'bin', 'node');
|
||||||
|
}
|
||||||
|
// dev : node du PATH (mêmes prebuilds node-pty que le repo).
|
||||||
|
return process.platform === 'win32' ? 'node.exe' : 'node';
|
||||||
|
}
|
||||||
40
packages/desktop/src/main/tray.ts
Normal file
40
packages/desktop/src/main/tray.ts
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
import { app, Menu, Tray, nativeImage } from 'electron';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { isAutoStartEnabled, setAutoStart } from './autostart';
|
||||||
|
|
||||||
|
function iconPath(): string {
|
||||||
|
return app.isPackaged
|
||||||
|
? join(process.resourcesPath, 'icon.png')
|
||||||
|
: join(__dirname, '..', 'resources', 'icon.png');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Icône de barre système : ouvrir la fenêtre, basculer le lancement au login, quitter. */
|
||||||
|
export function createTray(opts: { show: () => void; quit: () => void }): Tray {
|
||||||
|
const image = nativeImage.createFromPath(iconPath());
|
||||||
|
const tray = new Tray(image.isEmpty() ? nativeImage.createEmpty() : image.resize({ width: 18, height: 18 }));
|
||||||
|
tray.setToolTip('Arboretum');
|
||||||
|
|
||||||
|
const buildMenu = (): void => {
|
||||||
|
tray.setContextMenu(
|
||||||
|
Menu.buildFromTemplate([
|
||||||
|
{ label: 'Open Arboretum', click: opts.show },
|
||||||
|
{ type: 'separator' },
|
||||||
|
{
|
||||||
|
label: 'Launch at login',
|
||||||
|
type: 'checkbox',
|
||||||
|
checked: isAutoStartEnabled(),
|
||||||
|
click: (item) => {
|
||||||
|
setAutoStart(item.checked);
|
||||||
|
buildMenu();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ type: 'separator' },
|
||||||
|
{ label: 'Quit', click: opts.quit },
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
buildMenu();
|
||||||
|
tray.on('click', opts.show);
|
||||||
|
return tray;
|
||||||
|
}
|
||||||
13
packages/desktop/src/main/updater.ts
Normal file
13
packages/desktop/src/main/updater.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import { app } from 'electron';
|
||||||
|
import { autoUpdater } from 'electron-updater';
|
||||||
|
|
||||||
|
// Vérifie les mises à jour (provider generic -> assets de release Gitea, cf. electron-builder.yml).
|
||||||
|
// No-op en dev (pas de app-update.yml). Auto-update effectif : Windows (nsis) + Linux (AppImage) ;
|
||||||
|
// macOS reste manuel tant que l'app n'est pas signée.
|
||||||
|
export function initUpdater(): void {
|
||||||
|
if (!app.isPackaged) return;
|
||||||
|
autoUpdater.autoDownload = true;
|
||||||
|
void autoUpdater.checkForUpdatesAndNotify().catch(() => {
|
||||||
|
/* hors ligne / pas de release publiée : silencieux */
|
||||||
|
});
|
||||||
|
}
|
||||||
34
packages/desktop/src/main/window-state.ts
Normal file
34
packages/desktop/src/main/window-state.ts
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import { app } from 'electron';
|
||||||
|
import { readFileSync, writeFileSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
|
||||||
|
export interface WindowState {
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
x?: number;
|
||||||
|
y?: number;
|
||||||
|
maximized?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT: WindowState = { width: 1400, height: 900 };
|
||||||
|
|
||||||
|
function stateFile(): string {
|
||||||
|
return join(app.getPath('userData'), 'window-state.json');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function loadWindowState(): WindowState {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(readFileSync(stateFile(), 'utf8')) as Partial<WindowState>;
|
||||||
|
return { ...DEFAULT, ...parsed };
|
||||||
|
} catch {
|
||||||
|
return { ...DEFAULT };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveWindowState(state: WindowState): void {
|
||||||
|
try {
|
||||||
|
writeFileSync(stateFile(), JSON.stringify(state));
|
||||||
|
} catch {
|
||||||
|
/* best effort : quota / permissions */
|
||||||
|
}
|
||||||
|
}
|
||||||
7
packages/desktop/src/preload/preload.ts
Normal file
7
packages/desktop/src/preload/preload.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import { contextBridge } from 'electron';
|
||||||
|
|
||||||
|
// Preload minimal (sandbox activé) : expose seulement un marqueur permettant à la SPA de détecter
|
||||||
|
// qu'elle tourne dans l'app de bureau. Aucun accès Node/fs exposé au renderer.
|
||||||
|
contextBridge.exposeInMainWorld('arboretumDesktop', {
|
||||||
|
isDesktop: true,
|
||||||
|
});
|
||||||
17
packages/desktop/tsconfig.json
Normal file
17
packages/desktop/tsconfig.json
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"module": "CommonJS",
|
||||||
|
"moduleResolution": "node",
|
||||||
|
"lib": ["ES2022"],
|
||||||
|
"strict": true,
|
||||||
|
"exactOptionalPropertyTypes": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"types": ["node"]
|
||||||
|
},
|
||||||
|
"include": ["src/**/*.ts"]
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@johanleroy/git-arboretum",
|
"name": "@johanleroy/git-arboretum",
|
||||||
"version": "1.2.0",
|
"version": "2.0.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,23 +48,21 @@
|
|||||||
"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",
|
||||||
|
"chokidar": "^4.0.3",
|
||||||
"fastify": "^5.0.0",
|
"fastify": "^5.0.0",
|
||||||
"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"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,11 +19,11 @@ const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
|
|||||||
const results = [];
|
const results = [];
|
||||||
const check = (name, ok, detail = '') => {
|
const check = (name, ok, detail = '') => {
|
||||||
results.push({ name, ok, detail });
|
results.push({ name, ok, detail });
|
||||||
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? ` — ${detail}` : ''}`);
|
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? `: ${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'],
|
||||||
});
|
});
|
||||||
|
|||||||
159
packages/server/scripts/acceptance-p10.mjs
Normal file
159
packages/server/scripts/acceptance-p10.mjs
Normal file
@@ -0,0 +1,159 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Acceptation P10 (sans navigateur, sans quota Claude) : archivage automatique des sessions terminées.
|
||||||
|
// Vrai daemon + faux binaire `claude` (echo+sleep, comme p2) + 2e connexion sqlite (WAL) pour fabriquer
|
||||||
|
// des sessions managées terminées avec un ended_at ancien. Couvre : sweep archive-now (archived_at posé,
|
||||||
|
// event WS session_archived), exclusion par défaut + inclusion via ?includeArchived, archive/unarchive
|
||||||
|
// manuels, rétention=0 (no-op), et, preuve clé « pas de perte », resume d'une session ARCHIVÉE → 201.
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, chmodSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join, dirname } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
import { DatabaseSync } from 'node:sqlite';
|
||||||
|
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const WebSocket = require('ws');
|
||||||
|
|
||||||
|
const PORT = 7551;
|
||||||
|
const ORIGIN = `http://127.0.0.1:${PORT}`;
|
||||||
|
const OLD = '2020-01-01T00:00:00.000Z';
|
||||||
|
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-p10-'));
|
||||||
|
const claudeHome = join(tmp, 'claude');
|
||||||
|
const workDir = join(tmp, 'work');
|
||||||
|
const fakeBin = join(tmp, 'bin');
|
||||||
|
const dbPath = join(tmp, 'a.db');
|
||||||
|
mkdirSync(join(claudeHome, 'projects'), { recursive: true });
|
||||||
|
mkdirSync(join(claudeHome, 'sessions'), { recursive: true });
|
||||||
|
mkdirSync(workDir, { recursive: true });
|
||||||
|
mkdirSync(fakeBin, { recursive: true });
|
||||||
|
writeFileSync(join(fakeBin, 'claude'), '#!/usr/bin/env bash\necho "FAKE-CLAUDE args=[$*] cwd=$(pwd)"\nsleep 30\n');
|
||||||
|
chmodSync(join(fakeBin, 'claude'), 0o755);
|
||||||
|
|
||||||
|
// Insère une session managée « claude » terminée directement en DB (2e connexion WAL).
|
||||||
|
function insertManagedDeadSession(id, claudeSid, endedAt) {
|
||||||
|
const db = new DatabaseSync(dbPath);
|
||||||
|
db.prepare(
|
||||||
|
'INSERT INTO sessions (id, cwd, command, created_at, ended_at, claude_session_id) VALUES (?, ?, ?, ?, ?, ?)',
|
||||||
|
).run(id, workDir, 'claude', OLD, endedAt, claudeSid);
|
||||||
|
db.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
const srv = spawn(
|
||||||
|
'node',
|
||||||
|
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', dbPath, '--claude-home', claudeHome, '--no-discover'],
|
||||||
|
{ env: { ...process.env, ARBORETUM_LOG: 'warn', PATH: `${fakeBin}:${process.env.PATH}` }, 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 = 6000) => {
|
||||||
|
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) } : {}),
|
||||||
|
});
|
||||||
|
const listSessions = async (cookie, q = '') => (await (await j(`/api/v1/sessions${q}`, 'GET', cookie)).json()).sessions ?? [];
|
||||||
|
|
||||||
|
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'] });
|
||||||
|
|
||||||
|
// ---- A. Auto-archivage (sweep via archive-now) ----
|
||||||
|
insertManagedDeadSession('arch-old', 'sid-old', OLD);
|
||||||
|
const before = await listSessions(cookie);
|
||||||
|
check('session terminée ancienne visible par défaut (avant archivage)', before.some((s) => s.id === 'arch-old' && !s.archived));
|
||||||
|
|
||||||
|
c.state.msgs.length = 0;
|
||||||
|
const now = await (await j('/api/v1/sessions/archive-now', 'POST', cookie)).json();
|
||||||
|
check('POST /sessions/archive-now → ≥ 1 archivée', now.archived >= 1, `archived=${now.archived}`);
|
||||||
|
const evt = await c.waitMsg((m) => m.type === 'session_archived' && m.sessionId === 'arch-old');
|
||||||
|
check('event WS session_archived reçu', !!evt);
|
||||||
|
|
||||||
|
const def = await listSessions(cookie);
|
||||||
|
check('GET /sessions exclut l’archivée par défaut', !def.some((s) => s.id === 'arch-old'));
|
||||||
|
const inc = await listSessions(cookie, '?includeArchived=true');
|
||||||
|
check('GET /sessions?includeArchived=true inclut l’archivée (archived=true)', inc.some((s) => s.id === 'arch-old' && s.archived === true));
|
||||||
|
|
||||||
|
// ---- B. Preuve « pas de perte » : resume d'une session ARCHIVÉE → 201 ----
|
||||||
|
const resume = await j('/api/v1/sessions/arch-old/resume', 'POST', cookie);
|
||||||
|
const resumed = await resume.json();
|
||||||
|
check('resume d’une session archivée → 201 (PTY managé claude)', resume.status === 201 && resumed.session?.command === 'claude');
|
||||||
|
|
||||||
|
// ---- C. Archive / unarchive manuels ----
|
||||||
|
insertManagedDeadSession('manual1', 'sid-man', new Date().toISOString()); // récente → le sweep ne la touche pas
|
||||||
|
c.state.msgs.length = 0;
|
||||||
|
const arch = await j('/api/v1/sessions/manual1/archive', 'POST', cookie);
|
||||||
|
check('POST /sessions/:id/archive → 200', arch.status === 200);
|
||||||
|
check('archive manuel → event session_archived', !!(await c.waitMsg((m) => m.type === 'session_archived' && m.sessionId === 'manual1')));
|
||||||
|
check('archive manuel → exclue par défaut', !(await listSessions(cookie)).some((s) => s.id === 'manual1'));
|
||||||
|
|
||||||
|
const unarch = await j('/api/v1/sessions/manual1/archive', 'DELETE', cookie);
|
||||||
|
check('DELETE /sessions/:id/archive → 200', unarch.status === 200);
|
||||||
|
check('unarchive → ré-affichée par défaut (archived=false)', (await listSessions(cookie)).some((s) => s.id === 'manual1' && !s.archived));
|
||||||
|
|
||||||
|
const missing = await j('/api/v1/sessions/does-not-exist/archive', 'POST', cookie);
|
||||||
|
check('archive d’un id inconnu → 404', missing.status === 404);
|
||||||
|
|
||||||
|
// ---- D. Rétention = 0 → archivage désactivé (no-op) ----
|
||||||
|
const patch = await j('/api/v1/settings', 'PATCH', cookie, { retentionDays: 0 });
|
||||||
|
check('PATCH retentionDays=0 → 200', patch.status === 200);
|
||||||
|
insertManagedDeadSession('arch-old2', 'sid-old2', OLD);
|
||||||
|
const now0 = await (await j('/api/v1/sessions/archive-now', 'POST', cookie)).json();
|
||||||
|
check('rétention=0 → sweep n’archive rien', now0.archived === 0);
|
||||||
|
check('session ancienne reste visible (archivage désactivé)', (await listSessions(cookie)).some((s) => s.id === 'arch-old2' && !s.archived));
|
||||||
|
|
||||||
|
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 P10: ALL GREEN' : `\nACCEPTANCE P10: ${failed.length} FAILURE(S)`);
|
||||||
|
process.exit(failed.length === 0 ? 0 : 1);
|
||||||
|
}
|
||||||
117
packages/server/scripts/acceptance-p11.mjs
Normal file
117
packages/server/scripts/acceptance-p11.mjs
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Acceptation P11 (sans navigateur) : temps réel complet. Vrai daemon + vrai repo git tmp + client WS.
|
||||||
|
// Couvre : (1) `git checkout` en CLI sur le CHECKOUT PRINCIPAL → worktree_update (nouvelle branche)
|
||||||
|
// poussé en temps réel (< 500 ms) sans qu'aucun client n'ait `watch`é ce worktree ; (2) PATCH /settings
|
||||||
|
// → settings_update reçu par un client abonné au topic 'settings'.
|
||||||
|
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 = 7554;
|
||||||
|
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-p11-'));
|
||||||
|
const repo = join(tmp, 'repo');
|
||||||
|
execFileSync('mkdir', ['-p', repo]);
|
||||||
|
const git = (...args) => execFileSync('git', args, { cwd: repo, stdio: 'pipe' });
|
||||||
|
git('init', '-b', 'main');
|
||||||
|
git('config', 'user.email', 'test@arboretum.dev');
|
||||||
|
git('config', 'user.name', 'Test');
|
||||||
|
writeFileSync(join(repo, 'README.md'), '# demo\n');
|
||||||
|
git('add', '-A');
|
||||||
|
git('commit', '-m', 'init');
|
||||||
|
|
||||||
|
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 = 6000) => {
|
||||||
|
const t0 = Date.now();
|
||||||
|
while (Date.now() - t0 < timeout) {
|
||||||
|
const m = state.msgs.find(pred);
|
||||||
|
if (m) return m;
|
||||||
|
await sleep(40);
|
||||||
|
}
|
||||||
|
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: ['worktrees', 'settings'] });
|
||||||
|
|
||||||
|
// ---- (1) checkout du PRINCIPAL en CLI → worktree_update sans watch client ----
|
||||||
|
const addRepo = await j('/api/v1/repos', 'POST', cookie, { path: repo });
|
||||||
|
check('POST /repos → 201', addRepo.status === 201);
|
||||||
|
await sleep(1000); // laisse chokidar finir le scan initial du watcher permanent du principal
|
||||||
|
c.state.msgs.length = 0;
|
||||||
|
const t0 = Date.now();
|
||||||
|
git('checkout', '-b', 'feature'); // changement de branche du checkout principal, hors Arboretum
|
||||||
|
const branchMsg = await c.waitMsg((m) => m.type === 'worktree_update' && m.worktree?.isMain && m.worktree?.branch === 'feature', 5000);
|
||||||
|
const dt = branchMsg ? Date.now() - t0 : -1;
|
||||||
|
check('checkout principal en CLI → worktree_update (sans watch client)', !!branchMsg, branchMsg ? `${dt}ms` : 'timeout');
|
||||||
|
check('latence temps réel < 500 ms', branchMsg !== null && dt >= 0 && dt < 500, `${dt}ms`);
|
||||||
|
|
||||||
|
// ---- (2) PATCH /settings → settings_update reçu par l'abonné 'settings' ----
|
||||||
|
c.state.msgs.length = 0;
|
||||||
|
const patch = await j('/api/v1/settings', 'PATCH', cookie, { retentionDays: 7 });
|
||||||
|
check('PATCH /settings → 200', patch.status === 200);
|
||||||
|
const settingsMsg = await c.waitMsg((m) => m.type === 'settings_update' && m.settings?.retentionDays === 7, 3000);
|
||||||
|
check('settings_update reçu avec le nouvel état', !!settingsMsg);
|
||||||
|
|
||||||
|
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 P11: ALL GREEN' : `\nACCEPTANCE P11: ${failed.length} FAILURE(S)`);
|
||||||
|
process.exit(failed.length === 0 ? 0 : 1);
|
||||||
|
}
|
||||||
149
packages/server/scripts/acceptance-p12.mjs
Normal file
149
packages/server/scripts/acceptance-p12.mjs
Normal file
@@ -0,0 +1,149 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Acceptation P12a (sans navigateur, sans réseau/quota) : services git distants + clone. Vrai daemon
|
||||||
|
// + credential factice + clone d'un dépôt bare LOCAL (chemin de fichier, pas de réseau). Couvre :
|
||||||
|
// création de credential (secret chiffré), POST /repos/clone (202) → progression WS clone_update →
|
||||||
|
// done → repo auto-enregistré, ET surtout : le secret en clair est ABSENT de l'API, de la DB et du
|
||||||
|
// .git/config du dépôt cloné (garde-fou « jamais de fuite de secret »).
|
||||||
|
import { spawn, execFileSync } from 'node:child_process';
|
||||||
|
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, readFileSync, existsSync } 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 = 7555;
|
||||||
|
const ORIGIN = `http://127.0.0.1:${PORT}`;
|
||||||
|
const SECRET = 'arb-secret-token-9876XYZ'; // token factice : ne doit JAMAIS fuiter en clair
|
||||||
|
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-p12-'));
|
||||||
|
const work = join(tmp, 'work'); // racine de scan + destination des clones
|
||||||
|
const src = join(tmp, 'src'); // dépôt source (working)
|
||||||
|
const bare = join(tmp, 'source.git'); // remote bare local (file path)
|
||||||
|
const dbPath = join(tmp, 'a.db');
|
||||||
|
mkdirSync(work, { recursive: true });
|
||||||
|
mkdirSync(src, { recursive: true });
|
||||||
|
const g = (cwd, ...args) => execFileSync('git', args, { cwd, stdio: 'pipe' });
|
||||||
|
g(src, 'init', '-b', 'main');
|
||||||
|
g(src, 'config', 'user.email', 'test@arboretum.dev');
|
||||||
|
g(src, 'config', 'user.name', 'Test');
|
||||||
|
writeFileSync(join(src, 'README.md'), '# cloned demo\n');
|
||||||
|
g(src, 'add', '-A');
|
||||||
|
g(src, 'commit', '-m', 'init');
|
||||||
|
execFileSync('git', ['clone', '--bare', src, bare], { stdio: 'pipe' });
|
||||||
|
|
||||||
|
const srv = spawn(
|
||||||
|
'node',
|
||||||
|
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', dbPath, '--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 = 15000) => {
|
||||||
|
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);
|
||||||
|
|
||||||
|
// racine de scan = work (confine la destination du clone).
|
||||||
|
const patch = await j('/api/v1/settings', 'PATCH', cookie, { scanRoots: [work] });
|
||||||
|
check('PATCH scanRoots → 200', patch.status === 200);
|
||||||
|
|
||||||
|
// credential factice (secret chiffré côté serveur).
|
||||||
|
const createCred = await j('/api/v1/git-connections', 'POST', cookie, {
|
||||||
|
label: 'fake', service: 'gitea', authType: 'pat', baseUrl: 'http://localhost:9999', secret: SECRET,
|
||||||
|
});
|
||||||
|
const credBody = await createCred.json();
|
||||||
|
const credId = credBody.credential?.id;
|
||||||
|
check('POST /git-connections → 201', createCred.status === 201 && !!credId);
|
||||||
|
check('réponse de création SANS secret en clair', !JSON.stringify(credBody).includes(SECRET));
|
||||||
|
check('réponse expose secretLast4 (et hasSecret)', credBody.credential?.hasSecret === true && credBody.credential?.secretLast4 === SECRET.slice(-4));
|
||||||
|
|
||||||
|
// GET liste : pas de secret.
|
||||||
|
const listed = await (await j('/api/v1/git-connections', 'GET', cookie)).json();
|
||||||
|
check('GET /git-connections SANS secret en clair', !JSON.stringify(listed).includes(SECRET));
|
||||||
|
|
||||||
|
// WS abonné aux clones.
|
||||||
|
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: ['clones', 'worktrees'] });
|
||||||
|
|
||||||
|
// clone du bare local → dest sous la racine de scan.
|
||||||
|
const dest = join(work, 'cloned');
|
||||||
|
const clone = await j('/api/v1/repos/clone', 'POST', cookie, { credentialId: credId, remoteUrl: bare, dest });
|
||||||
|
const cloneBody = await clone.json();
|
||||||
|
check('POST /repos/clone → 202 + operationId', clone.status === 202 && !!cloneBody.operationId);
|
||||||
|
|
||||||
|
const doneMsg = await c.waitMsg((m) => m.type === 'clone_update' && m.operation?.id === cloneBody.operationId && m.operation?.state === 'done');
|
||||||
|
check('clone_update state=done reçu via WS', !!doneMsg, doneMsg ? `repoId=${doneMsg.operation.repoId}` : 'timeout');
|
||||||
|
check('le clone a produit un repoId (auto-enregistré)', !!doneMsg?.operation?.repoId);
|
||||||
|
|
||||||
|
// repo enregistré + visible.
|
||||||
|
const repos = await (await j('/api/v1/repos', 'GET', cookie)).json();
|
||||||
|
const cloned = (repos.repos ?? []).find((r) => r.path === dest);
|
||||||
|
check('repo cloné enregistré et listé', !!cloned);
|
||||||
|
check('le dépôt cloné existe sur disque (README.md)', existsSync(join(dest, 'README.md')));
|
||||||
|
|
||||||
|
// ---- garde-fou « pas de fuite de secret » ----
|
||||||
|
const gitConfig = existsSync(join(dest, '.git', 'config')) ? readFileSync(join(dest, '.git', 'config'), 'utf8') : '';
|
||||||
|
check('secret ABSENT du .git/config du clone', !gitConfig.includes(SECRET));
|
||||||
|
const dbBytes = [dbPath, `${dbPath}-wal`, `${dbPath}-shm`]
|
||||||
|
.filter((p) => existsSync(p))
|
||||||
|
.map((p) => readFileSync(p).toString('latin1'))
|
||||||
|
.join('');
|
||||||
|
check('secret ABSENT de la base (chiffré au repos)', !dbBytes.includes(SECRET));
|
||||||
|
|
||||||
|
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 P12: ALL GREEN' : `\nACCEPTANCE P12: ${failed.length} FAILURE(S)`);
|
||||||
|
process.exit(failed.length === 0 ? 0 : 1);
|
||||||
|
}
|
||||||
@@ -22,7 +22,7 @@ const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
|
|||||||
const results = [];
|
const results = [];
|
||||||
const check = (name, ok, detail = '') => {
|
const check = (name, ok, detail = '') => {
|
||||||
results.push({ name, ok, detail });
|
results.push({ name, ok, detail });
|
||||||
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? ` — ${detail}` : ''}`);
|
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? `: ${detail}` : ''}`);
|
||||||
};
|
};
|
||||||
|
|
||||||
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p2-'));
|
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p2-'));
|
||||||
@@ -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';
|
||||||
@@ -19,7 +19,7 @@ const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
|
|||||||
const results = [];
|
const results = [];
|
||||||
const check = (name, ok, detail = '') => {
|
const check = (name, ok, detail = '') => {
|
||||||
results.push({ name, ok, detail });
|
results.push({ name, ok, detail });
|
||||||
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? ` — ${detail}` : ''}`);
|
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? `: ${detail}` : ''}`);
|
||||||
};
|
};
|
||||||
|
|
||||||
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p3-'));
|
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p3-'));
|
||||||
@@ -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);
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
// Acceptation P4 (sans navigateur, sans quota Claude) : Web Push + commande WS `answer`.
|
// Acceptation P4 (sans navigateur, sans quota Claude) : Web Push + commande WS `answer`.
|
||||||
// Vrai daemon. Couvre : garde auth + Origin sur les routes push, clé VAPID exposée, subscribe
|
// Vrai daemon. Couvre : garde auth + Origin sur les routes push, clé VAPID exposée, subscribe
|
||||||
// idempotent / malformé / unsubscribe, et la commande `answer` (rejets INVALID_ANSWER /
|
// idempotent / malformé / unsubscribe, et la commande `answer` (rejets INVALID_ANSWER /
|
||||||
// NOT_CONTROLLING — la validation fine `select` vit dans les tests vitest sur fixtures).
|
// NOT_CONTROLLING : la validation fine `select` vit dans les tests vitest sur fixtures).
|
||||||
import { spawn } from 'node:child_process';
|
import { spawn } from 'node:child_process';
|
||||||
import { mkdtempSync, rmSync } from 'node:fs';
|
import { mkdtempSync, rmSync } from 'node:fs';
|
||||||
import { tmpdir } from 'node:os';
|
import { tmpdir } from 'node:os';
|
||||||
@@ -20,14 +20,14 @@ const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
|
|||||||
const results = [];
|
const results = [];
|
||||||
const check = (name, ok, detail = '') => {
|
const check = (name, ok, detail = '') => {
|
||||||
results.push({ name, ok, detail });
|
results.push({ name, ok, detail });
|
||||||
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? ` — ${detail}` : ''}`);
|
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? `: ${detail}` : ''}`);
|
||||||
};
|
};
|
||||||
|
|
||||||
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p4-'));
|
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 = '';
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
// group_removed sur le topic 'groups', ajout/retrait de repo, et purge CASCADE de la membership
|
// 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).
|
// quand le repo est supprimé (PRAGMA foreign_keys = ON).
|
||||||
import { spawn, execFileSync } from 'node:child_process';
|
import { spawn, execFileSync } from 'node:child_process';
|
||||||
import { mkdtempSync, rmSync } from 'node:fs';
|
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||||
import { tmpdir } from 'node:os';
|
import { tmpdir } from 'node:os';
|
||||||
import { join, dirname } from 'node:path';
|
import { join, dirname } from 'node:path';
|
||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from 'node:url';
|
||||||
@@ -20,23 +20,28 @@ const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
|
|||||||
const results = [];
|
const results = [];
|
||||||
const check = (name, ok, detail = '') => {
|
const check = (name, ok, detail = '') => {
|
||||||
results.push({ name, ok, detail });
|
results.push({ name, ok, detail });
|
||||||
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? ` — ${detail}` : ''}`);
|
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? `: ${detail}` : ''}`);
|
||||||
};
|
};
|
||||||
|
|
||||||
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p5-'));
|
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 repo = join(tmp, 'demo-repo');
|
||||||
execFileSync('mkdir', ['-p', repo]);
|
const repo2 = join(tmp, 'demo-repo-2');
|
||||||
const git = (...args) => execFileSync('git', args, { cwd: repo, stdio: 'pipe' });
|
initRepo(repo);
|
||||||
git('init', '-b', 'main');
|
initRepo(repo2);
|
||||||
git('config', 'user.email', 'test@arboretum.dev');
|
|
||||||
git('config', 'user.name', 'Test');
|
|
||||||
execFileSync('bash', ['-lc', 'echo "# demo" > README.md'], { cwd: repo });
|
|
||||||
git('add', '-A');
|
|
||||||
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 = '';
|
||||||
@@ -109,6 +114,71 @@ try {
|
|||||||
const pushedAdd = await c.waitMsg((m) => m.type === 'group_update' && m.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);
|
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.
|
// Renommage via PATCH.
|
||||||
const patched = await j(`/api/v1/groups/${group.id}`, 'PATCH', cookie, { label: 'Renamed' });
|
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');
|
check('PATCH /groups/:id → 200 (renommé)', patched.status === 200 && (await patched.json()).group?.label === 'Renamed');
|
||||||
|
|||||||
163
packages/server/scripts/acceptance-p7.mjs
Normal file
163
packages/server/scripts/acceptance-p7.mjs
Normal file
@@ -0,0 +1,163 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Acceptation P7 (sans navigateur, sans quota Claude) : moteur git « IDE » + API fichiers + watcher
|
||||||
|
// FS temps réel. Vrai daemon + vrai repo git tmp + vrai client WS. Couvre : GET /changes & /diff,
|
||||||
|
// staging sélectif + commit(staged), API fichiers content GET/PUT (Monaco) + refus de traversal,
|
||||||
|
// abonnement ciblé watch → worktree_changes à l'édition, checkout externe → worktree_update, unwatch.
|
||||||
|
import { spawn, execFileSync } from 'node:child_process';
|
||||||
|
import { mkdtempSync, rmSync, writeFileSync, appendFileSync } 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 = 7547;
|
||||||
|
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-p7-'));
|
||||||
|
const repo = join(tmp, 'demo-repo');
|
||||||
|
execFileSync('mkdir', ['-p', repo]);
|
||||||
|
const git = (...args) => execFileSync('git', args, { cwd: repo, stdio: 'pipe' });
|
||||||
|
git('init', '-b', 'main');
|
||||||
|
git('config', 'user.email', 'test@arboretum.dev');
|
||||||
|
git('config', 'user.name', 'Test');
|
||||||
|
writeFileSync(join(repo, 'README.md'), '# demo\n');
|
||||||
|
git('add', '-A');
|
||||||
|
git('commit', '-m', 'init');
|
||||||
|
|
||||||
|
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: ['worktrees'] });
|
||||||
|
|
||||||
|
const addRepo = await j('/api/v1/repos', 'POST', cookie, { path: repo });
|
||||||
|
const repoId = (await addRepo.json()).repo.id;
|
||||||
|
check('POST /repos → 201', addRepo.status === 201 && !!repoId);
|
||||||
|
const enc = encodeURIComponent(repo);
|
||||||
|
|
||||||
|
// ---- GET /changes : un fichier modifié + un untracked ----
|
||||||
|
appendFileSync(join(repo, 'README.md'), 'edited line\n');
|
||||||
|
writeFileSync(join(repo, 'untracked.txt'), 'new\n');
|
||||||
|
const ch = await (await j(`/api/v1/repos/${repoId}/worktrees/changes?path=${enc}`, 'GET', cookie)).json();
|
||||||
|
const byPath = Object.fromEntries((ch.changes ?? []).map((c2) => [c2.path, c2]));
|
||||||
|
check('GET /changes : README.md modifié non indexé', byPath['README.md']?.unstaged === true && byPath['README.md']?.staged === false);
|
||||||
|
check('GET /changes : untracked.txt détecté', byPath['untracked.txt']?.untracked === true);
|
||||||
|
|
||||||
|
// ---- GET /diff ----
|
||||||
|
const diff = await (await j(`/api/v1/repos/${repoId}/worktrees/diff?path=${enc}&file=README.md`, 'GET', cookie)).json();
|
||||||
|
check('GET /diff : contient la ligne ajoutée', typeof diff.diff === 'string' && diff.diff.includes('+edited line'));
|
||||||
|
|
||||||
|
// ---- staging sélectif + commit(staged) ----
|
||||||
|
const stage = await j(`/api/v1/repos/${repoId}/worktrees/stage`, 'POST', cookie, { path: repo, files: ['README.md'] });
|
||||||
|
const staged = await stage.json();
|
||||||
|
check('POST /stage → README.md staged', staged.worktree?.git?.stagedCount >= 1);
|
||||||
|
const commit = await j(`/api/v1/repos/${repoId}/worktrees/commit`, 'POST', cookie, { path: repo, message: 'commit staged only', mode: 'staged' });
|
||||||
|
check('POST /commit (mode=staged) → 200', commit.status === 200);
|
||||||
|
const ch2 = await (await j(`/api/v1/repos/${repoId}/worktrees/changes?path=${enc}`, 'GET', cookie)).json();
|
||||||
|
const paths2 = (ch2.changes ?? []).map((c2) => c2.path);
|
||||||
|
check('après commit staged : README committé, untracked restant', !paths2.includes('README.md') && paths2.includes('untracked.txt'));
|
||||||
|
|
||||||
|
// ---- API fichiers (Monaco) : GET content + PUT + refus traversal ----
|
||||||
|
const get1 = await (await j(`/api/v1/repos/${repoId}/files/content?wt=${enc}&path=untracked.txt`, 'GET', cookie)).json();
|
||||||
|
check('GET /files/content : contenu lu + langage', get1.content === 'new\n');
|
||||||
|
const put = await j(`/api/v1/repos/${repoId}/files/content`, 'PUT', cookie, { wt: repo, path: 'src/app.ts', content: 'export const x = 1\n' });
|
||||||
|
check('PUT /files/content (création) → 200', put.status === 200);
|
||||||
|
const get2 = await (await j(`/api/v1/repos/${repoId}/files/content?wt=${enc}&path=src/app.ts`, 'GET', cookie)).json();
|
||||||
|
check('GET après PUT : contenu écrit + langage typescript', get2.content === 'export const x = 1\n' && get2.language === 'typescript');
|
||||||
|
const trav = await j(`/api/v1/repos/${repoId}/files/content?wt=${enc}&path=${encodeURIComponent('../escape.txt')}`, 'GET', cookie);
|
||||||
|
check('GET /files/content : traversal ../ refusé', trav.status === 400 || trav.status === 403);
|
||||||
|
|
||||||
|
// ---- temps réel : watch → worktree_changes à l'édition ----
|
||||||
|
c.send({ type: 'watch', repoId, path: repo });
|
||||||
|
await sleep(900); // laisse chokidar finir son scan initial
|
||||||
|
const t0 = Date.now();
|
||||||
|
writeFileSync(join(repo, 'live.txt'), 'live edit\n');
|
||||||
|
const changesMsg = await c.waitMsg((m) => m.type === 'worktree_changes' && m.path === repo, 6000);
|
||||||
|
check('watch → worktree_changes ciblé reçu', !!changesMsg, changesMsg ? `${Date.now() - t0}ms` : 'timeout');
|
||||||
|
const updMsg = await c.waitMsg((m) => m.type === 'worktree_update' && m.worktree?.path === repo, 3000);
|
||||||
|
check('édition → worktree_update diffusé', !!updMsg);
|
||||||
|
|
||||||
|
// ---- checkout externe (CLI) → worktree_update avec nouvelle branche ----
|
||||||
|
c.state.msgs.length = 0; // reset pour ne capter que les nouveaux events
|
||||||
|
git('branch', 'feature');
|
||||||
|
git('checkout', 'feature');
|
||||||
|
const branchMsg = await c.waitMsg((m) => m.type === 'worktree_update' && m.worktree?.isMain && m.worktree?.branch === 'feature', 6000);
|
||||||
|
check('checkout externe → branche principale mise à jour en temps réel', !!branchMsg);
|
||||||
|
|
||||||
|
// ---- unwatch : plus de worktree_changes ----
|
||||||
|
c.send({ type: 'unwatch', repoId, path: repo });
|
||||||
|
await sleep(300);
|
||||||
|
c.state.msgs.length = 0;
|
||||||
|
writeFileSync(join(repo, 'after-unwatch.txt'), 'x\n');
|
||||||
|
const afterUnwatch = await c.waitMsg((m) => m.type === 'worktree_changes', 1500);
|
||||||
|
check('unwatch → plus de worktree_changes', !afterUnwatch);
|
||||||
|
|
||||||
|
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 P7: ALL GREEN' : `\nACCEPTANCE P7: ${failed.length} FAILURE(S)`);
|
||||||
|
process.exit(failed.length === 0 ? 0 : 1);
|
||||||
|
}
|
||||||
122
packages/server/scripts/acceptance-p8.mjs
Normal file
122
packages/server/scripts/acceptance-p8.mjs
Normal file
@@ -0,0 +1,122 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Acceptation P8 (sans navigateur) : API fichiers de l'éditeur Monaco + garde-fou conflit (mtime).
|
||||||
|
// Vrai daemon + vrai repo git tmp. Couvre : GET content (+mtime), PUT avec baseMtime correct → 200,
|
||||||
|
// PUT avec baseMtime périmé → 409 STALE_FILE, PUT sans baseMtime (overwrite) → 200, diff après
|
||||||
|
// édition cohérent, fs/list?includeFiles=1 (isFile), refus de traversal.
|
||||||
|
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';
|
||||||
|
|
||||||
|
const PORT = 7552;
|
||||||
|
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-p8-'));
|
||||||
|
const repo = join(tmp, 'demo-repo');
|
||||||
|
execFileSync('mkdir', ['-p', repo]);
|
||||||
|
const git = (...args) => execFileSync('git', args, { cwd: repo, stdio: 'pipe' });
|
||||||
|
git('init', '-b', 'main');
|
||||||
|
git('config', 'user.email', 'test@arboretum.dev');
|
||||||
|
git('config', 'user.name', 'Test');
|
||||||
|
writeFileSync(join(repo, 'README.md'), '# demo\n');
|
||||||
|
git('add', '-A');
|
||||||
|
git('commit', '-m', 'init');
|
||||||
|
|
||||||
|
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));
|
||||||
|
|
||||||
|
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 addRepo = await j('/api/v1/repos', 'POST', cookie, { path: repo });
|
||||||
|
const repoId = (await addRepo.json()).repo.id;
|
||||||
|
check('POST /repos → 201', addRepo.status === 201 && !!repoId);
|
||||||
|
const enc = encodeURIComponent(repo);
|
||||||
|
|
||||||
|
// ---- GET content : contenu + mtime ----
|
||||||
|
const get1 = await (await j(`/api/v1/repos/${repoId}/files/content?wt=${enc}&path=README.md`, 'GET', cookie)).json();
|
||||||
|
check('GET /files/content : contenu + mtime', get1.content === '# demo\n' && typeof get1.mtime === 'number');
|
||||||
|
const mtime0 = get1.mtime;
|
||||||
|
|
||||||
|
// ---- PUT avec baseMtime correct → 200 + nouveau mtime ----
|
||||||
|
const put1 = await j('/api/v1/repos/' + repoId + '/files/content', 'PUT', cookie, {
|
||||||
|
wt: repo, path: 'README.md', content: '# demo\nedited via editor\n', baseMtime: mtime0,
|
||||||
|
});
|
||||||
|
const put1Body = await put1.json();
|
||||||
|
check('PUT (baseMtime correct) → 200 + mtime', put1.status === 200 && typeof put1Body.mtime === 'number');
|
||||||
|
|
||||||
|
// ---- PUT avec baseMtime périmé (l'ancien) → 409 STALE_FILE ----
|
||||||
|
const putStale = await j('/api/v1/repos/' + repoId + '/files/content', 'PUT', cookie, {
|
||||||
|
wt: repo, path: 'README.md', content: 'concurrent overwrite\n', baseMtime: mtime0,
|
||||||
|
});
|
||||||
|
const staleBody = await putStale.json();
|
||||||
|
check('PUT (baseMtime périmé) → 409 STALE_FILE', putStale.status === 409 && staleBody.error?.code === 'STALE_FILE');
|
||||||
|
|
||||||
|
// ---- PUT sans baseMtime (overwrite forcé) → 200 ----
|
||||||
|
const putForce = await j('/api/v1/repos/' + repoId + '/files/content', 'PUT', cookie, {
|
||||||
|
wt: repo, path: 'README.md', content: '# demo\nforced\n',
|
||||||
|
});
|
||||||
|
check('PUT (sans baseMtime, overwrite) → 200', putForce.status === 200);
|
||||||
|
|
||||||
|
// ---- diff après édition ----
|
||||||
|
const ch = await (await j(`/api/v1/repos/${repoId}/worktrees/changes?path=${enc}`, 'GET', cookie)).json();
|
||||||
|
check('GET /changes : README.md modifié', (ch.changes ?? []).some((c) => c.path === 'README.md' && c.unstaged));
|
||||||
|
const diff = await (await j(`/api/v1/repos/${repoId}/worktrees/diff?path=${enc}&file=README.md`, 'GET', cookie)).json();
|
||||||
|
check('GET /diff : contient la ligne ajoutée', typeof diff.diff === 'string' && diff.diff.includes('+forced'));
|
||||||
|
|
||||||
|
// ---- création d'un nouveau fichier + lecture du langage ----
|
||||||
|
const putNew = await j('/api/v1/repos/' + repoId + '/files/content', 'PUT', cookie, { wt: repo, path: 'src/app.ts', content: 'export const x = 1\n' });
|
||||||
|
check('PUT (création src/app.ts) → 200', putNew.status === 200);
|
||||||
|
const getNew = await (await j(`/api/v1/repos/${repoId}/files/content?wt=${enc}&path=src/app.ts`, 'GET', cookie)).json();
|
||||||
|
check('GET nouveau fichier : langage typescript', getNew.language === 'typescript');
|
||||||
|
|
||||||
|
// ---- fs/list?includeFiles=1 : remonte les fichiers (arbre IDE) ----
|
||||||
|
const fs = await (await j(`/api/v1/fs/list?path=${enc}&includeFiles=1`, 'GET', cookie)).json();
|
||||||
|
const readme = (fs.entries ?? []).find((e) => e.name === 'README.md');
|
||||||
|
check('fs/list?includeFiles=1 : README.md (isFile)', readme?.isFile === true);
|
||||||
|
|
||||||
|
// ---- refus de traversal ----
|
||||||
|
const trav = await j(`/api/v1/repos/${repoId}/files/content`, 'PUT', cookie, { wt: repo, path: '../escape.txt', content: 'x' });
|
||||||
|
check('PUT traversal ../ refusé', trav.status === 400 || trav.status === 403);
|
||||||
|
} 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 P8: ALL GREEN' : `\nACCEPTANCE P8: ${failed.length} FAILURE(S)`);
|
||||||
|
process.exit(failed.length === 0 ? 0 : 1);
|
||||||
|
}
|
||||||
128
packages/server/scripts/acceptance-p9.mjs
Normal file
128
packages/server/scripts/acceptance-p9.mjs
Normal file
@@ -0,0 +1,128 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Acceptation P9 (sans navigateur) : cycle git propre depuis l'UI (primitives P7). Vrai daemon +
|
||||||
|
// vrai repo git tmp + remote bare local (file://). Couvre : staging sélectif → commit ne prend QUE
|
||||||
|
// le sélectionné ; amend d'un commit NON poussé → OK (HEAD change) ; amend d'un commit POUSSÉ → 409
|
||||||
|
// ALREADY_PUSHED ; pull --ff-only fast-forward → OK ; pull en divergence → refusé proprement.
|
||||||
|
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';
|
||||||
|
|
||||||
|
const PORT = 7553;
|
||||||
|
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-p9-'));
|
||||||
|
const repo = join(tmp, 'repo');
|
||||||
|
const bare = join(tmp, 'bare.git');
|
||||||
|
const clone2 = join(tmp, 'clone2');
|
||||||
|
const g = (cwd, ...args) => execFileSync('git', args, { cwd, stdio: 'pipe' }).toString();
|
||||||
|
const cfg = (cwd) => {
|
||||||
|
g(cwd, 'config', 'user.email', 'test@arboretum.dev');
|
||||||
|
g(cwd, 'config', 'user.name', 'Test');
|
||||||
|
};
|
||||||
|
|
||||||
|
execFileSync('mkdir', ['-p', repo]);
|
||||||
|
g(repo, 'init', '-b', 'main');
|
||||||
|
cfg(repo);
|
||||||
|
writeFileSync(join(repo, 'a.txt'), 'a\n');
|
||||||
|
g(repo, 'add', '-A');
|
||||||
|
g(repo, 'commit', '-m', 'init');
|
||||||
|
execFileSync('git', ['init', '--bare', bare], { stdio: 'pipe' });
|
||||||
|
g(bare, 'symbolic-ref', 'HEAD', 'refs/heads/main'); // pour que les clones se placent sur main
|
||||||
|
g(repo, 'remote', 'add', 'origin', bare);
|
||||||
|
g(repo, 'push', '-u', 'origin', 'main');
|
||||||
|
|
||||||
|
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));
|
||||||
|
|
||||||
|
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 addRepo = await j('/api/v1/repos', 'POST', cookie, { path: repo });
|
||||||
|
const repoId = (await addRepo.json()).repo.id;
|
||||||
|
check('POST /repos → 201', addRepo.status === 201 && !!repoId);
|
||||||
|
const enc = encodeURIComponent(repo);
|
||||||
|
const changes = async () => (await (await j(`/api/v1/repos/${repoId}/worktrees/changes?path=${enc}`, 'GET', cookie)).json()).changes ?? [];
|
||||||
|
|
||||||
|
// ---- staging sélectif : modifier 2 fichiers, n'indexer que a.txt, committer staged ----
|
||||||
|
writeFileSync(join(repo, 'a.txt'), 'a modified\n');
|
||||||
|
writeFileSync(join(repo, 'b.txt'), 'b new\n');
|
||||||
|
await j(`/api/v1/repos/${repoId}/worktrees/stage`, 'POST', cookie, { path: repo, files: ['a.txt'] });
|
||||||
|
const commit1 = await j(`/api/v1/repos/${repoId}/worktrees/commit`, 'POST', cookie, { path: repo, message: 'only a', mode: 'staged' });
|
||||||
|
check('commit (staged) → 200', commit1.status === 200);
|
||||||
|
const afterCommit = (await changes()).map((c) => c.path);
|
||||||
|
check('commit ne prend QUE le fichier indexé (b.txt reste, a.txt committé)', !afterCommit.includes('a.txt') && afterCommit.includes('b.txt'));
|
||||||
|
check('a.txt présent dans le dernier commit', g(repo, 'show', '--name-only', '--format=', 'HEAD').includes('a.txt'));
|
||||||
|
|
||||||
|
// ---- amend d'un commit NON poussé → OK, le sujet de HEAD change ----
|
||||||
|
const amendOk = await j(`/api/v1/repos/${repoId}/worktrees/commit`, 'POST', cookie, { path: repo, message: 'only a (amended)', amend: true });
|
||||||
|
check('amend (commit non poussé) → 200', amendOk.status === 200);
|
||||||
|
check('amend modifie le sujet de HEAD', g(repo, 'log', '-1', '--format=%s').trim() === 'only a (amended)');
|
||||||
|
|
||||||
|
// ---- push, puis amend d'un commit POUSSÉ → 409 ALREADY_PUSHED ----
|
||||||
|
const push = await j(`/api/v1/repos/${repoId}/worktrees/push`, 'POST', cookie, { path: repo });
|
||||||
|
check('push → 200', push.status === 200);
|
||||||
|
const amendPushed = await j(`/api/v1/repos/${repoId}/worktrees/commit`, 'POST', cookie, { path: repo, message: 'too late', amend: true });
|
||||||
|
const amendBody = await amendPushed.json();
|
||||||
|
check('amend (commit poussé) → 409 ALREADY_PUSHED', amendPushed.status === 409 && amendBody.error?.code === 'ALREADY_PUSHED');
|
||||||
|
|
||||||
|
// ---- pull --ff-only : un commit distant en avance → fast-forward OK ----
|
||||||
|
execFileSync('git', ['clone', bare, clone2], { stdio: 'pipe' });
|
||||||
|
cfg(clone2);
|
||||||
|
writeFileSync(join(clone2, 'c.txt'), 'c\n');
|
||||||
|
g(clone2, 'add', '-A');
|
||||||
|
g(clone2, 'commit', '-m', 'remote commit');
|
||||||
|
g(clone2, 'push', 'origin', 'main');
|
||||||
|
await j(`/api/v1/repos/${repoId}/worktrees/fetch`, 'POST', cookie, { path: repo });
|
||||||
|
const pullFf = await j(`/api/v1/repos/${repoId}/worktrees/pull`, 'POST', cookie, { path: repo, mode: 'ff-only' });
|
||||||
|
check('pull --ff-only (fast-forward) → 200', pullFf.status === 200);
|
||||||
|
check('le commit distant est intégré (remote commit dans l’historique)', g(repo, 'log', '--format=%s').includes('remote commit'));
|
||||||
|
|
||||||
|
// ---- divergence : commit local non poussé + commit distant → pull --ff-only refusé ----
|
||||||
|
writeFileSync(join(repo, 'a.txt'), 'a local divergent\n');
|
||||||
|
await j(`/api/v1/repos/${repoId}/worktrees/commit`, 'POST', cookie, { path: repo, message: 'local divergent', mode: 'all' });
|
||||||
|
writeFileSync(join(clone2, 'd.txt'), 'd\n');
|
||||||
|
g(clone2, 'add', '-A');
|
||||||
|
g(clone2, 'commit', '-m', 'remote divergent');
|
||||||
|
g(clone2, 'push', 'origin', 'main');
|
||||||
|
await j(`/api/v1/repos/${repoId}/worktrees/fetch`, 'POST', cookie, { path: repo });
|
||||||
|
const pullDiv = await j(`/api/v1/repos/${repoId}/worktrees/pull`, 'POST', cookie, { path: repo, mode: 'ff-only' });
|
||||||
|
check('pull --ff-only en divergence → refusé (non-200)', pullDiv.status !== 200, `status=${pullDiv.status}`);
|
||||||
|
} 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 P9: ALL GREEN' : `\nACCEPTANCE P9: ${failed.length} FAILURE(S)`);
|
||||||
|
process.exit(failed.length === 0 ? 0 : 1);
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
// Embarque la SPA buildée (packages/web/dist) dans public/ du package server,
|
// Embarque la SPA buildée (packages/web/dist) dans public/ du package server,
|
||||||
// pour que le tarball npm soit autonome. Branché sur le hook "prepack".
|
// pour que le tarball npm soit autonome. Branché sur le hook "prepack".
|
||||||
// ARBORETUM_PACK_NO_WEB=1 : mode tolérant (CI/smoke) — placeholder à la place du front.
|
// ARBORETUM_PACK_NO_WEB=1 : mode tolérant (CI/smoke), placeholder à la place du front.
|
||||||
import { cpSync, existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
import { cpSync, existsSync, mkdirSync, rmSync, writeFileSync } 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';
|
||||||
@@ -19,10 +19,10 @@ if (!existsSync(webDist)) {
|
|||||||
'<!doctype html>\n<html lang="en">\n<head><meta charset="utf-8"><title>Arboretum</title></head>\n' +
|
'<!doctype html>\n<html lang="en">\n<head><meta charset="utf-8"><title>Arboretum</title></head>\n' +
|
||||||
'<body><p>Arboretum server is running, but this package was built without the web UI.</p></body>\n</html>\n',
|
'<body><p>Arboretum server is running, but this package was built without the web UI.</p></body>\n</html>\n',
|
||||||
);
|
);
|
||||||
console.log('copy-web: ARBORETUM_PACK_NO_WEB=1 — wrote placeholder public/index.html');
|
console.log('copy-web: ARBORETUM_PACK_NO_WEB=1: wrote placeholder public/index.html');
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
}
|
}
|
||||||
console.error(`copy-web: ${webDist} not found — run npm run build -w @arboretum/web first`);
|
console.error(`copy-web: ${webDist} not found: run npm run build -w @arboretum/web first`);
|
||||||
process.exit(1);
|
process.exit(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';
|
||||||
@@ -10,17 +10,59 @@ import type { Db } from './db/index.js';
|
|||||||
import { AuthService, LoginRateLimiter, type AuthContext } from './auth/service.js';
|
import { AuthService, LoginRateLimiter, type AuthContext } from './auth/service.js';
|
||||||
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 { SessionArchiveService } from './core/session-archive.js';
|
||||||
|
import { SettingsBus } from './core/settings-bus.js';
|
||||||
|
import { GitCredentialsManager } from './core/git-credentials.js';
|
||||||
|
import { CloneManager } from './core/clone-manager.js';
|
||||||
|
import { registerGitConnectionRoutes } from './routes/git-connections.js';
|
||||||
import { WorktreeManager } from './core/worktree-manager.js';
|
import { WorktreeManager } from './core/worktree-manager.js';
|
||||||
|
import { RepoDiscoveryService } from './core/repo-discovery.js';
|
||||||
import { GroupManager } from './core/group-manager.js';
|
import { GroupManager } from './core/group-manager.js';
|
||||||
import { PushService } from './core/push-service.js';
|
import { PushService } from './core/push-service.js';
|
||||||
|
import { loadSecretBox } from './core/secret-box.js';
|
||||||
import { registerAuthRoutes } from './routes/auth.js';
|
import { registerAuthRoutes } from './routes/auth.js';
|
||||||
import { registerSessionRoutes } from './routes/sessions.js';
|
import { registerSessionRoutes } from './routes/sessions.js';
|
||||||
|
import { registerProjectRoutes } from './routes/projects.js';
|
||||||
import { registerRepoRoutes } from './routes/repos.js';
|
import { registerRepoRoutes } from './routes/repos.js';
|
||||||
import { registerGroupRoutes } from './routes/groups.js';
|
import { registerGroupRoutes } from './routes/groups.js';
|
||||||
import { registerWorktreeRoutes } from './routes/worktrees.js';
|
import { registerWorktreeRoutes } from './routes/worktrees.js';
|
||||||
|
import { registerGitRoutes } from './routes/git.js';
|
||||||
|
import { registerFileRoutes } from './routes/files.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 { FsWatcherService } from './core/fs-watcher.js';
|
||||||
|
import { registerAuditRoutes } from './routes/audit.js';
|
||||||
|
import { registerDataRoutes } from './routes/data.js';
|
||||||
import { registerWsGateway } from './ws/gateway.js';
|
import { registerWsGateway } from './ws/gateway.js';
|
||||||
|
import { isHttpsRequest } from './routes/auth.js';
|
||||||
|
|
||||||
|
// En-têtes de sécurité posés sur TOUTES les réponses (defense-in-depth + conformité scanners
|
||||||
|
// entreprise). Le terminal web reste du RCE par conception : ces en-têtes durcissent la SPA et
|
||||||
|
// le transport, ils ne remplacent pas le modèle loopback + auth + Origin.
|
||||||
|
const SECURITY_HEADERS: Record<string, string> = {
|
||||||
|
'X-Content-Type-Options': 'nosniff',
|
||||||
|
'X-Frame-Options': 'DENY',
|
||||||
|
'Referrer-Policy': 'no-referrer',
|
||||||
|
'Cross-Origin-Opener-Policy': 'same-origin',
|
||||||
|
'Permissions-Policy': 'geolocation=(), microphone=(), camera=(), payment=()',
|
||||||
|
// CSP calibrée pour la SPA : Tailwind/xterm injectent du style inline ; le WebSocket impose
|
||||||
|
// ws:/wss: en connect-src ; le service worker push impose worker-src 'self'.
|
||||||
|
'Content-Security-Policy': [
|
||||||
|
"default-src 'self'",
|
||||||
|
"script-src 'self'",
|
||||||
|
"style-src 'self' 'unsafe-inline'",
|
||||||
|
"img-src 'self' data:",
|
||||||
|
"font-src 'self' data:",
|
||||||
|
"connect-src 'self' ws: wss:",
|
||||||
|
"worker-src 'self'",
|
||||||
|
"manifest-src 'self'",
|
||||||
|
"frame-ancestors 'none'",
|
||||||
|
"base-uri 'self'",
|
||||||
|
"object-src 'none'",
|
||||||
|
"form-action 'self'",
|
||||||
|
].join('; '),
|
||||||
|
};
|
||||||
|
|
||||||
declare module 'fastify' {
|
declare module 'fastify' {
|
||||||
interface FastifyRequest {
|
interface FastifyRequest {
|
||||||
@@ -36,24 +78,82 @@ export interface AppBundle {
|
|||||||
auth: AuthService;
|
auth: AuthService;
|
||||||
manager: PtyManager;
|
manager: PtyManager;
|
||||||
discovery: DiscoveryService;
|
discovery: DiscoveryService;
|
||||||
|
sessionArchive: SessionArchiveService;
|
||||||
|
repoDiscovery: RepoDiscoveryService;
|
||||||
worktrees: WorktreeManager;
|
worktrees: WorktreeManager;
|
||||||
groups: GroupManager;
|
groups: GroupManager;
|
||||||
push: PushService;
|
push: PushService;
|
||||||
|
fsWatcher: FsWatcherService;
|
||||||
|
settingsBus: SettingsBus;
|
||||||
|
gitCredentials: GitCredentialsManager;
|
||||||
|
clones: CloneManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
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);
|
// Archivage auto des sessions terminées (P10). Démarré dans runDaemon() : jamais ici (tests).
|
||||||
|
const sessionArchive = new SessionArchiveService({ db });
|
||||||
|
// Watcher FS temps réel (P7) : armé à la demande sur les worktrees regardés via les commandes
|
||||||
|
// WS watch/unwatch. closeAll() au drain (libération des descripteurs).
|
||||||
|
const fsWatcher = new FsWatcherService();
|
||||||
|
const worktrees = new WorktreeManager(db, manager, discovery, fsWatcher);
|
||||||
|
// Démarré dans runDaemon() (jamais ici) → le scan ne tourne pas pendant les tests qui appellent buildApp.
|
||||||
|
const repoDiscovery = new RepoDiscoveryService(db, worktrees);
|
||||||
const groups = new GroupManager(db);
|
const groups = new GroupManager(db);
|
||||||
|
// P11 · bus de diffusion des réglages : PATCH /settings émet, la gateway relaie au topic 'settings'.
|
||||||
|
const settingsBus = new SettingsBus();
|
||||||
|
// P12 · services git distants : `box` (SecretBox) câblé ici pour chiffrer les secrets des credentials.
|
||||||
|
const gitCredentials = new GitCredentialsManager(db, box);
|
||||||
|
const clones = new CloneManager(db, worktrees, gitCredentials);
|
||||||
|
|
||||||
|
// 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, {
|
||||||
@@ -76,7 +176,7 @@ export function buildApp(config: Config, db: Db, serverVersion: string): AppBund
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Garde globale : auth sur tout /api/** et /ws ; check Origin strict quand l'en-tête est présent
|
// Garde globale : auth sur tout /api/** et /ws ; check Origin strict quand l'en-tête est présent
|
||||||
// (anti cross-site WebSocket hijacking — le cookie SameSite=Strict ne suffit pas pour les upgrades).
|
// (anti cross-site WebSocket hijacking : le cookie SameSite=Strict ne suffit pas pour les upgrades).
|
||||||
app.addHook('preValidation', async (req, reply) => {
|
app.addHook('preValidation', async (req, reply) => {
|
||||||
const isApi = req.url.startsWith('/api/');
|
const isApi = req.url.startsWith('/api/');
|
||||||
const isWs = req.url.startsWith('/ws');
|
const isWs = req.url.startsWith('/ws');
|
||||||
@@ -92,20 +192,27 @@ 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, sessionArchive, db);
|
||||||
registerRepoRoutes(app, worktrees);
|
registerProjectRoutes(app, manager, db);
|
||||||
registerGroupRoutes(app, groups);
|
registerRepoRoutes(app, worktrees, db);
|
||||||
registerWorktreeRoutes(app, worktrees);
|
registerGroupRoutes(app, groups, db, worktrees, manager);
|
||||||
registerPushRoutes(app, push);
|
registerWorktreeRoutes(app, worktrees, db);
|
||||||
|
registerGitRoutes(app, worktrees, db);
|
||||||
|
registerFileRoutes(app, worktrees, db);
|
||||||
|
registerPushRoutes(app, push, db);
|
||||||
|
registerSettingsRoutes(app, db, config, serverVersion, push, settingsBus);
|
||||||
|
registerGitConnectionRoutes(app, gitCredentials, clones, db);
|
||||||
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, groups, serverVersion);
|
registerWsGateway(scoped, manager, discovery, sessionArchive, worktrees, groups, settingsBus, clones, 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)
|
||||||
const publicDir = join(dirname(fileURLToPath(import.meta.url)), '..', 'public');
|
const publicDir = join(dirname(fileURLToPath(import.meta.url)), '..', 'public');
|
||||||
if (existsSync(publicDir)) {
|
if (existsSync(publicDir)) {
|
||||||
void app.register(fastifyStatic, { root: publicDir, wildcard: false });
|
void app.register(fastifyStatic, { root: publicDir, wildcard: false });
|
||||||
@@ -117,5 +224,5 @@ export function buildApp(config: Config, db: Db, serverVersion: string): AppBund
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return { app, auth, manager, discovery, worktrees, groups, push };
|
return { app, auth, manager, discovery, sessionArchive, repoDiscovery, worktrees, groups, push, fsWatcher, settingsBus, gitCredentials, clones };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -122,11 +122,16 @@ function quoteIfNeeded(token: string): string {
|
|||||||
return /\s/.test(token) ? `"${token}"` : token;
|
return /\s/.test(token) ? `"${token}"` : token;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function renderSystemdUnit(input: { exec: string; scriptArgs: string[] }): string {
|
export function renderSystemdUnit(input: { exec: string; scriptArgs: string[]; pathEnv?: string | undefined }): string {
|
||||||
const execStart = [input.exec, ...input.scriptArgs].map(quoteIfNeeded).join(' ');
|
const execStart = [input.exec, ...input.scriptArgs].map(quoteIfNeeded).join(' ');
|
||||||
|
// Un service systemd user démarre avec un PATH minimal (typiquement /usr/bin:/bin…) qui n'inclut
|
||||||
|
// PAS ~/.local/bin ni le bin npm/nvm où vit le CLI `claude` → resolveClaudeBin() (`which claude`)
|
||||||
|
// échouerait. On fige donc le PATH de l'environnement d'installation, où `claude` est résolvable.
|
||||||
|
// Doubles quotes systemd : tolèrent un chemin du PATH contenant des espaces.
|
||||||
|
const pathLine = input.pathEnv ? `\nEnvironment="PATH=${input.pathEnv}"` : '';
|
||||||
// KillSignal=SIGTERM + TimeoutStopSec=10 collent au drain de runDaemon (SIGTERM → drain 1s → close).
|
// KillSignal=SIGTERM + TimeoutStopSec=10 collent au drain de runDaemon (SIGTERM → drain 1s → close).
|
||||||
return `[Unit]
|
return `[Unit]
|
||||||
Description=Arboretum — git worktree & Claude Code dashboard
|
Description=Arboretum · git worktree & Claude Code dashboard
|
||||||
After=network-online.target
|
After=network-online.target
|
||||||
Wants=network-online.target
|
Wants=network-online.target
|
||||||
|
|
||||||
@@ -136,7 +141,7 @@ Restart=on-failure
|
|||||||
RestartSec=5
|
RestartSec=5
|
||||||
KillSignal=SIGTERM
|
KillSignal=SIGTERM
|
||||||
TimeoutStopSec=10
|
TimeoutStopSec=10
|
||||||
Environment=NODE_ENV=production
|
Environment=NODE_ENV=production${pathLine}
|
||||||
|
|
||||||
[Install]
|
[Install]
|
||||||
WantedBy=default.target
|
WantedBy=default.target
|
||||||
@@ -148,8 +153,14 @@ export function renderLaunchAgentPlist(input: {
|
|||||||
programArguments: string[];
|
programArguments: string[];
|
||||||
stdoutPath: string;
|
stdoutPath: string;
|
||||||
stderrPath: string;
|
stderrPath: string;
|
||||||
|
pathEnv?: string | undefined;
|
||||||
}): string {
|
}): string {
|
||||||
const args = input.programArguments.map((a) => ` <string>${xmlEscape(a)}</string>`).join('\n');
|
const args = input.programArguments.map((a) => ` <string>${xmlEscape(a)}</string>`).join('\n');
|
||||||
|
// launchd démarre un LaunchAgent avec un PATH minimal qui n'inclut pas ~/.local/bin ni le bin
|
||||||
|
// npm/nvm où vit le CLI `claude` → resolveClaudeBin() échouerait. On fige le PATH d'installation.
|
||||||
|
const pathEntry = input.pathEnv
|
||||||
|
? `\n <key>PATH</key>\n <string>${xmlEscape(input.pathEnv)}</string>`
|
||||||
|
: '';
|
||||||
// KeepAlive/SuccessfulExit=false ≈ Restart=on-failure (ne relance pas après un drain volontaire).
|
// KeepAlive/SuccessfulExit=false ≈ Restart=on-failure (ne relance pas après un drain volontaire).
|
||||||
return `<?xml version="1.0" encoding="UTF-8"?>
|
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">
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
@@ -175,7 +186,7 @@ ${args}
|
|||||||
<key>EnvironmentVariables</key>
|
<key>EnvironmentVariables</key>
|
||||||
<dict>
|
<dict>
|
||||||
<key>NODE_ENV</key>
|
<key>NODE_ENV</key>
|
||||||
<string>production</string>
|
<string>production</string>${pathEntry}
|
||||||
</dict>
|
</dict>
|
||||||
</dict>
|
</dict>
|
||||||
</plist>
|
</plist>
|
||||||
@@ -184,14 +195,14 @@ ${args}
|
|||||||
|
|
||||||
export function printTokenBanner(token: string, url: string): void {
|
export function printTokenBanner(token: string, url: string): void {
|
||||||
console.log('\n┌──────────────────────────────────────────────────────────────────┐');
|
console.log('\n┌──────────────────────────────────────────────────────────────────┐');
|
||||||
console.log('│ First start — your access token (shown once, store it safely): │');
|
console.log('│ First start : your access token (shown once, store it safely): │');
|
||||||
console.log('└──────────────────────────────────────────────────────────────────┘');
|
console.log('└──────────────────────────────────────────────────────────────────┘');
|
||||||
console.log(`\n ${token}\n`);
|
console.log(`\n ${token}\n`);
|
||||||
console.log(` Login at: ${url}/\n`);
|
console.log(` Login at: ${url}/\n`);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function printUsage(version: string): void {
|
export function printUsage(version: string): void {
|
||||||
console.log(`Arboretum v${version} — git worktree & Claude Code dashboard
|
console.log(`Arboretum v${version} · git worktree & Claude Code dashboard
|
||||||
|
|
||||||
Usage:
|
Usage:
|
||||||
arboretum [flags] Start the daemon (default)
|
arboretum [flags] Start the daemon (default)
|
||||||
@@ -207,7 +218,7 @@ Daemon flags:
|
|||||||
--allow-origin <url> Additional allowed Origin (repeatable)
|
--allow-origin <url> Additional allowed Origin (repeatable)
|
||||||
--db <path> SQLite database path
|
--db <path> SQLite database path
|
||||||
--vapid-contact <mailto|url> VAPID contact subject for Web Push
|
--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)
|
--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):
|
Install flags (daemon flags above are propagated to the service):
|
||||||
--bin-path <path> Use this binary in the service instead of node + script
|
--bin-path <path> Use this binary in the service instead of node + script
|
||||||
@@ -246,7 +257,7 @@ function bootstrapToken(serviceArgs: string[]): void {
|
|||||||
try {
|
try {
|
||||||
const token = new AuthService(db).ensureBootstrapToken();
|
const token = new AuthService(db).ensureBootstrapToken();
|
||||||
if (token) printTokenBanner(token, url);
|
if (token) printTokenBanner(token, url);
|
||||||
else console.log('\nAn access token already exists in this database — manage tokens from Settings.\n');
|
else console.log('\nAn access token already exists in this database. Manage tokens from Settings.\n');
|
||||||
} finally {
|
} finally {
|
||||||
db.close();
|
db.close();
|
||||||
}
|
}
|
||||||
@@ -258,9 +269,12 @@ export async function runInstall(argv: string[]): Promise<void> {
|
|||||||
const serviceArgs = buildServiceArgs(flags);
|
const serviceArgs = buildServiceArgs(flags);
|
||||||
const { exec, args: binArgs } = resolveBin(flags);
|
const { exec, args: binArgs } = resolveBin(flags);
|
||||||
const scriptArgs = [...binArgs, ...serviceArgs];
|
const scriptArgs = [...binArgs, ...serviceArgs];
|
||||||
|
// PATH de l'environnement d'installation (shell interactif où `claude` est résolvable) : on le
|
||||||
|
// fige dans l'unit/plist car systemd/launchd démarrent le service avec un PATH minimal.
|
||||||
|
const pathEnv = process.env.PATH;
|
||||||
|
|
||||||
if (platform === 'linux') {
|
if (platform === 'linux') {
|
||||||
const unit = renderSystemdUnit({ exec, scriptArgs });
|
const unit = renderSystemdUnit({ exec, scriptArgs, pathEnv });
|
||||||
const unitPath = systemdUnitPath();
|
const unitPath = systemdUnitPath();
|
||||||
if (flags.dryRun) {
|
if (flags.dryRun) {
|
||||||
console.log(`# ${unitPath}\n${unit}\n# commands:`);
|
console.log(`# ${unitPath}\n${unit}\n# commands:`);
|
||||||
@@ -280,7 +294,7 @@ export async function runInstall(argv: string[]): Promise<void> {
|
|||||||
run('systemctl', ['--user', 'enable', '--now', SERVICE_NAME], { check: true });
|
run('systemctl', ['--user', 'enable', '--now', SERVICE_NAME], { check: true });
|
||||||
// enable-linger best-effort : absent en CI / sans session loginctl, non bloquant.
|
// enable-linger best-effort : absent en CI / sans session loginctl, non bloquant.
|
||||||
if (run('loginctl', ['enable-linger', process.env.USER ?? '']) !== 0) {
|
if (run('loginctl', ['enable-linger', process.env.USER ?? '']) !== 0) {
|
||||||
console.warn('Warning: could not enable linger — the service may not start at boot.');
|
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`);
|
console.log(`\nArboretum service installed. Logs: journalctl --user -u ${SERVICE_NAME} -f`);
|
||||||
@@ -295,6 +309,7 @@ export async function runInstall(argv: string[]): Promise<void> {
|
|||||||
programArguments,
|
programArguments,
|
||||||
stdoutPath: logs.out,
|
stdoutPath: logs.out,
|
||||||
stderrPath: logs.err,
|
stderrPath: logs.err,
|
||||||
|
pathEnv,
|
||||||
});
|
});
|
||||||
const plistPath = launchAgentPlistPath(flags.label);
|
const plistPath = launchAgentPlistPath(flags.label);
|
||||||
const uid = process.getuid?.() ?? 0;
|
const uid = process.getuid?.() ?? 0;
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -11,12 +11,18 @@ export interface Config {
|
|||||||
/** origins supplémentaires autorisées (ex. https://machine.tailnet.ts.net) */
|
/** origins supplémentaires autorisées (ex. https://machine.tailnet.ts.net) */
|
||||||
allowedOrigins: string[];
|
allowedOrigins: string[];
|
||||||
printToken: boolean;
|
printToken: boolean;
|
||||||
/** ~/.claude/projects (transcripts JSONL) — surchargeable via --claude-home (tests). */
|
/** racine effective de l'install Claude (~/.claude par défaut, --claude-home, ou réglage claude_home). */
|
||||||
|
claudeHome: string;
|
||||||
|
/** true si --claude-home a été passé explicitement → a priorité sur le réglage claude_home. */
|
||||||
|
claudeHomeFromFlag: boolean;
|
||||||
|
/** ~/.claude/projects (transcripts JSONL) : surchargeable via --claude-home (tests). */
|
||||||
claudeProjectsDir: string;
|
claudeProjectsDir: string;
|
||||||
/** ~/.claude/sessions (registre des sessions CLI vivantes). */
|
/** ~/.claude/sessions (registre des sessions CLI vivantes). */
|
||||||
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 {
|
||||||
@@ -29,10 +35,12 @@ export function loadConfig(argv = process.argv.slice(2)): Config {
|
|||||||
'allow-origin': { type: 'string', multiple: true },
|
'allow-origin': { type: 'string', multiple: true },
|
||||||
'print-token': { type: 'boolean', default: false },
|
'print-token': { type: 'boolean', default: false },
|
||||||
'i-know-this-exposes-a-terminal': { type: 'boolean', default: false },
|
'i-know-this-exposes-a-terminal': { type: 'boolean', default: false },
|
||||||
// racine de l'install Claude (~/.claude par défaut) — surchargée par les tests d'acceptation.
|
// racine de l'install Claude (~/.claude par défaut) : surchargée par les tests d'acceptation.
|
||||||
'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,7 +57,16 @@ 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 });
|
||||||
const claudeHome = values['claude-home'] ?? join(homedir(), '.claude');
|
// 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 claudeHomeFlag = values['claude-home'];
|
||||||
|
const claudeHome = claudeHomeFlag ?? join(homedir(), '.claude');
|
||||||
return {
|
return {
|
||||||
port: Number(values.port),
|
port: Number(values.port),
|
||||||
bind,
|
bind,
|
||||||
@@ -57,8 +74,11 @@ export function loadConfig(argv = process.argv.slice(2)): Config {
|
|||||||
dataDir,
|
dataDir,
|
||||||
allowedOrigins: values['allow-origin'] ?? [],
|
allowedOrigins: values['allow-origin'] ?? [],
|
||||||
printToken: values['print-token'] ?? false,
|
printToken: values['print-token'] ?? false,
|
||||||
|
claudeHome,
|
||||||
|
claudeHomeFromFlag: claudeHomeFlag !== undefined,
|
||||||
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { execFileSync } from 'node:child_process';
|
import { execFileSync } from 'node:child_process';
|
||||||
|
import { accessSync, constants } from 'node:fs';
|
||||||
|
|
||||||
export interface SpawnSpec {
|
export interface SpawnSpec {
|
||||||
file: string;
|
file: string;
|
||||||
@@ -10,22 +11,76 @@ 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[];
|
||||||
|
/** chemin explicite du binaire `claude` (réglage UI) ; sinon résolution via PATH (`which`). */
|
||||||
|
claudeBinPath?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Diagnostic de résolution du binaire `claude` (exposé en lecture dans Réglages). */
|
||||||
|
export interface ClaudeBinDiagnostic {
|
||||||
|
/** chemin résolu du binaire, ou null si introuvable. */
|
||||||
|
path: string | null;
|
||||||
|
/** 'configured' = réglage explicite ; 'path' = trouvé via PATH ; null = introuvable. */
|
||||||
|
source: 'configured' | 'path' | null;
|
||||||
|
/** true si le binaire est présent et exécutable. */
|
||||||
|
ok: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
let cachedClaudeBin: string | null = null;
|
let cachedClaudeBin: string | null = null;
|
||||||
|
|
||||||
export function resolveClaudeBin(): string {
|
/** Recherche `claude` dans le PATH (sans throw). null si absent. */
|
||||||
if (cachedClaudeBin) return cachedClaudeBin;
|
function findClaudeOnPath(): string | null {
|
||||||
try {
|
try {
|
||||||
cachedClaudeBin = execFileSync('which', ['claude'], { encoding: 'utf8' }).trim();
|
return execFileSync('which', ['claude'], { encoding: 'utf8' }).trim() || null;
|
||||||
} catch {
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isExecutable(path: string): boolean {
|
||||||
|
try {
|
||||||
|
accessSync(path, constants.X_OK);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Résout le binaire `claude`. Si `configuredPath` est fourni (réglage UI), il est utilisé tel quel
|
||||||
|
* (validé exécutable, message clair sinon) et JAMAIS mis en cache (modifiable à chaud). Sinon :
|
||||||
|
* `which claude`, mis en cache. Un service systemd/launchd démarre avec un PATH minimal sans
|
||||||
|
* ~/.local/bin → `which claude` y échoue ; d'où le réglage de chemin explicite (et le PATH figé par
|
||||||
|
* `arboretum install`).
|
||||||
|
*/
|
||||||
|
export function resolveClaudeBin(configuredPath?: string | null): string {
|
||||||
|
if (configuredPath) {
|
||||||
|
if (!isExecutable(configuredPath)) {
|
||||||
|
throw new Error(`Configured Claude CLI path is not executable: ${configuredPath}`);
|
||||||
|
}
|
||||||
|
return configuredPath;
|
||||||
|
}
|
||||||
|
if (cachedClaudeBin) return cachedClaudeBin;
|
||||||
|
const found = findClaudeOnPath();
|
||||||
|
if (!found) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
'Claude Code CLI not found in PATH. Install it first: https://code.claude.com/docs/en/quickstart',
|
'Claude Code CLI not found in PATH. Install it first: https://code.claude.com/docs/en/quickstart',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
cachedClaudeBin = found;
|
||||||
return cachedClaudeBin;
|
return cachedClaudeBin;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Diagnostic non-throwing pour l'UI (Réglages) : recalculé à chaque appel, jamais caché. */
|
||||||
|
export function diagnoseClaudeBin(configuredPath?: string | null): ClaudeBinDiagnostic {
|
||||||
|
if (configuredPath) {
|
||||||
|
return { path: configuredPath, source: 'configured', ok: isExecutable(configuredPath) };
|
||||||
|
}
|
||||||
|
const found = findClaudeOnPath();
|
||||||
|
return found ? { path: found, source: 'path', ok: true } : { path: null, source: null, ok: false };
|
||||||
|
}
|
||||||
|
|
||||||
/** Module volontairement abstrait : le plan B « BYO API key / Agent SDK » se brancherait ici. */
|
/** Module volontairement abstrait : le plan B « BYO API key / Agent SDK » se brancherait ici. */
|
||||||
export function buildSpawnSpec(opts: SpawnOptions): SpawnSpec {
|
export function buildSpawnSpec(opts: SpawnOptions): SpawnSpec {
|
||||||
const env: NodeJS.ProcessEnv = {
|
const env: NodeJS.ProcessEnv = {
|
||||||
@@ -38,9 +93,11 @@ export function buildSpawnSpec(opts: SpawnOptions): SpawnSpec {
|
|||||||
}
|
}
|
||||||
const args: string[] = [];
|
const args: string[] = [];
|
||||||
if (opts.resume) {
|
if (opts.resume) {
|
||||||
// `--resume` doit toujours s'exécuter dans le cwd d'origine (garanti par l'appelant — spike S1).
|
// `--resume` doit toujours s'exécuter dans le cwd d'origine (garanti par l'appelant, spike S1).
|
||||||
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');
|
||||||
}
|
}
|
||||||
return { file: resolveClaudeBin(), args, env };
|
// 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(opts.claudeBinPath), args, env };
|
||||||
}
|
}
|
||||||
|
|||||||
63
packages/server/src/core/claude-settings.ts
Normal file
63
packages/server/src/core/claude-settings.ts
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
// Réglages liés au CLI Claude, persistés dans la table `settings` (clé/valeur), modifiables via
|
||||||
|
// l'onglet Réglages. Frontière de sécurité identique à scan-settings : clés NON sensibles, écrites
|
||||||
|
// uniquement via l'allow-list du PATCH /api/v1/settings et les validateurs ci-dessous.
|
||||||
|
//
|
||||||
|
// Motivation : un service systemd/launchd démarre avec un PATH minimal qui n'inclut pas ~/.local/bin
|
||||||
|
// (où vit le binaire `claude`) → `which claude` échoue. Plutôt que de bricoler le PATH du service,
|
||||||
|
// l'utilisateur peut pointer explicitement le binaire ici (effet : prochaine session, sans redémarrage).
|
||||||
|
import { accessSync, constants, statSync } from 'node:fs';
|
||||||
|
import { getSetting } from '../db/index.js';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
import { isSafeAbsolutePath } from './git.js';
|
||||||
|
|
||||||
|
/** Chemin explicite du binaire `claude` (override de la résolution via PATH). */
|
||||||
|
export const CLAUDE_BIN_PATH_KEY = 'claude_bin_path';
|
||||||
|
/** Override de la racine ~/.claude (transcripts + registre des sessions). */
|
||||||
|
export const CLAUDE_HOME_KEY = 'claude_home';
|
||||||
|
|
||||||
|
/** Chemin configuré du binaire `claude`, ou null si non défini (⇒ auto-détection via PATH). */
|
||||||
|
export function readClaudeBinPath(db: Db): string | null {
|
||||||
|
const raw = getSetting(db, CLAUDE_BIN_PATH_KEY)?.trim();
|
||||||
|
return raw ? raw : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Racine ~/.claude configurée, ou null si non défini (⇒ défaut/flag). */
|
||||||
|
export function readClaudeHome(db: Db): string | null {
|
||||||
|
const raw = getSetting(db, CLAUDE_HOME_KEY)?.trim();
|
||||||
|
return raw ? raw : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valide un chemin de binaire `claude`. Retourne `''` pour réinitialiser (auto-détection), le chemin
|
||||||
|
* normalisé s'il est absolu ET pointe vers un fichier exécutable, ou `null` si invalide (⇒ 400).
|
||||||
|
*/
|
||||||
|
export function normalizeClaudeBinPath(raw: unknown): string | null {
|
||||||
|
if (typeof raw !== 'string') return null;
|
||||||
|
const p = raw.trim();
|
||||||
|
if (p === '') return '';
|
||||||
|
if (!isSafeAbsolutePath(p)) return null;
|
||||||
|
try {
|
||||||
|
if (!statSync(p).isFile()) return null;
|
||||||
|
accessSync(p, constants.X_OK);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valide une racine ~/.claude. Retourne `''` pour réinitialiser (défaut), le chemin normalisé s'il
|
||||||
|
* est absolu ET pointe vers un répertoire existant, ou `null` si invalide (⇒ 400).
|
||||||
|
*/
|
||||||
|
export function normalizeClaudeHome(raw: unknown): string | null {
|
||||||
|
if (typeof raw !== 'string') return null;
|
||||||
|
const p = raw.trim();
|
||||||
|
if (p === '') return '';
|
||||||
|
if (!isSafeAbsolutePath(p)) return null;
|
||||||
|
try {
|
||||||
|
if (!statSync(p).isDirectory()) return null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return p;
|
||||||
|
}
|
||||||
118
packages/server/src/core/clone-manager.ts
Normal file
118
packages/server/src/core/clone-manager.ts
Normal file
@@ -0,0 +1,118 @@
|
|||||||
|
// Orchestration des clones (P12). Asynchrone : POST /repos/clone répond 202 avec un operationId,
|
||||||
|
// la progression est poussée en WS (topic 'clones') et lisible en REST (survit au refresh). À la fin,
|
||||||
|
// le repo cloné est auto-enregistré via WorktreeManager.addRepo (réutilise unicité/validation/event).
|
||||||
|
// `dest` est strictement confiné SOUS une racine de scan + non existant (mkdir implicite par git).
|
||||||
|
import { EventEmitter } from 'node:events';
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { rm, stat } from 'node:fs/promises';
|
||||||
|
import { resolve, sep } from 'node:path';
|
||||||
|
import type { CloneOperation, GitService } from '@arboretum/shared';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
import { isSafeAbsolutePath, cloneRepo } from './git.js';
|
||||||
|
import { readScanRoots } from './scan-settings.js';
|
||||||
|
import { withGitAuth } from './git-auth.js';
|
||||||
|
import type { GitAuth } from './git-clients/index.js';
|
||||||
|
import type { GitCredentialsManager } from './git-credentials.js';
|
||||||
|
import type { WorktreeManager } from './worktree-manager.js';
|
||||||
|
import { recordAudit } from './audit-log.js';
|
||||||
|
|
||||||
|
export interface CloneManagerEvents {
|
||||||
|
clone_update: [CloneOperation];
|
||||||
|
}
|
||||||
|
|
||||||
|
function httpError(statusCode: number, code: string, message: string): Error & { statusCode: number; code: string } {
|
||||||
|
return Object.assign(new Error(message), { statusCode, code });
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CloneManager extends EventEmitter<CloneManagerEvents> {
|
||||||
|
private readonly ops = new Map<string, CloneOperation>();
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly db: Db,
|
||||||
|
private readonly worktrees: WorktreeManager,
|
||||||
|
private readonly credentials: GitCredentialsManager,
|
||||||
|
) {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
get(id: string): CloneOperation | null {
|
||||||
|
return this.ops.get(id) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Démarre un clone (validation synchrone du dest → throw 4xx ; clone asynchrone ensuite).
|
||||||
|
* Retourne l'operationId à suivre via WS/REST. `actor` pour l'audit.
|
||||||
|
*/
|
||||||
|
async start(opts: { credentialId: string; remoteUrl: string; dest: string }, actor: string): Promise<string> {
|
||||||
|
const dest = resolve(opts.dest);
|
||||||
|
if (!isSafeAbsolutePath(dest)) throw httpError(400, 'BAD_REQUEST', 'dest must be an absolute, normalized path');
|
||||||
|
if (typeof opts.remoteUrl !== 'string' || opts.remoteUrl.trim() === '') throw httpError(400, 'BAD_REQUEST', 'remoteUrl is required');
|
||||||
|
const ctx = this.credentials.authContext(opts.credentialId);
|
||||||
|
if (!ctx) throw httpError(404, 'NOT_FOUND', 'No usable credential with this id');
|
||||||
|
|
||||||
|
// Confinement : dest DOIT être sous une racine de scan configurée (jamais d'écriture arbitraire).
|
||||||
|
const roots = readScanRoots(this.db);
|
||||||
|
if (roots.length === 0) throw httpError(400, 'NO_SCAN_ROOT', 'Configure a scan folder first (Settings → Discovery)');
|
||||||
|
const underRoot = roots.some((r) => {
|
||||||
|
const root = resolve(r);
|
||||||
|
return dest === root || dest.startsWith(root + sep);
|
||||||
|
});
|
||||||
|
if (!underRoot) throw httpError(400, 'OUTSIDE_SCAN_ROOT', 'dest must be inside a configured scan folder');
|
||||||
|
|
||||||
|
// Le parent doit exister ; le dest ne doit pas exister (git clone le crée).
|
||||||
|
const parent = dest.slice(0, dest.lastIndexOf(sep)) || sep;
|
||||||
|
try {
|
||||||
|
const st = await stat(parent);
|
||||||
|
if (!st.isDirectory()) throw httpError(400, 'BAD_DEST', 'Parent of dest is not a directory');
|
||||||
|
} catch (err) {
|
||||||
|
if ((err as { statusCode?: number }).statusCode) throw err;
|
||||||
|
throw httpError(404, 'NOT_FOUND', `Parent directory does not exist: ${parent}`);
|
||||||
|
}
|
||||||
|
if (await stat(dest).then(() => true).catch(() => false)) throw httpError(409, 'DEST_EXISTS', `Destination already exists: ${dest}`);
|
||||||
|
|
||||||
|
const id = randomUUID();
|
||||||
|
const op: CloneOperation = { id, state: 'pending', progress: null, phase: null, error: null, repoId: null, dest };
|
||||||
|
this.ops.set(id, op);
|
||||||
|
recordAudit(this.db, { actor, action: 'repo.clone', resourceId: id, details: { service: ctx.service, dest } });
|
||||||
|
// Lancement asynchrone (ne bloque pas la réponse 202).
|
||||||
|
void this.run(op, opts.remoteUrl, opts.credentialId, ctx);
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
private update(op: CloneOperation, patch: Partial<CloneOperation>): void {
|
||||||
|
Object.assign(op, patch);
|
||||||
|
this.emit('clone_update', { ...op });
|
||||||
|
}
|
||||||
|
|
||||||
|
private async run(
|
||||||
|
op: CloneOperation,
|
||||||
|
remoteUrl: string,
|
||||||
|
credentialId: string,
|
||||||
|
ctx: { service: GitService; baseUrl: string | null; auth: GitAuth },
|
||||||
|
): Promise<void> {
|
||||||
|
this.update(op, { state: 'running' });
|
||||||
|
let lastPct = -10;
|
||||||
|
const onProgress = (p: { phase: string; percent: number | null }): void => {
|
||||||
|
// throttle : on ne pousse que sur changement de phase ou +3% pour éviter le flood WS.
|
||||||
|
if (p.percent == null || p.percent - lastPct >= 3 || p.phase !== op.phase) {
|
||||||
|
lastPct = p.percent ?? lastPct;
|
||||||
|
this.update(op, { phase: p.phase, progress: p.percent });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
await withGitAuth(ctx.service, ctx.auth, (env) =>
|
||||||
|
cloneRepo({ url: remoteUrl, dest: op.dest, env, onProgress }),
|
||||||
|
);
|
||||||
|
// auto-enregistrement du repo cloné + métadonnées de provenance.
|
||||||
|
const repo = await this.worktrees.addRepo({ path: op.dest });
|
||||||
|
this.db
|
||||||
|
.prepare('UPDATE repos SET remote_url = ?, git_service = ?, credential_id = ? WHERE id = ?')
|
||||||
|
.run(remoteUrl, ctx.service, credentialId, repo.id);
|
||||||
|
this.update(op, { state: 'done', progress: 100, repoId: repo.id });
|
||||||
|
} catch (err) {
|
||||||
|
// nettoyage du clone partiel (best-effort).
|
||||||
|
await rm(op.dest, { recursive: true, force: true }).catch(() => {});
|
||||||
|
this.update(op, { state: 'error', error: err instanceof Error ? err.message : String(err) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
// Typage de dialogue à partir de l'écran reconstruit (ScreenReader) — fonctions PURES.
|
// Typage de dialogue à partir de l'écran reconstruit (ScreenReader) : fonctions PURES.
|
||||||
// L'écran sert à TYPER le dialogue et extraire ses options ; l'état (waiting vrai/faux) vient du
|
// L'écran sert à TYPER le dialogue et extraire ses options ; l'état (waiting vrai/faux) vient du
|
||||||
// registre (source primaire). Tolérant aux variations de rendu inter-versions (texte aplati + regex).
|
// registre (source primaire). Tolérant aux variations de rendu inter-versions (texte aplati + regex).
|
||||||
import type { DialogKind, DialogOption } from '@arboretum/shared';
|
import type { DialogKind, DialogOption } from '@arboretum/shared';
|
||||||
@@ -23,7 +23,7 @@ export function parseOptions(lines: string[]): DialogOption[] {
|
|||||||
/**
|
/**
|
||||||
* Retourne le dialogue typé visible à l'écran, ou null si aucun. `trust` et `question` priment sur
|
* Retourne le dialogue typé visible à l'écran, ou null si aucun. `trust` et `question` priment sur
|
||||||
* `permission` (un écran AskUserQuestion contient aussi « Esc to cancel »). Un écran numéroté non
|
* `permission` (un écran AskUserQuestion contient aussi « Esc to cancel »). Un écran numéroté non
|
||||||
* typé est traité en `permission` générique (best-effort — le fallback reste le terminal web).
|
* typé est traité en `permission` générique (best-effort, le fallback reste le terminal web).
|
||||||
*/
|
*/
|
||||||
export function classifyDialog(lines: string[]): ClassifiedDialog | null {
|
export function classifyDialog(lines: string[]): ClassifiedDialog | null {
|
||||||
const text = lines.join('\n');
|
const text = lines.join('\n');
|
||||||
|
|||||||
@@ -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');
|
||||||
@@ -60,13 +64,13 @@ export class DiscoveryService extends EventEmitter<DiscoveryServiceEvents> {
|
|||||||
return this.cache;
|
return this.cache;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Session découverte (avec son cwd d'origine lu sur disque) — pour resume/fork. null si absente. */
|
/** Session découverte (avec son cwd d'origine lu sur disque) : pour resume/fork. null si absente. */
|
||||||
getDiscovered(claudeSessionId: string): DiscoveredJsonl | null {
|
getDiscovered(claudeSessionId: string): DiscoveredJsonl | null {
|
||||||
return this.byId.get(claudeSessionId) ?? null;
|
return this.byId.get(claudeSessionId) ?? null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Vivacité FRAÎCHE d'une session (relit le registre, ne se fie pas au cache) — garde-fou
|
* Vivacité FRAÎCHE d'une session (relit le registre, ne se fie pas au cache) : garde-fou
|
||||||
* anti-corruption : la route /resume doit refuser une session devenue vivante depuis le dernier scan.
|
* anti-corruption : la route /resume doit refuser une session devenue vivante depuis le dernier scan.
|
||||||
*/
|
*/
|
||||||
isClaudeSessionLive(claudeSessionId: string): boolean {
|
isClaudeSessionLive(claudeSessionId: string): boolean {
|
||||||
@@ -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),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
199
packages/server/src/core/fs-watcher.ts
Normal file
199
packages/server/src/core/fs-watcher.ts
Normal file
@@ -0,0 +1,199 @@
|
|||||||
|
// Watcher FS des worktrees ACTIFS (regardés par un client OU portant une session vivante).
|
||||||
|
// Émet un signal débouncé `worktree_fs_change` que le WorktreeManager traduit en recalcul du
|
||||||
|
// statut git + broadcast WS. Pool LRU borné + refcount pour ne jamais épuiser les descripteurs :
|
||||||
|
// un worktree n'est watché que tant qu'il est observé/épinglé, et la taille totale est plafonnée.
|
||||||
|
import { EventEmitter } from 'node:events';
|
||||||
|
import { resolve, sep, join } from 'node:path';
|
||||||
|
import chokidar, { type FSWatcher } from 'chokidar';
|
||||||
|
import { resolveGitDir } from './git.js';
|
||||||
|
|
||||||
|
const DEFAULT_MAX_WATCHERS = 32;
|
||||||
|
const DEBOUNCE_MS = 200;
|
||||||
|
|
||||||
|
export interface FsWatcherEvents {
|
||||||
|
/** le contenu d'un worktree surveillé a changé (édition, staging, checkout externe…). */
|
||||||
|
worktree_fs_change: [{ repoId: string; path: string }];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface WatchEntry {
|
||||||
|
repoId: string;
|
||||||
|
path: string;
|
||||||
|
watcher: FSWatcher;
|
||||||
|
/** nombre de clients qui « regardent » ce worktree. */
|
||||||
|
refCount: number;
|
||||||
|
/** nombre de sessions vivantes épinglant ce worktree. */
|
||||||
|
sessionPins: number;
|
||||||
|
/** épingle « permanente » (checkout principal d'un repo enregistré) : jamais évincée (P11). */
|
||||||
|
repoPins: number;
|
||||||
|
lastUsed: number;
|
||||||
|
debounce: NodeJS.Timeout | null;
|
||||||
|
/** résolue quand chokidar a fini son scan initial (les events deviennent fiables). */
|
||||||
|
ready: Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ignore tout sous `.git/` SAUF `HEAD` et `index` (⇒ on détecte le `git checkout` externe et le
|
||||||
|
* staging) ainsi que `node_modules`. chokidar n'ignore pas le dossier `.git` lui-même afin de
|
||||||
|
* pouvoir descendre jusqu'à `HEAD`/`index`, mais saute ses sous-dossiers volumineux (objects…).
|
||||||
|
*/
|
||||||
|
export function isIgnoredPath(p: string): boolean {
|
||||||
|
if (p.includes(`${sep}node_modules${sep}`) || p.endsWith(`${sep}node_modules`)) return true;
|
||||||
|
if (p.includes(`${sep}.git${sep}`)) {
|
||||||
|
return !(p.endsWith(`${sep}HEAD`) || p.endsWith(`${sep}index`));
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FsWatcherOptions {
|
||||||
|
maxWatchers?: number;
|
||||||
|
debounceMs?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class FsWatcherService extends EventEmitter<FsWatcherEvents> {
|
||||||
|
private readonly entries = new Map<string, WatchEntry>();
|
||||||
|
private readonly maxWatchers: number;
|
||||||
|
private readonly debounceMs: number;
|
||||||
|
|
||||||
|
constructor(opts: FsWatcherOptions = {}) {
|
||||||
|
super();
|
||||||
|
this.maxWatchers = opts.maxWatchers ?? DEFAULT_MAX_WATCHERS;
|
||||||
|
this.debounceMs = opts.debounceMs ?? DEBOUNCE_MS;
|
||||||
|
}
|
||||||
|
|
||||||
|
private key(repoId: string, path: string): string {
|
||||||
|
return `${repoId}\0${resolve(path)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Un client commence à observer un worktree (vue IDE ouverte). */
|
||||||
|
watch(repoId: string, path: string): void {
|
||||||
|
const e = this.ensure(repoId, path);
|
||||||
|
e.refCount++;
|
||||||
|
e.lastUsed = Date.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Un client cesse d'observer ; le watcher reste (idle) jusqu'à éviction LRU. */
|
||||||
|
unwatch(repoId: string, path: string): void {
|
||||||
|
const e = this.entries.get(this.key(repoId, path));
|
||||||
|
if (!e) return;
|
||||||
|
e.refCount = Math.max(0, e.refCount - 1);
|
||||||
|
e.lastUsed = Date.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Épingle un worktree tant qu'une session y est vivante (jamais évincé). */
|
||||||
|
pinSession(repoId: string, path: string): void {
|
||||||
|
const e = this.ensure(repoId, path);
|
||||||
|
e.sessionPins++;
|
||||||
|
e.lastUsed = Date.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
unpinSession(repoId: string, path: string): void {
|
||||||
|
const e = this.entries.get(this.key(repoId, path));
|
||||||
|
if (!e) return;
|
||||||
|
e.sessionPins = Math.max(0, e.sessionPins - 1);
|
||||||
|
e.lastUsed = Date.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Épingle en PERMANENCE le checkout principal d'un repo enregistré (P11) : ainsi un `git checkout`
|
||||||
|
* en CLI sur le principal est détecté et rediffusé sans qu'aucun client n'ait « regardé » ce
|
||||||
|
* worktree. Idempotent (un seul pin par repo+path conservé). Jamais évincé par la LRU.
|
||||||
|
*/
|
||||||
|
pinRepo(repoId: string, path: string): void {
|
||||||
|
const e = this.ensure(repoId, path);
|
||||||
|
e.repoPins = 1; // idempotent : on ne cumule pas (un seul checkout principal par repo)
|
||||||
|
e.lastUsed = Date.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
unpinRepo(repoId: string, path: string): void {
|
||||||
|
const e = this.entries.get(this.key(repoId, path));
|
||||||
|
if (!e) return;
|
||||||
|
e.repoPins = 0;
|
||||||
|
e.lastUsed = Date.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Nombre de watchers actifs (test/diagnostic). */
|
||||||
|
size(): number {
|
||||||
|
return this.entries.size;
|
||||||
|
}
|
||||||
|
|
||||||
|
isWatching(repoId: string, path: string): boolean {
|
||||||
|
return this.entries.has(this.key(repoId, path));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Résout quand le watcher de ce worktree a fini son scan initial (utile aux tests). */
|
||||||
|
whenReady(repoId: string, path: string): Promise<void> {
|
||||||
|
return this.entries.get(this.key(repoId, path))?.ready ?? Promise.resolve();
|
||||||
|
}
|
||||||
|
|
||||||
|
private ensure(repoId: string, path: string): WatchEntry {
|
||||||
|
const key = this.key(repoId, path);
|
||||||
|
const existing = this.entries.get(key);
|
||||||
|
if (existing) return existing;
|
||||||
|
|
||||||
|
const abs = resolve(path);
|
||||||
|
const watcher = chokidar.watch(abs, {
|
||||||
|
ignored: (p: string) => isIgnoredPath(p),
|
||||||
|
ignoreInitial: true,
|
||||||
|
// coalesce les écritures rapides (build, génération) avant d'émettre.
|
||||||
|
awaitWriteFinish: { stabilityThreshold: 120, pollInterval: 40 },
|
||||||
|
});
|
||||||
|
let resolveReady: () => void = () => {};
|
||||||
|
const ready = new Promise<void>((r) => (resolveReady = r));
|
||||||
|
watcher.once('ready', () => resolveReady());
|
||||||
|
const entry: WatchEntry = { repoId, path: abs, watcher, refCount: 0, sessionPins: 0, repoPins: 0, lastUsed: Date.now(), debounce: null, ready };
|
||||||
|
const onChange = (): void => this.schedule(entry);
|
||||||
|
watcher.on('add', onChange).on('change', onChange).on('unlink', onChange).on('addDir', onChange).on('unlinkDir', onChange);
|
||||||
|
this.entries.set(key, entry);
|
||||||
|
|
||||||
|
// Worktree LIÉ : HEAD/index vivent hors du worktree (dans .git/worktrees/<n>). On les ajoute
|
||||||
|
// explicitement pour capter un changement de branche externe (git checkout en CLI).
|
||||||
|
void resolveGitDir(abs).then((gitDir) => {
|
||||||
|
if (!gitDir || !this.entries.has(key)) return;
|
||||||
|
if (gitDir === join(abs, '.git') || gitDir.startsWith(abs + sep)) return; // déjà couvert
|
||||||
|
watcher.add([join(gitDir, 'HEAD'), join(gitDir, 'index')]);
|
||||||
|
}).catch(() => {});
|
||||||
|
|
||||||
|
this.evictIfNeeded();
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
private schedule(entry: WatchEntry): void {
|
||||||
|
if (entry.debounce) clearTimeout(entry.debounce);
|
||||||
|
entry.debounce = setTimeout(() => {
|
||||||
|
entry.debounce = null;
|
||||||
|
entry.lastUsed = Date.now();
|
||||||
|
this.emit('worktree_fs_change', { repoId: entry.repoId, path: entry.path });
|
||||||
|
}, this.debounceMs);
|
||||||
|
entry.debounce.unref();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ferme les watchers idle (refCount===0 && sessionPins===0) les moins récents au-delà du plafond. */
|
||||||
|
private evictIfNeeded(): void {
|
||||||
|
if (this.entries.size <= this.maxWatchers) return;
|
||||||
|
const idle = [...this.entries.entries()]
|
||||||
|
.filter(([, e]) => e.refCount === 0 && e.sessionPins === 0 && e.repoPins === 0)
|
||||||
|
.sort((a, b) => a[1].lastUsed - b[1].lastUsed);
|
||||||
|
for (const [key, e] of idle) {
|
||||||
|
if (this.entries.size <= this.maxWatchers) break;
|
||||||
|
this.close(key, e);
|
||||||
|
}
|
||||||
|
// Si tout est actif (reffé/épinglé), on dépasse le plafond volontairement : un worktree
|
||||||
|
// explicitement observé ne doit jamais perdre son temps réel.
|
||||||
|
}
|
||||||
|
|
||||||
|
private close(key: string, e: WatchEntry): void {
|
||||||
|
if (e.debounce) clearTimeout(e.debounce);
|
||||||
|
void e.watcher.close().catch(() => {});
|
||||||
|
this.entries.delete(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Libère tous les descripteurs (drain SIGTERM/SIGINT). */
|
||||||
|
async closeAll(): Promise<void> {
|
||||||
|
const all = [...this.entries.entries()];
|
||||||
|
this.entries.clear();
|
||||||
|
await Promise.all(all.map(([, e]) => {
|
||||||
|
if (e.debounce) clearTimeout(e.debounce);
|
||||||
|
return e.watcher.close().catch(() => {});
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
40
packages/server/src/core/git-auth.ts
Normal file
40
packages/server/src/core/git-auth.ts
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
// Préparation d'un environnement d'authentification git ÉPHÉMÈRE (P12). HTTPS (pat/app_password) :
|
||||||
|
// les identifiants sont fournis via GIT_ASKPASS (script 0o700 lisant deux variables d'env), JAMAIS
|
||||||
|
// dans l'URL ni dans `.git/config`. GIT_TERMINAL_PROMPT=0 (pas d'invite bloquante). Le script est
|
||||||
|
// supprimé en `finally` ; le secret ne transite que par l'env du process enfant (jamais loggé).
|
||||||
|
import { mkdtemp, writeFile, rm, chmod } from 'node:fs/promises';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import type { GitService } from '@arboretum/shared';
|
||||||
|
import type { GitAuth } from './git-clients/index.js';
|
||||||
|
|
||||||
|
// Identité HTTPS par défaut quand l'utilisateur n'a pas fourni de username (token-as-password).
|
||||||
|
const SERVICE_DEFAULT_USER: Record<GitService, string> = { github: 'x-access-token', gitlab: 'oauth2', gitea: 'oauth2' };
|
||||||
|
|
||||||
|
export async function withGitAuth<T>(
|
||||||
|
service: GitService,
|
||||||
|
auth: GitAuth,
|
||||||
|
fn: (env: NodeJS.ProcessEnv) => Promise<T>,
|
||||||
|
): Promise<T> {
|
||||||
|
const dir = await mkdtemp(join(tmpdir(), 'arb-gitauth-'));
|
||||||
|
const askpass = join(dir, 'askpass.sh');
|
||||||
|
const user = auth.username || SERVICE_DEFAULT_USER[service];
|
||||||
|
await writeFile(
|
||||||
|
askpass,
|
||||||
|
"#!/bin/sh\ncase \"$1\" in\n Username*) printf '%s' \"$ARB_GIT_USER\" ;;\n *) printf '%s' \"$ARB_GIT_PASS\" ;;\nesac\n",
|
||||||
|
{ mode: 0o700 },
|
||||||
|
);
|
||||||
|
await chmod(askpass, 0o700);
|
||||||
|
const env: NodeJS.ProcessEnv = {
|
||||||
|
...process.env,
|
||||||
|
GIT_ASKPASS: askpass,
|
||||||
|
GIT_TERMINAL_PROMPT: '0',
|
||||||
|
ARB_GIT_USER: user,
|
||||||
|
ARB_GIT_PASS: auth.secret,
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
return await fn(env);
|
||||||
|
} finally {
|
||||||
|
await rm(dir, { recursive: true, force: true }).catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
156
packages/server/src/core/git-clients/index.ts
Normal file
156
packages/server/src/core/git-clients/index.ts
Normal file
@@ -0,0 +1,156 @@
|
|||||||
|
// Clients des services git distants (Gitea / GitLab / GitHub) : P12. Uniquement `fetch` global
|
||||||
|
// (Node ≥ 22), AUCUNE dépendance (pas d'octokit/gitbeaker). Chaque client expose verify() (test de
|
||||||
|
// connectivité/auth) et listRepos() (paginé). Erreurs typées : AUTH_FAILED / RATE_LIMITED / UNREACHABLE.
|
||||||
|
import type { GitAuthType, GitService, RemoteRepoSummary } from '@arboretum/shared';
|
||||||
|
|
||||||
|
const REQUEST_TIMEOUT_MS = 12_000;
|
||||||
|
const PER_PAGE = 30;
|
||||||
|
|
||||||
|
export interface GitAuth {
|
||||||
|
authType: GitAuthType;
|
||||||
|
username: string | null;
|
||||||
|
secret: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class GitServiceError extends Error {
|
||||||
|
constructor(
|
||||||
|
public readonly errorCode: string,
|
||||||
|
message?: string,
|
||||||
|
) {
|
||||||
|
super(message ?? errorCode);
|
||||||
|
this.name = 'GitServiceError';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GitClient {
|
||||||
|
verify(auth: GitAuth): Promise<{ login: string }>;
|
||||||
|
listRepos(auth: GitAuth, page: number, search?: string): Promise<{ repos: RemoteRepoSummary[]; nextPage: number | null }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** En-têtes d'auth selon le type. app_password → Basic (username:secret) ; pat → en-tête propre au service. */
|
||||||
|
function authHeaders(service: GitService, auth: GitAuth): Record<string, string> {
|
||||||
|
if (auth.authType === 'app_password') {
|
||||||
|
const basic = Buffer.from(`${auth.username ?? ''}:${auth.secret}`).toString('base64');
|
||||||
|
return { Authorization: `Basic ${basic}` };
|
||||||
|
}
|
||||||
|
// pat
|
||||||
|
if (service === 'gitlab') return { 'PRIVATE-TOKEN': auth.secret };
|
||||||
|
if (service === 'gitea') return { Authorization: `token ${auth.secret}` };
|
||||||
|
return { Authorization: `Bearer ${auth.secret}` }; // github
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Refuse une base self-hosted non http(s) (anti-SSRF schéma) ; renvoie l'origine normalisée sans `/` final. */
|
||||||
|
function normalizeBase(baseUrl: string): string {
|
||||||
|
let u: URL;
|
||||||
|
try {
|
||||||
|
u = new URL(baseUrl);
|
||||||
|
} catch {
|
||||||
|
throw new GitServiceError('BAD_BASE_URL', 'base_url must be a valid http(s) URL');
|
||||||
|
}
|
||||||
|
if (u.protocol !== 'http:' && u.protocol !== 'https:') throw new GitServiceError('BAD_BASE_URL', 'base_url must be http(s)');
|
||||||
|
return `${u.origin}${u.pathname}`.replace(/\/+$/, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchJson(url: string, headers: Record<string, string>): Promise<{ json: unknown; headers: Headers }> {
|
||||||
|
let res: Response;
|
||||||
|
try {
|
||||||
|
res = await fetch(url, { headers: { Accept: 'application/json', ...headers }, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
|
||||||
|
} catch {
|
||||||
|
throw new GitServiceError('UNREACHABLE', 'Could not reach the git service');
|
||||||
|
}
|
||||||
|
if (res.status === 429) throw new GitServiceError('RATE_LIMITED', 'Rate limited by the git service');
|
||||||
|
if (res.status === 401 || res.status === 403) {
|
||||||
|
// 403 + quota épuisé = rate limit (GitHub) ; sinon échec d'auth.
|
||||||
|
if (res.headers.get('x-ratelimit-remaining') === '0') throw new GitServiceError('RATE_LIMITED', 'Rate limited by the git service');
|
||||||
|
throw new GitServiceError('AUTH_FAILED', 'Authentication failed');
|
||||||
|
}
|
||||||
|
if (!res.ok) throw new GitServiceError(`HTTP_${res.status}`, `Unexpected response ${res.status}`);
|
||||||
|
return { json: await res.json().catch(() => null), headers: res.headers };
|
||||||
|
}
|
||||||
|
|
||||||
|
function githubBase(baseUrl: string | null): string {
|
||||||
|
return baseUrl ? normalizeBase(baseUrl) : 'https://api.github.com';
|
||||||
|
}
|
||||||
|
function gitlabBase(baseUrl: string | null): string {
|
||||||
|
return `${baseUrl ? normalizeBase(baseUrl) : 'https://gitlab.com'}/api/v4`;
|
||||||
|
}
|
||||||
|
function giteaBase(baseUrl: string | null): string {
|
||||||
|
if (!baseUrl) throw new GitServiceError('BAD_BASE_URL', 'Gitea requires a base_url (self-hosted instance)');
|
||||||
|
return `${normalizeBase(baseUrl)}/api/v1`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const githubClient = (baseUrl: string | null): GitClient => {
|
||||||
|
const base = githubBase(baseUrl);
|
||||||
|
return {
|
||||||
|
async verify(auth) {
|
||||||
|
const { json } = await fetchJson(`${base}/user`, authHeaders('github', auth));
|
||||||
|
return { login: String((json as { login?: string })?.login ?? '') };
|
||||||
|
},
|
||||||
|
async listRepos(auth, page) {
|
||||||
|
const { json } = await fetchJson(`${base}/user/repos?per_page=${PER_PAGE}&page=${page}&sort=updated`, authHeaders('github', auth));
|
||||||
|
const arr = Array.isArray(json) ? (json as Array<Record<string, unknown>>) : [];
|
||||||
|
const repos = arr.map((r): RemoteRepoSummary => ({
|
||||||
|
fullName: String(r.full_name ?? ''),
|
||||||
|
cloneUrl: String(r.clone_url ?? ''),
|
||||||
|
private: Boolean(r.private),
|
||||||
|
description: (r.description as string | null) ?? null,
|
||||||
|
defaultBranch: (r.default_branch as string | null) ?? null,
|
||||||
|
}));
|
||||||
|
return { repos, nextPage: arr.length === PER_PAGE ? page + 1 : null };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const gitlabClient = (baseUrl: string | null): GitClient => {
|
||||||
|
const base = gitlabBase(baseUrl);
|
||||||
|
return {
|
||||||
|
async verify(auth) {
|
||||||
|
const { json } = await fetchJson(`${base}/user`, authHeaders('gitlab', auth));
|
||||||
|
return { login: String((json as { username?: string })?.username ?? '') };
|
||||||
|
},
|
||||||
|
async listRepos(auth, page) {
|
||||||
|
const { json, headers } = await fetchJson(
|
||||||
|
`${base}/projects?membership=true&per_page=${PER_PAGE}&page=${page}&order_by=last_activity_at`,
|
||||||
|
authHeaders('gitlab', auth),
|
||||||
|
);
|
||||||
|
const arr = Array.isArray(json) ? (json as Array<Record<string, unknown>>) : [];
|
||||||
|
const repos = arr.map((r): RemoteRepoSummary => ({
|
||||||
|
fullName: String(r.path_with_namespace ?? ''),
|
||||||
|
cloneUrl: String(r.http_url_to_repo ?? ''),
|
||||||
|
private: r.visibility !== 'public',
|
||||||
|
description: (r.description as string | null) ?? null,
|
||||||
|
defaultBranch: (r.default_branch as string | null) ?? null,
|
||||||
|
}));
|
||||||
|
const next = headers.get('x-next-page');
|
||||||
|
return { repos, nextPage: next ? Number(next) : null };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const giteaClient = (baseUrl: string | null): GitClient => {
|
||||||
|
const base = giteaBase(baseUrl);
|
||||||
|
return {
|
||||||
|
async verify(auth) {
|
||||||
|
const { json } = await fetchJson(`${base}/user`, authHeaders('gitea', auth));
|
||||||
|
return { login: String((json as { login?: string })?.login ?? '') };
|
||||||
|
},
|
||||||
|
async listRepos(auth, page) {
|
||||||
|
const { json } = await fetchJson(`${base}/user/repos?page=${page}&limit=${PER_PAGE}`, authHeaders('gitea', auth));
|
||||||
|
const arr = Array.isArray(json) ? (json as Array<Record<string, unknown>>) : [];
|
||||||
|
const repos = arr.map((r): RemoteRepoSummary => ({
|
||||||
|
fullName: String(r.full_name ?? ''),
|
||||||
|
cloneUrl: String(r.clone_url ?? ''),
|
||||||
|
private: Boolean(r.private),
|
||||||
|
description: (r.description as string | null) ?? null,
|
||||||
|
defaultBranch: (r.default_branch as string | null) ?? null,
|
||||||
|
}));
|
||||||
|
return { repos, nextPage: arr.length === PER_PAGE ? page + 1 : null };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export function getGitClient(service: GitService, baseUrl: string | null): GitClient {
|
||||||
|
if (service === 'github') return githubClient(baseUrl);
|
||||||
|
if (service === 'gitlab') return gitlabClient(baseUrl);
|
||||||
|
return giteaClient(baseUrl);
|
||||||
|
}
|
||||||
180
packages/server/src/core/git-credentials.ts
Normal file
180
packages/server/src/core/git-credentials.ts
Normal file
@@ -0,0 +1,180 @@
|
|||||||
|
// Gestion des credentials des services git distants (P12). Les secrets (PAT/app password) sont
|
||||||
|
// chiffrés par SecretBox AVANT insertion et ne ressortent JAMAIS via l'API (résumés sans secret).
|
||||||
|
// getSecret()/authFor() sont INTERNES (clone, listRepos, test) : jamais routés.
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import type {
|
||||||
|
CreateGitCredentialRequest,
|
||||||
|
GitCredentialSummary,
|
||||||
|
GitService,
|
||||||
|
TestCredentialResponse,
|
||||||
|
UpdateGitCredentialRequest,
|
||||||
|
} from '@arboretum/shared';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
import type { SecretBox } from './secret-box.js';
|
||||||
|
import { getGitClient, GitServiceError, type GitAuth } from './git-clients/index.js';
|
||||||
|
import { recordAudit } from './audit-log.js';
|
||||||
|
|
||||||
|
interface GitCredentialRow {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
service: GitService;
|
||||||
|
base_url: string | null;
|
||||||
|
auth_type: GitCredentialSummary['authType'];
|
||||||
|
username: string | null;
|
||||||
|
secret_encrypted: string | null;
|
||||||
|
ssh_key_path: string | null;
|
||||||
|
oauth_access_encrypted: string | null;
|
||||||
|
oauth_refresh_encrypted: string | null;
|
||||||
|
oauth_expires_at: string | null;
|
||||||
|
created_at: string;
|
||||||
|
last_tested_at: string | null;
|
||||||
|
test_result: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function httpError(statusCode: number, code: string, message: string): Error & { statusCode: number; code: string } {
|
||||||
|
return Object.assign(new Error(message), { statusCode, code });
|
||||||
|
}
|
||||||
|
|
||||||
|
export class GitCredentialsManager {
|
||||||
|
constructor(
|
||||||
|
private readonly db: Db,
|
||||||
|
private readonly box: SecretBox,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
private getRow(id: string): GitCredentialRow | null {
|
||||||
|
return (this.db.prepare('SELECT * FROM git_credentials WHERE id = ?').get(id) as unknown as GitCredentialRow | undefined) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private toSummary(row: GitCredentialRow): GitCredentialSummary {
|
||||||
|
let secretLast4: string | null = null;
|
||||||
|
if (row.secret_encrypted) {
|
||||||
|
try {
|
||||||
|
const s = this.box.decrypt(row.secret_encrypted);
|
||||||
|
secretLast4 = s.length >= 4 ? s.slice(-4) : '••••';
|
||||||
|
} catch {
|
||||||
|
secretLast4 = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
label: row.label,
|
||||||
|
service: row.service,
|
||||||
|
baseUrl: row.base_url,
|
||||||
|
authType: row.auth_type,
|
||||||
|
username: row.username,
|
||||||
|
hasSecret: row.secret_encrypted != null,
|
||||||
|
secretLast4,
|
||||||
|
createdAt: row.created_at,
|
||||||
|
lastTestedAt: row.last_tested_at,
|
||||||
|
testResult: row.test_result,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
list(): GitCredentialSummary[] {
|
||||||
|
const rows = this.db.prepare('SELECT * FROM git_credentials ORDER BY created_at ASC').all() as unknown as GitCredentialRow[];
|
||||||
|
return rows.map((r) => this.toSummary(r));
|
||||||
|
}
|
||||||
|
|
||||||
|
get(id: string): GitCredentialSummary | null {
|
||||||
|
const row = this.getRow(id);
|
||||||
|
return row ? this.toSummary(row) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
create(opts: CreateGitCredentialRequest): GitCredentialSummary {
|
||||||
|
// P12a : seules les méthodes HTTPS (pat / app_password) sont supportées pour l'instant.
|
||||||
|
if (opts.authType !== 'pat' && opts.authType !== 'app_password') {
|
||||||
|
throw httpError(400, 'UNSUPPORTED_AUTH', 'Only pat and app_password are supported for now (SSH/OAuth: later phases)');
|
||||||
|
}
|
||||||
|
if (!opts.label?.trim()) throw httpError(400, 'BAD_REQUEST', 'label is required');
|
||||||
|
if (opts.service !== 'gitea' && opts.service !== 'gitlab' && opts.service !== 'github') {
|
||||||
|
throw httpError(400, 'BAD_REQUEST', 'service must be gitea, gitlab or github');
|
||||||
|
}
|
||||||
|
if (opts.service === 'gitea' && !opts.baseUrl) throw httpError(400, 'BAD_REQUEST', 'Gitea requires a base_url');
|
||||||
|
if (!opts.secret) throw httpError(400, 'BAD_REQUEST', 'secret (token) is required');
|
||||||
|
const row: GitCredentialRow = {
|
||||||
|
id: randomUUID(),
|
||||||
|
label: opts.label.trim(),
|
||||||
|
service: opts.service,
|
||||||
|
base_url: opts.baseUrl?.trim() || null,
|
||||||
|
auth_type: opts.authType,
|
||||||
|
username: opts.username?.trim() || null,
|
||||||
|
secret_encrypted: this.box.encrypt(opts.secret),
|
||||||
|
ssh_key_path: null,
|
||||||
|
oauth_access_encrypted: null,
|
||||||
|
oauth_refresh_encrypted: null,
|
||||||
|
oauth_expires_at: null,
|
||||||
|
created_at: new Date().toISOString(),
|
||||||
|
last_tested_at: null,
|
||||||
|
test_result: null,
|
||||||
|
};
|
||||||
|
this.db
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO git_credentials (id, label, service, base_url, auth_type, username, secret_encrypted, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||||
|
)
|
||||||
|
.run(row.id, row.label, row.service, row.base_url, row.auth_type, row.username, row.secret_encrypted, row.created_at);
|
||||||
|
return this.toSummary(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
update(id: string, patch: UpdateGitCredentialRequest): GitCredentialSummary {
|
||||||
|
const row = this.getRow(id);
|
||||||
|
if (!row) throw httpError(404, 'NOT_FOUND', 'No credential with this id');
|
||||||
|
if (patch.label !== undefined) row.label = patch.label.trim() || row.label;
|
||||||
|
if (patch.baseUrl !== undefined) row.base_url = patch.baseUrl.trim() || null;
|
||||||
|
if (patch.username !== undefined) row.username = patch.username.trim() || null;
|
||||||
|
if (patch.secret) row.secret_encrypted = this.box.encrypt(patch.secret);
|
||||||
|
this.db
|
||||||
|
.prepare('UPDATE git_credentials SET label = ?, base_url = ?, username = ?, secret_encrypted = ? WHERE id = ?')
|
||||||
|
.run(row.label, row.base_url, row.username, row.secret_encrypted, id);
|
||||||
|
return this.toSummary(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Supprime un credential et NULLifie repos.credential_id (pas de FK). */
|
||||||
|
remove(id: string): boolean {
|
||||||
|
const res = this.db.prepare('DELETE FROM git_credentials WHERE id = ?').run(id);
|
||||||
|
if (res.changes === 0) return false;
|
||||||
|
this.db.prepare('UPDATE repos SET credential_id = NULL WHERE credential_id = ?').run(id);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Secret déchiffré : INTERNE (clone/listRepos/test). Jamais exposé par une route. */
|
||||||
|
getSecret(id: string): string | null {
|
||||||
|
const row = this.getRow(id);
|
||||||
|
if (!row?.secret_encrypted) return null;
|
||||||
|
try {
|
||||||
|
return this.box.decrypt(row.secret_encrypted);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Contexte d'auth (service, base, secret déchiffré) pour le client API / le clone. */
|
||||||
|
authContext(id: string): { service: GitService; baseUrl: string | null; auth: GitAuth } | null {
|
||||||
|
const row = this.getRow(id);
|
||||||
|
if (!row) return null;
|
||||||
|
const secret = this.getSecret(id);
|
||||||
|
if (secret == null) return null;
|
||||||
|
return { service: row.service, baseUrl: row.base_url, auth: { authType: row.auth_type, username: row.username, secret } };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Teste la connectivité/auth (GET /user) et mémorise le diagnostic. */
|
||||||
|
async test(id: string): Promise<TestCredentialResponse> {
|
||||||
|
const ctx = this.authContext(id);
|
||||||
|
if (!ctx) throw httpError(404, 'NOT_FOUND', 'No credential with this id');
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
try {
|
||||||
|
const { login } = await getGitClient(ctx.service, ctx.baseUrl).verify(ctx.auth);
|
||||||
|
this.db.prepare('UPDATE git_credentials SET last_tested_at = ?, test_result = ? WHERE id = ?').run(now, 'ok', id);
|
||||||
|
return { ok: true, user: login };
|
||||||
|
} catch (err) {
|
||||||
|
const code = err instanceof GitServiceError ? err.errorCode : 'UNREACHABLE';
|
||||||
|
this.db.prepare('UPDATE git_credentials SET last_tested_at = ?, test_result = ? WHERE id = ?').run(now, code, id);
|
||||||
|
return { ok: false, error: code };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Helper d'audit partagé (jamais de secret dans details). */
|
||||||
|
export function auditCredential(db: Db, actor: string, action: string, id: string | null): void {
|
||||||
|
recordAudit(db, { actor, action, resourceId: id });
|
||||||
|
}
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
// Couche git sûre : tout passe par execFile (JAMAIS de shell), arguments en tableau, `--` avant
|
// Couche git sûre : tout passe par execFile (JAMAIS de shell), arguments en tableau, `--` avant
|
||||||
// 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, spawn } 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, FileChange } 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.
|
||||||
@@ -37,6 +39,24 @@ function git(cwd: string, args: string[]): Promise<string> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Variante tolérante : résout `{ stdout, code }` au lieu de rejeter sur code de sortie non nul.
|
||||||
|
* Utile pour `git diff --no-index` (code 1 = « les fichiers diffèrent », pas une erreur).
|
||||||
|
*/
|
||||||
|
function gitRaw(cwd: string, args: string[], timeoutMs: number = GIT_TIMEOUT_MS): Promise<{ stdout: string; code: number }> {
|
||||||
|
return new Promise((resolveP) => {
|
||||||
|
execFile(
|
||||||
|
'git',
|
||||||
|
args,
|
||||||
|
{ cwd, timeout: timeoutMs, maxBuffer: GIT_MAX_BUFFER, env: { ...process.env, GIT_OPTIONAL_LOCKS: '0', LC_ALL: 'C' } },
|
||||||
|
(err, stdout) => {
|
||||||
|
const code = err ? ((err as GitError).code as number) ?? 1 : 0;
|
||||||
|
resolveP({ stdout: stdout.toString(), code: typeof code === 'number' ? code : 1 });
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export interface ParsedWorktree {
|
export interface ParsedWorktree {
|
||||||
path: string;
|
path: string;
|
||||||
head: string | null;
|
head: string | null;
|
||||||
@@ -120,6 +140,21 @@ export function isSafeAbsolutePath(p: string): boolean {
|
|||||||
return p.startsWith('/') && resolve(p) === p && !p.split(sep).includes('..');
|
return p.startsWith('/') && resolve(p) === p && !p.split(sep).includes('..');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pathspec relatif sûr passé à git (`git add/restore/diff -- <p>`) : non vide, non absolu, sans
|
||||||
|
* segment `..`, ne commençant pas par `-` (anti-flag). Le `--` avant le pathspec reste obligatoire.
|
||||||
|
*/
|
||||||
|
export function isSafeRelativePath(p: string): boolean {
|
||||||
|
if (p.length === 0 || p.startsWith('/') || p.startsWith('-')) return false;
|
||||||
|
const parts = p.split(/[\\/]/);
|
||||||
|
return !parts.includes('..') && !parts.includes('.git');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Initialise un dépôt git dans `dir` (déjà créé et validé par l'appelant). `git init` est idempotent. */
|
||||||
|
export async function gitInit(dir: string): Promise<void> {
|
||||||
|
await git(dir, ['init']);
|
||||||
|
}
|
||||||
|
|
||||||
/** true si `path` est la racine d'un dépôt git (main worktree) accessible. */
|
/** true si `path` est la racine d'un dépôt git (main worktree) accessible. */
|
||||||
export async function isRepo(path: string): Promise<boolean> {
|
export async function isRepo(path: string): Promise<boolean> {
|
||||||
try {
|
try {
|
||||||
@@ -140,6 +175,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']));
|
||||||
}
|
}
|
||||||
@@ -166,28 +247,349 @@ export async function worktreeStatus(worktreePath: string): Promise<WorktreeGitS
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
let dirtyCount = 0;
|
let dirtyCount = 0;
|
||||||
|
let stagedCount = 0;
|
||||||
|
let unstagedCount = 0;
|
||||||
|
let conflictCount = 0;
|
||||||
try {
|
try {
|
||||||
const status = await git(worktreePath, ['status', '--porcelain=v1', '--untracked-files=all']);
|
// Un SEUL passage porcelain v2 -z : dirtyCount + compteurs fins (staged/unstaged/conflit).
|
||||||
dirtyCount = status.split('\n').filter((l) => l.trim() !== '').length;
|
const out = await git(worktreePath, ['status', '--porcelain=v2', '-z', '--untracked-files=all']);
|
||||||
|
const entries = parsePorcelainV2(out);
|
||||||
|
dirtyCount = entries.length;
|
||||||
|
for (const e of entries) {
|
||||||
|
if (e.conflicted) conflictCount++;
|
||||||
|
if (e.staged) stagedCount++;
|
||||||
|
if (e.unstaged) unstagedCount++;
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
/* ignore */
|
/* ignore */
|
||||||
}
|
}
|
||||||
return { ahead, behind, dirtyCount, upstream };
|
let lastCommitHash: string | null = null;
|
||||||
|
let lastCommitSubject: string | null = null;
|
||||||
|
try {
|
||||||
|
const lc = await lastCommit(worktreePath);
|
||||||
|
if (lc) {
|
||||||
|
lastCommitHash = lc.hash;
|
||||||
|
lastCommitSubject = lc.subject;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* repo sans commit : on laisse null */
|
||||||
|
}
|
||||||
|
return { ahead, behind, dirtyCount, upstream, stagedCount, unstagedCount, conflictCount, lastCommitHash, lastCommitSubject };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- P7 : statut détaillé / diff / staging / commit sélectif / fetch-pull (IDE worktree) ----
|
||||||
|
|
||||||
|
/** Entrée brute de `git status --porcelain=v2` (avant enrichissement numstat). */
|
||||||
|
export interface PorcelainV2Entry {
|
||||||
|
path: string;
|
||||||
|
indexStatus: string;
|
||||||
|
worktreeStatus: string;
|
||||||
|
staged: boolean;
|
||||||
|
unstaged: boolean;
|
||||||
|
untracked: boolean;
|
||||||
|
conflicted: boolean;
|
||||||
|
renamedFrom?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse `git status --porcelain=v2 -z --untracked-files=all` (testable sans repo réel). Format -z :
|
||||||
|
* champs séparés par NUL ; une entrée de renommage (type `2`) consomme un champ supplémentaire
|
||||||
|
* (l'ancien chemin). Les chemins ne sont jamais entre guillemets en mode -z (pas d'échappement).
|
||||||
|
*/
|
||||||
|
export function parsePorcelainV2(stdout: string): PorcelainV2Entry[] {
|
||||||
|
const fields = stdout.split('\0');
|
||||||
|
if (fields.length && fields[fields.length - 1] === '') fields.pop();
|
||||||
|
const out: PorcelainV2Entry[] = [];
|
||||||
|
for (let i = 0; i < fields.length; i++) {
|
||||||
|
const f = fields[i];
|
||||||
|
if (!f) continue;
|
||||||
|
const kind = f[0];
|
||||||
|
if (kind === '1') {
|
||||||
|
const t = f.split(' ');
|
||||||
|
const xy = t[1] ?? '..';
|
||||||
|
out.push(entryFromXy(t.slice(8).join(' '), xy, { conflicted: false }));
|
||||||
|
} else if (kind === '2') {
|
||||||
|
const t = f.split(' ');
|
||||||
|
const xy = t[1] ?? '..';
|
||||||
|
const path = t.slice(9).join(' ');
|
||||||
|
const renamedFrom = fields[++i]; // l'ancien chemin suit dans le champ NUL suivant
|
||||||
|
out.push(entryFromXy(path, xy, { conflicted: false, ...(renamedFrom ? { renamedFrom } : {}) }));
|
||||||
|
} else if (kind === 'u') {
|
||||||
|
const t = f.split(' ');
|
||||||
|
const xy = t[1] ?? '..';
|
||||||
|
out.push(entryFromXy(t.slice(10).join(' '), xy, { conflicted: true }));
|
||||||
|
} else if (kind === '?') {
|
||||||
|
out.push({ path: f.slice(2), indexStatus: '?', worktreeStatus: '?', staged: false, unstaged: true, untracked: true, conflicted: false });
|
||||||
|
}
|
||||||
|
// '!' (ignored) : exclu de la liste des changements.
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function entryFromXy(path: string, xy: string, opts: { conflicted: boolean; renamedFrom?: string }): PorcelainV2Entry {
|
||||||
|
const indexStatus = xy[0] ?? '.';
|
||||||
|
const worktreeStatus = xy[1] ?? '.';
|
||||||
|
return {
|
||||||
|
path,
|
||||||
|
indexStatus,
|
||||||
|
worktreeStatus,
|
||||||
|
staged: !opts.conflicted && indexStatus !== '.',
|
||||||
|
unstaged: opts.conflicted || worktreeStatus !== '.',
|
||||||
|
untracked: false,
|
||||||
|
conflicted: opts.conflicted,
|
||||||
|
...(opts.renamedFrom ? { renamedFrom: opts.renamedFrom } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse `git diff --numstat -z` → map chemin → {insertions, deletions, binary}. Les fichiers
|
||||||
|
* binaires sont marqués `'-'` par git. Les renommages ont un champ chemin vide suivi de
|
||||||
|
* deux champs NUL (ancien, nouveau) ; on indexe par le nouveau chemin.
|
||||||
|
*/
|
||||||
|
export function parseNumstatZ(stdout: string): Map<string, { insertions: number | null; deletions: number | null; binary: boolean }> {
|
||||||
|
const fields = stdout.split('\0');
|
||||||
|
if (fields.length && fields[fields.length - 1] === '') fields.pop();
|
||||||
|
const map = new Map<string, { insertions: number | null; deletions: number | null; binary: boolean }>();
|
||||||
|
for (let i = 0; i < fields.length; i++) {
|
||||||
|
const f = fields[i];
|
||||||
|
if (!f) continue;
|
||||||
|
const parts = f.split('\t');
|
||||||
|
if (parts.length < 3) continue;
|
||||||
|
const addRaw = parts[0] ?? '';
|
||||||
|
const delRaw = parts[1] ?? '';
|
||||||
|
let path = parts[2] ?? '';
|
||||||
|
if (path === '') {
|
||||||
|
// renommage : ancien chemin = champ suivant, nouveau chemin = champ d'après.
|
||||||
|
i++; // saute l'ancien chemin
|
||||||
|
path = fields[++i] ?? '';
|
||||||
|
if (path === '') continue;
|
||||||
|
}
|
||||||
|
const binary = addRaw === '-' || delRaw === '-';
|
||||||
|
map.set(path, {
|
||||||
|
insertions: binary ? null : Number(addRaw) || 0,
|
||||||
|
deletions: binary ? null : Number(delRaw) || 0,
|
||||||
|
binary,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_CHANGES = 5000;
|
||||||
|
|
||||||
|
/** Liste les fichiers modifiés d'un worktree (statut porcelain v2 enrichi des stats numstat). */
|
||||||
|
export async function listChanges(worktreePath: string): Promise<{ changes: FileChange[]; truncated: boolean }> {
|
||||||
|
const [statusOut, unstagedOut, stagedOut] = await Promise.all([
|
||||||
|
git(worktreePath, ['status', '--porcelain=v2', '-z', '--untracked-files=all']),
|
||||||
|
git(worktreePath, ['diff', '--numstat', '-z']),
|
||||||
|
git(worktreePath, ['diff', '--numstat', '-z', '--cached']),
|
||||||
|
]);
|
||||||
|
const entries = parsePorcelainV2(statusOut);
|
||||||
|
const unstaged = parseNumstatZ(unstagedOut);
|
||||||
|
const staged = parseNumstatZ(stagedOut);
|
||||||
|
const truncated = entries.length > MAX_CHANGES;
|
||||||
|
const slice = truncated ? entries.slice(0, MAX_CHANGES) : entries;
|
||||||
|
const changes: FileChange[] = slice.map((e) => {
|
||||||
|
const ns = unstaged.get(e.path) ?? staged.get(e.path);
|
||||||
|
const binary = ns?.binary ?? false;
|
||||||
|
// insertions/deletions = somme staged+unstaged quand disponible ; null pour binaire/untracked.
|
||||||
|
const u = unstaged.get(e.path);
|
||||||
|
const s = staged.get(e.path);
|
||||||
|
const sum = (a: number | null | undefined, b: number | null | undefined): number | null => {
|
||||||
|
if (a == null && b == null) return null;
|
||||||
|
return (a ?? 0) + (b ?? 0);
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
path: e.path,
|
||||||
|
indexStatus: e.indexStatus,
|
||||||
|
worktreeStatus: e.worktreeStatus,
|
||||||
|
staged: e.staged,
|
||||||
|
unstaged: e.unstaged,
|
||||||
|
untracked: e.untracked,
|
||||||
|
conflicted: e.conflicted,
|
||||||
|
insertions: binary ? null : sum(u?.insertions, s?.insertions),
|
||||||
|
deletions: binary ? null : sum(u?.deletions, s?.deletions),
|
||||||
|
binary,
|
||||||
|
...(e.renamedFrom ? { renamedFrom: e.renamedFrom } : {}),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
return { changes, truncated };
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_DIFF_BYTES = 512 * 1024;
|
||||||
|
|
||||||
|
/** Diff unifié d'un fichier. `staged` → diff de l'index ; `untracked` → diff vs /dev/null. */
|
||||||
|
export async function fileDiff(
|
||||||
|
worktreePath: string,
|
||||||
|
file: string,
|
||||||
|
opts: { staged?: boolean; untracked?: boolean } = {},
|
||||||
|
): Promise<{ diff: string; binary: boolean; tooLarge: boolean }> {
|
||||||
|
let raw: string;
|
||||||
|
if (opts.untracked) {
|
||||||
|
// --no-index sort en code 1 quand les fichiers diffèrent : on tolère via gitRaw.
|
||||||
|
const r = await gitRaw(worktreePath, ['diff', '--no-index', '--no-color', '--', '/dev/null', file]);
|
||||||
|
raw = r.stdout;
|
||||||
|
} else {
|
||||||
|
raw = await git(worktreePath, ['diff', '--no-color', ...(opts.staged ? ['--cached'] : []), '--', file]);
|
||||||
|
}
|
||||||
|
const binary = /^Binary files .* differ$/m.test(raw) || raw.includes('GIT binary patch');
|
||||||
|
if (binary) return { diff: '', binary: true, tooLarge: false };
|
||||||
|
if (raw.length > MAX_DIFF_BYTES) return { diff: raw.slice(0, MAX_DIFF_BYTES), binary: false, tooLarge: true };
|
||||||
|
return { diff: raw, binary: false, tooLarge: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Indexe des fichiers (`git add -- <files>`). Chaque chemin validé par l'appelant (isSafeRelativePath). */
|
||||||
|
export async function stageFiles(worktreePath: string, files: string[]): Promise<void> {
|
||||||
|
if (files.length === 0) return;
|
||||||
|
await git(worktreePath, ['add', '--', ...files]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Désindexe des fichiers (`git restore --staged -- <files>`). */
|
||||||
|
export async function unstageFiles(worktreePath: string, files: string[]): Promise<void> {
|
||||||
|
if (files.length === 0) return;
|
||||||
|
await git(worktreePath, ['restore', '--staged', '--', ...files]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Annule les modifications de l'arbre de travail de fichiers SUIVIS (`git restore -- <files>`). */
|
||||||
|
export async function restoreFiles(worktreePath: string, files: string[]): Promise<void> {
|
||||||
|
if (files.length === 0) return;
|
||||||
|
await git(worktreePath, ['restore', '--', ...files]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Supprime des fichiers NON SUIVIS (`git clean -f -- <files>`). Destructif : opt-in côté appelant. */
|
||||||
|
export async function cleanFiles(worktreePath: string, files: string[]): Promise<void> {
|
||||||
|
if (files.length === 0) return;
|
||||||
|
await git(worktreePath, ['clean', '-f', '--', ...files]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Commit de l'index uniquement (contraste avec `commitAll` = `git add -A` + commit). */
|
||||||
|
export async function commitStaged(worktreePath: string, message: string): Promise<void> {
|
||||||
|
await git(worktreePath, ['commit', '-m', message]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Réécrit le dernier commit. L'appelant garantit qu'il n'est pas déjà poussé. */
|
||||||
|
export async function amendCommit(worktreePath: string, message?: string): Promise<void> {
|
||||||
|
await git(worktreePath, message ? ['commit', '--amend', '-m', message] : ['commit', '--amend', '--no-edit']);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `git fetch --all --prune` (réseau → timeout élargi). */
|
||||||
|
export async function fetchRemote(worktreePath: string): Promise<void> {
|
||||||
|
await git(worktreePath, ['fetch', '--all', '--prune'], GIT_PUSH_TIMEOUT_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `git pull` : `ff-only` par défaut (jamais de merge surprise) ; `rebase` optionnel. */
|
||||||
|
export async function pull(worktreePath: string, mode: 'ff-only' | 'rebase' = 'ff-only'): Promise<void> {
|
||||||
|
const args = mode === 'rebase' ? ['-c', 'rebase.autoStash=false', 'pull', '--rebase'] : ['pull', '--ff-only'];
|
||||||
|
await git(worktreePath, args, GIT_PUSH_TIMEOUT_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Répertoire git absolu d'un worktree (`git rev-parse --absolute-git-dir`). Pour le checkout
|
||||||
|
* principal : `<path>/.git` ; pour un worktree LIÉ : `<repo>/.git/worktrees/<n>` (le `.git` du
|
||||||
|
* worktree est un fichier pointeur). Sert au watcher FS pour surveiller le bon `HEAD`/`index`.
|
||||||
|
*/
|
||||||
|
export async function resolveGitDir(worktreePath: string): Promise<string | null> {
|
||||||
|
const r = await gitRaw(worktreePath, ['rev-parse', '--absolute-git-dir']);
|
||||||
|
if (r.code !== 0) return null;
|
||||||
|
return r.stdout.trim() || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Dernier commit (HEAD) : hash court + sujet. null si le dépôt n'a aucun commit. */
|
||||||
|
export async function lastCommit(worktreePath: string): Promise<{ hash: string; subject: string } | null> {
|
||||||
|
const r = await gitRaw(worktreePath, ['log', '-1', '--format=%h%x00%s']);
|
||||||
|
if (r.code !== 0) return null;
|
||||||
|
const idx = r.stdout.indexOf('\0');
|
||||||
|
if (idx === -1) return null;
|
||||||
|
return { hash: r.stdout.slice(0, idx), subject: r.stdout.slice(idx + 1).replace(/\n$/, '') };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** true si le HEAD courant n'est pas encore poussé (amend autorisé). Sans upstream → true. */
|
||||||
|
export async function isUnpushed(worktreePath: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
await git(worktreePath, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']);
|
||||||
|
} catch {
|
||||||
|
return true; // pas d'upstream → rien n'est « partagé »
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const out = (await git(worktreePath, ['rev-list', '--count', '@{u}..HEAD'])).trim();
|
||||||
|
return (Number(out) || 0) > 0;
|
||||||
|
} catch {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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,3 +605,50 @@ export function isDirtyWorktreeError(err: unknown): boolean {
|
|||||||
const msg = `${(err as GitError)?.stderr ?? ''} ${(err as Error)?.message ?? ''}`;
|
const msg = `${(err as GitError)?.stderr ?? ''} ${(err as Error)?.message ?? ''}`;
|
||||||
return /contains modified or untracked files|is dirty|use --force/i.test(msg);
|
return /contains modified or untracked files|is dirty|use --force/i.test(msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const GIT_CLONE_TIMEOUT_MS = 10 * 60_000; // 10 min : un clone réseau peut être long.
|
||||||
|
|
||||||
|
export interface CloneProgress {
|
||||||
|
phase: string;
|
||||||
|
/** pourcentage 0-100 si git le rapporte, sinon null. */
|
||||||
|
percent: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clone un dépôt via `git clone --progress` (P12). `spawn` (et non execFile) pour streamer la
|
||||||
|
* progression depuis stderr. `env` éphémère (cf. withGitAuth) porte l'auth : JAMAIS dans l'URL.
|
||||||
|
* `--` sépare l'URL/dest des options. L'appelant valide `dest` (sous scanRoots, non existant).
|
||||||
|
*/
|
||||||
|
export function cloneRepo(opts: {
|
||||||
|
url: string;
|
||||||
|
dest: string;
|
||||||
|
env?: NodeJS.ProcessEnv;
|
||||||
|
branch?: string;
|
||||||
|
onProgress?: (p: CloneProgress) => void;
|
||||||
|
signal?: AbortSignal;
|
||||||
|
}): Promise<void> {
|
||||||
|
return new Promise((resolveP, reject) => {
|
||||||
|
const args = ['clone', '--progress'];
|
||||||
|
if (opts.branch) args.push('--branch', opts.branch);
|
||||||
|
args.push('--', opts.url, opts.dest);
|
||||||
|
const child = spawn('git', args, {
|
||||||
|
env: { ...(opts.env ?? process.env), GIT_TERMINAL_PROMPT: '0', LC_ALL: 'C' },
|
||||||
|
stdio: ['ignore', 'ignore', 'pipe'],
|
||||||
|
timeout: GIT_CLONE_TIMEOUT_MS,
|
||||||
|
...(opts.signal ? { signal: opts.signal } : {}),
|
||||||
|
});
|
||||||
|
let stderr = '';
|
||||||
|
child.stderr.on('data', (d: Buffer) => {
|
||||||
|
const s = d.toString();
|
||||||
|
stderr += s;
|
||||||
|
if (stderr.length > 64 * 1024) stderr = stderr.slice(-64 * 1024); // borne mémoire
|
||||||
|
const m = /([A-Za-z][A-Za-z ]+):\s+(\d+)%/.exec(s);
|
||||||
|
if (m && m[1] && m[2] && opts.onProgress) opts.onProgress({ phase: m[1].trim(), percent: Number(m[2]) });
|
||||||
|
});
|
||||||
|
child.on('error', (err) => reject(err));
|
||||||
|
child.on('close', (code) => {
|
||||||
|
if (code === 0) resolveP();
|
||||||
|
else reject(new Error(stderr.trim().split('\n').pop() || `git clone exited with code ${code}`));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// Gestion des groupes de travail (P5) : un groupe = collection nommée de repos (many-to-many).
|
// 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 —
|
// 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.
|
// 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.
|
// Tout est synchrone : aucune I/O git/fs, node:sqlite est synchrone.
|
||||||
import { EventEmitter } from 'node:events';
|
import { EventEmitter } from 'node:events';
|
||||||
@@ -167,6 +167,8 @@ export class GroupManager extends EventEmitter<GroupManagerEvents> {
|
|||||||
// CASCADE (PRAGMA foreign_keys = ON) purge group_repos.
|
// CASCADE (PRAGMA foreign_keys = ON) purge group_repos.
|
||||||
const res = this.db.prepare('DELETE FROM groups WHERE id = ?').run(id);
|
const res = this.db.prepare('DELETE FROM groups WHERE id = ?').run(id);
|
||||||
if (res.changes === 0) return false;
|
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);
|
this.emit('group_removed', id);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
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 };
|
||||||
|
}
|
||||||
@@ -10,7 +10,7 @@ const HEAD_BYTES = 256 * 1024;
|
|||||||
const TAIL_BYTES = 64 * 1024;
|
const TAIL_BYTES = 64 * 1024;
|
||||||
const TITLE_MAX = 120;
|
const TITLE_MAX = 120;
|
||||||
|
|
||||||
/** Reproduit le nom de dossier ~/.claude/projects à partir d'un cwd (validé 100 % — spike S4). */
|
/** Reproduit le nom de dossier ~/.claude/projects à partir d'un cwd (validé 100 %, spike S4). */
|
||||||
export function munge(cwd: string): string {
|
export function munge(cwd: string): string {
|
||||||
return cwd.replace(/[^A-Za-z0-9]/g, '-');
|
return cwd.replace(/[^A-Za-z0-9]/g, '-');
|
||||||
}
|
}
|
||||||
@@ -82,7 +82,7 @@ function extractMeta(objs: Array<Record<string, unknown>>, meta: Meta): void {
|
|||||||
setOnce('cwd', o.cwd);
|
setOnce('cwd', o.cwd);
|
||||||
setOnce('gitBranch', o.gitBranch);
|
setOnce('gitBranch', o.gitBranch);
|
||||||
setOnce('version', o.version);
|
setOnce('version', o.version);
|
||||||
// Titre : on retient la dernière valeur vue (la plus récente) — head puis tail → la queue gagne.
|
// Titre : on retient la dernière valeur vue (la plus récente) : head puis tail → la queue gagne.
|
||||||
const ai = asString(o.aiTitle);
|
const ai = asString(o.aiTitle);
|
||||||
if (ai) meta.aiTitle = ai;
|
if (ai) meta.aiTitle = ai;
|
||||||
const sum = asString(o.summary);
|
const sum = asString(o.summary);
|
||||||
|
|||||||
33
packages/server/src/core/project.ts
Normal file
33
packages/server/src/core/project.ts
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
// Création d'un nouveau projet : un dossier `<root>/<name>` créé sous une racine existante, dans
|
||||||
|
// lequel on lance ensuite une session. Couche PURE (testable sans fs) : la création réelle du
|
||||||
|
// dossier, le `git init` et le spawn vivent dans `routes/projects.ts`.
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { isSafeAbsolutePath } from './git.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valide un nom de projet : UN SEUL segment de dossier. Anti-traversal de base : refuse les noms
|
||||||
|
* vides, trop longs, `.`/`..`, et tout caractère de séparation (`/`, `\`) ou NUL. La résolution du
|
||||||
|
* chemin complet (et sa re-validation) est faite par {@link resolveProjectDir}.
|
||||||
|
*/
|
||||||
|
export function isSafeProjectName(name: string): boolean {
|
||||||
|
const n = name.trim();
|
||||||
|
if (n.length === 0 || n.length > 255) return false;
|
||||||
|
if (n === '.' || n === '..') return false;
|
||||||
|
return !/[/\\\0]/.test(n);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Résout le dossier de projet `<root>/<name>`. Suppose `root` déjà validé absolu et existant par
|
||||||
|
* l'appelant ; re-valide le chemin final via {@link isSafeAbsolutePath} (défense en profondeur).
|
||||||
|
* Lève si `name` est invalide ou si le chemin résultant échappe l'arborescence.
|
||||||
|
*/
|
||||||
|
export function resolveProjectDir(root: string, name: string): string {
|
||||||
|
if (!isSafeProjectName(name)) {
|
||||||
|
throw Object.assign(new Error(`Invalid project name: ${name}`), { statusCode: 400 });
|
||||||
|
}
|
||||||
|
const dir = join(root, name.trim());
|
||||||
|
if (!isSafeAbsolutePath(dir)) {
|
||||||
|
throw Object.assign(new Error(`Unsafe project path: ${dir}`), { statusCode: 400 });
|
||||||
|
}
|
||||||
|
return dir;
|
||||||
|
}
|
||||||
@@ -7,12 +7,15 @@ import pty from '@homebridge/node-pty-prebuilt-multiarch';
|
|||||||
import { FLOW, REPLAY_TAIL_BYTES, type SessionActivity, type SessionSummary } from '@arboretum/shared';
|
import { FLOW, REPLAY_TAIL_BYTES, type SessionActivity, type SessionSummary } from '@arboretum/shared';
|
||||||
import { RingBuffer } from './ring-buffer.js';
|
import { RingBuffer } from './ring-buffer.js';
|
||||||
import { buildSpawnSpec } from './claude-launcher.js';
|
import { buildSpawnSpec } from './claude-launcher.js';
|
||||||
|
import { readClaudeBinPath } from './claude-settings.js';
|
||||||
import { findByPid } from './session-registry.js';
|
import { findByPid } from './session-registry.js';
|
||||||
import { SessionActivityTracker } from './claude-adapter.js';
|
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 +23,36 @@ 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;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ligne `sessions` telle que lue pour construire un SessionSummary historique (session terminée).
|
||||||
|
* `type` (et non `interface`) pour que TS infère l'index signature implicite → cast direct depuis
|
||||||
|
* le `Record<string, SQLOutputValue>` de node:sqlite.
|
||||||
|
*/
|
||||||
|
type HistoricalRow = {
|
||||||
|
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;
|
||||||
|
archived_at: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 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 +81,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 +109,36 @@ 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 });
|
||||||
}
|
}
|
||||||
// Un resume/fork est toujours une session claude (le cwd d'origine est garanti par l'appelant — S1).
|
// 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).
|
||||||
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 } : {}) });
|
// Override de chemin du binaire claude (réglage UI) lu à chaque spawn → effet sans redémarrage.
|
||||||
|
const claudeBinPath = command === 'claude' ? readClaudeBinPath(this.db) : null;
|
||||||
|
const spec = buildSpawnSpec({
|
||||||
|
command,
|
||||||
|
...(claudeBinPath ? { claudeBinPath } : {}),
|
||||||
|
...(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 +160,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 +177,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));
|
||||||
@@ -128,7 +197,7 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
|||||||
return summary;
|
return summary;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Résout le claudeSessionId du CLI en pollant le registre par pid, puis le persiste (waitReady — S1). */
|
/** Résout le claudeSessionId du CLI en pollant le registre par pid, puis le persiste (waitReady, S1). */
|
||||||
private captureClaudeSessionId(s: ManagedSession): void {
|
private captureClaudeSessionId(s: ManagedSession): void {
|
||||||
const deadline = Date.now() + CLAUDE_ID_TIMEOUT_MS;
|
const deadline = Date.now() + CLAUDE_ID_TIMEOUT_MS;
|
||||||
const tick = (): void => {
|
const tick = (): void => {
|
||||||
@@ -145,6 +214,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()) {
|
||||||
@@ -166,36 +265,61 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
|||||||
return set;
|
return set;
|
||||||
}
|
}
|
||||||
|
|
||||||
list(): SessionSummary[] {
|
list(opts?: { includeArchived?: boolean }): SessionSummary[] {
|
||||||
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, archived_at 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 HistoricalRow[];
|
||||||
const historical: SessionSummary[] = rows
|
const historical: SessionSummary[] = rows
|
||||||
.filter((r) => !liveIds.has(r.id))
|
.filter((r) => !liveIds.has(r.id))
|
||||||
.map((r) => ({
|
// Sessions auto-archivées exclues par défaut (filtre indépendant et cumulable avec hidden).
|
||||||
id: r.id,
|
.filter((r) => (opts?.includeArchived ? true : r.archived_at == null))
|
||||||
cwd: r.cwd,
|
.map((r) => this.historicalSummary(r));
|
||||||
command: r.command,
|
|
||||||
title: r.title,
|
|
||||||
status: 'exited',
|
|
||||||
live: false,
|
|
||||||
createdAt: r.created_at,
|
|
||||||
endedAt: r.ended_at,
|
|
||||||
exitCode: r.exit_code,
|
|
||||||
clients: 0,
|
|
||||||
source: 'managed',
|
|
||||||
claudeSessionId: r.claude_session_id,
|
|
||||||
pid: null,
|
|
||||||
// une session claude morte avec un claudeSessionId connu est reprenable (--resume direct).
|
|
||||||
resumable: r.command === 'claude' && r.claude_session_id != null,
|
|
||||||
attachable: false,
|
|
||||||
registryStatus: null,
|
|
||||||
}));
|
|
||||||
return [...liveSummaries, ...historical];
|
return [...liveSummaries, ...historical];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Construit le SessionSummary d'une ligne historique (session managée terminée). */
|
||||||
|
private historicalSummary(r: HistoricalRow): SessionSummary {
|
||||||
|
const addedDirs = parseAddedDirs(r.added_dirs);
|
||||||
|
return {
|
||||||
|
id: r.id,
|
||||||
|
cwd: r.cwd,
|
||||||
|
command: r.command,
|
||||||
|
title: r.title,
|
||||||
|
status: 'exited' as const,
|
||||||
|
live: false,
|
||||||
|
createdAt: r.created_at,
|
||||||
|
endedAt: r.ended_at,
|
||||||
|
exitCode: r.exit_code,
|
||||||
|
clients: 0,
|
||||||
|
source: 'managed' as const,
|
||||||
|
claudeSessionId: r.claude_session_id,
|
||||||
|
pid: null,
|
||||||
|
// une session claude morte avec un claudeSessionId connu est reprenable (--resume direct).
|
||||||
|
resumable: r.command === 'claude' && r.claude_session_id != null,
|
||||||
|
attachable: false,
|
||||||
|
registryStatus: null,
|
||||||
|
...(addedDirs.length ? { addedDirs } : {}),
|
||||||
|
groupId: r.group_id,
|
||||||
|
archived: r.archived_at != null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ré-émet un `session_update` pour une session historique (P10) : utilisé au dés-archivage pour
|
||||||
|
* que tous les clients rafraîchissent le row (le champ `archived` repasse à false). No-op si la
|
||||||
|
* session est vivante (déjà couverte par le flux live) ou inconnue.
|
||||||
|
*/
|
||||||
|
emitHistoricalUpdate(id: string): void {
|
||||||
|
if (this.live.has(id)) return;
|
||||||
|
const r = this.db
|
||||||
|
.prepare('SELECT id, cwd, command, title, created_at, ended_at, exit_code, claude_session_id, added_dirs, group_id, archived_at FROM sessions WHERE id = ?')
|
||||||
|
.get(id) as HistoricalRow | undefined;
|
||||||
|
if (!r) return;
|
||||||
|
this.emit('session_update', this.historicalSummary(r));
|
||||||
|
}
|
||||||
|
|
||||||
get(id: string): SessionSummary | null {
|
get(id: string): SessionSummary | null {
|
||||||
const s = this.live.get(id);
|
const s = this.live.get(id);
|
||||||
return s ? this.summarize(s) : null;
|
return s ? this.summarize(s) : null;
|
||||||
@@ -221,7 +345,7 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Arrêt du daemon : SIGTERM à toutes les sessions (le CLI nettoie son registre sur SIGTERM — spike S1). */
|
/** Arrêt du daemon : SIGTERM à toutes les sessions (le CLI nettoie son registre sur SIGTERM, spike S1). */
|
||||||
shutdown(): void {
|
shutdown(): void {
|
||||||
for (const id of this.live.keys()) this.kill(id);
|
for (const id of this.live.keys()) this.kill(id);
|
||||||
}
|
}
|
||||||
@@ -272,7 +396,7 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
|||||||
/**
|
/**
|
||||||
* Répond à un dialogue Claude sans clavier (P4-A) : traduit une intention de haut
|
* Répond à un dialogue Claude sans clavier (P4-A) : traduit une intention de haut
|
||||||
* niveau en keystrokes PTY, validée contre l'état fin du tracker (P3-B).
|
* niveau en keystrokes PTY, validée contre l'état fin du tracker (P3-B).
|
||||||
* - 'select' N : positionne le curseur sur l'option N puis confirme (`"N\r"`) — protocole acté spike S3.
|
* - 'select' N : positionne le curseur sur l'option N puis confirme (`"N\r"`) : protocole acté spike S3.
|
||||||
* - 'confirm' : valide l'option pré-sélectionnée (`"\r"`).
|
* - 'confirm' : valide l'option pré-sélectionnée (`"\r"`).
|
||||||
* - 'deny' : refus universel (Esc).
|
* - 'deny' : refus universel (Esc).
|
||||||
* Réutilise le chemin write (mono-utilisateur : tout interactif peut répondre, observers non).
|
* Réutilise le chemin write (mono-utilisateur : tout interactif peut répondre, observers non).
|
||||||
@@ -293,7 +417,7 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
|||||||
s.proc.write(`${optionN}\r`);
|
s.proc.write(`${optionN}\r`);
|
||||||
return 'ok';
|
return 'ok';
|
||||||
}
|
}
|
||||||
// confirm/deny n'exigent qu'un état d'attente (le dialogue Trust précède le registre — S1).
|
// confirm/deny n'exigent qu'un état d'attente (le dialogue Trust précède le registre, S1).
|
||||||
if (act?.activity !== 'waiting') return 'invalid';
|
if (act?.activity !== 'waiting') return 'invalid';
|
||||||
s.proc.write(action === 'deny' ? '\x1b' : '\r');
|
s.proc.write(action === 'deny' ? '\x1b' : '\r');
|
||||||
return 'ok';
|
return 'ok';
|
||||||
@@ -322,30 +446,35 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
|||||||
// ---- interne ----
|
// ---- interne ----
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Push P4-B : notifie sur le FRONT MONTANT vers `waiting` uniquement (le tracker réémet
|
* Push P4-B : notifie sur le FRONT MONTANT vers un état qui requiert l'attention : `waiting`
|
||||||
* souvent le même état), avec un debounce annulable — un `waiting` ultra-bref (Claude répond
|
* (un dialogue bloque) ou `idle` atteint depuis `busy` (Claude a terminé sa réponse, la session
|
||||||
* tout seul) ne déclenche pas de notif. Cible tous les abonnements (un seul utilisateur).
|
* redevient disponible). Le tracker réémet souvent le même état → on ne réagit qu'au changement.
|
||||||
|
* Debounce annulable : un état ultra-bref (Claude repart tout seul) ne déclenche pas de notif :
|
||||||
|
* à l'échéance on revérifie l'état réel. Cible tous les abonnements (un seul utilisateur).
|
||||||
*/
|
*/
|
||||||
private maybeNotify(s: ManagedSession, next: SessionActivity | null): void {
|
private maybeNotify(s: ManagedSession, next: SessionActivity | null): void {
|
||||||
const prev = s.prevActivity;
|
const prev = s.prevActivity;
|
||||||
s.prevActivity = next;
|
s.prevActivity = next;
|
||||||
if (!this.push) return;
|
if (!this.push) return;
|
||||||
if (next === 'waiting' && prev !== 'waiting') {
|
const notifiable =
|
||||||
|
(next === 'waiting' && prev !== 'waiting') || (next === 'idle' && prev === 'busy');
|
||||||
|
if (notifiable) {
|
||||||
|
const target = next; // 'waiting' | 'idle'
|
||||||
if (s.notifyTimer) clearTimeout(s.notifyTimer);
|
if (s.notifyTimer) clearTimeout(s.notifyTimer);
|
||||||
s.notifyTimer = setTimeout(() => {
|
s.notifyTimer = setTimeout(() => {
|
||||||
s.notifyTimer = null;
|
s.notifyTimer = null;
|
||||||
const act = s.tracker?.snapshot();
|
const act = s.tracker?.snapshot();
|
||||||
if (s.exited || act?.activity !== 'waiting') return; // faux positif : annulé
|
if (s.exited || act?.activity !== target) return; // faux positif : l'état a déjà changé
|
||||||
void this.push?.notify({
|
const base = { sessionId: s.id, title: basename(s.cwd) || s.cwd, url: `/sessions/${s.id}` };
|
||||||
sessionId: s.id,
|
void this.push?.notify(
|
||||||
title: basename(s.cwd) || s.cwd,
|
target === 'idle'
|
||||||
body: act.dialog?.waitingFor ?? act.waitingFor ?? 'waiting for your input',
|
? { ...base, body: 'available for new instructions', kind: null }
|
||||||
kind: act.dialog?.kind ?? null,
|
: { ...base, body: act.dialog?.waitingFor ?? act.waitingFor ?? 'waiting for your input', kind: act.dialog?.kind ?? null },
|
||||||
url: `/sessions/${s.id}`,
|
);
|
||||||
});
|
|
||||||
}, NOTIFY_DEBOUNCE_MS);
|
}, NOTIFY_DEBOUNCE_MS);
|
||||||
s.notifyTimer.unref();
|
s.notifyTimer.unref();
|
||||||
} else if (next !== 'waiting' && s.notifyTimer) {
|
} else if (s.notifyTimer && next !== 'waiting' && next !== 'idle') {
|
||||||
|
// On quitte un état notifiable avant l'échéance (ex. Claude repart en busy) → annule.
|
||||||
clearTimeout(s.notifyTimer);
|
clearTimeout(s.notifyTimer);
|
||||||
s.notifyTimer = null;
|
s.notifyTimer = null;
|
||||||
}
|
}
|
||||||
@@ -427,6 +556,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,9 +4,11 @@
|
|||||||
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.
|
||||||
const require = createRequire(import.meta.url);
|
const require = createRequire(import.meta.url);
|
||||||
const webpush = require('web-push') as typeof import('web-push');
|
const webpush = require('web-push') as typeof import('web-push');
|
||||||
|
|
||||||
@@ -31,7 +33,7 @@ interface SubRow {
|
|||||||
auth: string;
|
auth: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Envoi d'une notif à un abonnement — injectable pour les tests ; défaut = web-push réel. */
|
/** Envoi d'une notif à un abonnement : injectable pour les tests ; défaut = web-push réel. */
|
||||||
export type PushSender = (
|
export type PushSender = (
|
||||||
subscription: { endpoint: string; keys: { p256dh: string; auth: string } },
|
subscription: { endpoint: string; keys: { p256dh: string; auth: string } },
|
||||||
payload: string,
|
payload: string,
|
||||||
@@ -47,22 +49,28 @@ 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Clé publique VAPID — sûre à exposer (applicationServerKey côté navigateur). */
|
/** Clé publique VAPID : sûre à exposer (applicationServerKey côté navigateur). */
|
||||||
publicKey(): string {
|
publicKey(): string {
|
||||||
return this.vapidPublic;
|
return this.vapidPublic;
|
||||||
}
|
}
|
||||||
|
|||||||
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 };
|
||||||
|
}
|
||||||
48
packages/server/src/core/retention-settings.ts
Normal file
48
packages/server/src/core/retention-settings.ts
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
// Réglages de rétention des sessions terminées (archivage auto), persistés dans `settings`.
|
||||||
|
// Frontière de sécurité : clés NON sensibles, n'entrent dans l'allow-list du PATCH /api/v1/settings
|
||||||
|
// que via les validateurs ci-dessous. Calqué sur scan-settings.ts.
|
||||||
|
import { getSetting } from '../db/index.js';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
|
||||||
|
export const RETENTION_DAYS_KEY = 'session_retention_days';
|
||||||
|
export const PURGE_DAYS_KEY = 'session_purge_days';
|
||||||
|
|
||||||
|
/** Au-delà de N jours après la fin, une session managée est auto-archivée. 0 = jamais. */
|
||||||
|
export const DEFAULT_RETENTION_DAYS = 30;
|
||||||
|
/** Purge définitive (DELETE) après N jours. 0 = désactivée (conçue mais OFF par défaut). */
|
||||||
|
export const DEFAULT_PURGE_DAYS = 0;
|
||||||
|
export const MIN_RETENTION_DAYS = 1;
|
||||||
|
export const MAX_RETENTION_DAYS = 3650;
|
||||||
|
|
||||||
|
/** Rétention en jours (0 = jamais archiver). Défaut DEFAULT_RETENTION_DAYS. Lecture tolérante. */
|
||||||
|
export function readRetentionDays(db: Db): number {
|
||||||
|
return readDaysSetting(db, RETENTION_DAYS_KEY, DEFAULT_RETENTION_DAYS);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Purge définitive en jours (0 = désactivée). Défaut DEFAULT_PURGE_DAYS. Lecture tolérante. */
|
||||||
|
export function readPurgeDays(db: Db): number {
|
||||||
|
return readDaysSetting(db, PURGE_DAYS_KEY, DEFAULT_PURGE_DAYS);
|
||||||
|
}
|
||||||
|
|
||||||
|
function readDaysSetting(db: Db, key: string, fallback: number): number {
|
||||||
|
const raw = getSetting(db, key);
|
||||||
|
if (raw === null) return fallback;
|
||||||
|
const n = Number(raw);
|
||||||
|
return isValidDays(n) ? n : fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valide un nombre de jours : entier `0` (= désactivé) OU dans [MIN, MAX]. Retourne null si invalide
|
||||||
|
* (⇒ 400). Le même validateur sert pour la rétention et la purge (mêmes bornes, même sémantique de 0).
|
||||||
|
*/
|
||||||
|
export function normalizeRetentionDays(raw: unknown): number | null {
|
||||||
|
return typeof raw === 'number' && isValidDays(raw) ? raw : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Alias sémantique pour la purge (mêmes règles). */
|
||||||
|
export const normalizePurgeDays = normalizeRetentionDays;
|
||||||
|
|
||||||
|
function isValidDays(n: number): boolean {
|
||||||
|
if (!Number.isInteger(n)) return false;
|
||||||
|
return n === 0 || (n >= MIN_RETENTION_DAYS && n <= MAX_RETENTION_DAYS);
|
||||||
|
}
|
||||||
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
// Reconstruction d'écran via @xterm/headless : terminal headless PERSISTANT par session, alimenté
|
// Reconstruction d'écran via @xterm/headless : terminal headless PERSISTANT par session, alimenté
|
||||||
// incrémentalement par le flux PTY. Remplace le strip ANSI naïf (qui « mange les espaces » et casse
|
// incrémentalement par le flux PTY. Remplace le strip ANSI naïf (qui « mange les espaces » et casse
|
||||||
// la détection des dialogues — verdict S1/S3). Aucune dépendance DOM (usage Node).
|
// la détection des dialogues, verdict S1/S3). Aucune dépendance DOM (usage Node).
|
||||||
import { createRequire } from 'node:module';
|
import { createRequire } from 'node:module';
|
||||||
import type { Terminal as XtermTerminal } from '@xterm/headless';
|
import type { Terminal as XtermTerminal } from '@xterm/headless';
|
||||||
|
|
||||||
|
|||||||
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'));
|
||||||
|
}
|
||||||
75
packages/server/src/core/session-archive.ts
Normal file
75
packages/server/src/core/session-archive.ts
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
// Archivage automatique des sessions terminées (P10). Scheduler calqué sur DiscoveryService :
|
||||||
|
// start()/stop() + setInterval().unref(). Soft-archive uniquement (jamais de DELETE dans cette
|
||||||
|
// itération ; la purge définitive est conçue mais désactivée par défaut, cf. retention-settings).
|
||||||
|
// Démarré dans runDaemon (jamais dans buildApp → ne tourne pas pendant les tests unitaires).
|
||||||
|
import { EventEmitter } from 'node:events';
|
||||||
|
import { archiveExpiredSessions, type Db } from '../db/index.js';
|
||||||
|
import { recordAudit } from './audit-log.js';
|
||||||
|
import { readRetentionDays } from './retention-settings.js';
|
||||||
|
|
||||||
|
/** Balayage toutes les 6 h : la rétention se compte en jours, pas besoin de plus fréquent. */
|
||||||
|
const DEFAULT_SWEEP_INTERVAL_MS = 6 * 60 * 60 * 1000;
|
||||||
|
const MS_PER_DAY = 24 * 60 * 60 * 1000;
|
||||||
|
|
||||||
|
export interface SessionArchiveEvents {
|
||||||
|
/** une session vient d'être archivée (relayée en `session_archived` par la gateway). */
|
||||||
|
session_archived: [{ id: string; archivedAt: string }];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SessionArchiveOptions {
|
||||||
|
db: Db;
|
||||||
|
intervalMs?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SessionArchiveService extends EventEmitter<SessionArchiveEvents> {
|
||||||
|
private readonly db: Db;
|
||||||
|
private readonly intervalMs: number;
|
||||||
|
private timer: NodeJS.Timeout | null = null;
|
||||||
|
|
||||||
|
constructor(opts: SessionArchiveOptions) {
|
||||||
|
super();
|
||||||
|
this.db = opts.db;
|
||||||
|
this.intervalMs = opts.intervalMs ?? DEFAULT_SWEEP_INTERVAL_MS;
|
||||||
|
}
|
||||||
|
|
||||||
|
start(): void {
|
||||||
|
if (this.timer) return;
|
||||||
|
this.sweep(); // passage immédiat au boot (synchrone, bon marché : un seul UPDATE borné)
|
||||||
|
this.timer = setInterval(() => this.sweep(), this.intervalMs);
|
||||||
|
this.timer.unref(); // ne maintient pas le process en vie
|
||||||
|
}
|
||||||
|
|
||||||
|
stop(): void {
|
||||||
|
if (this.timer) {
|
||||||
|
clearInterval(this.timer);
|
||||||
|
this.timer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Archive les sessions terminées plus anciennes que la rétention configurée. Retourne le nombre
|
||||||
|
* archivé. Tolérant : ne lève jamais (une erreur ne doit pas tuer le scheduler). `0 jour` = OFF.
|
||||||
|
*/
|
||||||
|
sweep(): number {
|
||||||
|
try {
|
||||||
|
const days = readRetentionDays(this.db);
|
||||||
|
if (days <= 0) return 0; // rétention désactivée
|
||||||
|
const now = new Date();
|
||||||
|
const archivedAt = now.toISOString();
|
||||||
|
const cutoffIso = new Date(now.getTime() - days * MS_PER_DAY).toISOString();
|
||||||
|
const ids = archiveExpiredSessions(this.db, archivedAt, cutoffIso);
|
||||||
|
for (const id of ids) {
|
||||||
|
this.emit('session_archived', { id, archivedAt });
|
||||||
|
recordAudit(this.db, { actor: 'system', action: 'session.autoArchive', resourceId: id });
|
||||||
|
}
|
||||||
|
return ids.length;
|
||||||
|
} catch {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Diffuse l'archivage d'une session (déjà archivée + auditée par l'appelant, ex. route manuelle). */
|
||||||
|
emitArchived(id: string, archivedAt: string): void {
|
||||||
|
this.emit('session_archived', { id, archivedAt });
|
||||||
|
}
|
||||||
|
}
|
||||||
11
packages/server/src/core/settings-bus.ts
Normal file
11
packages/server/src/core/settings-bus.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
// Bus d'événements des réglages (P11) : la route PATCH /settings émet le snapshot non sensible
|
||||||
|
// après une mise à jour réussie ; la gateway WS le relaie aux abonnés du topic 'settings'. Découple
|
||||||
|
// les routes de la gateway (pas de dépendance directe), comme les EventEmitter des managers.
|
||||||
|
import { EventEmitter } from 'node:events';
|
||||||
|
import type { SettingsBroadcast } from '@arboretum/shared';
|
||||||
|
|
||||||
|
export interface SettingsBusEvents {
|
||||||
|
settings_update: [SettingsBroadcast];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SettingsBus extends EventEmitter<SettingsBusEvents> {}
|
||||||
@@ -4,37 +4,63 @@
|
|||||||
import { EventEmitter } from 'node:events';
|
import { EventEmitter } from 'node:events';
|
||||||
import { execFile } from 'node:child_process';
|
import { execFile } from 'node:child_process';
|
||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
import { basename, dirname, join, resolve } from 'node:path';
|
import { basename, dirname, join, resolve, sep } from 'node:path';
|
||||||
import { existsSync } from 'node:fs';
|
import { existsSync, realpathSync } 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,
|
||||||
|
amendCommit,
|
||||||
|
cleanFiles,
|
||||||
|
commitAll,
|
||||||
|
commitStaged,
|
||||||
defaultBranch,
|
defaultBranch,
|
||||||
|
fetchRemote,
|
||||||
|
fileDiff,
|
||||||
isDirtyWorktreeError,
|
isDirtyWorktreeError,
|
||||||
isRepo,
|
isRepo,
|
||||||
isSafeAbsolutePath,
|
isSafeAbsolutePath,
|
||||||
|
isSafeRelativePath,
|
||||||
|
isUnpushed,
|
||||||
isValidBranchName,
|
isValidBranchName,
|
||||||
|
listBranches,
|
||||||
|
listChanges,
|
||||||
listWorktrees,
|
listWorktrees,
|
||||||
pruneWorktrees,
|
pruneWorktrees,
|
||||||
|
pull,
|
||||||
|
push,
|
||||||
removeWorktree,
|
removeWorktree,
|
||||||
|
restoreFiles,
|
||||||
|
stageFiles,
|
||||||
|
switchBranch,
|
||||||
|
unstageFiles,
|
||||||
worktreeStatus,
|
worktreeStatus,
|
||||||
type ParsedWorktree,
|
type ParsedWorktree,
|
||||||
} from './git.js';
|
} from './git.js';
|
||||||
|
import type { FsWatcherService } from './fs-watcher.js';
|
||||||
|
import type { FileChange, FileDiffResponse } from '@arboretum/shared';
|
||||||
|
|
||||||
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 +70,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 {
|
||||||
@@ -51,6 +78,9 @@ export interface WorktreeManagerEvents {
|
|||||||
repo_removed: [string];
|
repo_removed: [string];
|
||||||
worktree_update: [{ repoId: string; worktree: WorktreeSummary }];
|
worktree_update: [{ repoId: string; worktree: WorktreeSummary }];
|
||||||
worktree_removed: [{ repoId: string; path: string }];
|
worktree_removed: [{ repoId: string; path: string }];
|
||||||
|
/** P7 : le détail (liste des changements/diff) d'un worktree regardé a changé ; relayé en push
|
||||||
|
* ciblé `worktree_changes` aux seules connexions ayant `watch`é cette clé. */
|
||||||
|
worktree_changes: [{ repoId: string; path: string }];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Erreur portant un statusCode + code pour mapping HTTP direct par les routes. */
|
/** Erreur portant un statusCode + code pour mapping HTTP direct par les routes. */
|
||||||
@@ -96,13 +126,25 @@ 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,
|
||||||
private readonly ptyManager: PtyManager,
|
private readonly ptyManager: PtyManager,
|
||||||
private readonly discovery: DiscoveryService,
|
private readonly discovery: DiscoveryService,
|
||||||
|
private readonly fsWatcher?: FsWatcherService,
|
||||||
) {
|
) {
|
||||||
super();
|
super();
|
||||||
|
// P7 : un changement FS sur un worktree regardé invalide le cache, rediffuse le status frais
|
||||||
|
// (worktree_update : compteurs légers pour tout le dashboard) et signale aux clients qui le
|
||||||
|
// regardent de re-fetcher le détail (worktree_changes ciblé). On résout repoId → row à la volée.
|
||||||
|
this.fsWatcher?.on('worktree_fs_change', ({ repoId, path }) => {
|
||||||
|
this.factsCache.delete(repoId);
|
||||||
|
const row = this.getRepoRow(repoId);
|
||||||
|
if (row) void this.emitWorktree(row, path).catch(() => {});
|
||||||
|
this.emit('worktree_changes', { repoId, path });
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- repos ----
|
// ---- repos ----
|
||||||
@@ -121,6 +163,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,43 +186,132 @@ 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,
|
||||||
};
|
};
|
||||||
this.db
|
try {
|
||||||
.prepare('INSERT INTO repos (id, path, label, default_branch, post_create_hooks, pre_trust, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)')
|
this.db
|
||||||
.run(row.id, row.path, row.label, row.default_branch, row.post_create_hooks, row.pre_trust, row.created_at);
|
.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, 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);
|
||||||
|
this.armRepoWatcher(row); // P11 : temps réel du checkout principal dès l'enregistrement
|
||||||
return summary;
|
return summary;
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateRepo(id: string, patch: { label?: string; postCreateHooks?: PostCreateHook[]; preTrust?: boolean }): Promise<RepoSummary> {
|
/**
|
||||||
|
* P11 : arme un watcher PERMANENT sur le checkout principal de chaque repo visible : un
|
||||||
|
* `git checkout`/`switch` en CLI sur le principal est ainsi rediffusé en temps réel sans qu'un
|
||||||
|
* client ne l'ait « regardé ». Appelé depuis runDaemon (jamais buildApp → pas d'effet en tests purs).
|
||||||
|
*/
|
||||||
|
armMainCheckoutWatchers(): void {
|
||||||
|
const rows = this.db.prepare('SELECT id, path FROM repos WHERE hidden = 0').all() as Array<{ id: string; path: string }>;
|
||||||
|
for (const r of rows) this.armRepoWatcher(r);
|
||||||
|
}
|
||||||
|
|
||||||
|
private armRepoWatcher(row: { id: string; path: string }): void {
|
||||||
|
this.fsWatcher?.pinRepo(row.id, resolve(row.path));
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
// P11 : masqué → on libère le watcher permanent du principal ; ré-affiché → on le réarme.
|
||||||
|
if (patch.hidden !== undefined) {
|
||||||
|
if (row.hidden === 1) this.fsWatcher?.unpinRepo(id, resolve(row.path));
|
||||||
|
else this.armRepoWatcher(row);
|
||||||
|
}
|
||||||
return summary;
|
return summary;
|
||||||
}
|
}
|
||||||
|
|
||||||
removeRepo(id: string): boolean {
|
removeRepo(id: string): boolean {
|
||||||
|
const row = this.getRepoRow(id);
|
||||||
const res = this.db.prepare('DELETE FROM repos WHERE id = ?').run(id);
|
const res = this.db.prepare('DELETE FROM repos WHERE id = ?').run(id);
|
||||||
if (res.changes === 0) return false;
|
if (res.changes === 0) return false;
|
||||||
|
if (row) this.fsWatcher?.unpinRepo(id, resolve(row.path)); // P11 : libère le watcher permanent
|
||||||
this.factsCache.delete(id);
|
this.factsCache.delete(id);
|
||||||
this.emit('repo_removed', id);
|
this.emit('repo_removed', id);
|
||||||
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
|
||||||
|
this.armRepoWatcher(row); // P11 : temps réel du checkout principal du repo découvert
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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 +346,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 +385,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 +395,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 +416,293 @@ 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Commit dans le worktree visé. `mode='all'` (défaut, rétrocompat) = `git add -A` + commit ;
|
||||||
|
* `mode='staged'` = commit de l'index uniquement (staging sélectif préalable) ; `amend` réécrit
|
||||||
|
* le dernier commit (refusé s'il est déjà poussé). Le checkout principal est un worktree valide ici.
|
||||||
|
*/
|
||||||
|
async commitWorktree(
|
||||||
|
repoId: string,
|
||||||
|
path: string,
|
||||||
|
opts: { message: string; mode?: 'all' | 'staged'; amend?: boolean },
|
||||||
|
): 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');
|
||||||
|
const mode = opts.mode ?? 'all';
|
||||||
|
return this.withLock(repoId, async () => {
|
||||||
|
if (opts.amend && !(await isUnpushed(w.path))) {
|
||||||
|
throw httpError(409, 'ALREADY_PUSHED', 'Last commit is already pushed: amend would rewrite shared history');
|
||||||
|
}
|
||||||
|
const st = await worktreeStatus(w.path);
|
||||||
|
// Garde-fou « rien à committer » (sauf amend, qui peut ne changer que le message).
|
||||||
|
if (!opts.amend) {
|
||||||
|
if (mode === 'all' && st.dirtyCount === 0) {
|
||||||
|
throw httpError(409, 'NOTHING_TO_COMMIT', 'Nothing to commit: working tree is clean');
|
||||||
|
}
|
||||||
|
if (mode === 'staged' && (st.stagedCount ?? 0) === 0) {
|
||||||
|
throw httpError(409, 'NOTHING_STAGED', 'Nothing staged: stage files first');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (mode === 'all' && !opts.amend) await commitAll(w.path, opts.message);
|
||||||
|
else if (opts.amend) await amendCommit(w.path, opts.message);
|
||||||
|
else await commitStaged(w.path, opts.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;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- P7 : changes / diff / staging / fetch-pull / contenu fichier / watch ----
|
||||||
|
|
||||||
|
/** Résout et valide un worktree enregistré ; lève 404 si le repo/worktree n'existe pas. */
|
||||||
|
private async requireWorktree(repoId: string, path: string): Promise<{ row: RepoRow; w: ParsedWorktree }> {
|
||||||
|
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 { row, w };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Liste des fichiers modifiés d'un worktree (lecture, hors lock). */
|
||||||
|
async getWorktreeChanges(repoId: string, path: string): Promise<{ changes: FileChange[]; truncated: boolean }> {
|
||||||
|
const { w } = await this.requireWorktree(repoId, path);
|
||||||
|
return listChanges(w.path);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Diff unifié d'un fichier (détecte untracked → `git diff --no-index`). Lecture, hors lock. */
|
||||||
|
async getFileDiff(repoId: string, path: string, file: string, staged: boolean): Promise<FileDiffResponse> {
|
||||||
|
const { w } = await this.requireWorktree(repoId, path);
|
||||||
|
if (!isSafeRelativePath(file)) throw httpError(400, 'BAD_PATH', 'Invalid file path');
|
||||||
|
const { changes } = await listChanges(w.path);
|
||||||
|
const rec = changes.find((c) => c.path === file);
|
||||||
|
const untracked = !staged && (rec?.untracked ?? false);
|
||||||
|
const d = await fileDiff(w.path, file, { staged, untracked });
|
||||||
|
return { path: w.path, file, staged, binary: d.binary, tooLarge: d.tooLarge, diff: d.diff };
|
||||||
|
}
|
||||||
|
|
||||||
|
private validateFiles(files: string[]): void {
|
||||||
|
if (!Array.isArray(files) || files.length === 0) throw httpError(400, 'BAD_REQUEST', 'files (non-empty array) is required');
|
||||||
|
for (const f of files) {
|
||||||
|
if (typeof f !== 'string' || !isSafeRelativePath(f)) throw httpError(400, 'BAD_PATH', `Invalid file path: ${String(f)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Indexe des fichiers, puis rediffuse le statut. */
|
||||||
|
async stage(repoId: string, path: string, files: string[]): Promise<WorktreeSummary> {
|
||||||
|
const { row, w } = await this.requireWorktree(repoId, path);
|
||||||
|
this.validateFiles(files);
|
||||||
|
return this.withLock(repoId, async () => {
|
||||||
|
await stageFiles(w.path, files).catch((err) => { throw httpError(400, 'STAGE_FAILED', (err as Error).message); });
|
||||||
|
this.factsCache.delete(repoId);
|
||||||
|
this.emit('worktree_changes', { repoId, path: w.path });
|
||||||
|
return (await this.emitWorktree(row, w.path)) as WorktreeSummary;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Désindexe des fichiers, puis rediffuse le statut. */
|
||||||
|
async unstage(repoId: string, path: string, files: string[]): Promise<WorktreeSummary> {
|
||||||
|
const { row, w } = await this.requireWorktree(repoId, path);
|
||||||
|
this.validateFiles(files);
|
||||||
|
return this.withLock(repoId, async () => {
|
||||||
|
await unstageFiles(w.path, files).catch((err) => { throw httpError(400, 'UNSTAGE_FAILED', (err as Error).message); });
|
||||||
|
this.factsCache.delete(repoId);
|
||||||
|
this.emit('worktree_changes', { repoId, path: w.path });
|
||||||
|
return (await this.emitWorktree(row, w.path)) as WorktreeSummary;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Annule les changements locaux. Les fichiers SUIVIS sont restaurés (`git restore`) ; les fichiers
|
||||||
|
* NON SUIVIS ne sont supprimés (`git clean`) QUE si `includeUntracked` (destructif, opt-in).
|
||||||
|
*/
|
||||||
|
async discard(repoId: string, path: string, files: string[], includeUntracked: boolean): Promise<WorktreeSummary> {
|
||||||
|
const { row, w } = await this.requireWorktree(repoId, path);
|
||||||
|
this.validateFiles(files);
|
||||||
|
return this.withLock(repoId, async () => {
|
||||||
|
const { changes } = await listChanges(w.path);
|
||||||
|
const set = new Set(files);
|
||||||
|
const untracked = changes.filter((c) => set.has(c.path) && c.untracked).map((c) => c.path);
|
||||||
|
const tracked = files.filter((f) => !untracked.includes(f));
|
||||||
|
try {
|
||||||
|
await restoreFiles(w.path, tracked);
|
||||||
|
if (includeUntracked && untracked.length > 0) await cleanFiles(w.path, untracked);
|
||||||
|
} catch (err) {
|
||||||
|
throw httpError(400, 'DISCARD_FAILED', (err as Error).message);
|
||||||
|
}
|
||||||
|
this.factsCache.delete(repoId);
|
||||||
|
this.emit('worktree_changes', { repoId, path: w.path });
|
||||||
|
return (await this.emitWorktree(row, w.path)) as WorktreeSummary;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `git fetch --all --prune` puis rediffuse le statut (ahead/behind à jour). */
|
||||||
|
async fetch(repoId: string, path: string): Promise<WorktreeSummary> {
|
||||||
|
const { row, w } = await this.requireWorktree(repoId, path);
|
||||||
|
return this.withLock(repoId, async () => {
|
||||||
|
await fetchRemote(w.path).catch((err) => { throw httpError(400, 'FETCH_FAILED', (err as Error).message); });
|
||||||
|
this.factsCache.delete(repoId);
|
||||||
|
return (await this.emitWorktree(row, w.path)) as WorktreeSummary;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `git pull` (ff-only par défaut). */
|
||||||
|
async pull(repoId: string, path: string, mode: 'ff-only' | 'rebase' = 'ff-only'): Promise<WorktreeSummary> {
|
||||||
|
const { row, w } = await this.requireWorktree(repoId, path);
|
||||||
|
return this.withLock(repoId, async () => {
|
||||||
|
await pull(w.path, mode).catch((err) => { throw httpError(409, 'PULL_FAILED', (err as Error).message); });
|
||||||
|
this.factsCache.delete(repoId);
|
||||||
|
this.emit('worktree_changes', { repoId, path: w.path });
|
||||||
|
return (await this.emitWorktree(row, w.path)) as WorktreeSummary;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valide qu'un chemin relatif désigne bien un fichier DANS un worktree enregistré et renvoie son
|
||||||
|
* chemin absolu résolu. Défense en profondeur (anti `..`, anti symlink sortant), même si un
|
||||||
|
* terminal web est déjà du RCE par conception. Utilisé par l'API fichiers (lecture/écriture Monaco).
|
||||||
|
*/
|
||||||
|
async assertPathInWorktree(repoId: string, worktreeAbsPath: string, relPath: string): Promise<string> {
|
||||||
|
const row = this.getRepoRow(repoId);
|
||||||
|
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
|
||||||
|
if (!isSafeAbsolutePath(worktreeAbsPath)) throw httpError(400, 'BAD_PATH', 'Worktree path must be absolute and normalized');
|
||||||
|
const w = await this.findWorktree(row, worktreeAbsPath);
|
||||||
|
if (!w) throw httpError(404, 'NOT_FOUND', 'No such worktree under this repo');
|
||||||
|
if (!isSafeRelativePath(relPath)) throw httpError(400, 'BAD_PATH', 'Invalid file path');
|
||||||
|
const base = resolve(w.path);
|
||||||
|
const abs = resolve(join(base, relPath));
|
||||||
|
if (abs !== base && !abs.startsWith(base + sep)) throw httpError(403, 'PATH_OUTSIDE_WORKTREE', 'Path escapes the worktree');
|
||||||
|
// Anti symlink-escape : pour un fichier existant, le realpath doit rester sous le worktree.
|
||||||
|
if (existsSync(abs)) {
|
||||||
|
let real: string;
|
||||||
|
try {
|
||||||
|
real = realpathSync(abs);
|
||||||
|
} catch {
|
||||||
|
throw httpError(400, 'BAD_PATH', 'Cannot resolve path');
|
||||||
|
}
|
||||||
|
const realBase = realpathSync(base);
|
||||||
|
if (real !== realBase && !real.startsWith(realBase + sep)) throw httpError(403, 'PATH_OUTSIDE_WORKTREE', 'Path escapes the worktree (symlink)');
|
||||||
|
}
|
||||||
|
return abs;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Arme le watcher FS sur un worktree (validé) pour le push temps réel du détail. */
|
||||||
|
async watch(repoId: string, path: string): Promise<void> {
|
||||||
|
if (!this.fsWatcher) return;
|
||||||
|
await this.requireWorktree(repoId, path);
|
||||||
|
this.fsWatcher.watch(repoId, resolve(path));
|
||||||
|
}
|
||||||
|
|
||||||
|
unwatch(repoId: string, path: string): void {
|
||||||
|
this.fsWatcher?.unwatch(repoId, resolve(path));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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,15 +730,15 @@ 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 () => {
|
||||||
try {
|
try {
|
||||||
await removeWorktree(row.path, w.path, force);
|
await removeWorktree(row.path, w.path, force);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (!force && isDirtyWorktreeError(err)) {
|
if (!force && isDirtyWorktreeError(err)) {
|
||||||
throw httpError(409, 'WORKTREE_DIRTY', 'Worktree has uncommitted changes — pass force to delete anyway');
|
throw httpError(409, 'WORKTREE_DIRTY', 'Worktree has uncommitted changes: pass force to delete anyway');
|
||||||
}
|
}
|
||||||
throw httpError(500, 'WORKTREE_REMOVE_FAILED', (err as Error).message);
|
throw httpError(500, 'WORKTREE_REMOVE_FAILED', (err as Error).message);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 }> = [
|
||||||
{
|
{
|
||||||
@@ -28,7 +29,7 @@ const MIGRATIONS: Array<{ id: number; sql: string }> = [
|
|||||||
`,
|
`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
// P2 — découverte & reprise : corrélation avec les sessions Claude sur disque.
|
// P2 : découverte & reprise : corrélation avec les sessions Claude sur disque.
|
||||||
id: 2,
|
id: 2,
|
||||||
sql: `
|
sql: `
|
||||||
ALTER TABLE sessions ADD COLUMN claude_session_id TEXT;
|
ALTER TABLE sessions ADD COLUMN claude_session_id TEXT;
|
||||||
@@ -37,7 +38,7 @@ const MIGRATIONS: Array<{ id: number; sql: string }> = [
|
|||||||
`,
|
`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
// P3 — repos enregistrés. Les worktrees sont dérivés à la volée de git (non persistés).
|
// P3 : repos enregistrés. Les worktrees sont dérivés à la volée de git (non persistés).
|
||||||
id: 3,
|
id: 3,
|
||||||
sql: `
|
sql: `
|
||||||
CREATE TABLE repos (
|
CREATE TABLE repos (
|
||||||
@@ -52,7 +53,7 @@ const MIGRATIONS: Array<{ id: number; sql: string }> = [
|
|||||||
`,
|
`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
// P4 — abonnements Web Push. Liés au token d'auth (token_id) ; clés VAPID en settings.
|
// P4 : abonnements Web Push. Liés au token d'auth (token_id) ; clés VAPID en settings.
|
||||||
id: 4,
|
id: 4,
|
||||||
sql: `
|
sql: `
|
||||||
CREATE TABLE push_subscriptions (
|
CREATE TABLE push_subscriptions (
|
||||||
@@ -69,7 +70,7 @@ const MIGRATIONS: Array<{ id: number; sql: string }> = [
|
|||||||
`,
|
`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
// P5 — groupes de travail. Un groupe = collection de repos (many-to-many).
|
// P5 : groupes de travail. Un groupe = collection de repos (many-to-many).
|
||||||
// Worktrees/sessions NON persistés ici : servis par WorktreeManager/PtyManager
|
// 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).
|
// et filtrés côté client par repoId. CASCADE s'appuie sur PRAGMA foreign_keys = ON (cf. openDb).
|
||||||
id: 5,
|
id: 5,
|
||||||
@@ -93,6 +94,103 @@ const MIGRATIONS: Array<{ id: number; sql: string }> = [
|
|||||||
CREATE INDEX idx_group_repos_repo ON group_repos(repo_id);
|
CREATE INDEX idx_group_repos_repo ON group_repos(repo_id);
|
||||||
`,
|
`,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
// Découverte auto : un repo masqué reste en DB (exclu du dashboard) pour qu'un
|
||||||
|
// re-scan ne le ressuscite pas. hidden=1 = masqué.
|
||||||
|
id: 6,
|
||||||
|
sql: `ALTER TABLE repos ADD COLUMN hidden INTEGER NOT NULL DEFAULT 0;`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// Journal d'audit (conformité entreprise : GDPR/SOX/ISO 27001). Trace les mutations
|
||||||
|
// sensibles (tokens, réglages, secrets, abonnements push, groupes). Ne contient JAMAIS
|
||||||
|
// de secret en clair, `details` est un JSON de métadonnées non sensibles.
|
||||||
|
id: 7,
|
||||||
|
sql: `
|
||||||
|
CREATE TABLE audit_logs (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
ts TEXT NOT NULL,
|
||||||
|
actor TEXT NOT NULL,
|
||||||
|
action TEXT NOT NULL,
|
||||||
|
resource_id TEXT,
|
||||||
|
details TEXT,
|
||||||
|
result TEXT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_audit_ts ON audit_logs(ts);
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// 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
|
||||||
|
);
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// P10 : archivage automatique des sessions terminées (rétention configurable, défaut 30 j).
|
||||||
|
// `archived_at` NULL = active. Soft-archive : JAMAIS de DELETE (resume/fork restent intacts).
|
||||||
|
// Sémantique distincte de hidden_sessions (#9) : `hidden` est manuel et indexé par
|
||||||
|
// claude_session_id ; `archived` est automatique par ancienneté, indexé par `id`, et ne
|
||||||
|
// s'applique qu'aux sessions managées en DB. Les deux filtres sont indépendants et cumulables.
|
||||||
|
id: 10,
|
||||||
|
sql: `
|
||||||
|
ALTER TABLE sessions ADD COLUMN archived_at TEXT;
|
||||||
|
CREATE INDEX idx_sessions_archived_at ON sessions(archived_at);
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// P12 : connexions aux services git distants (Gitea/GitLab/GitHub). Les SECRETS (PAT, app
|
||||||
|
// password, tokens OAuth) sont chiffrés par SecretBox AVANT insertion (colonnes *_encrypted) :
|
||||||
|
// la base ne contient jamais de secret en clair. `ssh_key_path`/`oauth_*` sont posés dès
|
||||||
|
// maintenant (schéma stable) mais exploités en P12b/P12c. `test_result` = dernier diagnostic.
|
||||||
|
id: 11,
|
||||||
|
sql: `
|
||||||
|
CREATE TABLE git_credentials (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
label TEXT NOT NULL,
|
||||||
|
service TEXT NOT NULL CHECK (service IN ('gitea','gitlab','github')),
|
||||||
|
base_url TEXT,
|
||||||
|
auth_type TEXT NOT NULL CHECK (auth_type IN ('pat','app_password','ssh_key','oauth')),
|
||||||
|
username TEXT,
|
||||||
|
secret_encrypted TEXT,
|
||||||
|
ssh_key_path TEXT,
|
||||||
|
oauth_access_encrypted TEXT,
|
||||||
|
oauth_refresh_encrypted TEXT,
|
||||||
|
oauth_expires_at TEXT,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
last_tested_at TEXT,
|
||||||
|
test_result TEXT
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_git_credentials_service ON git_credentials(service);
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// P12 : un repo enregistré peut provenir d'un clone : on retient sa source (remote_url),
|
||||||
|
// le service détecté et le credential utilisé. PAS de FK sur credential_id (cohérent avec
|
||||||
|
// sessions.group_id #8) : la suppression d'un credential nullifie ce champ côté manager.
|
||||||
|
id: 12,
|
||||||
|
sql: `
|
||||||
|
ALTER TABLE repos ADD COLUMN remote_url TEXT;
|
||||||
|
ALTER TABLE repos ADD COLUMN git_service TEXT;
|
||||||
|
ALTER TABLE repos ADD COLUMN credential_id TEXT;
|
||||||
|
`,
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
export type Db = DatabaseSync;
|
export type Db = DatabaseSync;
|
||||||
@@ -101,10 +199,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(
|
||||||
@@ -132,3 +247,68 @@ 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Archivage des sessions terminées (par id, soft-archive, P10) ----
|
||||||
|
|
||||||
|
/** Archive une session managée (idempotent : ne touche pas une session déjà archivée). */
|
||||||
|
export function archiveSession(db: Db, id: string, archivedAt: string): void {
|
||||||
|
db.prepare('UPDATE sessions SET archived_at = ? WHERE id = ? AND archived_at IS NULL').run(archivedAt, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Dés-archive une session (idempotent). La session reste reprenable/forkable (inchangé). */
|
||||||
|
export function unarchiveSession(db: Db, id: string): void {
|
||||||
|
db.prepare('UPDATE sessions SET archived_at = NULL WHERE id = ?').run(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** true si une session managée avec cet id existe en DB. */
|
||||||
|
export function sessionExists(db: Db, id: string): boolean {
|
||||||
|
return db.prepare('SELECT 1 FROM sessions WHERE id = ?').get(id) != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** true si la session existe en DB et est archivée. */
|
||||||
|
export function isSessionArchived(db: Db, id: string): boolean {
|
||||||
|
const row = db.prepare('SELECT archived_at FROM sessions WHERE id = ?').get(id) as { archived_at: string | null } | undefined;
|
||||||
|
return row != null && row.archived_at != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Archive en masse les sessions terminées plus anciennes que `cutoffIso` (comparaison lexicographique
|
||||||
|
* sur ended_at, format ISO UTC). Retourne les `id` archivés (pour émettre les events + auditer).
|
||||||
|
* SELECT puis UPDATE dans une transaction → la liste retournée correspond exactement aux lignes mutées.
|
||||||
|
* Les sessions vivantes (ended_at NULL) et déjà archivées sont exclues.
|
||||||
|
*/
|
||||||
|
export function archiveExpiredSessions(db: Db, archivedAt: string, cutoffIso: string): string[] {
|
||||||
|
db.exec('BEGIN');
|
||||||
|
try {
|
||||||
|
const rows = db
|
||||||
|
.prepare('SELECT id FROM sessions WHERE ended_at IS NOT NULL AND ended_at < ? AND archived_at IS NULL')
|
||||||
|
.all(cutoffIso) as Array<{ id: string }>;
|
||||||
|
const stmt = db.prepare('UPDATE sessions SET archived_at = ? WHERE id = ?');
|
||||||
|
for (const r of rows) stmt.run(archivedAt, r.id);
|
||||||
|
db.exec('COMMIT');
|
||||||
|
return rows.map((r) => r.id);
|
||||||
|
} catch (err) {
|
||||||
|
db.exec('ROLLBACK');
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,27 +1,46 @@
|
|||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
import { readFileSync } from 'node:fs';
|
import { readFileSync, writeSync } 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, type Config } from './config.js';
|
import { loadConfig, type Config } from './config.js';
|
||||||
import { openDb } from './db/index.js';
|
import { openDb, type Db } from './db/index.js';
|
||||||
import { buildApp } from './app.js';
|
import { buildApp } from './app.js';
|
||||||
|
import { readClaudeHome } from './core/claude-settings.js';
|
||||||
import { runInstall, runUninstall, runStatus, printUsage, printTokenBanner } from './cli/install.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 };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Applique l'override `claude_home` (réglage UI) sur la config runtime, sauf si --claude-home a été
|
||||||
|
* passé explicitement (le flag gagne). Lu une seule fois au démarrage → un changement via l'UI prend
|
||||||
|
* effet au redémarrage du daemon (comme l'intervalle de scan). Mute `config`.
|
||||||
|
*/
|
||||||
|
function applyClaudeHomeOverride(config: Config, db: Db): void {
|
||||||
|
if (config.claudeHomeFromFlag) return;
|
||||||
|
const override = readClaudeHome(db);
|
||||||
|
if (!override) return;
|
||||||
|
config.claudeHome = override;
|
||||||
|
config.claudeProjectsDir = join(override, 'projects');
|
||||||
|
config.claudeSessionsDir = join(override, 'sessions');
|
||||||
|
}
|
||||||
|
|
||||||
/** Démarre le daemon : écoute HTTP, scan des sessions, drain propre au SIGTERM/SIGINT. */
|
/** Démarre le daemon : écoute HTTP, scan des sessions, drain propre au SIGTERM/SIGINT. */
|
||||||
export async function runDaemon(config: Config): Promise<void> {
|
export async function runDaemon(config: Config): Promise<void> {
|
||||||
const db = openDb(config.dbPath);
|
const db = openDb(config.dbPath);
|
||||||
const { app, auth, manager, discovery } = buildApp(config, db, pkg.version);
|
applyClaudeHomeOverride(config, db); // override claude_home (réglage UI) avant de câbler les services
|
||||||
|
const { app, auth, manager, discovery, sessionArchive, repoDiscovery, worktrees, fsWatcher } = 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
|
||||||
|
sessionArchive.start(); // archivage auto des sessions terminées (rétention configurable)
|
||||||
|
worktrees.armMainCheckoutWatchers(); // P11 : temps réel du checkout principal de chaque repo
|
||||||
|
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é.
|
||||||
printTokenBanner(bootstrapToken, url);
|
printTokenBanner(bootstrapToken, url);
|
||||||
@@ -29,12 +48,29 @@ export async function runDaemon(config: Config): Promise<void> {
|
|||||||
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).');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Handshake pour un shell embarquant le daemon (app de bureau) : si ARBORETUM_EMIT_TOKEN_FD est
|
||||||
|
// fourni, on mint un token frais et on l'écrit en JSON sur ce descripteur (pipe stdio privé
|
||||||
|
// parent<->enfant). Additif : sans cette variable, comportement strictement inchangé. Le token ne
|
||||||
|
// transite jamais par le renderer et n'est pas affiché.
|
||||||
|
const emitFd = process.env.ARBORETUM_EMIT_TOKEN_FD;
|
||||||
|
if (emitFd) {
|
||||||
|
try {
|
||||||
|
const token = auth.createToken('desktop');
|
||||||
|
writeSync(Number(emitFd), `${JSON.stringify({ token, url })}\n`);
|
||||||
|
} catch (err) {
|
||||||
|
app.log.warn(`token handshake failed: ${err instanceof Error ? err.message : String(err)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let shuttingDown = false;
|
let shuttingDown = false;
|
||||||
const shutdown = (signal: string): void => {
|
const shutdown = (signal: string): void => {
|
||||||
if (shuttingDown) return;
|
if (shuttingDown) return;
|
||||||
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();
|
||||||
|
sessionArchive.stop();
|
||||||
|
repoDiscovery.stop();
|
||||||
|
void fsWatcher.closeAll(); // libère les descripteurs des watchers FS
|
||||||
manager.shutdown();
|
manager.shutdown();
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
void app.close().then(() => process.exit(0));
|
void app.close().then(() => process.exit(0));
|
||||||
|
|||||||
17
packages/server/src/routes/audit.ts
Normal file
17
packages/server/src/routes/audit.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
// Consultation du journal d'audit (onglet Réglages / outils de conformité). Lecture seule, sous
|
||||||
|
// l'auth globale. Pagination par curseur `before` (ts décroissant).
|
||||||
|
import type { FastifyInstance } from 'fastify';
|
||||||
|
import type { AuditLogsResponse } from '@arboretum/shared';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
import { listAudit } from '../core/audit-log.js';
|
||||||
|
|
||||||
|
export function registerAuditRoutes(app: FastifyInstance, db: Db): void {
|
||||||
|
app.get('/api/v1/audit-logs', async (req): Promise<AuditLogsResponse> => {
|
||||||
|
const q = req.query as { limit?: string; before?: string };
|
||||||
|
const limit = Math.min(Math.max(Math.trunc(Number(q.limit) || 50), 1), 200);
|
||||||
|
const entries = listAudit(db, { limit, before: q.before ?? null });
|
||||||
|
// s'il reste potentiellement des entrées (page pleine), expose le curseur suivant.
|
||||||
|
const nextBefore = entries.length === limit ? entries[entries.length - 1]!.ts : null;
|
||||||
|
return { entries, nextBefore };
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,11 +1,20 @@
|
|||||||
import type { FastifyInstance, FastifyRequest } from 'fastify';
|
import type { FastifyInstance, FastifyRequest } from 'fastify';
|
||||||
import type { LoginRequest, LoginResponse, MeResponse } from '@arboretum/shared';
|
import type {
|
||||||
|
CreateTokenRequest,
|
||||||
|
CreateTokenResponse,
|
||||||
|
LoginRequest,
|
||||||
|
LoginResponse,
|
||||||
|
MeResponse,
|
||||||
|
TokensListResponse,
|
||||||
|
} from '@arboretum/shared';
|
||||||
import type { AuthService, LoginRateLimiter } from '../auth/service.js';
|
import type { AuthService, LoginRateLimiter } from '../auth/service.js';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
import { recordAudit } from '../core/audit-log.js';
|
||||||
|
|
||||||
// Tailscale Serve / un reverse-proxy TLS posent x-forwarded-proto. On ne sert jamais
|
// Tailscale Serve / un reverse-proxy TLS posent x-forwarded-proto. On ne sert jamais
|
||||||
// en TLS direct : `secure` n'est posé que derrière un front HTTPS, jamais en localhost http
|
// en TLS direct : `secure` n'est posé que derrière un front HTTPS, jamais en localhost http
|
||||||
// (sinon le navigateur refuserait le cookie sur http://127.0.0.1 et le login local casserait).
|
// (sinon le navigateur refuserait le cookie sur http://127.0.0.1 et le login local casserait).
|
||||||
function isHttpsRequest(req: FastifyRequest): boolean {
|
export function isHttpsRequest(req: FastifyRequest): boolean {
|
||||||
const xfp = req.headers['x-forwarded-proto'];
|
const xfp = req.headers['x-forwarded-proto'];
|
||||||
const proto = (Array.isArray(xfp) ? xfp[0] : xfp)?.split(',')[0]?.trim();
|
const proto = (Array.isArray(xfp) ? xfp[0] : xfp)?.split(',')[0]?.trim();
|
||||||
return proto === 'https';
|
return proto === 'https';
|
||||||
@@ -16,6 +25,7 @@ export function registerAuthRoutes(
|
|||||||
auth: AuthService,
|
auth: AuthService,
|
||||||
limiter: LoginRateLimiter,
|
limiter: LoginRateLimiter,
|
||||||
serverVersion: string,
|
serverVersion: string,
|
||||||
|
db: Db,
|
||||||
): void {
|
): void {
|
||||||
app.post('/api/v1/auth/login', { config: { public: true } }, async (req, reply) => {
|
app.post('/api/v1/auth/login', { config: { public: true } }, async (req, reply) => {
|
||||||
const wait = limiter.check();
|
const wait = limiter.check();
|
||||||
@@ -26,9 +36,11 @@ export function registerAuthRoutes(
|
|||||||
const ctx = typeof body?.token === 'string' ? auth.verifyRawToken(body.token) : null;
|
const ctx = typeof body?.token === 'string' ? auth.verifyRawToken(body.token) : null;
|
||||||
if (!ctx) {
|
if (!ctx) {
|
||||||
limiter.recordFailure();
|
limiter.recordFailure();
|
||||||
|
recordAudit(db, { actor: 'anonymous', action: 'login.failure', result: 'denied' });
|
||||||
return reply.status(401).send({ error: { code: 'BAD_TOKEN', message: 'Invalid token' } });
|
return reply.status(401).send({ error: { code: 'BAD_TOKEN', message: 'Invalid token' } });
|
||||||
}
|
}
|
||||||
limiter.recordSuccess();
|
limiter.recordSuccess();
|
||||||
|
recordAudit(db, { actor: ctx.tokenId, action: 'login.success' });
|
||||||
void reply.setCookie(auth.cookieName, auth.issueCookie(ctx), {
|
void reply.setCookie(auth.cookieName, auth.issueCookie(ctx), {
|
||||||
path: '/',
|
path: '/',
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
@@ -41,7 +53,12 @@ export function registerAuthRoutes(
|
|||||||
});
|
});
|
||||||
|
|
||||||
app.get('/api/v1/auth/me', async (req, reply) => {
|
app.get('/api/v1/auth/me', async (req, reply) => {
|
||||||
const res: MeResponse = { ok: true, tokenLabel: req.authContext?.label ?? 'unknown', serverVersion };
|
const res: MeResponse = {
|
||||||
|
ok: true,
|
||||||
|
tokenId: req.authContext?.tokenId ?? '',
|
||||||
|
tokenLabel: req.authContext?.label ?? 'unknown',
|
||||||
|
serverVersion,
|
||||||
|
};
|
||||||
return reply.send(res);
|
return reply.send(res);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -50,4 +67,39 @@ export function registerAuthRoutes(
|
|||||||
void reply.clearCookie(auth.cookieName, { path: '/', secure: isHttpsRequest(req) });
|
void reply.clearCookie(auth.cookieName, { path: '/', secure: isHttpsRequest(req) });
|
||||||
return reply.send({ ok: true });
|
return reply.send({ ok: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ---- Gestion des tokens d'accès (onglet Réglages) ----
|
||||||
|
// Sous l'auth globale (preValidation). On ne renvoie jamais le hash ; la valeur en clair
|
||||||
|
// d'un nouveau token n'est exposée qu'une seule fois, à la création.
|
||||||
|
app.get('/api/v1/auth/tokens', async (req): Promise<TokensListResponse> => {
|
||||||
|
const current = req.authContext?.tokenId;
|
||||||
|
return { tokens: auth.listTokens().map((t) => ({ ...t, current: t.id === current })) };
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post('/api/v1/auth/tokens', async (req, reply) => {
|
||||||
|
const body = req.body as Partial<CreateTokenRequest> | null;
|
||||||
|
const label = typeof body?.label === 'string' ? body.label.trim() : '';
|
||||||
|
if (label.length < 1 || label.length > 64) {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'label must be 1-64 characters' } });
|
||||||
|
}
|
||||||
|
const { id, token } = auth.createTokenRecord(label);
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'token.create', resourceId: id, details: { label } });
|
||||||
|
return reply.status(201).send({ id, label, token } satisfies CreateTokenResponse);
|
||||||
|
});
|
||||||
|
|
||||||
|
app.delete('/api/v1/auth/tokens/:id', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const result = auth.revokeToken(id);
|
||||||
|
const actor = req.authContext?.tokenId ?? 'unknown';
|
||||||
|
if (result === 'not_found') {
|
||||||
|
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No active token with this id' } });
|
||||||
|
}
|
||||||
|
if (result === 'last') {
|
||||||
|
recordAudit(db, { actor, action: 'token.revoke', resourceId: id, result: 'denied', details: { reason: 'last_active_token' } });
|
||||||
|
return reply.status(409).send({ error: { code: 'LAST_TOKEN', message: 'Cannot revoke the last active token' } });
|
||||||
|
}
|
||||||
|
recordAudit(db, { actor, action: 'token.revoke', resourceId: id });
|
||||||
|
// 200 + corps JSON (pas 204) : le mini-client REST du front parse toujours la réponse.
|
||||||
|
return reply.send({ ok: true });
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
54
packages/server/src/routes/data.ts
Normal file
54
packages/server/src/routes/data.ts
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
// RGPD (droits d'accès & d'effacement) : export et suppression des données rattachées au token
|
||||||
|
// authentifié. Modèle mono-utilisateur → le détenteur du token EST le sujet des données. Sous l'auth
|
||||||
|
// globale. La suppression se fait en deux temps (code de confirmation) pour éviter les clics accidentels.
|
||||||
|
import { createHash } from 'node:crypto';
|
||||||
|
import type { FastifyInstance } from 'fastify';
|
||||||
|
import type { DataExportResponse, DeleteMyDataRequest, DeleteMyDataResponse } from '@arboretum/shared';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
import type { AuthService } from '../auth/service.js';
|
||||||
|
import { readScanIntervalMin, readScanRoots } from '../core/scan-settings.js';
|
||||||
|
import { recordAudit } from '../core/audit-log.js';
|
||||||
|
|
||||||
|
export function registerDataRoutes(app: FastifyInstance, db: Db, auth: AuthService): void {
|
||||||
|
app.get('/api/v1/data/export', async (req): Promise<DataExportResponse> => {
|
||||||
|
const current = req.authContext!.tokenId;
|
||||||
|
const tokens = auth.listTokens().map((t) => ({ ...t, current: t.id === current }));
|
||||||
|
const pushSubscriptions = db
|
||||||
|
.prepare(
|
||||||
|
'SELECT endpoint, user_agent AS userAgent, created_at AS createdAt, last_ok_at AS lastOkAt FROM push_subscriptions WHERE token_id = ?',
|
||||||
|
)
|
||||||
|
.all(current) as DataExportResponse['pushSubscriptions'];
|
||||||
|
const sessions = db
|
||||||
|
.prepare(
|
||||||
|
'SELECT id, cwd, command, title, created_at AS createdAt, ended_at AS endedAt, exit_code AS exitCode FROM sessions ORDER BY created_at',
|
||||||
|
)
|
||||||
|
.all() as DataExportResponse['sessions'];
|
||||||
|
return {
|
||||||
|
exportedAt: new Date().toISOString(),
|
||||||
|
tokens,
|
||||||
|
pushSubscriptions,
|
||||||
|
sessions,
|
||||||
|
settings: { scanRoots: readScanRoots(db), scanIntervalMin: readScanIntervalMin(db) },
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post('/api/v1/data/delete-my-data', async (req, reply) => {
|
||||||
|
const current = req.authContext!.tokenId;
|
||||||
|
// code déterministe lié au token (sans état serveur) : renvoyé au 1er appel, exigé au 2nd.
|
||||||
|
const code = createHash('sha256').update(`delete:${current}`).digest('hex').slice(0, 12);
|
||||||
|
const body = (req.body as DeleteMyDataRequest | null) ?? {};
|
||||||
|
const subsCount = (db.prepare('SELECT COUNT(*) AS n FROM push_subscriptions WHERE token_id = ?').get(current) as { n: number }).n;
|
||||||
|
|
||||||
|
if (body.confirm !== code) {
|
||||||
|
const res: DeleteMyDataResponse = { status: 'pending', confirm: code, summary: { pushSubscriptions: subsCount, tokenRevoked: false } };
|
||||||
|
return reply.send(res);
|
||||||
|
}
|
||||||
|
|
||||||
|
db.prepare('DELETE FROM push_subscriptions WHERE token_id = ?').run(current);
|
||||||
|
// révoque le token courant (sauf si c'est le dernier actif → garde anti lock-out conservée).
|
||||||
|
const revoked = auth.revokeToken(current) === 'ok';
|
||||||
|
recordAudit(db, { actor: current, action: 'data.delete', details: { pushSubscriptions: subsCount, tokenRevoked: revoked } });
|
||||||
|
const res: DeleteMyDataResponse = { status: 'done', summary: { pushSubscriptions: subsCount, tokenRevoked: revoked } };
|
||||||
|
return reply.send(res);
|
||||||
|
});
|
||||||
|
}
|
||||||
96
packages/server/src/routes/files.ts
Normal file
96
packages/server/src/routes/files.ts
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
// API fichiers (P7) pour l'éditeur Monaco : lecture/écriture du contenu d'un fichier, strictement
|
||||||
|
// bornées à un worktree ENREGISTRÉ (WorktreeManager.assertPathInWorktree : anti `..`, anti symlink
|
||||||
|
// sortant). Authentifiée par le hook preValidation global. Un terminal web est déjà du RCE par
|
||||||
|
// conception, mais on borne quand même (défense en profondeur + moindre étonnement).
|
||||||
|
import type { FastifyInstance } from 'fastify';
|
||||||
|
import { readFile, writeFile, stat, mkdir } from 'node:fs/promises';
|
||||||
|
import { dirname, extname } from 'node:path';
|
||||||
|
import type { FileContentResponse, WriteFileRequest, WriteFileResponse } from '@arboretum/shared';
|
||||||
|
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';
|
||||||
|
|
||||||
|
const FILE_MAX_BYTES = 2 * 1024 * 1024;
|
||||||
|
|
||||||
|
/** Langage Monaco déduit de l'extension (sous-ensemble courant ; Monaco a un fallback 'plaintext'). */
|
||||||
|
const LANG_BY_EXT: Record<string, string> = {
|
||||||
|
'.ts': 'typescript', '.tsx': 'typescript', '.js': 'javascript', '.jsx': 'javascript', '.mjs': 'javascript', '.cjs': 'javascript',
|
||||||
|
'.json': 'json', '.vue': 'vue', '.css': 'css', '.scss': 'scss', '.less': 'less', '.html': 'html', '.md': 'markdown',
|
||||||
|
'.py': 'python', '.rb': 'ruby', '.go': 'go', '.rs': 'rust', '.java': 'java', '.c': 'c', '.h': 'c', '.cpp': 'cpp', '.cc': 'cpp',
|
||||||
|
'.cs': 'csharp', '.php': 'php', '.sh': 'shell', '.bash': 'shell', '.zsh': 'shell', '.yml': 'yaml', '.yaml': 'yaml',
|
||||||
|
'.toml': 'toml', '.xml': 'xml', '.sql': 'sql', '.swift': 'swift', '.kt': 'kotlin', '.dart': 'dart', '.lua': 'lua',
|
||||||
|
};
|
||||||
|
|
||||||
|
function languageFor(path: string): string | undefined {
|
||||||
|
return LANG_BY_EXT[extname(path).toLowerCase()];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Détecte un fichier binaire par présence d'un octet NUL dans le buffer. */
|
||||||
|
function looksBinary(buf: Buffer): boolean {
|
||||||
|
const n = Math.min(buf.length, 8192);
|
||||||
|
for (let i = 0; i < n; i++) if (buf[i] === 0) return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function registerFileRoutes(app: FastifyInstance, wt: WorktreeManager, db: Db): void {
|
||||||
|
// Lecture du contenu d'un fichier (UTF-8) d'un worktree.
|
||||||
|
app.get('/api/v1/repos/:id/files/content', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const q = req.query as { wt?: string; path?: string };
|
||||||
|
if (typeof q.wt !== 'string' || q.wt === '' || typeof q.path !== 'string' || q.path === '') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'wt and path are required' } });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const abs = await wt.assertPathInWorktree(id, q.wt, q.path);
|
||||||
|
const st = await stat(abs).catch(() => null);
|
||||||
|
if (!st || !st.isFile()) return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No such file' } });
|
||||||
|
if (st.size > FILE_MAX_BYTES) return reply.status(413).send({ error: { code: 'FILE_TOO_LARGE', message: `File exceeds ${FILE_MAX_BYTES} bytes` } });
|
||||||
|
const buf = await readFile(abs);
|
||||||
|
if (looksBinary(buf)) return reply.status(415).send({ error: { code: 'BINARY_FILE', message: 'Binary files are not editable' } });
|
||||||
|
const lang = languageFor(q.path);
|
||||||
|
const res: FileContentResponse = {
|
||||||
|
path: q.path,
|
||||||
|
content: buf.toString('utf-8'),
|
||||||
|
encoding: 'utf-8',
|
||||||
|
size: st.size,
|
||||||
|
mtime: st.mtimeMs,
|
||||||
|
...(lang ? { language: lang } : {}),
|
||||||
|
};
|
||||||
|
return reply.send(res);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Écriture (création/modification) du contenu d'un fichier d'un worktree.
|
||||||
|
app.put('/api/v1/repos/:id/files/content', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const body = req.body as Partial<WriteFileRequest> | null;
|
||||||
|
if (!body || typeof body.wt !== 'string' || typeof body.path !== 'string' || typeof body.content !== 'string') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'wt, path and content are required' } });
|
||||||
|
}
|
||||||
|
if (Buffer.byteLength(body.content, 'utf-8') > FILE_MAX_BYTES) {
|
||||||
|
return reply.status(413).send({ error: { code: 'FILE_TOO_LARGE', message: `Content exceeds ${FILE_MAX_BYTES} bytes` } });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const abs = await wt.assertPathInWorktree(id, body.wt, body.path);
|
||||||
|
// Garde-fou conflit (P8) : si le client a chargé le fichier (baseMtime) et qu'il a changé
|
||||||
|
// depuis (ex. Claude a écrit en parallèle), on refuse pour ne pas écraser silencieusement.
|
||||||
|
if (typeof body.baseMtime === 'number') {
|
||||||
|
const cur = await stat(abs).catch(() => null);
|
||||||
|
if (cur && cur.isFile() && cur.mtimeMs !== body.baseMtime) {
|
||||||
|
return reply.status(409).send({ error: { code: 'STALE_FILE', message: 'File changed on disk since it was loaded' } });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await mkdir(dirname(abs), { recursive: true }); // dirname reste sous le worktree (abs validé)
|
||||||
|
await writeFile(abs, body.content, 'utf-8');
|
||||||
|
const after = await stat(abs);
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'file.write', resourceId: id, details: { path: body.path } });
|
||||||
|
const res: WriteFileResponse = { ok: true, size: Buffer.byteLength(body.content, 'utf-8'), mtime: after.mtimeMs };
|
||||||
|
return reply.send(res);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -18,7 +18,7 @@ import type { FsEntry, FsListResponse } from '@arboretum/shared';
|
|||||||
*/
|
*/
|
||||||
export function registerFsRoutes(app: FastifyInstance): void {
|
export function registerFsRoutes(app: FastifyInstance): void {
|
||||||
app.get('/api/v1/fs/list', async (req, reply) => {
|
app.get('/api/v1/fs/list', async (req, reply) => {
|
||||||
const q = req.query as { path?: string; markRepos?: string; showHidden?: string };
|
const q = req.query as { path?: string; markRepos?: string; showHidden?: string; includeFiles?: string };
|
||||||
const raw = q.path && q.path.length > 0 ? q.path : homedir();
|
const raw = q.path && q.path.length > 0 ? q.path : homedir();
|
||||||
if (!raw.startsWith('/')) {
|
if (!raw.startsWith('/')) {
|
||||||
return reply.status(400).send({ error: { code: 'BAD_PATH', message: 'path must be absolute' } });
|
return reply.status(400).send({ error: { code: 'BAD_PATH', message: 'path must be absolute' } });
|
||||||
@@ -41,6 +41,7 @@ export function registerFsRoutes(app: FastifyInstance): void {
|
|||||||
|
|
||||||
const markRepos = q.markRepos === '1' || q.markRepos === 'true';
|
const markRepos = q.markRepos === '1' || q.markRepos === 'true';
|
||||||
const showHidden = q.showHidden === '1' || q.showHidden === 'true';
|
const showHidden = q.showHidden === '1' || q.showHidden === 'true';
|
||||||
|
const includeFiles = q.includeFiles === '1' || q.includeFiles === 'true';
|
||||||
|
|
||||||
let dirents;
|
let dirents;
|
||||||
try {
|
try {
|
||||||
@@ -63,13 +64,24 @@ export function registerFsRoutes(app: FastifyInstance): void {
|
|||||||
isDir = false;
|
isDir = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!isDir) continue;
|
|
||||||
const full = join(abs, d.name);
|
const full = join(abs, d.name);
|
||||||
|
if (!isDir) {
|
||||||
|
// En mode includeFiles, on remonte aussi les fichiers (arbre de l'IDE worktree).
|
||||||
|
if (!includeFiles) continue;
|
||||||
|
entries.push({ name: d.name, path: full, isFile: true });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
const entry: FsEntry = { name: d.name, path: full };
|
const entry: FsEntry = { name: d.name, path: full };
|
||||||
if (markRepos && existsSync(join(full, '.git'))) entry.isRepo = true;
|
if (markRepos && existsSync(join(full, '.git'))) entry.isRepo = true;
|
||||||
entries.push(entry);
|
entries.push(entry);
|
||||||
}
|
}
|
||||||
entries.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
|
// Dossiers d'abord, puis fichiers ; tri insensible à la casse dans chaque groupe.
|
||||||
|
entries.sort((a, b) => {
|
||||||
|
const af = a.isFile ? 1 : 0;
|
||||||
|
const bf = b.isFile ? 1 : 0;
|
||||||
|
if (af !== bf) return af - bf;
|
||||||
|
return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
|
||||||
|
});
|
||||||
|
|
||||||
const res: FsListResponse = {
|
const res: FsListResponse = {
|
||||||
path: abs,
|
path: abs,
|
||||||
|
|||||||
119
packages/server/src/routes/git-connections.ts
Normal file
119
packages/server/src/routes/git-connections.ts
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
// Routes des services git distants (P12) : CRUD des credentials (secrets JAMAIS renvoyés), test de
|
||||||
|
// connexion, listing des dépôts distants, et lancement/suivi d'un clone. Authentifiées par le hook
|
||||||
|
// preValidation global. Les secrets sont chiffrés par SecretBox dans le manager.
|
||||||
|
import type { FastifyInstance, FastifyReply } from 'fastify';
|
||||||
|
import type {
|
||||||
|
CloneRequest,
|
||||||
|
CloneStartResponse,
|
||||||
|
CloneStatusResponse,
|
||||||
|
CreateGitCredentialRequest,
|
||||||
|
GitCredentialResponse,
|
||||||
|
GitCredentialsListResponse,
|
||||||
|
RemoteReposResponse,
|
||||||
|
UpdateGitCredentialRequest,
|
||||||
|
} from '@arboretum/shared';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
import type { GitCredentialsManager } from '../core/git-credentials.js';
|
||||||
|
import type { CloneManager } from '../core/clone-manager.js';
|
||||||
|
import { getGitClient, GitServiceError } from '../core/git-clients/index.js';
|
||||||
|
import { recordAudit } from '../core/audit-log.js';
|
||||||
|
|
||||||
|
function sendError(reply: FastifyReply, err: unknown): FastifyReply {
|
||||||
|
const e = err as { statusCode?: number; code?: string; message?: string };
|
||||||
|
const status = typeof e.statusCode === 'number' ? e.statusCode : 500;
|
||||||
|
return reply.status(status).send({ error: { code: e.code ?? 'INTERNAL', message: e.message ?? 'Internal error' } });
|
||||||
|
}
|
||||||
|
|
||||||
|
const GIT_SERVICE_ERROR_STATUS: Record<string, number> = { AUTH_FAILED: 401, RATE_LIMITED: 429, UNREACHABLE: 502, BAD_BASE_URL: 400 };
|
||||||
|
|
||||||
|
export function registerGitConnectionRoutes(
|
||||||
|
app: FastifyInstance,
|
||||||
|
credentials: GitCredentialsManager,
|
||||||
|
clones: CloneManager,
|
||||||
|
db: Db,
|
||||||
|
): void {
|
||||||
|
const actor = (req: { authContext?: { tokenId: string } | null }): string => req.authContext?.tokenId ?? 'unknown';
|
||||||
|
|
||||||
|
app.get('/api/v1/git-connections', async (): Promise<GitCredentialsListResponse> => ({ credentials: credentials.list() }));
|
||||||
|
|
||||||
|
app.post('/api/v1/git-connections', async (req, reply) => {
|
||||||
|
try {
|
||||||
|
const cred = credentials.create((req.body ?? {}) as CreateGitCredentialRequest);
|
||||||
|
recordAudit(db, { actor: actor(req), action: 'git_credential.create', resourceId: cred.id, details: { service: cred.service, authType: cred.authType } });
|
||||||
|
const res: GitCredentialResponse = { credential: cred };
|
||||||
|
return reply.status(201).send(res);
|
||||||
|
} catch (err) {
|
||||||
|
return sendError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.patch('/api/v1/git-connections/:id', async (req, reply) => {
|
||||||
|
try {
|
||||||
|
const cred = credentials.update((req.params as { id: string }).id, (req.body ?? {}) as UpdateGitCredentialRequest);
|
||||||
|
recordAudit(db, { actor: actor(req), action: 'git_credential.update', resourceId: cred.id });
|
||||||
|
const res: GitCredentialResponse = { credential: cred };
|
||||||
|
return reply.send(res);
|
||||||
|
} catch (err) {
|
||||||
|
return sendError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.delete('/api/v1/git-connections/:id', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
if (!credentials.remove(id)) {
|
||||||
|
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No credential with this id' } });
|
||||||
|
}
|
||||||
|
recordAudit(db, { actor: actor(req), action: 'git_credential.delete', resourceId: id });
|
||||||
|
return reply.send({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post('/api/v1/git-connections/:id/test', async (req, reply) => {
|
||||||
|
try {
|
||||||
|
const result = await credentials.test((req.params as { id: string }).id);
|
||||||
|
recordAudit(db, { actor: actor(req), action: 'git_credential.test', resourceId: (req.params as { id: string }).id, details: { ok: result.ok } });
|
||||||
|
return reply.send(result);
|
||||||
|
} catch (err) {
|
||||||
|
return sendError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get('/api/v1/git-connections/:id/repos', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const q = req.query as { page?: string; search?: string };
|
||||||
|
const ctx = credentials.authContext(id);
|
||||||
|
if (!ctx) return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No usable credential with this id' } });
|
||||||
|
const page = Math.max(1, Number(q.page) || 1);
|
||||||
|
try {
|
||||||
|
const { repos, nextPage } = await getGitClient(ctx.service, ctx.baseUrl).listRepos(ctx.auth, page, q.search);
|
||||||
|
const res: RemoteReposResponse = { repos, nextPage };
|
||||||
|
return reply.send(res);
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof GitServiceError) {
|
||||||
|
return reply.status(GIT_SERVICE_ERROR_STATUS[err.errorCode] ?? 502).send({ error: { code: err.errorCode, message: err.message } });
|
||||||
|
}
|
||||||
|
return sendError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- Clone (asynchrone : 202 + suivi WS/REST) ----
|
||||||
|
app.post('/api/v1/repos/clone', async (req, reply) => {
|
||||||
|
const body = (req.body ?? {}) as Partial<CloneRequest>;
|
||||||
|
if (typeof body.credentialId !== 'string' || typeof body.remoteUrl !== 'string' || typeof body.dest !== 'string') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'credentialId, remoteUrl and dest are required' } });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const operationId = await clones.start({ credentialId: body.credentialId, remoteUrl: body.remoteUrl, dest: body.dest }, actor(req));
|
||||||
|
const res: CloneStartResponse = { operationId };
|
||||||
|
return reply.status(202).send(res);
|
||||||
|
} catch (err) {
|
||||||
|
return sendError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get('/api/v1/repos/clone/:id', async (req, reply) => {
|
||||||
|
const op = clones.get((req.params as { id: string }).id);
|
||||||
|
if (!op) return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No clone operation with this id' } });
|
||||||
|
const res: CloneStatusResponse = { operation: op };
|
||||||
|
return reply.send(res);
|
||||||
|
});
|
||||||
|
}
|
||||||
132
packages/server/src/routes/git.ts
Normal file
132
packages/server/src/routes/git.ts
Normal file
@@ -0,0 +1,132 @@
|
|||||||
|
// Routes git « IDE » (P7) : diff par fichier, statut détaillé, staging sélectif, discard, fetch, pull.
|
||||||
|
// Toutes authentifiées par le hook preValidation global (/api/**), validées strictement et auditées.
|
||||||
|
// Le commit (sélectif/amend) reste sur POST /worktrees/commit (routes/worktrees.ts) pour ne pas
|
||||||
|
// dupliquer la sémantique.
|
||||||
|
import type { FastifyInstance } from 'fastify';
|
||||||
|
import type {
|
||||||
|
WorktreeChangesResponse,
|
||||||
|
FileDiffResponse,
|
||||||
|
WorktreeFilesRequest,
|
||||||
|
DiscardFilesRequest,
|
||||||
|
FetchWorktreeRequest,
|
||||||
|
PullWorktreeRequest,
|
||||||
|
WorktreeResponse,
|
||||||
|
} from '@arboretum/shared';
|
||||||
|
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';
|
||||||
|
|
||||||
|
export function registerGitRoutes(app: FastifyInstance, wt: WorktreeManager, db: Db): void {
|
||||||
|
// Liste des fichiers modifiés d'un worktree (statut détaillé + stats +/-).
|
||||||
|
app.get('/api/v1/repos/:id/worktrees/changes', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const q = req.query as { path?: string };
|
||||||
|
if (typeof q.path !== 'string' || q.path === '') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path is required' } });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const { changes, truncated } = await wt.getWorktreeChanges(id, q.path);
|
||||||
|
return reply.send({ repoId: id, path: q.path, changes, truncated } satisfies WorktreeChangesResponse);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Diff unifié d'un fichier (staged ou non ; untracked détecté côté manager).
|
||||||
|
app.get('/api/v1/repos/:id/worktrees/diff', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const q = req.query as { path?: string; file?: string; staged?: string };
|
||||||
|
if (typeof q.path !== 'string' || q.path === '' || typeof q.file !== 'string' || q.file === '') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path and file are required' } });
|
||||||
|
}
|
||||||
|
const staged = q.staged === '1' || q.staged === 'true';
|
||||||
|
try {
|
||||||
|
const res = await wt.getFileDiff(id, q.path, q.file, staged);
|
||||||
|
return reply.send(res satisfies FileDiffResponse);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Staging sélectif.
|
||||||
|
app.post('/api/v1/repos/:id/worktrees/stage', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const body = req.body as Partial<WorktreeFilesRequest> | null;
|
||||||
|
if (!body || typeof body.path !== 'string' || !Array.isArray(body.files)) {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path and files are required' } });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const worktree = await wt.stage(id, body.path, body.files);
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'git.stage', resourceId: id, details: { path: body.path, count: body.files.length } });
|
||||||
|
return reply.send({ worktree } satisfies WorktreeResponse);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Désindexation sélective.
|
||||||
|
app.post('/api/v1/repos/:id/worktrees/unstage', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const body = req.body as Partial<WorktreeFilesRequest> | null;
|
||||||
|
if (!body || typeof body.path !== 'string' || !Array.isArray(body.files)) {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path and files are required' } });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const worktree = await wt.unstage(id, body.path, body.files);
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'git.unstage', resourceId: id, details: { path: body.path, count: body.files.length } });
|
||||||
|
return reply.send({ worktree } satisfies WorktreeResponse);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Annulation des changements locaux (restore ; clean des untracked uniquement si includeUntracked).
|
||||||
|
app.post('/api/v1/repos/:id/worktrees/discard', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const body = req.body as Partial<DiscardFilesRequest> | null;
|
||||||
|
if (!body || typeof body.path !== 'string' || !Array.isArray(body.files)) {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path and files are required' } });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const worktree = await wt.discard(id, body.path, body.files, body.includeUntracked === true);
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'git.discard', resourceId: id, details: { path: body.path, count: body.files.length, includeUntracked: body.includeUntracked === true } });
|
||||||
|
return reply.send({ worktree } satisfies WorktreeResponse);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Fetch (--all --prune) : actualise ahead/behind.
|
||||||
|
app.post('/api/v1/repos/:id/worktrees/fetch', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const body = req.body as Partial<FetchWorktreeRequest> | 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.fetch(id, body.path);
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'git.fetch', resourceId: id, details: { path: body.path } });
|
||||||
|
return reply.send({ worktree } satisfies WorktreeResponse);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Pull (ff-only par défaut, rebase optionnel).
|
||||||
|
app.post('/api/v1/repos/:id/worktrees/pull', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const body = req.body as Partial<PullWorktreeRequest> | null;
|
||||||
|
if (!body || typeof body.path !== 'string') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path is required' } });
|
||||||
|
}
|
||||||
|
const mode = body.mode === 'rebase' ? 'rebase' : 'ff-only';
|
||||||
|
try {
|
||||||
|
const worktree = await wt.pull(id, body.path, mode);
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'git.pull', resourceId: id, details: { path: body.path, mode } });
|
||||||
|
return reply.send({ worktree } satisfies WorktreeResponse);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -2,14 +2,27 @@ import type { FastifyInstance } from 'fastify';
|
|||||||
import type {
|
import type {
|
||||||
AddRepoRequest,
|
AddRepoRequest,
|
||||||
CreateGroupRequest,
|
CreateGroupRequest,
|
||||||
|
CreateGroupSessionRequest,
|
||||||
GroupResponse,
|
GroupResponse,
|
||||||
|
GroupSessionResponse,
|
||||||
GroupsListResponse,
|
GroupsListResponse,
|
||||||
UpdateGroupRequest,
|
UpdateGroupRequest,
|
||||||
} from '@arboretum/shared';
|
} from '@arboretum/shared';
|
||||||
import type { GroupManager } from '../core/group-manager.js';
|
import type { GroupManager } from '../core/group-manager.js';
|
||||||
|
import type { 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';
|
import { sendManagerError } from './repos.js';
|
||||||
|
|
||||||
export function registerGroupRoutes(app: FastifyInstance, gm: GroupManager): void {
|
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', async (): Promise<GroupsListResponse> => ({ groups: gm.listGroups() }));
|
||||||
|
|
||||||
app.get('/api/v1/groups/:id', async (req, reply) => {
|
app.get('/api/v1/groups/:id', async (req, reply) => {
|
||||||
@@ -33,6 +46,7 @@ export function registerGroupRoutes(app: FastifyInstance, gm: GroupManager): voi
|
|||||||
...(body.color !== undefined ? { color: body.color } : {}),
|
...(body.color !== undefined ? { color: body.color } : {}),
|
||||||
...(Array.isArray(body.repoIds) ? { repoIds: body.repoIds } : {}),
|
...(Array.isArray(body.repoIds) ? { repoIds: body.repoIds } : {}),
|
||||||
});
|
});
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'group.create', resourceId: group.id, details: { label: group.label } });
|
||||||
return reply.status(201).send({ group } satisfies GroupResponse);
|
return reply.status(201).send({ group } satisfies GroupResponse);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return sendManagerError(reply, err);
|
return sendManagerError(reply, err);
|
||||||
@@ -48,6 +62,7 @@ export function registerGroupRoutes(app: FastifyInstance, gm: GroupManager): voi
|
|||||||
...(body.description !== undefined ? { description: body.description } : {}),
|
...(body.description !== undefined ? { description: body.description } : {}),
|
||||||
...(body.color !== undefined ? { color: body.color } : {}),
|
...(body.color !== undefined ? { color: body.color } : {}),
|
||||||
});
|
});
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'group.update', resourceId: id });
|
||||||
return reply.send({ group } satisfies GroupResponse);
|
return reply.send({ group } satisfies GroupResponse);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return sendManagerError(reply, err);
|
return sendManagerError(reply, err);
|
||||||
@@ -59,6 +74,7 @@ export function registerGroupRoutes(app: FastifyInstance, gm: GroupManager): voi
|
|||||||
if (!gm.deleteGroup(id)) {
|
if (!gm.deleteGroup(id)) {
|
||||||
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No group with this id' } });
|
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No group with this id' } });
|
||||||
}
|
}
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'group.delete', resourceId: id });
|
||||||
return reply.send({ ok: true });
|
return reply.send({ ok: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -83,4 +99,64 @@ export function registerGroupRoutes(app: FastifyInstance, gm: GroupManager): voi
|
|||||||
return sendManagerError(reply, 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 } });
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
89
packages/server/src/routes/projects.ts
Normal file
89
packages/server/src/routes/projects.ts
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
import type { FastifyInstance } from 'fastify';
|
||||||
|
import { mkdir, stat } from 'node:fs/promises';
|
||||||
|
import type { CreateProjectRequest, CreateProjectResponse } from '@arboretum/shared';
|
||||||
|
import type { PtyManager } from '../core/pty-manager.js';
|
||||||
|
import { gitInit, isSafeAbsolutePath } from '../core/git.js';
|
||||||
|
import { resolveProjectDir } from '../core/project.js';
|
||||||
|
import { recordAudit } from '../core/audit-log.js';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Création d'un nouveau projet : crée le dossier `<root>/<name>` (la SEULE écriture fs autorisée
|
||||||
|
* côté serveur en dehors du dataDir) puis lance une session dedans. `git init` optionnel.
|
||||||
|
* Cohérent avec le modèle de sécurité : un client authentifié dispose déjà d'un terminal (RCE par
|
||||||
|
* conception). On valide tout de même strictement `name` (anti-traversal) et on exige une racine
|
||||||
|
* EXISTANTE (mkdir non récursif → pas de création d'arborescence arbitraire).
|
||||||
|
*
|
||||||
|
* POST /api/v1/projects { root, name, gitInit?, command? } → 201 { session, path, gitInitialized }
|
||||||
|
*/
|
||||||
|
export function registerProjectRoutes(app: FastifyInstance, manager: PtyManager, db: Db): void {
|
||||||
|
app.post('/api/v1/projects', async (req, reply) => {
|
||||||
|
const body = req.body as Partial<CreateProjectRequest> | null;
|
||||||
|
if (!body || typeof body.root !== 'string' || !isSafeAbsolutePath(body.root)) {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'root (absolute path) is required' } });
|
||||||
|
}
|
||||||
|
if (typeof body.name !== 'string') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'name is required' } });
|
||||||
|
}
|
||||||
|
if (body.command !== undefined && body.command !== 'claude' && body.command !== 'bash') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'command must be claude or bash' } });
|
||||||
|
}
|
||||||
|
|
||||||
|
// La racine doit exister et être un répertoire (mkdir non récursif derrière).
|
||||||
|
try {
|
||||||
|
const st = await stat(body.root);
|
||||||
|
if (!st.isDirectory()) {
|
||||||
|
return reply.status(400).send({ error: { code: 'NOT_A_DIRECTORY', message: `Not a directory: ${body.root}` } });
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
const code = (err as NodeJS.ErrnoException).code;
|
||||||
|
if (code === 'ENOENT') return reply.status(404).send({ error: { code: 'NOT_FOUND', message: `No such directory: ${body.root}` } });
|
||||||
|
if (code === 'EACCES') return reply.status(403).send({ error: { code: 'FORBIDDEN', message: `Permission denied: ${body.root}` } });
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_PATH', message: (err as Error).message } });
|
||||||
|
}
|
||||||
|
|
||||||
|
let dir: string;
|
||||||
|
try {
|
||||||
|
dir = resolveProjectDir(body.root, body.name);
|
||||||
|
} catch (err) {
|
||||||
|
return reply.status((err as { statusCode?: number }).statusCode ?? 400).send({ error: { code: 'BAD_REQUEST', message: (err as Error).message } });
|
||||||
|
}
|
||||||
|
|
||||||
|
// mkdir non récursif : EEXIST → 409 (on n'écrase jamais un dossier existant).
|
||||||
|
try {
|
||||||
|
await mkdir(dir);
|
||||||
|
} catch (err) {
|
||||||
|
const code = (err as NodeJS.ErrnoException).code;
|
||||||
|
if (code === 'EEXIST') return reply.status(409).send({ error: { code: 'PROJECT_EXISTS', message: `Already exists: ${dir}` } });
|
||||||
|
if (code === 'EACCES') return reply.status(403).send({ error: { code: 'FORBIDDEN', message: `Permission denied: ${dir}` } });
|
||||||
|
return reply.status(400).send({ error: { code: 'MKDIR_FAILED', message: (err as Error).message } });
|
||||||
|
}
|
||||||
|
|
||||||
|
const wantsGitInit = body.gitInit === true;
|
||||||
|
let gitInitialized = false;
|
||||||
|
if (wantsGitInit) {
|
||||||
|
try {
|
||||||
|
await gitInit(dir);
|
||||||
|
gitInitialized = true;
|
||||||
|
} catch {
|
||||||
|
// Le dossier est créé et la session démarrera quand même : un échec git n'annule pas le projet.
|
||||||
|
gitInitialized = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const session = manager.spawn({ cwd: dir, ...(body.command ? { command: body.command } : {}) });
|
||||||
|
recordAudit(db, {
|
||||||
|
actor: req.authContext?.tokenId ?? 'unknown',
|
||||||
|
action: 'project.create',
|
||||||
|
resourceId: dir,
|
||||||
|
details: { gitInit: gitInitialized },
|
||||||
|
});
|
||||||
|
const res: CreateProjectResponse = { session, path: dir, gitInitialized };
|
||||||
|
return reply.status(201).send(res);
|
||||||
|
} 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,35 @@
|
|||||||
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 type { SessionArchiveService } from '../core/session-archive.js';
|
||||||
|
import { archiveSession, hideSession, sessionExists, unarchiveSession, 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.get('/api/v1/sessions', async (): Promise<SessionsListResponse> => {
|
app: FastifyInstance,
|
||||||
return { sessions: mergeSessions(manager.list(), discovery.list()) };
|
manager: PtyManager,
|
||||||
|
discovery: DiscoveryService,
|
||||||
|
sessionArchive: SessionArchiveService,
|
||||||
|
db: Db,
|
||||||
|
): void {
|
||||||
|
app.get('/api/v1/sessions', async (req): Promise<SessionsListResponse> => {
|
||||||
|
const q = req.query as { includeHidden?: string; includeArchived?: string };
|
||||||
|
const includeHidden = q.includeHidden === 'true';
|
||||||
|
const includeArchived = q.includeArchived === 'true';
|
||||||
|
// `includeArchived` ne concerne QUE les sessions managées (manager.list) ; les découvertes
|
||||||
|
// n'ont pas de notion d'archivage. `hidden` est filtré ensuite, indépendamment.
|
||||||
|
const all = mergeSessions(manager.list({ includeArchived }), 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 +48,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 +83,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 +103,83 @@ 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);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Archive manuellement une session managée terminée (soft-archive). Exclue de la liste par défaut,
|
||||||
|
// reste reprenable/forkable. 404 si l'id n'est pas une session managée connue en DB.
|
||||||
|
app.post('/api/v1/sessions/:id/archive', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
if (!sessionExists(db, id)) {
|
||||||
|
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No managed session with this id to archive' } });
|
||||||
|
}
|
||||||
|
const archivedAt = new Date().toISOString();
|
||||||
|
archiveSession(db, id, archivedAt);
|
||||||
|
sessionArchive.emitArchived(id, archivedAt); // diffuse aux clients abonnés (session_archived)
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'session.archive', resourceId: id });
|
||||||
|
return reply.send({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
// Dés-archive une session : ré-émet un session_update pour que tous les clients ré-affichent le row.
|
||||||
|
app.delete('/api/v1/sessions/:id/archive', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
if (!sessionExists(db, id)) {
|
||||||
|
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No managed session with this id to unarchive' } });
|
||||||
|
}
|
||||||
|
unarchiveSession(db, id);
|
||||||
|
manager.emitHistoricalUpdate(id);
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'session.unarchive', resourceId: id });
|
||||||
|
return reply.send({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
// Déclenche un balayage d'archivage immédiat (rétention configurée). Renvoie le nombre archivé.
|
||||||
|
// Pratique pour l'UX et pour une acceptance déterministe (sans attendre le scheduler ~6 h).
|
||||||
|
app.post('/api/v1/sessions/archive-now', async (req, reply) => {
|
||||||
|
const archived = sessionArchive.sweep();
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'session.archiveNow', resourceId: null, details: { archived } });
|
||||||
|
return reply.send({ archived });
|
||||||
|
});
|
||||||
|
|
||||||
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)) {
|
||||||
|
|||||||
126
packages/server/src/routes/settings.ts
Normal file
126
packages/server/src/routes/settings.ts
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
// 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 type { SettingsBus } from '../core/settings-bus.js';
|
||||||
|
import { recordAudit } from '../core/audit-log.js';
|
||||||
|
import { diagnoseClaudeBin } from '../core/claude-launcher.js';
|
||||||
|
import {
|
||||||
|
SCAN_INTERVAL_KEY,
|
||||||
|
SCAN_ROOTS_KEY,
|
||||||
|
normalizeScanIntervalMin,
|
||||||
|
normalizeScanRoots,
|
||||||
|
readScanIntervalMin,
|
||||||
|
readScanRoots,
|
||||||
|
} from '../core/scan-settings.js';
|
||||||
|
import {
|
||||||
|
CLAUDE_BIN_PATH_KEY,
|
||||||
|
CLAUDE_HOME_KEY,
|
||||||
|
normalizeClaudeBinPath,
|
||||||
|
normalizeClaudeHome,
|
||||||
|
readClaudeBinPath,
|
||||||
|
readClaudeHome,
|
||||||
|
} from '../core/claude-settings.js';
|
||||||
|
import {
|
||||||
|
PURGE_DAYS_KEY,
|
||||||
|
RETENTION_DAYS_KEY,
|
||||||
|
normalizePurgeDays,
|
||||||
|
normalizeRetentionDays,
|
||||||
|
readPurgeDays,
|
||||||
|
readRetentionDays,
|
||||||
|
} from '../core/retention-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,
|
||||||
|
settingsBus: SettingsBus,
|
||||||
|
): 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,
|
||||||
|
claudeHome: config.claudeHome,
|
||||||
|
// Diagnostic recalculé à chaque GET : reflète l'état réel (override exécutable ? `which claude` ?).
|
||||||
|
claudeBin: diagnoseClaudeBin(readClaudeBinPath(db)),
|
||||||
|
});
|
||||||
|
const snapshot = (): SettingsResponse => ({
|
||||||
|
settings: {
|
||||||
|
scanRoots: readScanRoots(db),
|
||||||
|
scanIntervalMin: readScanIntervalMin(db),
|
||||||
|
claudeBinPath: readClaudeBinPath(db),
|
||||||
|
claudeHome: readClaudeHome(db),
|
||||||
|
retentionDays: readRetentionDays(db),
|
||||||
|
purgeDays: readPurgeDays(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));
|
||||||
|
}
|
||||||
|
if ('claudeBinPath' in body) {
|
||||||
|
const value = normalizeClaudeBinPath(body.claudeBinPath);
|
||||||
|
if (value === null) {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'claudeBinPath must be an absolute path to an executable file (or "" to reset)' } });
|
||||||
|
}
|
||||||
|
setSetting(db, CLAUDE_BIN_PATH_KEY, value);
|
||||||
|
}
|
||||||
|
if ('claudeHome' in body) {
|
||||||
|
const value = normalizeClaudeHome(body.claudeHome);
|
||||||
|
if (value === null) {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'claudeHome must be an absolute path to an existing directory (or "" to reset)' } });
|
||||||
|
}
|
||||||
|
setSetting(db, CLAUDE_HOME_KEY, value);
|
||||||
|
}
|
||||||
|
if ('retentionDays' in body) {
|
||||||
|
const value = normalizeRetentionDays(body.retentionDays);
|
||||||
|
if (value === null) {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'retentionDays must be 0 (never) or an integer between 1 and 3650' } });
|
||||||
|
}
|
||||||
|
setSetting(db, RETENTION_DAYS_KEY, String(value));
|
||||||
|
}
|
||||||
|
if ('purgeDays' in body) {
|
||||||
|
const value = normalizePurgeDays(body.purgeDays);
|
||||||
|
if (value === null) {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'purgeDays must be 0 (disabled) or an integer between 1 and 3650' } });
|
||||||
|
}
|
||||||
|
setSetting(db, PURGE_DAYS_KEY, String(value));
|
||||||
|
}
|
||||||
|
recordAudit(db, {
|
||||||
|
actor: req.authContext?.tokenId ?? 'unknown',
|
||||||
|
action: 'settings.update',
|
||||||
|
details: { keys: Object.keys(body) },
|
||||||
|
});
|
||||||
|
const snap = snapshot();
|
||||||
|
// P11 · diffuse le nouvel état non sensible à tous les clients abonnés au topic 'settings'.
|
||||||
|
settingsBus.emit('settings_update', snap.settings);
|
||||||
|
return reply.send(snap);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -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,63 @@ 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' } });
|
||||||
|
}
|
||||||
|
const amend = body.amend === true;
|
||||||
|
if (!amend && (typeof body.message !== 'string' || body.message.trim() === '')) {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'message is required' } });
|
||||||
|
}
|
||||||
|
const mode = body.mode === 'staged' ? 'staged' : 'all';
|
||||||
|
try {
|
||||||
|
const worktree = await wt.commitWorktree(id, body.path, {
|
||||||
|
message: typeof body.message === 'string' ? body.message.trim() : '',
|
||||||
|
mode,
|
||||||
|
amend,
|
||||||
|
});
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'worktree.commit', resourceId: id, details: { path: body.path, mode, amend } });
|
||||||
|
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 };
|
||||||
|
|||||||
@@ -7,14 +7,19 @@ import {
|
|||||||
parseClientMessage,
|
parseClientMessage,
|
||||||
type GroupSummary,
|
type GroupSummary,
|
||||||
type RepoSummary,
|
type RepoSummary,
|
||||||
|
type CloneOperation,
|
||||||
type ServerMessage,
|
type ServerMessage,
|
||||||
type SessionSummary,
|
type SessionSummary,
|
||||||
|
type SettingsBroadcast,
|
||||||
type WorktreeSummary,
|
type WorktreeSummary,
|
||||||
} from '@arboretum/shared';
|
} from '@arboretum/shared';
|
||||||
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 { SessionArchiveService } from '../core/session-archive.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';
|
import type { GroupManager } from '../core/group-manager.js';
|
||||||
|
import type { SettingsBus } from '../core/settings-bus.js';
|
||||||
|
import type { CloneManager } from '../core/clone-manager.js';
|
||||||
|
|
||||||
const HEARTBEAT_MS = 30_000;
|
const HEARTBEAT_MS = 30_000;
|
||||||
|
|
||||||
@@ -27,8 +32,11 @@ export function registerWsGateway(
|
|||||||
app: FastifyInstance,
|
app: FastifyInstance,
|
||||||
manager: PtyManager,
|
manager: PtyManager,
|
||||||
discovery: DiscoveryService,
|
discovery: DiscoveryService,
|
||||||
|
sessionArchive: SessionArchiveService,
|
||||||
worktrees: WorktreeManager,
|
worktrees: WorktreeManager,
|
||||||
groups: GroupManager,
|
groups: GroupManager,
|
||||||
|
settingsBus: SettingsBus,
|
||||||
|
clones: CloneManager,
|
||||||
serverVersion: string,
|
serverVersion: string,
|
||||||
): void {
|
): void {
|
||||||
app.get('/ws', { websocket: true }, (socket: WebSocket, req) => {
|
app.get('/ws', { websocket: true }, (socket: WebSocket, req) => {
|
||||||
@@ -39,7 +47,12 @@ export function registerWsGateway(
|
|||||||
let subscribedSessions = false;
|
let subscribedSessions = false;
|
||||||
let subscribedWorktrees = false;
|
let subscribedWorktrees = false;
|
||||||
let subscribedGroups = false;
|
let subscribedGroups = false;
|
||||||
|
let subscribedSettings = false;
|
||||||
|
let subscribedClones = false;
|
||||||
let alive = true;
|
let alive = true;
|
||||||
|
// Worktrees « regardés » par CETTE connexion (clé repoId\0path) → push ciblé de worktree_changes.
|
||||||
|
const watched = new Set<string>();
|
||||||
|
const watchKey = (repoId: string, path: string): string => `${repoId}\0${path}`;
|
||||||
|
|
||||||
const send = (msg: ServerMessage): void => {
|
const send = (msg: ServerMessage): void => {
|
||||||
if (socket.readyState === socket.OPEN) socket.send(JSON.stringify(msg));
|
if (socket.readyState === socket.OPEN) socket.send(JSON.stringify(msg));
|
||||||
@@ -54,6 +67,10 @@ export function registerWsGateway(
|
|||||||
const onSessionExit = (e: { sessionId: string; exitCode: number | null; signal: number | null }): void => {
|
const onSessionExit = (e: { sessionId: string; exitCode: number | null; signal: number | null }): void => {
|
||||||
if (subscribedSessions) send({ type: 'session_exit', ...e });
|
if (subscribedSessions) send({ type: 'session_exit', ...e });
|
||||||
};
|
};
|
||||||
|
// P10 · une session managée vient d'être archivée (auto par ancienneté ou manuellement).
|
||||||
|
const onSessionArchived = (e: { id: string; archivedAt: string }): void => {
|
||||||
|
if (subscribedSessions) send({ type: 'session_archived', sessionId: e.id });
|
||||||
|
};
|
||||||
// Les sessions découvertes (DiscoveryService) sont relayées sur le même flux que les managées.
|
// Les sessions découvertes (DiscoveryService) sont relayées sur le même flux que les managées.
|
||||||
const onDiscoveryUpdate = (session: SessionSummary): void => {
|
const onDiscoveryUpdate = (session: SessionSummary): void => {
|
||||||
if (subscribedSessions) send({ type: 'session_update', session });
|
if (subscribedSessions) send({ type: 'session_update', session });
|
||||||
@@ -76,15 +93,31 @@ export function registerWsGateway(
|
|||||||
const onGroupRemoved = (groupId: string): void => {
|
const onGroupRemoved = (groupId: string): void => {
|
||||||
if (subscribedGroups) send({ type: 'group_removed', groupId });
|
if (subscribedGroups) send({ type: 'group_removed', groupId });
|
||||||
};
|
};
|
||||||
|
// P11 · un réglage a changé : relayé aux connexions abonnées au topic 'settings'.
|
||||||
|
const onSettingsUpdate = (settings: SettingsBroadcast): void => {
|
||||||
|
if (subscribedSettings) send({ type: 'settings_update', settings });
|
||||||
|
};
|
||||||
|
// P12 · progression d'un clone : relayée aux abonnés du topic 'clones'.
|
||||||
|
const onCloneUpdate = (operation: CloneOperation): void => {
|
||||||
|
if (subscribedClones) send({ type: 'clone_update', operation });
|
||||||
|
};
|
||||||
|
// P7 · détail d'un worktree modifié : poussé UNIQUEMENT si cette connexion le regarde.
|
||||||
|
const onWorktreeChanges = (e: { repoId: string; path: string }): void => {
|
||||||
|
if (watched.has(watchKey(e.repoId, e.path))) send({ type: 'worktree_changes', ...e });
|
||||||
|
};
|
||||||
manager.on('session_update', onSessionUpdate);
|
manager.on('session_update', onSessionUpdate);
|
||||||
manager.on('session_exit', onSessionExit);
|
manager.on('session_exit', onSessionExit);
|
||||||
|
sessionArchive.on('session_archived', onSessionArchived);
|
||||||
discovery.on('discovery_update', onDiscoveryUpdate);
|
discovery.on('discovery_update', onDiscoveryUpdate);
|
||||||
worktrees.on('repo_update', onRepoUpdate);
|
worktrees.on('repo_update', onRepoUpdate);
|
||||||
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);
|
||||||
|
worktrees.on('worktree_changes', onWorktreeChanges);
|
||||||
groups.on('group_update', onGroupUpdate);
|
groups.on('group_update', onGroupUpdate);
|
||||||
groups.on('group_removed', onGroupRemoved);
|
groups.on('group_removed', onGroupRemoved);
|
||||||
|
settingsBus.on('settings_update', onSettingsUpdate);
|
||||||
|
clones.on('clone_update', onCloneUpdate);
|
||||||
|
|
||||||
const heartbeat = setInterval(() => {
|
const heartbeat = setInterval(() => {
|
||||||
if (!alive) {
|
if (!alive) {
|
||||||
@@ -124,6 +157,24 @@ export function registerWsGateway(
|
|||||||
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');
|
subscribedGroups = msg.topics.includes('groups');
|
||||||
|
subscribedSettings = msg.topics.includes('settings');
|
||||||
|
subscribedClones = msg.topics.includes('clones');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case 'watch': {
|
||||||
|
const key = watchKey(msg.repoId, msg.path);
|
||||||
|
if (watched.has(key)) return;
|
||||||
|
watched.add(key);
|
||||||
|
// Validation repo/worktree + armement du watcher FS (asynchrone, best-effort).
|
||||||
|
void worktrees.watch(msg.repoId, msg.path).catch((err) => {
|
||||||
|
watched.delete(key);
|
||||||
|
send({ type: 'error', code: 'NOT_FOUND', message: (err as Error).message });
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case 'unwatch': {
|
||||||
|
watched.delete(watchKey(msg.repoId, msg.path));
|
||||||
|
worktrees.unwatch(msg.repoId, msg.path);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
case 'attach': {
|
case 'attach': {
|
||||||
@@ -210,15 +261,25 @@ export function registerWsGateway(
|
|||||||
clearInterval(heartbeat);
|
clearInterval(heartbeat);
|
||||||
manager.off('session_update', onSessionUpdate);
|
manager.off('session_update', onSessionUpdate);
|
||||||
manager.off('session_exit', onSessionExit);
|
manager.off('session_exit', onSessionExit);
|
||||||
|
sessionArchive.off('session_archived', onSessionArchived);
|
||||||
discovery.off('discovery_update', onDiscoveryUpdate);
|
discovery.off('discovery_update', onDiscoveryUpdate);
|
||||||
worktrees.off('repo_update', onRepoUpdate);
|
worktrees.off('repo_update', onRepoUpdate);
|
||||||
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);
|
||||||
|
worktrees.off('worktree_changes', onWorktreeChanges);
|
||||||
groups.off('group_update', onGroupUpdate);
|
groups.off('group_update', onGroupUpdate);
|
||||||
groups.off('group_removed', onGroupRemoved);
|
groups.off('group_removed', onGroupRemoved);
|
||||||
|
settingsBus.off('settings_update', onSettingsUpdate);
|
||||||
|
clones.off('clone_update', onCloneUpdate);
|
||||||
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();
|
||||||
|
// Libère le refcount du watcher pour chaque worktree regardé par cette connexion.
|
||||||
|
for (const key of watched) {
|
||||||
|
const sep = key.indexOf('\0');
|
||||||
|
worktrees.unwatch(key.slice(0, sep), key.slice(sep + 1));
|
||||||
|
}
|
||||||
|
watched.clear();
|
||||||
});
|
});
|
||||||
|
|
||||||
void req;
|
void req;
|
||||||
|
|||||||
@@ -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' }));
|
||||||
@@ -76,7 +77,7 @@ afterAll(async () => {
|
|||||||
rmSync(dir, { recursive: true, force: true });
|
rmSync(dir, { recursive: true, force: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('app e2e — auth, origin et sessions', () => {
|
describe('app e2e · auth, origin et sessions', () => {
|
||||||
let t: TestApp;
|
let t: TestApp;
|
||||||
let cookieValue: string;
|
let cookieValue: string;
|
||||||
|
|
||||||
@@ -127,7 +128,8 @@ describe('app e2e — auth, origin et sessions', () => {
|
|||||||
cookies: { arb_session: cookieValue },
|
cookies: { arb_session: cookieValue },
|
||||||
});
|
});
|
||||||
expect(me.statusCode).toBe(200);
|
expect(me.statusCode).toBe(200);
|
||||||
expect(me.json()).toEqual({ ok: true, tokenLabel: 'initial', serverVersion: '0.0.0-test' });
|
expect(me.json()).toMatchObject({ ok: true, tokenLabel: 'initial', serverVersion: '0.0.0-test' });
|
||||||
|
expect(typeof (me.json() as { tokenId: string }).tokenId).toBe('string');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('cookie altéré → 401', async () => {
|
it('cookie altéré → 401', async () => {
|
||||||
@@ -146,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',
|
||||||
@@ -261,7 +277,7 @@ describe('app e2e — auth, origin et sessions', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('app e2e — rate limit du login', () => {
|
describe('app e2e · rate limit du login', () => {
|
||||||
it('mauvais token et bodies invalides → 401, puis 429 dès le 4e essai (backoff après 3 échecs consécutifs)', async () => {
|
it('mauvais token et bodies invalides → 401, puis 429 dès le 4e essai (backoff après 3 échecs consécutifs)', async () => {
|
||||||
const t = makeApp('ratelimit-failures');
|
const t = makeApp('ratelimit-failures');
|
||||||
const bad = await t.bundle.app.inject({ method: 'POST', url: '/api/v1/auth/login', payload: { token: 'arb_badbadbadbad' } });
|
const bad = await t.bundle.app.inject({ method: 'POST', url: '/api/v1/auth/login', payload: { token: 'arb_badbadbadbad' } });
|
||||||
@@ -293,7 +309,7 @@ describe('app e2e — rate limit du login', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('app e2e — découverte, resume & fork (P2)', () => {
|
describe('app e2e · découverte, resume & fork (P2)', () => {
|
||||||
let t: TestApp;
|
let t: TestApp;
|
||||||
let projectsDir: string;
|
let projectsDir: string;
|
||||||
let sessionsDir: string;
|
let sessionsDir: string;
|
||||||
@@ -353,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);
|
||||||
|
});
|
||||||
|
});
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user