2cddf06b6c
Co-authored-by: 旅行呀~ <travelxiao@qq.com>
67 lines
1.9 KiB
PowerShell
67 lines
1.9 KiB
PowerShell
# Agent-safe: test SSH auth against a remote (Gitea-friendly). Never prints private keys.
|
|
|
|
param(
|
|
[Parameter(Mandatory = $true)]
|
|
[string]$RemoteUrl
|
|
)
|
|
|
|
$ErrorActionPreference = 'Stop'
|
|
. (Join-Path $PSScriptRoot 'common.ps1')
|
|
|
|
$parsed = Parse-GitRemoteUrl -RemoteUrl $RemoteUrl
|
|
if ([string]$parsed.Protocol -ne 'ssh') {
|
|
Write-StatusLine -Key 'status' -Value 'skipped'
|
|
Write-StatusLine -Key 'reason' -Value 'not_ssh_remote'
|
|
Write-StatusLine -Key 'protocol' -Value ([string]$parsed.Protocol)
|
|
exit 0
|
|
}
|
|
|
|
$hostName = [string]$parsed.Host
|
|
$port = $parsed.Port
|
|
$sshArgs = @()
|
|
if ($null -ne $port -and [int]$port -ne 22) {
|
|
$sshArgs += @('-p', "$port")
|
|
}
|
|
$sshArgs += @('-o', 'BatchMode=yes', '-T', "git@$hostName")
|
|
|
|
$prevEap = $ErrorActionPreference
|
|
$ErrorActionPreference = 'Continue'
|
|
try {
|
|
$output = & ssh @sshArgs 2>&1 | Out-String
|
|
$code = $LASTEXITCODE
|
|
}
|
|
finally {
|
|
$ErrorActionPreference = $prevEap
|
|
}
|
|
|
|
$text = if ($null -eq $output) { '' } else { [string]$output }
|
|
$ok = $false
|
|
if ($text -match 'successfully authenticated' -or
|
|
$text -match 'Hi there,' -or
|
|
$text -match 'Welcome to Gitea' -or
|
|
$text -match "You've successfully authenticated") {
|
|
$ok = $true
|
|
}
|
|
|
|
# Gitea/GitHub often exit 1 even when auth succeeded (no shell).
|
|
if ($ok) {
|
|
Write-StatusLine -Key 'status' -Value 'ok'
|
|
} else {
|
|
Write-StatusLine -Key 'status' -Value 'failed'
|
|
Write-StatusLine -Key 'exit_code' -Value "$code"
|
|
}
|
|
|
|
Write-StatusLine -Key 'host' -Value $hostName
|
|
if ($null -ne $port) {
|
|
Write-StatusLine -Key 'port' -Value "$port"
|
|
} else {
|
|
Write-StatusLine -Key 'port' -Value '22'
|
|
}
|
|
# Safe to show SSH server greeting; strip nothing secret-bearing beyond pubkey auth result.
|
|
$oneLine = ($text -replace '\r?\n', ' ').Trim()
|
|
if ($oneLine.Length -gt 240) { $oneLine = $oneLine.Substring(0, 240) }
|
|
Write-StatusLine -Key 'message' -Value $oneLine
|
|
|
|
if (-not $ok) { exit 1 }
|
|
exit 0
|