From 8cce1dc1e4e3bda78638aa970efd372eb7e2ce5c Mon Sep 17 00:00:00 2001 From: Johan LEROY Date: Thu, 18 Jun 2026 14:16:53 +0200 Subject: [PATCH] =?UTF-8?q?feat:=20onglets=20R=C3=A9glages=20&=20Aide=20+?= =?UTF-8?q?=20ic=C3=B4ne=20Gitea?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Réglages : préférences (langue, notifications push + test), gestion complète des tokens d'accès (liste/création/révocation, garde anti lock-out sur le dernier token), URL Gitea configurable, infos serveur en lecture seule (port/bind/origines/VAPID + flags CLI). Aide : documentation bilingue EN/FR de toutes les fonctionnalités, avec recherche. Icône Gitea (lien externe) dans la nav (sidebar + MoreSheet mobile). Backend : routes /api/v1/auth/tokens (GET/POST/DELETE) + tokenId dans /me ; routes/settings.ts (GET/PATCH, allow-list stricte gitea_url, aucun secret exposé, URL validée http/https anti-XSS) ; AuthService.listTokens/revokeToken (transaction). Front : NavItem gère les liens externes, nav primaire/secondaire, store settings, vues SettingsView/HelpView. 236 tests verts (+15 nouveaux : auth-tokens, settings-routes). Co-Authored-By: Claude Opus 4.8 (1M context) --- packages/server/src/app.ts | 2 + packages/server/src/auth/service.ts | 53 ++- packages/server/src/routes/auth.ts | 47 ++- packages/server/src/routes/settings.ts | 67 ++++ packages/server/test/app.e2e.test.ts | 3 +- packages/server/test/auth-tokens.test.ts | 143 +++++++ packages/server/test/settings-routes.test.ts | 126 +++++++ packages/shared/src/api.ts | 46 +++ .../web/src/components/layout/AppShell.vue | 4 + .../web/src/components/layout/AppSidebar.vue | 17 +- .../src/components/layout/MobileTabBar.vue | 15 +- .../web/src/components/layout/MoreSheet.vue | 20 +- .../web/src/components/layout/NavItem.vue | 20 +- .../web/src/components/settings/ServerRow.vue | 33 ++ packages/web/src/components/ui/GiteaIcon.vue | 31 ++ packages/web/src/composables/useNav.ts | 27 +- packages/web/src/i18n/en.ts | 63 ++++ packages/web/src/i18n/fr.ts | 63 ++++ packages/web/src/router/index.ts | 2 + packages/web/src/stores/settings.ts | 34 ++ packages/web/src/views/HelpView.vue | 68 ++++ packages/web/src/views/SettingsView.vue | 257 +++++++++++++ packages/web/src/views/help-content.ts | 352 ++++++++++++++++++ 23 files changed, 1469 insertions(+), 24 deletions(-) create mode 100644 packages/server/src/routes/settings.ts create mode 100644 packages/server/test/auth-tokens.test.ts create mode 100644 packages/server/test/settings-routes.test.ts create mode 100644 packages/web/src/components/settings/ServerRow.vue create mode 100644 packages/web/src/components/ui/GiteaIcon.vue create mode 100644 packages/web/src/stores/settings.ts create mode 100644 packages/web/src/views/HelpView.vue create mode 100644 packages/web/src/views/SettingsView.vue create mode 100644 packages/web/src/views/help-content.ts diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts index 421613b..0f19eeb 100644 --- a/packages/server/src/app.ts +++ b/packages/server/src/app.ts @@ -19,6 +19,7 @@ import { registerRepoRoutes } from './routes/repos.js'; import { registerGroupRoutes } from './routes/groups.js'; import { registerWorktreeRoutes } from './routes/worktrees.js'; import { registerPushRoutes } from './routes/push.js'; +import { registerSettingsRoutes } from './routes/settings.js'; import { registerFsRoutes } from './routes/fs.js'; import { registerWsGateway } from './ws/gateway.js'; @@ -98,6 +99,7 @@ export function buildApp(config: Config, db: Db, serverVersion: string): AppBund registerGroupRoutes(app, groups); registerWorktreeRoutes(app, worktrees); registerPushRoutes(app, push); + registerSettingsRoutes(app, db, config, serverVersion, push); registerFsRoutes(app); // 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). diff --git a/packages/server/src/auth/service.ts b/packages/server/src/auth/service.ts index 197c030..bb31633 100644 --- a/packages/server/src/auth/service.ts +++ b/packages/server/src/auth/service.ts @@ -35,11 +35,60 @@ export class AuthService { } 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')}`; this.db .prepare('INSERT INTO auth_tokens (id, label, token_hash, created_at) VALUES (?, ?, ?, ?)') - .run(randomUUID(), label, sha256(raw), new Date().toISOString()); - return raw; + .run(id, label, sha256(raw), new Date().toISOString()); + 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 { diff --git a/packages/server/src/routes/auth.ts b/packages/server/src/routes/auth.ts index 0fc15fb..f42abf7 100644 --- a/packages/server/src/routes/auth.ts +++ b/packages/server/src/routes/auth.ts @@ -1,5 +1,12 @@ 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'; // Tailscale Serve / un reverse-proxy TLS posent x-forwarded-proto. On ne sert jamais @@ -41,7 +48,12 @@ export function registerAuthRoutes( }); 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); }); @@ -50,4 +62,35 @@ export function registerAuthRoutes( void reply.clearCookie(auth.cookieName, { path: '/', secure: isHttpsRequest(req) }); return reply.send({ ok: true }); }); + + // ---- Gestion des tokens d'accès (onglet Réglages) ---- + // Sous l'auth globale (preValidation). On ne renvoie jamais le hash ; la valeur en clair + // d'un nouveau token n'est exposée qu'une seule fois, à la création. + app.get('/api/v1/auth/tokens', async (req): Promise => { + 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 | 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); + 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); + if (result === 'not_found') { + return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No active token with this id' } }); + } + if (result === 'last') { + return reply.status(409).send({ error: { code: 'LAST_TOKEN', message: 'Cannot revoke the last active token' } }); + } + // 200 + corps JSON (pas 204) : le mini-client REST du front parse toujours la réponse. + return reply.send({ ok: true }); + }); } diff --git a/packages/server/src/routes/settings.ts b/packages/server/src/routes/settings.ts new file mode 100644 index 0000000..a669ef2 --- /dev/null +++ b/packages/server/src/routes/settings.ts @@ -0,0 +1,67 @@ +// 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, getSetting, setSetting } from '../db/index.js'; +import type { PushService } from '../core/push-service.js'; + +// Seule clé de `settings` modifiable via l'API. Les secrets ne figurent JAMAIS ici. +const GITEA_URL_KEY = 'gitea_url'; + +/** Valide/normalise une URL Gitea : http(s) uniquement (anti-XSS sur le href de l'icône). */ +function normalizeGiteaUrl(raw: string): string | null { + const trimmed = raw.trim(); + if (trimmed === '') return null; + let url: URL; + try { + url = new URL(trimmed); + } catch { + return null; + } + if (url.protocol !== 'http:' && url.protocol !== 'https:') return null; + return url.toString(); +} + +export function registerSettingsRoutes( + app: FastifyInstance, + db: Db, + config: Config, + serverVersion: string, + push: PushService, +): void { + // '' (effacé) est normalisé en null côté réponse. + const readGiteaUrl = (): string | null => getSetting(db, GITEA_URL_KEY) || null; + const serverInfo = (): ServerInfo => ({ + version: serverVersion, + port: config.port, + bind: config.bind, + allowedOrigins: config.allowedOrigins, + dataDir: config.dataDir, + vapidPublicKey: push.publicKey() || null, + vapidContact: config.vapidContact, + }); + const snapshot = (): SettingsResponse => ({ settings: { giteaUrl: readGiteaUrl() }, server: serverInfo() }); + + app.get('/api/v1/settings', async (): Promise => snapshot()); + + app.patch('/api/v1/settings', async (req, reply) => { + const body = (req.body as Partial | null) ?? {}; + if ('giteaUrl' in body) { + const v = body.giteaUrl; + if (v === null || v === '') { + setSetting(db, GITEA_URL_KEY, ''); // effacement + } else if (typeof v === 'string') { + const normalized = normalizeGiteaUrl(v); + if (!normalized) { + return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'giteaUrl must be a valid http(s) URL' } }); + } + setSetting(db, GITEA_URL_KEY, normalized); + } else { + return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'giteaUrl must be a string or null' } }); + } + } + return reply.send(snapshot()); + }); +} diff --git a/packages/server/test/app.e2e.test.ts b/packages/server/test/app.e2e.test.ts index d753010..939593e 100644 --- a/packages/server/test/app.e2e.test.ts +++ b/packages/server/test/app.e2e.test.ts @@ -127,7 +127,8 @@ describe('app e2e — auth, origin et sessions', () => { cookies: { arb_session: cookieValue }, }); 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 () => { diff --git a/packages/server/test/auth-tokens.test.ts b/packages/server/test/auth-tokens.test.ts new file mode 100644 index 0000000..a240aa1 --- /dev/null +++ b/packages/server/test/auth-tokens.test.ts @@ -0,0 +1,143 @@ +// Gestion des tokens d'accès via l'API REST (onglet Réglages) : create → list → revoke, +// flag « courant », jamais de hash exposé, garde anti lock-out sur le dernier token. +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { buildApp, type AppBundle } from '../src/app.js'; +import { openDb, type Db } from '../src/db/index.js'; +import type { Config } from '../src/config.js'; +import type { CreateTokenResponse, MeResponse, TokensListResponse } from '@arboretum/shared'; + +// Mêmes stubs que les autres tests de routes : pas de vrai claude ni de vrai PTY. +vi.mock('node:child_process', () => ({ execFileSync: () => '/usr/bin/claude\n' })); +vi.mock('@homebridge/node-pty-prebuilt-multiarch', () => { + class FakePty { + pid = 424242; + write = vi.fn(); + resize = vi.fn(); + pause = vi.fn(); + resume = vi.fn(); + kill = vi.fn(); + onData(): { dispose: () => void } { + return { dispose: () => {} }; + } + onExit(): { dispose: () => void } { + return { dispose: () => {} }; + } + } + return { default: { spawn: (): FakePty => new FakePty() } }; +}); + +process.env.ARBORETUM_LOG = 'silent'; + +let dir: string; +let bundle: AppBundle; +let db: Db; +let token: string; + +const auth = (): { authorization: string } => ({ authorization: `Bearer ${token}` }); + +beforeAll(() => { + dir = mkdtempSync(join(tmpdir(), 'arboretum-tokens-')); + const dbPath = join(dir, 'tokens.db'); + db = openDb(dbPath); + const config: Config = { + port: 7317, + bind: '127.0.0.1', + dbPath, + dataDir: dir, + allowedOrigins: [], + printToken: false, + claudeProjectsDir: join(dir, 'claude', 'projects'), + claudeSessionsDir: join(dir, 'claude', 'sessions'), + vapidContact: 'mailto:test@localhost', + }; + bundle = buildApp(config, db, '0.0.0-test'); + const t = bundle.auth.ensureBootstrapToken(); + if (!t) throw new Error('bootstrap token attendu sur une base vierge'); + token = t; +}); + +afterAll(async () => { + await bundle.app.close(); + db.close(); + rmSync(dir, { recursive: true, force: true }); +}); + +describe('routes de gestion des tokens', () => { + it('GET /auth/me expose le tokenId courant', async () => { + const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/me', headers: auth() }); + expect(res.statusCode).toBe(200); + const me = res.json() as MeResponse; + expect(typeof me.tokenId).toBe('string'); + expect(me.tokenId.length).toBeGreaterThan(0); + }); + + it('liste le token initial et le marque « courant », sans jamais exposer de hash', async () => { + const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/tokens', headers: auth() }); + expect(res.statusCode).toBe(200); + const body = res.json() as TokensListResponse; + expect(body.tokens).toHaveLength(1); + expect(body.tokens[0]?.label).toBe('initial'); + expect(body.tokens[0]?.current).toBe(true); + // aucune fuite de hash / valeur en clair + expect(JSON.stringify(body)).not.toMatch(/token_hash|tokenHash/); + }); + + it('crée un token (valeur en clair renvoyée une fois), puis utilisable pour s’authentifier', async () => { + const res = await bundle.app.inject({ + method: 'POST', + url: '/api/v1/auth/tokens', + headers: auth(), + payload: { label: 'laptop' }, + }); + expect(res.statusCode).toBe(201); + const created = res.json() as CreateTokenResponse; + expect(created.label).toBe('laptop'); + expect(created.token).toMatch(/^arb_[0-9a-f]{48}$/); + + // le nouveau token authentifie réellement + const me = await bundle.app.inject({ + method: 'GET', + url: '/api/v1/auth/me', + headers: { authorization: `Bearer ${created.token}` }, + }); + expect((me.json() as MeResponse).tokenLabel).toBe('laptop'); + }); + + it('rejette un label vide ou trop long (400)', async () => { + const empty = await bundle.app.inject({ method: 'POST', url: '/api/v1/auth/tokens', headers: auth(), payload: { label: ' ' } }); + expect(empty.statusCode).toBe(400); + const tooLong = await bundle.app.inject({ method: 'POST', url: '/api/v1/auth/tokens', headers: auth(), payload: { label: 'x'.repeat(65) } }); + expect(tooLong.statusCode).toBe(400); + }); + + it('révoque un token non courant (204), qui disparaît de la liste et n’authentifie plus', async () => { + const before = (await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/tokens', headers: auth() })).json() as TokensListResponse; + const victim = before.tokens.find((t) => !t.current); + expect(victim).toBeDefined(); + const del = await bundle.app.inject({ method: 'DELETE', url: `/api/v1/auth/tokens/${victim!.id}`, headers: auth() }); + expect(del.statusCode).toBe(200); + const after = (await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/tokens', headers: auth() })).json() as TokensListResponse; + expect(after.tokens.find((t) => t.id === victim!.id)).toBeUndefined(); + }); + + it('404 sur un id inconnu', async () => { + const res = await bundle.app.inject({ method: 'DELETE', url: '/api/v1/auth/tokens/nope-xyz', headers: auth() }); + expect(res.statusCode).toBe(404); + }); + + it('409 LAST_TOKEN : refuse de révoquer le dernier token actif', async () => { + const list = (await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/tokens', headers: auth() })).json() as TokensListResponse; + expect(list.tokens).toHaveLength(1); // seul le token courant subsiste + const res = await bundle.app.inject({ method: 'DELETE', url: `/api/v1/auth/tokens/${list.tokens[0]!.id}`, headers: auth() }); + expect(res.statusCode).toBe(409); + expect(res.json()).toMatchObject({ error: { code: 'LAST_TOKEN' } }); + }); + + it('sans authentification → 401', async () => { + const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/auth/tokens' }); + expect(res.statusCode).toBe(401); + }); +}); diff --git a/packages/server/test/settings-routes.test.ts b/packages/server/test/settings-routes.test.ts new file mode 100644 index 0000000..9580b08 --- /dev/null +++ b/packages/server/test/settings-routes.test.ts @@ -0,0 +1,126 @@ +// Routes Réglages : GET expose la config non sensible (jamais les secrets), PATCH n'écrit que +// l'allow-list et valide l'URL Gitea (http/https only, anti-XSS). +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { buildApp, type AppBundle } from '../src/app.js'; +import { getSetting, openDb, type Db } from '../src/db/index.js'; +import type { Config } from '../src/config.js'; +import type { SettingsResponse } from '@arboretum/shared'; + +vi.mock('node:child_process', () => ({ execFileSync: () => '/usr/bin/claude\n' })); +vi.mock('@homebridge/node-pty-prebuilt-multiarch', () => { + class FakePty { + pid = 424242; + write = vi.fn(); + resize = vi.fn(); + pause = vi.fn(); + resume = vi.fn(); + kill = vi.fn(); + onData(): { dispose: () => void } { + return { dispose: () => {} }; + } + onExit(): { dispose: () => void } { + return { dispose: () => {} }; + } + } + return { default: { spawn: (): FakePty => new FakePty() } }; +}); + +process.env.ARBORETUM_LOG = 'silent'; + +let dir: string; +let bundle: AppBundle; +let db: Db; +let token: string; + +const auth = (): { authorization: string } => ({ authorization: `Bearer ${token}` }); + +beforeAll(() => { + dir = mkdtempSync(join(tmpdir(), 'arboretum-settings-')); + const dbPath = join(dir, 'settings.db'); + db = openDb(dbPath); + const config: Config = { + port: 9999, + bind: '127.0.0.1', + dbPath, + dataDir: dir, + allowedOrigins: ['https://host.tailnet.ts.net'], + printToken: false, + claudeProjectsDir: join(dir, 'claude', 'projects'), + claudeSessionsDir: join(dir, 'claude', 'sessions'), + vapidContact: 'mailto:test@localhost', + }; + bundle = buildApp(config, db, '1.2.3-test'); + const t = bundle.auth.ensureBootstrapToken(); + if (!t) throw new Error('bootstrap token attendu'); + token = t; +}); + +afterAll(async () => { + await bundle.app.close(); + db.close(); + rmSync(dir, { recursive: true, force: true }); +}); + +describe('GET /api/v1/settings', () => { + it('renvoie la config serveur non sensible et giteaUrl null par défaut', async () => { + const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/settings', headers: auth() }); + expect(res.statusCode).toBe(200); + const body = res.json() as SettingsResponse; + expect(body.server.version).toBe('1.2.3-test'); + expect(body.server.port).toBe(9999); + expect(body.server.bind).toBe('127.0.0.1'); + expect(body.server.allowedOrigins).toEqual(['https://host.tailnet.ts.net']); + expect(body.server.vapidPublicKey).toBeTruthy(); // clé publique = sûre à exposer + expect(body.settings.giteaUrl).toBeNull(); + }); + + it('n’expose AUCUN secret (server_secret, clé privée VAPID)', async () => { + const res = await bundle.app.inject({ method: 'GET', url: '/api/v1/settings', headers: auth() }); + const raw = res.body; + const secret = getSetting(db, 'server_secret'); + const vapidPrivate = getSetting(db, 'vapid_private'); + expect(secret).toBeTruthy(); + expect(raw).not.toContain(secret as string); + expect(raw).not.toContain(vapidPrivate as string); + expect(raw).not.toMatch(/server_secret|vapid_private|privateKey/); + }); +}); + +describe('PATCH /api/v1/settings', () => { + it('enregistre une URL Gitea valide et la renvoie', async () => { + const res = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { giteaUrl: 'https://git.lidge.fr' } }); + expect(res.statusCode).toBe(200); + expect((res.json() as SettingsResponse).settings.giteaUrl).toBe('https://git.lidge.fr/'); + // persisté + const get = await bundle.app.inject({ method: 'GET', url: '/api/v1/settings', headers: auth() }); + expect((get.json() as SettingsResponse).settings.giteaUrl).toBe('https://git.lidge.fr/'); + }); + + it('efface l’URL avec null ou chaîne vide', async () => { + await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { giteaUrl: 'https://git.lidge.fr' } }); + const res = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { giteaUrl: null } }); + expect((res.json() as SettingsResponse).settings.giteaUrl).toBeNull(); + }); + + it('rejette une URL non http(s) — anti-XSS (400)', async () => { + const res = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { giteaUrl: 'javascript:alert(1)' } }); + expect(res.statusCode).toBe(400); + const notUrl = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { giteaUrl: 'pas une url' } }); + expect(notUrl.statusCode).toBe(400); + }); + + it('ignore toute clé hors allow-list (ne touche pas aux secrets)', async () => { + const before = getSetting(db, 'server_secret'); + await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { server_secret: 'pwned', vapid_private: 'pwned' } }); + expect(getSetting(db, 'server_secret')).toBe(before); // inchangé + expect(getSetting(db, 'vapid_private')).not.toBe('pwned'); + }); + + it('sans authentification → 401', async () => { + const res = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', payload: { giteaUrl: 'https://x.example' } }); + expect(res.statusCode).toBe(401); + }); +}); diff --git a/packages/shared/src/api.ts b/packages/shared/src/api.ts index 2f39dea..29b6771 100644 --- a/packages/shared/src/api.ts +++ b/packages/shared/src/api.ts @@ -14,10 +14,34 @@ export interface LoginResponse { } export interface MeResponse { ok: true; + /** id du token de la session courante — sert à marquer « courant » dans la liste des tokens. */ + tokenId: string; tokenLabel: string; serverVersion: string; } +// ---- Gestion des tokens d'accès (onglet Réglages) ---- +export interface TokenInfo { + id: string; + label: string; + createdAt: string; + lastUsedAt: string | null; + /** true pour le token de la session courante. */ + current: boolean; +} +export interface TokensListResponse { + tokens: TokenInfo[]; +} +export interface CreateTokenRequest { + label: string; +} +export interface CreateTokenResponse { + id: string; + label: string; + /** valeur en clair — affichée une seule fois, jamais re-récupérable. */ + token: string; +} + export interface CreateSessionRequest { cwd: string; /** binaire à lancer — défaut "claude" ; "bash" sert aux tests d'acceptation sans quota */ @@ -146,3 +170,25 @@ export interface PushSubscribeRequest { export interface PushUnsubscribeRequest { endpoint: string; } + +// ---- Réglages & info serveur (onglet Réglages) ---- +/** Config runtime non sensible du daemon — lecture seule (changée via flags CLI + redémarrage). */ +export interface ServerInfo { + version: string; + port: number; + bind: string; + allowedOrigins: string[]; + dataDir: string; + /** clé publique VAPID (sûre à exposer) ; null si push indisponible. */ + vapidPublicKey: string | null; + vapidContact: string; +} +export interface SettingsResponse { + /** réglages modifiables à chaud (allow-list serveur — jamais les secrets). */ + settings: { giteaUrl: string | null }; + server: ServerInfo; +} +export interface UpdateSettingsRequest { + /** URL de l'instance Gitea (http/https) ; null ou '' pour effacer. */ + giteaUrl?: string | null; +} diff --git a/packages/web/src/components/layout/AppShell.vue b/packages/web/src/components/layout/AppShell.vue index 0b94f25..4ad1c5c 100644 --- a/packages/web/src/components/layout/AppShell.vue +++ b/packages/web/src/components/layout/AppShell.vue @@ -23,6 +23,7 @@ import { onMounted, onUnmounted } from 'vue'; import { useSessionsStore } from '../../stores/sessions'; import { useWorktreesStore } from '../../stores/worktrees'; import { useGroupsStore } from '../../stores/groups'; +import { useSettingsStore } from '../../stores/settings'; import AppSidebar from './AppSidebar.vue'; import MobileTabBar from './MobileTabBar.vue'; @@ -31,11 +32,14 @@ defineProps<{ fullbleed?: boolean }>(); const sessions = useSessionsStore(); const worktrees = useWorktreesStore(); const groups = useGroupsStore(); +const settings = useSettingsStore(); onMounted(() => { void worktrees.fetchAll(); void sessions.fetchSessions(); void groups.fetchGroups(); + void settings.fetch(); // alimente l'icône de nav Gitea et la vue Réglages + worktrees.startRealtime(); sessions.startRealtime(); groups.startRealtime(); diff --git a/packages/web/src/components/layout/AppSidebar.vue b/packages/web/src/components/layout/AppSidebar.vue index e816ae8..2389592 100644 --- a/packages/web/src/components/layout/AppSidebar.vue +++ b/packages/web/src/components/layout/AppSidebar.vue @@ -15,7 +15,7 @@ +
@@ -40,6 +53,6 @@ import NavItem from './NavItem.vue'; import AppShellFooter from './AppShellFooter.vue'; const { t } = useI18n(); -const { items, isActive } = useNav(); +const { primary, secondary, isActive } = useNav(); const palette = useCommandPalette(); diff --git a/packages/web/src/components/layout/MobileTabBar.vue b/packages/web/src/components/layout/MobileTabBar.vue index 52da183..256d238 100644 --- a/packages/web/src/components/layout/MobileTabBar.vue +++ b/packages/web/src/components/layout/MobileTabBar.vue @@ -4,7 +4,7 @@ style="padding-bottom: env(safe-area-inset-bottom)" > - - {{ t('nav.settings') }} + + {{ t('nav.more') }} diff --git a/packages/web/src/components/layout/MoreSheet.vue b/packages/web/src/components/layout/MoreSheet.vue index 74b0cf6..1c67d72 100644 --- a/packages/web/src/components/layout/MoreSheet.vue +++ b/packages/web/src/components/layout/MoreSheet.vue @@ -7,7 +7,22 @@ style="padding-bottom: calc(1rem + env(safe-area-inset-bottom))" >
- + +
+ +
{{ t('common.close') }}
@@ -16,9 +31,12 @@ diff --git a/packages/web/src/components/layout/NavItem.vue b/packages/web/src/components/layout/NavItem.vue index 98f9889..bf683ca 100644 --- a/packages/web/src/components/layout/NavItem.vue +++ b/packages/web/src/components/layout/NavItem.vue @@ -1,7 +1,12 @@ diff --git a/packages/web/src/components/ui/GiteaIcon.vue b/packages/web/src/components/ui/GiteaIcon.vue new file mode 100644 index 0000000..d2b941e --- /dev/null +++ b/packages/web/src/components/ui/GiteaIcon.vue @@ -0,0 +1,31 @@ + + + diff --git a/packages/web/src/composables/useNav.ts b/packages/web/src/composables/useNav.ts index 1604422..d32d8fd 100644 --- a/packages/web/src/composables/useNav.ts +++ b/packages/web/src/composables/useNav.ts @@ -1,12 +1,17 @@ import { computed, type Component } from 'vue'; import { useRoute, type RouteLocationRaw } from 'vue-router'; import { useI18n } from 'vue-i18n'; -import { GitBranch, TerminalSquare, Boxes } from '@lucide/vue'; +import { Boxes, GitBranch, LifeBuoy, Settings, TerminalSquare } from '@lucide/vue'; import { useSessionsStore } from '../stores/sessions'; +import { useSettingsStore } from '../stores/settings'; +import GiteaIcon from '../components/ui/GiteaIcon.vue'; export interface NavEntry { key: string; - to: RouteLocationRaw; + /** route interne (exclusif avec `href`). */ + to?: RouteLocationRaw; + /** lien externe ouvert dans un nouvel onglet (exclusif avec `to`). */ + href?: string; icon: Component; label: string; match: string[]; // noms de routes considérés actifs pour cet item @@ -18,19 +23,33 @@ export function useNav() { const { t } = useI18n(); const route = useRoute(); const sessions = useSessionsStore(); + const settings = useSettingsStore(); // sessions vivantes bloquées sur un dialogue (le cœur de la supervision mobile). const waitingCount = computed( () => sessions.sessions.filter((s) => s.live && s.activity === 'waiting').length, ); - const items = computed(() => [ + // Onglets principaux : barre du bas mobile + haut de sidebar. + const primary = computed(() => [ { key: 'worktrees', to: { name: 'dashboard' }, icon: GitBranch, label: t('nav.worktrees'), match: ['dashboard'], badge: 0 }, { key: 'sessions', to: { name: 'sessions' }, icon: TerminalSquare, label: t('nav.sessions'), match: ['sessions', 'session'], badge: waitingCount.value }, { key: 'groups', to: { name: 'groups' }, icon: Boxes, label: t('nav.groups'), match: ['groups', 'group'], badge: 0 }, ]); + // Onglets secondaires : réglages, aide, et lien externe Gitea (uniquement si l'URL est configurée). + const secondary = computed(() => { + const items: NavEntry[] = [ + { key: 'settings', to: { name: 'settings' }, icon: Settings, label: t('nav.settings'), match: ['settings'], badge: 0 }, + { key: 'help', to: { name: 'help' }, icon: LifeBuoy, label: t('nav.help'), match: ['help'], badge: 0 }, + ]; + if (settings.giteaUrl) { + items.push({ key: 'gitea', href: settings.giteaUrl, icon: GiteaIcon, label: t('nav.gitea'), match: [], badge: 0 }); + } + return items; + }); + const isActive = (match: string[]): boolean => match.includes(String(route.name)); - return { items, isActive, waitingCount }; + return { primary, secondary, isActive, waitingCount }; } diff --git a/packages/web/src/i18n/en.ts b/packages/web/src/i18n/en.ts index 1d8a079..7b2a20b 100644 --- a/packages/web/src/i18n/en.ts +++ b/packages/web/src/i18n/en.ts @@ -174,6 +174,9 @@ export default { sessions: 'Sessions', groups: 'Groups', settings: 'Settings', + help: 'Help', + more: 'More', + gitea: 'Open Gitea', waiting: 'waiting', }, controls: { @@ -292,4 +295,64 @@ export default { count: 'no session waiting | 1 session waiting | {n} sessions waiting', empty: 'Nothing waiting', }, + settings: { + title: 'Settings', + // Préférences + preferences: 'Preferences', + preferencesHint: 'These apply to this browser only.', + language: 'Language', + notifications: 'Notifications', + notificationsEnabled: 'Enabled — you will be notified when a session needs input.', + notificationsDisabled: 'Disabled.', + enableNotifications: 'Enable notifications', + disableNotifications: 'Disable notifications', + testNotification: 'Send a test', + testSent: 'Test notification sent', + pushUnsupported: 'Push needs HTTPS (e.g. Tailscale Serve); on iOS, install the app to your home screen first.', + // Accès & sécurité + security: 'Access & security', + securityHint: 'Tokens grant full access to this server. Create one per device and revoke any you no longer use.', + tokens: 'Access tokens', + newTokenLabel: 'Label', + newTokenPlaceholder: 'e.g. phone, laptop', + createToken: 'Create token', + tokenCreated: 'Token created', + copyTokenHint: 'Copy this token now — for security it will never be shown again.', + copy: 'Copy', + copied: 'Copied', + current: 'current', + created: 'Created {date}', + lastUsed: 'last used {date}', + neverUsed: 'never used', + revoke: 'Revoke', + confirmRevoke: 'Confirm revoke', + tokenRevoked: 'Token revoked', + lastTokenError: 'You cannot revoke the last active token — create another one first.', + // Intégrations + integrations: 'Integrations', + gitea: 'Gitea', + giteaUrlLabel: 'Gitea instance URL', + giteaUrlPlaceholder: 'https://git.example.com', + giteaUrlHint: 'Adds a shortcut icon to the navigation. Leave empty to hide it.', + save: 'Save', + saved: 'Saved', + // Serveur (lecture seule) + server: 'Server', + serverHint: 'Set at startup via CLI flags — changing them requires restarting the daemon.', + version: 'Version', + port: 'Port', + bind: 'Bind address', + allowedOrigins: 'Allowed origins', + dataDir: 'Data directory', + vapidPublicKey: 'VAPID public key', + vapidContact: 'VAPID contact', + none: 'none', + flagHint: 'CLI flag: {flag}', + }, + help: { + title: 'Help', + intro: 'Everything Arboretum can do, and how to use it.', + searchPlaceholder: 'Search help…', + noMatch: 'No matching topic', + }, }; diff --git a/packages/web/src/i18n/fr.ts b/packages/web/src/i18n/fr.ts index 6f85a48..e7f419a 100644 --- a/packages/web/src/i18n/fr.ts +++ b/packages/web/src/i18n/fr.ts @@ -177,6 +177,9 @@ const fr: typeof en = { sessions: 'Sessions', groups: 'Groupes', settings: 'Réglages', + help: 'Aide', + more: 'Plus', + gitea: 'Ouvrir Gitea', waiting: 'en attente', }, controls: { @@ -295,6 +298,66 @@ const fr: typeof en = { count: 'aucune session en attente | 1 session en attente | {n} sessions en attente', empty: 'Rien à traiter', }, + settings: { + title: 'Réglages', + // Préférences + preferences: 'Préférences', + preferencesHint: 'Ces réglages ne s’appliquent qu’à ce navigateur.', + language: 'Langue', + notifications: 'Notifications', + notificationsEnabled: 'Activées — vous serez notifié lorsqu’une session attend une réponse.', + notificationsDisabled: 'Désactivées.', + enableNotifications: 'Activer les notifications', + disableNotifications: 'Désactiver les notifications', + testNotification: 'Envoyer un test', + testSent: 'Notification de test envoyée', + pushUnsupported: 'Le push exige HTTPS (ex. Tailscale Serve) ; sur iOS, installez d’abord l’app sur l’écran d’accueil.', + // Accès & sécurité + security: 'Accès & sécurité', + securityHint: 'Les jetons donnent un accès complet à ce serveur. Créez-en un par appareil et révoquez ceux que vous n’utilisez plus.', + tokens: 'Jetons d’accès', + newTokenLabel: 'Libellé', + newTokenPlaceholder: 'ex. téléphone, portable', + createToken: 'Créer un jeton', + tokenCreated: 'Jeton créé', + copyTokenHint: 'Copiez ce jeton maintenant — par sécurité il ne sera plus jamais affiché.', + copy: 'Copier', + copied: 'Copié', + current: 'courant', + created: 'Créé le {date}', + lastUsed: 'utilisé le {date}', + neverUsed: 'jamais utilisé', + revoke: 'Révoquer', + confirmRevoke: 'Confirmer la révocation', + tokenRevoked: 'Jeton révoqué', + lastTokenError: 'Impossible de révoquer le dernier jeton actif — créez-en un autre d’abord.', + // Intégrations + integrations: 'Intégrations', + gitea: 'Gitea', + giteaUrlLabel: 'URL de l’instance Gitea', + giteaUrlPlaceholder: 'https://git.exemple.com', + giteaUrlHint: 'Ajoute une icône de raccourci dans la navigation. Laissez vide pour la masquer.', + save: 'Enregistrer', + saved: 'Enregistré', + // Serveur (lecture seule) + server: 'Serveur', + serverHint: 'Définis au démarrage via des flags CLI — les modifier nécessite de redémarrer le daemon.', + version: 'Version', + port: 'Port', + bind: 'Adresse de liaison', + allowedOrigins: 'Origines autorisées', + dataDir: 'Répertoire de données', + vapidPublicKey: 'Clé publique VAPID', + vapidContact: 'Contact VAPID', + none: 'aucune', + flagHint: 'Flag CLI : {flag}', + }, + help: { + title: 'Aide', + intro: 'Tout ce qu’Arboretum sait faire, et comment l’utiliser.', + searchPlaceholder: 'Rechercher dans l’aide…', + noMatch: 'Aucun sujet correspondant', + }, }; export default fr; diff --git a/packages/web/src/router/index.ts b/packages/web/src/router/index.ts index 886cae7..5d0db4a 100644 --- a/packages/web/src/router/index.ts +++ b/packages/web/src/router/index.ts @@ -18,6 +18,8 @@ export const router = createRouter({ { path: '/sessions/:id', name: 'session', component: () => import('../views/SessionView.vue'), meta: { layout: 'fullbleed' } }, { path: '/groups', name: 'groups', component: () => import('../views/GroupsListView.vue'), meta: { layout: 'shell' } }, { path: '/groups/:id', name: 'group', component: () => import('../views/GroupView.vue'), meta: { layout: 'shell' } }, + { path: '/settings', name: 'settings', component: () => import('../views/SettingsView.vue'), meta: { layout: 'shell' } }, + { path: '/help', name: 'help', component: () => import('../views/HelpView.vue'), meta: { layout: 'shell' } }, { path: '/:pathMatch(.*)*', redirect: '/' }, ], }); diff --git a/packages/web/src/stores/settings.ts b/packages/web/src/stores/settings.ts new file mode 100644 index 0000000..f71a097 --- /dev/null +++ b/packages/web/src/stores/settings.ts @@ -0,0 +1,34 @@ +import { defineStore } from 'pinia'; +import { ref } from 'vue'; +import type { ServerInfo, SettingsResponse, UpdateSettingsRequest } from '@arboretum/shared'; +import { api } from '../lib/api'; + +// Réglages serveur + intégrations. `giteaUrl` alimente l'item de nav Gitea (affiché si défini). +// Les préférences purement client (langue) restent gérées par l'i18n/localStorage. +export const useSettingsStore = defineStore('settings', () => { + const server = ref(null); + const giteaUrl = ref(null); + const loaded = ref(false); + const saving = ref(false); + + function apply(res: SettingsResponse): void { + server.value = res.server; + giteaUrl.value = res.settings.giteaUrl; + loaded.value = true; + } + + async function fetch(): Promise { + apply(await api.get('/api/v1/settings')); + } + + async function save(patch: UpdateSettingsRequest): Promise { + saving.value = true; + try { + apply(await api.patch('/api/v1/settings', patch)); + } finally { + saving.value = false; + } + } + + return { server, giteaUrl, loaded, saving, fetch, save }; +}); diff --git a/packages/web/src/views/HelpView.vue b/packages/web/src/views/HelpView.vue new file mode 100644 index 0000000..dd8b2fc --- /dev/null +++ b/packages/web/src/views/HelpView.vue @@ -0,0 +1,68 @@ + + + diff --git a/packages/web/src/views/SettingsView.vue b/packages/web/src/views/SettingsView.vue new file mode 100644 index 0000000..db23920 --- /dev/null +++ b/packages/web/src/views/SettingsView.vue @@ -0,0 +1,257 @@ + + + diff --git a/packages/web/src/views/help-content.ts b/packages/web/src/views/help-content.ts new file mode 100644 index 0000000..0fbb643 --- /dev/null +++ b/packages/web/src/views/help-content.ts @@ -0,0 +1,352 @@ +// Contenu de l'onglet Aide, bilingue. Texte long-format → gardé hors des fichiers i18n +// (en.ts/fr.ts) pour ne pas les alourdir. HelpView mappe chaque `id` vers une icône Lucide. +import type { AppLocale } from '../i18n'; + +export interface HelpItem { + title: string; + body: string; +} +export interface HelpSection { + id: string; + title: string; + blurb: string; + items: HelpItem[]; +} + +const en: HelpSection[] = [ + { + id: 'gettingStarted', + title: 'Getting started & access', + blurb: + 'Arboretum is a single daemon that serves this dashboard to drive your git worktrees and the Claude Code sessions running on them, from any device.', + items: [ + { + title: 'Sign in with a token', + body: 'On first start the daemon prints a one-time access token. Paste it on the login screen. You can create extra tokens (one per device) and revoke old ones in Settings → Access & security.', + }, + { + title: 'Remote access via Tailscale Serve', + body: 'The daemon binds to 127.0.0.1. To reach it from your phone, run tailscale serve --bg 7317 and start Arboretum with --allow-origin https://..ts.net. The HTTPS that Tailscale provides is also what makes Web Push work.', + }, + { + title: 'Install as an app (PWA)', + body: 'On mobile, open Arboretum and choose Add to Home Screen. On iOS this install step is required before notifications can work.', + }, + ], + }, + { + id: 'worktrees', + title: 'Repositories & worktrees', + blurb: 'Register your git repos, then spin up an isolated worktree per branch — each can auto-start a session.', + items: [ + { + title: 'Add a repository', + body: 'On the Worktrees page, type or browse to the absolute path of a git repo and add it. Per-repo post-create hooks (e.g. npm ci) run automatically on new worktrees.', + }, + { + title: 'Create a worktree', + body: 'In a repo section, click New worktree, enter a branch (optionally create it), and optionally start a claude or bash session in it. Hooks run automatically.', + }, + { + title: 'Read worktree state', + body: 'Each card shows the branch, ahead/behind counts, dirty file count and flags (main, locked, prunable), plus the live state of any linked session.', + }, + { + title: 'Delete & prune', + body: 'Delete a worktree from its card (force-delete if dirty or locked), or prune all orphaned worktrees at the repo level.', + }, + ], + }, + { + id: 'sessions', + title: 'Sessions & the web terminal', + blurb: 'Run, observe, resume and answer Claude Code (or bash) sessions in a full xterm terminal, right in the browser.', + items: [ + { + title: 'Start a session', + body: 'On the Sessions page, set a working directory and a command (claude or bash) and launch. Open it to get an interactive terminal.', + }, + { + title: 'Discovered sessions', + body: 'Sessions you start in your own terminal are detected automatically and tagged as discovered. Observe them read-only, or resume/fork them once stopped.', + }, + { + title: 'Resume & fork', + body: 'Resume restarts a stopped session in its original working directory, with full scrollback replayed. Fork creates a fresh independent copy with the same command and cwd.', + }, + { + title: 'Observe vs interact', + body: 'Anyone opening a live session can type; open it as an observer for read-only monitoring that never slows the session down.', + }, + { + title: 'Fine-grained state', + body: 'Managed Claude sessions report waiting / busy / idle in real time. Waiting sessions are surfaced first and can trigger notifications.', + }, + { + title: 'Kill a session', + body: 'Kill a live session from its row (confirm to avoid accidents); it receives SIGTERM, then SIGKILL after a short grace delay.', + }, + ], + }, + { + id: 'mobile', + title: 'Mobile supervision', + blurb: 'Keep sessions moving from your phone, without opening a terminal.', + items: [ + { + title: 'Needs attention', + body: 'A banner at the top of the dashboard lists every session blocked on a dialog, with inline answer buttons.', + }, + { + title: 'Answer dialogs', + body: 'When Claude asks for trust, a permission or a choice, pick an option (or Deny) right from the card — no terminal needed.', + }, + { + title: 'Web Push notifications', + body: 'Enable notifications in Settings (or the footer bell). You get a push when a session starts waiting; tap it to answer. Requires HTTPS; on iOS, install the app first.', + }, + ], + }, + { + id: 'groups', + title: 'Work groups', + blurb: 'Bundle related repos (API, web, shared lib…) and operate on them together.', + items: [ + { + title: 'Create a group', + body: 'On the Groups page, name a group and pick its repos. Membership is lightweight and editable anytime.', + }, + { + title: 'List vs terminal grid', + body: 'A group view shows all its repos worktrees and sessions as a list, or switch to the terminal grid to watch several live sessions side by side.', + }, + { + title: 'Cross-repo feature', + body: 'Create the same worktree (and an optional session) across every repo of the group in one action; partial failures can be retried per repo.', + }, + ], + }, + { + id: 'productivity', + title: 'Productivity', + blurb: 'Find anything fast and tailor each list.', + items: [ + { + title: 'Command palette', + body: 'Press ⌘K (or Ctrl+K) to fuzzy-jump to any repo, worktree, session or group, or to run a quick action.', + }, + { + title: 'Sort, filter & search', + body: 'Every list has a toolbar to sort, filter (state, command, source, flags…) and search. Your choices persist in the URL, so links are shareable.', + }, + { + title: 'Pagination', + body: 'Long lists are paginated with a configurable page size; choose All to show everything at once.', + }, + { + title: 'Language', + body: 'Switch the interface between English and French anytime, from Settings or the footer.', + }, + ], + }, + { + id: 'settings', + title: 'Settings & security', + blurb: 'Configure the app and manage who can reach the daemon.', + items: [ + { + title: 'Notifications', + body: 'Enable or disable Web Push and send a test notification from Settings → Preferences.', + }, + { + title: 'Access tokens', + body: 'Create a token per device and revoke any you no longer trust. A new token value is shown only once — copy it immediately. The last active token cannot be revoked, to avoid locking yourself out.', + }, + { + title: 'Server info', + body: 'Settings → Server shows the running version and the startup configuration (port, bind, allowed origins, data directory, VAPID). These are set via CLI flags and need a daemon restart to change.', + }, + ], + }, + { + id: 'integrations', + title: 'Integrations', + blurb: 'Shortcuts to the tools around your repos.', + items: [ + { + title: 'Gitea', + body: 'Set your Gitea instance URL in Settings → Integrations to add a one-click Gitea icon to the navigation. Leave it empty to hide the icon.', + }, + ], + }, +]; + +const fr: HelpSection[] = [ + { + id: 'gettingStarted', + title: 'Prise en main & accès', + blurb: + 'Arboretum est un daemon unique qui sert ce dashboard pour piloter vos worktrees git et les sessions Claude Code qui tournent dessus, depuis n’importe quel appareil.', + items: [ + { + title: 'Se connecter avec un jeton', + body: 'Au premier démarrage, le daemon affiche un jeton d’accès à usage unique. Collez-le sur l’écran de connexion. Vous pouvez créer des jetons supplémentaires (un par appareil) et révoquer les anciens dans Réglages → Accès & sécurité.', + }, + { + title: 'Accès distant via Tailscale Serve', + body: 'Le daemon écoute sur 127.0.0.1. Pour y accéder depuis votre téléphone, lancez tailscale serve --bg 7317 et démarrez Arboretum avec --allow-origin https://..ts.net. Le HTTPS fourni par Tailscale est aussi ce qui permet au Web Push de fonctionner.', + }, + { + title: 'Installer comme une app (PWA)', + body: 'Sur mobile, ouvrez Arboretum et choisissez Ajouter à l’écran d’accueil. Sur iOS, cette installation est requise avant que les notifications puissent fonctionner.', + }, + ], + }, + { + id: 'worktrees', + title: 'Dépôts & worktrees', + blurb: 'Enregistrez vos dépôts git, puis créez un worktree isolé par branche — chacun peut démarrer une session automatiquement.', + items: [ + { + title: 'Ajouter un dépôt', + body: 'Sur la page Worktrees, saisissez (ou parcourez) le chemin absolu d’un dépôt git et ajoutez-le. Les hooks post-création par dépôt (ex. npm ci) s’exécutent automatiquement sur les nouveaux worktrees.', + }, + { + title: 'Créer un worktree', + body: 'Dans une section de dépôt, cliquez sur Nouveau worktree, saisissez une branche (à créer éventuellement) et démarrez si besoin une session claude ou bash. Les hooks s’exécutent automatiquement.', + }, + { + title: 'Lire l’état d’un worktree', + body: 'Chaque carte affiche la branche, l’avance/le retard, le nombre de fichiers modifiés et des indicateurs (main, verrouillé, élagable), ainsi que l’état en direct de la session liée.', + }, + { + title: 'Supprimer & élaguer', + body: 'Supprimez un worktree depuis sa carte (suppression forcée s’il est sale ou verrouillé), ou élaguez tous les worktrees orphelins au niveau du dépôt.', + }, + ], + }, + { + id: 'sessions', + title: 'Sessions & terminal web', + blurb: 'Lancez, observez, reprenez et répondez aux sessions Claude Code (ou bash) dans un vrai terminal xterm, directement dans le navigateur.', + items: [ + { + title: 'Démarrer une session', + body: 'Sur la page Sessions, indiquez un répertoire de travail et une commande (claude ou bash) puis lancez. Ouvrez-la pour obtenir un terminal interactif.', + }, + { + title: 'Sessions découvertes', + body: 'Les sessions lancées dans votre propre terminal sont détectées automatiquement et marquées « découvertes ». Observez-les en lecture seule, ou reprenez/forkez-les une fois arrêtées.', + }, + { + title: 'Reprendre & forker', + body: 'Reprendre relance une session arrêtée dans son répertoire d’origine, avec tout l’historique rejoué. Forker crée une copie indépendante neuve avec la même commande et le même cwd.', + }, + { + title: 'Observer ou interagir', + body: 'Quiconque ouvre une session vivante peut écrire ; ouvrez-la en observateur pour une supervision en lecture seule qui ne ralentit jamais la session.', + }, + { + title: 'États fins', + body: 'Les sessions Claude gérées rapportent en temps réel les états en attente / occupé / inactif. Les sessions en attente sont remontées en premier et peuvent déclencher des notifications.', + }, + { + title: 'Arrêter une session', + body: 'Arrêtez une session vivante depuis sa ligne (confirmation pour éviter les accidents) ; elle reçoit SIGTERM, puis SIGKILL après un court délai de grâce.', + }, + ], + }, + { + id: 'mobile', + title: 'Supervision mobile', + blurb: 'Faites avancer vos sessions depuis votre téléphone, sans ouvrir de terminal.', + items: [ + { + title: 'À traiter', + body: 'Une bannière en haut du dashboard liste toutes les sessions bloquées sur un dialogue, avec des boutons de réponse en ligne.', + }, + { + title: 'Répondre aux dialogues', + body: 'Quand Claude demande une confiance, une permission ou un choix, sélectionnez une option (ou Refuser) directement depuis la carte — sans terminal.', + }, + { + title: 'Notifications Web Push', + body: 'Activez les notifications dans Réglages (ou via la cloche du pied de page). Vous recevez un push quand une session passe en attente ; touchez-le pour répondre. Exige HTTPS ; sur iOS, installez d’abord l’app.', + }, + ], + }, + { + id: 'groups', + title: 'Groupes de travail', + blurb: 'Regroupez des dépôts liés (API, web, lib partagée…) et agissez dessus ensemble.', + items: [ + { + title: 'Créer un groupe', + body: 'Sur la page Groupes, nommez un groupe et choisissez ses dépôts. L’appartenance est légère et modifiable à tout moment.', + }, + { + title: 'Liste ou grille de terminaux', + body: 'La vue d’un groupe affiche les worktrees et sessions de tous ses dépôts en liste, ou basculez sur la grille de terminaux pour suivre plusieurs sessions vivantes côte à côte.', + }, + { + title: 'Feature cross-repo', + body: 'Créez le même worktree (et une session optionnelle) dans chaque dépôt du groupe en une seule action ; les échecs partiels sont rejouables dépôt par dépôt.', + }, + ], + }, + { + id: 'productivity', + title: 'Productivité', + blurb: 'Trouvez tout rapidement et adaptez chaque liste.', + items: [ + { + title: 'Palette de commandes', + body: 'Appuyez sur ⌘K (ou Ctrl+K) pour sauter en recherche floue vers n’importe quel dépôt, worktree, session ou groupe, ou lancer une action rapide.', + }, + { + title: 'Trier, filtrer & rechercher', + body: 'Chaque liste a une barre d’outils pour trier, filtrer (état, commande, source, indicateurs…) et rechercher. Vos choix persistent dans l’URL, donc les liens sont partageables.', + }, + { + title: 'Pagination', + body: 'Les longues listes sont paginées avec une taille de page configurable ; choisissez Tout pour afficher l’ensemble.', + }, + { + title: 'Langue', + body: 'Basculez l’interface entre l’anglais et le français à tout moment, depuis les Réglages ou le pied de page.', + }, + ], + }, + { + id: 'settings', + title: 'Réglages & sécurité', + blurb: 'Configurez l’application et gérez qui peut atteindre le daemon.', + items: [ + { + title: 'Notifications', + body: 'Activez ou désactivez le Web Push et envoyez une notification de test depuis Réglages → Préférences.', + }, + { + title: 'Jetons d’accès', + body: 'Créez un jeton par appareil et révoquez ceux en lesquels vous n’avez plus confiance. La valeur d’un nouveau jeton n’est affichée qu’une seule fois — copiez-la immédiatement. Le dernier jeton actif ne peut pas être révoqué, pour éviter de vous verrouiller dehors.', + }, + { + title: 'Infos serveur', + body: 'Réglages → Serveur affiche la version en cours et la configuration de démarrage (port, bind, origines autorisées, répertoire de données, VAPID). Ces valeurs se définissent via des flags CLI et nécessitent un redémarrage du daemon.', + }, + ], + }, + { + id: 'integrations', + title: 'Intégrations', + blurb: 'Des raccourcis vers les outils autour de vos dépôts.', + items: [ + { + title: 'Gitea', + body: 'Renseignez l’URL de votre instance Gitea dans Réglages → Intégrations pour ajouter une icône Gitea en un clic dans la navigation. Laissez vide pour masquer l’icône.', + }, + ], + }, +]; + +export const helpSections: Record = { en, fr };