vite-press init

This commit is contained in:
ryan
2026-05-09 16:26:45 +08:00
parent 8730f99fef
commit 797a15ae70
42 changed files with 4760 additions and 0 deletions
+79
View File
@@ -0,0 +1,79 @@
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: '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' }
]
}
]
}
+33
View File
@@ -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.
+31
View File
@@ -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`.
+21
View File
@@ -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.
+33
View File
@@ -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.
+60
View File
@@ -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
```
+32
View File
@@ -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.
+11
View File
@@ -0,0 +1,11 @@
# 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. [Run Server](./server.md): learn source startup, frontend build, and Swagger access.
3. [Connect Agent](./agent.md): use `agent_token` or `discovery_token` to bring a node online.
4. [Publish First Site](./first-site.md): create a site configuration, publish it, and verify node application.
5. [Upgrade and Maintenance](./upgrade.md): understand upgrade, uninstall, validation, and maintenance entry points.
+77
View File
@@ -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.
+52
View File
@@ -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.24+` |
| 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
```
+47
View File
@@ -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
```
+32
View File
@@ -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.
---
+44
View File
@@ -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
```
+64
View File
@@ -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
```
+74
View File
@@ -0,0 +1,74 @@
# 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` |
| `RegisterEnabled` | Allow new user registration | `false` |
| `PasswordRegisterEnabled` | Allow password registration | `true` |
| `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.
+10
View File
@@ -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` |
+32
View File
@@ -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 |