forked from solomon2773/nora
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.ps1
More file actions
2366 lines (2065 loc) · 97.5 KB
/
Copy pathsetup.ps1
File metadata and controls
2366 lines (2065 loc) · 97.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
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ============================================================
# Nora — One-line installer & setup (Windows PowerShell)
# ============================================================
# Usage:
# iwr -useb https://raw.githubusercontent.com/solomon2773/nora/master/setup.ps1 | iex
# — or —
# .\setup.ps1 (from inside the repo)
# .\setup.ps1 -Update
# .\setup.ps1 -CleanReinstall
#
# Clones the repo (if needed), generates secrets and database
# credentials, configures the platform, and starts Nora.
# Requires PowerShell 7+ (pwsh). Windows PowerShell 5 is not supported.
# ============================================================
param(
[switch]$Install,
[switch]$Update,
[switch]$CleanReinstall
)
$ErrorActionPreference = "Stop"
if ($PSVersionTable.PSVersion.Major -lt 7) {
Write-Host "[error] setup.ps1 requires PowerShell 7 or newer." -ForegroundColor Red
Write-Host " Current version: $($PSVersionTable.PSVersion)"
Write-Host " Install PowerShell 7, then run this script from pwsh:"
Write-Host " pwsh -ExecutionPolicy Bypass -File .\setup.ps1"
exit 1
}
$ENV_FILE = ".env"
$ENV_BACKUP_FILE = $null
$NORA_GITHUB_REPO_SLUG = "solomon2773/nora"
$PUBLIC_NGINX_TEMPLATE = "infra/nginx_public.conf.template"
$TLS_NGINX_TEMPLATE = "infra/nginx_tls.conf"
$PUBLIC_PROD_COMPOSE_OVERRIDE_TEMPLATE = "infra/docker-compose.public-prod.yml"
$TLS_COMPOSE_OVERRIDE_TEMPLATE = "infra/docker-compose.public-tls.yml"
$PUBLIC_NGINX_CONF = "nginx.public.conf"
$COMPOSE_OVERRIDE_FILE = "docker-compose.override.yml"
$SETUP_MODE = ""
$DEFAULT_HEALTHCHECK_ATTEMPTS = 221
$DEFAULT_HEALTHCHECK_INTERVAL_SECONDS = 3
$LEGACY_HEALTHCHECK_ATTEMPTS = 40
$LEGACY_HEALTHCHECK_INTERVAL_SECONDS = 3
$MAX_HEALTHCHECK_WINDOW_SECONDS = 3900
$DEFAULT_HEALTHCHECK_WINDOW_SECONDS = ($DEFAULT_HEALTHCHECK_ATTEMPTS - 1) * $DEFAULT_HEALTHCHECK_INTERVAL_SECONDS
$MIN_COMPOSE_VERSION = [version]"2.24.4"
$DEFAULT_COMPOSE_SECRETS_DIR = ".secrets/compose"
$DEFAULT_COMPOSE_PROJECT_NAME = "nora"
$COMPOSE_SECRET_NAMES = @(
"JWT_SECRET",
"ENCRYPTION_KEY",
"NORA_BACKUP_ENCRYPTION_KEY",
"NORA_AGENT_HUB_API_KEY_HASH_SECRET",
"NORA_API_KEY_HASH_SECRET",
"DB_PASSWORD"
)
$selectedModes = @($Install.IsPresent, $Update.IsPresent, $CleanReinstall.IsPresent) | Where-Object { $_ }
if ($selectedModes.Count -gt 1) {
Write-Host "[error] Choose only one setup mode." -ForegroundColor Red
exit 1
}
if ($Install) { $SETUP_MODE = "install" }
elseif ($Update) { $SETUP_MODE = "update" }
elseif ($CleanReinstall) { $SETUP_MODE = "clean-reinstall" }
# ── Color helpers ────────────────────────────────────────────
function Write-Info { param($msg) Write-Host "[info] $msg" -ForegroundColor Cyan }
function Write-Ok { param($msg) Write-Host "[ok] $msg" -ForegroundColor Green }
function Write-Warn { param($msg) Write-Host "[warn] $msg" -ForegroundColor Yellow }
function Write-Err { param($msg) Write-Host "[error] $msg" -ForegroundColor Red }
function Write-Header { param($msg) Write-Host "`n── $msg ──`n" -ForegroundColor Cyan }
function Test-BootstrapAdminEmail {
param([string]$Value)
if (-not $Value -or $Value -notmatch '^[^\s@]+@[^\s@]+$') { return $false }
if ($Value.Contains('<') -or $Value.Contains('>') -or $Value.Contains('{{')) { return $false }
return $Value -notmatch '^(?i:your_|replace[-_]with|placeholder)'
}
function Test-BootstrapAdminPasswordForbidden {
param([string]$Value)
$lowered = ([string]$Value).ToLowerInvariant()
if ($lowered -match '^(your_|example|sample|placeholder|changeme|replace-me|test-|demo-)' -or
$lowered.Contains('<') -or $lowered.Contains('{{')) {
return $true
}
$comparable = [regex]::Replace($lowered, '[^a-z0-9]', '')
foreach ($prefix in @('admin123', 'administrator', 'password', 'changeme', 'letmein', 'welcome1', 'qwerty123')) {
if ($comparable.StartsWith($prefix, [System.StringComparison]::Ordinal)) { return $true }
}
return $false
}
function Read-SecretText {
param([string]$Prompt)
$secureValue = Read-Host $Prompt -AsSecureString
$credential = [System.Net.NetworkCredential]::new('', $secureValue)
return $credential.Password
}
function ConvertTo-ComposeEnvLiteral {
param([AllowEmptyString()][string]$Value)
if ($null -eq $Value) { $Value = "" }
if ($Value.Contains("`r") -or $Value.Contains("`n")) {
throw "Compose environment values cannot contain newlines."
}
$slash = [char]92
if (
$Value.EndsWith([string]$slash, [System.StringComparison]::Ordinal) -or
$Value.Contains([string]::Concat($slash, [char]39))
) {
$escaped = $Value.Replace([string]$slash, [string]::Concat($slash, $slash))
$escaped = $escaped.Replace([string][char]34, [string]::Concat($slash, [char]34))
$escaped = $escaped.Replace('$', '$$')
return [string][char]34 + $escaped + [string][char]34
}
$escaped = $Value.Replace("'", [string]::Concat($slash, "'"))
return "'" + $escaped + "'"
}
function ConvertFrom-ComposeEnvLiteral {
param([AllowEmptyString()][string]$Value)
if ($null -eq $Value) { return "" }
$trimmed = $Value.Trim()
if ($trimmed.Length -lt 2) { return $trimmed }
$first = $trimmed.Substring(0, 1)
$last = $trimmed.Substring($trimmed.Length - 1, 1)
if ($first -eq '"' -and $last -eq '"') { $quoteMode = "double" }
elseif ($first -eq "'" -and $last -eq "'") { $quoteMode = "single" }
else { return $trimmed }
$body = $trimmed.Substring(1, $trimmed.Length - 2)
$slash = [char]92
$builder = [System.Text.StringBuilder]::new()
for ($index = 0; $index -lt $body.Length; $index += 1) {
$current = $body[$index]
if ($quoteMode -eq "single" -and $current -eq $slash -and ($index + 1) -lt $body.Length) {
$next = $body[$index + 1]
if ($next -eq [char]39) {
[void]$builder.Append($next)
$index += 1
continue
}
}
if ($quoteMode -eq "double" -and ($index + 1) -lt $body.Length) {
$next = $body[$index + 1]
if ($current -eq $slash -and ($next -eq $slash -or $next -eq [char]34)) {
[void]$builder.Append($next)
$index += 1
continue
}
if ($current -eq [char]36 -and $next -eq [char]36) {
[void]$builder.Append($current)
$index += 1
continue
}
}
[void]$builder.Append($current)
}
return $builder.ToString()
}
function Write-PublicNginxConfig {
param([string]$TemplatePath, [string]$Domain)
$content = Get-Content $TemplatePath -Raw
$content = $content.Replace('$' + '{DOMAIN}', $Domain)
$content | Out-File -FilePath $PUBLIC_NGINX_CONF -Encoding utf8NoBOM
}
function Write-ComposeOverride {
param([string]$TemplatePath)
Copy-Item $TemplatePath $COMPOSE_OVERRIDE_FILE -Force
}
function Protect-EnvFile {
param([string]$EnvPath)
if (-not (Test-Path -LiteralPath $EnvPath)) { return }
$resolvedPath = (Resolve-Path -LiteralPath $EnvPath).Path
if ($IsWindows) {
$icacls = Get-Command icacls.exe -ErrorAction SilentlyContinue
if (-not $icacls) {
throw "Cannot secure $EnvPath because icacls.exe is unavailable."
}
$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$arguments = @(
$resolvedPath,
"/inheritance:r",
"/grant:r",
"${identity}:(F)",
"*S-1-5-18:(F)",
"*S-1-5-32-544:(F)",
"/remove:g",
"*S-1-1-0",
"*S-1-5-32-545"
)
& $icacls.Source @arguments *> $null
if ($LASTEXITCODE -ne 0) {
throw "Failed to restrict the Windows ACL on $EnvPath."
}
return
}
$chmod = Get-Command chmod -ErrorAction SilentlyContinue
if (-not $chmod) { throw "Cannot secure $EnvPath because chmod is unavailable." }
& $chmod.Source 600 $resolvedPath
if ($LASTEXITCODE -ne 0) { throw "Failed to set mode 0600 on $EnvPath." }
$mode = (& stat -c '%a' $resolvedPath 2>$null)
if ($LASTEXITCODE -ne 0) { $mode = (& stat -f '%Lp' $resolvedPath 2>$null) }
if ($LASTEXITCODE -ne 0 -or "$mode".Trim() -ne "600") {
throw "Refusing to continue because $EnvPath is not mode 0600."
}
}
function Get-DockerComposeVersion {
$null = docker compose version 2>&1
if ($LASTEXITCODE -ne 0) { return $null }
$raw = [string](docker compose version --short 2>&1)
if ($LASTEXITCODE -ne 0) { return $null }
$match = [regex]::Match($raw, '\d+\.\d+\.\d+')
if (-not $match.Success) { return $null }
return [version]$match.Value
}
function Set-EnvValue {
param([string]$EnvPath, [string]$Name, [string]$Value)
$lines = if (Test-Path $EnvPath) { @(Get-Content -LiteralPath $EnvPath) } else { @() }
$pattern = '^\s*' + [regex]::Escape($Name) + '\s*='
$updated = [System.Collections.Generic.List[string]]::new()
$wrote = $false
foreach ($line in $lines) {
if ($line -match $pattern) {
if (-not $wrote) {
$updated.Add("$Name=$Value")
$wrote = $true
}
continue
}
$updated.Add($line)
}
if (-not $wrote) { $updated.Add("$Name=$Value") }
$updated | Out-File -FilePath $EnvPath -Encoding utf8NoBOM
Protect-EnvFile -EnvPath $EnvPath
}
function Get-DockerSocketGid {
if ((Test-Path "/var/run/docker.sock") -and (Get-Command stat -ErrorAction SilentlyContinue)) {
$detected = (& stat -c '%g' /var/run/docker.sock 2>$null)
if ($LASTEXITCODE -eq 0 -and "$detected" -match '^\d+$') { return "$detected" }
}
return "0"
}
function Get-NormalizedGeneratedComposeContent {
param([string]$Content)
$ignoredPatterns = @(
'NORA_KUBECONFIGS_DIR.*/kubeconfigs:ro',
'NORA_HOST_REPO_DIR.*/nora-host-repo:ro',
'^\s*NODE_PATH:\s*/app/node_modules\s*$'
)
$lines = $Content -split "`r?`n"
$kept = foreach ($line in $lines) {
$ignore = $false
foreach ($pattern in $ignoredPatterns) {
if ($line -match $pattern) {
$ignore = $true
break
}
}
if (-not $ignore) { $line }
}
return (($kept -join "`n").TrimEnd([char[]]"`r`n"))
}
function Test-ComposeOverrideMatchesGeneratedHistory {
param([string]$OverridePath, [string]$TemplatePath)
$overrideContent = Get-NormalizedGeneratedComposeContent -Content (Get-Content -LiteralPath $OverridePath -Raw)
if (Test-Path -LiteralPath $TemplatePath) {
$templateContent = Get-NormalizedGeneratedComposeContent -Content (Get-Content -LiteralPath $TemplatePath -Raw)
if ($overrideContent -ceq $templateContent) { return $true }
}
$null = git rev-parse --is-inside-work-tree 2>$null
if ($LASTEXITCODE -ne 0) { return $false }
$commits = @(git log --format=%H --all -- $TemplatePath 2>$null)
foreach ($commit in $commits) {
if (-not $commit) { continue }
$candidateLines = @(git show "${commit}:$TemplatePath" 2>$null)
if ($LASTEXITCODE -ne 0) { continue }
$candidateContent = Get-NormalizedGeneratedComposeContent -Content ($candidateLines -join "`n")
if ($overrideContent -ceq $candidateContent) { return $true }
}
return $false
}
function Backup-LegacyComposeOverride {
$timestamp = (Get-Date).ToUniversalTime().ToString("yyyyMMdd-HHmmssZ")
$candidate = "$COMPOSE_OVERRIDE_FILE.legacy-$timestamp"
$suffix = 1
while (Test-Path -LiteralPath $candidate) {
$candidate = "$COMPOSE_OVERRIDE_FILE.legacy-$timestamp.$suffix"
$suffix += 1
}
Copy-Item -LiteralPath $COMPOSE_OVERRIDE_FILE -Destination $candidate -Force
return $candidate
}
function Clear-PublicAccessArtifacts {
if (Test-Path $PUBLIC_NGINX_CONF) { Remove-Item $PUBLIC_NGINX_CONF -Force }
if (Test-Path $COMPOSE_OVERRIDE_FILE) { Remove-Item $COMPOSE_OVERRIDE_FILE -Force }
}
function Backup-ExistingEnvFile {
param([string]$EnvPath)
$resolvedEnvPath = (Resolve-Path -LiteralPath $EnvPath).Path
$envDirectory = Split-Path -Parent $resolvedEnvPath
$envName = Split-Path -Leaf $resolvedEnvPath
$timestamp = (Get-Date).ToUniversalTime().ToString("yyyyMMdd-HHmmssZ")
$candidate = Join-Path $envDirectory "$envName.backup-$timestamp"
$suffix = 1
while (Test-Path -LiteralPath $candidate) {
$candidate = Join-Path $envDirectory "$envName.backup-$timestamp.$suffix"
$suffix += 1
}
Protect-EnvFile -EnvPath $resolvedEnvPath
Copy-Item -LiteralPath $resolvedEnvPath -Destination $candidate -Force
Protect-EnvFile -EnvPath $candidate
return $candidate
}
function Update-SourceCheckout {
$null = git rev-parse --is-inside-work-tree 2>$null
if ($LASTEXITCODE -ne 0) {
return
}
$dirty = git status --porcelain
if ($dirty) {
Write-Warn "Skipping git pull because this worktree has uncommitted changes."
return
}
$branch = git symbolic-ref --quiet --short HEAD 2>$null
if ($LASTEXITCODE -ne 0 -or -not $branch) {
Write-Info "Skipping git pull because this checkout is detached."
return
}
$null = git rev-parse --abbrev-ref --symbolic-full-name "@{u}" 2>$null
if ($LASTEXITCODE -eq 0) {
Write-Info "Pulling latest code for $branch..."
git pull --ff-only
} else {
Write-Info "Skipping git pull because $branch has no upstream."
}
}
function Refresh-ReleaseTags {
$null = git rev-parse --is-inside-work-tree 2>$null
if ($LASTEXITCODE -ne 0) {
return
}
$branch = git symbolic-ref --quiet --short HEAD 2>$null | Select-Object -First 1
$remote = ""
if ($LASTEXITCODE -eq 0 -and $branch) {
$branch = $branch.Trim()
$remote = git config --get "branch.$branch.remote" 2>$null | Select-Object -First 1
if ($LASTEXITCODE -ne 0) { $remote = "" }
}
if (-not $remote) {
$remote = git remote 2>$null | Select-Object -First 1
if ($LASTEXITCODE -ne 0) { $remote = "" }
}
if ($remote) { $remote = $remote.Trim() }
if (-not $remote) {
Write-Warn "Skipping release tag refresh because this checkout has no Git remote."
return
}
Write-Info "Fetching release tags from $remote..."
git fetch --tags --prune $remote
if ($LASTEXITCODE -eq 0) {
Write-Ok "Release tags refreshed"
} else {
Write-Warn "Release tag refresh failed; Admin Settings may show stale release tracking."
}
}
function Resolve-CurrentReleaseCommit {
$null = git rev-parse --is-inside-work-tree 2>$null
if ($LASTEXITCODE -ne 0) {
return ""
}
$commit = git rev-parse HEAD 2>$null | Select-Object -First 1
if ($LASTEXITCODE -ne 0 -or -not $commit) {
return ""
}
return $commit.Trim()
}
function Resolve-CurrentReleaseVersion {
$null = git rev-parse --is-inside-work-tree 2>$null
if ($LASTEXITCODE -ne 0) {
return ""
}
$productVersionPattern = '^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$'
$tagsAtHead = @(git tag --points-at HEAD 2>$null)
if ($LASTEXITCODE -ne 0) {
return ""
}
$productTags = @(
$tagsAtHead |
ForEach-Object { $_.Trim() } |
Where-Object { $_ -match $productVersionPattern } |
Sort-Object { [version]$_.Substring(1) }
)
if ($productTags.Count -gt 0) {
return $productTags[-1]
}
return ""
}
function Update-ReleaseTrackingEnv {
param([string]$EnvPath)
if (-not (Test-Path $EnvPath)) {
return
}
$currentCommit = Resolve-CurrentReleaseCommit
if (-not $currentCommit) {
Write-Warn "Skipping release tracking stamp because the current Git commit could not be resolved."
return
}
$currentVersion = Resolve-CurrentReleaseVersion
$lines = Get-Content -LiteralPath $EnvPath
$updatedLines = New-Object System.Collections.Generic.List[string]
$sawVersion = $false
$sawCommit = $false
$sawRepo = $false
foreach ($line in $lines) {
if ($line -match '^NORA_CURRENT_VERSION=') {
$updatedLines.Add("NORA_CURRENT_VERSION=$currentVersion")
$sawVersion = $true
} elseif ($line -match '^NORA_CURRENT_COMMIT=') {
$updatedLines.Add("NORA_CURRENT_COMMIT=$currentCommit")
$sawCommit = $true
} elseif ($line -match '^NORA_GITHUB_REPO=') {
$updatedLines.Add("NORA_GITHUB_REPO=$NORA_GITHUB_REPO_SLUG")
$sawRepo = $true
} else {
$updatedLines.Add($line)
}
}
if (-not $sawVersion) { $updatedLines.Add("NORA_CURRENT_VERSION=$currentVersion") }
if (-not $sawCommit) { $updatedLines.Add("NORA_CURRENT_COMMIT=$currentCommit") }
if (-not $sawRepo) { $updatedLines.Add("NORA_GITHUB_REPO=$NORA_GITHUB_REPO_SLUG") }
$updatedLines | Out-File -FilePath $EnvPath -Encoding utf8NoBOM
Protect-EnvFile -EnvPath $EnvPath
$label = if ($currentVersion) { $currentVersion } else { "source checkout" }
Write-Ok "Release tracking stamped: $label @ $($currentCommit.Substring(0, [Math]::Min(12, $currentCommit.Length)))"
}
function Get-EnvAssignmentValue {
param([string]$Line)
$value = ($Line -replace '^[^=]*=', '').Trim()
$quoted =
($value.Length -ge 2) -and
(($value.StartsWith('"') -and $value.EndsWith('"')) -or ($value.StartsWith("'") -and $value.EndsWith("'")))
if (-not $quoted) {
$value = ($value -replace '\s+#.*$', '').Trim()
}
return ConvertFrom-ComposeEnvLiteral -Value $value
}
function Test-AgentHubHashSecretPresent {
param([string[]]$Lines)
foreach ($line in $Lines) {
if ($line -match '^\s*NORA_AGENT_HUB_API_KEY_HASH_SECRET\s*=') {
if (Get-EnvAssignmentValue -Line $line) {
return $true
}
}
}
return $false
}
function Test-BackupEncryptionKeyPresent {
param([string[]]$Lines)
foreach ($line in $Lines) {
if ($line -match '^\s*NORA_BACKUP_ENCRYPTION_KEY\s*=') {
if (Get-EnvAssignmentValue -Line $line) {
return $true
}
}
}
return $false
}
function Ensure-AgentHubHashSecretEnv {
param([string]$EnvPath)
if (-not (Test-Path $EnvPath)) {
return
}
Protect-EnvFile -EnvPath $EnvPath
$lines = Get-Content -LiteralPath $EnvPath
if (Test-AgentHubHashSecretPresent -Lines $lines) {
Write-Info "NORA_AGENT_HUB_API_KEY_HASH_SECRET already set; preserving existing value."
return
}
$secret = New-HexSecret
$updatedLines = New-Object System.Collections.Generic.List[string]
$wroteSecret = $false
foreach ($line in $lines) {
if ($line -match '^\s*NORA_AGENT_HUB_API_KEY_HASH_SECRET\s*=') {
if (-not $wroteSecret) {
$updatedLines.Add("NORA_AGENT_HUB_API_KEY_HASH_SECRET=$secret")
$wroteSecret = $true
}
continue
}
$updatedLines.Add($line)
}
if (-not $wroteSecret) {
if ($updatedLines.Count -gt 0) {
$updatedLines.Add("")
}
$updatedLines.Add("NORA_AGENT_HUB_API_KEY_HASH_SECRET=$secret")
}
$updatedLines | Out-File -FilePath $EnvPath -Encoding utf8NoBOM
Protect-EnvFile -EnvPath $EnvPath
Write-Ok "NORA_AGENT_HUB_API_KEY_HASH_SECRET generated (64-char hex)"
}
function Ensure-ApiKeyHashSecretEnv {
param([string]$EnvPath)
if (-not (Test-Path $EnvPath)) { return }
Protect-EnvFile -EnvPath $EnvPath
$existing = Read-EnvValue -EnvPath $EnvPath -Name "NORA_API_KEY_HASH_SECRET" -Default ""
if ($existing) {
Write-Info "NORA_API_KEY_HASH_SECRET already set; preserving existing value."
return
}
# Match lib/apiTokens.ts's legacy fallback order so introducing the primary
# name does not invalidate hashes produced by an existing installation.
$fallback = Read-EnvValue -EnvPath $EnvPath -Name "NORA_AGENT_HUB_API_KEY_HASH_SECRET" -Default ""
if (-not $fallback) { $fallback = Read-EnvValue -EnvPath $EnvPath -Name "ENCRYPTION_KEY" -Default "" }
if (-not $fallback) { $fallback = Read-EnvValue -EnvPath $EnvPath -Name "JWT_SECRET" -Default "" }
if (-not $fallback) { $fallback = New-HexSecret }
Set-EnvValue -EnvPath $EnvPath -Name "NORA_API_KEY_HASH_SECRET" -Value $fallback
Write-Ok "NORA_API_KEY_HASH_SECRET populated from the existing token-hash fallback"
}
function Ensure-BackupEncryptionKeyEnv {
param([string]$EnvPath)
if (-not (Test-Path $EnvPath)) {
return
}
Protect-EnvFile -EnvPath $EnvPath
$lines = Get-Content -LiteralPath $EnvPath
if (Test-BackupEncryptionKeyPresent -Lines $lines) {
Write-Info "NORA_BACKUP_ENCRYPTION_KEY already set; preserving existing value."
return
}
$secret = New-HexSecret
$updatedLines = New-Object System.Collections.Generic.List[string]
$wroteSecret = $false
foreach ($line in $lines) {
if ($line -match '^\s*NORA_BACKUP_ENCRYPTION_KEY\s*=') {
if (-not $wroteSecret) {
$updatedLines.Add("NORA_BACKUP_ENCRYPTION_KEY=$secret")
$wroteSecret = $true
}
continue
}
if ($line -match '^\s*ENCRYPTION_KEY\s*=') {
$updatedLines.Add($line)
if (-not $wroteSecret) {
$updatedLines.Add("NORA_BACKUP_ENCRYPTION_KEY=$secret")
$wroteSecret = $true
}
continue
}
$updatedLines.Add($line)
}
if (-not $wroteSecret) {
if ($updatedLines.Count -gt 0) {
$updatedLines.Add("")
}
$updatedLines.Add("NORA_BACKUP_ENCRYPTION_KEY=$secret")
}
$updatedLines | Out-File -FilePath $EnvPath -Encoding utf8NoBOM
Protect-EnvFile -EnvPath $EnvPath
Write-Ok "NORA_BACKUP_ENCRYPTION_KEY generated (64-char hex)"
}
function Protect-ComposeSecretsDirectory {
param([string]$SecretsDirectory)
if (-not $SecretsDirectory -or $SecretsDirectory -in @("/", ".", "..", "./", "../")) {
throw "NORA_COMPOSE_SECRETS_DIR must point to a dedicated non-root directory."
}
$candidatePath = if ([System.IO.Path]::IsPathRooted($SecretsDirectory)) {
[System.IO.Path]::GetFullPath($SecretsDirectory)
} else {
[System.IO.Path]::GetFullPath((Join-Path (Get-Location) $SecretsDirectory))
}
$currentPath = [System.IO.Path]::GetFullPath((Get-Location).Path)
$rootPath = [System.IO.Path]::GetPathRoot($candidatePath)
if ($candidatePath -eq $currentPath -or $candidatePath -eq $rootPath) {
throw "NORA_COMPOSE_SECRETS_DIR must not be the filesystem or repository root: $candidatePath"
}
$segments = $SecretsDirectory -split '[\\/]'
if ($segments | Where-Object { $_ -in @(".", "..") }) {
throw "NORA_COMPOSE_SECRETS_DIR must not contain '.' or '..' path segments."
}
$pathProbe = $candidatePath
while ($pathProbe) {
if (Test-Path -LiteralPath $pathProbe) {
$probeItem = Get-Item -LiteralPath $pathProbe -Force
if (($probeItem.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) {
throw "Refusing NORA_COMPOSE_SECRETS_DIR with symlinked path component: $pathProbe"
}
}
$parent = [System.IO.Directory]::GetParent($pathProbe)
if (-not $parent) { break }
$pathProbe = $parent.FullName
}
if (Test-Path -LiteralPath $candidatePath) {
$existingItem = Get-Item -LiteralPath $candidatePath -Force
if (-not $existingItem.PSIsContainer) {
throw "NORA_COMPOSE_SECRETS_DIR is not a directory: $candidatePath"
}
$unexpectedEntry = Get-ChildItem -LiteralPath $candidatePath -Force | Where-Object {
$_.Name -notin $COMPOSE_SECRET_NAMES
} | Select-Object -First 1
if ($unexpectedEntry) {
throw "Refusing non-dedicated NORA_COMPOSE_SECRETS_DIR; unexpected entry: $($unexpectedEntry.FullName)"
}
}
New-Item -ItemType Directory -Path $candidatePath -Force | Out-Null
$resolvedPath = (Resolve-Path -LiteralPath $candidatePath).Path
if ($IsWindows) {
$icacls = Get-Command icacls.exe -ErrorAction SilentlyContinue
if (-not $icacls) {
throw "Cannot secure $SecretsDirectory because icacls.exe is unavailable."
}
$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$arguments = @(
$resolvedPath,
"/inheritance:r",
"/grant:r",
"${identity}:(OI)(CI)(F)",
"*S-1-5-18:(OI)(CI)(F)",
"*S-1-5-32-544:(OI)(CI)(F)",
"/remove:g",
"*S-1-1-0",
"*S-1-5-32-545"
)
& $icacls.Source @arguments *> $null
if ($LASTEXITCODE -ne 0) {
throw "Failed to restrict the Windows ACL on $SecretsDirectory."
}
return
}
$chmod = Get-Command chmod -ErrorAction SilentlyContinue
if (-not $chmod) { throw "Cannot secure $SecretsDirectory because chmod is unavailable." }
& $chmod.Source 700 $resolvedPath
if ($LASTEXITCODE -ne 0) { throw "Failed to set mode 0700 on $SecretsDirectory." }
$mode = (& stat -c '%a' $resolvedPath 2>$null)
if ($LASTEXITCODE -ne 0) { $mode = (& stat -f '%Lp' $resolvedPath 2>$null) }
if ($LASTEXITCODE -ne 0 -or "$mode".Trim() -ne "700") {
throw "Refusing to continue because $SecretsDirectory is not mode 0700."
}
}
function Write-ComposeSecretFiles {
param([string]$EnvPath)
$secretsDirectory = Read-EnvValue -EnvPath $EnvPath -Name "NORA_COMPOSE_SECRETS_DIR" -Default $DEFAULT_COMPOSE_SECRETS_DIR
Protect-ComposeSecretsDirectory -SecretsDirectory $secretsDirectory
foreach ($secretName in $COMPOSE_SECRET_NAMES) {
$value = Read-EnvValue -EnvPath $EnvPath -Name $secretName -Default ""
if (-not $value) {
throw "Cannot materialize Compose secrets because $secretName is empty in $EnvPath."
}
$target = Join-Path $secretsDirectory $secretName
$temporary = Join-Path $secretsDirectory (".$secretName." + [guid]::NewGuid().ToString("N"))
try {
[System.IO.File]::WriteAllText($temporary, "$value`n", [System.Text.UTF8Encoding]::new($false))
if (-not $IsWindows) {
& chmod 444 $temporary
if ($LASTEXITCODE -ne 0) { throw "Failed to set mode 0444 on $temporary." }
}
Move-Item -LiteralPath $temporary -Destination $target -Force
if ($IsWindows) {
Protect-EnvFile -EnvPath $target
} else {
$mode = (& stat -c '%a' $target 2>$null)
if ($LASTEXITCODE -ne 0) { $mode = (& stat -f '%Lp' $target 2>$null) }
if ($LASTEXITCODE -ne 0 -or "$mode".Trim() -ne "444") {
throw "Refusing to continue because $target is not mode 0444."
}
}
} finally {
Remove-Item -LiteralPath $temporary -Force -ErrorAction SilentlyContinue
}
}
Set-EnvValue -EnvPath $EnvPath -Name "NORA_COMPOSE_SECRETS_DIR" -Value $secretsDirectory
Write-Ok "Compose secret files refreshed under $secretsDirectory (owner-only directory)"
}
function Get-ComposeProjectName {
param([string]$EnvPath = $ENV_FILE)
$projectName = Read-EnvValue -EnvPath $EnvPath -Name "COMPOSE_PROJECT_NAME" -Default $DEFAULT_COMPOSE_PROJECT_NAME
if ($projectName -notmatch '^[a-z0-9][a-z0-9_-]*$') {
throw "Invalid COMPOSE_PROJECT_NAME '$projectName'; use lowercase letters, digits, hyphens, or underscores."
}
return $projectName
}
function Remove-LocalAgentContainers {
param([string]$ProjectName)
$composeNetwork = "${ProjectName}_default"
$containerIds = @()
foreach ($label in @("openclaw.agent.id", "nora.agent.id")) {
$ids = docker ps -a --filter "label=$label" --filter "network=$composeNetwork" -q 2>$null
if ($ids) { $containerIds += $ids }
}
$containerIds = $containerIds | Where-Object { $_ } | Sort-Object -Unique
if (-not $containerIds) {
Write-Info "No local Nora agent containers found on $composeNetwork."
return
}
Write-Info "Removing local Nora agent containers attached to $composeNetwork..."
foreach ($containerId in $containerIds) {
docker rm -f $containerId 2>$null | Out-Null
}
Write-Ok "Removed local Nora agent containers"
}
function Invoke-CleanReinstallState {
$projectName = Get-ComposeProjectName -EnvPath $ENV_FILE
Write-Warn "Clean reinstall selected: local compose containers and volumes will be removed."
Write-Info "External Kubernetes, Proxmox, NemoClaw, and other VM resources will not be touched."
Remove-LocalAgentContainers -ProjectName $projectName
docker compose -p $projectName down -v --remove-orphans 2>$null
Write-Ok "Local Nora compose state cleaned for project $projectName"
}
function Start-NoraComposeStack {
Write-Host ""
Write-Info "Starting Nora (docker compose up -d --build)..."
Write-Info "Preserving Docker volumes and provisioned agent instances."
Write-Host ""
Write-Info "Pre-validating nginx configuration..."
docker compose run --rm --no-deps --interactive=false -T nginx nginx -t
if ($LASTEXITCODE -ne 0) { Write-Err "nginx configuration validation failed"; exit 1 }
docker compose up -d --build
if ($LASTEXITCODE -ne 0) { Write-Err "docker compose failed to start Nora"; exit 1 }
Write-Info "Recreating nginx so generated configuration mounts are refreshed..."
docker compose up -d --force-recreate --no-deps nginx
if ($LASTEXITCODE -ne 0) { Write-Err "nginx recreation failed"; exit 1 }
docker compose exec -T nginx nginx -t
if ($LASTEXITCODE -ne 0) { Write-Err "active nginx configuration validation failed"; exit 1 }
Write-Ok "Nginx configuration activated"
Test-NoraRuntimePermissions
Write-Host ""
Write-Ok "Nora is running!"
}
function Invoke-ComposeNodeProbe {
param([string]$Service, [string]$Description, [string]$Script, [object]$Budget)
Write-Info "Waiting for $Service probe: $($Budget.Attempts) attempts every $($Budget.IntervalSeconds)s ($($Budget.FirstToFinalWindowSeconds)s from first to final attempt)."
for ($attempt = 1; $attempt -le $Budget.Attempts; $attempt += 1) {
docker compose exec -T $Service node -e $Script *> $null
if ($LASTEXITCODE -eq 0) {
Write-Ok $Description
return
}
if ($attempt -lt $Budget.Attempts) {
Start-Sleep -Seconds $Budget.IntervalSeconds
}
}
docker compose exec -T $Service node -e $Script
Write-Err "$Description failed after $($Budget.Attempts) attempts every $($Budget.IntervalSeconds)s ($($Budget.FirstToFinalWindowSeconds)s first-to-final window). Inspect: docker compose logs --tail=100 $Service"
exit 1
}
function Test-NoraRuntimePermissions {
Write-Info "Verifying runtime permissions and upgrade mounts..."
$budget = Get-NoraHealthcheckBudget
$dockerProbe = 'const http=require("http");const request=http.request({socketPath:"/var/run/docker.sock",path:"/_ping",method:"GET"},response=>{let body="";response.setEncoding("utf8");response.on("data",chunk=>body+=chunk);response.on("end",()=>process.exit(response.statusCode===200&&body.trim()==="OK"?0:1));});request.setTimeout(5000,()=>request.destroy(new Error("Docker socket timeout")));request.on("error",error=>{console.error(error.message);process.exit(1);});request.end();'
$backendVolumeProbe = 'const fs=require("fs");fs.accessSync("/nora-host-repo/infra/run-release-upgrade.sh",fs.constants.R_OK);const path=`/var/lib/nora-upgrade/.nora-write-probe-${process.pid}`;try{fs.writeFileSync(path,"ok",{mode:0o600});fs.unlinkSync(path);}finally{try{fs.unlinkSync(path);}catch{}}'
$backupVolumeProbe = 'const fs=require("fs");const path=`/var/lib/nora-backups/.nora-write-probe-${process.pid}`;try{fs.writeFileSync(path,"ok",{mode:0o600});fs.unlinkSync(path);}finally{try{fs.unlinkSync(path);}catch{}}'
Invoke-ComposeNodeProbe -Service "worker-provisioner" -Description "Provisioner Docker socket access verified" -Script $dockerProbe -Budget $budget
Invoke-ComposeNodeProbe -Service "backend-api" -Description "Upgrade checkout and state volume verified" -Script $backendVolumeProbe -Budget $budget
Invoke-ComposeNodeProbe -Service "worker-backup" -Description "Backup volume write access verified" -Script $backupVolumeProbe -Budget $budget
}
# ── Helper: generate random hex ─────────────────────────────
function New-HexSecret {
param([Alias("Bytes")][int]$ByteCount = 32)
$secretBytes = [byte[]]::new($ByteCount)
$rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
try {
$rng.GetBytes($secretBytes)
} finally {
$rng.Dispose()
}
return ($secretBytes | ForEach-Object { $_.ToString("x2") }) -join ''
}
# ── Helper: refresh PATH from registry ─────────────────────
function Refresh-Path {
$env:Path = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" +
[System.Environment]::GetEnvironmentVariable("Path", "User")
}
# ── Helper: check if running as admin ──────────────────────
function Test-Admin {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = [Security.Principal.WindowsPrincipal]$identity
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
# ── Auto-install functions ─────────────────────────────────
function Install-WithWinget {
param([string]$PackageId, [string]$Name)
if (Get-Command winget -ErrorAction SilentlyContinue) {
Write-Info "Installing $Name via winget..."
winget install $PackageId --accept-package-agreements --accept-source-agreements --silent
Refresh-Path
return $true
}
return $false
}
function Install-WithChoco {
param([string]$PackageName, [string]$Name)
if (Get-Command choco -ErrorAction SilentlyContinue) {
Write-Info "Installing $Name via Chocolatey..."
choco install $PackageName -y
Refresh-Path
return $true
}
return $false
}
function Install-GitIfMissing {
if (Get-Command git -ErrorAction SilentlyContinue) { return }
Write-Info "Git not found — installing..."
if (Install-WithWinget "Git.Git" "Git") {
# winget install succeeded
} elseif (Install-WithChoco "git" "Git") {
# choco install succeeded
} else {
Write-Err "Cannot auto-install Git. No package manager found (winget or choco)."
Write-Host " Install manually: https://git-scm.com/download/win"
exit 1
}
# Verify
Refresh-Path
if (-not (Get-Command git -ErrorAction SilentlyContinue)) {
Write-Err "Git was installed but is not in PATH. Restart your terminal and re-run."
exit 1
}
Write-Ok "Git installed: $(git --version)"
}
function Install-DockerIfMissing {
if (Get-Command docker -ErrorAction SilentlyContinue) { return }
Write-Info "Docker not found — installing Docker Desktop..."
if (-not (Test-Admin)) {
Write-Err "Docker Desktop install requires administrator privileges."
Write-Host " Re-run this script as Administrator (right-click PowerShell > Run as Administrator)"
exit 1
}
if (Install-WithWinget "Docker.DockerDesktop" "Docker Desktop") {
# winget install succeeded
} elseif (Install-WithChoco "docker-desktop" "Docker Desktop") {
# choco install succeeded
} else {
Write-Err "Cannot auto-install Docker. No package manager found (winget or choco)."
Write-Host " Install manually: https://docs.docker.com/desktop/install/windows-install/"
exit 1
}
Refresh-Path
# Start Docker Desktop
$dockerExe = "C:\Program Files\Docker\Docker\Docker Desktop.exe"
if (Test-Path $dockerExe) {
Write-Info "Starting Docker Desktop..."
Start-Process $dockerExe
}
}
function Wait-ForDocker {
$max = 60
$waited = 0
Write-Info "Waiting for Docker daemon..."
while ($waited -lt $max) {
try {
$null = docker info 2>&1
return
} catch {}
Start-Sleep -Seconds 2
$waited += 2
Write-Host "." -NoNewline
}
Write-Host ""
Write-Err "Docker daemon didn't start within ${max}s."
Write-Host " Start Docker Desktop manually and re-run this script."
exit 1
}
function Read-EnvValue {
param([string]$EnvPath, [string]$Name, [string]$Default = "")
if (-not (Test-Path -LiteralPath $EnvPath)) {
return $Default
}
$pattern = '^\s*' + [regex]::Escape($Name) + '\s*=(.*)$'
foreach ($line in Get-Content -LiteralPath $EnvPath) {
if ($line -match $pattern) {
$value = $matches[1].Trim()
return ConvertFrom-ComposeEnvLiteral -Value $value
}
}
return $Default
}
function Read-EnvValueWithAlias {
param([string]$EnvPath, [string]$Name, [string]$AliasName, [string]$Default = "")