feat: clean install (Gitea en dur, scan off) + durcissement sécurité entreprise
Gitea - lien « Code source » hardcodé (REPO_SOURCE_URL) vers le dépôt, toujours visible - retrait complet du réglage configurable (api.ts, route+store settings, SettingsView, i18n, help, tests) Découverte des dépôts - aucune racine de scan par défaut → pas de scan au premier démarrage (clean install) - corrige la découverte des dépôts à l'INTÉRIEUR d'une racine qui est elle-même un repo (depth 0 = conteneur de scan, on descend ; depth > 0 = feuille) Sécurité « enterprise-deployable » - en-têtes HTTP durcis (CSP, X-Frame-Options, nosniff, Referrer-Policy, HSTS conditionnel, no-store API), header Server retiré - permissions DB 0o600 / dossier de données 0o700 ; error handler sanitisé ; garde Content-Type sur les mutations - chiffrement au repos AES-256-GCM des secrets (server_secret, clé privée VAPID) via SecretBox - journal d'audit (migration #7) + endpoint /audit-logs + RGPD export/effacement + UI Réglages - SECURITY.md, docs/ENTERPRISE_DEPLOYMENT.md, sections README EN/FR, SBOM CycloneDX en CI CI - pack-smoke packe depuis le contexte du package (cd packages/server) au lieu de « npm pack -w » : corrige l'embarquement de @arboretum/shared dans le tarball Purge des données personnelles du dépôt public - suppression de spikes/s4-discovery/result.json, reformulation du VERDICT - chemin de test générique, anonymisation des 5 fixtures de dialogues
This commit is contained in:
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 };
|
||||
});
|
||||
}
|
||||
@@ -8,11 +8,13 @@ import type {
|
||||
TokensListResponse,
|
||||
} from '@arboretum/shared';
|
||||
import type { AuthService, LoginRateLimiter } from '../auth/service.js';
|
||||
import type { Db } from '../db/index.js';
|
||||
import { recordAudit } from '../core/audit-log.js';
|
||||
|
||||
// Tailscale Serve / un reverse-proxy TLS posent x-forwarded-proto. On ne sert jamais
|
||||
// en TLS direct : `secure` n'est posé que derrière un front HTTPS, jamais en localhost http
|
||||
// (sinon le navigateur refuserait le cookie sur http://127.0.0.1 et le login local casserait).
|
||||
function isHttpsRequest(req: FastifyRequest): boolean {
|
||||
export function isHttpsRequest(req: FastifyRequest): boolean {
|
||||
const xfp = req.headers['x-forwarded-proto'];
|
||||
const proto = (Array.isArray(xfp) ? xfp[0] : xfp)?.split(',')[0]?.trim();
|
||||
return proto === 'https';
|
||||
@@ -23,6 +25,7 @@ export function registerAuthRoutes(
|
||||
auth: AuthService,
|
||||
limiter: LoginRateLimiter,
|
||||
serverVersion: string,
|
||||
db: Db,
|
||||
): void {
|
||||
app.post('/api/v1/auth/login', { config: { public: true } }, async (req, reply) => {
|
||||
const wait = limiter.check();
|
||||
@@ -33,9 +36,11 @@ export function registerAuthRoutes(
|
||||
const ctx = typeof body?.token === 'string' ? auth.verifyRawToken(body.token) : null;
|
||||
if (!ctx) {
|
||||
limiter.recordFailure();
|
||||
recordAudit(db, { actor: 'anonymous', action: 'login.failure', result: 'denied' });
|
||||
return reply.status(401).send({ error: { code: 'BAD_TOKEN', message: 'Invalid token' } });
|
||||
}
|
||||
limiter.recordSuccess();
|
||||
recordAudit(db, { actor: ctx.tokenId, action: 'login.success' });
|
||||
void reply.setCookie(auth.cookieName, auth.issueCookie(ctx), {
|
||||
path: '/',
|
||||
httpOnly: true,
|
||||
@@ -78,18 +83,22 @@ export function registerAuthRoutes(
|
||||
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'label must be 1–64 characters' } });
|
||||
}
|
||||
const { id, token } = auth.createTokenRecord(label);
|
||||
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'token.create', resourceId: id, details: { label } });
|
||||
return reply.status(201).send({ id, label, token } satisfies CreateTokenResponse);
|
||||
});
|
||||
|
||||
app.delete('/api/v1/auth/tokens/:id', async (req, reply) => {
|
||||
const { id } = req.params as { id: string };
|
||||
const result = auth.revokeToken(id);
|
||||
const actor = req.authContext?.tokenId ?? 'unknown';
|
||||
if (result === 'not_found') {
|
||||
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No active token with this id' } });
|
||||
}
|
||||
if (result === 'last') {
|
||||
recordAudit(db, { actor, action: 'token.revoke', resourceId: id, result: 'denied', details: { reason: 'last_active_token' } });
|
||||
return reply.status(409).send({ error: { code: 'LAST_TOKEN', message: 'Cannot revoke the last active token' } });
|
||||
}
|
||||
recordAudit(db, { actor, action: 'token.revoke', resourceId: id });
|
||||
// 200 + corps JSON (pas 204) : le mini-client REST du front parse toujours la réponse.
|
||||
return reply.send({ ok: true });
|
||||
});
|
||||
|
||||
54
packages/server/src/routes/data.ts
Normal file
54
packages/server/src/routes/data.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
// RGPD (droits d'accès & d'effacement) : export et suppression des données rattachées au token
|
||||
// authentifié. Modèle mono-utilisateur → le détenteur du token EST le sujet des données. Sous l'auth
|
||||
// globale. La suppression se fait en deux temps (code de confirmation) pour éviter les clics accidentels.
|
||||
import { createHash } from 'node:crypto';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import type { DataExportResponse, DeleteMyDataRequest, DeleteMyDataResponse } from '@arboretum/shared';
|
||||
import type { Db } from '../db/index.js';
|
||||
import type { AuthService } from '../auth/service.js';
|
||||
import { readScanIntervalMin, readScanRoots } from '../core/scan-settings.js';
|
||||
import { recordAudit } from '../core/audit-log.js';
|
||||
|
||||
export function registerDataRoutes(app: FastifyInstance, db: Db, auth: AuthService): void {
|
||||
app.get('/api/v1/data/export', async (req): Promise<DataExportResponse> => {
|
||||
const current = req.authContext!.tokenId;
|
||||
const tokens = auth.listTokens().map((t) => ({ ...t, current: t.id === current }));
|
||||
const pushSubscriptions = db
|
||||
.prepare(
|
||||
'SELECT endpoint, user_agent AS userAgent, created_at AS createdAt, last_ok_at AS lastOkAt FROM push_subscriptions WHERE token_id = ?',
|
||||
)
|
||||
.all(current) as DataExportResponse['pushSubscriptions'];
|
||||
const sessions = db
|
||||
.prepare(
|
||||
'SELECT id, cwd, command, title, created_at AS createdAt, ended_at AS endedAt, exit_code AS exitCode FROM sessions ORDER BY created_at',
|
||||
)
|
||||
.all() as DataExportResponse['sessions'];
|
||||
return {
|
||||
exportedAt: new Date().toISOString(),
|
||||
tokens,
|
||||
pushSubscriptions,
|
||||
sessions,
|
||||
settings: { scanRoots: readScanRoots(db), scanIntervalMin: readScanIntervalMin(db) },
|
||||
};
|
||||
});
|
||||
|
||||
app.post('/api/v1/data/delete-my-data', async (req, reply) => {
|
||||
const current = req.authContext!.tokenId;
|
||||
// code déterministe lié au token (sans état serveur) : renvoyé au 1er appel, exigé au 2nd.
|
||||
const code = createHash('sha256').update(`delete:${current}`).digest('hex').slice(0, 12);
|
||||
const body = (req.body as DeleteMyDataRequest | null) ?? {};
|
||||
const subsCount = (db.prepare('SELECT COUNT(*) AS n FROM push_subscriptions WHERE token_id = ?').get(current) as { n: number }).n;
|
||||
|
||||
if (body.confirm !== code) {
|
||||
const res: DeleteMyDataResponse = { status: 'pending', confirm: code, summary: { pushSubscriptions: subsCount, tokenRevoked: false } };
|
||||
return reply.send(res);
|
||||
}
|
||||
|
||||
db.prepare('DELETE FROM push_subscriptions WHERE token_id = ?').run(current);
|
||||
// révoque le token courant (sauf si c'est le dernier actif → garde anti lock-out conservée).
|
||||
const revoked = auth.revokeToken(current) === 'ok';
|
||||
recordAudit(db, { actor: current, action: 'data.delete', details: { pushSubscriptions: subsCount, tokenRevoked: revoked } });
|
||||
const res: DeleteMyDataResponse = { status: 'done', summary: { pushSubscriptions: subsCount, tokenRevoked: revoked } };
|
||||
return reply.send(res);
|
||||
});
|
||||
}
|
||||
@@ -7,9 +7,11 @@ import type {
|
||||
UpdateGroupRequest,
|
||||
} from '@arboretum/shared';
|
||||
import type { GroupManager } from '../core/group-manager.js';
|
||||
import type { Db } from '../db/index.js';
|
||||
import { recordAudit } from '../core/audit-log.js';
|
||||
import { sendManagerError } from './repos.js';
|
||||
|
||||
export function registerGroupRoutes(app: FastifyInstance, gm: GroupManager): void {
|
||||
export function registerGroupRoutes(app: FastifyInstance, gm: GroupManager, db: Db): void {
|
||||
app.get('/api/v1/groups', async (): Promise<GroupsListResponse> => ({ groups: gm.listGroups() }));
|
||||
|
||||
app.get('/api/v1/groups/:id', async (req, reply) => {
|
||||
@@ -33,6 +35,7 @@ export function registerGroupRoutes(app: FastifyInstance, gm: GroupManager): voi
|
||||
...(body.color !== undefined ? { color: body.color } : {}),
|
||||
...(Array.isArray(body.repoIds) ? { repoIds: body.repoIds } : {}),
|
||||
});
|
||||
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'group.create', resourceId: group.id, details: { label: group.label } });
|
||||
return reply.status(201).send({ group } satisfies GroupResponse);
|
||||
} catch (err) {
|
||||
return sendManagerError(reply, err);
|
||||
@@ -48,6 +51,7 @@ export function registerGroupRoutes(app: FastifyInstance, gm: GroupManager): voi
|
||||
...(body.description !== undefined ? { description: body.description } : {}),
|
||||
...(body.color !== undefined ? { color: body.color } : {}),
|
||||
});
|
||||
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'group.update', resourceId: id });
|
||||
return reply.send({ group } satisfies GroupResponse);
|
||||
} catch (err) {
|
||||
return sendManagerError(reply, err);
|
||||
@@ -59,6 +63,7 @@ export function registerGroupRoutes(app: FastifyInstance, gm: GroupManager): voi
|
||||
if (!gm.deleteGroup(id)) {
|
||||
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No group with this id' } });
|
||||
}
|
||||
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'group.delete', resourceId: id });
|
||||
return reply.send({ ok: true });
|
||||
});
|
||||
|
||||
|
||||
@@ -3,8 +3,10 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import type { PushSubscribeRequest, PushUnsubscribeRequest, VapidKeyResponse } from '@arboretum/shared';
|
||||
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.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.
|
||||
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);
|
||||
recordAudit(db, { actor: tokenId, action: 'push.subscribe' });
|
||||
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' } });
|
||||
}
|
||||
push.unsubscribe(body.endpoint);
|
||||
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'push.unsubscribe' });
|
||||
return reply.send({ ok: true });
|
||||
});
|
||||
|
||||
|
||||
@@ -4,8 +4,9 @@
|
||||
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 Db, setSetting } from '../db/index.js';
|
||||
import type { PushService } from '../core/push-service.js';
|
||||
import { recordAudit } from '../core/audit-log.js';
|
||||
import {
|
||||
SCAN_INTERVAL_KEY,
|
||||
SCAN_ROOTS_KEY,
|
||||
@@ -15,23 +16,7 @@ import {
|
||||
readScanRoots,
|
||||
} from '../core/scan-settings.js';
|
||||
|
||||
// Clés de `settings` modifiables via l'API (allow-list stricte). 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();
|
||||
}
|
||||
|
||||
// Réglages modifiables via l'API (allow-list stricte). Les secrets ne figurent JAMAIS ici.
|
||||
export function registerSettingsRoutes(
|
||||
app: FastifyInstance,
|
||||
db: Db,
|
||||
@@ -39,8 +24,6 @@ export function registerSettingsRoutes(
|
||||
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,
|
||||
@@ -52,7 +35,6 @@ export function registerSettingsRoutes(
|
||||
});
|
||||
const snapshot = (): SettingsResponse => ({
|
||||
settings: {
|
||||
giteaUrl: readGiteaUrl(),
|
||||
scanRoots: readScanRoots(db),
|
||||
scanIntervalMin: readScanIntervalMin(db),
|
||||
},
|
||||
@@ -63,20 +45,6 @@ export function registerSettingsRoutes(
|
||||
|
||||
app.patch('/api/v1/settings', async (req, reply) => {
|
||||
const body = (req.body as Partial<UpdateSettingsRequest> | 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' } });
|
||||
}
|
||||
}
|
||||
if ('scanRoots' in body) {
|
||||
const roots = normalizeScanRoots(body.scanRoots);
|
||||
if (!roots) {
|
||||
@@ -91,6 +59,11 @@ export function registerSettingsRoutes(
|
||||
}
|
||||
setSetting(db, SCAN_INTERVAL_KEY, String(interval));
|
||||
}
|
||||
recordAudit(db, {
|
||||
actor: req.authContext?.tokenId ?? 'unknown',
|
||||
action: 'settings.update',
|
||||
details: { keys: Object.keys(body) },
|
||||
});
|
||||
return reply.send(snapshot());
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user