@imenam/mcp-dependabot-tracker 1.0.8 → 1.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,11 +2,12 @@ import crypto from "crypto";
2
2
  import fs from "fs";
3
3
  import path from "path";
4
4
  import { DEFAULT_COMMIT_MESSAGE, } from "../../shared/schemas/model.schema.js";
5
+ import { analyseVulnerabilities, auditFacts } from "./analysis.js";
5
6
  import { CommandAbortedError, runCommand, tail } from "./commands.js";
6
7
  import { ConflictError, TrackerError } from "./errors.js";
7
8
  import { GitHubClient } from "./github.js";
8
9
  import { diffLockfiles, forceCandidates, parseAuditReport, parseLockfile, parseNpmJson, projectLabel, } from "./npm-audit.js";
9
- import { isActive } from "./store.js";
10
+ import { assertNotDeprecated, isActive } from "./store.js";
10
11
  /** Intervalle de lecture de la demande d'annulation pendant une étape. */
11
12
  const CANCEL_POLL_MS = 500;
12
13
  const MAX_LOG_ENTRIES = 300;
@@ -15,6 +16,8 @@ const MAX_LOG_TEXT = 4000;
15
16
  const CLONE_DIR = "repo";
16
17
  /** Paquets listés dans le corps de la pull request. */
17
18
  const MAX_PR_CHANGES = 60;
19
+ /** Dernières actions de Claude gardées dans l'opération pendant l'analyse. */
20
+ const ANALYSIS_ACTIVITY = 3;
18
21
  function now() {
19
22
  return new Date().toISOString();
20
23
  }
@@ -39,7 +42,12 @@ function gitAuthEnv(config) {
39
42
  GIT_CONFIG_VALUE_0: `AUTHORIZATION: basic ${basic}`,
40
43
  };
41
44
  }
42
- const NPM_ENV = { npm_config_update_notifier: "false", npm_config_fund: "false" };
45
+ /**
46
+ * Environnement des commandes npm. `allow_remote` autorise le téléchargement des
47
+ * archives de paquets à `bundleDependencies` (ex. `@tailwindcss/oxide-wasm32-wasi`),
48
+ * que npm 12 classe en dépendances distantes avec `--package-lock-only`.
49
+ */
50
+ const NPM_ENV = { npm_config_update_notifier: "false", npm_config_fund: "false", npm_config_allow_remote: "all" };
43
51
  /** Sous-commande git d'une liste d'arguments, après les options `-c clé=valeur`. */
44
52
  function subcommand(args) {
45
53
  let index = 0;
@@ -61,7 +69,7 @@ function newOperation(repo, kind, origin) {
61
69
  workDir: null,
62
70
  baseBranch: repo.branch,
63
71
  cancelRequested: false,
64
- steps: { clone: "pending", audit: "pending", fix: "pending", force: "pending", push: "pending" },
72
+ steps: { clone: "pending", audit: "pending", fix: "pending", analysis: "pending", force: "pending", push: "pending" },
65
73
  projects: [],
66
74
  counts: { initial: null, afterFix: null, afterForce: null },
67
75
  found: [],
@@ -71,6 +79,7 @@ function newOperation(repo, kind, origin) {
71
79
  commitMessage: DEFAULT_COMMIT_MESSAGE,
72
80
  branch: null,
73
81
  pullRequest: null,
82
+ analysis: null,
74
83
  error: null,
75
84
  log: [],
76
85
  };
@@ -82,6 +91,8 @@ class Runner {
82
91
  signal;
83
92
  config;
84
93
  cloneDir;
94
+ /** Dernier rapport `npm audit --json` de chaque projet, lu par l'analyse. */
95
+ auditReports = new Map();
85
96
  constructor(ctx, id, signal, config, cloneDir) {
86
97
  this.ctx = ctx;
87
98
  this.id = id;
@@ -173,7 +184,9 @@ async function cloneStep(runner) {
173
184
  async function auditAll(runner, count) {
174
185
  const vulnerabilities = [];
175
186
  for (const project of runner.operation.projects) {
176
- vulnerabilities.push(...parseAuditReport(await runner.npm(project, ["audit", "--json"]), project));
187
+ const report = await runner.npm(project, ["audit", "--json"]);
188
+ runner.auditReports.set(project, report);
189
+ vulnerabilities.push(...parseAuditReport(report, project));
177
190
  }
178
191
  runner.log(`${vulnerabilities.length} vulnerabilit${vulnerabilities.length === 1 ? "y" : "ies"}`);
179
192
  runner.update((operation) => ({
@@ -212,6 +225,54 @@ async function fixStep(runner, vulnerabilities) {
212
225
  runner.setStep("fix", "done");
213
226
  return remaining;
214
227
  }
228
+ /**
229
+ * Analyse par Claude des vulnérabilités restantes, quand l'analyse automatique
230
+ * est activée ; passée sinon, ou s'il ne reste rien. Son échec est enregistré
231
+ * dans l'analyse et laisse l'opération se poursuivre ; seule une annulation
232
+ * l'interrompt.
233
+ */
234
+ async function analysisStep(runner, ctx) {
235
+ const settings = ctx.settings();
236
+ if (!settings.analysis.auto || runner.operation.remaining.length === 0) {
237
+ runner.setStep("analysis", "skipped");
238
+ return;
239
+ }
240
+ runner.setStep("analysis", "running");
241
+ runner.update((operation) => ({
242
+ ...operation,
243
+ analysis: { startedAt: now(), endedAt: null, turns: 0, activity: [], report: null, task: null, error: null },
244
+ }));
245
+ const analysed = (fn) => runner.update((operation) => ({ ...operation, analysis: operation.analysis && fn(operation.analysis) }));
246
+ try {
247
+ const operation = runner.operation;
248
+ const { report, task } = await analyseVulnerabilities({
249
+ repoId: operation.repoId,
250
+ branch: operation.baseBranch,
251
+ cwd: runner.repoDir,
252
+ workDir: operation.workDir,
253
+ facts: operation.projects.flatMap((project) => auditFacts(runner.auditReports.get(project), project)),
254
+ forceCandidates: operation.forceCandidates,
255
+ settings,
256
+ claude: ctx.claude,
257
+ signal: runner.signal,
258
+ onLine: (line, turns) => {
259
+ runner.log(`claude: ${line}`);
260
+ analysed((analysis) => ({ ...analysis, turns, activity: [...analysis.activity, line].slice(-ANALYSIS_ACTIVITY) }));
261
+ },
262
+ });
263
+ runner.log(`Organizer task ${task.key}: ${task.url}`);
264
+ analysed((analysis) => ({ ...analysis, endedAt: now(), report, task }));
265
+ runner.setStep("analysis", "done");
266
+ }
267
+ catch (err) {
268
+ if (err instanceof CommandAbortedError || runner.signal.aborted)
269
+ throw err;
270
+ const message = err?.message ?? String(err);
271
+ runner.log(`Analysis failed: ${message}`);
272
+ analysed((analysis) => ({ ...analysis, endedAt: now(), error: message }));
273
+ runner.setStep("analysis", "failed");
274
+ }
275
+ }
215
276
  /** `npm audit fix --force` dans les projets qui ont une montée majeure à appliquer. */
216
277
  async function forceStep(runner) {
217
278
  runner.setStep("force", "running");
@@ -231,6 +292,7 @@ function pullRequestBody(operation) {
231
292
  `- Vulnerabilities before: ${operation.counts.initial}`,
232
293
  `- Vulnerabilities after: ${after}`,
233
294
  `- \`npm audit fix --force\`: ${operation.steps.force === "done" ? "applied" : "not applied"}`,
295
+ ...(operation.analysis?.task ? [`- Remaining vulnerabilities analysed by Claude: organizer task ${operation.analysis.task.key}`] : []),
234
296
  "",
235
297
  `Updated packages (${operation.changes.length}):`,
236
298
  "",
@@ -359,12 +421,14 @@ function inBackground(ctx, id, run) {
359
421
  }
360
422
  // --- Entrées ---------------------------------------------------------------------
361
423
  /**
362
- * Lance une correction depuis la GUI : clone, audit et `npm audit fix` s'exécutent
363
- * en arrière-plan, puis l'opération attend la décision sur `--force` ou le push.
424
+ * Lance une correction depuis la GUI : clone, audit, `npm audit fix` et
425
+ * l'analyse par Claude s'exécutent en arrière-plan, puis l'opération attend la
426
+ * décision sur `--force` ou le push. Refusé sur un dépôt déprécié.
364
427
  */
365
428
  export function startUserFix(ctx, repoId) {
366
429
  ctx.githubConfig();
367
430
  const repo = ctx.store.getRepo(repoId);
431
+ assertNotDeprecated(repo);
368
432
  const operation = ctx.store.createOperation(newOperation(repo, "fix", "user"));
369
433
  inBackground(ctx, operation.id, execute(ctx, operation.id, async (runner) => {
370
434
  await cloneStep(runner);
@@ -372,6 +436,7 @@ export function startUserFix(ctx, repoId) {
372
436
  if (vulnerabilities.length === 0)
373
437
  return finish(runner);
374
438
  await fixStep(runner, vulnerabilities);
439
+ await analysisStep(runner, ctx);
375
440
  if (runner.operation.forceCandidates.length > 0) {
376
441
  runner.update((current) => ({ ...current, status: "waiting_force" }));
377
442
  return;
@@ -384,11 +449,12 @@ export function startUserFix(ctx, repoId) {
384
449
  /**
385
450
  * Audit de la branche par défaut, celle que Dependabot analyse, lancé par
386
451
  * l'utilisateur et attendu jusqu'à sa fin. Refusé si une opération est en
387
- * cours sur le dépôt.
452
+ * cours sur le dépôt, ou s'il est déprécié.
388
453
  */
389
454
  export async function runDefaultBranchAudit(ctx, repoId) {
390
455
  ctx.githubConfig();
391
456
  const repo = ctx.store.getRepo(repoId);
457
+ assertNotDeprecated(repo);
392
458
  const operation = ctx.store.createOperation({ ...newOperation(repo, "audit", "user"), baseBranch: repo.defaultBranch });
393
459
  return execute(ctx, operation.id, async (runner) => {
394
460
  await cloneStep(runner);
@@ -442,11 +508,12 @@ export function cancelOperation(ctx, id) {
442
508
  /**
443
509
  * Opération menée par l'agent d'un bout à l'autre, attendue jusqu'à sa fin :
444
510
  * `audit` s'arrête après `npm audit` ; `fix` enchaîne `npm audit fix`, puis
445
- * `--force` et le push selon `plan`.
511
+ * `--force` et le push selon `plan`. Refusé sur un dépôt déprécié.
446
512
  */
447
513
  export async function runAgentOperation(ctx, repoId, kind, plan) {
448
514
  ctx.githubConfig();
449
515
  const repo = ctx.store.getRepo(repoId);
516
+ assertNotDeprecated(repo);
450
517
  const operation = ctx.store.createOperation({ ...newOperation(repo, kind, "agent"), commitMessage: plan.commitMessage });
451
518
  return execute(ctx, operation.id, async (runner) => {
452
519
  await cloneStep(runner);
@@ -454,6 +521,7 @@ export async function runAgentOperation(ctx, repoId, kind, plan) {
454
521
  if (kind === "audit" || vulnerabilities.length === 0)
455
522
  return finish(runner);
456
523
  await fixStep(runner, vulnerabilities);
524
+ runner.setStep("analysis", "skipped");
457
525
  if (plan.force && runner.operation.forceCandidates.length > 0) {
458
526
  await forceStep(runner);
459
527
  }
@@ -0,0 +1,43 @@
1
+ import { TASK_STATUSES } from "../../shared/schemas/model.schema.js";
2
+ export interface OrganizerConnection {
3
+ /** Adresse publique du site, sans barre oblique finale. */
4
+ url: string;
5
+ token: string;
6
+ }
7
+ /** Espace du token et son propriétaire, à qui les tâches de l'analyse sont assignées. */
8
+ export interface OrganizerSpace {
9
+ space: {
10
+ id: string;
11
+ name: string;
12
+ };
13
+ owner: {
14
+ id: string;
15
+ name: string;
16
+ email: string;
17
+ };
18
+ }
19
+ export interface OrganizerTask {
20
+ id: string;
21
+ key: string;
22
+ title: string;
23
+ status: (typeof TASK_STATUSES)[number];
24
+ assigneeIds: string[];
25
+ tags: string[];
26
+ }
27
+ /**
28
+ * Adresse du site, validée : absolue, en https sauf pour un site de cette
29
+ * machine (le token passerait en clair), sans identifiants, requête ni fragment.
30
+ */
31
+ export declare function organizerUrl(raw: string): string;
32
+ export declare class OrganizerClient {
33
+ private readonly connection;
34
+ constructor(connection: OrganizerConnection);
35
+ /** Adresse de la page d'une tâche sur le site. */
36
+ taskUrl(taskId: string): string;
37
+ /** Espace du token et son propriétaire. */
38
+ space(): Promise<OrganizerSpace>;
39
+ /** Tâche de l'espace, par sa clé (ex. `ORG-42`) ou son identifiant. */
40
+ task(ref: string): Promise<OrganizerTask>;
41
+ /** Données d'une lecture de l'API agent. Une redirection n'est jamais suivie : le token ne part que vers l'adresse réglée. */
42
+ private get;
43
+ }
@@ -0,0 +1,95 @@
1
+ import { TASK_STATUSES } from "../../shared/schemas/model.schema.js";
2
+ import { TrackerError } from "./errors.js";
3
+ /**
4
+ * Client de l'API agent d'un site organizer (`<url>/api/agent/…`), avec un
5
+ * token d'agent : il couvre un espace, avec les droits de son créateur. Chaque
6
+ * réponse réussie est une enveloppe `{ text, data }` ; une erreur porte `{ error }`.
7
+ */
8
+ const REQUEST_TIMEOUT_MS = 30_000;
9
+ const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
10
+ /**
11
+ * Adresse du site, validée : absolue, en https sauf pour un site de cette
12
+ * machine (le token passerait en clair), sans identifiants, requête ni fragment.
13
+ */
14
+ export function organizerUrl(raw) {
15
+ let url;
16
+ try {
17
+ url = new URL(raw.trim());
18
+ }
19
+ catch {
20
+ throw new TrackerError(`The organizer address is not an absolute URL (${raw}): expected e.g. https://organizer.example.com.`);
21
+ }
22
+ if (url.protocol !== "https:" && url.protocol !== "http:")
23
+ throw new TrackerError(`The organizer address must use http or https (${raw}).`);
24
+ if (url.protocol === "http:" && !LOCAL_HOSTS.has(url.hostname)) {
25
+ throw new TrackerError(`The organizer address must use https (${raw}): over http the token would travel in clear text. http is only accepted for a site on this machine.`);
26
+ }
27
+ if (url.search || url.hash || url.username || url.password) {
28
+ throw new TrackerError(`The organizer address must not contain credentials, a query or a fragment (${raw}).`);
29
+ }
30
+ return url.href.replace(/\/+$/, "");
31
+ }
32
+ export class OrganizerClient {
33
+ connection;
34
+ constructor(connection) {
35
+ this.connection = connection;
36
+ }
37
+ /** Adresse de la page d'une tâche sur le site. */
38
+ taskUrl(taskId) {
39
+ return `${this.connection.url}/#/task/${encodeURIComponent(taskId)}`;
40
+ }
41
+ /** Espace du token et son propriétaire. */
42
+ async space() {
43
+ const data = await this.get("context");
44
+ const owner = Array.isArray(data?.members) ? data.members.find((member) => member?.role === "owner") : undefined;
45
+ if (typeof data?.space?.id !== "string" || typeof data?.space?.name !== "string" || typeof owner?.id !== "string") {
46
+ throw new TrackerError(`The organizer at ${this.connection.url} sent an unexpected context: check that it is up to date.`);
47
+ }
48
+ return { space: { id: data.space.id, name: data.space.name }, owner: { id: owner.id, name: String(owner.name), email: String(owner.email) } };
49
+ }
50
+ /** Tâche de l'espace, par sa clé (ex. `ORG-42`) ou son identifiant. */
51
+ async task(ref) {
52
+ const task = (await this.get(`tasks/${encodeURIComponent(ref)}`))?.task;
53
+ if (typeof task?.id !== "string" ||
54
+ typeof task.key !== "string" ||
55
+ typeof task.title !== "string" ||
56
+ !TASK_STATUSES.includes(task.status) ||
57
+ !Array.isArray(task.assigneeIds) ||
58
+ !Array.isArray(task.tags)) {
59
+ throw new TrackerError(`The organizer at ${this.connection.url} sent an unexpected answer for task ${ref}: check that it is up to date.`);
60
+ }
61
+ return { id: task.id, key: task.key, title: task.title, status: task.status, assigneeIds: task.assigneeIds, tags: task.tags };
62
+ }
63
+ /** Données d'une lecture de l'API agent. Une redirection n'est jamais suivie : le token ne part que vers l'adresse réglée. */
64
+ async get(path) {
65
+ let response;
66
+ try {
67
+ response = await fetch(`${this.connection.url}/api/agent/${path}`, {
68
+ headers: { authorization: `Bearer ${this.connection.token}`, accept: "application/json" },
69
+ redirect: "manual",
70
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
71
+ });
72
+ }
73
+ catch (err) {
74
+ throw new TrackerError(`Cannot reach the organizer at ${this.connection.url} (${err?.cause?.message ?? err?.message ?? err}).`);
75
+ }
76
+ if (response.status >= 300 && response.status < 400) {
77
+ throw new TrackerError(`The organizer at ${this.connection.url} answered with a redirect (HTTP ${response.status}): use the final https address of the site.`);
78
+ }
79
+ let payload = null;
80
+ try {
81
+ payload = await response.json();
82
+ }
83
+ catch {
84
+ payload = null;
85
+ }
86
+ if (!response.ok) {
87
+ const reason = typeof payload?.error === "string" ? payload.error : `HTTP ${response.status}`;
88
+ throw new TrackerError(`The organizer at ${this.connection.url} refused the request: ${reason}`);
89
+ }
90
+ if (payload === null || typeof payload !== "object" || !("data" in payload)) {
91
+ throw new TrackerError(`The organizer at ${this.connection.url} sent an unexpected answer: check the address of the site.`);
92
+ }
93
+ return payload.data;
94
+ }
95
+ }
@@ -1,4 +1,4 @@
1
- import { type Alert, type AlertSeverity, type HandledAlert, type Operation, type PullRequest, type Repo, type Rights } from "../../shared/schemas/model.schema.js";
1
+ import { type Alert, type AlertSeverity, type AnalysisTask, type HandledAlert, type Operation, type PullRequest, type Repo, type Rights } from "../../shared/schemas/model.schema.js";
2
2
  import type { AuditFindings, RepoView } from "../../shared/schemas/api.schema.js";
3
3
  import type { GitHubConfig } from "./config.js";
4
4
  import { type OpenPullRequest } from "./github.js";
@@ -51,15 +51,23 @@ export declare function pruneHandledAlerts(handled: HandledAlert[], alerts: Aler
51
51
  */
52
52
  export declare function trackerPullRequests(repoId: string, pulls: OpenPullRequest[]): PullRequest[];
53
53
  export declare function repoView(store: Store, repo: Repo): RepoView;
54
+ /** Tâche organizer de la dernière analyse, tant qu'elle n'est pas terminée. `operations` va de la plus récente à la plus ancienne. */
55
+ export declare function openAnalysisTask(operations: Operation[]): AnalysisTask | null;
54
56
  export declare function listRepoViews(store: Store): RepoView[];
55
57
  /**
56
58
  * Relit les alertes Dependabot ouvertes du dépôt et ses pull requests ouvertes
57
59
  * par le tracker ; un échec est enregistré dans `syncError`, données précédentes
58
- * conservées.
60
+ * conservées. Refusé sur un dépôt déprécié.
59
61
  */
60
62
  export declare function syncRepository(store: Store, config: GitHubConfig, repoId: string): Promise<Repo>;
61
- /** Relit tout de suite, en parallèle, les alertes et les pull requests de chaque dépôt suivi. */
63
+ /** Dépôts suivis qui ne sont pas dépréciés. */
64
+ export declare function activeRepos(store: Store): Repo[];
65
+ /** Relit tout de suite, en parallèle, les alertes et les pull requests de chaque dépôt suivi non déprécié. */
62
66
  export declare function syncAllRepositories(store: Store, config: GitHubConfig): Promise<void>;
67
+ /** Marque le dépôt déprécié ; sans effet s'il l'est déjà, refusé pendant une opération en cours. */
68
+ export declare function deprecateRepository(store: Store, repoId: string): Repo;
69
+ /** Retire la marque « déprécié », puis relit aussitôt les alertes du dépôt ; il retrouve sa catégorie. */
70
+ export declare function restoreRepository(store: Store, config: GitHubConfig, repoId: string): Promise<Repo>;
63
71
  /** Suit un nouveau dépôt, rangé dans `categoryId`, avec l'audit pour seul droit de l'agent, puis lit ses alertes. */
64
72
  export declare function addRepository(store: Store, config: GitHubConfig, input: string, categoryId: string | null): Promise<Repo>;
65
73
  /** Dépôts accessibles au token qui ne sont pas encore suivis, proposés à l'ajout. */
@@ -75,5 +83,5 @@ export declare function markAlertHandled(store: Store, repoId: string, number: n
75
83
  /** Retire la marque « corrigée à la main » d'une alerte. */
76
84
  export declare function unmarkAlertHandled(store: Store, repoId: string, number: number): Repo;
77
85
  export declare function setRights(store: Store, repoId: string, rights: Rights): Repo;
78
- /** Dépôts jamais synchronisés, ou synchronisés il y a plus de `maxAgeMs`. */
86
+ /** Dépôts non dépréciés jamais synchronisés, ou synchronisés il y a plus de `maxAgeMs`. */
79
87
  export declare function staleRepos(store: Store, maxAgeMs: number, at?: number): Repo[];
@@ -1,10 +1,11 @@
1
1
  import { fromNpmSeverity, pendingAlerts, worstOf } from "../../shared/alerts.js";
2
2
  import { ALERT_SEVERITIES, DEFAULT_RIGHTS } from "../../shared/schemas/model.schema.js";
3
+ import { latestAnalysed } from "./analysis.js";
3
4
  import { ConflictError, NotFoundError } from "./errors.js";
4
5
  import { GitHubClient } from "./github.js";
5
6
  import { isTrackerBranch } from "./operations.js";
6
7
  import { parseRepoRef } from "./repo-ref.js";
7
- import { isActive } from "./store.js";
8
+ import { assertNotDeprecated, isActive } from "./store.js";
8
9
  /** Ancienneté au-delà de laquelle les alertes d'un dépôt sont relues sur GitHub. */
9
10
  export const SYNC_INTERVAL_MS = 10 * 60_000;
10
11
  function severityRank(severity) {
@@ -114,8 +115,14 @@ export function repoView(store, repo) {
114
115
  cleanAuditAt: cleanAuditAt(repo, operations),
115
116
  auditFindings: auditFindings(repo, operations),
116
117
  unfixable: unfixablePackages(repo, operations),
118
+ analysisTask: openAnalysisTask(operations),
117
119
  };
118
120
  }
121
+ /** Tâche organizer de la dernière analyse, tant qu'elle n'est pas terminée. `operations` va de la plus récente à la plus ancienne. */
122
+ export function openAnalysisTask(operations) {
123
+ const task = latestAnalysed(operations)?.analysis?.task ?? null;
124
+ return task && task.status !== "done" ? task : null;
125
+ }
119
126
  export function listRepoViews(store) {
120
127
  store.failOrphanedOperations();
121
128
  return sortRepos(store.listRepos().map((repo) => repoView(store, repo)));
@@ -123,10 +130,11 @@ export function listRepoViews(store) {
123
130
  /**
124
131
  * Relit les alertes Dependabot ouvertes du dépôt et ses pull requests ouvertes
125
132
  * par le tracker ; un échec est enregistré dans `syncError`, données précédentes
126
- * conservées.
133
+ * conservées. Refusé sur un dépôt déprécié.
127
134
  */
128
135
  export async function syncRepository(store, config, repoId) {
129
136
  const repo = store.getRepo(repoId);
137
+ assertNotDeprecated(repo);
130
138
  const github = new GitHubClient(config);
131
139
  try {
132
140
  const [alerts, pulls] = await Promise.all([github.listOpenAlerts(repo.owner, repo.name), github.listOpenPullRequests(repo.owner, repo.name)]);
@@ -144,9 +152,25 @@ export async function syncRepository(store, config, repoId) {
144
152
  return store.updateRepo(repo.id, (current) => ({ ...current, syncedAt: new Date().toISOString(), syncError: message }));
145
153
  }
146
154
  }
147
- /** Relit tout de suite, en parallèle, les alertes et les pull requests de chaque dépôt suivi. */
155
+ /** Dépôts suivis qui ne sont pas dépréciés. */
156
+ export function activeRepos(store) {
157
+ return store.listRepos().filter((repo) => repo.deprecatedAt === null);
158
+ }
159
+ /** Relit tout de suite, en parallèle, les alertes et les pull requests de chaque dépôt suivi non déprécié. */
148
160
  export async function syncAllRepositories(store, config) {
149
- await Promise.all(store.listRepos().map((repo) => syncRepository(store, config, repo.id)));
161
+ await Promise.all(activeRepos(store).map((repo) => syncRepository(store, config, repo.id)));
162
+ }
163
+ /** Marque le dépôt déprécié ; sans effet s'il l'est déjà, refusé pendant une opération en cours. */
164
+ export function deprecateRepository(store, repoId) {
165
+ const repo = store.getRepo(repoId);
166
+ if (store.activeOperation(repo.id))
167
+ throw new ConflictError(`An operation is in progress on ${repo.id}: wait for it to finish or cancel it before deprecating the repository.`);
168
+ return store.updateRepo(repo.id, (current) => (current.deprecatedAt === null ? { ...current, deprecatedAt: new Date().toISOString() } : current));
169
+ }
170
+ /** Retire la marque « déprécié », puis relit aussitôt les alertes du dépôt ; il retrouve sa catégorie. */
171
+ export async function restoreRepository(store, config, repoId) {
172
+ const repo = store.updateRepo(repoId, (current) => ({ ...current, deprecatedAt: null }));
173
+ return syncRepository(store, config, repo.id);
150
174
  }
151
175
  /** Suit un nouveau dépôt, rangé dans `categoryId`, avec l'audit pour seul droit de l'agent, puis lit ses alertes. */
152
176
  export async function addRepository(store, config, input, categoryId) {
@@ -170,6 +194,7 @@ export async function addRepository(store, config, input, categoryId) {
170
194
  pullRequests: [],
171
195
  syncedAt: null,
172
196
  syncError: null,
197
+ deprecatedAt: null,
173
198
  });
174
199
  return syncRepository(store, config, remote.fullName);
175
200
  }
@@ -215,7 +240,7 @@ export function unmarkAlertHandled(store, repoId, number) {
215
240
  export function setRights(store, repoId, rights) {
216
241
  return store.updateRepo(repoId, (repo) => ({ ...repo, rights }));
217
242
  }
218
- /** Dépôts jamais synchronisés, ou synchronisés il y a plus de `maxAgeMs`. */
243
+ /** Dépôts non dépréciés jamais synchronisés, ou synchronisés il y a plus de `maxAgeMs`. */
219
244
  export function staleRepos(store, maxAgeMs, at = Date.now()) {
220
- return store.listRepos().filter((repo) => repo.syncedAt === null || at - Date.parse(repo.syncedAt) > maxAgeMs);
245
+ return activeRepos(store).filter((repo) => repo.syncedAt === null || at - Date.parse(repo.syncedAt) > maxAgeMs);
221
246
  }
@@ -0,0 +1,21 @@
1
+ import { type SaveSettingsBody, type Settings, type SettingsView } from "../../shared/schemas/settings.schema.js";
2
+ import { type OrganizerConnection, type OrganizerSpace } from "./organizer.js";
3
+ /** Vérifications faites à l'enregistrement : remplacées dans les tests. */
4
+ export interface SettingsChecks {
5
+ organizer: (connection: OrganizerConnection) => Promise<OrganizerSpace>;
6
+ claudeToken: (token: string) => Promise<void>;
7
+ }
8
+ export declare function readSettings(dataDir: string): Settings;
9
+ /** Connexion à l'organizer, null tant que l'adresse ou le token manque. */
10
+ export declare function organizerConnection(settings: Settings): OrganizerConnection | null;
11
+ /** Vrai quand l'organizer (connexion testée) et Claude sont configurés. */
12
+ export declare function analysisReady(settings: Settings): boolean;
13
+ export declare function settingsView(settings: Settings): SettingsView;
14
+ /**
15
+ * Enregistre les réglages de la GUI. Une connexion à l'organizer modifiée est
16
+ * testée, un nouveau token Claude vérifié : un échec refuse tout
17
+ * l'enregistrement. L'analyse automatique exige l'organizer et Claude.
18
+ */
19
+ export declare function saveSettings(dataDir: string, body: SaveSettingsBody, checks: SettingsChecks): Promise<SettingsView>;
20
+ /** Teste la connexion enregistrée à l'organizer et relève son espace et son propriétaire. */
21
+ export declare function testOrganizer(dataDir: string, checks: SettingsChecks): Promise<SettingsView>;
@@ -0,0 +1,108 @@
1
+ import crypto from "crypto";
2
+ import fs from "fs";
3
+ import path from "path";
4
+ import { DEFAULT_SETTINGS, SettingsSchema } from "../../shared/schemas/settings.schema.js";
5
+ import { TrackerError } from "./errors.js";
6
+ import { organizerUrl } from "./organizer.js";
7
+ /**
8
+ * Réglages de l'analyse par Claude, dans `<données>/settings.json`, lisible par
9
+ * le seul compte du serveur : ils portent le token de l'organizer et celui de
10
+ * Claude, que la GUI ne reçoit jamais en entier.
11
+ */
12
+ /** Durée de validité d'un token créé par `claude setup-token`. */
13
+ const CLAUDE_TOKEN_VALIDITY_MS = 365 * 24 * 3600_000;
14
+ function settingsPath(dataDir) {
15
+ return path.join(dataDir, "settings.json");
16
+ }
17
+ export function readSettings(dataDir) {
18
+ const file = settingsPath(dataDir);
19
+ let raw;
20
+ try {
21
+ raw = fs.readFileSync(file, "utf-8");
22
+ }
23
+ catch (err) {
24
+ if (err.code === "ENOENT")
25
+ return DEFAULT_SETTINGS;
26
+ throw err;
27
+ }
28
+ const parsed = SettingsSchema.safeParse(JSON.parse(raw));
29
+ if (!parsed.success)
30
+ throw new TrackerError(`${file} is invalid: ${parsed.error.message}`);
31
+ return parsed.data;
32
+ }
33
+ function writeSettings(dataDir, settings) {
34
+ const file = settingsPath(dataDir);
35
+ const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
36
+ try {
37
+ fs.writeFileSync(tmp, JSON.stringify(SettingsSchema.parse(settings), null, 2), { encoding: "utf-8", mode: 0o600 });
38
+ fs.renameSync(tmp, file);
39
+ }
40
+ catch (err) {
41
+ fs.rmSync(tmp, { force: true });
42
+ throw err;
43
+ }
44
+ }
45
+ /** Connexion à l'organizer, null tant que l'adresse ou le token manque. */
46
+ export function organizerConnection(settings) {
47
+ const { url, token } = settings.organizer;
48
+ return url && token ? { url, token } : null;
49
+ }
50
+ /** Vrai quand l'organizer (connexion testée) et Claude sont configurés. */
51
+ export function analysisReady(settings) {
52
+ return organizerConnection(settings) !== null && settings.organizer.space !== null && settings.claude.token !== null;
53
+ }
54
+ function tokenHint(token) {
55
+ return token === null ? null : token.slice(-4);
56
+ }
57
+ export function settingsView(settings) {
58
+ const { savedAt } = settings.claude;
59
+ return {
60
+ organizer: { url: settings.organizer.url, tokenHint: tokenHint(settings.organizer.token), space: settings.organizer.space, owner: settings.organizer.owner },
61
+ claude: {
62
+ tokenHint: tokenHint(settings.claude.token),
63
+ savedAt,
64
+ expiresAt: savedAt === null ? null : new Date(Date.parse(savedAt) + CLAUDE_TOKEN_VALIDITY_MS).toISOString(),
65
+ },
66
+ analysis: settings.analysis,
67
+ ready: analysisReady(settings),
68
+ };
69
+ }
70
+ /** Espace et propriétaire relevés par un test de la connexion, ou rien sans connexion. */
71
+ async function checkedOrganizer(organizer, checks) {
72
+ if (!organizer.url || !organizer.token)
73
+ return { ...organizer, space: null, owner: null };
74
+ const found = await checks.organizer({ url: organizer.url, token: organizer.token });
75
+ return { ...organizer, space: found.space.name, owner: found.owner.name };
76
+ }
77
+ /**
78
+ * Enregistre les réglages de la GUI. Une connexion à l'organizer modifiée est
79
+ * testée, un nouveau token Claude vérifié : un échec refuse tout
80
+ * l'enregistrement. L'analyse automatique exige l'organizer et Claude.
81
+ */
82
+ export async function saveSettings(dataDir, body, checks) {
83
+ const current = readSettings(dataDir);
84
+ const url = body.organizerUrl === "" ? null : organizerUrl(body.organizerUrl);
85
+ const token = body.organizerToken ?? current.organizer.token;
86
+ const organizerChanged = url !== current.organizer.url || token !== current.organizer.token;
87
+ const organizer = organizerChanged ? await checkedOrganizer({ ...current.organizer, url, token }, checks) : current.organizer;
88
+ let claude = current.claude;
89
+ if (body.claudeToken !== undefined) {
90
+ await checks.claudeToken(body.claudeToken);
91
+ claude = { token: body.claudeToken, savedAt: new Date().toISOString() };
92
+ }
93
+ const next = { organizer, claude, analysis: body.analysis };
94
+ if (next.analysis.auto && !analysisReady(next)) {
95
+ throw new TrackerError("The automatic analysis needs the organizer connection and the Claude token.");
96
+ }
97
+ writeSettings(dataDir, next);
98
+ return settingsView(next);
99
+ }
100
+ /** Teste la connexion enregistrée à l'organizer et relève son espace et son propriétaire. */
101
+ export async function testOrganizer(dataDir, checks) {
102
+ const current = readSettings(dataDir);
103
+ if (!organizerConnection(current))
104
+ throw new TrackerError("Set the organizer address and token first.");
105
+ const next = { ...current, organizer: await checkedOrganizer(current.organizer, checks) };
106
+ writeSettings(dataDir, next);
107
+ return settingsView(next);
108
+ }
@@ -2,6 +2,8 @@ import { type Category, type Operation, type Repo } from "../../shared/schemas/m
2
2
  /** Vrai si le processus `pid` existe encore. */
3
3
  export declare function processAlive(pid: number): boolean;
4
4
  export declare function isActive(operation: Operation): boolean;
5
+ /** Refuse toute lecture GitHub ou opération sur un dépôt déprécié. */
6
+ export declare function assertNotDeprecated(repo: Repo): void;
5
7
  /**
6
8
  * Persistance : `<dataDir>/repos.json` pour les dépôts suivis et
7
9
  * `<dataDir>/operations/<id>.json` pour chaque opération. Plusieurs processus
@@ -40,7 +40,8 @@ export function processAlive(pid) {
40
40
  * choisie analyse sa branche par défaut, un dépôt sans catégorie n'est rangé
41
41
  * dans aucune, un fichier sans catégories n'en a aucune, un dépôt sans alerte
42
42
  * corrigée à la main n'en a aucune, un dépôt sans pull request en attente n'en
43
- * a aucune jusqu'à sa lecture suivante. Une alerte sans date
43
+ * a aucune jusqu'à sa lecture suivante, un dépôt sans date de dépréciation
44
+ * n'est pas déprécié. Une alerte sans date
44
45
  * d'émission prend celle de la lecture qui l'a rapportée ; la lecture suivante
45
46
  * la remplace par la vraie.
46
47
  */
@@ -56,6 +57,7 @@ function normalizeReposFile(file) {
56
57
  categoryId: repo?.categoryId ?? null,
57
58
  handledAlerts: repo?.handledAlerts ?? [],
58
59
  pullRequests: repo?.pullRequests ?? [],
60
+ deprecatedAt: repo?.deprecatedAt ?? null,
59
61
  alerts: Array.isArray(repo?.alerts)
60
62
  ? repo.alerts.map((alert) => ({ ...alert, createdAt: alert?.createdAt ?? repo.syncedAt ?? repo.addedAt }))
61
63
  : repo?.alerts,
@@ -65,12 +67,17 @@ function normalizeReposFile(file) {
65
67
  /**
66
68
  * Complète une opération écrite par une version antérieure : sans `found`, les
67
69
  * vulnérabilités du premier audit sont `remaining` tant qu'aucune correction
68
- * n'a suivi, et inconnues sinon.
70
+ * n'a suivi, et inconnues sinon ; sans étape d'analyse, l'analyse est passée.
69
71
  */
70
72
  function normalizeOperation(operation) {
71
- if (operation === null || typeof operation !== "object" || operation.found !== undefined)
73
+ if (operation === null || typeof operation !== "object")
72
74
  return operation;
73
- return { ...operation, found: operation.counts?.afterFix === null ? operation.remaining : [] };
75
+ return {
76
+ ...operation,
77
+ found: operation.found ?? (operation.counts?.afterFix === null ? operation.remaining : []),
78
+ steps: operation.steps && typeof operation.steps === "object" ? { analysis: "skipped", ...operation.steps } : operation.steps,
79
+ analysis: operation.analysis ?? null,
80
+ };
74
81
  }
75
82
  function sameName(a, b) {
76
83
  return a.trim().toLowerCase() === b.trim().toLowerCase();
@@ -89,6 +96,12 @@ function assertNameFree(file, name, exceptId) {
89
96
  export function isActive(operation) {
90
97
  return ACTIVE_STATUSES.includes(operation.status);
91
98
  }
99
+ /** Refuse toute lecture GitHub ou opération sur un dépôt déprécié. */
100
+ export function assertNotDeprecated(repo) {
101
+ if (repo.deprecatedAt !== null) {
102
+ throw new ConflictError(`Repository ${repo.id} is deprecated: it is neither synced nor audited. Only the user can restore it, in the GUI.`);
103
+ }
104
+ }
92
105
  /**
93
106
  * Persistance : `<dataDir>/repos.json` pour les dépôts suivis et
94
107
  * `<dataDir>/operations/<id>.json` pour chaque opération. Plusieurs processus