Merge pull request #170 from ReturnFI/beta

Configurable NormalSub
This commit is contained in:
Whispering Wind
2025-05-18 12:25:56 +03:30
committed by GitHub
9 changed files with 351 additions and 125 deletions

View File

@ -43,6 +43,18 @@
---
## 💎 حامی مالی
<div align="center">
[![Petrosky Hosting](https://img.shields.io/badge/Recommended_Host-Petrosky-blue?logo=server&logoColor=white)](https://client.petrosky.io/aff.php?aff=344)
[**هاستینگی برای تمام مسیر شما!**](https://client.petrosky.io/aff.php?aff=344) 👉
*سرورهای با کیفیت بهینه‌سازی شده برای Hysteria2 و اپلیکیشن‌های پروکسی*
</div>
## 📋 راهنمای شروع سریع
### نصب با یک کلیک

View File

@ -36,7 +36,17 @@ A powerful and user-friendly management panel for Hysteria2 proxy server. Featur
- ♻️ Hysteria2 Core Management (Restart, Update, Uninstall)
- ✏️ IP Address Management (IPv4 and IPv6)
## 💎 Sponsorship
<div align="center">
[![Petrosky Hosting](https://img.shields.io/badge/Recommended_Host-Petrosky-blue?logo=server&logoColor=white)](https://client.petrosky.io/aff.php?aff=344)
👉 [**A hosting for your entire journey!**](https://client.petrosky.io/aff.php?aff=344)
*Quality servers optimized for Hysteria2 and proxy applications*
</div>
## 📋 Quick Start Guide

View File

@ -1,30 +1,23 @@
# [1.9.3] - 2025-05-16
# [1.10.0] - 2025-05-18
## ✨ Changed
## ✨ New Features
### 🔧 System Improvements
### ⚙️ NormalSub Configuration Enhancements
* 🕒 **feat:** Replace unreliable cron jobs with a systemd-based `HysteriaScheduler` service
* 🔐 **feat:** Add file locking to prevent concurrent access issues with `users.json`
* ⏱️ **feat:** Schedule:
* Traffic updates every 1 minute
* Backups every 6 hours with isolated lock management
* 📝 **feat:** Add detailed logging for easier troubleshooting and monitoring
* 🛠️ **feat:** Add NormalSub subpath editing via Settings UI
- New 'Configure' tab in the Settings panel (visible only if NormalSub is active)
- Real-time client-side validation and live subpath editing
### 🛠️ Script Enhancements
* 🔌 **feat:** Add API endpoints
- `GET /api/v1/config/normalsub/subpath`: Fetch current subpath
- `PUT /api/v1/config/normalsub/edit_subpath`: Update the subpath securely
* 📦 **refactor:** Create shared scheduler install function (used in both `install.sh` & `upgrade.sh`)
* ⚙️ **enhance:** Improve `upgrade.sh`:
* Add service checks
* Backup handling
* Color UI
* Robust error handling
* 🧼 **fix:** Improve uninstall script to clean up `HysteriaScheduler` service completely
* 👤 **feat:** Add a default user after installation
* 🔁 **fix:** Automatically restart `normal-sub` service after changing its path
* 🖥️ **feat:** Add CLI command support
- `edit_subpath` option added to CLI and `normal-sub` command
- Automatically restarts the service after applying changes
### 🤖 Telegram Bot Improvements
* 🔧 **feat:** Add backend CLI + shell logic to update `.env` subpath for NormalSub
* **feat:** Show Normal-SUB link and QR code after adding user
* 🔁 If Normal-SUB is not available, fallback to Hysteria2 direct URI and QR
* 🧪 Improved input validation for username, traffic, and expiration
## 📄 Documentation
* 📚 **docs:** Add sponsorship section with referral link to README

View File

@ -421,10 +421,13 @@ def singbox(action: str, domain: str, port: int):
@cli.command('normal-sub')
@click.option('--action', '-a', required=True, help='Action to perform: start or stop', type=click.Choice(['start', 'stop'], case_sensitive=False))
@click.option('--domain', '-d', required=False, help='Domain name for SSL', type=str)
@click.option('--port', '-p', required=False, help='Port number for NormalSub service', type=int)
def normalsub(action: str, domain: str, port: int):
@click.option('--action', '-a', required=True,
type=click.Choice(['start', 'stop', 'edit_subpath'], case_sensitive=False),
help='Action to perform: start, stop, or edit_subpath')
@click.option('--domain', '-d', required=False, help='Domain name for SSL (for start action)', type=str)
@click.option('--port', '-p', required=False, help='Port number for NormalSub service (for start action)', type=int)
@click.option('--subpath', '-sp', required=False, help='New subpath (alphanumeric, for edit_subpath action)', type=str)
def normalsub(action: str, domain: str, port: int, subpath: str):
try:
if action == 'start':
if not domain or not port:
@ -434,6 +437,11 @@ def normalsub(action: str, domain: str, port: int):
elif action == 'stop':
cli_api.stop_normalsub()
click.echo(f'NormalSub stopped successfully.')
elif action == 'edit_subpath':
if not subpath:
raise click.UsageError('Error: --subpath is required for the edit_subpath action.')
cli_api.edit_normalsub_subpath(subpath)
click.echo(f'NormalSub subpath updated to {subpath} successfully.')
except Exception as e:
click.echo(f'{e}', err=True)

View File

@ -13,6 +13,8 @@ SCRIPT_DIR = '/etc/hysteria/core/scripts'
CONFIG_FILE = '/etc/hysteria/config.json'
CONFIG_ENV_FILE = '/etc/hysteria/.configs.env'
WEBPANEL_ENV_FILE = '/etc/hysteria/core/scripts/webpanel/.env'
NORMALSUB_ENV_FILE = '/etc/hysteria/core/scripts/normalsub/.env'
class Command(Enum):
'''Contains path to command's script'''
@ -510,6 +512,26 @@ def start_normalsub(domain: str, port: int):
raise InvalidInputError('Error: Both --domain and --port are required for the start action.')
run_cmd(['bash', Command.INSTALL_NORMALSUB.value, 'start', domain, str(port)])
def edit_normalsub_subpath(new_subpath: str):
'''Edits the subpath for NormalSub service.'''
if not new_subpath:
raise InvalidInputError('Error: New subpath cannot be empty.')
if not new_subpath.isalnum():
raise InvalidInputError('Error: New subpath must contain only alphanumeric characters (a-z, A-Z, 0-9).')
run_cmd(['bash', Command.INSTALL_NORMALSUB.value, 'edit_subpath', new_subpath])
def get_normalsub_subpath() -> str | None:
'''Retrieves the current SUBPATH for the NormalSub service from its .env file.'''
try:
if not os.path.exists(NORMALSUB_ENV_FILE):
return None
env_vars = dotenv_values(NORMALSUB_ENV_FILE)
return env_vars.get('SUBPATH')
except Exception as e:
print(f"Error reading NormalSub .env file: {e}")
return None
def stop_normalsub():
'''Stops NormalSub.'''

View File

@ -70,7 +70,6 @@ start_service() {
systemctl daemon-reload
systemctl enable hysteria-normal-sub.service > /dev/null 2>&1
systemctl start hysteria-normal-sub.service > /dev/null 2>&1
# systemctl restart caddy.service > /dev/null 2>&1 # We stopped caddy service just after its installation
systemctl daemon-reload > /dev/null 2>&1
if systemctl is-active --quiet hysteria-normal-sub.service; then
@ -85,12 +84,12 @@ stop_service() {
source /etc/hysteria/core/scripts/normalsub/.env
fi
# if [ -n "$HYSTERIA_DOMAIN" ]; then
# echo -e "${yellow}Deleting SSL certificate for domain: $HYSTERIA_DOMAIN...${NC}"
# certbot delete --cert-name "$HYSTERIA_DOMAIN" --non-interactive > /dev/null 2>&1
# else
# echo -e "${red}HYSTERIA_DOMAIN not found in .env. Skipping certificate deletion.${NC}"
# fi
if [ -n "$HYSTERIA_DOMAIN" ]; then
echo -e "${yellow}Deleting SSL certificate for domain: $HYSTERIA_DOMAIN...${NC}"
certbot delete --cert-name "$HYSTERIA_DOMAIN" --non-interactive > /dev/null 2>&1
else
echo -e "${red}HYSTERIA_DOMAIN not found in .env. Skipping certificate deletion.${NC}"
fi
systemctl stop hysteria-normal-sub.service > /dev/null 2>&1
systemctl disable hysteria-normal-sub.service > /dev/null 2>&1
@ -101,6 +100,38 @@ stop_service() {
echo -e "${yellow}normalsub service stopped and disabled. .env file removed.${NC}"
}
edit_subpath() {
local new_path="$1"
local env_file="/etc/hysteria/core/scripts/normalsub/.env"
if [[ ! "$new_path" =~ ^[a-zA-Z0-9]+$ ]]; then
echo -e "${red}Error: New subpath must contain only alphanumeric characters (a-z, A-Z, 0-9) and cannot be empty.${NC}"
exit 1
fi
if [ ! -f "$env_file" ]; then
echo -e "${red}Error: .env file ($env_file) not found. Please run the start command first.${NC}"
exit 1
fi
if grep -q "^SUBPATH=" "$env_file"; then
sed -i "s|^SUBPATH=.*|SUBPATH=$new_path|" "$env_file"
else
echo "SUBPATH=$new_path" >> "$env_file"
fi
echo -e "${green}SUBPATH updated to $new_path in $env_file.${NC}"
echo -e "${yellow}Restarting hysteria-normal-sub service...${NC}"
systemctl daemon-reload
systemctl restart hysteria-normal-sub.service
if systemctl is-active --quiet hysteria-normal-sub.service; then
echo -e "${green}hysteria-normal-sub service restarted successfully.${NC}"
else
echo -e "${red}Error: hysteria-normal-sub service failed to restart. Please check logs.${NC}"
fi
}
case "$1" in
start)
if [ -z "$2" ] || [ -z "$3" ]; then
@ -112,10 +143,15 @@ case "$1" in
stop)
stop_service
;;
edit_subpath)
if [ -z "$2" ]; then
echo -e "${red}Usage: $0 edit_subpath <NEW_SUBPATH> ${NC}"
exit 1
fi
edit_subpath "$2"
;;
*)
echo -e "${red}Usage: $0 {start|stop} <DOMAIN> <PORT> ${NC}"
echo -e "${red}Usage: $0 {start <DOMAIN> <PORT> | stop | edit_subpath <NEW_SUBPATH>} ${NC}"
exit 1
;;
esac
define_colors
esac

View File

@ -1,6 +1,6 @@
from fastapi import APIRouter, HTTPException
from ..schema.response import DetailResponse
from ..schema.config.normalsub import StartInputBody
from ..schema.config.normalsub import StartInputBody, EditSubPathInputBody, GetSubPathResponse
import cli_api
router = APIRouter()
@ -51,4 +51,38 @@ async def normal_sub_stop_api():
except Exception as e:
raise HTTPException(status_code=400, detail=f'Error: {str(e)}')
# TODO: Maybe would be nice to have a status endpoint
@router.put('/edit_subpath', response_model=DetailResponse, summary='Edit NormalSub Subpath')
async def normal_sub_edit_subpath_api(body: EditSubPathInputBody):
"""
Edits the subpath for the NormalSub service.
Args:
body (EditSubPathInputBody): The request body containing the new subpath.
Returns:
DetailResponse: A response object containing a success message indicating
that the NormalSub subpath has been updated successfully.
Raises:
HTTPException: If there is an error editing the NormalSub subpath, an
HTTPException with status code 400 and error details will be raised.
"""
try:
cli_api.edit_normalsub_subpath(body.subpath)
return DetailResponse(detail=f'Normalsub subpath updated to {body.subpath} successfully.')
except cli_api.InvalidInputError as e:
raise HTTPException(status_code=422, detail=f'Validation Error: {str(e)}')
except Exception as e:
raise HTTPException(status_code=400, detail=f'Error: {str(e)}')
@router.get('/subpath', response_model=GetSubPathResponse, summary='Get Current NormalSub Subpath')
async def normal_sub_get_subpath_api():
"""
Retrieves the current subpath for the NormalSub service.
"""
try:
current_subpath = cli_api.get_normalsub_subpath()
return GetSubPathResponse(subpath=current_subpath)
except Exception as e:
raise HTTPException(status_code=500, detail=f'Error retrieving subpath: {str(e)}')

View File

@ -1,9 +1,12 @@
from pydantic import BaseModel
# The StartInputBody is the same as in /hysteria/core/scripts/webpanel/routers/api/v1/schema/config/singbox.py but for /normalsub endpoint
# I'm defining it separately because highly likely it'll be different
from pydantic import BaseModel, Field
from typing import Optional
class StartInputBody(BaseModel):
domain: str
port: int
class EditSubPathInputBody(BaseModel):
subpath: str = Field(..., min_length=1, pattern=r"^[a-zA-Z0-9]+$", description="The new subpath, must be alphanumeric.")
class GetSubPathResponse(BaseModel):
subpath: Optional[str] = Field(None, description="The current NormalSub subpath, or null if not set/found.")

View File

@ -56,7 +56,7 @@
aria-controls='ip-limit' aria-selected='false'><i class="fas fa-user-slash"></i>
IP Limit</a>
</li>
<li class='nav-item'>
<li class='nav-item'>
<a class='nav-link' id='decoy-tab' data-toggle='pill' href='#decoy' role='tab'
aria-controls='decoy' aria-selected='false'><i class="fas fa-mask"></i>
Decoy Site</a>
@ -71,14 +71,18 @@
<ul class='nav nav-tabs' id='subs-tabs' role='tablist'>
<li class='nav-item'>
<a class='nav-link active' id='normal-tab' data-toggle='tab' href='#normal' role='tab'
aria-controls='normal' aria-selected='false'><strong>Normal</strong></a>
aria-controls='normal' aria-selected='true'><strong>Normal</strong></a>
</li>
<li class='nav-item normal-sub-config-tab-li' style="display: none;"> <!-- Initially hidden -->
<a class='nav-link' id='normal-sub-config-link-tab' data-toggle='tab' href='#normal-sub-config-content' role='tab'
aria-controls='normal-sub-config-content' aria-selected='false'><strong>Configure</strong></a>
</li>
</ul>
<div class='tab-content' id='subs-tabs-content'>
<br>
<!-- Normal Sub Tab -->
<!-- Normal Sub Service Control Tab -->
<div class='tab-pane fade show active' id='normal' role='tabpanel' aria-labelledby='normal-tab'>
<form id="normal">
<form id="normal_sub_service_form">
<div class='form-group'>
<label for='normal_domain'>Domain:</label>
<input type='text' class='form-control' id='normal_domain'
@ -101,7 +105,23 @@
</button>
<button id="normal_stop" type='button' class='btn btn-danger'
style="display: none;">Stop</button>
</form>
</div>
<!-- Normal Sub Configuration Tab -->
<div class='tab-pane fade' id='normal-sub-config-content' role='tabpanel' aria-labelledby='normal-sub-config-link-tab'>
<form id="normal_sub_config_form">
<div class='form-group'>
<label for='normal_subpath_input'>Subpath:</label>
<input type='text' class='form-control' id='normal_subpath_input'
placeholder='Enter subpath (e.g., mysub)'>
<div class="invalid-feedback">
Please enter a valid subpath (alphanumeric characters only, e.g., mysub).
</div>
</div>
<button id="normal_subpath_save_btn" type='button' class='btn btn-primary'>
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true" style="display: none;"></span>
Save Subpath
</button>
</form>
</div>
</div>
@ -109,7 +129,7 @@
<!-- Telegram Bot Tab -->
<div class='tab-pane fade' id='telegram' role='tabpanel' aria-labelledby='telegram-tab'>
<form id="telegram">
<form id="telegram_form">
<div class='form-group'>
<label for='telegram_api_token'>API Token:</label>
<input type='text' class='form-control' id='telegram_api_token'
@ -135,7 +155,7 @@
<!-- Port Tab -->
<div class='tab-pane fade' id='port' role='tabpanel' aria-labelledby='port-tab'>
<form id="port">
<form id="port_form">
<div class='form-group'>
<label for='hysteria_port'>Port:</label>
<input type='text' class='form-control' id='hysteria_port'
@ -150,7 +170,7 @@
<!-- SNI Tab -->
<div class='tab-pane fade' id='sni' role='tabpanel' aria-labelledby='sni-tab'>
<form id="sni">
<form id="sni_form">
<div class='form-group'>
<label for='sni_domain'>Domain:</label>
<input type='text' class='form-control' id='sni_domain'
@ -165,7 +185,7 @@
<!-- Change IP Tab -->
<div class='tab-pane fade' id='change_ip' role='tabpanel' aria-labelledby='ip-tab'>
<form id="change_ip">
<form id="change_ip_form">
<div class='form-group'>
<label for='ipv4'>IPv4:</label>
<input type='text' class='form-control' id='ipv4' placeholder='Enter IPv4 or Domain'
@ -231,7 +251,7 @@
<!-- IP Limit Configuration Sub Tab -->
<div class='tab-pane fade' id='ip-limit-config-content' role='tabpanel' aria-labelledby='ip-limit-config-tab'>
<form id="ip_limit_config">
<form id="ip_limit_config_form">
<div class='form-group'>
<label for='block_duration'>Block Duration (seconds):</label>
<input type='text' class='form-control' id='block_duration'
@ -253,8 +273,7 @@
</div>
</div>
</div>
<!-- Decoy Site Tab -->
<!-- Decoy Site Tab -->
<div class='tab-pane fade' id='decoy' role='tabpanel' aria-labelledby='decoy-tab'>
<form id="decoy_form">
<div class='form-group'>
@ -328,6 +347,12 @@
return /^[0-9]+$/.test(port) && parseInt(port) > 0 && parseInt(port) <= 65535;
}
function isValidSubPath(subpath) {
if (!subpath) return false;
return /^[a-zA-Z0-9]+$/.test(subpath);
}
function isValidIPorDomain(input) {
if (!input) return true;
@ -365,7 +390,7 @@
});
}
function sendRequest(url, type, data, successMessage, buttonSelector, showReload = true) {
function sendRequest(url, type, data, successMessage, buttonSelector, showReload = true, postSuccessCallback = null) {
$.ajax({
url: url,
type: type,
@ -378,13 +403,15 @@
}
},
success: function (response) {
if (showReload) {
Swal.fire("Success!", successMessage, "success").then(() => {
Swal.fire("Success!", successMessage, "success").then(() => {
if (showReload) {
location.reload();
});
} else {
Swal.fire("Success!", successMessage, "success");
}
} else {
if (postSuccessCallback) {
postSuccessCallback(response);
}
}
});
console.log("Success Response:", response);
},
error: function (xhr, status, error) {
@ -393,7 +420,7 @@
errorMessage = xhr.responseJSON.detail;
}
Swal.fire("Error!", errorMessage, "error");
console.error("AJAX Error:", status, error, xhr.responseText);
console.error("AJAX Error:", status, error, xhr.responseText);
},
complete: function() {
if (buttonSelector) {
@ -411,10 +438,12 @@
const id = input.attr('id');
let fieldValid = true;
if (id.includes('domain')) {
if (id === 'normal_domain' || id === 'sni_domain' || id === 'decoy_domain') {
fieldValid = isValidDomain(input.val());
} else if (id.includes('port')) {
} else if (id === 'normal_port' || id === 'hysteria_port') {
fieldValid = isValidPort(input.val());
} else if (id === 'normal_subpath_input') {
fieldValid = isValidSubPath(input.val());
} else if (id === 'ipv4' || id === 'ipv6') {
fieldValid = (input.val().trim() === '') ? true : isValidIPorDomain(input.val());
} else if (id === 'block_duration' || id === 'max_ips') {
@ -427,14 +456,15 @@
if (!fieldValid) {
input.addClass('is-invalid');
isValid = false;
isValid = false;
} else {
input.removeClass('is-invalid');
}
});
return isValid;
return isValid;
}
function initUI() {
$.ajax({
url: "{{ url_for('server_services_status_api') }}",
@ -481,50 +511,113 @@
console.error("Failed to fetch SNI domain:", error, xhr.responseText);
}
});
}
}
function updateServiceUI(data) {
const servicesMap = {
"hysteria_telegram_bot": "#telegram",
"hysteria_normal_sub": "#normal",
"hysteria_iplimit": "#ip-limit-service"
"hysteria_telegram_bot": "#telegram_form",
"hysteria_normal_sub": "#normal_sub_service_form",
"hysteria_iplimit": "#ip-limit-service"
};
Object.keys(servicesMap).forEach(service => {
let selector = servicesMap[service];
let isRunning = data[service];
let formSelector = servicesMap[service];
let isRunning = data[service];
if (isRunning) {
$(selector + " .form-group").hide();
$(selector + " .btn-success").hide();
$(selector + " .btn-danger").show();
if ($(selector + " .alert-info").length === 0) {
$(selector).prepend(`<div class='alert alert-info'>Service is running. You can stop it if needed.</div>`);
if (service === "hysteria_normal_sub") {
const $normalFormGroups = $("#normal_sub_service_form .form-group");
const $normalStartBtn = $("#normal_start");
const $normalStopBtn = $("#normal_stop");
const $normalAlert = $("#normal_sub_service_form .alert-info");
const $normalSubConfigTabLi = $(".normal-sub-config-tab-li");
if (isRunning) {
$normalFormGroups.hide();
$normalStartBtn.hide();
$normalStopBtn.show();
if ($normalAlert.length === 0) {
$("#normal_sub_service_form").prepend(`<div class='alert alert-info'>NormalSub service is running. You can stop it or configure its subpath.</div>`);
}
$normalSubConfigTabLi.show();
fetchNormalSubPath();
} else {
$normalFormGroups.show();
$normalStartBtn.show();
$normalStopBtn.hide();
$("#normal_sub_service_form .alert-info").remove();
$normalSubConfigTabLi.hide();
if ($('#normal-sub-config-link-tab').hasClass('active')) {
$('#normal-tab').tab('show');
}
$("#normal_subpath_input").val("");
$("#normal_subpath_input").removeClass('is-invalid');
}
if(service === "hysteria_iplimit"){
} else if (service === "hysteria_iplimit") {
if (isRunning) {
$("#ip_limit_start").hide();
$("#ip_limit_stop").show();
$(".ip-limit-config-tab-li").show();
}
} else {
$(selector + " .form-group").show();
$(selector + " .btn-success").show();
$(selector + " .btn-danger").hide();
$(selector + " .alert-info").remove();
if(service === "hysteria_iplimit"){
// TODO: Fetch IP Limit Config and populate fields
} else {
$("#ip_limit_start").show();
$("#ip_limit_stop").hide();
$(".ip-limit-config-tab-li").hide();
$('#ip-limit-service-tab').tab('show');
// TODO: Clear IP Limit Config fields
}
} else {
if (isRunning) {
$(formSelector + " .form-group").hide();
$(formSelector + " .btn-success").hide();
$(formSelector + " .btn-danger").show();
if ($(formSelector + " .alert-info").length === 0) {
$(formSelector).prepend(`<div class='alert alert-info'>Service is running. You can stop it if needed.</div>`);
}
} else {
$(formSelector + " .form-group").show();
$(formSelector + " .btn-success").show();
$(formSelector + " .btn-danger").hide();
$(formSelector + " .alert-info").remove();
}
}
});
}
function fetchNormalSubPath() {
$.ajax({
url: "{{ url_for('normal_sub_get_subpath_api') }}",
type: "GET",
success: function (data) {
$("#normal_subpath_input").val(data.subpath || "");
if (data.subpath) {
$("#normal_subpath_input").removeClass('is-invalid');
}
},
error: function (xhr, status, error) {
console.error("Failed to fetch NormalSub subpath:", error, xhr.responseText);
$("#normal_subpath_input").val("");
// Swal.fire("Error!", "Could not fetch NormalSub subpath.", "error"); // Avoid too many popups during init
}
});
}
function editNormalSubPath() {
if (!validateForm('normal_sub_config_form')) return;
const subpath = $("#normal_subpath_input").val();
confirmAction("change the NormalSub subpath to '" + subpath + "'", function () {
sendRequest(
"{{ url_for('normal_sub_edit_subpath_api') }}",
"PUT",
{ subpath: subpath },
"NormalSub subpath updated successfully!",
"#normal_subpath_save_btn",
false,
fetchNormalSubPath
);
});
}
function setupDecoy() {
if (!validateForm('decoy_form')) return;
@ -537,9 +630,9 @@
{ domain: domain, decoy_path: path },
"Decoy site setup initiated successfully!",
"#decoy_setup",
false
false,
function() { setTimeout(fetchDecoyStatus, 1000); }
);
setTimeout(fetchDecoyStatus, 2000);
});
}
@ -547,13 +640,13 @@
confirmAction("stop the decoy site", function () {
sendRequest(
"{{ url_for('stop_decoy_api') }}",
"POST",
"POST",
null,
"Decoy site stop initiated successfully!",
"#decoy_stop",
false
"#decoy_stop",
false,
function() { setTimeout(fetchDecoyStatus, 1000); }
);
setTimeout(fetchDecoyStatus, 2000);
});
}
@ -562,7 +655,7 @@
url: "{{ url_for('get_decoy_status_api') }}",
type: "GET",
success: function (data) {
updateDecoyStatusUI(data);
updateDecoyStatusUI(data);
},
error: function (xhr, status, error) {
$("#decoy_status_message").html('<div class="alert alert-danger">Failed to fetch decoy status.</div>');
@ -572,30 +665,37 @@
}
function updateDecoyStatusUI(data) {
const $form = $("#decoy_form");
const $formGroups = $form.find(".form-group");
const $setupBtn = $("#decoy_setup");
const $stopBtn = $("#decoy_stop");
const $alertInfo = $form.find(".alert-info");
if (data.active) {
$("#decoy_form .form-group").hide();
$("#decoy_setup").hide();
$("#decoy_stop").show();
$("#decoy_form .alert-info").remove();
if ($("#decoy_form .alert-info").length === 0) {
$("#decoy_form").prepend(`<div class='alert alert-info'>Decoy site is running. You can stop it if needed.</div>`);
}
$formGroups.hide();
$setupBtn.hide();
$stopBtn.show();
if ($alertInfo.length === 0) {
$form.prepend(`<div class='alert alert-info'>Decoy site is running. You can stop it if needed.</div>`);
} else {
$alertInfo.text('Decoy site is running. You can stop it if needed.');
}
$("#decoy_status_message").html(`
<strong>Status:</strong> <span class="text-success">Active</span><br>
<strong>Path:</strong> ${data.path || 'N/A'}
`);
} else {
$("#decoy_form .form-group").show();
$("#decoy_setup").show();
$("#decoy_stop").hide();
$("#decoy_form .alert-info").remove();
$formGroups.show();
$setupBtn.show();
$stopBtn.hide();
$alertInfo.remove();
$("#decoy_status_message").html('<strong>Status:</strong> <span class="text-danger">Not Active</span>');
}
}
function startTelegram() {
if (!validateForm('telegram')) return;
if (!validateForm('telegram_form')) return;
const apiToken = $("#telegram_api_token").val();
const adminId = $("#telegram_admin_id").val();
confirmAction("start the Telegram bot", function () {
@ -622,7 +722,7 @@
}
function startNormal() {
if (!validateForm('normal')) return;
if (!validateForm('normal_sub_service_form')) return;
const domain = $("#normal_domain").val();
const port = $("#normal_port").val();
confirmAction("start the normal subscription", function () {
@ -649,7 +749,7 @@
}
function changePort() {
if (!validateForm('port')) return;
if (!validateForm('port_form')) return;
const port = $("#hysteria_port").val();
const baseUrl = "{{ url_for('set_port_api', port='PORT_PLACEHOLDER') }}";
const url = baseUrl.replace("PORT_PLACEHOLDER", port);
@ -659,7 +759,7 @@
}
function changeSNI() {
if (!validateForm('sni')) return;
if (!validateForm('sni_form')) return;
const domain = $("#sni_domain").val();
const baseUrl = "{{ url_for('set_sni_api', sni='SNI_PLACEHOLDER') }}";
const url = baseUrl.replace("SNI_PLACEHOLDER", domain);
@ -669,8 +769,8 @@
}
function saveIP() {
if (!validateForm('change_ip')) return;
const ipv4 = $("#ipv4").val().trim() || null;
if (!validateForm('change_ip_form')) return;
const ipv4 = $("#ipv4").val().trim() || null;
const ipv6 = $("#ipv6").val().trim() || null;
confirmAction("save the new IP settings", function () {
sendRequest(
@ -713,7 +813,7 @@
progressBar.style.width = '0%';
progressBar.setAttribute('aria-valuenow', 0);
statusDiv.innerText = 'Uploading...';
statusDiv.className = 'mt-2';
statusDiv.className = 'mt-2';
$.ajax({
url: "{{ url_for('restore_api') }}",
@ -783,14 +883,14 @@
}
function configIPLimit() {
if (!validateForm('ip_limit_config')) return;
if (!validateForm('ip_limit_config_form')) return; // Ensure correct form ID
const blockDuration = $("#block_duration").val();
const maxIps = $("#max_ips").val();
confirmAction("save the IP Limit configuration", function () {
sendRequest(
"{{ url_for('config_ip_limit_api') }}",
"POST",
{ block_duration: parseInt(blockDuration), max_ips: parseInt(maxIps) },
{ block_duration: parseInt(blockDuration), max_ips: parseInt(maxIps) },
"IP Limit configuration saved successfully!",
"#ip_limit_change_config",
false
@ -804,6 +904,7 @@
$("#telegram_stop").on("click", stopTelegram);
$("#normal_start").on("click", startNormal);
$("#normal_stop").on("click", stopNormal);
$("#normal_subpath_save_btn").on("click", editNormalSubPath);
$("#port_change").on("click", changePort);
$("#sni_change").on("click", changeSNI);
$("#ip_change").on("click", saveIP);
@ -816,7 +917,6 @@
$("#decoy_stop").on("click", stopDecoy);
$('#normal_domain, #sni_domain, #decoy_domain').on('input', function () {
if (isValidDomain($(this).val())) {
$(this).removeClass('is-invalid');
@ -837,6 +937,16 @@
}
});
$('#normal_subpath_input').on('input', function () {
if (isValidSubPath($(this).val())) {
$(this).removeClass('is-invalid');
} else if ($(this).val().trim() !== "") {
$(this).addClass('is-invalid');
} else {
$(this).removeClass('is-invalid');
}
});
$('#ipv4, #ipv6').on('input', function () {
if (isValidIPorDomain($(this).val()) || $(this).val().trim() === '') {
$(this).removeClass('is-invalid');
@ -852,8 +962,7 @@
$(this).addClass('is-invalid');
}
});
$('#block_duration, #max_ips').on('input', function () {
$('#block_duration, #max_ips').on('input', function () {
if (isValidPositiveNumber($(this).val())) {
$(this).removeClass('is-invalid');
} else if ($(this).val().trim() !== "") {
@ -869,11 +978,10 @@
} else if ($(this).val().trim() !== "") {
$(this).addClass('is-invalid');
} else {
$(this).removeClass('is-invalid');
$(this).removeClass('is-invalid');
}
});
});
</script>
{% endblock %}