@imenam/mcp-dependabot-tracker 0.0.0-stage → 1.0.2
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.
- package/README.md +209 -2
- package/dist/shared/repo-search.d.ts +9 -0
- package/dist/shared/repo-search.js +24 -0
- package/dist/shared/schemas/api.schema.d.ts +53 -0
- package/dist/shared/schemas/api.schema.js +11 -0
- package/dist/shared/schemas/ipc.schema.d.ts +26 -0
- package/dist/shared/schemas/ipc.schema.js +31 -0
- package/dist/shared/schemas/model.schema.d.ts +276 -0
- package/dist/shared/schemas/model.schema.js +116 -0
- package/dist/src/cli/setup-mcp.d.ts +24 -0
- package/dist/src/cli/setup-mcp.js +137 -0
- package/dist/src/core/commands.d.ts +26 -0
- package/dist/src/core/commands.js +101 -0
- package/dist/src/core/config.d.ts +12 -0
- package/dist/src/core/config.js +18 -0
- package/dist/src/core/data-dir.d.ts +11 -0
- package/dist/src/core/data-dir.js +27 -0
- package/dist/src/core/errors.d.ts +12 -0
- package/dist/src/core/errors.js +21 -0
- package/dist/src/core/github.d.ts +45 -0
- package/dist/src/core/github.js +141 -0
- package/dist/src/core/log-dir.d.ts +6 -0
- package/dist/src/core/log-dir.js +13 -0
- package/dist/src/core/npm-audit.d.ts +36 -0
- package/dist/src/core/npm-audit.js +115 -0
- package/dist/src/core/operations.d.ts +42 -0
- package/dist/src/core/operations.js +438 -0
- package/dist/src/core/repo-ref.d.ts +9 -0
- package/dist/src/core/repo-ref.js +33 -0
- package/dist/src/core/repos.d.ts +25 -0
- package/dist/src/core/repos.js +90 -0
- package/dist/src/core/store.d.ts +49 -0
- package/dist/src/core/store.js +266 -0
- package/dist/src/gui-worker.d.ts +1 -0
- package/dist/src/gui-worker.js +326 -0
- package/dist/src/index.d.ts +2 -0
- package/dist/src/index.js +365 -0
- package/dist/src/tools/format.d.ts +7 -0
- package/dist/src/tools/format.js +81 -0
- package/dist/src/tools/tools.d.ts +15 -0
- package/dist/src/tools/tools.js +56 -0
- package/dist/src/tools/types.d.ts +21 -0
- package/dist/src/tools/types.js +38 -0
- package/dist/src/version.d.ts +1 -0
- package/dist/src/version.js +16 -0
- package/gui/dist/assets/index-Bn8FyH44.css +1 -0
- package/gui/dist/assets/index-do_lp18L.js +63 -0
- package/gui/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
- package/gui/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
- package/gui/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
- package/gui/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
- package/gui/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
- package/gui/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
- package/gui/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
- package/gui/dist/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
- package/gui/dist/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
- package/gui/dist/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
- package/gui/dist/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
- package/gui/dist/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
- package/gui/dist/index.html +13 -0
- package/package.json +57 -4
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
import crypto from "crypto";
|
|
2
|
+
import fs from "fs";
|
|
3
|
+
import path from "path";
|
|
4
|
+
import { DEFAULT_COMMIT_MESSAGE, } from "../../shared/schemas/model.schema.js";
|
|
5
|
+
import { CommandAbortedError, runCommand, tail } from "./commands.js";
|
|
6
|
+
import { ConflictError, TrackerError } from "./errors.js";
|
|
7
|
+
import { GitHubClient } from "./github.js";
|
|
8
|
+
import { diffLockfiles, forceCandidates, parseAuditReport, parseLockfile, parseNpmJson, projectLabel, } from "./npm-audit.js";
|
|
9
|
+
import { isActive } from "./store.js";
|
|
10
|
+
/** Intervalle de lecture de la demande d'annulation pendant une étape. */
|
|
11
|
+
const CANCEL_POLL_MS = 500;
|
|
12
|
+
const MAX_LOG_ENTRIES = 300;
|
|
13
|
+
const MAX_LOG_TEXT = 4000;
|
|
14
|
+
/** Dossier du clone dans le répertoire temporaire de l'opération. */
|
|
15
|
+
const CLONE_DIR = "repo";
|
|
16
|
+
/** Paquets listés dans le corps de la pull request. */
|
|
17
|
+
const MAX_PR_CHANGES = 60;
|
|
18
|
+
function now() {
|
|
19
|
+
return new Date().toISOString();
|
|
20
|
+
}
|
|
21
|
+
/** `fix/npm-audit-2026-10-28-143205`, à l'heure locale du serveur. */
|
|
22
|
+
export function branchName(date) {
|
|
23
|
+
const pad = (value) => String(value).padStart(2, "0");
|
|
24
|
+
const day = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
|
25
|
+
return `fix/npm-audit-${day}-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
|
|
26
|
+
}
|
|
27
|
+
/** Variables qui authentifient git auprès de GitHub par un en-tête HTTP, sans écrire le token dans le clone. */
|
|
28
|
+
function gitAuthEnv(config) {
|
|
29
|
+
const basic = Buffer.from(`x-access-token:${config.token}`).toString("base64");
|
|
30
|
+
return {
|
|
31
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
32
|
+
GCM_INTERACTIVE: "never",
|
|
33
|
+
GIT_CONFIG_COUNT: "1",
|
|
34
|
+
GIT_CONFIG_KEY_0: `http.${config.serverUrl}/.extraheader`,
|
|
35
|
+
GIT_CONFIG_VALUE_0: `AUTHORIZATION: basic ${basic}`,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
const NPM_ENV = { npm_config_update_notifier: "false", npm_config_fund: "false" };
|
|
39
|
+
/** Sous-commande git d'une liste d'arguments, après les options `-c clé=valeur`. */
|
|
40
|
+
function subcommand(args) {
|
|
41
|
+
let index = 0;
|
|
42
|
+
while (args[index] === "-c")
|
|
43
|
+
index += 2;
|
|
44
|
+
return args[index] ?? "";
|
|
45
|
+
}
|
|
46
|
+
function newOperation(repo, kind, origin) {
|
|
47
|
+
const createdAt = now();
|
|
48
|
+
return {
|
|
49
|
+
id: `op-${Date.now().toString(36)}-${crypto.randomBytes(3).toString("hex")}`,
|
|
50
|
+
repoId: repo.id,
|
|
51
|
+
kind,
|
|
52
|
+
origin,
|
|
53
|
+
status: "running",
|
|
54
|
+
createdAt,
|
|
55
|
+
updatedAt: createdAt,
|
|
56
|
+
pid: process.pid,
|
|
57
|
+
workDir: null,
|
|
58
|
+
baseBranch: repo.defaultBranch,
|
|
59
|
+
cancelRequested: false,
|
|
60
|
+
steps: { clone: "pending", audit: "pending", fix: "pending", force: "pending", push: "pending" },
|
|
61
|
+
projects: [],
|
|
62
|
+
counts: { initial: null, afterFix: null, afterForce: null },
|
|
63
|
+
remaining: [],
|
|
64
|
+
forceCandidates: [],
|
|
65
|
+
changes: [],
|
|
66
|
+
commitMessage: DEFAULT_COMMIT_MESSAGE,
|
|
67
|
+
branch: null,
|
|
68
|
+
pullRequest: null,
|
|
69
|
+
error: null,
|
|
70
|
+
log: [],
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
/** Exécution des étapes d'une opération, avec son signal d'annulation. */
|
|
74
|
+
class Runner {
|
|
75
|
+
ctx;
|
|
76
|
+
id;
|
|
77
|
+
signal;
|
|
78
|
+
config;
|
|
79
|
+
cloneDir;
|
|
80
|
+
constructor(ctx, id, signal, config, cloneDir) {
|
|
81
|
+
this.ctx = ctx;
|
|
82
|
+
this.id = id;
|
|
83
|
+
this.signal = signal;
|
|
84
|
+
this.config = config;
|
|
85
|
+
this.cloneDir = cloneDir;
|
|
86
|
+
}
|
|
87
|
+
get operation() {
|
|
88
|
+
return this.ctx.store.getOperation(this.id);
|
|
89
|
+
}
|
|
90
|
+
update(fn) {
|
|
91
|
+
return this.ctx.store.updateOperation(this.id, fn);
|
|
92
|
+
}
|
|
93
|
+
setStep(step, state) {
|
|
94
|
+
this.update((operation) => ({ ...operation, steps: { ...operation.steps, [step]: state } }));
|
|
95
|
+
}
|
|
96
|
+
log(text) {
|
|
97
|
+
const entry = { at: now(), text: text.length > MAX_LOG_TEXT ? `${text.slice(0, MAX_LOG_TEXT)}…` : text };
|
|
98
|
+
this.update((operation) => ({ ...operation, log: [...operation.log, entry].slice(-MAX_LOG_ENTRIES) }));
|
|
99
|
+
}
|
|
100
|
+
get repoDir() {
|
|
101
|
+
const workDir = this.operation.workDir;
|
|
102
|
+
if (!workDir)
|
|
103
|
+
throw new TrackerError(`Operation ${this.id} has no clone.`);
|
|
104
|
+
return path.join(workDir, CLONE_DIR);
|
|
105
|
+
}
|
|
106
|
+
async run(command, args, cwd, env = {}) {
|
|
107
|
+
this.log(`$ ${command} ${args.join(" ")}`);
|
|
108
|
+
return runCommand(command, args, { cwd, env, signal: this.signal });
|
|
109
|
+
}
|
|
110
|
+
/** git dans le clone ; un code de sortie non nul lève une erreur avec la fin de stderr. */
|
|
111
|
+
async git(args, options = {}) {
|
|
112
|
+
const result = await this.run("git", args, options.cwd ?? this.repoDir, options.auth ? gitAuthEnv(this.config) : {});
|
|
113
|
+
if (result.code !== 0) {
|
|
114
|
+
const detail = tail(result.stderr) || tail(result.stdout);
|
|
115
|
+
this.log(detail);
|
|
116
|
+
throw new TrackerError(`git ${subcommand(args)} failed: ${detail}`);
|
|
117
|
+
}
|
|
118
|
+
return result.stdout;
|
|
119
|
+
}
|
|
120
|
+
/** npm dans le dossier d'un projet du clone ; sa sortie JSON est lue même avec un code de sortie non nul. */
|
|
121
|
+
async npm(project, args) {
|
|
122
|
+
const result = await this.run("npm", args, path.join(this.repoDir, project), NPM_ENV);
|
|
123
|
+
return parseNpmJson(result.stdout, result.stderr, `npm ${args.slice(0, args.indexOf("--json")).join(" ")} in ${projectLabel(project) || "./"}`);
|
|
124
|
+
}
|
|
125
|
+
readLock(project) {
|
|
126
|
+
const file = path.join(this.repoDir, project, "package-lock.json");
|
|
127
|
+
return parseLockfile(fs.readFileSync(file, "utf-8"), project);
|
|
128
|
+
}
|
|
129
|
+
/** Lockfile du projet tel qu'il est dans le commit cloné. */
|
|
130
|
+
async originalLock(project) {
|
|
131
|
+
const file = project === "" ? "package-lock.json" : `${project}/package-lock.json`;
|
|
132
|
+
return parseLockfile(await this.git(["show", `HEAD:${file}`]), project);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
// --- Étapes -------------------------------------------------------------------
|
|
136
|
+
async function cloneStep(runner) {
|
|
137
|
+
runner.setStep("clone", "running");
|
|
138
|
+
const operation = runner.operation;
|
|
139
|
+
const [owner, name] = operation.repoId.split("/");
|
|
140
|
+
const workDir = fs.mkdtempSync(path.join(runner.cloneDir, "mcp-dependabot-tracker-"));
|
|
141
|
+
runner.update((current) => ({ ...current, workDir }));
|
|
142
|
+
const url = `${runner.config.serverUrl}/${owner}/${name}.git`;
|
|
143
|
+
await runner.git(["-c", "core.autocrlf=false", "clone", "--depth", "1", "--branch", operation.baseBranch, "--single-branch", url, CLONE_DIR], {
|
|
144
|
+
cwd: workDir,
|
|
145
|
+
auth: true,
|
|
146
|
+
});
|
|
147
|
+
const files = (await runner.git(["ls-files", "-z"])).split("\0");
|
|
148
|
+
const projects = files
|
|
149
|
+
.filter((file) => file === "package-lock.json" || file.endsWith("/package-lock.json"))
|
|
150
|
+
.map((file) => path.posix.dirname(file))
|
|
151
|
+
.map((dir) => (dir === "." ? "" : dir))
|
|
152
|
+
.sort();
|
|
153
|
+
if (projects.length === 0) {
|
|
154
|
+
throw new TrackerError(`No package-lock.json is tracked in ${operation.repoId}: npm audit needs a lockfile.`);
|
|
155
|
+
}
|
|
156
|
+
runner.update((current) => ({ ...current, projects }));
|
|
157
|
+
runner.log(`npm projects: ${projects.map((project) => projectLabel(project) || "./").join(", ")}`);
|
|
158
|
+
runner.setStep("clone", "done");
|
|
159
|
+
}
|
|
160
|
+
/** `npm audit` dans chaque projet ; enregistre le total sous `count` et les vulnérabilités restantes. */
|
|
161
|
+
async function auditAll(runner, count) {
|
|
162
|
+
const vulnerabilities = [];
|
|
163
|
+
for (const project of runner.operation.projects) {
|
|
164
|
+
vulnerabilities.push(...parseAuditReport(await runner.npm(project, ["audit", "--json"]), project));
|
|
165
|
+
}
|
|
166
|
+
runner.log(`${vulnerabilities.length} vulnerabilit${vulnerabilities.length === 1 ? "y" : "ies"}`);
|
|
167
|
+
runner.update((operation) => ({
|
|
168
|
+
...operation,
|
|
169
|
+
counts: { ...operation.counts, [count]: vulnerabilities.length },
|
|
170
|
+
remaining: vulnerabilities.map(({ project, name, severity, fix }) => ({ project, name, severity, fix })),
|
|
171
|
+
}));
|
|
172
|
+
return vulnerabilities;
|
|
173
|
+
}
|
|
174
|
+
/** Paquets modifiés depuis le commit cloné, dans tous les projets. */
|
|
175
|
+
async function refreshChanges(runner) {
|
|
176
|
+
const changes = [];
|
|
177
|
+
for (const project of runner.operation.projects) {
|
|
178
|
+
changes.push(...diffLockfiles(await runner.originalLock(project), runner.readLock(project), project));
|
|
179
|
+
}
|
|
180
|
+
runner.update((operation) => ({ ...operation, changes }));
|
|
181
|
+
}
|
|
182
|
+
async function auditStep(runner) {
|
|
183
|
+
runner.setStep("audit", "running");
|
|
184
|
+
const vulnerabilities = await auditAll(runner, "initial");
|
|
185
|
+
runner.setStep("audit", "done");
|
|
186
|
+
return vulnerabilities;
|
|
187
|
+
}
|
|
188
|
+
/** `npm audit fix` dans les projets vulnérables, sans installer node_modules ni lancer de scripts. */
|
|
189
|
+
async function fixStep(runner, vulnerabilities) {
|
|
190
|
+
runner.setStep("fix", "running");
|
|
191
|
+
const projects = new Set(vulnerabilities.map((vulnerability) => vulnerability.project));
|
|
192
|
+
for (const project of runner.operation.projects.filter((candidate) => projects.has(candidate))) {
|
|
193
|
+
await runner.npm(project, ["audit", "fix", "--package-lock-only", "--ignore-scripts", "--json"]);
|
|
194
|
+
}
|
|
195
|
+
const remaining = await auditAll(runner, "afterFix");
|
|
196
|
+
await refreshChanges(runner);
|
|
197
|
+
const locks = Object.fromEntries(runner.operation.projects.map((project) => [project, runner.readLock(project)]));
|
|
198
|
+
runner.update((operation) => ({ ...operation, forceCandidates: forceCandidates(remaining, locks) }));
|
|
199
|
+
runner.setStep("fix", "done");
|
|
200
|
+
return remaining;
|
|
201
|
+
}
|
|
202
|
+
/** `npm audit fix --force` dans les projets qui ont une montée majeure à appliquer. */
|
|
203
|
+
async function forceStep(runner) {
|
|
204
|
+
runner.setStep("force", "running");
|
|
205
|
+
const projects = new Set(runner.operation.forceCandidates.map((candidate) => candidate.project));
|
|
206
|
+
for (const project of runner.operation.projects.filter((candidate) => projects.has(candidate))) {
|
|
207
|
+
await runner.npm(project, ["audit", "fix", "--force", "--package-lock-only", "--ignore-scripts", "--json"]);
|
|
208
|
+
}
|
|
209
|
+
await auditAll(runner, "afterForce");
|
|
210
|
+
await refreshChanges(runner);
|
|
211
|
+
runner.setStep("force", "done");
|
|
212
|
+
}
|
|
213
|
+
function pullRequestBody(operation) {
|
|
214
|
+
const after = operation.counts.afterForce ?? operation.counts.afterFix;
|
|
215
|
+
const lines = [
|
|
216
|
+
"Automated `npm audit` fixes, made by mcp-dependabot-tracker in a temporary clone (`npm audit fix --package-lock-only --ignore-scripts`).",
|
|
217
|
+
"",
|
|
218
|
+
`- Vulnerabilities before: ${operation.counts.initial}`,
|
|
219
|
+
`- Vulnerabilities after: ${after}`,
|
|
220
|
+
`- \`npm audit fix --force\`: ${operation.steps.force === "done" ? "applied" : "not applied"}`,
|
|
221
|
+
"",
|
|
222
|
+
`Updated packages (${operation.changes.length}):`,
|
|
223
|
+
"",
|
|
224
|
+
];
|
|
225
|
+
for (const change of operation.changes.slice(0, MAX_PR_CHANGES)) {
|
|
226
|
+
lines.push(`- \`${projectLabel(change.project)}${change.name}\` ${change.from ?? "(added)"} → ${change.to ?? "(removed)"}`);
|
|
227
|
+
}
|
|
228
|
+
if (operation.changes.length > MAX_PR_CHANGES)
|
|
229
|
+
lines.push(`- … and ${operation.changes.length - MAX_PR_CHANGES} more`);
|
|
230
|
+
return lines.join("\n");
|
|
231
|
+
}
|
|
232
|
+
/** Commit des lockfiles modifiés sur une nouvelle branche, push, puis pull request vers la branche par défaut. */
|
|
233
|
+
async function pushStep(runner) {
|
|
234
|
+
runner.setStep("push", "running");
|
|
235
|
+
const operation = runner.operation;
|
|
236
|
+
const [owner, name] = operation.repoId.split("/");
|
|
237
|
+
const github = new GitHubClient(runner.config);
|
|
238
|
+
const user = await github.getAuthenticatedUser();
|
|
239
|
+
const branch = operation.branch ?? branchName(new Date());
|
|
240
|
+
runner.update((current) => ({ ...current, branch }));
|
|
241
|
+
await runner.git(["checkout", "-b", branch]);
|
|
242
|
+
await runner.git(["add", "-A"]);
|
|
243
|
+
if ((await runner.git(["status", "--porcelain"])).trim() === "") {
|
|
244
|
+
throw new TrackerError("Nothing to commit: the fixes left the files unchanged.");
|
|
245
|
+
}
|
|
246
|
+
await runner.git([
|
|
247
|
+
"-c",
|
|
248
|
+
`user.name=${user.name ?? user.login}`,
|
|
249
|
+
"-c",
|
|
250
|
+
`user.email=${user.id}+${user.login}@users.noreply.github.com`,
|
|
251
|
+
"commit",
|
|
252
|
+
"-m",
|
|
253
|
+
operation.commitMessage,
|
|
254
|
+
]);
|
|
255
|
+
await runner.git(["push", "origin", `HEAD:refs/heads/${branch}`], { auth: true });
|
|
256
|
+
const title = operation.commitMessage.split(/\r?\n/)[0];
|
|
257
|
+
let pullRequest;
|
|
258
|
+
try {
|
|
259
|
+
pullRequest = await github.createPullRequest(owner, name, { title, head: branch, base: operation.baseBranch, body: pullRequestBody(runner.operation) });
|
|
260
|
+
}
|
|
261
|
+
catch (err) {
|
|
262
|
+
throw new TrackerError(`Branch ${branch} was pushed, but the pull request could not be opened: ${err?.message ?? err}`);
|
|
263
|
+
}
|
|
264
|
+
runner.log(`Pull request #${pullRequest.number}: ${pullRequest.url}`);
|
|
265
|
+
runner.update((current) => ({ ...current, pullRequest }));
|
|
266
|
+
runner.setStep("push", "done");
|
|
267
|
+
}
|
|
268
|
+
// --- Enchaînement ------------------------------------------------------------
|
|
269
|
+
function finish(runner) {
|
|
270
|
+
runner.update((operation) => ({
|
|
271
|
+
...operation,
|
|
272
|
+
status: "done",
|
|
273
|
+
steps: Object.fromEntries(Object.entries(operation.steps).map(([step, state]) => [step, state === "pending" ? "skipped" : state])),
|
|
274
|
+
}));
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Après les corrections : la suite attend l'utilisateur, avec le nom de la
|
|
278
|
+
* branche qui sera poussée, ou l'opération se termine s'il n'y a rien à pousser.
|
|
279
|
+
*/
|
|
280
|
+
function settleForPush(runner) {
|
|
281
|
+
if (runner.operation.changes.length > 0) {
|
|
282
|
+
runner.update((operation) => ({ ...operation, status: "waiting_push", branch: branchName(new Date()) }));
|
|
283
|
+
}
|
|
284
|
+
else {
|
|
285
|
+
finish(runner);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Exécute `body` pour l'opération `id`, avec un signal déclenché par une demande
|
|
290
|
+
* d'annulation enregistrée par n'importe quel processus. Une erreur fait échouer
|
|
291
|
+
* l'opération et l'étape en cours ; une opération terminée perd son clone.
|
|
292
|
+
*/
|
|
293
|
+
async function execute(ctx, id, body) {
|
|
294
|
+
const controller = new AbortController();
|
|
295
|
+
const watcher = setInterval(() => {
|
|
296
|
+
try {
|
|
297
|
+
if (ctx.store.getOperation(id).cancelRequested)
|
|
298
|
+
controller.abort();
|
|
299
|
+
}
|
|
300
|
+
catch {
|
|
301
|
+
// Lecture concurrente ou verrou occupé : la demande est relue au tour suivant.
|
|
302
|
+
}
|
|
303
|
+
}, CANCEL_POLL_MS);
|
|
304
|
+
try {
|
|
305
|
+
const runner = new Runner(ctx, id, controller.signal, ctx.githubConfig(), ctx.cloneDir());
|
|
306
|
+
await body(runner);
|
|
307
|
+
}
|
|
308
|
+
catch (err) {
|
|
309
|
+
const cancelled = err instanceof CommandAbortedError || controller.signal.aborted;
|
|
310
|
+
ctx.store.updateOperation(id, (operation) => ({
|
|
311
|
+
...operation,
|
|
312
|
+
status: cancelled ? "cancelled" : "failed",
|
|
313
|
+
error: cancelled ? null : (err?.message ?? String(err)),
|
|
314
|
+
steps: Object.fromEntries(Object.entries(operation.steps).map(([step, state]) => [
|
|
315
|
+
step,
|
|
316
|
+
state === "running" ? (cancelled ? "skipped" : "failed") : state === "pending" ? "skipped" : state,
|
|
317
|
+
])),
|
|
318
|
+
}));
|
|
319
|
+
}
|
|
320
|
+
finally {
|
|
321
|
+
clearInterval(watcher);
|
|
322
|
+
}
|
|
323
|
+
return cleanUp(ctx, id);
|
|
324
|
+
}
|
|
325
|
+
/** Supprime le clone d'une opération terminée. */
|
|
326
|
+
function cleanUp(ctx, id) {
|
|
327
|
+
const operation = ctx.store.getOperation(id);
|
|
328
|
+
if (isActive(operation) || !operation.workDir)
|
|
329
|
+
return operation;
|
|
330
|
+
fs.rmSync(operation.workDir, { recursive: true, force: true });
|
|
331
|
+
return ctx.store.updateOperation(id, (current) => ({ ...current, workDir: null }));
|
|
332
|
+
}
|
|
333
|
+
/** Passe une opération en attente à `running` dans ce processus ; refusé si elle n'attend pas `expected`. */
|
|
334
|
+
function resume(ctx, id, expected, fn) {
|
|
335
|
+
return ctx.store.updateOperation(id, (operation) => {
|
|
336
|
+
if (operation.status !== expected) {
|
|
337
|
+
throw new ConflictError(`Operation ${id} is ${operation.status}, not ${expected}.`);
|
|
338
|
+
}
|
|
339
|
+
return fn({ ...operation, status: "running", pid: process.pid });
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
/** Laisse une exécution se poursuivre en arrière-plan ; une erreur imprévue est journalisée. */
|
|
343
|
+
function inBackground(ctx, id, run) {
|
|
344
|
+
run.catch((err) => ctx.logError(`Operation ${id} could not be recorded: ${err?.stack ?? err}`));
|
|
345
|
+
}
|
|
346
|
+
// --- Entrées ---------------------------------------------------------------------
|
|
347
|
+
/**
|
|
348
|
+
* Lance une correction depuis la GUI : clone, audit et `npm audit fix` s'exécutent
|
|
349
|
+
* en arrière-plan, puis l'opération attend la décision sur `--force` ou le push.
|
|
350
|
+
*/
|
|
351
|
+
export function startUserFix(ctx, repoId) {
|
|
352
|
+
ctx.githubConfig();
|
|
353
|
+
const repo = ctx.store.getRepo(repoId);
|
|
354
|
+
const operation = ctx.store.createOperation(newOperation(repo, "fix", "user"));
|
|
355
|
+
inBackground(ctx, operation.id, execute(ctx, operation.id, async (runner) => {
|
|
356
|
+
await cloneStep(runner);
|
|
357
|
+
const vulnerabilities = await auditStep(runner);
|
|
358
|
+
if (vulnerabilities.length === 0)
|
|
359
|
+
return finish(runner);
|
|
360
|
+
await fixStep(runner, vulnerabilities);
|
|
361
|
+
if (runner.operation.forceCandidates.length > 0) {
|
|
362
|
+
runner.update((current) => ({ ...current, status: "waiting_force" }));
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
runner.setStep("force", "skipped");
|
|
366
|
+
settleForPush(runner);
|
|
367
|
+
}));
|
|
368
|
+
return operation;
|
|
369
|
+
}
|
|
370
|
+
/** Applique ou passe `npm audit fix --force` sur une opération qui attend cette décision. */
|
|
371
|
+
export function decideForce(ctx, id, apply) {
|
|
372
|
+
const operation = resume(ctx, id, "waiting_force", (current) => current);
|
|
373
|
+
inBackground(ctx, id, execute(ctx, id, async (runner) => {
|
|
374
|
+
if (apply) {
|
|
375
|
+
await forceStep(runner);
|
|
376
|
+
}
|
|
377
|
+
else {
|
|
378
|
+
runner.setStep("force", "skipped");
|
|
379
|
+
}
|
|
380
|
+
settleForPush(runner);
|
|
381
|
+
}));
|
|
382
|
+
return operation;
|
|
383
|
+
}
|
|
384
|
+
/** Commit, push et pull request d'une opération qui attend le push. */
|
|
385
|
+
export function pushOperation(ctx, id, commitMessage) {
|
|
386
|
+
const operation = resume(ctx, id, "waiting_push", (current) => ({ ...current, commitMessage }));
|
|
387
|
+
inBackground(ctx, id, execute(ctx, id, async (runner) => {
|
|
388
|
+
await pushStep(runner);
|
|
389
|
+
finish(runner);
|
|
390
|
+
}));
|
|
391
|
+
return operation;
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Annule une opération : une opération en attente se termine aussitôt ; une
|
|
395
|
+
* opération en cours reçoit une demande d'annulation, lue par le processus qui
|
|
396
|
+
* l'exécute, qui arrête sa commande.
|
|
397
|
+
*/
|
|
398
|
+
export function cancelOperation(ctx, id) {
|
|
399
|
+
ctx.store.failOrphanedOperations();
|
|
400
|
+
const operation = ctx.store.updateOperation(id, (current) => {
|
|
401
|
+
if (!isActive(current))
|
|
402
|
+
throw new ConflictError(`Operation ${id} is already ${current.status}.`);
|
|
403
|
+
if (current.status === "running")
|
|
404
|
+
return { ...current, cancelRequested: true };
|
|
405
|
+
return {
|
|
406
|
+
...current,
|
|
407
|
+
status: "cancelled",
|
|
408
|
+
steps: Object.fromEntries(Object.entries(current.steps).map(([step, state]) => [step, state === "pending" ? "skipped" : state])),
|
|
409
|
+
};
|
|
410
|
+
});
|
|
411
|
+
return cleanUp(ctx, operation.id);
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Opération menée par l'agent d'un bout à l'autre, attendue jusqu'à sa fin :
|
|
415
|
+
* `audit` s'arrête après `npm audit` ; `fix` enchaîne `npm audit fix`, puis
|
|
416
|
+
* `--force` et le push selon `plan`.
|
|
417
|
+
*/
|
|
418
|
+
export async function runAgentOperation(ctx, repoId, kind, plan) {
|
|
419
|
+
ctx.githubConfig();
|
|
420
|
+
const repo = ctx.store.getRepo(repoId);
|
|
421
|
+
const operation = ctx.store.createOperation({ ...newOperation(repo, kind, "agent"), commitMessage: plan.commitMessage });
|
|
422
|
+
return execute(ctx, operation.id, async (runner) => {
|
|
423
|
+
await cloneStep(runner);
|
|
424
|
+
const vulnerabilities = await auditStep(runner);
|
|
425
|
+
if (kind === "audit" || vulnerabilities.length === 0)
|
|
426
|
+
return finish(runner);
|
|
427
|
+
await fixStep(runner, vulnerabilities);
|
|
428
|
+
if (plan.force && runner.operation.forceCandidates.length > 0) {
|
|
429
|
+
await forceStep(runner);
|
|
430
|
+
}
|
|
431
|
+
else {
|
|
432
|
+
runner.setStep("force", "skipped");
|
|
433
|
+
}
|
|
434
|
+
if (plan.push && runner.operation.changes.length > 0)
|
|
435
|
+
await pushStep(runner);
|
|
436
|
+
finish(runner);
|
|
437
|
+
});
|
|
438
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export interface RepoRef {
|
|
2
|
+
owner: string;
|
|
3
|
+
name: string;
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Lit `propriétaire/nom`, un lien web (`https://github.com/propriétaire/nom/…`)
|
|
7
|
+
* ou une URL de clone (`…/nom.git`, `git@github.com:propriétaire/nom.git`).
|
|
8
|
+
*/
|
|
9
|
+
export declare function parseRepoRef(input: string): RepoRef;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { TrackerError } from "./errors.js";
|
|
2
|
+
const SEGMENT = /^[A-Za-z0-9_.-]+$/;
|
|
3
|
+
/**
|
|
4
|
+
* Lit `propriétaire/nom`, un lien web (`https://github.com/propriétaire/nom/…`)
|
|
5
|
+
* ou une URL de clone (`…/nom.git`, `git@github.com:propriétaire/nom.git`).
|
|
6
|
+
*/
|
|
7
|
+
export function parseRepoRef(input) {
|
|
8
|
+
const raw = input.trim();
|
|
9
|
+
let pathPart = raw;
|
|
10
|
+
const scp = /^[^@\s]+@[^:\s]+:(.+)$/.exec(raw);
|
|
11
|
+
if (scp) {
|
|
12
|
+
pathPart = scp[1];
|
|
13
|
+
}
|
|
14
|
+
else if (/^[a-z]+:\/\//i.test(raw)) {
|
|
15
|
+
try {
|
|
16
|
+
pathPart = new URL(raw).pathname;
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
throw invalid(raw);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
const segments = pathPart.split("/").filter((segment) => segment !== "");
|
|
23
|
+
if (segments.length < 2)
|
|
24
|
+
throw invalid(raw);
|
|
25
|
+
const owner = segments[0];
|
|
26
|
+
const name = segments[1].replace(/\.git$/, "");
|
|
27
|
+
if (!SEGMENT.test(owner) || !SEGMENT.test(name) || name === "." || name === "..")
|
|
28
|
+
throw invalid(raw);
|
|
29
|
+
return { owner, name };
|
|
30
|
+
}
|
|
31
|
+
function invalid(raw) {
|
|
32
|
+
return new TrackerError(`"${raw}" is not a GitHub repository: expected owner/name or a github.com link.`);
|
|
33
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type Alert, type AlertSeverity, type Repo, type Rights } from "../../shared/schemas/model.schema.js";
|
|
2
|
+
import type { RepoView } from "../../shared/schemas/api.schema.js";
|
|
3
|
+
import type { GitHubConfig } from "./config.js";
|
|
4
|
+
import { type Store } from "./store.js";
|
|
5
|
+
/** Ancienneté au-delà de laquelle les alertes d'un dépôt sont relues sur GitHub. */
|
|
6
|
+
export declare const SYNC_INTERVAL_MS: number;
|
|
7
|
+
/** Alertes de la plus grave à la moins grave, puis par paquet. */
|
|
8
|
+
export declare function sortAlerts(alerts: Alert[]): Alert[];
|
|
9
|
+
/** Nombre d'alertes ouvertes par gravité. */
|
|
10
|
+
export declare function countBySeverity(alerts: Alert[]): Record<AlertSeverity, number>;
|
|
11
|
+
/** Dépôts triés par gravité la plus haute, puis par nombre d'alertes, puis par nom ; un dépôt sans alerte vient en dernier. */
|
|
12
|
+
export declare function sortRepos<T extends {
|
|
13
|
+
repo: Repo;
|
|
14
|
+
}>(views: T[]): T[];
|
|
15
|
+
export declare function repoView(store: Store, repo: Repo): RepoView;
|
|
16
|
+
export declare function listRepoViews(store: Store): RepoView[];
|
|
17
|
+
/** Relit les alertes Dependabot ouvertes du dépôt ; un échec est enregistré dans `syncError`, alertes précédentes conservées. */
|
|
18
|
+
export declare function syncRepository(store: Store, config: GitHubConfig, repoId: string): Promise<Repo>;
|
|
19
|
+
/** Suit un nouveau dépôt, avec l'audit pour seul droit de l'agent, puis lit ses alertes. */
|
|
20
|
+
export declare function addRepository(store: Store, config: GitHubConfig, input: string): Promise<Repo>;
|
|
21
|
+
/** Dépôts accessibles au token qui ne sont pas encore suivis, proposés à l'ajout. */
|
|
22
|
+
export declare function listAddableRepositories(store: Store, config: GitHubConfig): Promise<string[]>;
|
|
23
|
+
export declare function setRights(store: Store, repoId: string, rights: Rights): Repo;
|
|
24
|
+
/** Dépôts jamais synchronisés, ou synchronisés il y a plus de `maxAgeMs`. */
|
|
25
|
+
export declare function staleRepos(store: Store, maxAgeMs: number, at?: number): Repo[];
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { ALERT_SEVERITIES, DEFAULT_RIGHTS } from "../../shared/schemas/model.schema.js";
|
|
2
|
+
import { ConflictError } from "./errors.js";
|
|
3
|
+
import { GitHubClient } from "./github.js";
|
|
4
|
+
import { parseRepoRef } from "./repo-ref.js";
|
|
5
|
+
import { isActive } from "./store.js";
|
|
6
|
+
/** Ancienneté au-delà de laquelle les alertes d'un dépôt sont relues sur GitHub. */
|
|
7
|
+
export const SYNC_INTERVAL_MS = 10 * 60_000;
|
|
8
|
+
function severityRank(severity) {
|
|
9
|
+
return ALERT_SEVERITIES.indexOf(severity);
|
|
10
|
+
}
|
|
11
|
+
/** Alertes de la plus grave à la moins grave, puis par paquet. */
|
|
12
|
+
export function sortAlerts(alerts) {
|
|
13
|
+
return [...alerts].sort((a, b) => severityRank(a.severity) - severityRank(b.severity) || a.package.localeCompare(b.package) || a.number - b.number);
|
|
14
|
+
}
|
|
15
|
+
/** Nombre d'alertes ouvertes par gravité. */
|
|
16
|
+
export function countBySeverity(alerts) {
|
|
17
|
+
const counts = Object.fromEntries(ALERT_SEVERITIES.map((severity) => [severity, 0]));
|
|
18
|
+
for (const alert of alerts)
|
|
19
|
+
counts[alert.severity] += 1;
|
|
20
|
+
return counts;
|
|
21
|
+
}
|
|
22
|
+
/** Dépôts triés par gravité la plus haute, puis par nombre d'alertes, puis par nom ; un dépôt sans alerte vient en dernier. */
|
|
23
|
+
export function sortRepos(views) {
|
|
24
|
+
const key = (repo) => {
|
|
25
|
+
const worst = repo.alerts.reduce((best, alert) => Math.min(best, severityRank(alert.severity)), ALERT_SEVERITIES.length);
|
|
26
|
+
return { worst, count: repo.alerts.length };
|
|
27
|
+
};
|
|
28
|
+
return [...views].sort((a, b) => {
|
|
29
|
+
const ka = key(a.repo);
|
|
30
|
+
const kb = key(b.repo);
|
|
31
|
+
return ka.worst - kb.worst || kb.count - ka.count || a.repo.id.localeCompare(b.repo.id);
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
export function repoView(store, repo) {
|
|
35
|
+
const operations = store.listOperations(repo.id);
|
|
36
|
+
return {
|
|
37
|
+
repo: { ...repo, alerts: sortAlerts(repo.alerts) },
|
|
38
|
+
activeOperation: operations.find(isActive) ?? null,
|
|
39
|
+
latestOperation: operations[0] ?? null,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
export function listRepoViews(store) {
|
|
43
|
+
store.failOrphanedOperations();
|
|
44
|
+
return sortRepos(store.listRepos().map((repo) => repoView(store, repo)));
|
|
45
|
+
}
|
|
46
|
+
/** Relit les alertes Dependabot ouvertes du dépôt ; un échec est enregistré dans `syncError`, alertes précédentes conservées. */
|
|
47
|
+
export async function syncRepository(store, config, repoId) {
|
|
48
|
+
const repo = store.getRepo(repoId);
|
|
49
|
+
const github = new GitHubClient(config);
|
|
50
|
+
try {
|
|
51
|
+
const alerts = await github.listOpenAlerts(repo.owner, repo.name);
|
|
52
|
+
return store.updateRepo(repo.id, (current) => ({ ...current, alerts, syncedAt: new Date().toISOString(), syncError: null }));
|
|
53
|
+
}
|
|
54
|
+
catch (err) {
|
|
55
|
+
const message = err?.message ?? String(err);
|
|
56
|
+
return store.updateRepo(repo.id, (current) => ({ ...current, syncedAt: new Date().toISOString(), syncError: message }));
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** Suit un nouveau dépôt, avec l'audit pour seul droit de l'agent, puis lit ses alertes. */
|
|
60
|
+
export async function addRepository(store, config, input) {
|
|
61
|
+
const ref = parseRepoRef(input);
|
|
62
|
+
if (store.findRepo(`${ref.owner}/${ref.name}`))
|
|
63
|
+
throw new ConflictError(`Repository ${ref.owner}/${ref.name} is already tracked.`);
|
|
64
|
+
const remote = await new GitHubClient(config).getRepository(ref.owner, ref.name);
|
|
65
|
+
store.addRepo({
|
|
66
|
+
id: remote.fullName,
|
|
67
|
+
owner: remote.owner,
|
|
68
|
+
name: remote.name,
|
|
69
|
+
defaultBranch: remote.defaultBranch,
|
|
70
|
+
addedAt: new Date().toISOString(),
|
|
71
|
+
rights: DEFAULT_RIGHTS,
|
|
72
|
+
alerts: [],
|
|
73
|
+
syncedAt: null,
|
|
74
|
+
syncError: null,
|
|
75
|
+
});
|
|
76
|
+
return syncRepository(store, config, remote.fullName);
|
|
77
|
+
}
|
|
78
|
+
/** Dépôts accessibles au token qui ne sont pas encore suivis, proposés à l'ajout. */
|
|
79
|
+
export async function listAddableRepositories(store, config) {
|
|
80
|
+
const tracked = new Set(store.listRepos().map((repo) => repo.id.toLowerCase()));
|
|
81
|
+
const accessible = await new GitHubClient(config).listAccessibleRepositories();
|
|
82
|
+
return accessible.filter((name) => !tracked.has(name.toLowerCase()));
|
|
83
|
+
}
|
|
84
|
+
export function setRights(store, repoId, rights) {
|
|
85
|
+
return store.updateRepo(repoId, (repo) => ({ ...repo, rights }));
|
|
86
|
+
}
|
|
87
|
+
/** Dépôts jamais synchronisés, ou synchronisés il y a plus de `maxAgeMs`. */
|
|
88
|
+
export function staleRepos(store, maxAgeMs, at = Date.now()) {
|
|
89
|
+
return store.listRepos().filter((repo) => repo.syncedAt === null || at - Date.parse(repo.syncedAt) > maxAgeMs);
|
|
90
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { type Operation, type Repo } from "../../shared/schemas/model.schema.js";
|
|
2
|
+
/** Vrai si le processus `pid` existe encore. */
|
|
3
|
+
export declare function processAlive(pid: number): boolean;
|
|
4
|
+
export declare function isActive(operation: Operation): boolean;
|
|
5
|
+
/**
|
|
6
|
+
* Persistance : `<dataDir>/repos.json` pour les dépôts suivis et
|
|
7
|
+
* `<dataDir>/operations/<id>.json` pour chaque opération. Plusieurs processus
|
|
8
|
+
* (une instance du serveur par session d'agent) partagent le répertoire :
|
|
9
|
+
* chaque écriture passe par le verrou `<dataDir>/data.lock`.
|
|
10
|
+
*/
|
|
11
|
+
export declare class Store {
|
|
12
|
+
readonly dataDir: string;
|
|
13
|
+
private readonly reposPath;
|
|
14
|
+
private readonly operationsDir;
|
|
15
|
+
private readonly lockPath;
|
|
16
|
+
constructor(dataDir: string);
|
|
17
|
+
/** Sérialise les écritures entre processus : `wx` échoue si le verrou existe déjà. Non réentrant. */
|
|
18
|
+
private withLock;
|
|
19
|
+
private readRepos;
|
|
20
|
+
private writeRepos;
|
|
21
|
+
listRepos(): Repo[];
|
|
22
|
+
/** Dépôt d'identifiant `propriétaire/nom`, sans tenir compte de la casse, comme GitHub. */
|
|
23
|
+
findRepo(repoId: string): Repo | null;
|
|
24
|
+
getRepo(repoId: string): Repo;
|
|
25
|
+
addRepo(repo: Repo): Repo;
|
|
26
|
+
updateRepo(repoId: string, fn: (repo: Repo) => Repo): Repo;
|
|
27
|
+
/** Retire un dépôt et ses opérations ; refusé pendant une opération en cours. */
|
|
28
|
+
removeRepo(repoId: string): void;
|
|
29
|
+
private operationPath;
|
|
30
|
+
private readOperationFile;
|
|
31
|
+
private readAllOperations;
|
|
32
|
+
private readOperationsOf;
|
|
33
|
+
getOperation(id: string): Operation;
|
|
34
|
+
/** Opérations d'un dépôt, de la plus récente à la plus ancienne. */
|
|
35
|
+
listOperations(repoId: string): Operation[];
|
|
36
|
+
activeOperation(repoId: string): Operation | null;
|
|
37
|
+
/**
|
|
38
|
+
* Enregistre une nouvelle opération ; refusé si une autre est en cours sur le
|
|
39
|
+
* même dépôt. Les opérations terminées au-delà des 20 plus récentes sont supprimées.
|
|
40
|
+
*/
|
|
41
|
+
createOperation(operation: Operation): Operation;
|
|
42
|
+
updateOperation(id: string, fn: (operation: Operation) => Operation): Operation;
|
|
43
|
+
/**
|
|
44
|
+
* Opérations `running` dont le processus a disparu : elles passent en échec et
|
|
45
|
+
* leur clone est supprimé. Les opérations en attente d'une décision ne
|
|
46
|
+
* dépendent d'aucun processus et restent en l'état.
|
|
47
|
+
*/
|
|
48
|
+
failOrphanedOperations(): Operation[];
|
|
49
|
+
}
|