-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.ps1
More file actions
596 lines (514 loc) · 18.6 KB
/
install.ps1
File metadata and controls
596 lines (514 loc) · 18.6 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
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
function Get-EnvValue {
param(
[Parameter(Mandatory = $true)][string[]]$Names,
[Parameter()][string]$Default = ""
)
foreach ($name in $Names) {
$value = [Environment]::GetEnvironmentVariable($name)
if (-not [string]::IsNullOrWhiteSpace($value)) {
return $value
}
}
return $Default
}
$Repo = Get-EnvValue -Names @("PROFILEX_REPO", "PROFLEX_REPO") -Default "derekurban/profilex-cli"
$OfficialRepo = "derekurban/profilex-cli"
$LegacyRepo = "derekurban2001/profilex-cli"
$ModulePath = Get-EnvValue -Names @("PROFILEX_MODULE_PATH", "PROFLEX_MODULE_PATH") -Default "github.com/$Repo"
$BinaryBase = "profilex"
$BinaryName = "profilex.exe"
$OwnershipMarkerMagic = "profilex-owned-binary-v1"
$InstallDir = Get-EnvValue -Names @("PROFILEX_INSTALL_DIR", "PROFLEX_INSTALL_DIR") -Default (Join-Path $HOME ".local\bin")
$Version = Get-EnvValue -Names @("PROFILEX_VERSION", "PROFLEX_VERSION") -Default "latest"
$AutoPathRaw = Get-EnvValue -Names @("PROFILEX_AUTO_PATH", "PROFLEX_AUTO_PATH") -Default "1"
$VerifySignaturesRaw = Get-EnvValue -Names @("PROFILEX_VERIFY_SIGNATURES", "PROFLEX_VERIFY_SIGNATURES") -Default "1"
$AllowSourceFallbackRaw = Get-EnvValue -Names @("PROFILEX_ALLOW_SOURCE_FALLBACK", "PROFLEX_ALLOW_SOURCE_FALLBACK") -Default "0"
$AutoInstallGoRaw = Get-EnvValue -Names @("PROFILEX_AUTO_INSTALL_GO", "PROFLEX_AUTO_INSTALL_GO") -Default "1"
$CosignVersion = Get-EnvValue -Names @("PROFILEX_COSIGN_VERSION", "PROFLEX_COSIGN_VERSION") -Default "v2.5.3"
$CosignCacheDir = Get-EnvValue -Names @("PROFILEX_COSIGN_CACHE_DIR", "PROFLEX_COSIGN_CACHE_DIR") -Default ""
$DefaultCosignIdentityRegex = if ($Repo -eq $OfficialRepo -or $Repo -eq $LegacyRepo) {
"^https://github.com/(derekurban/profilex-cli|derekurban2001/profilex-cli)/.github/workflows/release.yml@refs/tags/.*$"
} else {
"^https://github.com/$Repo/.github/workflows/release.yml@refs/tags/.*$"
}
$CosignIdentityRegex = Get-EnvValue -Names @("PROFILEX_COSIGN_IDENTITY_RE", "PROFLEX_COSIGN_IDENTITY_RE") -Default $DefaultCosignIdentityRegex
$CosignOidcIssuer = Get-EnvValue -Names @("PROFILEX_COSIGN_OIDC_ISSUER", "PROFLEX_COSIGN_OIDC_ISSUER") -Default "https://token.actions.githubusercontent.com"
function Write-Log {
param([string]$Message)
Write-Host "[profilex-install] $Message"
}
function Write-WarnMessage {
param([string]$Message)
Write-Warning "[profilex-install] $Message"
}
function Fail {
param([string]$Message)
throw "[profilex-install] ERROR: $Message"
}
function Test-Truthy {
param([string]$Value)
if ([string]::IsNullOrWhiteSpace($Value)) {
return $false
}
switch ($Value.ToLowerInvariant()) {
"1" { return $true }
"true" { return $true }
"yes" { return $true }
"on" { return $true }
default { return $false }
}
}
function Get-Arch {
$arch = $null
$runtimeType = [Type]::GetType("System.Runtime.InteropServices.RuntimeInformation, System.Runtime.InteropServices.RuntimeInformation")
if ($null -ne $runtimeType) {
try {
$prop = $runtimeType.GetProperty("OSArchitecture")
if ($null -ne $prop) {
$value = $prop.GetValue($null, $null)
if ($null -ne $value) {
$arch = $value.ToString()
}
}
} catch {
$arch = $null
}
}
if ([string]::IsNullOrWhiteSpace($arch)) {
if (-not [string]::IsNullOrWhiteSpace($env:PROCESSOR_ARCHITEW6432)) {
$arch = $env:PROCESSOR_ARCHITEW6432
} elseif (-not [string]::IsNullOrWhiteSpace($env:PROCESSOR_ARCHITECTURE)) {
$arch = $env:PROCESSOR_ARCHITECTURE
}
}
if ([string]::IsNullOrWhiteSpace($arch)) {
Fail "Unable to determine architecture"
}
switch ($arch.ToUpperInvariant()) {
"X64" { return "amd64" }
"AMD64" { return "amd64" }
"X86_64" { return "amd64" }
"ARM64" { return "arm64" }
"AARCH64" { return "arm64" }
default { Fail "Unsupported architecture: $arch" }
}
}
function Refresh-SessionPathFromSystem {
$machinePath = [Environment]::GetEnvironmentVariable("Path", "Machine")
$userPath = [Environment]::GetEnvironmentVariable("Path", "User")
if ([string]::IsNullOrWhiteSpace($machinePath) -and [string]::IsNullOrWhiteSpace($userPath)) {
return
}
if ([string]::IsNullOrWhiteSpace($machinePath)) {
$env:Path = $userPath
return
}
if ([string]::IsNullOrWhiteSpace($userPath)) {
$env:Path = $machinePath
return
}
$env:Path = "$machinePath;$userPath"
}
function Ensure-GoAvailable {
if (Get-Command go -ErrorAction SilentlyContinue) {
return $true
}
if (-not (Test-Truthy $AutoInstallGoRaw)) {
return $false
}
Write-Log "Go not found on PATH. Attempting automatic Go install."
if (Get-Command winget -ErrorAction SilentlyContinue) {
$wingetAttempts = @(
@("--id", "GoLang.Go", "-e", "--accept-source-agreements", "--accept-package-agreements", "--silent", "--disable-interactivity"),
@("--id", "GoLang.Go", "-e", "--scope", "machine", "--accept-source-agreements", "--accept-package-agreements", "--silent", "--disable-interactivity")
)
foreach ($args in $wingetAttempts) {
try {
& winget install @args
} catch {
# Continue to next attempt.
}
Refresh-SessionPathFromSystem
if (Get-Command go -ErrorAction SilentlyContinue) {
Write-Log "Installed Go using winget"
return $true
}
}
}
if (Get-Command scoop -ErrorAction SilentlyContinue) {
try {
& scoop install go --no-update-scoop
} catch {
# Continue to final failure.
}
Refresh-SessionPathFromSystem
if (Get-Command go -ErrorAction SilentlyContinue) {
Write-Log "Installed Go using scoop"
return $true
}
}
return $false
}
function Get-FileSha256 {
param([Parameter(Mandatory = $true)][string]$Path)
return (Get-FileHash -Path $Path -Algorithm SHA256).Hash.ToLowerInvariant()
}
function Get-ExpectedChecksum {
param(
[Parameter(Mandatory = $true)][string]$ChecksumsFile,
[Parameter(Mandatory = $true)][string]$AssetName
)
foreach ($line in Get-Content -Path $ChecksumsFile) {
if ($line -match "^([A-Fa-f0-9]{64})\s+(.+)$") {
$hash = $Matches[1].ToLowerInvariant()
$name = $Matches[2].Trim()
if ($name -eq $AssetName) {
return $hash
}
}
}
return $null
}
function Get-OwnershipMarkerPath {
param([Parameter(Mandatory = $true)][string]$BinaryPath)
$dir = Split-Path -Path $BinaryPath -Parent
$name = Split-Path -Path $BinaryPath -Leaf
return Join-Path $dir ".$name.profilex-owner"
}
function Write-OwnershipMarker {
param([Parameter(Mandatory = $true)][string]$BinaryPath)
if (-not (Test-Path $BinaryPath)) {
return
}
$resolvedBinary = (Resolve-Path -Path $BinaryPath).Path
$markerPath = Get-OwnershipMarkerPath -BinaryPath $resolvedBinary
$timestamp = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
@(
$OwnershipMarkerMagic
"path=$resolvedBinary"
"repo=$Repo"
"installed_at=$timestamp"
) | Set-Content -Path $markerPath -Encoding UTF8
Write-Log "Wrote ownership marker $markerPath"
}
function Resolve-CosignCacheDir {
if (-not [string]::IsNullOrWhiteSpace($CosignCacheDir)) {
return $CosignCacheDir
}
$base = $env:LOCALAPPDATA
if ([string]::IsNullOrWhiteSpace($base)) {
if (-not [string]::IsNullOrWhiteSpace($HOME)) {
$base = Join-Path $HOME "AppData\Local"
} else {
return $null
}
}
return Join-Path $base "profilex\cache\cosign"
}
function Get-CachedCosignPath {
param([Parameter(Mandatory = $true)][string]$Arch)
$cacheDir = Resolve-CosignCacheDir
if ([string]::IsNullOrWhiteSpace($cacheDir)) {
return $null
}
$asset = "cosign-windows-$Arch.exe"
return Join-Path (Join-Path $cacheDir $CosignVersion) $asset
}
function Ensure-Cosign {
param(
[Parameter(Mandatory = $true)][string]$Arch,
[Parameter(Mandatory = $true)][string]$TempDir
)
$existing = Get-Command cosign -ErrorAction SilentlyContinue
if ($null -ne $existing -and $existing.Source) {
return $existing.Source
}
$asset = "cosign-windows-$Arch.exe"
$url = "https://github.com/sigstore/cosign/releases/download/$CosignVersion/$asset"
$cachedPath = Get-CachedCosignPath -Arch $Arch
if (-not [string]::IsNullOrWhiteSpace($cachedPath) -and (Test-Path $cachedPath)) {
$cachedInfo = Get-Item -LiteralPath $cachedPath -ErrorAction SilentlyContinue
if ($null -ne $cachedInfo -and $cachedInfo.Length -gt 0) {
Write-Log "Using cached cosign binary: $cachedPath"
return $cachedPath
}
Remove-Item -LiteralPath $cachedPath -Force -ErrorAction SilentlyContinue
}
$outFile = Join-Path $TempDir "$asset.download"
Write-Log "cosign not found; downloading $CosignVersion (windows/$Arch)"
Invoke-Download -Url $url -OutFile $outFile
if (-not [string]::IsNullOrWhiteSpace($cachedPath)) {
try {
New-Item -Path (Split-Path -Path $cachedPath -Parent) -ItemType Directory -Force | Out-Null
Copy-Item -Path $outFile -Destination $cachedPath -Force
Write-Log "Cached cosign binary: $cachedPath"
return $cachedPath
} catch {
Write-WarnMessage "Could not cache cosign binary: $($_.Exception.Message)"
}
}
return $outFile
}
function Verify-ChecksumsSignature {
param(
[Parameter(Mandatory = $true)][string]$Arch,
[Parameter(Mandatory = $true)][string]$TempDir,
[Parameter(Mandatory = $true)][string]$ChecksumsPath,
[Parameter(Mandatory = $true)][string]$SignaturePath,
[Parameter(Mandatory = $true)][string]$CertificatePath
)
if (-not (Test-Truthy $VerifySignaturesRaw)) {
Write-WarnMessage "Signature verification disabled via PROFILEX_VERIFY_SIGNATURES=0"
return
}
$cosignBin = Ensure-Cosign -Arch $Arch -TempDir $TempDir
& $cosignBin verify-blob `
--certificate $CertificatePath `
--signature $SignaturePath `
--certificate-identity-regexp $CosignIdentityRegex `
--certificate-oidc-issuer $CosignOidcIssuer `
$ChecksumsPath | Out-Null
if ($LASTEXITCODE -ne 0) {
Fail "Signature verification failed for checksums.txt"
}
}
function Invoke-Download {
param(
[Parameter(Mandatory = $true)][string]$Url,
[Parameter(Mandatory = $true)][string]$OutFile
)
try {
Invoke-WebRequest -Uri $Url -OutFile $OutFile -ErrorAction Stop
} catch {
$status = $null
$desc = $null
try {
if ($null -ne $_.Exception.Response) {
$status = [int]$_.Exception.Response.StatusCode
$desc = [string]$_.Exception.Response.StatusDescription
}
} catch {
$status = $null
}
if ($null -ne $status) {
Fail "Download failed ($status $desc): $Url"
}
Fail "Download failed: $Url ($($_.Exception.Message))"
}
}
function Get-LatestTag {
$api = "https://api.github.com/repos/$Repo/releases/latest"
try {
$release = Invoke-RestMethod -Uri $api
if ($null -ne $release -and $release.tag_name) {
return [string]$release.tag_name
}
} catch {
return $null
}
return $null
}
function New-TempDir {
$tempDir = Join-Path ([System.IO.Path]::GetTempPath()) ("profilex-install-" + [System.Guid]::NewGuid().ToString("N"))
New-Item -Path $tempDir -ItemType Directory -Force | Out-Null
return $tempDir
}
function Install-FromRelease {
param(
[Parameter(Mandatory = $true)][string]$ResolvedVersion,
[Parameter(Mandatory = $true)][string]$Arch
)
$verNoV = $ResolvedVersion.TrimStart("v")
$base = "https://github.com/$Repo/releases/download/$ResolvedVersion"
$assets = @(
@{ Name = "${BinaryBase}_${verNoV}_windows_${Arch}.zip"; Type = "zip" },
@{ Name = "${BinaryBase}_${verNoV}_windows_${Arch}.tar.gz"; Type = "tar.gz" }
)
$tempDir = New-TempDir
try {
try {
Write-Log "Trying GitHub release install: $ResolvedVersion (windows/$Arch)"
$checksumsPath = Join-Path $tempDir "checksums.txt"
$checksumsSigPath = Join-Path $tempDir "checksums.txt.sig"
$checksumsCertPath = Join-Path $tempDir "checksums.txt.pem"
Invoke-Download -Url "$base/checksums.txt" -OutFile $checksumsPath
if (Test-Truthy $VerifySignaturesRaw) {
Invoke-Download -Url "$base/checksums.txt.sig" -OutFile $checksumsSigPath
Invoke-Download -Url "$base/checksums.txt.pem" -OutFile $checksumsCertPath
Verify-ChecksumsSignature `
-Arch $Arch `
-TempDir $tempDir `
-ChecksumsPath $checksumsPath `
-SignaturePath $checksumsSigPath `
-CertificatePath $checksumsCertPath
} else {
Write-WarnMessage "Signature verification disabled via PROFILEX_VERIFY_SIGNATURES=0"
}
foreach ($asset in $assets) {
$assetPath = Join-Path $tempDir $asset.Name
$assetUrl = "$base/$($asset.Name)"
try {
Invoke-Download -Url $assetUrl -OutFile $assetPath
} catch {
continue
}
$expectedHash = Get-ExpectedChecksum -ChecksumsFile $checksumsPath -AssetName $asset.Name
if ([string]::IsNullOrWhiteSpace($expectedHash)) {
Fail "No checksum entry found for $($asset.Name)"
}
$actualHash = Get-FileSha256 -Path $assetPath
if ($expectedHash -ne $actualHash) {
Fail "Checksum mismatch for $($asset.Name)"
}
$extractDir = Join-Path $tempDir ("extract-" + $asset.Type.Replace(".", "-"))
New-Item -Path $extractDir -ItemType Directory -Force | Out-Null
if ($asset.Type -eq "zip") {
Expand-Archive -Path $assetPath -DestinationPath $extractDir -Force
} else {
if (-not (Get-Command tar -ErrorAction SilentlyContinue)) {
Write-WarnMessage "tar not found; cannot extract $($asset.Name)"
continue
}
& tar -xzf $assetPath -C $extractDir | Out-Null
}
$candidate = Get-ChildItem -Path $extractDir -Recurse -File |
Where-Object { $_.Name -ieq $BinaryName -or $_.Name -ieq $BinaryBase } |
Select-Object -First 1
if ($null -eq $candidate) {
continue
}
New-Item -Path $InstallDir -ItemType Directory -Force | Out-Null
$dest = Join-Path $InstallDir $BinaryName
Copy-Item -Path $candidate.FullName -Destination $dest -Force
Write-OwnershipMarker -BinaryPath $dest
Write-Log "Installed $BinaryName to $dest"
return $true
}
Write-WarnMessage "Release asset not found for windows/$Arch"
return $false
} catch {
Write-WarnMessage "Release install failed: $($_.Exception.Message)"
return $false
}
} finally {
Remove-Item -Path $tempDir -Recurse -Force -ErrorAction SilentlyContinue
}
}
function Install-WithGo {
param([Parameter(Mandatory = $true)][string]$RequestedVersion)
if (-not (Get-Command go -ErrorAction SilentlyContinue)) {
if (-not (Ensure-GoAvailable)) {
Fail "go is required for fallback install because no matching release binary was found. Install Go or publish a release tag (for example v0.1.0)."
}
}
Write-Log "Falling back to go install"
$pkgVersion = if ($RequestedVersion -eq "latest" -or [string]::IsNullOrWhiteSpace($RequestedVersion)) { "latest" } else { $RequestedVersion }
$env:GO111MODULE = "on"
& go install "$ModulePath@$pkgVersion"
if ($LASTEXITCODE -ne 0) {
Fail "go install failed"
}
$gobin = (& go env GOBIN).Trim()
if ([string]::IsNullOrWhiteSpace($gobin)) {
$gopath = (& go env GOPATH).Trim()
if ([string]::IsNullOrWhiteSpace($gopath)) {
Fail "Unable to resolve GOPATH from go env"
}
$gobin = Join-Path $gopath "bin"
}
$source = @(
(Join-Path $gobin $BinaryName),
(Join-Path $gobin $BinaryBase)
) | Where-Object { Test-Path $_ } | Select-Object -First 1
if ($null -eq $source) {
Fail "go install completed but binary not found in $gobin"
}
New-Item -Path $InstallDir -ItemType Directory -Force | Out-Null
$dest = Join-Path $InstallDir $BinaryName
Copy-Item -Path $source -Destination $dest -Force
Write-OwnershipMarker -BinaryPath $dest
Write-Log "Installed $BinaryName to $dest"
}
function Normalize-PathEntry {
param([string]$Entry)
if ([string]::IsNullOrWhiteSpace($Entry)) {
return ""
}
return $Entry.Trim().TrimEnd("\")
}
function Ensure-PathContainsInstallDir {
param([Parameter(Mandatory = $true)][string]$Dir)
if (-not (Test-Truthy $AutoPathRaw)) {
return
}
$normalizedDir = Normalize-PathEntry -Entry $Dir
$userPath = [Environment]::GetEnvironmentVariable("Path", "User")
$userEntries = @()
if (-not [string]::IsNullOrWhiteSpace($userPath)) {
$userEntries = $userPath -split ";"
}
$userHasDir = $false
foreach ($entry in $userEntries) {
if ((Normalize-PathEntry -Entry $entry) -ieq $normalizedDir) {
$userHasDir = $true
break
}
}
if (-not $userHasDir) {
$newUserPath = if ([string]::IsNullOrWhiteSpace($userPath)) { $Dir } else { "$userPath;$Dir" }
[Environment]::SetEnvironmentVariable("Path", $newUserPath, "User")
Write-Log "Added $Dir to User PATH"
} else {
Write-Log "User PATH already contains $Dir"
}
$sessionHasDir = $false
foreach ($entry in ($env:Path -split ";")) {
if ((Normalize-PathEntry -Entry $entry) -ieq $normalizedDir) {
$sessionHasDir = $true
break
}
}
if (-not $sessionHasDir) {
$env:Path = "$Dir;$env:Path"
Write-Log "Added $Dir to PATH for current PowerShell session"
}
}
function Main {
$arch = Get-Arch
$allowSourceFallback = Test-Truthy $AllowSourceFallbackRaw
$resolvedVersion = $Version
if ($Version -eq "latest") {
$latest = Get-LatestTag
if ([string]::IsNullOrWhiteSpace($latest)) {
if ($allowSourceFallback) {
Write-WarnMessage "Could not resolve latest release tag; using go install fallback"
$resolvedVersion = $null
} else {
Fail "Could not resolve latest release tag and source fallback is disabled (set PROFILEX_ALLOW_SOURCE_FALLBACK=1 to enable)."
}
} else {
$resolvedVersion = $latest
}
}
$installedFromRelease = $false
if (-not [string]::IsNullOrWhiteSpace($resolvedVersion) -and $resolvedVersion -ne "latest") {
$installedFromRelease = Install-FromRelease -ResolvedVersion $resolvedVersion -Arch $arch
}
if (-not $installedFromRelease) {
if ($allowSourceFallback) {
Write-WarnMessage "Release install failed; using go install fallback"
Install-WithGo -RequestedVersion $Version
} else {
Fail "Release install failed and source fallback is disabled (set PROFILEX_ALLOW_SOURCE_FALLBACK=1 to enable)."
}
}
Ensure-PathContainsInstallDir -Dir $InstallDir
if (-not (Get-Command $BinaryBase -ErrorAction SilentlyContinue)) {
Write-WarnMessage "$BinaryBase is installed but not currently available in this shell. Open a new terminal and try again."
}
Write-Log "Done"
Write-Log "Run: $BinaryBase --help"
}
Main