feat: add web admin panel for node management

Add Flask panel with login, add/delete nodes, and share link copy.
Generate sing-box config from SQLite; add uninstall script and clean install flow.
Panel served at https://DOMAIN:8444 via nginx.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
dekun
2026-06-16 09:10:19 +08:00
parent e8631a0e10
commit bccf6cfdce
21 changed files with 1069 additions and 305 deletions
+167
View File
@@ -0,0 +1,167 @@
#!/usr/bin/env python3
"""jiedian 管理面板:登录、添加/删除节点、复制分享链接。"""
from __future__ import annotations
import os
import secrets
import subprocess
from functools import wraps
from pathlib import Path
from flask import (
Flask,
jsonify,
redirect,
render_template,
request,
session,
url_for,
)
from db import add_node, delete_node, list_nodes, node_count, verify_admin
from links import build_links, load_env
ROOT = Path(os.environ.get("JIEDIAN_ROOT", Path(__file__).resolve().parents[1]))
SECRET_FILE = ROOT / "data" / ".panel_secret"
RENDER_SCRIPT = ROOT / "scripts" / "render-server.py"
def _secret_key() -> str:
if SECRET_FILE.exists():
return SECRET_FILE.read_text(encoding="utf-8").strip()
SECRET_FILE.parent.mkdir(parents=True, exist_ok=True)
key = secrets.token_hex(32)
SECRET_FILE.write_text(key, encoding="utf-8")
SECRET_FILE.chmod(0o600)
return key
app = Flask(__name__)
app.secret_key = _secret_key()
app.config.update(
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE="Lax",
PERMANENT_SESSION_LIFETIME=86400 * 7,
)
def login_required(view):
@wraps(view)
def wrapped(*args, **kwargs):
if not session.get("user"):
if request.path.startswith("/api/"):
return jsonify({"error": "未登录"}), 401
return redirect(url_for("login"))
return view(*args, **kwargs)
return wrapped
def apply_singbox() -> tuple[bool, str]:
env = os.environ.copy()
env["JIEDIAN_ROOT"] = str(ROOT)
proc = subprocess.run(
["python3", str(RENDER_SCRIPT)],
capture_output=True,
text=True,
env=env,
)
if proc.returncode != 0:
return False, proc.stderr or proc.stdout or "配置生成失败"
restart = subprocess.run(["systemctl", "restart", "sing-box"], capture_output=True, text=True)
if restart.returncode != 0:
return False, restart.stderr or restart.stdout or "sing-box 重启失败"
return True, "ok"
@app.route("/login", methods=["GET", "POST"])
def login():
if session.get("user"):
return redirect(url_for("dashboard"))
error = None
if request.method == "POST":
username = request.form.get("username", "").strip()
password = request.form.get("password", "")
if verify_admin(username, password):
session.permanent = True
session["user"] = username
return redirect(url_for("dashboard"))
error = "用户名或密码错误"
return render_template("login.html", error=error)
@app.route("/logout")
def logout():
session.clear()
return redirect(url_for("login"))
@app.route("/")
@login_required
def dashboard():
env = load_env()
nodes = []
for node in list_nodes():
item = dict(node)
item["links"] = build_links(node, env)
nodes.append(item)
return render_template(
"dashboard.html",
nodes=nodes,
domain=env.get("DOMAIN", ""),
vps_ip=env.get("VPS_IP", ""),
)
@app.route("/api/nodes", methods=["GET"])
@login_required
def api_list_nodes():
env = load_env()
data = []
for node in list_nodes():
item = {
"id": node["id"],
"name": node["name"],
"uuid": node["uuid"],
"created_at": node["created_at"],
"links": build_links(node, env),
}
data.append(item)
return jsonify(data)
@app.route("/api/nodes", methods=["POST"])
@login_required
def api_add_node():
body = request.get_json(silent=True) or {}
name = (body.get("name") or request.form.get("name") or "新节点").strip()
node = add_node(name)
ok, msg = apply_singbox()
if not ok:
delete_node(node["id"])
return jsonify({"error": msg}), 500
env = load_env()
return jsonify(
{
"id": node["id"],
"name": node["name"],
"links": build_links(node, env),
}
)
@app.route("/api/nodes/<int:node_id>", methods=["DELETE"])
@login_required
def api_delete_node(node_id: int):
if node_count() <= 1:
return jsonify({"error": "至少保留一个节点"}), 400
if not delete_node(node_id):
return jsonify({"error": "节点不存在"}), 404
ok, msg = apply_singbox()
if not ok:
return jsonify({"error": msg}), 500
return jsonify({"ok": True})
if __name__ == "__main__":
app.run(host="127.0.0.1", port=5080)
+124
View File
@@ -0,0 +1,124 @@
"""SQLite 数据库:管理员账号与节点。"""
from __future__ import annotations
import os
import secrets
import sqlite3
import subprocess
from pathlib import Path
from werkzeug.security import check_password_hash, generate_password_hash
ROOT = Path(os.environ.get("JIEDIAN_ROOT", Path(__file__).resolve().parents[1]))
DB_FILE = ROOT / "data" / "nodes.db"
def connect() -> sqlite3.Connection:
DB_FILE.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(DB_FILE)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON")
return conn
def init_db(env: dict[str, str]) -> None:
conn = connect()
conn.executescript(
"""
CREATE TABLE IF NOT EXISTS admin (
id INTEGER PRIMARY KEY,
username TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS nodes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
uuid TEXT NOT NULL UNIQUE,
hy2_password TEXT NOT NULL,
enabled INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
"""
)
username = env.get("PANEL_USERNAME", "admin")
password = env.get("PANEL_PASSWORD")
if not password:
raise SystemExit("请在 .env 中设置 PANEL_PASSWORD(运行 generate-keys.sh 可自动生成)")
row = conn.execute("SELECT id FROM admin WHERE username = ?", (username,)).fetchone()
if row is None:
conn.execute(
"INSERT INTO admin (username, password_hash) VALUES (?, ?)",
(username, generate_password_hash(password)),
)
count = conn.execute("SELECT COUNT(*) AS c FROM nodes").fetchone()["c"]
if count == 0:
uuid, hy2 = _generate_credentials()
conn.execute(
"INSERT INTO nodes (name, uuid, hy2_password) VALUES (?, ?, ?)",
("默认节点", uuid, hy2),
)
conn.commit()
conn.close()
def verify_admin(username: str, password: str) -> bool:
conn = connect()
row = conn.execute(
"SELECT password_hash FROM admin WHERE username = ?", (username,)
).fetchone()
conn.close()
if row is None:
return False
return check_password_hash(row["password_hash"], password)
def list_nodes() -> list[dict]:
conn = connect()
rows = conn.execute(
"SELECT id, name, uuid, hy2_password, enabled, created_at "
"FROM nodes ORDER BY id DESC"
).fetchall()
conn.close()
return [dict(row) for row in rows]
def add_node(name: str) -> dict:
name = name.strip() or "未命名节点"
uuid, hy2 = _generate_credentials()
conn = connect()
cur = conn.execute(
"INSERT INTO nodes (name, uuid, hy2_password) VALUES (?, ?, ?)",
(name, uuid, hy2),
)
node_id = cur.lastrowid
row = conn.execute("SELECT * FROM nodes WHERE id = ?", (node_id,)).fetchone()
conn.commit()
conn.close()
return dict(row)
def delete_node(node_id: int) -> bool:
conn = connect()
cur = conn.execute("DELETE FROM nodes WHERE id = ?", (node_id,))
conn.commit()
deleted = cur.rowcount > 0
conn.close()
return deleted
def node_count() -> int:
conn = connect()
count = conn.execute("SELECT COUNT(*) AS c FROM nodes").fetchone()["c"]
conn.close()
return count
def _generate_credentials() -> tuple[str, str]:
sb = "sing-box"
uuid = subprocess.check_output([sb, "generate", "uuid"], text=True).strip()
hy2 = secrets.token_urlsafe(18)[:24]
return uuid, hy2
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env python3
"""初始化 SQLite 数据库与默认管理员。"""
from __future__ import annotations
import os
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "panel"))
os.environ.setdefault("JIEDIAN_ROOT", str(ROOT))
from db import init_db # noqa: E402
def load_env() -> dict[str, str]:
env: dict[str, str] = {}
for line in (ROOT / ".env").read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, value = line.partition("=")
env[key.strip()] = value.strip()
return env
if __name__ == "__main__":
init_db(load_env())
print("数据库初始化完成")
+37
View File
@@ -0,0 +1,37 @@
"""分享链接生成。"""
from __future__ import annotations
import os
from pathlib import Path
from urllib.parse import quote
def load_env() -> dict[str, str]:
root = Path(os.environ.get("JIEDIAN_ROOT", Path(__file__).resolve().parents[1]))
env: dict[str, str] = {}
for line in (root / ".env").read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, value = line.partition("=")
env[key.strip()] = value.strip()
return env
def build_links(node: dict, env: dict | None = None) -> dict[str, str]:
env = env or load_env()
vps_ip = env["VPS_IP"]
domain = env["DOMAIN"]
reality_sni = env.get("REALITY_SERVER_NAME", "www.microsoft.com")
public_key = env["REALITY_PUBLIC_KEY"]
short_id = env["REALITY_SHORT_ID"]
name = quote(node["name"])
vless = (
f"vless://{node['uuid']}@{vps_ip}:443"
f"?encryption=none&flow=xtls-rprx-vision&security=reality"
f"&sni={reality_sni}&fp=chrome&pbk={public_key}&sid={short_id}"
f"&type=tcp#{name}"
)
hy2 = f"hy2://{node['hy2_password']}@{domain}:8443?sni={domain}#{name}-Hy2"
return {"vless": vless, "hy2": hy2}
+2
View File
@@ -0,0 +1,2 @@
flask>=3.0,<4
werkzeug>=3.0,<4
+74
View File
@@ -0,0 +1,74 @@
function toast(msg) {
const el = document.getElementById("toast");
el.textContent = msg;
el.classList.remove("hidden");
setTimeout(() => el.classList.add("hidden"), 2200);
}
document.querySelectorAll("[data-copy]").forEach((btn) => {
btn.addEventListener("click", async () => {
const text = btn.dataset.copy;
try {
await navigator.clipboard.writeText(text);
toast("已复制到剪贴板");
} catch {
toast("复制失败,请手动选择文本");
}
});
});
const modal = document.getElementById("modal");
const addBtn = document.getElementById("addBtn");
const cancelBtn = document.getElementById("cancelBtn");
const confirmAddBtn = document.getElementById("confirmAddBtn");
const nodeName = document.getElementById("nodeName");
if (addBtn) {
addBtn.addEventListener("click", () => {
nodeName.value = "";
modal.classList.remove("hidden");
nodeName.focus();
});
}
if (cancelBtn) {
cancelBtn.addEventListener("click", () => modal.classList.add("hidden"));
}
if (confirmAddBtn) {
confirmAddBtn.addEventListener("click", async () => {
const name = nodeName.value.trim() || "新节点";
confirmAddBtn.disabled = true;
try {
const res = await fetch("/api/nodes", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name }),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || "创建失败");
location.reload();
} catch (err) {
toast(err.message);
} finally {
confirmAddBtn.disabled = false;
}
});
}
document.querySelectorAll(".delete-btn").forEach((btn) => {
btn.addEventListener("click", async () => {
const id = btn.dataset.id;
if (!confirm("确定删除该节点?删除后对应链接将失效。")) return;
btn.disabled = true;
try {
const res = await fetch(`/api/nodes/${id}`, { method: "DELETE" });
const data = await res.json();
if (!res.ok) throw new Error(data.error || "删除失败");
location.reload();
} catch (err) {
toast(err.message);
btn.disabled = false;
}
});
});
+171
View File
@@ -0,0 +1,171 @@
:root {
--bg: #0f1419;
--card: #1a2332;
--border: #2a3544;
--text: #e7ecf3;
--muted: #8b98a8;
--primary: #3b82f6;
--danger: #ef4444;
--radius: 12px;
}
* { box-sizing: border-box; }
body {
margin: 0;
font-family: "Segoe UI", system-ui, sans-serif;
background: var(--bg);
color: var(--text);
min-height: 100vh;
}
.auth-wrap {
min-height: 100vh;
display: grid;
place-items: center;
padding: 24px;
}
.auth-card, .modal-card, .node-card {
background: var(--card);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 24px;
}
.auth-card { width: min(420px, 100%); }
.auth-card h1 { margin: 0 0 8px; font-size: 1.5rem; }
.topbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px 24px;
border-bottom: 1px solid var(--border);
background: rgba(26, 35, 50, 0.8);
backdrop-filter: blur(8px);
position: sticky;
top: 0;
}
.container { max-width: 960px; margin: 0 auto; padding: 24px; }
.hero {
display: flex;
justify-content: space-between;
align-items: center;
gap: 16px;
margin-bottom: 24px;
}
.hero h1 { margin: 0 0 8px; }
.muted { color: var(--muted); }
.form label, .field label {
display: block;
margin: 12px 0 6px;
color: var(--muted);
font-size: 0.9rem;
}
input[type="text"],
input[type="password"],
input[readonly] {
width: 100%;
padding: 10px 12px;
border-radius: 8px;
border: 1px solid var(--border);
background: #111827;
color: var(--text);
}
.btn {
border: 1px solid var(--border);
background: #111827;
color: var(--text);
padding: 8px 14px;
border-radius: 8px;
cursor: pointer;
text-decoration: none;
display: inline-block;
}
.btn:hover { border-color: var(--primary); }
.btn.primary {
background: var(--primary);
border-color: var(--primary);
color: white;
}
.btn.ghost { background: transparent; }
.btn.danger {
color: var(--danger);
border-color: rgba(239, 68, 68, 0.4);
}
.node-list { display: grid; gap: 16px; }
.node-head {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
}
.node-head h2 { margin: 0; font-size: 1.1rem; }
.tag {
font-size: 0.8rem;
color: var(--muted);
background: #111827;
padding: 4px 8px;
border-radius: 999px;
}
.copy-row {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px;
}
.node-actions { margin-top: 16px; text-align: right; }
.alert {
background: rgba(239, 68, 68, 0.15);
border: 1px solid rgba(239, 68, 68, 0.35);
padding: 10px 12px;
border-radius: 8px;
margin: 12px 0;
}
.toast {
position: fixed;
right: 24px;
bottom: 24px;
background: var(--card);
border: 1px solid var(--border);
padding: 12px 16px;
border-radius: 8px;
z-index: 20;
}
.hidden { display: none !important; }
.modal {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.55);
display: grid;
place-items: center;
padding: 24px;
z-index: 10;
}
.modal-card { width: min(420px, 100%); }
.modal-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
margin-top: 20px;
}
@media (max-width: 640px) {
.hero { flex-direction: column; align-items: flex-start; }
.copy-row { grid-template-columns: 1fr; }
}
+13
View File
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}jiedian 面板{% endblock %}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
{% block body %}{% endblock %}
{% block scripts %}{% endblock %}
</body>
</html>
+65
View File
@@ -0,0 +1,65 @@
{% extends "base.html" %}
{% block title %}节点管理 · jiedian{% endblock %}
{% block body %}
<header class="topbar">
<div>
<strong>jiedian 面板</strong>
<span class="muted"> · {{ domain }}</span>
</div>
<a class="btn ghost" href="{{ url_for('logout') }}">退出</a>
</header>
<main class="container">
<section class="hero">
<div>
<h1>节点列表</h1>
<p class="muted">VPS {{ vps_ip }} · Reality 443 · Hysteria2 8443</p>
</div>
<button id="addBtn" class="btn primary">+ 添加节点</button>
</section>
<div id="toast" class="toast hidden"></div>
<div id="nodeList" class="node-list">
{% for node in nodes %}
<article class="node-card" data-id="{{ node.id }}">
<div class="node-head">
<h2>{{ node.name }}</h2>
<span class="tag">{{ node.created_at[:10] }}</span>
</div>
<div class="field">
<label>VLESS + Reality</label>
<div class="copy-row">
<input readonly value="{{ node.links.vless }}">
<button class="btn" data-copy="{{ node.links.vless }}">复制</button>
</div>
</div>
<div class="field">
<label>Hysteria2</label>
<div class="copy-row">
<input readonly value="{{ node.links.hy2 }}">
<button class="btn" data-copy="{{ node.links.hy2 }}">复制</button>
</div>
</div>
<div class="node-actions">
<button class="btn danger delete-btn" data-id="{{ node.id }}">删除</button>
</div>
</article>
{% endfor %}
</div>
</main>
<div id="modal" class="modal hidden">
<div class="modal-card">
<h3>添加节点</h3>
<label>节点名称</label>
<input id="nodeName" type="text" placeholder="例如:手机、电脑">
<div class="modal-actions">
<button id="cancelBtn" class="btn ghost">取消</button>
<button id="confirmAddBtn" class="btn primary">创建</button>
</div>
</div>
</div>
{% endblock %}
{% block scripts %}
<script src="{{ url_for('static', filename='app.js') }}"></script>
{% endblock %}
+20
View File
@@ -0,0 +1,20 @@
{% extends "base.html" %}
{% block title %}登录 · jiedian{% endblock %}
{% block body %}
<div class="auth-wrap">
<div class="auth-card">
<h1>jiedian 管理面板</h1>
<p class="muted">登录后管理节点与分享链接</p>
{% if error %}
<div class="alert">{{ error }}</div>
{% endif %}
<form method="post" class="form">
<label>用户名</label>
<input type="text" name="username" autocomplete="username" required autofocus>
<label>密码</label>
<input type="password" name="password" autocomplete="current-password" required>
<button type="submit" class="btn primary">登录</button>
</form>
</div>
</div>
{% endblock %}