mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-09-29 05:56:38 +08:00
Compare commits
19 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e9fb331214 | |||
| 5d6d68d0a1 | |||
| c8e2c3620e | |||
| af8e9b477e | |||
| 314f6fd3f4 | |||
| 7eee788720 | |||
| f6e4967a9a | |||
| 7afe4e5d78 | |||
| c6a055d5d3 | |||
| 9a89428405 | |||
| 370d58ac4d | |||
| e85df49962 | |||
| 856e3f46d2 | |||
| 2d6cc908f5 | |||
| 797a15ae70 | |||
| 8730f99fef | |||
| 8ad4defcc7 | |||
| d3d32a6b6b | |||
| 9c57ec2f5c |
+3
-3
@@ -14,7 +14,6 @@ logs
|
||||
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
|
||||
#
|
||||
# Binaries for programs and plugins
|
||||
*.exe
|
||||
*.exe~
|
||||
*.dll
|
||||
*.so
|
||||
@@ -43,8 +42,9 @@ go.work.sum
|
||||
# .idea/
|
||||
# .vscode/
|
||||
|
||||
*.log
|
||||
|
||||
.DS_Store
|
||||
.codex-cache
|
||||
/.gomodcache/
|
||||
*.mmdb
|
||||
|
||||
*-source
|
||||
@@ -1,41 +1,41 @@
|
||||
# AGENTS.md
|
||||
|
||||
本文件是 OpenFlare 的 AI 接手入口,不承载详细设计、规范和计划。接手项目时,先按顺序阅读以下文档:
|
||||
|
||||
1. [docs/design.md](./docs/design.md)
|
||||
作用:理解当前 MVP 的产品范围、系统边界、核心对象和整体架构。
|
||||
|
||||
2. [docs/development-guidelines.md](./docs/development-guidelines.md)
|
||||
作用:理解当前开发规范,包括技术基线、分层约束、数据模型边界、API 约定、Agent 约束、测试要求。
|
||||
|
||||
3. [docs/development-plan.md](./docs/development-plan.md)
|
||||
作用:理解当前开发阶段、实施顺序、阶段目标和验收标准。
|
||||
|
||||
4. [docs/frontend-development-guidelines.md](./docs/frontend-development-guidelines.md)
|
||||
作用:理解新版前端的技术选型、目录分层、组件规范、请求层、状态管理、样式和测试约束。
|
||||
|
||||
5. [docs/deployment.md](./docs/deployment.md)
|
||||
作用:理解当前的部署方式和联调步骤,确保开发过程中产出的功能能够成功部署和验证。
|
||||
|
||||
6. [docs/app-config.md](./docs/app-config.md)
|
||||
作用:系统启动时支持的环境变量和配置项说明,确保开发过程中新增的配置项能够正确使用和文档化。
|
||||
|
||||
|
||||
## 执行要求
|
||||
|
||||
* 如果实现内容超出 `docs/design.md` 的范围,先修改设计文档,再继续编码。
|
||||
* 如果实现方式违反 `docs/development-guidelines.md`,应优先调整方案,而不是绕过规范。
|
||||
* 如果需求与当前开发阶段冲突,优先遵守 `docs/development-plan.md` 的阶段顺序。
|
||||
* 如果任务涉及前端改造或管理端 UI,必须同时阅读 `docs/frontend-development-guidelines.md`。
|
||||
|
||||
|
||||
## 文档维护要求
|
||||
|
||||
当以下内容发生变化时,应同步更新对应文档:
|
||||
|
||||
* 产品启动配置部署方式发生变化时: 更新 `docs/deployment.md`和 `README.md`
|
||||
* 产品范围或系统边界变化:更新 `docs/design.md`
|
||||
* 开发约束、代码规范、接口约定变化:更新 `docs/development-guidelines.md`
|
||||
* 阶段目标、顺序、验收标准变化:更新 `docs/development-plan.md`
|
||||
* 前端目录分层、组件规范、样式体系、测试基线变化:更新 `docs/frontend-development-guidelines.md`
|
||||
* 环境变量或配置项变化:更新 `docs/app-config.md`
|
||||
# AGENTS.md
|
||||
|
||||
本文件是 OpenFlare 的 AI 接手入口,不承载详细设计、规范和计划。接手项目时,先按顺序阅读以下 VitePress 文档源文件:
|
||||
|
||||
1. [docs/design/index.md](./docs/design/index.md)
|
||||
作用:理解当前 MVP 的产品范围、系统边界、核心对象和长期约束。
|
||||
|
||||
2. [docs/design/architecture.md](./docs/design/architecture.md)
|
||||
作用:理解 Server、Agent、OpenResty 与前端的职责边界。
|
||||
|
||||
3. [docs/design/release-model.md](./docs/design/release-model.md)
|
||||
作用:理解配置发布、激活、回滚与 Agent 应用模型。
|
||||
|
||||
4. [docs/design/development.md](./docs/design/development.md)
|
||||
作用:理解当前开发规范、阶段原则、分层约束、数据模型边界、API 约定、Agent 约束、前端规范与测试要求。
|
||||
|
||||
5. [docs/guide/deployment.md](./docs/guide/deployment.md)
|
||||
作用:理解当前部署方式、Agent 接入、升级、卸载和联调步骤。
|
||||
|
||||
6. [docs/reference/configuration.md](./docs/reference/configuration.md)
|
||||
作用:理解系统启动时支持的环境变量、命令行参数、运行时配置项和 Agent 配置字段。
|
||||
|
||||
线上文档入口:https://open-flare.pages.dev
|
||||
|
||||
## 执行要求
|
||||
|
||||
* 如果实现内容超出 [产品边界](./docs/design/index.md),先修改设计文档,再继续编码。
|
||||
* 如果实现方式违反 [开发约束](./docs/design/development.md),应优先调整方案,而不是绕过规范。
|
||||
* 如果需求与当前阶段原则冲突,优先遵守 [开发约束](./docs/design/development.md) 中的变更准入与验收标准。
|
||||
* 如果任务涉及前端改造或管理端 UI,必须同时遵守 [开发约束](./docs/design/development.md) 中的前端规范。
|
||||
|
||||
## 文档维护要求
|
||||
|
||||
当以下内容发生变化时,应同步更新对应 VitePress 页面:
|
||||
|
||||
* 产品范围或系统边界变化:更新 `docs/design/index.md`
|
||||
* 系统结构、模块职责变化:更新 `docs/design/architecture.md`
|
||||
* 发布、同步、回滚模型变化:更新 `docs/design/release-model.md`
|
||||
* 开发约束、代码规范、接口约定、阶段原则、测试基线变化:更新 `docs/design/development.md`
|
||||
* 产品启动、部署、升级、联调方式变化:更新 `docs/guide/deployment.md` 和 `README.md`
|
||||
* 环境变量、命令行参数、运行时配置、Agent 配置变化:更新 `docs/reference/configuration.md`
|
||||
|
||||
@@ -1,11 +1,5 @@
|
||||
<p align="right">
|
||||
<strong>中文</strong> | <a href="./README.en.md">English</a>
|
||||
</p>
|
||||
|
||||
<div align="center">
|
||||
|
||||
[//]: # ( <img src="./openflare_server/web/public/logo.png" width="120" height="120" alt="OpenFlare logo">)
|
||||
|
||||
# OpenFlare
|
||||
|
||||
轻量、自托管的 OpenResty 控制面,用于管理反向代理规则、配置发布、节点同步、TLS 证书与基础可观测能力。
|
||||
@@ -24,65 +18,28 @@
|
||||
</a>
|
||||
</p>
|
||||
|
||||
> [!NOTE]
|
||||
> 当前项目处于快速迭代期,设计与实现均不稳定,请确保使用最新版本并关注更新日志。
|
||||
|
||||
> [!WARNING]
|
||||
> 使用 root 用户初次登录系统后,务必修改默认密码 `123456`,并且确保关闭新用户注册功能。
|
||||
> 使用 `root` 用户初次登录系统后,务必修改默认密码 `123456`。
|
||||
|
||||
## 为什么存在
|
||||
## 文档
|
||||
|
||||
OpenFlare 解决的是一类朴素但高频的运维问题:
|
||||
**https://open-flare.pages.dev**
|
||||
|
||||
* 在一个管理端里维护域名到源站的反向代理规则
|
||||
* 生成完整 OpenResty 配置并以不可变版本发布
|
||||
* 让节点侧 Agent 自动拉取、校验、reload 与失败回滚
|
||||
* 统一托管证书、域名、节点凭证与版本状态
|
||||
* 提供足够实用的总览、节点详情与访问分析能力
|
||||
常用入口:
|
||||
|
||||
* [快速开始](https://open-flare.pages.dev/guide/quick-start)
|
||||
* [部署说明](https://open-flare.pages.dev/guide/deployment)
|
||||
* [配置项参考](https://open-flare.pages.dev/reference/configuration)
|
||||
* [系统设计](https://open-flare.pages.dev/design/)
|
||||
|
||||
## 核心能力
|
||||
|
||||
* 配置版本化:支持预览、发布、激活、历史回滚
|
||||
* Agent 自动应用:周期性同步、落盘、`openresty -t`、`openresty -s reload`、失败自动回滚
|
||||
* OpenResty 托管:统一管理主配置模板、性能参数、缓存参数与受管路由
|
||||
* TLS 与域名管理:支持证书托管、域名资产维护、精确匹配与通配符匹配
|
||||
* 访问与节点观测:支持请求窗口聚合、状态码分布、来源分布、节点资源与健康事件展示
|
||||
|
||||
## 系统架构
|
||||
|
||||
```text
|
||||
OpenFlare Server (Gin + GORM + SQLite/PostgreSQL + Web UI)
|
||||
|
|
||||
| HTTP API / Config Pull
|
||||
v
|
||||
OpenFlare Agent (register / heartbeat / sync / apply / update)
|
||||
|
|
||||
v
|
||||
Local OpenResty or Docker OpenResty
|
||||
|
|
||||
v
|
||||
Origin
|
||||
```
|
||||
|
||||
职责划分:
|
||||
|
||||
* `openflare_server`:管理端 UI、管理 API、Agent API、配置渲染、版本发布与状态存储
|
||||
* `openflare_agent`:节点注册、心跳、同步、本地写入、校验、reload、回滚、自更新
|
||||
* `openflare_server/web`:新版管理端前端,静态导出后由 Go Server 托管
|
||||
|
||||
## 界面预览
|
||||
|
||||
### 仪表盘总览
|
||||
|
||||

|
||||
|
||||
### 节点详情
|
||||
|
||||

|
||||
|
||||
### 配置新增
|
||||
|
||||

|
||||
* 反向代理网站配置与多域名绑定
|
||||
* 配置预览、发布、激活与历史回滚
|
||||
* Agent 自动注册、心跳、同步、校验、reload 与失败回滚
|
||||
* OpenResty 主配置、性能参数、缓存参数与 Lua 资源托管
|
||||
* TLS 证书、域名资产、节点凭证与版本状态管理
|
||||
* 请求聚合、访问分析、资源快照、健康事件与节点详情
|
||||
|
||||
## 快速开始
|
||||
|
||||
@@ -134,7 +91,7 @@ docker compose up -d
|
||||
* 用户名:`root`
|
||||
* 密码:`123456`
|
||||
|
||||
### 2. 接入 Agent
|
||||
### 2. 安装 Agent
|
||||
|
||||
**注意:** 安装agent前需确保存已经安装了Docker, 虽然支持裸Openresty,但未得到充分验证,可能存在未知问题.
|
||||
|
||||
@@ -156,6 +113,8 @@ curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/inst
|
||||
|
||||
安装脚本默认写入 `/opt/openflare-agent`,创建 `openflare-agent.service`,并可重复执行以重装或升级 Agent。
|
||||
|
||||
### 3. 卸载 Agent
|
||||
|
||||
如需彻底卸载 Agent 并清空本地数据,可执行:
|
||||
|
||||
```bash
|
||||
@@ -167,7 +126,7 @@ curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/unin
|
||||
* Docker 模式:删除对应 OpenResty 容器,并尝试移除镜像
|
||||
* 本机 `openresty_path` 模式:不改动本机 OpenResty,只提示用户手动卸载
|
||||
|
||||
### 3. 发布第一份配置
|
||||
### 4. 发布第一份配置
|
||||
|
||||
1. 登录管理端并新增反代规则
|
||||
2. 在发布前查看预览或变更摘要
|
||||
@@ -176,42 +135,20 @@ curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/unin
|
||||
|
||||
版本号格式固定为 `YYYYMMDD-NNN`,历史版本不可变,回滚通过重新激活旧版本完成。
|
||||
|
||||
## 仓库结构
|
||||
|
||||
* `openflare_server`:Gin + GORM + SQLite/PostgreSQL 单体控制面
|
||||
* `openflare_server/web`:Next.js 15 App Router 管理端前端
|
||||
* `openflare_agent`:Go 单体 Agent
|
||||
* `scripts`:安装脚本与辅助脚本
|
||||
* `docs`:设计、规范、部署与配置文档
|
||||
## 界面预览
|
||||
|
||||
## 本地开发
|
||||
### 仪表盘总览
|
||||
|
||||
### Server
|
||||

|
||||
|
||||
```bash
|
||||
cd openflare_server
|
||||
export SESSION_SECRET='replace-with-random-string'
|
||||
export SQLITE_PATH='./openflare.db'
|
||||
# 可选:设置 DSN 或 SQL_DSN 后切换到 PostgreSQL。
|
||||
# 如果 PostgreSQL 为空且 ./openflare.db 存在,启动时会自动迁移 SQLite 数据。
|
||||
# export DSN='postgres://openflare:secret@127.0.0.1:5432/openflare?sslmode=disable'
|
||||
go run .
|
||||
```
|
||||
### 节点详情
|
||||
|
||||
### Frontend
|
||||

|
||||
|
||||
```bash
|
||||
cd openflare_server/web
|
||||
pnpm install
|
||||
pnpm dev
|
||||
```
|
||||
### 配置新增
|
||||
|
||||
### Agent
|
||||
|
||||
```bash
|
||||
cd openflare_agent
|
||||
go run ./cmd/agent -config /path/to/agent.json
|
||||
```
|
||||

|
||||
|
||||
## 管理端与接口
|
||||
|
||||
@@ -226,6 +163,7 @@ go run ./cmd/agent -config /path/to/agent.json
|
||||
* 用户管理
|
||||
* 设置
|
||||
* 版本更新
|
||||
* POW 规则
|
||||
|
||||
登录管理端后,可访问 Swagger UI:`/swagger/index.html`
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/coverage
|
||||
/src/client/shared.ts
|
||||
/src/node/shared.ts
|
||||
*.log
|
||||
*.tgz
|
||||
.DS_Store
|
||||
.idea
|
||||
.temp
|
||||
.vite_opt_cache
|
||||
.vscode
|
||||
dist
|
||||
cache
|
||||
temp
|
||||
examples-temp
|
||||
node_modules
|
||||
pnpm-global
|
||||
TODOs.md
|
||||
*.timestamp-*.mjs
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"plugins": {
|
||||
"postcss-rtlcss": {
|
||||
"ltrPrefix": ":where([dir=\"ltr\"])",
|
||||
"rtlPrefix": ":where([dir=\"rtl\"])"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { defineConfig, type HeadConfig, resolveSiteDataByRoute } from 'vitepress'
|
||||
import llmstxt from 'vitepress-plugin-llms'
|
||||
|
||||
const prod = !!process.env.NETLIFY
|
||||
|
||||
export default defineConfig({
|
||||
title: 'OpenFlare',
|
||||
lastUpdated: true,
|
||||
cleanUrls: true,
|
||||
metaChunk: true,
|
||||
srcExclude: [
|
||||
'zh/**',
|
||||
'components/**',
|
||||
'snippets/**'
|
||||
],
|
||||
|
||||
markdown: {
|
||||
math: true
|
||||
},
|
||||
|
||||
sitemap: {
|
||||
hostname: 'https://openflare.io'
|
||||
},
|
||||
|
||||
head: [
|
||||
['meta', { name: 'theme-color', content: '#10b981' }],
|
||||
['meta', { property: 'og:type', content: 'website' }],
|
||||
['meta', { property: 'og:site_name', content: 'OpenFlare' }],
|
||||
['meta', { property: 'og:url', content: 'https://openflare.io/' }]
|
||||
],
|
||||
|
||||
themeConfig: {
|
||||
socialLinks: [
|
||||
{ icon: 'github', link: 'https://github.com/Rain-kl/OpenFlare' }
|
||||
],
|
||||
search: {
|
||||
provider: 'local'
|
||||
}
|
||||
},
|
||||
|
||||
locales: {
|
||||
root: { label: '简体中文', lang: 'zh-Hans', dir: 'ltr' },
|
||||
en: { label: 'English', lang: 'en-US', dir: 'ltr' }
|
||||
},
|
||||
|
||||
vite: {
|
||||
plugins: [
|
||||
prod &&
|
||||
llmstxt({
|
||||
workDir: '.',
|
||||
ignoreFiles: ['index.md']
|
||||
})
|
||||
],
|
||||
experimental: {
|
||||
enableNativePlugin: true
|
||||
}
|
||||
},
|
||||
|
||||
transformPageData: prod
|
||||
? (pageData, ctx) => {
|
||||
const site = resolveSiteDataByRoute(
|
||||
ctx.siteConfig.site,
|
||||
pageData.relativePath
|
||||
)
|
||||
const title = `${pageData.title || site.title} | ${
|
||||
pageData.description || site.description
|
||||
}`
|
||||
;((pageData.frontmatter.head ??= []) as HeadConfig[]).push(
|
||||
['meta', { property: 'og:locale', content: site.lang }],
|
||||
['meta', { property: 'og:title', content: title }]
|
||||
)
|
||||
}
|
||||
: undefined
|
||||
})
|
||||
@@ -0,0 +1,4 @@
|
||||
import Theme from 'vitepress/theme'
|
||||
import './styles.css'
|
||||
|
||||
export default Theme
|
||||
@@ -0,0 +1,20 @@
|
||||
:root {
|
||||
--vp-c-brand-1: #059669;
|
||||
--vp-c-brand-2: #10b981;
|
||||
--vp-c-brand-3: #34d399;
|
||||
--vp-c-brand-soft: rgba(16, 185, 129, 0.16);
|
||||
--vp-home-hero-name-color: transparent;
|
||||
--vp-home-hero-name-background: linear-gradient(120deg, #059669, #2563eb);
|
||||
--vp-font-family-base:
|
||||
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
|
||||
'Segoe UI', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji';
|
||||
}
|
||||
|
||||
.VPHomeHero .text,
|
||||
.VPHomeHero .tagline {
|
||||
max-width: 760px;
|
||||
}
|
||||
|
||||
.VPFeature {
|
||||
border-radius: 8px;
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 147 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 70 KiB |
+109
@@ -0,0 +1,109 @@
|
||||
import { defineAdditionalConfig, type DefaultTheme } from 'vitepress'
|
||||
|
||||
export default defineAdditionalConfig({
|
||||
description:
|
||||
'OpenFlare 是轻量、自托管的 OpenResty 控制面,用于管理反向代理、配置发布、节点同步、TLS 证书与基础观测。',
|
||||
|
||||
themeConfig: {
|
||||
nav: nav(),
|
||||
|
||||
sidebar: {
|
||||
'/guide/': { base: '/guide/', items: sidebarGuide() },
|
||||
'/reference/': { base: '/reference/', items: sidebarReference() },
|
||||
'/design/': { base: '/design/', items: sidebarDesign() }
|
||||
},
|
||||
|
||||
editLink: {
|
||||
pattern: 'https://github.com/Rain-kl/OpenFlare/edit/main/docs/:path',
|
||||
text: '在 GitHub 上编辑此页面'
|
||||
},
|
||||
|
||||
footer: {
|
||||
message: '基于 Apache License 2.0 发布',
|
||||
copyright: 'Copyright © OpenFlare contributors'
|
||||
},
|
||||
|
||||
docFooter: {
|
||||
prev: '上一页',
|
||||
next: '下一页'
|
||||
},
|
||||
|
||||
outline: {
|
||||
label: '页面导航'
|
||||
},
|
||||
|
||||
lastUpdated: {
|
||||
text: '最后更新于'
|
||||
},
|
||||
|
||||
notFound: {
|
||||
title: '页面未找到',
|
||||
quote: '这份文档还没有对应页面。',
|
||||
linkLabel: '前往首页',
|
||||
linkText: '回到 OpenFlare 文档'
|
||||
},
|
||||
|
||||
langMenuLabel: '语言',
|
||||
returnToTopLabel: '回到顶部',
|
||||
sidebarMenuLabel: '菜单',
|
||||
darkModeSwitchLabel: '主题',
|
||||
lightModeSwitchTitle: '切换到浅色模式',
|
||||
darkModeSwitchTitle: '切换到深色模式',
|
||||
skipToContentLabel: '跳转到内容'
|
||||
}
|
||||
})
|
||||
|
||||
function nav(): DefaultTheme.NavItem[] {
|
||||
return [
|
||||
{ text: '指南', link: '/guide/', activeMatch: '/guide/' },
|
||||
{ text: '参考', link: '/reference/', activeMatch: '/reference/' },
|
||||
{ text: '设计', link: '/design/', activeMatch: '/design/' }
|
||||
]
|
||||
}
|
||||
|
||||
function sidebarGuide(): DefaultTheme.SidebarItem[] {
|
||||
return [
|
||||
{
|
||||
text: '指南',
|
||||
items: [
|
||||
{ text: '概览', link: '' },
|
||||
{ text: '快速开始', link: 'quick-start' },
|
||||
{ text: '部署说明', link: 'deployment' },
|
||||
{ text: 'SSO 登录配置', link: 'sso' },
|
||||
{ text: '启动 Server', link: 'server' },
|
||||
{ text: '接入 Agent', link: 'agent' },
|
||||
{ text: '发布第一份配置', link: 'first-site' },
|
||||
{ text: '升级与维护', link: 'upgrade' }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
function sidebarReference(): DefaultTheme.SidebarItem[] {
|
||||
return [
|
||||
{
|
||||
text: '参考',
|
||||
items: [
|
||||
{ text: '概览', link: '' },
|
||||
{ text: '配置项', link: 'configuration' },
|
||||
{ text: '命令与脚本', link: 'cli' },
|
||||
{ text: 'API 约定', link: 'api' },
|
||||
{ text: '仓库结构', link: 'repository' }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
function sidebarDesign(): DefaultTheme.SidebarItem[] {
|
||||
return [
|
||||
{
|
||||
text: '设计',
|
||||
items: [
|
||||
{ text: '产品边界', link: '' },
|
||||
{ text: '系统架构', link: 'architecture' },
|
||||
{ text: '发布模型', link: 'release-model' },
|
||||
{ text: '开发约束', link: 'development' }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
-181
@@ -1,181 +0,0 @@
|
||||
# OpenFlare 设计基线
|
||||
|
||||
本文档定义 OpenFlare `1.0.0` 之后仍然有效的产品边界、系统结构与长期约束。第六版已经完成并并入正式版;过程性设计不再在这里维护。
|
||||
|
||||
## 1. 产品定位
|
||||
|
||||
OpenFlare 是一套自托管的 OpenResty 控制面,面向单团队或单组织内部运维场景,解决反向代理配置、节点同步、证书托管与基础观测的统一管理问题。
|
||||
|
||||
当前稳定能力包括:
|
||||
|
||||
* 反代规则管理
|
||||
* 网站级配置与多域名绑定
|
||||
* 源站管理与复用
|
||||
* 配置预览、发布、激活与回滚
|
||||
* Agent 注册、心跳、同步、应用结果上报
|
||||
* OpenResty 主配置模板、性能参数与缓存参数托管
|
||||
* HTTPS/TLS 与域名资产管理
|
||||
* 节点请求聚合、资源快照、健康事件与看板展示
|
||||
* 节点管理、令牌体系、部署与更新链路
|
||||
* 基于 Next.js 的正式管理端前端
|
||||
|
||||
默认工作方式:
|
||||
|
||||
* 所有节点消费同一份全局激活版本
|
||||
* Server 保存配置与状态,不直接 SSH 管理节点
|
||||
* Agent 是节点侧唯一受控落地入口
|
||||
|
||||
## 3. 技术基线
|
||||
|
||||
### 3.1 Server
|
||||
|
||||
`openflare_server` 继续作为单体控制面:
|
||||
|
||||
* Gin
|
||||
* GORM
|
||||
* SQLite / PostgreSQL
|
||||
* 现有登录与 Session 体系
|
||||
* 托管 `openflare_server/web` 静态构建产物
|
||||
|
||||
### 3.2 Agent
|
||||
|
||||
`openflare_agent` 继续作为 Go 单体程序:
|
||||
|
||||
* 单二进制
|
||||
* 节点本地执行
|
||||
* `openresty_path` 优先
|
||||
* 未配置 `openresty_path` 时默认使用 Docker OpenResty
|
||||
|
||||
### 3.3 Frontend
|
||||
|
||||
`openflare_server/web` 是正式前端基线:
|
||||
|
||||
* Next.js App Router
|
||||
* React 19
|
||||
* TypeScript
|
||||
* Tailwind CSS
|
||||
* 静态导出后由 Go Server 托管
|
||||
|
||||
## 4. 总体架构
|
||||
|
||||
```text
|
||||
OpenFlare Server (Gin + SQLite/PostgreSQL + Web UI)
|
||||
|
|
||||
| HTTP API / Config Pull
|
||||
v
|
||||
OpenFlare Agent (register / heartbeat / sync / apply / update)
|
||||
|
|
||||
v
|
||||
Local OpenResty or Docker OpenResty
|
||||
|
|
||||
v
|
||||
Origin
|
||||
```
|
||||
|
||||
职责分工:
|
||||
|
||||
* Server 负责配置、版本、节点、设置、证书、管理端 UI 与聚合查询
|
||||
* Agent 负责本地写入、校验、reload、回滚、自更新与轻量采集
|
||||
* 发布通过“生成完整版本并激活”完成
|
||||
* 历史版本不可变
|
||||
* heartbeat 响应返回激活版本摘要,Agent 仅在不一致时拉取完整配置
|
||||
|
||||
## 5. 核心对象
|
||||
|
||||
当前有效实体:
|
||||
|
||||
* `proxy_routes`
|
||||
* `origins`
|
||||
* `config_versions`
|
||||
* `nodes`
|
||||
* `node_system_profiles`
|
||||
* `apply_logs`
|
||||
* `tls_certificates`
|
||||
* `managed_domains`
|
||||
* `node_request_reports`
|
||||
* `node_access_logs`
|
||||
* `node_metric_snapshots`
|
||||
* `traffic_analytics_rollups`
|
||||
* `node_health_events`
|
||||
|
||||
稳定约束:
|
||||
|
||||
* `proxy_routes` 从“单域名规则”升级为“网站配置”聚合对象;一条记录对应一个网站,可绑定一个或多个域名,并共享一组站点级配置
|
||||
* `proxy_routes.site_name` 是网站的业务唯一标识;新建时默认取 `domains[0]`,后续允许独立维护,不随域名改动自动重写
|
||||
* `proxy_routes.domains` 至少包含一个域名,且 `domains[0]` 作为主域名;任一域名全局只能属于一个 `proxy_routes`
|
||||
* 为兼容历史数据,迁移期可保留 `proxy_routes.domain` 作为 `domains[0]` 的镜像字段,但业务读写与后续扩展必须以 `site_name` + `domains` 为准
|
||||
* `origins` 只保存源站地址、展示名与备注,不承载协议、端口、路径、权重或健康检查策略
|
||||
* `proxy_routes` 可选关联一个 `origins` 记录,用于复用源站地址;规则仍保存完整 `origin_url` 快照以参与渲染与版本快照
|
||||
* `proxy_routes` 至少包含一个上游地址;为兼容历史数据保留 `origin_url` 主上游字段,也允许在同一规则内补充多个上游做负载均衡
|
||||
* `proxy_routes` 上游统一渲染为带 keepalive 的 named `upstream`;单上游可附带 base path 或 query 并在 `proxy_pass` 中追加,多上游仍限定为纯 `scheme://host[:port]`
|
||||
* `proxy_routes.origin_host` 为可选字段,用于回源时覆盖 `Host` 请求头;未设置时默认透传访问域名
|
||||
* 网站级流量限制、反向代理与缓存配置当前按站点共享,不在同一网站内做域名级差异化配置;但 HTTPS 允许在同一站点内按域名绑定证书
|
||||
* `proxy_routes.domain_cert_ids` 用于记录与 `domains` 平行的域名证书绑定;值为 `0` 表示该域名不启用 HTTPS,仅保留 HTTP
|
||||
* 发布渲染时,带证书的域名按证书分组输出独立 `443 ssl` `server` 块;未绑定证书的域名不得被自动带入 HTTPS
|
||||
* 发布渲染时必须将 `proxy_routes.domains` 中的全部域名一并纳入同一站点配置,避免同站点在版本快照中被拆散
|
||||
* 所有上游地址都必须为合法 `http://` 或 `https://`
|
||||
* `config_versions` 必须保存完整快照、渲染结果与 `checksum`
|
||||
* 全局同时只能有一个激活版本
|
||||
* 回滚通过重新激活旧版本实现
|
||||
* `nodes` 只承载控制面状态与低频摘要,不承载高频观测事实
|
||||
* 指标、趋势和访问分析优先使用服务端聚合结果,而不是前端临时统计
|
||||
* 访问明细只保留受控时间窗口,不演变成通用日志平台
|
||||
|
||||
## 6. 发布模型
|
||||
|
||||
标准链路:
|
||||
|
||||
```text
|
||||
修改规则 -> 预览/查看 diff -> 发布 -> 生成完整配置版本 -> 激活版本 -> Agent 拉取 -> 本地应用 -> 上报结果
|
||||
```
|
||||
|
||||
发布规则:
|
||||
|
||||
1. 读取全部启用的 `proxy_routes`
|
||||
2. 读取 Server 侧 OpenResty 主配置与结构化参数
|
||||
3. 渲染完整 OpenResty 配置
|
||||
4. 计算 `checksum`
|
||||
5. 写入 `config_versions`
|
||||
6. 切换激活版本
|
||||
7. Agent 在后续 heartbeat 中发现并应用
|
||||
|
||||
版本号格式固定为 `YYYYMMDD-NNN`。
|
||||
|
||||
## 7. 模块边界
|
||||
|
||||
### 7.1 `openflare_server`
|
||||
|
||||
负责:
|
||||
|
||||
* 管理端 UI 与 API
|
||||
* Agent API
|
||||
* 配置渲染与版本发布
|
||||
* 数据存储与聚合查询
|
||||
* OpenResty 主配置模板、性能参数与缓存参数管理
|
||||
|
||||
### 7.2 `openflare_agent`
|
||||
|
||||
负责:
|
||||
|
||||
* 首次注册与凭证置换
|
||||
* 周期性心跳与同步
|
||||
* 主配置、路由配置、证书与 Lua 资源写入
|
||||
* 执行 `openresty -t` / `openresty -s reload`
|
||||
* 失败回滚
|
||||
* 对已失败并回退的目标版本做本地熔断,直到控制面出现新的激活版本
|
||||
* 节点观测采集与结果上报
|
||||
|
||||
### 7.3 `openflare_server/web`
|
||||
|
||||
负责:
|
||||
|
||||
* 管理端页面、布局、交互与主题
|
||||
* 总览、节点详情、规则、版本、节点、证书、域名、用户与设置页面
|
||||
* 统一请求层与前端状态管理
|
||||
|
||||
## 8. 文档维护原则
|
||||
|
||||
* 产品范围或系统边界变化时更新本文档
|
||||
* 已完成阶段不再以“版本计划”形式回填
|
||||
* 新阶段开始前,先补设计,再进入实现
|
||||
* 涉及网站级规则改造的详细需求与实施顺序,见 [docs/website-configuration-redesign.md](./website-configuration-redesign.md)
|
||||
@@ -0,0 +1,57 @@
|
||||
# 系统架构
|
||||
|
||||
OpenFlare 由 Server、Agent 与节点本地 OpenResty 组成。
|
||||
|
||||
```text
|
||||
OpenFlare Server (Gin + SQLite/PostgreSQL + Web UI)
|
||||
|
|
||||
| HTTP API / Config Pull
|
||||
v
|
||||
OpenFlare Agent (register / heartbeat / sync / apply / update)
|
||||
|
|
||||
v
|
||||
Local OpenResty or Docker OpenResty
|
||||
|
|
||||
v
|
||||
Origin
|
||||
```
|
||||
|
||||
## Server
|
||||
|
||||
`openflare_server` 是单体控制面:
|
||||
|
||||
* Gin
|
||||
* GORM
|
||||
* SQLite / PostgreSQL
|
||||
* 现有登录与 Session 体系
|
||||
* 认证源与外部账号绑定
|
||||
* 托管 `openflare_server/web` 静态构建产物
|
||||
|
||||
Server 负责管理端 UI 与 API、Agent API、配置渲染、版本发布、数据存储与聚合查询。
|
||||
|
||||
认证源登录由 Server 统一处理。管理端配置 `github` 或 `oidc` 认证源后,登录页从 `/api/status` 获取已启用认证源列表;OAuth/OIDC callback 仍回到管理端前端页面,再由前端调用 Server API 完成 code 交换、账号绑定与 Session 建立。
|
||||
|
||||
## Agent
|
||||
|
||||
`openflare_agent` 是 Go 单体程序:
|
||||
|
||||
* 单二进制
|
||||
* 节点本地执行
|
||||
* 优先使用 `openresty_path`
|
||||
* 未配置 `openresty_path` 时默认使用 Docker OpenResty
|
||||
|
||||
Agent 负责首次注册、周期性心跳、配置同步、文件写入、`openresty -t`、reload、失败回滚、自更新与轻量采集。
|
||||
|
||||
## Frontend
|
||||
|
||||
`openflare_server/web` 是正式管理端前端:
|
||||
|
||||
* Next.js App Router
|
||||
* React 19
|
||||
* TypeScript
|
||||
* Tailwind CSS
|
||||
* 静态导出后由 Go Server 托管
|
||||
|
||||
## 核心对象
|
||||
|
||||
当前有效实体包括 `proxy_routes`、`origins`、`config_versions`、`nodes`、`auth_sources`、`external_accounts`、`apply_logs`、`tls_certificates`、`managed_domains`、`node_request_reports`、`node_access_logs`、`node_metric_snapshots`、`traffic_analytics_rollups` 与 `node_health_events`。
|
||||
@@ -0,0 +1,293 @@
|
||||
# 开发约束
|
||||
|
||||
本文档融合原开发规范、前端规范与开发计划,是 OpenFlare `1.0.0` 之后的工程约束入口。
|
||||
|
||||
## 当前结论
|
||||
|
||||
* 第一版至第六版的主线能力已经全部完成。
|
||||
* `1.0.0` 是当前正式基线。
|
||||
* 已完成阶段的过程性任务以代码、测试与 Git 历史为准。
|
||||
* 新工作优先以缺陷修复、可维护性改进、文档与测试补强为主。
|
||||
|
||||
当前开发优先级:
|
||||
|
||||
1. 稳定性。
|
||||
2. 升级与回滚链路可靠性。
|
||||
3. 文档准确性。
|
||||
4. 测试覆盖补强。
|
||||
5. 在既有边界内的小步迭代。
|
||||
|
||||
## 变更准入
|
||||
|
||||
新需求进入实现前,按以下顺序判断:
|
||||
|
||||
1. 是否符合 [产品边界](./)。
|
||||
2. 是否符合本文档的后端、Agent 与前端约束。
|
||||
3. 是否会破坏现有发布、同步、回滚或升级主链路。
|
||||
4. 是否需要同步更新部署、配置、README 或文档站页面。
|
||||
|
||||
如果需求超出边界或引入新基础设施,应先更新设计文档,再开始实现。
|
||||
|
||||
任何合入正式基线的改动,至少应满足:
|
||||
|
||||
* 不破坏 Agent 心跳、同步、发布与回滚主链路。
|
||||
* 不破坏现有 OpenResty 主配置托管模型。
|
||||
* 不降低总览、节点详情与访问分析的既有可用性。
|
||||
* 有与风险相称的测试或联调验证。
|
||||
* 文档与代码保持一致。
|
||||
|
||||
## 技术基线
|
||||
|
||||
Server:
|
||||
|
||||
* Go 1.25+
|
||||
* Gin
|
||||
* GORM
|
||||
* SQLite / PostgreSQL
|
||||
* 现有登录体系
|
||||
|
||||
Agent:
|
||||
*
|
||||
* 单二进制
|
||||
* 节点本地执行
|
||||
* `openresty_path` 优先
|
||||
* 无 `openresty_path` 时默认 Docker OpenResty
|
||||
|
||||
Frontend:
|
||||
|
||||
* Next.js 15 App Router
|
||||
* React 19
|
||||
* TypeScript 5
|
||||
* Tailwind CSS 4
|
||||
* TanStack Query
|
||||
* React Hook Form + Zod
|
||||
* Zustand 仅用于轻量客户端状态
|
||||
* ESLint + Prettier
|
||||
* Vitest + Testing Library + Playwright
|
||||
* pnpm
|
||||
|
||||
## Server 分层
|
||||
|
||||
| 目录 | 职责 |
|
||||
| --- | --- |
|
||||
| `controller/` | 参数解析、调用 service、返回响应 |
|
||||
| `service/` | 业务逻辑、校验、事务编排、渲染 |
|
||||
| `model/` | 模型定义与持久化 |
|
||||
| `router/` | 路由注册 |
|
||||
| `middleware/` | 认证、鉴权、限流等横切逻辑 |
|
||||
| `common/` | 配置、全局状态与初始化入口 |
|
||||
| `utils/` | 纯工具函数与通用 helper |
|
||||
|
||||
禁止在 `controller/` 堆积业务逻辑,禁止在 `middleware/` 实现业务流程,禁止为简单需求新增平台层抽象。
|
||||
|
||||
## Agent 分层
|
||||
|
||||
Agent 保持现有模块边界:
|
||||
|
||||
* `config`
|
||||
* `heartbeat`
|
||||
* `sync`
|
||||
* `openresty` / `nginx`
|
||||
* `state`
|
||||
* `httpclient`
|
||||
* `protocol`
|
||||
* `internal/updater`
|
||||
|
||||
要求:
|
||||
|
||||
* 每个模块职责单一。
|
||||
* 外部命令调用集中封装。
|
||||
* 状态落盘与配置落盘分离。
|
||||
|
||||
## Frontend 分层
|
||||
|
||||
推荐目录:
|
||||
|
||||
```text
|
||||
app/
|
||||
components/
|
||||
features/
|
||||
lib/
|
||||
hooks/
|
||||
store/
|
||||
types/
|
||||
styles/
|
||||
tests/
|
||||
```
|
||||
|
||||
职责约束:
|
||||
|
||||
* `app/`:路由、布局、页面组装。
|
||||
* `features/`:按业务域组织模块。
|
||||
* `components/`:跨 feature 复用组件。
|
||||
* `lib/`:请求客户端、环境变量、工具函数、常量。
|
||||
* `store/`:少量跨页面 UI 状态。
|
||||
* `types/`:共享类型定义。
|
||||
|
||||
页面文件只负责获取路由参数、组织页面结构、调用 feature 组件;不应手写复杂 API 细节、复杂表单校验逻辑或维护大量彼此耦合的局部状态。
|
||||
|
||||
## 数据模型规范
|
||||
|
||||
当前有效实体:
|
||||
|
||||
* `proxy_routes`
|
||||
* `origins`
|
||||
* `config_versions`
|
||||
* `nodes`
|
||||
* `auth_sources`
|
||||
* `external_accounts`
|
||||
* `node_system_profiles`
|
||||
* `apply_logs`
|
||||
* `tls_certificates`
|
||||
* `managed_domains`
|
||||
* `node_request_reports`
|
||||
* `node_access_logs`
|
||||
* `node_metric_snapshots`
|
||||
* `traffic_analytics_rollups`
|
||||
* `node_health_events`
|
||||
* `options`
|
||||
|
||||
通用约束:
|
||||
|
||||
* 不新增平台化对象,除非设计文档明确要求。
|
||||
* `origins` 仅作为可复用源站地址目录,字段保持轻量。
|
||||
* `proxy_routes` 以“网站配置”作为聚合边界,必须包含唯一 `site_name` 与非空 `domains` 列表。
|
||||
* `proxy_routes.domains` 中的每个域名都必须全局唯一,列表第一项视为主域名。
|
||||
* `proxy_routes` 继续允许保存一个或多个上游地址用于负载均衡,但不引入独立 `origin_pool`。
|
||||
* 遗留 `domain` 字段只能作为 `domains[0]` 的兼容镜像;新代码不得继续以该字段作为唯一业务输入。
|
||||
* `proxy_routes` 如关联 `origins`,必须同时保存可直接渲染的 `origin_url`。
|
||||
* 上游统一使用 named `upstream` + keepalive;单上游如带 base path 或 query,应在 `proxy_pass` 上补回 URI,多上游仅允许纯 `scheme://host[:port]`。
|
||||
* 流量限制、反向代理与缓存配置当前都归属站点级 `proxy_routes`。
|
||||
* HTTPS 证书绑定必须通过与 `domains` 平行的 `domain_cert_ids` 逐域名保存;未绑定证书的域名不得参与 HTTPS 渲染。
|
||||
* `config_versions` 必须保存完整快照与渲染结果。
|
||||
* 全局同时只能有一个激活版本。
|
||||
* 回滚通过重新激活旧版本实现。
|
||||
* `nodes` 只保留控制面状态与低频摘要。
|
||||
* 观测数据必须按节点与时间窗口关联,快照与聚合结果采用追加式模型。
|
||||
* 原始访问明细必须有受控保留策略。
|
||||
* `auth_sources` 仅保存管理端第三方登录源配置,当前支持 `github` 与 `oidc`。
|
||||
* `external_accounts` 是第三方账号与本地用户的唯一绑定来源;旧 `users.github_id` 仅用于兼容迁移,不得作为新登录流程的业务输入。
|
||||
|
||||
## 数据库迁移
|
||||
|
||||
任何涉及表结构、索引、列类型、分表规则或内部持久化元数据的修改,都必须同步提升数据库版本号。
|
||||
|
||||
数据库版本号定义在 `openflare_server/model`,不得只依赖 `AutoMigrate` 隐式升级存量数据库。
|
||||
|
||||
每次提升数据库版本号时,必须补充从上一版本升级到新版本的显式迁移方法。迁移方法必须包含升级后的校验逻辑;只有校验通过,才能写入新的数据库版本记录。
|
||||
|
||||
新包启动后必须先检查数据库当前版本,再按顺序逐步升级到目标版本;禁止跳过中间升级步骤直接写目标版本。
|
||||
|
||||
空库初始化可以直接建立当前版本结构,但初始化完成后仍必须执行同版本校验,并落库当前数据库版本。
|
||||
|
||||
如果迁移失败或校验失败,启动流程必须中止,且不得提升数据库版本记录。涉及数据库版本变更的提交,必须补充对应的迁移测试或等效回归测试。
|
||||
|
||||
## API 与鉴权
|
||||
|
||||
管理端与 Agent API 统一使用 JSON。成功与失败都必须返回清晰 `message`:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "",
|
||||
"data": {}
|
||||
}
|
||||
```
|
||||
|
||||
约定:
|
||||
|
||||
* Agent API 固定放在 `/api/agent/*`。
|
||||
* 总览与节点详情优先使用专用聚合接口。
|
||||
* 管理端变更类接口统一使用 `POST`;只读接口使用 `GET`。
|
||||
* 管理端继续复用现有登录、角色与 Session。
|
||||
* 第三方登录统一通过认证源 API 进入,认证源管理接口必须要求 Root Session。
|
||||
* `/api/status` 只能返回已启用认证源的公开字段,不得返回 Client Secret。
|
||||
* 第三方账号未绑定且注册关闭时,应提供绑定已有账号流程,不得自动创建用户。
|
||||
* Agent 正式请求统一使用节点专属 `agent_token`。
|
||||
* 首次接入可使用全局 `discovery_token`。
|
||||
* Agent 请求头统一使用 `X-Agent-Token`。
|
||||
|
||||
禁止暴露远程 shell 或任意命令执行入口,禁止在日志中打印完整 Token,禁止绕过占位符约束保存不可渲染的主配置模板。
|
||||
|
||||
## 发布与运行
|
||||
|
||||
发布逻辑必须保持:
|
||||
|
||||
* 发布时读取全部启用的 `proxy_routes`。
|
||||
* 同时读取 OpenResty 主配置参数、反代性能参数与缓存参数。
|
||||
* 生成完整 OpenResty 配置。
|
||||
* 计算 `checksum`。
|
||||
* 写入 `config_versions`。
|
||||
* 通过切换 `is_active` 激活版本。
|
||||
|
||||
版本约束:
|
||||
|
||||
* 版本号格式固定为 `YYYYMMDD-NNN`。
|
||||
* 不在线修改历史版本。
|
||||
* 不做按节点分组的差异化版本。
|
||||
* 预览与 diff 是只读能力,不产生发布记录。
|
||||
|
||||
Agent 必须满足:
|
||||
|
||||
* 启动后读取或生成本地 `node_id`。
|
||||
* 周期性心跳与同步。
|
||||
* 常规同步优先依据 heartbeat 返回的版本摘要判断。
|
||||
* 发现新版本时先备份旧文件。
|
||||
* 写入主配置、路由配置与必要证书文件。
|
||||
* 写入新配置后以运行态恢复为目标执行激活,Docker 模式优先重建容器并确认容器保持运行。
|
||||
* 新配置激活失败时必须先尝试用目标配置恢复运行,再回滚到旧配置并重新拉起 OpenResty。
|
||||
* 回滚后 OpenResty 恢复正常时上报警告;回滚后仍无法恢复运行时上报失败。
|
||||
* 某个目标 `version + checksum` 一旦应用失败并回退,Agent 必须在本地状态中阻断该目标的重复应用。
|
||||
|
||||
## 前端请求、状态与类型
|
||||
|
||||
所有 API 请求必须统一经过 `lib/api/`:
|
||||
|
||||
* 统一处理 `success/message/data` 响应结构。
|
||||
* 统一处理鉴权失效、网络异常和通用错误消息。
|
||||
* 统一维护资源接口与请求路径。
|
||||
|
||||
状态分层:
|
||||
|
||||
* 服务端状态:TanStack Query。
|
||||
* 页面临时状态:组件内部 `useState`。
|
||||
* 跨页面 UI 状态:Zustand。
|
||||
|
||||
要求开启 TypeScript 严格模式,禁止滥用 `any`,API 响应、表单输入、业务实体必须有明确类型。
|
||||
|
||||
## 表单、交互、样式与主题
|
||||
|
||||
表单统一使用 React Hook Form 与 Zod。
|
||||
|
||||
高风险操作必须二次确认、展示操作对象名称,并明确成功与失败反馈。
|
||||
|
||||
样式原则:
|
||||
|
||||
* 统一使用 Tailwind CSS 与现有 token 体系。
|
||||
* 优先复用已有基础组件与布局组件。
|
||||
* 保持视觉层级、留白与语义颜色一致。
|
||||
|
||||
主题要求:
|
||||
|
||||
* 同时支持 `light`、`dark`、`system`。
|
||||
* 用户选择必须持久化。
|
||||
* 首屏尽量避免主题闪烁。
|
||||
|
||||
## 测试与交付
|
||||
|
||||
* 关键业务逻辑必须有单元测试或等效回归测试。
|
||||
* Agent 主链路修改必须验证同步、应用与回滚。
|
||||
* 前端页面至少覆盖加载态、空态、错误态与成功反馈。
|
||||
* Go 版本调整时,同步检查 `go.mod`、Dockerfile 与 CI 工作流。
|
||||
|
||||
## 后续维护方式
|
||||
|
||||
后续规划不再按“大版本阶段文档”维护,而采用以下方式:
|
||||
|
||||
* 产品边界变动:更新 [产品边界](./)。
|
||||
* 工程约束变动:更新本文档。
|
||||
* 部署与配置变动:更新 [部署说明](../guide/deployment.md)、[配置项](../reference/configuration.md) 与 README。
|
||||
|
||||
如果未来出现明确的新阶段目标,再单独新增专项计划文档;不要把已完成的历史计划继续堆回本文档。
|
||||
|
||||
当前专项“网站级规则与配置界面改造”的模型边界已纳入 [产品边界](./),执行时仍按数据模型、接口、前端页面、迁移测试与文档联动的顺序推进。
|
||||
@@ -0,0 +1,115 @@
|
||||
# 产品边界
|
||||
|
||||
OpenFlare 是一套自托管的 OpenResty 控制面,面向单团队或单组织内部运维场景,解决反向代理配置、节点同步、证书托管与基础观测的统一管理问题。
|
||||
|
||||
当前稳定能力包括:
|
||||
|
||||
| 能力 | 说明 |
|
||||
| --- | --- |
|
||||
| 反代规则管理 | 以网站配置为聚合边界,支持多域名与源站配置 |
|
||||
| 网站级配置 | 一条规则对应一个网站,可绑定一个或多个域名,并共享站点级配置 |
|
||||
| 源站管理 | 维护轻量源站目录,并允许网站保存可渲染的源站快照 |
|
||||
| 配置版本 | 支持预览、发布、激活、不可变历史与回滚 |
|
||||
| Agent 同步 | 支持注册、心跳、同步、应用结果上报与自更新 |
|
||||
| OpenResty 托管 | 管理主配置模板、性能参数、缓存参数与 Lua 资源 |
|
||||
| HTTPS/TLS | 托管证书与域名资产,并按域名绑定证书 |
|
||||
| 基础观测 | 聚合节点请求、资源快照、健康事件和访问分析 |
|
||||
| 节点管理 | 节点状态、令牌体系、部署与更新链路 |
|
||||
| 管理端前端 | 基于 Next.js 的正式管理端 |
|
||||
| 认证源登录 | 支持以认证源形式配置 GitHub 与标准 OIDC 登录入口,并允许第三方账号绑定已有本地用户 |
|
||||
|
||||
默认工作方式:
|
||||
|
||||
* 所有节点消费同一份全局激活版本。
|
||||
* Server 保存配置与状态,不直接 SSH 管理节点。
|
||||
* Agent 是节点侧唯一受控落地入口。
|
||||
|
||||
## 核心对象
|
||||
|
||||
当前有效实体:
|
||||
|
||||
* `proxy_routes`
|
||||
* `origins`
|
||||
* `config_versions`
|
||||
* `nodes`
|
||||
* `auth_sources`
|
||||
* `external_accounts`
|
||||
* `node_system_profiles`
|
||||
* `apply_logs`
|
||||
* `tls_certificates`
|
||||
* `managed_domains`
|
||||
* `node_request_reports`
|
||||
* `node_access_logs`
|
||||
* `node_metric_snapshots`
|
||||
* `traffic_analytics_rollups`
|
||||
* `node_health_events`
|
||||
|
||||
## 网站配置约束
|
||||
|
||||
`proxy_routes` 从“单域名规则”升级为“网站配置”聚合对象。一条记录对应一个网站,可绑定一个或多个域名,并共享一组站点级配置。
|
||||
|
||||
约束:
|
||||
|
||||
* `proxy_routes.site_name` 是网站的业务唯一标识。
|
||||
* `proxy_routes.domains` 至少包含一个域名,且 `domains[0]` 作为主域名。
|
||||
* 任一域名全局只能属于一个 `proxy_routes`。
|
||||
* 迁移期可保留 `proxy_routes.domain` 作为 `domains[0]` 的镜像字段,但业务读写与后续扩展必须以 `site_name` + `domains` 为准。
|
||||
* 网站级流量限制、反向代理与缓存配置当前按站点共享,不在同一网站内做域名级差异化配置。
|
||||
* HTTPS 允许在同一站点内按域名绑定证书。
|
||||
|
||||
## 源站约束
|
||||
|
||||
`origins` 只保存源站地址、展示名与备注,不承载协议、端口、路径、权重或健康检查策略。
|
||||
|
||||
`proxy_routes` 可选关联一个 `origins` 记录,用于复用源站地址;规则仍保存完整 `origin_url` 快照以参与渲染与版本快照。
|
||||
|
||||
上游约束:
|
||||
|
||||
* `proxy_routes` 至少包含一个上游地址。
|
||||
* 为兼容历史数据保留 `origin_url` 主上游字段,也允许在同一规则内补充多个上游做负载均衡。
|
||||
* 上游统一渲染为带 keepalive 的 named `upstream`。
|
||||
* 单上游可附带 base path 或 query 并在 `proxy_pass` 中追加。
|
||||
* 多上游限定为纯 `scheme://host[:port]`。
|
||||
* `proxy_routes.origin_host` 为可选字段,用于回源时覆盖 `Host` 请求头。
|
||||
* 所有上游地址都必须为合法 `http://` 或 `https://`。
|
||||
|
||||
## HTTPS 约束
|
||||
|
||||
`proxy_routes.domain_cert_ids` 用于记录与 `domains` 平行的域名证书绑定;值为 `0` 表示该域名不启用 HTTPS,仅保留 HTTP。
|
||||
|
||||
发布渲染时:
|
||||
|
||||
* 带证书的域名按证书分组输出独立 `443 ssl` `server` 块。
|
||||
* 未绑定证书的域名不得被自动带入 HTTPS。
|
||||
* 必须将 `proxy_routes.domains` 中的全部域名一并纳入同一站点配置,避免同站点在版本快照中被拆散。
|
||||
|
||||
## 认证源约束
|
||||
|
||||
`auth_sources` 是管理端第三方登录入口的配置对象,当前仅支持 `github` 与 `oidc` 两类。启用后的认证源会显示在登录页。
|
||||
|
||||
`external_accounts` 保存认证源外部账号与本地用户的绑定关系。第三方账号首次登录时:
|
||||
|
||||
* 已绑定本地用户则直接登录。
|
||||
* 当前已有本地登录 Session 时,绑定到当前用户。
|
||||
* 未绑定且允许注册时,自动创建普通用户并绑定。
|
||||
* 未绑定且关闭注册时,只允许用户输入已有本地账号密码完成绑定。
|
||||
|
||||
旧 `users.github_id` 仅作为升级迁移来源,新的第三方账号登录与绑定关系必须以 `external_accounts` 为准。
|
||||
|
||||
## 版本与观测约束
|
||||
|
||||
* `config_versions` 必须保存完整快照、渲染结果与 `checksum`。
|
||||
* 全局同时只能有一个激活版本。
|
||||
* 回滚通过重新激活旧版本实现。
|
||||
* `nodes` 只承载控制面状态与低频摘要,不承载高频观测事实。
|
||||
* 指标、趋势和访问分析优先使用服务端聚合结果,而不是前端临时统计。
|
||||
* 访问明细只保留受控时间窗口,不演变成通用日志平台。
|
||||
|
||||
## 文档维护原则
|
||||
|
||||
* 产品范围或系统边界变化时更新本文档。
|
||||
* 开发约束、代码规范、接口约定变化时更新 [开发约束](./development.md)。
|
||||
* 部署方式变化时更新 [部署说明](../guide/deployment.md) 与 README。
|
||||
* 配置项变化时更新 [配置项参考](../reference/configuration.md)。
|
||||
* 已完成阶段不再以“版本计划”形式回填。
|
||||
* 新阶段开始前,先补设计,再进入实现。
|
||||
@@ -0,0 +1,37 @@
|
||||
# 发布模型
|
||||
|
||||
OpenFlare 的发布模型以完整配置版本为中心,而不是在线修改节点配置。
|
||||
|
||||
标准链路:
|
||||
|
||||
```text
|
||||
修改规则 -> 预览/查看 diff -> 发布 -> 生成完整配置版本 -> 激活版本 -> Agent 拉取 -> 本地应用 -> 上报结果
|
||||
```
|
||||
|
||||
## 发布规则
|
||||
|
||||
Server 发布时必须:
|
||||
|
||||
1. 读取全部启用的 `proxy_routes`。
|
||||
2. 读取 Server 侧 OpenResty 主配置与结构化参数。
|
||||
3. 渲染完整 OpenResty 配置。
|
||||
4. 计算 `checksum`。
|
||||
5. 写入 `config_versions`。
|
||||
6. 切换激活版本。
|
||||
7. 让 Agent 在后续 heartbeat 中发现并应用。
|
||||
|
||||
版本号格式固定为 `YYYYMMDD-NNN`。
|
||||
|
||||
## 不可变历史
|
||||
|
||||
历史版本不可变。回滚不是修改旧版本,而是重新激活旧版本。
|
||||
|
||||
全局同时只能有一个激活版本,当前不做按节点分组的差异化版本。
|
||||
|
||||
## Agent 应用策略
|
||||
|
||||
Agent 发现新版本后会备份旧文件,写入主配置、路由配置、证书与必要 Lua 资源,再执行配置校验和 reload。
|
||||
|
||||
如果新配置激活失败,Agent 必须尝试恢复运行;回滚成功时上报警告,回滚后仍无法恢复运行时上报失败。
|
||||
|
||||
某个目标 `version + checksum` 一旦应用失败并回退,Agent 会在本地状态中阻断该目标重复应用。只有远端激活版本或 checksum 发生变化,才允许再次尝试。
|
||||
@@ -1,232 +0,0 @@
|
||||
# OpenFlare 开发规范
|
||||
|
||||
本文档描述 OpenFlare `1.0.0` 正式版之后的开发基线。
|
||||
|
||||
超出 [docs/design.md](./design.md) 边界的需求,必须先更新设计文档。
|
||||
|
||||
## 1. 技术基线
|
||||
|
||||
### 1.1 Server
|
||||
|
||||
`openflare_server` 继续作为单体控制面:
|
||||
|
||||
* Go 1.24+
|
||||
* Gin
|
||||
* GORM
|
||||
* SQLite / PostgreSQL
|
||||
* 现有登录体系
|
||||
|
||||
### 1.2 Agent
|
||||
|
||||
`openflare_agent` 继续作为 Go 单体程序:
|
||||
|
||||
* Go 1.24+
|
||||
* 单二进制
|
||||
* 节点本地执行
|
||||
* `openresty_path` 优先
|
||||
* 无 `openresty_path` 时默认 Docker OpenResty
|
||||
|
||||
### 1.3 Frontend
|
||||
|
||||
前端基线以 `openflare_server/web` 为准:
|
||||
|
||||
* Next.js 15 App Router
|
||||
* React 19
|
||||
* TypeScript
|
||||
* Tailwind CSS 4
|
||||
* TanStack Query
|
||||
* React Hook Form + Zod
|
||||
* Zustand 仅用于轻量客户端状态
|
||||
|
||||
前端细则见 [docs/frontend-development-guidelines.md](./frontend-development-guidelines.md)。
|
||||
|
||||
## 2. 分层与目录约束
|
||||
|
||||
### 2.1 Server
|
||||
|
||||
* `controller/`:参数解析、调用 service、返回响应
|
||||
* `service/`:业务逻辑、校验、事务编排、渲染
|
||||
* `model/`:模型定义与持久化
|
||||
* `router/`:路由注册
|
||||
* `middleware/`:认证、鉴权、限流等横切逻辑
|
||||
* `common/`:配置、全局状态与初始化入口
|
||||
* `utils/`:纯工具函数与通用 helper
|
||||
|
||||
禁止:
|
||||
|
||||
* 在 `controller/` 堆积业务逻辑
|
||||
* 在 `middleware/` 实现业务流程
|
||||
* 为简单需求新增平台层抽象
|
||||
|
||||
### 2.2 Agent
|
||||
|
||||
保持现有模块边界:
|
||||
|
||||
* `config`
|
||||
* `heartbeat`
|
||||
* `sync`
|
||||
* `openresty`
|
||||
* `state`
|
||||
* `httpclient`
|
||||
* `protocol`
|
||||
* `internal/updater`
|
||||
|
||||
要求:
|
||||
|
||||
* 每个模块职责单一
|
||||
* 外部命令调用集中封装
|
||||
* 状态落盘与配置落盘分离
|
||||
|
||||
### 2.3 Frontend
|
||||
|
||||
前端分层保持:
|
||||
|
||||
* `app/`
|
||||
* `features/`
|
||||
* `components/`
|
||||
* `lib/`
|
||||
* `store/`
|
||||
* `types/`
|
||||
|
||||
要求:
|
||||
|
||||
* 页面路由与布局放在 `app/`
|
||||
* API 请求统一收敛到 `lib/api/`
|
||||
* 业务逻辑优先放在 `features/`
|
||||
|
||||
## 3. 数据模型规范
|
||||
|
||||
当前有效实体:
|
||||
|
||||
* `proxy_routes`
|
||||
* `origins`
|
||||
* `config_versions`
|
||||
* `nodes`
|
||||
* `node_system_profiles`
|
||||
* `apply_logs`
|
||||
* `tls_certificates`
|
||||
* `managed_domains`
|
||||
* `node_request_reports`
|
||||
* `node_access_logs`
|
||||
* `node_metric_snapshots`
|
||||
* `traffic_analytics_rollups`
|
||||
* `node_health_events`
|
||||
* `options`
|
||||
|
||||
通用约束:
|
||||
|
||||
* 不新增平台化对象,除非设计文档明确要求
|
||||
* `origins` 仅作为可复用源站地址目录,字段保持轻量;协议、端口、路径与查询参数继续归属具体 `proxy_routes`
|
||||
* `proxy_routes` 以“网站配置”作为聚合边界,必须包含唯一 `site_name` 与非空 `domains` 列表;数据库内部 `id` 可继续作为技术主键,但不能替代 `site_name` 的业务唯一性
|
||||
* `proxy_routes.domains` 中的每个域名都必须全局唯一;列表第一项视为主域名,创建时若未显式填写 `site_name`,则默认使用主域名
|
||||
* `proxy_routes` 继续允许保存一个或多个上游地址用于负载均衡,但不引入独立 `origin_pool`
|
||||
* 迁移期如保留遗留 `domain` 字段,只能作为 `domains[0]` 的兼容镜像;新代码不得继续以该字段作为唯一业务输入
|
||||
* `proxy_routes` 如关联 `origins`,必须同时保存可直接渲染的 `origin_url`;源站地址变更时,由 service 负责同步更新引用该源站的规则快照
|
||||
* `proxy_routes` 的上游统一使用 named `upstream` + keepalive;单上游如带 base path 或 query,应在 `proxy_pass` 上补回 URI,多上游仅允许纯 `scheme://host[:port]`
|
||||
* `proxy_routes.origin_host` 为可选字段,仅用于覆盖回源 `Host` 请求头,不引入新的平台化对象
|
||||
* 流量限制、反向代理与缓存配置当前都归属站点级 `proxy_routes`,同一网站内不拆分域名级差异配置
|
||||
* HTTPS 的启停仍由站点级 `proxy_routes` 控制,但证书绑定必须通过与 `domains` 平行的 `domain_cert_ids` 记录逐域名保存;未绑定证书的域名不得参与 HTTPS 渲染
|
||||
* `proxy_routes.cert_ids` 仅作为站点级证书集合与兼容镜像,必须由 `domain_cert_ids` 推导生成;`cert_id` 继续作为首个已使用证书的兼容镜像
|
||||
* `config_versions` 必须保存完整快照与渲染结果
|
||||
* 全局同时只能有一个激活版本
|
||||
* 回滚通过重新激活旧版本实现
|
||||
* `nodes` 只保留控制面状态与低频摘要
|
||||
* 观测数据必须按节点与时间窗口关联
|
||||
* 快照与聚合结果采用追加式模型,不覆盖历史
|
||||
* 原始访问明细必须有受控保留策略
|
||||
|
||||
### 3.1 数据库版本与迁移
|
||||
|
||||
* 任何涉及表结构、索引、列类型、分表规则或内部持久化元数据的修改,都必须同步提升数据库版本号
|
||||
* 数据库版本号定义在 `openflare_server/model`,不得只依赖 `AutoMigrate` 隐式升级存量数据库
|
||||
* 每次提升数据库版本号时,必须补充从上一版本升级到新版本的显式迁移方法
|
||||
* 迁移方法必须包含升级后的校验逻辑;只有校验通过,才能写入新的数据库版本记录
|
||||
* 新包启动后必须先检查数据库当前版本,再按顺序逐步升级到目标版本;禁止跳过中间升级步骤直接写目标版本
|
||||
* 空库初始化可以直接建立当前版本结构,但初始化完成后仍必须执行同版本校验,并落库当前数据库版本
|
||||
* 数据库版本元数据属于内部控制信息,必须保存在独立内部表中,不能混入业务配置表
|
||||
* 如果迁移失败或校验失败,启动流程必须中止,且不得提升数据库版本记录
|
||||
* 涉及数据库版本变更的提交,必须补充对应的迁移测试或等效回归测试
|
||||
|
||||
## 4. API 与鉴权规范
|
||||
|
||||
### 4.1 API
|
||||
|
||||
* 管理端与 Agent API 统一使用 JSON
|
||||
* 成功与失败都必须返回清晰 `message`
|
||||
* Agent API 固定放在 `/api/agent/*`
|
||||
* 总览与节点详情优先使用专用聚合接口
|
||||
* 管理端变更类接口统一使用 `POST`;只读接口使用 `GET`
|
||||
|
||||
统一响应结构:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "",
|
||||
"data": {}
|
||||
}
|
||||
```
|
||||
|
||||
### 4.2 鉴权
|
||||
|
||||
管理端:
|
||||
|
||||
* 继续复用现有登录、角色与 Session
|
||||
|
||||
Agent:
|
||||
|
||||
* 正式请求统一使用节点专属 `agent_token`
|
||||
* 首次接入可使用全局 `discovery_token`
|
||||
* 请求头统一使用 `X-Agent-Token`
|
||||
|
||||
禁止:
|
||||
|
||||
* 暴露远程 shell 或任意命令执行入口
|
||||
* 在日志中打印完整 Token
|
||||
* 允许绕过占位符约束保存不可渲染的主配置模板
|
||||
|
||||
## 5. 发布与运行规范
|
||||
|
||||
发布逻辑必须保持以下事实:
|
||||
|
||||
* 发布时读取全部启用的 `proxy_routes`
|
||||
* 同时读取 OpenResty 主配置参数、反代性能参数与缓存参数
|
||||
* 生成完整 OpenResty 配置
|
||||
* 计算 `checksum`
|
||||
* 写入 `config_versions`
|
||||
* 通过切换 `is_active` 激活版本
|
||||
|
||||
版本约束:
|
||||
|
||||
* 版本号格式固定为 `YYYYMMDD-NNN`
|
||||
* 不在线修改历史版本
|
||||
* 不做按节点分组的差异化版本
|
||||
* 预览与 diff 是只读能力,不产生发布记录
|
||||
|
||||
Agent 必须满足:
|
||||
|
||||
* 启动后读取或生成本地 `node_id`
|
||||
* 周期性心跳与同步
|
||||
* 常规同步优先依据 heartbeat 返回的版本摘要判断
|
||||
* 发现新版本时先备份旧文件
|
||||
* 写入主配置、路由配置与必要证书文件
|
||||
* 写入新配置后以运行态恢复为目标执行激活,Docker 模式优先重建容器并确认容器保持运行
|
||||
* 新配置激活失败时必须先尝试用目标配置恢复运行,再回滚到旧配置并重新拉起 OpenResty
|
||||
* 回滚后 OpenResty 恢复正常时上报警告;回滚后仍无法恢复运行时上报失败
|
||||
* 某个目标 `version + checksum` 一旦应用失败并回退,Agent 必须在本地状态中阻断该目标的重复应用;只有远端激活版本或 checksum 发生变化时,才允许再次尝试
|
||||
|
||||
## 6. 测试与交付要求
|
||||
|
||||
* 关键业务逻辑必须有单元测试或等效回归测试
|
||||
* Agent 主链路修改必须验证同步、应用与回滚
|
||||
* 前端页面至少覆盖加载态、空态、错误态与成功反馈
|
||||
* Go 版本调整时,同步检查 `go.mod`、Dockerfile 与 CI 工作流
|
||||
|
||||
## 7. 文档维护要求
|
||||
|
||||
当以下内容变化时,必须同步更新对应文档:
|
||||
|
||||
* 产品范围或系统边界变化:更新 `docs/design.md`
|
||||
* 开发约束、接口约定、测试基线变化:更新本文档
|
||||
* 前端工程约束变化:更新 `docs/frontend-development-guidelines.md`
|
||||
* 配置项或部署方式变化:更新 `docs/app-config.md`、`docs/deployment.md` 与 `README.md`
|
||||
@@ -1,61 +0,0 @@
|
||||
# OpenFlare 开发计划
|
||||
|
||||
## 1. 当前结论
|
||||
|
||||
* 第一版至第六版的主线能力已经全部完成
|
||||
* `1.0.0` 是当前正式基线
|
||||
* 已完成阶段的过程性任务以代码、测试与 Git 历史为准
|
||||
* 新工作优先以缺陷修复、可维护性改进、文档与测试补强为主
|
||||
|
||||
## 2. 当前优先级
|
||||
|
||||
当前开发应优先关注:
|
||||
|
||||
1. 稳定性
|
||||
2. 升级与回滚链路可靠性
|
||||
3. 文档准确性
|
||||
4. 测试覆盖补强
|
||||
5. 在既有边界内的小步迭代
|
||||
|
||||
## 3. 变更准入原则
|
||||
|
||||
新需求进入实现前,按以下顺序判断:
|
||||
|
||||
1. 是否符合 [docs/design.md](./design.md) 的产品边界
|
||||
2. 是否符合 [docs/development-guidelines.md](./development-guidelines.md) 与前端规范
|
||||
3. 是否会破坏现有发布、同步、回滚或升级主链路
|
||||
4. 是否需要同步更新部署、配置或 README 文档
|
||||
|
||||
如果答案包含“超出边界”或“引入新基础设施”,先修改设计文档,再开始实现。
|
||||
|
||||
## 4. 当前验收标准
|
||||
|
||||
任何合入正式基线的改动,至少应满足:
|
||||
|
||||
* 不破坏 Agent 心跳、同步、发布与回滚主链路
|
||||
* 不破坏现有 OpenResty 主配置托管模型
|
||||
* 不降低总览、节点详情与访问分析的既有可用性
|
||||
* 有与风险相称的测试或联调验证
|
||||
* 文档与代码保持一致
|
||||
|
||||
## 5. 后续维护方式
|
||||
|
||||
后续规划不再按“大版本阶段文档”维护,而采用以下方式:
|
||||
|
||||
* 产品边界变动:更新 `docs/design.md`
|
||||
* 工程约束变动:更新 `docs/development-guidelines.md`
|
||||
* 前端工程变动:更新前端相关规范文档
|
||||
* 部署与配置变动:更新 `README.md`、`docs/deployment.md`、`docs/app-config.md`
|
||||
|
||||
如果未来出现明确的新阶段目标,再单独新增专项计划文档;不要把已完成的历史计划继续堆回本文件。
|
||||
|
||||
## 6. 当前专项计划
|
||||
|
||||
已确认需要推进“网站级规则与配置界面改造”专项,详细需求、实施顺序与验收标准见 [docs/website-configuration-redesign.md](./website-configuration-redesign.md)。
|
||||
|
||||
本专项的执行顺序固定为:
|
||||
|
||||
1. 先完成数据模型与配置渲染兼容方案
|
||||
2. 再调整接口、校验与版本 diff 语义
|
||||
3. 然后改造规则列表与网站配置子页面
|
||||
4. 最后补齐迁移、回归测试与文档联动
|
||||
@@ -0,0 +1,80 @@
|
||||
import { defineAdditionalConfig, type DefaultTheme } from 'vitepress'
|
||||
|
||||
export default defineAdditionalConfig({
|
||||
description:
|
||||
'OpenFlare is a lightweight, self-hosted OpenResty control plane for reverse proxy rules, releases, node sync, TLS certificates, and basic observability.',
|
||||
|
||||
themeConfig: {
|
||||
nav: nav(),
|
||||
|
||||
sidebar: {
|
||||
'/en/guide/': { base: '/en/guide/', items: sidebarGuide() },
|
||||
'/en/reference/': { base: '/en/reference/', items: sidebarReference() },
|
||||
'/en/design/': { base: '/en/design/', items: sidebarDesign() }
|
||||
},
|
||||
|
||||
editLink: {
|
||||
pattern: 'https://github.com/Rain-kl/OpenFlare/edit/main/docs/:path',
|
||||
text: 'Edit this page on GitHub'
|
||||
},
|
||||
|
||||
footer: {
|
||||
message: 'Released under the Apache License 2.0.',
|
||||
copyright: 'Copyright © OpenFlare contributors'
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
function nav(): DefaultTheme.NavItem[] {
|
||||
return [
|
||||
{ text: 'Guide', link: '/en/guide/', activeMatch: '/en/guide/' },
|
||||
{ text: 'Reference', link: '/en/reference/', activeMatch: '/en/reference/' },
|
||||
{ text: 'Design', link: '/en/design/', activeMatch: '/en/design/' }
|
||||
]
|
||||
}
|
||||
|
||||
function sidebarGuide(): DefaultTheme.SidebarItem[] {
|
||||
return [
|
||||
{
|
||||
text: 'Guide',
|
||||
items: [
|
||||
{ text: 'Overview', link: '' },
|
||||
{ text: 'Quick Start', link: 'quick-start' },
|
||||
{ text: 'Deployment', link: 'deployment' },
|
||||
{ text: 'Run Server', link: 'server' },
|
||||
{ text: 'Connect Agent', link: 'agent' },
|
||||
{ text: 'Publish First Site', link: 'first-site' },
|
||||
{ text: 'Upgrade and Maintenance', link: 'upgrade' }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
function sidebarReference(): DefaultTheme.SidebarItem[] {
|
||||
return [
|
||||
{
|
||||
text: 'Reference',
|
||||
items: [
|
||||
{ text: 'Overview', link: '' },
|
||||
{ text: 'Configuration', link: 'configuration' },
|
||||
{ text: 'Commands and Scripts', link: 'cli' },
|
||||
{ text: 'API Conventions', link: 'api' },
|
||||
{ text: 'Repository Layout', link: 'repository' }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
function sidebarDesign(): DefaultTheme.SidebarItem[] {
|
||||
return [
|
||||
{
|
||||
text: 'Design',
|
||||
items: [
|
||||
{ text: 'Product Boundary', link: '' },
|
||||
{ text: 'Architecture', link: 'architecture' },
|
||||
{ text: 'Release Model', link: 'release-model' },
|
||||
{ text: 'Development Constraints', link: 'development' }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
# Architecture
|
||||
|
||||
OpenFlare consists of Server, Agent, and local OpenResty on each node.
|
||||
|
||||
```text
|
||||
OpenFlare Server (Gin + SQLite/PostgreSQL + Web UI)
|
||||
|
|
||||
| HTTP API / Config Pull
|
||||
v
|
||||
OpenFlare Agent (register / heartbeat / sync / apply / update)
|
||||
|
|
||||
v
|
||||
Local OpenResty or Docker OpenResty
|
||||
|
|
||||
v
|
||||
Origin
|
||||
```
|
||||
|
||||
## Server
|
||||
|
||||
`openflare_server` is a monolithic control plane based on Gin, GORM, SQLite/PostgreSQL, the existing login/session system, and the static frontend build.
|
||||
|
||||
It owns the admin UI and API, Agent API, configuration rendering, version publishing, storage, and aggregate queries.
|
||||
|
||||
## Agent
|
||||
|
||||
`openflare_agent` is a single Go binary that runs locally on each node. It prefers `openresty_path` when configured and uses Docker OpenResty by default otherwise.
|
||||
|
||||
It handles registration, heartbeat, sync, file writes, `openresty -t`, reload, rollback, self-update, and lightweight collection.
|
||||
|
||||
## Frontend
|
||||
|
||||
`openflare_server/web` is the production frontend baseline: Next.js App Router, React 19, TypeScript, and Tailwind CSS.
|
||||
@@ -0,0 +1,31 @@
|
||||
# Development Constraints
|
||||
|
||||
After `1.0.0`, OpenFlare development prioritizes stability, upgrade and rollback reliability, documentation accuracy, test coverage, and small iterations inside the existing boundary.
|
||||
|
||||
## Change Admission
|
||||
|
||||
Before implementing a requirement, check:
|
||||
|
||||
1. Whether it fits the product boundary.
|
||||
2. Whether it follows Server, Agent, and frontend development rules.
|
||||
3. Whether it risks the publish, sync, rollback, or upgrade flow.
|
||||
4. Whether deployment, configuration, or README docs need updates.
|
||||
|
||||
If a requirement expands the boundary or introduces new infrastructure, update design documentation first.
|
||||
|
||||
## Database Migrations
|
||||
|
||||
Any table, index, column type, sharding, or internal persistence metadata change must bump the database version and include an explicit migration from the previous version.
|
||||
|
||||
Migrations must validate the upgraded schema. Startup must stop if migration or validation fails.
|
||||
|
||||
## Frontend Rules
|
||||
|
||||
`openflare_server/web` is the frontend baseline:
|
||||
|
||||
* Routes and layouts live in `app/`.
|
||||
* API calls are centralized under `lib/api/`.
|
||||
* Business logic belongs in `features/`.
|
||||
* Server state uses TanStack Query.
|
||||
* Forms use React Hook Form and Zod.
|
||||
* Theme supports `light`, `dark`, and `system`.
|
||||
@@ -0,0 +1,21 @@
|
||||
# Product Boundary
|
||||
|
||||
OpenFlare is a self-hosted OpenResty control plane for single-team or single-organization operations. It unifies reverse proxy configuration, node synchronization, certificate management, and basic observability.
|
||||
|
||||
Stable capabilities:
|
||||
|
||||
| Capability | Description |
|
||||
| --- | --- |
|
||||
| Reverse proxy management | Site-level configuration with multiple domains and origins |
|
||||
| Configuration versions | Preview, publish, activate, and rollback |
|
||||
| Agent sync | Registration, heartbeat, sync, and apply result reporting |
|
||||
| OpenResty management | Main template, performance options, cache options, and Lua assets |
|
||||
| HTTPS/TLS | Certificate storage and per-domain binding |
|
||||
| Basic observability | Request rollups, resource snapshots, health events, and access analytics |
|
||||
| Node management | Node state, tokens, deployment, and update flow |
|
||||
|
||||
Default operating model:
|
||||
|
||||
* All nodes consume the same globally active version.
|
||||
* Server stores configuration and state, but does not SSH into nodes.
|
||||
* Agent is the only controlled entry point on each node.
|
||||
@@ -0,0 +1,33 @@
|
||||
# Release Model
|
||||
|
||||
OpenFlare publishes complete configuration versions instead of modifying node configuration online.
|
||||
|
||||
```text
|
||||
Edit rules -> Preview / diff -> Publish -> Create full version -> Activate -> Agent pulls -> Agent applies -> Agent reports
|
||||
```
|
||||
|
||||
## Publish Rules
|
||||
|
||||
Server must:
|
||||
|
||||
1. Read all enabled `proxy_routes`.
|
||||
2. Read the OpenResty main template and structured options.
|
||||
3. Render the full OpenResty configuration.
|
||||
4. Compute `checksum`.
|
||||
5. Write `config_versions`.
|
||||
6. Switch the active version.
|
||||
7. Let Agents discover and apply it in later heartbeats.
|
||||
|
||||
Version numbers use `YYYYMMDD-NNN`.
|
||||
|
||||
## Immutable History
|
||||
|
||||
Historical versions are immutable. Rollback reactivates an old version.
|
||||
|
||||
Only one global active version exists at a time. Node-specific version groups are not part of the current model.
|
||||
|
||||
## Agent Apply Strategy
|
||||
|
||||
Agent backs up old files, writes the new main config, route config, certificates, and Lua assets, then validates and reloads.
|
||||
|
||||
If activation fails, Agent attempts to recover. A failed `version + checksum` is blocked locally until the remote active version or checksum changes.
|
||||
@@ -0,0 +1,60 @@
|
||||
# Connect Agent
|
||||
|
||||
OpenFlare Agent runs on proxy nodes. It handles registration, heartbeat, configuration sync, OpenResty file writes, validation, reload, rollback, and self-update.
|
||||
|
||||
## Authentication
|
||||
|
||||
| Method | Use case |
|
||||
| --- | --- |
|
||||
| `agent_token` | The node already exists or has a dedicated credential |
|
||||
| `discovery_token` | First-time auto-registration; Server exchanges it for a node token |
|
||||
|
||||
At least one of them is required.
|
||||
|
||||
## Install Script
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/install-agent.sh | bash -s -- \
|
||||
--server-url http://your-server:3000 \
|
||||
--agent-token YOUR_AGENT_TOKEN
|
||||
```
|
||||
|
||||
Or with discovery:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/install-agent.sh | bash -s -- \
|
||||
--server-url http://your-server:3000 \
|
||||
--discovery-token YOUR_DISCOVERY_TOKEN
|
||||
```
|
||||
|
||||
## Configuration Example
|
||||
|
||||
```json
|
||||
{
|
||||
"server_url": "http://127.0.0.1:3000",
|
||||
"agent_token": "replace-with-node-auth-token",
|
||||
"data_dir": "./data",
|
||||
"openresty_container_name": "openflare-openresty",
|
||||
"openresty_docker_image": "openresty/openresty:alpine",
|
||||
"openresty_observability_port": 18081,
|
||||
"observability_replay_minutes": 15,
|
||||
"heartbeat_interval": 10000,
|
||||
"request_timeout": 10000
|
||||
}
|
||||
```
|
||||
|
||||
Without `openresty_path`, Agent uses Docker OpenResty by default.
|
||||
|
||||
## Run from Source
|
||||
|
||||
```bash
|
||||
cd openflare_agent
|
||||
export LOG_LEVEL='info'
|
||||
go run ./cmd/agent -config /path/to/agent.json
|
||||
```
|
||||
|
||||
## Uninstall
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/uninstall-agent.sh | bash
|
||||
```
|
||||
@@ -0,0 +1,102 @@
|
||||
# Deployment
|
||||
|
||||
This page summarizes the OpenFlare deployment baseline, integration flow, upgrade entry points, and Agent install scripts.
|
||||
|
||||
## Requirements
|
||||
|
||||
Server:
|
||||
|
||||
* Go 1.25+
|
||||
* Node.js 18+
|
||||
* Writable SQLite directory or reachable PostgreSQL instance
|
||||
|
||||
Agent:
|
||||
|
||||
* Go 1.25+
|
||||
* Writable Agent data directory
|
||||
* Local mode requires `openresty -t` and `openresty -s reload`
|
||||
* Docker mode requires Docker access
|
||||
|
||||
## Docker Compose
|
||||
|
||||
PostgreSQL is recommended for production:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_DB: openflare
|
||||
POSTGRES_USER: openflare
|
||||
POSTGRES_PASSWORD: replace-with-strong-password
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U openflare -d openflare"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
openflare:
|
||||
image: ghcr.io/rain-kl/openflare:latest
|
||||
container_name: openflare
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
- "3000:3000"
|
||||
environment:
|
||||
SESSION_SECRET: replace-with-random-string
|
||||
SQLITE_PATH: /data/openflare.db
|
||||
DSN: postgres://openflare:replace-with-strong-password@postgres:5432/openflare?sslmode=disable
|
||||
GIN_MODE: release
|
||||
LOG_LEVEL: info
|
||||
volumes:
|
||||
- openflare-data:/data
|
||||
|
||||
volumes:
|
||||
postgres-data:
|
||||
openflare-data:
|
||||
```
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Open `http://localhost:3000`. The default account is `root` / `123456`; change the password immediately.
|
||||
|
||||
## Agent Install
|
||||
|
||||
Using `discovery_token`:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/install-agent.sh | bash -s -- \
|
||||
--server-url http://your-server:3000 \
|
||||
--discovery-token YOUR_DISCOVERY_TOKEN
|
||||
```
|
||||
|
||||
Using node-specific `agent_token`:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/install-agent.sh | bash -s -- \
|
||||
--server-url http://your-server:3000 \
|
||||
--agent-token YOUR_AGENT_TOKEN
|
||||
```
|
||||
|
||||
Supported options include `--server-url`, `--discovery-token`, `--agent-token`, `--install-dir`, `--repo`, and `--no-service`.
|
||||
|
||||
## Validation
|
||||
|
||||
1. Prepare `agent_token` or `discovery_token` in the console.
|
||||
2. Start Agent and confirm the node is online.
|
||||
3. Add an enabled reverse proxy site.
|
||||
4. Publish and activate a new version.
|
||||
5. Confirm Agent pulls, validates, reloads, and reports the result.
|
||||
|
||||
## Uninstall Agent
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/uninstall-agent.sh | bash
|
||||
```
|
||||
@@ -0,0 +1,32 @@
|
||||
# Publish First Site
|
||||
|
||||
OpenFlare publishes complete configuration versions. After editing a site, publish and activate a new version before Agents apply it.
|
||||
|
||||
## Create Site Configuration
|
||||
|
||||
Required fields:
|
||||
|
||||
| Field | Description |
|
||||
| --- | --- |
|
||||
| Site name | Business-unique identifier; defaults to the primary domain when omitted |
|
||||
| Domains | At least one domain; the first one is the primary domain |
|
||||
| Origin URL | Valid `http://` or `https://` upstream URL |
|
||||
| Enabled | Only enabled sites are rendered into releases |
|
||||
|
||||
A domain can belong to only one site.
|
||||
|
||||
## Bind Certificates
|
||||
|
||||
HTTPS certificates are bound per domain. Domains without certificates are not automatically rendered into `443 ssl` server blocks.
|
||||
|
||||
## Publish and Activate
|
||||
|
||||
```text
|
||||
Edit rules -> Preview / diff -> Publish -> Create full version -> Activate -> Agent pulls -> Agent applies -> Agent reports
|
||||
```
|
||||
|
||||
Server reads enabled sites, OpenResty template, performance options, and cache options, renders a full configuration, computes `checksum`, writes `config_versions`, then switches the active version.
|
||||
|
||||
## Verify
|
||||
|
||||
Check that the node is online, the node version matches the active version, the latest apply log succeeded, and the version page marks the new version as active.
|
||||
@@ -0,0 +1,12 @@
|
||||
# Guide
|
||||
|
||||
This section helps operators take OpenFlare from first boot to the first working reverse proxy configuration.
|
||||
|
||||
Suggested order:
|
||||
|
||||
1. [Quick Start](./quick-start.md): run Server with Docker Compose and complete the first login.
|
||||
2. [Deployment](./deployment.md): review production deployment, Agent install, validation, and upgrade.
|
||||
3. [Run Server](./server.md): learn source startup, frontend build, and Swagger access.
|
||||
4. [Connect Agent](./agent.md): use `agent_token` or `discovery_token` to bring a node online.
|
||||
5. [Publish First Site](./first-site.md): create a site configuration, publish it, and verify node application.
|
||||
6. [Upgrade and Maintenance](./upgrade.md): understand upgrade, uninstall, validation, and maintenance entry points.
|
||||
@@ -0,0 +1,77 @@
|
||||
# Quick Start
|
||||
|
||||
The minimal OpenFlare setup contains one Server and at least one Agent. Server owns the web console, release versions, and node state. Agent runs on proxy nodes and applies OpenResty configuration.
|
||||
|
||||
## Run Server
|
||||
|
||||
Docker Compose with PostgreSQL is recommended:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_DB: openflare
|
||||
POSTGRES_USER: openflare
|
||||
POSTGRES_PASSWORD: replace-with-strong-password
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U openflare -d openflare"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
openflare:
|
||||
image: ghcr.io/rain-kl/openflare:latest
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
- "3000:3000"
|
||||
environment:
|
||||
SESSION_SECRET: replace-with-random-string
|
||||
DSN: postgres://openflare:replace-with-strong-password@postgres:5432/openflare?sslmode=disable
|
||||
GIN_MODE: release
|
||||
LOG_LEVEL: info
|
||||
|
||||
volumes:
|
||||
postgres-data:
|
||||
```
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Open `http://localhost:3000`.
|
||||
|
||||
Default credentials:
|
||||
|
||||
| Username | Password |
|
||||
| --- | --- |
|
||||
| `root` | `123456` |
|
||||
|
||||
Change the default password immediately after first login.
|
||||
|
||||
## Connect a Node
|
||||
|
||||
Prepare a `discovery_token` or node-specific `agent_token` in the console, then run the install script on the node.
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/install-agent.sh | bash -s -- \
|
||||
--server-url http://your-server:3000 \
|
||||
--agent-token YOUR_AGENT_TOKEN
|
||||
```
|
||||
|
||||
The script installs Agent under `/opt/openflare-agent`, creates `openflare-agent.service`, and uses Docker OpenResty unless a local `openresty_path` is configured.
|
||||
|
||||
## Publish the First Configuration
|
||||
|
||||
1. Create a site configuration with a domain and origin URL.
|
||||
2. Preview the release or check the diff before publishing.
|
||||
3. Activate the new version.
|
||||
4. Wait for Agent to discover and apply it through heartbeat.
|
||||
|
||||
Version numbers use `YYYYMMDD-NNN`. Historical versions are immutable; rollback reactivates an old version.
|
||||
@@ -0,0 +1,52 @@
|
||||
# Run Server
|
||||
|
||||
OpenFlare Server is the Gin + GORM control plane. It owns the web console, management API, Agent API, configuration rendering, release publishing, and state storage.
|
||||
|
||||
## Requirements
|
||||
|
||||
| Item | Requirement |
|
||||
| --- |-------------------------------------------------------|
|
||||
| Go | `1.25+` |
|
||||
| Node.js | `18+` |
|
||||
| Database | Writable SQLite path or reachable PostgreSQL instance |
|
||||
|
||||
Set `SESSION_SECRET` explicitly in production and prefer PostgreSQL.
|
||||
|
||||
## Build Frontend
|
||||
|
||||
```bash
|
||||
cd openflare_server/web
|
||||
corepack enable
|
||||
pnpm install
|
||||
pnpm build
|
||||
```
|
||||
|
||||
## Run from Source
|
||||
|
||||
```bash
|
||||
cd openflare_server
|
||||
export SESSION_SECRET='replace-with-random-string'
|
||||
export SQLITE_PATH='./openflare.db'
|
||||
export LOG_LEVEL='info'
|
||||
# Optional PostgreSQL:
|
||||
# export DSN='postgres://openflare:secret@127.0.0.1:5432/openflare?sslmode=disable'
|
||||
go run .
|
||||
```
|
||||
|
||||
The default port is `3000`.
|
||||
|
||||
## Swagger
|
||||
|
||||
After logging in, open:
|
||||
|
||||
```text
|
||||
http://localhost:3000/swagger/index.html
|
||||
```
|
||||
|
||||
Regenerate Swagger files locally:
|
||||
|
||||
```bash
|
||||
go install github.com/swaggo/swag/cmd/swag@v1.16.4
|
||||
cd openflare_server
|
||||
swag init -g main.go -o docs
|
||||
```
|
||||
@@ -0,0 +1,47 @@
|
||||
# Upgrade and Maintenance
|
||||
|
||||
## Server Upgrade
|
||||
|
||||
Root users can check and upgrade stable Server releases from the console header. Manual binary upload is also supported.
|
||||
|
||||
Preview releases require manual selection. Stable releases are recommended for production.
|
||||
|
||||
## Agent Upgrade
|
||||
|
||||
Agents follow stable releases by default. Preview upgrades must be triggered manually.
|
||||
|
||||
The install script can be re-run for reinstall or upgrade:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/install-agent.sh | bash -s -- \
|
||||
--server-url http://your-server:3000 \
|
||||
--agent-token YOUR_AGENT_TOKEN
|
||||
```
|
||||
|
||||
## Data Maintenance
|
||||
|
||||
The settings page controls observability cleanup:
|
||||
|
||||
| Option | Description |
|
||||
| --- | --- |
|
||||
| `DatabaseAutoCleanupEnabled` | Enable daily cleanup |
|
||||
| `DatabaseAutoCleanupRetentionDays` | Retention days, minimum 1 |
|
||||
|
||||
When enabled, Server cleans access logs, metric snapshots, and request reports at 03:00 every day.
|
||||
|
||||
## Validation Commands
|
||||
|
||||
```bash
|
||||
cd openflare_server
|
||||
GOCACHE=/tmp/openflare-go-cache go test ./...
|
||||
```
|
||||
|
||||
```bash
|
||||
cd openflare_agent
|
||||
GOCACHE=/tmp/openflare-go-cache go test ./...
|
||||
```
|
||||
|
||||
```bash
|
||||
cd openflare_server/web
|
||||
pnpm build
|
||||
```
|
||||
@@ -0,0 +1,32 @@
|
||||
---
|
||||
layout: home
|
||||
|
||||
hero:
|
||||
name: OpenFlare
|
||||
text: Self-hosted OpenResty control plane
|
||||
tagline: Manage reverse proxy rules, configuration releases, node sync, TLS certificates, and basic observability.
|
||||
actions:
|
||||
- theme: brand
|
||||
text: Quick Start
|
||||
link: /en/guide/quick-start
|
||||
- theme: alt
|
||||
text: Design Boundary
|
||||
link: /en/design/
|
||||
- theme: alt
|
||||
text: GitHub
|
||||
link: https://github.com/Rain-kl/OpenFlare
|
||||
|
||||
features:
|
||||
- icon: 🧭
|
||||
title: Unified Control Plane
|
||||
details: Manage sites, domains, origins, certificates, nodes, and release state in one console.
|
||||
- icon: 🚀
|
||||
title: Immutable Releases
|
||||
details: Each publish creates a full OpenResty configuration snapshot that can be previewed, activated, and rolled back.
|
||||
- icon: 🔁
|
||||
title: Agent Automation
|
||||
details: Nodes pull, validate, reload, and roll back to the last runnable configuration on failure.
|
||||
- icon: 📊
|
||||
title: Basic Observability
|
||||
details: Includes request rollups, access analytics, resource snapshots, health events, and node details.
|
||||
---
|
||||
@@ -0,0 +1,44 @@
|
||||
# API Conventions
|
||||
|
||||
Management API and Agent API both use JSON.
|
||||
|
||||
## Response Shape
|
||||
|
||||
Success and failure responses should include a clear `message`:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "",
|
||||
"data": {}
|
||||
}
|
||||
```
|
||||
|
||||
## Paths
|
||||
|
||||
| Type | Convention |
|
||||
| --- | --- |
|
||||
| Management API | Authenticated by management Session |
|
||||
| Agent API | Fixed under `/api/agent/*` |
|
||||
| Read-only endpoints | `GET` |
|
||||
| Mutating endpoints | `POST` |
|
||||
|
||||
## Authentication
|
||||
|
||||
Management endpoints reuse the existing login, role, and Session system.
|
||||
|
||||
Agent requests use the node-specific `agent_token`. First-time registration can use a global `discovery_token`. The header is:
|
||||
|
||||
```http
|
||||
X-Agent-Token: <token>
|
||||
```
|
||||
|
||||
Do not log full tokens.
|
||||
|
||||
## Swagger
|
||||
|
||||
After logging in:
|
||||
|
||||
```text
|
||||
/swagger/index.html
|
||||
```
|
||||
@@ -0,0 +1,64 @@
|
||||
# Commands and Scripts
|
||||
|
||||
## Server
|
||||
|
||||
```bash
|
||||
cd openflare_server
|
||||
export SESSION_SECRET='replace-with-random-string'
|
||||
export SQLITE_PATH='./openflare.db'
|
||||
export LOG_LEVEL='info'
|
||||
go run .
|
||||
```
|
||||
|
||||
```bash
|
||||
go run . --port 3000 --log-dir ./logs
|
||||
```
|
||||
|
||||
```bash
|
||||
cd openflare_server
|
||||
GOCACHE=/tmp/openflare-go-cache go test ./...
|
||||
```
|
||||
|
||||
## Frontend
|
||||
|
||||
```bash
|
||||
cd openflare_server/web
|
||||
pnpm install
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
```bash
|
||||
cd openflare_server/web
|
||||
pnpm build
|
||||
```
|
||||
|
||||
## Agent
|
||||
|
||||
```bash
|
||||
cd openflare_agent
|
||||
go run ./cmd/agent -config /path/to/agent.json
|
||||
```
|
||||
|
||||
```bash
|
||||
cd openflare_agent
|
||||
go build -o openflare-agent ./cmd/agent
|
||||
```
|
||||
|
||||
```bash
|
||||
cd openflare_agent
|
||||
GOCACHE=/tmp/openflare-go-cache go test ./...
|
||||
```
|
||||
|
||||
## Install Agent
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/install-agent.sh | bash -s -- \
|
||||
--server-url http://your-server:3000 \
|
||||
--agent-token YOUR_AGENT_TOKEN
|
||||
```
|
||||
|
||||
## Uninstall Agent
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/uninstall-agent.sh | bash
|
||||
```
|
||||
@@ -0,0 +1,72 @@
|
||||
# Configuration
|
||||
|
||||
## Server CLI Flags
|
||||
|
||||
| Flag | Purpose | Default |
|
||||
| --- | --- | --- |
|
||||
| `--port` | Server listen port | `3000` |
|
||||
| `--log-dir` | Log directory | empty |
|
||||
| `--version` | Print version and exit | `false` |
|
||||
| `--help` | Print help and exit | `false` |
|
||||
|
||||
## Server Environment Variables
|
||||
|
||||
| Variable | Purpose | Default |
|
||||
| --- | --- | --- |
|
||||
| `PORT` | Server listen port | `3000` |
|
||||
| `GIN_MODE` | Gin mode | release unless `debug` |
|
||||
| `LOG_LEVEL` | Log level | `info` |
|
||||
| `SESSION_SECRET` | Session signing secret | random on startup |
|
||||
| `SQLITE_PATH` | SQLite database path | `openflare.db` |
|
||||
| `DSN` | PostgreSQL DSN, preferred over SQLite | empty |
|
||||
| `SQL_DSN` | Legacy PostgreSQL DSN, lower priority than `DSN` | empty |
|
||||
| `REDIS_CONN_STRING` | Redis connection string | empty |
|
||||
| `UPLOAD_PATH` | Upload directory | `upload` |
|
||||
| `AGENT_TOKEN` | Legacy global Agent token | empty |
|
||||
|
||||
When `DSN` and `SQL_DSN` both exist, `DSN` wins. PostgreSQL is preferred when configured. If PostgreSQL is empty and a local SQLite file exists, Server migrates SQLite data at startup.
|
||||
|
||||
## Frontend Build Variables
|
||||
|
||||
| Variable | Purpose | Default |
|
||||
| --- | --- | --- |
|
||||
| `NEXT_PUBLIC_API_BASE_URL` | Frontend API base path | `/api` |
|
||||
| `NEXT_PUBLIC_APP_VERSION` | Displayed frontend version | `dev` |
|
||||
| `NEXT_DEV_BACKEND_URL` | Local dev backend proxy target | `http://127.0.0.1:3000` |
|
||||
|
||||
## Runtime Options
|
||||
|
||||
The settings page maintains these hot-updatable options:
|
||||
|
||||
| Option | Purpose | Default |
|
||||
| --- | --- | --- |
|
||||
| `AgentHeartbeatInterval` | Agent heartbeat interval in milliseconds | `10000` |
|
||||
| `NodeOfflineThreshold` | Node offline threshold in milliseconds | `120000` |
|
||||
| `AgentUpdateRepo` | Agent update repository | `Rain-kl/OpenFlare` |
|
||||
| `GeoIPProvider` | Node/IP region provider | `ipinfo` |
|
||||
| `DatabaseAutoCleanupEnabled` | Enable daily observability cleanup | `false` |
|
||||
| `DatabaseAutoCleanupRetentionDays` | Retention days | `30` |
|
||||
|
||||
OpenResty performance and cache options are also stored in the Option table, including `OpenRestyWorkerProcesses`, `OpenRestyWorkerConnections`, `OpenRestyProxyConnectTimeout`, `OpenRestyProxyReadTimeout`, `OpenRestyCacheEnabled`, `OpenRestyCachePath`, and `OpenRestyCacheMaxSize`.
|
||||
|
||||
## Agent Configuration
|
||||
|
||||
Agent supports the `-config` CLI flag, an `agent.json` file, and the `LOG_LEVEL` environment variable.
|
||||
|
||||
| Field | Purpose | Required | Default / behavior |
|
||||
| --- | --- | --- | --- |
|
||||
| `server_url` | Control plane URL | yes | none |
|
||||
| `agent_token` | Node-specific auth token | one of `agent_token` / `discovery_token` | empty |
|
||||
| `discovery_token` | Global token for first registration | one of `agent_token` / `discovery_token` | empty |
|
||||
| `node_name` | Node name | no | host name |
|
||||
| `node_ip` | Node IP | no | auto-detected |
|
||||
| `openresty_path` | Local OpenResty path | no | empty; Docker mode |
|
||||
| `openresty_container_name` | Docker container name | no | `openflare-openresty` |
|
||||
| `openresty_docker_image` | Docker image | no | `openresty/openresty:alpine` |
|
||||
| `openresty_observability_port` | Local observability port | no | `18081` |
|
||||
| `docker_binary` | Docker binary name or path | no | `docker` |
|
||||
| `data_dir` | Agent data directory | no | `data` under config directory |
|
||||
| `heartbeat_interval` | Heartbeat interval | no | `10000` ms |
|
||||
| `request_timeout` | HTTP timeout | no | `10000` ms |
|
||||
|
||||
`heartbeat_interval` and `request_timeout` accept milliseconds or Go duration strings.
|
||||
@@ -0,0 +1,10 @@
|
||||
# Reference
|
||||
|
||||
This section collects stable runtime, API, and repository information for deployment, integration, and troubleshooting.
|
||||
|
||||
| Page | Content |
|
||||
| --- | --- |
|
||||
| [Configuration](./configuration.md) | Server environment variables, CLI flags, runtime options, and Agent config fields |
|
||||
| [Commands and Scripts](./cli.md) | Startup, build, test, install, and uninstall commands |
|
||||
| [API Conventions](./api.md) | Management API and Agent API response, auth, and path conventions |
|
||||
| [Repository Layout](./repository.md) | Responsibilities of `openflare_server`, `openflare_agent`, `openflare_server/web`, and `docs` |
|
||||
@@ -0,0 +1,32 @@
|
||||
# Repository Layout
|
||||
|
||||
| Path | Responsibility |
|
||||
| --- | --- |
|
||||
| `openflare_server` | Gin + GORM + SQLite/PostgreSQL control plane |
|
||||
| `openflare_server/web` | Next.js 15 App Router admin frontend, statically exported and served by Go Server |
|
||||
| `openflare_agent` | Go Agent running on nodes |
|
||||
| `scripts` | Agent install, uninstall, and helper scripts |
|
||||
| `docs` | VitePress docs site, design baseline, development rules, deployment and configuration docs |
|
||||
|
||||
## Server Layers
|
||||
|
||||
| Directory | Responsibility |
|
||||
| --- | --- |
|
||||
| `controller/` | Parse input, call service, return response |
|
||||
| `service/` | Business logic, validation, transactions, rendering |
|
||||
| `model/` | Models, database versioning, migrations |
|
||||
| `router/` | Route registration |
|
||||
| `middleware/` | Auth, authorization, rate limiting, cross-cutting logic |
|
||||
| `common/` | Configuration, global state, initialization |
|
||||
| `utils/` | Pure helpers |
|
||||
|
||||
## Frontend Layers
|
||||
|
||||
| Directory | Responsibility |
|
||||
| --- | --- |
|
||||
| `app/` | Routes, layouts, page composition |
|
||||
| `features/` | Business-domain modules |
|
||||
| `components/` | Cross-feature reusable components |
|
||||
| `lib/` | API client, env, utilities, constants |
|
||||
| `store/` | Small cross-page UI state |
|
||||
| `types/` | Shared types |
|
||||
@@ -1,128 +0,0 @@
|
||||
# OpenFlare 前端开发规范
|
||||
|
||||
本文档约束 `openflare_server/web` 的正式前端工程。它描述的是 `1.0.0` 之后仍然有效的结构、请求层、组件、样式、状态管理与测试基线。
|
||||
|
||||
## 1. 技术基线
|
||||
|
||||
默认技术栈:
|
||||
|
||||
* Next.js 15 App Router
|
||||
* React 19
|
||||
* TypeScript 5
|
||||
* Tailwind CSS 4
|
||||
* TanStack Query
|
||||
* React Hook Form + Zod
|
||||
* Zustand
|
||||
* ESLint + Prettier
|
||||
* Vitest + Testing Library + Playwright
|
||||
* pnpm
|
||||
|
||||
要求:
|
||||
|
||||
* 默认使用 TypeScript
|
||||
* 默认使用函数组件
|
||||
* 默认使用 App Router
|
||||
* 前端必须支持 `light`、`dark`、`system` 三种主题模式
|
||||
|
||||
|
||||
## 2. 目录与分层
|
||||
|
||||
推荐目录:
|
||||
|
||||
```text
|
||||
app/
|
||||
components/
|
||||
features/
|
||||
lib/
|
||||
hooks/
|
||||
store/
|
||||
types/
|
||||
styles/
|
||||
tests/
|
||||
```
|
||||
|
||||
职责约束:
|
||||
|
||||
* `app/`:路由、布局、页面组装
|
||||
* `features/`:按业务域组织模块
|
||||
* `components/`:跨 feature 复用组件
|
||||
* `lib/`:请求客户端、环境变量、工具函数、常量
|
||||
* `store/`:少量跨页面 UI 状态
|
||||
* `types/`:共享类型定义
|
||||
|
||||
## 3. 路由与页面
|
||||
|
||||
页面文件只负责:
|
||||
|
||||
* 获取路由参数
|
||||
* 组织页面结构
|
||||
* 调用 feature 组件
|
||||
|
||||
页面不应负责:
|
||||
|
||||
* 手写复杂 API 细节
|
||||
* 编写复杂表单校验逻辑
|
||||
* 维护大量彼此耦合的局部状态
|
||||
|
||||
## 4. 数据请求与类型
|
||||
|
||||
### 4.1 请求层
|
||||
|
||||
所有 API 请求必须统一经过 `lib/api/`。
|
||||
|
||||
要求:
|
||||
|
||||
* 统一处理 `success/message/data` 响应结构
|
||||
* 统一处理鉴权失效、网络异常和通用错误消息
|
||||
* 统一维护资源接口与请求路径
|
||||
|
||||
禁止:
|
||||
|
||||
* 在页面组件中直接调用 `fetch('/api/...')`
|
||||
* 在多个组件中重复拼接同一接口路径
|
||||
|
||||
### 4.2 状态分层
|
||||
|
||||
* 服务端状态:TanStack Query
|
||||
* 页面临时状态:组件内部 `useState`
|
||||
* 跨页面 UI 状态:Zustand
|
||||
|
||||
不推荐:
|
||||
|
||||
* 用 Zustand 保存服务端主数据
|
||||
* 用 Context 代替完整数据层方案
|
||||
|
||||
### 4.3 类型
|
||||
|
||||
要求:
|
||||
|
||||
* 开启 TypeScript 严格模式
|
||||
* 禁止滥用 `any`
|
||||
* API 响应、表单输入、业务实体必须有明确类型
|
||||
|
||||
## 5. 表单与交互
|
||||
|
||||
统一使用:
|
||||
|
||||
* React Hook Form
|
||||
* Zod
|
||||
|
||||
高风险操作必须:
|
||||
|
||||
* 二次确认
|
||||
* 展示操作对象名称
|
||||
* 明确成功与失败反馈
|
||||
|
||||
## 6. 样式与主题
|
||||
|
||||
样式原则:
|
||||
|
||||
* 统一使用 Tailwind CSS 与现有 token 体系
|
||||
* 优先复用已有基础组件与布局组件
|
||||
* 保持视觉层级、留白与语义颜色一致
|
||||
|
||||
主题要求:
|
||||
|
||||
* 同时支持 `light`、`dark`、`system`
|
||||
* 用户选择必须持久化
|
||||
* 首屏尽量避免主题闪烁
|
||||
@@ -0,0 +1,79 @@
|
||||
# 接入 Agent
|
||||
|
||||
OpenFlare Agent 运行在节点侧,负责注册、心跳、同步配置、写入 OpenResty 文件、校验、reload、失败回滚与自更新。
|
||||
|
||||
## 接入方式
|
||||
|
||||
Agent 支持两种认证入口:
|
||||
|
||||
| 方式 | 适用场景 |
|
||||
| --- | --- |
|
||||
| `agent_token` | 已在管理端创建或分配节点,使用节点专属凭证接入 |
|
||||
| `discovery_token` | 首次自动注册节点,由 Server 置换为节点专属凭证 |
|
||||
|
||||
二者至少填写一个。
|
||||
|
||||
## 安装脚本
|
||||
|
||||
使用 `discovery_token`:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/install-agent.sh | bash -s -- \
|
||||
--server-url http://your-server:3000 \
|
||||
--discovery-token YOUR_DISCOVERY_TOKEN
|
||||
```
|
||||
|
||||
使用节点专属 `agent_token`:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/install-agent.sh | bash -s -- \
|
||||
--server-url http://your-server:3000 \
|
||||
--agent-token YOUR_AGENT_TOKEN
|
||||
```
|
||||
|
||||
安装脚本会写入 `/opt/openflare-agent`,创建 `openflare-agent.service`,并可重复执行以重装或升级 Agent。
|
||||
|
||||
## 配置文件示例
|
||||
|
||||
```json
|
||||
{
|
||||
"server_url": "http://127.0.0.1:3000",
|
||||
"agent_token": "replace-with-node-auth-token",
|
||||
"data_dir": "./data",
|
||||
"openresty_container_name": "openflare-openresty",
|
||||
"openresty_docker_image": "openresty/openresty:alpine",
|
||||
"openresty_observability_port": 18081,
|
||||
"observability_replay_minutes": 15,
|
||||
"heartbeat_interval": 10000,
|
||||
"request_timeout": 10000
|
||||
}
|
||||
```
|
||||
|
||||
未配置 `openresty_path` 时,Agent 默认使用 Docker OpenResty。裸 OpenResty 模式需要显式配置本机路径和必要的配置写入目录。
|
||||
|
||||
## 源码运行
|
||||
|
||||
```bash
|
||||
cd openflare_agent
|
||||
export LOG_LEVEL='info'
|
||||
go run ./cmd/agent -config /path/to/agent.json
|
||||
```
|
||||
|
||||
## 编译后二进制运行
|
||||
|
||||
```bash
|
||||
cd openflare_agent
|
||||
go build -o openflare-agent ./cmd/agent
|
||||
export LOG_LEVEL='info'
|
||||
./openflare-agent -config /path/to/agent.json
|
||||
```
|
||||
|
||||
## 卸载
|
||||
|
||||
如需彻底卸载 Agent 并清空本地数据:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/uninstall-agent.sh | bash
|
||||
```
|
||||
|
||||
卸载脚本会停止并移除 `openflare-agent.service`,删除 `/opt/openflare-agent`,并根据配置尝试清理 Docker OpenResty 容器。
|
||||
@@ -1,51 +1,25 @@
|
||||
# OpenFlare 部署说明
|
||||
# 部署说明
|
||||
|
||||
本文档只保留 OpenFlare `1.0.0` 的当前部署基线、联调入口与升级方式。
|
||||
本文档说明 OpenFlare `1.0.0` 之后的部署基线、联调入口、升级方式与 Agent 一键部署流程。
|
||||
|
||||
## 1. 前置条件
|
||||
## 前置条件
|
||||
|
||||
### 1.1 Server
|
||||
Server:
|
||||
|
||||
* Go 1.24+
|
||||
* Go 1.25+
|
||||
* Node.js 18+
|
||||
* 可写 SQLite 文件目录,或可访问的 PostgreSQL 实例
|
||||
|
||||
### 1.2 Agent
|
||||
Agent:
|
||||
|
||||
* Go 1.24+
|
||||
* Go 1.25+
|
||||
* 对 Agent 数据目录有写权限
|
||||
* 本机模式下可执行 `openresty -t` 与 `openresty -s reload`
|
||||
* Docker 模式下具备 Docker 执行权限
|
||||
|
||||
## 2. 启动 Server
|
||||
## Docker Compose 启动 Server
|
||||
|
||||
### 2.1 构建前端
|
||||
|
||||
```bash
|
||||
cd openflare_server/web
|
||||
corepack enable
|
||||
pnpm install
|
||||
pnpm build
|
||||
```
|
||||
|
||||
`pnpm build` 会生成供 Go Server 托管的静态产物。
|
||||
|
||||
### 2.2 源码启动
|
||||
|
||||
```bash
|
||||
cd openflare_server
|
||||
export SESSION_SECRET='replace-with-random-string'
|
||||
export SQLITE_PATH='./openflare.db'
|
||||
export LOG_LEVEL='info'
|
||||
# 可选:设置后优先使用 PostgreSQL。
|
||||
# 如果 PostgreSQL 为空且本地 SQLite 文件存在,启动时会自动迁移数据。
|
||||
# export DSN='postgres://openflare:secret@127.0.0.1:5432/openflare?sslmode=disable'
|
||||
go run .
|
||||
```
|
||||
|
||||
默认监听 `3000` 端口。
|
||||
|
||||
### 2.3 Docker Compose 启动
|
||||
推荐生产部署使用 PostgreSQL:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
@@ -91,20 +65,43 @@ volumes:
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
### 2.4 首次登录
|
||||
首次访问 `http://localhost:3000`,默认账号为 `root` / `123456`。登录后请立即修改默认密码。
|
||||
|
||||
访问 `http://localhost:3000`
|
||||
## 源码启动 Server
|
||||
|
||||
默认账号:
|
||||
先构建管理端前端:
|
||||
|
||||
* 用户名:`root`
|
||||
* 密码:`123456`
|
||||
```bash
|
||||
cd openflare_server/web
|
||||
corepack enable
|
||||
pnpm install
|
||||
pnpm build
|
||||
```
|
||||
|
||||
### 2.5 Swagger
|
||||
再启动 Server:
|
||||
|
||||
登录管理端后访问:`http://localhost:3000/swagger/index.html`
|
||||
```bash
|
||||
cd openflare_server
|
||||
export SESSION_SECRET='replace-with-random-string'
|
||||
export SQLITE_PATH='./openflare.db'
|
||||
export LOG_LEVEL='info'
|
||||
# 可选:设置后优先使用 PostgreSQL。
|
||||
# 如果 PostgreSQL 为空且本地 SQLite 文件存在,启动时会自动迁移数据。
|
||||
# export DSN='postgres://openflare:secret@127.0.0.1:5432/openflare?sslmode=disable'
|
||||
go run .
|
||||
```
|
||||
|
||||
如需在本地重新生成文档:
|
||||
默认监听 `3000` 端口。
|
||||
|
||||
## Swagger
|
||||
|
||||
登录管理端后访问:
|
||||
|
||||
```text
|
||||
http://localhost:3000/swagger/index.html
|
||||
```
|
||||
|
||||
本地重新生成 Swagger:
|
||||
|
||||
```bash
|
||||
go install github.com/swaggo/swag/cmd/swag@v1.16.4
|
||||
@@ -112,11 +109,11 @@ cd openflare_server
|
||||
swag init -g main.go -o docs
|
||||
```
|
||||
|
||||
## 3. Agent 配置
|
||||
## Agent 接入模式
|
||||
|
||||
当前支持两种接入模式。
|
||||
Agent 支持两种接入模式。
|
||||
|
||||
### 3.1 使用节点专属 `agent_token`
|
||||
使用节点专属 `agent_token`:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -132,7 +129,7 @@ swag init -g main.go -o docs
|
||||
}
|
||||
```
|
||||
|
||||
### 3.2 使用全局 `discovery_token`
|
||||
使用全局 `discovery_token`:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -150,13 +147,44 @@ swag init -g main.go -o docs
|
||||
|
||||
说明:
|
||||
|
||||
* `agent_token` 与 `discovery_token` 至少填写一个
|
||||
* 未配置 `openresty_path` 时默认使用 Docker OpenResty
|
||||
* Agent 会暴露本机观测端口并在 server 恢复后补传最近窗口数据
|
||||
* `agent_token` 与 `discovery_token` 至少填写一个。
|
||||
* 未配置 `openresty_path` 时默认使用 Docker OpenResty。
|
||||
* Agent 会暴露本机观测端口并在 Server 恢复后补传最近窗口数据。
|
||||
|
||||
## 4. 启动 Agent
|
||||
## 一键部署 Agent
|
||||
|
||||
### 4.1 直接运行
|
||||
使用 `discovery_token`:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/install-agent.sh | bash -s -- \
|
||||
--server-url http://your-server:3000 \
|
||||
--discovery-token YOUR_DISCOVERY_TOKEN
|
||||
```
|
||||
|
||||
使用节点专属 `agent_token`:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/install-agent.sh | bash -s -- \
|
||||
--server-url http://your-server:3000 \
|
||||
--agent-token YOUR_AGENT_TOKEN
|
||||
```
|
||||
|
||||
支持参数:
|
||||
|
||||
| 参数 | 说明 |
|
||||
| --- | --- |
|
||||
| `--server-url` | Server 地址 |
|
||||
| `--discovery-token` | 首次自动注册 Token |
|
||||
| `--agent-token` | 节点专属 Token |
|
||||
| `--install-dir` | 安装目录 |
|
||||
| `--repo` | 下载 Agent 的仓库 |
|
||||
| `--no-service` | 不创建系统服务 |
|
||||
|
||||
安装脚本会下载最新 Agent、生成 `agent.json`、创建 `openflare-agent.service` 并启动服务。
|
||||
|
||||
## 手动启动 Agent
|
||||
|
||||
源码运行:
|
||||
|
||||
```bash
|
||||
cd openflare_agent
|
||||
@@ -164,7 +192,7 @@ export LOG_LEVEL='info'
|
||||
go run ./cmd/agent -config /path/to/agent.json
|
||||
```
|
||||
|
||||
### 4.2 编译后二进制运行
|
||||
编译后二进制运行:
|
||||
|
||||
```bash
|
||||
cd openflare_agent
|
||||
@@ -173,71 +201,9 @@ export LOG_LEVEL='info'
|
||||
./openflare-agent -config /path/to/agent.json
|
||||
```
|
||||
|
||||
## 5. 最小联调步骤
|
||||
## 卸载 Agent
|
||||
|
||||
1. 在管理端准备 `agent_token` 或 `discovery_token`
|
||||
2. 启动 Agent 并确认节点上线
|
||||
3. 新增一条启用中的反代规则
|
||||
4. 生成并激活新版本
|
||||
5. 确认 Agent 拉取配置、执行 `openresty -t`、reload 并上报结果
|
||||
|
||||
预期管理端可看到:
|
||||
|
||||
* 节点在线状态
|
||||
* 节点当前版本
|
||||
* 最近一次应用结果
|
||||
* 自动注册后的专属 `agent_token`
|
||||
|
||||
## 6. 升级说明
|
||||
|
||||
* Root 用户可在管理端顶栏检查并升级 Server 正式版
|
||||
* 如需尝试 preview 版本,可手动检查对应发布
|
||||
* 节点 Agent 默认只跟随正式版自动更新;preview 升级需要手动触发
|
||||
* 也可通过上传 Server 二进制的方式执行确认升级
|
||||
|
||||
## 7. 常用验证命令
|
||||
|
||||
### 7.1 Server
|
||||
|
||||
```bash
|
||||
cd openflare_server
|
||||
GOCACHE=/tmp/openflare-go-cache go test ./...
|
||||
```
|
||||
|
||||
### 7.2 Agent
|
||||
|
||||
```bash
|
||||
cd openflare_agent
|
||||
GOCACHE=/tmp/openflare-go-cache go test ./...
|
||||
```
|
||||
|
||||
### 7.3 Frontend
|
||||
|
||||
```bash
|
||||
cd openflare_server/web
|
||||
pnpm build
|
||||
```
|
||||
|
||||
## 8. Agent 一键部署
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/install-agent.sh | bash -s -- \
|
||||
--server-url http://your-server:3000 \
|
||||
--discovery-token YOUR_DISCOVERY_TOKEN
|
||||
```
|
||||
|
||||
支持参数:
|
||||
|
||||
* `--server-url`
|
||||
* `--discovery-token`
|
||||
* `--agent-token`
|
||||
* `--install-dir`
|
||||
* `--repo`
|
||||
* `--no-service`
|
||||
|
||||
安装脚本会下载最新 Agent、生成 `agent.json`、创建 `openflare-agent.service` 并启动服务。
|
||||
|
||||
如需彻底卸载 Agent 并清空本地数据,可执行:
|
||||
如需彻底卸载 Agent 并清空本地数据:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/uninstall-agent.sh | bash
|
||||
@@ -245,14 +211,52 @@ curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/unin
|
||||
|
||||
支持参数:
|
||||
|
||||
* `--install-dir`
|
||||
* `--service-name`
|
||||
| 参数 | 说明 |
|
||||
| --- | --- |
|
||||
| `--install-dir` | Agent 安装目录 |
|
||||
| `--service-name` | systemd 服务名 |
|
||||
|
||||
卸载脚本会先停止 Agent、移除 `openflare-agent.service`、删除整个安装目录,再根据卸载前保存的 `agent.json` 判断 OpenResty 安装方式:
|
||||
|
||||
* Docker 模式:删除对应容器,并尝试移除 OpenResty 镜像
|
||||
* 本机 `openresty_path` 模式:不改动本机 OpenResty,仅提示用户手动卸载
|
||||
* Docker 模式:删除对应容器,并尝试移除 OpenResty 镜像。
|
||||
* 本机 `openresty_path` 模式:不改动本机 OpenResty,仅提示用户手动卸载。
|
||||
|
||||
## 9. 文档维护要求
|
||||
## 最小联调步骤
|
||||
|
||||
部署方式、升级方式、接入模式或联调流程变化时,同步更新本文档和 `README.md`。
|
||||
1. 在管理端准备 `agent_token` 或 `discovery_token`。
|
||||
2. 启动 Agent 并确认节点上线。
|
||||
3. 新增一条启用中的反代规则。
|
||||
4. 生成并激活新版本。
|
||||
5. 确认 Agent 拉取配置、执行 `openresty -t`、reload 并上报结果。
|
||||
|
||||
预期管理端可看到节点在线状态、节点当前版本、最近一次应用结果,以及自动注册后的专属 `agent_token`。
|
||||
|
||||
## 升级说明
|
||||
|
||||
* Root 用户可在管理端顶栏检查并升级 Server 正式版。
|
||||
* 如需尝试 preview 版本,可手动检查对应发布。
|
||||
* 节点 Agent 默认只跟随正式版自动更新;preview 升级需要手动触发。
|
||||
* 也可通过上传 Server 二进制的方式执行确认升级。
|
||||
|
||||
## 常用验证命令
|
||||
|
||||
Server:
|
||||
|
||||
```bash
|
||||
cd openflare_server
|
||||
GOCACHE=/tmp/openflare-go-cache go test ./...
|
||||
```
|
||||
|
||||
Agent:
|
||||
|
||||
```bash
|
||||
cd openflare_agent
|
||||
GOCACHE=/tmp/openflare-go-cache go test ./...
|
||||
```
|
||||
|
||||
Frontend:
|
||||
|
||||
```bash
|
||||
cd openflare_server/web
|
||||
pnpm build
|
||||
```
|
||||
@@ -0,0 +1,45 @@
|
||||
# 发布第一份配置
|
||||
|
||||
OpenFlare 的发布链路以完整配置版本为中心。你修改网站配置后,需要生成新版本并激活,Agent 才会在后续 heartbeat 中拉取并应用。
|
||||
|
||||
## 创建网站配置
|
||||
|
||||
在管理端新增网站配置时至少需要:
|
||||
|
||||
| 字段 | 说明 |
|
||||
| --- | --- |
|
||||
| 网站名称 | 业务唯一标识;未显式填写时默认使用主域名 |
|
||||
| 域名 | 至少一个域名,第一项视为主域名 |
|
||||
| 源站地址 | 合法的 `http://` 或 `https://` 上游地址 |
|
||||
| 启用状态 | 只有启用的网站配置会参与发布渲染 |
|
||||
|
||||
同一个域名只能属于一个网站配置。同一网站内的流量限制、反向代理和缓存配置按站点共享。
|
||||
|
||||
## 绑定证书
|
||||
|
||||
HTTPS 证书按域名绑定。没有绑定证书的域名不会被自动放入 `443 ssl` server 块。
|
||||
|
||||
如果一个网站包含多个域名,发布渲染会按证书分组生成 HTTPS 配置,并确保所有域名仍属于同一站点快照。
|
||||
|
||||
## 发布与激活
|
||||
|
||||
标准链路:
|
||||
|
||||
```text
|
||||
修改规则 -> 预览/查看 diff -> 发布 -> 生成完整配置版本 -> 激活版本 -> Agent 拉取 -> 本地应用 -> 上报结果
|
||||
```
|
||||
|
||||
发布时 Server 会读取全部启用的网站配置、OpenResty 主配置模板、性能参数与缓存参数,渲染完整 OpenResty 配置,计算 `checksum`,写入 `config_versions`,再切换激活版本。
|
||||
|
||||
## 验证结果
|
||||
|
||||
发布后在管理端确认:
|
||||
|
||||
| 位置 | 期望结果 |
|
||||
| --- | --- |
|
||||
| 节点列表 | 节点在线 |
|
||||
| 节点详情 | 当前版本与激活版本一致 |
|
||||
| 应用记录 | 最近一次应用成功 |
|
||||
| 版本页面 | 新版本处于激活状态 |
|
||||
|
||||
如果目标版本应用失败并回滚,Agent 会在本地阻断同一 `version + checksum` 的重复应用,直到控制面激活版本或 checksum 发生变化。
|
||||
@@ -0,0 +1,15 @@
|
||||
# 指南
|
||||
|
||||
本部分面向使用者和部署者,帮助你把 OpenFlare 从首次启动推进到第一份可运行的代理配置。
|
||||
|
||||
推荐阅读顺序:
|
||||
|
||||
1. [快速开始](./quick-start.md):用 Docker Compose 启动 Server,并完成首次登录。
|
||||
2. [部署说明](./deployment.md):查看生产部署、Agent 一键安装、联调与升级。
|
||||
3. [SSO 登录配置](./sso.md):配置 GitHub OAuth 或标准 OIDC 登录入口。
|
||||
4. [启动 Server](./server.md):了解源码启动、前端构建和 Swagger 入口。
|
||||
5. [接入 Agent](./agent.md):选择 `agent_token` 或 `discovery_token`,让节点上线。
|
||||
6. [发布第一份配置](./first-site.md):创建网站配置,发布并确认节点应用。
|
||||
7. [升级与维护](./upgrade.md):了解升级、卸载、验证和日常维护入口。
|
||||
|
||||
如果你要参与开发,先阅读 [设计](../design/) 与 [开发约束](../design/development.md),再进入代码修改。
|
||||
@@ -0,0 +1,87 @@
|
||||
# 快速开始
|
||||
|
||||
OpenFlare 的最小运行单元包含一个 Server 和至少一个 Agent。Server 负责管理端、配置版本与节点状态,Agent 运行在代理节点上,负责写入 OpenResty 配置并 reload。
|
||||
|
||||
## 启动 Server
|
||||
|
||||
推荐使用 PostgreSQL 与 Docker Compose:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_DB: openflare
|
||||
POSTGRES_USER: openflare
|
||||
POSTGRES_PASSWORD: replace-with-strong-password
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U openflare -d openflare"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
openflare:
|
||||
image: ghcr.io/rain-kl/openflare:latest
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
- "3000:3000"
|
||||
environment:
|
||||
SESSION_SECRET: replace-with-random-string
|
||||
DSN: postgres://openflare:replace-with-strong-password@postgres:5432/openflare?sslmode=disable
|
||||
GIN_MODE: release
|
||||
LOG_LEVEL: info
|
||||
|
||||
volumes:
|
||||
postgres-data:
|
||||
```
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
访问 `http://localhost:3000`。
|
||||
|
||||
默认账号:
|
||||
|
||||
| 用户名 | 密码 |
|
||||
| --- | --- |
|
||||
| `root` | `123456` |
|
||||
|
||||
首次登录后请立即修改默认密码,并按需关闭新用户注册。
|
||||
|
||||
## 接入第一个节点
|
||||
|
||||
在管理端准备 `discovery_token` 或节点专属 `agent_token`,然后在节点上执行安装脚本。
|
||||
|
||||
使用 `discovery_token`:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/install-agent.sh | bash -s -- \
|
||||
--server-url http://your-server:3000 \
|
||||
--discovery-token YOUR_DISCOVERY_TOKEN
|
||||
```
|
||||
|
||||
使用节点专属 `agent_token`:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/install-agent.sh | bash -s -- \
|
||||
--server-url http://your-server:3000 \
|
||||
--agent-token YOUR_AGENT_TOKEN
|
||||
```
|
||||
|
||||
安装脚本默认把 Agent 放在 `/opt/openflare-agent`,创建 `openflare-agent.service`,并在未显式配置本机 OpenResty 时使用 Docker OpenResty。
|
||||
|
||||
## 发布第一份配置
|
||||
|
||||
1. 在管理端新增网站配置,填写域名与源站地址。
|
||||
2. 发布前查看预览或变更摘要。
|
||||
3. 激活新版本。
|
||||
4. 等待 Agent 通过 heartbeat 发现版本变更并应用。
|
||||
|
||||
版本号格式为 `YYYYMMDD-NNN`。历史版本不可变,回滚通过重新激活旧版本完成。
|
||||
@@ -0,0 +1,66 @@
|
||||
# 启动 Server
|
||||
|
||||
OpenFlare Server 是 Gin + GORM 单体控制面,负责管理端 UI、管理 API、Agent API、配置渲染、版本发布与状态存储。
|
||||
|
||||
## 前置条件
|
||||
|
||||
| 项目 | 要求 |
|
||||
| --- |-----------------------------------|
|
||||
| Go | `1.25+` |
|
||||
| Node.js | `18+` |
|
||||
| 数据库 | SQLite 文件目录可写,或可访问的 PostgreSQL 实例 |
|
||||
|
||||
生产环境建议显式配置 `SESSION_SECRET`,并优先使用 PostgreSQL。
|
||||
|
||||
## 构建管理端前端
|
||||
|
||||
```bash
|
||||
cd openflare_server/web
|
||||
corepack enable
|
||||
pnpm install
|
||||
pnpm build
|
||||
```
|
||||
|
||||
`pnpm build` 会生成供 Go Server 托管的静态产物。
|
||||
|
||||
## 源码启动
|
||||
|
||||
```bash
|
||||
cd openflare_server
|
||||
export SESSION_SECRET='replace-with-random-string'
|
||||
export SQLITE_PATH='./openflare.db'
|
||||
export LOG_LEVEL='info'
|
||||
# 可选:设置后优先使用 PostgreSQL。
|
||||
# export DSN='postgres://openflare:secret@127.0.0.1:5432/openflare?sslmode=disable'
|
||||
go run .
|
||||
```
|
||||
|
||||
默认监听 `3000` 端口。也可以通过命令行指定:
|
||||
|
||||
```bash
|
||||
go run . --port 3000 --log-dir ./logs
|
||||
```
|
||||
|
||||
## 首次登录
|
||||
|
||||
访问 `http://localhost:3000`。
|
||||
|
||||
| 用户名 | 密码 |
|
||||
| --- | --- |
|
||||
| `root` | `123456` |
|
||||
|
||||
## Swagger
|
||||
|
||||
登录管理端后访问:
|
||||
|
||||
```text
|
||||
http://localhost:3000/swagger/index.html
|
||||
```
|
||||
|
||||
如需在本地重新生成 Swagger 文档:
|
||||
|
||||
```bash
|
||||
go install github.com/swaggo/swag/cmd/swag@v1.16.4
|
||||
cd openflare_server
|
||||
swag init -g main.go -o docs
|
||||
```
|
||||
@@ -0,0 +1,104 @@
|
||||
# SSO 登录配置
|
||||
|
||||
OpenFlare 支持通过认证源配置第三方登录入口。当前支持 GitHub OAuth 与标准 OIDC Provider,例如 Logto、authentik、Keycloak、Casdoor 等。
|
||||
|
||||
认证源配置完成并启用后,会显示在登录页的第三方账号登录区域。用户可以通过第三方账号登录,也可以在已登录状态下把第三方账号绑定到当前本地账号。
|
||||
|
||||
## 使用前准备
|
||||
|
||||
你需要先准备:
|
||||
|
||||
| 项目 | 说明 |
|
||||
| --- | --- |
|
||||
| OpenFlare 访问地址 | 用户浏览器实际访问的地址,例如 `https://openflare.example.com` |
|
||||
| 认证源名称 | OpenFlare 内部唯一标识,例如 `github`、`company-oidc` |
|
||||
| Client ID | 第三方平台创建应用后提供 |
|
||||
| Client Secret | 第三方平台创建应用后提供 |
|
||||
| OIDC Discovery URL | 仅 OIDC 需要,例如 `https://idp.example.com/.well-known/openid-configuration` |
|
||||
|
||||
**确认系统设置->通用设置->服务器地址能正确和域名匹配**
|
||||
|
||||
认证源名称只能包含字母、数字、短横线或下划线,并且必须以字母或数字开头。认证源名称会出现在回调地址中,保存后如需修改名称,也必须同步修改第三方平台中的回调地址。
|
||||
|
||||
## 回调地址
|
||||
|
||||
第三方平台中的 Redirect URI / Callback URL 填写格式为:
|
||||
|
||||
```text
|
||||
<OpenFlare 访问地址>/oauth/<认证源名称>
|
||||
```
|
||||
|
||||
示例:
|
||||
|
||||
```text
|
||||
https://openflare.example.com/oauth/github
|
||||
https://openflare.example.com/oauth/company-oidc
|
||||
```
|
||||
|
||||
在管理端新增或修改认证源时,表单会根据当前浏览器访问地址和你输入的认证源名称自动显示应填写的回调地址。
|
||||
|
||||
## 配置 GitHub 登录
|
||||
|
||||
1. 在 GitHub 创建 OAuth App。
|
||||
2. `Homepage URL` 填写 OpenFlare 访问地址。
|
||||
3. `Authorization callback URL` 填写 OpenFlare 显示的回调地址,例如 `https://openflare.example.com/oauth/github`。
|
||||
4. 复制 GitHub 提供的 Client ID 和 Client Secret。
|
||||
5. 登录 OpenFlare 管理端,进入“设置 -> 系统设置 -> 配置认证源”。
|
||||
6. 新增认证源,类型选择 `GitHub`。
|
||||
7. 填写认证源名称、展示名称、Client ID、Client Secret。
|
||||
8. Scope 默认使用 `user:email`,通常无需修改。
|
||||
9. 保存并启用认证源。
|
||||
|
||||
启用后,登录页会显示对应的 GitHub 登录按钮。
|
||||
|
||||
## 配置 OIDC 登录
|
||||
|
||||
1. 在 OIDC Provider 中创建应用或客户端。
|
||||
2. 应用类型选择 Web / Confidential Client。
|
||||
3. Redirect URI / Callback URL 填写 OpenFlare 显示的回调地址,例如 `https://openflare.example.com/oauth/company-oidc`。
|
||||
4. 复制 Client ID 和 Client Secret。
|
||||
5. 获取 Provider 的 Discovery URL,通常以 `/.well-known/openid-configuration` 结尾。
|
||||
6. 登录 OpenFlare 管理端,进入“设置 -> 系统设置 -> 配置认证源”。
|
||||
7. 新增认证源,类型选择 `OIDC`。
|
||||
8. 填写认证源名称、展示名称、Client ID、Client Secret、OIDC Discovery URL。
|
||||
9. Scope 默认使用 `openid profile email`。如果 Provider 限制了 scope,请按 Provider 允许的值调整。
|
||||
10. 保存并启用认证源。
|
||||
|
||||
启用后,登录页会显示对应的 OIDC 登录按钮。
|
||||
|
||||
## 登录与绑定行为
|
||||
|
||||
第三方账号回到 OpenFlare 后按以下规则处理:
|
||||
|
||||
| 场景 | 行为 |
|
||||
| --- | --- |
|
||||
| 第三方账号已绑定本地用户 | 直接登录 |
|
||||
| 用户已登录并发起第三方授权 | 绑定到当前本地用户 |
|
||||
| 第三方账号未绑定,且允许注册 | 自动创建普通用户并绑定 |
|
||||
| 第三方账号未绑定,且关闭注册 | 要求输入已有本地账号密码完成绑定 |
|
||||
|
||||
如果希望只允许已有用户使用 SSO,可以关闭用户注册。未绑定的第三方账号会进入绑定已有账号流程。
|
||||
|
||||
## 修改认证源
|
||||
|
||||
修改认证源时,Client Secret 输入框留空表示保留已有密钥;填写新值则会覆盖保存。
|
||||
|
||||
如果修改了认证源名称,回调地址也会随之变化。你必须到第三方平台同步修改 Redirect URI / Callback URL,否则第三方平台会拒绝回调或返回错误。
|
||||
|
||||
## 常见问题
|
||||
|
||||
### 返回 `invalid_scope`
|
||||
|
||||
说明第三方平台不允许当前配置的 Scope。OIDC 默认 Scope 是 `openid profile email`,GitHub 默认 Scope 是 `user:email`。请到认证源编辑页调整 Scope,或在第三方平台放行对应 Scope。
|
||||
|
||||
### 提示回调地址不匹配
|
||||
|
||||
检查第三方平台中配置的 Redirect URI / Callback URL 是否与 OpenFlare 表单提示完全一致。协议、域名、端口和路径都必须一致。
|
||||
|
||||
### 登录页没有显示第三方登录按钮
|
||||
|
||||
检查认证源是否已启用,并确认 Client ID 和 Client Secret 已保存。启用认证源前,OpenFlare 会校验这些字段。
|
||||
|
||||
### 已经保存 Client Secret,但列表不显示明文
|
||||
|
||||
这是预期行为。OpenFlare 不会通过 API 回显 Client Secret,只显示该密钥是否已配置。
|
||||
@@ -0,0 +1,53 @@
|
||||
# 升级与维护
|
||||
|
||||
## Server 升级
|
||||
|
||||
Root 用户可以在管理端顶栏检查并升级 Server 正式版。也可以通过上传 Server 二进制的方式执行确认升级。
|
||||
|
||||
如需尝试 preview 版本,可手动检查对应发布。生产环境建议优先使用正式版。
|
||||
|
||||
## Agent 升级
|
||||
|
||||
节点 Agent 默认只跟随正式版自动更新。preview 升级需要手动触发。
|
||||
|
||||
安装脚本可重复执行,用于重装或升级 Agent:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/install-agent.sh | bash -s -- \
|
||||
--server-url http://your-server:3000 \
|
||||
--agent-token YOUR_AGENT_TOKEN
|
||||
```
|
||||
|
||||
## 数据维护
|
||||
|
||||
管理端设置页可以维护观测数据自动清理策略:
|
||||
|
||||
| 配置项 | 说明 |
|
||||
| --- | --- |
|
||||
| `DatabaseAutoCleanupEnabled` | 是否启用每日自动清理 |
|
||||
| `DatabaseAutoCleanupRetentionDays` | 自动清理保留天数,至少 1 天 |
|
||||
|
||||
开启后,Server 会在每天凌晨 3 点清理访问日志、指标快照与请求报告。
|
||||
|
||||
## 常用验证命令
|
||||
|
||||
Server:
|
||||
|
||||
```bash
|
||||
cd openflare_server
|
||||
GOCACHE=/tmp/openflare-go-cache go test ./...
|
||||
```
|
||||
|
||||
Agent:
|
||||
|
||||
```bash
|
||||
cd openflare_agent
|
||||
GOCACHE=/tmp/openflare-go-cache go test ./...
|
||||
```
|
||||
|
||||
Frontend:
|
||||
|
||||
```bash
|
||||
cd openflare_server/web
|
||||
pnpm build
|
||||
```
|
||||
@@ -0,0 +1,32 @@
|
||||
---
|
||||
layout: home
|
||||
|
||||
hero:
|
||||
name: OpenFlare
|
||||
text: 自托管 OpenResty 控制面
|
||||
tagline: 管理反向代理规则、配置发布、节点同步、TLS 证书与基础观测。
|
||||
actions:
|
||||
- theme: brand
|
||||
text: 快速开始
|
||||
link: /guide/quick-start
|
||||
- theme: alt
|
||||
text: 设计边界
|
||||
link: /design/
|
||||
- theme: alt
|
||||
text: GitHub
|
||||
link: https://github.com/Rain-kl/OpenFlare
|
||||
|
||||
features:
|
||||
- icon: 🧭
|
||||
title: 统一控制面
|
||||
details: 在一个管理端维护网站、域名、源站、证书、节点与版本状态。
|
||||
- icon: 🚀
|
||||
title: 不可变发布
|
||||
details: 每次发布生成完整 OpenResty 配置快照,可预览、激活和回滚。
|
||||
- icon: 🔁
|
||||
title: Agent 自动应用
|
||||
details: 节点侧自动拉取、校验、reload,并在失败时回滚到可运行配置。
|
||||
- icon: 📊
|
||||
title: 基础观测
|
||||
details: 提供请求聚合、访问分析、资源快照、健康事件与节点详情。
|
||||
---
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"$schema": "./node_modules/@lunariajs/core/config.schema.json",
|
||||
"repository": {
|
||||
"name": "Rain-kl/OpenFlare",
|
||||
"rootDir": "docs"
|
||||
},
|
||||
"files": [
|
||||
{
|
||||
"location": "**/config.ts",
|
||||
"pattern": "@lang/@path",
|
||||
"type": "universal"
|
||||
},
|
||||
{
|
||||
"location": "**/*.md",
|
||||
"pattern": "@lang/@path",
|
||||
"type": "universal"
|
||||
}
|
||||
],
|
||||
"defaultLocale": {
|
||||
"label": "简体中文",
|
||||
"lang": "zh"
|
||||
},
|
||||
"locales": [
|
||||
{
|
||||
"label": "English",
|
||||
"lang": "en"
|
||||
}
|
||||
],
|
||||
"outDir": ".vitepress/dist/_translations",
|
||||
"ignoreKeywords": ["lunaria-ignore"]
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "openflare-docs",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vitepress dev",
|
||||
"build": "vitepress build",
|
||||
"preview": "vitepress preview",
|
||||
"lunaria:build": "lunaria build",
|
||||
"lunaria:open": "open-cli .vitepress/dist/_translations/index.html"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@lunariajs/core": "^0.1.1",
|
||||
"markdown-it-mathjax3": "^4.3.2",
|
||||
"open-cli": "^8.0.0",
|
||||
"postcss-rtlcss": "^5.7.1",
|
||||
"vitepress": "2.0.0-alpha.17",
|
||||
"vitepress-plugin-llms": "^1.11.0"
|
||||
}
|
||||
}
|
||||
Generated
+2940
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,46 @@
|
||||
# API 约定
|
||||
|
||||
OpenFlare 的管理端 API 与 Agent API 都使用 JSON。
|
||||
|
||||
## 响应结构
|
||||
|
||||
成功与失败都应返回清晰的 `message`:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "",
|
||||
"data": {}
|
||||
}
|
||||
```
|
||||
|
||||
## 路径约定
|
||||
|
||||
| 类型 | 约定 |
|
||||
| --- | --- |
|
||||
| 管理端 API | 由管理端 Session 鉴权 |
|
||||
| Agent API | 固定放在 `/api/agent/*` |
|
||||
| 只读接口 | 使用 `GET` |
|
||||
| 变更类接口 | 使用 `POST` |
|
||||
|
||||
## 鉴权
|
||||
|
||||
管理端继续复用现有登录、角色与 Session。
|
||||
|
||||
Agent 正式请求统一使用节点专属 `agent_token`,首次接入可使用全局 `discovery_token`。Agent 请求头固定为:
|
||||
|
||||
```http
|
||||
X-Agent-Token: <token>
|
||||
```
|
||||
|
||||
日志中不得打印完整 Token。
|
||||
|
||||
## Swagger
|
||||
|
||||
登录管理端后可访问:
|
||||
|
||||
```text
|
||||
/swagger/index.html
|
||||
```
|
||||
|
||||
Swagger 文件位于 `openflare_server/docs`,由 `swag init` 生成。
|
||||
@@ -0,0 +1,90 @@
|
||||
# 命令与脚本
|
||||
|
||||
## Server
|
||||
|
||||
源码启动:
|
||||
|
||||
```bash
|
||||
cd openflare_server
|
||||
export SESSION_SECRET='replace-with-random-string'
|
||||
export SQLITE_PATH='./openflare.db'
|
||||
export LOG_LEVEL='info'
|
||||
go run .
|
||||
```
|
||||
|
||||
指定监听端口与日志目录:
|
||||
|
||||
```bash
|
||||
go run . --port 3000 --log-dir ./logs
|
||||
```
|
||||
|
||||
测试:
|
||||
|
||||
```bash
|
||||
cd openflare_server
|
||||
GOCACHE=/tmp/openflare-go-cache go test ./...
|
||||
```
|
||||
|
||||
## Frontend
|
||||
|
||||
开发:
|
||||
|
||||
```bash
|
||||
cd openflare_server/web
|
||||
pnpm install
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
构建静态产物:
|
||||
|
||||
```bash
|
||||
cd openflare_server/web
|
||||
pnpm build
|
||||
```
|
||||
|
||||
## Agent
|
||||
|
||||
源码运行:
|
||||
|
||||
```bash
|
||||
cd openflare_agent
|
||||
go run ./cmd/agent -config /path/to/agent.json
|
||||
```
|
||||
|
||||
编译:
|
||||
|
||||
```bash
|
||||
cd openflare_agent
|
||||
go build -o openflare-agent ./cmd/agent
|
||||
```
|
||||
|
||||
测试:
|
||||
|
||||
```bash
|
||||
cd openflare_agent
|
||||
GOCACHE=/tmp/openflare-go-cache go test ./...
|
||||
```
|
||||
|
||||
## 安装 Agent
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/install-agent.sh | bash -s -- \
|
||||
--server-url http://your-server:3000 \
|
||||
--agent-token YOUR_AGENT_TOKEN
|
||||
```
|
||||
|
||||
## 卸载 Agent
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/uninstall-agent.sh | bash
|
||||
```
|
||||
|
||||
## Swagger
|
||||
|
||||
重新生成 Swagger 文档:
|
||||
|
||||
```bash
|
||||
go install github.com/swaggo/swag/cmd/swag@v1.16.4
|
||||
cd openflare_server
|
||||
swag init -g main.go -o docs
|
||||
```
|
||||
@@ -1,16 +1,22 @@
|
||||
# OpenFlare 配置项说明
|
||||
# 配置项
|
||||
|
||||
本文档汇总 OpenFlare `1.0.0` 当前支持的 Server 与 Agent 配置项,只保留仍然有效的启动、部署与运行参数。
|
||||
|
||||
## 1. Server 配置
|
||||
## 配置来源
|
||||
|
||||
Server 支持三类配置来源:
|
||||
|
||||
1. 命令行参数
|
||||
2. 环境变量
|
||||
3. 数据库 `Option` 表中的运行时配置
|
||||
1. 命令行参数。
|
||||
2. 环境变量。
|
||||
3. 数据库 `Option` 表中的运行时配置。
|
||||
|
||||
### 1.1 命令行参数
|
||||
Agent 支持:
|
||||
|
||||
1. `-config` 命令行参数。
|
||||
2. `agent.json` 配置文件。
|
||||
3. 少量日志相关环境变量。
|
||||
|
||||
## Server 命令行参数
|
||||
|
||||
```bash
|
||||
cd openflare_server
|
||||
@@ -24,7 +30,7 @@ go run . --port 3000 --log-dir ./logs
|
||||
| `--version` | 输出当前版本后退出 | `false` |
|
||||
| `--help` | 输出帮助信息后退出 | `false` |
|
||||
|
||||
### 1.2 环境变量
|
||||
## Server 环境变量
|
||||
|
||||
| 环境变量 | 作用 | 默认值 |
|
||||
| --- | --- | --- |
|
||||
@@ -41,13 +47,13 @@ go run . --port 3000 --log-dir ./logs
|
||||
|
||||
说明:
|
||||
|
||||
* `DSN` 与 `SQL_DSN` 同时存在时优先使用 `DSN`
|
||||
* `DSN` 或 `SQL_DSN` 与 `SQLITE_PATH` 同时存在时优先使用 PostgreSQL
|
||||
* 当目标 PostgreSQL 数据库为空且本地 `SQLITE_PATH` 文件存在时,Server 启动阶段会自动迁移 SQLite 数据,并在日志中输出按表迁移进度
|
||||
* `SESSION_SECRET` 生产环境必须显式配置
|
||||
* `REDIS_CONN_STRING` 未配置时,相关能力回退为进程内实现
|
||||
* `DSN` 与 `SQL_DSN` 同时存在时优先使用 `DSN`。
|
||||
* `DSN` 或 `SQL_DSN` 与 `SQLITE_PATH` 同时存在时优先使用 PostgreSQL。
|
||||
* 当目标 PostgreSQL 数据库为空且本地 `SQLITE_PATH` 文件存在时,Server 启动阶段会自动迁移 SQLite 数据,并在日志中输出按表迁移进度。
|
||||
* `SESSION_SECRET` 生产环境必须显式配置。
|
||||
* `REDIS_CONN_STRING` 未配置时,相关能力回退为进程内实现。
|
||||
|
||||
### 1.3 `Option` 表中的运行时配置
|
||||
## 运行时 Option
|
||||
|
||||
以下配置由管理端设置页维护,可热更新:
|
||||
|
||||
@@ -57,10 +63,8 @@ go run . --port 3000 --log-dir ./logs
|
||||
| `NodeOfflineThreshold` | 节点离线阈值(毫秒) | `120000` |
|
||||
| `AgentUpdateRepo` | Agent 自更新仓库 | `Rain-kl/OpenFlare` |
|
||||
| `GeoIPProvider` | 节点/IP 归属解析方式 | `ipinfo` |
|
||||
| `RegisterEnabled` | 是否允许新用户注册 | `false` |
|
||||
| `PasswordRegisterEnabled` | 是否允许通过密码方式注册 | `true` |
|
||||
| `DatabaseAutoCleanupEnabled` | 是否启用每日自动清理观测数据 | `false` |
|
||||
| `DatabaseAutoCleanupRetentionDays` | 自动清理保留天数(至少 1 天) | `30` |
|
||||
| `DatabaseAutoCleanupRetentionDays` | 自动清理保留天数,至少 1 天 | `30` |
|
||||
| `GlobalApiRateLimitNum` / `GlobalApiRateLimitDuration` | 全局 API 限流次数 / 时间窗口 | `300` / `180` |
|
||||
| `GlobalWebRateLimitNum` / `GlobalWebRateLimitDuration` | 全局 Web 限流次数 / 时间窗口 | `300` / `180` |
|
||||
| `UploadRateLimitNum` / `UploadRateLimitDuration` | 上传接口限流次数 / 时间窗口 | `50` / `60` |
|
||||
@@ -69,10 +73,14 @@ go run . --port 3000 --log-dir ./logs
|
||||
|
||||
说明:
|
||||
|
||||
* `DatabaseAutoCleanupEnabled` 开启后,Server 会在每天凌晨 3 点自动清理 `node_access_logs`、`node_metric_snapshots`、`node_request_reports` 三类观测数据
|
||||
* `DatabaseAutoCleanupRetentionDays` 为统一保留天数,必须大于等于 1;管理端支持手动清理时留空保留天数,以直接删除对应数据集的全部历史记录
|
||||
* `DatabaseAutoCleanupEnabled` 开启后,Server 会在每天凌晨 3 点自动清理 `node_access_logs`、`node_metric_snapshots`、`node_request_reports` 三类观测数据。
|
||||
* `DatabaseAutoCleanupRetentionDays` 为统一保留天数,必须大于等于 1。
|
||||
* 管理端支持手动清理时留空保留天数,以直接删除对应数据集的全部历史记录。
|
||||
* 第三方登录不再通过 `GitHubOAuthEnabled`、`GitHubClientId`、`GitHubClientSecret` 作为主配置入口;这些旧 Option 仅用于升级时迁移默认 GitHub 认证源。
|
||||
* 微信登录旧 Option 保留为兼容字段,但管理端不再提供微信登录配置入口。
|
||||
* Turnstile 旧 Option 与后端校验能力保留,已有配置仍会生效;
|
||||
|
||||
### 1.4 OpenResty 参数
|
||||
## OpenResty 参数
|
||||
|
||||
OpenResty 性能参数与缓存参数继续统一保存在 `Option` 表。当前常用项包括:
|
||||
|
||||
@@ -91,13 +99,19 @@ OpenResty 性能参数与缓存参数继续统一保存在 `Option` 表。当前
|
||||
|
||||
这类参数必须以结构化方式校验、保存并参与版本渲染。
|
||||
|
||||
* 管理端不再暴露 `resolver` 配置;规则上游统一渲染为 named `upstream` 并启用 keepalive,单上游如带 base path 或 query,会在 `proxy_pass` 中补回原始 URI。
|
||||
* 多上游仍要求每个上游都为纯 `scheme://host[:port]`,且同一规则内协议一致,避免在负载均衡模式下引入不可预测的 URI 差异。
|
||||
* `OpenRestyCacheEnabled` 用于启用缓存基础设施与全局默认参数;实际是否缓存、按 URL / 后缀 / 路径等命中策略由各条 `proxy_routes` 单独决定,不再默认对所有规则开启缓存。
|
||||
* 默认缓存 Key 为 `$scheme$host$request_uri`,更贴近代理域名维度;如需按其他维度命中,可在性能页显式覆盖。
|
||||
* 默认 `keepalive_timeout` 为 `20` 秒,默认 `proxy_connect_timeout` 为 `3` 秒,优先兼顾资源占用与回源失败切换速度。
|
||||
* 默认事件模型为 `epoll`,并默认开启 `multi_accept`;HTTPS 监听默认使用独立 `http2 on;` 指令,避免新版 Nginx/OpenResty 对 `listen ... http2` 的弃用告警。
|
||||
### 1.5 前端构建环境变量
|
||||
约束:
|
||||
|
||||
* 管理端不再暴露 `resolver` 配置。
|
||||
* 规则上游统一渲染为 named `upstream` 并启用 keepalive。
|
||||
* 单上游如带 base path 或 query,会在 `proxy_pass` 中补回原始 URI。
|
||||
* 多上游仍要求每个上游都为纯 `scheme://host[:port]`,且同一规则内协议一致。
|
||||
* `OpenRestyCacheEnabled` 用于启用缓存基础设施与全局默认参数;实际是否缓存、按 URL / 后缀 / 路径等命中策略由各条 `proxy_routes` 单独决定。
|
||||
* 默认缓存 Key 为 `$scheme$host$request_uri`。
|
||||
* 默认 `keepalive_timeout` 为 `20` 秒,默认 `proxy_connect_timeout` 为 `3` 秒。
|
||||
* 默认事件模型为 `epoll`,并默认开启 `multi_accept`。
|
||||
* HTTPS 监听默认使用独立 `http2 on;` 指令,避免新版 Nginx/OpenResty 对 `listen ... http2` 的弃用告警。
|
||||
|
||||
## 前端构建环境变量
|
||||
|
||||
| 环境变量 | 作用 | 默认值 |
|
||||
| --- | --- | --- |
|
||||
@@ -105,27 +119,19 @@ OpenResty 性能参数与缓存参数继续统一保存在 `Option` 表。当前
|
||||
| `NEXT_PUBLIC_APP_VERSION` | 前端展示版本号 | `dev` |
|
||||
| `NEXT_DEV_BACKEND_URL` | 本地开发服务器代理的后端地址 | `http://127.0.0.1:3000` |
|
||||
|
||||
## 2. Agent 配置
|
||||
|
||||
Agent 当前支持:
|
||||
|
||||
1. `-config` 命令行参数
|
||||
2. `agent.json` 配置文件
|
||||
3. 少量日志相关环境变量
|
||||
|
||||
### 2.1 Agent 环境变量
|
||||
## Agent 环境变量
|
||||
|
||||
| 环境变量 | 作用 | 默认值 |
|
||||
| --- | --- | --- |
|
||||
| `LOG_LEVEL` | Agent 日志等级 | `info` |
|
||||
|
||||
### 2.2 Agent 命令行参数
|
||||
## Agent 命令行参数
|
||||
|
||||
| 参数 | 作用 | 默认值 |
|
||||
| --- | --- | --- |
|
||||
| `-config` | 指定 Agent 配置文件路径 | `./agent.json` |
|
||||
|
||||
### 2.3 Agent 配置字段
|
||||
## Agent 配置字段
|
||||
|
||||
| 字段 | 作用 | 是否必填 | 默认值/行为 |
|
||||
| --- | --- | --- | --- |
|
||||
@@ -154,17 +160,17 @@ Agent 当前支持:
|
||||
|
||||
说明:
|
||||
|
||||
* `agent_token` 与 `discovery_token` 不能同时为空
|
||||
* `heartbeat_interval` 与 `request_timeout` 支持毫秒整数或 Go duration 字符串
|
||||
* 未配置 `openresty_path` 时默认使用 Docker OpenResty 模式
|
||||
* Agent 自动探测到私网 `node_ip` 时,Server 会在注册/心跳阶段优先保留 Agent 直连来源的公网地址,避免 NAT/多网卡场景误登记内网网卡地址
|
||||
* `agent_token` 与 `discovery_token` 不能同时为空。
|
||||
* `heartbeat_interval` 与 `request_timeout` 支持毫秒整数或 Go duration 字符串。
|
||||
* 未配置 `openresty_path` 时默认使用 Docker OpenResty 模式。
|
||||
* Agent 自动探测到私网 `node_ip` 时,Server 会在注册/心跳阶段优先保留 Agent 直连来源的公网地址,避免 NAT/多网卡场景误登记内网网卡地址。
|
||||
|
||||
## 3. 维护要求
|
||||
## 维护要求
|
||||
|
||||
以下内容变化时,必须同步更新本文档:
|
||||
|
||||
* Server 命令行参数
|
||||
* Server 环境变量
|
||||
* Agent 命令行参数
|
||||
* Agent 配置字段
|
||||
* 任一配置项的默认值、用途或示例
|
||||
* Server 命令行参数。
|
||||
* Server 环境变量。
|
||||
* Agent 命令行参数。
|
||||
* Agent 配置字段。
|
||||
* 任一配置项的默认值、用途或示例。
|
||||
@@ -0,0 +1,10 @@
|
||||
# 参考
|
||||
|
||||
本部分收敛运行、接口与仓库层面的稳定信息,适合部署、联调和排查时快速查阅。
|
||||
|
||||
| 页面 | 内容 |
|
||||
| --- | --- |
|
||||
| [配置项](./configuration.md) | Server 环境变量、命令行参数、运行时 Option 与 Agent 配置字段 |
|
||||
| [命令与脚本](./cli.md) | 常用启动、构建、测试、安装和卸载命令 |
|
||||
| [API 约定](./api.md) | 管理端 API 与 Agent API 的响应结构、鉴权和路径约定 |
|
||||
| [仓库结构](./repository.md) | `openflare_server`、`openflare_agent`、`openflare_server/web` 与 `docs` 的职责 |
|
||||
@@ -0,0 +1,45 @@
|
||||
# 仓库结构
|
||||
|
||||
| 路径 | 职责 |
|
||||
| --- | --- |
|
||||
| `openflare_server` | Gin + GORM + SQLite/PostgreSQL 单体控制面 |
|
||||
| `openflare_server/web` | Next.js 15 App Router 管理端前端,静态导出后由 Go Server 托管 |
|
||||
| `openflare_agent` | Go 单体 Agent,运行在节点侧 |
|
||||
| `scripts` | Agent 安装、卸载等辅助脚本 |
|
||||
| `docs` | VitePress 文档站、设计基线、开发规范、部署与配置文档 |
|
||||
|
||||
## Server 分层
|
||||
|
||||
| 目录 | 职责 |
|
||||
| --- | --- |
|
||||
| `controller/` | 参数解析、调用 service、返回响应 |
|
||||
| `service/` | 业务逻辑、校验、事务编排、配置渲染 |
|
||||
| `model/` | 模型定义、数据库版本与迁移 |
|
||||
| `router/` | 路由注册 |
|
||||
| `middleware/` | 认证、鉴权、限流等横切逻辑 |
|
||||
| `common/` | 配置、全局状态与初始化入口 |
|
||||
| `utils/` | 纯工具函数与通用 helper |
|
||||
|
||||
## Agent 模块
|
||||
|
||||
| 模块 | 职责 |
|
||||
| --- | --- |
|
||||
| `config` | 配置读取与默认值 |
|
||||
| `heartbeat` | 心跳与版本摘要判断 |
|
||||
| `sync` | 配置拉取与应用编排 |
|
||||
| `nginx` / `openresty` | OpenResty 文件写入、校验、reload 与 Docker 模式管理 |
|
||||
| `state` | 本地状态与观测补报缓冲 |
|
||||
| `httpclient` | Server 通信 |
|
||||
| `protocol` | Agent API 协议类型 |
|
||||
| `internal/updater` | Agent 自更新 |
|
||||
|
||||
## Frontend 分层
|
||||
|
||||
| 目录 | 职责 |
|
||||
| --- | --- |
|
||||
| `app/` | 路由、布局、页面组装 |
|
||||
| `features/` | 按业务域组织模块 |
|
||||
| `components/` | 跨 feature 复用组件 |
|
||||
| `lib/` | 请求客户端、环境变量、工具函数、常量 |
|
||||
| `store/` | 少量跨页面 UI 状态 |
|
||||
| `types/` | 共享类型定义 |
|
||||
@@ -1,266 +0,0 @@
|
||||
# 网站配置改造需求与开发计划
|
||||
|
||||
## 1. 背景
|
||||
|
||||
当前规则模块以“一个域名对应一条规则”为中心,已经支持单域名绑定一个或多个上游,但无法表达“多个域名共享同一套站点配置”的场景。
|
||||
|
||||
现阶段已经出现以下真实需求:
|
||||
|
||||
* 多个域名指向同一站点,并共享反向代理、缓存等设置,同时允许按域名分别绑定 HTTPS 证书
|
||||
* 后续希望围绕“网站”继续叠加更多功能,而不是持续在规则列表中堆积字段
|
||||
* 现有抽屉式编辑界面已经不适合承载更复杂的配置结构
|
||||
|
||||
因此,本轮改造将 `proxy_routes` 从“单域名规则”升级为“网站配置”视角,并引入独立的配置子页面。
|
||||
|
||||
## 2. 目标
|
||||
|
||||
本轮改造的目标如下:
|
||||
|
||||
* 支持一个网站绑定多个域名
|
||||
* 支持一个网站绑定一个或多个上游
|
||||
* 引入 `site_name` 作为网站业务唯一标识
|
||||
* 将原列表页的“编辑”操作替换为“配置”,进入独立子页面管理
|
||||
* 将网站配置拆分为更清晰的功能分区,为后续扩展预留结构
|
||||
|
||||
## 3. 本轮范围
|
||||
|
||||
本轮仅覆盖以下站点级配置能力:
|
||||
|
||||
* 域名设置
|
||||
* 流量限制
|
||||
* 反向代理
|
||||
* 缓存
|
||||
|
||||
## 4. 核心模型要求
|
||||
|
||||
### 4.1 网站标识
|
||||
|
||||
* `site_name` 为网站业务唯一标识
|
||||
* 新建网站时,若用户未输入 `site_name`,默认取域名列表第一项
|
||||
* `site_name` 在首次生成后允许独立编辑,不随域名变更自动同步,避免影响引用、跳转和审计
|
||||
* 数据库内部主键可以继续使用现有数值 `id`,但业务层必须校验 `site_name` 唯一性
|
||||
|
||||
### 4.2 域名列表
|
||||
|
||||
* 网站的域名字段改为 `domains` 列表
|
||||
* `domains` 至少包含一个有效域名
|
||||
* `domains[0]` 视为主域名,用于列表摘要、默认展示和兼容历史逻辑
|
||||
* 同一网站内域名不能重复
|
||||
* 任一域名在全局只能属于一个网站
|
||||
* 域名列表需要支持新增、删除和调整顺序
|
||||
|
||||
### 4.3 历史兼容
|
||||
|
||||
* 存量单域名数据迁移后应自动转换为:
|
||||
`site_name = domain`
|
||||
`domains = [domain]`
|
||||
* 若迁移期保留旧 `domain` 字段,该字段仅作为 `domains[0]` 的兼容镜像,不再作为主要业务输入
|
||||
* 版本渲染、差异预览、接口返回和前端展示都应逐步以 `site_name + domains` 为准
|
||||
|
||||
## 5. 功能需求
|
||||
|
||||
### 5.1 列表页改造
|
||||
|
||||
规则列表改造为“网站列表”视图,要求如下:
|
||||
|
||||
* 保留当前列表页入口,但展示对象改为网站
|
||||
* 原“编辑”按钮替换为“配置”按钮
|
||||
* 点击“配置”进入网站配置子页面
|
||||
* 列表项至少展示:
|
||||
`site_name`
|
||||
主域名
|
||||
域名数量
|
||||
上游摘要
|
||||
HTTPS/缓存/启用状态摘要
|
||||
* 删除、发布等现有高风险操作仍保留明确确认
|
||||
|
||||
### 5.2 网站配置子页面
|
||||
|
||||
网站配置采用左右布局:
|
||||
|
||||
* 左侧为菜单栏,用于切换配置分区
|
||||
* 右侧为当前分区的设置面板
|
||||
* 默认进入“域名设置”分区
|
||||
* 建议基于 App Router 子路由或稳定的 tab 路由参数实现,保证可直接访问和刷新恢复
|
||||
|
||||
建议左侧菜单项固定为:
|
||||
|
||||
1. 域名设置
|
||||
2. 流量限制
|
||||
3. 反向代理
|
||||
4. 缓存
|
||||
|
||||
为降低跨分区校验干扰,每个分区应支持独立保存与反馈;若采用统一保存,也必须提供未保存修改提示。
|
||||
|
||||
### 5.3 域名设置
|
||||
|
||||
域名设置分区负责维护网站身份与域名列表,要求如下:
|
||||
|
||||
* 可编辑 `site_name`
|
||||
* 可维护 `domains` 列表
|
||||
* 可新增、删除、排序域名
|
||||
* 明确提示第一项为主域名
|
||||
* 每个域名可单独选择一张证书,形成与 `domains` 平行的 `domain_cert_ids`
|
||||
* 若某个域名未选择证书,则该域名不启用 HTTPS
|
||||
* `HTTP -> HTTPS` 跳转逻辑与域名证书绑定放在同一分区维护
|
||||
* 保存前校验:
|
||||
`site_name` 非空且唯一
|
||||
`domains` 非空
|
||||
每个域名格式合法
|
||||
域名在当前站点内不重复
|
||||
域名在全局不与其他网站冲突
|
||||
已选择证书的域名必须被对应证书覆盖
|
||||
|
||||
### 5.4 流量限制
|
||||
|
||||
流量限制分区用于配置站点级限流,第一期要求覆盖以下字段:
|
||||
|
||||
* `limit_conn perserver`
|
||||
* `limit_conn perip`
|
||||
* `limit_rate`
|
||||
|
||||
要求如下:
|
||||
|
||||
* 采用结构化字段存储,不允许直接录入原始 Nginx 片段
|
||||
* `limit_conn perserver` 与 `limit_conn perip` 为整数;空值或 `0` 视为未启用
|
||||
* `limit_rate` 采用人类可读格式录入,例如 `512k`、`1m`
|
||||
* 保存前进行格式校验,并在页面中提供示例说明
|
||||
* 配置发布后渲染为对应的 OpenResty/Nginx 指令
|
||||
|
||||
### 5.5 反向代理
|
||||
|
||||
反向代理分区负责维护网站回源配置,要求如下:
|
||||
|
||||
* 支持一个或多个上游
|
||||
* 至少保留一个上游
|
||||
* 支持维护回源主机名 `origin_host`
|
||||
* 继续兼容当前单上游带 path/query、多上游做负载均衡的模式
|
||||
* 若复用 `origins` 目录,只作为地址候选来源,不改变网站配置为主的编辑模型
|
||||
|
||||
建议继续保留当前兼容约束:
|
||||
|
||||
* 单上游可附带 path/query
|
||||
* 多上游模式下,上游项保持 `scheme://host[:port]` 形式
|
||||
* 同一网站的多个上游在多上游模式下维持统一协议,降低渲染复杂度
|
||||
|
||||
### 5.6 缓存
|
||||
|
||||
缓存分区负责维护站点级缓存策略,要求如下:
|
||||
|
||||
* 支持开启或关闭缓存
|
||||
* 支持多种缓存策略
|
||||
* 第一阶段至少兼容当前已存在的策略:
|
||||
`url`
|
||||
`suffix`
|
||||
`path_prefix`
|
||||
`path_exact`
|
||||
* 缓存规则继续采用结构化配置,不直接暴露原始 Nginx 片段
|
||||
* 保持当前安全绕过逻辑,不因界面改造改变默认缓存边界
|
||||
|
||||
## 6. 接口与渲染要求
|
||||
|
||||
* 列表接口需要返回 `site_name`、`domains`、主域名、状态摘要等字段
|
||||
* 详情接口需要按分区所需字段返回完整站点配置
|
||||
* 更新接口需要支持按分区或按网站整体更新,但服务端必须统一做跨字段校验
|
||||
* 配置 diff 不再只关注单个域名变更,还要能识别:
|
||||
网站新增/删除
|
||||
域名列表变更
|
||||
站点级配置变更
|
||||
* 发布渲染时,同一网站的全部域名必须落入同一份站点配置上下文中
|
||||
* 同一网站内,带证书的域名需按证书分组生成 HTTPS `server`;未配置证书的域名只保留 HTTP
|
||||
|
||||
## 7. 前端实现要求
|
||||
|
||||
* 列表页负责导航与摘要,不再承载完整编辑表单
|
||||
* 网站配置子页面中的每个分区表单继续遵循 `React Hook Form + Zod`
|
||||
* API 请求统一收敛在 `lib/api/`
|
||||
* 站点级数据查询与缓存继续使用 TanStack Query
|
||||
* 左侧菜单切换时需要明确处理未保存状态,避免无提示丢失修改
|
||||
* 页面至少覆盖加载态、空态、错误态和保存成功反馈
|
||||
|
||||
## 8. 数据迁移要求
|
||||
|
||||
实施前必须准备显式数据库迁移与校验逻辑,至少包含:
|
||||
|
||||
1. 新增 `site_name`、`domains` 与 `domain_cert_ids` 存储结构
|
||||
2. 将旧数据从单域名回填到站点结构,并补齐逐域名证书映射
|
||||
3. 为 `site_name` 建立唯一约束
|
||||
4. 为域名唯一性建立可校验约束
|
||||
5. 对迁移结果做一致性校验
|
||||
|
||||
迁移失败时,启动流程必须中止,不允许带半迁移状态继续运行。
|
||||
|
||||
## 9. 开发计划
|
||||
|
||||
### 阶段一:模型与渲染改造
|
||||
|
||||
目标:
|
||||
|
||||
* 定义网站级 `proxy_routes` 数据结构
|
||||
* 完成存量数据迁移
|
||||
* 调整配置渲染与发布链路,支持多域名同站点输出
|
||||
|
||||
交付物:
|
||||
|
||||
* 数据库迁移
|
||||
* model/service 调整
|
||||
* 配置渲染兼容实现
|
||||
* 迁移与渲染测试
|
||||
|
||||
### 阶段二:接口与校验改造
|
||||
|
||||
目标:
|
||||
|
||||
* 更新列表、详情、创建、更新接口的数据结构
|
||||
* 引入 `site_name`、`domains`、流量限制等字段校验
|
||||
* 调整版本 diff 与发布预览语义
|
||||
|
||||
交付物:
|
||||
|
||||
* API 契约更新
|
||||
* 服务端参数校验与错误消息
|
||||
* diff/preview 适配
|
||||
* 接口回归测试
|
||||
|
||||
### 阶段三:前端网站列表与配置子页面
|
||||
|
||||
目标:
|
||||
|
||||
* 将规则列表切换为网站列表
|
||||
* 用“配置”按钮替代“编辑”按钮
|
||||
* 落地左右布局的网站配置子页面与五个分区
|
||||
|
||||
交付物:
|
||||
|
||||
* 列表页 UI 改造
|
||||
* 子页面路由与布局
|
||||
* 域名设置、流量限制、反向代理、缓存四个分区
|
||||
* 前端交互与表单测试
|
||||
|
||||
### 阶段四:联调、发布验证与文档收口
|
||||
|
||||
目标:
|
||||
|
||||
* 验证从创建网站到发布配置的全链路
|
||||
* 验证 Agent 拉取、应用与回滚不受影响
|
||||
* 收口文档与测试
|
||||
|
||||
交付物:
|
||||
|
||||
* 联调记录
|
||||
* 发布/回滚回归验证
|
||||
* 文档同步更新
|
||||
|
||||
## 10. 验收标准
|
||||
|
||||
满足以下条件后,本专项可视为完成:
|
||||
|
||||
* 可以创建一个网站,并绑定多个域名
|
||||
* 一个网站可以绑定单个或多个上游
|
||||
* `site_name` 唯一,且创建时默认取第一个域名
|
||||
* 原列表页已用“配置”按钮替代“编辑”按钮
|
||||
* 网站配置子页面已经采用左侧菜单、右侧设置的布局
|
||||
* 五个分区均可独立完成基本配置与保存
|
||||
* 发布后的渲染结果可正确覆盖同一网站的全部域名,并只为已绑定证书的域名生成 HTTPS 配置
|
||||
* Agent 同步、应用、回滚链路不被破坏
|
||||
* 迁移、接口、渲染与前端关键路径均有对应测试或等效回归验证
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"server_url": "http://127.0.0.1:3000",
|
||||
"agent_token": "2380de64b00e99093e16590beb91e1a0",
|
||||
"agent_token": "373956188ddead1df6dd7c86cd330b73",
|
||||
"data_dir": "./data",
|
||||
"openresty_container_name": "openflare-openresty",
|
||||
"openresty_docker_image": "openresty/openresty:alpine",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
module openflare-agent
|
||||
|
||||
go 1.24.0
|
||||
go 1.25.0
|
||||
|
||||
require openflare v0.0.0
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ const LuaDirPlaceholder = "__OPENFLARE_LUA_DIR__"
|
||||
const ObservabilityListenPlaceholder = "__OPENFLARE_OBSERVABILITY_LISTEN__"
|
||||
const ObservabilityPortPlaceholder = "__OPENFLARE_OBSERVABILITY_PORT__"
|
||||
const ResolverDirectivePlaceholder = "__OPENFLARE_RESOLVER_DIRECTIVE__"
|
||||
const PowStaticDirPlaceholder = "__OPENFLARE_POW_STATIC_DIR__"
|
||||
const DockerMainConfigPath = "/usr/local/openresty/nginx/conf/nginx.conf"
|
||||
const DockerRouteConfigPath = "/etc/nginx/conf.d/openflare_routes.conf"
|
||||
const DockerAccessLogPath = "/etc/nginx/conf.d/openflare_access.log"
|
||||
@@ -396,6 +397,9 @@ func (m *Manager) writeTargetFiles(mainConfig string, routeConfig string, suppor
|
||||
if err := m.writeCertFiles(supportFiles); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := m.writePowConfig(supportFiles); err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.TrimSpace(m.OpenrestyResolverDirective) == "" && strings.Contains(routeConfig, "set $openflare_upstream ") {
|
||||
slog.Warn("runtime-resolved hostname upstreams detected without available resolvers; hostname origin requests may fail until resolvers are configured")
|
||||
}
|
||||
@@ -450,8 +454,21 @@ func (m *Manager) EnsureLuaAssets() error {
|
||||
if strings.TrimSpace(m.LuaDir) == "" {
|
||||
return nil
|
||||
}
|
||||
files := make([]managedFile, 0, len(ManagedObservabilityLuaFiles()))
|
||||
for _, file := range ManagedObservabilityLuaFiles() {
|
||||
allSupportFiles := append(ManagedObservabilityLuaFiles(), ManagedPowLuaFiles()...)
|
||||
existingPowConfig, err := m.readPowConfigFile()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if existingPowConfig != nil {
|
||||
allSupportFiles = append(allSupportFiles, *existingPowConfig)
|
||||
}
|
||||
powStaticFiles, err := ManagedPowStaticFiles()
|
||||
if err != nil {
|
||||
return fmt.Errorf("load pow static files: %w", err)
|
||||
}
|
||||
allSupportFiles = append(allSupportFiles, powStaticFiles...)
|
||||
files := make([]managedFile, 0, len(allSupportFiles))
|
||||
for _, file := range allSupportFiles {
|
||||
targetPath, err := luaFileTargetPath(m.LuaDir, file.Path)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -536,7 +553,11 @@ func (m *Manager) CurrentChecksum() (string, error) {
|
||||
if m.NginxCertDir != "" {
|
||||
normalizedRoute = strings.ReplaceAll(normalizedRoute, m.NginxCertDir, CertDirPlaceholder)
|
||||
}
|
||||
files, err := m.readCertFiles()
|
||||
if luaDir := m.luaRuntimePath(); luaDir != "" {
|
||||
normalizedRoute = strings.ReplaceAll(normalizedRoute, luaDir+"/pow/static", PowStaticDirPlaceholder)
|
||||
normalizedRoute = strings.ReplaceAll(normalizedRoute, luaDir, LuaDirPlaceholder)
|
||||
}
|
||||
files, err := m.readManagedSupportFiles()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -693,6 +714,7 @@ type backupState struct {
|
||||
RouteExisted bool
|
||||
RouteData []byte
|
||||
Files []protocol.SupportFile
|
||||
PowConfig *protocol.SupportFile
|
||||
}
|
||||
|
||||
type managedFile struct {
|
||||
@@ -739,6 +761,11 @@ func (m *Manager) backup() (*backupState, error) {
|
||||
return nil, err
|
||||
}
|
||||
state.Files = files
|
||||
powConfig, err := m.readPowConfigFile()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
state.PowConfig = powConfig
|
||||
slog.Debug("backup captured", "main_exists", state.MainExisted, "route_exists", state.RouteExisted, "cert_files", len(state.Files))
|
||||
return state, nil
|
||||
}
|
||||
@@ -762,10 +789,12 @@ func (m *Manager) restore(state *backupState) error {
|
||||
} else if err := os.Remove(m.RouteConfigPath); err != nil && !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
if m.CertDir == "" {
|
||||
return nil
|
||||
if m.CertDir != "" {
|
||||
if err := m.writeManagedCertFiles(state.Files); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return m.writeManagedCertFiles(state.Files)
|
||||
return m.restorePowConfig(state)
|
||||
}
|
||||
|
||||
func (m *Manager) writeCertFiles(certFiles []protocol.SupportFile) error {
|
||||
@@ -775,6 +804,26 @@ func (m *Manager) writeCertFiles(certFiles []protocol.SupportFile) error {
|
||||
return m.writeManagedCertFiles(certFiles)
|
||||
}
|
||||
|
||||
func (m *Manager) writePowConfig(supportFiles []protocol.SupportFile) error {
|
||||
if m.LuaDir == "" {
|
||||
return nil
|
||||
}
|
||||
configPath := filepath.Join(m.LuaDir, "pow_config.json")
|
||||
for _, file := range supportFiles {
|
||||
if file.Path == "pow_config.json" {
|
||||
if err := os.WriteFile(configPath, []byte(file.Content), 0o644); err != nil {
|
||||
return fmt.Errorf("write pow_config.json: %w", err)
|
||||
}
|
||||
slog.Info("wrote pow config", "path", configPath, "size", len(file.Content))
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if err := os.Remove(configPath); err != nil && !os.IsNotExist(err) {
|
||||
return fmt.Errorf("remove pow_config.json: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) writeManagedCertFiles(certFiles []protocol.SupportFile) error {
|
||||
files := make([]managedFile, 0, len(certFiles))
|
||||
for _, file := range certFiles {
|
||||
@@ -836,6 +885,53 @@ func (m *Manager) readCertFiles() ([]protocol.SupportFile, error) {
|
||||
return files, nil
|
||||
}
|
||||
|
||||
func (m *Manager) readPowConfigFile() (*protocol.SupportFile, error) {
|
||||
if m.LuaDir == "" {
|
||||
return nil, nil
|
||||
}
|
||||
configPath := filepath.Join(m.LuaDir, "pow_config.json")
|
||||
data, err := os.ReadFile(configPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &protocol.SupportFile{
|
||||
Path: "pow_config.json",
|
||||
Content: string(data),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (m *Manager) readManagedSupportFiles() ([]protocol.SupportFile, error) {
|
||||
files, err := m.readCertFiles()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
powConfig, err := m.readPowConfigFile()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if powConfig != nil {
|
||||
files = append(files, *powConfig)
|
||||
}
|
||||
return files, nil
|
||||
}
|
||||
|
||||
func (m *Manager) restorePowConfig(state *backupState) error {
|
||||
if state == nil || m.LuaDir == "" {
|
||||
return nil
|
||||
}
|
||||
configPath := filepath.Join(m.LuaDir, "pow_config.json")
|
||||
if state.PowConfig == nil {
|
||||
if err := os.Remove(configPath); err != nil && !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return os.WriteFile(configPath, []byte(state.PowConfig.Content), 0o644)
|
||||
}
|
||||
|
||||
func (m *Manager) certFileTargetPath(relativePath string) (string, error) {
|
||||
if strings.TrimSpace(m.CertDir) == "" {
|
||||
return "", errors.New("cert dir 不能为空")
|
||||
@@ -988,10 +1084,15 @@ func removeEmptyManagedDirs(baseDir string) error {
|
||||
}
|
||||
|
||||
func (m *Manager) renderRouteConfig(content string) string {
|
||||
if m.NginxCertDir == "" {
|
||||
return content
|
||||
rendered := content
|
||||
if m.NginxCertDir != "" {
|
||||
rendered = strings.ReplaceAll(rendered, CertDirPlaceholder, m.NginxCertDir)
|
||||
}
|
||||
return strings.ReplaceAll(content, CertDirPlaceholder, m.NginxCertDir)
|
||||
if luaDir := m.luaRuntimePath(); luaDir != "" {
|
||||
rendered = strings.ReplaceAll(rendered, LuaDirPlaceholder, luaDir)
|
||||
rendered = strings.ReplaceAll(rendered, PowStaticDirPlaceholder, luaDir+"/pow/static")
|
||||
}
|
||||
return rendered
|
||||
}
|
||||
|
||||
func (m *Manager) renderMainConfig(content string) string {
|
||||
|
||||
@@ -736,6 +736,13 @@ func TestManagerApplyWritesSupportFilesAndReplacesPlaceholder(t *testing.T) {
|
||||
if !strings.Contains(string(routeData), "/etc/nginx/openflare-certs/1.crt") {
|
||||
t.Fatalf("expected placeholder replacement in route config, got %s", string(routeData))
|
||||
}
|
||||
renderedRoute := manager.renderRouteConfig("access_by_lua_file __OPENFLARE_LUA_DIR__/pow/check.lua;\nlocation /.within.website/x/cmd/anubis/static/ { alias __OPENFLARE_POW_STATIC_DIR__/; }\n")
|
||||
if !strings.Contains(renderedRoute, "access_by_lua_file /etc/nginx/openflare-lua/pow/check.lua;") {
|
||||
t.Fatalf("expected lua dir placeholder replacement in route config, got %s", renderedRoute)
|
||||
}
|
||||
if !strings.Contains(renderedRoute, "alias /etc/nginx/openflare-lua/pow/static/;") {
|
||||
t.Fatalf("expected pow static dir placeholder replacement in route config, got %s", renderedRoute)
|
||||
}
|
||||
mainData, err := os.ReadFile(manager.MainConfigPath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to read main config: %v", err)
|
||||
@@ -867,6 +874,12 @@ func TestEnsureLuaAssetsKeepsBaseDirAndRemovesStaleFiles(t *testing.T) {
|
||||
if _, err := os.Stat(filepath.Join(luaDir, "log.lua")); err != nil {
|
||||
t.Fatalf("expected managed lua file to exist, stat err = %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(luaDir, "pow", "check.lua")); err != nil {
|
||||
t.Fatalf("expected managed pow lua file to exist, stat err = %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(luaDir, "pow", "static", "js", "main.mjs")); err != nil {
|
||||
t.Fatalf("expected managed pow static asset to exist, stat err = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCertFileMode(t *testing.T) {
|
||||
@@ -906,6 +919,105 @@ func TestManagerEnsureLuaAssetsWritesReadableFiles(t *testing.T) {
|
||||
if luaInfo.Mode().Perm() != 0o644 {
|
||||
t.Fatalf("unexpected lua mode: %o", luaInfo.Mode().Perm())
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(manager.LuaDir, "pow", "check.lua")); err != nil {
|
||||
t.Fatalf("failed to stat pow lua file: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureLuaAssetsPreservesPowConfig(t *testing.T) {
|
||||
tempDir := t.TempDir()
|
||||
luaDir := filepath.Join(tempDir, "lua")
|
||||
if err := os.MkdirAll(luaDir, 0o755); err != nil {
|
||||
t.Fatalf("MkdirAll failed: %v", err)
|
||||
}
|
||||
powConfigPath := filepath.Join(luaDir, "pow_config.json")
|
||||
want := `[{"domains":["pow.example.com"],"enabled":true}]`
|
||||
if err := os.WriteFile(powConfigPath, []byte(want), 0o644); err != nil {
|
||||
t.Fatalf("WriteFile failed: %v", err)
|
||||
}
|
||||
manager := &Manager{LuaDir: luaDir}
|
||||
|
||||
if err := manager.EnsureLuaAssets(); err != nil {
|
||||
t.Fatalf("EnsureLuaAssets failed: %v", err)
|
||||
}
|
||||
|
||||
got, err := os.ReadFile(powConfigPath)
|
||||
if err != nil {
|
||||
t.Fatalf("expected pow_config.json to remain after EnsureLuaAssets: %v", err)
|
||||
}
|
||||
if string(got) != want {
|
||||
t.Fatalf("unexpected pow_config.json content: got %s want %s", string(got), want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManagerCurrentChecksumIncludesPowConfig(t *testing.T) {
|
||||
tempDir := t.TempDir()
|
||||
mainPath := filepath.Join(tempDir, "nginx.conf")
|
||||
routePath := filepath.Join(tempDir, "routes.conf")
|
||||
luaDir := filepath.Join(tempDir, "lua")
|
||||
manager := &Manager{
|
||||
MainConfigPath: mainPath,
|
||||
RouteConfigPath: routePath,
|
||||
LuaDir: luaDir,
|
||||
NginxLuaDir: "/etc/nginx/openflare-lua",
|
||||
Executor: &fakeExecutor{},
|
||||
}
|
||||
|
||||
outcome := manager.Apply(
|
||||
context.Background(),
|
||||
"access_log __OPENFLARE_ACCESS_LOG__ openflare_json;\n",
|
||||
"location /.within.website/x/cmd/anubis/static/ { alias __OPENFLARE_POW_STATIC_DIR__/; }\n",
|
||||
[]protocol.SupportFile{{Path: "pow_config.json", Content: `[{"domains":["pow.example.com"],"enabled":true}]`}},
|
||||
)
|
||||
if outcome.Status != ApplyStatusSuccess {
|
||||
t.Fatalf("Apply failed: %#v", outcome)
|
||||
}
|
||||
|
||||
value, err := manager.CurrentChecksum()
|
||||
if err != nil {
|
||||
t.Fatalf("CurrentChecksum failed: %v", err)
|
||||
}
|
||||
expected := bundleChecksum(
|
||||
"access_log __OPENFLARE_ACCESS_LOG__ openflare_json;\n",
|
||||
"location /.within.website/x/cmd/anubis/static/ { alias __OPENFLARE_POW_STATIC_DIR__/; }\n",
|
||||
[]protocol.SupportFile{{Path: "pow_config.json", Content: `[{"domains":["pow.example.com"],"enabled":true}]`}},
|
||||
)
|
||||
if value != expected {
|
||||
t.Fatalf("unexpected checksum with pow config: got %s want %s", value, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManagedPowLuaFilesUseInternalChallengeFlow(t *testing.T) {
|
||||
if !strings.Contains(openRestyPowCheckLua, `return ngx.exec("/.within.website/x/cmd/anubis/api/make-challenge")`) {
|
||||
t.Fatal("expected check.lua to internally execute make-challenge instead of issuing a 302 redirect")
|
||||
}
|
||||
if strings.Contains(openRestyPowCheckLua, "ngx.redirect(") {
|
||||
t.Fatal("expected check.lua to avoid external redirects for challenge rendering")
|
||||
}
|
||||
if !strings.Contains(openRestyPowChallengeLua, `<h1 id="title" class="centered-div">`) {
|
||||
t.Fatal("expected challenge html to include Anubis-compatible title node")
|
||||
}
|
||||
if !strings.Contains(openRestyPowChallengeLua, `<div id="progress" role="progressbar" aria-labelledby="status"><div class="bar-inner"></div></div>`) {
|
||||
t.Fatal("expected challenge html to include Anubis-compatible progress markup")
|
||||
}
|
||||
if !strings.Contains(openRestyPowChallengeLua, `<script id="anubis_public_url" type="application/json">"__openflare_internal__"</script>`) {
|
||||
t.Fatal("expected challenge html to force Anubis frontend to reuse the current URL as redir target")
|
||||
}
|
||||
if !strings.Contains(openRestyPowCheckLua, `pow_sessions:set(session_key, "1", session_ttl)`) {
|
||||
t.Fatal("expected check.lua to refresh the PoW session TTL on each valid request")
|
||||
}
|
||||
if !strings.Contains(openRestyPowCheckLua, `ngx.header["Set-Cookie"] = session_cookie(cookie_val, session_ttl)`) {
|
||||
t.Fatal("expected check.lua to refresh the browser session cookie on each valid request")
|
||||
}
|
||||
if !strings.Contains(openRestyPowChallengeLua, `local session_ttl = config.session_ttl or 600`) {
|
||||
t.Fatal("expected challenge.lua to default session TTL to 10 minutes")
|
||||
}
|
||||
if !strings.Contains(openRestyPowVerifyLua, `local session_ttl = challenge_info.session_ttl or 600`) {
|
||||
t.Fatal("expected verify.lua to default session TTL to 10 minutes")
|
||||
}
|
||||
if !strings.Contains(openRestyPowVerifyLua, `if ngx.var.scheme == "https" then`) {
|
||||
t.Fatal("expected verify.lua to only mark the session cookie as Secure for HTTPS requests")
|
||||
}
|
||||
}
|
||||
|
||||
func TestManagerRollbackRestoresCertFiles(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,535 @@
|
||||
package nginx
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"openflare-agent/internal/protocol"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
//go:embed pow_static
|
||||
var powStaticFS embed.FS
|
||||
|
||||
const openRestyPowCheckLua = `local source = debug.getinfo(1, "S").source or ""
|
||||
if string.sub(source, 1, 1) == "@" then
|
||||
local script_path = string.sub(source, 2)
|
||||
local base_dir = string.match(script_path, "^(.*)/pow/[^/]+%.lua$")
|
||||
if base_dir and base_dir ~= "" then
|
||||
package.path = base_dir .. "/?.lua;" .. base_dir .. "/?/init.lua;" .. package.path
|
||||
end
|
||||
end
|
||||
|
||||
local cjson = require "cjson.safe"
|
||||
local policy = require "pow.policy"
|
||||
|
||||
local pow_config_dict = ngx.shared.openflare_pow_config
|
||||
local pow_sessions = ngx.shared.openflare_pow_sessions
|
||||
|
||||
local function session_cookie(value, ttl)
|
||||
local cookie = "__openflare_pow=" .. value .. "; Path=/; HttpOnly; SameSite=Lax; Max-Age=" .. tostring(ttl)
|
||||
if ngx.var.scheme == "https" then
|
||||
cookie = cookie .. "; Secure"
|
||||
end
|
||||
return cookie
|
||||
end
|
||||
|
||||
-- Lazy-load pow_config from file; reload when content changes
|
||||
local function load_pow_config()
|
||||
local config_paths = {
|
||||
ngx.config.prefix() .. "openflare-lua/pow_config.json",
|
||||
"/etc/nginx/openflare-lua/pow_config.json",
|
||||
"/usr/local/openresty/nginx/conf/pow_config.json"
|
||||
}
|
||||
for _, config_path in ipairs(config_paths) do
|
||||
local f = io.open(config_path, "r")
|
||||
if f then
|
||||
local content = f:read("*a")
|
||||
f:close()
|
||||
local current_hash = ngx.md5(content or "")
|
||||
|
||||
if current_hash == pow_config_dict:get("_config_hash") then
|
||||
return
|
||||
end
|
||||
|
||||
-- Clear old domain entries
|
||||
local old_keys = pow_config_dict:get("_domain_keys")
|
||||
if old_keys then
|
||||
for domain in string.gmatch(old_keys, "[^\n]+") do
|
||||
pow_config_dict:delete(domain)
|
||||
end
|
||||
end
|
||||
|
||||
local domain_keys = {}
|
||||
if content and content ~= "" and content ~= "{}" then
|
||||
local ok, entries = pcall(cjson.decode, content)
|
||||
if ok and entries and type(entries) == "table" then
|
||||
for _, entry in ipairs(entries) do
|
||||
if entry.domains then
|
||||
for _, domain in ipairs(entry.domains) do
|
||||
pow_config_dict:set(domain, cjson.encode(entry), 0)
|
||||
domain_keys[#domain_keys+1] = domain
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
pow_config_dict:set("_domain_keys", table.concat(domain_keys, "\n"), 0)
|
||||
pow_config_dict:set("_config_hash", current_hash, 0)
|
||||
return
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
load_pow_config()
|
||||
|
||||
local host = ngx.var.host
|
||||
if not host or host == "" then
|
||||
return
|
||||
end
|
||||
|
||||
local config_raw = pow_config_dict:get(host)
|
||||
if not config_raw then
|
||||
return
|
||||
end
|
||||
|
||||
local ok, route_config = pcall(cjson.decode, config_raw)
|
||||
if not ok or not route_config then
|
||||
return
|
||||
end
|
||||
|
||||
if not route_config.enabled then
|
||||
return
|
||||
end
|
||||
|
||||
local config = route_config.config or {}
|
||||
local session_ttl = config.session_ttl or 600
|
||||
local uri = ngx.var.uri or ""
|
||||
local ua = ngx.var.http_user_agent or ""
|
||||
local remote_ip = ngx.var.remote_addr or ""
|
||||
|
||||
-- Check whitelist: if matched, skip PoW
|
||||
local whitelist = config.whitelist or {}
|
||||
if policy.match_any(remote_ip, ua, uri, whitelist) then
|
||||
return
|
||||
end
|
||||
|
||||
-- Check blacklist: if matched, require PoW
|
||||
local blacklist = config.blacklist or {}
|
||||
local has_blacklist = policy.has_entries(blacklist)
|
||||
local need_pow = false
|
||||
if has_blacklist then
|
||||
need_pow = policy.match_any(remote_ip, ua, uri, blacklist)
|
||||
else
|
||||
-- No blacklist means all non-whitelisted need PoW
|
||||
need_pow = true
|
||||
end
|
||||
|
||||
if not need_pow then
|
||||
return
|
||||
end
|
||||
|
||||
-- Check valid session cookie
|
||||
local cookie_val = ngx.var["cookie___openflare_pow"]
|
||||
if cookie_val and cookie_val ~= "" then
|
||||
local session_key = host .. ":" .. cookie_val
|
||||
local session_data = pow_sessions:get(session_key)
|
||||
if session_data then
|
||||
pow_sessions:set(session_key, "1", session_ttl)
|
||||
ngx.header["Set-Cookie"] = session_cookie(cookie_val, session_ttl)
|
||||
return
|
||||
end
|
||||
end
|
||||
|
||||
-- If requesting the challenge API endpoints, let them through (handled by content_by_lua)
|
||||
local anubis_api_prefix = "/.within.website/x/cmd/anubis/api/"
|
||||
local anubis_static_prefix = "/.within.website/x/cmd/anubis/static/"
|
||||
if string.sub(uri, 1, #anubis_api_prefix) == anubis_api_prefix then
|
||||
return
|
||||
end
|
||||
if string.sub(uri, 1, #anubis_static_prefix) == anubis_static_prefix then
|
||||
return
|
||||
end
|
||||
|
||||
-- Render the challenge page through an internal redirect so the browser stays
|
||||
-- on the originally requested URL instead of seeing a 302 hop.
|
||||
ngx.req.set_uri_args({
|
||||
redir = ngx.var.scheme .. "://" .. host .. uri .. (ngx.var.args and ("?" .. ngx.var.args) or ""),
|
||||
host = host
|
||||
})
|
||||
return ngx.exec("/.within.website/x/cmd/anubis/api/make-challenge")
|
||||
`
|
||||
|
||||
const openRestyPowChallengeLua = `local cjson = require "cjson.safe"
|
||||
|
||||
local pow_config_dict = ngx.shared.openflare_pow_config
|
||||
local pow_challenges = ngx.shared.openflare_pow_challenges
|
||||
|
||||
local function generate_entropy()
|
||||
local pieces = {
|
||||
tostring(ngx.now()),
|
||||
tostring(ngx.worker.pid()),
|
||||
tostring(math.random()),
|
||||
ngx.var.remote_addr or "",
|
||||
ngx.var.http_user_agent or "",
|
||||
ngx.var.request_id or "",
|
||||
}
|
||||
return table.concat(pieces, ":")
|
||||
end
|
||||
|
||||
local args = ngx.req.get_uri_args()
|
||||
local host = args["host"] or ngx.var.host or ""
|
||||
local redir = args["redir"] or ""
|
||||
|
||||
local config_raw = pow_config_dict:get(host)
|
||||
if not config_raw then
|
||||
ngx.status = 403
|
||||
ngx.say("PoW not configured for this host")
|
||||
return
|
||||
end
|
||||
|
||||
local ok, route_config = pcall(cjson.decode, config_raw)
|
||||
if not ok or not route_config or not route_config.enabled then
|
||||
ngx.status = 403
|
||||
ngx.say("PoW not enabled for this host")
|
||||
return
|
||||
end
|
||||
|
||||
local config = route_config.config or {}
|
||||
local difficulty = config.difficulty or 4
|
||||
local algorithm = config.algorithm or "fast"
|
||||
local challenge_ttl = config.challenge_ttl or 300
|
||||
local session_ttl = config.session_ttl or 600
|
||||
|
||||
-- Generate challenge data without depending on ngx.random_bytes, which is not
|
||||
-- available in every OpenResty runtime build.
|
||||
local entropy = generate_entropy()
|
||||
local challenge_id = ngx.md5(entropy .. ":id")
|
||||
local challenge_data = ngx.md5(entropy .. ":data-a") .. ngx.md5(entropy .. ":data-b")
|
||||
|
||||
-- Store challenge
|
||||
local challenge_info = cjson.encode({
|
||||
data = challenge_data,
|
||||
difficulty = difficulty,
|
||||
host = host,
|
||||
redir = redir,
|
||||
session_ttl = session_ttl
|
||||
})
|
||||
pow_challenges:set(challenge_id, challenge_info, challenge_ttl)
|
||||
|
||||
local static_prefix = "/.within.website/x/cmd/anubis/static/"
|
||||
local title = "Making sure you're not a bot!"
|
||||
local lang = "en"
|
||||
|
||||
ngx.header.content_type = "text/html; charset=utf-8"
|
||||
ngx.say([[<!DOCTYPE html>
|
||||
<html lang="]] .. lang .. [[">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="robots" content="noindex,nofollow">
|
||||
<title>]] .. title .. [[</title>
|
||||
<link rel="stylesheet" href="]] .. static_prefix .. [[css/xess.css">
|
||||
<style>
|
||||
body,html{height:100%;display:flex;justify-content:center;align-items:center;margin-left:auto;margin-right:auto}
|
||||
.centered-div{text-align:center}
|
||||
#status{font-variant-numeric:tabular-nums}
|
||||
#progress{display:none;width:min(20rem,90%);height:2rem;border-radius:1rem;overflow:hidden;margin:1rem 0 2rem;outline-offset:2px;outline:#b16286 solid 4px}
|
||||
.bar-inner{background-color:#b16286;height:100%;width:0;transition:width .25s ease-in}
|
||||
</style>
|
||||
<script id="anubis_version" type="application/json">"openflare-pow"</script>
|
||||
<script id="anubis_challenge" type="application/json">]] .. cjson.encode({
|
||||
challenge = {
|
||||
id = challenge_id,
|
||||
randomData = challenge_data,
|
||||
method = algorithm
|
||||
},
|
||||
rules = {
|
||||
difficulty = difficulty,
|
||||
algorithm = algorithm
|
||||
}
|
||||
}) .. [[</script>
|
||||
<script id="anubis_base_prefix" type="application/json">""</script>
|
||||
<script id="anubis_public_url" type="application/json">"__openflare_internal__"</script>
|
||||
</head>
|
||||
<body id="top">
|
||||
<main>
|
||||
<h1 id="title" class="centered-div">]] .. title .. [[</h1>
|
||||
<div class="centered-div">
|
||||
<img id="image" style="width:100%;max-width:256px;" src="]] .. static_prefix .. [[img/pensive.webp?cacheBuster=openflare-pow">
|
||||
<p id="status">Loading...</p>
|
||||
<p>This site is protected by a Proof-of-Work challenge. Your browser will solve a small puzzle before the upstream response is shown.</p>
|
||||
<div id="progress" role="progressbar" aria-labelledby="status"><div class="bar-inner"></div></div>
|
||||
<details>
|
||||
<summary>Why am I seeing this?</summary>
|
||||
<p>OpenFlare is asking your browser to complete a lightweight computation to distinguish normal browser traffic from automated abuse. This should finish automatically.</p>
|
||||
</details>
|
||||
<noscript><p>JavaScript is required to pass this verification. Please enable JavaScript and reload.</p></noscript>
|
||||
</div>
|
||||
</main>
|
||||
<script type="module" src="]] .. static_prefix .. [[js/main.mjs"></script>
|
||||
</body>
|
||||
</html>]])
|
||||
`
|
||||
|
||||
const openRestyPowVerifyLua = `local cjson = require "cjson.safe"
|
||||
|
||||
local pow_challenges = ngx.shared.openflare_pow_challenges
|
||||
local pow_sessions = ngx.shared.openflare_pow_sessions
|
||||
|
||||
local args = ngx.req.get_uri_args()
|
||||
local challenge_id = args["id"] or ""
|
||||
local response = args["response"] or ""
|
||||
local nonce_str = args["nonce"] or ""
|
||||
local redir = args["redir"] or ""
|
||||
local elapsed = args["elapsedTime"] or ""
|
||||
|
||||
if challenge_id == "" or response == "" or nonce_str == "" then
|
||||
ngx.status = 400
|
||||
ngx.header.content_type = "application/json"
|
||||
ngx.say(cjson.encode({error = "missing parameters"}))
|
||||
return
|
||||
end
|
||||
|
||||
local nonce = tonumber(nonce_str)
|
||||
if not nonce then
|
||||
ngx.status = 400
|
||||
ngx.header.content_type = "application/json"
|
||||
ngx.say(cjson.encode({error = "invalid nonce"}))
|
||||
return
|
||||
end
|
||||
|
||||
-- Get stored challenge
|
||||
local challenge_raw = pow_challenges:get(challenge_id)
|
||||
if not challenge_raw then
|
||||
ngx.status = 410
|
||||
ngx.header.content_type = "application/json"
|
||||
ngx.say(cjson.encode({error = "challenge expired or not found"}))
|
||||
return
|
||||
end
|
||||
|
||||
local ok, challenge_info = pcall(cjson.decode, challenge_raw)
|
||||
if not ok or not challenge_info then
|
||||
ngx.status = 500
|
||||
ngx.header.content_type = "application/json"
|
||||
ngx.say(cjson.encode({error = "invalid challenge data"}))
|
||||
return
|
||||
end
|
||||
|
||||
local challenge_data = challenge_info.data or ""
|
||||
local difficulty = challenge_info.difficulty or 4
|
||||
local host = challenge_info.host or ngx.var.host or ""
|
||||
local session_ttl = challenge_info.session_ttl or 600
|
||||
|
||||
-- Compute SHA-256(challenge_data + nonce)
|
||||
local calc_string = challenge_data .. tostring(math.floor(nonce))
|
||||
local calculated = ngx.sha1_bin ~= nil and "" or ""
|
||||
|
||||
-- Use resty.sha256 for proper SHA-256
|
||||
local sha256 = require "resty.sha256"
|
||||
local str = require "resty.string"
|
||||
local hasher = sha256:new()
|
||||
hasher:update(calc_string)
|
||||
local hash_bytes = hasher:final()
|
||||
local hash_hex = str.to_hex(hash_bytes)
|
||||
|
||||
-- Verify hash matches response
|
||||
if hash_hex ~= string.lower(response) then
|
||||
ngx.status = 403
|
||||
ngx.header.content_type = "application/json"
|
||||
ngx.say(cjson.encode({error = "hash mismatch"}))
|
||||
return
|
||||
end
|
||||
|
||||
-- Verify difficulty (leading zeros in hex)
|
||||
local prefix = string.rep("0", difficulty)
|
||||
if string.sub(hash_hex, 1, difficulty) ~= prefix then
|
||||
ngx.status = 403
|
||||
ngx.header.content_type = "application/json"
|
||||
ngx.say(cjson.encode({error = "insufficient difficulty"}))
|
||||
return
|
||||
end
|
||||
|
||||
-- Invalidate challenge (prevent replay)
|
||||
pow_challenges:delete(challenge_id)
|
||||
|
||||
-- Generate session token
|
||||
local session_token = str.to_hex(ngx.sha1_bin(challenge_id .. ngx.now() .. tostring(ngx.worker.pid())))
|
||||
|
||||
-- Store session
|
||||
pow_sessions:set(host .. ":" .. session_token, "1", session_ttl)
|
||||
|
||||
-- Set cookie. Secure cookies are not sent over HTTP, so only add Secure when
|
||||
-- the current request itself is HTTPS.
|
||||
local cookie = "__openflare_pow=" .. session_token .. "; Path=/; HttpOnly; SameSite=Lax; Max-Age=" .. tostring(session_ttl)
|
||||
if ngx.var.scheme == "https" then
|
||||
cookie = cookie .. "; Secure"
|
||||
end
|
||||
ngx.header["Set-Cookie"] = cookie
|
||||
|
||||
if redir ~= "" then
|
||||
return ngx.redirect(redir)
|
||||
end
|
||||
|
||||
ngx.header.content_type = "application/json"
|
||||
ngx.say(cjson.encode({ok = true}))
|
||||
`
|
||||
|
||||
const openRestyPowPolicyLua = `local M = {}
|
||||
|
||||
local function match_ip(remote_ip, ips)
|
||||
if not ips or #ips == 0 then return false end
|
||||
for _, ip in ipairs(ips) do
|
||||
if ip == remote_ip then
|
||||
return true
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
local function match_cidr(remote_ip, cidrs)
|
||||
if not cidrs or #cidrs == 0 then return false end
|
||||
for _, cidr in ipairs(cidrs) do
|
||||
local m, err = ngx.re.match(cidr, "^(\\\\d{1,3}\\\\.\\\\d{1,3}\\\\.\\\\d{1,3}\\\\.\\\\d{1,3})/(\\\\d{1,2})$")
|
||||
if m then
|
||||
local mask_bits = tonumber(m[2])
|
||||
if mask_bits and mask_bits >= 0 and mask_bits <= 32 then
|
||||
local function ip_to_num(ip_str)
|
||||
local parts = {}
|
||||
for part in string.gmatch(ip_str, "%d+") do
|
||||
parts[#parts+1] = tonumber(part) or 0
|
||||
end
|
||||
if #parts ~= 4 then return 0 end
|
||||
return parts[1]*16777216 + parts[2]*65536 + parts[3]*256 + parts[4]
|
||||
end
|
||||
local remote_num = ip_to_num(remote_ip)
|
||||
local net_num = ip_to_num(m[1])
|
||||
if mask_bits == 0 then
|
||||
return true
|
||||
end
|
||||
local mask = math.floor(2^(32 - mask_bits))
|
||||
mask = 4294967296 - mask
|
||||
if bit.band(remote_num, mask) == bit.band(net_num, mask) then
|
||||
return true
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
local function match_path(uri, patterns)
|
||||
if not patterns or #patterns == 0 then return false end
|
||||
for _, pattern in ipairs(patterns) do
|
||||
local ok, match = pcall(ngx.re.match, uri, "^" .. ngx.re.gsub(pattern, "([%^%$%(%)%%%.%[%]%+%-%?])", function(c)
|
||||
if c == "*" then return ".*" end
|
||||
return "%" .. c
|
||||
end) .. "$", "i")
|
||||
if ok and match then
|
||||
return true
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
local function match_path_regex(uri, patterns)
|
||||
if not patterns or #patterns == 0 then return false end
|
||||
for _, pattern in ipairs(patterns) do
|
||||
local ok, match = pcall(ngx.re.match, uri, pattern)
|
||||
if ok and match then
|
||||
return true
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
local function match_ua(ua, patterns)
|
||||
if not patterns or #patterns == 0 then return false end
|
||||
for _, pattern in ipairs(patterns) do
|
||||
if ua and string.find(ua, pattern, 1, true) then
|
||||
return true
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
function M.match_any(remote_ip, ua, uri, list)
|
||||
if not list then return false end
|
||||
if match_ip(remote_ip, list.ips) then return true end
|
||||
if match_cidr(remote_ip, list.ip_cidrs) then return true end
|
||||
if match_path(uri, list.paths) then return true end
|
||||
if match_path_regex(uri, list.path_regexes) then return true end
|
||||
if match_ua(ua, list.user_agents) then return true end
|
||||
return false
|
||||
end
|
||||
|
||||
function M.has_entries(list)
|
||||
if not list then return false end
|
||||
return (#(list.ips or {}) + #(list.ip_cidrs or {}) + #(list.paths or {}) + #(list.path_regexes or {}) + #(list.user_agents or {})) > 0
|
||||
end
|
||||
|
||||
return M
|
||||
`
|
||||
|
||||
func ManagedPowLuaFiles() []protocol.SupportFile {
|
||||
return []protocol.SupportFile{
|
||||
{Path: "pow/check.lua", Content: openRestyPowCheckLua},
|
||||
{Path: "pow/challenge.lua", Content: openRestyPowChallengeLua},
|
||||
{Path: "pow/verify.lua", Content: openRestyPowVerifyLua},
|
||||
{Path: "pow/policy.lua", Content: openRestyPowPolicyLua},
|
||||
}
|
||||
}
|
||||
|
||||
func ManagedPowStaticFiles() ([]protocol.SupportFile, error) {
|
||||
var files []protocol.SupportFile
|
||||
entries, err := powStaticFS.ReadDir("pow_static")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var walk func(dir string) error
|
||||
walk = func(dir string) error {
|
||||
entries, err := powStaticFS.ReadDir(dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, entry := range entries {
|
||||
fullPath := filepath.Join(dir, entry.Name())
|
||||
if entry.IsDir() {
|
||||
if err := walk(fullPath); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
data, err := powStaticFS.ReadFile(fullPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Convert pow_static/css/xess.css -> pow/static/css/xess.css
|
||||
relPath := strings.TrimPrefix(fullPath, "pow_static/")
|
||||
files = append(files, protocol.SupportFile{
|
||||
Path: "pow/static/" + relPath,
|
||||
Content: string(data),
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for _, entry := range entries {
|
||||
fullPath := filepath.Join("pow_static", entry.Name())
|
||||
if entry.IsDir() {
|
||||
if err := walk(fullPath); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
data, err := powStaticFS.ReadFile(fullPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
relPath := strings.TrimPrefix(fullPath, "pow_static/")
|
||||
files = append(files, protocol.SupportFile{
|
||||
Path: "pow/static/" + relPath,
|
||||
Content: string(data),
|
||||
})
|
||||
}
|
||||
}
|
||||
return files, nil
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,7 @@
|
||||
@font-face {
|
||||
font-family: "Podkova";
|
||||
font-style: normal;
|
||||
font-weight: 400 800;
|
||||
font-display: swap;
|
||||
src: url("podkova.woff2") format("woff2");
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,149 @@
|
||||
:root {
|
||||
--body-sans-font: Geist, sans-serif;
|
||||
--body-preformatted-font: Iosevka Curly Iaso, monospace;
|
||||
--body-title-font: Podkova, serif;
|
||||
|
||||
--background: #1d2021;
|
||||
--text: #f9f5d7;
|
||||
--text-selection: #d3869b;
|
||||
--preformatted-background: #3c3836;
|
||||
--link-foreground: #b16286;
|
||||
--link-background: #282828;
|
||||
--blockquote-border-left: 1px solid #bdae93;
|
||||
|
||||
--progress-bar-outline: #b16286 solid 4px;
|
||||
--progress-bar-fill: #b16286;
|
||||
}
|
||||
@media (prefers-color-scheme: light) {
|
||||
:root {
|
||||
--background: #f9f5d7;
|
||||
--text: #1d2021;
|
||||
--text-selection: #d3869b;
|
||||
--preformatted-background: #ebdbb2;
|
||||
--link-foreground: #b16286;
|
||||
--link-background: #fbf1c7;
|
||||
--blockquote-border-left: 1px solid #655c54;
|
||||
}
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Geist";
|
||||
font-style: normal;
|
||||
font-weight: 100 900;
|
||||
font-display: swap;
|
||||
src: url("./static/geist.woff2") format("woff2");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Podkova";
|
||||
font-style: normal;
|
||||
font-weight: 400 800;
|
||||
font-display: swap;
|
||||
src: url("./static/podkova.woff2") format("woff2");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Iosevka Curly";
|
||||
font-style: monospace;
|
||||
font-display: swap;
|
||||
src: url("./static/iosevka-curly.woff2") format("woff2");
|
||||
}
|
||||
|
||||
main {
|
||||
font-family: var(--body-sans-font);
|
||||
max-width: 50rem;
|
||||
padding: 2rem;
|
||||
margin: auto;
|
||||
}
|
||||
|
||||
::selection {
|
||||
background: var(--text-selection);
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--background);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
body,
|
||||
html {
|
||||
height: 100%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
.centered-div {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
#status {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.centered-div {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
#status {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
#progress {
|
||||
display: none;
|
||||
width: min(20rem, 90%);
|
||||
height: 2rem;
|
||||
border-radius: 1rem;
|
||||
overflow: hidden;
|
||||
margin: 1rem 0 2rem;
|
||||
outline-offset: 2px;
|
||||
outline: var(--progress-bar-outline);
|
||||
}
|
||||
|
||||
.bar-inner {
|
||||
background-color: var(--progress-bar-fill);
|
||||
height: 100%;
|
||||
width: 0;
|
||||
transition: width 0.25s ease-in;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.bar-inner {
|
||||
transition: width 0.25s ease-in;
|
||||
}
|
||||
}
|
||||
|
||||
pre {
|
||||
background-color: var(--preformatted-background);
|
||||
padding: 1em;
|
||||
border: 0;
|
||||
font-family: var(--body-preformatted-font);
|
||||
}
|
||||
|
||||
a,
|
||||
a:active,
|
||||
a:visited {
|
||||
color: var(--link-foreground);
|
||||
background-color: var(--link-background);
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
h3,
|
||||
h4,
|
||||
h5 {
|
||||
margin-bottom: 0.1rem;
|
||||
font-family: var(--body-title-font);
|
||||
}
|
||||
|
||||
blockquote {
|
||||
border-left: var(--blockquote-border-left);
|
||||
margin: 0.5em 10px;
|
||||
padding: 0.5em 10px;
|
||||
}
|
||||
|
||||
footer {
|
||||
text-align: center;
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 30 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 28 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 26 KiB |
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
@licstart The following is the entire license notice for the
|
||||
JavaScript code in this page.
|
||||
|
||||
Copyright (c) 2025 Xe Iaso <xe.iaso@techaro.lol>
|
||||
|
||||
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 k=()=>navigator.hardwareConcurrency!==void 0?navigator.hardwareConcurrency:1;function n(c,b,w=5,e=null,g,u=Math.trunc(Math.max(k()/2,1))){console.debug("fast algo");let s="purejs";return window.isSecureContext&&(s="webcrypto"),(navigator.userAgent.includes("Firefox")||navigator.userAgent.includes("Goanna"))&&(console.log("Firefox detected, using pure-JS fallback"),s="purejs"),new Promise((p,l)=>{let m=`${c.basePrefix}/.within.website/x/cmd/anubis/static/js/worker/sha256-${s}.mjs?cacheBuster=${c.version}`,f=[],d=!1,a=()=>{console.log("PoW aborted"),i(),l(new DOMException("Aborted","AbortError"))},i=()=>{d||(d=!0,f.forEach(r=>r.terminate()),e?.removeEventListener("abort",a))};if(e!=null){if(e.aborted)return a();e.addEventListener("abort",a,{once:!0})}for(let r=0;r<u;r++){let t=new Worker(m);t.onmessage=o=>{typeof o.data=="number"?g?.(o.data):(i(),p(o.data))},t.onerror=o=>{i(),l(o)},t.postMessage({data:b,difficulty:w,nonce:r,threads:u}),f.push(t)}})}var P={fast:n,slow:n};})();
|
||||
//# sourceMappingURL=index.mjs.map
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
@licstart The following is the entire license notice for the
|
||||
JavaScript code in this page.
|
||||
|
||||
Copyright (c) 2025 Xe Iaso <xe.iaso@techaro.lol>
|
||||
|
||||
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 I=()=>navigator.hardwareConcurrency!==void 0?navigator.hardwareConcurrency:1;function _(e,n,s=5,o=null,i,u=Math.trunc(Math.max(I()/2,1))){console.debug("fast algo");let a="purejs";return window.isSecureContext&&(a="webcrypto"),(navigator.userAgent.includes("Firefox")||navigator.userAgent.includes("Goanna"))&&(console.log("Firefox detected, using pure-JS fallback"),a="purejs"),new Promise((E,x)=>{let M=`${e.basePrefix}/.within.website/x/cmd/anubis/static/js/worker/sha256-${a}.mjs?cacheBuster=${e.version}`,p=[],d=!1,b=()=>{console.log("PoW aborted"),h(),x(new DOMException("Aborted","AbortError"))},h=()=>{d||(d=!0,p.forEach(c=>c.terminate()),o?.removeEventListener("abort",b))};if(o!=null){if(o.aborted)return b();o.addEventListener("abort",b,{once:!0})}for(let c=0;c<u;c++){let g=new Worker(M);g.onmessage=m=>{typeof m.data=="number"?i?.(m.data):(h(),E(m.data))},g.onerror=m=>{h(),x(m)},g.postMessage({data:n,difficulty:s,nonce:c,threads:u}),p.push(g)}})}var j={fast:_,slow:_};var v=(e="",n={})=>{let s=new URL(e,window.location.href);return Object.entries(n).forEach(([o,i])=>s.searchParams.set(o,i)),s.toString()},L=e=>{let n=document.getElementById(e);return n===null?null:JSON.parse(n.textContent)},k=(e,n,s)=>v(`${s}/.within.website/x/cmd/anubis/static/img/${e}.webp`,{cacheBuster:n});var W=async()=>document.documentElement.lang,S=async e=>{let n=L("anubis_base_prefix");if(n!==null)try{return await(await fetch(`${n}/.within.website/x/cmd/anubis/static/locales/${e}.json`)).json()}catch(s){if(console.warn(`Failed to load translations for ${e}, falling back to English`),e!=="en")return await S("en");throw s}},C=()=>{let e=L("anubis_public_url");if(e!==null)return e&&window.location.href.startsWith(e)?new URLSearchParams(window.location.search).get("redir"):window.location.href},$={},D,A=async()=>{D=await W(),$=await S(D)},r=e=>$[`js_${e}`]||$[e]||e;(async()=>{await A();let e=[{name:"Web Workers",msg:r("web_workers_error"),value:window.Worker},{name:"Cookies",msg:r("cookies_error"),value:navigator.cookieEnabled}],n=document.getElementById("status"),s=document.getElementById("image"),o=document.getElementById("title"),i=document.getElementById("progress"),u=L("anubis_version"),a=L("anubis_base_prefix"),E=document.querySelector("details"),x=!1;E&&E.addEventListener("toggle",()=>{E.open&&(x=!0)});let M=({titleMsg:l,statusMsg:f,imageSrc:w})=>{o.innerHTML=l,n.innerHTML=f,s.src=w,i.style.display="none"};n.innerHTML=r("calculating");for(let{value:l,name:f,msg:w}of e)if(!l){M({titleMsg:`${r("missing_feature")} ${f}`,statusMsg:w,imageSrc:k("reject",u,a)});return}let{challenge:p,rules:d}=L("anubis_challenge"),b=j[d.algorithm];if(!b){M({titleMsg:r("challenge_error"),statusMsg:r("challenge_error_msg"),imageSrc:k("reject",u,a)});return}n.innerHTML=`${r("calculating_difficulty")} ${d.difficulty}, `,i.style.display="inline-block";let h=document.createTextNode(`${r("speed")} 0kH/s`);n.appendChild(h);let c=0,g=!1,m=Math.pow(16,-d.difficulty);try{let l=Date.now(),{hash:f,nonce:w}=await b({basePrefix:a,version:u},p.randomData,d.difficulty,null,t=>{let y=Date.now()-l;y-c>1e3&&(c=y,h.data=`${r("speed")} ${(t/y).toFixed(3)}kH/s`);let T=Math.pow(1-m,t),P=(1-Math.pow(T,2))*100;i["aria-valuenow"]=P,i.firstElementChild!==null&&(i.firstElementChild.style.width=`${P}%`),T<.1&&!g&&(n.append(document.createElement("br"),document.createTextNode(r("verification_longer"))),g=!0)}),H=Date.now();if(console.log({hash:f,nonce:w}),x){let y=function(){let T=C();window.location.replace(v(`${a}/.within.website/x/cmd/anubis/api/pass-challenge`,{id:p.id,response:f,nonce:w,redir:T,elapsedTime:H-l}))},t=document.getElementById("progress");t.style.display="flex",t.style.alignItems="center",t.style.justifyContent="center",t.style.height="2rem",t.style.borderRadius="1rem",t.style.cursor="pointer",t.style.background="#b16286",t.style.color="white",t.style.fontWeight="bold",t.style.outline="4px solid #b16286",t.style.outlineOffset="2px",t.style.width="min(20rem, 90%)",t.style.margin="1rem auto 2rem",t.innerHTML=r("finished_reading"),t.onclick=y,setTimeout(y,3e4)}else{let t=C();window.location.replace(v(`${a}/.within.website/x/cmd/anubis/api/pass-challenge`,{id:p.id,response:f,nonce:w,redir:t,elapsedTime:H-l}))}}catch(l){M({titleMsg:r("calculation_error"),statusMsg:`${r("calculation_error_msg")} ${l.message}`,imageSrc:k("reject",u,a)})}})();})();
|
||||
//# sourceMappingURL=main.mjs.map
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
@licstart The following is the entire license notice for the
|
||||
JavaScript code in this page.
|
||||
|
||||
Copyright (c) 2025 Xe Iaso <xe.iaso@techaro.lol>
|
||||
|
||||
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<c;n++)if(i[n]!==0){r=!1;break}if(r&&l&&i[c]>>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
|
||||
@@ -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 <a href=\"https://en.wikipedia.org/wiki/Proof_of_work\">Proof of Work</a>. 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 <a href=\"https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts#when_is_a_context_considered_secure\">MDN</a>.",
|
||||
"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...<br/>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:"
|
||||
}
|
||||
@@ -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。更多信息请参见 <a href=\"https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts#when_is_a_context_considered_secure\">MDN</a>。",
|
||||
"js_calculating": "计算中...",
|
||||
"js_missing_feature": "缺少功能",
|
||||
"js_challenge_error": "挑战错误!",
|
||||
"js_challenge_error_msg": "解决检查算法失败。 您可能会想要刷新页面。",
|
||||
"js_calculating_difficulty": "计算中...<br/>难度:",
|
||||
"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": "这是一种类似于验证码的措施,用于防止机器人和恶意请求。但是,您无需自己动手,您的浏览器会收到一个计算任务,必须解决该任务以确保它是有效的客户端。这个概念称为<a href=\"https://en.wikipedia.org/wiki/Proof_of_work\">工作量证明</a>。该任务在几秒钟内计算完毕,您将被授予访问网站的权限。感谢您的理解和耐心。"
|
||||
}
|
||||
@@ -11,7 +11,7 @@ RUN corepack enable && pnpm install --frozen-lockfile
|
||||
COPY ./web ./
|
||||
RUN NEXT_PUBLIC_APP_VERSION="$VERSION" pnpm build
|
||||
|
||||
FROM golang:1.24 AS builder2
|
||||
FROM golang:1.25 AS builder2
|
||||
|
||||
ARG VERSION
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
"openflare/model"
|
||||
)
|
||||
|
||||
// GetDefaultAcmeAccount godoc
|
||||
// @Summary Get default ACME account
|
||||
// @Tags AcmeAccounts
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Router /api/acme-accounts/default [get]
|
||||
func GetDefaultAcmeAccount(c *gin.Context) {
|
||||
account, err := model.GetDefaultAcmeAccount()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": false,
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "",
|
||||
"data": account,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"openflare/common"
|
||||
"openflare/model"
|
||||
"openflare/service"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-contrib/sessions"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const pendingExternalAccountSessionKey = "pending_external_account"
|
||||
|
||||
type authSourceTogglePayload struct {
|
||||
IsActive bool `json:"is_active"`
|
||||
}
|
||||
|
||||
type authSourcePayload struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
DisplayName string `json:"display_name"`
|
||||
IsActive bool `json:"is_active"`
|
||||
ClientID string `json:"client_id"`
|
||||
ClientSecret string `json:"client_secret"`
|
||||
OpenIDDiscoveryURL string `json:"openid_discovery_url"`
|
||||
Scopes string `json:"scopes"`
|
||||
IconURL string `json:"icon_url"`
|
||||
}
|
||||
|
||||
func (payload authSourcePayload) toModel() model.AuthSource {
|
||||
return model.AuthSource{
|
||||
Name: payload.Name,
|
||||
Type: payload.Type,
|
||||
DisplayName: payload.DisplayName,
|
||||
IsActive: payload.IsActive,
|
||||
ClientID: payload.ClientID,
|
||||
ClientSecret: payload.ClientSecret,
|
||||
OpenIDDiscoveryURL: payload.OpenIDDiscoveryURL,
|
||||
Scopes: payload.Scopes,
|
||||
IconURL: payload.IconURL,
|
||||
}
|
||||
}
|
||||
|
||||
func ListAuthSources(c *gin.Context) {
|
||||
sources, err := model.GetAuthSources()
|
||||
if err != nil {
|
||||
respondFailure(c, err.Error())
|
||||
return
|
||||
}
|
||||
respondSuccess(c, sources)
|
||||
}
|
||||
|
||||
func CreateAuthSource(c *gin.Context) {
|
||||
var payload authSourcePayload
|
||||
if err := decodeJSONBody(c.Request.Body, &payload); err != nil {
|
||||
respondBadRequest(c, "无效的参数")
|
||||
return
|
||||
}
|
||||
source := payload.toModel()
|
||||
if err := model.CreateAuthSource(&source); err != nil {
|
||||
respondFailure(c, err.Error())
|
||||
return
|
||||
}
|
||||
source.Sanitize()
|
||||
respondSuccess(c, source)
|
||||
}
|
||||
|
||||
func UpdateAuthSource(c *gin.Context) {
|
||||
id, err := parseAuthSourceID(c)
|
||||
if err != nil {
|
||||
respondBadRequest(c, err.Error())
|
||||
return
|
||||
}
|
||||
var payload authSourcePayload
|
||||
if err := decodeJSONBody(c.Request.Body, &payload); err != nil {
|
||||
respondBadRequest(c, "无效的参数")
|
||||
return
|
||||
}
|
||||
source := payload.toModel()
|
||||
source.ID = id
|
||||
keepSecret := strings.TrimSpace(source.ClientSecret) == ""
|
||||
if err := model.UpdateAuthSource(&source, keepSecret); err != nil {
|
||||
respondFailure(c, err.Error())
|
||||
return
|
||||
}
|
||||
updated, err := model.GetAuthSourceByID(id)
|
||||
if err != nil {
|
||||
respondFailure(c, err.Error())
|
||||
return
|
||||
}
|
||||
updated.Sanitize()
|
||||
respondSuccess(c, updated)
|
||||
}
|
||||
|
||||
func DeleteAuthSource(c *gin.Context) {
|
||||
id, err := parseAuthSourceID(c)
|
||||
if err != nil {
|
||||
respondBadRequest(c, err.Error())
|
||||
return
|
||||
}
|
||||
if err := model.DeleteAuthSource(id); err != nil {
|
||||
respondFailure(c, err.Error())
|
||||
return
|
||||
}
|
||||
respondSuccessMessage(c, "")
|
||||
}
|
||||
|
||||
func ToggleAuthSource(c *gin.Context) {
|
||||
id, err := parseAuthSourceID(c)
|
||||
if err != nil {
|
||||
respondBadRequest(c, err.Error())
|
||||
return
|
||||
}
|
||||
var payload authSourceTogglePayload
|
||||
if err := decodeJSONBody(c.Request.Body, &payload); err != nil {
|
||||
respondBadRequest(c, "无效的参数")
|
||||
return
|
||||
}
|
||||
if err := model.ToggleAuthSource(id, payload.IsActive); err != nil {
|
||||
respondFailure(c, err.Error())
|
||||
return
|
||||
}
|
||||
respondSuccessMessage(c, "")
|
||||
}
|
||||
|
||||
func OAuthAuthorize(c *gin.Context) {
|
||||
source, err := getAuthSourceFromRoute(c)
|
||||
if err != nil {
|
||||
respondBadRequest(c, err.Error())
|
||||
return
|
||||
}
|
||||
if !source.IsActive {
|
||||
respondFailure(c, "认证源未启用")
|
||||
return
|
||||
}
|
||||
if err := source.Validate(); err != nil {
|
||||
respondFailure(c, err.Error())
|
||||
return
|
||||
}
|
||||
state, err := service.GenerateOAuthState()
|
||||
if err != nil {
|
||||
respondFailure(c, err.Error())
|
||||
return
|
||||
}
|
||||
session := sessions.Default(c)
|
||||
session.Set(oauthStateSessionKey(source.ID), state)
|
||||
if err := session.Save(); err != nil {
|
||||
respondFailure(c, "无法保存授权状态,请重试")
|
||||
return
|
||||
}
|
||||
redirectURL := oauthFrontendCallbackURL(c, source.ID)
|
||||
authorizeURL, err := service.BuildAuthorizeURL(c.Request.Context(), source, redirectURL, state)
|
||||
if err != nil {
|
||||
respondFailure(c, err.Error())
|
||||
return
|
||||
}
|
||||
respondSuccess(c, gin.H{"authorize_url": authorizeURL})
|
||||
}
|
||||
|
||||
func OAuthCallback(c *gin.Context) {
|
||||
source, err := getAuthSourceFromRoute(c)
|
||||
if err != nil {
|
||||
respondBadRequest(c, err.Error())
|
||||
return
|
||||
}
|
||||
if !source.IsActive {
|
||||
respondFailure(c, "认证源未启用")
|
||||
return
|
||||
}
|
||||
session := sessions.Default(c)
|
||||
expectedState, _ := session.Get(oauthStateSessionKey(source.ID)).(string)
|
||||
state := c.Query("state")
|
||||
if expectedState == "" || state == "" || state != expectedState {
|
||||
respondFailure(c, "授权状态无效,请重新登录")
|
||||
return
|
||||
}
|
||||
session.Delete(oauthStateSessionKey(source.ID))
|
||||
if err := session.Save(); err != nil {
|
||||
respondFailure(c, "无法更新授权状态,请重试")
|
||||
return
|
||||
}
|
||||
if oauthError := c.Query("error"); oauthError != "" {
|
||||
description := c.Query("error_description")
|
||||
if description == "" {
|
||||
description = oauthError
|
||||
}
|
||||
respondFailure(c, description)
|
||||
return
|
||||
}
|
||||
|
||||
profile, err := service.ExchangeOAuthProfile(c.Request.Context(), source, c.Query("code"), oauthFrontendCallbackURL(c, source.ID))
|
||||
if err != nil {
|
||||
respondFailure(c, err.Error())
|
||||
return
|
||||
}
|
||||
var currentUserID *int
|
||||
if value := session.Get("id"); value != nil {
|
||||
if idValue, ok := value.(int); ok {
|
||||
currentUserID = &idValue
|
||||
}
|
||||
}
|
||||
result, pending, err := service.CompleteOAuthLogin(source, profile, currentUserID)
|
||||
if err != nil {
|
||||
respondFailure(c, err.Error())
|
||||
return
|
||||
}
|
||||
if pending != nil {
|
||||
raw, err := json.Marshal(pending)
|
||||
if err != nil {
|
||||
respondFailure(c, err.Error())
|
||||
return
|
||||
}
|
||||
session.Set(pendingExternalAccountSessionKey, string(raw))
|
||||
if err := session.Save(); err != nil {
|
||||
respondFailure(c, "无法保存待绑定账号,请重试")
|
||||
return
|
||||
}
|
||||
respondSuccess(c, result)
|
||||
return
|
||||
}
|
||||
if result.User != nil {
|
||||
cleanUser, err := setLoginSession(result.User, c)
|
||||
if err != nil {
|
||||
respondFailure(c, "无法保存会话信息,请重试")
|
||||
return
|
||||
}
|
||||
result.User = cleanUser
|
||||
}
|
||||
respondSuccess(c, result)
|
||||
}
|
||||
|
||||
func LinkExistingOAuthAccount(c *gin.Context) {
|
||||
session := sessions.Default(c)
|
||||
raw, _ := session.Get(pendingExternalAccountSessionKey).(string)
|
||||
if raw == "" {
|
||||
respondFailure(c, "待绑定第三方账号已失效,请重新登录")
|
||||
return
|
||||
}
|
||||
var pending service.PendingExternalAccount
|
||||
if err := json.Unmarshal([]byte(raw), &pending); err != nil {
|
||||
respondFailure(c, "待绑定第三方账号无效,请重新登录")
|
||||
return
|
||||
}
|
||||
var input service.LinkExistingRequest
|
||||
if err := decodeJSONBody(c.Request.Body, &input); err != nil {
|
||||
respondBadRequest(c, "无效的参数")
|
||||
return
|
||||
}
|
||||
user, err := service.LinkPendingExternalAccount(&pending, input)
|
||||
if err != nil {
|
||||
respondFailure(c, err.Error())
|
||||
return
|
||||
}
|
||||
session.Delete(pendingExternalAccountSessionKey)
|
||||
if err := session.Save(); err != nil {
|
||||
respondFailure(c, "无法更新会话信息,请重试")
|
||||
return
|
||||
}
|
||||
cleanUser, err := setLoginSession(user, c)
|
||||
if err != nil {
|
||||
respondFailure(c, "无法保存会话信息,请重试")
|
||||
return
|
||||
}
|
||||
respondSuccess(c, service.OAuthCallbackResult{Status: "linked", User: cleanUser})
|
||||
}
|
||||
|
||||
func ListExternalAccounts(c *gin.Context) {
|
||||
userID := c.GetInt("id")
|
||||
accounts, err := model.ListExternalAccountsByUserID(userID)
|
||||
if err != nil {
|
||||
respondFailure(c, err.Error())
|
||||
return
|
||||
}
|
||||
respondSuccess(c, accounts)
|
||||
}
|
||||
|
||||
func DeleteExternalAccount(c *gin.Context) {
|
||||
rawID := strings.TrimSpace(c.Param("id"))
|
||||
parsedID, err := strconv.ParseUint(rawID, 10, 64)
|
||||
if err != nil || parsedID == 0 {
|
||||
respondBadRequest(c, "绑定记录 ID 无效")
|
||||
return
|
||||
}
|
||||
if err := model.DeleteExternalAccountForUser(uint(parsedID), c.GetInt("id")); err != nil {
|
||||
respondFailure(c, err.Error())
|
||||
return
|
||||
}
|
||||
respondSuccessMessage(c, "")
|
||||
}
|
||||
|
||||
func parseAuthSourceID(c *gin.Context) (uint, error) {
|
||||
raw := c.Param("source_id")
|
||||
if raw == "" {
|
||||
raw = c.Param("id")
|
||||
}
|
||||
parsed, err := strconv.ParseUint(raw, 10, 64)
|
||||
if err != nil || parsed == 0 {
|
||||
return 0, fmt.Errorf("认证源 ID 无效")
|
||||
}
|
||||
return uint(parsed), nil
|
||||
}
|
||||
|
||||
func getAuthSourceFromRoute(c *gin.Context) (*model.AuthSource, error) {
|
||||
raw := strings.TrimSpace(c.Param("source"))
|
||||
if raw == "" {
|
||||
raw = strings.TrimSpace(c.Param("source_id"))
|
||||
}
|
||||
if raw == "" {
|
||||
raw = strings.TrimSpace(c.Param("id"))
|
||||
}
|
||||
if raw == "" {
|
||||
return nil, fmt.Errorf("认证源不能为空")
|
||||
}
|
||||
if parsed, err := strconv.ParseUint(raw, 10, 64); err == nil && parsed > 0 {
|
||||
source, err := model.GetAuthSourceByID(uint(parsed))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return source, nil
|
||||
}
|
||||
source, err := model.GetAuthSourceByName(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return source, nil
|
||||
}
|
||||
|
||||
func oauthStateSessionKey(sourceID uint) string {
|
||||
return fmt.Sprintf("oauth_state_%d", sourceID)
|
||||
}
|
||||
|
||||
func oauthFrontendCallbackURL(c *gin.Context, sourceID uint) string {
|
||||
base := strings.TrimRight(common.ServerAddress, "/")
|
||||
if base == "" {
|
||||
scheme := "http"
|
||||
if c.Request.TLS != nil || c.GetHeader("X-Forwarded-Proto") == "https" {
|
||||
scheme = "https"
|
||||
}
|
||||
host := c.Request.Host
|
||||
if forwardedHost := c.GetHeader("X-Forwarded-Host"); forwardedHost != "" {
|
||||
host = forwardedHost
|
||||
}
|
||||
base = scheme + "://" + host
|
||||
}
|
||||
source, err := model.GetAuthSourceByID(sourceID)
|
||||
sourceName := strconv.FormatUint(uint64(sourceID), 10)
|
||||
if err == nil && strings.TrimSpace(source.Name) != "" {
|
||||
sourceName = source.Name
|
||||
}
|
||||
callback, _ := url.JoinPath(base, "oauth", sourceName)
|
||||
return callback
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
"openflare/model"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type DnsAccountInput struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Authorization string `json:"authorization"`
|
||||
}
|
||||
|
||||
// GetDnsAccounts godoc
|
||||
// @Summary List DNS accounts
|
||||
// @Tags DnsAccounts
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Router /api/dns-accounts/ [get]
|
||||
func GetDnsAccounts(c *gin.Context) {
|
||||
accounts, err := model.ListDnsAccounts()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": false,
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "",
|
||||
"data": accounts,
|
||||
})
|
||||
}
|
||||
|
||||
// CreateDnsAccount godoc
|
||||
// @Summary Create DNS account
|
||||
// @Tags DnsAccounts
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param payload body DnsAccountInput true "DNS account payload"
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Router /api/dns-accounts/ [post]
|
||||
func CreateDnsAccount(c *gin.Context) {
|
||||
var input DnsAccountInput
|
||||
if err := json.NewDecoder(c.Request.Body).Decode(&input); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"success": false,
|
||||
"message": "无效的参数",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
account := &model.DnsAccount{
|
||||
Name: input.Name,
|
||||
Type: input.Type,
|
||||
Authorization: input.Authorization,
|
||||
}
|
||||
|
||||
if err := account.Insert(); err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": false,
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "",
|
||||
"data": account,
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateDnsAccount godoc
|
||||
// @Summary Update DNS account
|
||||
// @Tags DnsAccounts
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "DNS Account ID"
|
||||
// @Param payload body DnsAccountInput true "DNS account payload"
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Router /api/dns-accounts/{id}/update [post]
|
||||
func UpdateDnsAccount(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"success": false,
|
||||
"message": "无效的参数",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
var input DnsAccountInput
|
||||
if err := json.NewDecoder(c.Request.Body).Decode(&input); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"success": false,
|
||||
"message": "无效的参数",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
account, err := model.GetDnsAccountByID(uint(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": false,
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
account.Name = input.Name
|
||||
account.Type = input.Type
|
||||
account.Authorization = input.Authorization
|
||||
|
||||
if err := account.Update(); err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": false,
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "",
|
||||
"data": account,
|
||||
})
|
||||
}
|
||||
|
||||
// DeleteDnsAccount godoc
|
||||
// @Summary Delete DNS account
|
||||
// @Tags DnsAccounts
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "DNS Account ID"
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Router /api/dns-accounts/{id}/delete [post]
|
||||
func DeleteDnsAccount(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"success": false,
|
||||
"message": "无效的参数",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
account, err := model.GetDnsAccountByID(uint(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": false,
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Verify no cert uses this before deleting
|
||||
var count int64
|
||||
model.DB.Model(&model.TLSCertificate{}).Where("dns_account_id = ?", id).Count(&count)
|
||||
if count > 0 {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": false,
|
||||
"message": "该 DNS 账号已被证书使用,无法删除",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if err := account.Delete(); err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": false,
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "",
|
||||
})
|
||||
}
|
||||
@@ -1,160 +0,0 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
"openflare/common"
|
||||
"openflare/model"
|
||||
"openflare/utils"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func GetAllFiles(c *gin.Context) {
|
||||
p, _ := strconv.Atoi(c.Query("p"))
|
||||
if p < 0 {
|
||||
p = 0
|
||||
}
|
||||
files, err := model.GetAllFiles(p*common.ItemsPerPage, common.ItemsPerPage)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": false,
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "",
|
||||
"data": files,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
func SearchFiles(c *gin.Context) {
|
||||
keyword := c.Query("keyword")
|
||||
files, err := model.SearchFiles(keyword)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": false,
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "",
|
||||
"data": files,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
func UploadFile(c *gin.Context) {
|
||||
form, err := c.MultipartForm()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": false,
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
uploadPath := common.UploadPath
|
||||
description := c.PostForm("description")
|
||||
if description == "" {
|
||||
description = "无描述信息"
|
||||
}
|
||||
uploader := c.GetString("username")
|
||||
if uploader == "" {
|
||||
uploader = "访客用户"
|
||||
}
|
||||
uploaderId := c.GetInt("id")
|
||||
currentTime := time.Now().Format("2006-01-02 15:04:05")
|
||||
files := form.File["file"]
|
||||
for _, file := range files {
|
||||
filename := filepath.Base(file.Filename)
|
||||
ext := filepath.Ext(filename)
|
||||
link := utils.GetUUID() + ext
|
||||
savePath := filepath.Join(uploadPath, link) // both parts are checked, so this path should be safe to use
|
||||
if err := c.SaveUploadedFile(file, savePath); err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": false,
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
// save to database
|
||||
fileObj := &model.File{
|
||||
Description: description,
|
||||
Uploader: uploader,
|
||||
UploadTime: currentTime,
|
||||
UploaderId: uploaderId,
|
||||
Link: link,
|
||||
Filename: filename,
|
||||
}
|
||||
err = fileObj.Insert()
|
||||
if err != nil {
|
||||
_ = err
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
func DeleteFile(c *gin.Context) {
|
||||
fileIdStr := c.Param("id")
|
||||
fileId, err := strconv.Atoi(fileIdStr)
|
||||
if err != nil || fileId == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"success": false,
|
||||
"message": "无效的参数",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
fileObj := &model.File{
|
||||
Id: fileId,
|
||||
}
|
||||
model.DB.Where("id = ?", fileId).First(&fileObj)
|
||||
if fileObj.Link == "" {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": false,
|
||||
"message": "文件不存在!",
|
||||
})
|
||||
return
|
||||
}
|
||||
err = fileObj.Delete()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
} else {
|
||||
message := "文件删除成功"
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": message,
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func DownloadFile(c *gin.Context) {
|
||||
path := c.Param("file")
|
||||
fullPath := filepath.Join(common.UploadPath, path)
|
||||
if !strings.HasPrefix(fullPath, common.UploadPath) {
|
||||
// We may being attacked!
|
||||
c.Status(403)
|
||||
return
|
||||
}
|
||||
c.File(fullPath)
|
||||
// Update download counter
|
||||
go func() {
|
||||
model.UpdateDownloadCounter(path)
|
||||
}()
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"net/http"
|
||||
"openflare/common"
|
||||
"openflare/model"
|
||||
"openflare/service"
|
||||
"openflare/utils/mail"
|
||||
"openflare/utils/security"
|
||||
"openflare/utils/validation"
|
||||
@@ -19,6 +20,10 @@ import (
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Router /api/status [get]
|
||||
func GetStatus(c *gin.Context) {
|
||||
authSources, err := service.PublicAuthSources("/api")
|
||||
if err != nil {
|
||||
authSources = []service.PublicAuthSource{}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "",
|
||||
@@ -38,6 +43,7 @@ func GetStatus(c *gin.Context) {
|
||||
"turnstile_site_key": common.TurnstileSiteKey,
|
||||
"register_enabled": common.RegisterEnabled,
|
||||
"password_register_enabled": common.PasswordRegisterEnabled,
|
||||
"auth_sources": authSources,
|
||||
},
|
||||
})
|
||||
return
|
||||
|
||||
@@ -255,3 +255,114 @@ func DeleteTLSCertificate(c *gin.Context) {
|
||||
"message": "",
|
||||
})
|
||||
}
|
||||
|
||||
// ApplyTLSCertificate godoc
|
||||
// @Summary Apply TLS certificate via ACME
|
||||
// @Tags TLSCertificates
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param payload body service.TLSApplyInput true "TLS apply payload"
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Failure 400 {object} map[string]interface{}
|
||||
// @Router /api/tls-certificates/apply [post]
|
||||
func ApplyTLSCertificate(c *gin.Context) {
|
||||
var input service.TLSApplyInput
|
||||
if err := json.NewDecoder(c.Request.Body).Decode(&input); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"success": false,
|
||||
"message": "无效的参数",
|
||||
})
|
||||
return
|
||||
}
|
||||
certificate, err := service.ApplyTLSCertificate(input)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": false,
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "",
|
||||
"data": certificate,
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateAcmeCertificate godoc
|
||||
// @Summary Update ACME TLS certificate
|
||||
// @Tags TLSCertificates
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Certificate ID"
|
||||
// @Param payload body service.TLSApplyInput true "TLS apply payload"
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Failure 400 {object} map[string]interface{}
|
||||
// @Router /api/tls-certificates/{id}/update-acme [post]
|
||||
func UpdateAcmeCertificate(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"success": false,
|
||||
"message": "invalid request",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
var input service.TLSApplyInput
|
||||
if err := json.NewDecoder(c.Request.Body).Decode(&input); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"success": false,
|
||||
"message": "无效的参数",
|
||||
})
|
||||
return
|
||||
}
|
||||
certificate, err := service.UpdateAcmeCertificate(uint(id), input)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": false,
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "",
|
||||
"data": certificate,
|
||||
})
|
||||
}
|
||||
|
||||
// RenewTLSCertificate godoc
|
||||
// @Summary Renew TLS certificate
|
||||
// @Tags TLSCertificates
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Certificate ID"
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Failure 400 {object} map[string]interface{}
|
||||
// @Router /api/tls-certificates/{id}/renew [post]
|
||||
func RenewTLSCertificate(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"success": false,
|
||||
"message": "无效的参数",
|
||||
})
|
||||
return
|
||||
}
|
||||
certificate, err := service.RenewTLSCertificate(uint(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": false,
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "",
|
||||
"data": certificate,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2,9 +2,6 @@ package controller
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/gin-contrib/sessions"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"net/http"
|
||||
"openflare/common"
|
||||
"openflare/model"
|
||||
@@ -12,6 +9,10 @@ import (
|
||||
"openflare/utils/validation"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-contrib/sessions"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type LoginRequest struct {
|
||||
@@ -61,7 +62,7 @@ func Login(c *gin.Context) {
|
||||
}
|
||||
|
||||
// setup session & cookies and then return user info
|
||||
func setupLogin(user *model.User, c *gin.Context) {
|
||||
func setLoginSession(user *model.User, c *gin.Context) (*model.User, error) {
|
||||
session := sessions.Default(c)
|
||||
session.Set("id", user.Id)
|
||||
session.Set("username", user.Username)
|
||||
@@ -69,23 +70,31 @@ func setupLogin(user *model.User, c *gin.Context) {
|
||||
session.Set("status", user.Status)
|
||||
err := session.Save()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "无法保存会话信息,请重试",
|
||||
"success": false,
|
||||
})
|
||||
return
|
||||
return nil, err
|
||||
}
|
||||
cleanUser := model.User{
|
||||
cleanUser := &model.User{
|
||||
Id: user.Id,
|
||||
Username: user.Username,
|
||||
DisplayName: user.DisplayName,
|
||||
Role: user.Role,
|
||||
Status: user.Status,
|
||||
}
|
||||
return cleanUser, nil
|
||||
}
|
||||
|
||||
func setupLogin(user *model.User, c *gin.Context) {
|
||||
cleanUser, err := setLoginSession(user, c)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "无法保存会话信息,请重试",
|
||||
"success": false,
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "",
|
||||
"success": true,
|
||||
"data": cleanUser,
|
||||
"data": *cleanUser,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -107,70 +116,9 @@ func Logout(c *gin.Context) {
|
||||
}
|
||||
|
||||
func Register(c *gin.Context) {
|
||||
if !common.RegisterEnabled {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "管理员关闭了新用户注册",
|
||||
"success": false,
|
||||
})
|
||||
return
|
||||
}
|
||||
if !common.PasswordRegisterEnabled {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "管理员关闭了通过密码进行注册,请使用第三方账户验证的形式进行注册",
|
||||
"success": false,
|
||||
})
|
||||
return
|
||||
}
|
||||
var user model.User
|
||||
err := json.NewDecoder(c.Request.Body).Decode(&user)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": false,
|
||||
"message": "无效的参数",
|
||||
})
|
||||
return
|
||||
}
|
||||
if err := validation.Validate.Struct(&user); err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": false,
|
||||
"message": "输入不合法 " + err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
if common.EmailVerificationEnabled {
|
||||
if user.Email == "" || user.VerificationCode == "" {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": false,
|
||||
"message": "管理员开启了邮箱验证,请输入邮箱地址和验证码",
|
||||
})
|
||||
return
|
||||
}
|
||||
if !security.VerifyCodeWithKey(user.Email, user.VerificationCode, security.EmailVerificationPurpose) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": false,
|
||||
"message": "验证码错误或已过期",
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
cleanUser := model.User{
|
||||
Username: user.Username,
|
||||
Password: user.Password,
|
||||
DisplayName: user.Username,
|
||||
}
|
||||
if common.EmailVerificationEnabled {
|
||||
cleanUser.Email = user.Email
|
||||
}
|
||||
if err := cleanUser.Insert(); err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": false,
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "",
|
||||
"message": "非法请求",
|
||||
"success": false,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
+23
-17
@@ -1,26 +1,29 @@
|
||||
module openflare
|
||||
|
||||
// +heroku goVersion go1.24
|
||||
go 1.24.0
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
github.com/bwmarrin/snowflake v0.3.0
|
||||
github.com/dgraph-io/ristretto/v2 v2.2.0
|
||||
github.com/gin-contrib/cors v1.6.0
|
||||
github.com/gin-contrib/sessions v0.0.5
|
||||
github.com/gin-contrib/static v0.0.1
|
||||
github.com/gin-gonic/gin v1.9.1
|
||||
github.com/glebarez/sqlite v1.11.0
|
||||
github.com/go-playground/validator/v10 v10.19.0
|
||||
github.com/go-acme/lego/v4 v4.35.2
|
||||
github.com/go-playground/validator/v10 v10.23.0
|
||||
github.com/go-redis/redis/v8 v8.11.5
|
||||
github.com/google/uuid v1.3.0
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/oschwald/maxminddb-golang v1.13.1
|
||||
github.com/swaggo/files v1.0.1
|
||||
github.com/swaggo/gin-swagger v1.6.1
|
||||
github.com/swaggo/swag v1.16.4
|
||||
golang.org/x/crypto v0.45.0
|
||||
golang.org/x/net v0.47.0
|
||||
golang.org/x/crypto v0.50.0
|
||||
golang.org/x/net v0.53.0
|
||||
gorm.io/driver/postgres v1.6.0
|
||||
gorm.io/gorm v1.25.10
|
||||
gorm.io/sharding v0.6.2
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -28,16 +31,17 @@ require (
|
||||
github.com/PuerkitoBio/purell v1.1.1 // indirect
|
||||
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect
|
||||
github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff // indirect
|
||||
github.com/bwmarrin/snowflake v0.3.0 // indirect
|
||||
github.com/bytedance/sonic v1.11.2 // indirect
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect
|
||||
github.com/chenzhuoyu/iasm v0.9.1 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.13 // indirect
|
||||
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||
github.com/glebarez/go-sqlite v1.21.2 // indirect
|
||||
github.com/go-jose/go-jose/v4 v4.1.4 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.19.5 // indirect
|
||||
github.com/go-openapi/jsonreference v0.19.6 // indirect
|
||||
github.com/go-openapi/spec v0.20.4 // indirect
|
||||
@@ -56,28 +60,30 @@ require (
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/josharian/intern v1.0.0 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/json-iterator/go v1.1.13-0.20220915233716-71ac16282d12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/longbridgeapp/sqlparser v0.3.1 // indirect
|
||||
github.com/mailru/easyjson v0.7.6 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-isatty v0.0.21 // indirect
|
||||
github.com/miekg/dns v1.1.72 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.1.1 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/robfig/cron/v3 v3.0.1 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.12 // indirect
|
||||
golang.org/x/arch v0.7.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20230817173708-d852ddb80c63 // indirect
|
||||
golang.org/x/sync v0.18.0 // indirect
|
||||
golang.org/x/sys v0.38.0 // indirect
|
||||
golang.org/x/text v0.31.0 // indirect
|
||||
golang.org/x/tools v0.38.0 // indirect
|
||||
google.golang.org/protobuf v1.33.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect
|
||||
golang.org/x/mod v0.35.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/sys v0.43.0 // indirect
|
||||
golang.org/x/text v0.36.0 // indirect
|
||||
golang.org/x/tools v0.44.0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
gorm.io/sharding v0.6.2 // indirect
|
||||
modernc.org/libc v1.22.5 // indirect
|
||||
modernc.org/mathutil v1.5.0 // indirect
|
||||
modernc.org/memory v1.5.0 // indirect
|
||||
|
||||
+62
-40
@@ -12,6 +12,8 @@ github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1
|
||||
github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM=
|
||||
github.com/bytedance/sonic v1.11.2 h1:ywfwo0a/3j9HR8wsYGWsIWl2mvRsI950HyoxiBERw5A=
|
||||
github.com/bytedance/sonic v1.11.2/go.mod h1:iZcSUejdk5aukTND/Eu/ivjQuEL0Cu9/rf50Hi0u/g4=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
|
||||
@@ -23,8 +25,9 @@ github.com/chenzhuoyu/iasm v0.9.1 h1:tUHQJXo3NhBqw6s33wkGn9SP3bvrWLdlVIJ3hQBL7P0
|
||||
github.com/chenzhuoyu/iasm v0.9.1/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgraph-io/ristretto/v2 v2.2.0 h1:bkY3XzJcXoMuELV8F+vS8kzNgicwQFAaGINAEJdWGOM=
|
||||
github.com/dgraph-io/ristretto/v2 v2.2.0/go.mod h1:RZrm63UmcBAaYWC1DotLYBmTvgkrs0+XhBd7Npn7/zI=
|
||||
github.com/dgryski/go-farm v0.0.0-20240924180020-3414d57e47da h1:aIftn67I1fkbMa512G+w+Pxci9hJPB8oMnkcP3iZF38=
|
||||
@@ -33,10 +36,10 @@ github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/r
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
|
||||
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
|
||||
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
|
||||
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
|
||||
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
||||
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||
github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM=
|
||||
github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||
github.com/gin-contrib/cors v1.6.0 h1:0Z7D/bVhE6ja07lI8CTjTonp6SB07o8bNuFyRbsBUQg=
|
||||
github.com/gin-contrib/cors v1.6.0/go.mod h1:cI+h6iOAyxKRtUtC6iF/Si1KSFvGm/gK+kshxlCi8ro=
|
||||
github.com/gin-contrib/gzip v0.0.6 h1:NjcunTcGAj5CO1gn4N8jHOSIeRFHIbn51z6K+xaN4d4=
|
||||
@@ -54,6 +57,10 @@ github.com/glebarez/go-sqlite v1.21.2 h1:3a6LFC4sKahUunAmynQKLZceZCOzUthkRkEAl9g
|
||||
github.com/glebarez/go-sqlite v1.21.2/go.mod h1:sfxdZyhQjTM2Wry3gVYWaW072Ri1WMdWJi0k6+3382k=
|
||||
github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw=
|
||||
github.com/glebarez/sqlite v1.11.0/go.mod h1:h8/o8j5wiAsqSPoWELDUdJXhjAhsVliSn7bWZjOhrgQ=
|
||||
github.com/go-acme/lego/v4 v4.35.2 h1:uVQg+KC/yj9R2g7Q9W5wDqhvQvxV5SMu5eqFVoN5xZU=
|
||||
github.com/go-acme/lego/v4 v4.35.2/go.mod h1:pX2jN5n8OphMGY1IaMjYm5DAEzguBaKRt8AvJAgJXpc=
|
||||
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
|
||||
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
|
||||
github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
|
||||
github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY=
|
||||
github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
|
||||
@@ -74,23 +81,26 @@ github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI=
|
||||
github.com/go-playground/validator/v10 v10.19.0 h1:ol+5Fu+cSq9JD7SoSqe04GMI92cbn0+wvQ3bZ8b/AU4=
|
||||
github.com/go-playground/validator/v10 v10.19.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
|
||||
github.com/go-playground/validator/v10 v10.23.0 h1:/PwmTwZhS0dPkav3cdK9kV1FsAmrL8sThn8IHr/sO+o=
|
||||
github.com/go-playground/validator/v10 v10.23.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
|
||||
github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI=
|
||||
github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo=
|
||||
github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc=
|
||||
github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
|
||||
github.com/go-test/deep v1.0.7 h1:/VSMRlnY/JSyqxQUzQLKVMAskpY/NZKFA5j2P+0pP2M=
|
||||
github.com/go-test/deep v1.0.7/go.mod h1:QV8Hv/iy04NyLBxAdO9njL0iVPN1S4d/A3NVv1V36o8=
|
||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
|
||||
github.com/gomodule/redigo v2.0.0+incompatible h1:K/R+8tc58AaqLkqG2Ol3Qk+DR/TlNuhuh457pBFPtt0=
|
||||
github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
|
||||
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo=
|
||||
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
|
||||
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/context v1.1.1 h1:AWwleXJkX/nhcU9bZSnZoi3h/qGYqQAGhq6zZe/aQW8=
|
||||
github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg=
|
||||
github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ=
|
||||
@@ -113,8 +123,8 @@ github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/
|
||||
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
|
||||
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
|
||||
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/json-iterator/go v1.1.13-0.20220915233716-71ac16282d12 h1:9Nu54bhS/H/Kgo2/7xNSUuC5G28VR8ljfrLKU2G4IjU=
|
||||
github.com/json-iterator/go v1.1.13-0.20220915233716-71ac16282d12/go.mod h1:TBzl5BIHNXfS9+C35ZyJaklL7mLDbgUkcgXzSLa8Tk0=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
|
||||
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
||||
@@ -129,6 +139,8 @@ github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/longbridgeapp/assert v1.1.0 h1:L+/HISOhuGbNAAmJNXgk3+Tm5QmSB70kwdktJXgjL+I=
|
||||
github.com/longbridgeapp/assert v1.1.0/go.mod h1:UOI7O3rzlzlz715lQm0atWs6JbrYGuIJUEeOekutL6o=
|
||||
github.com/longbridgeapp/sqlparser v0.3.1 h1:iWOZWGIFgQrJRgobLXUNJdvqGRpbVXkyKUKUA5CNJBE=
|
||||
github.com/longbridgeapp/sqlparser v0.3.1/go.mod h1:GIHaUq8zvYyHLCLMJJykx1CdM6LHtkUih/QaJXySSx4=
|
||||
github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
|
||||
@@ -136,14 +148,17 @@ github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN
|
||||
github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA=
|
||||
github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
|
||||
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-isatty v0.0.21 h1:xYae+lCNBP7QuW4PUnNG61ffM4hVIfm+zUzDuSzYLGs=
|
||||
github.com/mattn/go-isatty v0.0.21/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
|
||||
github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI=
|
||||
github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=
|
||||
github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||
github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
|
||||
github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
|
||||
@@ -155,14 +170,16 @@ github.com/oschwald/maxminddb-golang v1.13.1 h1:G3wwjdN9JmIK2o/ermkHM+98oX5fS+k5
|
||||
github.com/oschwald/maxminddb-golang v1.13.1/go.mod h1:K4pgV9N/GcK694KSTmVSDTODk4IsCNThNdTmnaBZ/F8=
|
||||
github.com/pelletier/go-toml/v2 v2.1.1 h1:LWAJwfNvjQZCFIDKWYQaM62NcYeYViCmWIwmOStowAI=
|
||||
github.com/pelletier/go-toml/v2 v2.1.1/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8=
|
||||
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
|
||||
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
||||
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
||||
github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
|
||||
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
@@ -174,8 +191,8 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/swaggo/files v1.0.1 h1:J1bVJ4XHZNq0I46UU90611i9/YzdrF7x92oX1ig5IdE=
|
||||
github.com/swaggo/files v1.0.1/go.mod h1:0qXmMNH6sXNf+73t65aKeB+ApmgxdnkQzVTAj2uaMUg=
|
||||
github.com/swaggo/gin-swagger v1.6.1 h1:Ri06G4gc9N4t4k8hekMigJ9zKTFSlqj/9paAQCQs7cY=
|
||||
@@ -194,24 +211,24 @@ golang.org/x/arch v0.7.0 h1:pskyeJh/3AmoQ8CPE95vxHLqp1G1GfGNXTmcl9NEKTc=
|
||||
golang.org/x/arch v0.7.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
|
||||
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
|
||||
golang.org/x/exp v0.0.0-20230817173708-d852ddb80c63 h1:m64FZMko/V45gv0bNmrNYoDEq8U5YUhetc9cBWKS1TQ=
|
||||
golang.org/x/exp v0.0.0-20230817173708-d852ddb80c63/go.mod h1:0v4NqG35kSWCMzLaMeX+IQrlSnVE/bqGSyC2cz/9Le8=
|
||||
golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI=
|
||||
golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q=
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f h1:W3F4c+6OLc6H2lb//N1q4WpJkhzJCK5J6kUi1NTVXfM=
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f/go.mod h1:J1xhfL/vlindoeF/aINzNzt2Bket5bjo9sdOYzOsU80=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA=
|
||||
golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w=
|
||||
golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=
|
||||
golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
|
||||
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
|
||||
golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA=
|
||||
golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I=
|
||||
golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
@@ -220,9 +237,8 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
|
||||
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
|
||||
golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
@@ -232,16 +248,16 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
|
||||
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
|
||||
golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
|
||||
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ=
|
||||
golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs=
|
||||
golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=
|
||||
golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
|
||||
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
@@ -257,10 +273,16 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C
|
||||
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/mysql v1.5.1 h1:WUEH5VF9obL/lTtzjmML/5e6VfFR/788coz2uaVCAZw=
|
||||
gorm.io/driver/mysql v1.5.1/go.mod h1:Jo3Xu7mMhCyj8dlrb3WoCaRd1FhsVh+yMXb1jUInf5o=
|
||||
gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4=
|
||||
gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo=
|
||||
gorm.io/gorm v1.25.10 h1:dQpO+33KalOA+aFYGlK+EfxcI5MbO7EP2yYygwh9h+s=
|
||||
gorm.io/gorm v1.25.10/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
|
||||
gorm.io/hints v1.1.2 h1:b5j0kwk5p4+3BtDtYqqfY+ATSxjj+6ptPgVveuynn9o=
|
||||
gorm.io/hints v1.1.2/go.mod h1:/ARdpUHAtyEMCh5NNi3tI7FsGh+Cj/MIUlvNxCNCFWg=
|
||||
gorm.io/plugin/dbresolver v1.5.1 h1:s9Dj9f7r+1rE3nx/Ywzc85nXptUEaeOO0pt27xdopM8=
|
||||
gorm.io/plugin/dbresolver v1.5.1/go.mod h1:l4Cn87EHLEYuqUncpEeTC2tTJQkjngPSD+lo8hIvcT0=
|
||||
gorm.io/sharding v0.6.2 h1:V9inmbdhN+RfWPEKTvbKKKv7qxLz1CneBDQvuL5P7jg=
|
||||
gorm.io/sharding v0.6.2/go.mod h1:dXaAZv0qyUmLkLAciQ+NH2O1D1A4/ttrrZ/XK4xW9HU=
|
||||
modernc.org/libc v1.22.5 h1:91BNch/e5B0uPbJFgqbxXuOnxBQjlS//icfQEGmvyjE=
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package job
|
||||
|
||||
import (
|
||||
"github.com/robfig/cron/v3"
|
||||
"log/slog"
|
||||
)
|
||||
|
||||
var cronRunner *cron.Cron
|
||||
|
||||
func InitCronJobs() {
|
||||
cronRunner = cron.New()
|
||||
|
||||
// Register SSL renew job
|
||||
_, err := cronRunner.AddJob("0 0 * * *", &SSLRenewJob{})
|
||||
if err != nil {
|
||||
slog.Error("failed to register SSL renew cron job", "error", err)
|
||||
} else {
|
||||
slog.Info("registered SSL renew cron job")
|
||||
}
|
||||
|
||||
cronRunner.Start()
|
||||
}
|
||||
|
||||
func StopCronJobs() {
|
||||
if cronRunner != nil {
|
||||
cronRunner.Stop()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package job
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"openflare/model"
|
||||
"openflare/service"
|
||||
"time"
|
||||
)
|
||||
|
||||
type SSLRenewJob struct {
|
||||
}
|
||||
|
||||
func (j *SSLRenewJob) Run() {
|
||||
slog.Info("The scheduled certificate update task is currently in progress ...")
|
||||
|
||||
certificates, err := model.ListTLSCertificates()
|
||||
if err != nil {
|
||||
slog.Error("failed to list certificates in SSL renew job", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
for _, cert := range certificates {
|
||||
if !cert.AutoRenew || cert.Provider != "acme" || cert.ApplyStatus == "applying" {
|
||||
continue
|
||||
}
|
||||
|
||||
sub := cert.NotAfter.Sub(now)
|
||||
// Expiring in less than 7 days (7 * 24 hours)
|
||||
if sub.Hours() < 168 {
|
||||
slog.Info("Update the SSL certificate for the domain", "domain", cert.PrimaryDomain)
|
||||
|
||||
// Invoke renew process (async go-routine handles Lego inside)
|
||||
_, err := service.RenewTLSCertificate(cert.ID)
|
||||
if err != nil {
|
||||
slog.Error("Failed to update the SSL certificate", "domain", cert.PrimaryDomain, "error", err)
|
||||
continue
|
||||
}
|
||||
slog.Info("Triggered the SSL certificate renew for domain", "domain", cert.PrimaryDomain)
|
||||
}
|
||||
}
|
||||
slog.Info("The scheduled certificate update task has completed")
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"log/slog"
|
||||
"openflare/common"
|
||||
_ "openflare/docs"
|
||||
"openflare/job"
|
||||
"openflare/middleware"
|
||||
"openflare/model"
|
||||
"openflare/router"
|
||||
@@ -73,6 +74,9 @@ func main() {
|
||||
defer cancelBackgroundTasks()
|
||||
service.StartDatabaseAutoCleanupScheduler(backgroundCtx)
|
||||
|
||||
job.InitCronJobs()
|
||||
defer job.StopCronJobs()
|
||||
|
||||
// Initialize HTTP server
|
||||
server := gin.Default()
|
||||
//server.Use(gzip.Gzip(gzip.DefaultCompression))
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type AcmeAccount struct {
|
||||
ID uint `json:"id" gorm:"primaryKey"`
|
||||
Email string `json:"email" gorm:"size:255"`
|
||||
URL string `json:"url" gorm:"size:255"`
|
||||
PrivateKey string `json:"-" gorm:"type:text;not null"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func GetAcmeAccountByID(id uint) (*AcmeAccount, error) {
|
||||
account := &AcmeAccount{}
|
||||
err := DB.First(account, id).Error
|
||||
return account, err
|
||||
}
|
||||
|
||||
func GetDefaultAcmeAccount() (*AcmeAccount, error) {
|
||||
account := &AcmeAccount{}
|
||||
err := DB.Order("id asc").First(account).Error
|
||||
if err != nil {
|
||||
// Auto-create a default account placeholder if none exists
|
||||
account.Email = "admin@openflare.dev"
|
||||
err = DB.Create(account).Error
|
||||
}
|
||||
return account, err
|
||||
}
|
||||
|
||||
func (account *AcmeAccount) Insert() error {
|
||||
return DB.Create(account).Error
|
||||
}
|
||||
|
||||
func (account *AcmeAccount) Update() error {
|
||||
return DB.Save(account).Error
|
||||
}
|
||||
|
||||
func (account *AcmeAccount) Delete() error {
|
||||
return DB.Delete(account).Error
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
AuthSourceTypeGitHub = "github"
|
||||
AuthSourceTypeOIDC = "oidc"
|
||||
)
|
||||
|
||||
var authSourceNamePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_-]{0,79}$`)
|
||||
|
||||
type AuthSource struct {
|
||||
ID uint `json:"id"`
|
||||
Name string `json:"name" gorm:"uniqueIndex;size:80;not null"`
|
||||
Type string `json:"type" gorm:"index;size:20;not null"`
|
||||
DisplayName string `json:"display_name" gorm:"size:100"`
|
||||
IsActive bool `json:"is_active" gorm:"index;not null;default:false"`
|
||||
ClientID string `json:"client_id" gorm:"column:client_id;size:255"`
|
||||
ClientSecret string `json:"-" gorm:"column:client_secret;size:1024"`
|
||||
OpenIDDiscoveryURL string `json:"openid_discovery_url" gorm:"column:openid_discovery_url;size:1024"`
|
||||
Scopes string `json:"scopes" gorm:"size:255"`
|
||||
IconURL string `json:"icon_url" gorm:"size:1024"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ClientSecretConfigured bool `json:"client_secret_configured" gorm:"-"`
|
||||
}
|
||||
|
||||
type ExternalAccount struct {
|
||||
ID uint `json:"id"`
|
||||
AuthSourceID uint `json:"auth_source_id" gorm:"uniqueIndex:idx_external_account_source_external;index;not null"`
|
||||
UserID int `json:"user_id" gorm:"index;not null"`
|
||||
ExternalID string `json:"external_id" gorm:"uniqueIndex:idx_external_account_source_external;size:255;not null"`
|
||||
ExternalUsername string `json:"external_username" gorm:"size:255"`
|
||||
Email string `json:"email" gorm:"size:255"`
|
||||
AuthSource AuthSource `json:"-" gorm:"constraint:OnDelete:CASCADE"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type ExternalAccountView struct {
|
||||
ID uint `json:"id"`
|
||||
AuthSourceID uint `json:"auth_source_id"`
|
||||
AuthSourceName string `json:"auth_source_name"`
|
||||
AuthSourceType string `json:"auth_source_type"`
|
||||
AuthSourceLabel string `json:"auth_source_label"`
|
||||
ExternalUsername string `json:"external_username"`
|
||||
Email string `json:"email"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
func (source *AuthSource) Normalize() {
|
||||
source.Name = strings.TrimSpace(source.Name)
|
||||
source.Type = strings.TrimSpace(strings.ToLower(source.Type))
|
||||
source.DisplayName = strings.TrimSpace(source.DisplayName)
|
||||
source.ClientID = strings.TrimSpace(source.ClientID)
|
||||
source.ClientSecret = strings.TrimSpace(source.ClientSecret)
|
||||
source.OpenIDDiscoveryURL = strings.TrimSpace(source.OpenIDDiscoveryURL)
|
||||
source.Scopes = strings.TrimSpace(source.Scopes)
|
||||
source.IconURL = strings.TrimSpace(source.IconURL)
|
||||
if source.DisplayName == "" {
|
||||
source.DisplayName = source.Name
|
||||
}
|
||||
if source.Type == AuthSourceTypeOIDC && source.Scopes == "" {
|
||||
source.Scopes = "openid profile email"
|
||||
}
|
||||
if source.Type == AuthSourceTypeGitHub && source.Scopes == "" {
|
||||
source.Scopes = "user:email"
|
||||
}
|
||||
}
|
||||
|
||||
func (source *AuthSource) Validate() error {
|
||||
source.Normalize()
|
||||
if source.Name == "" {
|
||||
return errors.New("认证源名称不能为空")
|
||||
}
|
||||
if !authSourceNamePattern.MatchString(source.Name) {
|
||||
return errors.New("认证源名称只能包含字母、数字、短横线或下划线,且必须以字母或数字开头")
|
||||
}
|
||||
switch source.Type {
|
||||
case AuthSourceTypeGitHub:
|
||||
case AuthSourceTypeOIDC:
|
||||
if source.OpenIDDiscoveryURL == "" {
|
||||
return errors.New("OIDC 认证源必须配置 Discovery URL")
|
||||
}
|
||||
default:
|
||||
return errors.New("认证源类型仅支持 github 或 oidc")
|
||||
}
|
||||
if source.IsActive {
|
||||
if source.ClientID == "" || source.ClientSecret == "" {
|
||||
return errors.New("启用认证源前必须配置 Client ID 和 Client Secret")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (source *AuthSource) Sanitize() {
|
||||
source.ClientSecretConfigured = source.ClientSecret != ""
|
||||
source.ClientSecret = ""
|
||||
}
|
||||
|
||||
func GetAuthSources() ([]AuthSource, error) {
|
||||
var sources []AuthSource
|
||||
err := DB.Order("id asc").Find(&sources).Error
|
||||
for index := range sources {
|
||||
sources[index].Sanitize()
|
||||
}
|
||||
return sources, err
|
||||
}
|
||||
|
||||
func GetActiveAuthSources() ([]AuthSource, error) {
|
||||
var sources []AuthSource
|
||||
err := DB.Where("is_active = ?", true).Order("id asc").Find(&sources).Error
|
||||
for index := range sources {
|
||||
sources[index].Sanitize()
|
||||
}
|
||||
return sources, err
|
||||
}
|
||||
|
||||
func GetAuthSourceByID(id uint) (*AuthSource, error) {
|
||||
if id == 0 {
|
||||
return nil, errors.New("认证源 ID 不能为空")
|
||||
}
|
||||
var source AuthSource
|
||||
if err := DB.First(&source, "id = ?", id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
source.ClientSecretConfigured = source.ClientSecret != ""
|
||||
return &source, nil
|
||||
}
|
||||
|
||||
func GetAuthSourceByName(name string) (*AuthSource, error) {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
return nil, errors.New("认证源名称不能为空")
|
||||
}
|
||||
var source AuthSource
|
||||
if err := DB.First(&source, "name = ?", name).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
source.ClientSecretConfigured = source.ClientSecret != ""
|
||||
return &source, nil
|
||||
}
|
||||
|
||||
func CreateAuthSource(source *AuthSource) error {
|
||||
if err := source.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return DB.Create(source).Error
|
||||
}
|
||||
|
||||
func UpdateAuthSource(source *AuthSource, keepSecret bool) error {
|
||||
if source.ID == 0 {
|
||||
return errors.New("认证源 ID 不能为空")
|
||||
}
|
||||
var current AuthSource
|
||||
if err := DB.First(¤t, "id = ?", source.ID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if keepSecret {
|
||||
source.ClientSecret = current.ClientSecret
|
||||
}
|
||||
if err := source.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return DB.Model(¤t).Updates(map[string]any{
|
||||
"name": source.Name,
|
||||
"type": source.Type,
|
||||
"display_name": source.DisplayName,
|
||||
"is_active": source.IsActive,
|
||||
"client_id": source.ClientID,
|
||||
"client_secret": source.ClientSecret,
|
||||
"openid_discovery_url": source.OpenIDDiscoveryURL,
|
||||
"scopes": source.Scopes,
|
||||
"icon_url": source.IconURL,
|
||||
}).Error
|
||||
}
|
||||
|
||||
func ToggleAuthSource(id uint, isActive bool) error {
|
||||
source, err := GetAuthSourceByID(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
source.IsActive = isActive
|
||||
if err := source.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return DB.Model(&AuthSource{}).Where("id = ?", id).Update("is_active", isActive).Error
|
||||
}
|
||||
|
||||
func DeleteAuthSource(id uint) error {
|
||||
if id == 0 {
|
||||
return errors.New("认证源 ID 不能为空")
|
||||
}
|
||||
return DB.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Where("auth_source_id = ?", id).Delete(&ExternalAccount{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Delete(&AuthSource{}, "id = ?", id).Error
|
||||
})
|
||||
}
|
||||
|
||||
func FindExternalAccount(sourceID uint, externalID string) (*ExternalAccount, error) {
|
||||
var account ExternalAccount
|
||||
err := DB.Where("auth_source_id = ? AND external_id = ?", sourceID, externalID).First(&account).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &account, nil
|
||||
}
|
||||
|
||||
func LinkExternalAccount(account *ExternalAccount) error {
|
||||
if account.AuthSourceID == 0 || account.UserID == 0 || strings.TrimSpace(account.ExternalID) == "" {
|
||||
return errors.New("外部账号绑定信息不完整")
|
||||
}
|
||||
account.ExternalID = strings.TrimSpace(account.ExternalID)
|
||||
account.ExternalUsername = strings.TrimSpace(account.ExternalUsername)
|
||||
account.Email = strings.TrimSpace(account.Email)
|
||||
return DB.Where(ExternalAccount{
|
||||
AuthSourceID: account.AuthSourceID,
|
||||
ExternalID: account.ExternalID,
|
||||
}).FirstOrCreate(account).Error
|
||||
}
|
||||
|
||||
func ListExternalAccountsByUserID(userID int) ([]ExternalAccountView, error) {
|
||||
if userID <= 0 {
|
||||
return nil, errors.New("用户 ID 不能为空")
|
||||
}
|
||||
var accounts []ExternalAccount
|
||||
if err := DB.Preload("AuthSource").Where("user_id = ?", userID).Order("id asc").Find(&accounts).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
views := make([]ExternalAccountView, 0, len(accounts))
|
||||
for _, account := range accounts {
|
||||
label := account.AuthSource.DisplayName
|
||||
if label == "" {
|
||||
label = account.AuthSource.Name
|
||||
}
|
||||
views = append(views, ExternalAccountView{
|
||||
ID: account.ID,
|
||||
AuthSourceID: account.AuthSourceID,
|
||||
AuthSourceName: account.AuthSource.Name,
|
||||
AuthSourceType: account.AuthSource.Type,
|
||||
AuthSourceLabel: label,
|
||||
ExternalUsername: account.ExternalUsername,
|
||||
Email: account.Email,
|
||||
CreatedAt: account.CreatedAt,
|
||||
})
|
||||
}
|
||||
return views, nil
|
||||
}
|
||||
|
||||
func DeleteExternalAccountForUser(id uint, userID int) error {
|
||||
if id == 0 {
|
||||
return errors.New("绑定记录 ID 不能为空")
|
||||
}
|
||||
if userID <= 0 {
|
||||
return errors.New("用户 ID 不能为空")
|
||||
}
|
||||
result := DB.Where("id = ? AND user_id = ?", id, userID).Delete(&ExternalAccount{})
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return errors.New("绑定记录不存在")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import "time"
|
||||
|
||||
const (
|
||||
legacyDatabaseSchemaVersion = 1
|
||||
currentDatabaseSchemaVersion = 8
|
||||
currentDatabaseSchemaVersion = 11
|
||||
databaseSchemaVersionRowID = 1
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type DnsAccount struct {
|
||||
ID uint `json:"id" gorm:"primaryKey"`
|
||||
Name string `json:"name" gorm:"size:255;not null"`
|
||||
Type string `json:"type" gorm:"size:64;not null"`
|
||||
Authorization string `json:"-" gorm:"type:text;not null"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func ListDnsAccounts() (accounts []*DnsAccount, err error) {
|
||||
err = DB.Order("id desc").Find(&accounts).Error
|
||||
return accounts, err
|
||||
}
|
||||
|
||||
func GetDnsAccountByID(id uint) (*DnsAccount, error) {
|
||||
account := &DnsAccount{}
|
||||
err := DB.First(account, id).Error
|
||||
return account, err
|
||||
}
|
||||
|
||||
func (account *DnsAccount) Insert() error {
|
||||
return DB.Create(account).Error
|
||||
}
|
||||
|
||||
func (account *DnsAccount) Update() error {
|
||||
return DB.Save(account).Error
|
||||
}
|
||||
|
||||
func (account *DnsAccount) Delete() error {
|
||||
return DB.Delete(account).Error
|
||||
}
|
||||
@@ -26,6 +26,8 @@ func registeredModels() []any {
|
||||
return []any{
|
||||
&File{},
|
||||
&User{},
|
||||
&AuthSource{},
|
||||
&ExternalAccount{},
|
||||
&Option{},
|
||||
&Origin{},
|
||||
&ProxyRoute{},
|
||||
@@ -39,6 +41,8 @@ func registeredModels() []any {
|
||||
&NodeHealthEvent{},
|
||||
&TLSCertificate{},
|
||||
&ManagedDomain{},
|
||||
&AcmeAccount{},
|
||||
&DnsAccount{},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -863,7 +863,7 @@ func TestRunDatabaseSchemaMigrationDoesNotAdvanceVersionWhenValidationFails(t *t
|
||||
|
||||
err := runDatabaseSchemaMigration(db, "sqlite", databaseSchemaMigration{
|
||||
fromVersion: legacyDatabaseSchemaVersion,
|
||||
toVersion: currentDatabaseSchemaVersion,
|
||||
toVersion: 11,
|
||||
migrate: func(tx *gorm.DB, backend string) error {
|
||||
return autoMigrateSchemaMetadata(tx)
|
||||
},
|
||||
|
||||
@@ -1196,6 +1196,179 @@ 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 ensureDefaultGitHubAuthSource(db *gorm.DB) error {
|
||||
if db == nil || !db.Migrator().HasTable(&AuthSource{}) || !db.Migrator().HasTable(&ExternalAccount{}) {
|
||||
return nil
|
||||
}
|
||||
|
||||
var githubUserCount int64
|
||||
if db.Migrator().HasColumn(&User{}, "github_id") {
|
||||
if err := db.Model(&User{}).Where("github_id <> ''").Count(&githubUserCount).Error; err != nil {
|
||||
return fmt.Errorf("count legacy github users failed: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
optionMap := map[string]string{}
|
||||
if db.Migrator().HasTable(&Option{}) {
|
||||
var options []Option
|
||||
if err := db.Find(&options).Error; err != nil {
|
||||
return fmt.Errorf("query options for github auth source migration failed: %w", err)
|
||||
}
|
||||
for _, option := range options {
|
||||
optionMap[option.Key] = option.Value
|
||||
}
|
||||
}
|
||||
|
||||
clientID := strings.TrimSpace(optionMap["GitHubClientId"])
|
||||
clientSecret := strings.TrimSpace(optionMap["GitHubClientSecret"])
|
||||
enabled := optionMap["GitHubOAuthEnabled"] == "true" && clientID != "" && clientSecret != ""
|
||||
if githubUserCount == 0 && clientID == "" && clientSecret == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
source := AuthSource{}
|
||||
err := db.Where("type = ? AND name = ?", AuthSourceTypeGitHub, "GitHub").First(&source).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
source = AuthSource{
|
||||
Name: "GitHub",
|
||||
Type: AuthSourceTypeGitHub,
|
||||
DisplayName: "GitHub",
|
||||
IsActive: enabled,
|
||||
ClientID: clientID,
|
||||
ClientSecret: clientSecret,
|
||||
Scopes: "user:email",
|
||||
}
|
||||
if err := db.Create(&source).Error; err != nil {
|
||||
return fmt.Errorf("create default github auth source failed: %w", err)
|
||||
}
|
||||
} else if err != nil {
|
||||
return fmt.Errorf("query default github auth source failed: %w", err)
|
||||
} else {
|
||||
updates := map[string]any{}
|
||||
if source.ClientID == "" && clientID != "" {
|
||||
updates["client_id"] = clientID
|
||||
}
|
||||
if source.ClientSecret == "" && clientSecret != "" {
|
||||
updates["client_secret"] = clientSecret
|
||||
}
|
||||
if source.Scopes == "" {
|
||||
updates["scopes"] = "user:email"
|
||||
}
|
||||
if enabled && !source.IsActive {
|
||||
updates["is_active"] = true
|
||||
}
|
||||
if len(updates) > 0 {
|
||||
if err := db.Model(&source).Updates(updates).Error; err != nil {
|
||||
return fmt.Errorf("update default github auth source failed: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if githubUserCount == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var users []User
|
||||
if err := db.Select("id", "github_id", "username", "email").Where("github_id <> ''").Find(&users).Error; err != nil {
|
||||
return fmt.Errorf("query legacy github users failed: %w", err)
|
||||
}
|
||||
for _, user := range users {
|
||||
account := ExternalAccount{
|
||||
AuthSourceID: source.ID,
|
||||
UserID: user.Id,
|
||||
ExternalID: user.GitHubId,
|
||||
ExternalUsername: user.GitHubId,
|
||||
Email: user.Email,
|
||||
}
|
||||
if err := db.Where(ExternalAccount{
|
||||
AuthSourceID: source.ID,
|
||||
ExternalID: user.GitHubId,
|
||||
}).FirstOrCreate(&account).Error; err != nil {
|
||||
return fmt.Errorf("migrate github external account for user %d failed: %w", user.Id, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// migrateV10 adds configurable auth sources and external account bindings.
|
||||
func migrateV10(db *gorm.DB, backend string) error {
|
||||
if err := applyCurrentSchema(db, backend); err != nil {
|
||||
return err
|
||||
}
|
||||
return ensureDefaultGitHubAuthSource(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 validateDatabaseSchemaV10(db *gorm.DB, backend string) error {
|
||||
if err := validateDatabaseSchemaV9(db, backend); err != nil {
|
||||
return err
|
||||
}
|
||||
if !db.Migrator().HasTable(&AuthSource{}) {
|
||||
return fmt.Errorf("table auth_sources is missing")
|
||||
}
|
||||
if !db.Migrator().HasTable(&ExternalAccount{}) {
|
||||
return fmt.Errorf("table external_accounts is missing")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// migrateV11 adds acme and dns accounts and extends tls_certificates.
|
||||
func migrateV11(db *gorm.DB, backend string) error {
|
||||
if err := applyCurrentSchema(db, backend); err != nil {
|
||||
return err
|
||||
}
|
||||
// Default values will be applied by gorm for new columns automatically during AutoMigrate.
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateDatabaseSchemaV11(db *gorm.DB, backend string) error {
|
||||
if err := validateDatabaseSchemaV10(db, backend); err != nil {
|
||||
return err
|
||||
}
|
||||
if !db.Migrator().HasTable(&AcmeAccount{}) {
|
||||
return fmt.Errorf("table acme_accounts is missing")
|
||||
}
|
||||
if !db.Migrator().HasTable(&DnsAccount{}) {
|
||||
return fmt.Errorf("table dns_accounts is missing")
|
||||
}
|
||||
if !db.Migrator().HasColumn(&TLSCertificate{}, "provider") {
|
||||
return fmt.Errorf("column tls_certificates.provider is missing")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func databaseSchemaMigrations() []databaseSchemaMigration {
|
||||
return []databaseSchemaMigration{
|
||||
{fromVersion: 1, toVersion: 2, migrate: migrateV2, validate: validateDatabaseSchemaV2},
|
||||
@@ -1205,6 +1378,9 @@ 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},
|
||||
{fromVersion: 9, toVersion: 10, migrate: migrateV10, validate: validateDatabaseSchemaV10},
|
||||
{fromVersion: 10, toVersion: 11, migrate: migrateV11, validate: validateDatabaseSchemaV11},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1287,7 +1463,10 @@ 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 := ensureDefaultGitHubAuthSource(db); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateDatabaseSchemaV11(db, backend); err != nil {
|
||||
return err
|
||||
}
|
||||
return saveDatabaseSchemaVersion(db, currentDatabaseSchemaVersion)
|
||||
|
||||
@@ -35,7 +35,6 @@ func InitOptionMap() {
|
||||
common.OptionMap["GitHubOAuthEnabled"] = strconv.FormatBool(common.GitHubOAuthEnabled)
|
||||
common.OptionMap["WeChatAuthEnabled"] = strconv.FormatBool(common.WeChatAuthEnabled)
|
||||
common.OptionMap["TurnstileCheckEnabled"] = strconv.FormatBool(common.TurnstileCheckEnabled)
|
||||
common.OptionMap["RegisterEnabled"] = strconv.FormatBool(common.RegisterEnabled)
|
||||
common.OptionMap["SMTPServer"] = ""
|
||||
common.OptionMap["SMTPPort"] = strconv.Itoa(common.SMTPPort)
|
||||
common.OptionMap["SMTPAccount"] = ""
|
||||
@@ -187,8 +186,6 @@ func updateOptionMap(key string, value string) {
|
||||
common.WeChatAuthEnabled = boolValue
|
||||
case "TurnstileCheckEnabled":
|
||||
common.TurnstileCheckEnabled = boolValue
|
||||
case "RegisterEnabled":
|
||||
common.RegisterEnabled = boolValue
|
||||
}
|
||||
}
|
||||
switch key {
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"openflare/common"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestInitOptionMapDefaultsRegisterDisabled(t *testing.T) {
|
||||
previousRegisterEnabled := common.RegisterEnabled
|
||||
previousOptionMap := common.OptionMap
|
||||
previousDB := DB
|
||||
t.Cleanup(func() {
|
||||
common.RegisterEnabled = previousRegisterEnabled
|
||||
common.OptionMap = previousOptionMap
|
||||
DB = previousDB
|
||||
})
|
||||
|
||||
DB = openTestSQLiteDB(t, "options-defaults.db")
|
||||
common.RegisterEnabled = false
|
||||
common.OptionMap = nil
|
||||
|
||||
InitOptionMap()
|
||||
|
||||
if got := common.OptionMap["RegisterEnabled"]; got != "false" {
|
||||
t.Fatalf("expected RegisterEnabled default to be false, got %q", got)
|
||||
}
|
||||
if common.RegisterEnabled {
|
||||
t.Fatal("expected RegisterEnabled to remain false after InitOptionMap")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -3,15 +3,28 @@ package model
|
||||
import "time"
|
||||
|
||||
type TLSCertificate struct {
|
||||
ID uint `json:"id" gorm:"primaryKey"`
|
||||
Name string `json:"name" gorm:"uniqueIndex;size:255;not null"`
|
||||
CertPEM string `json:"-" gorm:"type:text;not null"`
|
||||
KeyPEM string `json:"-" gorm:"type:text;not null"`
|
||||
NotBefore time.Time `json:"not_before"`
|
||||
NotAfter time.Time `json:"not_after"`
|
||||
Remark string `json:"remark" gorm:"size:255"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ID uint `json:"id" gorm:"primaryKey"`
|
||||
Name string `json:"name" gorm:"uniqueIndex;size:255;not null"`
|
||||
CertPEM string `json:"-" gorm:"type:text;not null"`
|
||||
KeyPEM string `json:"-" gorm:"type:text;not null"`
|
||||
NotBefore time.Time `json:"not_before"`
|
||||
NotAfter time.Time `json:"not_after"`
|
||||
Remark string `json:"remark" gorm:"size:255"`
|
||||
Provider string `json:"provider" gorm:"size:64;default:'upload'"` // upload, acme
|
||||
AcmeAccountID uint `json:"acme_account_id"`
|
||||
DnsAccountID uint `json:"dns_account_id"`
|
||||
KeyAlgorithm string `json:"key_algorithm" gorm:"size:32"`
|
||||
AutoRenew bool `json:"auto_renew"`
|
||||
PrimaryDomain string `json:"primary_domain" gorm:"size:255"`
|
||||
OtherDomains string `json:"other_domains" gorm:"type:text"`
|
||||
DisableCNAME bool `json:"disable_cname"`
|
||||
SkipDNS bool `json:"skip_dns"`
|
||||
DNS1 string `json:"dns1" gorm:"size:128"`
|
||||
DNS2 string `json:"dns2" gorm:"size:128"`
|
||||
ApplyStatus string `json:"apply_status" gorm:"size:64;default:'ready'"`
|
||||
ApplyMessage string `json:"apply_message" gorm:"type:text"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func ListTLSCertificates() (certificates []*TLSCertificate, err error) {
|
||||
|
||||
@@ -21,6 +21,15 @@ func SetApiRouter(router *gin.Engine) {
|
||||
apiRouter.GET("/oauth/wechat", middleware.CriticalRateLimit(), controller.WeChatAuth)
|
||||
apiRouter.GET("/oauth/wechat/bind", middleware.CriticalRateLimit(), middleware.UserAuth(), controller.WeChatBind)
|
||||
apiRouter.GET("/oauth/email/bind", middleware.CriticalRateLimit(), middleware.UserAuth(), controller.EmailBind)
|
||||
apiRouter.GET("/oauth/:source/authorize", middleware.CriticalRateLimit(), controller.OAuthAuthorize)
|
||||
apiRouter.GET("/oauth/:source/callback", middleware.CriticalRateLimit(), controller.OAuthCallback)
|
||||
apiRouter.POST("/oauth/link-existing", middleware.CriticalRateLimit(), controller.LinkExistingOAuthAccount)
|
||||
externalAccountRoute := apiRouter.Group("/oauth/external-accounts")
|
||||
externalAccountRoute.Use(middleware.UserAuth(), middleware.NoTokenAuth())
|
||||
{
|
||||
externalAccountRoute.GET("/", controller.ListExternalAccounts)
|
||||
externalAccountRoute.POST("/:id/delete", controller.DeleteExternalAccount)
|
||||
}
|
||||
|
||||
userRoute := apiRouter.Group("/user")
|
||||
{
|
||||
@@ -58,6 +67,15 @@ func SetApiRouter(router *gin.Engine) {
|
||||
optionRoute.POST("/geoip/lookup", controller.LookupGeoIP)
|
||||
optionRoute.POST("/database/cleanup", controller.CleanupDatabaseObservability)
|
||||
}
|
||||
authSourceRoute := apiRouter.Group("/auth-sources")
|
||||
authSourceRoute.Use(middleware.RootAuth(), middleware.NoTokenAuth())
|
||||
{
|
||||
authSourceRoute.GET("/", controller.ListAuthSources)
|
||||
authSourceRoute.POST("/", controller.CreateAuthSource)
|
||||
authSourceRoute.POST("/:id/update", controller.UpdateAuthSource)
|
||||
authSourceRoute.POST("/:id/delete", controller.DeleteAuthSource)
|
||||
authSourceRoute.POST("/:id/toggle", controller.ToggleAuthSource)
|
||||
}
|
||||
updateRoute := apiRouter.Group("/update")
|
||||
updateRoute.Use(middleware.RootAuth(), middleware.NoTokenAuth())
|
||||
{
|
||||
@@ -67,14 +85,6 @@ func SetApiRouter(router *gin.Engine) {
|
||||
updateRoute.POST("/manual-upgrade", controller.ConfirmManualServerUpgrade)
|
||||
updateRoute.POST("/upgrade", controller.UpgradeServer)
|
||||
}
|
||||
fileRoute := apiRouter.Group("/file")
|
||||
fileRoute.Use(middleware.AdminAuth())
|
||||
{
|
||||
fileRoute.GET("/", controller.GetAllFiles)
|
||||
fileRoute.GET("/search", controller.SearchFiles)
|
||||
fileRoute.POST("/", middleware.UploadRateLimit(), controller.UploadFile)
|
||||
fileRoute.POST("/:id/delete", controller.DeleteFile)
|
||||
}
|
||||
proxyRoute := apiRouter.Group("/proxy-routes")
|
||||
proxyRoute.Use(middleware.AdminAuth())
|
||||
{
|
||||
@@ -110,8 +120,24 @@ func SetApiRouter(router *gin.Engine) {
|
||||
tlsCertificateRoute.GET("/:id/content", controller.GetTLSCertificateContent)
|
||||
tlsCertificateRoute.POST("/", controller.CreateTLSCertificate)
|
||||
tlsCertificateRoute.POST("/:id/update", controller.UpdateTLSCertificate)
|
||||
tlsCertificateRoute.POST("/:id/update-acme", controller.UpdateAcmeCertificate)
|
||||
tlsCertificateRoute.POST("/import-file", controller.ImportTLSCertificateFile)
|
||||
tlsCertificateRoute.POST("/:id/delete", controller.DeleteTLSCertificate)
|
||||
tlsCertificateRoute.POST("/apply", controller.ApplyTLSCertificate)
|
||||
tlsCertificateRoute.POST("/:id/renew", controller.RenewTLSCertificate)
|
||||
}
|
||||
acmeAccountRoute := apiRouter.Group("/acme-accounts")
|
||||
acmeAccountRoute.Use(middleware.AdminAuth())
|
||||
{
|
||||
acmeAccountRoute.GET("/default", controller.GetDefaultAcmeAccount)
|
||||
}
|
||||
dnsAccountRoute := apiRouter.Group("/dns-accounts")
|
||||
dnsAccountRoute.Use(middleware.AdminAuth())
|
||||
{
|
||||
dnsAccountRoute.GET("/", controller.GetDnsAccounts)
|
||||
dnsAccountRoute.POST("/", controller.CreateDnsAccount)
|
||||
dnsAccountRoute.POST("/:id/update", controller.UpdateDnsAccount)
|
||||
dnsAccountRoute.POST("/:id/delete", controller.DeleteDnsAccount)
|
||||
}
|
||||
configVersionRoute := apiRouter.Group("/config-versions")
|
||||
configVersionRoute.Use(middleware.AdminAuth())
|
||||
|
||||
@@ -382,8 +382,8 @@ func TestPhase1HTTPSAndCertificateImportLifecycle(t *testing.T) {
|
||||
t.Fatalf("expected active config to expose main_config, got %#v", activeConfig["main_config"])
|
||||
}
|
||||
supportFiles, ok := activeConfig["support_files"].([]any)
|
||||
if !ok || len(supportFiles) != 2 {
|
||||
t.Fatalf("expected active config to expose 2 support files, got %#v", activeConfig["support_files"])
|
||||
if !ok || len(supportFiles) != 3 {
|
||||
t.Fatalf("expected active config to expose 3 support files, got %#v", activeConfig["support_files"])
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user