# 升级旧部署时从公开 API 地址补齐浏览器来源,并校验显式配置。 . (Join-Path $PSScriptRoot "Initialize-PublicApiBaseUrl.ps1") function Initialize-SecurityOrigin { param([Parameter(Mandatory = $true)][string]$Path) if (-not (Test-Path $Path)) { throw "Environment file not found: $Path" } $content = Get-Content $Path -Raw -Encoding UTF8 if ($null -eq $content) { $content = "" } $apiUrl = Get-PublicEnvValue $content "CONFIG_PUBLIC_API_BASE_URL" if (-not (ConvertTo-PublicApiBaseUrl $apiUrl)) { throw "Configure a valid CONFIG_PUBLIC_API_BASE_URL first" } $apiUri = [Uri]$apiUrl $derived = $apiUri.GetLeftPart([UriPartial]::Authority) $current = Get-PublicEnvValue $content "CONFIG_SECURITY_ORIGIN" if (-not $current -or ($current -eq "http://127.0.0.1,http://localhost" -and $derived -ne "http://127.0.0.1")) { $content = Set-PublicEnvValue $content "CONFIG_SECURITY_ORIGIN" $derived [System.IO.File]::WriteAllText( (Resolve-Path $Path), $content, [System.Text.UTF8Encoding]::new($false) ) Write-Host " [OK] Browser origin: $derived" -ForegroundColor Green return } if ($current.StartsWith(',') -or $current.EndsWith(',') -or $current.Contains(',,')) { throw "CONFIG_SECURITY_ORIGIN contains an empty origin" } foreach ($value in $current.Split(',')) { $origin = $value.Trim() $uri = $null if (-not [Uri]::TryCreate($origin, [UriKind]::Absolute, [ref]$uri) -or $uri.Scheme -notin @('http', 'https') -or $uri.UserInfo -or $uri.Query -or $uri.Fragment -or $uri.AbsolutePath -ne '/' -or -not $uri.Host) { throw "CONFIG_SECURITY_ORIGIN must contain only http(s) origins without paths or wildcards" } } }