h){var e=new b;e.update(i),i=e.digest()}var n=new Uint8Array(h);return n.set(i),n}var B=o=>{let i=new j;return i.update(o),i.digest()};function I(o){return Array.from(o).map(i=>i.toString(16).padStart(2,"0")).join("")}addEventListener("message",async({data:o})=>{let{data:i,difficulty:e,threads:n}=o,t=o.nonce,r=t===0,a=0,p=Math.floor(e/2),u=e%2!==0;for(;;){let f=await B(i+t),c=new Uint8Array(f),l=!0;for(let s=0;s>4!==0&&(l=!1),l){let s=I(c);postMessage({hash:s,data:i,difficulty:e,nonce:t});return}t+=n,a++,t%1!==0&&(t=Math.trunc(t)),r&&(a&1023)===0&&postMessage(t)}});})();
+//# sourceMappingURL=sha256-purejs.mjs.map
diff --git a/openflare_agent/internal/nginx/pow_static/js/worker/sha256-webcrypto.mjs b/openflare_agent/internal/nginx/pow_static/js/worker/sha256-webcrypto.mjs
new file mode 100644
index 00000000..7d32193b
--- /dev/null
+++ b/openflare_agent/internal/nginx/pow_static/js/worker/sha256-webcrypto.mjs
@@ -0,0 +1,32 @@
+/*
+@licstart The following is the entire license notice for the
+JavaScript code in this page.
+
+Copyright (c) 2025 Xe Iaso
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+Includes code from https://github.com/aws/aws-sdk-js-crypto-helpers which is
+used under the terms of the Apache 2 license.
+
+@licend The above is the entire license notice
+for the JavaScript code in this page.
+*/
+(()=>{var h=new TextEncoder,y=async e=>{let s=h.encode(e);return await crypto.subtle.digest("SHA-256",s)},g=e=>e.reduce((s,a)=>s+a.toString(16).padStart(2,"0"),"");addEventListener("message",async({data:e})=>{let{data:s,difficulty:a,threads:d}=e,t=e.nonce,f=t===0,o=0,c=Math.floor(a/2),l=a%2!==0;for(;;){let u=await y(s+t),i=new Uint8Array(u),r=!0;for(let n=0;n>4!==0&&(r=!1),r){let n=g(i);postMessage({hash:n,data:s,difficulty:a,nonce:t});return}t+=d,o++,t%1!==0&&(t=Math.trunc(t)),f&&(o&1023)===0&&postMessage(t)}});})();
+//# sourceMappingURL=sha256-webcrypto.mjs.map
diff --git a/openflare_agent/internal/nginx/pow_static/locales/en.json b/openflare_agent/internal/nginx/pow_static/locales/en.json
new file mode 100644
index 00000000..4dffb969
--- /dev/null
+++ b/openflare_agent/internal/nginx/pow_static/locales/en.json
@@ -0,0 +1,66 @@
+{
+ "loading": "Loading...",
+ "why_am_i_seeing": "Why am I seeing this?",
+ "protected_by": "Protected by",
+ "protected_from": "From",
+ "made_with": "Made with ❤️ in 🇨🇦",
+ "mascot_design": "Mascot design by",
+ "ai_companies_explanation": "You are seeing this because the administrator of this website has set up Anubis to protect the server against the scourge of AI companies aggressively scraping websites. This can and does cause downtime for the websites, which makes their resources inaccessible for everyone.",
+ "anubis_compromise": "Anubis is a compromise. Anubis uses a Proof-of-Work scheme in the vein of Hashcash, a proposed proof-of-work scheme for reducing email spam. The idea is that at individual scales the additional load is ignorable, but at mass scraper levels it adds up and makes scraping much more expensive.",
+ "hack_purpose": "Ultimately, this is a placeholder solution so that more time can be spent on fingerprinting and identifying headless browsers (EG: via how they do font rendering) so that the challenge proof of work page doesn't need to be presented to users that are much more likely to be legitimate.",
+ "simplified_explanation": "This is a measure against bots and malicious requests similar to a CAPTCHA. However, instead of having to do work yourself, your browser is given a calculation task that it has to solve to ensure that it is a valid client. This concept is called Proof of Work. The task is calculated in a few seconds and you are granted access to the website. Thank you for your understanding and patience.",
+ "jshelter_note": "Please note that Anubis requires the use of modern JavaScript features that plugins like JShelter will disable. Please disable JShelter or other such plugins for this domain.",
+ "version_info": "This website is running Anubis version",
+ "try_again": "Try again",
+ "go_home": "Go home",
+ "contact_webmaster": "or if you believe you should not be blocked, please contact the webmaster at",
+ "connection_security": "Please wait a moment while we ensure the security of your connection.",
+ "javascript_required": "Sadly, you must enable JavaScript to get past this challenge. This is required because AI companies have changed the social contract around how website hosting works. A no-JS solution is a work-in-progress.",
+ "benchmark_requires_js": "Running the benchmark tool requires JavaScript to be enabled.",
+ "difficulty": "Difficulty:",
+ "algorithm": "Algorithm:",
+ "compare": "Compare:",
+ "time": "Time",
+ "iters": "Iters",
+ "time_a": "Time A",
+ "iters_a": "Iters A",
+ "time_b": "Time B",
+ "iters_b": "Iters B",
+ "static_check_endpoint": "This is just a check endpoint for your reverse proxy to use.",
+ "authorization_required": "Authorization required",
+ "cookies_disabled": "Your browser is configured to disable cookies. Anubis requires cookies for the legitimate interest of making sure you are a valid client. Please enable cookies for this domain",
+ "access_denied": "Access Denied: error code",
+ "dronebl_entry": "DroneBL reported an entry",
+ "see_dronebl_lookup": "see",
+ "internal_server_error": "Internal Server Error: administrator has misconfigured Anubis. Please contact the administrator and ask them to look for the logs around",
+ "invalid_redirect": "Invalid redirect",
+ "redirect_not_parseable": "Redirect URL not parseable",
+ "redirect_domain_not_allowed": "Redirect domain not allowed",
+ "missing_required_forwarded_headers": "Missing required X-Forwarded-* headers",
+ "failed_to_sign_jwt": "failed to sign JWT",
+ "invalid_invocation": "Invalid invocation of MakeChallenge",
+ "client_error_browser": "Client Error: Please ensure your browser is up to date and try again later.",
+ "oh_noes": "Oh noes!",
+ "benchmarking_anubis": "Benchmarking Anubis!",
+ "you_are_not_a_bot": "You are not a bot!",
+ "making_sure_not_bot": "Making sure you're not a bot!",
+ "celphase": "CELPHASE",
+ "js_web_crypto_error": "Your browser doesn't have a functioning web.crypto element. Are you viewing this over a secure context?",
+ "js_web_workers_error": "Your browser doesn't support web workers (Anubis uses this to avoid freezing your browser). Do you have a plugin like JShelter installed?",
+ "js_cookies_error": "Your browser doesn't store cookies. Anubis uses cookies to determine which clients have passed challenges by storing a signed token in a cookie. Please enable storing cookies for this domain. The names of the cookies Anubis stores may vary without notice. Cookie names and values are not part of the public API.",
+ "js_context_not_secure": "Your context is not secure!",
+ "js_context_not_secure_msg": "Try connecting over HTTPS or let the admin know to set up HTTPS. For more information, see MDN.",
+ "js_calculating": "Calculating...",
+ "js_missing_feature": "Missing feature",
+ "js_challenge_error": "Challenge error!",
+ "js_challenge_error_msg": "Failed to resolve check algorithm. You may want to reload the page.",
+ "js_calculating_difficulty": "Calculating...
Difficulty:",
+ "js_speed": "Speed:",
+ "js_verification_longer": "Verification is taking longer than expected. Please do not refresh the page.",
+ "js_success": "Success!",
+ "js_done_took": "Done! Took",
+ "js_iterations": "iterations",
+ "js_finished_reading": "I've finished reading, continue →",
+ "js_calculation_error": "Calculation error!",
+ "js_calculation_error_msg": "Failed to calculate challenge:"
+}
diff --git a/openflare_agent/internal/nginx/pow_static/locales/zh-CN.json b/openflare_agent/internal/nginx/pow_static/locales/zh-CN.json
new file mode 100644
index 00000000..19529607
--- /dev/null
+++ b/openflare_agent/internal/nginx/pow_static/locales/zh-CN.json
@@ -0,0 +1,66 @@
+{
+ "loading": "加载中...",
+ "why_am_i_seeing": "为什么我会看到这个?",
+ "protected_by": "本网站由",
+ "protected_from": "保护,来自",
+ "made_with": "在 🇨🇦 用 ❤️ 制作",
+ "mascot_design": "吉祥物由",
+ "ai_companies_explanation": "您会看到这个画面,是因为网站管理员启用了 Anubis 来保护服务器,避免 AI 公司大量爬取网站内容。这类行为会导致网站崩溃,让所有用户都无法正常访问资源。",
+ "anubis_compromise": "Anubis 是一种折中做法。它采用了类似 Hashcash 的工作量证明机制(Proof-of-Work),该机制最初是为了减少垃圾邮件而提出。其核心概念是:对个别用户而言,额外的计算负担可以忽略,但对大规模爬虫来说,累积起来的成本将大幅增加,从而让爬取行为变得更困难。",
+ "hack_purpose": "最终,这是一个占位符解决方案,以便将更多时间用于指纹识别和识别无头浏览器(例如:通过它们如何进行字体渲染),从而无需向更可能是合法用户的用户呈现挑战工作量证明页面。",
+ "jshelter_note": "请注意,Anubis 需要使用现代 JavaScript 功能,而像 JShelter 这类插件可能会阻挡这些功能。请为此域名停用 JShelter 或类似的插件。",
+ "version_info": "这个网站正在运行的 Anubis 版本为",
+ "try_again": "再试一次",
+ "go_home": "返回首页",
+ "contact_webmaster": "或者您觉得您不应该被封锁,请联系网站管理员于",
+ "connection_security": "请稍等,我们需要在继续之前检查您的连接安全性。",
+ "javascript_required": "很遗憾,您必须启用 JavaScript 才能通过这项验证。这是因为 AI 公司已经改变了网站托管的社会契约,因此我们必须采取这样的保护机制。无需 JavaScript 的解决方案仍在开发中。",
+ "benchmark_requires_js": "运行基准测试工具需要启用 JavaScript。",
+ "difficulty": "难度:",
+ "algorithm": "算法:",
+ "compare": "比较:",
+ "time": "时间",
+ "iters": "迭代",
+ "time_a": "时间 A",
+ "iters_a": "迭代 A",
+ "time_b": "时间 B",
+ "iters_b": "迭代 B",
+ "static_check_endpoint": "这是提供给您的反向代理服务器使用的检查端点。",
+ "authorization_required": "需要认证",
+ "cookies_disabled": "您的浏览器目前已禁用 Cookie,为了确认您是合法用户,Anubis 需要启用 Cookie。 请您为此域名启用 Cookie",
+ "access_denied": "拒绝访问:错误代码",
+ "dronebl_entry": "DroneBL 报告了一条记录",
+ "see_dronebl_lookup": "见",
+ "internal_server_error": "内部服务器错误:管理员错误地配置了 Anubis。 请联系管理员要求他们检查日志",
+ "invalid_redirect": "无效的重定向",
+ "redirect_not_parseable": "重定向 URL 无法解析",
+ "redirect_domain_not_allowed": "重定向的域名并不允许",
+ "failed_to_sign_jwt": "签署 JWT 失败",
+ "invalid_invocation": "无效的 MakeChallenge 调用",
+ "client_error_browser": "客户端错误:请确保您的浏览器是最新版本并稍候再试。",
+ "oh_noes": "哎呀糟糕了!",
+ "benchmarking_anubis": "正在进行 Anubis 性能测试!",
+ "you_are_not_a_bot": "你不是机器人!",
+ "making_sure_not_bot": "正在确认你是不是机器人!",
+ "celphase": "CELPHASE 设计",
+ "js_web_crypto_error": "您的浏览器无法正常使用 web.crypto 组件。您是否通过安全连接(HTTPS)查看此网站?",
+ "js_web_workers_error": "您的浏览器并不支持 Web workers (Anubis 使用这个来避免冻结您的浏览器 )您有安装像是 JShelter 之类的插件吗?",
+ "js_cookies_error": "您的浏览器无法存储 Cookie。 Anubis 会使用 Cookie 存储签署的凭证,以判断用户是否已通过验证。请为此域名启用 Cookie 存储功能。 请注意,Anubis 存储的 Cookie 名称可能会变动,且其名称与内容不属于公开 API 的一部分。",
+ "js_context_not_secure": "您的内容并不安全",
+ "js_context_not_secure_msg": "请尝试使用 HTTPS 连接,或联系网站管理员设置 HTTPS。更多信息请参见 MDN。",
+ "js_calculating": "计算中...",
+ "js_missing_feature": "缺少功能",
+ "js_challenge_error": "挑战错误!",
+ "js_challenge_error_msg": "解决检查算法失败。 您可能会想要刷新页面。",
+ "js_calculating_difficulty": "计算中...
难度:",
+ "js_speed": "速度:",
+ "js_verification_longer": "验证所花的时间高于预期。 请不要刷新页面。",
+ "js_success": "成功!",
+ "js_done_took": "完成! 花费",
+ "js_iterations": "迭代",
+ "js_finished_reading": "我读完了,继续 →",
+ "js_calculation_error": "计算错误!",
+ "js_calculation_error_msg": "计算挑战失败:",
+ "missing_required_forwarded_headers": "缺少必要的 X-Forwarded-* 头",
+ "simplified_explanation": "这是一种类似于验证码的措施,用于防止机器人和恶意请求。但是,您无需自己动手,您的浏览器会收到一个计算任务,必须解决该任务以确保它是有效的客户端。这个概念称为工作量证明。该任务在几秒钟内计算完毕,您将被授予访问网站的权限。感谢您的理解和耐心。"
+}
diff --git a/openflare_server/model/database_schema_version.go b/openflare_server/model/database_schema_version.go
index 969f9922..a8eaaafe 100644
--- a/openflare_server/model/database_schema_version.go
+++ b/openflare_server/model/database_schema_version.go
@@ -4,7 +4,7 @@ import "time"
const (
legacyDatabaseSchemaVersion = 1
- currentDatabaseSchemaVersion = 8
+ currentDatabaseSchemaVersion = 9
databaseSchemaVersionRowID = 1
)
diff --git a/openflare_server/model/migrations.go b/openflare_server/model/migrations.go
index f5f62508..0bb052e4 100644
--- a/openflare_server/model/migrations.go
+++ b/openflare_server/model/migrations.go
@@ -1196,6 +1196,39 @@ func migrateV8(db *gorm.DB, backend string) error {
return backfillProxyRouteDomainCertificateFields(db)
}
+// migrateV9 adds PoW (Proof-of-Work) anti-bot protection fields to proxy_routes.
+func migrateV9(db *gorm.DB, backend string) error {
+ if err := applyCurrentSchema(db, backend); err != nil {
+ return err
+ }
+ if err := backfillOriginsFromProxyRoutes(db); err != nil {
+ return err
+ }
+ if err := backfillProxyRouteSiteFields(db); err != nil {
+ return err
+ }
+ if err := ensureProxyRouteSiteNameUniqueIndex(db); err != nil {
+ return err
+ }
+ if err := backfillProxyRouteCertificateFields(db); err != nil {
+ return err
+ }
+ return backfillProxyRouteDomainCertificateFields(db)
+}
+
+func validateDatabaseSchemaV9(db *gorm.DB, backend string) error {
+ if err := validateDatabaseSchemaV8(db, backend); err != nil {
+ return err
+ }
+ if !db.Migrator().HasColumn(&ProxyRoute{}, "pow_enabled") {
+ return fmt.Errorf("column proxy_routes.pow_enabled is missing")
+ }
+ if !db.Migrator().HasColumn(&ProxyRoute{}, "pow_config") {
+ return fmt.Errorf("column proxy_routes.pow_config is missing")
+ }
+ return nil
+}
+
func databaseSchemaMigrations() []databaseSchemaMigration {
return []databaseSchemaMigration{
{fromVersion: 1, toVersion: 2, migrate: migrateV2, validate: validateDatabaseSchemaV2},
@@ -1205,6 +1238,7 @@ func databaseSchemaMigrations() []databaseSchemaMigration {
{fromVersion: 5, toVersion: 6, migrate: migrateV6, validate: validateDatabaseSchemaV6},
{fromVersion: 6, toVersion: 7, migrate: migrateV7, validate: validateDatabaseSchemaV7},
{fromVersion: 7, toVersion: 8, migrate: migrateV8, validate: validateDatabaseSchemaV8},
+ {fromVersion: 8, toVersion: 9, migrate: migrateV9, validate: validateDatabaseSchemaV9},
}
}
@@ -1287,7 +1321,7 @@ func initializeFreshDatabaseSchema(db *gorm.DB, backend string) error {
if err := backfillProxyRouteDomainCertificateFields(db); err != nil {
return err
}
- if err := validateDatabaseSchemaV8(db, backend); err != nil {
+ if err := validateDatabaseSchemaV9(db, backend); err != nil {
return err
}
return saveDatabaseSchemaVersion(db, currentDatabaseSchemaVersion)
diff --git a/openflare_server/model/proxy_route.go b/openflare_server/model/proxy_route.go
index f34208bc..f45cb3cb 100644
--- a/openflare_server/model/proxy_route.go
+++ b/openflare_server/model/proxy_route.go
@@ -24,6 +24,8 @@ type ProxyRoute struct {
CachePolicy string `json:"cache_policy" gorm:"size:32;not null;default:''"`
CacheRules string `json:"cache_rules" gorm:"type:text;not null;default:'[]'"`
CustomHeaders string `json:"custom_headers" gorm:"type:text;not null;default:'[]'"`
+ PoWEnabled bool `json:"pow_enabled" gorm:"column:pow_enabled;not null;default:false"`
+ PoWConfig string `json:"pow_config" gorm:"column:pow_config;type:text;not null;default:'{}'"`
Remark string `json:"remark" gorm:"size:255"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
@@ -76,6 +78,8 @@ func (route *ProxyRoute) Update() error {
"cache_policy": route.CachePolicy,
"cache_rules": route.CacheRules,
"custom_headers": route.CustomHeaders,
+ "pow_enabled": route.PoWEnabled,
+ "pow_config": route.PoWConfig,
"remark": route.Remark,
}).Error
}
diff --git a/openflare_server/service/agent.go b/openflare_server/service/agent.go
index 72e30957..a942a910 100644
--- a/openflare_server/service/agent.go
+++ b/openflare_server/service/agent.go
@@ -217,7 +217,7 @@ func GetActiveConfigForAgent() (*AgentConfigResponse, error) {
return nil, err
}
}
- supportFiles = filterCertificateSupportFiles(supportFiles)
+ supportFiles = filterAgentSupportFiles(supportFiles)
slog.Debug("agent fetched active config", "version", version.Version, "checksum", version.Checksum)
return &AgentConfigResponse{
Version: version.Version,
@@ -230,7 +230,7 @@ func GetActiveConfigForAgent() (*AgentConfigResponse, error) {
}, nil
}
-func filterCertificateSupportFiles(files []SupportFile) []SupportFile {
+func filterAgentSupportFiles(files []SupportFile) []SupportFile {
if len(files) == 0 {
return nil
}
@@ -240,6 +240,8 @@ func filterCertificateSupportFiles(files []SupportFile) []SupportFile {
switch {
case strings.HasSuffix(path, ".crt"), strings.HasSuffix(path, ".key"), strings.HasSuffix(path, ".pem"):
filtered = append(filtered, file)
+ case path == "pow_config.json":
+ filtered = append(filtered, file)
}
}
return filtered
diff --git a/openflare_server/service/agent_test.go b/openflare_server/service/agent_test.go
new file mode 100644
index 00000000..f1796eaf
--- /dev/null
+++ b/openflare_server/service/agent_test.go
@@ -0,0 +1,41 @@
+package service
+
+import "testing"
+
+func TestGetActiveConfigForAgentIncludesPoWConfig(t *testing.T) {
+ setupServiceTestDB(t)
+
+ _, err := CreateProxyRoute(ProxyRouteInput{
+ Domain: "pow-agent.example.com",
+ OriginURL: "https://origin.internal",
+ Enabled: true,
+ PoWEnabled: true,
+ PoWConfig: `{"difficulty":4,"algorithm":"fast","session_ttl":86400,"challenge_ttl":300,"whitelist":{"paths":["/.well-known/*","/favicon.ico","/robots.txt"],"user_agents":["Googlebot","bingbot","Baiduspider"]},"blacklist":{"ips":[],"ip_cidrs":[],"paths":[],"path_regexes":[],"user_agents":[]}}`,
+ })
+ if err != nil {
+ t.Fatalf("CreateProxyRoute failed: %v", err)
+ }
+
+ if _, err := PublishConfigVersion("root"); err != nil {
+ t.Fatalf("PublishConfigVersion failed: %v", err)
+ }
+
+ activeConfig, err := GetActiveConfigForAgent()
+ if err != nil {
+ t.Fatalf("GetActiveConfigForAgent failed: %v", err)
+ }
+
+ foundPowConfig := false
+ for _, file := range activeConfig.SupportFiles {
+ if file.Path != "pow_config.json" {
+ continue
+ }
+ foundPowConfig = true
+ if file.Content == "" {
+ t.Fatal("expected pow_config.json content to be populated")
+ }
+ }
+ if !foundPowConfig {
+ t.Fatal("expected agent config to include pow_config.json support file")
+ }
+}
diff --git a/openflare_server/service/config_version.go b/openflare_server/service/config_version.go
index 6f3d5ed2..4ba70265 100644
--- a/openflare_server/service/config_version.go
+++ b/openflare_server/service/config_version.go
@@ -83,6 +83,8 @@ type snapshotRoute struct {
CachePolicy string `json:"cache_policy,omitempty"`
CacheRules []string `json:"cache_rules,omitempty"`
CustomHeaders []ProxyRouteCustomHeaderInput `json:"custom_headers,omitempty"`
+ PoWEnabled bool `json:"pow_enabled,omitempty"`
+ PoWConfig *ProxyRoutePoWConfig `json:"pow_config,omitempty"`
Remark string `json:"remark,omitempty"`
}
@@ -429,7 +431,13 @@ func buildCurrentConfigBundle(requireRoutes bool) (*configBundle, error) {
if err != nil {
return nil, err
}
+ powConfigJSON, powSupportFiles, err := renderPowConfigBundle(routes)
+ if err != nil {
+ return nil, err
+ }
+ supportFiles = append(supportFiles, powSupportFiles...)
mainConfig := renderMainConfig(openRestyConfig)
+ supportFiles = append(supportFiles, SupportFile{Path: "pow_config.json", Content: powConfigJSON})
return &configBundle{
Routes: routes,
SnapshotRoutes: snapshotRoutes,
@@ -462,6 +470,13 @@ func buildSnapshotRoutes(routes []*model.ProxyRoute) ([]snapshotRoute, error) {
if err != nil {
return nil, fmt.Errorf("路由 %s 缓存规则无效", route.Domain)
}
+ powConfig, err := decodeStoredPoWConfig(route.PoWEnabled, route.PoWConfig)
+ if err != nil {
+ return nil, fmt.Errorf("路由 %s PoW 配置无效", route.Domain)
+ }
+ if !route.PoWEnabled {
+ powConfig = nil
+ }
items = append(items, snapshotRoute{
SiteName: normalizeProxyRouteSiteNameInput(route, route.SiteName, domains[0]),
Domain: domains[0],
@@ -482,6 +497,8 @@ func buildSnapshotRoutes(routes []*model.ProxyRoute) ([]snapshotRoute, error) {
CachePolicy: route.CachePolicy,
CacheRules: cacheRules,
CustomHeaders: customHeaders,
+ PoWEnabled: route.PoWEnabled,
+ PoWConfig: powConfig,
Remark: route.Remark,
})
}
@@ -586,6 +603,17 @@ func normalizeSnapshotRoutes(routes []snapshotRoute) []snapshotRoute {
if err == nil {
routes[index].LimitRate = normalizedLimitRate
}
+ if routes[index].PoWEnabled {
+ raw, err := json.Marshal(routes[index].PoWConfig)
+ if err == nil {
+ normalizedPoWConfig, err := normalizePoWConfig(true, string(raw))
+ if err == nil {
+ routes[index].PoWConfig = &normalizedPoWConfig
+ }
+ }
+ } else {
+ routes[index].PoWConfig = nil
+ }
}
return routes
}
@@ -611,7 +639,7 @@ func flattenSnapshotRoutesByDomain(routes []snapshotRoute) map[string]snapshotRo
}
func snapshotRouteConfigEqual(left snapshotRoute, right snapshotRoute) bool {
- if left.SiteName != right.SiteName || left.Domain != right.Domain || left.OriginURL != right.OriginURL || left.OriginHost != right.OriginHost || left.EnableHTTPS != right.EnableHTTPS || left.RedirectHTTP != right.RedirectHTTP || left.LimitConnPerServer != right.LimitConnPerServer || left.LimitConnPerIP != right.LimitConnPerIP || left.LimitRate != right.LimitRate || left.CacheEnabled != right.CacheEnabled || left.CachePolicy != right.CachePolicy || !uintSliceEqual(left.CertIDs, right.CertIDs) || !uintSliceEqual(left.DomainCertIDs, right.DomainCertIDs) {
+ if left.SiteName != right.SiteName || left.Domain != right.Domain || left.OriginURL != right.OriginURL || left.OriginHost != right.OriginHost || left.EnableHTTPS != right.EnableHTTPS || left.RedirectHTTP != right.RedirectHTTP || left.LimitConnPerServer != right.LimitConnPerServer || left.LimitConnPerIP != right.LimitConnPerIP || left.LimitRate != right.LimitRate || left.CacheEnabled != right.CacheEnabled || left.CachePolicy != right.CachePolicy || left.PoWEnabled != right.PoWEnabled || !uintSliceEqual(left.CertIDs, right.CertIDs) || !uintSliceEqual(left.DomainCertIDs, right.DomainCertIDs) {
return false
}
if len(left.Domains) != len(right.Domains) {
@@ -646,6 +674,41 @@ func snapshotRouteConfigEqual(left snapshotRoute, right snapshotRoute) bool {
return false
}
}
+ if !snapshotPoWConfigEqual(left.PoWConfig, right.PoWConfig) {
+ return false
+ }
+ return true
+}
+
+func snapshotPoWConfigEqual(left *ProxyRoutePoWConfig, right *ProxyRoutePoWConfig) bool {
+ if left == nil || right == nil {
+ return left == nil && right == nil
+ }
+ return left.Difficulty == right.Difficulty &&
+ left.Algorithm == right.Algorithm &&
+ left.SessionTTL == right.SessionTTL &&
+ left.ChallengeTTL == right.ChallengeTTL &&
+ stringSliceEqual(left.Whitelist.IPs, right.Whitelist.IPs) &&
+ stringSliceEqual(left.Whitelist.IPCidrs, right.Whitelist.IPCidrs) &&
+ stringSliceEqual(left.Whitelist.Paths, right.Whitelist.Paths) &&
+ stringSliceEqual(left.Whitelist.PathRegexes, right.Whitelist.PathRegexes) &&
+ stringSliceEqual(left.Whitelist.UserAgents, right.Whitelist.UserAgents) &&
+ stringSliceEqual(left.Blacklist.IPs, right.Blacklist.IPs) &&
+ stringSliceEqual(left.Blacklist.IPCidrs, right.Blacklist.IPCidrs) &&
+ stringSliceEqual(left.Blacklist.Paths, right.Blacklist.Paths) &&
+ stringSliceEqual(left.Blacklist.PathRegexes, right.Blacklist.PathRegexes) &&
+ stringSliceEqual(left.Blacklist.UserAgents, right.Blacklist.UserAgents)
+}
+
+func stringSliceEqual(left []string, right []string) bool {
+ if len(left) != len(right) {
+ return false
+ }
+ for index := range left {
+ if left[index] != right[index] {
+ return false
+ }
+ }
return true
}
@@ -835,7 +898,7 @@ func renderRouteConfig(routes []*model.ProxyRoute, cfg openRestyConfigSnapshot)
builder.WriteString(renderNamedUpstreamBlock(upstreamConfig))
}
if !route.EnableHTTPS {
- builder.WriteString(renderHTTPProxyServer(serverNames, route.OriginURL, route.OriginHost, customHeaders, cacheConfig, limitConfig, upstreamConfig, cfg))
+ builder.WriteString(renderHTTPProxyServer(serverNames, route.OriginURL, route.OriginHost, customHeaders, cacheConfig, limitConfig, upstreamConfig, route.PoWEnabled, cfg))
continue
}
certIDs, err := decodeStoredCertIDs(route.CertIDs, route.CertID)
@@ -896,7 +959,7 @@ func renderRouteConfig(routes []*model.ProxyRoute, cfg openRestyConfigSnapshot)
if route.RedirectHTTP {
if len(httpOnlyDomains) > 0 {
- builder.WriteString(renderHTTPProxyServer(renderServerNames(httpOnlyDomains), route.OriginURL, route.OriginHost, customHeaders, cacheConfig, limitConfig, upstreamConfig, cfg))
+ builder.WriteString(renderHTTPProxyServer(renderServerNames(httpOnlyDomains), route.OriginURL, route.OriginHost, customHeaders, cacheConfig, limitConfig, upstreamConfig, route.PoWEnabled, cfg))
}
for _, certID := range certIDs {
assignedDomains := domainsByCertID[certID]
@@ -906,14 +969,14 @@ func renderRouteConfig(routes []*model.ProxyRoute, cfg openRestyConfigSnapshot)
builder.WriteString(renderHTTPRedirectServer(renderServerNames(assignedDomains)))
}
} else {
- builder.WriteString(renderHTTPProxyServer(serverNames, route.OriginURL, route.OriginHost, customHeaders, cacheConfig, limitConfig, upstreamConfig, cfg))
+ builder.WriteString(renderHTTPProxyServer(serverNames, route.OriginURL, route.OriginHost, customHeaders, cacheConfig, limitConfig, upstreamConfig, route.PoWEnabled, cfg))
}
for _, certID := range certIDs {
assignedDomains := domainsByCertID[certID]
if len(assignedDomains) == 0 {
continue
}
- builder.WriteString(renderHTTPSServer(renderServerNames(assignedDomains), route.OriginURL, route.OriginHost, certID, customHeaders, cacheConfig, limitConfig, upstreamConfig, cfg))
+ builder.WriteString(renderHTTPSServer(renderServerNames(assignedDomains), route.OriginURL, route.OriginHost, certID, customHeaders, cacheConfig, limitConfig, upstreamConfig, route.PoWEnabled, cfg))
}
}
return builder.String(), dedupeSupportFiles(supportFiles), nil
@@ -1020,6 +1083,32 @@ func onOff(value bool) string {
return "off"
}
+const nginxPowStaticDirPlaceholder = "__OPENFLARE_POW_STATIC_DIR__"
+
+func renderPowAccessBlock(powEnabled bool) string {
+ if !powEnabled {
+ return ""
+ }
+ return fmt.Sprintf(" access_by_lua_file %s/pow/check.lua;\n", nginxLuaDirPlaceholder)
+}
+
+func renderPowLocationBlocks(powEnabled bool) string {
+ if !powEnabled {
+ return ""
+ }
+ return fmt.Sprintf("\n location = %spass-challenge {\n content_by_lua_file %s/pow/verify.lua;\n }\n\n location = %smake-challenge {\n content_by_lua_file %s/pow/challenge.lua;\n }\n\n", anubisAPIPrefix, nginxLuaDirPlaceholder, anubisAPIPrefix, nginxLuaDirPlaceholder)
+}
+
+func renderPowStaticLocationBlock(powEnabled bool) string {
+ if !powEnabled {
+ return ""
+ }
+ return fmt.Sprintf(" location %s {\n alias %s/;\n }\n\n", anubisStaticPrefix, nginxPowStaticDirPlaceholder)
+}
+
+const anubisStaticPrefix = "/.within.website/x/cmd/anubis/static/"
+const anubisAPIPrefix = "/.within.website/x/cmd/anubis/api/"
+
func normalizeSnapshotCertificateIDs(primaryCertID *uint, certIDs []uint) ([]uint, *uint, error) {
candidates := make([]uint, 0, len(certIDs)+1)
if primaryCertID != nil && *primaryCertID != 0 {
@@ -1130,18 +1219,18 @@ func nextVersionNumber(now time.Time) (string, error) {
return fmt.Sprintf("%s-%03d", prefix, count+1), nil
}
-func renderHTTPProxyServer(serverNames string, originURL string, originHost string, customHeaders []ProxyRouteCustomHeaderInput, cacheConfig routeCacheConfig, limitConfig routeLimitConfig, upstreamConfig routeUpstreamConfig, cfg openRestyConfigSnapshot) string {
- return fmt.Sprintf("server {\n listen 80;\n server_name %s;\n\n location / {\n%s%s%s%s }\n}\n\n", serverNames, renderProxyHeaderBlock(originURL, originHost, customHeaders, upstreamConfig), renderRouteLimitBlock(limitConfig), renderRouteCacheBlock(cacheConfig, cfg), renderProxyPassBlock(originURL, upstreamConfig))
+func renderHTTPProxyServer(serverNames string, originURL string, originHost string, customHeaders []ProxyRouteCustomHeaderInput, cacheConfig routeCacheConfig, limitConfig routeLimitConfig, upstreamConfig routeUpstreamConfig, powEnabled bool, cfg openRestyConfigSnapshot) string {
+ return fmt.Sprintf("server {\n listen 80;\n server_name %s;\n%s location / {\n%s%s%s%s%s }\n%s}\n\n", serverNames, renderPowLocationBlocks(powEnabled), renderPowAccessBlock(powEnabled), renderProxyHeaderBlock(originURL, originHost, customHeaders, upstreamConfig), renderRouteLimitBlock(limitConfig), renderRouteCacheBlock(cacheConfig, cfg), renderProxyPassBlock(originURL, upstreamConfig), renderPowStaticLocationBlock(powEnabled))
}
func renderHTTPRedirectServer(serverNames string) string {
return fmt.Sprintf("server {\n listen 80;\n server_name %s;\n\n return 301 https://$host$request_uri;\n}\n\n", serverNames)
}
-func renderHTTPSServer(serverNames string, originURL string, originHost string, certificateID uint, customHeaders []ProxyRouteCustomHeaderInput, cacheConfig routeCacheConfig, limitConfig routeLimitConfig, upstreamConfig routeUpstreamConfig, cfg openRestyConfigSnapshot) string {
+func renderHTTPSServer(serverNames string, originURL string, originHost string, certificateID uint, customHeaders []ProxyRouteCustomHeaderInput, cacheConfig routeCacheConfig, limitConfig routeLimitConfig, upstreamConfig routeUpstreamConfig, powEnabled bool, cfg openRestyConfigSnapshot) string {
certPath := fmt.Sprintf("%s/%s", nginxCertDirPlaceholder, certificateCertFileName(certificateID))
keyPath := fmt.Sprintf("%s/%s", nginxCertDirPlaceholder, certificateKeyFileName(certificateID))
- return fmt.Sprintf("server {\n listen 443 ssl;\n http2 on;\n server_name %s;\n ssl_certificate %s;\n ssl_certificate_key %s;\n\n location / {\n%s%s%s%s }\n}\n\n", serverNames, certPath, keyPath, renderProxyHeaderBlock(originURL, originHost, customHeaders, upstreamConfig), renderRouteLimitBlock(limitConfig), renderRouteCacheBlock(cacheConfig, cfg), renderProxyPassBlock(originURL, upstreamConfig))
+ return fmt.Sprintf("server {\n listen 443 ssl;\n http2 on;\n server_name %s;\n ssl_certificate %s;\n ssl_certificate_key %s;\n%s location / {\n%s%s%s%s%s }\n%s}\n\n", serverNames, certPath, keyPath, renderPowLocationBlocks(powEnabled), renderPowAccessBlock(powEnabled), renderProxyHeaderBlock(originURL, originHost, customHeaders, upstreamConfig), renderRouteLimitBlock(limitConfig), renderRouteCacheBlock(cacheConfig, cfg), renderProxyPassBlock(originURL, upstreamConfig), renderPowStaticLocationBlock(powEnabled))
}
func renderHTTPSServerWithCertificates(serverNames string, originURL string, originHost string, certificateIDs []uint, customHeaders []ProxyRouteCustomHeaderInput, cacheConfig routeCacheConfig, limitConfig routeLimitConfig, upstreamConfig routeUpstreamConfig, cfg openRestyConfigSnapshot) string {
@@ -1505,3 +1594,40 @@ func dedupeSupportFiles(files []SupportFile) []SupportFile {
}
return result
}
+
+func renderPowConfigBundle(routes []*model.ProxyRoute) (string, []SupportFile, error) {
+ type domainEntry struct {
+ Domains []string `json:"domains"`
+ Enabled bool `json:"enabled"`
+ Config map[string]interface{} `json:"config"`
+ }
+ entries := make([]domainEntry, 0)
+ hasPow := false
+ for _, route := range routes {
+ if !route.PoWEnabled {
+ continue
+ }
+ hasPow = true
+ domains, err := decodeStoredDomains(route.Domains, route.Domain)
+ if err != nil {
+ return "", nil, err
+ }
+ var cfg map[string]interface{}
+ if err := json.Unmarshal([]byte(route.PoWConfig), &cfg); err != nil {
+ return "", nil, fmt.Errorf("route %s pow_config is invalid", route.Domain)
+ }
+ entries = append(entries, domainEntry{
+ Domains: domains,
+ Enabled: true,
+ Config: cfg,
+ })
+ }
+ if !hasPow {
+ return "{}", nil, nil
+ }
+ data, err := json.Marshal(entries)
+ if err != nil {
+ return "", nil, err
+ }
+ return string(data), nil, nil
+}
diff --git a/openflare_server/service/https_phase1_test.go b/openflare_server/service/https_phase1_test.go
index fd99ee2b..837b7e68 100644
--- a/openflare_server/service/https_phase1_test.go
+++ b/openflare_server/service/https_phase1_test.go
@@ -5,6 +5,7 @@ import (
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
+ "encoding/json"
"encoding/pem"
"math/big"
"openflare/common"
@@ -923,6 +924,90 @@ func TestPreviewAndDiffConfigVersion(t *testing.T) {
}
}
+func TestPublishConfigVersionDetectsPoWChanges(t *testing.T) {
+ setupServiceTestDB(t)
+
+ route, err := CreateProxyRoute(ProxyRouteInput{
+ Domain: "pow.example.com",
+ OriginURL: "https://origin.internal",
+ Enabled: true,
+ })
+ if err != nil {
+ t.Fatalf("CreateProxyRoute failed: %v", err)
+ }
+
+ firstRelease, err := PublishConfigVersion("root")
+ if err != nil {
+ t.Fatalf("initial PublishConfigVersion failed: %v", err)
+ }
+ if !strings.Contains(firstRelease.Version.SupportFilesJSON, `"path":"pow_config.json"`) {
+ t.Fatal("expected publish to include pow_config.json support file")
+ }
+
+ _, err = UpdateProxyRoute(route.ID, ProxyRouteInput{
+ Domain: route.Domain,
+ OriginURL: route.OriginURL,
+ Enabled: true,
+ PoWEnabled: true,
+ PoWConfig: `{"difficulty":5,"algorithm":"slow","session_ttl":7200,"challenge_ttl":180,"whitelist":{"ips":["127.0.0.1"],"ip_cidrs":[],"paths":[],"path_regexes":[],"user_agents":[]},"blacklist":{"ips":[],"ip_cidrs":[],"paths":["/login"],"path_regexes":[],"user_agents":[]}}`,
+ RedirectHTTP: false,
+ })
+ if err != nil {
+ t.Fatalf("UpdateProxyRoute failed: %v", err)
+ }
+
+ diff, err := DiffConfigVersion()
+ if err != nil {
+ t.Fatalf("DiffConfigVersion failed: %v", err)
+ }
+ if len(diff.ModifiedDomains) != 1 || diff.ModifiedDomains[0] != "pow.example.com" {
+ t.Fatalf("expected PoW change to mark domain as modified, got %#v", diff.ModifiedDomains)
+ }
+ if len(diff.ModifiedSites) != 1 || diff.ModifiedSites[0] != "pow.example.com" {
+ t.Fatalf("expected PoW change to mark site as modified, got %#v", diff.ModifiedSites)
+ }
+
+ secondRelease, err := PublishConfigVersion("root")
+ if err != nil {
+ t.Fatalf("PublishConfigVersion after PoW change failed: %v", err)
+ }
+ if firstRelease.Version.Checksum == secondRelease.Version.Checksum {
+ t.Fatal("expected PoW change to alter published checksum")
+ }
+ if !strings.Contains(secondRelease.Version.SnapshotJSON, `"pow_enabled":true`) {
+ t.Fatal("expected snapshot to persist PoW enabled state")
+ }
+ if !strings.Contains(secondRelease.Version.MainConfig, "lua_shared_dict openflare_pow_config 1m;") {
+ t.Fatal("expected main config to declare shared dict for pow config")
+ }
+ if !strings.Contains(secondRelease.Version.RenderedConfig, "location /.within.website/x/cmd/anubis/static/ {") {
+ t.Fatal("expected rendered config to expose anubis static location")
+ }
+ if strings.Contains(secondRelease.Version.RenderedConfig, "location /.within.website/x/cmd/anubis/static/static/ {") {
+ t.Fatal("expected rendered config to avoid duplicate static path segment")
+ }
+ if !strings.Contains(secondRelease.Version.SnapshotJSON, `"difficulty":5`) {
+ t.Fatal("expected snapshot to persist PoW config")
+ }
+ var supportFiles []SupportFile
+ if err := json.Unmarshal([]byte(secondRelease.Version.SupportFilesJSON), &supportFiles); err != nil {
+ t.Fatalf("failed to decode support files: %v", err)
+ }
+ foundPowSupportFile := false
+ for _, file := range supportFiles {
+ if file.Path != "pow_config.json" {
+ continue
+ }
+ foundPowSupportFile = true
+ if !strings.Contains(file.Content, `"difficulty":5`) {
+ t.Fatalf("expected pow support file to persist config, got %s", file.Content)
+ }
+ }
+ if !foundPowSupportFile {
+ t.Fatal("expected publish to include pow_config.json support file")
+ }
+}
+
func TestRenderConfigUsesDefaultServerFallback(t *testing.T) {
setupServiceTestDB(t)
diff --git a/openflare_server/service/openresty_observability_assets.go b/openflare_server/service/openresty_observability_assets.go
index b55754eb..637e7a21 100644
--- a/openflare_server/service/openresty_observability_assets.go
+++ b/openflare_server/service/openresty_observability_assets.go
@@ -11,6 +11,9 @@ const (
func renderOpenRestyObservabilityTemplateBlock() string {
return stringsJoinLines(
" lua_shared_dict openflare_observability 10m;",
+ " lua_shared_dict openflare_pow_config 1m;",
+ " lua_shared_dict openflare_pow_challenges 10m;",
+ " lua_shared_dict openflare_pow_sessions 20m;",
fmt.Sprintf(" init_worker_by_lua_file %s/%s;", nginxLuaDirPlaceholder, openRestyObservabilityInitLuaPath),
fmt.Sprintf(" log_by_lua_file %s/%s;", nginxLuaDirPlaceholder, openRestyObservabilityLogLuaPath),
"",
diff --git a/openflare_server/service/proxy_route.go b/openflare_server/service/proxy_route.go
index 405cde5d..6ea9f704 100644
--- a/openflare_server/service/proxy_route.go
+++ b/openflare_server/service/proxy_route.go
@@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "net"
"net/url"
"openflare/model"
"regexp"
@@ -53,6 +54,8 @@ type ProxyRouteInput struct {
CachePolicy string `json:"cache_policy"`
CacheRules []string `json:"cache_rules"`
CustomHeaders []ProxyRouteCustomHeaderInput `json:"custom_headers"`
+ PoWEnabled bool `json:"pow_enabled"`
+ PoWConfig string `json:"pow_config"`
Remark string `json:"remark"`
}
@@ -83,6 +86,8 @@ type ProxyRouteView struct {
CacheRuleList []string `json:"cache_rule_list"`
CustomHeaders string `json:"custom_headers"`
CustomHeaderList []ProxyRouteCustomHeaderInput `json:"custom_header_list"`
+ PoWEnabled bool `json:"pow_enabled"`
+ PoWConfig *ProxyRoutePoWConfig `json:"pow_config"`
Remark string `json:"remark"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
@@ -196,6 +201,16 @@ func buildProxyRoute(route *model.ProxyRoute, input ProxyRouteInput) (*model.Pro
if err != nil {
return nil, err
}
+
+ powConfig, err := normalizePoWConfig(input.PoWEnabled, input.PoWConfig)
+ if err != nil {
+ return nil, err
+ }
+ powConfigJSON, err := json.Marshal(powConfig)
+ if err != nil {
+ return nil, err
+ }
+
if !input.EnableHTTPS {
input.RedirectHTTP = false
input.CertID = nil
@@ -267,6 +282,8 @@ func buildProxyRoute(route *model.ProxyRoute, input ProxyRouteInput) (*model.Pro
route.CachePolicy = normalizeCachePolicy(input.CacheEnabled, cachePolicy)
route.CacheRules = string(cacheRulesJSON)
route.CustomHeaders = string(customHeadersJSON)
+ route.PoWEnabled = input.PoWEnabled
+ route.PoWConfig = string(powConfigJSON)
route.Remark = remark
return route, nil
}
@@ -303,6 +320,10 @@ func buildProxyRouteView(route *model.ProxyRoute) (*ProxyRouteView, error) {
if err != nil {
return nil, err
}
+ powConfig, err := decodeStoredPoWConfig(route.PoWEnabled, route.PoWConfig)
+ if err != nil {
+ return nil, err
+ }
certIDs, err := decodeStoredCertIDs(route.CertIDs, route.CertID)
if err != nil {
return nil, err
@@ -343,6 +364,8 @@ func buildProxyRouteView(route *model.ProxyRoute) (*ProxyRouteView, error) {
CacheRuleList: cacheRules,
CustomHeaders: route.CustomHeaders,
CustomHeaderList: customHeaders,
+ PoWEnabled: route.PoWEnabled,
+ PoWConfig: powConfig,
Remark: route.Remark,
CreatedAt: route.CreatedAt,
UpdatedAt: route.UpdatedAt,
@@ -1048,3 +1071,132 @@ func validateOriginHost(raw string) error {
func isUniqueConstraintError(err error) bool {
return err != nil && strings.Contains(strings.ToLower(err.Error()), "unique")
}
+
+// PoW configuration types and validation
+
+type ProxyRoutePoWListConfig struct {
+ IPs []string `json:"ips"`
+ IPCidrs []string `json:"ip_cidrs"`
+ Paths []string `json:"paths"`
+ PathRegexes []string `json:"path_regexes"`
+ UserAgents []string `json:"user_agents"`
+}
+
+type ProxyRoutePoWConfig struct {
+ Difficulty int `json:"difficulty"`
+ Algorithm string `json:"algorithm"`
+ SessionTTL int `json:"session_ttl"`
+ ChallengeTTL int `json:"challenge_ttl"`
+ Whitelist ProxyRoutePoWListConfig `json:"whitelist"`
+ Blacklist ProxyRoutePoWListConfig `json:"blacklist"`
+}
+
+var powAlgorithmValues = map[string]bool{"fast": true, "slow": true}
+
+func defaultPoWConfig() ProxyRoutePoWConfig {
+ return ProxyRoutePoWConfig{
+ Difficulty: 4,
+ Algorithm: "fast",
+ SessionTTL: 86400,
+ ChallengeTTL: 300,
+ Whitelist: ProxyRoutePoWListConfig{IPs: []string{}, IPCidrs: []string{}, Paths: []string{}, PathRegexes: []string{}, UserAgents: []string{}},
+ Blacklist: ProxyRoutePoWListConfig{IPs: []string{}, IPCidrs: []string{}, Paths: []string{}, PathRegexes: []string{}, UserAgents: []string{}},
+ }
+}
+
+func normalizePoWConfig(enabled bool, raw string) (ProxyRoutePoWConfig, error) {
+ if !enabled {
+ return defaultPoWConfig(), nil
+ }
+
+ cfg := defaultPoWConfig()
+ text := strings.TrimSpace(raw)
+ if text != "" && text != "{}" {
+ if err := json.Unmarshal([]byte(text), &cfg); err != nil {
+ return cfg, errors.New("pow_config 格式无效")
+ }
+ }
+
+ if cfg.Difficulty < 1 || cfg.Difficulty > 16 {
+ return cfg, errors.New("pow_config.difficulty 必须在 1-16 之间")
+ }
+ if !powAlgorithmValues[cfg.Algorithm] {
+ return cfg, errors.New("pow_config.algorithm 必须为 fast 或 slow")
+ }
+ if cfg.SessionTTL < 60 {
+ return cfg, errors.New("pow_config.session_ttl 不能小于 60 秒")
+ }
+ if cfg.ChallengeTTL < 30 {
+ return cfg, errors.New("pow_config.challenge_ttl 不能小于 30 秒")
+ }
+
+ for _, cidr := range cfg.Whitelist.IPCidrs {
+ if _, _, err := net.ParseCIDR(cidr); err != nil {
+ return cfg, fmt.Errorf("pow_config 白名单 IP CIDR 格式无效: %s", cidr)
+ }
+ }
+ for _, cidr := range cfg.Blacklist.IPCidrs {
+ if _, _, err := net.ParseCIDR(cidr); err != nil {
+ return cfg, fmt.Errorf("pow_config 黑名单 IP CIDR 格式无效: %s", cidr)
+ }
+ }
+
+ for _, re := range cfg.Whitelist.PathRegexes {
+ if _, err := regexp.Compile(re); err != nil {
+ return cfg, fmt.Errorf("pow_config 白名单路径正则格式无效: %s", re)
+ }
+ }
+ for _, re := range cfg.Blacklist.PathRegexes {
+ if _, err := regexp.Compile(re); err != nil {
+ return cfg, fmt.Errorf("pow_config 黑名单路径正则格式无效: %s", re)
+ }
+ }
+
+ for _, ip := range cfg.Whitelist.IPs {
+ if net.ParseIP(ip) == nil {
+ return cfg, fmt.Errorf("pow_config 白名单 IP 格式无效: %s", ip)
+ }
+ }
+ for _, ip := range cfg.Blacklist.IPs {
+ if net.ParseIP(ip) == nil {
+ return cfg, fmt.Errorf("pow_config 黑名单 IP 格式无效: %s", ip)
+ }
+ }
+
+ type dimension struct {
+ name string
+ wl []string
+ bl []string
+ }
+ dimensions := []dimension{
+ {"IP", cfg.Whitelist.IPs, cfg.Blacklist.IPs},
+ {"IP CIDR", cfg.Whitelist.IPCidrs, cfg.Blacklist.IPCidrs},
+ {"路径", cfg.Whitelist.Paths, cfg.Blacklist.Paths},
+ {"路径正则", cfg.Whitelist.PathRegexes, cfg.Blacklist.PathRegexes},
+ {"User-Agent", cfg.Whitelist.UserAgents, cfg.Blacklist.UserAgents},
+ }
+ for _, dim := range dimensions {
+ if len(dim.wl) > 0 && len(dim.bl) > 0 {
+ return cfg, fmt.Errorf("pow_config %s 不能同时配置白名单和黑名单", dim.name)
+ }
+ }
+
+ return cfg, nil
+}
+
+func decodeStoredPoWConfig(enabled bool, raw string) (*ProxyRoutePoWConfig, error) {
+ if !enabled {
+ cfg := defaultPoWConfig()
+ return &cfg, nil
+ }
+ text := strings.TrimSpace(raw)
+ if text == "" || text == "{}" {
+ cfg := defaultPoWConfig()
+ return &cfg, nil
+ }
+ var cfg ProxyRoutePoWConfig
+ if err := json.Unmarshal([]byte(text), &cfg); err != nil {
+ return nil, errors.New("pow_config 格式无效")
+ }
+ return &cfg, nil
+}
diff --git a/openflare_server/web/app/layout.tsx b/openflare_server/web/app/layout.tsx
index 13700121..ee78dcf9 100644
--- a/openflare_server/web/app/layout.tsx
+++ b/openflare_server/web/app/layout.tsx
@@ -5,18 +5,18 @@ import type { ReactNode } from 'react';
import { AppProviders } from '@/components/providers/app-providers';
import { getThemeInitScript } from '@/lib/theme/theme';
-import './globals.css';
-import { Geist } from "next/font/google";
-import { cn } from "@/lib/utils";
-
-const geist = Geist({subsets:['latin'],variable:'--font-sans'});
-
+import './globals.css';
+import { Geist } from "next/font/google";
+import { cn } from "@/lib/utils";
+
+const geist = Geist({subsets:['latin'],variable:'--font-sans'});
+
export const metadata: Metadata = {
title: {
default: 'OpenFlare 控制台',
template: '%s | OpenFlare',
},
- description: 'OpenFlare 管理端新版工程骨架',
+ description: 'OpenFlare 管理端',
applicationName: 'OpenFlare',
};
@@ -24,8 +24,8 @@ interface RootLayoutProps {
children: ReactNode;
}
-export default function RootLayout({ children }: RootLayoutProps) {
- return (
+export default function RootLayout({ children }: RootLayoutProps) {
+ return (