merge: 控制面联调 M6 [tsk_nuoKSM4Vt-zK]
# Conflicts: # .gitignore # client/lib/widgets/home_shell.dart # client/lib/widgets/server_tile.dart # client/pubspec.yaml
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func post(t *testing.T, handler http.Handler, path, body, auth string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodPost, path, bytes.NewBufferString(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if auth != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+auth)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
handler.ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
// TestConnectReturnsValidConfig verifies that a well-formed request returns
|
||||
// a 200 with all four §3.1 top-level blocks present.
|
||||
func TestConnectReturnsValidConfig(t *testing.T) {
|
||||
h := makeHandler("test-token")
|
||||
w := post(t, h, "/v1/nodes/sg-1/connect", `{"device_id":"dev-001"}`, "test-token")
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("want 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
var out map[string]any
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
|
||||
t.Fatalf("response is not valid JSON: %v\nbody: %s", err, w.Body.String())
|
||||
}
|
||||
for _, key := range []string{"inbounds", "outbounds", "route", "dns"} {
|
||||
if _, ok := out[key]; !ok {
|
||||
t.Errorf("§3.1 block missing: %q", key)
|
||||
}
|
||||
}
|
||||
// outbounds must include urltest group named "auto"
|
||||
outs, _ := out["outbounds"].([]any)
|
||||
found := false
|
||||
for _, o := range outs {
|
||||
m, _ := o.(map[string]any)
|
||||
if m["type"] == "urltest" && m["tag"] == "auto" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Error("outbounds: missing urltest group 'auto'")
|
||||
}
|
||||
// inbound must have strict_route:true (Kill-switch)
|
||||
ins, _ := out["inbounds"].([]any)
|
||||
if len(ins) == 0 {
|
||||
t.Fatal("inbounds is empty")
|
||||
}
|
||||
tun, _ := ins[0].(map[string]any)
|
||||
if tun["strict_route"] != true {
|
||||
t.Error("inbounds[0].strict_route must be true (Kill-switch)")
|
||||
}
|
||||
}
|
||||
|
||||
// TestConnectRequiresAuth verifies that a missing / wrong token yields 401.
|
||||
func TestConnectRequiresAuth(t *testing.T) {
|
||||
h := makeHandler("secret")
|
||||
cases := []struct{ name, token string }{
|
||||
{"no-header", ""},
|
||||
{"wrong-token", "wrong"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
w := post(t, h, "/v1/nodes/sg-1/connect", `{"device_id":"x"}`, c.token)
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Errorf("want 401, got %d", w.Code)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestConnectNoAuthCheck verifies that an empty token skips auth entirely.
|
||||
func TestConnectNoAuthCheck(t *testing.T) {
|
||||
h := makeHandler("")
|
||||
w := post(t, h, "/v1/nodes/sg-1/connect", `{"device_id":"x"}`, "")
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("want 200, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestConnectRequiresDeviceID verifies that missing device_id yields 400.
|
||||
func TestConnectRequiresDeviceID(t *testing.T) {
|
||||
h := makeHandler("")
|
||||
cases := []struct{ name, body string }{
|
||||
{"empty-object", `{}`},
|
||||
{"blank-id", `{"device_id":""}`},
|
||||
{"not-json", `not-json`},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/nodes/sg-1/connect", bytes.NewBufferString(c.body))
|
||||
rw := httptest.NewRecorder()
|
||||
h.ServeHTTP(rw, req)
|
||||
if rw.Code != http.StatusBadRequest {
|
||||
t.Errorf("want 400, got %d", rw.Code)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestConnectMethodNotAllowed verifies that GET returns 405.
|
||||
func TestConnectMethodNotAllowed(t *testing.T) {
|
||||
h := makeHandler("")
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/nodes/sg-1/connect", nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusMethodNotAllowed {
|
||||
t.Errorf("want 405, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestConnectWrongPath verifies that unrelated paths return 404.
|
||||
func TestConnectWrongPath(t *testing.T) {
|
||||
h := makeHandler("")
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/nodes/sg-1/disconnect", nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("want 404, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user