fix(protect): 加壳产物不再把 127.0.0.1 写进壳 cfg

AcePanel 默认反代模板 proxy_set_header Host $proxy_host,后端看到的 Host 是
127.0.0.1:9998,于是每个产物的 cfg 都成了 https://127.0.0.1:9998/...,
到客户机上必然连不上。

- baseURL() 改为:app.public_url > X-Forwarded-Host > Host;推断出本机/内网
  地址时直接让加壳任务报错,不再静默产出坏产物
- config.yaml 增加 app.public_url(生产可直接写死站点地址)
- 新增 4 个单测(含 loopback 必须报错)
- docs/protect-base-url.md 记录事故与自查方法
This commit is contained in:
2026-11-24 08:42:21 +08:00
parent ead706ea52
commit f997035972
4 changed files with 203 additions and 6 deletions
+2
View File
@@ -4,6 +4,8 @@ app:
port: "8080"
jwt_secret: "your-secret-key-change-in-production"
jwt_expire_hours: "24"
# 加壳时写进壳 cfg 的站点根地址;留空则按请求头推断(反代需要传 X-Forwarded-Host)
public_url: ""
database:
host: "localhost"
+55 -6
View File
@@ -11,6 +11,7 @@ import (
"strings"
"time"
"verification-platform-backend/internal/config"
"verification-platform-backend/internal/database"
"verification-platform-backend/internal/model"
"verification-platform-backend/internal/protect"
@@ -31,8 +32,14 @@ func SetupProtectRoutes(r *gin.RouterGroup) {
}
}
// baseURL 从请求推断站点根地址(面板/应用共用同一域名)
func baseURL(c *gin.Context) string {
// baseURL 推断站点根地址(面板/应用共用同一域名)。
//
// 这里踩过一次真实的坑:AcePanel 默认的反代模板写的是 `proxy_set_header Host $proxy_host`,
// 于是后端看到的 Host 是 `127.0.0.1:9998`,打包出来的每个客户端都会把
// `https://127.0.0.1:9998/api/v1/app/<key>/login` 写进壳 cfg —— 到了客户机上根本连不上。
// 所以:优先 X-Forwarded-Host,其次(配置里的站点地址),最后才是请求 Host;
// 一旦推断出来是本机/内网地址,宁可让加壳任务报错,也不要产出一个连不上服务器的产物。
func baseURL(c *gin.Context) (string, error) {
scheme := c.GetHeader("X-Forwarded-Proto")
if scheme == "" {
if c.Request.TLS != nil {
@@ -41,11 +48,48 @@ func baseURL(c *gin.Context) string {
scheme = "http"
}
}
host := c.GetHeader("X-Forwarded-Host")
// 反代应当带上 X-Forwarded-Host;它才是用户浏览器里那个域名
host := strings.TrimSpace(c.GetHeader("X-Forwarded-Host"))
if host == "" {
host = c.Request.Host
host = strings.TrimSpace(c.Request.Host)
}
return fmt.Sprintf("%s://%s", scheme, host)
// 站点地址可以在 config.yaml 里显式指定(app.public_url),配了就优先用
if pub := strings.TrimRight(config.GetString("app.public_url"), "/"); pub != "" {
return pub, nil
}
if host == "" || isInternalHost(host) {
return "", fmt.Errorf("无法推断站点地址(反向代理没有传 X-Forwarded-Host,Host 为 %q),请在 config.yaml 配置 app.public_url", host)
}
return fmt.Sprintf("%s://%s", scheme, host), nil
}
// isInternalHost 判断 host 是不是只在本机/内网有意义(127.x、localhost、内网网段、无域名端口等)
func isInternalHost(host string) bool {
h := host
if i := strings.LastIndex(h, ":"); i > 0 && !strings.Contains(h[i:], "]") {
h = h[:i] // 去掉端口
}
h = strings.ToLower(strings.Trim(h, "[]"))
switch {
case h == "", h == "localhost", h == "0.0.0.0", h == "::1":
return true
case strings.HasPrefix(h, "127."), strings.HasPrefix(h, "10."), strings.HasPrefix(h, "192.168."):
return true
case strings.HasPrefix(h, "172."):
// 172.16.0.0/12
parts := strings.Split(h, ".")
if len(parts) == 4 {
if n, err := strconv.Atoi(parts[1]); err == nil && n >= 16 && n <= 31 {
return true
}
}
case strings.HasPrefix(h, "169.254."):
return true
}
return false
}
// HandleCreateProtectTask 上传原始程序 → 建任务 → 异步加壳
@@ -227,7 +271,12 @@ func HandleCreateProtectTask(c *gin.Context) {
response.Error(c, 400, "程序版本号只能包含字母、数字、点、下划线和横线,例如 1.2.3")
return
}
task, err := protect.CreateAndRunThemedVer(&app, userID, name, data, baseURL(c), signProfileID, certIdentity, theme, programVer)
siteURL, err := baseURL(c)
if err != nil {
response.Error(c, 400, err.Error())
return
}
task, err := protect.CreateAndRunThemedVer(&app, userID, name, data, siteURL, signProfileID, certIdentity, theme, programVer)
if err != nil {
response.ParamError(c, err.Error())
return
@@ -0,0 +1,80 @@
package admin
import (
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
)
func TestIsInternalHost(t *testing.T) {
cases := map[string]bool{
"127.0.0.1:9998": true,
"127.0.0.1": true,
"localhost:8080": true,
"localhost": true,
"10.0.0.5": true,
"192.168.1.10:443": true,
"172.16.0.1": true,
"172.31.255.1:8080": true,
"169.254.1.1": true,
"": true,
"[::1]:8080": true,
"0.0.0.0:8080": true,
"v.viaeon.com": false,
"v.viaeon.com:443": false,
"172.32.0.1": false, // 不在 172.16/12 里
"verify.example.com": false,
"8.8.8.8": false,
}
for host, want := range cases {
if got := isInternalHost(host); got != want {
t.Fatalf("isInternalHost(%q) = %v, want %v", host, got, want)
}
}
}
func newCtx(host, xfh, proto string) *gin.Context {
gin.SetMode(gin.TestMode)
req := httptest.NewRequest("POST", "/", nil)
req.Host = host
if xfh != "" {
req.Header.Set("X-Forwarded-Host", xfh)
}
if proto != "" {
req.Header.Set("X-Forwarded-Proto", proto)
}
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = req
return c
}
// 反代把 Host 改写成 127.0.0.1 时必须报错,绝不能把内网地址打进产物
func TestBaseURLRejectsLoopback(t *testing.T) {
u, err := baseURL(newCtx("127.0.0.1:9998", "", "https"))
if err == nil {
t.Fatalf("期望报错,实际返回 %q", u)
}
}
// 反代带了 X-Forwarded-Host 就用它
func TestBaseURLPrefersForwardedHost(t *testing.T) {
u, err := baseURL(newCtx("127.0.0.1:9998", "v.viaeon.com", "https"))
if err != nil {
t.Fatalf("期望成功,实际 %v", err)
}
if want := "https://v.viaeon.com"; u != want {
t.Fatalf("baseURL = %q, want %q", u, want)
}
}
// 直连(无反代)时用请求 Host
func TestBaseURLUsesRequestHost(t *testing.T) {
u, err := baseURL(newCtx("v.viaeon.com", "", "https"))
if err != nil {
t.Fatalf("期望成功,实际 %v", err)
}
if want := "https://v.viaeon.com"; u != want {
t.Fatalf("baseURL = %q, want %q", u, want)
}
}
+66
View File
@@ -0,0 +1,66 @@
# 加壳产物的服务器地址是怎么来的(`app.public_url` / 反代头)
## 结论
打包时写进壳 cfg 的 `api` 字段 = `<站点根地址>/api/v1/app/<app_key>/login`。
站点根地址按下面的顺序确定(`backend/internal/router/admin/protect.go` 的 `baseURL()`):
1. `config.yaml` 里的 **`app.public_url`**(配了就最优先,推荐生产环境配上)
2. 请求头 **`X-Forwarded-Host`**(反向代理应当传,值就是用户浏览器地址栏里的域名)
3. 请求的 `Host`
4. 上面两者都没有,或者拿到的是本机/内网地址(`127.x` / `localhost` / `10.x` / `172.16-31.x` / `192.168.x` / `169.254.x`)→ **加壳任务直接报错**,不产出连不上服务器的产物
## 为什么这么写(真实事故)
服务器上的站点是 AcePanel 管的,它默认的反向代理模板写的是:
```nginx
proxy_set_header Host $proxy_host; # ← 后端会看到 127.0.0.1:9998
```
于是 `baseURL()` 推断出 `https://127.0.0.1:9998`,产出的每个客户端壳里都写着:
```
{"api":"https://127.0.0.1:9998/api/v1/app/f26091ac.../login"}
```
客户机上的壳去连自己的 127.0.0.1:9998 —— 必然失败。已确认修复前产出的 `data/protect/*/…_protected.exe` 全部带这个错误地址。
## 正确配法
站点反代(AcePanel → 站点 → 反向代理)里应当是:
```nginx
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
```
`$host` 是请求里的域名(经 Cloudflare 到达时是 `v.viaeon.com`),`$proxy_host` 是上游地址(`127.0.0.1:9998`)。
懒得依赖反代的话,直接在部署目录的 `data/config.yaml` 里写死:
```yaml
app:
public_url: "https://v.viaeon.com"
```
改完重启容器生效(`docker compose restart app`)。
## 自查方法
产物里直接能看出来:
```bash
grep -aoE '\{"api":"[^"]*"' 产物.exe
```
应该看到 `"api":"https://v.viaeon.com/api/v1/app/<key>/login"`。
看到 `127.0.0.1` / `localhost` / 内网 IP 就是踩了这个坑,需要重新打包。
## 验收记录(2026-11-24)
- 反代改前:`proxy_set_header Host $proxy_host` → 探针实测后端收到 `Host: 127.0.0.1:9998`
- 反代改后:`Host $host` + `X-Forwarded-Host $host` → 探针实测后端收到
`Host: v.viaeon.com`、`X-Forwarded-Host: v.viaeon.com`、`X-Forwarded-Proto: https`
- 代码单测:`go test ./internal/router/admin -run "BaseURL|IsInternalHost"`(4 例通过,含「本机地址必须报错」)