-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.ps1
More file actions
783 lines (717 loc) · 30.5 KB
/
install.ps1
File metadata and controls
783 lines (717 loc) · 30.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
# APM CLI Installer Script (Windows / PowerShell)
#
# Usage:
# irm https://aka.ms/apm-windows | iex
#
# Pin a version (skips GitHub HTTP API - use for air-gapped / GHE):
# $env:VERSION = 'v1.2.3'; irm https://aka.ms/apm-windows | iex
# .\install.ps1 v1.2.3
#
# Custom install location (directory that will contain apm.cmd):
# $env:APM_INSTALL_DIR = "$env:LOCALAPPDATA\Programs\apm\bin"; irm ... | iex
#
# Fork or private mirror:
# $env:APM_REPO = 'my-org/apm'; irm ... | iex
#
# GitHub Enterprise Server / mirror (set VERSION to avoid unreachable api.github.com):
# $env:GITHUB_URL = 'https://github.corp.com'
# $env:VERSION = 'v1.2.3'
# irm https://.../install.ps1 | iex
#
# Private repositories: set GITHUB_APM_PAT or GITHUB_TOKEN
#
# Pinned installs require a .sha256 sidecar unless you opt out:
# $env:APM_SKIP_CHECKSUM = '1' # or: .\install.ps1 v1.2.3 -SkipChecksum
param(
[Parameter(Position = 0)]
[string]$Version = $null,
# Prefer $env:APM_REPO; -Repo remains for direct script invocation.
[string]$Repo = "microsoft/apm",
[switch]$SkipChecksum
)
$ErrorActionPreference = "Stop"
$skipChecksum = $SkipChecksum -or ($env:APM_SKIP_CHECKSUM -eq '1')
# ---------------------------------------------------------------------------
# Configuration (overridable via environment variables - parity with install.sh)
# ---------------------------------------------------------------------------
$githubUrl = if ($env:GITHUB_URL) {
$env:GITHUB_URL.Trim().Trim('"').TrimEnd('/')
} else {
"https://github.com"
}
if ($githubUrl -notmatch '(?i)^https://') {
Write-Host "GITHUB_URL must use an https:// URL." -ForegroundColor Red
exit 1
}
$apmRepo = if ($env:APM_REPO) { $env:APM_REPO.Trim() } else { $Repo }
if ($apmRepo -notmatch '^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$') {
Write-Host "APM_REPO must be owner/name (letters, digits, ._- only)." -ForegroundColor Red
exit 1
}
$pinnedVersion = $null
if ($env:VERSION) {
$pinnedVersion = $env:VERSION.Trim().TrimStart('@')
} elseif ($Version) {
$pinnedVersion = $Version.Trim().TrimStart('@')
}
if ($pinnedVersion -and $pinnedVersion -notmatch '^v?[0-9]+\.[0-9]+') {
Write-Host "VERSION must look like a release tag (for example v1.2.3 or 1.2.3)." -ForegroundColor Red
exit 1
}
$defaultInstallRoot = Join-Path $env:LOCALAPPDATA "Programs\apm"
$defaultBinDir = Join-Path $defaultInstallRoot "bin"
if ($env:APM_INSTALL_DIR) {
$rawBinDir = $env:APM_INSTALL_DIR.Trim().TrimEnd('\', '/')
$binDir = [System.IO.Path]::GetFullPath($rawBinDir)
$parent = Split-Path $binDir -Parent
if ($parent) {
$installRoot = $parent
} else {
# Single-segment path: keep bundles next to the shim directory
$installRoot = $binDir
}
$releasesDir = Join-Path $installRoot "releases"
} else {
$installRoot = $defaultInstallRoot
$binDir = $defaultBinDir
$releasesDir = Join-Path $installRoot "releases"
}
$assetName = "apm-windows-x86_64.zip"
# ---------------------------------------------------------------------------
# Helper functions
# ---------------------------------------------------------------------------
function Get-GitHubApiRoot {
param([string]$Url)
$u = $Url.Trim().TrimEnd('/')
if ($u -match '(?i)^https://github\.com$') {
return "https://api.github.com"
}
return "$u/api/v3"
}
function Write-Info {
param([string]$Message)
Write-Host $Message -ForegroundColor Cyan
}
function Write-Success {
param([string]$Message)
Write-Host $Message -ForegroundColor Green
}
function Write-WarningText {
param([string]$Message)
Write-Host $Message -ForegroundColor Yellow
}
function Write-ErrorText {
param([string]$Message)
Write-Host $Message -ForegroundColor Red
}
function Get-AuthHeader {
# For GHES, use a PAT issued on that host (github.com tokens often will not work).
if ($env:GITHUB_APM_PAT) {
return @{ Authorization = "token $($env:GITHUB_APM_PAT)" }
}
if ($env:GITHUB_TOKEN) {
return @{ Authorization = "token $($env:GITHUB_TOKEN)" }
}
return @{}
}
function Invoke-GitHubJson {
param(
[string]$Uri,
[hashtable]$Headers
)
if ($Headers.Count -gt 0) {
return Invoke-RestMethod -Uri $Uri -Headers $Headers
}
return Invoke-RestMethod -Uri $Uri
}
function Add-ToUserPath {
param([string]$PathEntry)
$currentUserPath = [Environment]::GetEnvironmentVariable("Path", "User")
$userEntries = @()
if ($currentUserPath) {
$userEntries = $currentUserPath.Split(";", [System.StringSplitOptions]::RemoveEmptyEntries)
}
if ($userEntries -notcontains $PathEntry) {
$newUserPath = if ($currentUserPath) { "$PathEntry;$currentUserPath" } else { $PathEntry }
[Environment]::SetEnvironmentVariable("Path", $newUserPath, "User")
Write-Info "Added $PathEntry to your user PATH."
}
if (($env:Path -split ";") -notcontains $PathEntry) {
$env:Path = "$PathEntry;$env:Path"
}
}
function Test-PythonRequirement {
foreach ($cmd in @("python3", "python")) {
$exe = Get-Command $cmd -ErrorAction SilentlyContinue
if ($exe) {
try {
$verStr = & $cmd -c "import sys; print('.'.join(map(str, sys.version_info[:2])))" 2>$null
if ($verStr) {
$parts = $verStr.Split('.')
$major = [int]$parts[0]
$minor = [int]$parts[1]
if ($major -gt 3 -or ($major -eq 3 -and $minor -ge 9)) {
return $cmd
}
}
} catch {
}
}
}
return $null
}
function Install-ViaPip {
$pythonCmd = Test-PythonRequirement
if (-not $pythonCmd) {
Write-ErrorText "Python 3.9+ is not available - cannot fall back to pip."
return $false
}
Write-Info "Attempting installation via pip ($pythonCmd)..."
$pipCmd = $null
foreach ($candidate in @("pip3", "pip")) {
if (Get-Command $candidate -ErrorAction SilentlyContinue) {
$pipCmd = $candidate
break
}
}
if (-not $pipCmd) {
$pipCmd = "$pythonCmd -m pip"
}
try {
if ($pipCmd -like "* -m pip") {
$output = & $pythonCmd -m pip install --user apm-cli 2>&1
$pipExitCode = $LASTEXITCODE
$output | Write-Host
} else {
$output = & $pipCmd install --user apm-cli 2>&1
$pipExitCode = $LASTEXITCODE
$output | Write-Host
}
if ($pipExitCode -ne 0) {
Write-ErrorText "pip install failed (exit code $pipExitCode)."
return $false
}
} catch {
Write-ErrorText "pip install failed: $_"
return $false
}
$apmExe = Get-Command apm -ErrorAction SilentlyContinue
if ($apmExe) {
$ver = & apm --version 2>$null
Write-Success "APM installed successfully via pip! Version: $ver"
Write-Info "Location: $($apmExe.Source)"
} else {
Write-WarningText "APM installed but not found in PATH."
Write-Host "You may need to add your Python user scripts directory to PATH."
}
return $true
}
function Write-ManualInstallHelp {
param(
[string]$GithubUrl,
[string]$ApmRepo
)
Write-Host ""
Write-Info "Manual installation options:"
Write-Host " 1. pip (recommended): pip install --user apm-cli"
Write-Host " 2. From source:"
Write-Host " git clone $GithubUrl/${ApmRepo}.git"
Write-Host " cd apm && uv sync && uv run pip install -e ."
Write-Host ""
Write-Host "Need help? Create an issue at: $GithubUrl/$ApmRepo/issues"
}
function Get-Sha256Hex {
# Stream-based SHA256 that works even when Get-FileHash is unavailable
# (hardened hosts, $PSModuleAutoLoadingPreference='None', restricted sessions).
# System.Security.Cryptography is a core .NET type allowed in ConstrainedLanguage.
param([string]$Path)
$cmd = Get-Command Get-FileHash -ErrorAction SilentlyContinue
if (-not $cmd) {
try {
Import-Module Microsoft.PowerShell.Utility -ErrorAction Stop
$cmd = Get-Command Get-FileHash -ErrorAction SilentlyContinue
} catch {
}
}
if ($cmd) {
return (Get-FileHash -Path $Path -Algorithm SHA256).Hash.ToLower()
}
$stream = $null
$hasher = $null
try {
$stream = [System.IO.File]::OpenRead($Path)
$hasher = [System.Security.Cryptography.SHA256]::Create()
$bytes = $hasher.ComputeHash($stream)
$sb = New-Object System.Text.StringBuilder
foreach ($b in $bytes) { [void]$sb.Append($b.ToString("x2")) }
return $sb.ToString()
} finally {
if ($hasher) { $hasher.Dispose() }
if ($stream) { $stream.Dispose() }
}
}
function Test-AccessDeniedError {
# AppLocker / WDAC / App Control for Business / SRP / Group Policy deny
# CreateProcess on EXEs under user-writable paths (e.g. %TEMP%,
# %LOCALAPPDATA%\Temp) with one of:
# 0x80070005 (E_ACCESSDENIED, Win32 5) -> "Access is denied"
# 0x800704EC (ERROR_ACCESS_DISABLED_BY_POLICY, -> "This program is
# Win32 1260) blocked by group policy"
# Both belong in the AppControl/AppLocker guidance bucket.
param([string]$Text)
if (-not $Text) { return $false }
return (
$Text -match 'Access is denied' -or
$Text -match 'blocked by group policy' -or
$Text -match '0x80070005' -or
$Text -match '0x800704EC'
)
}
function Test-AntivirusBlockError {
# Defender / 3rd-party AV real-time protection blocks CreateProcess on
# binaries it flags with HRESULT 0x800700E1 (ERROR_VIRUS_INFECTED,
# Win32 225) or 0x800700E2 (ERROR_VIRUS_DELETED, Win32 226). PowerShell
# surfaces these as "Operation did not complete successfully because
# the file contains a virus or potentially unwanted software". Our
# PyInstaller-built apm.exe is unsigned, which routinely trips
# false-positive heuristics.
param([string]$Text)
if (-not $Text) { return $false }
return (
$Text -match 'contains a virus' -or
$Text -match 'potentially unwanted software' -or
$Text -match '0x800700E1' -or
$Text -match '0x800700E2'
)
}
function Write-AppControlGuidance {
param(
[string]$Path,
[string]$TargetInstallDir
)
Write-Host ""
Write-ErrorText "The OS denied execution of $Path."
Write-Host "This is the standard signature of an enterprise application control policy"
Write-Host "(AppLocker or App Control for Business / WDAC) denying an unsigned binary"
Write-Host "from a user-writable path."
Write-Host ""
Write-Info "Options to unblock:"
if ($TargetInstallDir) {
Write-Host " 1. Ask your endpoint admin to allow-list the final install path"
Write-Host " ($TargetInstallDir) via an AppLocker/WDAC Path or Publisher rule."
} else {
Write-Host " 1. Ask your endpoint admin to allow-list apm.exe via an"
Write-Host " AppLocker/WDAC Path or Publisher rule."
}
Write-Host " 2. Set APM_TEMP_DIR to a directory your policy permits, then retry:"
Write-Host " `$env:APM_TEMP_DIR = `"`$env:LOCALAPPDATA\Programs\apm\tmp`""
Write-Host " 3. Install via pip into your user site:"
Write-Host " pip install --user apm-cli"
Write-Host ""
}
function Write-AntivirusGuidance {
param(
[string]$Path,
[string]$TargetInstallDir
)
Write-Host ""
Write-ErrorText "An antivirus product blocked execution of $Path."
Write-Host "Windows Defender (or another real-time scanner) flagged the binary."
Write-Host "The apm.exe release is built with PyInstaller and is currently"
Write-Host "unsigned, which routinely trips false-positive heuristics on"
Write-Host "unsigned binaries. Most blocks of apm.exe are false positives, but"
Write-Host "you should verify integrity before excluding it:"
Write-Host ""
Write-Host " 1. Verify the SHA256 of apm.exe against the published .sha256"
Write-Host " sidecar on the release page before adding any AV exclusion."
Write-Host " Do not exclude a binary whose checksum you have not verified."
Write-Host ""
Write-Info "If the checksum matches, options to unblock:"
if ($TargetInstallDir) {
# Single-quote-escape the path so the printed command stays valid
# even if the install directory contains a "'" character (rare but
# possible in usernames).
$escapedDir = $TargetInstallDir -replace "'", "''"
Write-Host " a. Add a Defender exclusion for the install directory (run in"
Write-Host " an elevated PowerShell, then rerun this installer):"
Write-Host " Add-MpPreference -ExclusionPath '$escapedDir'"
} else {
Write-Host " a. Add a Defender exclusion for apm.exe (run in an elevated"
Write-Host " PowerShell, then rerun this installer):"
Write-Host " Add-MpPreference -ExclusionProcess 'apm.exe'"
}
Write-Host " b. Install via pip into your user site (avoids the binary entirely):"
Write-Host " pip install --user apm-cli"
Write-Host " c. Help us get the false positive cleared by submitting the binary"
Write-Host " to Microsoft: https://www.microsoft.com/en-us/wdsi/filesubmission"
Write-Host ""
}
# ---------------------------------------------------------------------------
# Banner
# ---------------------------------------------------------------------------
Write-Host ""
Write-Host "===========================================================" -ForegroundColor Blue
Write-Host " APM Installer " -ForegroundColor Blue
Write-Host " The NPM for AI-Native Development " -ForegroundColor Blue
Write-Host "===========================================================" -ForegroundColor Blue
Write-Host ""
$apiRoot = Get-GitHubApiRoot -Url $githubUrl
$headers = @{}
# ---------------------------------------------------------------------------
# Stage 1 - Release metadata (skip GitHub API when VERSION is pinned)
# ---------------------------------------------------------------------------
$release = $null
$asset = $null
$tagName = $null
if ($pinnedVersion) {
$tagName = $pinnedVersion
Write-Success "Version: $tagName (pinned - skipping releases/latest API)"
} else {
Write-Info "Fetching latest release information..."
$latestUri = "$apiRoot/repos/$apmRepo/releases/latest"
try {
$release = Invoke-RestMethod -Uri $latestUri
} catch {
}
if (-not $release -or -not $release.tag_name) {
Write-Info "Unauthenticated request failed or returned no data. Retrying with authentication..."
$headers = Get-AuthHeader
if ($headers.Count -eq 0) {
Write-ErrorText "Repository may be private but no authentication token found."
Write-Host "Set GITHUB_APM_PAT or GITHUB_TOKEN and retry."
Write-ManualInstallHelp -GithubUrl $githubUrl -ApmRepo $apmRepo
exit 1
}
try {
$release = Invoke-GitHubJson -Uri $latestUri -Headers $headers
} catch {
Write-ErrorText "Failed to fetch release information: $_"
Write-ManualInstallHelp -GithubUrl $githubUrl -ApmRepo $apmRepo
exit 1
}
}
if (-not $release.tag_name) {
Write-ErrorText "Could not determine the latest release tag."
Write-ManualInstallHelp -GithubUrl $githubUrl -ApmRepo $apmRepo
exit 1
}
$tagName = $release.tag_name
$asset = $release.assets | Where-Object { $_.name -eq $assetName } | Select-Object -First 1
if (-not $asset) {
Write-ErrorText "Release $tagName does not contain $assetName."
Write-ManualInstallHelp -GithubUrl $githubUrl -ApmRepo $apmRepo
exit 1
}
Write-Success "Latest version: $tagName"
}
$releaseDir = Join-Path $releasesDir $tagName
$tempDir = Join-Path ([System.IO.Path]::GetTempPath()) ("apm-install-" + [System.Guid]::NewGuid().ToString("N"))
$zipPath = Join-Path $tempDir $assetName
New-Item -ItemType Directory -Force -Path $tempDir | Out-Null
New-Item -ItemType Directory -Force -Path $binDir | Out-Null
New-Item -ItemType Directory -Force -Path $releasesDir | Out-Null
try {
# ------------------------------------------------------------------
# Stage 2 - Download binary
# ------------------------------------------------------------------
Write-Info "Downloading $assetName ($tagName)..."
$downloadOk = $false
$directUrl = "$githubUrl/$apmRepo/releases/download/$tagName/$assetName"
if ($pinnedVersion) {
$pinDownloadErr = $null
try {
Invoke-WebRequest -Uri $directUrl -OutFile $zipPath -UseBasicParsing
$downloadOk = $true
Write-Success "Download successful"
} catch {
$pinDownloadErr = $_.Exception.Message
Write-WarningText "Unauthenticated download failed, retrying with authentication..."
}
if (-not $downloadOk) {
if ($headers.Count -eq 0) { $headers = Get-AuthHeader }
if ($headers.Count -eq 0) {
Write-ErrorText "Repository may be private but no authentication token found."
Write-Host "Set GITHUB_APM_PAT or GITHUB_TOKEN and retry."
if ($pinDownloadErr) {
Write-Host "Details: $pinDownloadErr"
}
Write-ManualInstallHelp -GithubUrl $githubUrl -ApmRepo $apmRepo
exit 1
}
try {
Invoke-WebRequest -Uri $directUrl -Headers $headers -OutFile $zipPath -UseBasicParsing
$downloadOk = $true
Write-Success "Download successful with authentication"
} catch {
Write-WarningText "Authenticated download failed: $($_.Exception.Message)"
}
}
} else {
try {
Invoke-WebRequest -Uri $asset.browser_download_url -OutFile $zipPath -UseBasicParsing
$downloadOk = $true
Write-Success "Download successful"
} catch {
Write-WarningText "Unauthenticated download failed, retrying with authentication..."
}
if (-not $downloadOk) {
if ($headers.Count -eq 0) { $headers = Get-AuthHeader }
if ($headers.Count -gt 0 -and $asset.url) {
try {
$apiHeaders = @{} + $headers
$apiHeaders["Accept"] = "application/octet-stream"
Invoke-WebRequest -Uri $asset.url -Headers $apiHeaders -OutFile $zipPath -UseBasicParsing
$downloadOk = $true
Write-Success "Download successful via GitHub API"
} catch {
Write-WarningText "API download failed, trying direct URL with auth..."
}
}
}
if (-not $downloadOk) {
if ($headers.Count -eq 0) { $headers = Get-AuthHeader }
if ($headers.Count -gt 0) {
try {
Invoke-WebRequest -Uri $asset.browser_download_url -Headers $headers -OutFile $zipPath -UseBasicParsing
$downloadOk = $true
Write-Success "Download successful with authentication"
} catch {
}
}
}
}
if (-not $downloadOk) {
Write-ErrorText "All download attempts failed."
Write-Host "Direct URL was: $directUrl"
Write-Host "This might mean:"
Write-Host " - Network connectivity issues"
Write-Host " - Invalid GitHub token or insufficient permissions"
Write-Host " - Private repository requires authentication"
Write-Host ""
Write-Info "Attempting automatic fallback to pip..."
if (Install-ViaPip) { exit 0 }
Write-ManualInstallHelp -GithubUrl $githubUrl -ApmRepo $apmRepo
exit 1
}
# ------------------------------------------------------------------
# Verify checksum (pinned installs require .sha256 unless skipped)
# ------------------------------------------------------------------
$sha256AssetName = "$assetName.sha256"
$sha256Url = "$githubUrl/$apmRepo/releases/download/$tagName/$sha256AssetName"
$sha256Source = $null
if (-not $pinnedVersion) {
$shaObj = $release.assets | Where-Object { $_.name -eq $sha256AssetName } | Select-Object -First 1
if ($shaObj) { $sha256Source = $shaObj }
}
$checksumRequired = [bool]($pinnedVersion -and -not $skipChecksum)
if ($skipChecksum -and $pinnedVersion) {
Write-WarningText "Skipping checksum verification (APM_SKIP_CHECKSUM or -SkipChecksum)."
} elseif ($sha256Source -or $pinnedVersion) {
Write-Info "Verifying download checksum..."
$sha256Path = Join-Path $tempDir $sha256AssetName
$fetched = $false
try {
if ($sha256Source) {
try {
Invoke-WebRequest -Uri $sha256Source.browser_download_url -OutFile $sha256Path -UseBasicParsing
$fetched = $true
} catch {
Write-WarningText "Unauthenticated checksum download failed, retrying with authentication..."
if ($headers.Count -eq 0) { $headers = Get-AuthHeader }
if ($headers.Count -eq 0) { throw }
try {
Invoke-WebRequest -Uri $sha256Source.browser_download_url -Headers $headers -OutFile $sha256Path -UseBasicParsing
$fetched = $true
} catch {
if (-not $sha256Source.url) { throw }
$apiHeaders = @{} + $headers
$apiHeaders["Accept"] = "application/octet-stream"
Invoke-WebRequest -Uri $sha256Source.url -Headers $apiHeaders -OutFile $sha256Path -UseBasicParsing
$fetched = $true
}
}
} else {
try {
Invoke-WebRequest -Uri $sha256Url -OutFile $sha256Path -UseBasicParsing
$fetched = $true
} catch {
if ($headers.Count -eq 0) { $headers = Get-AuthHeader }
if ($headers.Count -gt 0) {
Invoke-WebRequest -Uri $sha256Url -Headers $headers -OutFile $sha256Path -UseBasicParsing
$fetched = $true
} else {
throw
}
}
}
} catch {
if ($checksumRequired) {
Write-ErrorText "Could not download checksum file for pinned install."
Write-Host "$_"
Write-Host "Expected: $sha256Url"
Write-Host "To bypass integrity verification (emergency only), set APM_SKIP_CHECKSUM=1 or pass -SkipChecksum."
Write-ManualInstallHelp -GithubUrl $githubUrl -ApmRepo $apmRepo
exit 1
}
Write-WarningText "Could not download checksum file (non-fatal): $_"
}
if ($checksumRequired -and -not $fetched) {
Write-ErrorText "Pinned install requires the release .sha256 file next to the zip."
Write-Host "Expected: $sha256Url"
Write-Host "To bypass integrity verification (emergency only), set APM_SKIP_CHECKSUM=1 or pass -SkipChecksum."
Write-ManualInstallHelp -GithubUrl $githubUrl -ApmRepo $apmRepo
exit 1
}
if ($fetched -and (Test-Path $sha256Path)) {
try {
$expectedHash = (Get-Content $sha256Path -Raw).Trim().Split(" ")[0]
$actualHash = Get-Sha256Hex -Path $zipPath
if ($actualHash -ne $expectedHash) {
Write-ErrorText "Checksum verification FAILED."
Write-Host " Expected: $expectedHash"
Write-Host " Actual: $actualHash"
Write-Info "Attempting automatic fallback to pip..."
if (Install-ViaPip) { exit 0 }
Write-ManualInstallHelp -GithubUrl $githubUrl -ApmRepo $apmRepo
exit 1
}
Write-Success "Checksum verified"
} catch {
if ($checksumRequired) {
Write-ErrorText "Checksum verification failed: $_"
Write-ManualInstallHelp -GithubUrl $githubUrl -ApmRepo $apmRepo
exit 1
}
Write-WarningText "Could not verify checksum (non-fatal): $_"
}
} elseif ($checksumRequired) {
Write-ErrorText "Checksum file missing after download."
Write-Host "Expected: $sha256Url"
Write-ManualInstallHelp -GithubUrl $githubUrl -ApmRepo $apmRepo
exit 1
}
}
# ------------------------------------------------------------------
# Extract + stage + binary test + promote
#
# Order matters: AppLocker / App Control for Business commonly block
# executable launch from %TEMP%. We move the extracted bundle to the
# final per-user install root ($releasesDir, default
# %LOCALAPPDATA%\Programs\apm\releases\<tag>) BEFORE invoking
# apm.exe --version, so the binary test runs from the allow-listed
# path that the shim will keep pointing at. Until promotion succeeds
# we stage to a sibling `.new-<guid>` directory so a failed install
# never destroys the currently working release. See issue #1389.
# ------------------------------------------------------------------
Write-Info "Extracting package..."
Expand-Archive -Path $zipPath -DestinationPath $tempDir -Force
$packageDir = Join-Path $tempDir "apm-windows-x86_64"
if (-not (Test-Path $packageDir)) {
Write-ErrorText "Extracted package is missing the apm-windows-x86_64 directory."
Write-Info "Attempting automatic fallback to pip..."
if (Install-ViaPip) { exit 0 }
Write-ManualInstallHelp -GithubUrl $githubUrl -ApmRepo $apmRepo
exit 1
}
$stagingDir = "$releaseDir.new-" + [System.Guid]::NewGuid().ToString("N")
if (Test-Path $stagingDir) {
Remove-Item -Recurse -Force $stagingDir
}
try {
Move-Item -Path $packageDir -Destination $stagingDir -Force
} catch {
$stageError = "$_"
Write-ErrorText "Failed to stage release at ${stagingDir}: $stageError"
if (Test-AccessDeniedError -Text $stageError) {
Write-AppControlGuidance -Path $stagingDir -TargetInstallDir $releaseDir
}
Write-Info "Attempting automatic fallback to pip..."
if (Install-ViaPip) { exit 0 }
Write-ManualInstallHelp -GithubUrl $githubUrl -ApmRepo $apmRepo
exit 1
}
$stagedExe = Join-Path $stagingDir "apm.exe"
if (-not (Test-Path $stagedExe)) {
Write-ErrorText "Staged package is missing apm.exe."
Remove-Item -Recurse -Force $stagingDir -ErrorAction SilentlyContinue
Write-Info "Attempting automatic fallback to pip..."
if (Install-ViaPip) { exit 0 }
Write-ManualInstallHelp -GithubUrl $githubUrl -ApmRepo $apmRepo
exit 1
}
Write-Info "Testing binary..."
$testFailure = $null
try {
$testOutput = & $stagedExe --version 2>&1
if ($LASTEXITCODE -ne 0) { throw "exit code $LASTEXITCODE - $testOutput" }
Write-Success "Binary test successful: $testOutput"
} catch {
$testFailure = "$_"
}
if ($testFailure) {
$denied = Test-AccessDeniedError -Text $testFailure
$avBlocked = Test-AntivirusBlockError -Text $testFailure
Write-ErrorText "Downloaded binary failed to run: $testFailure"
if ($avBlocked) {
Write-AntivirusGuidance -Path $stagedExe -TargetInstallDir $releaseDir
} elseif ($denied) {
Write-AppControlGuidance -Path $stagedExe -TargetInstallDir $releaseDir
}
Remove-Item -Recurse -Force $stagingDir -ErrorAction SilentlyContinue
Write-Info "Attempting automatic fallback to pip..."
if (Install-ViaPip) { exit 0 }
Write-ManualInstallHelp -GithubUrl $githubUrl -ApmRepo $apmRepo
exit 1
}
# Promote: rename the existing release aside, then rename the staged
# tree into place. Win32 has no truly atomic directory replacement, so
# there is still a small gap where neither path exists; doing it this
# way minimizes that gap and lets us roll back if the second rename
# fails. Concurrent apm invocations during that window will fail and
# need a retry — acceptable for an install/self-update operation.
$backupDir = $null
if (Test-Path $releaseDir) {
$backupDir = "$releaseDir.old-" + [System.Guid]::NewGuid().ToString("N")
try {
Move-Item -Path $releaseDir -Destination $backupDir -Force
} catch {
Write-ErrorText "Failed to move existing release aside: $_"
Remove-Item -Recurse -Force $stagingDir -ErrorAction SilentlyContinue
Write-ManualInstallHelp -GithubUrl $githubUrl -ApmRepo $apmRepo
exit 1
}
}
try {
Move-Item -Path $stagingDir -Destination $releaseDir -Force
} catch {
Write-ErrorText "Failed to promote staged release: $_"
if ($backupDir -and (Test-Path $backupDir)) {
Move-Item -Path $backupDir -Destination $releaseDir -Force -ErrorAction SilentlyContinue
}
Remove-Item -Recurse -Force $stagingDir -ErrorAction SilentlyContinue
Write-ManualInstallHelp -GithubUrl $githubUrl -ApmRepo $apmRepo
exit 1
}
if ($backupDir -and (Test-Path $backupDir)) {
Remove-Item -Recurse -Force $backupDir -ErrorAction SilentlyContinue
}
$shimPath = Join-Path $binDir "apm.cmd"
$shimContent = "@echo off`r`n`"$releaseDir\apm.exe`" %*`r`n"
Set-Content -Path $shimPath -Value $shimContent -Encoding ASCII
Add-ToUserPath -PathEntry $binDir
Write-Host ""
Write-Success "APM $tagName installed successfully!"
Write-Info "Command shim: $shimPath"
Write-Host ""
Write-Info "Quick start:"
Write-Host " apm init my-app # Create a new APM project"
Write-Host " cd my-app && apm install # Install dependencies"
Write-Host " apm run # Run your first prompt"
Write-Host ""
Write-Host "Documentation: $githubUrl/$apmRepo"
Write-Info "Run 'apm --version' in a new terminal to verify the installation."
} finally {
if (Test-Path $tempDir) {
Remove-Item -Recurse -Force $tempDir
}
}