@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
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
# installer-machine.ps1 — installe l'agent de délégation sur un PC Windows et l'inscrit auprès de la centrale.
|
|
2
|
+
#
|
|
3
|
+
# powershell -NoProfile -ExecutionPolicy Bypass -File installer-machine.ps1 --centrale https://delegate.exemple
|
|
4
|
+
# [--nom "PC Accueil"] [--roles poste,films] [--paquet <dossier|fichier.tgz>] [--cle-publique <fichier.pem>]
|
|
5
|
+
# [--compte <nom>] [--service utilisateur|systeme] [--conducteur] [--a-la-demande] [--sans-service]
|
|
6
|
+
# [--a-blanc|--imprimer] [--verifier]
|
|
7
|
+
# powershell -NoProfile -ExecutionPolicy Bypass -File installer-machine.ps1 --desinstaller [--purger]
|
|
8
|
+
#
|
|
9
|
+
# PowerShell 5.1 (Windows 10 et 11) et PowerShell 7. Le CODE DE DEMANDE (page « Inscrire ce poste ») est lu sur
|
|
10
|
+
# l'ENTRÉE STANDARD : saisie masquée, ou un tube. Jamais en argument : --code est refusé. Jamais en administrateur
|
|
11
|
+
# (session élevée) ; rien n'est refait au second passage :
|
|
12
|
+
# 1. détecte node (>= 20), git, chrome, ffmpeg, piper, ssh, rsync, bash (Git for Windows), cœurs, mémoire, disque ;
|
|
13
|
+
# 2. installe Node 20 dans %LOCALAPPDATA%\mostajs\node s'il manque (archive zip de nodejs.org) ;
|
|
14
|
+
# 3. installe l'agent dans %LOCALAPPDATA%\mostajs\delegation\agent ;
|
|
15
|
+
# 4. pose la clé publique des ordres (--cle-publique) et imprime son empreinte ;
|
|
16
|
+
# 5. inscrit la machine ; le dossier de données n'est lisible que par ce compte (ACL, icacls) ;
|
|
17
|
+
# 6. écrit la configuration agent.mjs UNE fois ;
|
|
18
|
+
# 7. tâche planifiée « \mostajs\delegation-agent » qui lance le VEILLEUR (il relance l'agent après une panne ; la
|
|
19
|
+
# tâche se relance toutes les 5 minutes si le veilleur ne tourne plus, sans jamais en lancer deux) :
|
|
20
|
+
# --service utilisateur (défaut) : à l'ouverture de VOTRE session, enregistrée sans droits d'administrateur ;
|
|
21
|
+
# --service systeme : AU DÉMARRAGE, sans session, sous ce compte en S4U (aucun mot de passe conservé) ; la
|
|
22
|
+
# définition est préparée et la commande imprimée pour un administrateur (le script ne s'élève jamais).
|
|
23
|
+
# --compte <nom> : imprime la création d'un compte local dédié sans privilège et la relance de ce script sous lui.
|
|
24
|
+
# --a-blanc (ou --imprimer) : dit ce qui serait fait et imprime la définition de la tâche ; rien n'est écrit.
|
|
25
|
+
# --desinstaller : arrête et retire la tâche, l'agent ; garde jeton et configuration (--purger : tout).
|
|
26
|
+
# Journaux : %LOCALAPPDATA%\mostajs\delegation\journaux\agent.log (tourné au-delà de 5 Mo).
|
|
27
|
+
# Variables (essais) : DELEGATION_NODE, DELEGATION_NODE_VERSION.
|
|
28
|
+
# Author: Dr Hamid MADANI <drmdh@msn.com>
|
|
29
|
+
$ErrorActionPreference = 'Stop'
|
|
30
|
+
Set-StrictMode -Version 2
|
|
31
|
+
try { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch { }
|
|
32
|
+
|
|
33
|
+
function Dire([string]$t) { Write-Host $t }
|
|
34
|
+
function Echouer([string]$t, [int]$code) { [Console]::Error.WriteLine("✗ $t"); exit $code }
|
|
35
|
+
|
|
36
|
+
$Centrale = ''; $Nom = ''; $Roles = ''; $Paquet = ''; $Cle = ''; $Compte = ''; $Service = 'utilisateur'
|
|
37
|
+
$Conducteur = $false; $ALaDemande = $false; $SansService = $false; $ABlanc = $false; $Verifier = $false
|
|
38
|
+
$Desinstaller = $false; $Purger = $false
|
|
39
|
+
$Reste = @()
|
|
40
|
+
$i = 0
|
|
41
|
+
while ($i -lt $args.Count) {
|
|
42
|
+
$a = [string]$args[$i]
|
|
43
|
+
$v = ''
|
|
44
|
+
if ($i + 1 -lt $args.Count) { $v = [string]$args[$i + 1] }
|
|
45
|
+
$pas = 1
|
|
46
|
+
switch -Exact ($a) {
|
|
47
|
+
'--centrale' { $Centrale = $v; $Reste += @($a, $v); $pas = 2 }
|
|
48
|
+
'--nom' { $Nom = $v; $Reste += @($a, $v); $pas = 2 }
|
|
49
|
+
'--roles' { $Roles = $v; $Reste += @($a, $v); $pas = 2 }
|
|
50
|
+
'--paquet' { $Paquet = $v; $Reste += @($a, $v); $pas = 2 }
|
|
51
|
+
'--cle-publique' { $Cle = $v; $Reste += @($a, $v); $pas = 2 }
|
|
52
|
+
'--compte' { $Compte = $v; $pas = 2 }
|
|
53
|
+
'--service' { $Service = $v; $pas = 2 }
|
|
54
|
+
'--conducteur' { $Conducteur = $true; $Reste += $a }
|
|
55
|
+
'--a-la-demande' { $ALaDemande = $true; $Reste += $a }
|
|
56
|
+
'--sans-service' { $SansService = $true; $Reste += $a }
|
|
57
|
+
'--a-blanc' { $ABlanc = $true }
|
|
58
|
+
'--imprimer' { $ABlanc = $true }
|
|
59
|
+
'--verifier' { $Verifier = $true }
|
|
60
|
+
'--desinstaller' { $Desinstaller = $true }
|
|
61
|
+
'--purger' { $Purger = $true }
|
|
62
|
+
'--help' { Get-Content -LiteralPath $PSCommandPath -TotalCount 31 | Select-Object -Skip 1 | ForEach-Object { $_ -replace '^# ?', '' }; exit 0 }
|
|
63
|
+
'-h' { Get-Content -LiteralPath $PSCommandPath -TotalCount 31 | Select-Object -Skip 1 | ForEach-Object { $_ -replace '^# ?', '' }; exit 0 }
|
|
64
|
+
'--code' { Echouer "le code de demande se lit sur l'entrée standard (saisie masquée ou tube), jamais en argument" 2 }
|
|
65
|
+
default {
|
|
66
|
+
if ($a -like '--code=*') { Echouer "le code de demande se lit sur l'entrée standard (saisie masquée ou tube), jamais en argument" 2 }
|
|
67
|
+
Echouer "option inconnue : $a (--help)" 2
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
$i += $pas
|
|
71
|
+
}
|
|
72
|
+
if (@('utilisateur', 'systeme') -notcontains $Service) { Echouer '--service : utilisateur ou systeme' 2 }
|
|
73
|
+
if (-not $Verifier -and -not $Desinstaller -and -not $Centrale) { Echouer '--centrale <adresse> est requis (--help)' 2 }
|
|
74
|
+
if ($Centrale -and ($Centrale -notmatch '^https?://[A-Za-z0-9.:_-]+(/.*)?$')) { Echouer '--centrale : une adresse http(s)' 2 }
|
|
75
|
+
|
|
76
|
+
$EstWindows = ($env:OS -eq 'Windows_NT')
|
|
77
|
+
if (-not $EstWindows -and -not $ABlanc) { Echouer 'ce script est pour Windows ; Linux : installer-machine.sh ; macOS : installer-machine-macos.sh' 2 }
|
|
78
|
+
# Jamais administrateur : une session élevée est refusée (l'agent tourne sous un compte sans privilège).
|
|
79
|
+
if ($EstWindows) {
|
|
80
|
+
$principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
|
|
81
|
+
if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
|
|
82
|
+
Echouer "jamais administrateur : relancez ce script dans une session NON élevée, sous le compte de l'agent (--compte <nom>)" 2
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
$Qui = [Environment]::UserName
|
|
87
|
+
if ($env:USERDOMAIN) { $Qui = "$($env:USERDOMAIN)\$Qui" }
|
|
88
|
+
$LocalAppData = $env:LOCALAPPDATA
|
|
89
|
+
if (-not $LocalAppData) { $LocalAppData = Join-Path $HOME 'AppData\Local' }
|
|
90
|
+
$D = Join-Path $LocalAppData 'mostajs\delegation'
|
|
91
|
+
$Journaux = Join-Path $D 'journaux'
|
|
92
|
+
$Journal = Join-Path $Journaux 'agent.log'
|
|
93
|
+
$AgentDir = Join-Path $D 'agent'
|
|
94
|
+
$Lien = Join-Path $AgentDir 'node_modules\@mostajs\delegation'
|
|
95
|
+
$AgentBin = Join-Path $Lien 'bin\delegation-agent.mjs'
|
|
96
|
+
$Config = Join-Path $D 'agent.mjs'
|
|
97
|
+
$Jeton = Join-Path $D 'jeton'
|
|
98
|
+
$ClePosee = Join-Path $D 'cle-publique.pem'
|
|
99
|
+
$TacheXml = Join-Path $D 'delegation-agent.tache.xml'
|
|
100
|
+
$NomTache = 'delegation-agent'
|
|
101
|
+
$CheminTache = '\mostajs\'
|
|
102
|
+
$NodeVersion = $env:DELEGATION_NODE_VERSION
|
|
103
|
+
if (-not $NodeVersion) { $NodeVersion = '20.18.1' }
|
|
104
|
+
$NodeRacine = Join-Path $LocalAppData 'mostajs\node'
|
|
105
|
+
|
|
106
|
+
# ── Compte dédié (R5) : on n'installe que SOUS ce compte ; sinon, on dit comment le créer et relancer ──
|
|
107
|
+
if ($Compte -and ($Compte -ne [Environment]::UserName)) {
|
|
108
|
+
if ($Compte -notmatch '^[A-Za-z][A-Za-z0-9_.-]{0,19}$') { Echouer '--compte : un nom de compte local Windows (20 caractères au plus)' 2 }
|
|
109
|
+
$copie = 'C:\Users\Public\installer-machine.ps1'
|
|
110
|
+
$suite = ($Reste | ForEach-Object { if ($_ -match '\s') { '"' + $_ + '"' } else { $_ } }) -join ' '
|
|
111
|
+
Dire "Compte dédié « $Compte » : l'agent tourne sous ce compte sans privilège, jamais sous le vôtre ni en administrateur."
|
|
112
|
+
Dire "Un administrateur le prépare une fois, dans un PowerShell « exécuté en tant qu'administrateur » (ce script ne s'élève jamais) :"
|
|
113
|
+
Dire " New-LocalUser -Name $Compte -Description 'Agent de délégation' -Password (Read-Host -AsSecureString 'Mot de passe du compte')"
|
|
114
|
+
Dire " Add-LocalGroupMember -SID S-1-5-32-545 -Member $Compte # groupe Utilisateurs (nom indépendant de la langue)"
|
|
115
|
+
Dire " Copy-Item '$PSCommandPath' '$copie'"
|
|
116
|
+
Dire "puis lance l'installation SOUS ce compte (session non élevée ; le mot de passe du compte, puis le code, seront demandés) :"
|
|
117
|
+
Dire " runas /user:$Compte `"powershell -NoProfile -ExecutionPolicy Bypass -File $copie $suite --service systeme`""
|
|
118
|
+
Dire "Cette installation imprimera la commande d'administrateur qui enregistre la tâche au démarrage."
|
|
119
|
+
Dire "Rien n'est écrit ici."
|
|
120
|
+
exit 0
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function Tache-Existante { Get-ScheduledTask -TaskName $NomTache -TaskPath $CheminTache -ErrorAction SilentlyContinue }
|
|
124
|
+
|
|
125
|
+
if ($Desinstaller) {
|
|
126
|
+
if ($ABlanc) { Dire "── À blanc : rien n'est écrit ni lancé ──"; Dire " serait fait : arrêter et retirer la tâche $CheminTache$NomTache, retirer $AgentDir"; exit 0 }
|
|
127
|
+
$t = Tache-Existante
|
|
128
|
+
if ($t) {
|
|
129
|
+
try { Stop-ScheduledTask -TaskName $NomTache -TaskPath $CheminTache } catch { }
|
|
130
|
+
try { Unregister-ScheduledTask -TaskName $NomTache -TaskPath $CheminTache -Confirm:$false; Dire '✓ tâche planifiée retirée' }
|
|
131
|
+
catch {
|
|
132
|
+
Dire 'La tâche appartient au système (--service systeme) : un administrateur la retire une fois :'
|
|
133
|
+
Dire " Unregister-ScheduledTask -TaskName '$NomTache' -TaskPath '$CheminTache' -Confirm:`$false"
|
|
134
|
+
}
|
|
135
|
+
} else { Dire '✓ aucune tâche planifiée' }
|
|
136
|
+
# Le veilleur et l'agent de ce compte, s'ils tournent encore.
|
|
137
|
+
try {
|
|
138
|
+
Get-CimInstance Win32_Process -Filter "Name = 'node.exe'" | Where-Object { $_.CommandLine -and ($_.CommandLine -like '*delegation-veilleur*' -or $_.CommandLine -like '*delegation-agent.mjs*') } |
|
|
139
|
+
ForEach-Object { try { Stop-Process -Id $_.ProcessId -Force } catch { } }
|
|
140
|
+
} catch { }
|
|
141
|
+
if (Test-Path -LiteralPath $AgentDir) { Remove-Item -LiteralPath $AgentDir -Recurse -Force }
|
|
142
|
+
if (Test-Path -LiteralPath $TacheXml) { Remove-Item -LiteralPath $TacheXml -Force }
|
|
143
|
+
if ($env:PUBLIC) {
|
|
144
|
+
$publicXml = Join-Path $env:PUBLIC "mostajs\delegation-agent-$([Environment]::UserName).tache.xml"
|
|
145
|
+
if (Test-Path -LiteralPath $publicXml) { Remove-Item -LiteralPath $publicXml -Force }
|
|
146
|
+
}
|
|
147
|
+
Dire '✓ agent retiré'
|
|
148
|
+
if ($Purger) {
|
|
149
|
+
if (Test-Path -LiteralPath $D) { Remove-Item -LiteralPath $D -Recurse -Force }
|
|
150
|
+
Dire "✓ purgé : $D (jeton, configuration, clé) — une réinstallation demandera un nouveau code"
|
|
151
|
+
} else { Dire " gardés : jeton et configuration dans $D (--purger pour tout effacer)" }
|
|
152
|
+
exit 0
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
# ── 1. Détection ──
|
|
156
|
+
function Present([string]$n) { return [bool](Get-Command $n -ErrorAction SilentlyContinue) }
|
|
157
|
+
function Etat([string]$n) { if (Present $n) { return 'présent' } else { return 'absent' } }
|
|
158
|
+
function Majeure([string]$node) { try { return [int](& $node -p "process.versions.node.split('.')[0]") } catch { return 0 } }
|
|
159
|
+
$NodeExe = $env:DELEGATION_NODE
|
|
160
|
+
if (-not $NodeExe) { $c = Get-Command node -ErrorAction SilentlyContinue; if ($c) { $NodeExe = $c.Source } }
|
|
161
|
+
$NodeOk = $false
|
|
162
|
+
if ($NodeExe -and (Test-Path -LiteralPath $NodeExe) -and ((Majeure $NodeExe) -ge 20)) { $NodeOk = $true }
|
|
163
|
+
$Chrome = 'absent'
|
|
164
|
+
foreach ($cle in @('HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe', 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe')) {
|
|
165
|
+
try { $p = (Get-ItemProperty -LiteralPath $cle -ErrorAction Stop).'(default)'; if ($p) { $Chrome = $p; break } } catch { }
|
|
166
|
+
}
|
|
167
|
+
$Bash = 'absent'
|
|
168
|
+
foreach ($b in @("$env:ProgramFiles\Git\bin\bash.exe", "$LocalAppData\Programs\Git\bin\bash.exe")) { if ($b -and (Test-Path -LiteralPath $b)) { $Bash = $b; break } }
|
|
169
|
+
$Coeurs = '?'; $Memoire = '?'; $Disque = '?'
|
|
170
|
+
try { $cs = Get-CimInstance Win32_ComputerSystem; $Coeurs = $cs.NumberOfLogicalProcessors; $Memoire = [math]::Round($cs.TotalPhysicalMemory / 1MB) } catch { }
|
|
171
|
+
try { $Disque = [math]::Round((Get-PSDrive -Name $HOME.Substring(0, 1)).Free / 1MB) } catch { }
|
|
172
|
+
|
|
173
|
+
Dire '── Détection ──'
|
|
174
|
+
if ($NodeOk) { Dire " node : v$(& $NodeExe -p 'process.versions.node') ($NodeExe)" } else { Dire " node : absent ou < 20 (Node $NodeVersion sera installé dans $NodeRacine)" }
|
|
175
|
+
Dire " git : $(Etat 'git')"
|
|
176
|
+
Dire " chrome : $Chrome"
|
|
177
|
+
Dire " ffmpeg : $(Etat 'ffmpeg')"
|
|
178
|
+
Dire " piper : $(Etat 'piper')"
|
|
179
|
+
Dire " ssh : $(Etat 'ssh')"
|
|
180
|
+
Dire " rsync : $(Etat 'rsync')"
|
|
181
|
+
Dire " bash : $Bash (les types qui passent par bash le déclarent en capacité)"
|
|
182
|
+
Dire " cœurs : $Coeurs"
|
|
183
|
+
Dire " mémoire : $Memoire Mo"
|
|
184
|
+
Dire " disque : $Disque Mo libres"
|
|
185
|
+
|
|
186
|
+
if ($Verifier) { if ($NodeOk) { exit 0 } else { Dire '✗ Node >= 20 manque'; exit 1 } }
|
|
187
|
+
|
|
188
|
+
function Definition-Tache([string]$node, [string]$bins) {
|
|
189
|
+
$sortie = & $node (Join-Path $bins 'delegation-service.mjs') 'tache-windows' --mode $Service --utilisateur $Qui --node $node `
|
|
190
|
+
--veilleur (Join-Path $bins 'delegation-veilleur.mjs') --configuration $Config --journal $Journal --donnees $D
|
|
191
|
+
if ($LASTEXITCODE -ne 0) { Echouer 'définition de la tâche refusée' 1 }
|
|
192
|
+
return (($sortie | ForEach-Object { $_.TrimEnd("`r") }) -join "`r`n") + "`r`n"
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if ($ABlanc) {
|
|
196
|
+
Dire "── À blanc : rien n'est écrit ni lancé ──"
|
|
197
|
+
$source = 'npm @mostajs/delegation'
|
|
198
|
+
if ($Paquet) { $source = "paquet $Paquet" }
|
|
199
|
+
Dire " serait fait : agent dans $AgentDir ($source)"
|
|
200
|
+
if (Test-Path -LiteralPath $Jeton) { Dire ' déjà inscrite : rien ne serait redemandé' } else { Dire " inscription auprès de $Centrale (code de demande lu sur l'entrée standard)" }
|
|
201
|
+
Dire " configuration $Config (si absente) ; ACL : $Qui et SYSTEM seuls sur $D ; journaux $Journal"
|
|
202
|
+
if ($SansService) { Dire ' tâche : aucune' }
|
|
203
|
+
elseif ($Service -eq 'systeme') { Dire " tâche : $CheminTache$NomTache au démarrage (S4U, $Qui), préparée dans $TacheXml pour un administrateur" }
|
|
204
|
+
else { Dire " tâche : $CheminTache$NomTache à l'ouverture de session de $Qui, enregistrée sans droits d'administrateur" }
|
|
205
|
+
if ($NodeOk -and (Test-Path -LiteralPath (Join-Path $PSScriptRoot 'delegation-service.mjs')) -and -not $SansService) {
|
|
206
|
+
Dire '── définition de la tâche qui serait posée ──'
|
|
207
|
+
Write-Output (Definition-Tache $NodeExe $PSScriptRoot)
|
|
208
|
+
} else { Dire " (la définition de la tâche sera générée après l'installation de l'agent)" }
|
|
209
|
+
exit 0
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
# ── 2. Node 20 ──
|
|
213
|
+
if (-not $NodeOk) {
|
|
214
|
+
$arch = 'x64'
|
|
215
|
+
if ($env:PROCESSOR_ARCHITECTURE -eq 'ARM64') { $arch = 'arm64' }
|
|
216
|
+
$cible = Join-Path $NodeRacine "node-v$NodeVersion-win-$arch"
|
|
217
|
+
$NodeExe = Join-Path $cible 'node.exe'
|
|
218
|
+
if (-not (Test-Path -LiteralPath $NodeExe)) {
|
|
219
|
+
New-Item -ItemType Directory -Force -Path $NodeRacine | Out-Null
|
|
220
|
+
$zip = Join-Path $NodeRacine "node-v$NodeVersion-win-$arch.zip"
|
|
221
|
+
Dire "→ installation de Node $NodeVersion dans $cible"
|
|
222
|
+
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
|
|
223
|
+
Invoke-WebRequest -UseBasicParsing -Uri "https://nodejs.org/dist/v$NodeVersion/node-v$NodeVersion-win-$arch.zip" -OutFile $zip
|
|
224
|
+
Expand-Archive -LiteralPath $zip -DestinationPath $NodeRacine -Force
|
|
225
|
+
Remove-Item -LiteralPath $zip -Force
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
$Npm = Join-Path (Split-Path -Parent $NodeExe) 'npm.cmd'
|
|
229
|
+
if (-not (Test-Path -LiteralPath $Npm)) { $Npm = 'npm' }
|
|
230
|
+
|
|
231
|
+
# ── 3. L'agent ; le dossier de données réservé à ce compte (ACL : l'utilisateur et SYSTEM, héritage coupé) ──
|
|
232
|
+
New-Item -ItemType Directory -Force -Path $D, $Journaux, $AgentDir | Out-Null
|
|
233
|
+
& icacls $D /inheritance:r /grant:r "${Qui}:(OI)(CI)F" "*S-1-5-18:(OI)(CI)F" | Out-Null
|
|
234
|
+
if ($LASTEXITCODE -ne 0) { Echouer "icacls n'a pas restreint $D" 1 }
|
|
235
|
+
if ($Paquet) {
|
|
236
|
+
if (-not (Test-Path -LiteralPath $Paquet)) { Echouer "--paquet : $Paquet introuvable" 1 }
|
|
237
|
+
$src = (Resolve-Path -LiteralPath $Paquet).Path
|
|
238
|
+
& $Npm install --prefix $AgentDir --no-audit --no-fund $src | Out-Null
|
|
239
|
+
if ($LASTEXITCODE -ne 0) { Echouer "npm install $src a échoué" 1 }
|
|
240
|
+
Dire "→ agent : installé depuis $src"
|
|
241
|
+
} elseif (-not (Test-Path -LiteralPath $AgentBin)) {
|
|
242
|
+
& $Npm install --prefix $AgentDir --no-audit --no-fund '@mostajs/delegation' | Out-Null
|
|
243
|
+
if ($LASTEXITCODE -ne 0) { Echouer 'npm install @mostajs/delegation a échoué' 1 }
|
|
244
|
+
Dire '→ agent : installé depuis npm'
|
|
245
|
+
} else { Dire '✓ agent déjà installé' }
|
|
246
|
+
if (-not (Test-Path -LiteralPath $AgentBin)) { Echouer "agent introuvable : $AgentBin" 1 }
|
|
247
|
+
$Bins = Join-Path $Lien 'bin'
|
|
248
|
+
|
|
249
|
+
# ── 4. La clé publique des ordres signés (R1) : copiée ici, son empreinte imprimée pour la comparer ──
|
|
250
|
+
if ($Cle) {
|
|
251
|
+
if (-not (Test-Path -LiteralPath $Cle)) { Echouer "--cle-publique : $Cle introuvable" 1 }
|
|
252
|
+
if (Select-String -LiteralPath $Cle -Pattern 'PRIVATE KEY' -SimpleMatch -Quiet) { Echouer "--cle-publique : c'est une clé PRIVÉE ; elle ne quitte jamais le poste du fondateur" 1 }
|
|
253
|
+
$emp = & $NodeExe (Join-Path $Bins 'delegation-cle.mjs') 'empreinte' $Cle
|
|
254
|
+
if ($LASTEXITCODE -ne 0) { Echouer '--cle-publique : clé illisible' 1 }
|
|
255
|
+
$neuve = $true
|
|
256
|
+
if (Test-Path -LiteralPath $ClePosee) { $neuve = ((Get-Content -Raw -LiteralPath $Cle) -ne (Get-Content -Raw -LiteralPath $ClePosee)) }
|
|
257
|
+
if ($neuve) { Copy-Item -LiteralPath $Cle -Destination $ClePosee -Force }
|
|
258
|
+
Dire "✓ clé publique des ordres : empreinte $emp — comparez-la avec celle du poste du fondateur"
|
|
259
|
+
} elseif (-not (Test-Path -LiteralPath $ClePosee)) {
|
|
260
|
+
Dire "⚠ aucune clé publique des ordres (--cle-publique) : l'agent refusera de démarrer tant qu'elle manque ($ClePosee)"
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
# ── 5. L'inscription (le code ne passe que par l'entrée standard, puis par un tube) ──
|
|
264
|
+
if (Test-Path -LiteralPath $Jeton) {
|
|
265
|
+
Dire "✓ machine déjà inscrite : rien n'est redemandé"
|
|
266
|
+
} else {
|
|
267
|
+
$Code = ''
|
|
268
|
+
if ([Console]::IsInputRedirected) { $Code = [Console]::In.ReadLine() }
|
|
269
|
+
else {
|
|
270
|
+
$sec = Read-Host -Prompt 'Code de demande (page « Inscrire ce poste »)' -AsSecureString
|
|
271
|
+
$bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($sec)
|
|
272
|
+
try { $Code = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr) } finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr) }
|
|
273
|
+
}
|
|
274
|
+
if (-not $Code) { Echouer "aucun code de demande reçu sur l'entrée standard" 1 }
|
|
275
|
+
$enr = @('--enroler', '--url', $Centrale, '--jeton-fichier', $Jeton)
|
|
276
|
+
if ($Nom) { $enr += @('--nom', $Nom) }
|
|
277
|
+
if ($Roles) { $enr += @('--roles', $Roles) }
|
|
278
|
+
$Code.Trim() | & $NodeExe $AgentBin @enr
|
|
279
|
+
$sortieEnr = $LASTEXITCODE
|
|
280
|
+
$Code = ''
|
|
281
|
+
if ($sortieEnr -ne 0) { Echouer "l'inscription a échoué" 1 }
|
|
282
|
+
& icacls $Jeton /inheritance:r /grant:r "${Qui}:F" "*S-1-5-18:F" | Out-Null
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
# ── 6. La configuration (écrite une fois, jamais écrasée) ──
|
|
286
|
+
$conf = @('configuration', '--sortie', $Config, '--centrale', $Centrale, '--jeton', $Jeton, '--cle', $ClePosee, '--roles', $Roles, '--module', (Join-Path $Lien 'src\index.js'))
|
|
287
|
+
if ($Conducteur) { $conf += '--conducteur' }
|
|
288
|
+
& $NodeExe (Join-Path $Bins 'delegation-service.mjs') @conf
|
|
289
|
+
if ($LASTEXITCODE -ne 0) { Echouer "configuration refusée" 1 }
|
|
290
|
+
|
|
291
|
+
# ── 7. La tâche planifiée (le veilleur relance l'agent ; la tâche relance le veilleur) ──
|
|
292
|
+
if ($SansService) {
|
|
293
|
+
Dire "✓ sans tâche : lancer à la main « & '$NodeExe' '$(Join-Path $Bins 'delegation-veilleur.mjs')' --journal '$Journal' --config '$Config' »"
|
|
294
|
+
Dire "✓ fini. La machine attend l'acceptation du fondateur dans la console de la centrale."
|
|
295
|
+
exit 0
|
|
296
|
+
}
|
|
297
|
+
$xml = Definition-Tache $NodeExe $Bins
|
|
298
|
+
$avant = ''
|
|
299
|
+
if (Test-Path -LiteralPath $TacheXml) { $avant = [System.IO.File]::ReadAllText($TacheXml, [System.Text.Encoding]::Unicode) }
|
|
300
|
+
$change = ($avant -ne $xml)
|
|
301
|
+
if ($change) { [System.IO.File]::WriteAllText($TacheXml, $xml, [System.Text.Encoding]::Unicode) }
|
|
302
|
+
|
|
303
|
+
if ($Service -eq 'systeme') {
|
|
304
|
+
# Le dossier de données n'est lisible que par ce compte (ACL) : la définition, qui ne contient aucun secret, est
|
|
305
|
+
# copiée dans le dossier public pour l'administrateur qui l'enregistre.
|
|
306
|
+
$public = $env:PUBLIC
|
|
307
|
+
if (-not $public) { $public = 'C:\Users\Public' }
|
|
308
|
+
$publicXml = Join-Path $public "mostajs\delegation-agent-$([Environment]::UserName).tache.xml"
|
|
309
|
+
New-Item -ItemType Directory -Force -Path (Split-Path -Parent $publicXml) | Out-Null
|
|
310
|
+
[System.IO.File]::WriteAllText($publicXml, $xml, [System.Text.Encoding]::Unicode)
|
|
311
|
+
if ($change) { Dire "→ tâche au démarrage préparée : $publicXml" } else { Dire "✓ tâche au démarrage inchangée : $publicXml" }
|
|
312
|
+
Dire "Pour l'enregistrer (un administrateur, une fois ; démarrage au boot sans session, sous $Qui en S4U, sans mot de passe conservé) :"
|
|
313
|
+
Dire " Register-ScheduledTask -TaskName '$NomTache' -TaskPath '$CheminTache' -Xml ([System.IO.File]::ReadAllText('$publicXml')) -Force"
|
|
314
|
+
Dire " Start-ScheduledTask -TaskName '$NomTache' -TaskPath '$CheminTache'"
|
|
315
|
+
} elseif ($ALaDemande) {
|
|
316
|
+
Dire "✓ à la demande : définition préparée ($TacheXml), rien n'est enregistré. Pour démarrer :"
|
|
317
|
+
Dire " & '$NodeExe' '$(Join-Path $Bins 'delegation-veilleur.mjs')' --journal '$Journal' --config '$Config'"
|
|
318
|
+
} else {
|
|
319
|
+
$t = Tache-Existante
|
|
320
|
+
if ($change -or -not $t) {
|
|
321
|
+
Register-ScheduledTask -TaskName $NomTache -TaskPath $CheminTache -Xml $xml -Force | Out-Null
|
|
322
|
+
Dire "→ tâche planifiée posée : $CheminTache$NomTache (à l'ouverture de session de $Qui)"
|
|
323
|
+
} else { Dire '✓ tâche planifiée inchangée' }
|
|
324
|
+
$t = Tache-Existante
|
|
325
|
+
if ($t -and $t.State -ne 'Running') { Start-ScheduledTask -TaskName $NomTache -TaskPath $CheminTache; Dire '✓ tâche démarrée' } else { Dire '✓ tâche déjà en marche' }
|
|
326
|
+
Dire "La tâche démarre à l'ouverture de VOTRE session. Démarrage au boot sans session ouverte :"
|
|
327
|
+
Dire ' (A) recommandée : un compte dédié et une tâche au démarrage — relancer ce script avec --compte <nom>'
|
|
328
|
+
Dire " (B) l'ouverture automatique de session de ce compte (déconseillée : le mot de passe est gardé dans le registre)"
|
|
329
|
+
}
|
|
330
|
+
Dire "✓ fini. Journaux : $Journal. La machine attend l'acceptation du fondateur dans la console de la centrale."
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# installer-machine.sh — installe l'agent de délégation sur un PC Linux et l'inscrit auprès de la centrale.
|
|
3
|
+
#
|
|
4
|
+
# bash installer-machine.sh --centrale https://delegate.exemple [--nom "PC Accueil"] [--roles poste,films]
|
|
5
|
+
# [--paquet <dossier|fichier.tgz>] [--conducteur] [--a-la-demande] [--sans-service] [--service utilisateur|systeme]
|
|
6
|
+
# [--cle-publique <fichier.pem>] [--compte <nom>] [--essai] [--verifier] [--help]
|
|
7
|
+
#
|
|
8
|
+
# Le CODE DE DEMANDE (page « Inscrire ce poste » de la centrale) est lu sur l'ENTRÉE STANDARD : saisie masquée au
|
|
9
|
+
# clavier, ou un tube. Jamais en argument (`ps` et l'historique le montreraient) : --code est refusé.
|
|
10
|
+
# Ce que fait le script, sans sudo et sans rien refaire au second passage :
|
|
11
|
+
# 1. détecte node (>= 20), git, chrome, ffmpeg, piper, ssh, rsync, cœurs, mémoire, disque ;
|
|
12
|
+
# 2. installe Node 20 dans ~/.local s'il manque (archive de nodejs.org) ;
|
|
13
|
+
# 3. installe l'agent dans ~/.delegation/agent (paquet local, archive, ou npm) ;
|
|
14
|
+
# 4. inscrit la machine (jeton durable dans ~/.delegation/jeton, 600) : elle apparaît « en attente » à la centrale ;
|
|
15
|
+
# 5. écrit ~/.delegation/agent.mjs (600) UNE fois : adresse, jeton, rôles, capacités détectées à chaque démarrage,
|
|
16
|
+
# canal « auto », aucun type (les commandes de la machine s'y ajoutent à la main) ;
|
|
17
|
+
# 6. pose le service systemd utilisateur (démarrage au boot, Restart=always) ; --service systeme prépare une unité
|
|
18
|
+
# système et imprime la commande à lancer par un administrateur (le script ne lance jamais sudo).
|
|
19
|
+
# Durcissement (0.7.0) : jamais root ; --compte <nom> imprime la création d'un compte dédié sans privilège et la commande
|
|
20
|
+
# pour relancer ce script sous ce compte (R5) ; --cle-publique pose la clé publique des ordres signés et imprime son
|
|
21
|
+
# empreinte (R1) : sans elle, l'agent refuse de démarrer ; l'empreinte du poste est imprimée à l'inscription (R3) ;
|
|
22
|
+
# chaque tâche travaille dans un dossier jetable (R5).
|
|
23
|
+
# Variables (essais, cas particuliers) : DELEGATION_NODE (node à utiliser), DELEGATION_SYSTEMCTL, DELEGATION_LOGINCTL,
|
|
24
|
+
# DELEGATION_UID (identifiant vu par le contrôle « jamais root »),
|
|
25
|
+
# DELEGATION_NODE_VERSION (Node à installer, défaut 20.18.1).
|
|
26
|
+
# @author Dr Hamid MADANI <drmdh@msn.com>
|
|
27
|
+
set -euo pipefail
|
|
28
|
+
|
|
29
|
+
usage() {
|
|
30
|
+
sed -n '2,28p' "$0" | sed 's/^# \{0,1\}//'
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
ORIG=("$@")
|
|
34
|
+
CENTRALE="" NOM="" ROLES="" PAQUET="" CLE="" COMPTE="" CONDUCTEUR=0 A_LA_DEMANDE=0 SANS_SERVICE=0 SERVICE="utilisateur" ESSAI=0 VERIFIER=0
|
|
35
|
+
while [ $# -gt 0 ]; do
|
|
36
|
+
case "$1" in
|
|
37
|
+
--centrale) CENTRALE="${2:-}"; shift 2 ;;
|
|
38
|
+
--nom) NOM="${2:-}"; shift 2 ;;
|
|
39
|
+
--roles) ROLES="${2:-}"; shift 2 ;;
|
|
40
|
+
--paquet) PAQUET="${2:-}"; shift 2 ;;
|
|
41
|
+
--cle-publique) CLE="${2:-}"; shift 2 ;;
|
|
42
|
+
--compte) COMPTE="${2:-}"; shift 2 ;;
|
|
43
|
+
--conducteur) CONDUCTEUR=1; shift ;;
|
|
44
|
+
--a-la-demande) A_LA_DEMANDE=1; shift ;;
|
|
45
|
+
--sans-service) SANS_SERVICE=1; shift ;;
|
|
46
|
+
--service) SERVICE="${2:-}"; shift 2 ;;
|
|
47
|
+
--essai) ESSAI=1; shift ;;
|
|
48
|
+
--verifier) VERIFIER=1; shift ;;
|
|
49
|
+
--help|-h) usage; exit 0 ;;
|
|
50
|
+
--code|--code=*) echo "✗ le code de demande se lit sur l'entrée standard (saisie masquée ou tube), jamais en argument" >&2; exit 2 ;;
|
|
51
|
+
*) echo "✗ option inconnue : $1 (--help)" >&2; exit 2 ;;
|
|
52
|
+
esac
|
|
53
|
+
done
|
|
54
|
+
case "$SERVICE" in utilisateur|systeme) ;; *) echo "✗ --service : utilisateur ou systeme" >&2; exit 2 ;; esac
|
|
55
|
+
if [ "$VERIFIER" = 0 ] && [ -z "$CENTRALE" ]; then echo "✗ --centrale <adresse> est requis (--help)" >&2; exit 2; fi
|
|
56
|
+
if [ -n "$CENTRALE" ] && ! [[ "$CENTRALE" =~ ^https?://[A-Za-z0-9.:_-]+(/.*)?$ ]]; then echo "✗ --centrale : une adresse http(s)" >&2; exit 2; fi
|
|
57
|
+
|
|
58
|
+
if [ "${DELEGATION_UID:-$(id -u)}" = 0 ]; then echo "✗ jamais root : l'agent tourne sous un compte sans privilège (--compte <nom>)" >&2; exit 2; fi
|
|
59
|
+
UTILISATEUR="${USER:-$(id -un)}"
|
|
60
|
+
|
|
61
|
+
# ── Compte dédié (R5) : on n'installe que SOUS ce compte ; sinon, on dit comment le créer et relancer ──
|
|
62
|
+
if [ -n "$COMPTE" ] && [ "$COMPTE" != "$UTILISATEUR" ]; then
|
|
63
|
+
[[ "$COMPTE" =~ ^[a-z_][a-z0-9_-]{0,31}$ ]] || { echo "✗ --compte : un nom de compte Linux" >&2; exit 2; }
|
|
64
|
+
RESTE=(); saute=0
|
|
65
|
+
for a in "${ORIG[@]}"; do
|
|
66
|
+
if [ "$saute" = 1 ]; then saute=0; continue; fi
|
|
67
|
+
if [ "$a" = "--compte" ]; then saute=1; continue; fi
|
|
68
|
+
RESTE+=("$(printf '%q' "$a")")
|
|
69
|
+
done
|
|
70
|
+
echo "Compte dédié « $COMPTE » : l'agent tourne sous ce compte sans privilège, jamais sous le vôtre ni root."
|
|
71
|
+
echo "Un administrateur le prépare une fois (ce script ne lance jamais sudo) :"
|
|
72
|
+
echo " sudo useradd --system --create-home --shell /usr/sbin/nologin $COMPTE"
|
|
73
|
+
echo " sudo install -o $COMPTE -m 755 $(printf '%q' "$(readlink -f "$0")") ~$COMPTE/installer-machine.sh"
|
|
74
|
+
echo "puis lance l'installation sous ce compte (le code de demande sera demandé) :"
|
|
75
|
+
echo " sudo -u $COMPTE -H bash ~$COMPTE/installer-machine.sh ${RESTE[*]}"
|
|
76
|
+
echo "Rien n'est écrit ici."
|
|
77
|
+
exit 0
|
|
78
|
+
fi
|
|
79
|
+
D="$HOME/.delegation"
|
|
80
|
+
CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}"
|
|
81
|
+
UNITE_UTIL="$CONFIG_DIR/systemd/user/delegation-agent.service"
|
|
82
|
+
UNITE_SYS="$D/delegation-agent.service"
|
|
83
|
+
SYSTEMCTL="${DELEGATION_SYSTEMCTL:-systemctl}"
|
|
84
|
+
LOGINCTL="${DELEGATION_LOGINCTL:-loginctl}"
|
|
85
|
+
NODE_VERSION="${DELEGATION_NODE_VERSION:-20.18.1}"
|
|
86
|
+
|
|
87
|
+
# ── 1. Détection ──
|
|
88
|
+
present() { command -v "$1" >/dev/null 2>&1; }
|
|
89
|
+
majeure() { "$1" -p 'process.versions.node.split(".")[0]' 2>/dev/null || echo 0; }
|
|
90
|
+
NODE="${DELEGATION_NODE:-$(command -v node || true)}"
|
|
91
|
+
NODE_OK=0
|
|
92
|
+
if [ -n "$NODE" ] && [ -x "$NODE" ] && [ "$(majeure "$NODE")" -ge 20 ]; then NODE_OK=1; fi
|
|
93
|
+
CHROME="absent"; for c in google-chrome google-chrome-stable chromium chromium-browser; do if present "$c"; then CHROME="$c"; break; fi; done
|
|
94
|
+
COEURS="$(nproc 2>/dev/null || echo '?')"
|
|
95
|
+
MEMOIRE="$(awk '/^MemTotal:/ { printf "%d", $2 / 1024 }' /proc/meminfo 2>/dev/null || echo '?')"
|
|
96
|
+
DISQUE="$(df -Pm "$HOME" 2>/dev/null | awk 'NR == 2 { print $4 }' || echo '?')"
|
|
97
|
+
etat() { if present "$1"; then echo "présent"; else echo "absent"; fi; }
|
|
98
|
+
|
|
99
|
+
echo "── Détection ──"
|
|
100
|
+
if [ "$NODE_OK" = 1 ]; then echo " node : v$("$NODE" -p process.versions.node) ($NODE)"; else echo " node : absent ou < 20 (Node $NODE_VERSION sera installé dans ~/.local)"; fi
|
|
101
|
+
echo " git : $(etat git)"
|
|
102
|
+
echo " chrome : $CHROME"
|
|
103
|
+
echo " ffmpeg : $(etat ffmpeg)"
|
|
104
|
+
echo " piper : $(etat piper)"
|
|
105
|
+
echo " ssh : $(etat ssh)"
|
|
106
|
+
echo " rsync : $(etat rsync)"
|
|
107
|
+
echo " cœurs : $COEURS"
|
|
108
|
+
echo " mémoire : ${MEMOIRE} Mo"
|
|
109
|
+
echo " disque : ${DISQUE} Mo libres dans $HOME"
|
|
110
|
+
|
|
111
|
+
if [ "$VERIFIER" = 1 ]; then
|
|
112
|
+
if [ "$NODE_OK" = 1 ]; then exit 0; else echo "✗ Node >= 20 manque"; exit 1; fi
|
|
113
|
+
fi
|
|
114
|
+
|
|
115
|
+
if [ "$ESSAI" = 1 ]; then
|
|
116
|
+
echo "── Essai : rien n'est écrit ──"
|
|
117
|
+
echo " serait fait : agent dans $D/agent ($( [ -n "$PAQUET" ] && echo "paquet $PAQUET" || echo 'npm @mostajs/delegation'))"
|
|
118
|
+
if [ -s "$D/jeton" ]; then echo " déjà inscrite : rien ne serait redemandé"; else echo " inscription auprès de $CENTRALE (code de demande lu sur l'entrée standard)"; fi
|
|
119
|
+
echo " configuration $D/agent.mjs (si absente) ; service $( [ "$SANS_SERVICE" = 1 ] && echo 'aucun' || echo "$SERVICE" )"
|
|
120
|
+
exit 0
|
|
121
|
+
fi
|
|
122
|
+
|
|
123
|
+
# ── 2. Node 20 ──
|
|
124
|
+
if [ "$NODE_OK" = 0 ]; then
|
|
125
|
+
case "$(uname -m)" in x86_64) ARCH=x64 ;; aarch64|arm64) ARCH=arm64 ;; *) echo "✗ architecture $(uname -m) non prise en charge" >&2; exit 1 ;; esac
|
|
126
|
+
CIBLE="$HOME/.local/node-v$NODE_VERSION-linux-$ARCH"
|
|
127
|
+
if [ ! -x "$CIBLE/bin/node" ]; then
|
|
128
|
+
mkdir -p "$HOME/.local"
|
|
129
|
+
echo "→ installation de Node $NODE_VERSION dans $CIBLE"
|
|
130
|
+
curl -fsSL "https://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-$ARCH.tar.xz" | tar -xJ -C "$HOME/.local"
|
|
131
|
+
fi
|
|
132
|
+
NODE="$CIBLE/bin/node"
|
|
133
|
+
fi
|
|
134
|
+
NPM="$(dirname "$NODE")/npm"; [ -x "$NPM" ] || NPM="npm"
|
|
135
|
+
|
|
136
|
+
# ── 3. L'agent ──
|
|
137
|
+
mkdir -p "$D"; chmod 700 "$D"
|
|
138
|
+
AGENT_DIR="$D/agent"
|
|
139
|
+
LIEN="$AGENT_DIR/node_modules/@mostajs/delegation"
|
|
140
|
+
if [ -n "$PAQUET" ] && [ -d "$PAQUET" ]; then
|
|
141
|
+
SOURCE="$(cd "$PAQUET" && pwd)"
|
|
142
|
+
mkdir -p "$AGENT_DIR/node_modules/@mostajs"
|
|
143
|
+
if [ "$(readlink "$LIEN" 2>/dev/null || true)" != "$SOURCE" ]; then ln -sfn "$SOURCE" "$LIEN"; echo "→ agent : lien vers le paquet local $SOURCE"; else echo "✓ agent déjà installé (paquet local)"; fi
|
|
144
|
+
elif [ -n "$PAQUET" ]; then
|
|
145
|
+
[ -f "$PAQUET" ] || { echo "✗ --paquet : $PAQUET introuvable" >&2; exit 1; }
|
|
146
|
+
mkdir -p "$AGENT_DIR"; "$NPM" install --prefix "$AGENT_DIR" --no-audit --no-fund "$(cd "$(dirname "$PAQUET")" && pwd)/$(basename "$PAQUET")" >/dev/null
|
|
147
|
+
echo "→ agent : installé depuis $PAQUET"
|
|
148
|
+
elif [ ! -e "$LIEN/bin/delegation-agent.mjs" ]; then
|
|
149
|
+
mkdir -p "$AGENT_DIR"; "$NPM" install --prefix "$AGENT_DIR" --no-audit --no-fund @mostajs/delegation >/dev/null
|
|
150
|
+
echo "→ agent : installé depuis npm"
|
|
151
|
+
else
|
|
152
|
+
echo "✓ agent déjà installé"
|
|
153
|
+
fi
|
|
154
|
+
AGENT_BIN="$LIEN/bin/delegation-agent.mjs"
|
|
155
|
+
[ -e "$AGENT_BIN" ] || { echo "✗ agent introuvable : $AGENT_BIN" >&2; exit 1; }
|
|
156
|
+
|
|
157
|
+
# ── La clé publique des ordres signés (R1) : copiée ici, son empreinte imprimée pour la comparer ──
|
|
158
|
+
if [ -n "$CLE" ]; then
|
|
159
|
+
[ -f "$CLE" ] || { echo "✗ --cle-publique : $CLE introuvable" >&2; exit 1; }
|
|
160
|
+
if command grep -q "PRIVATE KEY" "$CLE"; then echo "✗ --cle-publique : c'est une clé PRIVÉE ; elle ne quitte jamais le poste du fondateur" >&2; exit 1; fi
|
|
161
|
+
EMP="$("$NODE" "$LIEN/bin/delegation-cle.mjs" empreinte "$CLE")" || { echo "✗ --cle-publique : clé illisible" >&2; exit 1; }
|
|
162
|
+
if ! cmp -s "$CLE" "$D/cle-publique.pem" 2>/dev/null; then cp "$CLE" "$D/cle-publique.pem"; chmod 644 "$D/cle-publique.pem"; fi
|
|
163
|
+
echo "✓ clé publique des ordres : empreinte $EMP — comparez-la avec celle du poste du fondateur"
|
|
164
|
+
elif [ ! -s "$D/cle-publique.pem" ]; then
|
|
165
|
+
echo "⚠ aucune clé publique des ordres (--cle-publique) : l'agent refusera de démarrer tant qu'elle manque ($D/cle-publique.pem)"
|
|
166
|
+
fi
|
|
167
|
+
|
|
168
|
+
# ── 4. L'inscription (le code ne passe que par l'entrée standard, puis par un tube) ──
|
|
169
|
+
if [ -s "$D/jeton" ]; then
|
|
170
|
+
echo "✓ machine déjà inscrite : rien n'est redemandé"
|
|
171
|
+
else
|
|
172
|
+
CODE=""
|
|
173
|
+
if [ -t 0 ]; then read -r -s -p "Code de demande (page « Inscrire ce poste ») : " CODE; echo; else IFS= read -r CODE || true; fi
|
|
174
|
+
if [ -z "$CODE" ]; then echo "✗ aucun code de demande reçu sur l'entrée standard" >&2; exit 1; fi
|
|
175
|
+
ARGS=(--enroler --url "$CENTRALE" --jeton-fichier "$D/jeton")
|
|
176
|
+
[ -n "$NOM" ] && ARGS+=(--nom "$NOM")
|
|
177
|
+
[ -n "$ROLES" ] && ARGS+=(--roles "$ROLES")
|
|
178
|
+
printf '%s\n' "$CODE" | "$NODE" "$AGENT_BIN" "${ARGS[@]}"
|
|
179
|
+
CODE=""
|
|
180
|
+
chmod 600 "$D/jeton"
|
|
181
|
+
fi
|
|
182
|
+
|
|
183
|
+
# ── 5. La configuration (écrite une fois, jamais écrasée) ──
|
|
184
|
+
if [ -e "$D/agent.mjs" ]; then
|
|
185
|
+
echo "✓ configuration gardée : $D/agent.mjs"
|
|
186
|
+
else
|
|
187
|
+
( umask 077
|
|
188
|
+
D_CENTRALE="$CENTRALE" D_JETON="$D/jeton" D_CLE="$D/cle-publique.pem" D_ROLES="$ROLES" D_CONDUCTEUR="$CONDUCTEUR" D_MODULE="$LIEN/src/index.js" D_SORTIE="$D/agent.mjs" \
|
|
189
|
+
"$NODE" -e '
|
|
190
|
+
const e = process.env; const fs = require("node:fs");
|
|
191
|
+
const roles = (e.D_ROLES || "").split(",").map((x) => x.trim()).filter(Boolean);
|
|
192
|
+
const t = `// Agent de délégation de cette machine : écrit une fois par installer-machine.sh, jamais écrasé.
|
|
193
|
+
// Les TYPES et leurs commandes s ajoutent ici à la main : la centrale n envoie que { type, entrees }.
|
|
194
|
+
import { detecterCapacites } from ${JSON.stringify(e.D_MODULE)};
|
|
195
|
+
const capacites = detecterCapacites().capacites; // relevées à chaque démarrage
|
|
196
|
+
export default {
|
|
197
|
+
url: ${JSON.stringify(e.D_CENTRALE)},
|
|
198
|
+
jetonFichier: ${JSON.stringify(e.D_JETON)},
|
|
199
|
+
roles: ${JSON.stringify(roles)},
|
|
200
|
+
capacites: [...capacites${e.D_CONDUCTEUR === "1" ? ", \"conducteur\"" : ""}],
|
|
201
|
+
racine: "~/cidev",
|
|
202
|
+
travailJetable: true, // un dossier de travail neuf par tâche, effacé à la fin
|
|
203
|
+
clesFichiers: [${JSON.stringify(e.D_CLE)}], // les clés publiques des ordres signés : sans elles, l agent ne démarre pas
|
|
204
|
+
intervalleS: 30,
|
|
205
|
+
canal: { mode: "auto" },
|
|
206
|
+
types: [],
|
|
207
|
+
};
|
|
208
|
+
`;
|
|
209
|
+
fs.writeFileSync(e.D_SORTIE, t, { mode: 0o600, flag: "wx" });
|
|
210
|
+
' )
|
|
211
|
+
chmod 600 "$D/agent.mjs"
|
|
212
|
+
echo "→ configuration écrite : $D/agent.mjs (aucun type : ajoutez les commandes de cette machine)"
|
|
213
|
+
fi
|
|
214
|
+
|
|
215
|
+
# ── 6. Le service ──
|
|
216
|
+
unite() { # $1 : utilisateur | systeme
|
|
217
|
+
echo "[Unit]"
|
|
218
|
+
echo "Description=Agent de délégation (@mostajs/delegation)"
|
|
219
|
+
echo "After=network-online.target"
|
|
220
|
+
echo "Wants=network-online.target"
|
|
221
|
+
echo ""
|
|
222
|
+
echo "[Service]"
|
|
223
|
+
echo "Type=simple"
|
|
224
|
+
if [ "$1" = systeme ]; then echo "User=$UTILISATEUR"; echo "WorkingDirectory=$HOME"; fi
|
|
225
|
+
echo "ExecStart=\"$NODE\" \"$AGENT_BIN\" --config \"$D/agent.mjs\""
|
|
226
|
+
echo "Restart=always"
|
|
227
|
+
echo "RestartSec=5"
|
|
228
|
+
echo "RestartPreventExitStatus=2"
|
|
229
|
+
echo ""
|
|
230
|
+
echo "[Install]"
|
|
231
|
+
if [ "$1" = systeme ]; then echo "WantedBy=multi-user.target"; else echo "WantedBy=default.target"; fi
|
|
232
|
+
}
|
|
233
|
+
ecrire_si_change() { # $1 fichier ; contenu sur l'entrée standard ; rend 0 s'il a changé
|
|
234
|
+
local tmp; tmp="$(mktemp)"; cat > "$tmp"
|
|
235
|
+
if [ -f "$1" ] && cmp -s "$tmp" "$1"; then rm -f "$tmp"; return 1; fi
|
|
236
|
+
mkdir -p "$(dirname "$1")"; mv "$tmp" "$1"; chmod 644 "$1"; return 0
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
if [ "$SANS_SERVICE" = 1 ]; then
|
|
240
|
+
echo "✓ sans service : lancer à la main « $NODE $AGENT_BIN --config $D/agent.mjs »"
|
|
241
|
+
elif [ "$SERVICE" = systeme ]; then
|
|
242
|
+
if unite systeme | ecrire_si_change "$UNITE_SYS"; then echo "→ unité système préparée : $UNITE_SYS"; else echo "✓ unité système inchangée : $UNITE_SYS"; fi
|
|
243
|
+
echo "Pour l'installer (un administrateur, une fois) :"
|
|
244
|
+
echo " sudo cp $UNITE_SYS /etc/systemd/system/delegation-agent.service"
|
|
245
|
+
echo " sudo systemctl daemon-reload && sudo systemctl enable --now delegation-agent.service"
|
|
246
|
+
else
|
|
247
|
+
if unite utilisateur | ecrire_si_change "$UNITE_UTIL"; then
|
|
248
|
+
"$SYSTEMCTL" --user daemon-reload
|
|
249
|
+
echo "→ service utilisateur posé : $UNITE_UTIL"
|
|
250
|
+
else
|
|
251
|
+
echo "✓ service utilisateur inchangé"
|
|
252
|
+
fi
|
|
253
|
+
if [ "$A_LA_DEMANDE" = 1 ]; then
|
|
254
|
+
echo "✓ à la demande : service posé, non activé (systemctl --user start delegation-agent.service)"
|
|
255
|
+
else
|
|
256
|
+
"$SYSTEMCTL" --user enable --now delegation-agent.service
|
|
257
|
+
echo "✓ service activé"
|
|
258
|
+
fi
|
|
259
|
+
LINGER="$("$LOGINCTL" show-user "$UTILISATEUR" --property=Linger --value 2>/dev/null || echo no)"
|
|
260
|
+
if [ "$LINGER" != "yes" ]; then
|
|
261
|
+
echo "Démarrage au boot sans session ouverte : la persistance (linger) n'est pas active. Deux voies :"
|
|
262
|
+
echo " (A) recommandée : un administrateur lance une fois « sudo loginctl enable-linger $UTILISATEUR »"
|
|
263
|
+
echo " (B) un service système : relancer ce script avec --service systeme, puis la commande sudo qu'il imprime"
|
|
264
|
+
fi
|
|
265
|
+
fi
|
|
266
|
+
echo "✓ fini. La machine attend l'acceptation du fondateur dans la console de la centrale."
|