@imenam/mcp-dependabot-tracker 1.0.24 → 1.0.25
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 +186 -75
- package/dist/shared/schemas/agent-token.schema.d.ts +47 -0
- package/dist/shared/schemas/agent-token.schema.js +18 -0
- package/dist/shared/schemas/api.schema.d.ts +23 -23
- package/dist/shared/schemas/api.schema.js +8 -8
- package/dist/shared/schemas/deploy.schema.d.ts +174 -0
- package/dist/shared/schemas/deploy.schema.js +72 -0
- package/dist/shared/schemas/model.schema.d.ts +9 -26
- package/dist/shared/schemas/model.schema.js +7 -15
- package/dist/src/cli/setup-mcp.d.ts +19 -16
- package/dist/src/cli/setup-mcp.js +35 -82
- package/dist/src/cli/users.d.ts +5 -0
- package/dist/src/cli/users.js +164 -0
- package/dist/src/core/agent-tokens.d.ts +15 -0
- package/dist/src/core/agent-tokens.js +96 -0
- package/dist/src/core/auth.d.ts +774 -0
- package/dist/src/core/auth.js +191 -0
- package/dist/src/core/commands.d.ts +1 -1
- package/dist/src/core/commands.js +47 -4
- package/dist/src/core/config.d.ts +2 -3
- package/dist/src/core/config.js +2 -9
- package/dist/src/core/data-dir.d.ts +3 -1
- package/dist/src/core/data-dir.js +11 -5
- package/dist/src/core/deploy-servers.d.ts +77 -0
- package/dist/src/core/deploy-servers.js +480 -0
- package/dist/src/core/deployments.d.ts +75 -0
- package/dist/src/core/deployments.js +387 -0
- package/dist/src/core/github.d.ts +2 -0
- package/dist/src/core/github.js +8 -0
- package/dist/src/core/log-dir.d.ts +1 -5
- package/dist/src/core/log-dir.js +1 -5
- package/dist/src/core/npm-sandbox.d.ts +19 -3
- package/dist/src/core/npm-sandbox.js +87 -17
- package/dist/src/core/operations.d.ts +20 -18
- package/dist/src/core/operations.js +86 -70
- package/dist/src/core/repair.d.ts +0 -7
- package/dist/src/core/repair.js +10 -33
- package/dist/src/core/repos.d.ts +2 -3
- package/dist/src/core/repos.js +4 -7
- package/dist/src/core/server-config.d.ts +29 -0
- package/dist/src/core/server-config.js +85 -0
- package/dist/src/core/settings.d.ts +9 -3
- package/dist/src/core/settings.js +49 -10
- package/dist/src/core/ssh.d.ts +31 -0
- package/dist/src/core/ssh.js +82 -0
- package/dist/src/core/store.d.ts +5 -12
- package/dist/src/core/store.js +82 -160
- package/dist/src/core/vault.d.ts +10 -0
- package/dist/src/core/vault.js +50 -0
- package/dist/src/index.d.ts +9 -0
- package/dist/src/index.js +46 -455
- package/dist/src/mcp.d.ts +6 -0
- package/dist/src/mcp.js +59 -0
- package/dist/src/server/app.d.ts +47 -0
- package/dist/src/server/app.js +273 -0
- package/dist/src/server/serve.d.ts +7 -0
- package/dist/src/server/serve.js +178 -0
- package/dist/src/tools/client.d.ts +15 -0
- package/dist/src/tools/client.js +62 -0
- package/dist/src/tools/format.d.ts +4 -5
- package/dist/src/tools/format.js +39 -16
- package/dist/src/tools/tools.d.ts +101 -15
- package/dist/src/tools/tools.js +91 -62
- package/gui/dist/assets/index-FrRzRTkV.js +71 -0
- package/gui/dist/assets/index-o3l3BAZD.css +1 -0
- package/gui/dist/index.html +2 -2
- package/package.json +11 -4
- package/dist/shared/schemas/ipc.schema.d.ts +0 -26
- package/dist/shared/schemas/ipc.schema.js +0 -53
- package/dist/src/gui-worker.d.ts +0 -1
- package/dist/src/gui-worker.js +0 -379
- package/gui/dist/assets/index-BFMdldjC.css +0 -1
- package/gui/dist/assets/index-BFWRvPPl.js +0 -64
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
import crypto from "crypto";
|
|
2
|
+
import fs from "fs";
|
|
3
|
+
import path from "path";
|
|
4
|
+
import { StringDecoder } from "string_decoder";
|
|
5
|
+
import { DeploymentSchema } from "../../shared/schemas/deploy.schema.js";
|
|
6
|
+
import { ConflictError, NotFoundError, TrackerError } from "./errors.js";
|
|
7
|
+
import { GitHubClient } from "./github.js";
|
|
8
|
+
import { connectSsh, openExec } from "./ssh.js";
|
|
9
|
+
import { assertNotDeprecated } from "./store.js";
|
|
10
|
+
/** Déploiements terminés conservés par dépôt ; les plus anciens sont supprimés. */
|
|
11
|
+
const KEPT_DEPLOYMENTS_PER_REPO = 20;
|
|
12
|
+
/** Taille maximale de la sortie gardée : au-delà, seule la fin est conservée. */
|
|
13
|
+
export const OUTPUT_LIMIT = 200_000;
|
|
14
|
+
/** Intervalle d'écriture de la sortie pendant l'exécution. */
|
|
15
|
+
const FLUSH_MS = 500;
|
|
16
|
+
const DEPLOYMENT_ID_PATTERN = /^[a-z0-9-]+$/;
|
|
17
|
+
/** Ligne de trace de bash pour une ligne du script : `+__DT<fichier>:<ligne>__ commande`. */
|
|
18
|
+
const TRACE_LINE = /^\++__DT([^:]*):(\d+)__ /;
|
|
19
|
+
const PID_MARKER = /__DTPID_(\d+)__/;
|
|
20
|
+
/** Nom du fichier du script sur le serveur, celui que porte la trace de ses lignes. */
|
|
21
|
+
const SCRIPT_FILE = "deploy.sh";
|
|
22
|
+
function writeJsonAtomic(target, value) {
|
|
23
|
+
const tmp = `${target}.${crypto.randomBytes(4).toString("hex")}.tmp`;
|
|
24
|
+
try {
|
|
25
|
+
fs.writeFileSync(tmp, JSON.stringify(value, null, 2), { encoding: "utf-8", mode: 0o600 });
|
|
26
|
+
fs.renameSync(tmp, target);
|
|
27
|
+
}
|
|
28
|
+
catch (err) {
|
|
29
|
+
fs.rmSync(tmp, { force: true });
|
|
30
|
+
throw err;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/** Valeur entre apostrophes pour sh : `'` devient `'\''`. */
|
|
34
|
+
function shellQuote(value) {
|
|
35
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Script transmis à `sh -s` : écrit le script de déploiement et son lanceur
|
|
39
|
+
* dans un dossier temporaire, puis exécute le lanceur avec bash, l'entrée
|
|
40
|
+
* venant de /dev/null, depuis le dossier personnel. Le lanceur envoie la
|
|
41
|
+
* sortie du script sur stdout et la trace de bash (`set -x`) sur stderr, d'où
|
|
42
|
+
* le tracker lit la ligne en cours ; le numéro du processus, lu au début de
|
|
43
|
+
* stderr, sert à interrompre tout le groupe.
|
|
44
|
+
*/
|
|
45
|
+
export function remoteWrapper(script, variables) {
|
|
46
|
+
const token = crypto.randomBytes(8).toString("hex");
|
|
47
|
+
const body = script.endsWith("\n") ? script : `${script}\n`;
|
|
48
|
+
const exports = Object.entries(variables)
|
|
49
|
+
.map(([name, value]) => `export ${name}=${shellQuote(value)}`)
|
|
50
|
+
.join("\n");
|
|
51
|
+
return [
|
|
52
|
+
`d=$(mktemp -d) || exit 1`,
|
|
53
|
+
`trap 'rm -rf "$d"' EXIT`,
|
|
54
|
+
`cat > "$d/${SCRIPT_FILE}" <<'DTSCRIPT_${token}'`,
|
|
55
|
+
`${body}DTSCRIPT_${token}`,
|
|
56
|
+
`cat > "$d/run.sh" <<'DTRUN_${token}'`,
|
|
57
|
+
`exec 3>&2 2>&1`,
|
|
58
|
+
exports,
|
|
59
|
+
`BASH_XTRACEFD=3`,
|
|
60
|
+
`PS4='+__DT\${BASH_SOURCE[0]##*/}:\${LINENO}__ '`,
|
|
61
|
+
`set -x`,
|
|
62
|
+
`. "$1"`,
|
|
63
|
+
`DTRUN_${token}`,
|
|
64
|
+
`printf '__DTPID_%s__\\n' "$$" >&2`,
|
|
65
|
+
`cd`,
|
|
66
|
+
`bash "$d/run.sh" "$d/${SCRIPT_FILE}" </dev/null`,
|
|
67
|
+
`exit $?`,
|
|
68
|
+
``,
|
|
69
|
+
].join("\n");
|
|
70
|
+
}
|
|
71
|
+
/** Lit la trace de bash ligne à ligne et rend la dernière ligne du script commencée. */
|
|
72
|
+
export class TraceReader {
|
|
73
|
+
onLine;
|
|
74
|
+
buffer = "";
|
|
75
|
+
pid = null;
|
|
76
|
+
constructor(onLine) {
|
|
77
|
+
this.onLine = onLine;
|
|
78
|
+
}
|
|
79
|
+
push(chunk) {
|
|
80
|
+
this.buffer += chunk;
|
|
81
|
+
let end;
|
|
82
|
+
while ((end = this.buffer.indexOf("\n")) !== -1) {
|
|
83
|
+
const line = this.buffer.slice(0, end);
|
|
84
|
+
this.buffer = this.buffer.slice(end + 1);
|
|
85
|
+
const pid = PID_MARKER.exec(line);
|
|
86
|
+
if (pid && this.pid === null) {
|
|
87
|
+
this.pid = Number(pid[1]);
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
const trace = TRACE_LINE.exec(line);
|
|
91
|
+
if (trace && trace[1] === SCRIPT_FILE)
|
|
92
|
+
this.onLine(Number(trace[2]));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
/** Ajoute `text` à la sortie ; au-delà de la limite, seule la fin est gardée. */
|
|
97
|
+
export function appendOutput(output, text) {
|
|
98
|
+
const joined = output + text;
|
|
99
|
+
if (joined.length <= OUTPUT_LIMIT)
|
|
100
|
+
return { output: joined, truncated: false };
|
|
101
|
+
return { output: joined.slice(joined.length - OUTPUT_LIMIT), truncated: true };
|
|
102
|
+
}
|
|
103
|
+
export function deploymentSummary({ script: _script, output: _output, ...summary }) {
|
|
104
|
+
return summary;
|
|
105
|
+
}
|
|
106
|
+
/** Déploiements : `<données>/deployments/<id>.json`, écrits par le seul serveur. */
|
|
107
|
+
export class DeploymentStore {
|
|
108
|
+
dir;
|
|
109
|
+
constructor(dataDir) {
|
|
110
|
+
this.dir = path.join(dataDir, "deployments");
|
|
111
|
+
fs.mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
112
|
+
}
|
|
113
|
+
pathOf(id) {
|
|
114
|
+
if (!DEPLOYMENT_ID_PATTERN.test(id))
|
|
115
|
+
throw new NotFoundError(`Deployment "${id}" not found.`);
|
|
116
|
+
return path.join(this.dir, `${id}.json`);
|
|
117
|
+
}
|
|
118
|
+
readFile(file) {
|
|
119
|
+
let raw;
|
|
120
|
+
try {
|
|
121
|
+
raw = fs.readFileSync(file, "utf-8");
|
|
122
|
+
}
|
|
123
|
+
catch (err) {
|
|
124
|
+
if (err.code === "ENOENT")
|
|
125
|
+
return null;
|
|
126
|
+
throw err;
|
|
127
|
+
}
|
|
128
|
+
const parsed = DeploymentSchema.safeParse(JSON.parse(raw));
|
|
129
|
+
if (!parsed.success)
|
|
130
|
+
throw new TrackerError(`${file} is invalid: ${parsed.error.message}`);
|
|
131
|
+
return parsed.data;
|
|
132
|
+
}
|
|
133
|
+
readAll() {
|
|
134
|
+
const deployments = [];
|
|
135
|
+
for (const entry of fs.readdirSync(this.dir)) {
|
|
136
|
+
if (!entry.endsWith(".json"))
|
|
137
|
+
continue;
|
|
138
|
+
const deployment = this.readFile(path.join(this.dir, entry));
|
|
139
|
+
if (deployment)
|
|
140
|
+
deployments.push(deployment);
|
|
141
|
+
}
|
|
142
|
+
return deployments.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
143
|
+
}
|
|
144
|
+
/** Déploiements d'un dépôt, du plus récent au plus ancien. */
|
|
145
|
+
list(repoId) {
|
|
146
|
+
const key = repoId.toLowerCase();
|
|
147
|
+
return this.readAll().filter((deployment) => deployment.repoId.toLowerCase() === key);
|
|
148
|
+
}
|
|
149
|
+
get(id) {
|
|
150
|
+
const deployment = this.readFile(this.pathOf(id));
|
|
151
|
+
if (!deployment)
|
|
152
|
+
throw new NotFoundError(`Deployment "${id}" not found.`);
|
|
153
|
+
return deployment;
|
|
154
|
+
}
|
|
155
|
+
/** Déploiement en cours sur le serveur `serverId`, quel que soit le dépôt. */
|
|
156
|
+
runningOnServer(serverId) {
|
|
157
|
+
return this.readAll().find((deployment) => deployment.status === "running" && deployment.serverId === serverId) ?? null;
|
|
158
|
+
}
|
|
159
|
+
active(repoId) {
|
|
160
|
+
return this.list(repoId).find((deployment) => deployment.status === "running") ?? null;
|
|
161
|
+
}
|
|
162
|
+
/** Enregistre un déploiement ; refusé si un autre est en cours sur le dépôt. Au-delà des 20 plus récents, les anciens sont supprimés. */
|
|
163
|
+
create(deployment) {
|
|
164
|
+
const existing = this.list(deployment.repoId);
|
|
165
|
+
const active = existing.find((candidate) => candidate.status === "running");
|
|
166
|
+
if (active)
|
|
167
|
+
throw new ConflictError(`A deployment is already running on ${deployment.repoId}: wait for it to finish or interrupt it.`);
|
|
168
|
+
writeJsonAtomic(this.pathOf(deployment.id), DeploymentSchema.parse(deployment));
|
|
169
|
+
for (const old of existing.slice(KEPT_DEPLOYMENTS_PER_REPO - 1))
|
|
170
|
+
fs.rmSync(this.pathOf(old.id), { force: true });
|
|
171
|
+
return deployment;
|
|
172
|
+
}
|
|
173
|
+
update(id, fn) {
|
|
174
|
+
const updated = DeploymentSchema.parse({ ...fn(this.get(id)), updatedAt: new Date().toISOString() });
|
|
175
|
+
writeJsonAtomic(this.pathOf(id), updated);
|
|
176
|
+
return updated;
|
|
177
|
+
}
|
|
178
|
+
/** Supprime les déploiements d'un dépôt retiré du suivi. */
|
|
179
|
+
removeRepo(repoId) {
|
|
180
|
+
for (const deployment of this.list(repoId))
|
|
181
|
+
fs.rmSync(this.pathOf(deployment.id), { force: true });
|
|
182
|
+
}
|
|
183
|
+
/** Déploiements encore `running` au démarrage du serveur, que son arrêt a interrompus : ils passent en échec. */
|
|
184
|
+
failInterrupted() {
|
|
185
|
+
return this.readAll()
|
|
186
|
+
.filter((deployment) => deployment.status === "running")
|
|
187
|
+
.map((deployment) => this.update(deployment.id, (current) => ({
|
|
188
|
+
...current,
|
|
189
|
+
status: "failed",
|
|
190
|
+
endedAt: new Date().toISOString(),
|
|
191
|
+
error: "Interrompu : le serveur du tracker s'est arrêté pendant le déploiement.",
|
|
192
|
+
})));
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Déploiement des dépôts : chaque dépôt choisit un serveur et un script ; un
|
|
197
|
+
* déploiement exécute ce script sur le serveur, par SSH, et en suit la ligne en
|
|
198
|
+
* cours et la sortie. Un déploiement réussi retire la marque « à déployer ».
|
|
199
|
+
*/
|
|
200
|
+
export class Deployer {
|
|
201
|
+
store;
|
|
202
|
+
servers;
|
|
203
|
+
deployments;
|
|
204
|
+
github;
|
|
205
|
+
logError;
|
|
206
|
+
running = new Map();
|
|
207
|
+
constructor(store, servers, deployments, github, logError) {
|
|
208
|
+
this.store = store;
|
|
209
|
+
this.servers = servers;
|
|
210
|
+
this.deployments = deployments;
|
|
211
|
+
this.github = github;
|
|
212
|
+
this.logError = logError;
|
|
213
|
+
}
|
|
214
|
+
/** Serveur, script, déploiement en cours et derniers déploiements d'un dépôt. */
|
|
215
|
+
view(repoId) {
|
|
216
|
+
const repo = this.store.getRepo(repoId);
|
|
217
|
+
const deployments = this.deployments.list(repo.id);
|
|
218
|
+
return {
|
|
219
|
+
server: repo.deployServerId === null ? null : this.servers.view(this.servers.get(repo.deployServerId)),
|
|
220
|
+
script: repo.deployScript,
|
|
221
|
+
activeDeployment: deployments.find((deployment) => deployment.status === "running") ?? null,
|
|
222
|
+
deployments: deployments.map(deploymentSummary),
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
setServer(repoId, serverId) {
|
|
226
|
+
if (serverId !== null)
|
|
227
|
+
this.servers.get(serverId);
|
|
228
|
+
const repo = this.store.getRepo(repoId);
|
|
229
|
+
if (this.deployments.active(repo.id))
|
|
230
|
+
throw new ConflictError(`A deployment is running on ${repo.id}: wait for it to finish before changing its server.`);
|
|
231
|
+
this.store.updateRepo(repo.id, (current) => ({ ...current, deployServerId: serverId }));
|
|
232
|
+
return this.view(repo.id);
|
|
233
|
+
}
|
|
234
|
+
saveScript(repoId, script) {
|
|
235
|
+
const repo = this.store.getRepo(repoId);
|
|
236
|
+
this.store.updateRepo(repo.id, (current) => ({ ...current, deployScript: script.replace(/\r\n/g, "\n") }));
|
|
237
|
+
return this.view(repo.id);
|
|
238
|
+
}
|
|
239
|
+
/** Refuse une opération sur la clé d'un serveur pendant qu'un déploiement l'utilise. */
|
|
240
|
+
assertServerIdle(serverId) {
|
|
241
|
+
const running = this.deployments.runningOnServer(serverId);
|
|
242
|
+
if (running)
|
|
243
|
+
throw new ConflictError(`A deployment of ${running.repoId} is running on this server: wait for it to finish or interrupt it.`);
|
|
244
|
+
}
|
|
245
|
+
/** Lance le script du dépôt sur son serveur ; le déploiement se poursuit en arrière-plan. */
|
|
246
|
+
async start(repoId) {
|
|
247
|
+
const repo = this.store.getRepo(repoId);
|
|
248
|
+
assertNotDeprecated(repo);
|
|
249
|
+
if (repo.deployServerId === null)
|
|
250
|
+
throw new ConflictError(`${repo.id} has no deployment server: connect one first.`);
|
|
251
|
+
if (!repo.deployScript.trim())
|
|
252
|
+
throw new ConflictError(`${repo.id} has no deployment script: write it first.`);
|
|
253
|
+
const server = this.servers.get(repo.deployServerId);
|
|
254
|
+
if (server.publicKey === null)
|
|
255
|
+
throw new ConflictError(`The key of ${server.name} was revoked: install a new key first.`);
|
|
256
|
+
if (server.testedAt === null)
|
|
257
|
+
throw new ConflictError(`The connection to ${server.name} has not been tested: test it before deploying.`);
|
|
258
|
+
if (this.deployments.active(repo.id))
|
|
259
|
+
throw new ConflictError(`A deployment is already running on ${repo.id}: wait for it to finish or interrupt it.`);
|
|
260
|
+
const commit = await new GitHubClient(this.github).getBranchCommit(repo.owner, repo.name, repo.branch);
|
|
261
|
+
const now = new Date().toISOString();
|
|
262
|
+
const deployment = this.deployments.create({
|
|
263
|
+
id: `dep-${Date.now().toString(36)}-${crypto.randomBytes(3).toString("hex")}`,
|
|
264
|
+
repoId: repo.id,
|
|
265
|
+
serverId: server.id,
|
|
266
|
+
server: `${server.name} · ${server.username}@${server.host}:${server.port}`,
|
|
267
|
+
branch: repo.branch,
|
|
268
|
+
commit,
|
|
269
|
+
script: repo.deployScript,
|
|
270
|
+
status: "running",
|
|
271
|
+
createdAt: now,
|
|
272
|
+
updatedAt: now,
|
|
273
|
+
endedAt: null,
|
|
274
|
+
currentLine: null,
|
|
275
|
+
exitCode: null,
|
|
276
|
+
output: "",
|
|
277
|
+
outputTruncated: false,
|
|
278
|
+
cancelRequested: false,
|
|
279
|
+
error: null,
|
|
280
|
+
});
|
|
281
|
+
void this.run(deployment).catch((err) => this.logError(`Deployment ${deployment.id} crashed: ${err?.stack ?? err}`));
|
|
282
|
+
return deployment;
|
|
283
|
+
}
|
|
284
|
+
/** Interrompt un déploiement en cours : le groupe de processus du script reçoit SIGTERM, puis la connexion est fermée. */
|
|
285
|
+
async cancel(id) {
|
|
286
|
+
const deployment = this.deployments.get(id);
|
|
287
|
+
if (deployment.status !== "running")
|
|
288
|
+
throw new ConflictError(`Deployment ${id} is not running (${deployment.status}).`);
|
|
289
|
+
const updated = this.deployments.update(id, (current) => ({ ...current, cancelRequested: true }));
|
|
290
|
+
const running = this.running.get(id);
|
|
291
|
+
if (running) {
|
|
292
|
+
const pid = running.trace.pid;
|
|
293
|
+
if (pid !== null) {
|
|
294
|
+
try {
|
|
295
|
+
const killer = await openExec(running.client, `kill -TERM -- -${pid} 2>/dev/null || kill -TERM ${pid}`);
|
|
296
|
+
await new Promise((resolve) => killer.on("close", () => resolve()).resume());
|
|
297
|
+
}
|
|
298
|
+
catch {
|
|
299
|
+
// La fermeture du canal ci-dessous arrête le script quand le signal n'a pas pu être envoyé.
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
running.channel.close();
|
|
303
|
+
}
|
|
304
|
+
return updated;
|
|
305
|
+
}
|
|
306
|
+
async run(initial) {
|
|
307
|
+
const id = initial.id;
|
|
308
|
+
let output = "";
|
|
309
|
+
let truncated = false;
|
|
310
|
+
let currentLine = null;
|
|
311
|
+
let dirty = false;
|
|
312
|
+
const flush = () => {
|
|
313
|
+
if (!dirty)
|
|
314
|
+
return;
|
|
315
|
+
dirty = false;
|
|
316
|
+
const [snapshot, wasTruncated, line] = [output, truncated, currentLine];
|
|
317
|
+
this.deployments.update(id, (current) => ({ ...current, output: snapshot, outputTruncated: wasTruncated, currentLine: line }));
|
|
318
|
+
};
|
|
319
|
+
const finish = (fields) => {
|
|
320
|
+
this.running.delete(id);
|
|
321
|
+
const [snapshot, wasTruncated, line] = [output, truncated, currentLine];
|
|
322
|
+
const done = this.deployments.update(id, (current) => {
|
|
323
|
+
const status = current.cancelRequested && fields.status !== "done" ? "cancelled" : fields.status;
|
|
324
|
+
return { ...current, ...fields, status, output: snapshot, outputTruncated: wasTruncated, currentLine: line, endedAt: new Date().toISOString() };
|
|
325
|
+
});
|
|
326
|
+
if (done.status === "done")
|
|
327
|
+
this.store.updateRepo(done.repoId, (repo) => ({ ...repo, deployPendingAt: null }));
|
|
328
|
+
};
|
|
329
|
+
let client;
|
|
330
|
+
try {
|
|
331
|
+
({ client } = await connectSsh(this.servers.target(initial.serverId)));
|
|
332
|
+
}
|
|
333
|
+
catch (err) {
|
|
334
|
+
finish({ status: "failed", error: err?.message ?? String(err) });
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
const timer = setInterval(() => {
|
|
338
|
+
try {
|
|
339
|
+
flush();
|
|
340
|
+
}
|
|
341
|
+
catch (err) {
|
|
342
|
+
this.logError(`Output of deployment ${id} not saved: ${err?.message ?? err}`);
|
|
343
|
+
}
|
|
344
|
+
}, FLUSH_MS);
|
|
345
|
+
try {
|
|
346
|
+
const channel = await openExec(client, "sh -s");
|
|
347
|
+
const trace = new TraceReader((line) => {
|
|
348
|
+
currentLine = line;
|
|
349
|
+
dirty = true;
|
|
350
|
+
});
|
|
351
|
+
this.running.set(id, { client, channel, trace });
|
|
352
|
+
if (this.deployments.get(id).cancelRequested)
|
|
353
|
+
channel.close();
|
|
354
|
+
const stdout = new StringDecoder("utf8");
|
|
355
|
+
const stderr = new StringDecoder("utf8");
|
|
356
|
+
const append = (text) => {
|
|
357
|
+
const next = appendOutput(output, text);
|
|
358
|
+
output = next.output;
|
|
359
|
+
truncated = truncated || next.truncated;
|
|
360
|
+
dirty = true;
|
|
361
|
+
};
|
|
362
|
+
channel.on("data", (chunk) => append(stdout.write(chunk)));
|
|
363
|
+
channel.stderr.on("data", (chunk) => trace.push(stderr.write(chunk)));
|
|
364
|
+
const exitCode = await new Promise((resolve) => {
|
|
365
|
+
let code = null;
|
|
366
|
+
channel.on("exit", (exit) => (code = typeof exit === "number" ? exit : null));
|
|
367
|
+
channel.on("close", () => resolve(code));
|
|
368
|
+
channel.end(remoteWrapper(initial.script, { BRANCH: initial.branch, COMMIT: initial.commit ?? "", REPO: initial.repoId }));
|
|
369
|
+
});
|
|
370
|
+
append(stdout.end());
|
|
371
|
+
trace.push(`${stderr.end()}\n`);
|
|
372
|
+
if (exitCode === 0)
|
|
373
|
+
finish({ status: "done", exitCode });
|
|
374
|
+
else if (exitCode === null)
|
|
375
|
+
finish({ status: "failed", exitCode, error: "Le script s'est arrêté sans code de sortie : connexion coupée ou processus tué." });
|
|
376
|
+
else
|
|
377
|
+
finish({ status: "failed", exitCode, error: `Le script s'est arrêté avec le code ${exitCode}${currentLine !== null ? `, à la ligne ${currentLine}` : ""}.` });
|
|
378
|
+
}
|
|
379
|
+
catch (err) {
|
|
380
|
+
finish({ status: "failed", error: err?.message ?? String(err) });
|
|
381
|
+
}
|
|
382
|
+
finally {
|
|
383
|
+
clearInterval(timer);
|
|
384
|
+
client.end();
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
}
|
|
@@ -42,6 +42,8 @@ export declare class GitHubClient {
|
|
|
42
42
|
listAccessibleRepositories(): Promise<string[]>;
|
|
43
43
|
/** Noms des branches du dépôt, toutes pages comprises. */
|
|
44
44
|
listBranches(owner: string, name: string): Promise<string[]>;
|
|
45
|
+
/** SHA du dernier commit de `branch`. */
|
|
46
|
+
getBranchCommit(owner: string, name: string, branch: string): Promise<string>;
|
|
45
47
|
getAuthenticatedUser(): Promise<GitHubUser>;
|
|
46
48
|
/** Pull requests ouvertes du dépôt, toutes pages comprises. */
|
|
47
49
|
listOpenPullRequests(owner: string, name: string): Promise<OpenPullRequest[]>;
|
package/dist/src/core/github.js
CHANGED
|
@@ -122,6 +122,14 @@ export class GitHubClient {
|
|
|
122
122
|
}
|
|
123
123
|
return names;
|
|
124
124
|
}
|
|
125
|
+
/** SHA du dernier commit de `branch`. */
|
|
126
|
+
async getBranchCommit(owner, name, branch) {
|
|
127
|
+
const { json } = await this.request("GET", `/repos/${owner}/${name}/branches/${encodeURIComponent(branch)}`);
|
|
128
|
+
const sha = json?.commit?.sha;
|
|
129
|
+
if (typeof sha !== "string")
|
|
130
|
+
throw new TrackerError(`GitHub API returned no commit for the branch ${branch} of ${owner}/${name}.`);
|
|
131
|
+
return sha;
|
|
132
|
+
}
|
|
125
133
|
async getAuthenticatedUser() {
|
|
126
134
|
const { json } = await this.request("GET", "/user");
|
|
127
135
|
return { login: json.login, id: json.id, name: json.name ?? null };
|
|
@@ -1,6 +1,2 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Répertoire des logs : MCP_LOG_DIR s'il est renseigné, sinon <dataDir>/logs.
|
|
3
|
-
* Lu depuis process.env au démarrage, avant le chargement du .env du package :
|
|
4
|
-
* la variable vient donc de la déclaration du serveur dans le client MCP.
|
|
5
|
-
*/
|
|
1
|
+
/** Répertoire des logs : MCP_LOG_DIR s'il est renseigné, sinon <dataDir>/logs. */
|
|
6
2
|
export declare function resolveLogDir(): string;
|
package/dist/src/core/log-dir.js
CHANGED
|
@@ -1,10 +1,6 @@
|
|
|
1
1
|
import path from "path";
|
|
2
2
|
import { resolveDataDir } from "./data-dir.js";
|
|
3
|
-
/**
|
|
4
|
-
* Répertoire des logs : MCP_LOG_DIR s'il est renseigné, sinon <dataDir>/logs.
|
|
5
|
-
* Lu depuis process.env au démarrage, avant le chargement du .env du package :
|
|
6
|
-
* la variable vient donc de la déclaration du serveur dans le client MCP.
|
|
7
|
-
*/
|
|
3
|
+
/** Répertoire des logs : MCP_LOG_DIR s'il est renseigné, sinon <dataDir>/logs. */
|
|
8
4
|
export function resolveLogDir() {
|
|
9
5
|
const configured = process.env.MCP_LOG_DIR?.trim();
|
|
10
6
|
if (configured)
|
|
@@ -1,12 +1,28 @@
|
|
|
1
1
|
import { type CommandResult } from "./commands.js";
|
|
2
|
+
/**
|
|
3
|
+
* Vérifie, sous Linux, que bubblewrap crée un bac à sable pour le compte et
|
|
4
|
+
* avec les restrictions du serveur : le tracker y lance toutes les commandes
|
|
5
|
+
* npm d'une opération, et Claude Code refuse de démarrer sans lui. Lève une
|
|
6
|
+
* erreur qui dit quoi installer ou régler ; sans effet sur les autres systèmes.
|
|
7
|
+
*/
|
|
8
|
+
export declare function assertSandboxAvailable(platform?: NodeJS.Platform, command?: string): Promise<void>;
|
|
2
9
|
export interface NpmSandbox {
|
|
3
10
|
/** Clone du dépôt, seul dossier du projet en écriture. */
|
|
4
11
|
root: string;
|
|
5
12
|
/** Cache npm de l'opération, hors du clone. */
|
|
6
13
|
cache: string;
|
|
7
14
|
}
|
|
8
|
-
/**
|
|
9
|
-
export declare
|
|
15
|
+
/** Cache npm d'une opération, dans son répertoire temporaire, à côté du clone. */
|
|
16
|
+
export declare const NPM_CACHE_DIR = "npm-cache";
|
|
17
|
+
export interface NpmRunOptions {
|
|
18
|
+
/** Variables propres à la commande, en plus de celles de `npmEnv`. */
|
|
19
|
+
env?: Record<string, string>;
|
|
20
|
+
/** Annulation de l'opération : arrête la commande. */
|
|
21
|
+
signal?: AbortSignal;
|
|
22
|
+
platform?: NodeJS.Platform;
|
|
23
|
+
}
|
|
24
|
+
/** Arguments de bubblewrap pour lancer `npm <args>` dans `cwd`, un dossier du clone, avec les variables `extraEnv` en plus. */
|
|
25
|
+
export declare function bwrapArgs(sandbox: NpmSandbox, cwd: string, args: string[], extraEnv?: Record<string, string>): string[];
|
|
10
26
|
/**
|
|
11
27
|
* Dossier d'un projet du clone, d'après son chemin relatif (`""` pour la
|
|
12
28
|
* racine) ; lève une erreur hors du clone, dans `node_modules` ou sans
|
|
@@ -14,4 +30,4 @@ export declare function bwrapArgs(sandbox: NpmSandbox, cwd: string, args: string
|
|
|
14
30
|
*/
|
|
15
31
|
export declare function projectDir(sandbox: NpmSandbox, project: string): string;
|
|
16
32
|
/** Lance `npm <args>` dans un projet du clone et rend son code de sortie et ses sorties. */
|
|
17
|
-
export declare function runSandboxedNpm(sandbox: NpmSandbox, project: string, args: string[],
|
|
33
|
+
export declare function runSandboxedNpm(sandbox: NpmSandbox, project: string, args: string[], options?: NpmRunOptions): Promise<CommandResult>;
|
|
@@ -1,21 +1,79 @@
|
|
|
1
|
+
import { spawn } from "child_process";
|
|
1
2
|
import fs from "fs";
|
|
2
3
|
import path from "path";
|
|
3
|
-
import { runCommand } from "./commands.js";
|
|
4
|
+
import { runCommand, tail } from "./commands.js";
|
|
4
5
|
import { TrackerError } from "./errors.js";
|
|
5
6
|
/**
|
|
6
|
-
* Commandes npm
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
7
|
+
* Commandes npm d'une opération : celles du tracker (`npm audit`, `npm audit
|
|
8
|
+
* fix`) et celles lancées pour Claude pendant ses corrections, hors du bac à
|
|
9
|
+
* sable de Claude Code, qui garde en lecture seule les manifestes, les lockfiles
|
|
10
|
+
* et `node_modules`. Sous Linux, chaque commande tourne dans un bac à sable
|
|
11
|
+
* bubblewrap du tracker : système en lecture seule (`/usr`, Node.js, et de
|
|
12
|
+
* `/etc` les seuls fichiers de `ETC_ENTRIES`), clone et cache npm de l'opération
|
|
13
|
+
* en écriture, `/tmp` vide, aucun autre dossier du serveur visible (ni `/opt`,
|
|
14
|
+
* ni `/home`, ni les données du tracker, ni les autres clones),
|
|
12
15
|
* environnement réduit à PATH, LANG, HOME et au cache npm. Ailleurs, la
|
|
13
16
|
* commande tourne directement dans le clone, avec le cache de l'opération.
|
|
14
17
|
*/
|
|
15
18
|
/** Dossiers système montés en lecture seule, ou recréés en lien symbolique quand ils en sont un. */
|
|
16
|
-
const SYSTEM_DIRS = ["/usr", "/bin", "/sbin", "/lib", "/lib32", "/lib64", "/
|
|
17
|
-
/**
|
|
18
|
-
|
|
19
|
+
const SYSTEM_DIRS = ["/usr", "/bin", "/sbin", "/lib", "/lib32", "/lib64", "/run/systemd/resolve"];
|
|
20
|
+
/**
|
|
21
|
+
* Fichiers et dossiers de `/etc` montés en lecture seule : résolution de noms,
|
|
22
|
+
* comptes, certificats, éditeur de liens, alternatives de Debian, fuseau horaire
|
|
23
|
+
* et identité du système. Le reste de `/etc` est absent du bac à sable.
|
|
24
|
+
*/
|
|
25
|
+
const ETC_ENTRIES = [
|
|
26
|
+
"/etc/resolv.conf",
|
|
27
|
+
"/etc/hosts",
|
|
28
|
+
"/etc/host.conf",
|
|
29
|
+
"/etc/gai.conf",
|
|
30
|
+
"/etc/nsswitch.conf",
|
|
31
|
+
"/etc/passwd",
|
|
32
|
+
"/etc/group",
|
|
33
|
+
"/etc/ssl",
|
|
34
|
+
"/etc/ca-certificates",
|
|
35
|
+
"/etc/ca-certificates.conf",
|
|
36
|
+
"/etc/pki",
|
|
37
|
+
"/etc/crypto-policies",
|
|
38
|
+
"/etc/ld.so.cache",
|
|
39
|
+
"/etc/ld.so.conf",
|
|
40
|
+
"/etc/ld.so.conf.d",
|
|
41
|
+
"/etc/alternatives",
|
|
42
|
+
"/etc/localtime",
|
|
43
|
+
"/etc/os-release",
|
|
44
|
+
];
|
|
45
|
+
/** Bac à sable minimal, du type de ceux où le tracker lance les commandes npm sous Linux. */
|
|
46
|
+
const BWRAP_PROBE = ["--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--unshare-user", "--unshare-pid", "--unshare-net", "true"];
|
|
47
|
+
/** Durée maximale du test de bubblewrap. */
|
|
48
|
+
const BWRAP_PROBE_TIMEOUT_MS = 10_000;
|
|
49
|
+
/**
|
|
50
|
+
* Vérifie, sous Linux, que bubblewrap crée un bac à sable pour le compte et
|
|
51
|
+
* avec les restrictions du serveur : le tracker y lance toutes les commandes
|
|
52
|
+
* npm d'une opération, et Claude Code refuse de démarrer sans lui. Lève une
|
|
53
|
+
* erreur qui dit quoi installer ou régler ; sans effet sur les autres systèmes.
|
|
54
|
+
*/
|
|
55
|
+
export function assertSandboxAvailable(platform = process.platform, command = "bwrap") {
|
|
56
|
+
if (platform !== "linux")
|
|
57
|
+
return Promise.resolve();
|
|
58
|
+
return new Promise((resolve, reject) => {
|
|
59
|
+
const child = spawn(command, BWRAP_PROBE, { stdio: ["ignore", "ignore", "pipe"], timeout: BWRAP_PROBE_TIMEOUT_MS });
|
|
60
|
+
let stderr = "";
|
|
61
|
+
child.stderr.on("data", (chunk) => (stderr += String(chunk)));
|
|
62
|
+
child.on("error", (err) => reject(new TrackerError(err.code === "ENOENT"
|
|
63
|
+
? "The npm commands of an operation need bubblewrap (bwrap), which isolates them on Linux, and it is not in the PATH of the server. Install it on the server: sudo apt-get install -y bubblewrap socat"
|
|
64
|
+
: `The npm commands of an operation need bubblewrap (bwrap), which could not be started: ${err.message}`)));
|
|
65
|
+
child.on("close", (code) => {
|
|
66
|
+
if (code === 0)
|
|
67
|
+
return resolve();
|
|
68
|
+
reject(new TrackerError(`bubblewrap (bwrap) is installed but cannot create a sandbox for the account of the server${stderr.trim() ? `: ${tail(stderr, 3)}` : "."} ` +
|
|
69
|
+
"Check the AppArmor restriction on user namespaces (kernel.apparmor_restrict_unprivileged_userns on Ubuntu 24.04 and later) and the hardening of the service (RestrictNamespaces, PrivateUsers, SystemCallFilter)."));
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
/** Cache npm d'une opération, dans son répertoire temporaire, à côté du clone. */
|
|
74
|
+
export const NPM_CACHE_DIR = "npm-cache";
|
|
75
|
+
/** Variables transmises à npm : chemins, langue, HOME, cache de l'opération, mode CI pour que les tests ne restent pas en veille, puis `extra`. */
|
|
76
|
+
function npmEnv(sandbox, home, extra = {}) {
|
|
19
77
|
return {
|
|
20
78
|
PATH: process.env.PATH ?? "/usr/bin:/bin",
|
|
21
79
|
LANG: process.env.LANG ?? "C.UTF-8",
|
|
@@ -23,14 +81,15 @@ function npmEnv(sandbox, home) {
|
|
|
23
81
|
npm_config_cache: sandbox.cache,
|
|
24
82
|
npm_config_update_notifier: "false",
|
|
25
83
|
CI: "true",
|
|
84
|
+
...extra,
|
|
26
85
|
};
|
|
27
86
|
}
|
|
28
87
|
/** Préfixe d'installation de Node.js (`<préfixe>/bin/node`), où se trouve aussi npm. */
|
|
29
88
|
function nodePrefix() {
|
|
30
89
|
return path.dirname(path.dirname(fs.realpathSync(process.execPath)));
|
|
31
90
|
}
|
|
32
|
-
/** Arguments de bubblewrap pour lancer `npm <args>` dans `cwd`, un dossier du clone. */
|
|
33
|
-
export function bwrapArgs(sandbox, cwd, args) {
|
|
91
|
+
/** Arguments de bubblewrap pour lancer `npm <args>` dans `cwd`, un dossier du clone, avec les variables `extraEnv` en plus. */
|
|
92
|
+
export function bwrapArgs(sandbox, cwd, args, extraEnv = {}) {
|
|
34
93
|
const mounts = [];
|
|
35
94
|
for (const dir of [...SYSTEM_DIRS, nodePrefix()]) {
|
|
36
95
|
let stat;
|
|
@@ -45,7 +104,17 @@ export function bwrapArgs(sandbox, cwd, args) {
|
|
|
45
104
|
else
|
|
46
105
|
mounts.push("--ro-bind", dir, dir);
|
|
47
106
|
}
|
|
48
|
-
const
|
|
107
|
+
for (const entry of ETC_ENTRIES) {
|
|
108
|
+
let target;
|
|
109
|
+
try {
|
|
110
|
+
target = fs.realpathSync(entry);
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
mounts.push("--ro-bind", target, entry);
|
|
116
|
+
}
|
|
117
|
+
const env = Object.entries(npmEnv(sandbox, "/tmp", extraEnv)).flatMap(([name, value]) => ["--setenv", name, value]);
|
|
49
118
|
return [
|
|
50
119
|
"--die-with-parent",
|
|
51
120
|
"--new-session",
|
|
@@ -80,10 +149,11 @@ export function projectDir(sandbox, project) {
|
|
|
80
149
|
return dir;
|
|
81
150
|
}
|
|
82
151
|
/** Lance `npm <args>` dans un projet du clone et rend son code de sortie et ses sorties. */
|
|
83
|
-
export function runSandboxedNpm(sandbox, project, args,
|
|
152
|
+
export function runSandboxedNpm(sandbox, project, args, options = {}) {
|
|
84
153
|
const cwd = projectDir(sandbox, project);
|
|
85
154
|
fs.mkdirSync(sandbox.cache, { recursive: true });
|
|
86
|
-
if (platform === "linux")
|
|
87
|
-
return runCommand("bwrap", bwrapArgs(sandbox, cwd, args), { cwd: sandbox.root, env: {} });
|
|
88
|
-
|
|
155
|
+
if ((options.platform ?? process.platform) === "linux") {
|
|
156
|
+
return runCommand("bwrap", bwrapArgs(sandbox, cwd, args, options.env), { cwd: sandbox.root, env: {}, signal: options.signal });
|
|
157
|
+
}
|
|
158
|
+
return runCommand("npm", args, { cwd, env: npmEnv(sandbox, sandbox.cache, options.env), signal: options.signal });
|
|
89
159
|
}
|