Files
EveryPublish/client/core/internal/pairing/pairing.go
T

117 lines
3.3 KiB
Go

package pairing
import (
"bytes"
"crypto/ed25519"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
)
func httpJSON(method, url, token string, body interface{}) (int, []byte, error) {
var buf bytes.Buffer
if body != nil {
raw, _ := json.Marshal(body)
buf.Write(raw)
}
req, err := http.NewRequest(method, url, &buf)
if err != nil {
return 0, nil, err
}
req.Header.Set("Content-Type", "application/json")
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return 0, nil, err
}
defer resp.Body.Close()
raw, _ := io.ReadAll(resp.Body)
return resp.StatusCode, raw, nil
}
func field(raw []byte, key string) string {
var m map[string]interface{}
_ = json.Unmarshal(raw, &m)
if d, ok := m["data"].(map[string]interface{}); ok {
if v, ok := d[key]; ok {
switch t := v.(type) {
case string:
return t
case float64:
return strconv.FormatInt(int64(t), 10)
}
}
}
return ""
}
type ginH map[string]interface{}
// AutoPair 开发便利:登录 → 取配对码 → 配对(无 UI 场景闭环用)
func AutoPair(server, email, password, deviceName, pubKeyB64 string) (uint64, error) {
code, raw, err := httpJSON("POST", server+"/api/v1/auth/login", "", ginH{"email": email, "password": password})
if err != nil || code != 200 {
return 0, fmt.Errorf("login failed: %s", string(raw))
}
token := field(raw, "accessToken")
code, raw, err = httpJSON("POST", server+"/api/v1/agent/pair-code", token, nil)
if err != nil || code != 200 {
return 0, fmt.Errorf("pair-code failed: %s", string(raw))
}
pairCode := field(raw, "code")
return PairWithCode(server, pairCode, deviceName, "core", "0.2.0", pubKeyB64)
}
// PairWithCode 凭配对码注册设备,返回服务器分配的设备 ID
func PairWithCode(server, pairCode, deviceName, osName, version, pubKeyB64 string) (uint64, error) {
pairCode = strings.ToUpper(strings.TrimSpace(pairCode))
deviceName = strings.TrimSpace(deviceName)
if deviceName == "" {
deviceName = "macOS Agent"
}
pubKeyB64 = strings.TrimSpace(pubKeyB64)
if pubKeyB64 == "" {
return 0, fmt.Errorf("本机设备公钥为空,请重启客户端后重试")
}
pubKey, keyErr := base64.StdEncoding.DecodeString(pubKeyB64)
if keyErr != nil || len(pubKey) != ed25519.PublicKeySize {
return 0, fmt.Errorf("本机设备公钥格式错误,请重启客户端后重试")
}
code, raw, err := httpJSON("POST", server+"/api/v1/agent/pair", "", ginH{
"code": pairCode, "deviceName": deviceName, "os": osName, "version": version, "publicKey": pubKeyB64,
})
if err != nil {
return 0, fmt.Errorf("配对请求失败:%w", err)
}
if code != http.StatusOK {
return 0, fmt.Errorf("%s", responseMessage(raw, "配对失败"))
}
id, _ := strconv.ParseUint(field(raw, "deviceId"), 10, 64)
if id == 0 {
return 0, fmt.Errorf("pair response missing deviceId")
}
return id, nil
}
func responseMessage(raw []byte, fallback string) string {
var envelope struct {
Code int `json:"code"`
Message string `json:"message"`
}
if err := json.Unmarshal(raw, &envelope); err == nil && strings.TrimSpace(envelope.Message) != "" {
return envelope.Message
}
if text := strings.TrimSpace(string(raw)); text != "" {
return text
}
return fallback
}