@imenam/mcp-dependabot-tracker 1.0.32 → 1.0.34

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.
@@ -0,0 +1,484 @@
1
+ import { spawnSync } from "child_process";
2
+ import fs from "fs";
3
+ import path from "path";
4
+ import dotenv from "dotenv";
5
+ import { addUser, closeAuth, createAuth, generateAuthSecret, listUsers, migrateAuth } from "../core/auth.js";
6
+ import { readServerConfig } from "../core/server-config.js";
7
+ import { SERVICE_NAME, mergeEnvFile, nextFreeSubIdRange, renderNginxSite, renderSystemdUnit, subIdRangesOf, } from "../core/setup-files.js";
8
+ import { generateVaultKey } from "../core/vault.js";
9
+ import { promptHidden, promptLine } from "./prompt.js";
10
+ /**
11
+ * Commande `setup` : installation complète du serveur sur une machine Linux
12
+ * avec systemd, lancée en root. Elle pose ses questions (adresse publique,
13
+ * port, compte de service, données, nginx et certificat, premier compte), en
14
+ * proposant les valeurs du `.env` existant, puis : installe les paquets
15
+ * manquants, crée le compte de service, lui attribue une plage libre de
16
+ * sous-identifiants et active son lingering, écrit le `.env` (clés générées
17
+ * une fois, puis conservées), crée le premier compte de l'interface, prépare
18
+ * Podman rootless, écrit et démarre l'unité systemd, vérifie que le serveur
19
+ * répond, puis configure nginx et le certificat quand ils sont demandés.
20
+ * Relancée, elle reprend la configuration en place.
21
+ */
22
+ export const SETUP_USAGE = `Usage : mcp-dependabot-tracker setup [options]
23
+
24
+ Installe le serveur sur cette machine (Linux, systemd), en root. Les questions
25
+ proposent les valeurs du .env existant ; sans terminal, ou avec --non-interactive,
26
+ chaque réponse vient d'une option, sinon du .env existant ou du défaut.
27
+
28
+ --app-url=<url> adresse publique de l'interface (https://…)
29
+ --port=<n> port d'écoute, sur 127.0.0.1 [4700]
30
+ --service-user=<compte> compte système du service [${SERVICE_NAME}]
31
+ --data-dir=<chemin> répertoire des données [<dossier du compte>/data]
32
+ --nginx=oui|non servir l'adresse publique par nginx [oui en https]
33
+ --certbot=oui|non obtenir le certificat avec certbot [oui avec nginx]
34
+ --admin-email=<adresse> premier compte de l'interface
35
+ --admin-name=<nom> nom affiché de ce compte
36
+ --non-interactive ne rien demander
37
+
38
+ Le mot de passe du compte n'est jamais un argument : il est saisi sans écho, ou
39
+ lu dans SETUP_ADMIN_PASSWORD.`;
40
+ const VALUE_OPTIONS = ["app-url", "port", "service-user", "data-dir", "nginx", "certbot", "admin-email", "admin-name"];
41
+ /** Paquets nécessaires au serveur : git, Podman rootless, et le bac à sable de Claude Code. */
42
+ export const BASE_PACKAGES = ["git", "podman", "uidmap", "passt", "slirp4netns", "catatonit", "bubblewrap", "socat"];
43
+ const DEFAULT_PORT = "4700";
44
+ const MIN_PASSWORD_LENGTH = 12;
45
+ const HEALTH_TIMEOUT_MS = 30_000;
46
+ const RUNTIME_DIR_TIMEOUT_MS = 10_000;
47
+ class SetupError extends Error {
48
+ }
49
+ function fail(message) {
50
+ throw new SetupError(message);
51
+ }
52
+ /** Machine réelle : commandes, terminal et fichiers de la machine. */
53
+ export function realHost(packageRoot) {
54
+ return {
55
+ platform: process.platform,
56
+ isRoot: typeof process.getuid === "function" && process.getuid() === 0,
57
+ interactive: process.stdin.isTTY === true,
58
+ root: "/",
59
+ packageRoot,
60
+ nodePath: process.execPath,
61
+ run: (command, args, options = {}) => {
62
+ const result = spawnSync(command, args, {
63
+ cwd: options.cwd,
64
+ env: { ...process.env, ...options.env },
65
+ encoding: "utf-8",
66
+ stdio: options.inherit ? ["ignore", "inherit", "inherit"] : ["ignore", "pipe", "pipe"],
67
+ });
68
+ if (result.error)
69
+ return { code: 127, stdout: "", stderr: result.error.message };
70
+ return { code: result.status ?? 1, stdout: result.stdout ?? "", stderr: result.stderr ?? "" };
71
+ },
72
+ ask: (question) => promptLine(`${question} : `),
73
+ askSecret: (question) => promptHidden(`${question} : `),
74
+ say: (line) => process.stdout.write(`${line}\n`),
75
+ waitHealthy: async (port, timeoutMs) => {
76
+ const deadline = Date.now() + timeoutMs;
77
+ while (Date.now() < deadline) {
78
+ const ok = await fetch(`http://127.0.0.1:${port}/health`).then((response) => response.ok, () => false);
79
+ if (ok)
80
+ return true;
81
+ await new Promise((resolve) => setTimeout(resolve, 1000));
82
+ }
83
+ return false;
84
+ },
85
+ };
86
+ }
87
+ /** Lit les options `--nom=valeur` ; une option inconnue ou répétée est refusée. */
88
+ export function parseSetupArgs(argv) {
89
+ const values = {};
90
+ let nonInteractive = false;
91
+ for (const arg of argv) {
92
+ if (arg === "--non-interactive") {
93
+ nonInteractive = true;
94
+ continue;
95
+ }
96
+ const match = /^--([a-z-]+)=(.*)$/.exec(arg);
97
+ if (!match)
98
+ fail(`Argument inattendu : « ${arg} ».\n\n${SETUP_USAGE}`);
99
+ const [, name, value] = match;
100
+ if (name === "admin-password" || name === "password")
101
+ fail("Le mot de passe ne se passe pas en argument, qui reste lisible dans l'historique et la liste des processus : saisissez-le, ou définissez SETUP_ADMIN_PASSWORD.");
102
+ if (!VALUE_OPTIONS.includes(name))
103
+ fail(`Option inconnue : --${name}.\n\n${SETUP_USAGE}`);
104
+ if (values[name] !== undefined)
105
+ fail(`--${name} est donné plusieurs fois.`);
106
+ values[name] = value.trim();
107
+ }
108
+ return { values, nonInteractive };
109
+ }
110
+ class Prompter {
111
+ host;
112
+ args;
113
+ constructor(host, args) {
114
+ this.host = host;
115
+ this.args = args;
116
+ }
117
+ get interactive() {
118
+ return this.host.interactive && !this.args.nonInteractive;
119
+ }
120
+ provided(option) {
121
+ return this.args.values[option];
122
+ }
123
+ /** Réponse : option, puis saisie (valeur proposée sur Entrée), ou valeur proposée sans terminal. */
124
+ async value(spec) {
125
+ const given = this.provided(spec.option);
126
+ if (given !== undefined) {
127
+ try {
128
+ const value = spec.validate(given);
129
+ this.host.say(` ${spec.question} : ${given}`);
130
+ return value;
131
+ }
132
+ catch (err) {
133
+ fail(`--${spec.option} : ${err.message}`);
134
+ }
135
+ }
136
+ if (!this.interactive) {
137
+ if (spec.proposed === undefined)
138
+ fail(`Sans terminal, --${spec.option} est requis (${spec.question.toLowerCase()}).`);
139
+ try {
140
+ const value = spec.validate(spec.proposed);
141
+ this.host.say(` ${spec.question} : ${spec.proposed}`);
142
+ return value;
143
+ }
144
+ catch (err) {
145
+ fail(`${spec.question} : la valeur ${spec.proposed} est invalide, ${err.message} Passez --${spec.option}.`);
146
+ }
147
+ }
148
+ for (;;) {
149
+ const raw = await this.host.ask(`${spec.question}${spec.proposed !== undefined ? ` [${spec.proposed}]` : ""}`);
150
+ const candidate = raw === "" ? spec.proposed : raw;
151
+ if (candidate === undefined) {
152
+ this.host.say(" ! Une réponse est attendue.");
153
+ continue;
154
+ }
155
+ try {
156
+ return spec.validate(candidate);
157
+ }
158
+ catch (err) {
159
+ this.host.say(` ! ${err.message}`);
160
+ }
161
+ }
162
+ }
163
+ }
164
+ function validateAppUrl(raw) {
165
+ let url;
166
+ try {
167
+ url = new URL(raw);
168
+ }
169
+ catch {
170
+ throw new Error(`« ${raw} » n'est pas une adresse : attendu par exemple https://deps.example.com.`);
171
+ }
172
+ if (url.protocol !== "https:")
173
+ throw new Error("une adresse en https est attendue : le serveur installé est servi derrière un reverse proxy qui porte le certificat.");
174
+ if (url.pathname !== "/" || url.search || url.hash || url.username)
175
+ throw new Error("l'adresse ne doit avoir ni chemin, ni paramètres, ni identifiants : l'interface est servie à la racine.");
176
+ return url;
177
+ }
178
+ function validatePort(raw) {
179
+ const port = Number(raw);
180
+ if (!/^\d+$/.test(raw) || port < 1 || port > 65535)
181
+ throw new Error(`port invalide (${raw}) : un entier entre 1 et 65535.`);
182
+ return port;
183
+ }
184
+ function validateServiceUser(raw) {
185
+ if (!/^[a-z_][a-z0-9_-]{0,31}$/.test(raw))
186
+ throw new Error(`compte invalide (${raw}) : minuscules, chiffres, « _ » et « - ».`);
187
+ return raw;
188
+ }
189
+ function validateAbsolutePath(raw) {
190
+ if (!path.isAbsolute(raw))
191
+ throw new Error(`chemin absolu attendu (${raw}).`);
192
+ return path.resolve(raw);
193
+ }
194
+ function validateBoolean(raw) {
195
+ const value = raw.trim().toLowerCase();
196
+ if (["o", "oui", "y", "yes"].includes(value))
197
+ return true;
198
+ if (["n", "non", "no"].includes(value))
199
+ return false;
200
+ throw new Error(`réponse invalide (${raw}) : oui ou non.`);
201
+ }
202
+ function validateEmail(raw) {
203
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(raw))
204
+ throw new Error(`adresse e-mail invalide (${raw}).`);
205
+ return raw.toLowerCase();
206
+ }
207
+ function validateName(raw) {
208
+ if (raw.trim() === "")
209
+ throw new Error("nom vide.");
210
+ return raw.trim();
211
+ }
212
+ // --- Système -------------------------------------------------------------------
213
+ /** Chemin d'un fichier système sous la racine de l'hôte. */
214
+ function sys(host, file) {
215
+ return path.join(host.root, file);
216
+ }
217
+ function readIfExists(file) {
218
+ return fs.existsSync(file) ? fs.readFileSync(file, "utf-8") : undefined;
219
+ }
220
+ /** Lance une commande et lève une erreur qui cite sa sortie si elle échoue. */
221
+ function must(host, command, args, options = {}) {
222
+ const result = host.run(command, args, options);
223
+ if (result.code !== 0) {
224
+ const output = `${result.stderr}\n${result.stdout}`.trim().split("\n").slice(-6).join("\n");
225
+ fail(`« ${[command, ...args].join(" ")} » a échoué (code ${result.code})${output ? ` :\n${output}` : "."}`);
226
+ }
227
+ return result;
228
+ }
229
+ /** Compte système d'après `getent passwd`, ou null s'il n'existe pas. */
230
+ function accountOf(host, user) {
231
+ const result = host.run("getent", ["passwd", user]);
232
+ if (result.code !== 0)
233
+ return null;
234
+ const [, , uid, gid, , home] = result.stdout.trim().split(":");
235
+ return { uid: Number(uid), gid: Number(gid), home };
236
+ }
237
+ /** Paquets de `wanted` qui ne sont pas installés. */
238
+ function missingPackages(host, wanted) {
239
+ return wanted.filter((name) => !host.run("dpkg-query", ["-W", "-f=${Status}", name]).stdout.includes("install ok installed"));
240
+ }
241
+ async function waitFor(check, timeoutMs) {
242
+ const deadline = Date.now() + timeoutMs;
243
+ for (;;) {
244
+ if (check())
245
+ return true;
246
+ if (Date.now() >= deadline)
247
+ return false;
248
+ await new Promise((resolve) => setTimeout(resolve, 200));
249
+ }
250
+ }
251
+ /** Site nginx déjà activé, autre que celui du tracker, qui sert `hostname`. */
252
+ function nginxSiteServing(host, hostname) {
253
+ const dir = sys(host, "/etc/nginx/sites-enabled");
254
+ if (!fs.existsSync(dir))
255
+ return null;
256
+ const pattern = new RegExp(`server_name[^;]*\\s${hostname.replace(/\./g, "\\.")}[\\s;]`);
257
+ for (const entry of fs.readdirSync(dir)) {
258
+ if (entry === SERVICE_NAME)
259
+ continue;
260
+ const text = readIfExists(path.join(dir, entry));
261
+ if (text !== undefined && pattern.test(text))
262
+ return path.join("/etc/nginx/sites-enabled", entry);
263
+ }
264
+ return null;
265
+ }
266
+ async function readPassword(host, prompter) {
267
+ const fromEnv = process.env.SETUP_ADMIN_PASSWORD;
268
+ if (fromEnv) {
269
+ if (fromEnv.length < MIN_PASSWORD_LENGTH)
270
+ fail(`SETUP_ADMIN_PASSWORD doit faire au moins ${MIN_PASSWORD_LENGTH} caractères.`);
271
+ host.say(" Mot de passe : repris de SETUP_ADMIN_PASSWORD.");
272
+ return fromEnv;
273
+ }
274
+ if (!prompter.interactive)
275
+ fail("Sans terminal, SETUP_ADMIN_PASSWORD est requis pour créer le compte.");
276
+ for (;;) {
277
+ const first = await host.askSecret(`Mot de passe, non affiché (${MIN_PASSWORD_LENGTH} caractères minimum)`);
278
+ if (first.length < MIN_PASSWORD_LENGTH) {
279
+ host.say(` ! Au moins ${MIN_PASSWORD_LENGTH} caractères.`);
280
+ continue;
281
+ }
282
+ if ((await host.askSecret("Confirmation")) !== first) {
283
+ host.say(" ! Les deux saisies diffèrent.");
284
+ continue;
285
+ }
286
+ return first;
287
+ }
288
+ }
289
+ /** Comptes de l'interface déjà créés dans `dataDir`. */
290
+ async function existingAccounts(dataDir, env) {
291
+ if (!fs.existsSync(path.join(dataDir, "auth.sqlite")))
292
+ return 0;
293
+ const auth = createAuth(dataDir, readServerConfig(env));
294
+ try {
295
+ await migrateAuth(auth);
296
+ return (await listUsers(auth)).length;
297
+ }
298
+ finally {
299
+ closeAuth(auth);
300
+ }
301
+ }
302
+ async function planAccount(host, prompter, count) {
303
+ if (count > 0 && prompter.provided("admin-email") === undefined) {
304
+ const answer = prompter.interactive ? await host.ask(`${count} compte(s) existe(nt) déjà. Adresse d'un compte à ajouter (Entrée pour aucun)`) : "";
305
+ if (answer === "") {
306
+ host.say(` Comptes : inchangés (${count}).`);
307
+ return null;
308
+ }
309
+ const email = validateEmail(answer);
310
+ return { email, name: await prompter.value({ option: "admin-name", question: "Nom affiché", validate: validateName }), password: await readPassword(host, prompter) };
311
+ }
312
+ const email = await prompter.value({ option: "admin-email", question: "Adresse e-mail du premier compte", validate: validateEmail });
313
+ const name = await prompter.value({ option: "admin-name", question: "Nom affiché", validate: validateName });
314
+ return { email, name, password: await readPassword(host, prompter) };
315
+ }
316
+ /** Exécute la commande ; rend le code de sortie. */
317
+ export async function runSetup(argv, host) {
318
+ const step = (title) => host.say(`\n== ${title}`);
319
+ try {
320
+ const args = parseSetupArgs(argv);
321
+ if (host.platform !== "linux")
322
+ fail("setup installe un service systemd : lancez-le sur le serveur Linux qui hébergera le tracker.");
323
+ if (!host.isRoot)
324
+ fail("setup crée un compte système et écrit dans /etc : relancez-le en root (sudo).");
325
+ if (host.run("systemctl", ["--version"]).code !== 0)
326
+ fail("systemd est introuvable (systemctl) : setup installe un service systemd.");
327
+ const prompter = new Prompter(host, args);
328
+ const envFile = path.join(host.packageRoot, ".env");
329
+ const existingText = readIfExists(envFile);
330
+ const existing = existingText === undefined ? {} : dotenv.parse(existingText);
331
+ const kept = (key) => (existing[key] ? existing[key] : undefined);
332
+ host.say("Dependabot Tracker — installation du serveur");
333
+ host.say(existingText === undefined ? ` Nouvelle configuration : ${envFile}` : ` Configuration existante reprise : ${envFile}`);
334
+ step("Adresse");
335
+ const appUrl = await prompter.value({ option: "app-url", question: "Adresse publique de l'interface", proposed: kept("APP_URL"), validate: validateAppUrl });
336
+ const port = await prompter.value({ option: "port", question: "Port d'écoute (sur 127.0.0.1)", proposed: kept("APP_PORT") ?? DEFAULT_PORT, validate: validatePort });
337
+ step("Compte de service et données");
338
+ const serviceUser = await prompter.value({ option: "service-user", question: "Compte système du service", proposed: SERVICE_NAME, validate: validateServiceUser });
339
+ const current = accountOf(host, serviceUser);
340
+ const home = current?.home ?? `/var/lib/${serviceUser}`;
341
+ const dataDir = await prompter.value({ option: "data-dir", question: "Répertoire des données", proposed: kept("DATA_DIR") ?? `${home}/data`, validate: validateAbsolutePath });
342
+ step("Reverse proxy");
343
+ const nginx = await prompter.value({ option: "nginx", question: `Servir ${appUrl.hostname} par nginx`, proposed: "oui", validate: validateBoolean });
344
+ const servedBy = nginx ? nginxSiteServing(host, appUrl.hostname) : null;
345
+ if (servedBy)
346
+ host.say(` nginx sert déjà ${appUrl.hostname} (${servedBy}) : ce site est gardé tel quel.`);
347
+ const certbot = nginx && !servedBy ? await prompter.value({ option: "certbot", question: "Obtenir le certificat avec certbot", proposed: "oui", validate: validateBoolean }) : false;
348
+ if (!nginx)
349
+ host.say(` Le reverse proxy qui porte le certificat de ${appUrl.hostname} doit joindre 127.0.0.1:${port}.`);
350
+ const values = {
351
+ DATA_DIR: dataDir,
352
+ APP_URL: appUrl.origin,
353
+ APP_PORT: String(port),
354
+ AUTH_SECRET: kept("AUTH_SECRET") ?? generateAuthSecret(),
355
+ VAULT_KEY: kept("VAULT_KEY") ?? generateVaultKey(),
356
+ TRUSTED_PROXIES: kept("TRUSTED_PROXIES") ?? "127.0.0.1",
357
+ };
358
+ const env = { ...existing, ...values };
359
+ try {
360
+ readServerConfig(env);
361
+ }
362
+ catch (err) {
363
+ fail(err.message);
364
+ }
365
+ step("Premier compte de l'interface");
366
+ const account = await planAccount(host, prompter, await existingAccounts(dataDir, env));
367
+ const certbotEmail = certbot ? (account?.email ?? (await prompter.value({ option: "admin-email", question: "Adresse e-mail pour Let's Encrypt", validate: validateEmail }))) : null;
368
+ if (prompter.interactive) {
369
+ const go = validateBoolean((await host.ask("\nTout est prêt. Lancer l'installation ? [oui]")) || "oui");
370
+ if (!go)
371
+ fail("installation abandonnée, rien n'a été modifié.");
372
+ }
373
+ step("Paquets");
374
+ const packages = [...BASE_PACKAGES, ...(nginx && !servedBy ? ["nginx"] : []), ...(certbot ? ["certbot", "python3-certbot-nginx"] : [])];
375
+ const missing = missingPackages(host, packages);
376
+ if (missing.length === 0)
377
+ host.say(" Tous présents.");
378
+ else {
379
+ host.say(` Installation : ${missing.join(" ")}`);
380
+ must(host, "apt-get", ["update"], { inherit: true, env: { DEBIAN_FRONTEND: "noninteractive" } });
381
+ must(host, "apt-get", ["install", "-y", ...missing], { inherit: true, env: { DEBIAN_FRONTEND: "noninteractive" } });
382
+ }
383
+ step("Compte de service");
384
+ if (current)
385
+ host.say(` ${serviceUser} existe (uid ${current.uid}, ${current.home}).`);
386
+ else {
387
+ must(host, "useradd", ["--system", "--user-group", "--create-home", "--home-dir", home, "--shell", "/usr/sbin/nologin", serviceUser]);
388
+ host.say(` ${serviceUser} créé (${home}).`);
389
+ }
390
+ const accountInfo = accountOf(host, serviceUser) ?? fail(`le compte ${serviceUser} est introuvable après sa création.`);
391
+ const group = must(host, "id", ["-gn", serviceUser]).stdout.trim();
392
+ const subuid = readIfExists(sys(host, "/etc/subuid")) ?? "";
393
+ const subgid = readIfExists(sys(host, "/etc/subgid")) ?? "";
394
+ if (subIdRangesOf(subuid, serviceUser).length > 0 && subIdRangesOf(subgid, serviceUser).length > 0) {
395
+ host.say(" Sous-identifiants : plage déjà attribuée.");
396
+ }
397
+ else {
398
+ const range = nextFreeSubIdRange(subuid, subgid);
399
+ const spec = `${range.start}-${range.start + range.count - 1}`;
400
+ must(host, "usermod", ["--add-subuids", spec, "--add-subgids", spec, serviceUser]);
401
+ host.say(` Sous-identifiants : ${spec}.`);
402
+ }
403
+ must(host, "loginctl", ["enable-linger", serviceUser]);
404
+ const runtimeDir = `/run/user/${accountInfo.uid}`;
405
+ if (!(await waitFor(() => fs.existsSync(sys(host, runtimeDir)), RUNTIME_DIR_TIMEOUT_MS))) {
406
+ fail(`${runtimeDir} n'existe pas malgré le lingering : vérifiez « loginctl show-user ${serviceUser} ».`);
407
+ }
408
+ host.say(` Lingering actif (${runtimeDir}).`);
409
+ step("Configuration");
410
+ fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
411
+ fs.writeFileSync(envFile, mergeEnvFile(existingText, values), { mode: 0o640 });
412
+ fs.chmodSync(envFile, 0o640);
413
+ must(host, "chown", [`root:${group}`, envFile]);
414
+ host.say(` ${envFile} (lisible par root et ${group} seulement)`);
415
+ if (account) {
416
+ const auth = createAuth(dataDir, readServerConfig(env));
417
+ try {
418
+ await migrateAuth(auth);
419
+ const user = await addUser(auth, account);
420
+ host.say(` Compte ${user.email} créé.`);
421
+ }
422
+ finally {
423
+ closeAuth(auth);
424
+ }
425
+ }
426
+ must(host, "chown", ["-R", `${serviceUser}:${group}`, dataDir]);
427
+ step("Podman");
428
+ const asService = (command) => must(host, "runuser", ["-u", serviceUser, "--", "env", `XDG_RUNTIME_DIR=${runtimeDir}`, ...command], { cwd: accountInfo.home });
429
+ asService(["podman", "system", "migrate"]);
430
+ const rootless = asService(["podman", "info", "--format", "{{.Host.Security.Rootless}}"]).stdout.trim();
431
+ if (rootless !== "true")
432
+ fail(`Podman ne tourne pas en rootless sous ${serviceUser} (podman info : ${rootless || "rien"}).`);
433
+ host.say(` Rootless sous ${serviceUser}.`);
434
+ step("Service");
435
+ const layout = { serviceUser, serviceGroup: group, uid: accountInfo.uid, home: accountInfo.home, dataDir, packageRoot: host.packageRoot, nodePath: host.nodePath, port };
436
+ const unitFile = sys(host, `/etc/systemd/system/${SERVICE_NAME}.service`);
437
+ fs.mkdirSync(path.dirname(unitFile), { recursive: true });
438
+ fs.writeFileSync(unitFile, renderSystemdUnit(layout));
439
+ host.say(` /etc/systemd/system/${SERVICE_NAME}.service`);
440
+ const dropIns = sys(host, `/etc/systemd/system/${SERVICE_NAME}.service.d`);
441
+ if (fs.existsSync(dropIns) && fs.readdirSync(dropIns).length > 0) {
442
+ host.say(` Attention : /etc/systemd/system/${SERVICE_NAME}.service.d contient ${fs.readdirSync(dropIns).join(", ")}, qui complète(nt) l'unité.`);
443
+ }
444
+ must(host, "systemctl", ["daemon-reload"]);
445
+ must(host, "systemctl", ["enable", SERVICE_NAME]);
446
+ must(host, "systemctl", ["restart", SERVICE_NAME]);
447
+ if (!(await host.waitHealthy(port, HEALTH_TIMEOUT_MS)))
448
+ fail(`le serveur ne répond pas sur 127.0.0.1:${port} : voyez « journalctl -u ${SERVICE_NAME} -n 50 ».`);
449
+ host.say(` Démarré, répond sur 127.0.0.1:${port}.`);
450
+ if (nginx && !servedBy) {
451
+ step("nginx");
452
+ const site = sys(host, `/etc/nginx/sites-available/${SERVICE_NAME}`);
453
+ const enabled = sys(host, `/etc/nginx/sites-enabled/${SERVICE_NAME}`);
454
+ const existingSite = readIfExists(site);
455
+ if (existingSite === undefined) {
456
+ fs.mkdirSync(path.dirname(site), { recursive: true });
457
+ fs.writeFileSync(site, renderNginxSite(appUrl.hostname, port));
458
+ host.say(` /etc/nginx/sites-available/${SERVICE_NAME}`);
459
+ }
460
+ else
461
+ host.say(` /etc/nginx/sites-available/${SERVICE_NAME} existe : gardé tel quel.`);
462
+ if (!fs.existsSync(enabled))
463
+ must(host, "ln", ["-s", `/etc/nginx/sites-available/${SERVICE_NAME}`, enabled]);
464
+ must(host, "nginx", ["-t"]);
465
+ must(host, "systemctl", ["reload", "nginx"]);
466
+ host.say(" Site activé, nginx rechargé.");
467
+ if (certbot) {
468
+ must(host, "certbot", ["--nginx", "-d", appUrl.hostname, "--non-interactive", "--agree-tos", "-m", certbotEmail, "--redirect", "--keep-until-expiring"], { inherit: true });
469
+ host.say(` Certificat en place pour ${appUrl.hostname}.`);
470
+ }
471
+ }
472
+ step("Terminé");
473
+ host.say(` Interface : ${appUrl.origin}`);
474
+ host.say(` Données : ${dataDir} ; service : systemctl status ${SERVICE_NAME}`);
475
+ host.say(" Reste à faire dans l'interface : le token GitHub du tracker (Réglages › GitHub), puis le token Claude pour les corrections par Claude.");
476
+ if (account)
477
+ host.say(` Protégez le compte par un second facteur : mcp-dependabot-tracker user totp ${account.email}`);
478
+ return 0;
479
+ }
480
+ catch (err) {
481
+ process.stderr.write(`Installation interrompue : ${err?.message ?? err}\n`);
482
+ return 1;
483
+ }
484
+ }
@@ -1,8 +1,8 @@
1
- import readline from "readline";
2
1
  import QRCode from "qrcode";
3
2
  import { addUser, createAuth, currentTotpCode, disableTotp, enableTotp, listUsers, migrateAuth, prepareTotp, removeUser, setUserPassword } from "../core/auth.js";
4
3
  import { resolveDataDir } from "../core/data-dir.js";
5
4
  import { readAuthEnv } from "../core/server-config.js";
5
+ import { promptHidden, promptLine } from "./prompt.js";
6
6
  export const USERS_USAGE = [
7
7
  " mcp-dependabot-tracker user add <email> [--name=<nom>] crée un compte (mot de passe demandé)",
8
8
  " mcp-dependabot-tracker user password <email> change le mot de passe et ferme les sessions",
@@ -10,33 +10,6 @@ export const USERS_USAGE = [
10
10
  " mcp-dependabot-tracker user remove <email> supprime le compte",
11
11
  " mcp-dependabot-tracker user list liste les comptes",
12
12
  ].join("\n");
13
- /** Lit une ligne sur le terminal sans l'afficher. */
14
- function promptHidden(question) {
15
- return new Promise((resolve) => {
16
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true });
17
- const output = rl;
18
- let muted = false;
19
- output._writeToOutput = (text) => {
20
- if (!muted || text.includes("\n"))
21
- output.output.write(muted ? "\n" : text);
22
- };
23
- rl.question(question, (answer) => {
24
- rl.close();
25
- resolve(answer);
26
- });
27
- muted = true;
28
- });
29
- }
30
- /** Lit une ligne sur le terminal. */
31
- function promptLine(question) {
32
- return new Promise((resolve) => {
33
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true });
34
- rl.question(question, (answer) => {
35
- rl.close();
36
- resolve(answer.trim());
37
- });
38
- });
39
- }
40
13
  /** Essais du code de l'application avant l'abandon de l'activation. */
41
14
  const TOTP_CONFIRMATION_TRIES = 3;
42
15
  /** QR code de `text` en caractères, pour un terminal : deux modules par caractère, sur fond clair. */
@@ -725,6 +725,8 @@ export declare function createAuth(dataDir: string, env: AuthEnv): import("bette
725
725
  }];
726
726
  }>;
727
727
  export type Auth = ReturnType<typeof createAuth>;
728
+ /** Ferme la base SQLite d'une instance. */
729
+ export declare function closeAuth(auth: Auth): void;
728
730
  /** Crée ou complète les tables de Better Auth. */
729
731
  export declare function migrateAuth(auth: Auth): Promise<void>;
730
732
  /** Nouveau secret de session : 48 octets aléatoires en base64. */
@@ -70,6 +70,10 @@ export function createAuth(dataDir, env) {
70
70
  plugins: [twoFactor({ issuer: APP_NAME, totpOptions: { digits: TOTP_DIGITS, period: TOTP_PERIOD_SECONDS } })],
71
71
  });
72
72
  }
73
+ /** Ferme la base SQLite d'une instance. */
74
+ export function closeAuth(auth) {
75
+ auth.options.database.close();
76
+ }
73
77
  /** Crée ou complète les tables de Better Auth. */
74
78
  export async function migrateAuth(auth) {
75
79
  const { runMigrations } = await getMigrations(auth.options);
@@ -15,6 +15,8 @@ export declare class CommandAbortedError extends Error {
15
15
  }
16
16
  /** Arrête le processus et ses enfants. */
17
17
  export declare function killTree(pid: number): void;
18
+ /** Environnement du serveur transmis aux commandes : les seules variables de `PASSED_ENV`. */
19
+ export declare function inheritedEnv(): NodeJS.ProcessEnv;
18
20
  /**
19
21
  * Lance une commande sans shell, et attend sa fin. La commande reçoit les
20
22
  * variables système du serveur (`PASSED_ENV`), sans aucun de ses secrets, plus
@@ -64,7 +64,7 @@ const PASSED_ENV = [
64
64
  "XDG_DATA_HOME",
65
65
  ];
66
66
  /** Environnement du serveur transmis aux commandes : les seules variables de `PASSED_ENV`. */
67
- function inheritedEnv() {
67
+ export function inheritedEnv() {
68
68
  const env = {};
69
69
  for (const name of PASSED_ENV) {
70
70
  if (process.env[name] !== undefined)
@@ -32,6 +32,20 @@ export declare function organizerServer(connection: OrganizerConnection): {
32
32
  ORGANIZER_TOKEN: string;
33
33
  };
34
34
  };
35
+ /**
36
+ * Lancement du serveur `package-tools` du tracker sur le clone et le cache de
37
+ * l'opération, avec les outils de ses gestionnaires. Il reçoit les variables
38
+ * système du serveur (`HOME`, `XDG_RUNTIME_DIR`…), qui remplacent celles de
39
+ * Claude Code : Podman rootless y trouve le stockage et le dossier
40
+ * d'exécution du compte du serveur, où sont ses images.
41
+ */
42
+ export declare function packagesServer(input: Pick<RepairInput, "cwd" | "scope" | "managers" | "containers">, cache: string): {
43
+ command: string;
44
+ args: string[];
45
+ env: {
46
+ [k: string]: string;
47
+ };
48
+ };
35
49
  export interface RepairInput {
36
50
  repoId: string;
37
51
  branch: string;
@@ -4,6 +4,7 @@ import { fileURLToPath } from "url";
4
4
  import { z } from "zod";
5
5
  import { RepairReportSchema, TEST_OUTCOMES } from "../../shared/schemas/model.schema.js";
6
6
  import { runClaudeSession } from "./claude.js";
7
+ import { inheritedEnv } from "./commands.js";
7
8
  import { TrackerError } from "./errors.js";
8
9
  import { CACHE_DIR } from "./containers.js";
9
10
  import { managerOf } from "./managers/index.js";
@@ -52,12 +53,19 @@ export function organizerServer(connection) {
52
53
  const launch = process.platform === "win32" ? { command: "cmd", args: ["/c", "npx", "-y", ORGANIZER_PACKAGE] } : { command: "npx", args: ["-y", ORGANIZER_PACKAGE] };
53
54
  return { ...launch, env: { ORGANIZER_URL: connection.url, ORGANIZER_TOKEN: connection.token } };
54
55
  }
55
- /** Lancement du serveur `package-tools` du tracker sur le clone et le cache de l'opération, avec les outils de ses gestionnaires. */
56
- function packagesServer(input, cache) {
56
+ /**
57
+ * Lancement du serveur `package-tools` du tracker sur le clone et le cache de
58
+ * l'opération, avec les outils de ses gestionnaires. Il reçoit les variables
59
+ * système du serveur (`HOME`, `XDG_RUNTIME_DIR`…), qui remplacent celles de
60
+ * Claude Code : Podman rootless y trouve le stockage et le dossier
61
+ * d'exécution du compte du serveur, où sont ses images.
62
+ */
63
+ export function packagesServer(input, cache) {
57
64
  const entry = fileURLToPath(new URL("../package-tools.js", import.meta.url));
58
65
  return {
59
66
  command: process.execPath,
60
67
  args: [entry, "--root", input.cwd, "--cache", cache, "--scope", input.scope, "--managers", input.managers.join(","), "--runtime", JSON.stringify(input.containers.command)],
68
+ env: Object.fromEntries(Object.entries(inheritedEnv()).filter((entry) => entry[1] !== undefined)),
61
69
  };
62
70
  }
63
71
  /** Résultat demandé à Claude avec l'organizer : le rapport et la clé de la tâche. */
@@ -118,6 +118,12 @@ export declare function listRepoBranches(store: Store, config: GitHubConfig, rep
118
118
  export declare function setBranch(store: Store, config: GitHubConfig, repoId: string, branch: string): Promise<Repo>;
119
119
  /** Range le dépôt dans une catégorie, ou dans aucune avec null. */
120
120
  export declare function setCategory(store: Store, repoId: string, categoryId: string | null): Repo;
121
+ /**
122
+ * Remplace les tags du dépôt. Chaque nom est épuré de ses espaces de bord ; un
123
+ * nom déjà porté par un autre dépôt, à la casse près, reprend son écriture ; les
124
+ * doublons disparaissent et les tags sont rangés dans l'ordre alphabétique.
125
+ */
126
+ export declare function setTags(store: Store, repoId: string, tags: string[]): Repo;
121
127
  /** Marque une alerte ouverte comme corrigée à la main ; sans effet si elle l'est déjà. */
122
128
  export declare function markAlertHandled(store: Store, repoId: string, number: number): Repo;
123
129
  /** Retire la marque « corrigée à la main » d'une alerte. */