fix(deploy): 初始化并校验公开 API 地址

This commit is contained in:
2026-07-16 01:00:32 +08:00
parent 64bbf5c109
commit 6ee9666b0c
14 changed files with 692 additions and 10 deletions
+102
View File
@@ -0,0 +1,102 @@
function Get-PublicEnvValue {
param([string]$Content, [string]$Key)
$match = [regex]::Match($Content, "(?m)^$([regex]::Escape($Key))=(.*)$")
if (-not $match.Success) { return "" }
$value = $match.Groups[1].Value.Trim()
if ($value.Length -ge 2) {
$first = $value.Substring(0, 1)
$last = $value.Substring($value.Length - 1, 1)
if (($first -eq "'" -and $last -eq "'") -or ($first -eq '"' -and $last -eq '"')) {
return $value.Substring(1, $value.Length - 2)
}
}
return $value
}
function Set-PublicEnvValue {
param([string]$Content, [string]$Key, [string]$Value)
$pattern = "(?m)^$([regex]::Escape($Key))=.*(?:\r?\n)?"
$replacement = "$Key=$Value`r`n"
if ([regex]::IsMatch($Content, $pattern)) {
return [regex]::Replace($Content, $pattern, $replacement, 1)
}
if ($Content -and -not $Content.EndsWith("`n")) { $Content += "`r`n" }
return $Content + $replacement
}
function ConvertTo-PublicApiBaseUrl {
param([string]$Value)
$normalized = if ($null -eq $Value) { "" } else { $Value.Trim().TrimEnd('/') }
if (-not $normalized) { return $null }
$uri = $null
if (-not [Uri]::TryCreate($normalized, [UriKind]::Absolute, [ref]$uri)) { return $null }
if ($uri.Scheme -notin @("http", "https")) { return $null }
if ($uri.UserInfo -or $uri.Query -or $uri.Fragment) { return $null }
if (-not $uri.Host -or $uri.Port -lt 1 -or $uri.Port -gt 65535) { return $null }
return $normalized
}
function Get-DerivedPublicApiBaseUrl {
param([string]$Content)
$apiUrl = Get-PublicEnvValue $Content "NUXT_PUBLIC_BASE_APIURL"
$absoluteApiUrl = ConvertTo-PublicApiBaseUrl $apiUrl
if ($absoluteApiUrl) { return $absoluteApiUrl }
if (-not $apiUrl.StartsWith('/')) { return $null }
$origin = $null
$socketUrl = Get-PublicEnvValue $Content "NUXT_PUBLIC_BASE_SOCKETURL"
$socketUri = $null
if ([Uri]::TryCreate($socketUrl, [UriKind]::Absolute, [ref]$socketUri) -and
$socketUri.Scheme -in @("ws", "wss")) {
$scheme = if ($socketUri.Scheme -eq "wss") { "https" } else { "http" }
$origin = "${scheme}://$($socketUri.Authority)"
}
if (-not $origin) {
$securityOrigin = (Get-PublicEnvValue $Content "CONFIG_SECURITY_ORIGIN").Split(',')[0].Trim()
$securityUri = $null
if ([Uri]::TryCreate($securityOrigin, [UriKind]::Absolute, [ref]$securityUri) -and
$securityUri.Scheme -in @("http", "https")) {
$origin = "$($securityUri.Scheme)://$($securityUri.Authority)"
}
}
if (-not $origin) { return $null }
return ConvertTo-PublicApiBaseUrl "$($origin.TrimEnd('/'))$apiUrl"
}
function Initialize-PublicApiBaseUrl {
param(
[Parameter(Mandatory = $true)][string]$Path,
[ValidateSet("configure", "upgrade")][string]$Mode = "upgrade",
[string]$Override = $env:DEPLOY_PUBLIC_API_BASE_URL
)
if (-not (Test-Path $Path)) { throw "Environment file not found: $Path" }
$content = Get-Content $Path -Raw -Encoding UTF8
if ($null -eq $content) { $content = "" }
if (-not $Override) { $Override = Get-PublicEnvValue $content "DEPLOY_PUBLIC_API_BASE_URL" }
$current = Get-PublicEnvValue $content "CONFIG_PUBLIC_API_BASE_URL"
if ($Override) {
$selected = ConvertTo-PublicApiBaseUrl $Override
if (-not $selected) { throw "Invalid public API base URL: $Override" }
} elseif ($current) {
if (-not (ConvertTo-PublicApiBaseUrl $current)) {
throw "Invalid CONFIG_PUBLIC_API_BASE_URL: $current"
}
return
} else {
$selected = Get-DerivedPublicApiBaseUrl $content
if (-not $selected) {
throw "Cannot derive CONFIG_PUBLIC_API_BASE_URL. Set a full URL such as https://example.com/api"
}
}
$content = Set-PublicEnvValue $content "CONFIG_PUBLIC_API_BASE_URL" $selected
[System.IO.File]::WriteAllText(
(Resolve-Path $Path),
$content,
[System.Text.UTF8Encoding]::new($false)
)
Write-Host " [OK] Public API base URL: $selected" -ForegroundColor Green
}
+93
View File
@@ -0,0 +1,93 @@
#Requires -Version 5.1
$ErrorActionPreference = "Stop"
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
. (Join-Path $scriptDir "Initialize-PublicApiBaseUrl.ps1")
$tempDir = Join-Path ([System.IO.Path]::GetTempPath()) ("easyai-public-url-" + [Guid]::NewGuid())
[System.IO.Directory]::CreateDirectory($tempDir) | Out-Null
function Write-TestEnv {
param([string]$Name, [string[]]$Lines)
$path = Join-Path $tempDir $Name
[System.IO.File]::WriteAllText($path, ($Lines -join "`r`n") + "`r`n", [System.Text.UTF8Encoding]::new($false))
return $path
}
function Assert-PublicUrl {
param([string]$Path, [string]$Expected)
$content = Get-Content $Path -Raw -Encoding UTF8
$actual = Get-PublicEnvValue $content "CONFIG_PUBLIC_API_BASE_URL"
if ($actual -ne $Expected) { throw "Expected '$Expected', got '$actual'" }
}
try {
$existing = Write-TestEnv "existing.env" @(
"CONFIG_PUBLIC_API_BASE_URL=https://existing.example.com:8443/api",
"NUXT_PUBLIC_BASE_APIURL=/api"
)
Initialize-PublicApiBaseUrl -Path $existing -Mode upgrade
Assert-PublicUrl $existing "https://existing.example.com:8443/api"
$absolute = Write-TestEnv "absolute.env" @(
"CONFIG_PUBLIC_API_BASE_URL=",
"NUXT_PUBLIC_BASE_APIURL=http://10.0.0.8:4100"
)
Initialize-PublicApiBaseUrl -Path $absolute -Mode upgrade
Assert-PublicUrl $absolute "http://10.0.0.8:4100"
$websocket = Write-TestEnv "websocket.env" @(
"CONFIG_PUBLIC_API_BASE_URL=",
"NUXT_PUBLIC_BASE_APIURL=/api",
"NUXT_PUBLIC_BASE_SOCKETURL=wss://demo.example.com/socket.io"
)
Initialize-PublicApiBaseUrl -Path $websocket -Mode upgrade
Assert-PublicUrl $websocket "https://demo.example.com/api"
$securityOrigin = Write-TestEnv "security-origin.env" @(
"CONFIG_PUBLIC_API_BASE_URL=",
"NUXT_PUBLIC_BASE_APIURL=/api",
"NUXT_PUBLIC_BASE_SOCKETURL=",
"CONFIG_SECURITY_ORIGIN=http://demo.example.com,https://demo.example.com"
)
Initialize-PublicApiBaseUrl -Path $securityOrigin -Mode upgrade
Assert-PublicUrl $securityOrigin "http://demo.example.com/api"
$fileOverride = Write-TestEnv "file-override.env" @(
"CONFIG_PUBLIC_API_BASE_URL=",
"DEPLOY_PUBLIC_API_BASE_URL=https://proxy.example.com:9443/custom-api",
"NUXT_PUBLIC_BASE_APIURL=/api"
)
Initialize-PublicApiBaseUrl -Path $fileOverride -Mode upgrade
Assert-PublicUrl $fileOverride "https://proxy.example.com:9443/custom-api"
$explicitOverride = Write-TestEnv "explicit-override.env" @(
"CONFIG_PUBLIC_API_BASE_URL=",
"NUXT_PUBLIC_BASE_APIURL=/api"
)
Initialize-PublicApiBaseUrl `
-Path $explicitOverride `
-Mode configure `
-Override "http://192.168.1.20:4567"
Assert-PublicUrl $explicitOverride "http://192.168.1.20:4567"
$invalid = Write-TestEnv "invalid.env" @(
"CONFIG_PUBLIC_API_BASE_URL=ftp://bad.example.com/api",
"NUXT_PUBLIC_BASE_APIURL=https://good.example.com/api"
)
$blocked = $false
try { Initialize-PublicApiBaseUrl -Path $invalid -Mode upgrade } catch { $blocked = $true }
if (-not $blocked) { throw "Invalid existing CONFIG_PUBLIC_API_BASE_URL must block startup" }
$unresolved = Write-TestEnv "unresolved.env" @(
"CONFIG_PUBLIC_API_BASE_URL=",
"NUXT_PUBLIC_BASE_APIURL=/api"
)
$blocked = $false
try { Initialize-PublicApiBaseUrl -Path $unresolved -Mode upgrade } catch { $blocked = $true }
if (-not $blocked) { throw "Unresolved public API URL must block startup" }
Write-Host "Public API base URL PowerShell tests passed" -ForegroundColor Green
} finally {
Remove-Item $tempDir -Recurse -Force -ErrorAction SilentlyContinue
}
+157
View File
@@ -0,0 +1,157 @@
#!/bin/bash
# 初始化并持久化后端对外公开 API 地址。不会 source .env,避免执行其中内容。
public_url_read_env_value() {
local file="$1"
local key="$2"
local value
value="$(awk -v key="$key" 'index($0, key "=") == 1 { print substr($0, length(key) + 2); exit }' "$file")"
value="$(printf '%s' "$value" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')"
case "$value" in
\"*\") value="${value#\"}"; value="${value%\"}" ;;
\'*\') value="${value#\'}"; value="${value%\'}" ;;
esac
printf '%s' "$value"
}
public_url_write_env_value() {
local file="$1"
local key="$2"
local value="$3"
local tmp
tmp="$(mktemp "${file}.tmp.XXXXXX")"
awk -v key="$key" -v value="$value" '
BEGIN { replaced = 0 }
index($0, key "=") == 1 {
if (!replaced) {
print key "=" value
replaced = 1
}
next
}
{ print }
END {
if (!replaced) print key "=" value
}
' "$file" > "$tmp"
chmod 600 "$tmp"
mv "$tmp" "$file"
}
public_url_normalize() {
local value
value="$(printf '%s' "$1" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')"
while [ "${value%/}" != "$value" ]; do value="${value%/}"; done
printf '%s' "$value"
}
public_url_validate() {
local value rest authority host port
value="$(public_url_normalize "$1")"
case "$value" in
http://*|https://*) ;;
*) return 1 ;;
esac
case "$value" in
*[[:space:]@?#]*) return 1 ;;
esac
rest="${value#*://}"
authority="${rest%%/*}"
[ -n "$authority" ] || return 1
if [[ "$authority" == \[* ]]; then
[[ "$authority" =~ ^\[[0-9A-Fa-f:.]+\](:[0-9]+)?$ ]] || return 1
if [[ "$authority" == *]:* ]]; then port="${authority##*:}"; fi
else
[[ "$authority" =~ ^[A-Za-z0-9._-]+(:[0-9]+)?$ ]] || return 1
if [[ "$authority" == *:* ]]; then
host="${authority%:*}"
port="${authority##*:}"
[ -n "$host" ] || return 1
fi
fi
if [ -n "${port:-}" ]; then
[[ "$port" =~ ^[0-9]+$ ]] || return 1
[ "$port" -ge 1 ] && [ "$port" -le 65535 ] || return 1
fi
}
public_url_derive_from_env() {
local file="$1"
local api_url socket_url security_origin origin scheme combined
api_url="$(public_url_read_env_value "$file" "NUXT_PUBLIC_BASE_APIURL")"
if public_url_validate "$api_url"; then
public_url_normalize "$api_url"
return 0
fi
[[ "$api_url" == /* ]] || return 1
socket_url="$(public_url_read_env_value "$file" "NUXT_PUBLIC_BASE_SOCKETURL")"
if [[ "$socket_url" =~ ^(ws|wss)://([^/?#[:space:]]+) ]]; then
scheme="http"
[ "${BASH_REMATCH[1]}" = "wss" ] && scheme="https"
origin="${scheme}://${BASH_REMATCH[2]}"
fi
if [ -z "${origin:-}" ]; then
security_origin="$(public_url_read_env_value "$file" "CONFIG_SECURITY_ORIGIN")"
security_origin="${security_origin%%,*}"
security_origin="$(public_url_normalize "$security_origin")"
if [[ "$security_origin" =~ ^(https?://[^/]+) ]]; then
origin="${BASH_REMATCH[1]}"
fi
fi
[ -n "${origin:-}" ] || return 1
combined="$(public_url_normalize "${origin}${api_url}")"
public_url_validate "$combined" || return 1
printf '%s' "$combined"
}
init_public_api_base_url() {
local file="${1:-.env}"
local mode="${2:-upgrade}"
local override="${3:-${DEPLOY_PUBLIC_API_BASE_URL:-}}"
local current selected
if [ ! -f "$file" ]; then
echo "❌ 环境配置文件不存在: $file" >&2
return 1
fi
if [ "$mode" != "configure" ] && [ "$mode" != "upgrade" ]; then
echo "❌ 公开 API 地址初始化模式无效: $mode(仅支持 configure/upgrade" >&2
return 1
fi
if [ -z "$override" ]; then
override="$(public_url_read_env_value "$file" "DEPLOY_PUBLIC_API_BASE_URL")"
fi
current="$(public_url_read_env_value "$file" "CONFIG_PUBLIC_API_BASE_URL")"
if [ -n "$override" ]; then
selected="$(public_url_normalize "$override")"
elif [ -n "$current" ]; then
if ! public_url_validate "$current"; then
echo "❌ CONFIG_PUBLIC_API_BASE_URL 配置无效: $current" >&2
return 1
fi
return 0
else
selected="$(public_url_derive_from_env "$file")" || {
echo "❌ 无法从现有前端配置推导 CONFIG_PUBLIC_API_BASE_URL" >&2
echo " 请设置完整地址,例如 https://example.com/api" >&2
return 1
}
fi
if ! public_url_validate "$selected"; then
echo "❌ 公开 API 地址配置无效: $selected" >&2
return 1
fi
selected="$(public_url_normalize "$selected")"
public_url_write_env_value "$file" "CONFIG_PUBLIC_API_BASE_URL" "$selected"
echo " ✓ 已配置公开 API 地址: $selected"
}
if [ "${BASH_SOURCE[0]}" = "$0" ]; then
init_public_api_base_url "${1:-.env}" "${2:-upgrade}" "${3:-}"
fi
+80
View File
@@ -0,0 +1,80 @@
#!/bin/bash
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT
cp \
"$REPO_ROOT/start.sh" \
"$REPO_ROOT/docker-compose.yml" \
"$REPO_ROOT/.env.sample" \
"$REPO_ROOT/.env.tools.sample" \
"$REPO_ROOT/.env.ASG.sample" \
"$REPO_ROOT/.env.AMS.sample" \
"$REPO_ROOT/easyai-proxy.conf.sample" \
"$TMP_DIR/"
mkdir -p "$TMP_DIR/scripts"
cp \
"$REPO_ROOT/scripts/init-security-env.sh" \
"$REPO_ROOT/scripts/init-public-api-base-url.sh" \
"$TMP_DIR/scripts/"
cd "$TMP_DIR"
reset_case() {
rm -f \
.env \
.env.tools \
.env.ASG \
.env.AMS \
demo.example.com.conf
}
sed -i.bak 's/^SERVER_HTTP_PORT=.*/SERVER_HTTP_PORT=4100/' .env.sample
rm -f .env.sample.bak
DEPLOY_NON_INTERACTIVE=1 \
DEPLOY_DRY_RUN=1 \
DEPLOY_ACCESS=ip \
DEPLOY_IP=10.0.0.8 \
bash start.sh >/dev/null
grep -qx 'NUXT_PUBLIC_BASE_APIURL=http://10.0.0.8:4100' .env
grep -qx 'CONFIG_PUBLIC_API_BASE_URL=http://10.0.0.8:4100' .env
if command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; then
docker compose config --quiet
fi
reset_case
DEPLOY_NON_INTERACTIVE=1 \
DEPLOY_DRY_RUN=1 \
DEPLOY_ACCESS=domain \
DEPLOY_DOMAIN=demo.example.com \
DEPLOY_HTTPS=false \
bash start.sh >/dev/null
grep -qx 'NUXT_PUBLIC_BASE_SOCKETURL=ws://demo.example.com/socket.io' .env
grep -qx 'CONFIG_PUBLIC_API_BASE_URL=http://demo.example.com/api' .env
grep -q 'proxy_set_header X-Forwarded-Host $easyai_forwarded_host;' demo.example.com.conf
grep -q 'proxy_set_header X-Forwarded-Port $server_port;' demo.example.com.conf
grep -q "proxy_set_header X-Original-Prefix '/api';" demo.example.com.conf
reset_case
DEPLOY_NON_INTERACTIVE=1 \
DEPLOY_DRY_RUN=1 \
DEPLOY_ACCESS=domain \
DEPLOY_DOMAIN=demo.example.com \
DEPLOY_HTTPS=true \
bash start.sh >/dev/null
grep -qx 'NUXT_PUBLIC_BASE_SOCKETURL=wss://demo.example.com/socket.io' .env
grep -qx 'CONFIG_PUBLIC_API_BASE_URL=https://demo.example.com/api' .env
reset_case
DEPLOY_NON_INTERACTIVE=1 \
DEPLOY_DRY_RUN=1 \
DEPLOY_ACCESS=ip \
DEPLOY_IP=10.0.0.8 \
DEPLOY_PUBLIC_API_BASE_URL=https://edge.example.com:8443/custom-api \
bash start.sh >/dev/null
grep -qx 'CONFIG_PUBLIC_API_BASE_URL=https://edge.example.com:8443/custom-api' .env
echo "Deployment public URL dry-run tests passed"
+93
View File
@@ -0,0 +1,93 @@
#!/bin/bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=scripts/init-public-api-base-url.sh
. "${SCRIPT_DIR}/init-public-api-base-url.sh"
TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT
fail() {
echo "FAIL: $*" >&2
exit 1
}
assert_env_value() {
local file="$1"
local expected="$2"
local actual
actual="$(public_url_read_env_value "$file" "CONFIG_PUBLIC_API_BASE_URL")"
[ "$actual" = "$expected" ] || fail "expected $expected, got $actual"
}
write_env() {
local file="$1"
shift
printf '%s\n' "$@" > "$file"
}
existing="$TMP_DIR/existing.env"
write_env "$existing" \
"CONFIG_PUBLIC_API_BASE_URL=https://existing.example.com:8443/api" \
"NUXT_PUBLIC_BASE_APIURL=/api"
init_public_api_base_url "$existing" upgrade >/dev/null
assert_env_value "$existing" "https://existing.example.com:8443/api"
absolute="$TMP_DIR/absolute.env"
write_env "$absolute" \
"CONFIG_PUBLIC_API_BASE_URL=" \
"NUXT_PUBLIC_BASE_APIURL=http://10.0.0.8:4100"
init_public_api_base_url "$absolute" upgrade >/dev/null
assert_env_value "$absolute" "http://10.0.0.8:4100"
websocket="$TMP_DIR/websocket.env"
write_env "$websocket" \
"CONFIG_PUBLIC_API_BASE_URL=" \
"NUXT_PUBLIC_BASE_APIURL=/api" \
"NUXT_PUBLIC_BASE_SOCKETURL=wss://demo.example.com/socket.io"
init_public_api_base_url "$websocket" upgrade >/dev/null
assert_env_value "$websocket" "https://demo.example.com/api"
security_origin="$TMP_DIR/security-origin.env"
write_env "$security_origin" \
"CONFIG_PUBLIC_API_BASE_URL=" \
"NUXT_PUBLIC_BASE_APIURL=/api" \
"NUXT_PUBLIC_BASE_SOCKETURL=" \
"CONFIG_SECURITY_ORIGIN=http://demo.example.com,https://demo.example.com"
init_public_api_base_url "$security_origin" upgrade >/dev/null
assert_env_value "$security_origin" "http://demo.example.com/api"
file_override="$TMP_DIR/file-override.env"
write_env "$file_override" \
"CONFIG_PUBLIC_API_BASE_URL=" \
"DEPLOY_PUBLIC_API_BASE_URL=https://proxy.example.com:9443/custom-api" \
"NUXT_PUBLIC_BASE_APIURL=/api"
init_public_api_base_url "$file_override" upgrade >/dev/null
assert_env_value "$file_override" "https://proxy.example.com:9443/custom-api"
explicit_override="$TMP_DIR/explicit-override.env"
write_env "$explicit_override" \
"CONFIG_PUBLIC_API_BASE_URL=" \
"NUXT_PUBLIC_BASE_APIURL=/api"
init_public_api_base_url "$explicit_override" configure "http://192.168.1.20:4567" >/dev/null
assert_env_value "$explicit_override" "http://192.168.1.20:4567"
invalid="$TMP_DIR/invalid.env"
write_env "$invalid" \
"CONFIG_PUBLIC_API_BASE_URL=ftp://bad.example.com/api" \
"NUXT_PUBLIC_BASE_APIURL=https://good.example.com/api"
if init_public_api_base_url "$invalid" upgrade >/dev/null 2>&1; then
fail "invalid existing CONFIG_PUBLIC_API_BASE_URL must block startup"
fi
unresolved="$TMP_DIR/unresolved.env"
write_env "$unresolved" \
"CONFIG_PUBLIC_API_BASE_URL=" \
"NUXT_PUBLIC_BASE_APIURL=/api"
if init_public_api_base_url "$unresolved" upgrade >/dev/null 2>&1; then
fail "unresolved public API URL must block startup"
fi
echo "Public API base URL shell tests passed"