feat(tls): self-signed certificate generation, Windows installer and settings UI
This commit is contained in:
+153
-62
@@ -1,59 +1,57 @@
|
||||
# Script: install-whatido-cert.ps1
|
||||
# Назначение: скачивает самоподписанный сертификат WhatIDo и импортирует его в
|
||||
# локальное хранилище "Доверенные корневые центры сертификации" (LocalMachine\Root).
|
||||
# После перезапуска браузера (или повторного подключения) предупреждение о
|
||||
# самоподписанном сертификате исчезает.
|
||||
# Импортирует самоподписанный сертификат WhatIDo в локальное хранилище
|
||||
# "Доверенные корневые центры сертификации" (Root), чтобы браузер перестал
|
||||
# показывать предупреждение о небезопасном подключении.
|
||||
#
|
||||
# Запуск (от имени администратора):
|
||||
# Обычный запуск — двойной клик по install-whatido-cert.cmd в этой же папке.
|
||||
# Из PowerShell:
|
||||
# .\install-whatido-cert.ps1
|
||||
#
|
||||
# Или удаленно / по URL:
|
||||
# .\install-whatido-cert.ps1 -Url 'http://192.168.88.100:3003/certs/cert.pem'
|
||||
# .\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] $CertUrl = 'http://127.0.0.1:3003/certs/cert.pem'
|
||||
[string] $CertPath = '',
|
||||
|
||||
[string] $CertUrl = 'http://127.0.0.1:3003/certs/cert.pem',
|
||||
|
||||
[string] $CheckHost = '',
|
||||
|
||||
[switch] $Uninstall
|
||||
)
|
||||
|
||||
# Путь, куда временно сохранится сертификат
|
||||
$TempCert = [System.IO.Path]::GetTempFileName() + '.cer'
|
||||
trap {
|
||||
if (Test-Path $TempCert) { Remove-Item -Force $TempCert -ErrorAction SilentlyContinue }
|
||||
}
|
||||
|
||||
# --- 1. Скачиваем сертификат ---
|
||||
Write-Host "Скачивание сертификата из: $CertUrl" -ForegroundColor Cyan
|
||||
|
||||
try {
|
||||
$bytes = Invoke-WebRequest -Uri $CertUrl -UseBasicParsing -TimeoutSec 30 -ErrorAction Stop
|
||||
$bytes.Content | Out-File -FilePath $TempCert -Encoding Byte -Force
|
||||
Write-Host "Сертификат сохранён во временный файл: $TempCert" -ForegroundColor Green
|
||||
}
|
||||
catch {
|
||||
Write-Error "Не удалось скачать сертификат: $_"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# --- 2. Проверяем, что файл — это X.509 сертификат ---
|
||||
$certContent = [System.IO.File]::ReadAllBytes($TempCert)
|
||||
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certContent)
|
||||
|
||||
Write-Host "Сертификат: $($cert.Subject)" -ForegroundColor Yellow
|
||||
Write-Host "Выдан: $($cert.Issuer)" -ForegroundColor Yellow
|
||||
Write-Host "Срок действия: от $($cert.NotBefore) до $($cert.NotAfter)" -ForegroundColor Yellow
|
||||
Write-Host "Кол-во IP в SAN: $($cert.Extensions | Where-Object { $_.Oid.FriendlyName -eq 'Subject Alternative Name' } | ForEach-Object { $_.Format($true) -split ',' } | Measure-Object). IP-адресов в сертификате" -ForegroundColor Yellow
|
||||
|
||||
if ($cert.Subject -notmatch 'whatido') {
|
||||
Write-Warning "Тема сертификата '$($cert.Subject)' отличается от ожидаемой ('CN=whatido.local')."
|
||||
$continue = Read-Host "Продолжить установку? (y/n)"
|
||||
if ($continue -ne 'y' -and $continue -ne 'Y') { exit 0 }
|
||||
}
|
||||
|
||||
# --- 3. Проверяем, есть ли уже такой сертификат в хранилище ---
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$storePath = "Cert:\$StoreLocation\Root"
|
||||
if (!(Test-Path $storePath)) {
|
||||
|
||||
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
|
||||
}
|
||||
@@ -61,29 +59,122 @@ if (!(Test-Path $storePath)) {
|
||||
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store('Root', $StoreLocation)
|
||||
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
|
||||
|
||||
$existing = $store.Certificates | Where-Object {
|
||||
$_.Thumbprint -eq $cert.Thumbprint -or $_.Thumbprint -eq $cert.Thumbprint.ToUpperInvariant()
|
||||
}
|
||||
|
||||
if ($existing) {
|
||||
Write-Host "Сертификат уже установлен в хранилище $storePath" -ForegroundColor Green
|
||||
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
|
||||
}
|
||||
|
||||
# --- 4. Импортируем в хранилище корневых сертификатов ---
|
||||
Write-Host "Импортируем сертификат в: $storePath" -ForegroundColor Cyan
|
||||
# --- 1. Получаем сертификат: файл рядом со скриптом, потом - загрузка по URL ---
|
||||
$bytes = $null
|
||||
$source = ''
|
||||
|
||||
$store.Add($cert)
|
||||
Write-Host "Успешно: сертификат добавлен в хранилище 'Доверенные корневые центры сертификации' ($StoreLocation)" -ForegroundColor Green
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# --- 5. Показываем итоговое содержимое (для подтверждения) ---
|
||||
$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.Certificates |
|
||||
Where-Object { $_.NotAfter -gt (Get-Date) -and $_.Subject -match 'whatido' } |
|
||||
Select-Object -First 5 Subject, NotAfter, Thumbprint |
|
||||
Format-Table -AutoSize
|
||||
|
||||
$store.Close()
|
||||
|
||||
# --- 6. Очистка ---
|
||||
Remove-Item -Force $TempCert -ErrorAction SilentlyContinue
|
||||
Write-Host "Временный файл удалён." -ForegroundColor Gray
|
||||
Write-Host "Перезапустите браузер полностью и откройте приложение по адресу из сертификата." -ForegroundColor Cyan
|
||||
Write-Host "Откат: .\install-whatido-cert.ps1 -Uninstall" -ForegroundColor Gray
|
||||
|
||||
Reference in New Issue
Block a user