fix: 旧版明文缓存兼容 + 自动迁移 DPAPI + 写 User 环境变量

This commit is contained in:
bookworm 2026-04-10 11:05:25 +08:00
parent 105a328120
commit b58538bbae

View File

@ -473,18 +473,29 @@ function Get-CachedSecrets {
}
$props = Get-ItemProperty $regPath -ErrorAction SilentlyContinue
$loaded = 0
$needMigrate = $false
foreach ($p in $props.PSObject.Properties) {
# B9: 只加载白名单内的 Key (防止 PATH/COMSPEC 注入)
if ($CacheAllowedKeys -contains $p.Name) {
try {
$val = Unprotect-String $p.Value
$val = $null
# 先尝试 DPAPI 解密 (新格式)
try { $val = Unprotect-String $p.Value } catch {}
# 回退: 旧版明文格式 (非 Base64 / DPAPI 失败)
if (-not $val -and $p.Value -and $p.Value.Length -lt 200) {
$val = $p.Value
$needMigrate = $true
}
if ($val) {
[System.Environment]::SetEnvironmentVariable($p.Name, $val, "Process")
[System.Environment]::SetEnvironmentVariable($p.Name, $val, "User")
$loaded++
} catch {
Bw-Log "WARN" "缓存解密失败: $($p.Name)"
}
}
}
# 旧缓存自动迁移为 DPAPI 格式
if ($needMigrate -and $loaded -gt 0) {
Save-SecretsToCache
Bw-Log "INFO" "旧版明文缓存已迁移为 DPAPI 加密"
}
return ($loaded -gt 0 -and $env:ANTHROPIC_API_KEY)
} catch { return $false }
}