@mostajs/delegation 0.0.0-stage → 0.9.0
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/CHANGELOG.md +224 -0
- package/LICENSE +15 -0
- package/README.md +226 -2
- package/bin/delegation-agent.mjs +98 -0
- package/bin/delegation-cle.mjs +44 -0
- package/bin/delegation-lancer.mjs +17 -0
- package/bin/delegation-service.mjs +38 -0
- package/bin/delegation-train.mjs +16 -0
- package/bin/delegation-veilleur.mjs +24 -0
- package/bin/installer-machine-macos.sh +270 -0
- package/bin/installer-machine.ps1 +330 -0
- package/bin/installer-machine.sh +266 -0
- package/llms.txt +68 -0
- package/package.json +51 -4
- package/src/agent.js +334 -0
- package/src/api.js +368 -0
- package/src/bornes.js +72 -0
- package/src/file.js +175 -0
- package/src/index.js +17 -0
- package/src/lanceur.js +164 -0
- package/src/parc.js +282 -0
- package/src/plateforme.js +134 -0
- package/src/services.js +154 -0
- package/src/signature.js +116 -0
- package/src/stockage.js +30 -0
- package/src/train.js +370 -0
- package/src/types.js +98 -0
- package/src/veilleur.js +80 -0
package/src/lanceur.js
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// @mostajs/delegation — l'EXÉCUTANT, repris du lanceur de cidev (lancer.mjs) : les étapes une à
|
|
2
|
+
// une, un journal par étape, etat.json relu par la console. Une étape en échec arrête l'exécution, sauf `continuer`.
|
|
3
|
+
// Ajout : la REPRISE — les étapes déjà faites d'une exécution précédente (même id, même code) ne sont pas rejouées.
|
|
4
|
+
// Aucun secret n'est écrit dans les journaux : l'environnement est passé, jamais imprimé.
|
|
5
|
+
// @author Dr Hamid MADANI <drmdh@msn.com>
|
|
6
|
+
import { spawn, execFileSync, spawnSync } from 'node:child_process';
|
|
7
|
+
import { readFileSync, writeFileSync, mkdirSync, createWriteStream, readdirSync, existsSync, renameSync, rmSync } from 'node:fs';
|
|
8
|
+
import { randomBytes } from 'node:crypto';
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import { homedir } from 'node:os';
|
|
11
|
+
import { trouverBash as trouverBashParDefaut, commandeArretArbre } from './plateforme.js';
|
|
12
|
+
|
|
13
|
+
const tilde = (p) => String(p || '').replace(/^~(?=[\\/]|$)/, homedir());
|
|
14
|
+
const iso = () => new Date().toISOString();
|
|
15
|
+
const ID = /^[A-Za-z0-9._-]{3,80}$/;
|
|
16
|
+
const erreur = (code, message) => Object.assign(new Error(message), { code });
|
|
17
|
+
|
|
18
|
+
/** Le nombre d'essais déclarés dans les sources (même relevé que test-scripts/run-tests.sh). */
|
|
19
|
+
function essaisDeclares(cwd) {
|
|
20
|
+
try {
|
|
21
|
+
const d = join(cwd, 'test-scripts', 'unit');
|
|
22
|
+
const s = readdirSync(d).filter((f) => f.endsWith('.test.mjs')).map((f) => readFileSync(join(d, f), 'utf8')).join('\n');
|
|
23
|
+
const re = /(^|[^A-Za-z0-9_.])test(\.skip)?\((['"`])(T-[A-Z0-9]+-[0-9]+[a-z]?)/gm; const v = new Set(); let m;
|
|
24
|
+
while ((m = re.exec(s))) v.add(m[4]);
|
|
25
|
+
return v.size;
|
|
26
|
+
} catch { return null; }
|
|
27
|
+
}
|
|
28
|
+
const commitDe = (cwd) => { try { return execFileSync('git', ['-C', cwd, 'log', '-1', '--format=%h %s'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(); } catch { return null; } };
|
|
29
|
+
|
|
30
|
+
/** Relève la progression dans les lignes de sortie : essais (▶ fichier, ✓, ✗) ou films (✓ CODE, ✗ CODE). */
|
|
31
|
+
export function analyseur(e, cwd, attendu = null) {
|
|
32
|
+
if (e.analyse === 'suite') {
|
|
33
|
+
const p = e.progression = { passes: 0, echoues: 0, attendu: essaisDeclares(cwd), fichier: null, fichiers: {}, echecs: [] };
|
|
34
|
+
let dernier = null;
|
|
35
|
+
return (ligne) => {
|
|
36
|
+
const f = /^▶\s+(\S+)/.exec(ligne);
|
|
37
|
+
if (f) { p.fichier = f[1]; p.fichiers[f[1]] ||= { passes: 0, echoues: 0 }; return; }
|
|
38
|
+
const t = /^\s+([✓✗✔✘])\s+(T-[A-Z0-9]+-[0-9]+[a-z]?)\s*(.*)$/.exec(ligne);
|
|
39
|
+
if (t) {
|
|
40
|
+
const ok = t[1] === '✓' || t[1] === '✔';
|
|
41
|
+
const fic = p.fichiers[p.fichier] ||= { passes: 0, echoues: 0 };
|
|
42
|
+
if (ok) { p.passes += 1; fic.passes += 1; dernier = null; } else {
|
|
43
|
+
p.echoues += 1; fic.echoues += 1;
|
|
44
|
+
dernier = { essai: t[2] || '', titre: t[3].replace(/^[—–-]\s*/, '').slice(0, 200), fichier: p.fichier, message: '' }; p.echecs.push(dernier);
|
|
45
|
+
}
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
if (dernier && /^\s{4,}\S/.test(ligne) && dernier.message.length < 600) dernier.message += `${ligne.trim()}\n`;
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
if (e.analyse === 'films') {
|
|
52
|
+
const p = e.progression = { passes: 0, echoues: 0, attendu, courant: null, echecs: [] };
|
|
53
|
+
return (ligne) => {
|
|
54
|
+
const ok = /^\s*✓\s+([A-Z][A-Z0-9-]*\d[a-z]?)\b/.exec(ligne);
|
|
55
|
+
const ko = /^\s*✗\s+([A-Z][A-Z0-9-]*\d[a-z]?)\b(.*)$/.exec(ligne);
|
|
56
|
+
const n = /(\d+)\s+sc[ée]nario\(?s?\)?\s+à tourner/i.exec(ligne);
|
|
57
|
+
if (n && p.attendu == null) p.attendu = Number(n[1]);
|
|
58
|
+
const ra = /recette automatisée.*?(\d+) verte\(s\), (\d+) rouge\(s\), (\d+) sans verdict/.exec(ligne);
|
|
59
|
+
if (ra) p.recette = { vertes: Number(ra[1]), rouges: Number(ra[2]), sansVerdict: Number(ra[3]) };
|
|
60
|
+
if (ok) { p.passes += 1; p.courant = ok[1]; } else if (ko) { p.echoues += 1; p.courant = ko[1]; p.echecs.push({ essai: ko[1], titre: ko[2].trim().replace(/^[—–:,-]\s*/, '').slice(0, 300), message: '' }); }
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
return () => {};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Une étape a SOIT une `commande` (chaîne, passée à bash), SOIT un `programme` et ses `arguments` (sans shell). */
|
|
67
|
+
function defautsEtape(e) {
|
|
68
|
+
if (!e || typeof e !== 'object' || typeof e.code !== 'string' || !e.code) return 'code : une chaîne';
|
|
69
|
+
if (e.programme != null) {
|
|
70
|
+
if (typeof e.programme !== 'string' || !e.programme) return `${e.code} : programme, une chaîne`;
|
|
71
|
+
if (e.arguments != null && (!Array.isArray(e.arguments) || e.arguments.some((a) => typeof a !== 'string'))) return `${e.code} : arguments, une liste de chaînes`;
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
return typeof e.commande === 'string' && e.commande ? null : `${e.code} : une commande (chaîne) ou un programme et ses arguments`;
|
|
75
|
+
}
|
|
76
|
+
/** Le texte d'une étape tel que le journal et etat.json le montrent. */
|
|
77
|
+
const texteEtape = (e) => (e.programme != null ? [e.programme, ...(e.arguments || [])].map((a) => (/[\s"']/.test(a) ? JSON.stringify(a) : a)).join(' ') : e.commande);
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Exécute une exécution `{ id, titre?, attendu?, env?, etapes: [{ code, titre?, commande | programme + arguments, cwd?, analyse?, continuer? }] }`.
|
|
81
|
+
* 0.9.0 (R9) : une étape `{ programme, arguments }` part par spawn SANS shell (les métacaractères restent à la lettre,
|
|
82
|
+
* sous tous les systèmes) ; une étape `commande` passe par bash — sous Windows, celui de Git for Windows ; s'il manque,
|
|
83
|
+
* l'étape échoue (code 127) et son journal dit pourquoi.
|
|
84
|
+
* Sortie : <racine>/executions/<id>/etat.json et <code>.log. Rend l'état final.
|
|
85
|
+
* @param {object} def
|
|
86
|
+
* @param {{ racine?: string, reprendre?: boolean, env?: object, travail?: boolean, signal?: AbortSignal }} [o]
|
|
87
|
+
* travail (0.7.0, R5) : un dossier JETABLE par exécution (<racine>/travail/<id>-<hasard>), cwd des étapes qui n'en
|
|
88
|
+
* déclarent pas, nommé dans DELEGATION_TRAVAIL, effacé à la fin (succès, échec ou arrêt) ; les journaux restent.
|
|
89
|
+
* plateforme, trouverBash (essais) : le système simulé et la recherche de bash.
|
|
90
|
+
*/
|
|
91
|
+
export async function lancerExecution(def, { racine = process.env.CIDEV_RACINE || join(homedir(), 'cidev'), reprendre = false, env: envPlus = {}, surEtat = null, signal = null, travail = false, plateforme = process.platform, trouverBash = () => trouverBashParDefaut({ plateforme }) } = {}) {
|
|
92
|
+
if (!ID.test(def?.id || '')) throw erreur('E_ID', 'id d’exécution invalide (3 à 80 caractères : lettres, chiffres, . _ -)');
|
|
93
|
+
if (!Array.isArray(def.etapes)) throw erreur('E_ETAPES', 'etapes : une liste');
|
|
94
|
+
for (const e of def.etapes) { const d = defautsEtape(e); if (d) throw erreur('E_ETAPES', `étape refusée : ${d}`); }
|
|
95
|
+
const DOS = join(racine, 'executions', def.id);
|
|
96
|
+
mkdirSync(DOS, { recursive: true });
|
|
97
|
+
const avant = reprendre && existsSync(join(DOS, 'etat.json')) ? JSON.parse(readFileSync(join(DOS, 'etat.json'), 'utf8')) : null;
|
|
98
|
+
const faiteAvant = (code) => avant?.etapes?.find((x) => x.code === code && x.etat === 'fait') || null;
|
|
99
|
+
const jetable = travail ? join(racine, 'travail', `${def.id}-${randomBytes(4).toString('hex')}`) : null;
|
|
100
|
+
if (jetable) mkdirSync(jetable, { recursive: true, mode: 0o700 });
|
|
101
|
+
|
|
102
|
+
const etat = {
|
|
103
|
+
id: def.id, titre: def.titre || def.id, pid: process.pid, debut: iso(), fin: null, etat: 'en_cours', reprise: Boolean(avant), ...(jetable ? { travail: jetable } : {}),
|
|
104
|
+
etapes: def.etapes.map((e) => faiteAvant(e.code) || ({ code: e.code, titre: e.titre || e.code, commande: texteEtape(e), cwd: e.cwd || jetable || '~', analyse: e.analyse || null,
|
|
105
|
+
etat: 'a_faire', debut: null, fin: null, sortie: null, progression: null, commit: null })),
|
|
106
|
+
};
|
|
107
|
+
// surEtat(état, { finEtape }) : chaque écriture de etat.json est aussi rendue à l'appelant (l'agent en fait sa progression).
|
|
108
|
+
const ecrire = (finEtape = false) => {
|
|
109
|
+
const t = join(DOS, 'etat.json.tmp'); writeFileSync(t, JSON.stringify(etat, null, 1)); renameSync(t, join(DOS, 'etat.json'));
|
|
110
|
+
if (surEtat) { try { surEtat(structuredClone(etat), { finEtape }); } catch { /* l'appelant ne doit pas arrêter l'exécution */ } }
|
|
111
|
+
};
|
|
112
|
+
ecrire();
|
|
113
|
+
|
|
114
|
+
const executer = async (e, brute) => {
|
|
115
|
+
const cwd = tilde(e.cwd);
|
|
116
|
+
e.etat = 'en_cours'; e.debut = iso(); e.fin = null; e.sortie = null; e.commit = existsSync(join(cwd, '.git')) ? commitDe(cwd) : null; ecrire();
|
|
117
|
+
const log = createWriteStream(join(DOS, `${e.code}.log`), { flags: 'a' });
|
|
118
|
+
log.write(`$ ${texteEtape(brute)}\n# dans ${cwd} — ${e.debut}\n`);
|
|
119
|
+
const lire = analyseur(e, cwd, def.attendu ?? null);
|
|
120
|
+
const env = { ...process.env, FORCE_COLOR: '0', NO_COLOR: '1', ...(def.env || {}), ...envPlus, ...(jetable ? { DELEGATION_TRAVAIL: jetable } : {}) };
|
|
121
|
+
let reste = ''; let derniere = 0;
|
|
122
|
+
const code = await new Promise((ok) => {
|
|
123
|
+
// Sans shell quand l'étape nomme son programme ; bash sinon. POSIX : groupe de processus à part, un arrêt tue
|
|
124
|
+
// l'étape ET ses enfants ; Windows : taskkill /T sur l'arbre (pas de groupe de processus).
|
|
125
|
+
const win = plateforme === 'win32';
|
|
126
|
+
let prog; let args;
|
|
127
|
+
if (brute.programme != null) { prog = brute.programme; args = brute.arguments || []; } else {
|
|
128
|
+
const bash = win ? trouverBash() : 'bash';
|
|
129
|
+
if (!bash) { log.write('# erreur : bash introuvable (une étape « commande » exige bash : Git for Windows, et la capacité « bash » déclarée par le type)\n'); ok(127); return; }
|
|
130
|
+
prog = bash; args = ['-lc', brute.commande];
|
|
131
|
+
}
|
|
132
|
+
const p = spawn(prog, args, { cwd, env, stdio: ['ignore', 'pipe', 'pipe'], detached: !win, windowsHide: true, shell: false });
|
|
133
|
+
const tuer = () => {
|
|
134
|
+
const arbre = commandeArretArbre(p.pid, plateforme);
|
|
135
|
+
try { if (arbre) spawnSync(arbre.programme, arbre.arguments, { stdio: 'ignore', windowsHide: true }); else process.kill(-p.pid, 'SIGTERM'); } catch { /* déjà fini */ }
|
|
136
|
+
};
|
|
137
|
+
if (signal) { if (signal.aborted) tuer(); else signal.addEventListener('abort', tuer, { once: true }); p.on('close', () => signal.removeEventListener('abort', tuer)); }
|
|
138
|
+
const recevoir = (b) => {
|
|
139
|
+
log.write(b);
|
|
140
|
+
const lignes = (reste + b.toString('utf8')).split('\n'); reste = lignes.pop();
|
|
141
|
+
for (const l of lignes) lire(l.replace(/\x1b\[[0-9;]*m/g, ''));
|
|
142
|
+
if (Date.now() - derniere > 1000) { derniere = Date.now(); ecrire(); }
|
|
143
|
+
};
|
|
144
|
+
p.stdout.on('data', recevoir); p.stderr.on('data', recevoir);
|
|
145
|
+
p.on('error', (x) => { log.write(`\n# erreur : ${x.message}\n`); ok(127); });
|
|
146
|
+
p.on('close', (c, s) => ok(c ?? (s ? 128 : 1)));
|
|
147
|
+
});
|
|
148
|
+
if (reste) lire(reste);
|
|
149
|
+
e.sortie = code; e.fin = iso(); e.etat = signal?.aborted ? 'interrompue' : code === 0 ? 'fait' : 'echec';
|
|
150
|
+
await new Promise((ok) => log.end(`\n# fin : code ${code} — ${e.fin}\n`, ok)); ecrire(true);
|
|
151
|
+
return code === 0 || Boolean(brute.continuer);
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
let bon = true;
|
|
155
|
+
for (const [i, e] of etat.etapes.entries()) {
|
|
156
|
+
if (e.etat === 'fait') continue; // reprise : déjà faite
|
|
157
|
+
if (!bon || signal?.aborted) { e.etat = 'saute'; continue; }
|
|
158
|
+
if (!(await executer(e, def.etapes[i]))) bon = false;
|
|
159
|
+
}
|
|
160
|
+
// Arrêtée de l'extérieur (bail dépassé, tâche reprise par la centrale) : « interrompue », jamais « échec ».
|
|
161
|
+
if (jetable) { try { rmSync(jetable, { recursive: true, force: true }); } catch { /* déjà parti */ } }
|
|
162
|
+
etat.fin = iso(); etat.etat = signal?.aborted ? 'interrompue' : etat.etapes.every((e) => e.etat === 'fait') ? 'fait' : 'echec'; ecrire(true);
|
|
163
|
+
return structuredClone(etat);
|
|
164
|
+
}
|
package/src/parc.js
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
// @mostajs/delegation — le PARC : les machines annoncées depuis la centrale, enrôlées, acceptées (exigence du 20/11/2026).
|
|
2
|
+
//
|
|
3
|
+
// annoncer (nom, rôles, capacités attendues) → jeton d'ENRÔLEMENT : à usage unique, 30 min, montré une fois, gardé en
|
|
4
|
+
// empreinte → la machine s'enrôle avec lui (capacités détectées) → jeton DURABLE (empreinte seule) → « en attente »
|
|
5
|
+
// → accepter | refuser. Une machine acceptée peut être suspendue, reprise, renommée, retirée ; son jeton révoqué (elle
|
|
6
|
+
// reçoit alors un nouveau jeton d'enrôlement et repasse par l'acceptation).
|
|
7
|
+
// Rien n'est tiré par une machine non acceptée (l'API le refuse en 403). Chaque geste au journal : qui, quoi, quand.
|
|
8
|
+
// Aucun jeton n'est jamais écrit, ni dans le fichier ni au journal : seulement des empreintes SHA-256.
|
|
9
|
+
//
|
|
10
|
+
// 0.6.0 (décision du fondateur, 20/11/2026) :
|
|
11
|
+
// - l'INSCRIPTION part du PC : `demander()` (page publique) rend un CODE DE DEMANDE à usage unique, 15 min, gardé en
|
|
12
|
+
// empreinte, qui ne révèle rien du parc ; la machine s'enrôle avec lui (nom, rôles, capacités détectées) et naît
|
|
13
|
+
// « en attente », origine « inscription ». Plafonds : demandes vivantes et machines inscrites en attente (E_TROP).
|
|
14
|
+
// L'annonce par le fondateur reste le second chemin (origine « annonce ») ;
|
|
15
|
+
// - le RÉGLAGE de la centrale (maestro) : n'exécute rien par défaut ; par type autorisé (jamais « train ») ;
|
|
16
|
+
// concurrence 1 à 8 ; chaque changement au journal ;
|
|
17
|
+
// - la MARCHE : hors-ligne / en-ligne notés au journal.
|
|
18
|
+
//
|
|
19
|
+
// 0.7.0 (durcissement, décisions du 21/11/2026) :
|
|
20
|
+
// - R2 : capacités et rôles FIGÉS à l'acceptation (`capacitesAcceptees`, `rolesAcceptes`) ; une annonce qui en ajoute
|
|
21
|
+
// ne les obtient pas : ils attendent une nouvelle acceptation (`capacitesEnAttente`, `accepterCapacites`) ;
|
|
22
|
+
// - R3 : l'EMPREINTE de la machine (`empreinteMachine`), lisible sur le PC et dans la console, comparée à l'acceptation
|
|
23
|
+
// (`accepter(id, { empreinte })`, exigée avec `exigerEmpreinte`) ;
|
|
24
|
+
// - R4 : le dernier signe de vie (`vu`) gardé dans le parc ; une machine muette depuis N jours est mise en sommeil.
|
|
25
|
+
// @author Dr Hamid MADANI <drmdh@msn.com>
|
|
26
|
+
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
27
|
+
import { readFileSync, writeFileSync, renameSync, existsSync, mkdirSync } from 'node:fs';
|
|
28
|
+
import { dirname } from 'node:path';
|
|
29
|
+
import { bornerJson } from './bornes.js';
|
|
30
|
+
|
|
31
|
+
export const FORMAT_PARC = 'mostajs-delegation-parc/1';
|
|
32
|
+
export const ETATS_MACHINE = Object.freeze(['annoncee', 'en_attente', 'acceptee', 'suspendue', 'refusee', 'retiree']);
|
|
33
|
+
const NOM = /^[\p{L}\p{N} ._-]{2,40}$/u;
|
|
34
|
+
const CAPACITE = /^[A-Za-z0-9@._-]{1,40}$/;
|
|
35
|
+
const erreur = (code, message) => Object.assign(new Error(message), { code });
|
|
36
|
+
const empreinte = (j) => createHash('sha256').update(String(j)).digest('hex');
|
|
37
|
+
const egales = (a, b) => { const x = Buffer.from(String(a), 'hex'); const y = Buffer.from(String(b), 'hex'); return x.length === y.length && x.length > 0 && timingSafeEqual(x, y); };
|
|
38
|
+
const liste = (v) => (Array.isArray(v) ? [...new Set(v.filter((x) => typeof x === 'string' && CAPACITE.test(x)))].slice(0, 64) : []);
|
|
39
|
+
const B32E = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
|
40
|
+
/**
|
|
41
|
+
* L'empreinte d'une machine (R3), calculée des deux côtés depuis l'empreinte SHA-256 de son jeton durable : le PC la
|
|
42
|
+
* calcule depuis son jeton, la centrale depuis l'empreinte qu'elle garde. 60 bits, 12 caractères base32 (XXXX-XXXX-XXXX).
|
|
43
|
+
*/
|
|
44
|
+
export function empreinteMachine(empreinteJetonHex) {
|
|
45
|
+
const h = createHash('sha256').update(`mostajs-delegation-machine:${String(empreinteJetonHex)}`).digest();
|
|
46
|
+
let bits = 0; let v = 0; let o = '';
|
|
47
|
+
for (const x of h) { v = ((v << 8) | x) & 0xffff; bits += 8; while (bits >= 5 && o.length < 12) { o += B32E[(v >>> (bits - 5)) & 31]; bits -= 5; } if (o.length >= 12) break; }
|
|
48
|
+
return o.match(/.{4}/g).join('-');
|
|
49
|
+
}
|
|
50
|
+
const normEmpreinte = (e) => String(e || '').toUpperCase().replace(/[\s-]/g, '');
|
|
51
|
+
const sauf = (a, b) => (a || []).filter((x) => !(b || []).includes(x));
|
|
52
|
+
const inter = (a, b) => (a || []).filter((x) => (b || []).includes(x));
|
|
53
|
+
const memes = (a, b) => (a || []).length === (b || []).length && (a || []).every((x) => (b || []).includes(x));
|
|
54
|
+
const slug = (nom) => nom.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 40) || 'machine';
|
|
55
|
+
|
|
56
|
+
/** Ce que la machine dit d'elle-même à l'enrôlement, borné. */
|
|
57
|
+
function bornerDetection(d) {
|
|
58
|
+
const x = d && typeof d === 'object' ? d : {};
|
|
59
|
+
const n = (v, max) => (typeof v === 'number' && Number.isFinite(v) ? Math.min(max, Math.max(0, v)) : null);
|
|
60
|
+
return { capacites: liste(x.capacites), cpus: n(x.cpus, 4096), memoireMo: n(x.memoireMo, 1e9), disqueMo: n(x.disqueMo, 1e12),
|
|
61
|
+
systeme: typeof x.systeme === 'string' ? x.systeme.slice(0, 40).replace(/[^A-Za-z0-9._ -]/g, '') : null,
|
|
62
|
+
hote: typeof x.hote === 'string' ? x.hote.slice(0, 64).replace(/[^A-Za-z0-9._-]/g, '') : null };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* @param {{ fichier?: string, maintenant?: () => Date, dureeEnrolementMin?: number }} [o] sans fichier : en mémoire.
|
|
67
|
+
*/
|
|
68
|
+
export const REGLAGE_CENTRALE = Object.freeze({ executer: false, types: [], concurrence: 1 });
|
|
69
|
+
const TYPE = /^[a-z][a-z0-9-]{1,40}$/;
|
|
70
|
+
const B32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
|
71
|
+
/** Un code de demande lisible : 120 bits, 24 caractères base32 en six groupes (XXXX-XXXX-…). */
|
|
72
|
+
const nouveauCode = () => { const b = randomBytes(15); let bits = 0; let v = 0; let o = '';
|
|
73
|
+
for (const x of b) { v = (v << 8) | x; bits += 8; while (bits >= 5) { o += B32[(v >>> (bits - 5)) & 31]; bits -= 5; } }
|
|
74
|
+
return o.match(/.{4}/g).join('-'); };
|
|
75
|
+
/** Ce que l'on tape ou colle : majuscules, sans tirets ni espaces. */
|
|
76
|
+
const normaliserCode = (c) => String(c || '').toUpperCase().replace(/[\s-]/g, '');
|
|
77
|
+
/** Le réglage de la centrale, borné : « train » (conducteur) n'y entre jamais, même écrit à la main dans le fichier. */
|
|
78
|
+
const reglageSur = (r) => ({ executer: r?.executer === true,
|
|
79
|
+
types: [...new Set(Array.isArray(r?.types) ? r.types.filter((t) => typeof t === 'string' && TYPE.test(t) && t !== 'train') : [])],
|
|
80
|
+
concurrence: Number.isInteger(r?.concurrence) && r.concurrence >= 1 && r.concurrence <= 8 ? r.concurrence : 1 });
|
|
81
|
+
|
|
82
|
+
export function creerParc({ fichier = null, maintenant = () => new Date(), dureeEnrolementMin = 30, dureeDemandeMin = 15, demandesMax = 20, attenteMax = 20,
|
|
83
|
+
exigerEmpreinte = false, vuEcritureMin = 10 } = {}) {
|
|
84
|
+
let d = null; let suite = Promise.resolve();
|
|
85
|
+
const lire = () => {
|
|
86
|
+
if (fichier && existsSync(fichier)) {
|
|
87
|
+
const x = JSON.parse(readFileSync(fichier, 'utf8'));
|
|
88
|
+
if (x.format !== FORMAT_PARC) throw erreur('E_FORMAT', `${fichier} : format « ${x.format} », attendu ${FORMAT_PARC}`);
|
|
89
|
+
return x;
|
|
90
|
+
}
|
|
91
|
+
return { format: FORMAT_PARC, machines: [], journal: [] };
|
|
92
|
+
};
|
|
93
|
+
const charger = () => { const x = lire(); x.demandes ||= []; x.centrale = reglageSur(x.centrale || REGLAGE_CENTRALE); return x; };
|
|
94
|
+
const purger = () => { const t = maintenant().getTime(); d.demandes = d.demandes.filter((x) => Date.parse(x.expire) >= t); };
|
|
95
|
+
const sauver = () => {
|
|
96
|
+
if (!fichier) return;
|
|
97
|
+
mkdirSync(dirname(fichier), { recursive: true });
|
|
98
|
+
writeFileSync(`${fichier}.tmp`, `${JSON.stringify(d, null, 1)}\n`, { mode: 0o600 }); renameSync(`${fichier}.tmp`, fichier);
|
|
99
|
+
};
|
|
100
|
+
const enSerie = (fn) => { const p = suite.then(() => { if (!d) d = charger(); return fn(); }); suite = p.catch(() => {}); return p; };
|
|
101
|
+
const iso = () => maintenant().toISOString();
|
|
102
|
+
const noter = (m, quoi, par, plus = {}) => d.journal.push({ machine: m.id, quoi, par: par ?? null, quand: iso(), ...plus });
|
|
103
|
+
const trouver = (id) => { const m = d.machines.find((x) => x.id === id); if (!m) throw erreur('E_INCONNUE', `machine inconnue « ${id} »`); return m; };
|
|
104
|
+
const vue = (m) => ({ id: m.id, nom: m.nom, roles: [...m.roles], capacitesAttendues: [...m.capacitesAttendues], etat: m.etat, detecte: m.detecte ? structuredClone(m.detecte) : null,
|
|
105
|
+
cree: m.cree, maj: m.maj, aJeton: Boolean(m.jeton), enrolementJusqua: m.enrolement?.expire ?? null, origine: m.origine || 'annonce',
|
|
106
|
+
empreinte: m.jeton ? empreinteMachine(m.jeton) : null, vu: m.vu ?? null,
|
|
107
|
+
capacitesAcceptees: m.capacitesAcceptees ? [...m.capacitesAcceptees] : null, rolesAcceptes: m.rolesAcceptes ? [...m.rolesAcceptes] : null,
|
|
108
|
+
capacitesEnAttente: [...(m.capacitesEnAttente || [])], rolesEnAttente: [...(m.rolesEnAttente || [])],
|
|
109
|
+
annonce: m.annonce ? { capacites: [...m.annonce.capacites], roles: [...m.annonce.roles] } : null });
|
|
110
|
+
const passer = (m, de, vers, quoi, par) => {
|
|
111
|
+
if (!de.includes(m.etat)) throw erreur('E_TRANSITION', `la machine ${m.id} est « ${m.etat} » : ${quoi} impossible`);
|
|
112
|
+
m.etat = vers; m.maj = iso(); noter(m, quoi, par);
|
|
113
|
+
};
|
|
114
|
+
const nouvelEnrolement = (m) => {
|
|
115
|
+
const jeton = randomBytes(32).toString('base64url');
|
|
116
|
+
m.enrolement = { empreinte: empreinte(jeton), expire: new Date(maintenant().getTime() + dureeEnrolementMin * 60_000).toISOString() };
|
|
117
|
+
return jeton;
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
return {
|
|
121
|
+
/** Annonce une machine à venir ; rend le jeton d'enrôlement, montré une seule fois. */
|
|
122
|
+
annoncer: ({ nom, roles = [], capacites = [], par } = {}) => enSerie(() => {
|
|
123
|
+
if (typeof nom !== 'string' || !NOM.test(nom.trim())) throw erreur('E_NOM', 'nom : 2 à 40 caractères (lettres, chiffres, espace, . _ -)');
|
|
124
|
+
let id = slug(nom.trim()); for (let i = 2; d.machines.some((x) => x.id === id); i++) id = `${slug(nom.trim()).slice(0, 36)}-${i}`;
|
|
125
|
+
const m = { id, nom: nom.trim(), roles: liste(roles), capacitesAttendues: liste(capacites), etat: 'annoncee', jeton: null, enrolement: null, detecte: null, cree: iso(), maj: iso() };
|
|
126
|
+
const jetonEnrolement = nouvelEnrolement(m);
|
|
127
|
+
d.machines.push(m); noter(m, 'annoncee', par); sauver();
|
|
128
|
+
return { machine: vue(m), jetonEnrolement };
|
|
129
|
+
}),
|
|
130
|
+
/**
|
|
131
|
+
* La page PUBLIQUE « Inscrire ce poste » : un code de demande (usage unique, `dureeDemandeMin`), montré une fois,
|
|
132
|
+
* gardé en empreinte. Ne rend RIEN d'autre que { code, expire } ; E_TROP au-delà des plafonds (message neutre).
|
|
133
|
+
*/
|
|
134
|
+
demander: ({ origine = null } = {}) => enSerie(() => {
|
|
135
|
+
purger();
|
|
136
|
+
const attente = d.machines.filter((m) => m.etat === 'en_attente' && m.origine === 'inscription').length;
|
|
137
|
+
if (d.demandes.length >= demandesMax || attente >= attenteMax) throw erreur('E_TROP', 'inscription momentanément indisponible : réessayez plus tard');
|
|
138
|
+
const code = nouveauCode();
|
|
139
|
+
const expire = new Date(maintenant().getTime() + dureeDemandeMin * 60_000).toISOString();
|
|
140
|
+
d.demandes.push({ empreinte: empreinte(normaliserCode(code)), expire });
|
|
141
|
+
d.journal.push({ machine: '(demande)', quoi: 'demande', par: 'page publique', quand: iso(), ...(origine ? { motif: String(origine).slice(0, 64) } : {}) });
|
|
142
|
+
sauver();
|
|
143
|
+
return { code, expire };
|
|
144
|
+
}),
|
|
145
|
+
/**
|
|
146
|
+
* La machine s'enrôle : avec le jeton d'enrôlement d'une annonce, ou avec un CODE DE DEMANDE (inscription depuis le
|
|
147
|
+
* PC). Rend son jeton DURABLE (une seule fois). E_ENROLEMENT sinon (inconnu, déjà utilisé, expiré).
|
|
148
|
+
*/
|
|
149
|
+
enroler: (jetonOuCode, { detecte, nom, roles } = {}) => enSerie(() => {
|
|
150
|
+
const e = empreinte(jetonOuCode);
|
|
151
|
+
let m = d.machines.find((x) => x.etat === 'annoncee' && x.enrolement && egales(x.enrolement.empreinte, e));
|
|
152
|
+
if (m && Date.parse(m.enrolement.expire) < maintenant().getTime()) m = null;
|
|
153
|
+
if (!m) {
|
|
154
|
+
purger();
|
|
155
|
+
const ec = empreinte(normaliserCode(jetonOuCode));
|
|
156
|
+
const i = d.demandes.findIndex((x) => egales(x.empreinte, ec));
|
|
157
|
+
if (i < 0) throw erreur('E_ENROLEMENT', 'jeton d’enrôlement ou code de demande inconnu, déjà utilisé ou expiré');
|
|
158
|
+
d.demandes.splice(i, 1);
|
|
159
|
+
const det = bornerDetection(detecte);
|
|
160
|
+
const brut = typeof nom === 'string' && NOM.test(nom.trim()) ? nom.trim() : (det.hote && NOM.test(det.hote) ? det.hote : 'Poste');
|
|
161
|
+
let id = slug(brut); for (let k = 2; d.machines.some((x) => x.id === id); k++) id = `${slug(brut).slice(0, 36)}-${k}`;
|
|
162
|
+
m = { id, nom: brut, roles: liste(roles), capacitesAttendues: [], etat: 'annoncee', origine: 'inscription', jeton: null, enrolement: null, detecte: null, cree: iso(), maj: iso() };
|
|
163
|
+
d.machines.push(m);
|
|
164
|
+
}
|
|
165
|
+
const jeton = randomBytes(32).toString('base64url');
|
|
166
|
+
m.jeton = empreinte(jeton); m.enrolement = null; m.detecte = bornerDetection(detecte);
|
|
167
|
+
if (m.origine !== 'inscription' && Array.isArray(roles) && !m.roles.length) m.roles = liste(roles);
|
|
168
|
+
m.etat = 'en_attente'; m.maj = iso(); noter(m, m.origine === 'inscription' ? 'inscrite' : 'enrolee', m.id); sauver();
|
|
169
|
+
return { id: m.id, jeton };
|
|
170
|
+
}),
|
|
171
|
+
/**
|
|
172
|
+
* Accepte une machine en attente. R3 : `empreinte` (lue sur le PC) doit être la sienne (E_EMPREINTE), exigée avec
|
|
173
|
+
* `exigerEmpreinte`. R2 : ses capacités et rôles sont FIGÉS (`capacites`/`roles` donnés, sinon ceux de sa dernière
|
|
174
|
+
* annonce, sinon ceux détectés à l'enrôlement) ; rien de connu : figés à sa première annonce.
|
|
175
|
+
*/
|
|
176
|
+
accepter: (id, { par, empreinte, capacites, roles } = {}) => enSerie(() => {
|
|
177
|
+
const m = trouver(id);
|
|
178
|
+
if (m.etat !== 'en_attente') throw erreur('E_TRANSITION', `la machine ${m.id} est « ${m.etat} » : acceptee impossible`);
|
|
179
|
+
const sienne = m.jeton ? empreinteMachine(m.jeton) : null;
|
|
180
|
+
if ((exigerEmpreinte || empreinte != null) && (!sienne || normEmpreinte(empreinte) !== normEmpreinte(sienne))) {
|
|
181
|
+
throw erreur('E_EMPREINTE', `empreinte ${empreinte ? 'différente' : 'absente'} : comparez celle qu'affiche le poste avant d'accepter`);
|
|
182
|
+
}
|
|
183
|
+
const caps = liste(capacites ?? m.annonce?.capacites ?? m.detecte?.capacites ?? []);
|
|
184
|
+
m.capacitesAcceptees = caps.length ? caps : null;
|
|
185
|
+
m.rolesAcceptes = m.capacitesAcceptees ? liste(roles ?? m.annonce?.roles ?? m.roles) : null;
|
|
186
|
+
m.capacitesEnAttente = []; m.rolesEnAttente = [];
|
|
187
|
+
m.etat = 'acceptee'; m.maj = iso(); noter(m, 'acceptee', par, empreinte != null ? { motif: `empreinte ${sienne}` } : {}); sauver();
|
|
188
|
+
}),
|
|
189
|
+
/**
|
|
190
|
+
* Ce qu'une machine annonce (appel de l'API à chaque annonce). En attente : retenu pour l'acceptation. Acceptée ou
|
|
191
|
+
* suspendue : seules les capacités et rôles acceptés valent ; les ajouts attendent une nouvelle acceptation (journal
|
|
192
|
+
* « capacites-demandees », une fois par demande). Rend { capacites, roles, refusees: { capacites, roles } }.
|
|
193
|
+
*/
|
|
194
|
+
noterAnnonce: (id, { capacites = [], roles = [] } = {}) => enSerie(() => {
|
|
195
|
+
const m = d.machines.find((x) => x.id === id);
|
|
196
|
+
const c = liste(capacites); const r = liste(roles);
|
|
197
|
+
const rien = { capacites: [], roles: [] };
|
|
198
|
+
if (!m) return { capacites: c, roles: r, refusees: rien };
|
|
199
|
+
if (m.etat === 'en_attente') {
|
|
200
|
+
if (!m.annonce || !memes(m.annonce.capacites, c) || !memes(m.annonce.roles, r)) { m.annonce = { capacites: c, roles: r }; sauver(); }
|
|
201
|
+
return { capacites: c, roles: r, refusees: rien };
|
|
202
|
+
}
|
|
203
|
+
if (!['acceptee', 'suspendue'].includes(m.etat)) return { capacites: [], roles: [], refusees: rien };
|
|
204
|
+
if (!m.capacitesAcceptees) { // acceptée sans rien de connu (ou avant 0.7.0) : figée à cette première annonce
|
|
205
|
+
m.capacitesAcceptees = c; m.rolesAcceptes = r; noter(m, 'capacites-figees', 'centrale', { motif: `capacités : ${c.join(', ') || 'aucune'} ; rôles : ${r.join(', ') || 'aucun'}` }); sauver();
|
|
206
|
+
return { capacites: c, roles: r, refusees: rien };
|
|
207
|
+
}
|
|
208
|
+
const nc = sauf(c, m.capacitesAcceptees); const nr = sauf(r, m.rolesAcceptes);
|
|
209
|
+
if ((nc.length || nr.length) && !(memes(nc, m.capacitesEnAttente) && memes(nr, m.rolesEnAttente))) {
|
|
210
|
+
m.capacitesEnAttente = nc; m.rolesEnAttente = nr; m.maj = iso();
|
|
211
|
+
noter(m, 'capacites-demandees', m.id, { motif: `capacités : ${nc.join(', ') || 'aucune'} ; rôles : ${nr.join(', ') || 'aucun'}` }); sauver();
|
|
212
|
+
}
|
|
213
|
+
return { capacites: inter(c, m.capacitesAcceptees), roles: inter(r, m.rolesAcceptes), refusees: { capacites: nc, roles: nr } };
|
|
214
|
+
}),
|
|
215
|
+
/** Le fondateur accepte les ajouts demandés (capacités et/ou rôles) ; ce qu'il n'accepte pas est écarté. */
|
|
216
|
+
accepterCapacites: (id, { par, capacites = true, roles = true } = {}) => enSerie(() => {
|
|
217
|
+
const m = trouver(id);
|
|
218
|
+
const ac = capacites ? [...(m.capacitesEnAttente || [])] : []; const ar = roles ? [...(m.rolesEnAttente || [])] : [];
|
|
219
|
+
m.capacitesAcceptees = [...new Set([...(m.capacitesAcceptees || []), ...ac])]; m.rolesAcceptes = [...new Set([...(m.rolesAcceptes || []), ...ar])];
|
|
220
|
+
m.capacitesEnAttente = []; m.rolesEnAttente = []; m.maj = iso();
|
|
221
|
+
noter(m, 'capacites-acceptees', par, { motif: `capacités : ${ac.join(', ') || 'aucune'} ; rôles : ${ar.join(', ') || 'aucun'}` }); sauver();
|
|
222
|
+
return vue(m);
|
|
223
|
+
}),
|
|
224
|
+
refuserCapacites: (id, { par } = {}) => enSerie(() => {
|
|
225
|
+
const m = trouver(id); const motif = `capacités : ${(m.capacitesEnAttente || []).join(', ') || 'aucune'} ; rôles : ${(m.rolesEnAttente || []).join(', ') || 'aucun'}`;
|
|
226
|
+
m.capacitesEnAttente = []; m.rolesEnAttente = []; m.maj = iso(); noter(m, 'capacites-refusees', par, { motif }); sauver();
|
|
227
|
+
return vue(m);
|
|
228
|
+
}),
|
|
229
|
+
/** Le dernier signe de vie (R4), écrit au plus toutes les `vuEcritureMin` minutes. */
|
|
230
|
+
noterVu: (id, quand) => enSerie(() => {
|
|
231
|
+
const m = d.machines.find((x) => x.id === id); if (!m) return;
|
|
232
|
+
const avant = m.vu ? Date.parse(m.vu) : 0;
|
|
233
|
+
m.vu = quand;
|
|
234
|
+
if (Date.parse(quand) - avant >= vuEcritureMin * 60_000) sauver();
|
|
235
|
+
}),
|
|
236
|
+
/** Une machine acceptée muette depuis trop longtemps : suspendue (« muette » au journal), jamais effacée. */
|
|
237
|
+
mettreEnSommeil: (id, motif) => enSerie(() => {
|
|
238
|
+
const m = trouver(id); if (m.etat !== 'acceptee') return false;
|
|
239
|
+
m.etat = 'suspendue'; m.maj = iso(); noter(m, 'muette', 'centrale', { motif }); sauver(); return true;
|
|
240
|
+
}),
|
|
241
|
+
refuser: (id, { par } = {}) => enSerie(() => { const m = trouver(id); passer(m, ['en_attente', 'annoncee'], 'refusee', 'refusee', par); m.jeton = null; m.enrolement = null; sauver(); }),
|
|
242
|
+
suspendre: (id, { par } = {}) => enSerie(() => { passer(trouver(id), ['acceptee'], 'suspendue', 'suspendue', par); sauver(); }),
|
|
243
|
+
reprendre: (id, { par } = {}) => enSerie(() => { passer(trouver(id), ['suspendue'], 'acceptee', 'reprise', par); sauver(); }),
|
|
244
|
+
retirer: (id, { par } = {}) => enSerie(() => { const m = trouver(id); passer(m, ETATS_MACHINE.filter((x) => x !== 'retiree'), 'retiree', 'retiree', par); m.jeton = null; m.enrolement = null; sauver(); }),
|
|
245
|
+
/** Révoque le jeton durable : la machine repasse par l'enrôlement (nouveau jeton, montré une fois) et l'acceptation. */
|
|
246
|
+
revoquer: (id, { par } = {}) => enSerie(() => {
|
|
247
|
+
const m = trouver(id);
|
|
248
|
+
passer(m, ['en_attente', 'acceptee', 'suspendue', 'annoncee'], 'annoncee', 'revoquee', par);
|
|
249
|
+
m.jeton = null; const jetonEnrolement = nouvelEnrolement(m); sauver();
|
|
250
|
+
return { jetonEnrolement };
|
|
251
|
+
}),
|
|
252
|
+
renommer: (id, nom, { par } = {}) => enSerie(() => {
|
|
253
|
+
if (typeof nom !== 'string' || !NOM.test(nom.trim())) throw erreur('E_NOM', 'nom : 2 à 40 caractères');
|
|
254
|
+
const m = trouver(id); const avant = m.nom; m.nom = nom.trim(); m.maj = iso(); noter(m, 'renommee', par, { motif: `${avant} → ${m.nom}` }); sauver();
|
|
255
|
+
}),
|
|
256
|
+
/** La machine que désigne un jeton durable (en attente, acceptée ou suspendue), ou null. */
|
|
257
|
+
identifier: (jeton) => enSerie(() => {
|
|
258
|
+
const e = empreinte(jeton);
|
|
259
|
+
const m = d.machines.find((x) => x.jeton && ['en_attente', 'acceptee', 'suspendue'].includes(x.etat) && egales(x.jeton, e));
|
|
260
|
+
return m ? vue(m) : null;
|
|
261
|
+
}),
|
|
262
|
+
machines: () => enSerie(() => d.machines.map(vue)),
|
|
263
|
+
/** Les empreintes des jetons durables admis au canal (en attente, acceptées, suspendues) : usage interne de l'API. */
|
|
264
|
+
empreintes: () => enSerie(() => d.machines.filter((x) => x.jeton && ['en_attente', 'acceptee', 'suspendue'].includes(x.etat)).map((x) => ({ id: x.id, jeton: x.jeton }))),
|
|
265
|
+
/** Le réglage de la centrale (maestro) : { executer, types, concurrence } ; désactivé par défaut. */
|
|
266
|
+
reglageCentrale: () => enSerie(() => ({ ...d.centrale, types: [...d.centrale.types] })),
|
|
267
|
+
/** Le fondateur règle la centrale ; « train » refusé (E_INTERDIT) ; concurrence 1 à 8 (E_REGLAGE) ; au journal. */
|
|
268
|
+
reglerCentrale: ({ executer = false, types = [], concurrence = 1 } = {}, { par } = {}) => enSerie(() => {
|
|
269
|
+
if (!Array.isArray(types) || types.some((t) => typeof t !== 'string' || !TYPE.test(t))) throw erreur('E_REGLAGE', 'types : des noms de types');
|
|
270
|
+
if (types.includes('train')) throw erreur('E_INTERDIT', 'le conducteur de train (« train ») ne va jamais à la centrale');
|
|
271
|
+
if (!Number.isInteger(concurrence) || concurrence < 1 || concurrence > 8) throw erreur('E_REGLAGE', 'concurrence : un entier de 1 à 8');
|
|
272
|
+
d.centrale = reglageSur({ executer: executer === true, types, concurrence });
|
|
273
|
+
d.journal.push({ machine: 'centrale', quoi: 'centrale-reglee', par: par ?? null, quand: iso(),
|
|
274
|
+
motif: `exécute : ${d.centrale.executer ? 'oui' : 'non'} ; types : ${d.centrale.types.join(', ') || 'aucun'} ; concurrence : ${d.centrale.concurrence}` });
|
|
275
|
+
sauver(); return { ...d.centrale, types: [...d.centrale.types] };
|
|
276
|
+
}),
|
|
277
|
+
/** La marche d'une machine vue par l'API (« hors-ligne », « en-ligne ») : au journal, sans changer son état. */
|
|
278
|
+
noterMarche: (id, quoi, motif) => enSerie(() => { const m = d.machines.find((x) => x.id === id); if (!m) return; noter(m, quoi, 'centrale', motif ? { motif } : {}); sauver(); }),
|
|
279
|
+
machine: (id) => enSerie(() => { const m = d.machines.find((x) => x.id === id); return m ? vue(m) : null; }),
|
|
280
|
+
journal: (id) => enSerie(() => d.journal.filter((l) => !id || l.machine === id).map((l) => bornerJson(l))),
|
|
281
|
+
};
|
|
282
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// @mostajs/delegation — ce qui dépend du SYSTÈME (R9, 0.9.0) : Linux, macOS, Windows. Chemins et dossier de données,
|
|
2
|
+
// « jamais root » (jamais administrateur élevé sous Windows), signaux d'arrêt, arrêt d'un arbre de processus,
|
|
3
|
+
// recherche des programmes sans shell, droits du jeton et de la clé (600/700, ou ACL icacls sous Windows).
|
|
4
|
+
// Chaque fonction prend la plateforme, l'environnement et ses sondes en option : les essais simulent un autre système.
|
|
5
|
+
// @author Dr Hamid MADANI <drmdh@msn.com>
|
|
6
|
+
import { chmodSync, statSync } from 'node:fs';
|
|
7
|
+
import { posix, win32 } from 'node:path';
|
|
8
|
+
import { homedir, userInfo } from 'node:os';
|
|
9
|
+
import { spawnSync } from 'node:child_process';
|
|
10
|
+
|
|
11
|
+
const chemin = (plateforme) => (plateforme === 'win32' ? win32 : posix);
|
|
12
|
+
const executerParDefaut = (programme, args) => spawnSync(programme, args, { stdio: 'ignore', windowsHide: true });
|
|
13
|
+
const estFichier = (p) => { try { return statSync(p).isFile(); } catch { return false; } };
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Les chemins de l'agent sur cette plateforme : dossier de données (jeton, configuration, clé publique, agent installé)
|
|
17
|
+
* et journaux. Linux `~/.delegation` ; macOS `~/Library/Application Support/mostajs/delegation` (journaux dans
|
|
18
|
+
* `~/Library/Logs/mostajs-delegation`) ; Windows `%LOCALAPPDATA%\mostajs\delegation`.
|
|
19
|
+
*/
|
|
20
|
+
export function cheminsAgent({ plateforme = process.platform, env = process.env, home = homedir() } = {}) {
|
|
21
|
+
const p = chemin(plateforme);
|
|
22
|
+
let donnees; let journaux;
|
|
23
|
+
if (plateforme === 'win32') {
|
|
24
|
+
donnees = p.join(env.LOCALAPPDATA || p.join(home, 'AppData', 'Local'), 'mostajs', 'delegation');
|
|
25
|
+
journaux = p.join(donnees, 'journaux');
|
|
26
|
+
} else if (plateforme === 'darwin') {
|
|
27
|
+
donnees = p.join(home, 'Library', 'Application Support', 'mostajs', 'delegation');
|
|
28
|
+
journaux = p.join(home, 'Library', 'Logs', 'mostajs-delegation');
|
|
29
|
+
} else {
|
|
30
|
+
donnees = p.join(home, '.delegation');
|
|
31
|
+
journaux = p.join(donnees, 'journaux');
|
|
32
|
+
}
|
|
33
|
+
return { donnees, journaux, agent: p.join(donnees, 'agent'), jeton: p.join(donnees, 'jeton'), configuration: p.join(donnees, 'agent.mjs'),
|
|
34
|
+
clePublique: p.join(donnees, 'cle-publique.pem') };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** « ~ », « ~/x » et, sous Windows, « ~\x » → le dossier personnel. Un « ~ » ailleurs qu'en tête ne bouge pas. */
|
|
38
|
+
export function etendreTilde(p, { home = homedir(), plateforme = process.platform } = {}) {
|
|
39
|
+
const s = String(p ?? '');
|
|
40
|
+
const re = plateforme === 'win32' ? /^~(?=[\\/]|$)/ : /^~(?=\/|$)/;
|
|
41
|
+
return s.replace(re, () => home);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Les signaux qui arrêtent proprement l'agent : SIGBREAK (Ctrl+Pause, fermeture de console) s'ajoute sous Windows. */
|
|
45
|
+
export function signauxArret(plateforme = process.platform) {
|
|
46
|
+
return plateforme === 'win32' ? ['SIGTERM', 'SIGINT', 'SIGBREAK'] : ['SIGTERM', 'SIGINT'];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Vrai si le processus a les pleins pouvoirs : root (uid 0) sous Linux et macOS ; sous Windows, une session ÉLEVÉE
|
|
51
|
+
* (`net session` ne réussit qu'en administrateur élevé ; un administrateur non élevé, sous le contrôle de compte
|
|
52
|
+
* d'utilisateur, n'a pas ces droits et passe).
|
|
53
|
+
*/
|
|
54
|
+
export function estAdministrateur({ plateforme = process.platform, uid = process.getuid?.(), executer = executerParDefaut } = {}) {
|
|
55
|
+
if (plateforme !== 'win32') return uid === 0;
|
|
56
|
+
try { const r = executer('net', ['session']); return !r?.error && r?.status === 0; } catch { return false; }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** La commande qui arrête un processus ET ses enfants : `taskkill /T /F` sous Windows ; null ailleurs (kill du groupe). */
|
|
60
|
+
export function commandeArretArbre(pid, plateforme = process.platform) {
|
|
61
|
+
return plateforme === 'win32' ? { programme: 'taskkill', arguments: ['/PID', String(pid), '/T', '/F'] } : null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Cherche un programme dans le PATH, sans shell ; sous Windows, avec les extensions de PATHEXT. Rend son chemin ou null. */
|
|
65
|
+
export function trouverProgramme(nom, { plateforme = process.platform, env = process.env, existe = estFichier } = {}) {
|
|
66
|
+
const p = chemin(plateforme);
|
|
67
|
+
const dossiers = String(env.PATH ?? env.Path ?? '').split(plateforme === 'win32' ? ';' : ':').filter(Boolean);
|
|
68
|
+
const exts = plateforme === 'win32' ? ['', ...String(env.PATHEXT || '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean)] : [''];
|
|
69
|
+
for (const d of dossiers) {
|
|
70
|
+
for (const e of exts) {
|
|
71
|
+
if (plateforme === 'win32' && e === '' && !/\.[A-Za-z0-9]+$/.test(nom)) continue;
|
|
72
|
+
for (const x of plateforme === 'win32' && e ? [e, e.toLowerCase()] : [e]) {
|
|
73
|
+
const f = p.join(d, `${nom}${x}`);
|
|
74
|
+
if (existe(f)) return f;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Le bash qui exécute les étapes « commande ». Sous Windows : celui de Git for Windows, jamais le `bash.exe` de
|
|
83
|
+
* System32 (le lanceur WSL, qui exécuterait la commande dans un autre système).
|
|
84
|
+
*/
|
|
85
|
+
export function trouverBash({ plateforme = process.platform, env = process.env, existe = estFichier } = {}) {
|
|
86
|
+
if (plateforme !== 'win32') return trouverProgramme('bash', { plateforme, env, existe });
|
|
87
|
+
const p = win32;
|
|
88
|
+
for (const racine of [env.ProgramFiles, env['ProgramFiles(x86)'], env.ProgramW6432, env.LOCALAPPDATA && p.join(env.LOCALAPPDATA, 'Programs')].filter(Boolean)) {
|
|
89
|
+
for (const f of [p.join(racine, 'Git', 'bin', 'bash.exe'), p.join(racine, 'Git', 'usr', 'bin', 'bash.exe')]) if (existe(f)) return f;
|
|
90
|
+
}
|
|
91
|
+
const sansSystem32 = String(env.PATH ?? env.Path ?? '').split(';').filter((d) => d && !/\\(System32|SysWOW64|WindowsApps)\\?$/i.test(d)).join(';');
|
|
92
|
+
return trouverProgramme('bash', { plateforme, env: { ...env, PATH: sansSystem32 }, existe });
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Chrome ou Chromium : dans le PATH (Linux), dans /Applications (macOS), dans Program Files (Windows). */
|
|
96
|
+
export function trouverChrome({ plateforme = process.platform, env = process.env, existe = estFichier, home = homedir() } = {}) {
|
|
97
|
+
if (plateforme === 'darwin') {
|
|
98
|
+
for (const app of ['Google Chrome.app/Contents/MacOS/Google Chrome', 'Chromium.app/Contents/MacOS/Chromium']) {
|
|
99
|
+
for (const d of ['/Applications', posix.join(home, 'Applications')]) { const f = posix.join(d, app); if (existe(f)) return f; }
|
|
100
|
+
}
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
if (plateforme === 'win32') {
|
|
104
|
+
for (const r of [env.ProgramFiles, env['ProgramFiles(x86)'], env.LOCALAPPDATA].filter(Boolean)) {
|
|
105
|
+
for (const f of [win32.join(r, 'Google', 'Chrome', 'Application', 'chrome.exe'), win32.join(r, 'Chromium', 'Application', 'chrome.exe')]) if (existe(f)) return f;
|
|
106
|
+
}
|
|
107
|
+
return trouverProgramme('chrome', { plateforme, env, existe });
|
|
108
|
+
}
|
|
109
|
+
for (const c of ['google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser']) { const f = trouverProgramme(c, { plateforme, env, existe }); if (f) return f; }
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Vrai si un fichier secret est lisible par d'autres comptes. Sous Windows, le mode ne dit rien (l'ACL décide) : faux. */
|
|
114
|
+
export function droitsTropOuverts(mode, plateforme = process.platform) {
|
|
115
|
+
return plateforme !== 'win32' && (mode & 0o077) !== 0;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Restreint un fichier (ou un dossier) secret à son propriétaire : 600 / 700 sous POSIX ; sous Windows, l'ACL par
|
|
120
|
+
* `icacls` (héritage coupé, l'utilisateur et SYSTEM seuls ; pour un dossier, hérité par ses enfants). Rend { ok }.
|
|
121
|
+
*/
|
|
122
|
+
export function restreindreAcces(cible, { plateforme = process.platform, utilisateur, dossier = false, executer = executerParDefaut } = {}) {
|
|
123
|
+
if (plateforme !== 'win32') {
|
|
124
|
+
try { chmodSync(cible, dossier ? 0o700 : 0o600); return { ok: true }; } catch (e) { return { ok: false, motif: e.message }; }
|
|
125
|
+
}
|
|
126
|
+
const qui = utilisateur || (process.env.USERDOMAIN ? `${process.env.USERDOMAIN}\\${userInfo().username}` : userInfo().username);
|
|
127
|
+
const h = dossier ? '(OI)(CI)' : '';
|
|
128
|
+
const args = [cible, '/inheritance:r', '/grant:r', `${qui}:${h}F`, `*S-1-5-18:${h}F`];
|
|
129
|
+
try {
|
|
130
|
+
const r = executer('icacls', args);
|
|
131
|
+
return r?.status === 0 ? { ok: true, programme: 'icacls', arguments: args } : { ok: false, programme: 'icacls', arguments: args, motif: `icacls : code ${r?.status ?? r?.error?.message}` };
|
|
132
|
+
} catch (e) { return { ok: false, motif: e.message }; }
|
|
133
|
+
}
|
|
134
|
+
|