feat(remote): 支持单行连接与同机实例继承

- 远端地址和注册令牌合并为单行填写\n- 同机实例通过机器级配置继承远端连接\n- 实例令牌仍按实例独立保存
This commit is contained in:
yml
2026-11-21 22:01:33 +08:00
parent 3cb7a6bad8
commit d37fd50233
8 changed files with 310 additions and 27 deletions
+2 -2
View File
@@ -79,9 +79,9 @@ GOOS=linux GOARCH=amd64 wails build
./build/bin/douyu-control -addr :18080 -data ./remote-data
```
程序会打印一个带自动登录信息的管理链接。桌面端在“设置 -> 远端控制”中填写控制中心地址和注册令牌,实例首次连接会换取独立令牌并保存在本机。
程序会打印一个带自动登录信息的管理链接。桌面端在“设置 -> 远端控制”中用一行填写控制中心地址和注册令牌,实例首次连接会换取独立令牌;同机其他实例会自动继承远程地址和注册令牌。
桌面端只填写根地址,例如 `https://control.example.com`,不要带 `/#admin=...` 或子路径。
连接示例:`https://control.example.com enroll-token`。不要带 `/#admin=...` 或子路径。
公网部署使用 [deploy/control-center](deploy/control-center/README.md) 中的 Docker Compose 和 Caddy 示例。容器只监听回环地址,HTTPS 由宿主机现有 Caddy 终止。
+14 -3
View File
@@ -156,13 +156,20 @@
| 字段 | 说明 |
|---|---|
| 启用远端上报 | 开启或关闭当前实例的远端功能 |
| 控制中心地址 | 例如 `https://control.example.com` |
| 注册令牌 | 与控制中心的 `DOUYU_CONTROL_ENROLL_TOKEN` 相同 |
| 控制中心连接 | 一行填写地址和注册令牌,例如 `https://control.example.com enroll-token` |
| 机器显示名称 | 留空时使用主机名 |
实例令牌不需要填写,也不会显示在设置中。旧版 `remoteToken` 仅作为兼容字段保留。
控制中心地址必须是根地址,例如 `https://control.example.com`。不要填写 `/#admin=...`、查询参数或子路径。
连接信息支持空格或 `|` 分隔,也支持 `#enroll=<令牌>` 格式。地址必须是根地址,不要填写 `/#admin=...`、其他查询参数或子路径。
远程启用状态、控制中心地址、注册令牌和机器名称保存在:
```text
<机器数据根目录>/remote/remote-profile.json
```
同一台电脑上后续启动的实例会自动继承该文件。实例令牌仍按实例独立保存在 `remote/instances/`,不会互相覆盖。
主界面顶栏会显示远端状态:
@@ -369,8 +376,11 @@ to RFC3339
```text
<机器数据根目录>/remote/machine_id
<机器数据根目录>/remote/instances/<实例>.json
<机器数据根目录>/remote/remote-profile.json
```
`remote-profile.json` 用于同机多实例继承远程地址和注册令牌,权限必须为当前用户私有。
软件原本的人类可读日志仍保存在各实例的 `LogDir`,远端功能不会删除或替换本地日志。
## 12. 异步与离线行为
@@ -455,6 +465,7 @@ GET /api/export?format=json 能下载结构化日志
| 2026-11-21 | 建立远端控制、自动注册、动态机器聚合、实时日志、运行记录、主界面状态入口、CSV/JSON 导出 |
| 2026-11-21 | 实例快照增加结构化代理状态,Web 控制台可查看代理组、出口和账号分组 |
| 2026-11-21 | 增加独立注册令牌配置和 `deploy/control-center` Docker/Caddy 部署目录 |
| 2026-11-21 | 远端连接改为单行填写,并增加同机多实例自动继承 |
## 18. 代理白名单协同规划
+32 -22
View File
@@ -1,7 +1,8 @@
<script setup lang="ts">
import { computed, nextTick, ref } from 'vue'
import { useSettings, type RetryStage } from '@/composables/useSettings'
import { useSettings, type RetryStage, type Settings } from '@/composables/useSettings'
import { useToast } from '@/composables/useToast'
import { formatRemoteConnection, parseRemoteConnection } from '@/utils/remoteConnection'
import {
TestProxy,
FetchProxy,
@@ -43,8 +44,7 @@ const formData = ref({
proxyWhitelistPassword: '',
proxyWhitelistSignKey: '',
remoteEnabled: false,
remoteUrl: '',
remoteEnrollmentToken: '',
remoteConnection: '',
remoteToken: '',
remoteMachineName: ''
})
@@ -154,7 +154,7 @@ const handleProxyDrill = async () => {
drillRunning.value = true
drillResult.value = null
try {
const saved = await saveSettings(formData.value)
const saved = await saveForm()
if (!saved) return
const res = await RunProxyDrill(types.ProxyDrillRequest.createFrom({
simulatedAccounts: drillAccounts.value
@@ -175,10 +175,29 @@ const handleProxyDrill = async () => {
const copySettingsToForm = () => {
formData.value = {
...settings.value,
remoteConnection: formatRemoteConnection(settings.value.remoteUrl, settings.value.remoteEnrollmentToken),
retryStages: settings.value.retryStages.map(s => ({ ...s }))
}
}
const saveForm = async () => {
let remote
try {
remote = parseRemoteConnection(formData.value.remoteConnection)
} catch (e: any) {
showToast('控制中心连接无效', e?.message || String(e), 'error')
return false
}
const { remoteConnection, ...rest } = formData.value
void remoteConnection
const payload: Settings = {
...rest,
remoteUrl: remote.url,
remoteEnrollmentToken: remote.enrollmentToken
}
return saveSettings(payload)
}
const handleSelectSharedProxyConfig = async (save: boolean) => {
try {
const res = await SelectSharedProxyConfigFile(save)
@@ -220,7 +239,7 @@ const handleSaveSharedProxyConfig = async () => {
if (!path) return
formData.value.sharedProxyConfigFile = path
try {
const saved = await saveSettings(formData.value)
const saved = await saveForm()
if (!saved) return
const res = await SaveSharedProxyConfig(path)
if (!res.success) {
@@ -253,7 +272,7 @@ const close = () => {
}
const handleSave = async () => {
const success = await saveSettings(formData.value)
const success = await saveForm()
if (success) {
close()
}
@@ -600,26 +619,17 @@ defineExpose({ open, close })
</div>
<template v-if="formData.remoteEnabled">
<div class="form-group">
<label class="form-label">控制中心地址</label>
<label class="form-label">控制中心连接</label>
<input
v-model="formData.remoteUrl"
v-model="formData.remoteConnection"
class="form-input"
type="url"
placeholder="https://control.example.com 或 http://127.0.0.1:18080"
type="text"
autocomplete="off"
placeholder="https://control.khhao.com 注册令牌"
>
<div class="form-hint">只填写控制中心根地址,不要带 /#admin= 后面的管理令牌。</div>
<div class="form-hint">一行粘贴“远程地址 + 注册令牌”,空格或 | 分隔;同机其他实例会自动继承。</div>
</div>
<div class="form-row">
<div class="form-group">
<label class="form-label">注册令牌</label>
<input
v-model="formData.remoteEnrollmentToken"
class="form-input"
type="password"
autocomplete="off"
placeholder="填写控制中心的 DOUYU_CONTROL_ENROLL_TOKEN"
>
</div>
<div class="form-group">
<label class="form-label">机器显示名称</label>
<input
@@ -631,7 +641,7 @@ defineExpose({ open, close })
</div>
</div>
<div class="form-hint">
首次连接使用注册令牌领取独立实例令牌并保存在本机,后续不需要再次填写。注册令牌只用于注册,不会作为实例连接令牌使用。
注册令牌只用于首次领取独立实例令牌,不会作为实例连接令牌使用。远程地址和注册令牌由同一台电脑的实例共享,实例令牌仍各自独立保存。
Cookie、CSRF、代理密码、签名密钥和 Trace 内容不会上传。远端只接收结构化日志、运行摘要和控制命令。
</div>
</template>
+73
View File
@@ -0,0 +1,73 @@
export interface ParsedRemoteConnection {
url: string
enrollmentToken: string
}
export function formatRemoteConnection(url: string, enrollmentToken: string): string {
const address = url.trim()
const token = enrollmentToken.trim()
if (!address) return token
return token ? `${address} ${token}` : address
}
export function parseRemoteConnection(raw: string): ParsedRemoteConnection {
const value = raw.trim()
if (!value) {
return { url: '', enrollmentToken: '' }
}
let address = value
let enrollmentToken = ''
const separated = value.match(/^(\S+?)(?:\s+|\s*\|\s*)(.+)$/)
if (separated) {
address = separated[1].trim()
enrollmentToken = separated[2].trim()
}
let parsed: URL
try {
parsed = new URL(address)
} catch {
throw new Error('控制中心连接格式错误,应为:https://control.example.com 注册令牌')
}
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
throw new Error('控制中心地址必须以 http:// 或 https:// 开头')
}
if (parsed.username || parsed.password) {
throw new Error('控制中心地址不能包含用户名或密码')
}
if (parsed.pathname.trim() !== '' && parsed.pathname.trim() !== '/') {
throw new Error('控制中心地址必须是根地址,不能包含子路径')
}
const hash = parsed.hash.startsWith('#') ? parsed.hash.slice(1) : parsed.hash
const hashParams = new URLSearchParams(hash)
if (hashParams.has('admin')) {
throw new Error('这里不能填写 #admin 管理链接,请填写地址和注册令牌')
}
if (!enrollmentToken) {
enrollmentToken = hashParams.get('enroll') || hashParams.get('enrollment') || ''
}
hashParams.delete('enroll')
hashParams.delete('enrollment')
if (hashParams.toString()) {
throw new Error('控制中心地址包含无法识别的片段')
}
if (!enrollmentToken) {
enrollmentToken = parsed.searchParams.get('enroll') || parsed.searchParams.get('enrollment') || ''
}
parsed.searchParams.delete('enroll')
parsed.searchParams.delete('enrollment')
if (parsed.searchParams.toString()) {
throw new Error('控制中心地址不能包含其他查询参数')
}
parsed.hash = ''
parsed.search = ''
parsed.pathname = ''
return {
url: parsed.origin,
enrollmentToken: enrollmentToken.trim()
}
}
+13
View File
@@ -187,6 +187,14 @@ func (a *App) Startup(ctx context.Context) {
// 优先初始化调度器和账号库,避免前端首屏请求早于启动网络探测时读到 nil。
cfg := config.LoadConfig(a.paths.ConfigFile)
profileFound := false
if profile, ok, err := config.LoadMachineRemoteProfile(); err != nil {
logger.LogEvent("配置", "warn", "读取本机共享远端配置失败: %v", err)
} else if ok {
config.ApplyMachineRemoteProfile(&cfg, profile)
profileFound = true
logger.LogEvent("配置", "success", "已继承本机共享远端配置")
}
sharedPath := strings.TrimSpace(cfg.SharedProxyConfigFile)
if sharedPath == "" {
if inheritedPath, err := config.LoadSharedProxyConfigPointer(); err != nil {
@@ -205,6 +213,11 @@ func (a *App) Startup(ctx context.Context) {
logger.LogEvent("配置", "success", "已加载共享代理配置: %s", sharedPath)
}
}
if !profileFound && cfg.RemoteEnabled {
if err := config.SaveMachineRemoteProfile(cfg); err != nil {
logger.LogEvent("配置", "warn", "初始化本机共享远端配置失败: %v", err)
}
}
a.setCfg(cfg)
logger.SetMinLevel(cfg.LogLevel)
a.replaceTrace(cfg)
+3
View File
@@ -180,6 +180,9 @@ func (a *App) SaveSettings(cfg types.Config) types.ErrorResult {
cfg.RemoteToken != oldCfg.RemoteToken ||
cfg.RemoteMachineName != oldCfg.RemoteMachineName
if remoteChanged {
if err := config.SaveMachineRemoteProfile(cfg); err != nil {
logger.LogEvent("配置", "warn", "保存本机共享远端配置失败: %v", err)
}
a.configureRemote(cfg)
}
if clientChanged {
+107
View File
@@ -0,0 +1,107 @@
package config
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"douyu_go/internal/types"
)
const machineRemoteProfileSchemaVersion = 1
const machineRemoteProfileFile = "remote-profile.json"
type MachineRemoteProfile struct {
SchemaVersion int `json:"schemaVersion"`
UpdatedAt string `json:"updatedAt"`
Enabled bool `json:"enabled"`
URL string `json:"url"`
EnrollmentToken string `json:"enrollmentToken"`
MachineName string `json:"machineName"`
}
func machineRemoteProfilePath() string {
return filepath.Join(defaultDataDir(), "remote", machineRemoteProfileFile)
}
// LoadMachineRemoteProfile loads the remote connection shared by every local instance.
func LoadMachineRemoteProfile() (MachineRemoteProfile, bool, error) {
data, err := os.ReadFile(machineRemoteProfilePath())
if errors.Is(err, os.ErrNotExist) {
return MachineRemoteProfile{}, false, nil
}
if err != nil {
return MachineRemoteProfile{}, false, err
}
var profile MachineRemoteProfile
if err := json.Unmarshal(data, &profile); err != nil {
return MachineRemoteProfile{}, false, fmt.Errorf("解析本机远端配置失败: %w", err)
}
if profile.SchemaVersion != machineRemoteProfileSchemaVersion {
return MachineRemoteProfile{}, false, fmt.Errorf(
"不支持的本机远端配置版本 %d,当前仅支持 %d",
profile.SchemaVersion, machineRemoteProfileSchemaVersion,
)
}
profile.URL = strings.TrimSpace(profile.URL)
profile.EnrollmentToken = strings.TrimSpace(profile.EnrollmentToken)
profile.MachineName = strings.TrimSpace(profile.MachineName)
return profile, true, nil
}
// SaveMachineRemoteProfile persists connection metadata inherited by future local instances.
func SaveMachineRemoteProfile(cfg types.Config) error {
profile := MachineRemoteProfile{
SchemaVersion: machineRemoteProfileSchemaVersion,
UpdatedAt: time.Now().Format(time.RFC3339),
Enabled: cfg.RemoteEnabled,
URL: strings.TrimSpace(cfg.RemoteURL),
EnrollmentToken: strings.TrimSpace(cfg.RemoteEnrollmentToken),
MachineName: strings.TrimSpace(cfg.RemoteMachineName),
}
data, err := json.MarshalIndent(profile, "", " ")
if err != nil {
return err
}
path := machineRemoteProfilePath()
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
return err
}
temp, err := os.CreateTemp(filepath.Dir(path), ".remote-profile-*.tmp")
if err != nil {
return err
}
tempPath := temp.Name()
defer func() {
_ = os.Remove(tempPath)
}()
if err := temp.Chmod(0600); err != nil {
_ = temp.Close()
return err
}
if _, err := temp.Write(data); err != nil {
_ = temp.Close()
return err
}
if err := temp.Close(); err != nil {
return err
}
if err := os.Rename(tempPath, path); err != nil {
return err
}
return nil
}
func ApplyMachineRemoteProfile(cfg *types.Config, profile MachineRemoteProfile) {
if cfg == nil {
return
}
cfg.RemoteEnabled = profile.Enabled
cfg.RemoteURL = profile.URL
cfg.RemoteEnrollmentToken = profile.EnrollmentToken
cfg.RemoteMachineName = profile.MachineName
}
@@ -0,0 +1,66 @@
package config
import (
"os"
"path/filepath"
"testing"
"douyu_go/internal/types"
)
func TestMachineRemoteProfileIsInheritedByOtherInstances(t *testing.T) {
root := t.TempDir()
t.Setenv("DOUYU_DATA_DIR", root)
source := types.Config{
RemoteEnabled: true,
RemoteURL: " https://control.khhao.com ",
RemoteEnrollmentToken: " enroll-secret ",
RemoteMachineName: " PC-01 ",
}
if err := SaveMachineRemoteProfile(source); err != nil {
t.Fatal(err)
}
info, err := os.Stat(filepath.Join(root, "remote", machineRemoteProfileFile))
if err != nil {
t.Fatal(err)
}
if info.Mode().Perm() != 0600 {
t.Fatalf("profile mode=%o, want 600", info.Mode().Perm())
}
profile, ok, err := LoadMachineRemoteProfile()
if err != nil {
t.Fatal(err)
}
if !ok {
t.Fatal("machine remote profile should exist")
}
var inherited types.Config
ApplyMachineRemoteProfile(&inherited, profile)
if !inherited.RemoteEnabled ||
inherited.RemoteURL != "https://control.khhao.com" ||
inherited.RemoteEnrollmentToken != "enroll-secret" ||
inherited.RemoteMachineName != "PC-01" {
t.Fatalf("unexpected inherited remote config: %+v", inherited)
}
}
func TestMachineRemoteProfileCanDisableRemoteForNewInstances(t *testing.T) {
t.Setenv("DOUYU_DATA_DIR", t.TempDir())
if err := SaveMachineRemoteProfile(types.Config{
RemoteEnabled: false,
RemoteURL: "https://control.khhao.com",
}); err != nil {
t.Fatal(err)
}
profile, ok, err := LoadMachineRemoteProfile()
if err != nil || !ok {
t.Fatalf("LoadMachineRemoteProfile() ok=%v err=%v", ok, err)
}
cfg := types.Config{RemoteEnabled: true}
ApplyMachineRemoteProfile(&cfg, profile)
if cfg.RemoteEnabled {
t.Fatal("disabled machine profile should disable remote for new instances")
}
}