Files
pangolin/server/cmd/mockserver/main.go
T
wangjia bd8f974a25 feat(M6): 控制面联调 — mock connect server + 客户端 ConnectApi 透传
tsk_nuoKSM4Vt-zK

## 服务端(server/cmd/mockserver)
- `main.go`(79 行):独立 mock HTTP server,实现 POST /v1/nodes/:id/connect
  - 路径/请求体/响应体字段名与 §3.1 契约逐字一致
  - Bearer token 鉴权(-token 参数,空值跳过,不入库)
  - 缺少 device_id → 400;未授权 → 401;非 POST → 405
  - 返回完整 sing-box config JSON(tun + REALITY/Hy2 outbound + urltest + route/dns)
  - 注:mock 联调;待 #5/#6 真实 connect 接口就绪后替换
- `main_test.go`:6 项单测,覆盖 §3.1 结构校验、auth、method、path

## 客户端(client/)
- `lib/services/connect_api.dart`:ConnectApi 类
  - fetchConfig(nodeId, deviceId) → 原始响应体字符串(不做任何修改)
  - 错误路径:HTTP 非 200 / 超时 / 非法 JSON → ConnectApiException(含双语 message)
- `lib/services/vpn_bridge.dart`:VpnBridge stub(M6 联调,libbox 绑定待 11C)
  - start(configJson) 原样存储,不修改;stop() 清空
- `lib/widgets/home_shell.dart`:_toggle/_pick 替换为真实 API 流程
  - ConnectApi.fetchConfig → VpnBridge.start(透传,无中间变换)
  - 错误路径:ConnectApiException → SnackBar,status 回 off,无残留半开隧道
  - API URL/token/deviceId 由 --dart-define 注入(不入库)
- `lib/widgets/server_tile.dart`:ServerInfo 新增 nodeId 字段
- `pubspec.yaml`:新增 http: ^1.2.1 依赖
- `test/connect_passthrough_test.dart`:4 项透传断言单测
  - 核心:fetchConfig 返回字符串 === VpnBridge.start 接收字符串(逐字节相等)
  - 空格/格式原样保留(不经 jsonEncode 重序列化)
  - HTTP 错误、非法 JSON 错误路径覆盖

## 运行方式(M6 联调)
```
# 启动 mock server(无 auth)
go run ./server/cmd/mockserver -addr :8081

# 启动客户端(指向 mock server)
flutter run \
  --dart-define=PANGOLIN_API_URL=http://localhost:8081 \
  --dart-define=PANGOLIN_API_TOKEN=dev-mock-token \
  --dart-define=PANGOLIN_DEVICE_ID=demo-device-001
```

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-13 14:16:29 +08:00

80 lines
3.7 KiB
Go

// Package main implements a minimal mock server for POST /v1/nodes/:id/connect.
// Returns a fixed sing-box config JSON per §3.1 contract (ARCHITECTURE.md).
//
// Usage:
//
// go run ./cmd/mockserver [-addr :8081] [-token <bearer-token>]
//
// 注:mock 联调;待 #5/#6 真实 connect 接口就绪后切换为真实后端。
// tsk_nuoKSM4Vt-zK (M6)
package main
import (
"encoding/json"
"flag"
"log"
"net/http"
"regexp"
"strings"
)
// connectConfig is the canonical sing-box config per §3.1.
// Fields match the nodes table columns: reality_public_key / reality_short_id / hy2_password.
// In production the API renders these per-user from the nodes table.
// Placeholders here are mock values for integration testing only.
const connectConfig = `{"log":{"level":"warn","timestamp":true},"inbounds":[{"type":"tun","tag":"tun-in","address":["172.19.0.1/30"],"mtu":9000,"auto_route":true,"strict_route":true,"stack":"system"}],"outbounds":[{"type":"vless","tag":"reality-out","server":"18.136.60.128","server_port":11443,"uuid":"ffffffff-ffff-ffff-ffff-ffffffffffff","flow":"xtls-rprx-vision","tls":{"enabled":true,"server_name":"www.apple.com","utls":{"enabled":true,"fingerprint":"chrome"},"reality":{"enabled":true,"public_key":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","short_id":"deadbeef"}}},{"type":"hysteria2","tag":"hy2-out","server":"18.136.60.128","server_port":443,"password":"mock-hy2-password","tls":{"enabled":true,"insecure":true,"alpn":["h3"]}},{"type":"urltest","tag":"auto","outbounds":["reality-out","hy2-out"],"url":"https://www.gstatic.com/generate_204","interval":"3m","tolerance":50},{"type":"block","tag":"block"},{"type":"direct","tag":"direct"}],"route":{"rules":[{"ip_cidr":["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16","127.0.0.0/8"],"outbound":"direct"}],"final":"auto","auto_detect_interface":true},"dns":{"servers":[{"tag":"remote","address":"tls://8.8.8.8","detour":"auto"},{"tag":"local","address":"223.5.5.5","detour":"direct"}],"final":"remote","strategy":"ipv4_only"}}`
var reConnect = regexp.MustCompile(`^/v1/nodes/[^/]+/connect$`)
func jsonErr(w http.ResponseWriter, status int, code, zh, en string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]string{
"code": code,
"message_zh": zh,
"message_en": en,
})
}
// makeHandler returns the HTTP handler for the mock connect server.
// token may be empty to skip auth checking (useful in test environments).
func makeHandler(token string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !reConnect.MatchString(r.URL.Path) {
http.NotFound(w, r)
return
}
if r.Method != http.MethodPost {
w.Header().Set("Allow", "POST")
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
if token != "" {
got := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
if got != token {
jsonErr(w, http.StatusUnauthorized, "unauthorized", "鉴权失败", "Unauthorized")
return
}
}
var body struct {
DeviceID string `json:"device_id"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil || strings.TrimSpace(body.DeviceID) == "" {
jsonErr(w, http.StatusBadRequest, "bad_request", "缺少 device_id", "Missing device_id")
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(connectConfig))
}
}
func main() {
addr := flag.String("addr", ":8081", "listen address")
token := flag.String("token", "", "required Bearer token (empty = skip auth check)")
flag.Parse()
log.Printf("[mock] pangolin connect server on %s auth=%v", *addr, *token != "")
if err := http.ListenAndServe(*addr, makeHandler(*token)); err != nil {
log.Fatal(err)
}
}