Files
WhatIDo/install-whatido-cert.ps1
T

181 lines
7.4 KiB
PowerShell
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Script: install-whatido-cert.ps1
# Импортирует самоподписанный сертификат WhatIDo в локальное хранилище
# "Доверенные корневые центры сертификации" (Root), чтобы браузер перестал
# показывать предупреждение о небезопасном подключении.
#
# Обычный запуск — двойной клик по install-whatido-cert.cmd в этой же папке.
# Из PowerShell:
# .\install-whatido-cert.ps1
# .\install-whatido-cert.ps1 -StoreLocation CurrentUser
# .\install-whatido-cert.ps1 -CheckHost 192.168.88.55
# Удаление:
# .\install-whatido-cert.ps1 -Uninstall
param(
[ValidateSet('LocalMachine', 'CurrentUser', IgnoresCase = $false)]
[string] $StoreLocation = 'LocalMachine',
[string] $CertPath = '',
[string] $CertUrl = 'http://127.0.0.1:3003/certs/cert.pem',
[string] $CheckHost = '',
[switch] $Uninstall
)
$ErrorActionPreference = 'Stop'
$storePath = "Cert:\$StoreLocation\Root"
function ConvertFrom-PemToDer([byte[]] $Bytes) {
$text = [System.Text.Encoding]::ASCII.GetString($Bytes)
if ($text -notmatch '-----BEGIN CERTIFICATE-----') { return $Bytes }
$body = ($text -split "`r?`n" | Where-Object { $_ -and $_ -notmatch '-----' }) -join ''
return [Convert]::FromBase64String($body.Trim())
}
function Get-SanValues($Cert) {
$ext = $Cert.Extensions | Where-Object { $_.Oid.FriendlyName -eq 'Subject Alternative Name' }
if (-not $ext) { return @() }
return @($ext.Format($false) -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ })
}
function Get-HostInSan($Cert, [string] $HostName) {
if (-not $HostName) { return $null }
$h = $HostName.Trim()
foreach ($s in (Get-SanValues $Cert)) {
$v = ($s -split ':', 2)[1]
if ($null -eq $v) { continue }
if ($v -ieq $h) { return $s }
}
return $null
}
if (-not (Test-Path $storePath)) {
Write-Error "Хранилище не найдено: $storePath"
exit 1
}
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store('Root', $StoreLocation)
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
if ($Uninstall) {
$targets = @($store.Certificates | Where-Object { $_.Subject -match 'whatido' })
if (-not $targets) {
Write-Host "В хранилище $storePath нет сертификатов WhatIDo." -ForegroundColor Green
} else {
foreach ($t in $targets) {
$store.Remove($t)
Write-Host "Удалён: $($t.Subject)" -ForegroundColor Yellow
}
}
$store.Close()
Write-Host "Готово. Перезапустите браузер." -ForegroundColor Cyan
exit 0
}
# --- 1. Получаем сертификат: файл рядом со скриптом, потом - загрузка по URL ---
$bytes = $null
$source = ''
if ($CertPath) {
if (-not (Test-Path $CertPath)) { Write-Error "Файл не найден: $CertPath"; $store.Close(); exit 1 }
$bytes = [System.IO.File]::ReadAllBytes((Resolve-Path $CertPath))
$source = $CertPath
} else {
$here = $PSScriptRoot
if (-not $here) { $here = Split-Path -Parent $MyInvocation.MyCommand.Path }
foreach ($name in @('whatido-cert.cer', 'whatido-cert.pem', 'cert.pem')) {
$candidate = Join-Path $here $name
if (Test-Path $candidate) {
$bytes = [System.IO.File]::ReadAllBytes($candidate)
$source = $candidate
break
}
}
if (-not $bytes) {
Write-Host "Рядом со скриптом сертификата нет, скачиваем из $CertUrl" -ForegroundColor Cyan
try {
$dl = Invoke-WebRequest -Uri $CertUrl -UseBasicParsing -TimeoutSec 30
$bytes = [byte[]] $dl.Content
if ($bytes.Length -ge 2 -and [char] $bytes[0] -eq '{') { $bytes = [System.Text.Encoding]::UTF8.GetBytes($dl.Content) }
$source = $CertUrl
} catch {
Write-Error "Не удалось скачать сертификат: $_"
$store.Close()
exit 1
}
}
}
$bytes = ConvertFrom-PemToDer $bytes
if (-not $bytes -or $bytes.Length -lt 100) {
Write-Error "Полученные данные не похожи на сертификат (источник: $source)"
$store.Close()
exit 1
}
# --- 2. Показываем, что именно ставим ---
try {
$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($bytes)
} catch {
Write-Error "Не удалось разобрать сертификат: $_"
$store.Close()
exit 1
}
Write-Host "Источник: $source" -ForegroundColor Cyan
Write-Host "Тема: $($cert.Subject)" -ForegroundColor Yellow
Write-Host "Издатель: $($cert.Issuer)" -ForegroundColor Yellow
Write-Host "Срок: $($cert.NotBefore) - $($cert.NotAfter)" -ForegroundColor Yellow
Write-Host "Отпечаток: $($cert.Thumbprint)" -ForegroundColor DarkGray
$san = @(Get-SanValues $cert)
Write-Host "Адреса в сертификате: $($san.Count)" -ForegroundColor Yellow
foreach ($s in ($san | Select-Object -First 12)) { Write-Host " $s" -ForegroundColor DarkGray }
if ($san.Count -gt 12) { Write-Host " ... и ещё $($san.Count - 12)" -ForegroundColor DarkGray }
if ($cert.Subject -match 'whatido' -and $cert.Issuer -ne $cert.Subject) {
Write-Warning "Сертификат выпущен не самим собой. Продолжайте, только если доверяете его издателю."
}
if ($CheckHost) {
$hit = Get-HostInSan $cert $CheckHost
if ($hit) {
Write-Host "Адрес $CheckHost покрыт сертификатом ($hit) - предупреждение браузера исчезнет." -ForegroundColor Green
} else {
Write-Warning "Адрес $CheckHost НЕ входит в сертификат. После установки предупреждение останется. Добавьте адрес в CERT_HOSTNAMES в .env и пересоздайте сертификат."
}
}
# --- 3. Идемпотентность: если такой сертификат уже есть - ничего не делаем ---
$existing = $store.Certificates | Where-Object { $_.Thumbprint -eq $cert.Thumbprint }
if ($existing) {
Write-Host "Сертификат уже установлен в $storePath" -ForegroundColor Green
$store.Close()
Write-Host "Перезапустите браузер." -ForegroundColor Cyan
exit 0
}
# --- 4. Импорт ---
try {
$store.Add($cert)
} catch {
Write-Error "Не удалось добавить сертификат: $_"
$store.Close()
exit 1
}
Write-Host "Сертификат добавлен в хранилище $storePath" -ForegroundColor Green
# --- 5. Итог ---
Write-Host "Теперь в хранилище:" -ForegroundColor Cyan
$store.Certificates |
Where-Object { $_.NotAfter -gt (Get-Date) -and $_.Subject -match 'whatido' } |
Select-Object -First 5 Subject, NotAfter, Thumbprint |
Format-Table -AutoSize
$store.Close()
Write-Host "Перезапустите браузер полностью и откройте приложение по адресу из сертификата." -ForegroundColor Cyan
Write-Host "Откат: .\install-whatido-cert.ps1 -Uninstall" -ForegroundColor Gray