From be4e764db4f058962e23141a9c9f4734a77572e7 Mon Sep 17 00:00:00 2001 From: Hiddify Date: Mon, 18 Mar 2024 20:44:23 +0100 Subject: [PATCH] new: add random secret if not provided --- config/config.go | 23 +++++++++++++++++++++++ config/option.go | 2 +- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/config/config.go b/config/config.go index e574913..69c0596 100644 --- a/config/config.go +++ b/config/config.go @@ -2,8 +2,10 @@ package config import ( "bytes" + "encoding/base64" "encoding/json" "fmt" + "math/rand" "net" "net/netip" "net/url" @@ -70,6 +72,9 @@ func BuildConfig(opt ConfigOptions, input option.Options) (*option.Options, erro } if opt.EnableClashApi { + if opt.ClashApiSecret == "" { + opt.ClashApiSecret = generateRandomString(16) + } options.Experimental = &option.ExperimentalOptions{ ClashAPI: &option.ClashAPIOptions{ ExternalController: fmt.Sprintf("%s:%d", "127.0.0.1", opt.ClashApiPort), @@ -632,3 +637,21 @@ func removeDuplicateStr(strSlice []string) []string { } return list } + +func generateRandomString(length int) string { + // Determine the number of bytes needed + bytesNeeded := (length*6 + 7) / 8 + + // Generate random bytes + randomBytes := make([]byte, bytesNeeded) + _, err := rand.Read(randomBytes) + if err != nil { + return "hiddify" + } + + // Encode random bytes to base64 + randomString := base64.URLEncoding.EncodeToString(randomBytes) + + // Trim padding characters and return the string + return randomString[:length] +} diff --git a/config/option.go b/config/option.go index 1df1f46..535afda 100644 --- a/config/option.go +++ b/config/option.go @@ -121,7 +121,7 @@ func DefaultConfigOptions() *ConfigOptions { LogLevel: "warn", EnableClashApi: true, ClashApiPort: 6756, - ClashApiSecret: "hiddify", + ClashApiSecret: "", GeoIPPath: "geoip.db", GeoSitePath: "geosite.db", Rules: []Rule{},