diff --git a/README.MD b/README.MD index 4d041ea..5f7835e 100644 --- a/README.MD +++ b/README.MD @@ -56,3 +56,29 @@ GOOS=linux GOARCH=amd64 wails build | `DOUYU_FONT` | 自定义字体路径 | 自动检测系统字体 | | `DOUYU_TRACE` | 启用 HTTP 追踪 | 关闭 | | `DOUYU_TRACE_MAX_BODY` | trace 正文最大字节数 | 无限制 | +| `DOUYU_CONTROL_ADDR` | 远端控制台监听地址 | `:18080` | +| `DOUYU_CONTROL_DATA` | 远端控制台数据目录 | `remote-data` | +| `DOUYU_CONTROL_OPERATOR_TOKEN` | 网页控制台令牌 | 启动时随机生成 | +| `DOUYU_CONTROL_ENROLL_TOKEN` | 可选的新实例注册口令 | 空 | +| `DOUYU_CONTROL_ENROLL_WINDOW` | 无注册口令时的自动注册窗口 | `10m` | + +## 远端控制(可选) + +远端控制不参与本地定时、代理准备、锁单和支付链路。网络中断时实例继续本地抢购,事件写入本地缓冲后可重连补传。 + +构建并启动控制中心: + +```bash +./build.sh control +./build/bin/douyu-control -addr :18080 -data ./remote-data +``` + +程序会打印一个带自动登录信息的管理链接。桌面端在“设置 -> 远端控制”中只需要填写控制中心地址,实例首次连接会自动注册并把独立令牌保存在本机。默认自动注册窗口为控制中心启动后的 10 分钟,窗口关闭后不再接受新实例。 + +说明: + +- 实例主动通过 WebSocket 外连并自动注册,不需要为每台抢购电脑开放入站端口,也不需要手工配置实例令牌。 +- 控制台按 `machineId` 动态聚合任意数量的实例,可查看机器、实例、运行结果和实时结构化日志;不假定固定实例数。 +- 当前支持远端刷新状态、停止抢购和取消定时;启动/定时任务仍以本地配置为准。 +- Cookie、CSRF、代理密码、白名单签名密钥和 Trace 正文不会上传。 +- 公网部署时请在控制中心前放置 HTTPS 反向代理,并使用强随机令牌。 diff --git a/build.sh b/build.sh index e5c1178..9bc36fd 100755 --- a/build.sh +++ b/build.sh @@ -8,6 +8,7 @@ # ./build.sh mac-arm # 构建 macOS ARM64 版本 # ./build.sh release # 构建 Windows amd64 和 macOS ARM64 # ./build.sh linux # 构建 Linux 版本 +# ./build.sh control # 构建远端控制台 # ./build.sh clean # 清理构建产物 # ./build.sh install # 安装前端依赖 @@ -173,6 +174,14 @@ build_linux() { ls -lh build/bin/ } +# 构建远端控制中心 +build_control() { + info "构建远端控制中心..." + mkdir -p build/bin + go build -o build/bin/douyu-control ./cmd/douyu-control + success "远端控制中心构建完成: build/bin/douyu-control" +} + # 清理构建产物 clean_build() { info "清理构建产物..." @@ -196,6 +205,7 @@ show_help() { echo " ./build.sh mac-arm # 构建 macOS ARM64 版本" echo " ./build.sh release # 构建 Windows amd64 和 macOS ARM64" echo " ./build.sh linux # 构建 Linux 版本" + echo " ./build.sh control # 构建远端控制台" echo " ./build.sh clean # 清理构建产物" echo " ./build.sh install # 安装前端依赖" echo " ./build.sh help # 显示此帮助" @@ -232,6 +242,9 @@ main() { linux) build_linux ;; + control) + build_control + ;; clean) clean_build ;; diff --git a/cmd/douyu-control/main.go b/cmd/douyu-control/main.go new file mode 100644 index 0000000..c649b28 --- /dev/null +++ b/cmd/douyu-control/main.go @@ -0,0 +1,90 @@ +package main + +import ( + "flag" + "fmt" + "log" + "os" + "os/signal" + "strings" + "syscall" + "time" + + "douyu_go/internal/remote" +) + +func main() { + addr := flag.String("addr", env("DOUYU_CONTROL_ADDR", ":18080"), "HTTP listen address") + dataDir := flag.String("data", env("DOUYU_CONTROL_DATA", "remote-data"), "remote data directory") + agentToken := flag.String("agent-token", os.Getenv("DOUYU_CONTROL_AGENT_TOKEN"), "token used by application instances") + operatorToken := flag.String("operator-token", os.Getenv("DOUYU_CONTROL_OPERATOR_TOKEN"), "token used by the web console") + enrollToken := flag.String("enroll-token", os.Getenv("DOUYU_CONTROL_ENROLL_TOKEN"), "optional token required for automatic instance enrollment") + enrollWindow := flag.Duration("enroll-window", durationEnv("DOUYU_CONTROL_ENROLL_WINDOW", 10*time.Minute), "automatic enrollment window when enroll-token is empty") + flag.Parse() + + var err error + if strings.TrimSpace(*operatorToken) == "" { + *operatorToken, err = remote.RandomToken() + if err != nil { + log.Fatal(err) + } + } + + server, err := remote.NewServer(remote.ServerOptions{ + Addr: *addr, + DataDir: *dataDir, + AgentToken: *agentToken, + OperatorToken: *operatorToken, + EnrollToken: *enrollToken, + EnrollWindow: *enrollWindow, + }) + if err != nil { + log.Fatal(err) + } + defer server.Close() + + fmt.Printf("远端控制台: http://%s/#admin=%s\n", displayAddr(*addr), *operatorToken) + if strings.TrimSpace(*enrollToken) != "" { + fmt.Printf("实例注册需要注册令牌: %s\n", *enrollToken) + } else { + fmt.Printf("实例自动注册窗口: %s(启动后开始计时)\n", enrollWindow.String()) + } + if strings.TrimSpace(*agentToken) != "" { + fmt.Printf("兼容实例共享令牌: %s\n", *agentToken) + } + fmt.Printf("数据目录: %s\n", *dataDir) + + signals := make(chan os.Signal, 1) + signal.Notify(signals, os.Interrupt, syscall.SIGTERM) + go func() { + <-signals + _ = server.Close() + os.Exit(0) + }() + if err := server.ListenAndServe(); err != nil { + log.Fatal(err) + } +} + +func env(key, fallback string) string { + if value := strings.TrimSpace(os.Getenv(key)); value != "" { + return value + } + return fallback +} + +func displayAddr(addr string) string { + if strings.HasPrefix(addr, ":") { + return "127.0.0.1" + addr + } + return addr +} + +func durationEnv(key string, fallback time.Duration) time.Duration { + raw := strings.TrimSpace(os.Getenv(key)) + value, err := time.ParseDuration(raw) + if err != nil || value <= 0 { + return fallback + } + return value +} diff --git a/frontend/src/components/layout/RightConsole.vue b/frontend/src/components/layout/RightConsole.vue index dd3d127..3e8fc71 100644 --- a/frontend/src/components/layout/RightConsole.vue +++ b/frontend/src/components/layout/RightConsole.vue @@ -1,5 +1,5 @@ @@ -70,6 +107,17 @@ onMounted(loadSettings) {{ formatRemain(countdownSeconds) }} + + {{ remoteSummary }} + 保存到共享文件 - 共享文件仅包含代理提取 API、分组、备用比例和白名单设置,不包含账号、CK、当前代理 IP 或过期时间。文件中可能包含密码和密钥,请妥善保管。 + 共享文件包含代理提取 API、分组、备用比例、白名单和远端控制设置,不包含账号、CK、当前代理 IP 或过期时间。文件中可能包含密码、签名密钥和远端令牌,请妥善保管。 @@ -560,6 +568,49 @@ defineExpose({ open, close }) 用于获取斗鱼服务端时间,一般不需要修改 + + + 远端控制(可选) + + + + 启用远端上报 + 日志、结果和状态异步上报;远端不可用时绝不影响本地抢购 + + + + + + + + + + 控制中心地址 + + + + + 机器显示名称 + + + + + 首次连接会在控制中心注册窗口内自动领取独立实例令牌并保存在本机,无需手工配置。 + Cookie、CSRF、代理密码、签名密钥和 Trace 内容不会上传。远端只接收结构化日志、运行摘要和控制命令。 + + + + 和平小店商品列表 diff --git a/frontend/src/composables/useSettings.ts b/frontend/src/composables/useSettings.ts index ddb451e..4b5f43c 100644 --- a/frontend/src/composables/useSettings.ts +++ b/frontend/src/composables/useSettings.ts @@ -1,7 +1,6 @@ import { ref } from 'vue' import { useToast } from './useToast' import { GetSettings, SaveSettings } from '@wails/go/app/App' -import { types } from '@wails/go/models' export interface RetryStage { maxElapsed: number @@ -31,6 +30,10 @@ export interface Settings { proxyWhitelistReplace: boolean proxyWhitelistPassword: string proxyWhitelistSignKey: string + remoteEnabled: boolean + remoteUrl: string + remoteToken: string + remoteMachineName: string } const defaultRetryStages: RetryStage[] = [ @@ -62,7 +65,11 @@ const settings = ref({ proxyAutoWhitelist: false, proxyWhitelistReplace: true, proxyWhitelistPassword: '', - proxyWhitelistSignKey: '' + proxyWhitelistSignKey: '', + remoteEnabled: false, + remoteUrl: '', + remoteToken: '', + remoteMachineName: '' }) export function useSettings() { @@ -70,7 +77,7 @@ export function useSettings() { const loadSettings = async () => { try { - const cfg = await GetSettings() + const cfg: any = await GetSettings() settings.value = { timeApiUrl: cfg.timeApiUrl || '', activity: cfg.activity || '', @@ -95,7 +102,11 @@ export function useSettings() { proxyAutoWhitelist: !!cfg.proxyAutoWhitelist, proxyWhitelistReplace: !!cfg.proxyWhitelistReplace, proxyWhitelistPassword: cfg.proxyWhitelistPassword || '', - proxyWhitelistSignKey: cfg.proxyWhitelistSignKey || '' + proxyWhitelistSignKey: cfg.proxyWhitelistSignKey || '', + remoteEnabled: !!cfg.remoteEnabled, + remoteUrl: cfg.remoteUrl || '', + remoteToken: cfg.remoteToken || '', + remoteMachineName: cfg.remoteMachineName || '' } } catch (e: any) { showToast('读取设置失败', e.message, 'error') @@ -104,7 +115,9 @@ export function useSettings() { const saveSettings = async (newSettings: Settings) => { try { - const d = await SaveSettings(types.Config.createFrom(newSettings)) + // Generated Wails bindings may lag behind newly added backend fields during + // development; the raw object preserves forward-compatible settings. + const d = await SaveSettings(newSettings as any) if (d.success) { settings.value = { ...newSettings } showToast('设置已保存', '配置已生效', 'success') diff --git a/go.mod b/go.mod index d2550dc..bac26cd 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.26.3 require github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 require ( + github.com/gorilla/websocket v1.5.3 github.com/wailsapp/wails/v2 v2.15.0 github.com/xuri/excelize/v2 v2.9.1 golang.org/x/image v0.42.0 @@ -17,7 +18,6 @@ require ( github.com/go-ole/go-ole v1.3.0 // indirect github.com/godbus/dbus/v5 v5.1.0 // indirect github.com/google/uuid v1.6.0 // indirect - github.com/gorilla/websocket v1.5.3 // indirect github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e // indirect github.com/labstack/echo/v4 v4.13.3 // indirect github.com/labstack/gommon v0.4.2 // indirect diff --git a/internal/app/app.go b/internal/app/app.go index 5533874..1891bce 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -16,6 +16,7 @@ import ( "douyu_go/internal/constants" imgpkg "douyu_go/internal/image" "douyu_go/internal/logger" + "douyu_go/internal/remote" "douyu_go/internal/seckill" "douyu_go/internal/trace" "douyu_go/internal/types" @@ -53,6 +54,9 @@ type App struct { closeLog func() closeTrace func() + + remoteMu sync.RWMutex + remoteAgent *remote.Agent } // getClient 返回当前 client 指针快照(读锁保护)。 @@ -228,8 +232,10 @@ func (a *App) Startup(ctx context.Context) { scheduler.UpdateProxySettings(cfg) scheduler.SetStateChangeCallback(func(state string) { runtime.EventsEmit(a.ctx, seckillStateEvent, state) + a.remoteSetState(state) }) scheduler.LoadAccounts() + a.configureRemote(cfg) startupRefreshTried := false tryRefreshStartupProxy := func(reason string) bool { @@ -304,6 +310,7 @@ func (a *App) Startup(ctx context.Context) { // Shutdown Wails 应用关闭时调用。 func (a *App) Shutdown(ctx context.Context) { + a.closeRemote() if scheduler := a.getScheduler(); scheduler != nil { scheduler.Close() } diff --git a/internal/app/app_activity.go b/internal/app/app_activity.go index 78c45ba..6f7ba6b 100644 --- a/internal/app/app_activity.go +++ b/internal/app/app_activity.go @@ -8,6 +8,7 @@ import ( "douyu_go/internal/config" "douyu_go/internal/constants" "douyu_go/internal/logger" + "douyu_go/internal/remote" "douyu_go/internal/types" ) @@ -117,6 +118,9 @@ func (a *App) SaveSettings(cfg types.Config) types.ErrorResult { if cfg.LogLevel == "" { cfg.LogLevel = "info" } + cfg.RemoteURL = strings.TrimSpace(cfg.RemoteURL) + cfg.RemoteToken = strings.TrimSpace(cfg.RemoteToken) + cfg.RemoteMachineName = strings.TrimSpace(cfg.RemoteMachineName) if proxyURL := a.effectiveProxyURL(cfg); proxyURL != "" { if _, err := client.ParseProxyURL(proxyURL); err != nil { logger.LogEvent("代理", "warn", "设置保存失败,代理地址无效: %v", err) @@ -137,6 +141,14 @@ func (a *App) SaveSettings(cfg types.Config) types.ErrorResult { return types.ErrorResult{Error: "AES 签名密钥长度应为 16、24 或 32 字节"} } } + if cfg.RemoteEnabled { + if strings.TrimSpace(cfg.RemoteURL) == "" { + return types.ErrorResult{Error: "远端控制需要填写控制中心地址"} + } + if err := remote.ValidateServerURL(cfg.RemoteURL); err != nil { + return types.ErrorResult{Error: "远端控制地址无效: " + err.Error()} + } + } // 写入文件 if err := config.SaveConfig(a.paths.ConfigFile, cfg); err != nil { @@ -161,6 +173,13 @@ func (a *App) SaveSettings(cfg types.Config) types.ErrorResult { logger.SetMinLevel(cfg.LogLevel) a.scheduler.UpdateSettings(cfg.Concurrency, cfg.Attempts, cfg.RetryStages, cfg.SeckillMode) a.scheduler.UpdateProxySettings(cfg) + remoteChanged := cfg.RemoteEnabled != oldCfg.RemoteEnabled || + cfg.RemoteURL != oldCfg.RemoteURL || + cfg.RemoteToken != oldCfg.RemoteToken || + cfg.RemoteMachineName != oldCfg.RemoteMachineName + if remoteChanged { + a.configureRemote(cfg) + } if clientChanged { proxyURL := a.effectiveProxyURL(cfg) newClient, clientErr := client.NewWithProxy(act, cfg.TimeAPIURL, a.getTrace(), proxyURL) @@ -186,7 +205,7 @@ func (a *App) SaveSettings(cfg types.Config) types.ErrorResult { } } - logger.LogEvent("配置", "success", "配置已保存并生效: 日志等级=%s 并发=%d 重试=%d 重试阶段=%d 模式=%d trace=%v 代理=%v", - cfg.LogLevel, cfg.Concurrency, cfg.Attempts, len(cfg.RetryStages), cfg.SeckillMode, cfg.TraceEnabled, cfg.ProxyEnabled) + logger.LogEvent("配置", "success", "配置已保存并生效: 日志等级=%s 并发=%d 重试=%d 重试阶段=%d 模式=%d trace=%v 代理=%v 远端=%v", + cfg.LogLevel, cfg.Concurrency, cfg.Attempts, len(cfg.RetryStages), cfg.SeckillMode, cfg.TraceEnabled, cfg.ProxyEnabled, cfg.RemoteEnabled) return types.ErrorResult{Success: true} } diff --git a/internal/app/app_remote.go b/internal/app/app_remote.go new file mode 100644 index 0000000..14590ab --- /dev/null +++ b/internal/app/app_remote.go @@ -0,0 +1,123 @@ +package app + +import ( + "fmt" + "os" + "strings" + "time" + + "douyu_go/internal/logger" + "douyu_go/internal/remote" + "douyu_go/internal/types" +) + +func (a *App) configureRemote(cfg types.Config) { + a.closeRemote() + if !cfg.RemoteEnabled { + return + } + serverURL := strings.TrimSpace(cfg.RemoteURL) + token := strings.TrimSpace(cfg.RemoteToken) + if serverURL == "" { + logger.LogEvent("远端", "warn", "远端控制已启用,但控制中心地址为空") + return + } + machineID, err := remote.LoadOrCreateMachineID(a.paths.DataDir) + if err != nil { + logger.LogEvent("远端", "warn", "远端机器标识初始化失败: %v", err) + return + } + machineName := strings.TrimSpace(cfg.RemoteMachineName) + if machineName == "" { + machineName, _ = os.Hostname() + } + agent, err := remote.NewAgent(remote.AgentOptions{ + DataDir: a.paths.DataDir, + ServerURL: serverURL, + Token: token, + MachineID: machineID, + MachineName: machineName, + InstanceID: a.instanceName, + Instance: a.instanceName, + Version: a.GetVersion(), + Snapshot: func() remote.Snapshot { + scheduler := a.getScheduler() + if scheduler == nil { + return remote.Snapshot{} + } + return remote.Snapshot{ + ActivityID: a.getCfg().Activity, + Running: scheduler.IsRunning(), + Results: scheduler.Results(), + AccountCount: scheduler.AccountCount(), + } + }, + Stop: func() error { + result := a.StopSeckill() + if result.Error != "" { + return fmt.Errorf("%s", result.Error) + } + return nil + }, + Cancel: func() error { + a.CancelSchedule() + return nil + }, + }) + if err != nil { + logger.LogEvent("远端", "warn", "远端控制初始化失败: %v", err) + return + } + agent.SetState("idle") + logger.SetObserver(agent.Observe) + agent.Start(a.ctx) + a.remoteMu.Lock() + a.remoteAgent = agent + a.remoteMu.Unlock() + logger.LogEvent("远端", "info", "远端控制已启用: %s,机器=%s,实例=%s", serverURL, machineName, a.instanceName) +} + +func (a *App) closeRemote() { + logger.SetObserver(nil) + a.remoteMu.Lock() + agent := a.remoteAgent + a.remoteAgent = nil + a.remoteMu.Unlock() + if agent != nil { + _ = agent.Close() + } +} + +func (a *App) remoteSetState(state string) { + a.remoteMu.RLock() + agent := a.remoteAgent + a.remoteMu.RUnlock() + if agent != nil { + agent.SetState(state) + } +} + +func (a *App) GetRemoteStatus() types.RemoteStatusResult { + a.remoteMu.RLock() + agent := a.remoteAgent + a.remoteMu.RUnlock() + if agent == nil { + return types.RemoteStatusResult{Enabled: false, Message: "远端控制未启用"} + } + connected, lastError, lastConnect := agent.Status() + message := "未连接" + if connected { + message = "已连接" + } else if lastError != "" { + message = lastError + } + result := types.RemoteStatusResult{ + Enabled: true, + Connected: connected, + Message: message, + } + if !lastConnect.IsZero() { + result.LastConnect = lastConnect.Format(time.RFC3339) + } + return result +} diff --git a/internal/config/config.go b/internal/config/config.go index 0406a35..ae2c955 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -6,6 +6,7 @@ import ( "os" "path/filepath" "strconv" + "strings" "douyu_go/internal/activity" "douyu_go/internal/constants" @@ -231,11 +232,18 @@ func LoadConfig(path string) types.Config { cfg.RetryStages = defaultRetryStages() } normalizeProxyConfig(&cfg) + normalizeRemoteConfig(&cfg) normalizeXiaodianConfig(&cfg) logger.LogEvent("配置", "success", "配置加载完成: %s", path) return cfg } +func normalizeRemoteConfig(cfg *types.Config) { + cfg.RemoteURL = strings.TrimSpace(cfg.RemoteURL) + cfg.RemoteToken = strings.TrimSpace(cfg.RemoteToken) + cfg.RemoteMachineName = strings.TrimSpace(cfg.RemoteMachineName) +} + func normalizeProxyConfig(cfg *types.Config) { if cfg.AccountsPerProxy <= 0 { cfg.AccountsPerProxy = constants.DefaultAccountsPerProxy diff --git a/internal/config/shared_proxy_config.go b/internal/config/shared_proxy_config.go index a58f677..911ca05 100644 --- a/internal/config/shared_proxy_config.go +++ b/internal/config/shared_proxy_config.go @@ -65,8 +65,8 @@ func LoadSharedProxyConfig(path string) (types.SharedProxyConfig, error) { shared.SchemaVersion, SharedProxyConfigSchemaVersion, ) } - if !hasSharedProxySettings(shared.Proxy) { - return types.SharedProxyConfig{}, errors.New("共享代理配置中没有 proxy 设置") + if !hasSharedProxySettings(shared.Proxy) && !hasSharedRemoteSettings(shared.Remote) { + return types.SharedProxyConfig{}, errors.New("共享配置中没有 proxy 或 remote 设置") } return shared, nil } @@ -104,6 +104,19 @@ func ApplySharedProxyConfig(cfg *types.Config, shared types.SharedProxyConfig) { if proxy.WhitelistSignKey != nil { cfg.ProxyWhitelistSignKey = strings.TrimSpace(*proxy.WhitelistSignKey) } + remote := shared.Remote + if remote.Enabled != nil { + cfg.RemoteEnabled = *remote.Enabled + } + if remote.URL != nil { + cfg.RemoteURL = strings.TrimSpace(*remote.URL) + } + if remote.Token != nil { + cfg.RemoteToken = strings.TrimSpace(*remote.Token) + } + if remote.MachineName != nil { + cfg.RemoteMachineName = strings.TrimSpace(*remote.MachineName) + } normalizeProxyConfig(cfg) } @@ -127,6 +140,12 @@ func SaveSharedProxyConfig(path string, cfg types.Config) error { WhitelistPassword: stringPointer(cfg.ProxyWhitelistPassword), WhitelistSignKey: stringPointer(cfg.ProxyWhitelistSignKey), }, + Remote: types.SharedRemoteSettings{ + Enabled: boolPointer(cfg.RemoteEnabled), + URL: stringPointer(cfg.RemoteURL), + Token: stringPointer(cfg.RemoteToken), + MachineName: stringPointer(cfg.RemoteMachineName), + }, } data, err := json.MarshalIndent(shared, "", " ") if err != nil { @@ -179,6 +198,13 @@ func hasSharedProxySettings(proxy types.SharedProxySettings) bool { proxy.WhitelistSignKey != nil } +func hasSharedRemoteSettings(remote types.SharedRemoteSettings) bool { + return remote.Enabled != nil || + remote.URL != nil || + remote.Token != nil || + remote.MachineName != nil +} + func boolPointer(value bool) *bool { return &value } func intPointer(value int) *int { return &value } func stringPointer(value string) *string { return &value } diff --git a/internal/config/shared_proxy_config_test.go b/internal/config/shared_proxy_config_test.go index 6d4c75d..2b8270c 100644 --- a/internal/config/shared_proxy_config_test.go +++ b/internal/config/shared_proxy_config_test.go @@ -22,6 +22,10 @@ func TestSharedProxyConfigRoundTripExcludesRuntimeProxy(t *testing.T) { ProxyWhitelistReplace: true, ProxyWhitelistPassword: "login-pass", ProxyWhitelistSignKey: "0123456789abcdef", + RemoteEnabled: true, + RemoteURL: "https://control.example.com", + RemoteToken: "remote-token", + RemoteMachineName: "PC-01", } if err := SaveSharedProxyConfig(path, cfg); err != nil { t.Fatal(err) @@ -48,6 +52,10 @@ func TestSharedProxyConfigRoundTripExcludesRuntimeProxy(t *testing.T) { if !local.ProxyEnabled || local.ProxyAPI != cfg.ProxyAPI || local.AccountsPerProxy != 5 { t.Fatalf("unexpected merged config: %+v", local) } + if !local.RemoteEnabled || local.RemoteURL != cfg.RemoteURL || + local.RemoteToken != cfg.RemoteToken || local.RemoteMachineName != cfg.RemoteMachineName { + t.Fatalf("remote settings were not merged: %+v", local) + } } func TestApplySharedProxyConfigSupportsPartialOverrides(t *testing.T) { diff --git a/internal/logger/logger.go b/internal/logger/logger.go index 0882388..08b4644 100644 --- a/internal/logger/logger.go +++ b/internal/logger/logger.go @@ -27,6 +27,11 @@ var minLevel atomic.Int32 var douyuOffset atomic.Int64 +var ( + observerMu sync.RWMutex + observer func(types.LogEntry) +) + // SetMinLevel 设置日志最低显示等级。 func SetMinLevel(level string) { minLevel.Store(int32(levelPriority(level))) @@ -37,6 +42,14 @@ func SetDouyuOffset(offset time.Duration) { douyuOffset.Store(int64(offset)) } +// SetObserver installs a non-blocking structured log observer used by optional +// remote telemetry. The callback must return quickly and must not emit logs. +func SetObserver(fn func(types.LogEntry)) { + observerMu.Lock() + observer = fn + observerMu.Unlock() +} + func levelPriority(level string) int { switch strings.ToLower(level) { case "debug": @@ -128,13 +141,22 @@ type sink struct { // write 分发一条日志:内存同步写入,文件异步写入,终端尽力写入。 func (s *sink) write(entry types.LogEntry) { - s.store.Append(entry) + entry = s.store.Append(entry) if s.async != nil { _, _ = s.async.Write([]byte(entry.Message + "\n")) } if s.stdout { _, _ = os.Stdout.Write([]byte(entry.Message + "\n")) } + observerMu.RLock() + notify := observer + observerMu.RUnlock() + if notify != nil { + func() { + defer func() { _ = recover() }() + notify(entry) + }() + } } var globalSink *sink diff --git a/internal/remote/agent.go b/internal/remote/agent.go new file mode 100644 index 0000000..5a96c4d --- /dev/null +++ b/internal/remote/agent.go @@ -0,0 +1,517 @@ +package remote + +import ( + "context" + "errors" + "fmt" + "math/rand" + "net/http" + "net/url" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/gorilla/websocket" + + "douyu_go/internal/constants" + "douyu_go/internal/types" +) + +type AgentOptions struct { + DataDir string + ServerURL string + Token string + MachineID string + MachineName string + InstanceID string + Instance string + Version string + EnrollmentToken string + Snapshot func() Snapshot + Stop func() error + Cancel func() error +} + +type Agent struct { + opts AgentOptions + spool *EventSpool + streamID string + + ctx context.Context + cancel context.CancelFunc + wg sync.WaitGroup + + mu sync.RWMutex + snapshot Snapshot + runCounter atomic.Uint64 + seq atomic.Uint64 + stateWake chan struct{} + writeMu sync.Mutex + connected atomic.Bool + lastError string + lastConnect time.Time +} + +func NewAgent(opts AgentOptions) (*Agent, error) { + opts.ServerURL = strings.TrimSpace(opts.ServerURL) + opts.Token = strings.TrimSpace(opts.Token) + opts.EnrollmentToken = strings.TrimSpace(opts.EnrollmentToken) + opts.MachineName = strings.TrimSpace(opts.MachineName) + opts.Instance = strings.TrimSpace(opts.Instance) + if opts.ServerURL == "" { + return nil, errors.New("远端地址为空") + } + if opts.MachineName == "" { + opts.MachineName = opts.MachineID + } + if opts.Instance == "" { + opts.Instance = opts.InstanceID + } + if opts.MachineID == "" { + id, err := LoadOrCreateMachineID(opts.DataDir) + if err != nil { + return nil, err + } + opts.MachineID = id + } + if opts.InstanceID == "" { + opts.InstanceID = opts.Instance + } + spool, err := NewEventSpool(filepath.Join(strings.TrimSpace(opts.DataDir), "remote")) + if err != nil { + return nil, err + } + streamID, err := randomID() + if err != nil { + _ = spool.Close() + return nil, err + } + now := time.Now() + agent := &Agent{ + opts: opts, + spool: spool, + streamID: streamID, + stateWake: make(chan struct{}, 1), + snapshot: Snapshot{ + MachineID: opts.MachineID, + MachineName: opts.MachineName, + InstanceID: opts.InstanceID, + InstanceName: opts.Instance, + Version: opts.Version, + State: "idle", + UpdatedAt: now, + }, + } + agent.refreshSnapshot() + return agent, nil +} + +func (a *Agent) Start(ctx context.Context) { + if a == nil { + return + } + a.ctx, a.cancel = context.WithCancel(ctx) + a.wg.Add(1) + go a.run() +} + +func (a *Agent) Close() error { + if a == nil { + return nil + } + if a.cancel != nil { + a.cancel() + } + a.wg.Wait() + return a.spool.Close() +} + +func (a *Agent) Observe(entry types.LogEntry) { + if a == nil || a.spool == nil { + return + } + occurred := time.Now() + if parsed, err := time.ParseInLocation("2006-01-02 15:04:05.000", entry.Time, constants.CST); err == nil { + occurred = parsed + } + a.mu.RLock() + runID := "" + if a.snapshot.Running { + runID = a.snapshot.RunID + } + a.mu.RUnlock() + a.spool.Enqueue(LogEvent{ + MachineID: a.opts.MachineID, + MachineName: a.opts.MachineName, + InstanceID: a.opts.InstanceID, + InstanceName: a.opts.Instance, + StreamID: a.streamID, + Sequence: a.seq.Add(1), + Time: occurred, + RunID: runID, + Category: entry.Category, + Level: entry.Level, + Account: entry.Account, + Message: stripLogPrefix(entry.Message), + }) +} + +func (a *Agent) SetState(state string) { + if a == nil { + return + } + state = strings.TrimSpace(state) + if state == "" { + return + } + a.mu.Lock() + running := state == "running" || state == "stopping" + if running && !a.snapshot.Running { + a.snapshot.RunID = fmt.Sprintf("%s-%s-%d", a.opts.InstanceID, time.Now().Format("20060102_150405"), a.runCounter.Add(1)) + } + a.snapshot.State = state + a.snapshot.Running = running + if state == "idle" { + a.snapshot.Running = false + } + a.mu.Unlock() + a.refreshSnapshot() + select { + case a.stateWake <- struct{}{}: + default: + } +} + +func (a *Agent) Connected() bool { + return a != nil && a.connected.Load() +} + +func (a *Agent) Status() (bool, string, time.Time) { + if a == nil { + return false, "", time.Time{} + } + a.mu.RLock() + defer a.mu.RUnlock() + return a.connected.Load(), a.lastError, a.lastConnect +} + +func (a *Agent) run() { + defer a.wg.Done() + backoff := 2 * time.Second + for { + if a.ctx.Err() != nil { + return + } + startedAt := time.Now() + if err := a.ensureToken(); err != nil { + a.mu.Lock() + a.connected.Store(false) + a.lastError = err.Error() + a.mu.Unlock() + wait := jitter(backoff, 20) + timer := time.NewTimer(wait) + select { + case <-a.ctx.Done(): + timer.Stop() + return + case <-timer.C: + } + continue + } + err := a.runConnection() + if a.ctx.Err() != nil { + return + } + if time.Since(startedAt) > 30*time.Second { + backoff = 2 * time.Second + } + a.mu.Lock() + a.connected.Store(false) + if err != nil { + a.lastError = err.Error() + } + a.mu.Unlock() + wait := jitter(backoff, 20) + timer := time.NewTimer(wait) + select { + case <-a.ctx.Done(): + timer.Stop() + return + case <-timer.C: + } + if backoff < 30*time.Second { + backoff *= 2 + if backoff > 30*time.Second { + backoff = 30 * time.Second + } + } + } +} + +func (a *Agent) runConnection() error { + wsURL, err := agentWebSocketURL(a.opts.ServerURL) + if err != nil { + return err + } + header := http.Header{} + header.Set("Authorization", "Bearer "+a.opts.Token) + dialer := websocket.Dialer{HandshakeTimeout: 8 * time.Second} + conn, response, err := dialer.DialContext(a.ctx, wsURL, header) + if err != nil { + if response != nil && response.StatusCode == http.StatusUnauthorized { + a.opts.Token = "" + clearAgentCredential(a.opts.DataDir) + return errors.New("远端拒绝了实例令牌,将重新自动注册") + } + return fmt.Errorf("连接远端失败: %w", err) + } + defer conn.Close() + conn.SetReadLimit(1 << 20) + _ = conn.SetReadDeadline(time.Now().Add(70 * time.Second)) + conn.SetPongHandler(func(string) error { + return conn.SetReadDeadline(time.Now().Add(70 * time.Second)) + }) + + a.mu.Lock() + a.connected.Store(true) + a.lastError = "" + a.lastConnect = time.Now() + a.mu.Unlock() + defer a.connected.Store(false) + + if err := a.writeEnvelope(conn, Envelope{Type: MessageHello, Hello: a.currentSnapshot()}); err != nil { + return err + } + + done := make(chan struct{}) + go func() { + defer close(done) + a.readLoop(conn) + }() + + ticker := time.NewTicker(time.Second) + defer ticker.Stop() + heartbeat := time.NewTicker(5 * time.Second) + defer heartbeat.Stop() + pingTicker := time.NewTicker(25 * time.Second) + defer pingTicker.Stop() + for { + if err := a.flushEvents(conn); err != nil { + return err + } + select { + case <-a.ctx.Done(): + return a.ctx.Err() + case <-done: + return errors.New("远端连接已断开") + case <-a.stateWake: + if err := a.writeEnvelope(conn, Envelope{Type: MessageSnapshot, Snapshot: a.currentSnapshot()}); err != nil { + return err + } + case <-a.spool.Wake(): + case <-ticker.C: + if err := a.flushEvents(conn); err != nil { + return err + } + case <-heartbeat.C: + if err := a.writeEnvelope(conn, Envelope{Type: MessageHeartbeat, Snapshot: a.currentSnapshot()}); err != nil { + return err + } + case <-pingTicker.C: + if err := conn.WriteControl(websocket.PingMessage, nil, time.Now().Add(5*time.Second)); err != nil { + return err + } + } + } +} + +func (a *Agent) readLoop(conn *websocket.Conn) { + for { + var envelope Envelope + if err := conn.ReadJSON(&envelope); err != nil { + return + } + if envelope.Type != MessageCommand || envelope.Command == nil { + continue + } + cmd := *envelope.Command + result := a.runCommand(cmd) + result.ID = cmd.ID + result.Type = cmd.Type + result.FinishedAt = time.Now() + _ = a.writeEnvelope(conn, Envelope{Type: MessageCommandResult, Result: &result}) + } +} + +func (a *Agent) runCommand(cmd Command) CommandResult { + if !cmd.ExpiresAt.IsZero() && time.Now().After(cmd.ExpiresAt) { + return CommandResult{Success: false, Message: "命令已过期"} + } + switch strings.TrimSpace(cmd.Type) { + case "ping": + return CommandResult{Success: true, Message: "pong"} + case "status": + a.refreshSnapshot() + return CommandResult{Success: true, Message: "状态已刷新"} + case "stop": + if a.opts.Stop == nil { + return CommandResult{Success: false, Message: "当前实例不支持停止命令"} + } + if err := a.opts.Stop(); err != nil { + return CommandResult{Success: false, Message: err.Error()} + } + return CommandResult{Success: true, Message: "停止命令已提交"} + case "cancel_schedule": + if a.opts.Cancel == nil { + return CommandResult{Success: false, Message: "当前实例不支持取消定时"} + } + if err := a.opts.Cancel(); err != nil { + return CommandResult{Success: false, Message: err.Error()} + } + return CommandResult{Success: true, Message: "取消定时命令已提交"} + default: + return CommandResult{Success: false, Message: "不支持的命令"} + } +} + +func (a *Agent) flushEvents(conn *websocket.Conn) error { + events, next, err := a.spool.ReadPending(200) + if err != nil || len(events) == 0 { + return err + } + if err := a.writeEnvelope(conn, Envelope{Type: MessageEvents, Events: events}); err != nil { + return err + } + a.spool.Ack(next) + return nil +} + +func (a *Agent) writeEnvelope(conn *websocket.Conn, envelope Envelope) error { + a.writeMu.Lock() + defer a.writeMu.Unlock() + _ = conn.SetWriteDeadline(time.Now().Add(10 * time.Second)) + return conn.WriteJSON(envelope) +} + +func (a *Agent) refreshSnapshot() { + a.mu.Lock() + next := a.snapshot + a.mu.Unlock() + if a.opts.Snapshot != nil { + partial := a.opts.Snapshot() + if partial.ActivityID != "" { + next.ActivityID = partial.ActivityID + } + next.Results = cloneResults(partial.Results) + next.AccountCount = partial.AccountCount + } + a.mu.Lock() + next.MachineID = a.opts.MachineID + next.MachineName = a.opts.MachineName + next.InstanceID = a.opts.InstanceID + next.InstanceName = a.opts.Instance + next.Version = a.opts.Version + next.State = a.snapshot.State + next.Running = a.snapshot.Running + next.RunID = a.snapshot.RunID + next.QueuedEvents = a.spool.Queued() + next.DroppedEvents = a.spool.Dropped() + next.UpdatedAt = time.Now() + a.snapshot = next + a.mu.Unlock() +} + +func (a *Agent) currentSnapshot() *Snapshot { + a.refreshSnapshot() + a.mu.RLock() + defer a.mu.RUnlock() + copy := a.snapshot + copy.Results = cloneResults(a.snapshot.Results) + return © +} + +func cloneResults(source map[string]string) map[string]string { + if len(source) == 0 { + return nil + } + out := make(map[string]string, len(source)) + for key, value := range source { + out[key] = value + } + return out +} + +func agentWebSocketURL(raw string) (string, error) { + raw = strings.TrimSpace(raw) + if raw == "" { + return "", errors.New("远端地址为空") + } + u, err := url.Parse(raw) + if err != nil { + return "", err + } + switch strings.ToLower(u.Scheme) { + case "http": + u.Scheme = "ws" + case "https": + u.Scheme = "wss" + case "ws", "wss": + default: + return "", errors.New("远端地址必须以 http://、https://、ws:// 或 wss:// 开头") + } + if strings.TrimSpace(u.Path) == "" || u.Path == "/" { + u.Path = "/ws/agent" + } + return u.String(), nil +} + +// ValidateServerURL checks the configured control-center address. +func ValidateServerURL(raw string) error { + _, err := agentWebSocketURL(raw) + return err +} + +func stripLogPrefix(message string) string { + message = strings.TrimSpace(message) + if index := strings.LastIndex(message, "] "); index >= 0 { + rest := message[index+2:] + if strings.HasPrefix(message, "20") { + return rest + } + } + return message +} + +func jitter(d time.Duration, percent int64) time.Duration { + if d <= 0 { + return 0 + } + span := int64(d) * percent / 100 + if span <= 0 { + return d + } + return d + time.Duration(rand.Int63n(span)) +} + +func (a *Agent) ensureToken() error { + if strings.TrimSpace(a.opts.Token) != "" { + return nil + } + token, err := loadAgentCredential(a.opts.DataDir, a.opts.ServerURL, a.opts.MachineID, a.opts.InstanceID) + if err != nil { + return fmt.Errorf("读取实例凭据失败: %w", err) + } + if token == "" { + token, err = enrollAgent(a.opts.ServerURL, a.opts) + if err != nil { + return err + } + if err := saveAgentCredential(a.opts.DataDir, a.opts.ServerURL, a.opts.MachineID, a.opts.InstanceID, token); err != nil { + return fmt.Errorf("保存实例凭据失败: %w", err) + } + } + a.opts.Token = token + return nil +} diff --git a/internal/remote/credentials.go b/internal/remote/credentials.go new file mode 100644 index 0000000..c1e73db --- /dev/null +++ b/internal/remote/credentials.go @@ -0,0 +1,159 @@ +package remote + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "path/filepath" + "strings" + "time" +) + +type agentCredential struct { + ServerURL string `json:"serverUrl"` + MachineID string `json:"machineId"` + InstanceID string `json:"instanceId"` + Token string `json:"token"` + EnrolledAt string `json:"enrolledAt,omitempty"` +} + +func loadAgentCredential(dataDir, serverURL, machineID, instanceID string) (string, error) { + path := agentCredentialPath(dataDir) + data, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return "", nil + } + if err != nil { + return "", err + } + var credential agentCredential + if err := json.Unmarshal(data, &credential); err != nil { + return "", err + } + if credential.ServerURL != serverURL || credential.MachineID != machineID || credential.InstanceID != instanceID { + return "", nil + } + return strings.TrimSpace(credential.Token), nil +} + +func saveAgentCredential(dataDir, serverURL, machineID, instanceID, token string) error { + path := agentCredentialPath(dataDir) + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + credential := agentCredential{ + ServerURL: serverURL, + MachineID: machineID, + InstanceID: instanceID, + Token: token, + EnrolledAt: time.Now().Format(time.RFC3339), + } + data, err := json.MarshalIndent(credential, "", " ") + if err != nil { + return err + } + temp, err := os.CreateTemp(filepath.Dir(path), ".agent-credential-*.tmp") + if err != nil { + return err + } + tempPath := temp.Name() + defer func() { _ = os.Remove(tempPath) }() + if err := temp.Chmod(0o600); 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 + } + return os.Rename(tempPath, path) +} + +func clearAgentCredential(dataDir string) { + _ = os.Remove(agentCredentialPath(dataDir)) +} + +func agentCredentialPath(dataDir string) string { + return filepath.Join(MachineDataDir(dataDir), "remote", "instances", safeInstanceFileName(dataDir)+".json") +} + +func safeInstanceFileName(dataDir string) string { + base := filepath.Base(filepath.Clean(dataDir)) + if base == "" || base == "." { + return "default" + } + return base +} + +func enrollAgent(serverURL string, options AgentOptions) (string, error) { + endpoint, err := enrollHTTPURL(serverURL) + if err != nil { + return "", err + } + payload := map[string]string{ + "machineId": options.MachineID, + "machineName": options.MachineName, + "instanceId": options.InstanceID, + "instanceName": options.Instance, + } + data, err := json.Marshal(payload) + if err != nil { + return "", err + } + request, err := http.NewRequest(http.MethodPost, endpoint, bytes.NewReader(data)) + if err != nil { + return "", err + } + request.Header.Set("Content-Type", "application/json") + if token := strings.TrimSpace(options.EnrollmentToken); token != "" { + request.Header.Set("X-Enroll-Token", token) + } + client := &http.Client{Timeout: 10 * time.Second} + response, err := client.Do(request) + if err != nil { + return "", fmt.Errorf("自动注册实例失败: %w", err) + } + defer response.Body.Close() + body, _ := io.ReadAll(io.LimitReader(response.Body, 64<<10)) + if response.StatusCode != http.StatusOK { + return "", fmt.Errorf("自动注册实例失败: HTTP %d %s", response.StatusCode, strings.TrimSpace(string(body))) + } + var result struct { + Token string `json:"token"` + } + if err := json.Unmarshal(body, &result); err != nil { + return "", fmt.Errorf("解析实例注册结果失败: %w", err) + } + if strings.TrimSpace(result.Token) == "" { + return "", errors.New("实例注册成功但未返回令牌") + } + return strings.TrimSpace(result.Token), nil +} + +func enrollHTTPURL(raw string) (string, error) { + u, err := url.Parse(strings.TrimSpace(raw)) + if err != nil { + return "", err + } + switch strings.ToLower(u.Scheme) { + case "http", "https": + case "ws": + u.Scheme = "http" + case "wss": + u.Scheme = "https" + default: + return "", errors.New("远端地址协议无效") + } + if strings.TrimSpace(u.Path) == "" || u.Path == "/" { + u.Path = "/api/enroll" + } + return u.String(), nil +} diff --git a/internal/remote/hub.go b/internal/remote/hub.go new file mode 100644 index 0000000..ce52585 --- /dev/null +++ b/internal/remote/hub.go @@ -0,0 +1,475 @@ +package remote + +import ( + "bufio" + "encoding/csv" + "encoding/json" + "io" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "sync" + "time" +) + +type EventExportFilter struct { + MachineID string + InstanceID string + RunID string + Query string + From time.Time + To time.Time +} + +const ( + maxServerEvents = 20000 + maxRunRecords = 500 +) + +type Hub struct { + mu sync.RWMutex + dataDir string + events []ServerEvent + nextEvent uint64 + instances map[string]InstanceState + runs map[string]RunRecord + commands map[string]CommandAudit + eventFile *os.File + runFile *os.File +} + +func NewHub(dataDir string) (*Hub, error) { + if strings.TrimSpace(dataDir) == "" { + dataDir = "remote-data" + } + if err := os.MkdirAll(dataDir, 0o700); err != nil { + return nil, err + } + hub := &Hub{ + dataDir: dataDir, + instances: make(map[string]InstanceState), + runs: make(map[string]RunRecord), + commands: make(map[string]CommandAudit), + } + if err := hub.loadEvents(); err != nil { + return nil, err + } + if err := hub.loadRuns(); err != nil { + return nil, err + } + eventFile, err := os.OpenFile(filepath.Join(dataDir, "events.ndjson"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600) + if err != nil { + return nil, err + } + runFile, err := os.OpenFile(filepath.Join(dataDir, "runs.ndjson"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600) + if err != nil { + _ = eventFile.Close() + return nil, err + } + hub.eventFile = eventFile + hub.runFile = runFile + return hub, nil +} + +func (h *Hub) Close() error { + h.mu.Lock() + defer h.mu.Unlock() + if h.eventFile != nil { + _ = h.eventFile.Close() + h.eventFile = nil + } + if h.runFile != nil { + _ = h.runFile.Close() + h.runFile = nil + } + return nil +} + +func (h *Hub) ApplySnapshot(snapshot Snapshot, remoteAddr string) { + if snapshot.MachineID == "" || snapshot.InstanceID == "" { + return + } + now := time.Now() + if snapshot.UpdatedAt.IsZero() { + snapshot.UpdatedAt = now + } + key := instanceKey(snapshot.MachineID, snapshot.InstanceID) + h.mu.Lock() + state := InstanceState{ + Snapshot: snapshot, + Online: true, + LastSeen: now, + RemoteAddr: remoteAddr, + } + h.instances[key] = state + h.updateRunLocked(snapshot, now) + h.mu.Unlock() +} + +func (h *Hub) MarkOffline(machineID, instanceID string) { + key := instanceKey(machineID, instanceID) + h.mu.Lock() + if state, ok := h.instances[key]; ok { + state.Online = false + state.LastSeen = time.Now() + h.instances[key] = state + } + h.mu.Unlock() +} + +func (h *Hub) AppendEvents(events []LogEvent) { + if len(events) == 0 { + return + } + h.mu.Lock() + defer h.mu.Unlock() + for _, event := range events { + h.nextEvent++ + serverEvent := ServerEvent{Seq: h.nextEvent, LogEvent: event} + h.events = append(h.events, serverEvent) + if len(h.events) > maxServerEvents { + copy(h.events, h.events[len(h.events)-maxServerEvents:]) + h.events = h.events[:maxServerEvents] + } + if h.eventFile != nil { + if data, err := json.Marshal(serverEvent); err == nil { + _, _ = h.eventFile.Write(append(data, '\n')) + } + } + } +} + +func (h *Hub) AddCommand(audit CommandAudit) { + h.mu.Lock() + h.commands[audit.ID] = audit + h.mu.Unlock() +} + +func (h *Hub) MarkCommandDelivered(id string) { + h.mu.Lock() + audit, ok := h.commands[id] + if !ok { + h.mu.Unlock() + return + } + audit.State = "delivered" + audit.DeliveredAt = time.Now() + h.commands[id] = audit + h.mu.Unlock() +} + +func (h *Hub) ApplyCommandResult(result CommandResult) { + h.mu.Lock() + audit, ok := h.commands[result.ID] + if !ok { + h.mu.Unlock() + return + } + audit.State = "failed" + if result.Success { + audit.State = "success" + } + audit.Message = result.Message + audit.FinishedAt = result.FinishedAt + h.commands[result.ID] = audit + h.mu.Unlock() +} + +func (h *Hub) Dashboard() DashboardState { + h.mu.RLock() + defer h.mu.RUnlock() + instances := make([]InstanceState, 0, len(h.instances)) + for _, state := range h.instances { + if time.Since(state.LastSeen) > 45*time.Second { + state.Online = false + } + instances = append(instances, state) + } + sort.Slice(instances, func(i, j int) bool { + if instances[i].MachineName == instances[j].MachineName { + return instances[i].InstanceName < instances[j].InstanceName + } + return instances[i].MachineName < instances[j].MachineName + }) + runs := make([]RunRecord, 0, len(h.runs)) + for _, run := range h.runs { + runs = append(runs, run) + } + sort.Slice(runs, func(i, j int) bool { + return runs[i].UpdatedAt.After(runs[j].UpdatedAt) + }) + if len(runs) > maxRunRecords { + runs = runs[:maxRunRecords] + } + commands := make([]CommandAudit, 0, len(h.commands)) + for _, command := range h.commands { + commands = append(commands, command) + } + sort.Slice(commands, func(i, j int) bool { + return commands[i].CreatedAt.After(commands[j].CreatedAt) + }) + if len(commands) > 100 { + commands = commands[:100] + } + return DashboardState{ + ServerTime: time.Now(), + Instances: instances, + Runs: runs, + Commands: commands, + } +} + +func (h *Hub) EventsSince(since uint64, limit int) []ServerEvent { + return h.EventsSinceFiltered(since, limit, "", "", "") +} + +func (h *Hub) EventsSinceFiltered(since uint64, limit int, machineID, instanceID, runID string) []ServerEvent { + if limit <= 0 || limit > 1000 { + limit = 300 + } + h.mu.RLock() + defer h.mu.RUnlock() + out := make([]ServerEvent, 0, limit) + for _, event := range h.events { + if event.Seq <= since { + continue + } + if machineID != "" && event.MachineID != machineID { + continue + } + if instanceID != "" && event.InstanceID != instanceID { + continue + } + if runID != "" && event.RunID != runID { + continue + } + out = append(out, event) + if len(out) >= limit { + break + } + } + return out +} + +func (h *Hub) ExportEvents(w io.Writer, format string, filter EventExportFilter) (int, error) { + file, err := os.Open(filepath.Join(h.dataDir, "events.ndjson")) + if err != nil { + return 0, err + } + defer file.Close() + + format = strings.ToLower(strings.TrimSpace(format)) + var jsonFirst = true + var csvWriter *csv.Writer + if format == "json" { + if _, err := io.WriteString(w, "["); err != nil { + return 0, err + } + } else { + if _, err := w.Write([]byte{0xEF, 0xBB, 0xBF}); err != nil { + return 0, err + } + csvWriter = csv.NewWriter(w) + if err := csvWriter.Write([]string{ + "seq", "time", "machine_id", "machine_name", "instance_id", "instance_name", + "run_id", "category", "level", "account", "message", + }); err != nil { + return 0, err + } + } + + query := strings.ToLower(strings.TrimSpace(filter.Query)) + scanner := bufio.NewScanner(file) + scanner.Buffer(make([]byte, 0, 64*1024), 2*1024*1024) + count := 0 + for scanner.Scan() { + var event ServerEvent + if json.Unmarshal(scanner.Bytes(), &event) != nil || !matchesExport(event.LogEvent, filter, query) { + continue + } + count++ + if format == "json" { + data, err := json.Marshal(event) + if err != nil { + return count, err + } + if !jsonFirst { + if _, err := io.WriteString(w, ","); err != nil { + return count, err + } + } + jsonFirst = false + if _, err := w.Write(data); err != nil { + return count, err + } + continue + } + if err := csvWriter.Write([]string{ + strconv.FormatUint(event.Seq, 10), + event.Time.Format(time.RFC3339Nano), + event.MachineID, + event.MachineName, + event.InstanceID, + event.InstanceName, + event.RunID, + event.Category, + event.Level, + event.Account, + event.Message, + }); err != nil { + return count, err + } + } + if err := scanner.Err(); err != nil { + return count, err + } + if format == "json" { + if _, err := io.WriteString(w, "]"); err != nil { + return count, err + } + return count, nil + } + if csvWriter != nil { + csvWriter.Flush() + if err := csvWriter.Error(); err != nil { + return count, err + } + } + return count, nil +} + +func matchesExport(event LogEvent, filter EventExportFilter, query string) bool { + if filter.MachineID != "" && event.MachineID != filter.MachineID { + return false + } + if filter.InstanceID != "" && event.InstanceID != filter.InstanceID { + return false + } + if filter.RunID != "" && event.RunID != filter.RunID { + return false + } + if !filter.From.IsZero() && event.Time.Before(filter.From) { + return false + } + if !filter.To.IsZero() && event.Time.After(filter.To) { + return false + } + if query != "" { + haystack := strings.ToLower(strings.Join([]string{ + event.MachineName, event.InstanceName, event.Account, event.Message, + }, " ")) + if !strings.Contains(haystack, query) { + return false + } + } + return true +} + +func (h *Hub) updateRunLocked(snapshot Snapshot, now time.Time) { + if snapshot.RunID == "" { + return + } + run, ok := h.runs[snapshot.RunID] + if !ok { + run = RunRecord{ + RunID: snapshot.RunID, + MachineID: snapshot.MachineID, + MachineName: snapshot.MachineName, + InstanceID: snapshot.InstanceID, + InstanceName: snapshot.InstanceName, + StartedAt: now, + } + } + run.State = snapshot.State + run.Running = snapshot.Running + run.Results = cloneResults(snapshot.Results) + run.UpdatedAt = now + if !snapshot.Running && run.FinishedAt.IsZero() { + run.FinishedAt = now + } + h.runs[snapshot.RunID] = run + if len(h.runs) > maxRunRecords { + h.pruneRunsLocked() + } + if h.runFile != nil { + if data, err := json.Marshal(run); err == nil { + _, _ = h.runFile.Write(append(data, '\n')) + } + } +} + +func (h *Hub) pruneRunsLocked() { + type entry struct { + id string + at time.Time + } + items := make([]entry, 0, len(h.runs)) + for id, run := range h.runs { + items = append(items, entry{id: id, at: run.UpdatedAt}) + } + sort.Slice(items, func(i, j int) bool { + return items[i].at.Before(items[j].at) + }) + for len(h.runs) > maxRunRecords && len(items) > 0 { + delete(h.runs, items[0].id) + items = items[1:] + } +} + +func (h *Hub) loadEvents() error { + file, err := os.Open(filepath.Join(h.dataDir, "events.ndjson")) + if os.IsNotExist(err) { + return nil + } + if err != nil { + return err + } + defer file.Close() + scanner := bufio.NewScanner(file) + buf := make([]byte, 0, 64*1024) + scanner.Buffer(buf, 2*1024*1024) + for scanner.Scan() { + var event ServerEvent + if json.Unmarshal(scanner.Bytes(), &event) != nil { + continue + } + if event.Seq > h.nextEvent { + h.nextEvent = event.Seq + } + h.events = append(h.events, event) + if len(h.events) > maxServerEvents { + copy(h.events, h.events[len(h.events)-maxServerEvents:]) + h.events = h.events[:maxServerEvents] + } + } + return scanner.Err() +} + +func (h *Hub) loadRuns() error { + file, err := os.Open(filepath.Join(h.dataDir, "runs.ndjson")) + if os.IsNotExist(err) { + return nil + } + if err != nil { + return err + } + defer file.Close() + scanner := bufio.NewScanner(file) + for scanner.Scan() { + var run RunRecord + if json.Unmarshal(scanner.Bytes(), &run) != nil || run.RunID == "" { + continue + } + h.runs[run.RunID] = run + } + if len(h.runs) > maxRunRecords { + h.pruneRunsLocked() + } + return scanner.Err() +} + +func instanceKey(machineID, instanceID string) string { + return machineID + "\x00" + instanceID +} diff --git a/internal/remote/machine.go b/internal/remote/machine.go new file mode 100644 index 0000000..1aa707e --- /dev/null +++ b/internal/remote/machine.go @@ -0,0 +1,82 @@ +package remote + +import ( + "crypto/rand" + "encoding/hex" + "errors" + "os" + "path/filepath" + "strings" +) + +const machineIDFileName = "machine_id" + +// MachineDataDir derives the directory shared by every local application instance. +func MachineDataDir(dataDir string) string { + clean := filepath.Clean(strings.TrimSpace(dataDir)) + if clean == "." || clean == "" { + return clean + } + if filepath.Base(filepath.Dir(clean)) == "instances" { + return filepath.Dir(filepath.Dir(clean)) + } + return clean +} + +// LoadOrCreateMachineID returns a stable random identifier shared by all instances on this machine. +func LoadOrCreateMachineID(dataDir string) (string, error) { + root := MachineDataDir(dataDir) + if root == "" { + return "", errors.New("机器数据目录为空") + } + dir := filepath.Join(root, "remote") + if err := os.MkdirAll(dir, 0o700); err != nil { + return "", err + } + path := filepath.Join(dir, machineIDFileName) + if value, err := readMachineID(path); err == nil { + return value, nil + } else if !errors.Is(err, os.ErrNotExist) { + return "", err + } + + value, err := randomID() + if err != nil { + return "", err + } + file, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) + if errors.Is(err, os.ErrExist) { + return readMachineID(path) + } + if err != nil { + return "", err + } + if _, err := file.WriteString(value + "\n"); err != nil { + _ = file.Close() + return "", err + } + if err := file.Close(); err != nil { + return "", err + } + return value, nil +} + +func readMachineID(path string) (string, error) { + data, err := os.ReadFile(path) + if err != nil { + return "", err + } + value := strings.TrimSpace(string(data)) + if value == "" { + return "", errors.New("机器标识文件为空") + } + return value, nil +} + +func randomID() (string, error) { + var raw [16]byte + if _, err := rand.Read(raw[:]); err != nil { + return "", err + } + return hex.EncodeToString(raw[:]), nil +} diff --git a/internal/remote/protocol.go b/internal/remote/protocol.go new file mode 100644 index 0000000..c3bc820 --- /dev/null +++ b/internal/remote/protocol.go @@ -0,0 +1,131 @@ +package remote + +import ( + "encoding/json" + "time" +) + +const ( + MessageHello = "hello" + MessageHeartbeat = "heartbeat" + MessageSnapshot = "snapshot" + MessageEvents = "events" + MessageCommand = "command" + MessageCommandAck = "command_ack" + MessageCommandResult = "command_result" +) + +// Snapshot is the latest state reported by one application instance. +type Snapshot struct { + MachineID string `json:"machineId"` + MachineName string `json:"machineName"` + InstanceID string `json:"instanceId"` + InstanceName string `json:"instanceName"` + Version string `json:"version"` + ActivityID string `json:"activityId,omitempty"` + State string `json:"state"` + Running bool `json:"running"` + RunID string `json:"runId,omitempty"` + Results map[string]string `json:"results,omitempty"` + AccountCount int `json:"accountCount"` + QueuedEvents uint64 `json:"queuedEvents"` + DroppedEvents uint64 `json:"droppedEvents"` + UpdatedAt time.Time `json:"updatedAt"` +} + +// LogEvent is one structured event uploaded by an application instance. +type LogEvent struct { + MachineID string `json:"machineId"` + MachineName string `json:"machineName"` + InstanceID string `json:"instanceId"` + InstanceName string `json:"instanceName"` + StreamID string `json:"streamId"` + Sequence uint64 `json:"sequence"` + Time time.Time `json:"time"` + RunID string `json:"runId,omitempty"` + Category string `json:"category"` + Level string `json:"level"` + Account string `json:"account,omitempty"` + Message string `json:"message"` +} + +// Command is a control instruction sent from the server to one instance. +type Command struct { + ID string `json:"id"` + Type string `json:"type"` + Payload json.RawMessage `json:"payload,omitempty"` + CreatedAt time.Time `json:"createdAt"` + ExpiresAt time.Time `json:"expiresAt"` +} + +// CommandResult reports the terminal state of one command. +type CommandResult struct { + ID string `json:"id"` + Type string `json:"type"` + Success bool `json:"success"` + Message string `json:"message,omitempty"` + FinishedAt time.Time `json:"finishedAt"` +} + +// Envelope is the JSON message used by the agent WebSocket. +type Envelope struct { + Type string `json:"type"` + Hello *Snapshot `json:"hello,omitempty"` + Snapshot *Snapshot `json:"snapshot,omitempty"` + Events []LogEvent `json:"events,omitempty"` + Command *Command `json:"command,omitempty"` + Result *CommandResult `json:"result,omitempty"` + Error string `json:"error,omitempty"` +} + +// InstanceState is the server-side view of one connected or recently seen instance. +type InstanceState struct { + Snapshot + Online bool `json:"online"` + LastSeen time.Time `json:"lastSeen"` + RemoteAddr string `json:"remoteAddr,omitempty"` +} + +// RunRecord is a compact run history entry reconstructed from snapshots. +type RunRecord struct { + RunID string `json:"runId"` + MachineID string `json:"machineId"` + MachineName string `json:"machineName"` + InstanceID string `json:"instanceId"` + InstanceName string `json:"instanceName"` + State string `json:"state"` + Running bool `json:"running"` + StartedAt time.Time `json:"startedAt"` + FinishedAt time.Time `json:"finishedAt,omitempty"` + Results map[string]string `json:"results,omitempty"` + UpdatedAt time.Time `json:"updatedAt"` +} + +// ServerEvent is a persisted event with a server-side cursor. +type ServerEvent struct { + Seq uint64 `json:"seq"` + LogEvent +} + +// DashboardState is the polling payload consumed by the remote web console. +type DashboardState struct { + ServerTime time.Time `json:"serverTime"` + Instances []InstanceState `json:"instances"` + Runs []RunRecord `json:"runs"` + Commands []CommandAudit `json:"commands"` +} + +// CommandAudit records one command and its delivery/execution state. +type CommandAudit struct { + ID string `json:"id"` + MachineID string `json:"machineId"` + MachineName string `json:"machineName"` + InstanceID string `json:"instanceId"` + InstanceName string `json:"instanceName"` + Type string `json:"type"` + State string `json:"state"` + Message string `json:"message,omitempty"` + CreatedAt time.Time `json:"createdAt"` + DeliveredAt time.Time `json:"deliveredAt,omitempty"` + FinishedAt time.Time `json:"finishedAt,omitempty"` +} diff --git a/internal/remote/remote_test.go b/internal/remote/remote_test.go new file mode 100644 index 0000000..43fa1ec --- /dev/null +++ b/internal/remote/remote_test.go @@ -0,0 +1,326 @@ +package remote + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "time" + + "douyu_go/internal/types" +) + +func TestLoadOrCreateMachineIDSharedByInstances(t *testing.T) { + root := t.TempDir() + defaultDir := root + instanceDir := filepath.Join(root, "instances", "instance-2") + if err := os.MkdirAll(instanceDir, 0o700); err != nil { + t.Fatal(err) + } + first, err := LoadOrCreateMachineID(defaultDir) + if err != nil { + t.Fatal(err) + } + second, err := LoadOrCreateMachineID(instanceDir) + if err != nil { + t.Fatal(err) + } + if first != second { + t.Fatalf("machine id differs: %q != %q", first, second) + } +} + +func TestEventSpoolPersistsOffset(t *testing.T) { + dir := t.TempDir() + spool, err := NewEventSpool(dir) + if err != nil { + t.Fatal(err) + } + event := LogEvent{MachineID: "m", InstanceID: "i", StreamID: "s", Sequence: 1, Message: "hello"} + if !spool.Enqueue(event) { + t.Fatal("event was not queued") + } + events, next, err := readSpoolEventually(spool, 1) + if err != nil { + t.Fatal(err) + } + if len(events) != 1 || events[0].Message != "hello" { + t.Fatalf("events = %#v", events) + } + spool.Ack(next) + if err := spool.Close(); err != nil { + t.Fatal(err) + } + + reopened, err := NewEventSpool(dir) + if err != nil { + t.Fatal(err) + } + defer reopened.Close() + events, _, err = reopened.ReadPending(10) + if err != nil { + t.Fatal(err) + } + if len(events) != 0 { + t.Fatalf("acknowledged events replayed: %#v", events) + } +} + +func TestAgentServerRoundTripAndCommand(t *testing.T) { + server, err := NewServer(ServerOptions{ + DataDir: t.TempDir(), + AgentToken: "agent-token", + OperatorToken: "operator-token", + }) + if err != nil { + t.Fatal(err) + } + defer server.Close() + httpServer := httptest.NewServer(server.Handler()) + defer httpServer.Close() + + stopped := make(chan struct{}, 1) + agent, err := NewAgent(AgentOptions{ + DataDir: t.TempDir(), + ServerURL: httpServer.URL, + Token: "agent-token", + MachineID: "machine-1", + MachineName: "PC-01", + InstanceID: "实例 2", + Instance: "实例 2", + Version: "test", + Snapshot: func() Snapshot { + return Snapshot{ActivityID: "peace", Results: map[string]string{"a": "成功|test"}} + }, + Stop: func() error { + select { + case stopped <- struct{}{}: + default: + } + return nil + }, + }) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + agent.Start(ctx) + defer agent.Close() + agent.SetState("running") + agent.Observe(types.LogEntry{Time: time.Now().Format("2006-01-02 15:04:05.000"), Level: "info", Category: "抢购", Account: "a", Message: "开始抢购"}) + + waitUntil(t, 5*time.Second, func() bool { + return len(server.hub.Dashboard().Instances) == 1 + }) + waitUntil(t, 5*time.Second, func() bool { + return len(server.hub.EventsSince(0, 10)) == 1 + }) + + body := bytes.NewBufferString(`{"machineId":"machine-1","instanceId":"实例 2","type":"stop"}`) + request, err := http.NewRequest(http.MethodPost, httpServer.URL+"/api/command", body) + if err != nil { + t.Fatal(err) + } + request.Header.Set("Content-Type", "application/json") + request.Header.Set("X-Control-Token", "operator-token") + response, err := http.DefaultClient.Do(request) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + t.Fatalf("command status = %d", response.StatusCode) + } + select { + case <-stopped: + case <-time.After(5 * time.Second): + t.Fatal("stop command was not delivered") + } + agent.SetState("idle") + waitUntil(t, 5*time.Second, func() bool { + runs := server.hub.Dashboard().Runs + return len(runs) == 1 && !runs[0].Running + }) +} + +func TestDashboardRequiresOperatorToken(t *testing.T) { + server, err := NewServer(ServerOptions{DataDir: t.TempDir(), AgentToken: "a", OperatorToken: "operator"}) + if err != nil { + t.Fatal(err) + } + defer server.Close() + httpServer := httptest.NewServer(server.Handler()) + defer httpServer.Close() + + response, err := http.Get(httpServer.URL + "/api/dashboard") + if err != nil { + t.Fatal(err) + } + response.Body.Close() + if response.StatusCode != http.StatusUnauthorized { + t.Fatalf("status = %d, want 401", response.StatusCode) + } +} + +func TestAgentAutoEnrollsWithoutManualToken(t *testing.T) { + server, err := NewServer(ServerOptions{ + DataDir: t.TempDir(), + OperatorToken: "operator-token", + EnrollWindow: time.Minute, + }) + if err != nil { + t.Fatal(err) + } + defer server.Close() + httpServer := httptest.NewServer(server.Handler()) + defer httpServer.Close() + + dataDir := t.TempDir() + agent, err := NewAgent(AgentOptions{ + DataDir: dataDir, + ServerURL: httpServer.URL, + MachineID: "machine-auto", + MachineName: "PC-AUTO", + InstanceID: "实例 3", + Instance: "实例 3", + Version: "test", + }) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + agent.Start(ctx) + defer agent.Close() + waitUntil(t, 5*time.Second, func() bool { + return len(server.hub.Dashboard().Instances) == 1 + }) + token, err := loadAgentCredential(dataDir, httpServer.URL, "machine-auto", "实例 3") + if err != nil { + t.Fatal(err) + } + if token == "" { + t.Fatal("auto enrollment did not save an instance token") + } +} + +func TestHubAggregatesDynamicInstanceCount(t *testing.T) { + hub, err := NewHub(t.TempDir()) + if err != nil { + t.Fatal(err) + } + defer hub.Close() + for _, id := range []string{"默认实例", "实例 2", "实例 3", "实例 5", "临时实例"} { + hub.ApplySnapshot(Snapshot{ + MachineID: "machine-1", + MachineName: "PC-01", + InstanceID: id, + InstanceName: id, + State: "idle", + AccountCount: 10, + }, "127.0.0.1") + } + state := hub.Dashboard() + if len(state.Instances) != 5 { + t.Fatalf("instances = %d, want 5", len(state.Instances)) + } + machines := make(map[string]struct{}) + for _, instance := range state.Instances { + machines[instance.MachineID] = struct{}{} + } + if len(machines) != 1 { + t.Fatalf("machines = %d, want 1", len(machines)) + } +} + +func TestEventsCanBeFilteredByInstanceAndRun(t *testing.T) { + hub, err := NewHub(t.TempDir()) + if err != nil { + t.Fatal(err) + } + defer hub.Close() + hub.AppendEvents([]LogEvent{ + {MachineID: "m1", InstanceID: "i1", RunID: "r1", Message: "a"}, + {MachineID: "m1", InstanceID: "i2", RunID: "r2", Message: "b"}, + {MachineID: "m1", InstanceID: "i1", RunID: "r2", Message: "c"}, + }) + byInstance := hub.EventsSinceFiltered(0, 10, "m1", "i1", "") + if len(byInstance) != 2 { + t.Fatalf("by instance = %d, want 2", len(byInstance)) + } + byRun := hub.EventsSinceFiltered(0, 10, "", "", "r2") + if len(byRun) != 2 { + t.Fatalf("by run = %d, want 2", len(byRun)) + } + both := hub.EventsSinceFiltered(0, 10, "m1", "i1", "r2") + if len(both) != 1 || both[0].Message != "c" { + t.Fatalf("combined filter = %#v", both) + } +} + +func TestExportEventsCSVAndJSON(t *testing.T) { + hub, err := NewHub(t.TempDir()) + if err != nil { + t.Fatal(err) + } + defer hub.Close() + hub.AppendEvents([]LogEvent{ + {MachineID: "m1", MachineName: "PC-1", InstanceID: "i1", InstanceName: "实例 1", RunID: "r1", Time: time.Now(), Category: "抢购", Level: "success", Account: "a", Message: "成功"}, + {MachineID: "m2", MachineName: "PC-2", InstanceID: "i2", InstanceName: "实例 2", RunID: "r2", Time: time.Now(), Category: "抢购", Level: "warn", Account: "b", Message: "失败"}, + }) + var csvData bytes.Buffer + count, err := hub.ExportEvents(&csvData, "csv", EventExportFilter{MachineID: "m1"}) + if err != nil { + t.Fatal(err) + } + if count != 1 || !bytes.Contains(csvData.Bytes(), []byte("machine_id")) || !bytes.Contains(csvData.Bytes(), []byte("PC-1")) { + t.Fatalf("csv export count=%d data=%s", count, csvData.String()) + } + var jsonData bytes.Buffer + count, err = hub.ExportEvents(&jsonData, "json", EventExportFilter{Query: "失败"}) + if err != nil { + t.Fatal(err) + } + if count != 1 || !bytes.Contains(jsonData.Bytes(), []byte(`"machineId":"m2"`)) { + t.Fatalf("json export count=%d data=%s", count, jsonData.String()) + } +} + +func readSpoolEventually(spool *EventSpool, want int) ([]LogEvent, int64, error) { + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + events, next, err := spool.ReadPending(10) + if err != nil || len(events) >= want { + return events, next, err + } + time.Sleep(20 * time.Millisecond) + } + return nil, 0, context.DeadlineExceeded +} + +func waitUntil(t *testing.T, timeout time.Duration, condition func() bool) { + t.Helper() + deadline := time.Now().Add(timeout) + for time.Now().Before(deadline) { + if condition() { + return + } + time.Sleep(25 * time.Millisecond) + } + t.Fatal("condition was not met before timeout") +} + +func TestEnvelopeJSON(t *testing.T) { + data, err := json.Marshal(Envelope{Type: MessageEvents, Events: []LogEvent{{Message: "x"}}}) + if err != nil { + t.Fatal(err) + } + if !bytes.Contains(data, []byte(`"events"`)) { + t.Fatalf("json = %s", data) + } +} diff --git a/internal/remote/server.go b/internal/remote/server.go new file mode 100644 index 0000000..e996fd8 --- /dev/null +++ b/internal/remote/server.go @@ -0,0 +1,458 @@ +package remote + +import ( + "crypto/subtle" + "embed" + "encoding/json" + "errors" + "fmt" + "io/fs" + "net/http" + "strconv" + "strings" + "sync" + "time" + + "github.com/gorilla/websocket" +) + +//go:embed web/* +var webAssets embed.FS + +type ServerOptions struct { + Addr string + DataDir string + AgentToken string + OperatorToken string + EnrollToken string + EnrollWindow time.Duration +} + +type Server struct { + opts ServerOptions + hub *Hub + tokens *tokenStore + upgrader websocket.Upgrader + enrollUntil time.Time + + sessionsMu sync.RWMutex + sessions map[string]*agentConn +} + +type agentConn struct { + conn *websocket.Conn + writeMu sync.Mutex + machineID string + machineName string + instanceID string + instanceName string + remoteAddr string +} + +func NewServer(opts ServerOptions) (*Server, error) { + opts.Addr = strings.TrimSpace(opts.Addr) + if opts.Addr == "" { + opts.Addr = ":18080" + } + opts.AgentToken = strings.TrimSpace(opts.AgentToken) + opts.OperatorToken = strings.TrimSpace(opts.OperatorToken) + opts.EnrollToken = strings.TrimSpace(opts.EnrollToken) + if opts.OperatorToken == "" { + return nil, errors.New("OperatorToken 不能为空") + } + if opts.EnrollWindow <= 0 { + opts.EnrollWindow = 10 * time.Minute + } + hub, err := NewHub(opts.DataDir) + if err != nil { + return nil, err + } + tokens, err := newTokenStore(opts.DataDir) + if err != nil { + _ = hub.Close() + return nil, err + } + return &Server{ + opts: opts, + hub: hub, + tokens: tokens, + enrollUntil: time.Now().Add(opts.EnrollWindow), + sessions: make(map[string]*agentConn), + upgrader: websocket.Upgrader{ + HandshakeTimeout: 8 * time.Second, + CheckOrigin: func(r *http.Request) bool { + origin := strings.TrimSpace(r.Header.Get("Origin")) + return origin == "" || sameOrigin(origin, r.Host) + }, + }, + }, nil +} + +func (s *Server) Close() error { + s.sessionsMu.Lock() + for _, session := range s.sessions { + _ = session.conn.Close() + } + s.sessions = make(map[string]*agentConn) + s.sessionsMu.Unlock() + return s.hub.Close() +} + +func (s *Server) Handler() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("/api/health", s.handleHealth) + mux.HandleFunc("/api/dashboard", s.handleDashboard) + mux.HandleFunc("/api/events", s.handleEvents) + mux.HandleFunc("/api/export", s.handleExport) + mux.HandleFunc("/api/command", s.handleCommand) + mux.HandleFunc("/api/enroll", s.handleEnroll) + mux.HandleFunc("/ws/agent", s.handleAgent) + + assets, _ := fs.Sub(webAssets, "web") + mux.Handle("/", http.FileServer(http.FS(assets))) + return mux +} + +func (s *Server) handleExport(w http.ResponseWriter, r *http.Request) { + if !s.authorize(w, r, s.opts.OperatorToken) { + return + } + if r.Method != http.MethodGet { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + format := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("format"))) + if format == "" { + format = "csv" + } + if format != "csv" && format != "json" { + writeJSON(w, http.StatusBadRequest, map[string]any{"error": "format 仅支持 csv 或 json"}) + return + } + filter := EventExportFilter{ + MachineID: strings.TrimSpace(r.URL.Query().Get("machineId")), + InstanceID: strings.TrimSpace(r.URL.Query().Get("instanceId")), + RunID: strings.TrimSpace(r.URL.Query().Get("runId")), + Query: strings.TrimSpace(r.URL.Query().Get("q")), + } + if raw := strings.TrimSpace(r.URL.Query().Get("from")); raw != "" { + value, err := time.Parse(time.RFC3339, raw) + if err != nil { + writeJSON(w, http.StatusBadRequest, map[string]any{"error": "from 时间格式应为 RFC3339"}) + return + } + filter.From = value + } + if raw := strings.TrimSpace(r.URL.Query().Get("to")); raw != "" { + value, err := time.Parse(time.RFC3339, raw) + if err != nil { + writeJSON(w, http.StatusBadRequest, map[string]any{"error": "to 时间格式应为 RFC3339"}) + return + } + filter.To = value + } + extension := format + if format == "json" { + extension = "json" + } + w.Header().Set("Content-Type", exportContentType(format)) + w.Header().Set("Content-Disposition", fmt.Sprintf( + `attachment; filename="douyu-logs-%s.%s"`, + time.Now().Format("20060102-150405"), + extension, + )) + if _, err := s.hub.ExportEvents(w, format, filter); err != nil { + // Headers may already be committed. The client receives a truncated file + // rather than blocking the control plane. + return + } +} + +func (s *Server) handleEnroll(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + if s.opts.EnrollToken != "" { + provided := strings.TrimSpace(r.Header.Get("X-Enroll-Token")) + if subtle.ConstantTimeCompare([]byte(provided), []byte(s.opts.EnrollToken)) != 1 { + writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "注册令牌无效"}) + return + } + } else if time.Now().After(s.enrollUntil) { + writeJSON(w, http.StatusForbidden, map[string]any{"error": "实例自动注册窗口已关闭"}) + return + } + var request struct { + MachineID string `json:"machineId"` + MachineName string `json:"machineName"` + InstanceID string `json:"instanceId"` + InstanceName string `json:"instanceName"` + } + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10)).Decode(&request); err != nil { + writeJSON(w, http.StatusBadRequest, map[string]any{"error": "请求格式错误"}) + return + } + request.MachineID = strings.TrimSpace(request.MachineID) + request.InstanceID = strings.TrimSpace(request.InstanceID) + if request.MachineID == "" || request.InstanceID == "" { + writeJSON(w, http.StatusBadRequest, map[string]any{"error": "缺少机器或实例标识"}) + return + } + token, err := s.tokens.Issue(request.MachineID, request.MachineName, request.InstanceID, request.InstanceName) + if err != nil { + writeJSON(w, http.StatusInternalServerError, map[string]any{"error": "生成实例令牌失败"}) + return + } + writeJSON(w, http.StatusOK, map[string]any{"token": token}) +} + +func (s *Server) ListenAndServe() error { + server := &http.Server{ + Addr: s.opts.Addr, + Handler: s.Handler(), + ReadHeaderTimeout: 10 * time.Second, + IdleTimeout: 90 * time.Second, + } + return server.ListenAndServe() +} + +func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, http.StatusOK, map[string]any{ + "success": true, + "serverTime": time.Now(), + }) +} + +func (s *Server) handleDashboard(w http.ResponseWriter, r *http.Request) { + if !s.authorize(w, r, s.opts.OperatorToken) { + return + } + if r.Method != http.MethodGet { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + writeJSON(w, http.StatusOK, s.hub.Dashboard()) +} + +func (s *Server) handleEvents(w http.ResponseWriter, r *http.Request) { + if !s.authorize(w, r, s.opts.OperatorToken) { + return + } + if r.Method != http.MethodGet { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + since, _ := strconv.ParseUint(r.URL.Query().Get("since"), 10, 64) + limit, _ := strconv.Atoi(r.URL.Query().Get("limit")) + writeJSON(w, http.StatusOK, map[string]any{ + "events": s.hub.EventsSinceFiltered( + since, + limit, + strings.TrimSpace(r.URL.Query().Get("machineId")), + strings.TrimSpace(r.URL.Query().Get("instanceId")), + strings.TrimSpace(r.URL.Query().Get("runId")), + ), + }) +} + +func (s *Server) handleCommand(w http.ResponseWriter, r *http.Request) { + if !s.authorize(w, r, s.opts.OperatorToken) { + return + } + if r.Method != http.MethodPost { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + var request struct { + MachineID string `json:"machineId"` + InstanceID string `json:"instanceId"` + Type string `json:"type"` + } + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10)).Decode(&request); err != nil { + writeJSON(w, http.StatusBadRequest, map[string]any{"error": "请求格式错误"}) + return + } + request.Type = strings.TrimSpace(request.Type) + if !allowedCommand(request.Type) { + writeJSON(w, http.StatusBadRequest, map[string]any{"error": "不支持的命令"}) + return + } + id, err := randomID() + if err != nil { + writeJSON(w, http.StatusInternalServerError, map[string]any{"error": err.Error()}) + return + } + key := instanceKey(request.MachineID, request.InstanceID) + s.sessionsMu.RLock() + session := s.sessions[key] + s.sessionsMu.RUnlock() + if session == nil { + writeJSON(w, http.StatusConflict, map[string]any{"error": "实例当前离线"}) + return + } + now := time.Now() + command := Command{ + ID: id, + Type: request.Type, + CreatedAt: now, + ExpiresAt: now.Add(30 * time.Second), + } + s.hub.AddCommand(CommandAudit{ + ID: id, + MachineID: request.MachineID, + MachineName: session.machineName, + InstanceID: request.InstanceID, + InstanceName: session.instanceName, + Type: request.Type, + State: "queued", + CreatedAt: now, + }) + if err := session.write(Envelope{Type: MessageCommand, Command: &command}); err != nil { + writeJSON(w, http.StatusBadGateway, map[string]any{"error": "命令发送失败: " + err.Error()}) + return + } + s.hub.MarkCommandDelivered(id) + writeJSON(w, http.StatusOK, map[string]any{"success": true, "commandId": id}) +} + +func (s *Server) handleAgent(w http.ResponseWriter, r *http.Request) { + token := requestToken(r) + legacy := s.opts.AgentToken != "" && subtle.ConstantTimeCompare([]byte(token), []byte(s.opts.AgentToken)) == 1 + if !legacy && !s.tokens.Valid(token) { + writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "未授权"}) + return + } + conn, err := s.upgrader.Upgrade(w, r, nil) + if err != nil { + return + } + session := &agentConn{conn: conn, remoteAddr: r.RemoteAddr} + defer conn.Close() + + var key string + defer func() { + if key != "" { + s.sessionsMu.Lock() + if s.sessions[key] == session { + delete(s.sessions, key) + s.hub.MarkOffline(session.machineID, session.instanceID) + } + s.sessionsMu.Unlock() + } + }() + + conn.SetReadLimit(2 << 20) + for { + var envelope Envelope + if err := conn.ReadJSON(&envelope); err != nil { + return + } + switch envelope.Type { + case MessageHello, MessageHeartbeat, MessageSnapshot: + snapshot := envelope.Hello + if envelope.Type != MessageHello { + snapshot = envelope.Snapshot + } + if snapshot == nil || snapshot.MachineID == "" || snapshot.InstanceID == "" { + continue + } + if !legacy && !s.tokens.Matches(token, snapshot.MachineID, snapshot.InstanceID) { + _ = conn.WriteControl( + websocket.CloseMessage, + websocket.FormatCloseMessage(websocket.ClosePolicyViolation, "instance token identity mismatch"), + time.Now().Add(2*time.Second), + ) + return + } + session.machineID = snapshot.MachineID + session.machineName = snapshot.MachineName + session.instanceID = snapshot.InstanceID + session.instanceName = snapshot.InstanceName + newKey := instanceKey(snapshot.MachineID, snapshot.InstanceID) + s.sessionsMu.Lock() + if key != "" && key != newKey { + delete(s.sessions, key) + } + s.sessions[newKey] = session + key = newKey + s.sessionsMu.Unlock() + s.hub.ApplySnapshot(*snapshot, r.RemoteAddr) + case MessageEvents: + s.hub.AppendEvents(envelope.Events) + case MessageCommandResult: + if envelope.Result != nil { + s.hub.ApplyCommandResult(*envelope.Result) + } + } + } +} + +func (c *agentConn) write(envelope Envelope) error { + c.writeMu.Lock() + defer c.writeMu.Unlock() + _ = c.conn.SetWriteDeadline(time.Now().Add(10 * time.Second)) + return c.conn.WriteJSON(envelope) +} + +func (s *Server) authorize(w http.ResponseWriter, r *http.Request, expected string) bool { + provided := requestToken(r) + if subtle.ConstantTimeCompare([]byte(provided), []byte(expected)) == 1 { + return true + } + writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "未授权"}) + return false +} + +func requestToken(r *http.Request) string { + provided := strings.TrimSpace(r.Header.Get("X-Control-Token")) + if provided == "" { + auth := strings.TrimSpace(r.Header.Get("Authorization")) + if strings.HasPrefix(strings.ToLower(auth), "bearer ") { + provided = strings.TrimSpace(auth[7:]) + } + } + if provided == "" { + provided = strings.TrimSpace(r.URL.Query().Get("token")) + } + return provided +} + +func allowedCommand(command string) bool { + switch command { + case "ping", "status", "stop", "cancel_schedule": + return true + default: + return false + } +} + +func writeJSON(w http.ResponseWriter, status int, value any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(value) +} + +func exportContentType(format string) string { + if format == "json" { + return "application/json; charset=utf-8" + } + return "text/csv; charset=utf-8" +} + +func sameOrigin(origin, host string) bool { + origin = strings.TrimSpace(origin) + if origin == "" { + return true + } + origin = strings.TrimPrefix(strings.TrimPrefix(origin, "https://"), "http://") + return strings.EqualFold(origin, host) +} + +func RandomToken() (string, error) { + id, err := randomID() + if err != nil { + return "", err + } + return fmt.Sprintf("%s-%s", id[:16], id[16:]), nil +} diff --git a/internal/remote/spool.go b/internal/remote/spool.go new file mode 100644 index 0000000..14eca76 --- /dev/null +++ b/internal/remote/spool.go @@ -0,0 +1,199 @@ +package remote + +import ( + "bufio" + "encoding/json" + "errors" + "io" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "sync/atomic" +) + +// EventSpool is a bounded, non-blocking durable queue for remote events. +// Logging never waits for disk or network I/O. If the in-memory handoff is full, +// the event is dropped so the seckill path keeps priority. +type EventSpool struct { + mu sync.Mutex + path string + offsetPath string + file *os.File + queue chan LogEvent + wake chan struct{} + done chan struct{} + wg sync.WaitGroup + writeEnd int64 + sentEnd int64 + dropped atomic.Uint64 + queued atomic.Uint64 + closed atomic.Bool +} + +func NewEventSpool(dir string) (*EventSpool, error) { + if err := os.MkdirAll(dir, 0o700); err != nil { + return nil, err + } + path := filepath.Join(dir, "events.ndjson") + file, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0o600) + if err != nil { + return nil, err + } + info, err := file.Stat() + if err != nil { + _ = file.Close() + return nil, err + } + s := &EventSpool{ + path: path, + offsetPath: filepath.Join(dir, "events.offset"), + file: file, + queue: make(chan LogEvent, 8192), + wake: make(chan struct{}, 1), + done: make(chan struct{}), + writeEnd: info.Size(), + } + s.sentEnd = loadSpoolOffset(s.offsetPath, info.Size()) + s.wg.Add(1) + go s.writer() + return s, nil +} + +func (s *EventSpool) Enqueue(event LogEvent) bool { + if s == nil || s.closed.Load() { + return false + } + select { + case s.queue <- event: + s.queued.Add(1) + return true + default: + s.dropped.Add(1) + return false + } +} + +func (s *EventSpool) Wake() <-chan struct{} { + if s == nil { + return nil + } + return s.wake +} + +func (s *EventSpool) ReadPending(limit int) ([]LogEvent, int64, error) { + if s == nil { + return nil, 0, nil + } + if limit <= 0 || limit > 500 { + limit = 200 + } + s.mu.Lock() + defer s.mu.Unlock() + if s.sentEnd >= s.writeEnd { + return nil, s.sentEnd, nil + } + length := s.writeEnd - s.sentEnd + buf := make([]byte, length) + n, err := s.file.ReadAt(buf, s.sentEnd) + if err != nil && !errors.Is(err, io.EOF) { + return nil, s.sentEnd, err + } + buf = buf[:n] + reader := bufio.NewReader(strings.NewReader(string(buf))) + events := make([]LogEvent, 0, limit) + consumed := int64(0) + for len(events) < limit { + line, err := reader.ReadBytes('\n') + if err != nil { + break + } + consumed += int64(len(line)) + var event LogEvent + if json.Unmarshal(line, &event) == nil { + events = append(events, event) + } + } + return events, s.sentEnd + consumed, nil +} + +func (s *EventSpool) Ack(offset int64) { + if s == nil || offset < 0 { + return + } + s.mu.Lock() + if offset > s.sentEnd { + s.sentEnd = offset + } + current := s.sentEnd + s.mu.Unlock() + _ = os.WriteFile(s.offsetPath, []byte(strconv.FormatInt(current, 10)), 0o600) +} + +func (s *EventSpool) Dropped() uint64 { + if s == nil { + return 0 + } + return s.dropped.Load() +} + +func (s *EventSpool) Queued() uint64 { + if s == nil { + return 0 + } + return s.queued.Load() +} + +func (s *EventSpool) Close() error { + if s == nil || !s.closed.CompareAndSwap(false, true) { + return nil + } + close(s.done) + s.wg.Wait() + s.mu.Lock() + defer s.mu.Unlock() + return s.file.Close() +} + +func (s *EventSpool) writer() { + defer s.wg.Done() + for { + select { + case <-s.done: + return + case event := <-s.queue: + s.queued.Add(^uint64(0)) + data, err := json.Marshal(event) + if err != nil { + continue + } + data = append(data, '\n') + s.mu.Lock() + _, err = s.file.Write(data) + if err == nil { + s.writeEnd += int64(len(data)) + } + s.mu.Unlock() + if err != nil { + continue + } + select { + case s.wake <- struct{}{}: + default: + } + } + } +} + +func loadSpoolOffset(path string, fileSize int64) int64 { + data, err := os.ReadFile(path) + if err != nil { + return 0 + } + value, err := strconv.ParseInt(strings.TrimSpace(string(data)), 10, 64) + if err != nil || value < 0 || value > fileSize { + return 0 + } + return value +} diff --git a/internal/remote/token_store.go b/internal/remote/token_store.go new file mode 100644 index 0000000..c2ae15c --- /dev/null +++ b/internal/remote/token_store.go @@ -0,0 +1,133 @@ +package remote + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" + "sync" + "time" +) + +type issuedToken struct { + MachineID string `json:"machineId"` + MachineName string `json:"machineName"` + InstanceID string `json:"instanceId"` + Instance string `json:"instanceName"` + Token string `json:"token"` + IssuedAt time.Time `json:"issuedAt"` +} + +type tokenStore struct { + mu sync.RWMutex + path string + byToken map[string]issuedToken + byKey map[string]issuedToken +} + +func newTokenStore(dataDir string) (*tokenStore, error) { + store := &tokenStore{ + path: filepath.Join(dataDir, "agent_tokens.json"), + byToken: make(map[string]issuedToken), + byKey: make(map[string]issuedToken), + } + if err := store.load(); err != nil { + return nil, err + } + return store, nil +} + +func (s *tokenStore) Issue(machineID, machineName, instanceID, instance string) (string, error) { + key := instanceKey(machineID, instanceID) + s.mu.Lock() + if existing, ok := s.byKey[key]; ok && time.Since(existing.IssuedAt) < 24*time.Hour { + s.mu.Unlock() + return existing.Token, nil + } + token, err := RandomToken() + if err != nil { + s.mu.Unlock() + return "", err + } + item := issuedToken{ + MachineID: machineID, + MachineName: machineName, + InstanceID: instanceID, + Instance: instance, + Token: token, + IssuedAt: time.Now(), + } + s.byToken[token] = item + s.byKey[key] = item + err = s.saveLocked() + s.mu.Unlock() + return token, err +} + +func (s *tokenStore) Valid(token string) bool { + s.mu.RLock() + _, ok := s.byToken[token] + s.mu.RUnlock() + return ok +} + +func (s *tokenStore) Matches(token, machineID, instanceID string) bool { + s.mu.RLock() + item, ok := s.byToken[token] + s.mu.RUnlock() + return ok && item.MachineID == machineID && item.InstanceID == instanceID +} + +func (s *tokenStore) load() error { + data, err := os.ReadFile(s.path) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return err + } + var items []issuedToken + if err := json.Unmarshal(data, &items); err != nil { + return err + } + for _, item := range items { + if item.Token == "" || item.MachineID == "" || item.InstanceID == "" { + continue + } + s.byToken[item.Token] = item + s.byKey[instanceKey(item.MachineID, item.InstanceID)] = item + } + return nil +} + +func (s *tokenStore) saveLocked() error { + items := make([]issuedToken, 0, len(s.byKey)) + for _, item := range s.byKey { + items = append(items, item) + } + data, err := json.MarshalIndent(items, "", " ") + if err != nil { + return err + } + temp, err := os.CreateTemp(filepath.Dir(s.path), ".agent-tokens-*.tmp") + if err != nil { + return err + } + tempPath := temp.Name() + defer func() { _ = os.Remove(tempPath) }() + if err := temp.Chmod(0o600); 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, s.path); err != nil { + return err + } + return nil +} diff --git a/internal/remote/web/index.html b/internal/remote/web/index.html new file mode 100644 index 0000000..3176c89 --- /dev/null +++ b/internal/remote/web/index.html @@ -0,0 +1,482 @@ + + + + + + 斗鱼抢购远端控制台 + + + + + + 斗鱼抢购远端控制台 + 未连接 + + + + 连接 + + + + + + 机器与实例 + + + 等待连接 + 最近运行 + 暂无运行记录 + + + + 实时日志 + 全部实例 + + + + 全部日志 + 导出 CSV + 导出 JSON + 清空 + + + + + + + + + diff --git a/internal/types/responses.go b/internal/types/responses.go index 098b81b..19afd16 100644 --- a/internal/types/responses.go +++ b/internal/types/responses.go @@ -56,6 +56,14 @@ type LogsResult struct { File string `json:"file"` } +// RemoteStatusResult reports the optional remote control connection state. +type RemoteStatusResult struct { + Enabled bool `json:"enabled"` + Connected bool `json:"connected"` + Message string `json:"message,omitempty"` + LastConnect string `json:"lastConnect,omitempty"` +} + // TimeResult 服务端/本地时间查询结果。 type TimeResult struct { ServerTime string `json:"serverTime"` diff --git a/internal/types/shared_proxy_config.go b/internal/types/shared_proxy_config.go index c2d2c3d..433361a 100644 --- a/internal/types/shared_proxy_config.go +++ b/internal/types/shared_proxy_config.go @@ -3,9 +3,10 @@ package types // SharedProxyConfig 是跨实例、跨电脑同步的代理配置。 // 该文件不包含代理 URL、代理过期时间、账号或 Cookie。 type SharedProxyConfig struct { - SchemaVersion int `json:"schemaVersion"` - UpdatedAt string `json:"updatedAt,omitempty"` - Proxy SharedProxySettings `json:"proxy"` + SchemaVersion int `json:"schemaVersion"` + UpdatedAt string `json:"updatedAt,omitempty"` + Proxy SharedProxySettings `json:"proxy"` + Remote SharedRemoteSettings `json:"remote,omitempty"` } // SharedProxySettings 使用指针区分“未提供”与显式零值,支持部分配置覆盖。 @@ -21,6 +22,15 @@ type SharedProxySettings struct { WhitelistSignKey *string `json:"whitelistSignKey,omitempty"` } +// SharedRemoteSettings 是本机或跨电脑共享的远端控制中心配置。 +// 令牌会写入共享 JSON 文件,调用方必须限制该文件权限并避免外部泄露。 +type SharedRemoteSettings struct { + Enabled *bool `json:"enabled,omitempty"` + URL *string `json:"url,omitempty"` + Token *string `json:"token,omitempty"` + MachineName *string `json:"machineName,omitempty"` +} + // FileDialogResult 返回通过系统文件选择器选中的路径。 type FileDialogResult struct { Success bool `json:"success"` diff --git a/internal/types/types.go b/internal/types/types.go index 9e7f7ae..7dc5aa3 100644 --- a/internal/types/types.go +++ b/internal/types/types.go @@ -29,6 +29,10 @@ type Config struct { ProxyWhitelistReplace bool `json:"proxyWhitelistReplace"` // 白名单已满时替换最早 IP ProxyWhitelistPassword string `json:"proxyWhitelistPassword"` // 白名单签名使用的登录密码 ProxyWhitelistSignKey string `json:"proxyWhitelistSignKey"` // 白名单签名使用的 AES 密钥 + RemoteEnabled bool `json:"remoteEnabled"` // 是否上报远端控制中心 + RemoteURL string `json:"remoteUrl"` // 远端控制中心根地址 + RemoteToken string `json:"remoteToken"` // 实例连接远端使用的令牌 + RemoteMachineName string `json:"remoteMachineName"` // 远端展示的机器名称,留空使用主机名 } // ProxyTestResult 代理测试结果。