Repository navigation
Expand file tree
/
Copy pathinstall.ps1
More file actions
819 lines (763 loc) · 29.5 KB
/
Copy pathinstall.ps1
File metadata and controls
819 lines (763 loc) · 29.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
[CmdletBinding()]
param()
$ErrorActionPreference = "Stop"
$ProgressPreference = "SilentlyContinue"
$Repository = if ($env:NANOCTL_REPOSITORY) { $env:NANOCTL_REPOSITORY } else { "extoci/nanoctl" }
$RequestedVersion = if ($env:NANOCTL_VERSION) { $env:NANOCTL_VERSION.Trim() } else { "latest" }
$ControlPlane = if ($env:NANOCTL_CONTROL_PLANE) {
$env:NANOCTL_CONTROL_PLANE
} else {
"https://nanoctl.vercel.app"
}
if (-not $IsWindows -and $PSVersionTable.PSEdition -eq "Core") {
throw "This installer supports Windows. On Linux or macOS, use install.sh."
}
$architecture = if ($env:PROCESSOR_ARCHITEW6432) {
$env:PROCESSOR_ARCHITEW6432
} else {
$env:PROCESSOR_ARCHITECTURE
}
$target = switch ($architecture.ToUpperInvariant()) {
"AMD64" { "windows-x64" }
"ARM64" { "windows-arm64" }
default { throw "Unsupported Windows architecture: $architecture" }
}
$resolvedVersion = if ($RequestedVersion -eq "latest") {
$release = Invoke-RestMethod `
-UseBasicParsing `
-Headers @{ Accept = "application/vnd.github+json"; "User-Agent" = "nanoctl-installer" } `
-Uri "https://api.github.com/repos/$Repository/releases/latest"
[string]$release.tag_name
} elseif ($RequestedVersion.StartsWith("v")) {
$RequestedVersion
} else {
"v$RequestedVersion"
}
if ($resolvedVersion -notmatch "^v\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$") {
throw "The release version '$resolvedVersion' is not a valid nanoctl semantic version."
}
$displayVersion = $resolvedVersion.Substring(1)
$baseUrl = "https://github.com/$Repository/releases/download/$resolvedVersion"
$asset = "nanoctl-$target.exe"
$temporary = Join-Path ([IO.Path]::GetTempPath()) ("nanoctl-" + [Guid]::NewGuid().ToString("N"))
$installRoot = Join-Path $env:LOCALAPPDATA "nanoctl"
$binaryPath = Join-Path $installRoot "nanoctl.exe"
$candidatePath = Join-Path $installRoot "nanoctl.installing.exe"
$taskName = "nanoctl Agent"
$currentIdentity = [Security.Principal.WindowsIdentity]::GetCurrent()
$currentUser = $currentIdentity.Name
$currentUserSid = $currentIdentity.User.Value
$transactionId = [Guid]::NewGuid().ToString("N")
$previousPath = Join-Path $installRoot ("nanoctl.{0}.previous.exe" -f $transactionId)
$failedPath = Join-Path $installRoot ("nanoctl.{0}.failed.exe" -f $transactionId)
$runnerPath = Join-Path $installRoot "run-agent.vbs"
$logPath = Join-Path $env:LOCALAPPDATA "nanoctl\agent.log"
$readyPath = Join-Path $installRoot "agent.ready"
$lockPath = Join-Path $installRoot "install.lock"
$legacyTaskXmlPath = Join-Path $temporary "legacy-task.xml"
$lockStream = $null
$lockAcquired = $false
$activated = $false
$completed = $false
$configPath = $null
$existingTask = $null
function Ensure-HeadlessRunner {
param([Parameter(Mandatory = $true)][string]$Path)
$runner = @'
Option Explicit
On Error Resume Next
Dim shell, fso, binaryPath, configPath, logPath, readyPath, readyToken, command, exitCode, stream
Set shell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
binaryPath = WScript.Arguments(0)
configPath = WScript.Arguments(1)
logPath = WScript.Arguments(2)
readyPath = WScript.Arguments(3)
readyToken = WScript.Arguments(4)
Set stream = fso.OpenTextFile(logPath, 8, True)
stream.WriteLine "headless runner started"
stream.Close
If fso.FileExists(readyPath) Then fso.DeleteFile readyPath, True
command = Chr(34) & binaryPath & Chr(34) & " --config " & Chr(34) & configPath & Chr(34) & _
" --log-file " & Chr(34) & logPath & Chr(34) & " --ready-file " & Chr(34) & readyPath & Chr(34) & _
" --ready-token " & Chr(34) & readyToken & Chr(34) & " run"
Err.Clear
exitCode = shell.Run(command, 0, True)
If Err.Number <> 0 Then
Set stream = fso.OpenTextFile(logPath, 8, True)
stream.WriteLine "headless runner error " & Err.Description
stream.Close
exitCode = 1
Else
Set stream = fso.OpenTextFile(logPath, 8, True)
stream.WriteLine "headless runner child exited with code " & exitCode
stream.Close
End If
WScript.Quit exitCode
'@
# Windows Script Host expects this generated VBScript to be ANSI/ASCII. Windows PowerShell
# 5.1's UTF8 encoder writes a BOM that can make wscript.exe reject the script before logging.
Set-Content -LiteralPath $Path -Value $runner -Encoding ASCII -Force
}
function New-HeadlessTaskAction {
param([Parameter(Mandatory = $true)][string]$ConfigPath)
Ensure-HeadlessRunner -Path $runnerPath
$wscript = Join-Path $env:SystemRoot "System32\wscript.exe"
$arguments = '//B //NoLogo "{0}" "{1}" "{2}" "{3}" "{4}" "{5}"' -f `
$runnerPath, $binaryPath, $ConfigPath, $logPath, $readyPath, $transactionId
New-ScheduledTaskAction -Execute $wscript -Argument $arguments -WorkingDirectory $installRoot
}
function Register-AgentTask {
param([Parameter(Mandatory = $true)][string]$ConfigPath)
if (Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue) {
Unregister-ScheduledTask -TaskName $taskName -Confirm:$false
}
$action = New-HeadlessTaskAction -ConfigPath $ConfigPath
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $currentUser
$principal = New-ScheduledTaskPrincipal `
-UserId $currentUser `
-LogonType Interactive `
-RunLevel Limited
# Task Scheduler requires RestartOnFailure intervals of at least one minute.
$settings = New-ScheduledTaskSettingsSet `
-Hidden `
-AllowStartIfOnBatteries `
-DontStopIfGoingOnBatteries `
-ExecutionTimeLimit ([TimeSpan]::Zero) `
-MultipleInstances IgnoreNew `
-RestartCount 999 `
-RestartInterval (New-TimeSpan -Minutes 1) `
-StartWhenAvailable
Register-ScheduledTask `
-TaskName $taskName `
-Action $action `
-Trigger $trigger `
-Principal $principal `
-Settings $settings `
-Description "nanoctl remote desktop agent for the current desktop user." | Out-Null
$script:taskReplaced = $true
}
function Get-AgentFailureDetails {
$task = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
$taskInfo = Get-ScheduledTaskInfo -TaskName $taskName -ErrorAction SilentlyContinue
$action = if ($task) {
(@($task.Actions) | ForEach-Object { "$($_.Execute) $($_.Arguments)" }) -join "`n"
} else {
"(task definition unavailable)"
}
$logTail = if (Test-Path -LiteralPath $logPath -PathType Leaf) {
(Get-Content -LiteralPath $logPath -Tail 40 -ErrorAction SilentlyContinue | Out-String).Trim()
} else {
"(agent log was not created at $logPath)"
}
"task state: $($task.State)`nprincipal: $($task.Principal.UserId)`naction: $action`nlast run: $($taskInfo.LastRunTime)`nlast result: $($taskInfo.LastTaskResult)`nlog: $logPath`n$logTail"
}
function Get-ReadyAgentProcess {
param(
[Parameter(Mandatory = $true)][string]$ReadyPath,
[Parameter(Mandatory = $true)][string]$BinaryPath,
[Parameter(Mandatory = $true)][string]$ReadyToken,
[Parameter(Mandatory = $true)][string]$ReadyVersion
)
if (-not (Test-Path -LiteralPath $ReadyPath -PathType Leaf)) {
return $null
}
$marker = Get-Content -LiteralPath $ReadyPath -Raw -ErrorAction SilentlyContinue
if ($marker -notmatch '(?m)^\s*pid=(\d+)\s*$') {
return $null
}
$agentProcessIdText = $Matches[1]
if ($marker -notmatch "(?m)^\s*token=$([regex]::Escape($ReadyToken))\s*$") {
return $null
}
if ($marker -notmatch "(?m)^\s*version=$([regex]::Escape($ReadyVersion))\s*$") {
return $null
}
[int]$agentProcessId = 0
if (-not [int]::TryParse($agentProcessIdText, [ref]$agentProcessId)) {
return $null
}
$process = Get-Process -Id $agentProcessId -ErrorAction SilentlyContinue
if (-not $process) {
return $null
}
try {
$processPath = [IO.Path]::GetFullPath([string]$process.Path)
$expectedPath = [IO.Path]::GetFullPath($BinaryPath)
if (-not [String]::Equals($processPath, $expectedPath, [StringComparison]::OrdinalIgnoreCase)) {
return $null
}
} catch {
# Readiness is fail-closed: without an executable path, the marker cannot prove that this
# transaction's binary is the live process.
return $null
}
return $process
}
function Wait-AgentTask {
param(
[Parameter(Mandatory = $true)][string]$ReadyPath,
[Parameter(Mandatory = $true)][string]$BinaryPath,
[Parameter(Mandatory = $true)][string]$ReadyToken,
[Parameter(Mandatory = $true)][string]$ReadyVersion
)
if (Test-Path -LiteralPath $ReadyPath -PathType Leaf) {
Remove-Item -LiteralPath $ReadyPath -Force -ErrorAction Stop
}
Start-ScheduledTask -TaskName $taskName
$deadline = [DateTime]::UtcNow.AddSeconds(90)
$readyProcess = $null
while ([DateTime]::UtcNow -lt $deadline) {
$readyProcess = Get-ReadyAgentProcess `
-ReadyPath $ReadyPath `
-BinaryPath $BinaryPath `
-ReadyToken $ReadyToken `
-ReadyVersion $ReadyVersion
if ($readyProcess) {
break
}
Start-Sleep -Milliseconds 200
}
if (-not $readyProcess) {
throw "The nanoctl agent did not become ready. $((Get-AgentFailureDetails))"
}
# Start-ScheduledTask is asynchronous. The agent's PID marker is authoritative; Task Scheduler
# can report Ready while a windowless runner owns the live child process.
Start-Sleep -Seconds 5
if (-not (Get-ReadyAgentProcess `
-ReadyPath $ReadyPath `
-BinaryPath $BinaryPath `
-ReadyToken $ReadyToken `
-ReadyVersion $ReadyVersion)) {
throw "The nanoctl agent exited during its startup stability window. $((Get-AgentFailureDetails))"
}
}
function Wait-AgentProcessExit {
param([Parameter(Mandatory = $true)][string[]]$Paths)
$normalizedPaths = @(
foreach ($path in $Paths) {
if (-not $path) { continue }
try {
[IO.Path]::GetFullPath([string]$path)
} catch {
continue
}
}
)
for ($attempt = 0; $attempt -lt 600; $attempt++) {
$running = @(Get-Process -Name nanoctl -ErrorAction SilentlyContinue | Where-Object {
if (-not $_.Path) { return $false }
try {
$processPath = [IO.Path]::GetFullPath([string]$_.Path)
} catch {
return $false
}
foreach ($expectedPath in $normalizedPaths) {
if ([String]::Equals($processPath, $expectedPath, [StringComparison]::OrdinalIgnoreCase)) {
return $true
}
}
return $false
})
if ($running.Count -eq 0) { return }
Start-Sleep -Milliseconds 100
}
throw "Timed out while waiting for the previous nanoctl process to exit."
}
function Get-TaskConfigPath {
param($Task)
foreach ($action in @($Task.Actions)) {
$arguments = [string]$action.Arguments
if ($arguments -match '(?i)run-agent\.vbs"\s+"[^"]+"\s+"([^"]+)"') {
return $Matches[1]
}
if ($arguments -match '(?i)(?:--config|-ConfigPath)\s+"([^"]+)"') {
return $Matches[1]
}
if ($arguments -match '(?i)(?:--config|-ConfigPath)\s+([^\s]+)') {
return $Matches[1]
}
}
return $null
}
function Get-TaskBinaryPath {
param($Task)
foreach ($action in @($Task.Actions)) {
$arguments = [string]$action.Arguments
if ($arguments -match '(?i)run-agent\.vbs"\s+"([^"]+)"') {
return $Matches[1]
}
if ($arguments -match '(?i)(?:-BinaryPath)\s+"([^"]+)"') {
return $Matches[1]
}
$execute = [string]$action.Execute
if ($execute -match '(?i)\\nanoctl\.exe$') {
return $execute
}
}
return $null
}
function Get-BinaryConfigPath {
param([string]$Path)
if (-not $Path -or -not (Test-Path -LiteralPath $Path -PathType Leaf)) {
return $null
}
$pathOutput = & $Path paths 2>$null
if ($LASTEXITCODE -eq 0) {
foreach ($line in @($pathOutput)) {
if ([string]$line -match "^config=(.+)$") {
return $Matches[1].Trim()
}
}
}
return $null
}
function Test-ConfigEnrolled {
param([string]$Path)
if (-not $Path -or -not (Test-Path -LiteralPath $Path -PathType Leaf)) {
return $false
}
$contents = Get-Content -LiteralPath $Path -Raw -ErrorAction SilentlyContinue
return [bool]($contents -match '(?m)^\s*device_id\s*=\s*["''][^"'']+["'']\s*$')
}
function Assert-ConfigOwner {
param([Parameter(Mandatory = $true)][string]$Path)
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
return
}
$owner = (Get-Acl -LiteralPath $Path).Owner
try {
$ownerSid = Resolve-AccountSid -Account $owner
} catch {
throw "Could not resolve the enrolled configuration owner '$owner'. Run the installer as the account that enrolled nanoctl."
}
if ($ownerSid -eq $currentUserSid) {
return
}
if ($ownerSid -eq "S-1-5-32-544" -and (Test-CurrentProcessElevated)) {
return
}
if ($ownerSid -eq "S-1-5-32-544") {
throw (
"The enrolled configuration is owned by 'BUILTIN\Administrators', but '$currentUser' " +
"is not running with an administrator token. Run the installer once from an elevated " +
"PowerShell window to repair this legacy enrollment."
)
}
if ($ownerSid -ne $currentUserSid) {
throw (
"The enrolled configuration belongs to '$owner', but this installer is running as '$currentUser'. " +
"Sign in as the account that enrolled nanoctl; do not update another Windows user's installation."
)
}
}
function Assert-ExistingTaskOwner {
param($Task)
$taskUser = [string]$Task.Principal.UserId
if (-not $taskUser -or $taskUser -match '(?i)^SYSTEM$|^NT AUTHORITY\\') {
throw "The existing nanoctl task is not a per-user interactive task. Remove the managed installation with its administrator script before using this installer."
}
$taskLogonType = [string]$Task.Principal.LogonType
if ($taskLogonType -and $taskLogonType -notmatch '(?i)^(Interactive|InteractiveToken)$') {
throw "The existing nanoctl task does not run in the interactive user session; refusing to migrate it."
}
try {
$taskSid = Resolve-AccountSid -Account $taskUser
} catch {
throw "Could not resolve the existing nanoctl task owner '$taskUser'. Run the installer as the account that owns the task."
}
if ($taskSid -ne $currentUserSid) {
throw (
"The existing nanoctl task belongs to '$taskUser', but this installer is running as '$currentUser'. " +
"Sign in as the account that owns the task before upgrading."
)
}
}
function Resolve-AccountSid {
param([Parameter(Mandatory = $true)][string]$Account)
if ($Account -match '^S-\d-') {
return ([Security.Principal.SecurityIdentifier]$Account).Value
}
return ([Security.Principal.NTAccount]$Account).Translate(
[Security.Principal.SecurityIdentifier]
).Value
}
function Test-CurrentProcessElevated {
try {
$principal = [Security.Principal.WindowsPrincipal]::new($currentIdentity)
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
} catch {
return $false
}
}
function Test-CurrentAccountAdministrator {
if (Test-CurrentProcessElevated) {
return $true
}
try {
$administratorSid = [Security.Principal.SecurityIdentifier]::new("S-1-5-32-544")
return @($currentIdentity.Groups | Where-Object {
$_.Value -eq $administratorSid.Value
}).Count -gt 0
} catch {
return $false
}
}
function Set-CurrentProcessNanoctlPath {
$processPathEntries = @($env:Path -split ";" | Where-Object {
$_ -and -not [String]::Equals($_, $installRoot, [StringComparison]::OrdinalIgnoreCase)
})
$env:Path = (@($installRoot) + $processPathEntries) -join ";"
}
function Invoke-ElevatedInstaller {
if ($env:NANOCTL_ELEVATION_ATTEMPTED -eq "1") {
throw "The installer was elevated, but Windows still did not grant an administrator token."
}
$scriptUri = "$baseUrl/install.ps1"
$escapedRepository = $Repository.Replace("'", "''")
$escapedVersion = $resolvedVersion.Replace("'", "''")
$escapedControlPlane = $ControlPlane.Replace("'", "''")
$escapedScriptUri = $scriptUri.Replace("'", "''")
$elevatedCommand = @"
`$ErrorActionPreference = 'Stop'
`$env:NANOCTL_REPOSITORY = '$escapedRepository'
`$env:NANOCTL_VERSION = '$escapedVersion'
`$env:NANOCTL_CONTROL_PLANE = '$escapedControlPlane'
`$env:NANOCTL_ELEVATION_ATTEMPTED = '1'
Invoke-Expression (Invoke-RestMethod -UseBasicParsing -Uri '$escapedScriptUri')
"@
$encodedCommand = [Convert]::ToBase64String(
[Text.Encoding]::Unicode.GetBytes($elevatedCommand)
)
$powerShell = if ($PSVersionTable.PSEdition -eq "Desktop") {
Join-Path $PSHOME "powershell.exe"
} else {
(Get-Process -Id $PID).Path
}
Write-Host "Repairing the legacy administrator-owned enrollment (Windows will ask once)."
try {
$process = Start-Process `
-FilePath $powerShell `
-Verb RunAs `
-ArgumentList @(
"-NoProfile",
"-ExecutionPolicy", "Bypass",
"-EncodedCommand", $encodedCommand
) `
-Wait `
-PassThru
} catch {
throw "Administrator approval was cancelled or Windows could not start the repair: $($_.Exception.Message)"
}
if ($process.ExitCode -ne 0) {
throw "The elevated nanoctl repair failed with exit code $($process.ExitCode)."
}
}
function Get-PreflightConfigPath {
$task = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
$taskConfigPath = if ($task) { Get-TaskConfigPath -Task $task } else { $null }
$taskBinaryPath = if ($task) { Get-TaskBinaryPath -Task $task } else { $null }
if (-not $taskConfigPath) {
$taskConfigPath = Get-BinaryConfigPath -Path $taskBinaryPath
}
if (-not $taskConfigPath) {
$taskConfigPath = Get-BinaryConfigPath -Path $binaryPath
}
if ($taskConfigPath) {
return $taskConfigPath
}
return Join-Path $env:APPDATA "nanoctl\nanoctl\config\config.toml"
}
function Test-ConfigNeedsAdministratorRepair {
param([string]$Path)
if (-not $Path) {
return $false
}
try {
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
return $false
}
$owner = (Get-Acl -LiteralPath $Path).Owner
return (Resolve-AccountSid -Account $owner) -eq "S-1-5-32-544"
} catch {
# An administrator account's filtered token can be unable to read the legacy ACL. Elevation is
# still safe here: the elevated transaction repeats all cross-user ownership checks before it
# changes the task, configuration, or install directory.
return Test-CurrentAccountAdministrator
}
}
function Ensure-ConfigUserAccess {
param([Parameter(Mandatory = $true)][string]$Path)
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
return
}
$owner = (Get-Acl -LiteralPath $Path).Owner
$ownerSid = Resolve-AccountSid -Account $owner
if ($ownerSid -ne "S-1-5-32-544") {
return
}
& icacls.exe $Path `
/grant:r "*${currentUserSid}:(F)" | Out-Null
if ($LASTEXITCODE -ne 0) {
throw (
"The enrolled configuration is owned by 'BUILTIN\Administrators' and could not be " +
"made writable by '$currentUser'. Run the installer from an elevated PowerShell window."
)
}
}
function Set-OwnerProtectedAcl {
& icacls.exe $installRoot `
/inheritance:r `
/grant:r "*${currentUserSid}:(OI)(CI)(M)" "*S-1-5-18:(OI)(CI)(F)" | Out-Null
if ($LASTEXITCODE -ne 0) {
throw "Could not protect the nanoctl installation directory."
}
& icacls.exe $logPath `
/inheritance:r `
/grant:r "*${currentUserSid}:(M)" "*S-1-5-18:(F)" | Out-Null
if ($LASTEXITCODE -ne 0) {
throw "Could not protect the nanoctl agent log."
}
}
function Restore-LegacyTask {
if (-not (Test-Path -LiteralPath $legacyTaskXmlPath -PathType Leaf)) {
return $false
}
$xml = Get-Content -LiteralPath $legacyTaskXmlPath -Raw
Register-ScheduledTask -TaskName $taskName -Xml $xml -Force | Out-Null
return $true
}
function Start-RestoredTask {
Start-ScheduledTask -TaskName $taskName
Start-Sleep -Seconds 2
$restored = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
if (-not $restored -or $restored.State -ne "Running") {
throw "The previous nanoctl task could not be restarted."
}
}
$preflightConfigPath = Get-PreflightConfigPath
if (-not (Test-CurrentProcessElevated) -and
(Test-CurrentAccountAdministrator) -and
(Test-ConfigNeedsAdministratorRepair -Path $preflightConfigPath)) {
Invoke-ElevatedInstaller
$repairedVersion = (& $binaryPath --version 2>&1 | Out-String).Trim()
if ($LASTEXITCODE -ne 0 -or
$repairedVersion -notmatch "(?m)^nanoctl\s+$([regex]::Escape($displayVersion))\s*$") {
throw "The elevated nanoctl repair completed, but the installed binary did not report version $displayVersion."
}
Set-CurrentProcessNanoctlPath
Write-Host "The legacy enrollment was repaired and nanoctl was updated."
return
}
try {
New-Item -ItemType Directory -Path $installRoot -Force | Out-Null
New-Item -ItemType File -Path $logPath -Force | Out-Null
$lockStream = [IO.File]::Open(
$lockPath,
[IO.FileMode]::OpenOrCreate,
[IO.FileAccess]::ReadWrite,
[IO.FileShare]::None
)
$lockAcquired = $true
New-Item -ItemType Directory -Path $temporary | Out-Null
$download = Join-Path $temporary "nanoctl.exe"
$checksum = Join-Path $temporary "nanoctl.exe.sha256"
Write-Host "Downloading nanoctl $displayVersion for $target..."
Invoke-WebRequest -UseBasicParsing "$baseUrl/$asset" -OutFile $download
Invoke-WebRequest -UseBasicParsing "$baseUrl/$asset.sha256" -OutFile $checksum
$expected = ((Get-Content -LiteralPath $checksum -Raw) -split "\s+")[0]
if ($expected -notmatch "^[0-9a-fA-F]{64}$") {
throw "The release checksum is invalid."
}
$actual = (Get-FileHash -LiteralPath $download -Algorithm SHA256).Hash
if ($actual -ine $expected) {
throw "The release checksum did not match."
}
$downloadVersion = (& $download --version 2>&1 | Out-String).Trim()
if ($LASTEXITCODE -ne 0) {
throw "The downloaded nanoctl executable did not start."
}
if ($downloadVersion -notmatch "(?m)^nanoctl\s+$([regex]::Escape($displayVersion))\s*$") {
throw "The downloaded nanoctl version '$downloadVersion' does not match the requested release $displayVersion."
}
$probeLogPath = Join-Path $temporary "log-probe.txt"
& $download --log-file $probeLogPath --version | Out-Null
if ($LASTEXITCODE -ne 0) {
throw "The downloaded nanoctl executable is incompatible with this installer."
}
Remove-Item -LiteralPath $probeLogPath -Force -ErrorAction SilentlyContinue
$existingTask = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
if ($existingTask) {
Assert-ExistingTaskOwner -Task $existingTask
Export-ScheduledTask -TaskName $taskName | Set-Content -LiteralPath $legacyTaskXmlPath -Encoding UTF8
}
$legacyConfigPath = if ($existingTask) { Get-TaskConfigPath -Task $existingTask } else { $null }
$legacyBinaryPath = if ($existingTask) { Get-TaskBinaryPath -Task $existingTask } else { $null }
if (-not $legacyConfigPath) {
$legacyConfigPath = Get-BinaryConfigPath -Path $legacyBinaryPath
}
if ($legacyConfigPath -and (Test-ConfigEnrolled -Path $legacyConfigPath)) {
Assert-ConfigOwner -Path $legacyConfigPath
Ensure-ConfigUserAccess -Path $legacyConfigPath
}
# Do not change an existing installation's ACL until its task/configuration ownership has
# passed the migration checks above. A rejected cross-user upgrade must be side-effect free.
Set-OwnerProtectedAcl
if ($existingTask) {
Stop-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
for ($attempt = 0; $attempt -lt 50; $attempt++) {
$state = (Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue).State
if ($state -ne "Running") { break }
Start-Sleep -Milliseconds 100
}
Wait-AgentProcessExit -Paths @($binaryPath, $legacyBinaryPath)
}
New-Item -ItemType Directory -Path $installRoot -Force | Out-Null
Copy-Item -LiteralPath $download -Destination $candidatePath -Force
if (Test-Path -LiteralPath $binaryPath -PathType Leaf) {
Move-Item -LiteralPath $binaryPath -Destination $previousPath
}
Move-Item -LiteralPath $candidatePath -Destination $binaryPath -Force
$activated = $true
$pathOutput = & $binaryPath paths
if ($LASTEXITCODE -ne 0 -or $pathOutput -notmatch "^config=(.+)$") {
throw "The installed binary returned an invalid configuration path."
}
$defaultConfigPath = $Matches[1].Trim()
$configPath = $defaultConfigPath
if ($legacyConfigPath -and (Test-Path -LiteralPath $legacyConfigPath -PathType Leaf)) {
if (Test-ConfigEnrolled -Path $legacyConfigPath) {
# Preserve an explicit v1.0.9 --config location. A new default config can exist from a
# partially failed attempt and must not silently replace the enrolled configuration.
$configPath = (Resolve-Path -LiteralPath $legacyConfigPath).Path
if ($configPath -ne $defaultConfigPath) {
Write-Host "Preserving the existing configuration at $configPath."
}
} elseif (-not (Test-ConfigEnrolled -Path $defaultConfigPath)) {
New-Item -ItemType Directory -Path (Split-Path -Parent $defaultConfigPath) -Force | Out-Null
Copy-Item -LiteralPath $legacyConfigPath -Destination $defaultConfigPath
Write-Host "Migrated the existing configuration from $legacyConfigPath."
}
}
Assert-ConfigOwner -Path $configPath
Ensure-ConfigUserAccess -Path $configPath
if (-not (Test-ConfigEnrolled -Path $configPath)) {
$setupCode = $env:NANOCTL_ENROLL_CODE
if (-not $setupCode) {
$setupCode = Read-Host "Setup code"
}
if (-not $setupCode) {
throw "The setup code cannot be empty."
}
& $binaryPath --config $configPath enroll $setupCode --control-plane $ControlPlane
if ($LASTEXITCODE -ne 0) {
throw "nanoctl enrollment failed."
}
}
Register-AgentTask -ConfigPath $configPath
Wait-AgentTask `
-ReadyPath $readyPath `
-BinaryPath $binaryPath `
-ReadyToken $transactionId `
-ReadyVersion $displayVersion
& $binaryPath --config $configPath doctor
if ($LASTEXITCODE -ne 0) {
throw "nanoctl installed but failed its health check. See $logPath for service diagnostics."
}
try {
$userPath = [Environment]::GetEnvironmentVariable("Path", "User")
$pathEntries = @($userPath -split ";" | Where-Object {
$_ -and -not [String]::Equals($_, $installRoot, [StringComparison]::OrdinalIgnoreCase)
})
$newPath = (@($installRoot) + $pathEntries) -join ";"
[Environment]::SetEnvironmentVariable("Path", $newPath, "User")
# Persistent environment changes are inherited only by new Windows processes. Always update the
# PowerShell process running the installer too, and move the install root ahead of any stale
# 1.0.9 entry that may already be present in this process's PATH.
Set-CurrentProcessNanoctlPath
} catch {
Write-Warning "nanoctl is running, but the installer could not update PATH: $($_.Exception.Message)"
}
$resolvedCommand = Get-Command nanoctl -All -ErrorAction SilentlyContinue | Select-Object -First 1
$resolvedCommandPath = if ($resolvedCommand) {
if ($resolvedCommand.Source) { [string]$resolvedCommand.Source } else { [string]$resolvedCommand.Path }
} else {
$null
}
$resolvedCommandMatchesInstall = $false
if ($resolvedCommandPath) {
try {
$resolvedCommandMatchesInstall = [String]::Equals(
[IO.Path]::GetFullPath($resolvedCommandPath),
[IO.Path]::GetFullPath($binaryPath),
[StringComparison]::OrdinalIgnoreCase
)
} catch {
$resolvedCommandMatchesInstall = $false
}
}
if (-not $resolvedCommandMatchesInstall) {
throw (
"nanoctl installed at '$binaryPath', but command resolution still points to " +
"'$resolvedCommandPath'. Close this shell and remove any older nanoctl entry from PATH."
)
}
$resolvedCommandVersion = (& $resolvedCommandPath --version 2>&1 | Out-String).Trim()
if ($LASTEXITCODE -ne 0 -or
$resolvedCommandVersion -notmatch "(?m)^nanoctl\s+$([regex]::Escape($displayVersion))\s*$") {
throw "The installed nanoctl command did not report version $displayVersion."
}
if (Test-Path -LiteralPath $previousPath -PathType Leaf) {
Remove-Item -LiteralPath $previousPath -Force -ErrorAction SilentlyContinue
}
$completed = $true
Write-Host ""
Write-Host "nanoctl is installed, enrolled, and running."
Write-Host "Installed version: $(& $binaryPath --version)"
Write-Host "Command path: $resolvedCommandPath"
Write-Host "nanoctl is available in this PowerShell session and in newly opened terminals."
Write-Host "Run this installer again at any time to update."
}
catch {
try {
if ($script:taskReplaced -and (Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue)) {
Stop-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue
}
if ($activated) {
Wait-AgentProcessExit -Paths @($binaryPath)
}
if (Test-Path -LiteralPath $previousPath -PathType Leaf) {
if (Test-Path -LiteralPath $binaryPath -PathType Leaf) {
Move-Item -LiteralPath $binaryPath -Destination $failedPath -Force -ErrorAction SilentlyContinue
}
Move-Item -LiteralPath $previousPath -Destination $binaryPath -Force
} elseif ($activated) {
Remove-Item -LiteralPath $binaryPath -Force -ErrorAction SilentlyContinue
}
Remove-Item -LiteralPath $readyPath -Force -ErrorAction SilentlyContinue
if ($existingTask) {
if (Restore-LegacyTask) {
Start-RestoredTask
} elseif (Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue) {
Start-ScheduledTask -TaskName $taskName
}
}
} catch {
Write-Warning "nanoctl rollback could not fully restore the previous task and binary: $($_.Exception.Message)"
}
throw
}
finally {
if (-not $completed -and (Test-Path -LiteralPath $candidatePath -PathType Leaf)) {
Remove-Item -LiteralPath $candidatePath -Force -ErrorAction SilentlyContinue
}
if ($lockStream) {
$lockStream.Dispose()
$lockStream = $null
}
if ($lockAcquired) {
Remove-Item -LiteralPath $lockPath -Force -ErrorAction SilentlyContinue
}
Remove-Item -LiteralPath $temporary -Recurse -Force -ErrorAction SilentlyContinue
}