-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.ps1
More file actions
1188 lines (1111 loc) · 61 KB
/
Copy pathinstall.ps1
File metadata and controls
1188 lines (1111 loc) · 61 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
# Java Version Manager
# Copyright (C) 2026 DiamTek / Alexéy Shishkin
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
[CmdletBinding()]
param(
[switch]$Quiet,
[switch]$Update,
[string]$TargetDir,
[string]$Branch,
[string]$Channel = "Stable",
[switch]$SkipIntegrity
)
if (-not $PSBoundParameters.ContainsKey('Channel') -and $env:JVM_CHANNEL) {
$Channel = $env:JVM_CHANNEL
}
if (-not $PSBoundParameters.ContainsKey('Branch') -and $env:JVM_BRANCH) {
$Branch = $env:JVM_BRANCH
}
if ($Branch) {
if ($Branch -notmatch '^[a-zA-Z0-9_.\-]+(/[a-zA-Z0-9_.\-]+)*$' -or $Branch -match '\.\.') {
Write-Host "[ ERROR ] Invalid branch or tag name: '$Branch'" -ForegroundColor Red
exit 1
}
}
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
if ($ExecutionContext.SessionState.LanguageMode -ne 'FullLanguage') {
Write-Host "[ ERROR ] PowerShell is operating in $($ExecutionContext.SessionState.LanguageMode) mode." -ForegroundColor Red
Write-Host " FullLanguage mode is required by DiamTek Java Version Manager installer" -ForegroundColor Yellow
Write-Host " to safely manage system environment variables, configure NTFS DACLs, and verify cryptography." -ForegroundColor Yellow
exit 1
}
$isFullLanguage = $true
if ($isFullLanguage) {
try {
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor 3072 -bor 12288
} catch { Write-Verbose "TLS protocol configuration skipped: $($_.Exception.Message)" }
try {
if ([System.Net.WebRequest]::DefaultWebProxy) {
[System.Net.WebRequest]::DefaultWebProxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
}
} catch { Write-Verbose "DefaultWebProxy configuration skipped: $($_.Exception.Message)" }
}
# Ensure legacy or leaked proxy parameter defaults do not break PowerShell Core (CWE-754 / CWE-755)
if ($PSDefaultParameterValues.ContainsKey('Invoke-WebRequest:ProxyUseDefaultCredentials')) {
$null = $PSDefaultParameterValues.Remove('Invoke-WebRequest:ProxyUseDefaultCredentials')
}
if ($PSDefaultParameterValues.ContainsKey('Invoke-RestMethod:ProxyUseDefaultCredentials')) {
$null = $PSDefaultParameterValues.Remove('Invoke-RestMethod:ProxyUseDefaultCredentials')
}
$actionName = if ($Update) { "Updating" } else { "Installing" }
Write-Host "[ ACTION ] $actionName DiamTek Java Version Manager..." -ForegroundColor Cyan
function Update-Progress {
param(
[int]$Percent,
[string]$Activity
)
if ($Quiet) { return }
$clamped = [math]::Max(0, [math]::Min(100, $Percent))
$barLength = 30
$filled = [math]::Floor(($clamped / 100) * $barLength)
$empty = $barLength - $filled
$bar = ('=' * $filled) + (' ' * $empty)
$paddedActivity = $Activity.PadRight(52)
Write-Host ("`r[ ACTION ] [{0}] {1,3}% {2}$([char]27)[K" -f $bar, $clamped, $paddedActivity) -NoNewline -ForegroundColor Cyan
}
function Get-FileSha256 {
param([string]$Path)
if (Get-Command Get-FileHash -ErrorAction SilentlyContinue) {
try {
return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLower()
} catch { Write-Verbose "Get-FileHash fallback triggered: $($_.Exception.Message)" }
}
$sha256 = $null
$stream = $null
try {
$sha256 = [System.Security.Cryptography.SHA256]::Create()
$stream = [System.IO.File]::OpenRead((Resolve-Path -LiteralPath $Path))
$hashBytes = $sha256.ComputeHash($stream)
return ([System.BitConverter]::ToString($hashBytes) -replace '-','').ToLower()
} finally {
if ($null -ne $stream) { $stream.Close(); $stream.Dispose() }
if ($null -ne $sha256) { $sha256.Dispose() }
}
}
function Test-HasReparsePointInLineage([string]$TargetPath) {
if ([string]::IsNullOrWhiteSpace($TargetPath)) { return $false }
try {
$curr = [System.IO.Path]::GetFullPath($TargetPath)
$root = [System.IO.Path]::GetPathRoot($curr)
while ($curr -and ($curr.TrimEnd('\') -ne $root.TrimEnd('\'))) {
if (Test-Path -LiteralPath $curr) {
$item = Get-Item -LiteralPath $curr -Force -ErrorAction Stop
if ([bool]($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint)) { return $true }
}
$curr = Split-Path -Path $curr -Parent
}
} catch { return $true }
return $false
}
function Initialize-SecureDirectory([string]$DirPath, [switch]$RestrictDacl) {
if ([string]::IsNullOrWhiteSpace($DirPath)) { throw "Invalid directory path." }
if (Test-HasReparsePointInLineage $DirPath) {
Write-Host ""
Write-Host "[ ERROR ] Security violation (CWE-59): Reparse point or symlink detected in directory lineage: $DirPath" -ForegroundColor Red
exit 1
}
if (-not (Test-Path -LiteralPath $DirPath)) {
New-Item -ItemType Directory -Path $DirPath -Force | Out-Null
}
if (Test-HasReparsePointInLineage $DirPath) {
Write-Host ""
Write-Host "[ ERROR ] Security violation (CWE-59): Post-creation reparse point detected at: $DirPath" -ForegroundColor Red
exit 1
}
if ($RestrictDacl) {
$icaclsBin = Join-Path ([Environment]::GetFolderPath([Environment+SpecialFolder]::System)) "icacls.exe"
if (-not (Test-Path -LiteralPath $icaclsBin)) {
Write-Host ""
Write-Host "[ ERROR ] Security policy violation (CWE-276): icacls.exe not found in System32 to enforce directory DACL." -ForegroundColor Red
exit 1
}
& $icaclsBin $DirPath /inheritance:r /grant:r "*S-1-5-18:(OI)(CI)F" "*S-1-5-32-544:(OI)(CI)F" "$($env:USERNAME):(OI)(CI)F" *> $null
if ($LASTEXITCODE -ne 0) {
Write-Host ""
Write-Host "[ ERROR ] Security violation (CWE-276): Failed to apply restrictive DACL isolation on secure directory: $DirPath" -ForegroundColor Red
Write-Host " icacls.exe DACL restriction returned exit code $LASTEXITCODE" -ForegroundColor Yellow
exit 1
}
}
}
# 1. Determine destination directory
Update-Progress -Percent 5 -Activity "Initializing environment..."
if ($TargetDir -and (Test-HasReparsePointInLineage $TargetDir)) {
Write-Host ""
Write-Host "[ ERROR ] Security violation (CWE-59): TargetDir cannot be or traverse a reparse point: $TargetDir" -ForegroundColor Red
exit 1
}
$normTarget = if ($TargetDir -and (Test-Path -LiteralPath $TargetDir)) { (Resolve-Path -LiteralPath $TargetDir).Path } else { $null }
if ($normTarget) {
$installDir = $normTarget
} else {
$installDir = "$env:LOCALAPPDATA\DiamTek\JVM\bin"
}
$repoRoot = if ($installDir.EndsWith("\bin", [StringComparison]::OrdinalIgnoreCase)) { Split-Path $installDir -Parent } else { $installDir }
$isDefaultAppDataRoot = $repoRoot.StartsWith("$env:LOCALAPPDATA\DiamTek", [StringComparison]::OrdinalIgnoreCase)
Initialize-SecureDirectory -DirPath $repoRoot -RestrictDacl:$isDefaultAppDataRoot
Initialize-SecureDirectory -DirPath $installDir -RestrictDacl:$isDefaultAppDataRoot
$batPath = Join-Path $installDir "jvm.bat"
Update-Progress -Percent 15 -Activity "Resolving latest release from GitHub..."
$rawBranch = if ($Branch) { $Branch } else { "" }
if (-not $rawBranch) {
if ($Channel -ne "Nightly") {
$apiRes = $null; $sr = $null
try {
$apiReq = [Net.HttpWebRequest]::Create("https://api.github.com/repos/DiamTek/Java-Version-Manager-Windows/releases/latest")
$apiReq.UserAgent = "DiamTek-JVM"
$apiReq.Timeout = 3000
$apiRes = $apiReq.GetResponse()
$sr = New-Object System.IO.StreamReader($apiRes.GetResponseStream())
$json = $sr.ReadToEnd()
if ($json -match '"tag_name":\s*"([^"]+)"') {
$rawBranch = $matches[1]
}
} catch {
Write-Verbose "GitHub API release lookup failed: $($_.Exception.Message)"
} finally {
if ($null -ne $sr) { $sr.Close(); $sr.Dispose() }
if ($null -ne $apiRes) { $apiRes.Close() }
}
if (-not $rawBranch) {
$redirRes = $null
try {
$redirReq = [Net.HttpWebRequest]::Create("https://github.com/DiamTek/Java-Version-Manager-Windows/releases/latest")
$redirReq.AllowAutoRedirect = $false
$redirReq.UserAgent = "DiamTek-JVM"
$redirReq.Timeout = 4000
$redirRes = $redirReq.GetResponse()
$loc = $redirRes.GetResponseHeader("Location")
if ($loc -and $loc -match '/releases/tag/([^/]+)$') {
$rawBranch = $matches[1]
}
} catch {
Write-Verbose "GitHub redirect tag lookup failed: $($_.Exception.Message)"
} finally {
if ($null -ne $redirRes) { $redirRes.Close() }
}
}
}
if (-not $rawBranch) {
$apiRes = $null; $sr = $null
try {
$apiReq = [Net.HttpWebRequest]::Create("https://api.github.com/repos/DiamTek/Java-Version-Manager-Windows/commits/main")
$apiReq.UserAgent = "DiamTek-JVM"
$apiReq.Timeout = 3000
$apiRes = $apiReq.GetResponse()
$sr = New-Object System.IO.StreamReader($apiRes.GetResponseStream())
$json = $sr.ReadToEnd()
if ($json -match '"sha":\s*"([0-9a-f]{40})"') {
$rawBranch = $matches[1]
}
} catch {
$rawBranch = "HEAD"
Write-Verbose "Falling back to HEAD branch ref: $($_.Exception.Message)"
} finally {
if ($null -ne $sr) { $sr.Close(); $sr.Dispose() }
if ($null -ne $apiRes) { $apiRes.Close() }
}
}
}
$cacheBuster = [DateTimeOffset]::UtcNow.Ticks
$noCacheHeaders = @{ 'Cache-Control' = 'no-cache'; 'Pragma' = 'no-cache' }
$url = "https://raw.githubusercontent.com/DiamTek/Java-Version-Manager-Windows/$rawBranch/jvm.bat?t=$cacheBuster"
Update-Progress -Percent 35 -Activity "Fetching core JVM engine..."
if (-not $Update -and $PSScriptRoot -and (Test-Path (Join-Path $PSScriptRoot "jvm.bat"))) {
$content = [System.IO.File]::ReadAllText((Join-Path $PSScriptRoot "jvm.bat"))
} else {
$content = $null
# If on a tagged release on Stable channel, attempt direct release asset download to preserve exact binary layout
if ($Channel -ne "Nightly" -and $rawBranch -match '^v?[0-9]') {
$tempBatPath = "$batPath.tmp.$([System.IO.Path]::GetRandomFileName())"
try {
$relUrl = "https://github.com/DiamTek/Java-Version-Manager-Windows/releases/download/$rawBranch/jvm.bat"
Invoke-WebRequest -Uri $relUrl -Headers $noCacheHeaders -OutFile $tempBatPath -UseBasicParsing -TimeoutSec 10
if ((Test-Path -LiteralPath $tempBatPath) -and (Get-Item -LiteralPath $tempBatPath).Length -gt 0) {
$content = [System.IO.File]::ReadAllText($tempBatPath)
}
} catch {
Write-Verbose "Release asset download fallback triggered: $($_.Exception.Message)"
} finally {
if ($tempBatPath -and (Test-Path -LiteralPath $tempBatPath)) {
Remove-Item -LiteralPath $tempBatPath -Force -ErrorAction SilentlyContinue
}
}
}
if (-not $content) {
$apiRes = $null; $sr = $null
try {
$apiReq = [Net.HttpWebRequest]::Create("https://api.github.com/repos/DiamTek/Java-Version-Manager-Windows/contents/jvm.bat?ref=$rawBranch")
$apiReq.Method = "GET"
$apiReq.Timeout = 4000
$apiReq.UserAgent = "DiamTek-JVM"
$apiReq.Accept = "application/vnd.github.v3.raw"
$apiReq.Headers.Add("Cache-Control", "no-cache")
$apiReq.Headers.Add("Pragma", "no-cache")
$apiRes = $apiReq.GetResponse()
$sr = New-Object System.IO.StreamReader($apiRes.GetResponseStream())
$content = $sr.ReadToEnd()
} catch {
try {
$rawWget = Invoke-WebRequest -Uri $url -Headers $noCacheHeaders -UseBasicParsing -TimeoutSec 5
$content = if ($rawWget.Content -is [byte[]]) { [System.Text.Encoding]::UTF8.GetString($rawWget.Content) } else { [string]$rawWget.Content }
} catch {
Write-Verbose "Raw GitHub download failed: $($_.Exception.Message)"
}
} finally {
if ($null -ne $sr) { $sr.Close(); $sr.Dispose() }
if ($null -ne $apiRes) { $apiRes.Close() }
}
}
}
# 2. Integrity Check
if (-not $content -or $content.Length -eq 0 -or $content -notmatch "rem END OF SCRIPT") {
Write-Host ""
Write-Host "[ ERROR ] Download failed integrity check. File is empty or truncated." -ForegroundColor Red
exit 1
}
# Fetch SHA256SUMS.txt if on Stable channel / tagged release
$shaHashMap = @{}
if ($Channel -ne "Nightly" -and $rawBranch -match '^v?[0-9]') {
try {
$shaText = $null
try {
$resp = Invoke-WebRequest -Uri "https://github.com/DiamTek/Java-Version-Manager-Windows/releases/download/$rawBranch/SHA256SUMS.txt" -Headers $noCacheHeaders -UserAgent "DiamTek-JVM" -UseBasicParsing -TimeoutSec 5
$shaText = if ($resp.Content -is [byte[]]) { [System.Text.Encoding]::UTF8.GetString($resp.Content) } else { [string]$resp.Content }
} catch {
try {
$shaText = (Invoke-RestMethod -Uri "https://github.com/DiamTek/Java-Version-Manager-Windows/releases/download/$rawBranch/SHA256SUMS.txt" -Headers $noCacheHeaders -UserAgent "DiamTek-JVM" -TimeoutSec 5)
} catch {
try {
$relJson = (Invoke-RestMethod -Uri "https://api.github.com/repos/DiamTek/Java-Version-Manager-Windows/releases/tags/$rawBranch" -UserAgent "DiamTek-JVM")
$asset = $relJson.assets | Where-Object { $_.name -eq "SHA256SUMS.txt" } | Select-Object -First 1
if ($asset) {
$rawAsset = Invoke-WebRequest -Uri $asset.browser_download_url -UserAgent "DiamTek-JVM" -UseBasicParsing -TimeoutSec 5
$shaText = if ($rawAsset.Content -is [byte[]]) { [System.Text.Encoding]::UTF8.GetString($rawAsset.Content) } else { [string]$rawAsset.Content }
}
} catch { Write-Verbose "Release asset SHA256SUMS lookup failed: $($_.Exception.Message)" }
}
}
if ($shaText) {
foreach ($sLine in ($shaText -split "`r?`n")) {
if ($sLine -match '^([0-9a-fA-F]{64})\s+[\*]?(.+)$') {
$shaHashMap[$matches[2].Trim()] = $matches[1].ToLower()
}
}
}
} catch { Write-Verbose "SHA256SUMS parsing skipped: $($_.Exception.Message)" }
}
function Remove-ReparsePointOrFail([string]$FilePath) {
if ([string]::IsNullOrWhiteSpace($FilePath)) { return }
if (Test-HasReparsePointInLineage $FilePath) {
if (Test-Path -LiteralPath $FilePath) {
try {
$item = Get-Item -LiteralPath $FilePath -Force -ErrorAction Stop
if ([bool]($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint)) {
Remove-Item -LiteralPath $FilePath -Force -ErrorAction Stop
}
} catch { Write-Verbose "Could not remove existing reparse point at ${FilePath}: $($_.Exception.Message)" }
}
if (Test-HasReparsePointInLineage $FilePath) {
Write-Host ""
Write-Host "[ ERROR ] Security violation (CWE-59): Reparse point or symlink detected at path: $FilePath" -ForegroundColor Red
exit 1
}
}
}
function Invoke-TrustedGitHubDownload([string]$Uri, [string]$OutFile, [int]$MaxBytes = 5242880) {
$allowedHosts = @('github.com', 'raw.githubusercontent.com', 'objects.githubusercontent.com', 'api.github.com', 'release-assets.githubusercontent.com', 'cdn.jsdelivr.net')
$req = [System.Net.HttpWebRequest]::Create($Uri)
$req.Method = "GET"
$req.Timeout = 15000
$req.ReadWriteTimeout = 15000
$req.UserAgent = "DiamTek-JVM"
$req.Headers.Add("Cache-Control", "no-cache")
$req.Headers.Add("Pragma", "no-cache")
$res = $null
try {
$res = $req.GetResponse()
$finalUri = $res.ResponseUri
if (-not $finalUri -or $finalUri.Scheme -ne 'https' -or ($allowedHosts -notcontains $finalUri.Host.ToLowerInvariant())) {
throw "Security violation (CWE-601): Untrusted redirect host or scheme '$finalUri'"
}
if ($res.ContentLength -gt $MaxBytes) {
throw "Security violation (CWE-400): Payload ContentLength ($($res.ContentLength)) exceeds ceiling ($MaxBytes bytes)"
}
$stream = $null
$fs = $null
$downloadOk = $false
try {
$stream = $res.GetResponseStream()
$fs = [System.IO.File]::Open($OutFile, [System.IO.FileMode]::Create, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None)
$buf = New-Object byte[] 16384
$total = 0
while (($read = $stream.Read($buf, 0, $buf.Length)) -gt 0) {
$total += $read
if ($total -gt $MaxBytes) {
throw "Security violation (CWE-400): Stream exceeded $MaxBytes byte safety ceiling"
}
$fs.Write($buf, 0, $read)
}
$downloadOk = $true
} finally {
if ($null -ne $fs) { $fs.Close(); $fs.Dispose() }
if ($null -ne $stream) { $stream.Close(); $stream.Dispose() }
if (-not $downloadOk -and $OutFile -and (Test-Path -LiteralPath $OutFile)) {
Remove-Item -LiteralPath $OutFile -Force -ErrorAction SilentlyContinue
}
}
} finally {
if ($null -ne $res) { $res.Close() }
}
return ((Test-Path -LiteralPath $OutFile) -and (Get-Item -LiteralPath $OutFile).Length -gt 0)
}
function Test-GitBlobSha1([string]$FilePath, [string]$RemoteRelPath, [string]$RefName) {
$sha1 = $null
try {
$meta = Invoke-RestMethod -Uri "https://api.github.com/repos/DiamTek/Java-Version-Manager-Windows/contents/$RemoteRelPath`?ref=$RefName" -Headers $noCacheHeaders -UserAgent "DiamTek-JVM" -TimeoutSec 5
if ($meta -and $meta.sha) {
$expectedGitSha = ([string]$meta.sha).ToLower()
$sha1 = [System.Security.Cryptography.SHA1]::Create()
$rawBytes = [System.IO.File]::ReadAllBytes($FilePath)
$rawText = [System.IO.File]::ReadAllText($FilePath, [System.Text.Encoding]::UTF8)
$lfBytes = [System.Text.Encoding]::UTF8.GetBytes(($rawText -replace "`r`n", "`n"))
foreach ($b in @($rawBytes, $lfBytes)) {
$hdr = [System.Text.Encoding]::ASCII.GetBytes("blob $($b.Length)`0")
$blob = New-Object byte[] ($hdr.Length + $b.Length)
[Array]::Copy($hdr, 0, $blob, 0, $hdr.Length)
[Array]::Copy($b, 0, $blob, $hdr.Length, $b.Length)
$g = ([System.BitConverter]::ToString($sha1.ComputeHash($blob)) -replace '-', '').ToLower()
if ($g -eq $expectedGitSha) { return $true }
}
return $false
}
} catch {
Write-Verbose "Git blob SHA-1 lookup failed for ${RemoteRelPath}: $($_.Exception.Message)"
} finally {
if ($null -ne $sha1) { $sha1.Dispose() }
}
return $false
}
Update-Progress -Percent 50 -Activity "Sanitizing code format and encoding..."
$sanitizedContent = ($content -replace "`r?`n", "`r`n").Replace([char]160, ' ')
# Stage to an isolated temporary file first to prevent TOCTOU and avoid clobbering existing installation on failure (CWE-459 / CWE-460)
$stageBat = "$batPath.stage.$([Guid]::NewGuid().ToString('N')).tmp"
$batBackup = "$batPath.bak.$([Guid]::NewGuid().ToString('N')).tmp"
$installCommitted = $false
try {
[System.IO.File]::WriteAllText($stageBat, $sanitizedContent, (New-Object System.Text.UTF8Encoding($false)))
# Verify jvm.bat SHA256 integrity on the staged file
$actualJvmHash = Get-FileSha256 -Path $stageBat
if ($shaHashMap.ContainsKey("jvm.bat")) {
$expectedJvmHash = $shaHashMap["jvm.bat"]
if ($actualJvmHash -ne $expectedJvmHash) {
Write-Host ""
Write-Host "[ ERROR ] Cryptographic integrity check failed for jvm.bat!" -ForegroundColor Red
Write-Host " Expected: $expectedJvmHash" -ForegroundColor Red
Write-Host " Computed: $actualJvmHash" -ForegroundColor Red
Write-Host " Installation aborted to prevent untrusted execution." -ForegroundColor Red
Remove-Item -LiteralPath $stageBat -Force -ErrorAction SilentlyContinue
exit 1
}
} elseif ($Channel -ne "Nightly" -and $rawBranch -match '^v?[0-9]') {
Write-Host ""
Write-Host "[ ERROR ] Cryptographic integrity manifest (SHA256SUMS.txt) required for official release $rawBranch on Stable channel." -ForegroundColor Red
Write-Host " Could not verify jvm.bat hash against release manifest. Aborting installation." -ForegroundColor Red
Remove-Item -LiteralPath $stageBat -Force -ErrorAction SilentlyContinue
exit 1
} else {
# Nightly or non-tagged release Git-blob SHA-1 integrity verification (CWE-494 / CWE-345)
if ($SkipIntegrity) {
Write-Host "[ WARN ] Security notice: Skipping integrity verification per -SkipIntegrity flag." -ForegroundColor Yellow
} else {
$sha1 = $null
$verifiedNightly = $false
$nightlyErr = ""
try {
$meta = Invoke-RestMethod -Uri "https://api.github.com/repos/DiamTek/Java-Version-Manager-Windows/contents/jvm.bat?ref=$rawBranch" -Headers $noCacheHeaders -UserAgent "DiamTek-JVM" -TimeoutSec 5
if ($meta -and $meta.sha) {
$expectedGitSha = ([string]$meta.sha).ToLower()
$sha1 = [System.Security.Cryptography.SHA1]::Create()
$rawBytes = [System.IO.File]::ReadAllBytes($stageBat)
$lfBytes = [System.Text.Encoding]::UTF8.GetBytes(($sanitizedContent -replace "`r`n", "`n"))
$matchedGit = $false
$computedGit = ""
foreach ($b in @($rawBytes, $lfBytes)) {
$hdr = [System.Text.Encoding]::ASCII.GetBytes("blob $($b.Length)`0")
$blob = New-Object byte[] ($hdr.Length + $b.Length)
[Array]::Copy($hdr, 0, $blob, 0, $hdr.Length)
[Array]::Copy($b, 0, $blob, $hdr.Length, $b.Length)
$g = ([System.BitConverter]::ToString($sha1.ComputeHash($blob)) -replace '-', '').ToLower()
if (-not $computedGit) { $computedGit = $g }
if ($g -eq $expectedGitSha) { $matchedGit = $true; break }
}
if ($matchedGit) {
$verifiedNightly = $true
} else {
Write-Host ""
Write-Host "[ ERROR ] Cryptographic Git blob SHA-1 check failed for Nightly jvm.bat!" -ForegroundColor Red
Write-Host " Expected Git Blob SHA: $expectedGitSha" -ForegroundColor Red
Write-Host " Computed Git Blob SHA: $computedGit" -ForegroundColor Red
Remove-Item -LiteralPath $stageBat -Force -ErrorAction SilentlyContinue
exit 1
}
} else {
$nightlyErr = "No Git blob SHA returned by GitHub API for ref '$rawBranch'."
}
} catch {
$nightlyErr = $_.Exception.Message
} finally {
if ($null -ne $sha1) { $sha1.Dispose() }
}
if (-not $verifiedNightly) {
Write-Host ""
Write-Host "[ ERROR ] Fail-closed integrity check (CWE-494): Failed to verify Nightly Git blob SHA-1 against GitHub tree." -ForegroundColor Red
if ($nightlyErr) {
Write-Host " Detail: $nightlyErr" -ForegroundColor Yellow
}
Write-Host " Aborting installation to prevent unverified code execution." -ForegroundColor Red
Write-Host " Pass -SkipIntegrity if explicitly overriding in an air-gapped test environment." -ForegroundColor Yellow
Remove-Item -LiteralPath $stageBat -Force -ErrorAction SilentlyContinue
exit 1
}
}
}
# Move verified staged engine into place atomically after verifying target is not a symlink/reparse point
Remove-ReparsePointOrFail -FilePath $batPath
if (Test-Path -LiteralPath $batPath) {
Copy-Item -LiteralPath $batPath -Destination $batBackup -Force -ErrorAction SilentlyContinue
}
Move-Item -LiteralPath $stageBat -Destination $batPath -Force
Update-Progress -Percent 65 -Activity "Fetching documentation, license, & uninstaller..."
Initialize-SecureDirectory -DirPath $repoRoot -RestrictDacl:$isDefaultAppDataRoot
$companionFiles = @("LICENSE", "README.md", "uninstall.ps1", "assets/icon.ico", "assets/icon.png")
foreach ($cf in $companionFiles) {
$destFile = Join-Path $repoRoot ($cf -replace '/', '\')
$destDir = Split-Path $destFile -Parent
Initialize-SecureDirectory -DirPath $destDir -RestrictDacl:$isDefaultAppDataRoot
Remove-ReparsePointOrFail -FilePath $destFile
$localSource = if ($PSScriptRoot) { Join-Path $PSScriptRoot ($cf -replace '/', '\') } else { $null }
if (-not $Update -and $localSource -and (Test-Path -LiteralPath $localSource)) {
Copy-Item -LiteralPath $localSource -Destination $destFile -Force
if ((Split-Path $destFile -Leaf) -eq "uninstall.ps1") {
$uninstShaFile = "$destFile.sha256"
Remove-ReparsePointOrFail -FilePath $uninstShaFile
[System.IO.File]::WriteAllText($uninstShaFile, (Get-FileSha256 -Path $destFile), (New-Object System.Text.UTF8Encoding($false)))
}
} else {
$downloadSuccess = $false
$baseName = Split-Path $destFile -Leaf
$stageCf = "$destFile.stage.$([Guid]::NewGuid().ToString('N')).tmp"
try {
if ($Channel -ne "Nightly" -and $rawBranch -match '^v?[0-9]' -and @("LICENSE", "README.md", "uninstall.ps1") -contains $baseName) {
try {
$relAssetUrl = "https://github.com/DiamTek/Java-Version-Manager-Windows/releases/download/$rawBranch/$baseName"
$downloadSuccess = Invoke-TrustedGitHubDownload -Uri $relAssetUrl -OutFile $stageCf
} catch { Write-Verbose "Release companion download failed for ${baseName}: $($_.Exception.Message)" }
}
if (-not $downloadSuccess) {
try {
$downloadSuccess = Invoke-TrustedGitHubDownload -Uri "https://raw.githubusercontent.com/DiamTek/Java-Version-Manager-Windows/$rawBranch/$cf`?t=$cacheBuster" -OutFile $stageCf
} catch {
if ($baseName -ne "uninstall.ps1") {
try {
$downloadSuccess = Invoke-TrustedGitHubDownload -Uri "https://raw.githubusercontent.com/DiamTek/Java-Version-Manager-Windows/HEAD/$cf`?t=$cacheBuster" -OutFile $stageCf
} catch {
if (-not (Test-Path -LiteralPath $destFile)) {
Write-Host ""
Write-Host " [WARN] Could not fetch $cf. Proceeding anyway." -ForegroundColor Yellow
}
}
}
}
}
if ($downloadSuccess -and (Test-Path -LiteralPath $stageCf)) {
$verifiedCf = $true
if ($shaHashMap.ContainsKey($baseName)) {
$actualCfHash = Get-FileSha256 -Path $stageCf
$expectedCfHash = $shaHashMap[$baseName]
if ($actualCfHash -ne $expectedCfHash) {
$verifiedCf = $false
Write-Host ""
Write-Host " [ ERROR ] Integrity check failed for $baseName (SHA256 mismatch)!" -ForegroundColor Red
Write-Host " Expected: $expectedCfHash" -ForegroundColor Red
Write-Host " Computed: $actualCfHash" -ForegroundColor Red
Remove-Item -LiteralPath $stageCf -Force -ErrorAction SilentlyContinue
if ($baseName -eq "uninstall.ps1") {
Write-Host " [ FATAL ] Security-critical uninstaller failed integrity verification. Aborting." -ForegroundColor Red
exit 1
}
}
} elseif ($baseName -eq "uninstall.ps1" -and $Channel -ne "Nightly" -and $rawBranch -match '^v?[0-9]') {
$verifiedCf = $false
Remove-Item -LiteralPath $stageCf -Force -ErrorAction SilentlyContinue
Write-Host ""
Write-Host " [ FATAL ] Missing SHA-256 entry for security-critical uninstall.ps1 in release manifest. Aborting." -ForegroundColor Red
exit 1
} elseif ($baseName -eq "uninstall.ps1") {
if (-not (Test-GitBlobSha1 -FilePath $stageCf -RemoteRelPath $cf -RefName $rawBranch)) {
$verifiedCf = $false
Remove-Item -LiteralPath $stageCf -Force -ErrorAction SilentlyContinue
Write-Host ""
Write-Host " [ FATAL ] Cryptographic Git blob SHA-1 check failed for Nightly uninstall.ps1. Aborting." -ForegroundColor Red
exit 1
}
}
if ($verifiedCf -and (Test-Path -LiteralPath $stageCf)) {
Remove-ReparsePointOrFail -FilePath $destFile
Move-Item -LiteralPath $stageCf -Destination $destFile -Force
if ($baseName -eq "uninstall.ps1") {
$uninstShaFile = "$destFile.sha256"
Remove-ReparsePointOrFail -FilePath $uninstShaFile
[System.IO.File]::WriteAllText($uninstShaFile, (Get-FileSha256 -Path $destFile), (New-Object System.Text.UTF8Encoding($false)))
}
}
}
} finally {
if ($stageCf -and (Test-Path -LiteralPath $stageCf)) {
Remove-Item -LiteralPath $stageCf -Force -ErrorAction SilentlyContinue
}
}
}
}
$installCommitted = $true
} finally {
if ($stageBat -and (Test-Path -LiteralPath $stageBat)) {
Remove-Item -LiteralPath $stageBat -Force -ErrorAction SilentlyContinue
}
if (-not $installCommitted -and $batBackup -and (Test-Path -LiteralPath $batBackup)) {
Move-Item -LiteralPath $batBackup -Destination $batPath -Force -ErrorAction SilentlyContinue
}
if ($batBackup -and (Test-Path -LiteralPath $batBackup)) {
Remove-Item -LiteralPath $batBackup -Force -ErrorAction SilentlyContinue
}
Get-ChildItem -LiteralPath $repoRoot -Filter "*.stage.*.tmp" -Recurse -Force -ErrorAction SilentlyContinue | Remove-Item -Force -ErrorAction SilentlyContinue
}
if ($installDir -ne $repoRoot) {
$legacyUninstall = Join-Path $installDir "uninstall.ps1"
if (Test-Path -LiteralPath $legacyUninstall) {
Remove-Item -LiteralPath $legacyUninstall -Force -ErrorAction SilentlyContinue
}
}
$channelFile = Join-Path $repoRoot "channel.txt"
Remove-ReparsePointOrFail -FilePath $channelFile
if (-not (Test-Path -LiteralPath $channelFile)) {
$cVal = if ($Channel -eq "Nightly") { "NIGHTLY" } else { "STABLE" }
[System.IO.File]::WriteAllText($channelFile, "$cVal`r`n", (New-Object System.Text.UTF8Encoding($false)))
}
# 3. Safe REG_EXPAND_SZ Path Injection
Update-Progress -Percent 80 -Activity "Configuring User PATH..."
function Normalize-PathEntry([string]$p) {
if (-not $p) { return "" }
$clean = $p.Trim().Trim('`"').Trim("'").Trim()
if ($clean.Length -gt 3) {
return $clean.TrimEnd('\', '/')
}
return $clean
}
$userPath = ""
$existingKind = [Microsoft.Win32.RegistryValueKind]::ExpandString
$envKey = $null
try {
$envKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey("Environment")
if ($null -ne $envKey) {
$raw = $envKey.GetValue("Path", "", [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
if ($null -ne $raw) { $userPath = [string]$raw }
$existingKind = try { $envKey.GetValueKind("Path") } catch { [Microsoft.Win32.RegistryValueKind]::ExpandString }
}
} catch {
try {
$userPath = (Get-ItemProperty -Path 'HKCU:\Environment' -Name 'Path' -ErrorAction SilentlyContinue).Path
} catch { Write-Verbose "Fallback HKCU Path read skipped: $($_.Exception.Message)" }
} finally {
if ($null -ne $envKey) { $envKey.Close() }
}
$pathArray = @($userPath -split ';' | Where-Object { $_ -ne '' } | ForEach-Object { Normalize-PathEntry $_ })
$normalizedInstallDir = Normalize-PathEntry $installDir
if ($normalizedInstallDir -notin $pathArray) {
$newPathList = @()
foreach ($p in ($pathArray + $normalizedInstallDir)) {
if ($p -and ($newPathList -notcontains $p)) { $newPathList += $p }
}
$newPath = $newPathList -join ';'
# Query Machine PATH to compute effective Combined PATH
$machinePath = [Environment]::GetEnvironmentVariable('Path', 'Machine')
$combinedLength = if ($machinePath) { $machinePath.Length + 1 + $newPath.Length } else { $newPath.Length }
if ($combinedLength -gt 8191) {
Write-Host ""
Write-Host "[ ERROR ] Combined PATH length ($combinedLength chars) exceeds Windows 8191-character limit!" -ForegroundColor Red
Write-Host " System PATH ($($machinePath.Length) chars) + User PATH ($($newPath.Length) chars)." -ForegroundColor Red
Write-Host " Modification aborted to prevent environment block corruption." -ForegroundColor Red
} else {
if ($combinedLength -gt 2048) {
Write-Host ""
Write-Host "[ WARNING] Combined PATH length ($combinedLength chars) exceeds 2048 characters (User: $($newPath.Length), System: $($machinePath.Length))." -ForegroundColor Yellow
Write-Host " Some legacy Win32 applications may truncate PATH." -ForegroundColor Yellow
}
# Preserve REG_SZ only if existing was String and no variable references exist; otherwise enforce ExpandString
$targetKind = if ($existingKind -eq [Microsoft.Win32.RegistryValueKind]::String -and $newPath -notmatch '%') {
[Microsoft.Win32.RegistryValueKind]::String
} else {
[Microsoft.Win32.RegistryValueKind]::ExpandString
}
try {
Set-ItemProperty -Path 'HKCU:\Environment' -Name 'Path' -Value $newPath -Type $targetKind -Force
} catch {
[Microsoft.Win32.Registry]::SetValue("HKEY_CURRENT_USER\Environment", "Path", $newPath, $targetKind)
}
# Broadcast WM_SETTINGCHANGE safely
try {
if (-not ("Win32.NativeMethods" -as [type])) {
$code = @'
[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);
'@
Add-Type -MemberDefinition $code -Name NativeMethods -Namespace Win32 -ErrorAction SilentlyContinue
}
$HWND_BROADCAST = [IntPtr]0xFFFF
$WM_SETTINGCHANGE = 0x001A
$result = [UIntPtr]::Zero
[Win32.NativeMethods]::SendMessageTimeout($HWND_BROADCAST, $WM_SETTINGCHANGE, [UIntPtr]::Zero, 'Environment', 2, 1000, [ref]$result) | Out-Null
} catch { Write-Verbose "WM_SETTINGCHANGE broadcast skipped: $($_.Exception.Message)" }
}
}
# 4. Install PowerShell Profile Hook natively
Update-Progress -Percent 90 -Activity "Configuring PowerShell profile..."
$profileCode = @'
# >>> jvm >>>
function jvm {
$bat = '__FALLBACK_BAT__'
if (-not (Test-Path -LiteralPath $bat)) {
$bat = Get-Command jvm.bat -CommandType Application -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source -First 1
}
if (-not $bat -or -not (Test-Path -LiteralPath $bat)) {
Write-Error "jvm: Java Version Manager is not installed or not in PATH. Please reinstall JVM or restart your terminal."
return
}
# Handle UNC directory paths via pushd
$isUnc = ($pwd.Provider.Name -eq 'FileSystem' -and $pwd.Path -like '\\*')
if ($isUnc) {
pushd -LiteralPath $pwd.Path
try {
& $bat @args
} finally {
popd
}
} else {
& $bat @args
}
function Set-JvmVar {
param([string]$Name, [string]$OldValue, [string]$NewValue)
$allowedVars = @('JAVA_HOME', 'MAVEN_HOME', 'GRADLE_HOME', 'KOTLIN_HOME', 'SCALA_HOME', 'GROOVY_HOME')
if ($allowedVars -notcontains $Name) { return }
if ($OldValue) { $OldValue = $OldValue.Trim('`"').TrimEnd('\') }
if ($NewValue) { $NewValue = $NewValue.Trim('`"').TrimEnd('\') }
# Validate NewValue is a genuine directory and contains no injection characters
if (-not [string]::IsNullOrWhiteSpace($NewValue)) {
if ($NewValue -match '[\0;&|<>`"\r\n\$%]') { return }
if (-not (Test-Path -LiteralPath $NewValue -PathType Container)) { return }
# Storage boundary enforcement
$canonicalPath = (Resolve-Path -LiteralPath $NewValue -ErrorAction SilentlyContinue).Path
$allowedRoots = @(
"$env:LOCALAPPDATA\DiamTek\JVM",
"$env:LOCALAPPDATA\JavaVersionManager",
"$env:ProgramFiles\Java",
"${env:ProgramFiles(x86)}\Java",
"$env:USERPROFILE\.jdks"
)
$isAllowed = $false
foreach ($root in $allowedRoots) {
$normRoot = $root.TrimEnd('\')
$rootPrefix = $normRoot + '\'
if ($canonicalPath -and ($canonicalPath.Equals($normRoot, [StringComparison]::OrdinalIgnoreCase) -or $canonicalPath.StartsWith($rootPrefix, [StringComparison]::OrdinalIgnoreCase))) {
$isAllowed = $true
break
}
}
if (-not $isAllowed) { return }
}
# CLM-compliant environment update
Set-Item -Path "env:$Name" -Value $NewValue -Force
$parts = $env:Path -split ';' | Where-Object { $_ -ne '' }
if (-not [string]::IsNullOrWhiteSpace($OldValue)) {
$parts = $parts | Where-Object { $_.TrimEnd('\') -ne "$OldValue\bin" }
}
if (-not [string]::IsNullOrWhiteSpace($NewValue)) {
$parts = $parts | Where-Object { $_.TrimEnd('\') -ne "$NewValue\bin" }
$parts = @("$NewValue\bin") + $parts
}
$env:Path = $parts -join ';'
}
$sessionFile = Join-Path $env:LOCALAPPDATA 'DiamTek\JVM\temp\.jvm_session_target'
if (Test-Path $sessionFile) {
$lines = Get-Content $sessionFile -ErrorAction SilentlyContinue
Remove-Item $sessionFile -Force -ErrorAction SilentlyContinue
foreach ($line in $lines) {
if ([string]::IsNullOrWhiteSpace($line)) { continue }
if ($line -match '^([A-Za-z0-9_]+)=(.*)$') {
$key = $matches[1]
$val = $matches[2]
} else {
$key = 'JAVA_HOME'
$val = $line
}
$old = (Get-Item -Path "env:$key" -ErrorAction SilentlyContinue).Value
Set-JvmVar -Name $key -OldValue $old -NewValue $val
}
} else {
foreach ($v in @('JAVA_HOME', 'MAVEN_HOME', 'GRADLE_HOME', 'KOTLIN_HOME', 'SCALA_HOME', 'GROOVY_HOME')) {
$old = (Get-Item -Path "env:$v" -ErrorAction SilentlyContinue).Value
$new = (Get-ItemProperty -Path 'HKCU:\Environment' -Name $v -ErrorAction SilentlyContinue).$v
if ([string]::IsNullOrEmpty($new)) {
$new = (Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' -Name $v -ErrorAction SilentlyContinue).$v
}
if ($old -eq $new) { continue }
Set-JvmVar -Name $v -OldValue $old -NewValue $new
}
}
}
if (Get-Command Register-ArgumentCompleter -ErrorAction SilentlyContinue) {
Register-ArgumentCompleter -Native -CommandName @('jvm', 'jvm.bat', '.\jvm.bat') -ScriptBlock {
param($wordToComplete, $commandAst, $cursorPosition)
$subcommands = @(
'list', 'ls', 'install', 'uninstall', 'rm', 'remove', 'use', 'default',
'pin', 'local', 'current', 'status', 'info', 'whoami', 'which', 'path',
'doctor', 'check', 'clean', 'prune', 'clear', 'update', 'self-update',
'self-uninstall', 'open', 'home', 'exec', 'run', 'env', 'hook',
'link', 'unlink', 'version', 'help', 'channel'
)
$candidates = @('java', 'maven', 'gradle', 'kotlin', 'scala', 'groovy')
$vendors = @('adoptium', 'temurin', 'oracle', 'corretto', 'zulu', 'microsoft', 'graalvm', 'liberica', 'bellsoft', 'semeru', 'ibm', 'openj9')
$openTargets = @('home', 'dir', 'bin', 'config', 'cache', 'downloads', 'backup', 'backups', 'links')
$hookTargets = @('install', 'status', 'check', 'remove', 'uninstall')
$flags = @(
'--vendor', '--symlink', '--registry', '--legacy', '--session', '--global',
'--skip-checksum', '--no-verify', '--latest', '--yes', '-y', '--no-color',
'--channel', '--nightly', '--stable',
'--version', '-v', '--help', '-h'
)
$elements = @($commandAst.CommandElements | ForEach-Object { $_.Extent.Text })
$count = $elements.Count
$prev = if ($wordToComplete -and $count -ge 2) { $elements[-2] } elseif (-not $wordToComplete -and $count -ge 1) { $elements[-1] } else { '' }
$completions = @()
if ($prev -in @('--vendor')) {
$completions = $vendors
} elseif ($prev -in @('channel', '--channel')) {
$completions = @('stable', 'nightly')
} elseif ($prev -in @('open', 'home')) {
$completions = $openTargets
} elseif ($prev -in @('hook')) {
$completions = $hookTargets
} elseif ($prev -in @('use', 'default', 'pin', 'local', 'uninstall', 'rm', 'remove', 'which', 'path')) {
$installed = @()
$linksDir = "$env:LOCALAPPDATA\JavaVersionManager\links"
if (Test-Path -LiteralPath $linksDir) {
$installed += @(Get-ChildItem -LiteralPath $linksDir -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Name)
}
$jdksDir = "$env:USERPROFILE\.jdks"
if (Test-Path -LiteralPath $jdksDir) {
$installed += @(Get-ChildItem -LiteralPath $jdksDir -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Name)
}
$completions = @($installed | Select-Object -Unique) + $candidates
} elseif ($wordToComplete -like '-*') {
$completions = $flags
} else {
$completions = $subcommands + $candidates + $flags
}
$completions | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object {
[System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
}
}
}
# <<< jvm <<<
'@
$batPathEscaped = $batPath.Replace("'", "''")
$profileCode = $profileCode.Replace('__FALLBACK_BAT__', $batPathEscaped)
$userProfile = [Environment]::GetFolderPath('UserProfile')
$myDocs = [Environment]::GetFolderPath('MyDocuments')
$regDocs = (Get-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders' -Name 'Personal' -ErrorAction SilentlyContinue).Personal
$expandedDocs = if ($regDocs) { [System.Environment]::ExpandEnvironmentVariables($regDocs) } else { $null }
$profiles = @(
$PROFILE,
(Join-Path $userProfile 'Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1'),
(Join-Path $userProfile 'Documents\PowerShell\Microsoft.PowerShell_profile.ps1'),
(Join-Path $myDocs 'WindowsPowerShell\Microsoft.PowerShell_profile.ps1'),
(Join-Path $myDocs 'PowerShell\Microsoft.PowerShell_profile.ps1')
)
if ($expandedDocs) {
$profiles += (Join-Path $expandedDocs 'WindowsPowerShell\Microsoft.PowerShell_profile.ps1')
$profiles += (Join-Path $expandedDocs 'PowerShell\Microsoft.PowerShell_profile.ps1')
}
$profiles = $profiles | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | Select-Object -Unique
function Test-HasReparsePointInLineage([string]$TargetPath) {
if ([string]::IsNullOrWhiteSpace($TargetPath)) { return $false }
try {
$curr = [System.IO.Path]::GetFullPath($TargetPath)
$root = [System.IO.Path]::GetPathRoot($curr)
while ($curr -and ($curr.TrimEnd('\') -ne $root.TrimEnd('\'))) {
if (Test-Path -LiteralPath $curr) {
$item = Get-Item -LiteralPath $curr -Force -ErrorAction Stop
if ([bool]($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint)) { return $true }
}
$curr = Split-Path -Path $curr -Parent
}
} catch { return $true }
return $false
}
$utf8NoBom = New-Object System.Text.UTF8Encoding($false)
foreach ($p in $profiles) {
if ([string]::IsNullOrWhiteSpace($p)) { continue }
$stageProf = $null
try {
if (Test-HasReparsePointInLineage $p) { continue }
$profileDir = Split-Path -Path $p -Parent
if (-not (Test-Path -LiteralPath $profileDir)) { New-Item -ItemType Directory -Path $profileDir -Force -ErrorAction SilentlyContinue | Out-Null }
if (Test-HasReparsePointInLineage $profileDir) { continue }
$profContent = ''
if (Test-Path -LiteralPath $p) {
if (Test-HasReparsePointInLineage $p) { continue }
$profContent = [System.IO.File]::ReadAllText($p, [System.Text.Encoding]::UTF8)
}
$blockPattern = '(?s)# >>> jvm >>>.*?# <<< jvm <<<'
$m = [Regex]::Match($profContent, $blockPattern)
if ($m.Success) {
$profContent = $profContent.Substring(0, $m.Index) + $profileCode + $profContent.Substring($m.Index + $m.Length)
} else {
$profContent = if ([string]::IsNullOrWhiteSpace($profContent)) { $profileCode } else { "$profContent`r`n`r`n$profileCode" }
}
$stageProf = "$p.stage.$([Guid]::NewGuid().ToString('N')).tmp"
[System.IO.File]::WriteAllText($stageProf, $profContent, $utf8NoBom)
if (-not (Test-HasReparsePointInLineage $p)) {
Move-Item -LiteralPath $stageProf -Destination $p -Force
}
} catch {
Write-Verbose "Profile hook update skipped for ${p}: $($_.Exception.Message)"
} finally {
if ($stageProf -and (Test-Path -LiteralPath $stageProf)) {
Remove-Item -LiteralPath $stageProf -Force -ErrorAction SilentlyContinue
}
}
}
# 5. Register Windows Uninstaller & Start Menu Shortcuts
Update-Progress -Percent 96 -Activity "Registering Windows uninstaller & shortcuts..."
try {
# Windows Settings / Control Panel 'Installed Apps' Registration
$uninstallRegPath = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\DiamTek.JVM"
if (-not (Test-Path $uninstallRegPath)) { New-Item -Path $uninstallRegPath -Force | Out-Null }
$sys32Dir = [Environment]::GetFolderPath([Environment+SpecialFolder]::System)
$systemPowerShell = Join-Path $sys32Dir "WindowsPowerShell\v1.0\powershell.exe"
if (-not (Test-Path -LiteralPath $systemPowerShell)) {
throw "Trusted Windows PowerShell binary not found at $systemPowerShell"
}
$uninstallScriptPath = Join-Path $repoRoot "uninstall.ps1"
$uninstallCommand = "`"$systemPowerShell`" -NoProfile -ExecutionPolicy Bypass -File `"$uninstallScriptPath`""
$quietUninstallCommand = "`"$systemPowerShell`" -NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$uninstallScriptPath`" -Quiet"
$displayVer = "1.0.1"
if (Test-Path -LiteralPath $batPath) {
$batHead = Get-Content -LiteralPath $batPath -Raw -ErrorAction SilentlyContinue
if ($batHead -match 'set\s+"JVM_VERSION=(.*?)"') {
$displayVer = $matches[1].Trim()
}
}
Set-ItemProperty -Path $uninstallRegPath -Name "DisplayName" -Value "DiamTek Java Version Manager"
Set-ItemProperty -Path $uninstallRegPath -Name "DisplayVersion" -Value $displayVer
Set-ItemProperty -Path $uninstallRegPath -Name "Publisher" -Value "DiamTek / Alexéy Shishkin"
Set-ItemProperty -Path $uninstallRegPath -Name "InstallLocation" -Value $repoRoot
Set-ItemProperty -Path $uninstallRegPath -Name "UninstallString" -Value $uninstallCommand
Set-ItemProperty -Path $uninstallRegPath -Name "QuietUninstallString" -Value $quietUninstallCommand
$iconPath = Join-Path $repoRoot "assets\icon.ico"
if (-not (Test-Path -LiteralPath $iconPath)) { $iconPath = Join-Path $repoRoot "icon.ico" }
if (-not (Test-Path -LiteralPath $iconPath)) { $iconPath = Join-Path $sys32Dir "shell32.dll,27" }