@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/services.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
// @mostajs/delegation — ce que l'agent pose pour démarrer au boot et redémarrer après une panne, hors Linux (R9, 0.9.0) :
|
|
2
|
+
// macOS : un plist launchd (LaunchAgent de l'utilisateur, ou LaunchDaemon sous un compte dédié) — RunAtLoad,
|
|
3
|
+
// KeepAlive { SuccessfulExit: false } (relance après une panne, pas après un arrêt propre), ThrottleInterval ;
|
|
4
|
+
// Windows : une tâche planifiée (au démarrage en S4U pour un compte dédié, ou à l'ouverture de session) qui lance le
|
|
5
|
+
// VEILLEUR (lui relance l'agent), répétée toutes les 5 min sans jamais doubler, relancée après un échec.
|
|
6
|
+
// Et la configuration de l'agent (agent.mjs), écrite une fois. Générés ici, en JavaScript, pour être VALIDÉS par les
|
|
7
|
+
// essais sur n'importe quel système ; les installateurs (bash, PowerShell) ne font que les poser.
|
|
8
|
+
// @author Dr Hamid MADANI <drmdh@msn.com>
|
|
9
|
+
import { writeFileSync, existsSync } from 'node:fs';
|
|
10
|
+
import { pathToFileURL } from 'node:url';
|
|
11
|
+
import { posix } from 'node:path';
|
|
12
|
+
|
|
13
|
+
export const LABEL_LAUNCHD = 'dev.mostajs.delegation-agent';
|
|
14
|
+
export const TACHE_WINDOWS = Object.freeze({ chemin: '\\mostajs\\', nom: 'delegation-agent' });
|
|
15
|
+
const erreur = (code, message) => Object.assign(new Error(message), { code });
|
|
16
|
+
const xml = (s) => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
17
|
+
const requis = (o, cles) => { for (const k of cles) if (typeof o[k] !== 'string' || !o[k]) throw erreur('E_OPTION', `${k} : requis`); };
|
|
18
|
+
const COMPTE_MAC = /^[A-Za-z_][A-Za-z0-9_.-]{0,31}$/;
|
|
19
|
+
|
|
20
|
+
/** Où poser le plist : ~/Library/LaunchAgents (utilisateur, sans sudo) ou /Library/LaunchDaemons (système). */
|
|
21
|
+
export function cheminPlist({ mode = 'utilisateur', home }) {
|
|
22
|
+
return mode === 'systeme' ? `/Library/LaunchDaemons/${LABEL_LAUNCHD}.plist` : posix.join(home, 'Library', 'LaunchAgents', `${LABEL_LAUNCHD}.plist`);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Le plist launchd de l'agent.
|
|
27
|
+
* @param {{ mode: 'utilisateur'|'systeme', node: string, agent: string, configuration: string, journaux: string,
|
|
28
|
+
* donnees: string, home: string, compte?: string }} o compte : requis en « systeme » (clé UserName), jamais root.
|
|
29
|
+
*/
|
|
30
|
+
export function plistLaunchd(o) {
|
|
31
|
+
const { mode = 'utilisateur', node, agent, configuration, journaux, donnees, home, compte } = o || {};
|
|
32
|
+
if (!['utilisateur', 'systeme'].includes(mode)) throw erreur('E_OPTION', 'mode : utilisateur ou systeme');
|
|
33
|
+
requis(o, ['node', 'agent', 'configuration', 'journaux', 'donnees', 'home']);
|
|
34
|
+
if (mode === 'systeme' && (!COMPTE_MAC.test(compte || '') || compte === 'root')) throw erreur('E_OPTION', 'compte : un compte sans privilège (jamais root), requis pour un LaunchDaemon');
|
|
35
|
+
const chaine = (v) => `<string>${xml(v)}</string>`;
|
|
36
|
+
const lignes = [
|
|
37
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
38
|
+
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
|
|
39
|
+
'<plist version="1.0">',
|
|
40
|
+
'<dict>',
|
|
41
|
+
'\t<key>Label</key>', `\t${chaine(LABEL_LAUNCHD)}`,
|
|
42
|
+
'\t<key>ProgramArguments</key>', '\t<array>', ...[node, agent, '--config', configuration].map((a) => `\t\t${chaine(a)}`), '\t</array>',
|
|
43
|
+
...(mode === 'systeme' ? ['\t<key>UserName</key>', `\t${chaine(compte)}`] : []),
|
|
44
|
+
'\t<key>WorkingDirectory</key>', `\t${chaine(donnees)}`,
|
|
45
|
+
'\t<key>RunAtLoad</key>', '\t<true/>',
|
|
46
|
+
'\t<key>KeepAlive</key>', '\t<dict>', '\t\t<key>SuccessfulExit</key>', '\t\t<false/>', '\t</dict>',
|
|
47
|
+
'\t<key>ThrottleInterval</key>', '\t<integer>30</integer>',
|
|
48
|
+
'\t<key>ProcessType</key>', `\t${chaine('Background')}`,
|
|
49
|
+
'\t<key>StandardOutPath</key>', `\t${chaine(posix.join(journaux, 'agent.log'))}`,
|
|
50
|
+
'\t<key>StandardErrorPath</key>', `\t${chaine(posix.join(journaux, 'agent.err.log'))}`,
|
|
51
|
+
'\t<key>EnvironmentVariables</key>', '\t<dict>',
|
|
52
|
+
'\t\t<key>HOME</key>', `\t\t${chaine(home)}`,
|
|
53
|
+
'\t\t<key>PATH</key>', `\t\t${chaine('/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin')}`,
|
|
54
|
+
'\t</dict>',
|
|
55
|
+
'</dict>',
|
|
56
|
+
'</plist>',
|
|
57
|
+
];
|
|
58
|
+
return `${lignes.join('\n')}\n`;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const COMPTE_WIN = /^[^"<>&|\r\n]{1,104}$/;
|
|
62
|
+
/**
|
|
63
|
+
* La définition (XML du Planificateur de tâches) de la tâche Windows de l'agent.
|
|
64
|
+
* @param {{ mode: 'utilisateur'|'systeme', utilisateur: string, node: string, veilleur: string, configuration: string,
|
|
65
|
+
* journal: string, donnees: string }} o
|
|
66
|
+
* systeme : déclencheur AU DÉMARRAGE (un administrateur l'enregistre une fois), ouverture S4U (aucun mot de passe
|
|
67
|
+
* conservé) sous `utilisateur`, le compte dédié ; utilisateur : à l'ouverture de SA session (sans droits).
|
|
68
|
+
*/
|
|
69
|
+
export function tacheWindows(o) {
|
|
70
|
+
const { mode = 'utilisateur', utilisateur, node, veilleur, configuration, journal, donnees } = o || {};
|
|
71
|
+
if (!['utilisateur', 'systeme'].includes(mode)) throw erreur('E_OPTION', 'mode : utilisateur ou systeme');
|
|
72
|
+
requis(o, ['utilisateur', 'node', 'veilleur', 'configuration', 'journal', 'donnees']);
|
|
73
|
+
if (!COMPTE_WIN.test(utilisateur)) throw erreur('E_OPTION', 'utilisateur : un nom de compte Windows');
|
|
74
|
+
for (const k of ['node', 'veilleur', 'configuration', 'journal', 'donnees']) if (/["\r\n]/.test(o[k])) throw erreur('E_OPTION', `${k} : un chemin sans guillemet`);
|
|
75
|
+
const repetition = ['\t\t\t<Repetition>', '\t\t\t\t<Interval>PT5M</Interval>', '\t\t\t\t<StopAtDurationEnd>false</StopAtDurationEnd>', '\t\t\t</Repetition>'];
|
|
76
|
+
const declencheur = mode === 'systeme'
|
|
77
|
+
? ['\t\t<BootTrigger>', ...repetition, '\t\t\t<Enabled>true</Enabled>', '\t\t\t<Delay>PT30S</Delay>', '\t\t</BootTrigger>']
|
|
78
|
+
: ['\t\t<LogonTrigger>', ...repetition, '\t\t\t<Enabled>true</Enabled>', `\t\t\t<UserId>${xml(utilisateur)}</UserId>`, '\t\t</LogonTrigger>'];
|
|
79
|
+
const args = `"${veilleur}" --journal "${journal}" --config "${configuration}"`;
|
|
80
|
+
const lignes = [
|
|
81
|
+
'<?xml version="1.0" encoding="UTF-16"?>',
|
|
82
|
+
'<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">',
|
|
83
|
+
'\t<RegistrationInfo>',
|
|
84
|
+
'\t\t<Author>@mostajs/delegation</Author>',
|
|
85
|
+
'\t\t<Description>Agent de délégation : tire ses tâches de la centrale ; relancé par son veilleur, et par cette tâche toutes les 5 minutes s’il ne tourne plus.</Description>',
|
|
86
|
+
'\t</RegistrationInfo>',
|
|
87
|
+
'\t<Triggers>', ...declencheur, '\t</Triggers>',
|
|
88
|
+
'\t<Principals>',
|
|
89
|
+
'\t\t<Principal id="Author">',
|
|
90
|
+
`\t\t\t<UserId>${xml(utilisateur)}</UserId>`,
|
|
91
|
+
`\t\t\t<LogonType>${mode === 'systeme' ? 'S4U' : 'InteractiveToken'}</LogonType>`,
|
|
92
|
+
'\t\t\t<RunLevel>LeastPrivilege</RunLevel>',
|
|
93
|
+
'\t\t</Principal>',
|
|
94
|
+
'\t</Principals>',
|
|
95
|
+
'\t<Settings>',
|
|
96
|
+
'\t\t<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>',
|
|
97
|
+
'\t\t<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>',
|
|
98
|
+
'\t\t<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>',
|
|
99
|
+
'\t\t<AllowHardTerminate>true</AllowHardTerminate>',
|
|
100
|
+
'\t\t<StartWhenAvailable>true</StartWhenAvailable>',
|
|
101
|
+
'\t\t<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>',
|
|
102
|
+
'\t\t<IdleSettings>', '\t\t\t<StopOnIdleEnd>false</StopOnIdleEnd>', '\t\t\t<RestartOnIdle>false</RestartOnIdle>', '\t\t</IdleSettings>',
|
|
103
|
+
'\t\t<AllowStartOnDemand>true</AllowStartOnDemand>',
|
|
104
|
+
'\t\t<Enabled>true</Enabled>',
|
|
105
|
+
'\t\t<Hidden>false</Hidden>',
|
|
106
|
+
'\t\t<RunOnlyIfIdle>false</RunOnlyIfIdle>',
|
|
107
|
+
'\t\t<WakeToRun>false</WakeToRun>',
|
|
108
|
+
'\t\t<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>',
|
|
109
|
+
'\t\t<Priority>7</Priority>',
|
|
110
|
+
'\t\t<RestartOnFailure>', '\t\t\t<Interval>PT1M</Interval>', '\t\t\t<Count>10</Count>', '\t\t</RestartOnFailure>',
|
|
111
|
+
'\t</Settings>',
|
|
112
|
+
'\t<Actions Context="Author">',
|
|
113
|
+
'\t\t<Exec>',
|
|
114
|
+
`\t\t\t<Command>${xml(node)}</Command>`,
|
|
115
|
+
`\t\t\t<Arguments>${xml(args)}</Arguments>`,
|
|
116
|
+
`\t\t\t<WorkingDirectory>${xml(donnees)}</WorkingDirectory>`,
|
|
117
|
+
'\t\t</Exec>',
|
|
118
|
+
'\t</Actions>',
|
|
119
|
+
'</Task>',
|
|
120
|
+
];
|
|
121
|
+
return `${lignes.join('\r\n')}\r\n`;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* La configuration de l'agent (agent.mjs), écrite UNE fois (jamais écrasée) en 600 : adresse, jeton, rôles, capacités
|
|
126
|
+
* détectées à chaque démarrage, clé publique des ordres, canal « auto », aucun type. L'import du module est une URL
|
|
127
|
+
* file:// (un chemin « C:\… » n'est pas un spécificateur ESM valable sous Windows). Rend vrai si elle a été écrite.
|
|
128
|
+
*/
|
|
129
|
+
export function ecrireConfigurationAgent({ sortie, centrale, jetonFichier, cleFichier, roles = [], conducteur = false, module, racine = '~/cidev' }) {
|
|
130
|
+
if (!sortie || !centrale || !jetonFichier || !module) throw erreur('E_OPTION', 'sortie, centrale, jetonFichier et module requis');
|
|
131
|
+
if (existsSync(sortie)) return false;
|
|
132
|
+
const url = /^file:/.test(module) ? module : pathToFileURL(module).href;
|
|
133
|
+
const t = `// Agent de délégation de cette machine : écrit une fois à l'installation, jamais écrasé.
|
|
134
|
+
// Les TYPES et leurs commandes s'ajoutent ici à la main : la centrale n'envoie que { type, entrees }.
|
|
135
|
+
// Sous Windows, préférez des étapes { programme, arguments } (sans shell) ; un type qui passe par bash déclare la
|
|
136
|
+
// capacité « bash » (Git for Windows).
|
|
137
|
+
import { detecterCapacites } from ${JSON.stringify(url)};
|
|
138
|
+
const capacites = detecterCapacites().capacites; // relevées à chaque démarrage
|
|
139
|
+
export default {
|
|
140
|
+
url: ${JSON.stringify(centrale)},
|
|
141
|
+
jetonFichier: ${JSON.stringify(jetonFichier)},
|
|
142
|
+
roles: ${JSON.stringify(roles)},
|
|
143
|
+
capacites: [...capacites${conducteur ? ', "conducteur"' : ''}],
|
|
144
|
+
racine: ${JSON.stringify(racine)},
|
|
145
|
+
travailJetable: true, // un dossier de travail neuf par tâche, effacé à la fin
|
|
146
|
+
clesFichiers: [${cleFichier ? JSON.stringify(cleFichier) : ''}], // les clés publiques des ordres signés : sans elles, l'agent ne démarre pas
|
|
147
|
+
intervalleS: 30,
|
|
148
|
+
canal: { mode: "auto" },
|
|
149
|
+
types: [],
|
|
150
|
+
};
|
|
151
|
+
`;
|
|
152
|
+
writeFileSync(sortie, t, { mode: 0o600, flag: 'wx' });
|
|
153
|
+
return true;
|
|
154
|
+
}
|
package/src/signature.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
// @mostajs/delegation — les ORDRES SIGNÉS (R1, décision du fondateur du 21/11/2026, D-E2).
|
|
2
|
+
//
|
|
3
|
+
// Au feu vert, la console fait signer l'ordre `{ id, type, entrees, echeance, nonce }` par la clé Ed25519 du fondateur.
|
|
4
|
+
// La clé PRIVÉE reste sur son poste (un fichier en 600, jamais dans un dépôt) ; la centrale et les machines n'ont que des
|
|
5
|
+
// clés PUBLIQUES. L'agent vérifie avec SES clés publiques locales : une centrale compromise ne peut plus fabriquer un feu
|
|
6
|
+
// vert, ni retoucher les entrées d'un ordre, ni rejouer un ordre déjà exécuté, ni en servir un expiré.
|
|
7
|
+
// Seul node:crypto est utilisé.
|
|
8
|
+
// @author Dr Hamid MADANI <drmdh@msn.com>
|
|
9
|
+
import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, sign, verify } from 'node:crypto';
|
|
10
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
11
|
+
|
|
12
|
+
const erreur = (code, message) => Object.assign(new Error(message), { code });
|
|
13
|
+
/** Tolérance d'horloge entre le poste et la machine, en millisecondes. */
|
|
14
|
+
export const TOLERANCE_HORLOGE_MS = 5 * 60_000;
|
|
15
|
+
|
|
16
|
+
/** Une paire de clés Ed25519 au format PEM (SPKI pour la publique, PKCS#8 pour la privée). */
|
|
17
|
+
export function creerCleSignature() {
|
|
18
|
+
const { publicKey, privateKey } = generateKeyPairSync('ed25519');
|
|
19
|
+
return { publique: publicKey.export({ type: 'spki', format: 'pem' }), privee: privateKey.export({ type: 'pkcs8', format: 'pem' }) };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const publiqueDe = (pem) => {
|
|
23
|
+
const s = String(pem);
|
|
24
|
+
return /PRIVATE KEY/.test(s) ? createPublicKey(createPrivateKey(s)) : createPublicKey(s);
|
|
25
|
+
};
|
|
26
|
+
/** L'empreinte courte d'une clé (publique ou privée : la même) : 16 chiffres hexadécimaux en quatre groupes. */
|
|
27
|
+
export function empreinteCle(pem) {
|
|
28
|
+
const der = publiqueDe(pem).export({ type: 'spki', format: 'der' });
|
|
29
|
+
return createHash('sha256').update(der).digest('hex').slice(0, 16).match(/.{4}/g).join('-');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** JSON canonique : clés triées à toute profondeur ; c'est ce texte qui est signé. */
|
|
33
|
+
export function canonique(v) {
|
|
34
|
+
if (Array.isArray(v)) return `[${v.map(canonique).join(',')}]`;
|
|
35
|
+
if (v && typeof v === 'object') return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canonique(v[k])}`).join(',')}}`;
|
|
36
|
+
return JSON.stringify(v ?? null);
|
|
37
|
+
}
|
|
38
|
+
const corpsOrdre = (t, o) => canonique({ id: t.id, type: t.type, entrees: t.entrees ?? {}, echeance: o.echeance, nonce: o.nonce });
|
|
39
|
+
|
|
40
|
+
/** L'ordre à signer pour une tâche : échéance (`dureeH`, 24 h par défaut) et nonce neufs. */
|
|
41
|
+
export function nouvelOrdre(tache, { dureeH = 24, maintenant = () => new Date() } = {}) {
|
|
42
|
+
if (!tache?.id || !tache?.type) throw erreur('E_ORDRE', 'nouvelOrdre : une tâche { id, type, entrees }');
|
|
43
|
+
if (!(Number(dureeH) > 0) || Number(dureeH) > 24 * 30) throw erreur('E_ORDRE', 'dureeH : de 0 à 720 heures');
|
|
44
|
+
return { id: tache.id, type: tache.type, entrees: structuredClone(tache.entrees ?? {}),
|
|
45
|
+
echeance: new Date(maintenant().getTime() + Number(dureeH) * 3600_000).toISOString(), nonce: randomBytes(16).toString('hex') };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Signe un ordre avec la clé privée (PEM) ; rend ce qui accompagne la tâche : { echeance, nonce, cle, signature }. */
|
|
49
|
+
export function signerOrdre(ordre, clePrivee) {
|
|
50
|
+
const k = createPrivateKey(String(clePrivee));
|
|
51
|
+
const signature = sign(null, Buffer.from(corpsOrdre(ordre, ordre)), k).toString('base64');
|
|
52
|
+
return { echeance: ordre.echeance, nonce: ordre.nonce, cle: empreinteCle(clePrivee), signature };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Vérifie l'ordre qui accompagne une tâche avec des clés publiques. Rend { ok, motif?, cle? }.
|
|
57
|
+
* Motifs : non signé, clé inconnue, signature invalide, expiré.
|
|
58
|
+
*/
|
|
59
|
+
export function verifierOrdre(tache, ordre, clesPubliques = [], { maintenant = () => new Date(), toleranceMs = TOLERANCE_HORLOGE_MS } = {}) {
|
|
60
|
+
if (!ordre || typeof ordre !== 'object' || typeof ordre.signature !== 'string' || typeof ordre.nonce !== 'string' || typeof ordre.echeance !== 'string') return { ok: false, motif: 'ordre non signé' };
|
|
61
|
+
if (!/^[0-9a-f]{32}$/.test(ordre.nonce)) return { ok: false, motif: 'ordre non signé (nonce illisible)' };
|
|
62
|
+
const cles = (clesPubliques || []).map((pem) => { try { return { pem, e: empreinteCle(pem) }; } catch { return null; } }).filter(Boolean);
|
|
63
|
+
const k = cles.find((x) => x.e === ordre.cle);
|
|
64
|
+
if (!k) return { ok: false, motif: `clé inconnue (${String(ordre.cle || '?').slice(0, 19)})` };
|
|
65
|
+
let bon = false;
|
|
66
|
+
try { bon = verify(null, Buffer.from(corpsOrdre(tache, ordre)), publiqueDe(k.pem), Buffer.from(ordre.signature, 'base64')); } catch { bon = false; }
|
|
67
|
+
if (!bon) return { ok: false, motif: 'signature invalide (ordre retouché ou mal signé)' };
|
|
68
|
+
const fin = Date.parse(ordre.echeance);
|
|
69
|
+
if (!Number.isFinite(fin) || maintenant().getTime() > fin + toleranceMs) return { ok: false, motif: `ordre expiré (${ordre.echeance})` };
|
|
70
|
+
return { ok: true, cle: k.e };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Lit la clé privée du fondateur depuis un fichier LOCAL au poste ; refuse un fichier lisible par d'autres comptes
|
|
75
|
+
* (E_CLE). Le chemin vient de la configuration du poste (une variable d'environnement), jamais d'un dépôt.
|
|
76
|
+
*/
|
|
77
|
+
export function lireClePrivee(chemin) {
|
|
78
|
+
if (!chemin) throw erreur('E_CLE', 'chemin de la clé privée absent');
|
|
79
|
+
let st;
|
|
80
|
+
try { st = statSync(chemin); } catch { throw erreur('E_CLE', `clé privée introuvable : ${chemin}`); }
|
|
81
|
+
if (process.platform !== 'win32' && (st.mode & 0o077) !== 0) throw erreur('E_CLE', `${chemin} est lisible par d'autres comptes : chmod 600`);
|
|
82
|
+
const pem = readFileSync(chemin, 'utf8');
|
|
83
|
+
try { createPrivateKey(pem); } catch { throw erreur('E_CLE', `${chemin} : pas une clé privée lisible`); }
|
|
84
|
+
return pem;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Le format de l'attestation de provenance d'un index de films (T2 du train). */
|
|
88
|
+
export const FORMAT_ATTESTATION = 'mostajs-delegation-attestation/1';
|
|
89
|
+
/**
|
|
90
|
+
* Signe une attestation (un objet sans `cle` ni `signature`) : rend l'objet augmenté de { cle, signature }.
|
|
91
|
+
* Le texte signé est le JSON canonique de l'objet.
|
|
92
|
+
*/
|
|
93
|
+
export function signerAttestation(sujet, clePrivee) {
|
|
94
|
+
const { cle: _c, signature: _s, ...corps } = sujet || {};
|
|
95
|
+
const signature = sign(null, Buffer.from(canonique(corps)), createPrivateKey(String(clePrivee))).toString('base64');
|
|
96
|
+
return { ...corps, cle: empreinteCle(clePrivee), signature };
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Vérifie une attestation avec des clés publiques ; `index` (chemin) : l'empreinte SHA-256 du fichier doit être celle
|
|
100
|
+
* attestée. Rend { ok, motif? }.
|
|
101
|
+
*/
|
|
102
|
+
export function verifierAttestation(att, clesPubliques = [], { index = null } = {}) {
|
|
103
|
+
if (!att || typeof att !== 'object' || typeof att.signature !== 'string') return { ok: false, motif: 'attestation non signée' };
|
|
104
|
+
if (att.format !== FORMAT_ATTESTATION) return { ok: false, motif: `format inattendu : ${att.format}` };
|
|
105
|
+
const k = (clesPubliques || []).find((pem) => { try { return empreinteCle(pem) === att.cle; } catch { return false; } });
|
|
106
|
+
if (!k) return { ok: false, motif: 'clé inconnue' };
|
|
107
|
+
const { cle: _c, signature, ...corps } = att;
|
|
108
|
+
let bon = false;
|
|
109
|
+
try { bon = verify(null, Buffer.from(canonique(corps)), publiqueDe(k), Buffer.from(signature, 'base64')); } catch { bon = false; }
|
|
110
|
+
if (!bon) return { ok: false, motif: 'signature invalide' };
|
|
111
|
+
if (index) {
|
|
112
|
+
let h = null; try { h = createHash('sha256').update(readFileSync(index)).digest('hex'); } catch { /* absent */ }
|
|
113
|
+
if (h !== att.index?.sha256) return { ok: false, motif: 'index différent de celui attesté' };
|
|
114
|
+
}
|
|
115
|
+
return { ok: true };
|
|
116
|
+
}
|
package/src/stockage.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// @mostajs/delegation — où vit la file : en mémoire (essais) ou dans un fichier JSON écrit de façon atomique.
|
|
2
|
+
// @author Dr Hamid MADANI <drmdh@msn.com>
|
|
3
|
+
import { readFileSync, writeFileSync, renameSync, existsSync, mkdirSync } from 'node:fs';
|
|
4
|
+
import { dirname } from 'node:path';
|
|
5
|
+
|
|
6
|
+
export const FORMAT_FILE = 'mostajs-delegation-file/1';
|
|
7
|
+
const vide = () => ({ format: FORMAT_FILE, taches: [], journal: [] });
|
|
8
|
+
|
|
9
|
+
/** Stockage en mémoire : une copie à chaque lecture, comme le fichier. */
|
|
10
|
+
export function creerStockageMemoire() {
|
|
11
|
+
let d = vide();
|
|
12
|
+
return { lire: async () => structuredClone(d), ecrire: async (x) => { d = structuredClone(x); } };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Stockage fichier : écrit dans <chemin>.tmp puis renomme — jamais de fichier à moitié écrit. */
|
|
16
|
+
export function creerStockageFichier(chemin) {
|
|
17
|
+
return {
|
|
18
|
+
async lire() {
|
|
19
|
+
if (!existsSync(chemin)) return vide();
|
|
20
|
+
const d = JSON.parse(readFileSync(chemin, 'utf8'));
|
|
21
|
+
if (d.format !== FORMAT_FILE) throw Object.assign(new Error(`${chemin} : format « ${d.format} », attendu ${FORMAT_FILE}`), { code: 'E_FORMAT' });
|
|
22
|
+
return d;
|
|
23
|
+
},
|
|
24
|
+
async ecrire(d) {
|
|
25
|
+
mkdirSync(dirname(chemin), { recursive: true });
|
|
26
|
+
writeFileSync(`${chemin}.tmp`, `${JSON.stringify(d, null, 1)}\n`);
|
|
27
|
+
renameSync(`${chemin}.tmp`, chemin);
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
}
|