feat(dcauth): 新增后台手机号与设备认证登录
登录链路改为账号密码 + 短信验证码 + DCAuth 设备签名,并新增后台手机号绑定、 登录日志、设备绑定与重置接口。
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
# DCAuth Windows 客户端
|
||||
|
||||
三个系统共用的设备认证客户端,通过 `dcauth://` 协议被浏览器唤起。
|
||||
|
||||
## 构建
|
||||
|
||||
```bash
|
||||
cd apps/dcauth
|
||||
GOOS=windows GOARCH=amd64 go build -trimpath -ldflags "-H windowsgui -s -w" -o dist/DCAuth.exe .
|
||||
```
|
||||
|
||||
ARM64:
|
||||
|
||||
```bash
|
||||
GOOS=windows GOARCH=arm64 go build -trimpath -ldflags "-H windowsgui -s -w" -o dist/DCAuth-arm64.exe .
|
||||
```
|
||||
|
||||
## 首次运行
|
||||
|
||||
直接双击 exe 会:
|
||||
|
||||
- 注册 `dcauth://` 协议到当前 Windows 用户。
|
||||
- 生成 Ed25519 设备密钥,使用 Windows DPAPI 加密保存在 `%LOCALAPPDATA%\DCAuth\device.key`。
|
||||
- 显示设备码和机器码,并复制到剪贴板。
|
||||
|
||||
## macOS 开发调试
|
||||
|
||||
Mac 上不需要安装 Windows exe,也不需要注册自定义协议。登录页在开发模式会显示一条 `dcauth://...` 链接,复制后执行:
|
||||
|
||||
```bash
|
||||
cd apps/dcauth
|
||||
go run . "dcauth://authorize?app=order_site&challenge_id=...&challenge=...&api=http%3A%2F%2Flocalhost%3A5173"
|
||||
```
|
||||
|
||||
客户端会提示确认,然后直接调用本地 Vite 代理的 `/api/dcauth/authorize`,完成本机签名。
|
||||
|
||||
如果只是测后台业务,不想每次都走短信和设备验证,可以在“后台用户”里把测试账号设为 **技术测试**。该账号只使用账号密码登录;正式账号仍必须走短信 + DCAuth。
|
||||
|
||||
## 浏览器联动
|
||||
|
||||
登录页创建 challenge 后跳转:
|
||||
|
||||
```text
|
||||
dcauth://authorize?app=order_site&challenge_id=...&challenge=...&api=https%3A%2F%2Forder.khhao.com
|
||||
```
|
||||
|
||||
客户端校验 app 和 api 白名单后,弹出确认框,签名并提交到:
|
||||
|
||||
```text
|
||||
POST /api/dcauth/authorize
|
||||
```
|
||||
|
||||
浏览器轮询 challenge 状态,拿到一次性 ticket 后完成登录。
|
||||
|
||||
## 支持的应用
|
||||
|
||||
| app | 生产入口 |
|
||||
|---|---|
|
||||
| `order_site` | `https://order.khhao.com` |
|
||||
| `live_hub` | `https://live.khhao.com` |
|
||||
| `affiliate_dash` | `https://skin.khhao.com` |
|
||||
|
||||
本地开发入口已内置在 `main.go` 的 `appRegistry` 中,包括 `http://localhost`、`http://127.0.0.1`、`http://192.168.10.6` 及对应 Vite 端口。
|
||||
|
||||
## 安全说明
|
||||
|
||||
- 私钥不离开本机,使用 DPAPI 保护。
|
||||
- 服务端只保存公钥和机器码哈希/脱敏值。
|
||||
- 机器码采集主板 UUID、MachineGuid、主板/BIOS/系统盘序列号、CPU ID,不上传原始序列号。
|
||||
- 正式分发前建议使用代码签名证书,避免 SmartScreen 和杀毒软件误报。
|
||||
- 如果要做到 token 也不能复制,需要后续让 exe 对每次 API 请求签名,或把 exe 作为唯一客户端。
|
||||
@@ -0,0 +1,89 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const crockfordAlphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
|
||||
|
||||
func buildDeviceID(publicKey []byte) string {
|
||||
material := append([]byte("dcauth.device.v1"), publicKey...)
|
||||
sum := sha256.Sum256(material)
|
||||
return formatCode("D1", sum[:])
|
||||
}
|
||||
|
||||
func buildMachineCode() (string, error) {
|
||||
components, err := collectHardwareComponents()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
keys := make([]string, 0, len(components))
|
||||
for key := range components {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
|
||||
parts := []string{"dcauth.machine.v1"}
|
||||
for _, key := range keys {
|
||||
parts = append(parts, key+"="+components[key])
|
||||
}
|
||||
sum := sha256.Sum256([]byte(strings.Join(parts, "\n")))
|
||||
return formatCode("M1", sum[:]), nil
|
||||
}
|
||||
|
||||
func formatCode(prefix string, data []byte) string {
|
||||
encoded := base32Crockford(data)
|
||||
if len(encoded) > 20 {
|
||||
encoded = encoded[:20]
|
||||
}
|
||||
groups := make([]string, 0, 5)
|
||||
for len(encoded) > 0 {
|
||||
size := 4
|
||||
if len(encoded) < size {
|
||||
size = len(encoded)
|
||||
}
|
||||
groups = append(groups, encoded[:size])
|
||||
encoded = encoded[size:]
|
||||
}
|
||||
return prefix + "-" + strings.Join(groups, "-")
|
||||
}
|
||||
|
||||
func base32Crockford(data []byte) string {
|
||||
var builder strings.Builder
|
||||
var buffer uint32
|
||||
var bits uint
|
||||
for _, value := range data {
|
||||
buffer = (buffer << 8) | uint32(value)
|
||||
bits += 8
|
||||
for bits >= 5 {
|
||||
bits -= 5
|
||||
builder.WriteByte(crockfordAlphabet[(buffer>>bits)&31])
|
||||
}
|
||||
}
|
||||
if bits > 0 {
|
||||
builder.WriteByte(crockfordAlphabet[(buffer<<(5-bits))&31])
|
||||
}
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
func normalizeComponent(value string) string {
|
||||
normalized := strings.ToUpper(strings.TrimSpace(value))
|
||||
normalized = strings.Join(strings.Fields(normalized), "")
|
||||
switch normalized {
|
||||
case "", "0", "NONE", "N/A", "NA", "UNKNOWN", "DEFAULTSTRING",
|
||||
"TOBEFILLEDBYO.E.M.", "TOBEFILLEDBYOEM", "SYSTEMSERIALNUMBER",
|
||||
"00000000-0000-0000-0000-000000000000":
|
||||
return ""
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
func ensureNotEmpty(components map[string]string) error {
|
||||
if len(components) == 0 {
|
||||
return fmt.Errorf("无法读取本机硬件信息,请联系管理员")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
//go:build !windows
|
||||
|
||||
package main
|
||||
|
||||
func protectData(data []byte) ([]byte, error) {
|
||||
return append([]byte(nil), data...), nil
|
||||
}
|
||||
|
||||
func unprotectData(data []byte) ([]byte, error) {
|
||||
return append([]byte(nil), data...), nil
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//go:build windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
type dataBlob struct {
|
||||
cbData uint32
|
||||
pbData *byte
|
||||
}
|
||||
|
||||
var (
|
||||
crypt32DLL = syscall.NewLazyDLL("crypt32.dll")
|
||||
kernel32DLL = syscall.NewLazyDLL("kernel32.dll")
|
||||
cryptProtectData = crypt32DLL.NewProc("CryptProtectData")
|
||||
unprotect = crypt32DLL.NewProc("CryptUnprotectData")
|
||||
localFree = kernel32DLL.NewProc("LocalFree")
|
||||
)
|
||||
|
||||
func protectData(data []byte) ([]byte, error) {
|
||||
if len(data) == 0 {
|
||||
return nil, fmt.Errorf("empty data")
|
||||
}
|
||||
input := dataBlob{cbData: uint32(len(data)), pbData: &data[0]}
|
||||
var output dataBlob
|
||||
result, _, err := cryptProtectData.Call(
|
||||
uintptr(unsafe.Pointer(&input)),
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
uintptr(unsafe.Pointer(&output)),
|
||||
)
|
||||
if result == 0 {
|
||||
return nil, fmt.Errorf("CryptProtectData failed: %w", err)
|
||||
}
|
||||
defer localFree.Call(uintptr(unsafe.Pointer(output.pbData)))
|
||||
return cloneBlob(output), nil
|
||||
}
|
||||
|
||||
func unprotectData(data []byte) ([]byte, error) {
|
||||
if len(data) == 0 {
|
||||
return nil, fmt.Errorf("empty data")
|
||||
}
|
||||
input := dataBlob{cbData: uint32(len(data)), pbData: &data[0]}
|
||||
var output dataBlob
|
||||
result, _, err := unprotect.Call(
|
||||
uintptr(unsafe.Pointer(&input)),
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
uintptr(unsafe.Pointer(&output)),
|
||||
)
|
||||
if result == 0 {
|
||||
return nil, fmt.Errorf("CryptUnprotectData failed: %w", err)
|
||||
}
|
||||
defer localFree.Call(uintptr(unsafe.Pointer(output.pbData)))
|
||||
return cloneBlob(output), nil
|
||||
}
|
||||
|
||||
func cloneBlob(blob dataBlob) []byte {
|
||||
if blob.pbData == nil || blob.cbData == 0 {
|
||||
return nil
|
||||
}
|
||||
return append([]byte(nil), unsafe.Slice(blob.pbData, int(blob.cbData))...)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
module dcauth
|
||||
|
||||
go 1.23
|
||||
@@ -0,0 +1,19 @@
|
||||
//go:build !windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
func collectHardwareComponents() (map[string]string, error) {
|
||||
hostname, _ := os.Hostname()
|
||||
components := map[string]string{
|
||||
"platform": runtime.GOOS + "-" + runtime.GOARCH,
|
||||
}
|
||||
if normalized := normalizeComponent(hostname); normalized != "" {
|
||||
components["hostname"] = normalized
|
||||
}
|
||||
return components, ensureNotEmpty(components)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
//go:build windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os/exec"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func collectHardwareComponents() (map[string]string, error) {
|
||||
components := map[string]string{}
|
||||
|
||||
script := `
|
||||
$ErrorActionPreference = 'SilentlyContinue'
|
||||
$cs = Get-CimInstance Win32_ComputerSystemProduct
|
||||
$bb = Get-CimInstance Win32_BaseBoard
|
||||
$bios = Get-CimInstance Win32_BIOS
|
||||
$cpu = Get-CimInstance Win32_Processor | Select-Object -First 1
|
||||
$disk = Get-CimInstance Win32_DiskDrive | Where-Object { $_.Index -eq 0 } | Select-Object -First 1
|
||||
[pscustomobject]@{
|
||||
smbiosUuid = [string]$cs.UUID
|
||||
baseboardSerial = [string]$bb.SerialNumber
|
||||
biosSerial = [string]$bios.SerialNumber
|
||||
cpuId = [string]$cpu.ProcessorId
|
||||
systemDiskSerial = [string]$disk.SerialNumber
|
||||
} | ConvertTo-Json -Compress
|
||||
`
|
||||
output, err := exec.Command(
|
||||
"powershell.exe",
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-ExecutionPolicy", "Bypass",
|
||||
"-Command", script,
|
||||
).Output()
|
||||
if err == nil {
|
||||
var payload map[string]string
|
||||
if json.Unmarshal([]byte(strings.TrimSpace(string(output))), &payload) == nil {
|
||||
for key, value := range payload {
|
||||
if normalized := normalizeComponent(value); normalized != "" {
|
||||
components[key] = normalized
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if machineGUID := readMachineGUID(); machineGUID != "" {
|
||||
components["machineGuid"] = machineGUID
|
||||
}
|
||||
if err := ensureNotEmpty(components); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return components, nil
|
||||
}
|
||||
|
||||
func readMachineGUID() string {
|
||||
output, err := exec.Command(
|
||||
"reg", "query", `HKLM\SOFTWARE\Microsoft\Cryptography`, "/v", "MachineGuid",
|
||||
).Output()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
line := strings.TrimSpace(string(output))
|
||||
for _, candidate := range strings.Split(line, "\n") {
|
||||
fields := strings.Fields(strings.TrimSpace(candidate))
|
||||
if len(fields) >= 3 && strings.EqualFold(fields[0], "MachineGuid") {
|
||||
return normalizeComponent(strings.Join(fields[2:], " "))
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ed25519"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const clientVersion = "1.0.0"
|
||||
|
||||
type appConfig struct {
|
||||
DisplayName string
|
||||
AllowedAPIs []string
|
||||
}
|
||||
|
||||
var appRegistry = map[string]appConfig{
|
||||
"order_site": {
|
||||
DisplayName: "订单后台",
|
||||
AllowedAPIs: []string{
|
||||
"https://order.khhao.com",
|
||||
"http://localhost",
|
||||
"http://127.0.0.1",
|
||||
"http://localhost:5173",
|
||||
"http://127.0.0.1:5173",
|
||||
"http://localhost:3000",
|
||||
"http://127.0.0.1:3000",
|
||||
"http://192.168.10.6",
|
||||
"http://192.168.10.6:5173",
|
||||
},
|
||||
},
|
||||
"live_hub": {
|
||||
DisplayName: "直播运营后台",
|
||||
AllowedAPIs: []string{
|
||||
"https://live.khhao.com",
|
||||
"http://localhost:5174",
|
||||
"http://127.0.0.1:5174",
|
||||
"http://localhost:8800",
|
||||
"http://127.0.0.1:8800",
|
||||
},
|
||||
},
|
||||
"affiliate_dash": {
|
||||
DisplayName: "皮肤分销后台",
|
||||
AllowedAPIs: []string{
|
||||
"https://skin.khhao.com",
|
||||
"http://localhost:15173",
|
||||
"http://127.0.0.1:15173",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
type identity struct {
|
||||
privateKey ed25519.PrivateKey
|
||||
publicKey ed25519.PublicKey
|
||||
deviceID string
|
||||
machineCode string
|
||||
}
|
||||
|
||||
type authorizeRequest struct {
|
||||
App string `json:"app"`
|
||||
ChallengeID string `json:"challengeId"`
|
||||
Challenge string `json:"challenge"`
|
||||
DeviceID string `json:"deviceId"`
|
||||
MachineCode string `json:"machineCode"`
|
||||
PublicKey string `json:"publicKey"`
|
||||
Signature string `json:"signature"`
|
||||
Timestamp int64 `json:"timestamp"`
|
||||
ClientVersion string `json:"clientVersion"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
registerProtocol()
|
||||
|
||||
identity, err := loadOrCreateIdentity()
|
||||
if err != nil {
|
||||
showError("DCAuth 初始化失败", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
protocolArg := findProtocolArg(os.Args[1:])
|
||||
if protocolArg == "" {
|
||||
text := fmt.Sprintf(
|
||||
"设备码:%s\n机器码:%s\n\n设备码用于识别本机,机器码用于管理员核对。\n请从后台登录页点击“验证本机”完成登录。",
|
||||
identity.deviceID,
|
||||
identity.machineCode,
|
||||
)
|
||||
copyToClipboard(identity.deviceID + "\n" + identity.machineCode)
|
||||
showInfo("DCAuth 设备信息", text+"\n\n设备码和机器码已复制到剪贴板。")
|
||||
return
|
||||
}
|
||||
|
||||
target, err := parseAuthorizeURL(protocolArg)
|
||||
if err != nil {
|
||||
showError("DCAuth 协议无效", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
app := appRegistry[target.App]
|
||||
if !confirm(
|
||||
app.DisplayName+" · 本机登录确认",
|
||||
fmt.Sprintf("是否确认使用本机设备登录「%s」?\n\n设备码:%s\n机器码:%s", app.DisplayName, identity.deviceID, identity.machineCode),
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := submitAuthorization(identity, target); err != nil {
|
||||
showError("本机验证失败", err.Error())
|
||||
return
|
||||
}
|
||||
showInfo("本机验证成功", "已确认本机设备,请回到浏览器继续登录。")
|
||||
}
|
||||
|
||||
type authorizeTarget struct {
|
||||
App string
|
||||
ChallengeID string
|
||||
Challenge string
|
||||
APIBase string
|
||||
}
|
||||
|
||||
func findProtocolArg(args []string) string {
|
||||
for _, arg := range args {
|
||||
if strings.HasPrefix(strings.ToLower(strings.TrimSpace(arg)), "dcauth://") {
|
||||
return strings.TrimSpace(arg)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func parseAuthorizeURL(raw string) (authorizeTarget, error) {
|
||||
parsed, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return authorizeTarget{}, fmt.Errorf("无法解析协议地址")
|
||||
}
|
||||
if !strings.EqualFold(parsed.Scheme, "dcauth") {
|
||||
return authorizeTarget{}, fmt.Errorf("协议 scheme 不是 dcauth")
|
||||
}
|
||||
if !strings.EqualFold(parsed.Host, "authorize") && !strings.EqualFold(strings.Trim(parsed.Path, "/"), "authorize") {
|
||||
return authorizeTarget{}, fmt.Errorf("不支持的协议动作")
|
||||
}
|
||||
|
||||
query := parsed.Query()
|
||||
appID := strings.TrimSpace(query.Get("app"))
|
||||
challengeID := strings.TrimSpace(query.Get("challenge_id"))
|
||||
challenge := strings.TrimSpace(query.Get("challenge"))
|
||||
apiBase := strings.TrimRight(strings.TrimSpace(query.Get("api")), "/")
|
||||
|
||||
if appID == "" || challengeID == "" || challenge == "" || apiBase == "" {
|
||||
return authorizeTarget{}, fmt.Errorf("缺少 app、challenge_id、challenge 或 api 参数")
|
||||
}
|
||||
if len(challengeID) > 128 || len(challenge) > 512 {
|
||||
return authorizeTarget{}, fmt.Errorf("challenge 参数过长")
|
||||
}
|
||||
|
||||
config, ok := appRegistry[appID]
|
||||
if !ok {
|
||||
return authorizeTarget{}, fmt.Errorf("未知应用:%s", appID)
|
||||
}
|
||||
origin, err := normalizeOrigin(apiBase)
|
||||
if err != nil {
|
||||
return authorizeTarget{}, err
|
||||
}
|
||||
if !containsOrigin(config.AllowedAPIs, origin) {
|
||||
return authorizeTarget{}, fmt.Errorf("应用 %s 不允许访问 %s", appID, origin)
|
||||
}
|
||||
|
||||
return authorizeTarget{
|
||||
App: appID,
|
||||
ChallengeID: challengeID,
|
||||
Challenge: challenge,
|
||||
APIBase: origin,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func normalizeOrigin(raw string) (string, error) {
|
||||
parsed, err := url.Parse(raw)
|
||||
if err != nil || parsed.Host == "" {
|
||||
return "", fmt.Errorf("api 地址无效")
|
||||
}
|
||||
if parsed.Scheme != "https" && parsed.Scheme != "http" {
|
||||
return "", fmt.Errorf("api 地址必须使用 http 或 https")
|
||||
}
|
||||
if parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" {
|
||||
return "", fmt.Errorf("api 地址不允许携带用户信息、查询串或片段")
|
||||
}
|
||||
path := strings.TrimRight(parsed.EscapedPath(), "/")
|
||||
if path != "" {
|
||||
return "", fmt.Errorf("api 必须是不带路径的 origin")
|
||||
}
|
||||
return strings.ToLower(parsed.Scheme) + "://" + strings.ToLower(parsed.Host), nil
|
||||
}
|
||||
|
||||
func containsOrigin(allowed []string, origin string) bool {
|
||||
for _, item := range allowed {
|
||||
if strings.EqualFold(strings.TrimRight(item, "/"), origin) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func submitAuthorization(id identity, target authorizeTarget) error {
|
||||
timestamp := time.Now().Unix()
|
||||
canonical := strings.Join([]string{
|
||||
"dcauth.v1",
|
||||
target.App,
|
||||
target.ChallengeID,
|
||||
target.Challenge,
|
||||
id.deviceID,
|
||||
id.machineCode,
|
||||
fmt.Sprintf("%d", timestamp),
|
||||
}, "\n")
|
||||
signature := ed25519.Sign(id.privateKey, []byte(canonical))
|
||||
|
||||
payload := authorizeRequest{
|
||||
App: target.App,
|
||||
ChallengeID: target.ChallengeID,
|
||||
Challenge: target.Challenge,
|
||||
DeviceID: id.deviceID,
|
||||
MachineCode: id.machineCode,
|
||||
PublicKey: base64.RawURLEncoding.EncodeToString(id.publicKey),
|
||||
Signature: base64.RawURLEncoding.EncodeToString(signature),
|
||||
Timestamp: timestamp,
|
||||
ClientVersion: clientVersion,
|
||||
}
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return fmt.Errorf("生成请求失败")
|
||||
}
|
||||
|
||||
request, err := http.NewRequest(http.MethodPost, target.APIBase+"/api/dcauth/authorize", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return fmt.Errorf("生成请求失败")
|
||||
}
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("User-Agent", "DCAuth/"+clientVersion)
|
||||
|
||||
client := &http.Client{Timeout: 15 * time.Second}
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
return fmt.Errorf("无法连接服务器:%w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
responseBody, _ := io.ReadAll(io.LimitReader(response.Body, 64*1024))
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
return fmt.Errorf("服务器拒绝本机验证(HTTP %d):%s", response.StatusCode, summarizeResponse(responseBody))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func summarizeResponse(body []byte) string {
|
||||
var payload map[string]any
|
||||
if json.Unmarshal(body, &payload) == nil {
|
||||
for _, key := range []string{"msg", "message", "detail", "error"} {
|
||||
if value, ok := payload[key].(string); ok && strings.TrimSpace(value) != "" {
|
||||
return strings.TrimSpace(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
text := strings.TrimSpace(string(body))
|
||||
if len(text) > 200 {
|
||||
text = text[:200] + "..."
|
||||
}
|
||||
if text == "" {
|
||||
return "无响应内容"
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
func deviceKeyPath() (string, error) {
|
||||
base := strings.TrimSpace(os.Getenv("LOCALAPPDATA"))
|
||||
if base == "" {
|
||||
configDir, err := os.UserConfigDir()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("无法定位用户配置目录")
|
||||
}
|
||||
base = configDir
|
||||
}
|
||||
dir := filepath.Join(base, "DCAuth")
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return "", fmt.Errorf("无法创建设备密钥目录:%w", err)
|
||||
}
|
||||
return filepath.Join(dir, "device.key"), nil
|
||||
}
|
||||
|
||||
func loadOrCreateIdentity() (identity, error) {
|
||||
keyPath, err := deviceKeyPath()
|
||||
if err != nil {
|
||||
return identity{}, err
|
||||
}
|
||||
|
||||
var privateKey ed25519.PrivateKey
|
||||
encrypted, readErr := os.ReadFile(keyPath)
|
||||
if readErr == nil {
|
||||
raw, err := unprotectData(encrypted)
|
||||
if err != nil {
|
||||
return identity{}, fmt.Errorf("设备密钥无法解密,请确认当前 Windows 用户未变化")
|
||||
}
|
||||
if len(raw) != ed25519.PrivateKeySize {
|
||||
return identity{}, fmt.Errorf("设备密钥文件损坏,请删除 %s 后重试", keyPath)
|
||||
}
|
||||
privateKey = ed25519.PrivateKey(raw)
|
||||
} else if os.IsNotExist(readErr) {
|
||||
_, generated, err := ed25519.GenerateKey(nil)
|
||||
if err != nil {
|
||||
return identity{}, fmt.Errorf("生成设备密钥失败")
|
||||
}
|
||||
privateKey = generated
|
||||
protected, err := protectData([]byte(privateKey))
|
||||
if err != nil {
|
||||
return identity{}, fmt.Errorf("保护设备密钥失败:%w", err)
|
||||
}
|
||||
if err := os.WriteFile(keyPath, protected, 0o600); err != nil {
|
||||
return identity{}, fmt.Errorf("保存设备密钥失败:%w", err)
|
||||
}
|
||||
} else {
|
||||
return identity{}, fmt.Errorf("读取设备密钥失败:%w", readErr)
|
||||
}
|
||||
|
||||
publicKey := privateKey.Public().(ed25519.PublicKey)
|
||||
machineCode, err := buildMachineCode()
|
||||
if err != nil {
|
||||
return identity{}, err
|
||||
}
|
||||
return identity{
|
||||
privateKey: privateKey,
|
||||
publicKey: publicKey,
|
||||
deviceID: buildDeviceID(publicKey),
|
||||
machineCode: machineCode,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestParseAuthorizeURLAllowedOrigins(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
api string
|
||||
expected string
|
||||
}{
|
||||
{name: "localhost", api: "http%3A%2F%2Flocalhost", expected: "http://localhost"},
|
||||
{name: "localhost trailing slash", api: "http%3A%2F%2Flocalhost%2F", expected: "http://localhost"},
|
||||
{name: "lan address", api: "http%3A%2F%2F192.168.10.6", expected: "http://192.168.10.6"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
raw := "dcauth://authorize?app=order_site&challenge_id=challenge-id&challenge=challenge-value&api=" + tt.api
|
||||
target, err := parseAuthorizeURL(raw)
|
||||
if err != nil {
|
||||
t.Fatalf("parseAuthorizeURL() error = %v", err)
|
||||
}
|
||||
if target.APIBase != tt.expected {
|
||||
t.Fatalf("APIBase = %q, want %q", target.APIBase, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseAuthorizeURLRejectsUnknownOrigin(t *testing.T) {
|
||||
raw := "dcauth://authorize?app=order_site&challenge_id=challenge-id&challenge=challenge-value&api=http%3A%2F%2Fexample.com"
|
||||
if _, err := parseAuthorizeURL(raw); err == nil {
|
||||
t.Fatal("parseAuthorizeURL() accepted an unknown origin")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
//go:build !windows
|
||||
|
||||
package main
|
||||
|
||||
func registerProtocol() {}
|
||||
@@ -0,0 +1,26 @@
|
||||
//go:build windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func registerProtocol() {
|
||||
executable, err := os.Executable()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
executable, err = filepath.Abs(executable)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
command := `"` + executable + `" "%1"`
|
||||
|
||||
_ = exec.Command("reg", "add", `HKCU\Software\Classes\dcauth`, "/ve", "/d", "URL:DCAuth Protocol", "/f").Run()
|
||||
_ = exec.Command("reg", "add", `HKCU\Software\Classes\dcauth`, "/v", "URL Protocol", "/d", "", "/f").Run()
|
||||
_ = exec.Command("reg", "add", `HKCU\Software\Classes\dcauth\DefaultIcon`, "/ve", "/d", executable+",0", "/f").Run()
|
||||
_ = exec.Command("reg", "add", `HKCU\Software\Classes\dcauth\shell\open\command`, "/ve", "/d", command, "/f").Run()
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
//go:build !windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
func showInfo(title, text string) {
|
||||
fmt.Printf("[%s]\n%s\n", title, text)
|
||||
}
|
||||
|
||||
func showError(title, text string) {
|
||||
fmt.Fprintf(os.Stderr, "[%s]\n%s\n", title, text)
|
||||
}
|
||||
|
||||
func confirm(title, text string) bool {
|
||||
fmt.Printf("[%s]\n%s\n[y/N] ", title, text)
|
||||
var answer string
|
||||
_, _ = fmt.Scanln(&answer)
|
||||
return answer == "y" || answer == "Y"
|
||||
}
|
||||
|
||||
func copyToClipboard(text string) {
|
||||
_ = text
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
//go:build windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"unicode/utf16"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
mbOK = 0x00000000
|
||||
mbOKCancel = 0x00000001
|
||||
mbIconError = 0x00000010
|
||||
mbIconQuestion = 0x00000020
|
||||
mbIconInformation = 0x00000040
|
||||
idOK = 1
|
||||
)
|
||||
|
||||
const (
|
||||
cfUnicodeText = 13
|
||||
gmemMoveable = 0x0002
|
||||
)
|
||||
|
||||
var (
|
||||
user32DLL = syscall.NewLazyDLL("user32.dll")
|
||||
messageBoxW = user32DLL.NewProc("MessageBoxW")
|
||||
openClip = user32DLL.NewProc("OpenClipboard")
|
||||
closeClip = user32DLL.NewProc("CloseClipboard")
|
||||
emptyClip = user32DLL.NewProc("EmptyClipboard")
|
||||
setClipData = user32DLL.NewProc("SetClipboardData")
|
||||
globalAlloc = kernel32DLL.NewProc("GlobalAlloc")
|
||||
globalLock = kernel32DLL.NewProc("GlobalLock")
|
||||
globalUnlock = kernel32DLL.NewProc("GlobalUnlock")
|
||||
)
|
||||
|
||||
func showInfo(title, text string) {
|
||||
showMessage(title, text, mbOK|mbIconInformation)
|
||||
}
|
||||
|
||||
func showError(title, text string) {
|
||||
showMessage(title, text, mbOK|mbIconError)
|
||||
}
|
||||
|
||||
func confirm(title, text string) bool {
|
||||
return showMessage(title, text, mbOKCancel|mbIconQuestion) == idOK
|
||||
}
|
||||
|
||||
func showMessage(title, text string, flags uint) int {
|
||||
titlePtr, _ := syscall.UTF16PtrFromString(title)
|
||||
textPtr, _ := syscall.UTF16PtrFromString(text)
|
||||
result, _, _ := messageBoxW.Call(
|
||||
0,
|
||||
uintptr(unsafe.Pointer(textPtr)),
|
||||
uintptr(unsafe.Pointer(titlePtr)),
|
||||
uintptr(flags),
|
||||
)
|
||||
return int(result)
|
||||
}
|
||||
|
||||
func copyToClipboard(text string) {
|
||||
opened, _, _ := openClip.Call(0)
|
||||
if opened == 0 {
|
||||
return
|
||||
}
|
||||
defer closeClip.Call()
|
||||
emptyClip.Call()
|
||||
|
||||
encoded := utf16.Encode([]rune(text))
|
||||
encoded = append(encoded, 0)
|
||||
size := uintptr(len(encoded) * 2)
|
||||
handle, _, _ := globalAlloc.Call(gmemMoveable, size)
|
||||
if handle == 0 {
|
||||
return
|
||||
}
|
||||
pointer, _, _ := globalLock.Call(handle)
|
||||
if pointer == 0 {
|
||||
return
|
||||
}
|
||||
target := unsafe.Slice((*uint16)(unsafe.Pointer(pointer)), len(encoded))
|
||||
copy(target, encoded)
|
||||
globalUnlock.Call(handle)
|
||||
setClipData.Call(cfUnicodeText, handle)
|
||||
}
|
||||
Reference in New Issue
Block a user