Compare commits
15 Commits
2c0773f4f7
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| c4194166fe | |||
| 605870c80b | |||
| 9e47640eeb | |||
| 1d23bf1773 | |||
| 807b765e2c | |||
| 7d561e0c6b | |||
| 8ffb56d0ad | |||
| e48f52fc29 | |||
| bca5f8f240 | |||
| 61c2a0c004 | |||
| c9d3665399 | |||
| 43728ec30e | |||
| b231e78498 | |||
| ec6b3cb93f | |||
| 8f28ae3c67 |
@@ -0,0 +1,7 @@
|
||||
.git
|
||||
.gitignore
|
||||
node_modules
|
||||
out
|
||||
subs.json
|
||||
npm-debug.log
|
||||
.DS_Store
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
FROM docker.m.daocloud.io/library/node:20-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
ENV NODE_ENV=production \
|
||||
HOST=0.0.0.0 \
|
||||
PORT=3000 \
|
||||
AUTO_OPEN=0
|
||||
|
||||
COPY package*.json ./
|
||||
RUN if [ -f package-lock.json ]; then npm ci --omit=dev; else npm install --omit=dev; fi
|
||||
|
||||
COPY sub2proxy.js ./
|
||||
COPY public ./public
|
||||
COPY templates ./templates
|
||||
|
||||
RUN mkdir -p out && printf '[]\n' > subs.json
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
||||
CMD node -e "require('http').get('http://127.0.0.1:'+(process.env.PORT||3000)+'/api/health',r=>process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))"
|
||||
|
||||
CMD ["node", "sub2proxy.js"]
|
||||
@@ -34,3 +34,48 @@ node sub2proxy.js
|
||||
node sub2proxy.js --cli
|
||||
```
|
||||
配置会自动输出到 `out/CatMata-sub.yaml` 和 `out/CatMata-sub.json`,并归档于 `out/history`。
|
||||
|
||||
## Docker / 飞牛部署
|
||||
|
||||
### 使用 Compose
|
||||
先确认当前目录下存在 `subs.json`,再运行:
|
||||
```bash
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
默认访问地址:
|
||||
```text
|
||||
http://飞牛IP:3000
|
||||
```
|
||||
|
||||
首次部署请先修改 `docker-compose.yml` 中的密码和密钥:
|
||||
```yaml
|
||||
ADMIN_PASSWORD: "你的管理员密码"
|
||||
VIEWER_PASSWORD: "你的用户访问密码"
|
||||
SESSION_SECRET: "一段随机字符串"
|
||||
LINK_TOKEN_SECRET: "另一段随机字符串"
|
||||
```
|
||||
|
||||
页面入口:
|
||||
* 管理员控制台:`http://飞牛IP:3000/config`
|
||||
* 用户只读配置页:`http://飞牛IP:3000/sub`
|
||||
|
||||
需要持久化的数据:
|
||||
* `subs.json` - 订阅源配置,控制面板修改后会写入这里
|
||||
* `out/` - 当前输出和历史配置
|
||||
* `templates/` - Clash / Sing-box 模板,默认只读挂载
|
||||
|
||||
### 手机/电脑一键导入
|
||||
如果手机或电脑通过 `http://飞牛IP:3000` 打开控制面板,导入链接会自动使用这个地址生成,Clash 客户端可以直接从飞牛拉取配置。
|
||||
|
||||
如果你通过反向代理、域名或 HTTPS 访问,建议在 `docker-compose.yml` 中设置:
|
||||
```yaml
|
||||
PUBLIC_BASE_URL: "https://你的域名"
|
||||
```
|
||||
|
||||
如果使用局域网固定 IP,也可以显式设置:
|
||||
```yaml
|
||||
PUBLIC_BASE_URL: "http://192.168.1.10:3000"
|
||||
```
|
||||
|
||||
注意:不要让导入链接使用 `127.0.0.1` 或 `localhost`,手机/电脑上的 Clash 会把它理解为设备自己,而不是飞牛服务器。
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
services:
|
||||
sub2proxy:
|
||||
build: .
|
||||
container_name: sub2proxy
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "3000:3000"
|
||||
environment:
|
||||
PORT: "3000"
|
||||
HOST: "0.0.0.0"
|
||||
AUTO_OPEN: "0"
|
||||
ADMIN_PASSWORD: "change-admin-password"
|
||||
VIEWER_PASSWORD: "change-viewer-password"
|
||||
SESSION_SECRET: "change-session-secret"
|
||||
LINK_TOKEN_SECRET: "change-link-token-secret"
|
||||
# Set this when clients should import through a fixed LAN IP, domain, or reverse proxy.
|
||||
# PUBLIC_BASE_URL: "http://192.168.1.10:3000"
|
||||
volumes:
|
||||
- ./subs.json:/app/subs.json
|
||||
- ./out:/app/out
|
||||
- ./templates:/app/templates:ro
|
||||
+337
-57
@@ -6,6 +6,7 @@
|
||||
<title>CatMata Sub2Proxy 控制面板</title>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
|
||||
<script src="https://unpkg.com/lucide@latest"></script>
|
||||
<script src="https://unpkg.com/sortablejs@1.15.2/Sortable.min.js"></script>
|
||||
<style>
|
||||
:root {
|
||||
--bg-main: #0b0f19;
|
||||
@@ -28,6 +29,24 @@
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: rgba(255, 255, 255, 0.15) transparent;
|
||||
}
|
||||
|
||||
/* Custom Scrollbar Styles */
|
||||
::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
border-radius: 3px;
|
||||
}
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--accent-purple);
|
||||
}
|
||||
|
||||
body {
|
||||
@@ -92,6 +111,12 @@
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.sidebar-wrapper {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.5rem;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
background: var(--bg-card);
|
||||
backdrop-filter: blur(12px);
|
||||
@@ -306,9 +331,24 @@
|
||||
|
||||
/* Proxy Nodes view */
|
||||
.table-container {
|
||||
max-height: 380px;
|
||||
overflow-y: auto;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
/* Sortable Dragging Styling */
|
||||
.sortable-ghost {
|
||||
background: rgba(139, 92, 246, 0.1) !important;
|
||||
border-left: 2px solid var(--accent-purple) !important;
|
||||
opacity: 0.85;
|
||||
}
|
||||
.drag-handle {
|
||||
cursor: grab;
|
||||
}
|
||||
.drag-handle:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
@@ -316,6 +356,10 @@
|
||||
}
|
||||
|
||||
th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
background: #0f1523; /* solid dark background matching blended card color */
|
||||
z-index: 10;
|
||||
padding: 1rem;
|
||||
color: var(--text-secondary);
|
||||
font-weight: 600;
|
||||
@@ -473,7 +517,6 @@
|
||||
|
||||
/* Logger Terminal */
|
||||
.console-panel {
|
||||
margin-top: 2rem;
|
||||
background: #090d16;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 16px;
|
||||
@@ -482,8 +525,8 @@
|
||||
|
||||
.console-header {
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
padding: 0.75rem 1.5rem;
|
||||
font-size: 0.8rem;
|
||||
padding: 0.6rem 1rem;
|
||||
font-size: 0.78rem;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-secondary);
|
||||
@@ -494,15 +537,16 @@
|
||||
}
|
||||
|
||||
.console-logs {
|
||||
padding: 1rem 1.5rem;
|
||||
height: 120px;
|
||||
padding: 0.8rem 1rem;
|
||||
height: 180px;
|
||||
overflow-y: auto;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.85rem;
|
||||
font-size: 0.8rem;
|
||||
color: #a78bfa;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.log-line {
|
||||
@@ -667,21 +711,37 @@
|
||||
|
||||
<!-- Content Layout -->
|
||||
<div class="layout">
|
||||
<!-- Sidebar Navigation -->
|
||||
<nav class="sidebar">
|
||||
<button class="nav-btn active" onclick="switchTab('subs')" id="btn-tab-subs">
|
||||
<i data-lucide="link"></i>订阅源管理
|
||||
</button>
|
||||
<button class="nav-btn" onclick="switchTab('proxies')" id="btn-tab-proxies">
|
||||
<i data-lucide="shield"></i>代理节点列表
|
||||
</button>
|
||||
<button class="nav-btn" onclick="switchTab('dns')" id="btn-tab-dns">
|
||||
<i data-lucide="globe"></i>DNS 规则配置
|
||||
</button>
|
||||
<button class="nav-btn" onclick="switchTab('history')" id="btn-tab-history">
|
||||
<i data-lucide="history"></i>生成历史记录
|
||||
</button>
|
||||
</nav>
|
||||
<!-- Sidebar and Console Wrapper -->
|
||||
<div class="sidebar-wrapper">
|
||||
<!-- Sidebar Navigation -->
|
||||
<nav class="sidebar">
|
||||
<button class="nav-btn active" onclick="switchTab('subs')" id="btn-tab-subs">
|
||||
<i data-lucide="link"></i>订阅源管理
|
||||
</button>
|
||||
<button class="nav-btn" onclick="switchTab('proxies')" id="btn-tab-proxies">
|
||||
<i data-lucide="shield"></i>代理节点列表
|
||||
</button>
|
||||
<button class="nav-btn" onclick="switchTab('dns')" id="btn-tab-dns">
|
||||
<i data-lucide="globe"></i>DNS 规则配置
|
||||
</button>
|
||||
<button class="nav-btn" onclick="switchTab('history')" id="btn-tab-history">
|
||||
<i data-lucide="history"></i>生成历史记录
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
<!-- Console Terminal -->
|
||||
<div class="console-panel">
|
||||
<div class="console-header">
|
||||
<span>控制台日志</span>
|
||||
<button class="btn btn-secondary" style="padding: 0.25rem 0.5rem; font-size: 0.75rem;" onclick="clearLogs()">
|
||||
清空
|
||||
</button>
|
||||
</div>
|
||||
<div class="console-logs" id="console-logs">
|
||||
<div class="log-line log-info">系统初始化完成。请添加订阅源或拉取配置。</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Main Panel -->
|
||||
<main class="main-content">
|
||||
@@ -710,7 +770,9 @@
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>名称 (Tag)</th>
|
||||
<th style="width: 50px; text-align: center;">排序</th>
|
||||
<th>解析名 (Tag)</th>
|
||||
<th>代理名</th>
|
||||
<th>协议 (Type)</th>
|
||||
<th>服务器 (Server)</th>
|
||||
<th>端口 (Port)</th>
|
||||
@@ -719,7 +781,7 @@
|
||||
</thead>
|
||||
<tbody id="proxies-list">
|
||||
<tr>
|
||||
<td colspan="5" style="text-align: center; color: var(--text-secondary); padding: 3rem;">
|
||||
<td colspan="7" style="text-align: center; color: var(--text-secondary); padding: 3rem;">
|
||||
请先点击右上角 “一键拉取” 按钮解析节点
|
||||
</td>
|
||||
</tr>
|
||||
@@ -757,6 +819,43 @@
|
||||
<i data-lucide="refresh-cw"></i>刷新历史
|
||||
</button>
|
||||
</div>
|
||||
<!-- Latest Subscription Links -->
|
||||
<div style="margin-bottom: 1.5rem; background: rgba(255, 255, 255, 0.02); border: 1px solid var(--border-color); border-radius: 12px; padding: 1.25rem; display: flex; flex-direction: column; gap: 1rem;">
|
||||
<div style="font-size: 0.95rem; font-weight: 600; color: var(--text-primary); display: flex; align-items: center; gap: 0.5rem;">
|
||||
<i data-lucide="link" style="width: 16px; height: 16px; color: var(--accent-purple);"></i>最新订阅地址 (无Token/持久链接)
|
||||
</div>
|
||||
<div style="display: flex; flex-wrap: wrap; gap: 1rem;">
|
||||
<div style="flex: 1; min-width: 280px; display: flex; align-items: center; justify-content: space-between; background: rgba(255, 255, 255, 0.01); border: 1px solid var(--border-color); border-radius: 8px; padding: 0.75rem 1rem;">
|
||||
<div style="display: flex; flex-direction: column; gap: 0.25rem;">
|
||||
<span style="font-size: 0.75rem; font-weight: 600; color: #a78bfa; text-transform: uppercase;">Clash (YAML)</span>
|
||||
<span style="font-size: 0.85rem; font-family: var(--font-mono); color: var(--text-secondary); word-break: break-all;" id="latest-clash-link">加载中...</span>
|
||||
</div>
|
||||
<div style="display: flex; gap: 0.5rem; align-items: center;">
|
||||
<button type="button" class="btn btn-secondary" style="padding: 0.35rem 0.75rem; font-size: 0.8rem;" onclick="copyLatestLink('clash')">
|
||||
<i data-lucide="copy" style="width: 12px; height: 12px;"></i>复制
|
||||
</button>
|
||||
<a class="btn btn-primary" style="padding: 0.35rem 0.75rem; font-size: 0.8rem; text-decoration: none; background: linear-gradient(135deg, #10B981 0%, #059669 100%);" id="latest-clash-import" href="#">
|
||||
<i data-lucide="zap" style="width: 12px; height: 12px;"></i>导入 Clash
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="flex: 1; min-width: 280px; display: flex; align-items: center; justify-content: space-between; background: rgba(255, 255, 255, 0.01); border: 1px solid var(--border-color); border-radius: 8px; padding: 0.75rem 1rem;">
|
||||
<div style="display: flex; flex-direction: column; gap: 0.25rem;">
|
||||
<span style="font-size: 0.75rem; font-weight: 600; color: #f472b6; text-transform: uppercase;">Sing-box (JSON)</span>
|
||||
<span style="font-size: 0.85rem; font-family: var(--font-mono); color: var(--text-secondary); word-break: break-all;" id="latest-singbox-link">加载中...</span>
|
||||
</div>
|
||||
<div style="display: flex; gap: 0.5rem; align-items: center;">
|
||||
<button type="button" class="btn btn-secondary" style="padding: 0.35rem 0.75rem; font-size: 0.8rem;" onclick="copyLatestLink('singbox')">
|
||||
<i data-lucide="copy" style="width: 12px; height: 12px;"></i>复制
|
||||
</button>
|
||||
<a class="btn btn-primary" style="padding: 0.35rem 0.75rem; font-size: 0.8rem; text-decoration: none; background: linear-gradient(135deg, #3B82F6 0%, #2563EB 100%);" id="latest-singbox-import" href="#">
|
||||
<i data-lucide="zap" style="width: 12px; height: 12px;"></i>导入 Sing-box
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="table-container">
|
||||
<table>
|
||||
<thead>
|
||||
@@ -764,12 +863,14 @@
|
||||
<th>生成时间</th>
|
||||
<th>节点数量</th>
|
||||
<th>本地下载</th>
|
||||
<th>复制链接</th>
|
||||
<th>一键导入</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="history-list">
|
||||
<tr>
|
||||
<td colspan="4" style="text-align: center; color: var(--text-secondary); padding: 3rem;">
|
||||
<td colspan="6" style="text-align: center; color: var(--text-secondary); padding: 3rem;">
|
||||
暂无生成历史记录,运行生成配置后将在此归档
|
||||
</td>
|
||||
</tr>
|
||||
@@ -779,19 +880,6 @@
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<!-- Console Terminal -->
|
||||
<div class="console-panel">
|
||||
<div class="console-header">
|
||||
<span>控制台日志 (Console Logs)</span>
|
||||
<button class="btn btn-secondary" style="padding: 0.25rem 0.5rem; font-size: 0.75rem;" onclick="clearLogs()">
|
||||
清空日志
|
||||
</button>
|
||||
</div>
|
||||
<div class="console-logs" id="console-logs">
|
||||
<div class="log-line log-info">系统初始化完成。请添加订阅源或拉取配置。</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Drawer Modal for editing a node's details -->
|
||||
@@ -856,14 +944,52 @@
|
||||
let subscriptions = [];
|
||||
let proxies = []; // In-memory editable proxies
|
||||
let originalDns = { clash: '', singbox: '' };
|
||||
let appConfig = { publicBaseUrl: '' };
|
||||
|
||||
// On Load
|
||||
window.addEventListener('DOMContentLoaded', () => {
|
||||
window.addEventListener('DOMContentLoaded', async () => {
|
||||
lucide.createIcons();
|
||||
await loadAppConfig();
|
||||
updateLatestUrls();
|
||||
loadSubscriptions();
|
||||
loadDnsTemplates();
|
||||
|
||||
// Initialize Sortable on proxies list
|
||||
const el = document.getElementById('proxies-list');
|
||||
new Sortable(el, {
|
||||
handle: '.drag-handle',
|
||||
animation: 150,
|
||||
ghostClass: 'sortable-ghost',
|
||||
onEnd: function (evt) {
|
||||
const oldIndex = evt.oldIndex;
|
||||
const newIndex = evt.newIndex;
|
||||
|
||||
if (oldIndex === newIndex) return;
|
||||
if (proxies.length === 0) return;
|
||||
|
||||
// Update memory proxies array order
|
||||
const movedItem = proxies.splice(oldIndex, 1)[0];
|
||||
proxies.splice(newIndex, 0, movedItem);
|
||||
|
||||
// Rerender table to update button dataset index
|
||||
renderProxiesTable();
|
||||
log(`调整代理节点顺序:从位置 ${oldIndex + 1} 移动到 ${newIndex + 1}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
async function loadAppConfig() {
|
||||
try {
|
||||
const res = await fetch('/api/app-config');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
appConfig.publicBaseUrl = (data.publicBaseUrl || '').replace(/\/+$/, '');
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('Failed to load app config:', e);
|
||||
}
|
||||
}
|
||||
|
||||
// Logging helper
|
||||
function log(message, type = 'info') {
|
||||
const logs = document.getElementById('console-logs');
|
||||
@@ -1093,6 +1219,24 @@
|
||||
}
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value ?? '').replace(/[&<>"']/g, ch => ({
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
"'": '''
|
||||
})[ch]);
|
||||
}
|
||||
|
||||
function getParsedName(node) {
|
||||
return node.name || node.tag || '';
|
||||
}
|
||||
|
||||
function getProxyName(node) {
|
||||
return node.proxyName || node.originalName || getParsedName(node);
|
||||
}
|
||||
|
||||
function renderProxiesTable() {
|
||||
const list = document.getElementById('proxies-list');
|
||||
const counter = document.getElementById('proxies-counter');
|
||||
@@ -1103,7 +1247,7 @@
|
||||
if (proxies.length === 0) {
|
||||
list.innerHTML = `
|
||||
<tr>
|
||||
<td colspan="5" style="text-align: center; color: var(--text-secondary); padding: 3rem;">
|
||||
<td colspan="7" style="text-align: center; color: var(--text-secondary); padding: 3rem;">
|
||||
未提取到任何代理节点
|
||||
</td>
|
||||
</tr>
|
||||
@@ -1113,15 +1257,29 @@
|
||||
|
||||
proxies.forEach((node, idx) => {
|
||||
const tr = document.createElement('tr');
|
||||
const parsedName = getParsedName(node);
|
||||
const proxyName = getProxyName(node);
|
||||
const nodeType = node.type || '';
|
||||
const server = node.server || '';
|
||||
const port = node.port || node.server_port || '';
|
||||
tr.innerHTML = `
|
||||
<td style="font-weight: 500;">${node.name || node.tag}</td>
|
||||
<td><span class="node-proto proto-${(node.type || '').toLowerCase()}">${node.type}</span></td>
|
||||
<td style="font-family: var(--font-mono); font-size: 0.85rem;">${node.server}</td>
|
||||
<td style="font-family: var(--font-mono); font-size: 0.85rem;">${node.port || node.server_port}</td>
|
||||
<td class="drag-handle" style="text-align: center; color: var(--text-secondary);">
|
||||
<i data-lucide="grip-vertical" style="width: 16px; height: 16px;"></i>
|
||||
</td>
|
||||
<td style="font-weight: 500;" title="${escapeHtml(parsedName)}">${escapeHtml(parsedName)}</td>
|
||||
<td title="${escapeHtml(proxyName)}">${escapeHtml(proxyName)}</td>
|
||||
<td><span class="node-proto proto-${escapeHtml(nodeType.toLowerCase())}">${escapeHtml(nodeType)}</span></td>
|
||||
<td style="font-family: var(--font-mono); font-size: 0.85rem;">${escapeHtml(server)}</td>
|
||||
<td style="font-family: var(--font-mono); font-size: 0.85rem;">${escapeHtml(port)}</td>
|
||||
<td>
|
||||
<button class="btn btn-secondary" style="padding: 0.25rem 0.5rem; font-size: 0.75rem;" onclick="openNodeDrawer(${idx})">
|
||||
<i data-lucide="sliders" style="width: 12px; height: 12px;"></i>修改参数
|
||||
</button>
|
||||
<div style="display: flex; gap: 0.5rem;">
|
||||
<button class="btn btn-secondary" style="padding: 0.25rem 0.5rem; font-size: 0.75rem;" onclick="openNodeDrawer(${idx})">
|
||||
<i data-lucide="sliders" style="width: 12px; height: 12px;"></i>修改参数
|
||||
</button>
|
||||
<button class="btn btn-danger" style="padding: 0.25rem 0.5rem; font-size: 0.75rem;" onclick="deleteProxy(${idx})">
|
||||
<i data-lucide="trash-2" style="width: 12px; height: 12px;"></i>删除
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
`;
|
||||
list.appendChild(tr);
|
||||
@@ -1129,6 +1287,16 @@
|
||||
lucide.createIcons();
|
||||
}
|
||||
|
||||
function deleteProxy(idx) {
|
||||
const nodeName = getParsedName(proxies[idx]);
|
||||
if (confirm(`确定要删除代理节点 "${nodeName}" 吗?\n(注:这仅会从当前页面内存中删除。如需应用更改,请在删除后点击右上角“保存并生成配置”按钮重新生成配置文件)`)) {
|
||||
log(`在内存中删除代理节点: ${nodeName}`);
|
||||
proxies.splice(idx, 1);
|
||||
renderProxiesTable();
|
||||
showToast('代理节点已删除');
|
||||
}
|
||||
}
|
||||
|
||||
// Modal Drawer for Editing Nodes
|
||||
let currentEditNodeIndex = null;
|
||||
|
||||
@@ -1139,17 +1307,18 @@
|
||||
const container = document.getElementById('node-edit-form');
|
||||
const overlay = document.getElementById('node-drawer-overlay');
|
||||
|
||||
title.textContent = `修改节点: ${node.name || node.tag}`;
|
||||
title.textContent = `修改节点: ${getParsedName(node)}`;
|
||||
container.innerHTML = '';
|
||||
|
||||
const commonFields = [
|
||||
{ name: 'name', label: '节点 Tag/Name', val: node.name || node.tag, type: 'text' },
|
||||
{ name: 'name', label: '解析名 (Tag)', val: getParsedName(node), type: 'text' },
|
||||
{ name: 'proxyName', label: '代理名', val: getProxyName(node), type: 'text', readonly: true },
|
||||
{ name: 'server', label: '服务器 IP/域名', val: node.server, type: 'text' },
|
||||
{ name: 'port', label: '端口', val: node.port || node.server_port, type: 'number' }
|
||||
];
|
||||
|
||||
commonFields.forEach(f => {
|
||||
container.appendChild(createFormField(f.name, f.label, f.val, f.type));
|
||||
container.appendChild(createFormField(f.name, f.label, f.val, f.type, { readonly: f.readonly }));
|
||||
});
|
||||
|
||||
const t = (node.type || '').toLowerCase();
|
||||
@@ -1190,12 +1359,13 @@
|
||||
overlay.classList.add('active');
|
||||
}
|
||||
|
||||
function createFormField(name, label, value, type) {
|
||||
function createFormField(name, label, value, type, options = {}) {
|
||||
const div = document.createElement('div');
|
||||
div.className = 'form-group';
|
||||
const readonlyAttr = options.readonly ? ' readonly aria-readonly="true"' : '';
|
||||
div.innerHTML = `
|
||||
<label for="edit-${name}">${label}</label>
|
||||
<input type="${type}" id="edit-${name}" class="form-control" value="${value !== undefined ? value : ''}">
|
||||
<label for="edit-${escapeHtml(name)}">${escapeHtml(label)}</label>
|
||||
<input type="${escapeHtml(type)}" id="edit-${escapeHtml(name)}" class="form-control" value="${escapeHtml(value !== undefined ? value : '')}"${readonlyAttr}>
|
||||
`;
|
||||
return div;
|
||||
}
|
||||
@@ -1362,6 +1532,94 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteHistory(yamlFile, jsonFile, timeStr) {
|
||||
if (confirm(`确定要删除该历史生成记录吗?\n生成时间: ${timeStr}\n(注意:此操作将物理删除对应的配置文件归档且不可逆!)`)) {
|
||||
log(`正在请求删除历史记录: ${timeStr}`);
|
||||
try {
|
||||
const res = await fetch('/api/history/delete', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ yamlFile, jsonFile })
|
||||
});
|
||||
if (res.ok) {
|
||||
log(`成功删除历史记录: ${timeStr}`, 'success');
|
||||
showToast('历史记录删除成功');
|
||||
loadHistory();
|
||||
} else {
|
||||
const errText = await res.text();
|
||||
log(`删除历史记录失败: ${errText}`, 'error');
|
||||
showToast('删除历史记录失败', 'error');
|
||||
}
|
||||
} catch (e) {
|
||||
log(`删除历史记录异常: ${e.message}`, 'error');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getClientImportOrigin() {
|
||||
if (appConfig.publicBaseUrl) {
|
||||
return appConfig.publicBaseUrl;
|
||||
}
|
||||
|
||||
const localHosts = new Set(['localhost', '127.0.0.1', '::1']);
|
||||
if (!localHosts.has(window.location.hostname)) {
|
||||
return window.location.origin;
|
||||
}
|
||||
|
||||
const port = window.location.port ? `:${window.location.port}` : '';
|
||||
return `${window.location.protocol}//127.0.0.1${port}`;
|
||||
}
|
||||
|
||||
async function copyLinkToClipboard(link) {
|
||||
try {
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
await navigator.clipboard.writeText(link);
|
||||
} else {
|
||||
const textarea = document.createElement('textarea');
|
||||
textarea.value = link;
|
||||
textarea.setAttribute('readonly', '');
|
||||
textarea.style.position = 'fixed';
|
||||
textarea.style.left = '-9999px';
|
||||
document.body.appendChild(textarea);
|
||||
textarea.select();
|
||||
document.execCommand('copy');
|
||||
document.body.removeChild(textarea);
|
||||
}
|
||||
showToast('链接已复制');
|
||||
} catch (e) {
|
||||
showToast('复制链接失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
let latestClashUrl = '';
|
||||
let latestSingboxUrl = '';
|
||||
|
||||
function updateLatestUrls() {
|
||||
const clientOrigin = getClientImportOrigin();
|
||||
latestClashUrl = `${clientOrigin}/sub/clash/latest`;
|
||||
latestSingboxUrl = `${clientOrigin}/sub/singbox/latest`;
|
||||
|
||||
const clashLinkEl = document.getElementById('latest-clash-link');
|
||||
const singboxLinkEl = document.getElementById('latest-singbox-link');
|
||||
if (clashLinkEl) clashLinkEl.textContent = latestClashUrl;
|
||||
if (singboxLinkEl) singboxLinkEl.textContent = latestSingboxUrl;
|
||||
|
||||
const clashImportEl = document.getElementById('latest-clash-import');
|
||||
const singboxImportEl = document.getElementById('latest-singbox-import');
|
||||
if (clashImportEl) {
|
||||
clashImportEl.href = `clash://install-config?url=${encodeURIComponent(latestClashUrl)}&name=${encodeURIComponent('CatMata-Latest')}`;
|
||||
}
|
||||
if (singboxImportEl) {
|
||||
singboxImportEl.href = `sing-box://import-remote-profile?url=${encodeURIComponent(latestSingboxUrl)}#${encodeURIComponent('CatMata-Latest')}`;
|
||||
}
|
||||
}
|
||||
|
||||
function copyLatestLink(type) {
|
||||
const link = type === 'clash' ? latestClashUrl : latestSingboxUrl;
|
||||
copyLinkToClipboard(link);
|
||||
}
|
||||
|
||||
|
||||
function renderHistoryList(list) {
|
||||
const tbody = document.getElementById('history-list');
|
||||
tbody.innerHTML = '';
|
||||
@@ -1369,7 +1627,7 @@
|
||||
if (!list || list.length === 0) {
|
||||
tbody.innerHTML = `
|
||||
<tr>
|
||||
<td colspan="4" style="text-align: center; color: var(--text-secondary); padding: 3rem;">
|
||||
<td colspan="6" style="text-align: center; color: var(--text-secondary); padding: 3rem;">
|
||||
暂无生成历史记录,运行生成配置后将在此归档
|
||||
</td>
|
||||
</tr>
|
||||
@@ -1378,14 +1636,21 @@
|
||||
}
|
||||
|
||||
const origin = window.location.origin;
|
||||
const clientOrigin = getClientImportOrigin();
|
||||
|
||||
list.forEach(item => {
|
||||
const yamlDownloadUrl = `${origin}/api/download?file=${item.yamlFile}`;
|
||||
const jsonDownloadUrl = `${origin}/api/download?file=${item.jsonFile}`;
|
||||
const yamlFileParam = encodeURIComponent(item.yamlFile);
|
||||
const jsonFileParam = encodeURIComponent(item.jsonFile);
|
||||
const yamlTokenParam = item.yamlToken ? `&token=${encodeURIComponent(item.yamlToken)}` : '';
|
||||
const jsonTokenParam = item.jsonToken ? `&token=${encodeURIComponent(item.jsonToken)}` : '';
|
||||
const yamlDownloadUrl = `${origin}/api/download?file=${yamlFileParam}${yamlTokenParam}`;
|
||||
const jsonDownloadUrl = `${origin}/api/download?file=${jsonFileParam}${jsonTokenParam}`;
|
||||
const yamlImportProfileUrl = `${clientOrigin}/api/profile?file=${yamlFileParam}${yamlTokenParam}`;
|
||||
const jsonImportProfileUrl = `${clientOrigin}/api/profile?file=${jsonFileParam}${jsonTokenParam}`;
|
||||
|
||||
// Construct client URI schemes
|
||||
const clashImportUrl = `clash://install-config?url=${encodeURIComponent(yamlDownloadUrl)}&name=${encodeURIComponent('CatMata-' + item.timeStr.replace(/[: ]/g, '-'))}`;
|
||||
const singboxImportUrl = `sing-box://import-remote-profile?url=${encodeURIComponent(jsonDownloadUrl)}#${encodeURIComponent('CatMata-' + item.timeStr.replace(/[: ]/g, '-'))}`;
|
||||
const clashImportUrl = `clash://install-config?url=${encodeURIComponent(yamlImportProfileUrl)}&name=${encodeURIComponent('CatMata-' + item.timeStr.replace(/[: ]/g, '-'))}`;
|
||||
const singboxImportUrl = `sing-box://import-remote-profile?url=${encodeURIComponent(jsonImportProfileUrl)}#${encodeURIComponent('CatMata-' + item.timeStr.replace(/[: ]/g, '-'))}`;
|
||||
|
||||
const tr = document.createElement('tr');
|
||||
tr.innerHTML = `
|
||||
@@ -1401,6 +1666,16 @@
|
||||
</a>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<div style="display: flex; gap: 0.5rem;">
|
||||
<button type="button" class="btn btn-secondary" style="padding: 0.25rem 0.5rem; font-size: 0.75rem;" onclick="copyLinkToClipboard('${yamlImportProfileUrl}')">
|
||||
<i data-lucide="copy" style="width: 12px; height: 12px;"></i>YAML
|
||||
</button>
|
||||
<button type="button" class="btn btn-secondary" style="padding: 0.25rem 0.5rem; font-size: 0.75rem;" onclick="copyLinkToClipboard('${jsonImportProfileUrl}')">
|
||||
<i data-lucide="copy" style="width: 12px; height: 12px;"></i>JSON
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<div style="display: flex; gap: 0.5rem;">
|
||||
<a class="btn btn-primary" style="padding: 0.25rem 0.5rem; font-size: 0.75rem; text-decoration: none; background: linear-gradient(135deg, #10B981 0%, #059669 100%); box-shadow: 0 4px 10px rgba(16, 185, 129, 0.2);" href="${clashImportUrl}">
|
||||
@@ -1411,6 +1686,11 @@
|
||||
</a>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<button class="btn btn-danger" style="padding: 0.25rem 0.5rem; font-size: 0.75rem;" onclick="deleteHistory('${item.yamlFile}', '${item.jsonFile}', '${item.timeStr}')">
|
||||
<i data-lucide="trash-2" style="width: 12px; height: 12px;"></i>删除
|
||||
</button>
|
||||
</td>
|
||||
`;
|
||||
tbody.appendChild(tr);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>登录 - CatMata Sub2Proxy</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f5f7fb;
|
||||
--panel: #ffffff;
|
||||
--text: #111827;
|
||||
--muted: #6b7280;
|
||||
--line: #dbe3ef;
|
||||
--primary: #2563eb;
|
||||
--primary-dark: #1d4ed8;
|
||||
--danger: #dc2626;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
}
|
||||
|
||||
main {
|
||||
width: min(420px, calc(100vw - 32px));
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
padding: 28px;
|
||||
box-shadow: 0 24px 70px rgba(15, 23, 42, 0.08);
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin: 0;
|
||||
font-size: 1.45rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 8px 0 22px;
|
||||
color: var(--muted);
|
||||
line-height: 1.6;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
label {
|
||||
display: block;
|
||||
margin-bottom: 8px;
|
||||
color: #374151;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
input {
|
||||
width: 100%;
|
||||
height: 44px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 6px;
|
||||
padding: 0 12px;
|
||||
font: inherit;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
input:focus {
|
||||
border-color: var(--primary);
|
||||
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.14);
|
||||
}
|
||||
|
||||
button {
|
||||
width: 100%;
|
||||
height: 44px;
|
||||
margin-top: 16px;
|
||||
border: 0;
|
||||
border-radius: 6px;
|
||||
background: var(--primary);
|
||||
color: #fff;
|
||||
font: inherit;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background: var(--primary-dark);
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
cursor: wait;
|
||||
opacity: 0.72;
|
||||
}
|
||||
|
||||
.error {
|
||||
min-height: 22px;
|
||||
margin-top: 12px;
|
||||
color: var(--danger);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.link {
|
||||
display: block;
|
||||
margin-top: 18px;
|
||||
color: var(--muted);
|
||||
text-align: center;
|
||||
text-decoration: none;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.link:hover {
|
||||
color: var(--primary);
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>CatMata Sub2Proxy</h1>
|
||||
<p>输入管理员密码进入完整控制面板。</p>
|
||||
<form id="login-form">
|
||||
<label for="password">管理员密码</label>
|
||||
<input id="password" name="password" type="password" autocomplete="current-password" required autofocus>
|
||||
<button id="submit-btn" type="submit">登录</button>
|
||||
<div class="error" id="error"></div>
|
||||
</form>
|
||||
<a class="link" href="/sub">进入用户配置页</a>
|
||||
</main>
|
||||
|
||||
<script>
|
||||
const form = document.getElementById('login-form');
|
||||
const input = document.getElementById('password');
|
||||
const button = document.getElementById('submit-btn');
|
||||
const error = document.getElementById('error');
|
||||
|
||||
form.addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
error.textContent = '';
|
||||
button.disabled = true;
|
||||
button.textContent = '正在登录...';
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/login', {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ role: 'admin', password: input.value })
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
throw new Error(data.error || '登录失败');
|
||||
}
|
||||
window.location.href = data.redirectTo || '/config';
|
||||
} catch (e) {
|
||||
error.textContent = e.message;
|
||||
button.disabled = false;
|
||||
button.textContent = '登录';
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,537 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>配置记录 - CatMata Sub2Proxy</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f5f7fb;
|
||||
--panel: #ffffff;
|
||||
--text: #111827;
|
||||
--muted: #6b7280;
|
||||
--line: #dbe3ef;
|
||||
--primary: #2563eb;
|
||||
--primary-dark: #1d4ed8;
|
||||
--green: #059669;
|
||||
--danger: #dc2626;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: rgba(0, 0, 0, 0.15) transparent;
|
||||
}
|
||||
|
||||
/* Custom Scrollbar Styles */
|
||||
::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: rgba(0, 0, 0, 0.12);
|
||||
border-radius: 3px;
|
||||
}
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--primary);
|
||||
}
|
||||
|
||||
[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
}
|
||||
|
||||
.login-shell {
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.login-panel,
|
||||
.main-panel {
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 24px 70px rgba(15, 23, 42, 0.08);
|
||||
}
|
||||
|
||||
.login-panel {
|
||||
width: min(420px, 100%);
|
||||
padding: 28px;
|
||||
}
|
||||
|
||||
.main-panel {
|
||||
width: min(1100px, calc(100vw - 32px));
|
||||
margin: 32px auto;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
align-items: center;
|
||||
padding: 22px 24px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin: 0;
|
||||
font-size: 1.35rem;
|
||||
font-weight: 750;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 8px 0 22px;
|
||||
color: var(--muted);
|
||||
line-height: 1.6;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
label {
|
||||
display: block;
|
||||
margin-bottom: 8px;
|
||||
color: #374151;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
input {
|
||||
width: 100%;
|
||||
height: 44px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 6px;
|
||||
padding: 0 12px;
|
||||
font: inherit;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
input:focus {
|
||||
border-color: var(--primary);
|
||||
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.14);
|
||||
}
|
||||
|
||||
button,
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 34px;
|
||||
border: 0;
|
||||
border-radius: 6px;
|
||||
padding: 0 12px;
|
||||
color: #fff;
|
||||
font: inherit;
|
||||
font-size: 0.86rem;
|
||||
font-weight: 700;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.login-panel button {
|
||||
width: 100%;
|
||||
height: 44px;
|
||||
margin-top: 16px;
|
||||
background: var(--primary);
|
||||
}
|
||||
|
||||
.login-panel button:hover,
|
||||
.btn-primary:hover {
|
||||
background: var(--primary-dark);
|
||||
}
|
||||
|
||||
.login-panel button:disabled {
|
||||
cursor: wait;
|
||||
opacity: 0.72;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: #334155;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: var(--primary);
|
||||
}
|
||||
|
||||
.btn-green {
|
||||
background: var(--green);
|
||||
}
|
||||
|
||||
.error {
|
||||
min-height: 22px;
|
||||
margin-top: 12px;
|
||||
color: var(--danger);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.muted {
|
||||
color: var(--muted);
|
||||
font-size: 0.92rem;
|
||||
}
|
||||
|
||||
.table-wrap {
|
||||
max-height: 480px;
|
||||
overflow-y: auto;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
min-width: 760px;
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
padding: 14px 16px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
text-align: left;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
background: #f8fafc;
|
||||
z-index: 10;
|
||||
color: #475569;
|
||||
font-size: 0.78rem;
|
||||
font-weight: 750;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
td {
|
||||
font-size: 0.94rem;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.empty {
|
||||
padding: 48px 16px;
|
||||
color: var(--muted);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
header {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.main-panel {
|
||||
width: calc(100vw - 20px);
|
||||
margin: 10px auto;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<section class="login-shell" id="login-view">
|
||||
<main class="login-panel">
|
||||
<h1>配置记录</h1>
|
||||
<p>输入访问密码查看可下载和导入的配置。</p>
|
||||
<form id="login-form">
|
||||
<label for="password">访问密码</label>
|
||||
<input id="password" name="password" type="password" autocomplete="current-password" required autofocus>
|
||||
<button id="submit-btn" type="submit">进入</button>
|
||||
<div class="error" id="error"></div>
|
||||
</form>
|
||||
</main>
|
||||
</section>
|
||||
|
||||
<section class="main-panel" id="history-view" hidden>
|
||||
<header>
|
||||
<div>
|
||||
<h1>配置生成记录</h1>
|
||||
<div class="muted" id="summary">正在加载...</div>
|
||||
</div>
|
||||
</header>
|
||||
<div style="padding: 20px 24px; border-bottom: 1px solid var(--line); background: #fafbfc; display: flex; flex-direction: column; gap: 12px;">
|
||||
<h3 style="margin: 0; font-size: 0.95rem; font-weight: 700; color: #374151;">最新订阅地址 (无Token/持久链接)</h3>
|
||||
<div style="display: flex; flex-wrap: wrap; gap: 16px;">
|
||||
<div style="flex: 1; min-width: 280px; display: flex; align-items: center; justify-content: space-between; background: #fff; border: 1px solid var(--line); border-radius: 6px; padding: 10px 14px;">
|
||||
<div style="display: flex; flex-direction: column; gap: 4px;">
|
||||
<span style="font-size: 0.78rem; font-weight: 750; color: var(--primary); text-transform: uppercase;">Clash (YAML)</span>
|
||||
<span style="font-size: 0.85rem; font-family: monospace; color: var(--muted); word-break: break-all;" id="latest-clash-link">加载中...</span>
|
||||
</div>
|
||||
<div style="display: flex; gap: 8px; align-items: center;">
|
||||
<button type="button" class="btn btn-secondary" onclick="copyLatestLink('clash')">复制</button>
|
||||
<a class="btn btn-green" id="latest-clash-import" href="#">导入 Clash</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="flex: 1; min-width: 280px; display: flex; align-items: center; justify-content: space-between; background: #fff; border: 1px solid var(--line); border-radius: 6px; padding: 10px 14px;">
|
||||
<div style="display: flex; flex-direction: column; gap: 4px;">
|
||||
<span style="font-size: 0.78rem; font-weight: 750; color: var(--primary); text-transform: uppercase;">Sing-box (JSON)</span>
|
||||
<span style="font-size: 0.85rem; font-family: monospace; color: var(--muted); word-break: break-all;" id="latest-singbox-link">加载中...</span>
|
||||
</div>
|
||||
<div style="display: flex; gap: 8px; align-items: center;">
|
||||
<button type="button" class="btn btn-secondary" onclick="copyLatestLink('singbox')">复制</button>
|
||||
<a class="btn btn-primary" id="latest-singbox-import" href="#">导入 Sing-box</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>生成时间</th>
|
||||
<th>节点数</th>
|
||||
<th>下载配置</th>
|
||||
<th>复制链接</th>
|
||||
<th>导入客户端</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="history-list">
|
||||
<tr>
|
||||
<td colspan="5" class="empty">正在加载记录...</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<script>
|
||||
let appConfig = { publicBaseUrl: '' };
|
||||
|
||||
const loginView = document.getElementById('login-view');
|
||||
const historyView = document.getElementById('history-view');
|
||||
const form = document.getElementById('login-form');
|
||||
const input = document.getElementById('password');
|
||||
const button = document.getElementById('submit-btn');
|
||||
const error = document.getElementById('error');
|
||||
const listEl = document.getElementById('history-list');
|
||||
const summaryEl = document.getElementById('summary');
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value ?? '').replace(/[&<>"']/g, ch => ({
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
"'": '''
|
||||
})[ch]);
|
||||
}
|
||||
|
||||
function getClientImportOrigin() {
|
||||
if (appConfig.publicBaseUrl) {
|
||||
return appConfig.publicBaseUrl;
|
||||
}
|
||||
|
||||
const localHosts = new Set(['localhost', '127.0.0.1', '::1']);
|
||||
if (!localHosts.has(window.location.hostname)) {
|
||||
return window.location.origin;
|
||||
}
|
||||
|
||||
const port = window.location.port ? `:${window.location.port}` : '';
|
||||
return `${window.location.protocol}//127.0.0.1${port}`;
|
||||
}
|
||||
|
||||
async function copyLinkToClipboard(link) {
|
||||
try {
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
await navigator.clipboard.writeText(link);
|
||||
} else {
|
||||
const textarea = document.createElement('textarea');
|
||||
textarea.value = link;
|
||||
textarea.setAttribute('readonly', '');
|
||||
textarea.style.position = 'fixed';
|
||||
textarea.style.left = '-9999px';
|
||||
document.body.appendChild(textarea);
|
||||
textarea.select();
|
||||
document.execCommand('copy');
|
||||
document.body.removeChild(textarea);
|
||||
}
|
||||
summaryEl.textContent = '链接已复制';
|
||||
} catch (e) {
|
||||
summaryEl.textContent = '复制链接失败';
|
||||
}
|
||||
}
|
||||
|
||||
let latestClashUrl = '';
|
||||
let latestSingboxUrl = '';
|
||||
|
||||
function updateLatestUrls() {
|
||||
const clientOrigin = getClientImportOrigin();
|
||||
latestClashUrl = `${clientOrigin}/sub/clash/latest`;
|
||||
latestSingboxUrl = `${clientOrigin}/sub/singbox/latest`;
|
||||
|
||||
const clashLinkEl = document.getElementById('latest-clash-link');
|
||||
const singboxLinkEl = document.getElementById('latest-singbox-link');
|
||||
if (clashLinkEl) clashLinkEl.textContent = latestClashUrl;
|
||||
if (singboxLinkEl) singboxLinkEl.textContent = latestSingboxUrl;
|
||||
|
||||
const clashImportEl = document.getElementById('latest-clash-import');
|
||||
const singboxImportEl = document.getElementById('latest-singbox-import');
|
||||
if (clashImportEl) {
|
||||
clashImportEl.href = `clash://install-config?url=${encodeURIComponent(latestClashUrl)}&name=${encodeURIComponent('CatMata-Latest')}`;
|
||||
}
|
||||
if (singboxImportEl) {
|
||||
singboxImportEl.href = `sing-box://import-remote-profile?url=${encodeURIComponent(latestSingboxUrl)}#${encodeURIComponent('CatMata-Latest')}`;
|
||||
}
|
||||
}
|
||||
|
||||
function copyLatestLink(type) {
|
||||
const link = type === 'clash' ? latestClashUrl : latestSingboxUrl;
|
||||
copyLinkToClipboard(link);
|
||||
}
|
||||
|
||||
|
||||
async function loadAppConfig() {
|
||||
try {
|
||||
const res = await fetch('/api/app-config', { credentials: 'same-origin' });
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
appConfig.publicBaseUrl = (data.publicBaseUrl || '').replace(/\/+$/, '');
|
||||
}
|
||||
} catch (e) {
|
||||
appConfig.publicBaseUrl = '';
|
||||
}
|
||||
}
|
||||
|
||||
async function checkSession() {
|
||||
const res = await fetch('/api/session', { credentials: 'same-origin' });
|
||||
if (!res.ok) return false;
|
||||
const data = await res.json();
|
||||
return data.authenticated && (data.role === 'viewer' || data.role === 'admin');
|
||||
}
|
||||
|
||||
function showHistory() {
|
||||
loginView.hidden = true;
|
||||
historyView.hidden = false;
|
||||
}
|
||||
|
||||
function showLogin(message = '') {
|
||||
historyView.hidden = true;
|
||||
loginView.hidden = false;
|
||||
error.textContent = message;
|
||||
}
|
||||
|
||||
async function loadHistory() {
|
||||
const res = await fetch('/api/history', { credentials: 'same-origin' });
|
||||
if (res.status === 401) {
|
||||
showLogin('请先输入访问密码。');
|
||||
return;
|
||||
}
|
||||
if (!res.ok) {
|
||||
listEl.innerHTML = '<tr><td colspan="5" class="empty">加载记录失败</td></tr>';
|
||||
return;
|
||||
}
|
||||
|
||||
const items = await res.json();
|
||||
summaryEl.textContent = `共 ${items.length} 条记录`;
|
||||
renderHistory(items);
|
||||
}
|
||||
|
||||
function renderHistory(items) {
|
||||
if (!items || items.length === 0) {
|
||||
listEl.innerHTML = '<tr><td colspan="5" class="empty">暂无生成记录</td></tr>';
|
||||
return;
|
||||
}
|
||||
|
||||
const origin = window.location.origin;
|
||||
const clientOrigin = getClientImportOrigin();
|
||||
listEl.innerHTML = '';
|
||||
|
||||
items.forEach(item => {
|
||||
const yamlFileParam = encodeURIComponent(item.yamlFile);
|
||||
const jsonFileParam = encodeURIComponent(item.jsonFile);
|
||||
const yamlTokenParam = item.yamlToken ? `&token=${encodeURIComponent(item.yamlToken)}` : '';
|
||||
const jsonTokenParam = item.jsonToken ? `&token=${encodeURIComponent(item.jsonToken)}` : '';
|
||||
const yamlDownloadUrl = `${origin}/api/download?file=${yamlFileParam}${yamlTokenParam}`;
|
||||
const jsonDownloadUrl = `${origin}/api/download?file=${jsonFileParam}${jsonTokenParam}`;
|
||||
const yamlImportProfileUrl = `${clientOrigin}/api/profile?file=${yamlFileParam}${yamlTokenParam}`;
|
||||
const jsonImportProfileUrl = `${clientOrigin}/api/profile?file=${jsonFileParam}${jsonTokenParam}`;
|
||||
const clashImportUrl = `clash://install-config?url=${encodeURIComponent(yamlImportProfileUrl)}&name=${encodeURIComponent('CatMata-' + item.timeStr.replace(/[: ]/g, '-'))}`;
|
||||
const singboxImportUrl = `sing-box://import-remote-profile?url=${encodeURIComponent(jsonImportProfileUrl)}#${encodeURIComponent('CatMata-' + item.timeStr.replace(/[: ]/g, '-'))}`;
|
||||
|
||||
const tr = document.createElement('tr');
|
||||
tr.innerHTML = `
|
||||
<td>${escapeHtml(item.timeStr)}</td>
|
||||
<td>${escapeHtml(item.nodesCount)} 个节点</td>
|
||||
<td>
|
||||
<div class="actions">
|
||||
<a class="btn btn-secondary" href="${yamlDownloadUrl}" target="_blank">YAML</a>
|
||||
<a class="btn btn-secondary" href="${jsonDownloadUrl}" target="_blank">JSON</a>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<div class="actions">
|
||||
<button type="button" class="btn btn-secondary" onclick="copyLinkToClipboard('${yamlImportProfileUrl}')">YAML</button>
|
||||
<button type="button" class="btn btn-secondary" onclick="copyLinkToClipboard('${jsonImportProfileUrl}')">JSON</button>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<div class="actions">
|
||||
<a class="btn btn-green" href="${clashImportUrl}">导入 Clash</a>
|
||||
<a class="btn btn-primary" href="${singboxImportUrl}">导入 Sing-box</a>
|
||||
</div>
|
||||
</td>
|
||||
`;
|
||||
listEl.appendChild(tr);
|
||||
});
|
||||
}
|
||||
|
||||
form.addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
error.textContent = '';
|
||||
button.disabled = true;
|
||||
button.textContent = '正在进入...';
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/login', {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ role: 'viewer', password: input.value })
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
throw new Error(data.error || '密码不正确');
|
||||
}
|
||||
const targetPath = data.redirectTo || '/sub';
|
||||
if (targetPath === '/sub' || targetPath === '/sub/' || targetPath === window.location.pathname) {
|
||||
input.value = '';
|
||||
showHistory();
|
||||
await loadHistory();
|
||||
} else {
|
||||
window.location.href = targetPath;
|
||||
}
|
||||
} catch (e) {
|
||||
error.textContent = e.message;
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
button.textContent = '进入';
|
||||
}
|
||||
});
|
||||
|
||||
(async function init() {
|
||||
await loadAppConfig();
|
||||
updateLatestUrls();
|
||||
if (await checkSession()) {
|
||||
showHistory();
|
||||
await loadHistory();
|
||||
} else {
|
||||
showLogin();
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+451
-25
@@ -2,6 +2,7 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const http = require('http');
|
||||
const crypto = require('crypto');
|
||||
const { execSync, exec } = require('child_process');
|
||||
|
||||
// Auto-install js-yaml if missing
|
||||
@@ -52,6 +53,12 @@ function clashToSingbox(node) {
|
||||
if (node.sni) tls.server_name = node.sni;
|
||||
if (node.hasOwnProperty('skip-cert-verify')) tls.insecure = !!node['skip-cert-verify'];
|
||||
if (node.alpn) tls.alpn = node.alpn;
|
||||
if (node['client-fingerprint']) {
|
||||
tls.utls = {
|
||||
enabled: true,
|
||||
fingerprint: node['client-fingerprint']
|
||||
};
|
||||
}
|
||||
sb.tls = tls;
|
||||
} else if (t === 'vless') {
|
||||
sb.type = 'vless';
|
||||
@@ -108,6 +115,12 @@ function clashToSingbox(node) {
|
||||
if (node.sni) tls.server_name = node.sni;
|
||||
if (node.hasOwnProperty('skip-cert-verify')) tls.insecure = !!node['skip-cert-verify'];
|
||||
if (node.alpn) tls.alpn = node.alpn;
|
||||
if (node['client-fingerprint']) {
|
||||
tls.utls = {
|
||||
enabled: true,
|
||||
fingerprint: node['client-fingerprint']
|
||||
};
|
||||
}
|
||||
sb.tls = tls;
|
||||
} else if (t === 'vmess') {
|
||||
sb.type = 'vmess';
|
||||
@@ -120,6 +133,12 @@ function clashToSingbox(node) {
|
||||
tls.enabled = true;
|
||||
if (node.servername) tls.server_name = node.servername;
|
||||
if (node.hasOwnProperty('skip-cert-verify')) tls.insecure = !!node['skip-cert-verify'];
|
||||
if (node['client-fingerprint']) {
|
||||
tls.utls = {
|
||||
enabled: true,
|
||||
fingerprint: node['client-fingerprint']
|
||||
};
|
||||
}
|
||||
}
|
||||
sb.tls = tls;
|
||||
|
||||
@@ -133,9 +152,34 @@ function clashToSingbox(node) {
|
||||
}
|
||||
} else {
|
||||
sb.type = t;
|
||||
|
||||
// Process generic TLS conversion if any TLS feature is detected
|
||||
const hasTls = node.tls || node.servername || node.sni || node['client-fingerprint'] || node['skip-cert-verify'];
|
||||
if (hasTls) {
|
||||
const tls = { enabled: true };
|
||||
if (node.servername || node.sni) tls.server_name = node.servername || node.sni;
|
||||
if (node.hasOwnProperty('skip-cert-verify')) tls.insecure = !!node['skip-cert-verify'];
|
||||
if (node.alpn) tls.alpn = node.alpn;
|
||||
if (node['client-fingerprint']) {
|
||||
tls.utls = {
|
||||
enabled: true,
|
||||
fingerprint: node['client-fingerprint']
|
||||
};
|
||||
}
|
||||
sb.tls = tls;
|
||||
}
|
||||
|
||||
// Copy other fields but filter out Clash proprietary/incompatible fields
|
||||
const excludeKeys = [
|
||||
'name', 'port', 'type', 'server', 'tls', 'servername', 'sni',
|
||||
'skip-cert-verify', 'client-fingerprint', 'alpn', 'udp',
|
||||
'reality-opts', 'ws-opts', 'grpc-opts', 'h2-opts', 'http-opts',
|
||||
'packet-encoding'
|
||||
];
|
||||
for (const k in node) {
|
||||
if (!['name', 'port', 'type', 'server'].includes(k)) {
|
||||
sb[k] = node[k];
|
||||
if (!excludeKeys.includes(k)) {
|
||||
const newKey = k.replace(/-/g, '_');
|
||||
sb[newKey] = node[k];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -314,6 +358,7 @@ function parseSingboxNodes(content) {
|
||||
const usedNames = new Set();
|
||||
|
||||
function renameNode(node, subName, isClash = true) {
|
||||
const originalName = isClash ? (node.name || node.tag || '') : (node.tag || node.name || '');
|
||||
const typeStr = (node.type || '').toLowerCase();
|
||||
const protoClean = getProtoName(typeStr);
|
||||
const baseName = `${subName}-${protoClean}`;
|
||||
@@ -326,6 +371,7 @@ function renameNode(node, subName, isClash = true) {
|
||||
}
|
||||
|
||||
usedNames.add(newName.toLowerCase());
|
||||
node.proxyName = originalName || newName;
|
||||
|
||||
if (isClash) {
|
||||
node.name = newName;
|
||||
@@ -380,6 +426,12 @@ function detectTemplates() {
|
||||
return { yamlTpl, jsonTpl };
|
||||
}
|
||||
|
||||
function stripUiOnlyNodeFields(node) {
|
||||
const cleanNode = JSON.parse(JSON.stringify(node));
|
||||
delete cleanNode.proxyName;
|
||||
return cleanNode;
|
||||
}
|
||||
|
||||
function replaceNodeRefs(data, oldNodesSet, fallbackNode) {
|
||||
if (data && typeof data === 'object') {
|
||||
if (Array.isArray(data)) {
|
||||
@@ -403,7 +455,17 @@ function replaceNodeRefs(data, oldNodesSet, fallbackNode) {
|
||||
// Configuration paths
|
||||
const subsFile = 'subs.json';
|
||||
const outDir = 'out';
|
||||
const PORT = 3000;
|
||||
const PORT = Number.parseInt(process.env.PORT || '3000', 10);
|
||||
const HOST = process.env.HOST || '0.0.0.0';
|
||||
const PUBLIC_BASE_URL = String(process.env.PUBLIC_BASE_URL || '').trim().replace(/\/+$/, '');
|
||||
const AUTO_OPEN = !['0', 'false', 'no', 'off'].includes(String(process.env.AUTO_OPEN || '1').toLowerCase());
|
||||
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'admin';
|
||||
const VIEWER_PASSWORD = process.env.VIEWER_PASSWORD || 'viewer';
|
||||
const SESSION_SECRET = process.env.SESSION_SECRET || ADMIN_PASSWORD || 'sub2proxy-session-secret';
|
||||
const LINK_TOKEN_SECRET = process.env.LINK_TOKEN_SECRET || SESSION_SECRET;
|
||||
const SESSION_COOKIE = 'sub2proxy_session';
|
||||
const SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
const sessions = new Map();
|
||||
|
||||
// Central configuration generation function
|
||||
function generateConfigs(rawClashNodes, dns = null) {
|
||||
@@ -411,10 +473,11 @@ function generateConfigs(rawClashNodes, dns = null) {
|
||||
if (!fs.existsSync(outDir)) {
|
||||
fs.mkdirSync(outDir, { recursive: true });
|
||||
}
|
||||
const clashNodes = rawClashNodes.map(stripUiOnlyNodeFields);
|
||||
|
||||
// 1. Process Clash Config
|
||||
const clashConfig = yaml.load(fs.readFileSync(yamlTpl, 'utf-8')) || {};
|
||||
clashConfig.proxies = rawClashNodes;
|
||||
clashConfig.proxies = clashNodes;
|
||||
|
||||
if (dns && dns.clash) {
|
||||
clashConfig.dns = yaml.load(dns.clash);
|
||||
@@ -422,7 +485,7 @@ function generateConfigs(rawClashNodes, dns = null) {
|
||||
|
||||
const groupNames = new Set((clashConfig['proxy-groups'] || []).map(g => g.name));
|
||||
const specialNames = new Set(['DIRECT', 'REJECT', 'PASS', 'COMPATIBLE']);
|
||||
const newNodeNames = rawClashNodes.map(n => n.name);
|
||||
const newNodeNames = clashNodes.map(n => n.name);
|
||||
|
||||
for (const group of (clashConfig['proxy-groups'] || [])) {
|
||||
const oldProxies = group.proxies || [];
|
||||
@@ -438,7 +501,7 @@ function generateConfigs(rawClashNodes, dns = null) {
|
||||
|
||||
// 2. Process Sing-box Config
|
||||
const sbConfig = JSON.parse(fs.readFileSync(jsonTpl, 'utf-8')) || {};
|
||||
const allSingboxNodes = rawClashNodes.map(n => {
|
||||
const allSingboxNodes = clashNodes.map(n => {
|
||||
const nodeCopy = JSON.parse(JSON.stringify(n));
|
||||
return clashToSingbox(nodeCopy);
|
||||
});
|
||||
@@ -552,27 +615,283 @@ function readJsonBody(req) {
|
||||
});
|
||||
}
|
||||
|
||||
function sendJson(res, statusCode, payload) {
|
||||
res.writeHead(statusCode, { 'Content-Type': 'application/json; charset=utf-8' });
|
||||
res.end(JSON.stringify(payload));
|
||||
}
|
||||
|
||||
function serveHtml(res, fileName) {
|
||||
const htmlPath = path.join(__dirname, 'public', fileName);
|
||||
if (fs.existsSync(htmlPath)) {
|
||||
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
||||
res.end(fs.readFileSync(htmlPath));
|
||||
} else {
|
||||
res.writeHead(404);
|
||||
res.end(`${fileName} not found`);
|
||||
}
|
||||
}
|
||||
|
||||
function redirect(res, location) {
|
||||
res.writeHead(302, { Location: location });
|
||||
res.end();
|
||||
}
|
||||
|
||||
function parseCookies(req) {
|
||||
const header = req.headers.cookie || '';
|
||||
const cookies = {};
|
||||
header.split(';').forEach(part => {
|
||||
const index = part.indexOf('=');
|
||||
if (index === -1) return;
|
||||
const key = part.slice(0, index).trim();
|
||||
const value = part.slice(index + 1).trim();
|
||||
if (key) {
|
||||
try {
|
||||
cookies[key] = decodeURIComponent(value);
|
||||
} catch (e) {
|
||||
cookies[key] = value;
|
||||
}
|
||||
}
|
||||
});
|
||||
return cookies;
|
||||
}
|
||||
|
||||
function setSessionCookie(res, token) {
|
||||
const maxAge = Math.floor(SESSION_TTL_MS / 1000);
|
||||
res.setHeader('Set-Cookie', `${SESSION_COOKIE}=${encodeURIComponent(token)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}`);
|
||||
}
|
||||
|
||||
function clearSessionCookie(res) {
|
||||
res.setHeader('Set-Cookie', `${SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`);
|
||||
}
|
||||
|
||||
function safeCompare(a, b) {
|
||||
const left = Buffer.from(String(a || ''));
|
||||
const right = Buffer.from(String(b || ''));
|
||||
if (left.length !== right.length) return false;
|
||||
return crypto.timingSafeEqual(left, right);
|
||||
}
|
||||
|
||||
function authenticatePassword(password, requestedRole = 'admin') {
|
||||
if (requestedRole === 'viewer' && safeCompare(password, VIEWER_PASSWORD)) {
|
||||
return 'viewer';
|
||||
}
|
||||
if (safeCompare(password, ADMIN_PASSWORD)) {
|
||||
return 'admin';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function createSession(role) {
|
||||
const token = crypto.randomBytes(32).toString('hex');
|
||||
sessions.set(token, {
|
||||
role,
|
||||
expiresAt: Date.now() + SESSION_TTL_MS
|
||||
});
|
||||
return token;
|
||||
}
|
||||
|
||||
function getSession(req) {
|
||||
const token = parseCookies(req)[SESSION_COOKIE];
|
||||
if (!token) return null;
|
||||
const session = sessions.get(token);
|
||||
if (!session) return null;
|
||||
if (session.expiresAt < Date.now()) {
|
||||
sessions.delete(token);
|
||||
return null;
|
||||
}
|
||||
session.expiresAt = Date.now() + SESSION_TTL_MS;
|
||||
return session;
|
||||
}
|
||||
|
||||
function hasRole(req, roles) {
|
||||
const session = getSession(req);
|
||||
if (!session) return false;
|
||||
if (roles.includes(session.role)) return true;
|
||||
return roles.includes('viewer') && session.role === 'admin';
|
||||
}
|
||||
|
||||
function requireRole(req, res, roles) {
|
||||
if (hasRole(req, roles)) return true;
|
||||
sendJson(res, 401, { error: 'Unauthorized' });
|
||||
return false;
|
||||
}
|
||||
|
||||
function getHistoryList() {
|
||||
const historyJsonPath = path.join(outDir, 'history', 'history.json');
|
||||
if (!fs.existsSync(historyJsonPath)) return [];
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(historyJsonPath, 'utf-8'));
|
||||
} catch (e) {
|
||||
console.error("Failed to parse history.json:", e.message);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function signFileName(fileName) {
|
||||
return crypto.createHmac('sha256', LINK_TOKEN_SECRET).update(fileName).digest('hex');
|
||||
}
|
||||
|
||||
function withFileTokens(historyList) {
|
||||
return historyList.map(item => ({
|
||||
...item,
|
||||
yamlToken: signFileName(item.yamlFile),
|
||||
jsonToken: signFileName(item.jsonFile)
|
||||
}));
|
||||
}
|
||||
|
||||
function hasFileAccess(req, fileName, token) {
|
||||
if (hasRole(req, ['admin', 'viewer'])) return true;
|
||||
return Boolean(token) && safeCompare(token, signFileName(fileName));
|
||||
}
|
||||
|
||||
// HTTP Server setup
|
||||
function startServer() {
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const parsedUrl = new URL(req.url, `http://${req.headers.host}`);
|
||||
const pathname = parsedUrl.pathname;
|
||||
|
||||
// Static Index file
|
||||
if (pathname === '/' || pathname === '/index.html') {
|
||||
const htmlPath = path.join(__dirname, 'public', 'index.html');
|
||||
if (fs.existsSync(htmlPath)) {
|
||||
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
||||
res.end(fs.readFileSync(htmlPath));
|
||||
if (pathname === '/sub/clash/latest' && req.method === 'GET') {
|
||||
const filePath = path.join(outDir, 'CatMata-sub.yaml');
|
||||
if (fs.existsSync(filePath)) {
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'text/yaml; charset=utf-8',
|
||||
'Cache-Control': 'no-store',
|
||||
'Access-Control-Allow-Origin': '*'
|
||||
});
|
||||
res.end(fs.readFileSync(filePath));
|
||||
} else {
|
||||
const history = getHistoryList();
|
||||
if (history.length > 0 && history[0].yamlFile) {
|
||||
const histPath = path.join(outDir, 'history', history[0].yamlFile);
|
||||
if (fs.existsSync(histPath)) {
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'text/yaml; charset=utf-8',
|
||||
'Cache-Control': 'no-store',
|
||||
'Access-Control-Allow-Origin': '*'
|
||||
});
|
||||
res.end(fs.readFileSync(histPath));
|
||||
return;
|
||||
}
|
||||
}
|
||||
res.writeHead(404);
|
||||
res.end('index.html not found');
|
||||
res.end('Latest Clash profile not found');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === '/sub/singbox/latest' && req.method === 'GET') {
|
||||
const filePath = path.join(outDir, 'CatMata-sub.json');
|
||||
if (fs.existsSync(filePath)) {
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
'Cache-Control': 'no-store',
|
||||
'Access-Control-Allow-Origin': '*'
|
||||
});
|
||||
res.end(fs.readFileSync(filePath));
|
||||
} else {
|
||||
const history = getHistoryList();
|
||||
if (history.length > 0 && history[0].jsonFile) {
|
||||
const histPath = path.join(outDir, 'history', history[0].jsonFile);
|
||||
if (fs.existsSync(histPath)) {
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
'Cache-Control': 'no-store',
|
||||
'Access-Control-Allow-Origin': '*'
|
||||
});
|
||||
res.end(fs.readFileSync(histPath));
|
||||
return;
|
||||
}
|
||||
}
|
||||
res.writeHead(404);
|
||||
res.end('Latest Sing-box profile not found');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === '/login' || pathname === '/login.html') {
|
||||
serveHtml(res, 'login.html');
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === '/viewer' || pathname === '/viewer.html') {
|
||||
redirect(res, '/sub');
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === '/sub' || pathname === '/sub/') {
|
||||
serveHtml(res, 'viewer.html');
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === '/' || pathname === '/index.html') {
|
||||
redirect(res, '/config');
|
||||
return;
|
||||
}
|
||||
|
||||
// Static Index file
|
||||
if (pathname === '/config' || pathname === '/config/') {
|
||||
if (!hasRole(req, ['admin'])) {
|
||||
redirect(res, '/login.html');
|
||||
return;
|
||||
}
|
||||
serveHtml(res, 'index.html');
|
||||
return;
|
||||
}
|
||||
|
||||
// API: GET /api/health
|
||||
if (pathname === '/api/health' && req.method === 'GET') {
|
||||
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
||||
res.end(JSON.stringify({ ok: true }));
|
||||
return;
|
||||
}
|
||||
|
||||
// API: GET /api/session
|
||||
if (pathname === '/api/session' && req.method === 'GET') {
|
||||
const session = getSession(req);
|
||||
sendJson(res, 200, { authenticated: Boolean(session), role: session ? session.role : null });
|
||||
return;
|
||||
}
|
||||
|
||||
// API: POST /api/login
|
||||
if (pathname === '/api/login' && req.method === 'POST') {
|
||||
try {
|
||||
const { password, role } = await readJsonBody(req);
|
||||
const nextRole = authenticatePassword(password, role);
|
||||
if (!nextRole) {
|
||||
sendJson(res, 401, { error: '密码不正确' });
|
||||
return;
|
||||
}
|
||||
|
||||
const token = createSession(nextRole);
|
||||
setSessionCookie(res, token);
|
||||
sendJson(res, 200, {
|
||||
success: true,
|
||||
role: nextRole,
|
||||
redirectTo: nextRole === 'admin' ? '/config' : '/sub'
|
||||
});
|
||||
} catch (e) {
|
||||
sendJson(res, 400, { error: e.message });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// API: POST /api/logout
|
||||
if (pathname === '/api/logout' && req.method === 'POST') {
|
||||
clearSessionCookie(res);
|
||||
sendJson(res, 200, { success: true });
|
||||
return;
|
||||
}
|
||||
|
||||
// API: GET /api/app-config
|
||||
if (pathname === '/api/app-config' && req.method === 'GET') {
|
||||
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
||||
res.end(JSON.stringify({ publicBaseUrl: PUBLIC_BASE_URL }));
|
||||
return;
|
||||
}
|
||||
|
||||
// API: GET /api/subs
|
||||
if (pathname === '/api/subs' && req.method === 'GET') {
|
||||
if (!requireRole(req, res, ['admin'])) return;
|
||||
if (fs.existsSync(subsFile)) {
|
||||
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
||||
res.end(fs.readFileSync(subsFile));
|
||||
@@ -585,6 +904,7 @@ function startServer() {
|
||||
|
||||
// API: POST /api/subs
|
||||
if (pathname === '/api/subs' && req.method === 'POST') {
|
||||
if (!requireRole(req, res, ['admin'])) return;
|
||||
try {
|
||||
const payload = await readJsonBody(req);
|
||||
fs.writeFileSync(subsFile, JSON.stringify(payload, null, 2), 'utf-8');
|
||||
@@ -599,6 +919,7 @@ function startServer() {
|
||||
|
||||
// API: GET /api/dns
|
||||
if (pathname === '/api/dns' && req.method === 'GET') {
|
||||
if (!requireRole(req, res, ['admin'])) return;
|
||||
try {
|
||||
const { yamlTpl, jsonTpl } = detectTemplates();
|
||||
const clashConfig = yaml.load(fs.readFileSync(yamlTpl, 'utf-8')) || {};
|
||||
@@ -618,6 +939,7 @@ function startServer() {
|
||||
|
||||
// API: POST /api/fetch (Fetches and converts in-memory)
|
||||
if (pathname === '/api/fetch' && req.method === 'POST') {
|
||||
if (!requireRole(req, res, ['admin'])) return;
|
||||
try {
|
||||
if (!fs.existsSync(subsFile)) {
|
||||
res.writeHead(400);
|
||||
@@ -653,6 +975,7 @@ function startServer() {
|
||||
renameNode(sbNode, subName, false);
|
||||
|
||||
const cNode = singboxToClash(sbNode);
|
||||
cNode.proxyName = sbNode.proxyName || cNode.name;
|
||||
allClashNodes.push(cNode);
|
||||
}
|
||||
}
|
||||
@@ -669,6 +992,7 @@ function startServer() {
|
||||
|
||||
// API: POST /api/generate (Generates and writes configurations)
|
||||
if (pathname === '/api/generate' && req.method === 'POST') {
|
||||
if (!requireRole(req, res, ['admin'])) return;
|
||||
try {
|
||||
const { proxies: rawClashNodes, dns } = await readJsonBody(req);
|
||||
if (!rawClashNodes || !Array.isArray(rawClashNodes) || rawClashNodes.length === 0) {
|
||||
@@ -690,20 +1014,15 @@ function startServer() {
|
||||
|
||||
// API: GET /api/history
|
||||
if (pathname === '/api/history' && req.method === 'GET') {
|
||||
const historyJsonPath = path.join(outDir, 'history', 'history.json');
|
||||
if (fs.existsSync(historyJsonPath)) {
|
||||
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
||||
res.end(fs.readFileSync(historyJsonPath));
|
||||
} else {
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end(JSON.stringify([]));
|
||||
}
|
||||
if (!requireRole(req, res, ['admin', 'viewer'])) return;
|
||||
sendJson(res, 200, withFileTokens(getHistoryList()));
|
||||
return;
|
||||
}
|
||||
|
||||
// API: GET /api/download
|
||||
if (pathname === '/api/download' && req.method === 'GET') {
|
||||
const fileName = parsedUrl.searchParams.get('file');
|
||||
const token = parsedUrl.searchParams.get('token');
|
||||
if (!fileName) {
|
||||
res.writeHead(400);
|
||||
res.end('Missing file parameter');
|
||||
@@ -718,6 +1037,12 @@ function startServer() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!hasFileAccess(req, fileName, token)) {
|
||||
res.writeHead(401);
|
||||
res.end('Unauthorized');
|
||||
return;
|
||||
}
|
||||
|
||||
const filePath = path.join(outDir, 'history', fileName);
|
||||
if (fs.existsSync(filePath)) {
|
||||
const isYaml = fileName.endsWith('.yaml');
|
||||
@@ -733,15 +1058,116 @@ function startServer() {
|
||||
return;
|
||||
}
|
||||
|
||||
// API: GET /api/profile
|
||||
// Remote import clients should receive the profile body directly, not as a browser attachment.
|
||||
if (pathname === '/api/profile' && req.method === 'GET') {
|
||||
const fileName = parsedUrl.searchParams.get('file');
|
||||
const token = parsedUrl.searchParams.get('token');
|
||||
if (!fileName) {
|
||||
res.writeHead(400);
|
||||
res.end('Missing file parameter');
|
||||
return;
|
||||
}
|
||||
|
||||
const safeRegex = /^CatMata-sub-\d{8}-\d{6}\.(yaml|json)$/;
|
||||
if (!safeRegex.test(fileName)) {
|
||||
res.writeHead(400);
|
||||
res.end('Invalid file name');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!hasFileAccess(req, fileName, token)) {
|
||||
res.writeHead(401);
|
||||
res.end('Unauthorized');
|
||||
return;
|
||||
}
|
||||
|
||||
const filePath = path.join(outDir, 'history', fileName);
|
||||
if (fs.existsSync(filePath)) {
|
||||
const isYaml = fileName.endsWith('.yaml');
|
||||
res.writeHead(200, {
|
||||
'Content-Type': isYaml ? 'text/yaml; charset=utf-8' : 'application/json; charset=utf-8',
|
||||
'Cache-Control': 'no-store',
|
||||
'Access-Control-Allow-Origin': '*'
|
||||
});
|
||||
res.end(fs.readFileSync(filePath));
|
||||
} else {
|
||||
res.writeHead(404);
|
||||
res.end('File not found');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// API: POST /api/history/delete
|
||||
if (pathname === '/api/history/delete' && req.method === 'POST') {
|
||||
if (!requireRole(req, res, ['admin'])) return;
|
||||
try {
|
||||
const { yamlFile, jsonFile } = await readJsonBody(req);
|
||||
if (!yamlFile || !jsonFile) {
|
||||
res.writeHead(400);
|
||||
res.end('Missing yamlFile or jsonFile parameter');
|
||||
return;
|
||||
}
|
||||
|
||||
// Security check: prevent directory traversal
|
||||
const safeRegex = /^CatMata-sub-\d{8}-\d{6}\.(yaml|json)$/;
|
||||
if (!safeRegex.test(yamlFile) || !safeRegex.test(jsonFile)) {
|
||||
res.writeHead(400);
|
||||
res.end('Invalid file name');
|
||||
return;
|
||||
}
|
||||
|
||||
const historyDir = path.join(outDir, 'history');
|
||||
const yamlPath = path.join(historyDir, yamlFile);
|
||||
const jsonPath = path.join(historyDir, jsonFile);
|
||||
|
||||
// Delete physical files
|
||||
if (fs.existsSync(yamlPath)) {
|
||||
fs.unlinkSync(yamlPath);
|
||||
}
|
||||
if (fs.existsSync(jsonPath)) {
|
||||
fs.unlinkSync(jsonPath);
|
||||
}
|
||||
|
||||
// Update history.json
|
||||
const historyJsonPath = path.join(historyDir, 'history.json');
|
||||
let historyList = [];
|
||||
if (fs.existsSync(historyJsonPath)) {
|
||||
try {
|
||||
historyList = JSON.parse(fs.readFileSync(historyJsonPath, 'utf-8'));
|
||||
} catch (e) {
|
||||
console.error("Failed to parse history.json, resetting:", e.message);
|
||||
}
|
||||
}
|
||||
|
||||
historyList = historyList.filter(item => item.yamlFile !== yamlFile || item.jsonFile !== jsonFile);
|
||||
|
||||
fs.writeFileSync(historyJsonPath, JSON.stringify(historyList, null, 2), 'utf-8');
|
||||
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end(JSON.stringify({ success: true }));
|
||||
} catch (e) {
|
||||
res.writeHead(500);
|
||||
res.end(e.message);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
res.writeHead(404);
|
||||
res.end('Not Found');
|
||||
});
|
||||
|
||||
server.listen(PORT, () => {
|
||||
server.listen(PORT, HOST, () => {
|
||||
const displayHost = HOST === '0.0.0.0' || HOST === '::' ? 'localhost' : HOST;
|
||||
console.log(`CatMata Sub2Proxy 控制面板已启动!`);
|
||||
console.log(`本地访问地址: http://localhost:${PORT}`);
|
||||
console.log(`正在自动打开默认浏览器...`);
|
||||
openBrowser(`http://localhost:${PORT}`);
|
||||
console.log(`访问地址: http://${displayHost}:${PORT}`);
|
||||
if (PUBLIC_BASE_URL) {
|
||||
console.log(`客户端导入地址基准: ${PUBLIC_BASE_URL}`);
|
||||
}
|
||||
if (AUTO_OPEN) {
|
||||
console.log(`正在自动打开默认浏览器...`);
|
||||
openBrowser(`http://localhost:${PORT}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -570,7 +570,7 @@
|
||||
"experimental": {
|
||||
"cache_file": {
|
||||
"enabled": true,
|
||||
"store_dns": true
|
||||
"store_fakeip": true
|
||||
},
|
||||
"clash_api": {
|
||||
"external_controller": "127.0.0.1:9090",
|
||||
|
||||
Reference in New Issue
Block a user