Add files via upload

This commit is contained in:
wcwq98 2025-01-05 15:03:47 +08:00 committed by GitHub
parent 96d693fa93
commit 061c4cb568
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 449 additions and 345 deletions

View File

@ -10,12 +10,16 @@ require (
github.com/cloudwego/base64x v0.1.4 // indirect github.com/cloudwego/base64x v0.1.4 // indirect
github.com/cloudwego/iasm v0.2.0 // indirect github.com/cloudwego/iasm v0.2.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/gin-contrib/sessions v1.0.2 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect github.com/gin-contrib/sse v0.1.0 // indirect
github.com/gin-gonic/gin v1.10.0 // indirect github.com/gin-gonic/gin v1.10.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.20.0 // indirect github.com/go-playground/validator/v10 v10.20.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect github.com/goccy/go-json v0.10.2 // indirect
github.com/gorilla/context v1.1.2 // indirect
github.com/gorilla/securecookie v1.1.2 // indirect
github.com/gorilla/sessions v1.2.2 // indirect
github.com/json-iterator/go v1.1.12 // indirect github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect github.com/klauspost/cpuid/v2 v2.2.7 // indirect
github.com/leodido/go-urn v1.4.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect
@ -26,10 +30,10 @@ require (
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect github.com/ugorji/go/codec v1.2.12 // indirect
golang.org/x/arch v0.8.0 // indirect golang.org/x/arch v0.8.0 // indirect
golang.org/x/crypto v0.23.0 // indirect golang.org/x/crypto v0.31.0 // indirect
golang.org/x/net v0.25.0 // indirect golang.org/x/net v0.33.0 // indirect
golang.org/x/sys v0.20.0 // indirect golang.org/x/sys v0.28.0 // indirect
golang.org/x/text v0.15.0 // indirect golang.org/x/text v0.21.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect google.golang.org/protobuf v1.34.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect
) )

View File

@ -12,6 +12,8 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0= github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk= github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
github.com/gin-contrib/sessions v1.0.2 h1:UaIjUvTH1cMeOdj3in6dl+Xb6It8RiKRF9Z1anbUyCA=
github.com/gin-contrib/sessions v1.0.2/go.mod h1:KxKxWqWP5LJVDCInulOl4WbLzK2KSPlLesfZ66wRvMs=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU= github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
@ -25,6 +27,12 @@ github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaC
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/gorilla/context v1.1.2 h1:WRkNAv2uoa03QNIc1A6u4O7DAGMUVoopZhkiXWA2V1o=
github.com/gorilla/context v1.1.2/go.mod h1:KDPwT9i/MeWHiLl90fuTgrt4/wPcv75vFAZLaOOcbxM=
github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=
github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
github.com/gorilla/sessions v1.2.2 h1:lqzMYz6bOfvn2WriPUjNByzeXIlVzURcPmgMczkmTjY=
github.com/gorilla/sessions v1.2.2/go.mod h1:ePLdVu+jbEgHH+KWw8I1z2wqd0BAdAQh/8LRvBeoNcQ=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
@ -63,14 +71,22 @@ golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI= golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac= golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk= golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg= google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=

View File

@ -171,7 +171,7 @@ func main() {
session := sessions.Default(c) session := sessions.Default(c)
session.Set("user", true) session.Set("user", true)
session.Options(sessions.Options{ session.Options(sessions.Options{
MaxAge: 3600 * 24, // 24小时 MaxAge: 3600 * 2, // 2小时
}) })
if err := session.Save(); err != nil { if err := session.Save(); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Session保存失败"}) c.JSON(http.StatusInternalServerError, gin.H{"error": "Session保存失败"})
@ -266,7 +266,15 @@ func main() {
c.JSON(200, gin.H{"message": "服务停止成功"}) c.JSON(200, gin.H{"message": "服务停止成功"})
}) })
authorized.POST("/restart_service", func(c *gin.Context) {
cmd := exec.Command("systemctl", "restart", "realm")
if err := cmd.Run(); err != nil {
c.JSON(500, gin.H{"error": "服务重启失败"})
return
}
c.JSON(200, gin.H{"message": "服务重启成功"})
})
authorized.GET("/check_status", func(c *gin.Context) { authorized.GET("/check_status", func(c *gin.Context) {
cmd := exec.Command("systemctl", "is-active", "--quiet", "realm") cmd := exec.Command("systemctl", "is-active", "--quiet", "realm")
err := cmd.Run() err := cmd.Run()

View File

@ -2,71 +2,147 @@ document.addEventListener('DOMContentLoaded', () => {
const outputDiv = document.getElementById('output'); const outputDiv = document.getElementById('output');
const startButton = document.getElementById('startButton'); const startButton = document.getElementById('startButton');
const stopButton = document.getElementById('stopButton'); const stopButton = document.getElementById('stopButton');
const restartButton = document.getElementById('restartButton');
const addRuleButton = document.getElementById('addRuleButton'); const addRuleButton = document.getElementById('addRuleButton');
const addBatchRulesButton = document.getElementById('addBatchRulesButton');
const logoutButton = document.getElementById('logoutButton');
const localPortInput = document.getElementById('localPort'); const localPortInput = document.getElementById('localPort');
const remoteIPInput = document.getElementById('remoteIP'); const remoteIPInput = document.getElementById('remoteIP');
const remotePortInput = document.getElementById('remotePort'); const remotePortInput = document.getElementById('remotePort');
const rulesInput = document.getElementById('rulesInput');
async function fetchForwardingRules() { // 更新服务状态
async function updateServiceStatus() {
try { try {
const response = await fetch('/get_rules'); const response = await fetch('/check_status');
if (!response.ok) { if (!response.ok) {
throw new Error('获取规则失败:' + response.statusText); throw new Error('检查状态失败:' + response.statusText);
}
const data = await response.json();
const statusElement = document.getElementById('serviceStatus');
if (data.status === "启用") {
statusElement.textContent = "运行中";
statusElement.className = 'status-tag running';
} else {
statusElement.textContent = "已停止";
statusElement.className = 'status-tag stopped';
} }
const rules = await response.json();
const tbody = document.querySelector('#forwardingTable tbody');
tbody.innerHTML = '';
rules.forEach((rule, index) => {
const [, localPort] = rule.Listen.split(':');
const lastColonIndex = rule.Remote.lastIndexOf(':');
const remoteIP = rule.Remote.substring(0, lastColonIndex);
const remotePort = rule.Remote.substring(lastColonIndex + 1);
const row = document.createElement('tr');
row.innerHTML = `
<td>${index + 1}</td>
<td>${localPort}</td>
<td>${remoteIP}</td>
<td>${remotePort}</td>
<td><button data-listen="${rule.Listen}" class="delete-btn">删除</button></td>
`;
tbody.appendChild(row);
});
// 为删除按钮添加事件监听
const deleteButtons = document.querySelectorAll('.delete-btn');
deleteButtons.forEach(button => {
button.addEventListener('click', function() {
const listenAddress = this.getAttribute('data-listen');
deleteRule(listenAddress);
});
});
} catch (error) { } catch (error) {
console.error('请求失败:', error); console.error('状态检查失败:', error);
outputDiv.textContent = '获取转发规则失败'; const statusElement = document.getElementById('serviceStatus');
statusElement.textContent = "未知";
statusElement.className = 'status-tag stopped';
} }
} }
// 获取转发规则
async function fetchForwardingRules() {
try {
const response = await fetch('/get_rules', {
method: 'GET',
headers: {
'Cache-Control': 'no-cache',
'Pragma': 'no-cache'
},
});
if (!response.ok) {
throw new Error('获取规则失败:' + response.statusText);
}
const rules = await response.json();
const tbody = document.querySelector('#forwardingTable tbody');
tbody.innerHTML = '';
// 创建当前规则的端口占用列表
const usedPorts = new Set();
if (!Array.isArray(rules)) {
throw new Error('服务器返回的数据格式不正确');
}
rules.forEach(rule => {
// 检查规则格式并统一属性名
const listen = rule.Listen || rule.listen;
const remote = rule.Remote || rule.remote;
if (!listen || !remote) {
console.error('规则格式错误:', rule);
return;
}
const localPort = listen.split(':')[1];
usedPorts.add(localPort);
const lastColonIndex = remote.lastIndexOf(':');
const remoteIP = remote.substring(0, lastColonIndex);
const remotePort = remote.substring(lastColonIndex + 1);
const row = document.createElement('tr');
row.innerHTML = `
<td>${tbody.children.length + 1}</td>
<td>${localPort}</td>
<td>${remoteIP}</td>
<td>${remotePort}</td>
<td><button class="delete-btn" data-listen="${listen}">删除</button></td>
`;
tbody.appendChild(row);
});
// 为删除按钮添加事件监听
document.querySelectorAll('.delete-btn').forEach(button => {
button.addEventListener('click', function() {
deleteRule(this.getAttribute('data-listen'));
});
});
return usedPorts;
} catch (error) {
console.error('获取规则失败:', error);
outputDiv.textContent = `获取转发规则失败: ${error.message}`;
// 添加更详细的错误信息输出
if (error.response) {
console.error('Response status:', error.response.status);
console.error('Response text:', await error.response.text());
}
return new Set();
}
}
// 删除规则
async function deleteRule(listenAddress) { async function deleteRule(listenAddress) {
try { try {
const response = await fetch(`/delete_rule?listen=${encodeURIComponent(listenAddress)}`, { const response = await fetch(`/delete_rule?listen=${encodeURIComponent(listenAddress)}`, {
method: 'DELETE' method: 'DELETE'
}); });
if (!response.ok) { if (!response.ok) {
throw new Error('删除规则失败:' + response.statusText); throw new Error('删除规则失败:' + response.statusText);
} }
fetchForwardingRules(); // 重新获取规则列表
// 删除成功后重启服务
const restartResponse = await fetch('/restart_service', {
method: 'POST'
});
if (!restartResponse.ok) {
throw new Error('重启服务失败:' + restartResponse.statusText);
}
outputDiv.textContent = '规则已删除,服务已重启';
await fetchForwardingRules();
await updateServiceStatus();
} catch (error) { } catch (error) {
console.error('删除规则失败:', error); console.error('删除失败:', error);
outputDiv.textContent = '删除规则失败'; outputDiv.textContent = error.message;
} }
} }
// 添加单个规则
async function addRule() { async function addRule() {
const localPort = localPortInput.value; const localPort = localPortInput.value.trim();
const remoteIP = remoteIPInput.value; const remoteIP = remoteIPInput.value.trim();
const remotePort = remotePortInput.value; const remotePort = remotePortInput.value.trim();
if (!localPort || !remoteIP || !remotePort) { if (!localPort || !remoteIP || !remotePort) {
outputDiv.textContent = '请填写所有字段'; outputDiv.textContent = '请填写所有字段';
@ -74,27 +150,123 @@ document.addEventListener('DOMContentLoaded', () => {
} }
try { try {
const usedPorts = await fetchForwardingRules();
if (usedPorts.has(localPort)) {
outputDiv.textContent = `端口 ${localPort} 已被占用`;
return;
}
const response = await fetch('/add_rule', { const response = await fetch('/add_rule', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
body: JSON.stringify({ body: JSON.stringify({
localPort, listen: `0.0.0.0:${localPort}`,
remoteIP, remote: `${remoteIP}:${remotePort}`
remotePort
}) })
}); });
if (!response.ok) { if (!response.ok) {
throw new Error('添加规则失败:' + response.statusText); throw new Error('添加规则失败:' + response.statusText);
} }
fetchForwardingRules(); // 重新获取规则列表
// 添加成功后重启服务
const restartResponse = await fetch('/restart_service', {
method: 'POST'
});
if (!restartResponse.ok) {
throw new Error('重启服务失败:' + restartResponse.statusText);
}
outputDiv.textContent = '规则添加成功,服务已重启';
localPortInput.value = '';
remoteIPInput.value = '';
remotePortInput.value = '';
await fetchForwardingRules();
await updateServiceStatus();
} catch (error) { } catch (error) {
console.error('添加规则失败:', error); console.error('添加失败:', error);
outputDiv.textContent = '添加规则失败'; outputDiv.textContent = error.message;
} }
} }
// 批量添加规则
async function addBatchRules() {
const rules = rulesInput.value.trim().split('\n').filter(Boolean);
if (rules.length === 0) {
outputDiv.textContent = '请输入要添加的规则';
return;
}
const usedPorts = await fetchForwardingRules();
const failedRules = [];
let hasSuccess = false;
for (const rule of rules) {
const match = rule.match(/^(\d+):(\[.*?\]:\d+|\S+)$/);
if (!match) {
failedRules.push(`格式错误: ${rule}`);
continue;
}
const localPort = match[1];
const remoteAddress = match[2];
if (usedPorts.has(localPort)) {
failedRules.push(`端口 ${localPort} 已被占用`);
continue;
}
try {
const response = await fetch('/add_rule', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
listen: `0.0.0.0:${localPort}`,
remote: remoteAddress
})
});
if (!response.ok) {
failedRules.push(`添加失败: ${rule}`);
continue;
}
usedPorts.add(localPort);
hasSuccess = true;
} catch (error) {
failedRules.push(`添加失败: ${rule} - ${error.message}`);
}
}
if (hasSuccess) {
try {
const restartResponse = await fetch('/restart_service', {
method: 'POST'
});
if (!restartResponse.ok) {
throw new Error('重启服务失败');
}
} catch (error) {
failedRules.push('服务重启失败');
}
}
rulesInput.value = '';
await fetchForwardingRules();
await updateServiceStatus();
if (failedRules.length > 0) {
outputDiv.textContent = `添加完成。\n失败的规则:\n${failedRules.join('\n')}`;
} else {
outputDiv.textContent = '所有规则添加成功,服务已重启';
}
}
// 事件监听器
startButton.addEventListener('click', async () => { startButton.addEventListener('click', async () => {
try { try {
const response = await fetch('/start_service', { const response = await fetch('/start_service', {
@ -103,11 +275,11 @@ document.addEventListener('DOMContentLoaded', () => {
if (!response.ok) { if (!response.ok) {
throw new Error('启动服务失败:' + response.statusText); throw new Error('启动服务失败:' + response.statusText);
} }
const result = await response.json(); outputDiv.textContent = '服务启动成功';
outputDiv.textContent = result.output; await updateServiceStatus();
} catch (error) { } catch (error) {
console.error('启动服务失败:', error); console.error('启动失败:', error);
outputDiv.textContent = '启动服务失败'; outputDiv.textContent = error.message;
} }
}); });
@ -119,16 +291,53 @@ document.addEventListener('DOMContentLoaded', () => {
if (!response.ok) { if (!response.ok) {
throw new Error('停止服务失败:' + response.statusText); throw new Error('停止服务失败:' + response.statusText);
} }
const result = await response.json(); outputDiv.textContent = '服务停止成功';
outputDiv.textContent = result.output; await updateServiceStatus();
} catch (error) { } catch (error) {
console.error('停止服务失败:', error); console.error('停止失败:', error);
outputDiv.textContent = '停止服务失败'; outputDiv.textContent = error.message;
}
});
restartButton.addEventListener('click', async () => {
try {
const response = await fetch('/restart_service', {
method: 'POST'
});
if (!response.ok) {
throw new Error('重启服务失败:' + response.statusText);
}
outputDiv.textContent = '服务重启成功';
await updateServiceStatus();
} catch (error) {
console.error('重启失败:', error);
outputDiv.textContent = error.message;
}
});
logoutButton.addEventListener('click', async () => {
try {
const response = await fetch('/logout', {
method: 'POST'
});
if (response.ok) {
window.location.href = '/login';
} else {
throw new Error('登出失败:' + response.statusText);
}
} catch (error) {
console.error('登出失败:', error);
outputDiv.textContent = error.message;
} }
}); });
addRuleButton.addEventListener('click', addRule); addRuleButton.addEventListener('click', addRule);
addBatchRulesButton.addEventListener('click', addBatchRules);
// 初始化时获取规则列表 // 初始化
fetchForwardingRules(); fetchForwardingRules();
}); updateServiceStatus();
// 定期更新服务状态
setInterval(updateServiceStatus, 15000);
});

View File

@ -36,6 +36,12 @@
button:hover { button:hover {
background-color: #218838; background-color: #218838;
} }
.delete-btn {
background-color: #dc3545;
}
.delete-btn:hover {
background-color: #c82333;
}
table { table {
width: 100%; width: 100%;
border-collapse: collapse; border-collapse: collapse;
@ -56,7 +62,7 @@
display: block; display: block;
margin-bottom: 5px; margin-bottom: 5px;
} }
.form-group input { .form-group input, .form-group textarea {
width: calc(100% - 22px); width: calc(100% - 22px);
padding: 10px; padding: 10px;
border: 1px solid #ccc; border: 1px solid #ccc;
@ -64,12 +70,12 @@
} }
#output { #output {
margin-top: 20px; margin-top: 20px;
background-color: #fff; background-color: #f8f9fa;
padding: 10px; padding: 10px;
border: 1px solid #ccc; border: 1px solid #ccc;
border-radius: 5px; border-radius: 5px;
min-height: 50px; min-height: 50px;
white-space: pre-wrap; /* 保持空格和换行 */ white-space: pre-wrap;
} }
.status-tag { .status-tag {
display: inline-flex; display: inline-flex;
@ -81,292 +87,94 @@
margin-left: 10px; margin-left: 10px;
font-weight: 500; font-weight: 500;
} }
.status-tag.running { .status-tag.running {
background-color: #52c41a; background-color: #52c41a;
color: white; color: white;
} }
.status-tag.stopped { .status-tag.stopped {
background-color: #ff4d4f; background-color: #ff4d4f;
color: white; color: white;
} }
.status-wrapper { .status-wrapper {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
margin-left: 15px; margin-left: 15px;
} }
.status-label { .status-label {
color: #666; color: #666;
margin-right: 8px; margin-right: 8px;
} }
.button-group { .button-group {
display: flex; display: flex;
align-items: center; align-items: center;
margin-bottom: 20px; margin-bottom: 20px;
} }
#logoutButton {
background-color: #6c757d;
}
#logoutButton:hover {
background-color: #5a6268;
}
</style> </style>
</head> </head>
<body> <body>
<div class="container">
<h1>Realm 转发管理面板</h1>
<div class="container"> <div class="button-group">
<h1>Realm 转发管理面板</h1> <button id="startButton">启动服务</button>
<button id="stopButton">停止服务</button>
<div class="button-group"> <button id="restartButton">重启服务</button>
<button id="startButton">启动服务</button> <button id="logoutButton">登出</button>
<button id="stopButton">停止服务</button> <div class="status-wrapper">
<button id="logoutButton">登出</button> <span class="status-label">状态:</span>
<div class="status-wrapper"> <span id="serviceStatus" class="status-tag">检查中...</span>
<span class="status-label">状态:</span> </div>
<span id="serviceStatus" class="status-tag">检查中...</span>
</div> </div>
<div id="output"></div>
<h2>当前转发规则</h2>
<table id="forwardingTable">
<thead>
<tr>
<th>序号</th>
<th>中转端口</th>
<th>落地机 IP</th>
<th>目标端口</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<!-- 动态填充转发规则 -->
</tbody>
</table>
<h2>添加转发规则</h2>
<div class="form-group">
<label for="localPort">中转端口:</label>
<input type="number" id="localPort" required>
</div>
<div class="form-group">
<label for="remoteIP">落地机 IP:</label>
<input type="text" id="remoteIP" required>
</div>
<div class="form-group">
<label for="remotePort">目标端口:</label>
<input type="number" id="remotePort" required>
</div>
<button id="addRuleButton">添加规则</button>
<h2>批量添加转发规则</h2>
<div class="form-group">
<label for="rulesInput">请输入转发规则(每行一个规则):</label>
<p>IPv4 格式:中转端口:落地机IP:目标端口</p>
<p>IPv6 格式:中转端口:[落地机IPv6]:目标端口</p>
<textarea id="rulesInput" rows="5"></textarea>
</div>
<button id="addBatchRulesButton">批量添加规则</button>
</div> </div>
<div id="output"></div> <script src="/static/app.js"></script>
<h2>当前转发规则</h2>
<table id="forwardingTable">
<thead>
<tr>
<th>序号</th>
<th>中转端口</th>
<th>落地鸡 IP</th>
<th>目标端口</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<!-- 动态填充转发规则 -->
</tbody>
</table>
<h2>添加转发规则</h2>
<div class="form-group">
<label for="localPort">中转端口:</label>
<input type="number" id="localPort" required>
</div>
<div class="form-group">
<label for="remoteIP">落地鸡 IP:</label>
<input type="text" id="remoteIP" required>
</div>
<div class="form-group">
<label for="remotePort">目标端口:</label>
<input type="number" id="remotePort" required>
</div>
<button id="addRuleButton">添加规则</button>
</div>
<script>
async function updateServiceStatus() {
try {
const response = await fetch(`/check_status`, {
method: 'GET'
});
if (!response.ok) {
throw new Error('检查状态失败:' + response.statusText);
}
const data = await response.json();
const statusElement = document.getElementById('serviceStatus');
if (data.status === "启用") {
statusElement.textContent = "运行中";
statusElement.className = 'status-tag running';
} else {
statusElement.textContent = "已停止";
statusElement.className = 'status-tag stopped';
}
} catch (error) {
console.error('更新状态失败:', error);
document.getElementById('serviceStatus').textContent = '未知';
document.getElementById('serviceStatus').className = 'status-tag stopped';
}
}
// 启动服务
document.getElementById('startButton').onclick = async function() {
try {
const response = await fetch(`/start_service`, {
method: 'POST'
});
if (!response.ok) {
throw new Error('启动服务失败:' + response.statusText);
}
const data = await response.json();
document.getElementById('output').innerText = data.message || '服务启动成功';
await updateServiceStatus();
} catch (error) {
console.error('启动服务失败:', error);
document.getElementById('output').innerText = error.message;
}
};
// 停止服务
document.getElementById('stopButton').onclick = async function() {
try {
const response = await fetch(`/stop_service`, {
method: 'POST'
});
if (!response.ok) {
throw new Error('停止服务失败:' + response.statusText);
}
const data = await response.json();
document.getElementById('output').innerText = data.message || '服务停止成功';
await updateServiceStatus();
} catch (error) {
console.error('停止服务失败:', error);
document.getElementById('output').innerText = error.message;
}
};
// 添加转发规则
document.getElementById('addRuleButton').onclick = async function() {
const localPort = document.getElementById('localPort').value;
const remoteIP = document.getElementById('remoteIP').value;
const remotePort = document.getElementById('remotePort').value;
try {
const response = await fetch(`/add_rule`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
listen: `0.0.0.0:${localPort}`,
remote: `${remoteIP}:${remotePort}`
}),
});
if (!response.ok) {
throw new Error('添加规则失败:' + response.statusText);
}
alert('转发规则添加成功!');
await fetchForwardingRules(); // 刷新规则列表
} catch (error) {
console.error('添加规则失败:', error);
alert('添加规则失败:' + error.message);
}
};
// 删除转发规则
async function deleteRule(listenAddress) {
try {
const response = await fetch(`/delete_rule?listen=${encodeURIComponent(listenAddress)}`, {
method: 'DELETE'
});
if (!response.ok) {
throw new Error('删除规则失败:' + response.statusText);
}
alert('转发规则删除成功!');
await fetchForwardingRules(); // 刷新规则列表
} catch (error) {
console.error('删除规则失败:', error);
alert('删除规则失败:' + error.message);
}
}
// 获取当前转发规则
async function fetchForwardingRules() {
try {
const response = await fetch(`/get_rules`);
if (!response.ok) {
throw new Error('获取规则失败:' + response.statusText);
}
const rules = await response.json();
const tbody = document.querySelector('#forwardingTable tbody');
tbody.innerHTML = ''; // 清空现有规则
rules.forEach((rule, index) => {
const row = document.createElement('tr');
let localPort = '', remoteIP = '', remotePort = '';
// 处理本地端口
if (rule.listen) { // 改为小写 listen
[, localPort] = rule.listen.split(':');
}
// 处理远程地址和端口
if (rule.remote) { // 改为小写 remote
// 检查是否是IPv6地址
if (rule.remote.includes('[')) {
// IPv6格式: [2001:db8::1]:80
const matches = rule.remote.match(/\[(.*)\]:(.*)$/);
if (matches) {
remoteIP = matches[1];
remotePort = matches[2];
}
} else if (rule.remote.includes(':')) {
// 检查冒号的数量来判断是IPv6还是IPv4
const colonCount = (rule.remote.match(/:/g) || []).length;
if (colonCount > 1) {
// IPv6地址没有方括号的情况
const lastColon = rule.remote.lastIndexOf(':');
remoteIP = rule.remote.substring(0, lastColon);
remotePort = rule.remote.substring(lastColon + 1);
} else {
// IPv4地址
[remoteIP, remotePort] = rule.remote.split(':');
}
}
}
row.innerHTML = `
<td>${index + 1}</td>
<td>${localPort || 'N/A'}</td>
<td>${remoteIP || 'N/A'}</td>
<td>${remotePort || 'N/A'}</td>
<td><button onclick="deleteRule('${rule.listen || ''}')">删除</button></td>
`;
tbody.appendChild(row);
});
} catch (error) {
console.error('获取转发规则失败:', error);
alert('获取转发规则失败:' + error.message);
}
}
// 页面加载时获取转发规则和服务状态
window.onload = async function() {
await fetchForwardingRules();
await updateServiceStatus();
// 每10秒更新一次状态
setInterval(updateServiceStatus, 10000);
};
// 登出功能
document.getElementById('logoutButton').onclick = async function() {
try {
const response = await fetch('/logout', {
method: 'POST'
});
if (!response.ok) {
throw new Error('登出失败:' + response.statusText);
}
// 登出成功,重定向到登录页面
window.location.href = '/login';
} catch (error) {
console.error('登出失败:', error);
alert('登出失败:' + error.message);
}
};
</script>
</body> </body>
</html> </html>

View File

@ -38,10 +38,11 @@
} }
.form-group input { .form-group input {
width: 100%; width: 100%;
padding: 10px; padding: 12px;
border: 1px solid #ddd; border: 1px solid #ddd;
border-radius: 4px; border-radius: 4px;
box-sizing: border-box; box-sizing: border-box;
font-size: 16px;
} }
.password-input-wrapper { .password-input-wrapper {
position: relative; position: relative;
@ -55,6 +56,8 @@
border: none; border: none;
cursor: pointer; cursor: pointer;
color: #666; color: #666;
padding: 5px;
font-size: 20px;
} }
button[type="submit"] { button[type="submit"] {
width: 100%; width: 100%;
@ -65,14 +68,35 @@
border-radius: 4px; border-radius: 4px;
cursor: pointer; cursor: pointer;
font-size: 16px; font-size: 16px;
transition: background-color 0.3s;
} }
button[type="submit"]:hover { button[type="submit"]:hover {
background-color: #218838; background-color: #218838;
} }
.error-message { .error-message {
color: #dc3545; color: #dc3545;
margin-top: 10px; margin-top: 15px;
text-align: center; text-align: center;
min-height: 20px;
font-size: 14px;
}
.loading {
opacity: 0.7;
cursor: not-allowed;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.loading-spinner {
display: none;
width: 20px;
height: 20px;
border: 3px solid #f3f3f3;
border-top: 3px solid #28a745;
border-radius: 50%;
animation: spin 1s linear infinite;
margin: 10px auto;
} }
</style> </style>
</head> </head>
@ -82,30 +106,50 @@
<form id="loginForm"> <form id="loginForm">
<div class="form-group"> <div class="form-group">
<div class="password-input-wrapper"> <div class="password-input-wrapper">
<input type="password" id="password" placeholder="请输入密码" required> <input
<button type="button" class="password-toggle" id="togglePassword">👁</button> type="password"
id="password"
placeholder="请输入密码"
required
autocomplete="current-password"
minlength="4"
>
<button
type="button"
class="password-toggle"
id="togglePassword"
aria-label="切换密码显示"
>👁</button>
</div> </div>
</div> </div>
<button type="submit">登录</button> <button type="submit" id="submitButton">登录</button>
<div class="loading-spinner" id="loadingSpinner"></div>
<div id="errorMessage" class="error-message"></div> <div id="errorMessage" class="error-message"></div>
</form> </form>
</div> </div>
<script> <script>
document.getElementById('togglePassword').addEventListener('click', function() { const form = document.getElementById('loginForm');
const passwordInput = document.getElementById('password'); const passwordInput = document.getElementById('password');
if (passwordInput.type === 'password') { const toggleButton = document.getElementById('togglePassword');
passwordInput.type = 'text'; const submitButton = document.getElementById('submitButton');
this.textContent = '👁‍🗨'; const errorMessage = document.getElementById('errorMessage');
} else { const loadingSpinner = document.getElementById('loadingSpinner');
passwordInput.type = 'password';
this.textContent = '👁'; // 密码显示切换
} toggleButton.addEventListener('click', function() {
const type = passwordInput.type === 'password' ? 'text' : 'password';
passwordInput.type = type;
this.textContent = type === 'password' ? '👁' : '👁‍🗨';
}); });
document.getElementById('loginForm').addEventListener('submit', async function(e) { // 登录表单提交
form.addEventListener('submit', async function(e) {
e.preventDefault(); e.preventDefault();
const password = document.getElementById('password').value; errorMessage.textContent = '';
submitButton.disabled = true;
submitButton.classList.add('loading');
loadingSpinner.style.display = 'block';
try { try {
const response = await fetch('/login', { const response = await fetch('/login', {
@ -113,7 +157,9 @@
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
body: JSON.stringify({ password }), body: JSON.stringify({
password: passwordInput.value
}),
}); });
const data = await response.json(); const data = await response.json();
@ -121,13 +167,26 @@
if (response.ok) { if (response.ok) {
window.location.href = '/'; window.location.href = '/';
} else { } else {
document.getElementById('errorMessage').textContent = data.error || '登录失败'; throw new Error(data.error || '密码错误');
} }
} catch (error) { } catch (error) {
document.getElementById('errorMessage').textContent = '登录失败,请重试'; errorMessage.textContent = error.message || '登录失败,请重试';
} finally {
submitButton.disabled = false;
submitButton.classList.remove('loading');
loadingSpinner.style.display = 'none';
} }
}); });
// 页面加载完成后聚焦密码输入框
window.addEventListener('load', () => {
passwordInput.focus();
});
// 清除之前的错误信息
passwordInput.addEventListener('input', () => {
errorMessage.textContent = '';
});
</script> </script>
</body> </body>
</html> </html>