mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-10-09 00:56:37 +08:00
refactor(backend): rename OpenFlare directory to lowercase openflare
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Package option provides handler-level error message constants for the openflare option module.
|
||||
package option
|
||||
|
||||
const (
|
||||
errInvalidParams = "无效的参数"
|
||||
errOptionInitFailed = "系统选项初始化失败"
|
||||
errGeoIPProvider = "归属方式仅支持 disabled、mmdb、ip-api、geojs、ipinfo"
|
||||
errGeoIPIPEmpty = "IP 不能为空"
|
||||
errGeoIPIPInvalid = "IP 格式无效"
|
||||
errGeoIPLookupDisabled = "GeoIP 查询已禁用"
|
||||
)
|
||||
@@ -0,0 +1,178 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package option
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"Wavelet/openflare/plugins/server/domain/option/uptimekuma"
|
||||
"Wavelet/openflare/plugins/server/kernel/geoip"
|
||||
"Wavelet/openflare/plugins/server/kernel/model"
|
||||
"Wavelet/openflare/plugins/server/kernel/repository"
|
||||
"Wavelet/pkg/buildinfo"
|
||||
)
|
||||
|
||||
type publicAuthSourceView struct {
|
||||
ID uint64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
DisplayName string `json:"display_name"`
|
||||
AuthorizeURL string `json:"authorize_url"`
|
||||
IconURL string `json:"icon_url"`
|
||||
}
|
||||
|
||||
type statusView struct {
|
||||
Version string `json:"version"`
|
||||
StartTime int64 `json:"start_time"`
|
||||
EmailVerification bool `json:"email_verification"`
|
||||
ServerAddress string `json:"server_address"`
|
||||
PasswordRegisterEnabled bool `json:"password_register_enabled"`
|
||||
CapLoginEnabled bool `json:"cap_login_enabled"`
|
||||
AuthSources []publicAuthSourceView `json:"auth_sources"`
|
||||
}
|
||||
|
||||
type geoIPLookupRequest struct {
|
||||
Provider string `json:"provider"`
|
||||
IP string `json:"ip"`
|
||||
}
|
||||
|
||||
type geoIPLookupView struct {
|
||||
Provider string `json:"provider"`
|
||||
IP string `json:"ip"`
|
||||
ISOCode string `json:"iso_code"`
|
||||
Name string `json:"name"`
|
||||
Latitude *float64 `json:"latitude,omitempty"`
|
||||
Longitude *float64 `json:"longitude,omitempty"`
|
||||
}
|
||||
|
||||
type optionBatchPayload struct {
|
||||
Options []model.OpenFlareOption `json:"options"`
|
||||
}
|
||||
|
||||
func listOptions(ctx context.Context) ([]model.OpenFlareOption, error) {
|
||||
// 从 SystemConfig 读取所有业务配置
|
||||
configs, err := repository.ListAdminSystemConfigs(ctx, "business")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
options := make([]model.OpenFlareOption, 0, len(configs))
|
||||
for _, config := range configs {
|
||||
// 跳过敏感配置(如密码、令牌)
|
||||
if config.Visibility == model.ConfigVisibilityHidden && isSecretConfigKey(config.Key) {
|
||||
continue
|
||||
}
|
||||
// 将 snake_case key 转换为 PascalCase 以保持向后兼容
|
||||
options = append(options, model.OpenFlareOption{
|
||||
Key: config.Key,
|
||||
Value: config.Value,
|
||||
})
|
||||
}
|
||||
return options, nil
|
||||
}
|
||||
|
||||
func updateOption(ctx context.Context, option model.OpenFlareOption) error {
|
||||
return updateOptions(ctx, []model.OpenFlareOption{option})
|
||||
}
|
||||
|
||||
func updateOptionsBatch(ctx context.Context, payload optionBatchPayload) error {
|
||||
if len(payload.Options) == 0 {
|
||||
return errors.New(errInvalidParams)
|
||||
}
|
||||
return updateOptions(ctx, payload.Options)
|
||||
}
|
||||
|
||||
func updateOptions(ctx context.Context, options []model.OpenFlareOption) error {
|
||||
if err := validateOptions(ctx, options); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 将每个 option 更新到 SystemConfig
|
||||
for _, opt := range options {
|
||||
if err := repository.SaveOrUpdateSystemConfig(ctx, opt.Key, opt.Value); err != nil {
|
||||
return fmt.Errorf("failed to update config %s: %w", opt.Key, err)
|
||||
}
|
||||
|
||||
// 特殊处理:GeoIP 配置变更时刷新运行时
|
||||
if opt.Key == model.ConfigKeyGeoIPProvider {
|
||||
if err := geoip.RefreshRuntimeProvider(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func getStatus(ctx context.Context, baseAPIPath string) *statusView {
|
||||
authSources, err := publicAuthSources(ctx, baseAPIPath)
|
||||
if err != nil {
|
||||
authSources = []publicAuthSourceView{}
|
||||
}
|
||||
|
||||
// 从 SystemConfig 读取配置
|
||||
emailVerification, _ := repository.GetBoolByKey(ctx, model.ConfigKeyEmailLoginVerificationEnabled)
|
||||
serverAddress, _ := repository.GetSystemConfigByKey(ctx, model.ConfigKeyServerAddress)
|
||||
passwordRegisterEnabled, _ := repository.GetBoolByKey(ctx, model.ConfigKeyPasswordRegisterEnabled)
|
||||
capLoginEnabled, _ := repository.GetBoolByKey(ctx, model.ConfigKeyCapLoginEnabled)
|
||||
|
||||
return &statusView{
|
||||
Version: buildinfo.Version,
|
||||
StartTime: model.StartTime,
|
||||
EmailVerification: emailVerification,
|
||||
ServerAddress: serverAddress.Value,
|
||||
PasswordRegisterEnabled: passwordRegisterEnabled,
|
||||
CapLoginEnabled: capLoginEnabled,
|
||||
AuthSources: authSources,
|
||||
}
|
||||
}
|
||||
|
||||
func publicAuthSources(ctx context.Context, baseAPIPath string) ([]publicAuthSourceView, error) {
|
||||
sources, err := repository.GetActiveAuthSources(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make([]publicAuthSourceView, 0, len(sources))
|
||||
base := strings.TrimRight(baseAPIPath, "/")
|
||||
for _, source := range sources {
|
||||
result = append(result, publicAuthSourceView{
|
||||
ID: source.ID,
|
||||
Name: source.Name,
|
||||
Type: source.Type,
|
||||
DisplayName: source.DisplayName,
|
||||
AuthorizeURL: fmt.Sprintf("%s/oauth/%s/authorize", base, source.Name),
|
||||
IconURL: source.IconURL,
|
||||
})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func lookupGeoIP(_ context.Context, provider, rawIP string) (*geoIPLookupView, error) {
|
||||
view, err := geoip.Lookup(provider, rawIP)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &geoIPLookupView{
|
||||
Provider: view.Provider,
|
||||
IP: view.IP,
|
||||
ISOCode: view.ISOCode,
|
||||
Name: view.Name,
|
||||
Latitude: view.Latitude,
|
||||
Longitude: view.Longitude,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func syncUptimeKuma(ctx context.Context) error {
|
||||
return uptimekuma.SyncToUptimeKuma(ctx)
|
||||
}
|
||||
|
||||
// isSecretConfigKey 判断 SystemConfig 的 key 是否为敏感配置
|
||||
func isSecretConfigKey(key string) bool {
|
||||
return strings.Contains(key, "token") ||
|
||||
strings.Contains(key, "secret") ||
|
||||
strings.Contains(key, "password")
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package option
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"Wavelet/openflare/plugins/server/kernel/model"
|
||||
"Wavelet/openflare/plugins/server/kernel/repository"
|
||||
db "Wavelet/plugins/infra/database"
|
||||
|
||||
"github.com/glebarez/sqlite"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func setupOptionTestDB(t *testing.T) func() {
|
||||
t.Helper()
|
||||
|
||||
sqliteDB, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{
|
||||
DisableForeignKeyConstraintWhenMigrating: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, sqliteDB.AutoMigrate(&model.SystemConfig{}))
|
||||
|
||||
db.SetDB(sqliteDB)
|
||||
|
||||
// 预填充一些业务配置用于测试
|
||||
seedConfigs := []model.SystemConfig{
|
||||
{Key: "geoip_provider", Value: "ipinfo", Type: "business", Visibility: 0},
|
||||
{Key: "uptime_kuma_password", Value: "secret-pwd", Type: "business", Visibility: 0},
|
||||
}
|
||||
for _, cfg := range seedConfigs {
|
||||
require.NoError(t, sqliteDB.Create(&cfg).Error)
|
||||
}
|
||||
|
||||
return func() {
|
||||
db.SetDB(nil)
|
||||
}
|
||||
}
|
||||
|
||||
// setTestConfig 设置测试配置的辅助函数
|
||||
func setTestConfig(t *testing.T, ctx context.Context, key, value string) {
|
||||
t.Helper()
|
||||
require.NoError(t, db.DB(ctx).Model(&model.SystemConfig{}).Where("key = ?", key).Update("value", value).Error)
|
||||
}
|
||||
|
||||
func TestListOptionsFiltersSecretKeys(t *testing.T) {
|
||||
cleanup := setupOptionTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
options, err := listOptions(ctx)
|
||||
require.NoError(t, err)
|
||||
|
||||
keys := make(map[string]string, len(options))
|
||||
for _, option := range options {
|
||||
keys[option.Key] = option.Value
|
||||
}
|
||||
|
||||
// geoip_provider 应该出现在列表中
|
||||
assert.Equal(t, "ipinfo", keys["geoip_provider"])
|
||||
// 敏感配置(密码)应该被过滤掉
|
||||
assert.NotContains(t, keys, "uptime_kuma_password")
|
||||
}
|
||||
|
||||
func TestUpdateOptionPersistsToSystemConfig(t *testing.T) {
|
||||
cleanup := setupOptionTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
err := updateOption(ctx, model.OpenFlareOption{
|
||||
Key: model.ConfigKeyGeoIPProvider,
|
||||
Value: "mmdb",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// 验证配置已写入 SystemConfig
|
||||
config, err := repository.GetSystemConfigByKey(ctx, model.ConfigKeyGeoIPProvider)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "mmdb", config.Value)
|
||||
}
|
||||
|
||||
func TestUpdateOpenRestyOptionPersistsToSystemConfig(t *testing.T) {
|
||||
cleanup := setupOptionTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, db.DB(ctx).Create(&model.SystemConfig{
|
||||
Key: model.ConfigKeyOpenRestyEventsUse,
|
||||
Value: "epoll",
|
||||
Type: "business",
|
||||
Visibility: 0,
|
||||
}).Error)
|
||||
|
||||
err := updateOption(ctx, model.OpenFlareOption{
|
||||
Key: model.ConfigKeyOpenRestyEventsUse,
|
||||
Value: "kqueue",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
config, err := repository.GetSystemConfigByKey(ctx, model.ConfigKeyOpenRestyEventsUse)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "kqueue", config.Value)
|
||||
}
|
||||
|
||||
func TestLookupGeoIPDisabledProvider(t *testing.T) {
|
||||
cleanup := setupOptionTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
view, err := lookupGeoIP(ctx, "disabled", "8.8.8.8")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "disabled", view.Provider)
|
||||
assert.Equal(t, "8.8.8.8", view.IP)
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package option
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"Wavelet/openflare/plugins/server/kernel/model"
|
||||
openrestyrender "Wavelet/openflare/share/render/openresty"
|
||||
)
|
||||
|
||||
const (
|
||||
maxOriginErrorPageHTMLBytes = 256 << 10 // 256 KiB
|
||||
maxSWOfflineDomains = 1000
|
||||
)
|
||||
|
||||
var openRestyOptionValidators = map[string]func(key, value string) error{
|
||||
model.ConfigKeyOpenRestyDefaultServerReturnStatus: validateOpenRestyDefaultServerReturnStatus,
|
||||
model.ConfigKeyOpenRestyWorkerProcesses: validateOpenRestyWorkerProcesses,
|
||||
model.ConfigKeyOpenRestyWorkerConnections: validatePositiveIntegerOption,
|
||||
model.ConfigKeyOpenRestyWorkerRlimitNofile: validatePositiveIntegerOption,
|
||||
model.ConfigKeyOpenRestyKeepaliveTimeout: validatePositiveIntegerOption,
|
||||
model.ConfigKeyOpenRestyKeepaliveRequests: validatePositiveIntegerOption,
|
||||
model.ConfigKeyOpenRestyClientHeaderTimeout: validatePositiveIntegerOption,
|
||||
model.ConfigKeyOpenRestyClientBodyTimeout: validatePositiveIntegerOption,
|
||||
model.ConfigKeyOpenRestySendTimeout: validatePositiveIntegerOption,
|
||||
model.ConfigKeyOpenRestyProxyConnectTimeout: validatePositiveIntegerOption,
|
||||
model.ConfigKeyOpenRestyProxySendTimeout: validatePositiveIntegerOption,
|
||||
model.ConfigKeyOpenRestyProxyReadTimeout: validatePositiveIntegerOption,
|
||||
model.ConfigKeyOpenRestyGzipMinLength: validatePositiveIntegerOption,
|
||||
model.ConfigKeyOpenRestyGzipCompLevel: validateOpenRestyGzipCompLevel,
|
||||
model.ConfigKeyOpenRestyEventsUse: validateOpenRestyEventsUse,
|
||||
model.ConfigKeyOpenRestyResolvers: validateOpenRestyResolvers,
|
||||
model.ConfigKeyOpenRestyEventsMultiAcceptEnabled: validateBooleanOption,
|
||||
model.ConfigKeyOpenRestyWebsocketEnabled: validateBooleanOption,
|
||||
model.ConfigKeyOpenRestyHTTP3Enabled: validateBooleanOption,
|
||||
model.ConfigKeyOpenRestyProxyRequestBufferingEnabled: validateBooleanOption,
|
||||
model.ConfigKeyOpenRestyProxyBufferingEnabled: validateBooleanOption,
|
||||
model.ConfigKeyOpenRestyGzipEnabled: validateBooleanOption,
|
||||
model.ConfigKeyOpenRestyCacheEnabled: validateBooleanOption,
|
||||
model.ConfigKeyOpenRestyCacheLockEnabled: validateBooleanOption,
|
||||
model.ConfigKeyOpenRestyProxyBuffers: validateOpenRestyProxyBuffers,
|
||||
model.ConfigKeyOpenRestyLargeClientHeaderBuffers: validateOpenRestyProxyBuffers,
|
||||
model.ConfigKeyOpenRestyProxyBufferSize: validateOpenRestySizeValue,
|
||||
model.ConfigKeyOpenRestyProxyBusyBuffersSize: validateOpenRestySizeValue,
|
||||
model.ConfigKeyOpenRestyCacheMaxSize: validateOpenRestySizeValue,
|
||||
model.ConfigKeyOpenRestyClientMaxBodySize: validateOpenRestySizeValue,
|
||||
model.ConfigKeyOpenRestyCachePath: validateOpenRestyCachePath,
|
||||
model.ConfigKeyOpenRestyCacheLevels: validateOpenRestyCacheLevels,
|
||||
model.ConfigKeyOpenRestyCacheInactive: validateOpenRestyDurationToken,
|
||||
model.ConfigKeyOpenRestyCacheLockTimeout: validateOpenRestyDurationToken,
|
||||
model.ConfigKeyOpenRestyCacheKeyTemplate: validateOpenRestyCacheKeyTemplate,
|
||||
model.ConfigKeyOpenRestyCacheUseStale: validateOpenRestyCacheUseStale,
|
||||
model.ConfigKeyOpenRestyMainConfigTemplate: validateOpenRestyMainConfigTemplate,
|
||||
model.ConfigKeyOpenRestyDefaultLimitConnPerServer: validateNonNegativeIntegerOption,
|
||||
model.ConfigKeyOpenRestyDefaultLimitConnPerIP: validateNonNegativeIntegerOption,
|
||||
model.ConfigKeyOpenRestyDefaultLimitRate: validateOpenRestyDefaultLimitRate,
|
||||
model.ConfigKeyOpenRestyDefaultLimitReqPerIP: validateOpenRestyDefaultLimitReqPerIP,
|
||||
model.ConfigKeyOriginErrorPageEnabled: validateBooleanOption,
|
||||
model.ConfigKeyOriginErrorPageStatusCodes: validateOriginErrorPageStatusCodes,
|
||||
model.ConfigKeyOriginErrorPageHTML: validateOriginErrorPageHTML,
|
||||
model.ConfigKeyOriginErrorPageGetOnly: validateBooleanOption,
|
||||
model.ConfigKeySWOfflineEnabled: validateBooleanOption,
|
||||
model.ConfigKeySWOfflineHTML: validateSWOfflineHTML,
|
||||
model.ConfigKeySWOfflineDomains: validateSWOfflineDomains,
|
||||
}
|
||||
|
||||
var openRestyDefaultLimitRatePattern = regexp.MustCompile(`^\d+[kKmM]?$`)
|
||||
|
||||
func validateOpenRestyOption(key, value string) error {
|
||||
// HTML 按原始字节长度校验,避免 TrimSpace 影响上限判断
|
||||
if key == model.ConfigKeyOriginErrorPageHTML || key == model.ConfigKeySWOfflineHTML {
|
||||
return validateOriginErrorPageHTML(key, value)
|
||||
}
|
||||
trimmed := strings.TrimSpace(value)
|
||||
if validator, ok := openRestyOptionValidators[key]; ok {
|
||||
return validator(key, trimmed)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateOpenRestyDefaultServerReturnStatus(key, trimmed string) error {
|
||||
if err := validatePositiveIntegerOption(key, trimmed); err != nil {
|
||||
return err
|
||||
}
|
||||
statusCode, _ := strconv.Atoi(trimmed)
|
||||
if statusCode < 100 || statusCode > 999 {
|
||||
return fmt.Errorf("%s 必须在 100 到 999 之间", key)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateOpenRestyWorkerProcesses(key, trimmed string) error {
|
||||
if trimmed == "auto" {
|
||||
return nil
|
||||
}
|
||||
return validatePositiveIntegerOption(key, trimmed)
|
||||
}
|
||||
|
||||
func validateOpenRestyGzipCompLevel(key, trimmed string) error {
|
||||
if err := validatePositiveIntegerOption(key, trimmed); err != nil {
|
||||
return err
|
||||
}
|
||||
level, _ := strconv.Atoi(trimmed)
|
||||
if level > maxOpenRestyGzipCompLevel {
|
||||
return fmt.Errorf("%s 不能大于 %d", key, maxOpenRestyGzipCompLevel)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateOpenRestyEventsUse(key, trimmed string) error {
|
||||
if trimmed == "" {
|
||||
return nil
|
||||
}
|
||||
switch trimmed {
|
||||
case "epoll", "kqueue", "poll", "select", "rtsig", "/dev/poll", "eventport":
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("%s 仅支持 epoll、kqueue、poll、select、rtsig、/dev/poll、eventport 或留空", key)
|
||||
}
|
||||
}
|
||||
|
||||
func validateOpenRestyResolvers(key, trimmed string) error {
|
||||
if trimmed == "" {
|
||||
return nil
|
||||
}
|
||||
if !regexp.MustCompile(`^[a-zA-Z0-9.:\-\s]+$`).MatchString(trimmed) {
|
||||
return fmt.Errorf("%s 包含非法字符,请填入有效的 IP 地址或域名,以空格分隔", key)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateOpenRestyProxyBuffers(key, trimmed string) error {
|
||||
if openRestyProxyBuffersPattern.MatchString(trimmed) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("%s 格式必须类似 \"16 16k\"", key)
|
||||
}
|
||||
|
||||
func validateOpenRestySizeValue(key, trimmed string) error {
|
||||
if openRestySizePattern.MatchString(trimmed) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("%s 格式必须为整数或带 k/m/g 单位的大小值", key)
|
||||
}
|
||||
|
||||
func validateOpenRestyCachePath(key, trimmed string) error {
|
||||
if strings.ContainsAny(trimmed, "\r\n\t") {
|
||||
return fmt.Errorf("%s 不能包含换行或制表符", key)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateOpenRestyCacheLevels(key, trimmed string) error {
|
||||
if openRestyCacheLevelsPattern.MatchString(trimmed) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("%s 格式必须类似 \"1:2\" 或 \"1:2:2\"", key)
|
||||
}
|
||||
|
||||
func validateOpenRestyDurationToken(key, trimmed string) error {
|
||||
if openRestyDurationTokenPattern.MatchString(trimmed) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("%s 格式必须为带单位的时长,例如 30m 或 5s", key)
|
||||
}
|
||||
|
||||
func validateOpenRestyCacheKeyTemplate(key, trimmed string) error {
|
||||
if trimmed == "" {
|
||||
return fmt.Errorf("%s 不能为空", key)
|
||||
}
|
||||
if strings.ContainsAny(trimmed, "\r\n") {
|
||||
return fmt.Errorf("%s 不能包含换行", key)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateOpenRestyCacheUseStale(key, trimmed string) error {
|
||||
if trimmed == "" {
|
||||
return fmt.Errorf("%s 不能为空", key)
|
||||
}
|
||||
allowedTokens := map[string]struct{}{
|
||||
"error": {}, "timeout": {}, "invalid_header": {}, "updating": {},
|
||||
"http_500": {}, "http_502": {}, "http_503": {}, "http_504": {},
|
||||
"http_403": {}, "http_404": {}, "http_429": {}, "off": {},
|
||||
}
|
||||
for token := range strings.FieldsSeq(trimmed) {
|
||||
if _, ok := allowedTokens[token]; !ok {
|
||||
return fmt.Errorf("%s 包含不支持的值 %q", key, token)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateOpenRestyMainConfigTemplate(key, value string) error {
|
||||
if strings.TrimSpace(value) == "" {
|
||||
return fmt.Errorf("%s 不能为空", key)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateOpenRestyDefaultLimitRate(key, trimmed string) error {
|
||||
if trimmed == "" || trimmed == "0" {
|
||||
return nil
|
||||
}
|
||||
if !openRestyDefaultLimitRatePattern.MatchString(strings.ToLower(trimmed)) {
|
||||
return fmt.Errorf("%s 格式不合法,请使用 512k、1m 或纯数字,空表示关闭", key)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var openRestyDefaultLimitReqPerIPPattern = regexp.MustCompile(`^\d+r/[sm]$`)
|
||||
|
||||
func validateOpenRestyDefaultLimitReqPerIP(key, trimmed string) error {
|
||||
if trimmed == "" || trimmed == "0" {
|
||||
return nil
|
||||
}
|
||||
if !openRestyDefaultLimitReqPerIPPattern.MatchString(strings.ToLower(trimmed)) {
|
||||
return fmt.Errorf("%s 格式不合法,请输入类似 10r/s、100r/m,或留空关闭", key)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateOriginErrorPageStatusCodes(key, trimmed string) error {
|
||||
if trimmed == "" {
|
||||
return fmt.Errorf("%s 不能为空", key)
|
||||
}
|
||||
var tags []string
|
||||
if err := json.Unmarshal([]byte(trimmed), &tags); err != nil {
|
||||
return fmt.Errorf("%s 必须为 JSON 字符串数组", key)
|
||||
}
|
||||
if len(tags) == 0 {
|
||||
return fmt.Errorf("%s 至少包含一个状态码标签", key)
|
||||
}
|
||||
codes, err := openrestyrender.ExpandStatusCodeTags(tags)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: %w", key, err)
|
||||
}
|
||||
if len(codes) == 0 {
|
||||
return fmt.Errorf("%s 展开后不能为空", key)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateOriginErrorPageHTML(key, value string) error {
|
||||
if len(value) > maxOriginErrorPageHTMLBytes {
|
||||
return fmt.Errorf("%s 长度不能超过 %d 字节(256 KiB)", key, maxOriginErrorPageHTMLBytes)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateSWOfflineHTML(key, value string) error {
|
||||
return validateOriginErrorPageHTML(key, value)
|
||||
}
|
||||
|
||||
func validateSWOfflineDomains(key, value string) error {
|
||||
var domains []string
|
||||
if err := json.Unmarshal([]byte(value), &domains); err != nil || domains == nil {
|
||||
return fmt.Errorf("%s 必须为 JSON 字符串数组", key)
|
||||
}
|
||||
if len(domains) > maxSWOfflineDomains {
|
||||
return fmt.Errorf("%s 最多支持 %d 个域名", key, maxSWOfflineDomains)
|
||||
}
|
||||
seen := make(map[string]struct{}, len(domains))
|
||||
for _, raw := range domains {
|
||||
domain := strings.ToLower(strings.TrimSpace(raw))
|
||||
if domain == "" {
|
||||
return fmt.Errorf("%s 包含空域名", key)
|
||||
}
|
||||
if raw != domain {
|
||||
return fmt.Errorf("%s 域名必须为小写且不含首尾空格:%s", key, raw)
|
||||
}
|
||||
if _, ok := seen[domain]; ok {
|
||||
return fmt.Errorf("%s 包含重复域名 %s", key, domain)
|
||||
}
|
||||
seen[domain] = struct{}{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package option
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"Wavelet/openflare/plugins/server/kernel/model"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestValidateOriginErrorPageStatusCodes(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
value string
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "合法单码与区间",
|
||||
value: `["522","500-502"]`,
|
||||
},
|
||||
{
|
||||
name: "默认区间",
|
||||
value: `["500-599"]`,
|
||||
},
|
||||
{
|
||||
name: "非法标签",
|
||||
value: `["abc"]`,
|
||||
wantErr: "无效状态码",
|
||||
},
|
||||
{
|
||||
name: "非 JSON 数组",
|
||||
value: `500-599`,
|
||||
wantErr: "必须为 JSON 字符串数组",
|
||||
},
|
||||
{
|
||||
name: "空数组",
|
||||
value: `[]`,
|
||||
wantErr: "至少包含一个状态码标签",
|
||||
},
|
||||
{
|
||||
name: "越界状态码",
|
||||
value: `["399"]`,
|
||||
wantErr: "状态码须在",
|
||||
},
|
||||
{
|
||||
name: "空字符串",
|
||||
value: "",
|
||||
wantErr: "不能为空",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
err := validateOpenRestyOption(model.ConfigKeyOriginErrorPageStatusCodes, tt.value)
|
||||
if tt.wantErr == "" {
|
||||
require.NoError(t, err)
|
||||
return
|
||||
}
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), tt.wantErr)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateOriginErrorPageHTML(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
require.NoError(t, validateOpenRestyOption(model.ConfigKeyOriginErrorPageHTML, ""))
|
||||
require.NoError(t, validateOpenRestyOption(model.ConfigKeyOriginErrorPageHTML, "<html>ok</html>"))
|
||||
|
||||
oversized := strings.Repeat("a", maxOriginErrorPageHTMLBytes+1)
|
||||
err := validateOpenRestyOption(model.ConfigKeyOriginErrorPageHTML, oversized)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "长度不能超过")
|
||||
|
||||
// 恰好上限应通过
|
||||
atLimit := strings.Repeat("b", maxOriginErrorPageHTMLBytes)
|
||||
require.NoError(t, validateOpenRestyOption(model.ConfigKeyOriginErrorPageHTML, atLimit))
|
||||
}
|
||||
|
||||
func TestValidateOriginErrorPageEnabled(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
require.NoError(t, validateOpenRestyOption(model.ConfigKeyOriginErrorPageEnabled, "true"))
|
||||
require.NoError(t, validateOpenRestyOption(model.ConfigKeyOriginErrorPageEnabled, "false"))
|
||||
err := validateOpenRestyOption(model.ConfigKeyOriginErrorPageEnabled, "yes")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "true 或 false")
|
||||
}
|
||||
|
||||
func TestValidateSWOfflineDomains(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
value string
|
||||
ok bool
|
||||
}{
|
||||
{"empty array", `[]`, true},
|
||||
{"single", `["example.com"]`, true},
|
||||
{"multiple", `["example.com","api.example.com"]`, true},
|
||||
{"invalid json", `not-json`, false},
|
||||
{"null", "null", false},
|
||||
{"empty element", `[""]`, false},
|
||||
{"duplicate", `["example.com","example.com"]`, false},
|
||||
{"whitespace dedup", `[" Example.com ","example.com"]`, false},
|
||||
{"over limit", fmt.Sprintf(`[%s]`, strings.Repeat(`"a.com",`, maxSWOfflineDomains)+`"a.com"`), false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := validateSWOfflineDomains("sw_offline_domains", tc.value)
|
||||
if tc.ok && err != nil {
|
||||
t.Fatalf("want ok, got %v", err)
|
||||
}
|
||||
if !tc.ok && err == nil {
|
||||
t.Fatal("want error, got nil")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package option
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"Wavelet/openflare/plugins/server/kernel/apiutil"
|
||||
"Wavelet/openflare/plugins/server/kernel/model"
|
||||
"Wavelet/pkg/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// GetStatusHandler 获取公开运行状态。
|
||||
// @Summary 获取 OpenFlare 公开状态
|
||||
// @Description 返回版本、认证源与系统公开配置,无需登录
|
||||
// @Tags openflare-option
|
||||
// @Produce json
|
||||
// @Success 200 {object} response.Any{data=option.statusView} "公开状态"
|
||||
// @Failure 400 {object} response.Any "参数错误"
|
||||
// @Failure 500 {object} response.Any "内部错误"
|
||||
// @Router /api/v1/d/status [get]
|
||||
func GetStatusHandler(c *gin.Context) {
|
||||
view := getStatus(c.Request.Context(), "/api/v1/d")
|
||||
c.JSON(http.StatusOK, response.OK(view))
|
||||
}
|
||||
|
||||
// ListOptionsHandler 列出全部配置项。
|
||||
// @Summary 列出 OpenFlare 配置项
|
||||
// @Description 返回全部非敏感 OpenFlare 配置项,需要管理员权限
|
||||
// @Tags openflare-option
|
||||
// @Produce json
|
||||
// @Security SessionCookie
|
||||
// @Success 200 {object} response.Any{data=[]model.OpenFlareOption} "配置项列表"
|
||||
// @Failure 400 {object} response.Any "参数错误"
|
||||
// @Failure 401 {object} response.Any "未登录"
|
||||
// @Failure 404 {object} response.Any "无权限或不存在"
|
||||
// @Failure 500 {object} response.Any "内部错误"
|
||||
// @Router /api/v1/d/option [get]
|
||||
func ListOptionsHandler(c *gin.Context) {
|
||||
options, err := listOptions(c.Request.Context())
|
||||
if apiutil.AbortBadRequestOnError(c, err) {
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, response.OK(options))
|
||||
}
|
||||
|
||||
// UpdateOptionHandler 更新单个配置项。
|
||||
// @Summary 更新 OpenFlare 配置项
|
||||
// @Description 更新单个 OpenFlare 配置项,需要管理员权限
|
||||
// @Tags openflare-option
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security SessionCookie
|
||||
// @Param request body model.OpenFlareOption true "配置项"
|
||||
// @Success 200 {object} response.Any "更新成功"
|
||||
// @Failure 400 {object} response.Any "参数错误"
|
||||
// @Failure 401 {object} response.Any "未登录"
|
||||
// @Failure 404 {object} response.Any "无权限或不存在"
|
||||
// @Failure 500 {object} response.Any "内部错误"
|
||||
// @Router /api/v1/d/option/update [post]
|
||||
func UpdateOptionHandler(c *gin.Context) {
|
||||
var option model.OpenFlareOption
|
||||
if !apiutil.BindJSON(c, &option) {
|
||||
return
|
||||
}
|
||||
if apiutil.AbortBadRequestOnError(c, updateOption(c.Request.Context(), option)) {
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, response.OKNil())
|
||||
}
|
||||
|
||||
// UpdateOptionsBatchHandler 批量更新配置项。
|
||||
// @Summary 批量更新 OpenFlare 配置项
|
||||
// @Description 批量更新多个 OpenFlare 配置项,需要管理员权限
|
||||
// @Tags openflare-option
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security SessionCookie
|
||||
// @Param request body option.optionBatchPayload true "批量配置项"
|
||||
// @Success 200 {object} response.Any "更新成功"
|
||||
// @Failure 400 {object} response.Any "参数错误"
|
||||
// @Failure 401 {object} response.Any "未登录"
|
||||
// @Failure 404 {object} response.Any "无权限或不存在"
|
||||
// @Failure 500 {object} response.Any "内部错误"
|
||||
// @Router /api/v1/d/option/update-batch [post]
|
||||
func UpdateOptionsBatchHandler(c *gin.Context) {
|
||||
var payload optionBatchPayload
|
||||
if !apiutil.BindJSON(c, &payload) {
|
||||
return
|
||||
}
|
||||
if apiutil.AbortBadRequestOnError(c, updateOptionsBatch(c.Request.Context(), payload)) {
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, response.OKNil())
|
||||
}
|
||||
|
||||
// LookupGeoIPHandler 查询 GeoIP 信息。
|
||||
// @Summary GeoIP 地址查询
|
||||
// @Description 按提供商与 IP 查询地理位置信息,需要管理员权限
|
||||
// @Tags openflare-option
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security SessionCookie
|
||||
// @Param request body option.geoIPLookupRequest true "查询参数"
|
||||
// @Success 200 {object} response.Any{data=option.geoIPLookupView} "GeoIP 查询结果"
|
||||
// @Failure 400 {object} response.Any "参数错误"
|
||||
// @Failure 401 {object} response.Any "未登录"
|
||||
// @Failure 404 {object} response.Any "无权限或不存在"
|
||||
// @Failure 500 {object} response.Any "内部错误"
|
||||
// @Router /api/v1/d/option/geoip/lookup [post]
|
||||
func LookupGeoIPHandler(c *gin.Context) {
|
||||
var request geoIPLookupRequest
|
||||
if !apiutil.BindJSON(c, &request) {
|
||||
return
|
||||
}
|
||||
view, err := lookupGeoIP(c.Request.Context(), request.Provider, request.IP)
|
||||
if apiutil.AbortBadRequestOnError(c, err) {
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, response.OK(view))
|
||||
}
|
||||
|
||||
// SyncUptimeKumaHandler 同步 Uptime Kuma 监控。
|
||||
// @Summary 同步 Uptime Kuma
|
||||
// @Description 将 OpenFlare 节点同步到 Uptime Kuma,需要管理员权限
|
||||
// @Tags openflare-option
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security SessionCookie
|
||||
// @Success 200 {object} response.Any{data=string} "同步成功"
|
||||
// @Failure 400 {object} response.Any "参数错误"
|
||||
// @Failure 401 {object} response.Any "未登录"
|
||||
// @Failure 404 {object} response.Any "无权限或不存在"
|
||||
// @Failure 500 {object} response.Any "内部错误"
|
||||
// @Router /api/v1/d/uptimekuma/sync [post]
|
||||
func SyncUptimeKumaHandler(c *gin.Context) {
|
||||
if apiutil.AbortBadRequestOnError(c, syncUptimeKuma(c.Request.Context())) {
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, response.OK("同步成功"))
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Package uptimekuma provides a Socket.IO client and sync implementation for Uptime Kuma.
|
||||
package uptimekuma
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const emitAckTimeout = 10 * time.Second
|
||||
|
||||
// Monitor represents a monitor entry from Uptime Kuma.
|
||||
type Monitor struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
URL string `json:"url"`
|
||||
Type string `json:"type"`
|
||||
Interval int `json:"interval"`
|
||||
MaxRetries int `json:"maxretries"`
|
||||
RetryInterval int `json:"retryInterval"`
|
||||
Timeout int `json:"timeout"`
|
||||
Tags []Tag `json:"tags"`
|
||||
}
|
||||
|
||||
// Tag represents a tag attached to a monitor.
|
||||
type Tag struct {
|
||||
ID int `json:"tag_id"`
|
||||
Name string `json:"name"`
|
||||
Color string `json:"color"`
|
||||
}
|
||||
|
||||
// TagItem represents a tag returned by getTags.
|
||||
type TagItem struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Color string `json:"color"`
|
||||
}
|
||||
|
||||
// SocketIOClient is a minimal Engine.IO/Socket.IO polling client for Uptime Kuma.
|
||||
type SocketIOClient struct {
|
||||
baseURL string
|
||||
httpClient *http.Client
|
||||
sid string
|
||||
ackMutex sync.Mutex
|
||||
ackID int
|
||||
ackChanMap map[int]chan string
|
||||
doneChan chan struct{}
|
||||
closeOnce sync.Once
|
||||
|
||||
monitorListMutex sync.RWMutex
|
||||
monitorList map[string]Monitor
|
||||
monitorListChan chan struct{}
|
||||
monitorListOnce sync.Once
|
||||
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
|
||||
err error
|
||||
}
|
||||
|
||||
// NewSocketIOClient creates a Socket.IO polling client for the given base URL.
|
||||
func NewSocketIOClient(baseURL string) *SocketIOClient {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
return &SocketIOClient{
|
||||
baseURL: strings.TrimSuffix(baseURL, "/"),
|
||||
httpClient: &http.Client{
|
||||
Timeout: 60 * time.Second,
|
||||
},
|
||||
ackChanMap: make(map[int]chan string),
|
||||
doneChan: make(chan struct{}),
|
||||
monitorListChan: make(chan struct{}),
|
||||
monitorList: make(map[string]Monitor),
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
}
|
||||
}
|
||||
|
||||
// Connect performs the Engine.IO handshake and starts the polling loop.
|
||||
func (c *SocketIOClient) Connect() error {
|
||||
slog.Debug("Uptime Kuma client starting handshake", "baseURL", c.baseURL)
|
||||
u := c.baseURL + "/socket.io/?EIO=4&transport=polling"
|
||||
reqHandshake, err := http.NewRequestWithContext(c.ctx, http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create handshake request failed: %w", err)
|
||||
}
|
||||
resp, err := c.httpClient.Do(reqHandshake)
|
||||
if err != nil {
|
||||
slog.Error("Uptime Kuma handshake connection failed", "url", u, "error", err)
|
||||
return fmt.Errorf("handshake request failed: %w", err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
bs, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
slog.Error("Failed to read Uptime Kuma handshake response body", "error", err)
|
||||
return fmt.Errorf("read handshake body failed: %w", err)
|
||||
}
|
||||
|
||||
bodyStr := string(bs)
|
||||
slog.Debug("Received handshake response from Uptime Kuma", "body", bodyStr)
|
||||
if len(bodyStr) == 0 || bodyStr[0] != '0' {
|
||||
return fmt.Errorf("invalid handshake response format: %s", bodyStr)
|
||||
}
|
||||
|
||||
var hs struct {
|
||||
Sid string `json:"sid"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(bodyStr[1:]), &hs); err != nil {
|
||||
return fmt.Errorf("unmarshal handshake sid failed: %w", err)
|
||||
}
|
||||
c.sid = hs.Sid
|
||||
slog.Debug("Uptime Kuma handshake success", "sid", c.sid)
|
||||
|
||||
slog.Debug("Sending namespace connect request to Uptime Kuma", "sid", c.sid)
|
||||
connectURL := fmt.Sprintf("%s/socket.io/?EIO=4&transport=polling&sid=%s", c.baseURL, c.sid)
|
||||
req, err := http.NewRequestWithContext(c.ctx, http.MethodPost, connectURL, strings.NewReader("40"))
|
||||
if err != nil {
|
||||
return fmt.Errorf("create connect request failed: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "text/plain;charset=UTF-8")
|
||||
respConnect, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
slog.Error("Uptime Kuma namespace connect request failed", "sid", c.sid, "error", err)
|
||||
return fmt.Errorf("namespace connect failed: %w", err)
|
||||
}
|
||||
_ = respConnect.Body.Close()
|
||||
slog.Debug("Namespace connected successfully to Uptime Kuma", "sid", c.sid)
|
||||
|
||||
go c.pollLoop()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *SocketIOClient) pollLoop() {
|
||||
slog.Debug("Uptime Kuma polling loop started", "sid", c.sid)
|
||||
defer c.Close()
|
||||
for {
|
||||
select {
|
||||
case <-c.doneChan:
|
||||
slog.Debug("Uptime Kuma polling loop stopped (doneChan closed)", "sid", c.sid)
|
||||
return
|
||||
default:
|
||||
}
|
||||
|
||||
u := fmt.Sprintf("%s/socket.io/?EIO=4&transport=polling&sid=%s", c.baseURL, c.sid)
|
||||
reqPoll, err := http.NewRequestWithContext(c.ctx, http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
slog.Error("Failed to create Uptime Kuma polling request", "sid", c.sid, "error", err)
|
||||
c.err = err
|
||||
return
|
||||
}
|
||||
resp, err := c.httpClient.Do(reqPoll)
|
||||
if err != nil {
|
||||
slog.Error("Uptime Kuma polling request failed", "sid", c.sid, "error", err)
|
||||
c.err = err
|
||||
return
|
||||
}
|
||||
|
||||
bs, err := io.ReadAll(resp.Body)
|
||||
_ = resp.Body.Close()
|
||||
if err != nil {
|
||||
slog.Error("Failed to read Uptime Kuma polling body", "sid", c.sid, "error", err)
|
||||
c.err = err
|
||||
return
|
||||
}
|
||||
|
||||
bodyStr := string(bs)
|
||||
if len(bodyStr) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
slog.Debug("Received polling payload from Uptime Kuma", "length", len(bodyStr))
|
||||
packets := strings.SplitSeq(bodyStr, "\x1e")
|
||||
for pkt := range packets {
|
||||
if len(pkt) == 0 {
|
||||
continue
|
||||
}
|
||||
engineIOType := pkt[0]
|
||||
payload := pkt[1:]
|
||||
|
||||
slog.Debug("Parsing engine.io packet", "type", string(engineIOType), "payload_len", len(payload))
|
||||
switch engineIOType {
|
||||
case '2':
|
||||
slog.Debug("Received engine.io ping, responding with pong", "sid", c.sid)
|
||||
c.sendPong()
|
||||
case '4':
|
||||
if len(payload) == 0 {
|
||||
continue
|
||||
}
|
||||
socketIOType := payload[0]
|
||||
socketIOPayload := payload[1:]
|
||||
|
||||
slog.Debug("Parsing socket.io packet", "type", string(socketIOType), "payload", socketIOPayload)
|
||||
switch socketIOType {
|
||||
case '2':
|
||||
c.handleEvent(socketIOPayload)
|
||||
case '3':
|
||||
c.handleAck(socketIOPayload)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *SocketIOClient) sendPong() {
|
||||
u := fmt.Sprintf("%s/socket.io/?EIO=4&transport=polling&sid=%s", c.baseURL, c.sid)
|
||||
req, err := http.NewRequestWithContext(c.ctx, http.MethodPost, u, strings.NewReader("3"))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
req.Header.Set("Content-Type", "text/plain;charset=UTF-8")
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err == nil {
|
||||
_ = resp.Body.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *SocketIOClient) handleEvent(payload string) {
|
||||
var arr []json.RawMessage
|
||||
if err := json.Unmarshal([]byte(payload), &arr); err != nil || len(arr) < 2 {
|
||||
return
|
||||
}
|
||||
var eventName string
|
||||
if err := json.Unmarshal(arr[0], &eventName); err != nil {
|
||||
return
|
||||
}
|
||||
if eventName == "monitorList" {
|
||||
var list map[string]Monitor
|
||||
if err := json.Unmarshal(arr[1], &list); err == nil {
|
||||
c.monitorListMutex.Lock()
|
||||
c.monitorList = list
|
||||
c.monitorListMutex.Unlock()
|
||||
c.monitorListOnce.Do(func() {
|
||||
close(c.monitorListChan)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *SocketIOClient) handleAck(payload string) {
|
||||
idx := strings.IndexByte(payload, '[')
|
||||
if idx == -1 {
|
||||
return
|
||||
}
|
||||
ackIDStr := payload[:idx]
|
||||
ackID, err := strconv.Atoi(ackIDStr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
c.ackMutex.Lock()
|
||||
ch, ok := c.ackChanMap[ackID]
|
||||
if ok {
|
||||
delete(c.ackChanMap, ackID)
|
||||
c.ackMutex.Unlock()
|
||||
select {
|
||||
case ch <- payload[idx:]:
|
||||
default:
|
||||
}
|
||||
} else {
|
||||
c.ackMutex.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// Emit sends a Socket.IO event and waits for the corresponding ack.
|
||||
func (c *SocketIOClient) Emit(event string, args ...any) (string, error) {
|
||||
c.ackMutex.Lock()
|
||||
id := c.ackID
|
||||
c.ackID++
|
||||
ch := make(chan string, 1)
|
||||
c.ackChanMap[id] = ch
|
||||
c.ackMutex.Unlock()
|
||||
|
||||
payloadArr := make([]any, 1, 1+len(args))
|
||||
payloadArr[0] = event
|
||||
payloadArr = append(payloadArr, args...)
|
||||
bs, err := json.Marshal(payloadArr)
|
||||
if err != nil {
|
||||
c.ackMutex.Lock()
|
||||
delete(c.ackChanMap, id)
|
||||
c.ackMutex.Unlock()
|
||||
slog.Error("Failed to marshal event payload", "event", event, "error", err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
body := fmt.Sprintf("42%d%s", id, string(bs))
|
||||
slog.Debug("Emitting Socket.IO event", "event", event, "ackID", id, "payload_len", len(bs))
|
||||
|
||||
u := fmt.Sprintf("%s/socket.io/?EIO=4&transport=polling&sid=%s", c.baseURL, c.sid)
|
||||
req, err := http.NewRequestWithContext(c.ctx, http.MethodPost, u, strings.NewReader(body))
|
||||
if err != nil {
|
||||
c.ackMutex.Lock()
|
||||
delete(c.ackChanMap, id)
|
||||
c.ackMutex.Unlock()
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Content-Type", "text/plain;charset=UTF-8")
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
c.ackMutex.Lock()
|
||||
delete(c.ackChanMap, id)
|
||||
c.ackMutex.Unlock()
|
||||
slog.Error("Failed to send Emit request", "event", event, "ackID", id, "error", err)
|
||||
return "", err
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
|
||||
select {
|
||||
case result := <-ch:
|
||||
slog.Debug("Received Ack for event", "event", event, "ackID", id, "response", result)
|
||||
return result, nil
|
||||
case <-time.After(emitAckTimeout):
|
||||
c.ackMutex.Lock()
|
||||
delete(c.ackChanMap, id)
|
||||
c.ackMutex.Unlock()
|
||||
slog.Error("Timeout waiting for event Ack", "event", event, "ackID", id)
|
||||
return "", fmt.Errorf("timeout waiting for ack for event: %s", event)
|
||||
case <-c.doneChan:
|
||||
c.ackMutex.Lock()
|
||||
delete(c.ackChanMap, id)
|
||||
c.ackMutex.Unlock()
|
||||
slog.Error("Client closed while waiting for event Ack", "event", event, "ackID", id)
|
||||
return "", fmt.Errorf("client closed while waiting for event ack: %s", event)
|
||||
}
|
||||
}
|
||||
|
||||
// Close shuts down the polling loop.
|
||||
func (c *SocketIOClient) Close() {
|
||||
c.closeOnce.Do(func() {
|
||||
c.cancel()
|
||||
close(c.doneChan)
|
||||
})
|
||||
}
|
||||
|
||||
// GetMonitorListChan returns a channel closed when the first monitorList event arrives.
|
||||
func (c *SocketIOClient) GetMonitorListChan() <-chan struct{} {
|
||||
return c.monitorListChan
|
||||
}
|
||||
|
||||
// GetMonitorList returns a copy of the current monitor list.
|
||||
func (c *SocketIOClient) GetMonitorList() map[string]Monitor {
|
||||
c.monitorListMutex.RLock()
|
||||
defer c.monitorListMutex.RUnlock()
|
||||
|
||||
m := make(map[string]Monitor, len(c.monitorList))
|
||||
maps.Copy(m, c.monitorList)
|
||||
return m
|
||||
}
|
||||
|
||||
// ParseAckResponse unmarshals an ack payload and validates the ok status when present.
|
||||
func ParseAckResponse(response string, target any) error {
|
||||
var arr []json.RawMessage
|
||||
if err := json.Unmarshal([]byte(response), &arr); err != nil || len(arr) == 0 {
|
||||
return fmt.Errorf("invalid ack response format: %s", response)
|
||||
}
|
||||
|
||||
var status struct {
|
||||
Ok bool `json:"ok"`
|
||||
Msg string `json:"msg"`
|
||||
}
|
||||
if err := json.Unmarshal(arr[0], &status); err == nil {
|
||||
if !status.Ok {
|
||||
errMsg := status.Msg
|
||||
if errMsg == "" {
|
||||
errMsg = "unknown error from Uptime Kuma"
|
||||
}
|
||||
return fmt.Errorf("uptime Kuma error response: %s", errMsg)
|
||||
}
|
||||
}
|
||||
|
||||
if target != nil {
|
||||
return json.Unmarshal(arr[0], target)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package uptimekuma
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
|
||||
"Wavelet/openflare/plugins/server/kernel/model"
|
||||
"Wavelet/openflare/plugins/server/kernel/repository"
|
||||
)
|
||||
|
||||
const uptimeKumaTagOpenFlare = "OpenFlare"
|
||||
|
||||
var isSyncing atomic.Bool
|
||||
|
||||
// kumaConfig 封装 UptimeKuma 配置
|
||||
type kumaConfig struct {
|
||||
URL string
|
||||
Username string
|
||||
Password string
|
||||
MonitorScope string
|
||||
SelectedSites string
|
||||
Interval int
|
||||
Retry int
|
||||
RetryInterval int
|
||||
Timeout int
|
||||
}
|
||||
|
||||
// loadKumaConfig 从 SystemConfig 加载 UptimeKuma 配置
|
||||
func loadKumaConfig(ctx context.Context) *kumaConfig {
|
||||
url, _ := repository.GetSystemConfigByKey(ctx, model.ConfigKeyUptimeKumaURL)
|
||||
username, _ := repository.GetSystemConfigByKey(ctx, model.ConfigKeyUptimeKumaUsername)
|
||||
password, _ := repository.GetSystemConfigByKey(ctx, model.ConfigKeyUptimeKumaPassword)
|
||||
scope, _ := repository.GetSystemConfigByKey(ctx, model.ConfigKeyUptimeKumaMonitorScope)
|
||||
selected, _ := repository.GetSystemConfigByKey(ctx, model.ConfigKeyUptimeKumaSelectedSites)
|
||||
|
||||
interval, _ := repository.GetIntByKey(ctx, model.ConfigKeyUptimeKumaInterval)
|
||||
if interval <= 0 {
|
||||
interval = 60
|
||||
}
|
||||
retry, _ := repository.GetIntByKey(ctx, model.ConfigKeyUptimeKumaRetry)
|
||||
retryInterval, _ := repository.GetIntByKey(ctx, model.ConfigKeyUptimeKumaRetryInterval)
|
||||
if retryInterval <= 0 {
|
||||
retryInterval = 60
|
||||
}
|
||||
timeout, _ := repository.GetIntByKey(ctx, model.ConfigKeyUptimeKumaTimeout)
|
||||
if timeout <= 0 {
|
||||
timeout = 48
|
||||
}
|
||||
|
||||
if scope.Value == "" {
|
||||
scope.Value = "all"
|
||||
}
|
||||
|
||||
return &kumaConfig{
|
||||
URL: strings.TrimSpace(url.Value),
|
||||
Username: strings.TrimSpace(username.Value),
|
||||
Password: strings.TrimSpace(password.Value),
|
||||
MonitorScope: scope.Value,
|
||||
SelectedSites: selected.Value,
|
||||
Interval: interval,
|
||||
Retry: retry,
|
||||
RetryInterval: retryInterval,
|
||||
Timeout: timeout,
|
||||
}
|
||||
}
|
||||
|
||||
// SyncToUptimeKuma synchronizes enabled proxy routes to Uptime Kuma monitors.
|
||||
func SyncToUptimeKuma(ctx context.Context) error {
|
||||
// 检查是否启用
|
||||
enabled, _ := repository.GetBoolByKey(ctx, model.ConfigKeyUptimeKumaEnabled)
|
||||
if !enabled {
|
||||
return errors.New("uptime Kuma integration is disabled")
|
||||
}
|
||||
|
||||
if !isSyncing.CompareAndSwap(false, true) {
|
||||
return errors.New("sync task is already in progress, please try again later")
|
||||
}
|
||||
defer isSyncing.Store(false)
|
||||
|
||||
// 加载配置
|
||||
config := loadKumaConfig(ctx)
|
||||
|
||||
// 验证配置
|
||||
if err := validateKumaConfig(config); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
slog.Info("Starting Uptime Kuma sync process",
|
||||
"url", config.URL,
|
||||
"username", config.Username,
|
||||
"scope", config.MonitorScope,
|
||||
)
|
||||
|
||||
allRoutes, err := repository.ListProxyRoutes(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to list local proxy routes: %w", err)
|
||||
}
|
||||
|
||||
expectedRoutes := filterExpectedRoutes(allRoutes, config)
|
||||
|
||||
client, err := connectAndLoginUptimeKuma(config.URL, config.Username, config.Password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
openFlareTagID, err := ensureOpenFlareTag(client)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
existingOpenFlareMonitors := filterOpenFlareMonitors(client.GetMonitorList(), openFlareTagID)
|
||||
expectedSitesMap := syncRouteMonitors(ctx, client, expectedRoutes, existingOpenFlareMonitors, openFlareTagID, config)
|
||||
removeStaleMonitors(client, existingOpenFlareMonitors, expectedSitesMap)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func filterExpectedRoutes(allRoutes []*model.ProxyRoute, config *kumaConfig) []*model.ProxyRoute {
|
||||
scope := config.MonitorScope
|
||||
if scope == "selected" {
|
||||
selectedList := strings.Split(config.SelectedSites, ",")
|
||||
selectedMap := make(map[string]bool)
|
||||
for _, name := range selectedList {
|
||||
trimmedName := strings.TrimSpace(name)
|
||||
if trimmedName != "" {
|
||||
selectedMap[trimmedName] = true
|
||||
}
|
||||
}
|
||||
var expectedRoutes []*model.ProxyRoute
|
||||
for _, route := range allRoutes {
|
||||
if route.Enabled && selectedMap[route.SiteName] {
|
||||
expectedRoutes = append(expectedRoutes, route)
|
||||
}
|
||||
}
|
||||
return expectedRoutes
|
||||
}
|
||||
|
||||
var expectedRoutes []*model.ProxyRoute
|
||||
for _, route := range allRoutes {
|
||||
if route.Enabled {
|
||||
expectedRoutes = append(expectedRoutes, route)
|
||||
}
|
||||
}
|
||||
return expectedRoutes
|
||||
}
|
||||
|
||||
func ensureOpenFlareTag(client *SocketIOClient) (int, error) {
|
||||
slog.Debug("Fetching tags from Uptime Kuma")
|
||||
tagsAck, err := client.Emit("getTags")
|
||||
if err != nil {
|
||||
slog.Error("Failed to request tags from Uptime Kuma", "error", err)
|
||||
return 0, fmt.Errorf("failed to fetch tags: %w", err)
|
||||
}
|
||||
|
||||
var tagsResult struct {
|
||||
Ok bool `json:"ok"`
|
||||
Tags []TagItem `json:"tags"`
|
||||
}
|
||||
if err := ParseAckResponse(tagsAck, &tagsResult); err != nil {
|
||||
slog.Error("Failed to parse tags response from Uptime Kuma", "error", err)
|
||||
return 0, fmt.Errorf("parse tags response failed: %w", err)
|
||||
}
|
||||
|
||||
for _, tag := range tagsResult.Tags {
|
||||
if tag.Name == uptimeKumaTagOpenFlare {
|
||||
slog.Debug("Found existing OpenFlare tag", "tag_id", tag.ID)
|
||||
return tag.ID, nil
|
||||
}
|
||||
}
|
||||
|
||||
slog.Debug("OpenFlare tag not found, creating new tag")
|
||||
addTagAck, err := client.Emit("addTag", map[string]string{
|
||||
"name": uptimeKumaTagOpenFlare,
|
||||
"color": "#4f46e5",
|
||||
})
|
||||
if err != nil {
|
||||
slog.Error("Failed to create OpenFlare tag in Uptime Kuma", "error", err)
|
||||
return 0, fmt.Errorf("failed to create tag: %w", err)
|
||||
}
|
||||
|
||||
var tagResult struct {
|
||||
Ok bool `json:"ok"`
|
||||
Tag struct {
|
||||
ID int `json:"id"`
|
||||
} `json:"tag"`
|
||||
}
|
||||
if err := ParseAckResponse(addTagAck, &tagResult); err != nil || tagResult.Tag.ID == 0 {
|
||||
slog.Error("Failed to parse addTag response from Uptime Kuma", "error", err)
|
||||
return 0, fmt.Errorf("parse addTag response failed: %w", err)
|
||||
}
|
||||
|
||||
slog.Debug("Successfully created OpenFlare tag", "tag_id", tagResult.Tag.ID)
|
||||
return tagResult.Tag.ID, nil
|
||||
}
|
||||
|
||||
func filterOpenFlareMonitors(monitors map[string]Monitor, openFlareTagID int) map[string]Monitor {
|
||||
existingOpenFlareMonitors := make(map[string]Monitor)
|
||||
for _, monitor := range monitors {
|
||||
hasOpenFlareTag := false
|
||||
for _, tag := range monitor.Tags {
|
||||
if tag.Name == uptimeKumaTagOpenFlare || tag.ID == openFlareTagID {
|
||||
hasOpenFlareTag = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if hasOpenFlareTag {
|
||||
existingOpenFlareMonitors[monitor.Name] = monitor
|
||||
}
|
||||
}
|
||||
return existingOpenFlareMonitors
|
||||
}
|
||||
|
||||
func routeMonitorURL(ctx context.Context, route *model.ProxyRoute) (string, error) {
|
||||
if route == nil {
|
||||
return "", errors.New("proxy route is nil")
|
||||
}
|
||||
domains, err := repository.ListZoneDomainsByRouteID(ctx, route.ID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(domains) == 0 {
|
||||
return "", fmt.Errorf("route %s has no zone domains", route.SiteName)
|
||||
}
|
||||
domain := domains[0].Domain
|
||||
if route.EnableHTTPS {
|
||||
return "https://" + domain, nil
|
||||
}
|
||||
return "http://" + domain, nil
|
||||
}
|
||||
|
||||
func monitorPayload(id int, name, targetURL string, config *kumaConfig) map[string]any {
|
||||
payload := map[string]any{
|
||||
"type": "http",
|
||||
"name": name,
|
||||
"url": targetURL,
|
||||
"interval": config.Interval,
|
||||
"maxretries": config.Retry,
|
||||
"retryInterval": config.RetryInterval,
|
||||
"timeout": config.Timeout,
|
||||
"active": true,
|
||||
"resendInterval": 0,
|
||||
"expiryNotification": false,
|
||||
"ignoreTls": false,
|
||||
"accepted_statuscodes": []string{"200-299"},
|
||||
"dns_resolve_type": "A",
|
||||
"conditions": []any{},
|
||||
}
|
||||
if id > 0 {
|
||||
payload["id"] = id
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
func monitorNeedsUpdate(existing Monitor, targetURL string, config *kumaConfig) bool {
|
||||
return existing.URL != targetURL ||
|
||||
existing.Interval != config.Interval ||
|
||||
existing.MaxRetries != config.Retry ||
|
||||
existing.RetryInterval != config.RetryInterval ||
|
||||
existing.Timeout != config.Timeout
|
||||
}
|
||||
|
||||
func createMonitor(client *SocketIOClient, siteName, targetURL string, openFlareTagID int, config *kumaConfig) error {
|
||||
slog.Info("Creating monitor in Uptime Kuma", "name", siteName, "url", targetURL)
|
||||
addAck, err := client.Emit("add", monitorPayload(0, siteName, targetURL, config))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var addResult struct {
|
||||
Ok bool `json:"ok"`
|
||||
MonitorID int `json:"monitorID"`
|
||||
}
|
||||
if err := ParseAckResponse(addAck, &addResult); err != nil || addResult.MonitorID == 0 {
|
||||
return fmt.Errorf("parse add monitor result failed: %w", err)
|
||||
}
|
||||
|
||||
slog.Debug("Adding OpenFlare tag to the new monitor",
|
||||
"name", siteName,
|
||||
"monitor_id", addResult.MonitorID,
|
||||
"tag_id", openFlareTagID,
|
||||
)
|
||||
tagAck, err := client.Emit("addMonitorTag", openFlareTagID, addResult.MonitorID, "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ParseAckResponse(tagAck, nil); err != nil {
|
||||
return fmt.Errorf("parse add tag result failed: %w", err)
|
||||
}
|
||||
|
||||
slog.Debug("OpenFlare tag successfully added to monitor", "name", siteName, "monitor_id", addResult.MonitorID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func updateMonitor(client *SocketIOClient, monitorID int, siteName, targetURL string, config *kumaConfig) error {
|
||||
slog.Info("Updating monitor in Uptime Kuma due to settings mismatch", "name", siteName)
|
||||
editAck, err := client.Emit("editMonitor", monitorPayload(monitorID, siteName, targetURL, config))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ParseAckResponse(editAck, nil); err != nil {
|
||||
return fmt.Errorf("parse edit monitor result failed: %w", err)
|
||||
}
|
||||
slog.Info("Successfully updated monitor in Uptime Kuma", "name", siteName)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package uptimekuma
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"Wavelet/openflare/plugins/server/kernel/model"
|
||||
)
|
||||
|
||||
const monitorListWaitTimeout = 5 * time.Second
|
||||
|
||||
// validateKumaConfig 验证 kumaConfig 配置完整性
|
||||
func validateKumaConfig(config *kumaConfig) error {
|
||||
if strings.TrimSpace(config.URL) == "" {
|
||||
return errors.New("uptime Kuma URL is not configured")
|
||||
}
|
||||
if strings.TrimSpace(config.Username) == "" {
|
||||
return errors.New("uptime Kuma username is not configured")
|
||||
}
|
||||
if strings.TrimSpace(config.Password) == "" {
|
||||
return errors.New("uptime Kuma password is not configured")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func connectAndLoginUptimeKuma(kumaURL, kumaUsername, kumaPassword string) (*SocketIOClient, error) {
|
||||
slog.Debug("Connecting to Uptime Kuma socket endpoint", "url", kumaURL)
|
||||
client := NewSocketIOClient(kumaURL)
|
||||
if err := client.Connect(); err != nil {
|
||||
slog.Error("Failed to connect to Uptime Kuma endpoint", "url", kumaURL, "error", err)
|
||||
return nil, fmt.Errorf("failed to connect to Uptime Kuma: %w", err)
|
||||
}
|
||||
|
||||
slog.Debug("Sending login request to Uptime Kuma", "username", kumaUsername)
|
||||
loginAck, err := client.Emit("login", map[string]string{
|
||||
"username": kumaUsername,
|
||||
"password": kumaPassword,
|
||||
})
|
||||
if err != nil {
|
||||
client.Close()
|
||||
slog.Error("Failed to send login request to Uptime Kuma", "username", kumaUsername, "error", err)
|
||||
return nil, fmt.Errorf("login request failed: %w", err)
|
||||
}
|
||||
|
||||
var loginResult struct {
|
||||
Ok bool `json:"ok"`
|
||||
}
|
||||
if err := ParseAckResponse(loginAck, &loginResult); err != nil || !loginResult.Ok {
|
||||
client.Close()
|
||||
slog.Error("Uptime Kuma login verification failed", "username", kumaUsername, "error", err)
|
||||
return nil, fmt.Errorf("login failed: %w", err)
|
||||
}
|
||||
slog.Debug("Successfully logged into Uptime Kuma", "username", kumaUsername)
|
||||
|
||||
slog.Debug("Waiting for monitor list push from Uptime Kuma")
|
||||
select {
|
||||
case <-client.GetMonitorListChan():
|
||||
slog.Debug("Received monitor list from Uptime Kuma")
|
||||
case <-time.After(monitorListWaitTimeout):
|
||||
client.Close()
|
||||
slog.Error("Timeout waiting for Uptime Kuma monitorList push event")
|
||||
return nil, errors.New("timeout waiting for monitorList event from Uptime Kuma")
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func syncRouteMonitors(ctx context.Context, client *SocketIOClient, expectedRoutes []*model.ProxyRoute, existingMonitors map[string]Monitor, openFlareTagID int, config *kumaConfig) map[string]bool {
|
||||
expectedSitesMap := make(map[string]bool, len(expectedRoutes))
|
||||
for _, route := range expectedRoutes {
|
||||
expectedSitesMap[route.SiteName] = true
|
||||
targetURL, urlErr := routeMonitorURL(ctx, route)
|
||||
if urlErr != nil {
|
||||
slog.Error("Failed to resolve monitor URL", "name", route.SiteName, "error", urlErr)
|
||||
continue
|
||||
}
|
||||
|
||||
existing, exists := existingMonitors[route.SiteName]
|
||||
if !exists {
|
||||
if err := createMonitor(client, route.SiteName, targetURL, openFlareTagID, config); err != nil {
|
||||
slog.Error("Failed to add monitor to Uptime Kuma", "name", route.SiteName, "error", err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if monitorNeedsUpdate(existing, targetURL, config) {
|
||||
if err := updateMonitor(client, existing.ID, route.SiteName, targetURL, config); err != nil {
|
||||
slog.Error("Failed to edit monitor in Uptime Kuma", "name", route.SiteName, "error", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return expectedSitesMap
|
||||
}
|
||||
|
||||
func removeStaleMonitors(client *SocketIOClient, existingMonitors map[string]Monitor, expectedSitesMap map[string]bool) {
|
||||
for name, monitor := range existingMonitors {
|
||||
if expectedSitesMap[name] {
|
||||
continue
|
||||
}
|
||||
slog.Info("Deleting monitor in Uptime Kuma", "name", name, "monitorID", monitor.ID)
|
||||
deleteAck, err := client.Emit("deleteMonitor", monitor.ID)
|
||||
if err != nil {
|
||||
slog.Error("Failed to delete monitor in Uptime Kuma", "name", name, "monitorID", monitor.ID, "error", err)
|
||||
continue
|
||||
}
|
||||
if err := ParseAckResponse(deleteAck, nil); err != nil {
|
||||
slog.Error("Failed to parse delete monitor result", "name", name, "monitorID", monitor.ID, "error", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package uptimekuma
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"Wavelet/openflare/plugins/server/kernel/model"
|
||||
"Wavelet/openflare/plugins/server/kernel/repository"
|
||||
db "Wavelet/plugins/infra/database"
|
||||
|
||||
"github.com/glebarez/sqlite"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type mockKumaServer struct {
|
||||
mu sync.Mutex
|
||||
postsReceived []string
|
||||
pendingPackets chan string
|
||||
monitorList string
|
||||
}
|
||||
|
||||
func newMockKumaServer(monitorList string) *mockKumaServer {
|
||||
return &mockKumaServer{
|
||||
pendingPackets: make(chan string, 100),
|
||||
monitorList: monitorList,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *mockKumaServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
transport := r.URL.Query().Get("transport")
|
||||
sid := r.URL.Query().Get("sid")
|
||||
|
||||
if r.Method == http.MethodGet {
|
||||
if transport == "polling" && sid == "" {
|
||||
w.Header().Set("Content-Type", "text/plain;charset=UTF-8")
|
||||
_, _ = w.Write([]byte(`0{"sid":"mock-sid"}`))
|
||||
return
|
||||
}
|
||||
|
||||
if transport == "polling" && sid == "mock-sid" {
|
||||
w.Header().Set("Content-Type", "text/plain;charset=UTF-8")
|
||||
select {
|
||||
case pkt := <-s.pendingPackets:
|
||||
_, _ = w.Write([]byte(pkt))
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
_, _ = w.Write([]byte(""))
|
||||
}
|
||||
return
|
||||
}
|
||||
} else if r.Method == http.MethodPost {
|
||||
bodyBytes, _ := io.ReadAll(r.Body)
|
||||
bodyStr := string(bodyBytes)
|
||||
s.postsReceived = append(s.postsReceived, bodyStr)
|
||||
|
||||
w.Header().Set("Content-Type", "text/plain;charset=UTF-8")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
if bodyStr == "40" {
|
||||
s.pendingPackets <- fmt.Sprintf(`42["monitorList",%s]`, s.monitorList)
|
||||
return
|
||||
}
|
||||
|
||||
if strings.HasPrefix(bodyStr, "42") {
|
||||
payload := bodyStr[2:]
|
||||
digitsEnd := 0
|
||||
for digitsEnd < len(payload) && payload[digitsEnd] >= '0' && payload[digitsEnd] <= '9' {
|
||||
digitsEnd++
|
||||
}
|
||||
if digitsEnd == 0 {
|
||||
return
|
||||
}
|
||||
ackIDStr := payload[:digitsEnd]
|
||||
jsonArrayStr := payload[digitsEnd:]
|
||||
|
||||
var arr []json.RawMessage
|
||||
if err := json.Unmarshal([]byte(jsonArrayStr), &arr); err != nil || len(arr) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
var eventName string
|
||||
_ = json.Unmarshal(arr[0], &eventName)
|
||||
|
||||
switch eventName {
|
||||
case "login", "loginByToken":
|
||||
s.pendingPackets <- fmt.Sprintf("43%s[{\"ok\":true}]", ackIDStr)
|
||||
case "getTags":
|
||||
s.pendingPackets <- fmt.Sprintf("43%s[{\"ok\":true,\"tags\":[{\"id\":10,\"name\":\"OpenFlare\",\"color\":\"#4f46e5\"}]}]", ackIDStr)
|
||||
case "addTag":
|
||||
s.pendingPackets <- fmt.Sprintf("43%s[{\"ok\":true,\"tag\":{\"id\":10}}]", ackIDStr)
|
||||
case "add":
|
||||
s.pendingPackets <- fmt.Sprintf("43%s[{\"ok\":true,\"monitorID\":100}]", ackIDStr)
|
||||
case "addMonitorTag":
|
||||
s.pendingPackets <- fmt.Sprintf("43%s[{\"ok\":true}]", ackIDStr)
|
||||
case "editMonitor":
|
||||
s.pendingPackets <- fmt.Sprintf("43%s[{\"ok\":true}]", ackIDStr)
|
||||
case "deleteMonitor":
|
||||
s.pendingPackets <- fmt.Sprintf("43%s[{\"ok\":true}]", ackIDStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func setupSyncTestDB(t *testing.T) func() {
|
||||
t.Helper()
|
||||
|
||||
sqliteDB, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{
|
||||
DisableForeignKeyConstraintWhenMigrating: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, sqliteDB.AutoMigrate(&model.ProxyRoute{}, &model.Zone{}, &model.ZoneDomain{}, &model.SystemConfig{}))
|
||||
|
||||
db.SetDB(sqliteDB)
|
||||
return func() {
|
||||
db.SetDB(nil)
|
||||
}
|
||||
}
|
||||
|
||||
func createRouteZoneDomain(t *testing.T, ctx context.Context, route *model.ProxyRoute, domain string) {
|
||||
t.Helper()
|
||||
zone := &model.Zone{Domain: fmt.Sprintf("zone-%d.example", route.ID)}
|
||||
require.NoError(t, db.DB(ctx).Create(zone).Error)
|
||||
require.NoError(t, db.DB(ctx).Create(&model.ZoneDomain{
|
||||
ZoneID: zone.ID,
|
||||
ProxyRouteID: &route.ID,
|
||||
Domain: domain,
|
||||
}).Error)
|
||||
}
|
||||
|
||||
func backupUptimeKumaConfig(ctx context.Context) func() {
|
||||
// 备份所有 UptimeKuma 相关配置
|
||||
configs := []string{
|
||||
model.ConfigKeyUptimeKumaEnabled,
|
||||
model.ConfigKeyUptimeKumaURL,
|
||||
model.ConfigKeyUptimeKumaUsername,
|
||||
model.ConfigKeyUptimeKumaPassword,
|
||||
model.ConfigKeyUptimeKumaMonitorScope,
|
||||
model.ConfigKeyUptimeKumaSelectedSites,
|
||||
model.ConfigKeyUptimeKumaInterval,
|
||||
model.ConfigKeyUptimeKumaRetry,
|
||||
model.ConfigKeyUptimeKumaRetryInterval,
|
||||
model.ConfigKeyUptimeKumaTimeout,
|
||||
}
|
||||
|
||||
oldValues := make(map[string]string)
|
||||
for _, key := range configs {
|
||||
config, _ := repository.GetSystemConfigByKey(ctx, key)
|
||||
oldValues[key] = config.Value
|
||||
}
|
||||
|
||||
return func() {
|
||||
// 恢复所有配置
|
||||
for key, value := range oldValues {
|
||||
_ = db.DB(ctx).Model(&model.SystemConfig{}).Where("key = ?", key).Update("value", value).Error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// setTestConfig 设置测试配置的辅助函数(不存在则创建)
|
||||
func setTestConfig(ctx context.Context, key, value string) {
|
||||
_ = repository.SaveOrUpdateSystemConfig(ctx, key, value)
|
||||
}
|
||||
|
||||
func TestSyncToUptimeKumaDisabled(t *testing.T) {
|
||||
cleanup := setupSyncTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
restore := backupUptimeKumaConfig(ctx)
|
||||
defer restore()
|
||||
|
||||
setTestConfig(ctx, model.ConfigKeyUptimeKumaEnabled, "false")
|
||||
|
||||
err := SyncToUptimeKuma(ctx)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "disabled")
|
||||
}
|
||||
|
||||
func TestSyncToUptimeKumaSuccess(t *testing.T) {
|
||||
cleanup := setupSyncTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
restore := backupUptimeKumaConfig(ctx)
|
||||
defer restore()
|
||||
|
||||
require.NoError(t, db.DB(ctx).Where("1 = 1").Delete(&model.ProxyRoute{}).Error)
|
||||
|
||||
routeA := &model.ProxyRoute{
|
||||
SiteName: "site-a",
|
||||
OriginURL: "http://10.0.0.1",
|
||||
Enabled: true,
|
||||
EnableHTTPS: false,
|
||||
}
|
||||
routeB := &model.ProxyRoute{
|
||||
SiteName: "site-b",
|
||||
OriginURL: "https://10.0.0.2",
|
||||
Enabled: true,
|
||||
EnableHTTPS: true,
|
||||
}
|
||||
routeC := &model.ProxyRoute{
|
||||
SiteName: "site-c",
|
||||
OriginURL: "http://10.0.0.3",
|
||||
Enabled: false,
|
||||
EnableHTTPS: false,
|
||||
}
|
||||
|
||||
require.NoError(t, repository.CreateProxyRouteRecord(ctx, routeA))
|
||||
require.NoError(t, repository.CreateProxyRouteRecord(ctx, routeB))
|
||||
require.NoError(t, repository.CreateProxyRouteRecord(ctx, routeC))
|
||||
createRouteZoneDomain(t, ctx, routeA, "site-a.com")
|
||||
createRouteZoneDomain(t, ctx, routeB, "site-b.com")
|
||||
createRouteZoneDomain(t, ctx, routeC, "site-c.com")
|
||||
|
||||
monitorListJSON := `{
|
||||
"99": {
|
||||
"id": 99,
|
||||
"name": "site-old",
|
||||
"url": "http://site-old.com",
|
||||
"interval": 60,
|
||||
"tags": [{"tag_id": 10, "name": "OpenFlare"}]
|
||||
},
|
||||
"98": {
|
||||
"id": 98,
|
||||
"name": "site-a",
|
||||
"url": "http://site-a.com",
|
||||
"interval": 30,
|
||||
"tags": [{"tag_id": 10, "name": "OpenFlare"}]
|
||||
}
|
||||
}`
|
||||
|
||||
mockSrv := newMockKumaServer(monitorListJSON)
|
||||
server := httptest.NewServer(mockSrv)
|
||||
defer server.Close()
|
||||
|
||||
// 设置测试配置
|
||||
setTestConfig(ctx, model.ConfigKeyUptimeKumaEnabled, "true")
|
||||
setTestConfig(ctx, model.ConfigKeyUptimeKumaURL, server.URL)
|
||||
setTestConfig(ctx, model.ConfigKeyUptimeKumaUsername, "admin")
|
||||
setTestConfig(ctx, model.ConfigKeyUptimeKumaPassword, "password")
|
||||
setTestConfig(ctx, model.ConfigKeyUptimeKumaMonitorScope, "all")
|
||||
setTestConfig(ctx, model.ConfigKeyUptimeKumaInterval, "60")
|
||||
setTestConfig(ctx, model.ConfigKeyUptimeKumaRetry, "0")
|
||||
setTestConfig(ctx, model.ConfigKeyUptimeKumaRetryInterval, "60")
|
||||
setTestConfig(ctx, model.ConfigKeyUptimeKumaTimeout, "48")
|
||||
|
||||
require.NoError(t, SyncToUptimeKuma(ctx))
|
||||
|
||||
mockSrv.mu.Lock()
|
||||
posts := mockSrv.postsReceived
|
||||
mockSrv.mu.Unlock()
|
||||
|
||||
hasLogin := false
|
||||
hasGetTags := false
|
||||
hasAddSiteB := false
|
||||
hasTagSiteB := false
|
||||
hasEditSiteA := false
|
||||
hasDeleteOld := false
|
||||
|
||||
for _, body := range posts {
|
||||
if strings.Contains(body, `"login"`) && strings.Contains(body, `"admin"`) && strings.Contains(body, `"password"`) {
|
||||
hasLogin = true
|
||||
}
|
||||
if strings.Contains(body, `"getTags"`) {
|
||||
hasGetTags = true
|
||||
}
|
||||
if strings.Contains(body, `"add"`) && strings.Contains(body, `"site-b"`) && strings.Contains(body, `"https://site-b.com"`) {
|
||||
hasAddSiteB = true
|
||||
}
|
||||
if strings.Contains(body, `"addMonitorTag"`) && strings.Contains(body, `10`) && strings.Contains(body, `100`) {
|
||||
hasTagSiteB = true
|
||||
}
|
||||
if strings.Contains(body, `"editMonitor"`) && strings.Contains(body, `98`) && strings.Contains(body, `"site-a"`) && strings.Contains(body, `"interval":60`) {
|
||||
hasEditSiteA = true
|
||||
}
|
||||
if strings.Contains(body, `"deleteMonitor"`) && strings.Contains(body, `99`) {
|
||||
hasDeleteOld = true
|
||||
}
|
||||
}
|
||||
|
||||
assert.True(t, hasLogin, "expected login event to be called")
|
||||
assert.True(t, hasGetTags, "expected getTags event to be called")
|
||||
assert.True(t, hasAddSiteB, "expected site-b to be added")
|
||||
assert.True(t, hasTagSiteB, "expected site-b to be tagged")
|
||||
assert.True(t, hasEditSiteA, "expected site-a to be edited/updated")
|
||||
assert.True(t, hasDeleteOld, "expected site-old to be deleted")
|
||||
}
|
||||
|
||||
func TestSyncToUptimeKumaSelectedScope(t *testing.T) {
|
||||
cleanup := setupSyncTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
restore := backupUptimeKumaConfig(ctx)
|
||||
defer restore()
|
||||
|
||||
require.NoError(t, db.DB(ctx).Where("1 = 1").Delete(&model.ProxyRoute{}).Error)
|
||||
|
||||
routeA := &model.ProxyRoute{
|
||||
SiteName: "site-a",
|
||||
OriginURL: "http://10.0.0.1",
|
||||
Enabled: true,
|
||||
EnableHTTPS: false,
|
||||
}
|
||||
routeB := &model.ProxyRoute{
|
||||
SiteName: "site-b",
|
||||
OriginURL: "http://10.0.0.2",
|
||||
Enabled: true,
|
||||
EnableHTTPS: false,
|
||||
}
|
||||
|
||||
require.NoError(t, repository.CreateProxyRouteRecord(ctx, routeA))
|
||||
require.NoError(t, repository.CreateProxyRouteRecord(ctx, routeB))
|
||||
createRouteZoneDomain(t, ctx, routeA, "site-a.com")
|
||||
createRouteZoneDomain(t, ctx, routeB, "site-b.com")
|
||||
|
||||
mockSrv := newMockKumaServer(`{}`)
|
||||
server := httptest.NewServer(mockSrv)
|
||||
defer server.Close()
|
||||
|
||||
// 设置测试配置
|
||||
setTestConfig(ctx, model.ConfigKeyUptimeKumaEnabled, "true")
|
||||
setTestConfig(ctx, model.ConfigKeyUptimeKumaURL, server.URL)
|
||||
setTestConfig(ctx, model.ConfigKeyUptimeKumaUsername, "admin")
|
||||
setTestConfig(ctx, model.ConfigKeyUptimeKumaPassword, "password")
|
||||
setTestConfig(ctx, model.ConfigKeyUptimeKumaMonitorScope, "selected")
|
||||
setTestConfig(ctx, model.ConfigKeyUptimeKumaSelectedSites, "site-a")
|
||||
|
||||
require.NoError(t, SyncToUptimeKuma(ctx))
|
||||
|
||||
mockSrv.mu.Lock()
|
||||
posts := mockSrv.postsReceived
|
||||
mockSrv.mu.Unlock()
|
||||
|
||||
hasLogin := false
|
||||
hasAddSiteA := false
|
||||
hasAddSiteB := false
|
||||
|
||||
for _, body := range posts {
|
||||
if strings.Contains(body, `"login"`) && strings.Contains(body, `"admin"`) && strings.Contains(body, `"password"`) {
|
||||
hasLogin = true
|
||||
}
|
||||
if strings.Contains(body, `"add"`) && strings.Contains(body, `"site-a"`) {
|
||||
hasAddSiteA = true
|
||||
}
|
||||
if strings.Contains(body, `"add"`) && strings.Contains(body, `"site-b"`) {
|
||||
hasAddSiteB = true
|
||||
}
|
||||
}
|
||||
|
||||
assert.True(t, hasLogin, "expected login event to be called")
|
||||
assert.True(t, hasAddSiteA, "expected site-a to be added")
|
||||
assert.False(t, hasAddSiteB, "expected site-b NOT to be added (not in selected scope)")
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package option
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"Wavelet/openflare/plugins/server/kernel/geoip"
|
||||
"Wavelet/openflare/plugins/server/kernel/model"
|
||||
"Wavelet/openflare/plugins/server/kernel/repository"
|
||||
)
|
||||
|
||||
const maxOpenRestyGzipCompLevel = 9
|
||||
|
||||
var (
|
||||
openRestySizePattern = regexp.MustCompile(`^\d+[kKmMgG]?$`)
|
||||
openRestyProxyBuffersPattern = regexp.MustCompile(`^\d+\s+\d+[kKmMgG]?$`)
|
||||
openRestyCacheLevelsPattern = regexp.MustCompile(`^\d{1,2}(?::\d{1,2}){0,2}$`)
|
||||
openRestyDurationTokenPattern = regexp.MustCompile(`^\d+[smhdwSMHDW]$`)
|
||||
)
|
||||
|
||||
const optionValueTrue = "true"
|
||||
|
||||
// protectedConfigKeyMessage 命中受保护 key 时返回给管理员的业务错误文案。
|
||||
const protectedConfigKeyMessage = "该配置项由系统任务管理,禁止手动修改"
|
||||
|
||||
// protectedConfigKeys 仅允许内部(迁移任务/bootstrap)写入的 key。
|
||||
var protectedConfigKeys = map[string]bool{
|
||||
model.ConfigKeyLogDatabase: true,
|
||||
model.ConfigKeyLogDBMigration: true,
|
||||
}
|
||||
|
||||
func isProtectedConfigKey(key string) bool { return protectedConfigKeys[key] }
|
||||
|
||||
func buildOptionValidationState(ctx context.Context, options []model.OpenFlareOption) map[string]string {
|
||||
// 从 SystemConfig 读取所有业务配置构建状态
|
||||
configs, err := repository.ListAdminSystemConfigs(ctx, "business")
|
||||
state := make(map[string]string, len(configs)+len(options))
|
||||
|
||||
if err == nil {
|
||||
for _, config := range configs {
|
||||
state[config.Key] = config.Value
|
||||
}
|
||||
}
|
||||
|
||||
// 应用待验证的新值
|
||||
for _, option := range options {
|
||||
state[option.Key] = option.Value
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
func validateOptionWithState(ctx context.Context, option model.OpenFlareOption, state map[string]string) error {
|
||||
|
||||
if err := validateOpenRestyOption(option.Key, option.Value); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateGeoIPOption(option.Key, option.Value); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateLogRetentionOption(option.Key, option.Value); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateAgentOption(option.Key, option.Value); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validatePagesOption(option.Key, option.Value); err != nil {
|
||||
return err
|
||||
}
|
||||
return validateUptimeKumaOption(ctx, option.Key, option.Value, state)
|
||||
}
|
||||
|
||||
func validatePositiveIntegerOption(key, value string) error {
|
||||
intValue, err := strconv.Atoi(value)
|
||||
if err != nil || intValue <= 0 {
|
||||
return fmt.Errorf("%s 必须为大于 0 的整数", key)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateNonNegativeIntegerOption(key, value string) error {
|
||||
intValue, err := strconv.Atoi(value)
|
||||
if err != nil || intValue < 0 {
|
||||
return fmt.Errorf("%s 必须为大于等于 0 的整数", key)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateBooleanOption(key, value string) error {
|
||||
switch value {
|
||||
case optionValueTrue, "false":
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("%s 必须为 true 或 false", key)
|
||||
}
|
||||
}
|
||||
|
||||
func validateGeoIPOption(key, value string) error {
|
||||
if key != model.ConfigKeyGeoIPProvider {
|
||||
return nil
|
||||
}
|
||||
if geoip.IsValidProvider(value) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("%s 仅支持 disabled、mmdb、ip-api、geojs、ipinfo", key)
|
||||
}
|
||||
|
||||
func validateLogRetentionOption(key, value string) error {
|
||||
switch key {
|
||||
case model.ConfigKeyLogRetentionDaysPostgres, model.ConfigKeyLogRetentionDaysSQLite, model.ConfigKeyLogRetentionDaysClickHouse:
|
||||
intValue, err := strconv.Atoi(value)
|
||||
if err != nil || intValue < 1 {
|
||||
return fmt.Errorf("%s 必须为大于等于 1 的整数天", key)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateAgentOption(key, value string) error {
|
||||
if key == model.ConfigKeyAgentWebsocketUpgradeEnabled {
|
||||
return validateBooleanOption(key, strings.TrimSpace(value))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validatePagesOption(key, value string) error {
|
||||
trimmed := strings.TrimSpace(value)
|
||||
switch key {
|
||||
case model.ConfigKeyPagesMaxPackageSizeMB:
|
||||
intValue, err := strconv.Atoi(trimmed)
|
||||
if err != nil || intValue < 1 || intValue > 2048 {
|
||||
return fmt.Errorf("%s 必须为 1~2048 的整数(MiB)", key)
|
||||
}
|
||||
case model.ConfigKeyPagesMaxHistoryCount:
|
||||
intValue, err := strconv.Atoi(trimmed)
|
||||
if err != nil || intValue < 0 {
|
||||
return fmt.Errorf("%s 必须为大于等于 0 的整数(0 表示不限制)", key)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateUptimeKumaOption(ctx context.Context, key, value string, state map[string]string) error {
|
||||
trimmed := strings.TrimSpace(value)
|
||||
switch key {
|
||||
case model.ConfigKeyUptimeKumaEnabled:
|
||||
return validateUptimeKumaEnabled(ctx, key, trimmed, state)
|
||||
case model.ConfigKeyUptimeKumaUsername:
|
||||
return validateUptimeKumaUsername(trimmed, state)
|
||||
case model.ConfigKeyUptimeKumaURL:
|
||||
return validateUptimeKumaURL(trimmed)
|
||||
case model.ConfigKeyUptimeKumaMonitorScope:
|
||||
return validateUptimeKumaMonitorScope(trimmed)
|
||||
case model.ConfigKeyUptimeKumaSyncInterval, model.ConfigKeyUptimeKumaInterval, model.ConfigKeyUptimeKumaRetryInterval, model.ConfigKeyUptimeKumaTimeout:
|
||||
return validatePositiveIntegerOption(key, trimmed)
|
||||
case model.ConfigKeyUptimeKumaRetry:
|
||||
return validateUptimeKumaRetry(key, trimmed)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateUptimeKumaEnabled(ctx context.Context, key, trimmed string, state map[string]string) error {
|
||||
if err := validateBooleanOption(key, trimmed); err != nil {
|
||||
return err
|
||||
}
|
||||
if trimmed != optionValueTrue {
|
||||
return nil
|
||||
}
|
||||
url := strings.TrimSpace(state[model.ConfigKeyUptimeKumaURL])
|
||||
username := strings.TrimSpace(state[model.ConfigKeyUptimeKumaUsername])
|
||||
password := strings.TrimSpace(state[model.ConfigKeyUptimeKumaPassword])
|
||||
if url == "" {
|
||||
return errors.New("启用 Uptime Kuma 时地址不能为空")
|
||||
}
|
||||
if username == "" {
|
||||
return errors.New("启用 Uptime Kuma 时用户名不能为空")
|
||||
}
|
||||
// 如果待验证的密码为空,且当前配置中也没有密码,则报错
|
||||
if password == "" {
|
||||
existingPwd, _ := repository.GetSystemConfigByKey(ctx, model.ConfigKeyUptimeKumaPassword)
|
||||
if strings.TrimSpace(existingPwd.Value) == "" {
|
||||
return errors.New("启用 Uptime Kuma 时密码不能为空")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateUptimeKumaUsername(trimmed string, state map[string]string) error {
|
||||
if trimmed == "" && state[model.ConfigKeyUptimeKumaEnabled] == optionValueTrue {
|
||||
return errors.New("启用 Uptime Kuma 时用户名不能为空")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateUptimeKumaURL(trimmed string) error {
|
||||
if trimmed != "" && !strings.HasPrefix(trimmed, "http://") && !strings.HasPrefix(trimmed, "https://") {
|
||||
return errors.New("uptime Kuma 地址必须以 http:// 或 https:// 开头")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateUptimeKumaMonitorScope(trimmed string) error {
|
||||
if trimmed != "all" && trimmed != "selected" {
|
||||
return errors.New("监控范围必须为全部站点 (all) 或选择站点 (selected)")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateUptimeKumaRetry(key, trimmed string) error {
|
||||
intValue, err := strconv.Atoi(trimmed)
|
||||
if err != nil || intValue < 0 {
|
||||
return fmt.Errorf("%s 必须为大于等于 0 的整数", key)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateOptions(ctx context.Context, options []model.OpenFlareOption) error {
|
||||
if len(options) == 0 {
|
||||
return errors.New(errInvalidParams)
|
||||
}
|
||||
|
||||
state := buildOptionValidationState(ctx, options)
|
||||
for _, option := range options {
|
||||
if strings.TrimSpace(option.Key) == "" {
|
||||
return errors.New(errInvalidParams)
|
||||
}
|
||||
if isProtectedConfigKey(option.Key) {
|
||||
return errors.New(protectedConfigKeyMessage)
|
||||
}
|
||||
if err := validateOptionWithState(ctx, option, state); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user