mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-11-17 18:45:03 +03:00
Compare commits
21 Commits
v3.4.0
...
bcd1358032
| Author | SHA1 | Date | |
|---|---|---|---|
| bcd1358032 | |||
| e8878b71a4 | |||
| 11c5b53fac | |||
| 896016f7f6 | |||
| e2d25d0ac7 | |||
| fe025e8af3 | |||
| 3ba43bd86d | |||
| ae9bbdf267 | |||
| 2830f97f50 | |||
| 1d1128cf94 | |||
| aad2b3eb1e | |||
| 93ff60e568 | |||
| 23e73cd4a3 | |||
| b0c1156dd6 | |||
| 5dbd5b1d12 | |||
| bd60e770f4 | |||
| a5e865c109 | |||
| 82600936d6 | |||
| 14de0557f9 | |||
| c93beef267 | |||
| 48c2fb27b8 |
@@ -4,3 +4,16 @@ XUI_LOG_FOLDER=x-ui
|
|||||||
XUI_BIN_FOLDER=x-ui
|
XUI_BIN_FOLDER=x-ui
|
||||||
XUI_INIT_WEB_BASE_PATH=/
|
XUI_INIT_WEB_BASE_PATH=/
|
||||||
# XUI_PORT=8080
|
# XUI_PORT=8080
|
||||||
|
|
||||||
|
# Optional tunnel health monitor (disabled by default). It periodically probes a
|
||||||
|
# URL and restarts xray-core after repeated failures. Point XUI_TUNNEL_HEALTH_PROXY
|
||||||
|
# at a local xray inbound so the probe tests the tunnel; without it the probe only
|
||||||
|
# checks host connectivity and a restart will not fix host network issues. A restart
|
||||||
|
# drops every connected client.
|
||||||
|
# XUI_TUNNEL_HEALTH_MONITOR=true
|
||||||
|
# XUI_TUNNEL_HEALTH_PROXY=socks5://127.0.0.1:1080
|
||||||
|
# XUI_TUNNEL_HEALTH_URL=https://www.cloudflare.com/cdn-cgi/trace
|
||||||
|
# XUI_TUNNEL_HEALTH_INTERVAL=30s
|
||||||
|
# XUI_TUNNEL_HEALTH_TIMEOUT=10s
|
||||||
|
# XUI_TUNNEL_HEALTH_FAILURES=3
|
||||||
|
# XUI_TUNNEL_HEALTH_COOLDOWN=5m
|
||||||
|
|||||||
@@ -97,7 +97,13 @@ jobs:
|
|||||||
export CC=$(realpath "$(find "$TOOLCHAIN_DIR/bin" -name '*-gcc.br_real' -type f -executable | head -n1)")
|
export CC=$(realpath "$(find "$TOOLCHAIN_DIR/bin" -name '*-gcc.br_real' -type f -executable | head -n1)")
|
||||||
[ -z "$CC" ] && { echo "No gcc.br_real found in $TOOLCHAIN_DIR/bin" >&2; exit 1; }
|
[ -z "$CC" ] && { echo "No gcc.br_real found in $TOOLCHAIN_DIR/bin" >&2; exit 1; }
|
||||||
cd -
|
cd -
|
||||||
go build -ldflags "-w -s -linkmode external -extldflags '-static'" -o xui-release -v main.go
|
# Stamp the commit into per-commit (dev channel) builds only; tagged
|
||||||
|
# stable releases stay unstamped so config.IsDevBuild() returns false.
|
||||||
|
LDFLAGS="-w -s -linkmode external -extldflags '-static'"
|
||||||
|
if [[ "$GITHUB_REF" != refs/tags/* ]]; then
|
||||||
|
LDFLAGS="$LDFLAGS -X github.com/mhsanaei/3x-ui/v3/internal/config.buildCommit=${GITHUB_SHA::8} -X github.com/mhsanaei/3x-ui/v3/internal/config.buildDate=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||||
|
fi
|
||||||
|
go build -ldflags "$LDFLAGS" -o xui-release -v main.go
|
||||||
file xui-release
|
file xui-release
|
||||||
ldd xui-release || echo "Static binary confirmed"
|
ldd xui-release || echo "Static binary confirmed"
|
||||||
|
|
||||||
@@ -245,7 +251,12 @@ jobs:
|
|||||||
go version
|
go version
|
||||||
gcc --version
|
gcc --version
|
||||||
|
|
||||||
go build -ldflags "-w -s" -o xui-release.exe -v main.go
|
# Stamp the commit into per-commit (dev channel) builds only.
|
||||||
|
LDFLAGS="-w -s"
|
||||||
|
if [[ "$GITHUB_REF" != refs/tags/* ]]; then
|
||||||
|
LDFLAGS="$LDFLAGS -X github.com/mhsanaei/3x-ui/v3/internal/config.buildCommit=${GITHUB_SHA:0:8} -X github.com/mhsanaei/3x-ui/v3/internal/config.buildDate=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||||
|
fi
|
||||||
|
go build -ldflags "$LDFLAGS" -o xui-release.exe -v main.go
|
||||||
|
|
||||||
- name: Copy and download resources
|
- name: Copy and download resources
|
||||||
shell: pwsh
|
shell: pwsh
|
||||||
@@ -302,3 +313,61 @@ jobs:
|
|||||||
asset_name: x-ui-windows-amd64.zip
|
asset_name: x-ui-windows-amd64.zip
|
||||||
overwrite: true
|
overwrite: true
|
||||||
prerelease: true
|
prerelease: true
|
||||||
|
|
||||||
|
# =================================
|
||||||
|
# Rolling dev channel (per-commit)
|
||||||
|
# =================================
|
||||||
|
# Publishes/overwrites the build artifacts to a single fixed-tag pre-release
|
||||||
|
# `dev-latest`, force-moved to the new commit on every push to main. The panel's
|
||||||
|
# "Dev" update channel installs from this tag. `--latest=false` is load-bearing:
|
||||||
|
# it keeps releases/latest pointing at the real stable tag, so the stable
|
||||||
|
# channel is unaffected.
|
||||||
|
publish-dev:
|
||||||
|
name: Publish rolling dev release
|
||||||
|
needs: [build, build-windows]
|
||||||
|
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
# Serialize racing pushes; never cancel an in-flight upload, or the dev
|
||||||
|
# release could be left with a partial asset set.
|
||||||
|
concurrency:
|
||||||
|
group: dev-release
|
||||||
|
cancel-in-progress: false
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v7
|
||||||
|
|
||||||
|
- name: Download all build artifacts
|
||||||
|
uses: actions/download-artifact@v7
|
||||||
|
with:
|
||||||
|
path: dev-artifacts
|
||||||
|
merge-multiple: true
|
||||||
|
|
||||||
|
- name: Publish dev-latest pre-release
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
COMMIT: ${{ github.sha }}
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
short="${COMMIT::8}"
|
||||||
|
notes="Rolling development build — installs via the panel's Dev update channel.
|
||||||
|
|
||||||
|
commit=${COMMIT}
|
||||||
|
built=$(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||||
|
|
||||||
|
Automated per-commit build from main. Not a stable release."
|
||||||
|
|
||||||
|
# Force-move the dev-latest tag to this commit so the release tracks it.
|
||||||
|
git tag -f dev-latest "${COMMIT}"
|
||||||
|
git push -f origin refs/tags/dev-latest
|
||||||
|
|
||||||
|
if gh release view dev-latest >/dev/null 2>&1; then
|
||||||
|
gh release edit dev-latest --prerelease --latest=false \
|
||||||
|
--title "Dev build ${short}" --notes "${notes}"
|
||||||
|
else
|
||||||
|
gh release create dev-latest --prerelease --latest=false \
|
||||||
|
--target "${COMMIT}" --title "Dev build ${short}" --notes "${notes}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
gh release upload dev-latest dev-artifacts/*.tar.gz dev-artifacts/*.zip --clobber
|
||||||
|
|||||||
@@ -146,6 +146,13 @@ docker run -d --cap-add=NET_ADMIN --cap-add=NET_RAW ... ghcr.io/mhsanaei/3x-ui
|
|||||||
| `XUI_ENABLE_FAIL2BAN` | Enable Fail2ban-based IP-limit enforcement | `true` |
|
| `XUI_ENABLE_FAIL2BAN` | Enable Fail2ban-based IP-limit enforcement | `true` |
|
||||||
| `XUI_LOG_LEVEL` | Log verbosity (`debug`, `info`, `warning`, `error`) | `info` |
|
| `XUI_LOG_LEVEL` | Log verbosity (`debug`, `info`, `warning`, `error`) | `info` |
|
||||||
| `XUI_DEBUG` | Enable debug mode | `false` |
|
| `XUI_DEBUG` | Enable debug mode | `false` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_MONITOR` | Enable the tunnel health monitor (probes a URL and restarts xray after repeated failures; a restart drops all clients) | `false` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_PROXY` | Proxy the probe is sent through; point it at a local xray inbound so the probe tests the tunnel (e.g. `socks5://127.0.0.1:1080`). Empty means the probe only checks host connectivity | — |
|
||||||
|
| `XUI_TUNNEL_HEALTH_URL` | URL probed for tunnel health | `https://www.cloudflare.com/cdn-cgi/trace` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_INTERVAL` | Interval between probes | `30s` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_TIMEOUT` | Per-probe timeout | `10s` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_FAILURES` | Consecutive failures before a restart is triggered | `3` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_COOLDOWN` | Minimum delay between consecutive restarts | `5m` |
|
||||||
|
|
||||||
## Supported Languages
|
## Supported Languages
|
||||||
|
|
||||||
|
|||||||
@@ -232,6 +232,14 @@
|
|||||||
"description": "Hide server settings in happ subscription (Only for Happ)",
|
"description": "Hide server settings in happ subscription (Only for Happ)",
|
||||||
"type": "boolean"
|
"type": "boolean"
|
||||||
},
|
},
|
||||||
|
"subIncyEnableRouting": {
|
||||||
|
"description": "Enable routing injection for the Incy client",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"subIncyRoutingRules": {
|
||||||
|
"description": "Incy routing deep-link injected into the subscription body (Only for Incy)",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
"subJsonEnable": {
|
"subJsonEnable": {
|
||||||
"description": "Enable JSON subscription endpoint",
|
"description": "Enable JSON subscription endpoint",
|
||||||
"type": "boolean"
|
"type": "boolean"
|
||||||
@@ -457,6 +465,8 @@
|
|||||||
"subEnableRouting",
|
"subEnableRouting",
|
||||||
"subEncrypt",
|
"subEncrypt",
|
||||||
"subHideSettings",
|
"subHideSettings",
|
||||||
|
"subIncyEnableRouting",
|
||||||
|
"subIncyRoutingRules",
|
||||||
"subJsonEnable",
|
"subJsonEnable",
|
||||||
"subJsonFinalMask",
|
"subJsonFinalMask",
|
||||||
"subJsonMux",
|
"subJsonMux",
|
||||||
@@ -727,6 +737,14 @@
|
|||||||
"description": "Hide server settings in happ subscription (Only for Happ)",
|
"description": "Hide server settings in happ subscription (Only for Happ)",
|
||||||
"type": "boolean"
|
"type": "boolean"
|
||||||
},
|
},
|
||||||
|
"subIncyEnableRouting": {
|
||||||
|
"description": "Enable routing injection for the Incy client",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"subIncyRoutingRules": {
|
||||||
|
"description": "Incy routing deep-link injected into the subscription body (Only for Incy)",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
"subJsonEnable": {
|
"subJsonEnable": {
|
||||||
"description": "Enable JSON subscription endpoint",
|
"description": "Enable JSON subscription endpoint",
|
||||||
"type": "boolean"
|
"type": "boolean"
|
||||||
@@ -959,6 +977,8 @@
|
|||||||
"subEnableRouting",
|
"subEnableRouting",
|
||||||
"subEncrypt",
|
"subEncrypt",
|
||||||
"subHideSettings",
|
"subHideSettings",
|
||||||
|
"subIncyEnableRouting",
|
||||||
|
"subIncyRoutingRules",
|
||||||
"subJsonEnable",
|
"subJsonEnable",
|
||||||
"subJsonFinalMask",
|
"subJsonFinalMask",
|
||||||
"subJsonMux",
|
"subJsonMux",
|
||||||
@@ -4220,6 +4240,46 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"/panel/api/server/setUpdateChannel": {
|
||||||
|
"post": {
|
||||||
|
"tags": [
|
||||||
|
"Server"
|
||||||
|
],
|
||||||
|
"summary": "Toggle the panel update channel between stable and the rolling per-commit dev release. Only effective on dev builds.",
|
||||||
|
"operationId": "post_panel_api_server_setUpdateChannel",
|
||||||
|
"requestBody": {
|
||||||
|
"required": true,
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "Successful response",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"success": {
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"msg": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"obj": {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"/panel/api/server/updateGeofile": {
|
"/panel/api/server/updateGeofile": {
|
||||||
"post": {
|
"post": {
|
||||||
"tags": [
|
"tags": [
|
||||||
@@ -5456,7 +5516,7 @@
|
|||||||
"tags": [
|
"tags": [
|
||||||
"Clients"
|
"Clients"
|
||||||
],
|
],
|
||||||
"summary": "Shift expiry and/or traffic quota for many clients in one call. addDays/addBytes may be negative. Clients with unlimited expiry (expiryTime=0) or unlimited traffic (totalGB=0) are skipped for the corresponding field — bulk extend never converts unlimited to limited. Returns the adjusted count and per-email skip reasons.",
|
"summary": "Shift expiry and/or traffic quota for many clients in one call. addDays/addBytes may be negative. Clients with unlimited expiry (expiryTime=0) or unlimited traffic (totalGB=0) are skipped for the corresponding field — bulk extend never converts unlimited to limited. The optional flow directive sets the XTLS flow on every client: \"none\" clears it, \"xtls-rprx-vision\"/\"xtls-rprx-vision-udp443\" set it where the inbound supports it (omit or \"\" to leave it unchanged). Returns the adjusted count and per-email skip reasons.",
|
||||||
"operationId": "post_panel_api_clients_bulkAdjust",
|
"operationId": "post_panel_api_clients_bulkAdjust",
|
||||||
"requestBody": {
|
"requestBody": {
|
||||||
"required": true,
|
"required": true,
|
||||||
@@ -5471,7 +5531,8 @@
|
|||||||
"bob"
|
"bob"
|
||||||
],
|
],
|
||||||
"addDays": 30,
|
"addDays": 30,
|
||||||
"addBytes": 53687091200
|
"addBytes": 53687091200,
|
||||||
|
"flow": "xtls-rprx-vision"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -7379,7 +7440,7 @@
|
|||||||
"tags": [
|
"tags": [
|
||||||
"Nodes"
|
"Nodes"
|
||||||
],
|
],
|
||||||
"summary": "Trigger the official panel self-updater on each given node (downloads the latest release and restarts). Only enabled, online nodes are updated; offline/disabled ones are reported as skipped. Returns a per-node result list.",
|
"summary": "Trigger the official panel self-updater on each given node (downloads the latest release and restarts). Only enabled, online nodes are updated; offline/disabled ones are reported as skipped. Set \"dev\": true to move the nodes to the rolling per-commit dev channel instead of the latest stable release. Returns a per-node result list.",
|
||||||
"operationId": "post_panel_api_nodes_updatePanel",
|
"operationId": "post_panel_api_nodes_updatePanel",
|
||||||
"requestBody": {
|
"requestBody": {
|
||||||
"required": true,
|
"required": true,
|
||||||
@@ -7393,7 +7454,8 @@
|
|||||||
1,
|
1,
|
||||||
2,
|
2,
|
||||||
3
|
3
|
||||||
]
|
],
|
||||||
|
"dev": false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -59,8 +59,8 @@ export function useNodeMutations() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const updatePanelsMut = useMutation({
|
const updatePanelsMut = useMutation({
|
||||||
mutationFn: (ids: number[]) =>
|
mutationFn: ({ ids, dev }: { ids: number[]; dev: boolean }) =>
|
||||||
HttpUtil.post<NodeUpdateResult[]>('/panel/api/nodes/updatePanel', { ids }, {
|
HttpUtil.post<NodeUpdateResult[]>('/panel/api/nodes/updatePanel', { ids, dev }, {
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
}),
|
}),
|
||||||
onSuccess: (msg) => { if (msg?.success) invalidate(); },
|
onSuccess: (msg) => { if (msg?.success) invalidate(); },
|
||||||
@@ -72,7 +72,7 @@ export function useNodeMutations() {
|
|||||||
remove: (id: number) => removeMut.mutateAsync(id),
|
remove: (id: number) => removeMut.mutateAsync(id),
|
||||||
setEnable: (id: number, enable: boolean) => setEnableMut.mutateAsync({ id, enable }),
|
setEnable: (id: number, enable: boolean) => setEnableMut.mutateAsync({ id, enable }),
|
||||||
probe: (id: number) => probeMut.mutateAsync(id),
|
probe: (id: number) => probeMut.mutateAsync(id),
|
||||||
updatePanels: (ids: number[]): Promise<Msg<NodeUpdateResult[]>> => updatePanelsMut.mutateAsync(ids),
|
updatePanels: (ids: number[], dev: boolean): Promise<Msg<NodeUpdateResult[]>> => updatePanelsMut.mutateAsync({ ids, dev }),
|
||||||
testConnection: async (payload: Partial<NodeRecord>): Promise<Msg<ProbeResult>> => {
|
testConnection: async (payload: Partial<NodeRecord>): Promise<Msg<ProbeResult>> => {
|
||||||
const raw = await HttpUtil.post('/panel/api/nodes/test', payload);
|
const raw = await HttpUtil.post('/panel/api/nodes/test', payload);
|
||||||
return parseMsg(raw, ProbeResultSchema, 'nodes/test');
|
return parseMsg(raw, ProbeResultSchema, 'nodes/test');
|
||||||
|
|||||||
@@ -52,6 +52,8 @@ export const EXAMPLES: Record<string, unknown> = {
|
|||||||
"subEnableRouting": false,
|
"subEnableRouting": false,
|
||||||
"subEncrypt": false,
|
"subEncrypt": false,
|
||||||
"subHideSettings": false,
|
"subHideSettings": false,
|
||||||
|
"subIncyEnableRouting": false,
|
||||||
|
"subIncyRoutingRules": "",
|
||||||
"subJsonEnable": false,
|
"subJsonEnable": false,
|
||||||
"subJsonFinalMask": "",
|
"subJsonFinalMask": "",
|
||||||
"subJsonMux": "",
|
"subJsonMux": "",
|
||||||
@@ -152,6 +154,8 @@ export const EXAMPLES: Record<string, unknown> = {
|
|||||||
"subEnableRouting": false,
|
"subEnableRouting": false,
|
||||||
"subEncrypt": false,
|
"subEncrypt": false,
|
||||||
"subHideSettings": false,
|
"subHideSettings": false,
|
||||||
|
"subIncyEnableRouting": false,
|
||||||
|
"subIncyRoutingRules": "",
|
||||||
"subJsonEnable": false,
|
"subJsonEnable": false,
|
||||||
"subJsonFinalMask": "",
|
"subJsonFinalMask": "",
|
||||||
"subJsonMux": "",
|
"subJsonMux": "",
|
||||||
|
|||||||
@@ -206,6 +206,14 @@ export const SCHEMAS: Record<string, unknown> = {
|
|||||||
"description": "Hide server settings in happ subscription (Only for Happ)",
|
"description": "Hide server settings in happ subscription (Only for Happ)",
|
||||||
"type": "boolean"
|
"type": "boolean"
|
||||||
},
|
},
|
||||||
|
"subIncyEnableRouting": {
|
||||||
|
"description": "Enable routing injection for the Incy client",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"subIncyRoutingRules": {
|
||||||
|
"description": "Incy routing deep-link injected into the subscription body (Only for Incy)",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
"subJsonEnable": {
|
"subJsonEnable": {
|
||||||
"description": "Enable JSON subscription endpoint",
|
"description": "Enable JSON subscription endpoint",
|
||||||
"type": "boolean"
|
"type": "boolean"
|
||||||
@@ -431,6 +439,8 @@ export const SCHEMAS: Record<string, unknown> = {
|
|||||||
"subEnableRouting",
|
"subEnableRouting",
|
||||||
"subEncrypt",
|
"subEncrypt",
|
||||||
"subHideSettings",
|
"subHideSettings",
|
||||||
|
"subIncyEnableRouting",
|
||||||
|
"subIncyRoutingRules",
|
||||||
"subJsonEnable",
|
"subJsonEnable",
|
||||||
"subJsonFinalMask",
|
"subJsonFinalMask",
|
||||||
"subJsonMux",
|
"subJsonMux",
|
||||||
@@ -701,6 +711,14 @@ export const SCHEMAS: Record<string, unknown> = {
|
|||||||
"description": "Hide server settings in happ subscription (Only for Happ)",
|
"description": "Hide server settings in happ subscription (Only for Happ)",
|
||||||
"type": "boolean"
|
"type": "boolean"
|
||||||
},
|
},
|
||||||
|
"subIncyEnableRouting": {
|
||||||
|
"description": "Enable routing injection for the Incy client",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"subIncyRoutingRules": {
|
||||||
|
"description": "Incy routing deep-link injected into the subscription body (Only for Incy)",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
"subJsonEnable": {
|
"subJsonEnable": {
|
||||||
"description": "Enable JSON subscription endpoint",
|
"description": "Enable JSON subscription endpoint",
|
||||||
"type": "boolean"
|
"type": "boolean"
|
||||||
@@ -933,6 +951,8 @@ export const SCHEMAS: Record<string, unknown> = {
|
|||||||
"subEnableRouting",
|
"subEnableRouting",
|
||||||
"subEncrypt",
|
"subEncrypt",
|
||||||
"subHideSettings",
|
"subHideSettings",
|
||||||
|
"subIncyEnableRouting",
|
||||||
|
"subIncyRoutingRules",
|
||||||
"subJsonEnable",
|
"subJsonEnable",
|
||||||
"subJsonFinalMask",
|
"subJsonFinalMask",
|
||||||
"subJsonMux",
|
"subJsonMux",
|
||||||
|
|||||||
@@ -58,6 +58,8 @@ export interface AllSetting {
|
|||||||
subEnableRouting: boolean;
|
subEnableRouting: boolean;
|
||||||
subEncrypt: boolean;
|
subEncrypt: boolean;
|
||||||
subHideSettings: boolean;
|
subHideSettings: boolean;
|
||||||
|
subIncyEnableRouting: boolean;
|
||||||
|
subIncyRoutingRules: string;
|
||||||
subJsonEnable: boolean;
|
subJsonEnable: boolean;
|
||||||
subJsonFinalMask: string;
|
subJsonFinalMask: string;
|
||||||
subJsonMux: string;
|
subJsonMux: string;
|
||||||
@@ -159,6 +161,8 @@ export interface AllSettingView {
|
|||||||
subEnableRouting: boolean;
|
subEnableRouting: boolean;
|
||||||
subEncrypt: boolean;
|
subEncrypt: boolean;
|
||||||
subHideSettings: boolean;
|
subHideSettings: boolean;
|
||||||
|
subIncyEnableRouting: boolean;
|
||||||
|
subIncyRoutingRules: string;
|
||||||
subJsonEnable: boolean;
|
subJsonEnable: boolean;
|
||||||
subJsonFinalMask: string;
|
subJsonFinalMask: string;
|
||||||
subJsonMux: string;
|
subJsonMux: string;
|
||||||
|
|||||||
@@ -70,6 +70,8 @@ export const AllSettingSchema = z.object({
|
|||||||
subEnableRouting: z.boolean(),
|
subEnableRouting: z.boolean(),
|
||||||
subEncrypt: z.boolean(),
|
subEncrypt: z.boolean(),
|
||||||
subHideSettings: z.boolean(),
|
subHideSettings: z.boolean(),
|
||||||
|
subIncyEnableRouting: z.boolean(),
|
||||||
|
subIncyRoutingRules: z.string(),
|
||||||
subJsonEnable: z.boolean(),
|
subJsonEnable: z.boolean(),
|
||||||
subJsonFinalMask: z.string(),
|
subJsonFinalMask: z.string(),
|
||||||
subJsonMux: z.string(),
|
subJsonMux: z.string(),
|
||||||
@@ -172,6 +174,8 @@ export const AllSettingViewSchema = z.object({
|
|||||||
subEnableRouting: z.boolean(),
|
subEnableRouting: z.boolean(),
|
||||||
subEncrypt: z.boolean(),
|
subEncrypt: z.boolean(),
|
||||||
subHideSettings: z.boolean(),
|
subHideSettings: z.boolean(),
|
||||||
|
subIncyEnableRouting: z.boolean(),
|
||||||
|
subIncyRoutingRules: z.string(),
|
||||||
subJsonEnable: z.boolean(),
|
subJsonEnable: z.boolean(),
|
||||||
subJsonFinalMask: z.string(),
|
subJsonFinalMask: z.string(),
|
||||||
subJsonMux: z.string(),
|
subJsonMux: z.string(),
|
||||||
|
|||||||
@@ -341,7 +341,7 @@ export function useClients() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const bulkAdjustMut = useMutation({
|
const bulkAdjustMut = useMutation({
|
||||||
mutationFn: async (payload: { emails: string[]; addDays: number; addBytes: number }): Promise<Msg<BulkAdjustResult>> => {
|
mutationFn: async (payload: { emails: string[]; addDays: number; addBytes: number; flow: string }): Promise<Msg<BulkAdjustResult>> => {
|
||||||
const raw = await HttpUtil.post('/panel/api/clients/bulkAdjust', payload, JSON_HEADERS);
|
const raw = await HttpUtil.post('/panel/api/clients/bulkAdjust', payload, JSON_HEADERS);
|
||||||
return parseMsg(raw, BulkAdjustResultSchema, 'clients/bulkAdjust');
|
return parseMsg(raw, BulkAdjustResultSchema, 'clients/bulkAdjust');
|
||||||
},
|
},
|
||||||
@@ -350,13 +350,13 @@ export function useClients() {
|
|||||||
|
|
||||||
const attachMut = useMutation({
|
const attachMut = useMutation({
|
||||||
mutationFn: ({ email, inboundIds }: { email: string; inboundIds: number[] }) =>
|
mutationFn: ({ email, inboundIds }: { email: string; inboundIds: number[] }) =>
|
||||||
HttpUtil.post(`/panel/api/clients/${encodeURIComponent(email)}/attach`, { inboundIds }, JSON_HEADERS),
|
HttpUtil.post(`/panel/api/clients/${encodeURIComponent(email)}/attach`, { inboundIds }, { ...JSON_HEADERS, silentSuccess: true }),
|
||||||
onSuccess: (msg) => { if (msg?.success) invalidateAll(); },
|
onSuccess: (msg) => { if (msg?.success) invalidateAll(); },
|
||||||
});
|
});
|
||||||
|
|
||||||
const setExternalLinksMut = useMutation({
|
const setExternalLinksMut = useMutation({
|
||||||
mutationFn: ({ email, externalLinks }: { email: string; externalLinks: ExternalLinkInput[] }) =>
|
mutationFn: ({ email, externalLinks }: { email: string; externalLinks: ExternalLinkInput[] }) =>
|
||||||
HttpUtil.post(`/panel/api/clients/${encodeURIComponent(email)}/externalLinks`, { externalLinks }, JSON_HEADERS),
|
HttpUtil.post(`/panel/api/clients/${encodeURIComponent(email)}/externalLinks`, { externalLinks }, { ...JSON_HEADERS, silentSuccess: true }),
|
||||||
onSuccess: (msg) => { if (msg?.success) invalidateAll(); },
|
onSuccess: (msg) => { if (msg?.success) invalidateAll(); },
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -370,7 +370,7 @@ export function useClients() {
|
|||||||
|
|
||||||
const detachMut = useMutation({
|
const detachMut = useMutation({
|
||||||
mutationFn: ({ email, inboundIds }: { email: string; inboundIds: number[] }) =>
|
mutationFn: ({ email, inboundIds }: { email: string; inboundIds: number[] }) =>
|
||||||
HttpUtil.post(`/panel/api/clients/${encodeURIComponent(email)}/detach`, { inboundIds }, JSON_HEADERS),
|
HttpUtil.post(`/panel/api/clients/${encodeURIComponent(email)}/detach`, { inboundIds }, { ...JSON_HEADERS, silentSuccess: true }),
|
||||||
onSuccess: (msg) => { if (msg?.success) invalidateAll(); },
|
onSuccess: (msg) => { if (msg?.success) invalidateAll(); },
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -435,9 +435,9 @@ export function useClients() {
|
|||||||
if (!Array.isArray(payloads) || payloads.length === 0) return Promise.resolve(null as unknown as Msg<BulkCreateResult>);
|
if (!Array.isArray(payloads) || payloads.length === 0) return Promise.resolve(null as unknown as Msg<BulkCreateResult>);
|
||||||
return bulkCreateMut.mutateAsync(payloads);
|
return bulkCreateMut.mutateAsync(payloads);
|
||||||
}, [bulkCreateMut]);
|
}, [bulkCreateMut]);
|
||||||
const bulkAdjust = useCallback((emails: string[], addDays: number, addBytes: number) => {
|
const bulkAdjust = useCallback((emails: string[], addDays: number, addBytes: number, flow = '') => {
|
||||||
if (!Array.isArray(emails) || emails.length === 0) return Promise.resolve(null);
|
if (!Array.isArray(emails) || emails.length === 0) return Promise.resolve(null);
|
||||||
return bulkAdjustMut.mutateAsync({ emails, addDays, addBytes });
|
return bulkAdjustMut.mutateAsync({ emails, addDays, addBytes, flow });
|
||||||
}, [bulkAdjustMut]);
|
}, [bulkAdjustMut]);
|
||||||
const bulkAddToGroup = useCallback((emails: string[], group: string) => {
|
const bulkAddToGroup = useCallback((emails: string[], group: string) => {
|
||||||
if (!Array.isArray(emails) || emails.length === 0) return Promise.resolve(null);
|
if (!Array.isArray(emails) || emails.length === 0) return Promise.resolve(null);
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// per client. This file is the single frontend source of truth for the picker
|
// per client. This file is the single frontend source of truth for the picker
|
||||||
// UI and the live preview — keep the token list in sync with remark_vars.go.
|
// UI and the live preview — keep the token list in sync with remark_vars.go.
|
||||||
|
|
||||||
export type RemarkVarGroup = 'client' | 'traffic' | 'time';
|
export type RemarkVarGroup = 'client' | 'traffic' | 'time' | 'connection';
|
||||||
|
|
||||||
export interface RemarkVar {
|
export interface RemarkVar {
|
||||||
/** Bare token name, e.g. "TRAFFIC_LEFT" (rendered as {{TRAFFIC_LEFT}}). */
|
/** Bare token name, e.g. "TRAFFIC_LEFT" (rendered as {{TRAFFIC_LEFT}}). */
|
||||||
@@ -13,7 +13,7 @@ export interface RemarkVar {
|
|||||||
sample: string;
|
sample: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const REMARK_VAR_GROUPS: RemarkVarGroup[] = ['client', 'traffic', 'time'];
|
export const REMARK_VAR_GROUPS: RemarkVarGroup[] = ['client', 'traffic', 'time', 'connection'];
|
||||||
|
|
||||||
export const REMARK_VARIABLES: RemarkVar[] = [
|
export const REMARK_VARIABLES: RemarkVar[] = [
|
||||||
// Client identity
|
// Client identity
|
||||||
@@ -36,11 +36,19 @@ export const REMARK_VARIABLES: RemarkVar[] = [
|
|||||||
{ token: 'DOWN', group: 'traffic', sample: '3.20GB' },
|
{ token: 'DOWN', group: 'traffic', sample: '3.20GB' },
|
||||||
// Time / status
|
// Time / status
|
||||||
{ token: 'STATUS', group: 'time', sample: 'active' },
|
{ token: 'STATUS', group: 'time', sample: 'active' },
|
||||||
|
{ token: 'STATUS_EMOJI', group: 'time', sample: '✅' },
|
||||||
{ token: 'DAYS_LEFT', group: 'time', sample: '12' },
|
{ token: 'DAYS_LEFT', group: 'time', sample: '12' },
|
||||||
|
{ token: 'TIME_LEFT', group: 'time', sample: '12d 4h 30m' },
|
||||||
|
{ token: 'USAGE_PERCENTAGE', group: 'time', sample: '52.3%' },
|
||||||
{ token: 'EXPIRE_DATE', group: 'time', sample: '2026-09-01' },
|
{ token: 'EXPIRE_DATE', group: 'time', sample: '2026-09-01' },
|
||||||
|
{ token: 'JALALI_EXPIRE_DATE', group: 'time', sample: '1405/06/10' },
|
||||||
{ token: 'EXPIRE_UNIX', group: 'time', sample: '1788300000' },
|
{ token: 'EXPIRE_UNIX', group: 'time', sample: '1788300000' },
|
||||||
{ token: 'CREATED_UNIX', group: 'time', sample: '1700000000' },
|
{ token: 'CREATED_UNIX', group: 'time', sample: '1700000000' },
|
||||||
{ token: 'RESET_DAYS', group: 'time', sample: '30' },
|
{ token: 'RESET_DAYS', group: 'time', sample: '30' },
|
||||||
|
// Connection (inbound config descriptors)
|
||||||
|
{ token: 'PROTOCOL', group: 'connection', sample: 'VLESS' },
|
||||||
|
{ token: 'TRANSPORT', group: 'connection', sample: 'ws' },
|
||||||
|
{ token: 'SECURITY', group: 'connection', sample: 'TLS' },
|
||||||
];
|
];
|
||||||
|
|
||||||
const SAMPLE_BY_TOKEN: Record<string, string> = Object.fromEntries(
|
const SAMPLE_BY_TOKEN: Record<string, string> = Object.fromEntries(
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import type {
|
|||||||
DnsRuleForm,
|
DnsRuleForm,
|
||||||
FreedomFinalRuleForm,
|
FreedomFinalRuleForm,
|
||||||
FreedomOutboundFormSettings,
|
FreedomOutboundFormSettings,
|
||||||
|
HttpOutboundFormSettings,
|
||||||
HysteriaOutboundFormSettings,
|
HysteriaOutboundFormSettings,
|
||||||
LoopbackOutboundFormSettings,
|
LoopbackOutboundFormSettings,
|
||||||
MuxForm,
|
MuxForm,
|
||||||
@@ -178,6 +179,26 @@ function simpleAuthFromWire(raw: Raw, defaultPort: number): SimpleAuthFormSettin
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function stringRecordFromWire(raw: unknown): Record<string, string> {
|
||||||
|
const obj = asObject(raw);
|
||||||
|
const out: Record<string, string> = {};
|
||||||
|
for (const [k, v] of Object.entries(obj)) {
|
||||||
|
if (typeof v === 'string') out[k] = v;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// HTTP outbound reuses the SOCKS server/user shape but also carries xray's
|
||||||
|
// top-level `settings.headers` (HTTPClientConfig.Headers), the CONNECT
|
||||||
|
// headers sent to the upstream proxy. xray ignores per-server `headers`,
|
||||||
|
// so only the settings-level map round-trips (issue #5519).
|
||||||
|
function httpFromWire(raw: Raw): HttpOutboundFormSettings {
|
||||||
|
return {
|
||||||
|
...simpleAuthFromWire(raw, 8080),
|
||||||
|
headers: stringRecordFromWire(raw.headers),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function wireguardFromWire(raw: Raw): WireguardOutboundFormSettings {
|
function wireguardFromWire(raw: Raw): WireguardOutboundFormSettings {
|
||||||
const secretKey = asString(raw.secretKey);
|
const secretKey = asString(raw.secretKey);
|
||||||
const pubKey = secretKey.length > 0
|
const pubKey = secretKey.length > 0
|
||||||
@@ -395,7 +416,7 @@ export function rawOutboundToFormValues(raw: RawOutboundRow): OutboundFormValues
|
|||||||
case 'trojan': typed = { protocol: 'trojan', settings: trojanFromWire(settings) }; break;
|
case 'trojan': typed = { protocol: 'trojan', settings: trojanFromWire(settings) }; break;
|
||||||
case 'shadowsocks': typed = { protocol: 'shadowsocks', settings: shadowsocksFromWire(settings) }; break;
|
case 'shadowsocks': typed = { protocol: 'shadowsocks', settings: shadowsocksFromWire(settings) }; break;
|
||||||
case 'socks': typed = { protocol: 'socks', settings: simpleAuthFromWire(settings, 1080) }; break;
|
case 'socks': typed = { protocol: 'socks', settings: simpleAuthFromWire(settings, 1080) }; break;
|
||||||
case 'http': typed = { protocol: 'http', settings: simpleAuthFromWire(settings, 8080) }; break;
|
case 'http': typed = { protocol: 'http', settings: httpFromWire(settings) }; break;
|
||||||
case 'wireguard': typed = { protocol: 'wireguard', settings: wireguardFromWire(settings) }; break;
|
case 'wireguard': typed = { protocol: 'wireguard', settings: wireguardFromWire(settings) }; break;
|
||||||
case 'hysteria': typed = { protocol: 'hysteria', settings: hysteriaFromWire(settings) }; break;
|
case 'hysteria': typed = { protocol: 'hysteria', settings: hysteriaFromWire(settings) }; break;
|
||||||
case 'freedom': typed = { protocol: 'freedom', settings: freedomFromWire(settings) }; break;
|
case 'freedom': typed = { protocol: 'freedom', settings: freedomFromWire(settings) }; break;
|
||||||
@@ -489,6 +510,14 @@ function simpleAuthToWire(s: SimpleAuthFormSettings) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function httpToWire(s: HttpOutboundFormSettings): Raw {
|
||||||
|
const wire: Raw = simpleAuthToWire(s);
|
||||||
|
if (s.headers && Object.keys(s.headers).length > 0) {
|
||||||
|
wire.headers = s.headers;
|
||||||
|
}
|
||||||
|
return wire;
|
||||||
|
}
|
||||||
|
|
||||||
function wireguardToWire(s: WireguardOutboundFormSettings) {
|
function wireguardToWire(s: WireguardOutboundFormSettings) {
|
||||||
return {
|
return {
|
||||||
mtu: s.mtu || undefined,
|
mtu: s.mtu || undefined,
|
||||||
@@ -629,7 +658,7 @@ export function formValuesToWirePayload(values: OutboundFormValues): WireOutboun
|
|||||||
case 'trojan': settings = trojanToWire(values.settings); break;
|
case 'trojan': settings = trojanToWire(values.settings); break;
|
||||||
case 'shadowsocks': settings = shadowsocksToWire(values.settings); break;
|
case 'shadowsocks': settings = shadowsocksToWire(values.settings); break;
|
||||||
case 'socks': settings = simpleAuthToWire(values.settings); break;
|
case 'socks': settings = simpleAuthToWire(values.settings); break;
|
||||||
case 'http': settings = simpleAuthToWire(values.settings); break;
|
case 'http': settings = httpToWire(values.settings); break;
|
||||||
case 'wireguard': settings = wireguardToWire(values.settings); break;
|
case 'wireguard': settings = wireguardToWire(values.settings); break;
|
||||||
case 'hysteria': settings = hysteriaToWire(values.settings); break;
|
case 'hysteria': settings = hysteriaToWire(values.settings); break;
|
||||||
case 'freedom': settings = freedomToWire(values.settings); break;
|
case 'freedom': settings = freedomToWire(values.settings); break;
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ export class AllSetting {
|
|||||||
pageSize = 25;
|
pageSize = 25;
|
||||||
expireDiff = 0;
|
expireDiff = 0;
|
||||||
trafficDiff = 0;
|
trafficDiff = 0;
|
||||||
remarkTemplate = '{{INBOUND}}|📊{{TRAFFIC_LEFT}}|⏳{{DAYS_LEFT}}D';
|
remarkTemplate = '{{INBOUND}}-{{EMAIL}}|📊{{TRAFFIC_LEFT}}|⏳{{DAYS_LEFT}}D';
|
||||||
datepicker: 'gregorian' | 'jalalian' = 'gregorian';
|
datepicker: 'gregorian' | 'jalalian' = 'gregorian';
|
||||||
tgBotEnable = false;
|
tgBotEnable = false;
|
||||||
tgBotToken = '';
|
tgBotToken = '';
|
||||||
@@ -35,6 +35,8 @@ export class AllSetting {
|
|||||||
subAnnounce = '';
|
subAnnounce = '';
|
||||||
subEnableRouting = false;
|
subEnableRouting = false;
|
||||||
subRoutingRules = '';
|
subRoutingRules = '';
|
||||||
|
subIncyEnableRouting = false;
|
||||||
|
subIncyRoutingRules = '';
|
||||||
subListen = '';
|
subListen = '';
|
||||||
subPort = 2096;
|
subPort = 2096;
|
||||||
subPath = '/sub/';
|
subPath = '/sub/';
|
||||||
|
|||||||
@@ -400,6 +400,15 @@ export const sections: readonly Section[] = [
|
|||||||
path: '/panel/api/server/updatePanel',
|
path: '/panel/api/server/updatePanel',
|
||||||
summary: 'Self-update the panel to the latest version. The server restarts on success.',
|
summary: 'Self-update the panel to the latest version. The server restarts on success.',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
method: 'POST',
|
||||||
|
path: '/panel/api/server/setUpdateChannel',
|
||||||
|
summary: 'Toggle the panel update channel between stable and the rolling per-commit dev release. Only effective on dev builds.',
|
||||||
|
params: [
|
||||||
|
{ name: 'dev', in: 'body (form)', type: 'boolean', desc: 'true = dev channel, false = stable.' },
|
||||||
|
],
|
||||||
|
body: 'dev=true',
|
||||||
|
},
|
||||||
{
|
{
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
path: '/panel/api/server/updateGeofile',
|
path: '/panel/api/server/updateGeofile',
|
||||||
@@ -635,8 +644,8 @@ export const sections: readonly Section[] = [
|
|||||||
{
|
{
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
path: '/panel/api/clients/bulkAdjust',
|
path: '/panel/api/clients/bulkAdjust',
|
||||||
summary: 'Shift expiry and/or traffic quota for many clients in one call. addDays/addBytes may be negative. Clients with unlimited expiry (expiryTime=0) or unlimited traffic (totalGB=0) are skipped for the corresponding field — bulk extend never converts unlimited to limited. Returns the adjusted count and per-email skip reasons.',
|
summary: 'Shift expiry and/or traffic quota for many clients in one call. addDays/addBytes may be negative. Clients with unlimited expiry (expiryTime=0) or unlimited traffic (totalGB=0) are skipped for the corresponding field — bulk extend never converts unlimited to limited. The optional flow directive sets the XTLS flow on every client: "none" clears it, "xtls-rprx-vision"/"xtls-rprx-vision-udp443" set it where the inbound supports it (omit or "" to leave it unchanged). Returns the adjusted count and per-email skip reasons.',
|
||||||
body: '{\n "emails": ["alice", "bob"],\n "addDays": 30,\n "addBytes": 53687091200\n}',
|
body: '{\n "emails": ["alice", "bob"],\n "addDays": 30,\n "addBytes": 53687091200,\n "flow": "xtls-rprx-vision"\n}',
|
||||||
response: '{\n "success": true,\n "obj": {\n "adjusted": 2,\n "skipped": [\n { "email": "carol", "reason": "unlimited expiry" }\n ]\n }\n}',
|
response: '{\n "success": true,\n "obj": {\n "adjusted": 2,\n "skipped": [\n { "email": "carol", "reason": "unlimited expiry" }\n ]\n }\n}',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -936,8 +945,8 @@ export const sections: readonly Section[] = [
|
|||||||
{
|
{
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
path: '/panel/api/nodes/updatePanel',
|
path: '/panel/api/nodes/updatePanel',
|
||||||
summary: 'Trigger the official panel self-updater on each given node (downloads the latest release and restarts). Only enabled, online nodes are updated; offline/disabled ones are reported as skipped. Returns a per-node result list.',
|
summary: 'Trigger the official panel self-updater on each given node (downloads the latest release and restarts). Only enabled, online nodes are updated; offline/disabled ones are reported as skipped. Set "dev": true to move the nodes to the rolling per-commit dev channel instead of the latest stable release. Returns a per-node result list.',
|
||||||
body: '{\n "ids": [1, 2, 3]\n}',
|
body: '{\n "ids": [1, 2, 3],\n "dev": false\n}',
|
||||||
response: '{\n "success": true,\n "obj": [\n { "id": 1, "name": "de-1", "ok": true },\n { "id": 2, "name": "fr-1", "ok": false, "error": "node is offline" }\n ]\n}',
|
response: '{\n "success": true,\n "obj": [\n { "id": 1, "name": "de-1", "ok": true },\n { "id": 2, "name": "fr-1", "ok": false, "error": "node is offline" }\n ]\n}',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,16 +1,19 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { Alert, Form, InputNumber, Modal, message } from 'antd';
|
import { Alert, Form, InputNumber, Modal, Select, message } from 'antd';
|
||||||
|
|
||||||
import { ClientBulkAdjustFormSchema } from '@/schemas/client';
|
import { ClientBulkAdjustFormSchema } from '@/schemas/client';
|
||||||
|
import { TLS_FLOW_CONTROL } from '@/schemas/primitives/flow';
|
||||||
|
|
||||||
const GB = 1024 * 1024 * 1024;
|
const GB = 1024 * 1024 * 1024;
|
||||||
|
|
||||||
|
const FLOW_CLEAR = 'none';
|
||||||
|
|
||||||
interface ClientBulkAdjustModalProps {
|
interface ClientBulkAdjustModalProps {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
count: number;
|
count: number;
|
||||||
onOpenChange: (open: boolean) => void;
|
onOpenChange: (open: boolean) => void;
|
||||||
onSubmit: (addDays: number, addBytes: number) => Promise<{ adjusted: number; skipped?: { email: string; reason: string }[] } | null>;
|
onSubmit: (addDays: number, addBytes: number, flow: string) => Promise<{ adjusted: number; skipped?: { email: string; reason: string }[] } | null>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function ClientBulkAdjustModal({ open, count, onOpenChange, onSubmit }: ClientBulkAdjustModalProps) {
|
export default function ClientBulkAdjustModal({ open, count, onOpenChange, onSubmit }: ClientBulkAdjustModalProps) {
|
||||||
@@ -18,12 +21,14 @@ export default function ClientBulkAdjustModal({ open, count, onOpenChange, onSub
|
|||||||
const [messageApi, messageContextHolder] = message.useMessage();
|
const [messageApi, messageContextHolder] = message.useMessage();
|
||||||
const [addDays, setAddDays] = useState<number>(0);
|
const [addDays, setAddDays] = useState<number>(0);
|
||||||
const [addGB, setAddGB] = useState<number>(0);
|
const [addGB, setAddGB] = useState<number>(0);
|
||||||
|
const [flow, setFlow] = useState<string>('');
|
||||||
const [submitting, setSubmitting] = useState(false);
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (open) {
|
if (open) {
|
||||||
setAddDays(0);
|
setAddDays(0);
|
||||||
setAddGB(0);
|
setAddGB(0);
|
||||||
|
setFlow('');
|
||||||
}
|
}
|
||||||
}, [open]);
|
}, [open]);
|
||||||
|
|
||||||
@@ -31,16 +36,17 @@ export default function ClientBulkAdjustModal({ open, count, onOpenChange, onSub
|
|||||||
const validated = ClientBulkAdjustFormSchema.safeParse({
|
const validated = ClientBulkAdjustFormSchema.safeParse({
|
||||||
addDays: Math.trunc(Number(addDays) || 0),
|
addDays: Math.trunc(Number(addDays) || 0),
|
||||||
addGB: Number(addGB) || 0,
|
addGB: Number(addGB) || 0,
|
||||||
|
flow,
|
||||||
});
|
});
|
||||||
if (!validated.success) {
|
if (!validated.success) {
|
||||||
messageApi.warning(t(validated.error.issues[0]?.message ?? 'somethingWentWrong'));
|
messageApi.warning(t(validated.error.issues[0]?.message ?? 'somethingWentWrong'));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const { addDays: days, addGB: gb } = validated.data;
|
const { addDays: days, addGB: gb, flow: flowValue } = validated.data;
|
||||||
setSubmitting(true);
|
setSubmitting(true);
|
||||||
try {
|
try {
|
||||||
const bytes = Math.trunc(gb * GB);
|
const bytes = Math.trunc(gb * GB);
|
||||||
const result = await onSubmit(days, bytes);
|
const result = await onSubmit(days, bytes, flowValue);
|
||||||
if (!result) return;
|
if (!result) return;
|
||||||
const ok = result.adjusted ?? 0;
|
const ok = result.adjusted ?? 0;
|
||||||
const skipped = result.skipped?.length ?? 0;
|
const skipped = result.skipped?.length ?? 0;
|
||||||
@@ -95,6 +101,18 @@ export default function ClientBulkAdjustModal({ open, count, onOpenChange, onSub
|
|||||||
step={1}
|
step={1}
|
||||||
/>
|
/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
<Form.Item label={t('pages.clients.bulkFlow')}>
|
||||||
|
<Select
|
||||||
|
value={flow}
|
||||||
|
onChange={setFlow}
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
options={[
|
||||||
|
{ value: '', label: t('pages.clients.bulkFlowNoChange') },
|
||||||
|
{ value: FLOW_CLEAR, label: t('pages.clients.bulkFlowDisable') },
|
||||||
|
...Object.values(TLS_FLOW_CONTROL).map((k) => ({ value: k, label: k })),
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
</Form>
|
</Form>
|
||||||
</Modal>
|
</Modal>
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -357,7 +357,7 @@ export default function ClientInfoModal({
|
|||||||
const parts = parseLinkParts(link);
|
const parts = parseLinkParts(link);
|
||||||
const fallback = `${t('pages.clients.link')} ${idx + 1}`;
|
const fallback = `${t('pages.clients.link')} ${idx + 1}`;
|
||||||
const rowTitle = (parts && linkMetaText(parts)) || fallback;
|
const rowTitle = (parts && linkMetaText(parts)) || fallback;
|
||||||
const qrRemark = [parts?.remark, client.email].filter(Boolean).join('-') || rowTitle;
|
const qrRemark = parts?.remark || rowTitle;
|
||||||
const canQr = !isPostQuantumLink(link);
|
const canQr = !isPostQuantumLink(link);
|
||||||
return (
|
return (
|
||||||
<div key={idx} className="link-row">
|
<div key={idx} className="link-row">
|
||||||
|
|||||||
@@ -106,7 +106,7 @@ export default function ClientQrModal({
|
|||||||
children: (
|
children: (
|
||||||
<QrPanel
|
<QrPanel
|
||||||
value={link}
|
value={link}
|
||||||
remark={`${client?.email || ''} #${idx + 1}`}
|
remark={parts?.remark || `${client?.email || ''} #${idx + 1}`}
|
||||||
showQr={!isPostQuantumLink(link)}
|
showQr={!isPostQuantumLink(link)}
|
||||||
/>
|
/>
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -685,16 +685,18 @@ export default function ClientsPage() {
|
|||||||
}
|
}
|
||||||
const updateMsg = await update(meta.email, payload);
|
const updateMsg = await update(meta.email, payload);
|
||||||
if (!updateMsg?.success) return updateMsg;
|
if (!updateMsg?.success) return updateMsg;
|
||||||
|
const rawEmail = (payload as { email?: unknown }).email;
|
||||||
|
const emailKey = typeof rawEmail === 'string' && rawEmail.trim() ? rawEmail.trim() : meta.email;
|
||||||
if (Array.isArray(meta.attach) && meta.attach.length > 0) {
|
if (Array.isArray(meta.attach) && meta.attach.length > 0) {
|
||||||
const r = await attach(meta.email, meta.attach);
|
const r = await attach(emailKey, meta.attach);
|
||||||
if (!r?.success) return r;
|
if (!r?.success) return r;
|
||||||
}
|
}
|
||||||
if (Array.isArray(meta.detach) && meta.detach.length > 0) {
|
if (Array.isArray(meta.detach) && meta.detach.length > 0) {
|
||||||
const r = await detach(meta.email, meta.detach);
|
const r = await detach(emailKey, meta.detach);
|
||||||
if (!r?.success) return r;
|
if (!r?.success) return r;
|
||||||
}
|
}
|
||||||
// Always replace the client's external links (an empty set clears them).
|
// Always replace the client's external links (an empty set clears them).
|
||||||
const r = await setExternalLinks(meta.email, meta.externalLinks);
|
const r = await setExternalLinks(emailKey, meta.externalLinks);
|
||||||
if (!r?.success) return r;
|
if (!r?.success) return r;
|
||||||
return updateMsg;
|
return updateMsg;
|
||||||
}, [create, update, attach, detach, setExternalLinks]);
|
}, [create, update, attach, detach, setExternalLinks]);
|
||||||
@@ -1418,8 +1420,8 @@ export default function ClientsPage() {
|
|||||||
open={bulkAdjustOpen}
|
open={bulkAdjustOpen}
|
||||||
count={selectedRowKeys.length}
|
count={selectedRowKeys.length}
|
||||||
onOpenChange={setBulkAdjustOpen}
|
onOpenChange={setBulkAdjustOpen}
|
||||||
onSubmit={async (addDays, addBytes) => {
|
onSubmit={async (addDays, addBytes, flow) => {
|
||||||
const msg = await bulkAdjust([...selectedRowKeys], addDays, addBytes);
|
const msg = await bulkAdjust([...selectedRowKeys], addDays, addBytes, flow);
|
||||||
if (msg?.success) {
|
if (msg?.success) {
|
||||||
setSelectedRowKeys([]);
|
setSelectedRowKeys([]);
|
||||||
return msg.obj ?? { adjusted: 0 };
|
return msg.obj ?? { adjusted: 0 };
|
||||||
|
|||||||
@@ -285,8 +285,12 @@ export default function InboundFormModal({
|
|||||||
) => {
|
) => {
|
||||||
if (block?.id === authId) return true;
|
if (block?.id === authId) return true;
|
||||||
const label = (block?.label || '').toLowerCase().replace(/[-_\s]/g, '');
|
const label = (block?.label || '').toLowerCase().replace(/[-_\s]/g, '');
|
||||||
if (authId === 'mlkem768') return label.includes('mlkem768');
|
if (authId === 'mlkem768') return label.includes('mlkem768') && !label.includes('xorpub') && !label.includes('random');
|
||||||
if (authId === 'x25519') return label.includes('x25519');
|
if (authId === 'x25519') return label.includes('x25519') && !label.includes('xorpub') && !label.includes('random');
|
||||||
|
if (authId === 'mlkem768_xorpub') return label.includes('mlkem768') && label.includes('xorpub');
|
||||||
|
if (authId === 'mlkem768_random') return label.includes('mlkem768') && label.includes('random');
|
||||||
|
if (authId === 'x25519_xorpub') return label.includes('x25519') && label.includes('xorpub');
|
||||||
|
if (authId === 'x25519_random') return label.includes('x25519') && label.includes('random');
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -319,7 +323,19 @@ export default function InboundFormModal({
|
|||||||
const parts = enc.split('.').filter(Boolean);
|
const parts = enc.split('.').filter(Boolean);
|
||||||
const authKey = parts[parts.length - 1] || '';
|
const authKey = parts[parts.length - 1] || '';
|
||||||
if (!authKey) return t('pages.inbounds.vlessAuthCustom');
|
if (!authKey) return t('pages.inbounds.vlessAuthCustom');
|
||||||
return authKey.length > 300
|
const mode = parts[1] || 'native';
|
||||||
|
const keyType = authKey.length > 300 ? 'mlkem768' : 'x25519';
|
||||||
|
if (mode === 'xorpub') {
|
||||||
|
return keyType === 'mlkem768'
|
||||||
|
? t('pages.inbounds.vlessAuthMlkem768Xorpub')
|
||||||
|
: t('pages.inbounds.vlessAuthX25519Xorpub');
|
||||||
|
}
|
||||||
|
if (mode === 'random') {
|
||||||
|
return keyType === 'mlkem768'
|
||||||
|
? t('pages.inbounds.vlessAuthMlkem768Random')
|
||||||
|
: t('pages.inbounds.vlessAuthX25519Random');
|
||||||
|
}
|
||||||
|
return keyType === 'mlkem768'
|
||||||
? t('pages.inbounds.vlessAuthMlkem768')
|
? t('pages.inbounds.vlessAuthMlkem768')
|
||||||
: t('pages.inbounds.vlessAuthX25519');
|
: t('pages.inbounds.vlessAuthX25519');
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -1,12 +1,21 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { Button, Form, Input, InputNumber, Space, Typography } from 'antd';
|
import { Button, Form, Input, InputNumber, Select, Space, Typography } from 'antd';
|
||||||
|
|
||||||
|
type VlessAuthKind =
|
||||||
|
| 'x25519'
|
||||||
|
| 'x25519_xorpub'
|
||||||
|
| 'x25519_random'
|
||||||
|
| 'mlkem768'
|
||||||
|
| 'mlkem768_xorpub'
|
||||||
|
| 'mlkem768_random';
|
||||||
|
|
||||||
interface VlessFieldsProps {
|
interface VlessFieldsProps {
|
||||||
saving: boolean;
|
saving: boolean;
|
||||||
selectedVlessAuth: string;
|
selectedVlessAuth: string;
|
||||||
network: string;
|
network: string;
|
||||||
security: string;
|
security: string;
|
||||||
getNewVlessEnc: (kind: 'x25519' | 'mlkem768') => void;
|
getNewVlessEnc: (kind: VlessAuthKind) => void;
|
||||||
clearVlessEnc: () => void;
|
clearVlessEnc: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -19,6 +28,17 @@ export default function VlessFields({
|
|||||||
clearVlessEnc,
|
clearVlessEnc,
|
||||||
}: VlessFieldsProps) {
|
}: VlessFieldsProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const [authKind, setAuthKind] = useState<VlessAuthKind>('x25519');
|
||||||
|
|
||||||
|
const authOptions = [
|
||||||
|
{ value: 'x25519', label: t('pages.inbounds.vlessAuthX25519') },
|
||||||
|
{ value: 'x25519_xorpub', label: t('pages.inbounds.vlessAuthX25519Xorpub') },
|
||||||
|
{ value: 'x25519_random', label: t('pages.inbounds.vlessAuthX25519Random') },
|
||||||
|
{ value: 'mlkem768', label: t('pages.inbounds.vlessAuthMlkem768') },
|
||||||
|
{ value: 'mlkem768_xorpub', label: t('pages.inbounds.vlessAuthMlkem768Xorpub') },
|
||||||
|
{ value: 'mlkem768_random', label: t('pages.inbounds.vlessAuthMlkem768Random') },
|
||||||
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Form.Item name={['settings', 'decryption']} label={t('pages.inbounds.decryption')}>
|
<Form.Item name={['settings', 'decryption']} label={t('pages.inbounds.decryption')}>
|
||||||
@@ -27,13 +47,16 @@ export default function VlessFields({
|
|||||||
<Form.Item name={['settings', 'encryption']} label={t('pages.inbounds.encryption')}>
|
<Form.Item name={['settings', 'encryption']} label={t('pages.inbounds.encryption')}>
|
||||||
<Input />
|
<Input />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item label=" ">
|
<Form.Item label={t('pages.inbounds.vlessAuthGenerate')}>
|
||||||
<Space size={8} wrap>
|
<Space size={8} wrap>
|
||||||
<Button type="primary" loading={saving} onClick={() => getNewVlessEnc('x25519')}>
|
<Select
|
||||||
{t('pages.inbounds.vlessAuthX25519')}
|
value={authKind}
|
||||||
</Button>
|
onChange={(v) => setAuthKind(v)}
|
||||||
<Button type="primary" loading={saving} onClick={() => getNewVlessEnc('mlkem768')}>
|
options={authOptions}
|
||||||
{t('pages.inbounds.vlessAuthMlkem768')}
|
style={{ width: 240 }}
|
||||||
|
/>
|
||||||
|
<Button type="primary" loading={saving} onClick={() => getNewVlessEnc(authKind)}>
|
||||||
|
{t('pages.inbounds.vlessAuthGenerateButton')}
|
||||||
</Button>
|
</Button>
|
||||||
<Button danger onClick={clearVlessEnc}>{t('clear')}</Button>
|
<Button danger onClick={clearVlessEnc}>{t('clear')}</Button>
|
||||||
</Space>
|
</Space>
|
||||||
|
|||||||
@@ -65,6 +65,8 @@ export default function IndexPage() {
|
|||||||
useEffect(() => { setMessageInstance(messageApi); }, [messageApi]);
|
useEffect(() => { setMessageInstance(messageApi); }, [messageApi]);
|
||||||
|
|
||||||
const [accessLogEnable, setAccessLogEnable] = useState(false);
|
const [accessLogEnable, setAccessLogEnable] = useState(false);
|
||||||
|
const [isDevBuild, setIsDevBuild] = useState(false);
|
||||||
|
const [devChannelEnable, setDevChannelEnable] = useState(false);
|
||||||
const [panelUpdateInfo, setPanelUpdateInfo] = useState<PanelUpdateInfo>({
|
const [panelUpdateInfo, setPanelUpdateInfo] = useState<PanelUpdateInfo>({
|
||||||
currentVersion: '',
|
currentVersion: '',
|
||||||
latestVersion: '',
|
latestVersion: '',
|
||||||
@@ -87,8 +89,14 @@ export default function IndexPage() {
|
|||||||
const [loadingTip, setLoadingTip] = useState(t('loading'));
|
const [loadingTip, setLoadingTip] = useState(t('loading'));
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
HttpUtil.post<{ accessLogEnable?: boolean }>('/panel/api/setting/defaultSettings').then((msg) => {
|
HttpUtil.post<{ accessLogEnable?: boolean; isDevBuild?: boolean; devChannelEnable?: boolean }>(
|
||||||
if (msg?.success && msg.obj) setAccessLogEnable(!!msg.obj.accessLogEnable);
|
'/panel/api/setting/defaultSettings',
|
||||||
|
).then((msg) => {
|
||||||
|
if (msg?.success && msg.obj) {
|
||||||
|
setAccessLogEnable(!!msg.obj.accessLogEnable);
|
||||||
|
setIsDevBuild(!!msg.obj.isDevBuild);
|
||||||
|
setDevChannelEnable(!!msg.obj.devChannelEnable);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
HttpUtil.get<PanelUpdateInfo>('/panel/api/server/getPanelUpdateInfo').then((msg) => {
|
HttpUtil.get<PanelUpdateInfo>('/panel/api/server/getPanelUpdateInfo').then((msg) => {
|
||||||
if (msg?.success && msg.obj) setPanelUpdateInfo(msg.obj);
|
if (msg?.success && msg.obj) setPanelUpdateInfo(msg.obj);
|
||||||
@@ -119,13 +127,21 @@ export default function IndexPage() {
|
|||||||
}, [refresh]);
|
}, [refresh]);
|
||||||
|
|
||||||
function openPanelVersion() {
|
function openPanelVersion() {
|
||||||
if (panelUpdateInfo.updateAvailable) {
|
if (panelUpdateInfo.updateAvailable || isDevBuild) {
|
||||||
setPanelUpdateOpen(true);
|
setPanelUpdateOpen(true);
|
||||||
} else {
|
} else {
|
||||||
window.open('https://github.com/MHSanaei/3x-ui/releases', '_blank', 'noopener,noreferrer');
|
window.open('https://github.com/MHSanaei/3x-ui/releases', '_blank', 'noopener,noreferrer');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function handleChannelChange(dev: boolean) {
|
||||||
|
const res = await HttpUtil.post('/panel/api/server/setUpdateChannel', { dev });
|
||||||
|
if (!res?.success) return;
|
||||||
|
setDevChannelEnable(dev);
|
||||||
|
const msg = await HttpUtil.get<PanelUpdateInfo>('/panel/api/server/getPanelUpdateInfo');
|
||||||
|
if (msg?.success && msg.obj) setPanelUpdateInfo(msg.obj);
|
||||||
|
}
|
||||||
|
|
||||||
function openTelegram() {
|
function openTelegram() {
|
||||||
window.open('https://t.me/XrayUI', '_blank', 'noopener,noreferrer');
|
window.open('https://t.me/XrayUI', '_blank', 'noopener,noreferrer');
|
||||||
}
|
}
|
||||||
@@ -224,7 +240,9 @@ export default function IndexPage() {
|
|||||||
{isMobile && displayVersion && (
|
{isMobile && displayVersion && (
|
||||||
<Tag color={panelUpdateInfo.updateAvailable ? 'orange' : 'green'}>
|
<Tag color={panelUpdateInfo.updateAvailable ? 'orange' : 'green'}>
|
||||||
{panelUpdateInfo.updateAvailable
|
{panelUpdateInfo.updateAvailable
|
||||||
? `v${panelUpdateInfo.latestVersion}`
|
? panelUpdateInfo.channel === 'dev'
|
||||||
|
? panelUpdateInfo.latestVersion
|
||||||
|
: `v${panelUpdateInfo.latestVersion}`
|
||||||
: `v${displayVersion}`}
|
: `v${displayVersion}`}
|
||||||
</Tag>
|
</Tag>
|
||||||
)}
|
)}
|
||||||
@@ -446,6 +464,9 @@ export default function IndexPage() {
|
|||||||
<PanelUpdateModal
|
<PanelUpdateModal
|
||||||
open={panelUpdateOpen}
|
open={panelUpdateOpen}
|
||||||
info={panelUpdateInfo}
|
info={panelUpdateInfo}
|
||||||
|
isDevBuild={isDevBuild}
|
||||||
|
devChannelEnable={devChannelEnable}
|
||||||
|
onChannelChange={handleChannelChange}
|
||||||
onClose={() => setPanelUpdateOpen(false)}
|
onClose={() => setPanelUpdateOpen(false)}
|
||||||
onBusy={setBusy}
|
onBusy={setBusy}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { Alert, Button, Modal, Tag } from 'antd';
|
import { Alert, Button, Modal, Switch, Tag } from 'antd';
|
||||||
import { CloudDownloadOutlined } from '@ant-design/icons';
|
import { CloudDownloadOutlined } from '@ant-design/icons';
|
||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
|
|
||||||
@@ -7,8 +8,11 @@ import { HttpUtil, PromiseUtil } from '@/utils';
|
|||||||
import './PanelUpdateModal.css';
|
import './PanelUpdateModal.css';
|
||||||
|
|
||||||
export interface PanelUpdateInfo {
|
export interface PanelUpdateInfo {
|
||||||
|
channel?: string;
|
||||||
currentVersion: string;
|
currentVersion: string;
|
||||||
latestVersion: string;
|
latestVersion: string;
|
||||||
|
currentCommit?: string;
|
||||||
|
latestCommit?: string;
|
||||||
updateAvailable: boolean;
|
updateAvailable: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -20,13 +24,27 @@ interface BusyEvent {
|
|||||||
interface PanelUpdateModalProps {
|
interface PanelUpdateModalProps {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
info: PanelUpdateInfo;
|
info: PanelUpdateInfo;
|
||||||
|
isDevBuild?: boolean;
|
||||||
|
devChannelEnable?: boolean;
|
||||||
|
onChannelChange?: (dev: boolean) => void | Promise<void>;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
onBusy: (e: BusyEvent) => void;
|
onBusy: (e: BusyEvent) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function PanelUpdateModal({ open, info, onClose, onBusy }: PanelUpdateModalProps) {
|
export default function PanelUpdateModal({
|
||||||
|
open,
|
||||||
|
info,
|
||||||
|
isDevBuild,
|
||||||
|
devChannelEnable,
|
||||||
|
onChannelChange,
|
||||||
|
onClose,
|
||||||
|
onBusy,
|
||||||
|
}: PanelUpdateModalProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [modal, contextHolder] = Modal.useModal();
|
const [modal, contextHolder] = Modal.useModal();
|
||||||
|
const [channelBusy, setChannelBusy] = useState(false);
|
||||||
|
|
||||||
|
const isDev = info.channel === 'dev';
|
||||||
|
|
||||||
async function pollUntilBack(): Promise<boolean> {
|
async function pollUntilBack(): Promise<boolean> {
|
||||||
await PromiseUtil.sleep(5000);
|
await PromiseUtil.sleep(5000);
|
||||||
@@ -43,6 +61,16 @@ export default function PanelUpdateModal({ open, info, onClose, onBusy }: PanelU
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function handleChannel(checked: boolean) {
|
||||||
|
if (!onChannelChange) return;
|
||||||
|
setChannelBusy(true);
|
||||||
|
try {
|
||||||
|
await onChannelChange(checked);
|
||||||
|
} finally {
|
||||||
|
setChannelBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function updatePanel() {
|
function updatePanel() {
|
||||||
modal.confirm({
|
modal.confirm({
|
||||||
title: t('pages.index.panelUpdateDialog'),
|
title: t('pages.index.panelUpdateDialog'),
|
||||||
@@ -84,15 +112,41 @@ export default function PanelUpdateModal({ open, info, onClose, onBusy }: PanelU
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{isDevBuild && (
|
||||||
|
<div className="version-list">
|
||||||
|
<div className="version-list-item">
|
||||||
|
<span>{t('pages.index.devChannel')}</span>
|
||||||
|
<Switch
|
||||||
|
checked={!!devChannelEnable}
|
||||||
|
loading={channelBusy}
|
||||||
|
onChange={handleChannel}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{devChannelEnable && (
|
||||||
|
<Alert
|
||||||
|
type="info"
|
||||||
|
className="mb-12"
|
||||||
|
title={t('pages.index.devChannelWarning')}
|
||||||
|
showIcon
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className="version-list">
|
<div className="version-list">
|
||||||
<div className="version-list-item">
|
<div className="version-list-item">
|
||||||
<span>{t('pages.index.currentPanelVersion')}</span>
|
<span>{isDev ? t('pages.index.currentCommit') : t('pages.index.currentPanelVersion')}</span>
|
||||||
<Tag color="green">v{info.currentVersion || '?'}</Tag>
|
{isDev ? (
|
||||||
|
<Tag color="green">{info.currentCommit || '?'}</Tag>
|
||||||
|
) : (
|
||||||
|
<Tag color="green">v{info.currentVersion || '?'}</Tag>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
{info.updateAvailable ? (
|
{info.updateAvailable ? (
|
||||||
<div className="version-list-item">
|
<div className="version-list-item">
|
||||||
<span>{t('pages.index.latestPanelVersion')}</span>
|
<span>{isDev ? t('pages.index.latestCommit') : t('pages.index.latestPanelVersion')}</span>
|
||||||
<Tag color="purple">{info.latestVersion || '-'}</Tag>
|
<Tag color="purple">{(isDev ? info.latestCommit : info.latestVersion) || '-'}</Tag>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="version-list-item">
|
<div className="version-list-item">
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { useQuery } from '@tanstack/react-query';
|
import { useQuery } from '@tanstack/react-query';
|
||||||
import { Button, Card, Col, ConfigProvider, Input, Layout, Modal, Result, Row, Spin, Statistic, Typography, message } from 'antd';
|
import { Alert, Button, Card, Checkbox, Col, ConfigProvider, Input, Layout, Modal, Result, Row, Spin, Statistic, Typography, message } from 'antd';
|
||||||
import {
|
import {
|
||||||
CheckCircleOutlined,
|
CheckCircleOutlined,
|
||||||
CloseCircleOutlined,
|
CloseCircleOutlined,
|
||||||
@@ -21,6 +21,33 @@ import { setMessageInstance } from '@/utils/messageBus';
|
|||||||
import { HttpUtil } from '@/utils';
|
import { HttpUtil } from '@/utils';
|
||||||
import type { PanelUpdateInfo } from '../index/PanelUpdateModal';
|
import type { PanelUpdateInfo } from '../index/PanelUpdateModal';
|
||||||
|
|
||||||
|
// Confirm-dialog body that lets the operator pick the stable or dev channel for
|
||||||
|
// a node panel update. Reports changes via onChange so the imperative
|
||||||
|
// modal.confirm onOk can read the latest choice through a ref.
|
||||||
|
function UpdateChannelChoice({ onChange }: { onChange: (dev: boolean) => void }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [dev, setDev] = useState(false);
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<p>{t('pages.nodes.updateConfirmContent')}</p>
|
||||||
|
<Checkbox
|
||||||
|
checked={dev}
|
||||||
|
onChange={(e) => { setDev(e.target.checked); onChange(e.target.checked); }}
|
||||||
|
>
|
||||||
|
{t('pages.nodes.updateDevChannel')}
|
||||||
|
</Checkbox>
|
||||||
|
{dev && (
|
||||||
|
<Alert
|
||||||
|
type="info"
|
||||||
|
showIcon
|
||||||
|
style={{ marginTop: 8 }}
|
||||||
|
message={t('pages.index.devChannelWarning')}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export default function NodesPage() {
|
export default function NodesPage() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { isDark, isUltra, antdThemeConfig } = useTheme();
|
const { isDark, isUltra, antdThemeConfig } = useTheme();
|
||||||
@@ -136,8 +163,10 @@ export default function NodesPage() {
|
|||||||
await setEnable(node.id, next);
|
await setEnable(node.id, next);
|
||||||
}, [setEnable]);
|
}, [setEnable]);
|
||||||
|
|
||||||
const runUpdate = useCallback(async (ids: number[]) => {
|
const devRef = useRef(false);
|
||||||
const msg = await updatePanels(ids);
|
|
||||||
|
const runUpdate = useCallback(async (ids: number[], dev: boolean) => {
|
||||||
|
const msg = await updatePanels(ids, dev);
|
||||||
if (!msg?.success) {
|
if (!msg?.success) {
|
||||||
messageApi.error(msg?.msg || t('somethingWentWrong'));
|
messageApi.error(msg?.msg || t('somethingWentWrong'));
|
||||||
return;
|
return;
|
||||||
@@ -156,12 +185,13 @@ export default function NodesPage() {
|
|||||||
}, [updatePanels, messageApi, t]);
|
}, [updatePanels, messageApi, t]);
|
||||||
|
|
||||||
const onUpdateNode = useCallback((node: NodeRecord) => {
|
const onUpdateNode = useCallback((node: NodeRecord) => {
|
||||||
|
devRef.current = false;
|
||||||
modal.confirm({
|
modal.confirm({
|
||||||
title: t('pages.nodes.updateConfirmTitle', { count: 1 }),
|
title: t('pages.nodes.updateConfirmTitle', { count: 1 }),
|
||||||
content: t('pages.nodes.updateConfirmContent'),
|
content: <UpdateChannelChoice onChange={(v) => { devRef.current = v; }} />,
|
||||||
okText: t('update'),
|
okText: t('update'),
|
||||||
cancelText: t('cancel'),
|
cancelText: t('cancel'),
|
||||||
onOk: () => runUpdate([node.id]),
|
onOk: () => runUpdate([node.id], devRef.current),
|
||||||
});
|
});
|
||||||
}, [modal, t, runUpdate]);
|
}, [modal, t, runUpdate]);
|
||||||
|
|
||||||
@@ -173,12 +203,13 @@ export default function NodesPage() {
|
|||||||
messageApi.warning(t('pages.nodes.toasts.updateNoneEligible'));
|
messageApi.warning(t('pages.nodes.toasts.updateNoneEligible'));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
devRef.current = false;
|
||||||
modal.confirm({
|
modal.confirm({
|
||||||
title: t('pages.nodes.updateConfirmTitle', { count: eligible.length }),
|
title: t('pages.nodes.updateConfirmTitle', { count: eligible.length }),
|
||||||
content: t('pages.nodes.updateConfirmContent'),
|
content: <UpdateChannelChoice onChange={(v) => { devRef.current = v; }} />,
|
||||||
okText: t('update'),
|
okText: t('update'),
|
||||||
cancelText: t('cancel'),
|
cancelText: t('cancel'),
|
||||||
onOk: () => runUpdate(eligible),
|
onOk: () => runUpdate(eligible, devRef.current),
|
||||||
});
|
});
|
||||||
}, [modal, t, nodes, selectedIds, runUpdate, messageApi]);
|
}, [modal, t, nodes, selectedIds, runUpdate, messageApi]);
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Input, InputNumber, Switch, Tabs } from 'antd';
|
import { Input, InputNumber, Switch, Tabs } from 'antd';
|
||||||
import { BranchesOutlined, IdcardOutlined, InfoCircleOutlined, NodeIndexOutlined, SafetyCertificateOutlined, SettingOutlined } from '@ant-design/icons';
|
import { BranchesOutlined, CompassOutlined, IdcardOutlined, InfoCircleOutlined, NodeIndexOutlined, SafetyCertificateOutlined, SettingOutlined } from '@ant-design/icons';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import type { AllSetting } from '@/models/setting';
|
import type { AllSetting } from '@/models/setting';
|
||||||
import { SettingListItem } from '@/components/ui';
|
import { SettingListItem } from '@/components/ui';
|
||||||
@@ -178,6 +178,21 @@ export default function SubscriptionGeneralTab({ allSetting, updateSetting }: Su
|
|||||||
</>
|
</>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
key: '7',
|
||||||
|
label: catTabLabel(<CompassOutlined />, 'Incy', isMobile),
|
||||||
|
children: (
|
||||||
|
<>
|
||||||
|
<SettingListItem paddings="small" title={t('pages.settings.subIncyEnableRouting')} description={t('pages.settings.subIncyEnableRoutingDesc')}>
|
||||||
|
<Switch checked={allSetting.subIncyEnableRouting} onChange={(v) => updateSetting({ subIncyEnableRouting: v })} />
|
||||||
|
</SettingListItem>
|
||||||
|
<SettingListItem paddings="small" title={t('pages.settings.subIncyRoutingRules')} description={t('pages.settings.subIncyRoutingRulesDesc')}>
|
||||||
|
<Input.TextArea value={allSetting.subIncyRoutingRules} placeholder="incy://routing/onadd/..."
|
||||||
|
onChange={(e) => updateSetting({ subIncyRoutingRules: e.target.value })} />
|
||||||
|
</SettingListItem>
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
},
|
||||||
]} />
|
]} />
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -139,6 +139,7 @@ export default function SubPage() {
|
|||||||
);
|
);
|
||||||
const streisandUrl = useMemo(() => `streisand://import/${encodeURIComponent(subUrl)}`, []);
|
const streisandUrl = useMemo(() => `streisand://import/${encodeURIComponent(subUrl)}`, []);
|
||||||
const happUrl = useMemo(() => `happ://add/${subUrl}`, []);
|
const happUrl = useMemo(() => `happ://add/${subUrl}`, []);
|
||||||
|
const incyUrl = useMemo(() => `incy://add/${subUrl}`, []);
|
||||||
|
|
||||||
const pageClass = useMemo(() => {
|
const pageClass = useMemo(() => {
|
||||||
const classes = ['subscription-page'];
|
const classes = ['subscription-page'];
|
||||||
@@ -200,6 +201,7 @@ export default function SubPage() {
|
|||||||
{ key: 'android-v2raytun', label: 'V2RayTun', onClick: () => copy(subUrl) },
|
{ key: 'android-v2raytun', label: 'V2RayTun', onClick: () => copy(subUrl) },
|
||||||
{ key: 'android-npvtunnel', label: 'NPV Tunnel', onClick: () => copy(subUrl) },
|
{ key: 'android-npvtunnel', label: 'NPV Tunnel', onClick: () => copy(subUrl) },
|
||||||
{ key: 'android-happ', label: 'Happ', onClick: () => open(`happ://add/${subUrl}`) },
|
{ key: 'android-happ', label: 'Happ', onClick: () => open(`happ://add/${subUrl}`) },
|
||||||
|
{ key: 'android-incy', label: 'Incy', onClick: () => open(`incy://add/${subUrl}`) },
|
||||||
], [copy, open]);
|
], [copy, open]);
|
||||||
|
|
||||||
const iosMenuItems = useMemo(() => [
|
const iosMenuItems = useMemo(() => [
|
||||||
@@ -209,7 +211,8 @@ export default function SubPage() {
|
|||||||
{ key: 'ios-v2raytun', label: 'V2RayTun', onClick: () => copy(subUrl) },
|
{ key: 'ios-v2raytun', label: 'V2RayTun', onClick: () => copy(subUrl) },
|
||||||
{ key: 'ios-npvtunnel', label: 'NPV Tunnel', onClick: () => copy(subUrl) },
|
{ key: 'ios-npvtunnel', label: 'NPV Tunnel', onClick: () => copy(subUrl) },
|
||||||
{ key: 'ios-happ', label: 'Happ', onClick: () => open(happUrl) },
|
{ key: 'ios-happ', label: 'Happ', onClick: () => open(happUrl) },
|
||||||
], [copy, open, shadowrocketUrl, v2boxUrl, streisandUrl, happUrl]);
|
{ key: 'ios-incy', label: 'Incy', onClick: () => open(incyUrl) },
|
||||||
|
], [copy, open, shadowrocketUrl, v2boxUrl, streisandUrl, happUrl, incyUrl]);
|
||||||
|
|
||||||
const langMenuItems = useMemo(
|
const langMenuItems = useMemo(
|
||||||
() => (LanguageManager.supportedLanguages as { value: string; name: string; icon: string }[]).map((l) => ({
|
() => (LanguageManager.supportedLanguages as { value: string; name: string; icon: string }[]).map((l) => ({
|
||||||
@@ -418,7 +421,7 @@ export default function SubPage() {
|
|||||||
const parts = parseLinkParts(link);
|
const parts = parseLinkParts(link);
|
||||||
const fallback = `Link ${idx + 1}`;
|
const fallback = `Link ${idx + 1}`;
|
||||||
const rowTitle = parts?.remark || fallback;
|
const rowTitle = parts?.remark || fallback;
|
||||||
const qrLabel = [parts?.remark, linkEmails[idx]].filter(Boolean).join('-') || rowTitle;
|
const qrLabel = parts?.remark || rowTitle;
|
||||||
const canQr = !isPostQuantumLink(link);
|
const canQr = !isPostQuantumLink(link);
|
||||||
return (
|
return (
|
||||||
<div key={link} className="sub-link-row">
|
<div key={link} className="sub-link-row">
|
||||||
|
|||||||
@@ -221,6 +221,7 @@ export default function XrayPage() {
|
|||||||
testingAll={testingAll}
|
testingAll={testingAll}
|
||||||
inboundTags={inboundTags}
|
inboundTags={inboundTags}
|
||||||
subscriptionOutbounds={subscriptionOutbounds}
|
subscriptionOutbounds={subscriptionOutbounds}
|
||||||
|
subscriptionOutboundTags={subscriptionOutboundTags}
|
||||||
isMobile={isMobile}
|
isMobile={isMobile}
|
||||||
onResetTraffic={resetOutboundsTraffic}
|
onResetTraffic={resetOutboundsTraffic}
|
||||||
onTest={onTestOutbound}
|
onTest={onTestOutbound}
|
||||||
|
|||||||
@@ -83,6 +83,7 @@ interface OutboundFormModalProps {
|
|||||||
open: boolean;
|
open: boolean;
|
||||||
outbound: Record<string, unknown> | null;
|
outbound: Record<string, unknown> | null;
|
||||||
existingTags: string[];
|
existingTags: string[];
|
||||||
|
dialerProxyTags?: string[];
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
onConfirm: (outbound: Record<string, unknown>) => void;
|
onConfirm: (outbound: Record<string, unknown>) => void;
|
||||||
}
|
}
|
||||||
@@ -92,6 +93,7 @@ export default function OutboundFormModal({
|
|||||||
open,
|
open,
|
||||||
outbound: outboundProp,
|
outbound: outboundProp,
|
||||||
existingTags,
|
existingTags,
|
||||||
|
dialerProxyTags,
|
||||||
onClose,
|
onClose,
|
||||||
onConfirm,
|
onConfirm,
|
||||||
}: OutboundFormModalProps) {
|
}: OutboundFormModalProps) {
|
||||||
@@ -514,7 +516,7 @@ export default function OutboundFormModal({
|
|||||||
{security === 'reality' && realityAllowed && <RealityForm />}
|
{security === 'reality' && realityAllowed && <RealityForm />}
|
||||||
|
|
||||||
{((streamAllowed && network) || !streamAllowed || protocol === 'wireguard') && (
|
{((streamAllowed && network) || !streamAllowed || protocol === 'wireguard') && (
|
||||||
<SockoptForm form={form} outboundTags={existingTags} />
|
<SockoptForm form={form} outboundTags={dialerProxyTags ?? existingTags} />
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<FinalMaskForm
|
<FinalMaskForm
|
||||||
|
|||||||
@@ -75,6 +75,7 @@ interface OutboundsTabProps {
|
|||||||
testingAll: boolean;
|
testingAll: boolean;
|
||||||
inboundTags: string[];
|
inboundTags: string[];
|
||||||
subscriptionOutbounds?: unknown[];
|
subscriptionOutbounds?: unknown[];
|
||||||
|
subscriptionOutboundTags?: string[];
|
||||||
isMobile: boolean;
|
isMobile: boolean;
|
||||||
onResetTraffic: (tag: string) => void;
|
onResetTraffic: (tag: string) => void;
|
||||||
onTest: (index: number, mode: string) => void;
|
onTest: (index: number, mode: string) => void;
|
||||||
@@ -94,6 +95,7 @@ export default function OutboundsTab({
|
|||||||
testingAll,
|
testingAll,
|
||||||
inboundTags: _inboundTags,
|
inboundTags: _inboundTags,
|
||||||
subscriptionOutbounds,
|
subscriptionOutbounds,
|
||||||
|
subscriptionOutboundTags,
|
||||||
isMobile,
|
isMobile,
|
||||||
onResetTraffic,
|
onResetTraffic,
|
||||||
onTest,
|
onTest,
|
||||||
@@ -140,6 +142,19 @@ export default function OutboundsTab({
|
|||||||
|
|
||||||
const rows = useMemo(() => outbounds.map((o, i) => ({ ...o, key: i })), [outbounds]);
|
const rows = useMemo(() => outbounds.map((o, i) => ({ ...o, key: i })), [outbounds]);
|
||||||
|
|
||||||
|
const dialerProxyTags = useMemo(() => {
|
||||||
|
const tags = new Set<string>();
|
||||||
|
(templateSettings?.outbounds || []).forEach((o, i) => {
|
||||||
|
if (i === editingIndex) return;
|
||||||
|
if (o?.protocol === 'blackhole') return;
|
||||||
|
if (o?.tag) tags.add(o.tag);
|
||||||
|
});
|
||||||
|
for (const tag of subscriptionOutboundTags || []) {
|
||||||
|
if (tag) tags.add(tag);
|
||||||
|
}
|
||||||
|
return [...tags];
|
||||||
|
}, [templateSettings?.outbounds, editingIndex, subscriptionOutboundTags]);
|
||||||
|
|
||||||
const mutate = useCallback(
|
const mutate = useCallback(
|
||||||
(mutator: (next: XraySettingsValue) => void) => {
|
(mutator: (next: XraySettingsValue) => void) => {
|
||||||
setTemplateSettings((prev) => {
|
setTemplateSettings((prev) => {
|
||||||
@@ -521,6 +536,7 @@ export default function OutboundsTab({
|
|||||||
open={modalOpen}
|
open={modalOpen}
|
||||||
outbound={editingOutbound}
|
outbound={editingOutbound}
|
||||||
existingTags={existingTags}
|
existingTags={existingTags}
|
||||||
|
dialerProxyTags={dialerProxyTags}
|
||||||
onClose={() => setModalOpen(false)}
|
onClose={() => setModalOpen(false)}
|
||||||
onConfirm={onConfirm}
|
onConfirm={onConfirm}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { Form, Input } from 'antd';
|
import { Form, Input } from 'antd';
|
||||||
|
|
||||||
|
import { HeaderMapEditor } from '@/components/form';
|
||||||
|
|
||||||
export default function HttpFields() {
|
export default function HttpFields() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
return (
|
return (
|
||||||
@@ -11,6 +13,9 @@ export default function HttpFields() {
|
|||||||
<Form.Item label={t('password')} name={['settings', 'pass']}>
|
<Form.Item label={t('password')} name={['settings', 'pass']}>
|
||||||
<Input />
|
<Input />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
<Form.Item label={t('pages.inbounds.form.headers')} name={['settings', 'headers']}>
|
||||||
|
<HeaderMapEditor mode="v1" />
|
||||||
|
</Form.Item>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -188,8 +188,9 @@ export const ClientBulkAdjustFormSchema = z
|
|||||||
.object({
|
.object({
|
||||||
addDays: z.number().int(),
|
addDays: z.number().int(),
|
||||||
addGB: z.number(),
|
addGB: z.number(),
|
||||||
|
flow: z.string().optional().default(''),
|
||||||
})
|
})
|
||||||
.refine((v) => v.addDays !== 0 || v.addGB !== 0, {
|
.refine((v) => v.addDays !== 0 || v.addGB !== 0 || v.flow !== '', {
|
||||||
message: 'pages.clients.bulkAdjustNothing',
|
message: 'pages.clients.bulkAdjustNothing',
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -80,6 +80,7 @@ export const HttpOutboundFormSettingsSchema = z.object({
|
|||||||
port: PortSchema.default(8080),
|
port: PortSchema.default(8080),
|
||||||
user: z.string().default(''),
|
user: z.string().default(''),
|
||||||
pass: z.string().default(''),
|
pass: z.string().default(''),
|
||||||
|
headers: z.record(z.string(), z.string()).default({}),
|
||||||
});
|
});
|
||||||
export type HttpOutboundFormSettings = z.infer<typeof HttpOutboundFormSettingsSchema>;
|
export type HttpOutboundFormSettings = z.infer<typeof HttpOutboundFormSettingsSchema>;
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,12 @@ export type TunnelNetwork = z.infer<typeof TunnelNetworkSchema>;
|
|||||||
// with arr=false.
|
// with arr=false.
|
||||||
export const TunnelInboundSettingsSchema = z.object({
|
export const TunnelInboundSettingsSchema = z.object({
|
||||||
rewriteAddress: z.string().optional(),
|
rewriteAddress: z.string().optional(),
|
||||||
rewritePort: PortSchema.optional(),
|
// AntD InputNumber writes null when cleared; accept it and collapse to
|
||||||
|
// undefined so the field is omitted from the payload instead of crashing
|
||||||
|
// validation with "Invalid input" (issue #5516). The trailing .optional()
|
||||||
|
// keeps the key optional in the inferred type (a bare .transform() would
|
||||||
|
// make it required).
|
||||||
|
rewritePort: PortSchema.nullable().transform((v) => v ?? undefined).optional(),
|
||||||
portMap: z.record(z.string(), z.string()).default({}),
|
portMap: z.record(z.string(), z.string()).default({}),
|
||||||
allowedNetwork: TunnelNetworkSchema.default('tcp,udp'),
|
allowedNetwork: TunnelNetworkSchema.default('tcp,udp'),
|
||||||
followRedirect: z.boolean().default(false),
|
followRedirect: z.boolean().default(false),
|
||||||
|
|||||||
@@ -21,5 +21,6 @@ export type HttpOutboundServer = z.infer<typeof HttpOutboundServerSchema>;
|
|||||||
|
|
||||||
export const HttpOutboundSettingsSchema = z.object({
|
export const HttpOutboundSettingsSchema = z.object({
|
||||||
servers: z.array(HttpOutboundServerSchema).min(1),
|
servers: z.array(HttpOutboundServerSchema).min(1),
|
||||||
|
headers: z.record(z.string(), z.string()).optional(),
|
||||||
});
|
});
|
||||||
export type HttpOutboundSettings = z.infer<typeof HttpOutboundSettingsSchema>;
|
export type HttpOutboundSettings = z.infer<typeof HttpOutboundSettingsSchema>;
|
||||||
|
|||||||
@@ -39,6 +39,8 @@ export const AllSettingSchema = z.object({
|
|||||||
subAnnounce: z.string().optional(),
|
subAnnounce: z.string().optional(),
|
||||||
subEnableRouting: z.boolean().optional(),
|
subEnableRouting: z.boolean().optional(),
|
||||||
subRoutingRules: z.string().optional(),
|
subRoutingRules: z.string().optional(),
|
||||||
|
subIncyEnableRouting: z.boolean().optional(),
|
||||||
|
subIncyRoutingRules: z.string().optional(),
|
||||||
subListen: z.string().optional(),
|
subListen: z.string().optional(),
|
||||||
subPort: port.optional(),
|
subPort: port.optional(),
|
||||||
subPath: absolutePath.optional(),
|
subPath: absolutePath.optional(),
|
||||||
|
|||||||
@@ -175,6 +175,29 @@ describe('outbound-form-adapter: round-trip', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('http preserves top-level settings.headers across wire → form → wire (#5519)', () => {
|
||||||
|
const headers = { 'X-T5-Auth': '683556433', Host: '153.3.236.22:443' };
|
||||||
|
const form = rawOutboundToFormValues({
|
||||||
|
protocol: 'http',
|
||||||
|
tag: 'h',
|
||||||
|
settings: { servers: [{ address: 'a', port: 443, users: [] }], headers },
|
||||||
|
});
|
||||||
|
expect(form.protocol).toBe('http');
|
||||||
|
if (form.protocol === 'http') {
|
||||||
|
expect(form.settings.headers).toEqual(headers);
|
||||||
|
}
|
||||||
|
const back = formValuesToWirePayload(form);
|
||||||
|
expect(back.settings).toMatchObject({ headers });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('http omits headers when empty', () => {
|
||||||
|
const back = formValuesToWirePayload(rawOutboundToFormValues({
|
||||||
|
protocol: 'http',
|
||||||
|
settings: { servers: [{ address: 'a', port: 8080, users: [] }] },
|
||||||
|
}));
|
||||||
|
expect(back.settings).not.toHaveProperty('headers');
|
||||||
|
});
|
||||||
|
|
||||||
it('wireguard csv-joins address and reserved on read, splits on write', () => {
|
it('wireguard csv-joins address and reserved on read, splits on write', () => {
|
||||||
const wire = {
|
const wire = {
|
||||||
protocol: 'wireguard',
|
protocol: 'wireguard',
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
|
import { TunnelInboundSettingsSchema } from '@/schemas/protocols/inbound/tunnel';
|
||||||
|
|
||||||
|
// Regression for issue #5516: AntD InputNumber writes null when the Rewrite
|
||||||
|
// port field is cleared, which used to crash validation with "Invalid input".
|
||||||
|
describe('TunnelInboundSettingsSchema rewritePort', () => {
|
||||||
|
it('accepts null (cleared field) and omits the port', () => {
|
||||||
|
const parsed = TunnelInboundSettingsSchema.parse({ rewritePort: null });
|
||||||
|
expect(parsed.rewritePort).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts a missing field', () => {
|
||||||
|
const parsed = TunnelInboundSettingsSchema.parse({});
|
||||||
|
expect(parsed.rewritePort).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('preserves a valid port', () => {
|
||||||
|
const parsed = TunnelInboundSettingsSchema.parse({ rewritePort: 8443 });
|
||||||
|
expect(parsed.rewritePort).toBe(8443);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('still rejects out-of-range ports', () => {
|
||||||
|
expect(() => TunnelInboundSettingsSchema.parse({ rewritePort: 70000 })).toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
+19
-14
@@ -19,6 +19,7 @@ export class Msg<T = unknown> {
|
|||||||
|
|
||||||
export interface HttpOptions extends AxiosRequestConfig {
|
export interface HttpOptions extends AxiosRequestConfig {
|
||||||
silent?: boolean;
|
silent?: boolean;
|
||||||
|
silentSuccess?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface HttpModal {
|
export interface HttpModal {
|
||||||
@@ -27,20 +28,24 @@ export interface HttpModal {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class HttpUtil {
|
export class HttpUtil {
|
||||||
static _handleMsg(msg: unknown): void {
|
static _handleMsg(msg: unknown, silentSuccess = false): void {
|
||||||
if (!(msg instanceof Msg) || msg.msg === '') {
|
if (!(msg instanceof Msg) || msg.msg === '') {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const messageType = msg.success ? 'success' : 'error';
|
if (msg.success) {
|
||||||
getMessage()[messageType](msg.msg);
|
if (!silentSuccess) {
|
||||||
if (
|
getMessage().success(msg.msg);
|
||||||
msg.success &&
|
}
|
||||||
msg.obj &&
|
if (
|
||||||
typeof msg.obj === 'object' &&
|
msg.obj &&
|
||||||
(msg.obj as { nodePending?: unknown }).nodePending === true
|
typeof msg.obj === 'object' &&
|
||||||
) {
|
(msg.obj as { nodePending?: unknown }).nodePending === true
|
||||||
getMessage().warning(i18next.t('pages.inbounds.toasts.savedNodeOfflineWillSync'));
|
) {
|
||||||
|
getMessage().warning(i18next.t('pages.inbounds.toasts.savedNodeOfflineWillSync'));
|
||||||
|
}
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
getMessage().error(msg.msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
static _respToMsg(resp: AxiosResponse | undefined): Msg {
|
static _respToMsg(resp: AxiosResponse | undefined): Msg {
|
||||||
@@ -59,11 +64,11 @@ export class HttpUtil {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static async get<T = unknown>(url: string, params?: unknown, options: HttpOptions = {}): Promise<Msg<T>> {
|
static async get<T = unknown>(url: string, params?: unknown, options: HttpOptions = {}): Promise<Msg<T>> {
|
||||||
const { silent, ...axiosOpts } = options;
|
const { silent, silentSuccess, ...axiosOpts } = options;
|
||||||
try {
|
try {
|
||||||
const resp = await axios.get(url, { params, ...axiosOpts });
|
const resp = await axios.get(url, { params, ...axiosOpts });
|
||||||
const msg = this._respToMsg(resp) as Msg<T>;
|
const msg = this._respToMsg(resp) as Msg<T>;
|
||||||
if (!silent) this._handleMsg(msg);
|
if (!silent) this._handleMsg(msg, silentSuccess);
|
||||||
return msg;
|
return msg;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('GET request failed:', error);
|
console.error('GET request failed:', error);
|
||||||
@@ -75,11 +80,11 @@ export class HttpUtil {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static async post<T = unknown>(url: string, data?: unknown, options: HttpOptions = {}): Promise<Msg<T>> {
|
static async post<T = unknown>(url: string, data?: unknown, options: HttpOptions = {}): Promise<Msg<T>> {
|
||||||
const { silent, ...axiosOpts } = options;
|
const { silent, silentSuccess, ...axiosOpts } = options;
|
||||||
try {
|
try {
|
||||||
const resp = await axios.post(url, data, axiosOpts);
|
const resp = await axios.post(url, data, axiosOpts);
|
||||||
const msg = this._respToMsg(resp) as Msg<T>;
|
const msg = this._respToMsg(resp) as Msg<T>;
|
||||||
if (!silent) this._handleMsg(msg);
|
if (!silent) this._handleMsg(msg, silentSuccess);
|
||||||
return msg;
|
return msg;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('POST request failed:', error);
|
console.error('POST request failed:', error);
|
||||||
|
|||||||
@@ -20,6 +20,15 @@ var version string
|
|||||||
//go:embed name
|
//go:embed name
|
||||||
var name string
|
var name string
|
||||||
|
|
||||||
|
// buildCommit and buildDate are injected at build time via `-ldflags -X` for
|
||||||
|
// CI per-commit (dev channel) builds; see .github/workflows/release.yml. They
|
||||||
|
// stay empty for a plain `go build` and for stable tagged releases, which is how
|
||||||
|
// IsDevBuild tells a rolling dev build apart from a stable/local one.
|
||||||
|
var (
|
||||||
|
buildCommit string
|
||||||
|
buildDate string
|
||||||
|
)
|
||||||
|
|
||||||
// LogLevel represents the logging level for the application.
|
// LogLevel represents the logging level for the application.
|
||||||
type LogLevel string
|
type LogLevel string
|
||||||
|
|
||||||
@@ -42,6 +51,39 @@ func GetName() string {
|
|||||||
return strings.TrimSpace(name)
|
return strings.TrimSpace(name)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetBuildCommit returns the short git commit this binary was built from, or an
|
||||||
|
// empty string for a plain/local build or a stable tagged release.
|
||||||
|
func GetBuildCommit() string {
|
||||||
|
return strings.TrimSpace(buildCommit)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetBuildDate returns the UTC build timestamp injected at build time, or empty.
|
||||||
|
func GetBuildDate() string {
|
||||||
|
return strings.TrimSpace(buildDate)
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsDevBuild reports whether this binary is a CI per-commit (dev channel) build,
|
||||||
|
// detected by the injected commit. Stable releases and local builds return false.
|
||||||
|
func IsDevBuild() bool {
|
||||||
|
return GetBuildCommit() != ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetReportedVersion returns the version a panel advertises to a managing master
|
||||||
|
// node: the plain version for stable builds, or "dev+<short commit>" for dev
|
||||||
|
// builds. The dev form mirrors the master's getPanelUpdateInfo latestVersion so
|
||||||
|
// a node on the current dev commit compares as up to date instead of always
|
||||||
|
// showing "update available".
|
||||||
|
func GetReportedVersion() string {
|
||||||
|
if !IsDevBuild() {
|
||||||
|
return GetVersion()
|
||||||
|
}
|
||||||
|
commit := GetBuildCommit()
|
||||||
|
if len(commit) > 8 {
|
||||||
|
commit = commit[:8]
|
||||||
|
}
|
||||||
|
return "dev+" + commit
|
||||||
|
}
|
||||||
|
|
||||||
// GetLogLevel returns the current logging level based on environment variables or defaults to Info.
|
// GetLogLevel returns the current logging level based on environment variables or defaults to Info.
|
||||||
func GetLogLevel() LogLevel {
|
func GetLogLevel() LogLevel {
|
||||||
if IsDebug() {
|
if IsDebug() {
|
||||||
|
|||||||
@@ -5,6 +5,26 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestGetReportedVersion(t *testing.T) {
|
||||||
|
orig := buildCommit
|
||||||
|
t.Cleanup(func() { buildCommit = orig })
|
||||||
|
|
||||||
|
buildCommit = ""
|
||||||
|
if got := GetReportedVersion(); got != GetVersion() {
|
||||||
|
t.Fatalf("stable build: GetReportedVersion = %q, want %q", got, GetVersion())
|
||||||
|
}
|
||||||
|
|
||||||
|
buildCommit = "1d1128cf"
|
||||||
|
if got := GetReportedVersion(); got != "dev+1d1128cf" {
|
||||||
|
t.Fatalf("dev build: GetReportedVersion = %q, want %q", got, "dev+1d1128cf")
|
||||||
|
}
|
||||||
|
|
||||||
|
buildCommit = "1d1128cf945c4615efa05cf41ba7fa766e2ee428"
|
||||||
|
if got := GetReportedVersion(); got != "dev+1d1128cf" {
|
||||||
|
t.Fatalf("dev build (full sha): GetReportedVersion = %q, want %q", got, "dev+1d1128cf")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestGetPortOverride(t *testing.T) {
|
func TestGetPortOverride(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
|
|||||||
@@ -45,8 +45,8 @@ func TestChar_C1_VlessExternalProxy(t *testing.T) {
|
|||||||
}`
|
}`
|
||||||
s := &SubService{}
|
s := &SubService{}
|
||||||
got := s.genVlessLink(charVlessInbound(stream), "user")
|
got := s.genVlessLink(charVlessInbound(stream), "user")
|
||||||
want := "vless://11111111-2222-4333-8444-555555555555@cdn1.example.com:8443?alpn=h3%2Ch2&encryption=none&fp=firefox&pcs=UElO&security=tls&sni=sni1.example.com&type=tcp#char-R1\n" +
|
want := "vless://11111111-2222-4333-8444-555555555555@cdn1.example.com:8443?alpn=h3%2Ch2&encryption=none&fp=firefox&pcs=UElO&security=tls&sni=sni1.example.com&type=tcp#char-R1-user\n" +
|
||||||
"vless://11111111-2222-4333-8444-555555555555@cdn2.example.com:80?encryption=none&security=none&type=tcp#char-R2"
|
"vless://11111111-2222-4333-8444-555555555555@cdn2.example.com:80?encryption=none&security=none&type=tcp#char-R2-user"
|
||||||
if got != want {
|
if got != want {
|
||||||
t.Fatalf("C1 mismatch.\n got: %q\nwant: %q", got, want)
|
t.Fatalf("C1 mismatch.\n got: %q\nwant: %q", got, want)
|
||||||
}
|
}
|
||||||
@@ -106,8 +106,8 @@ func TestChar_C2_VmessExternalProxy(t *testing.T) {
|
|||||||
}
|
}
|
||||||
s := &SubService{}
|
s := &SubService{}
|
||||||
got := s.genVmessLink(in, "user")
|
got := s.genVmessLink(in, "user")
|
||||||
want := "vmess://ewogICJhZGQiOiAidm0xLmV4YW1wbGUuY29tIiwKICAiYWxwbiI6ICJoMiIsCiAgImZwIjogImNocm9tZSIsCiAgImlkIjogIjExMTExMTExLTIyMjItNDMzMy04NDQ0LTU1NTU1NTU1NTU1NSIsCiAgIm5ldCI6ICJ0Y3AiLAogICJwb3J0IjogODQ0MywKICAicHMiOiAiY2hhci1WMSIsCiAgInNjeSI6ICJhdXRvIiwKICAic25pIjogInNuaTEuZXhhbXBsZS5jb20iLAogICJ0bHMiOiAidGxzIiwKICAidHlwZSI6ICJub25lIiwKICAidiI6ICIyIgp9\n" +
|
want := "vmess://ewogICJhZGQiOiAidm0xLmV4YW1wbGUuY29tIiwKICAiYWxwbiI6ICJoMiIsCiAgImZwIjogImNocm9tZSIsCiAgImlkIjogIjExMTExMTExLTIyMjItNDMzMy04NDQ0LTU1NTU1NTU1NTU1NSIsCiAgIm5ldCI6ICJ0Y3AiLAogICJwb3J0IjogODQ0MywKICAicHMiOiAiY2hhci1WMS11c2VyIiwKICAic2N5IjogImF1dG8iLAogICJzbmkiOiAic25pMS5leGFtcGxlLmNvbSIsCiAgInRscyI6ICJ0bHMiLAogICJ0eXBlIjogIm5vbmUiLAogICJ2IjogIjIiCn0=\n" +
|
||||||
"vmess://ewogICJhZGQiOiAidm0yLmV4YW1wbGUuY29tIiwKICAiaWQiOiAiMTExMTExMTEtMjIyMi00MzMzLTg0NDQtNTU1NTU1NTU1NTU1IiwKICAibmV0IjogInRjcCIsCiAgInBvcnQiOiA4MCwKICAicHMiOiAiY2hhci1WMiIsCiAgInNjeSI6ICJhdXRvIiwKICAidGxzIjogIm5vbmUiLAogICJ0eXBlIjogIm5vbmUiLAogICJ2IjogIjIiCn0="
|
"vmess://ewogICJhZGQiOiAidm0yLmV4YW1wbGUuY29tIiwKICAiaWQiOiAiMTExMTExMTEtMjIyMi00MzMzLTg0NDQtNTU1NTU1NTU1NTU1IiwKICAibmV0IjogInRjcCIsCiAgInBvcnQiOiA4MCwKICAicHMiOiAiY2hhci1WMi11c2VyIiwKICAic2N5IjogImF1dG8iLAogICJ0bHMiOiAibm9uZSIsCiAgInR5cGUiOiAibm9uZSIsCiAgInYiOiAiMiIKfQ=="
|
||||||
if got != want {
|
if got != want {
|
||||||
t.Fatalf("C2 mismatch.\n got: %q\nwant: %q", got, want)
|
t.Fatalf("C2 mismatch.\n got: %q\nwant: %q", got, want)
|
||||||
}
|
}
|
||||||
@@ -143,7 +143,7 @@ func TestChar_C3_TrojanExternalProxy(t *testing.T) {
|
|||||||
}
|
}
|
||||||
s := &SubService{}
|
s := &SubService{}
|
||||||
got := s.genTrojanLink(in, "user")
|
got := s.genTrojanLink(in, "user")
|
||||||
want := "trojan://p%40ss%2Fw%2Brd%3D@tj.example.com:8443?fp=chrome&security=tls&sni=tj.sni&type=tcp#char-TJ"
|
want := "trojan://p%40ss%2Fw%2Brd%3D@tj.example.com:8443?fp=chrome&security=tls&sni=tj.sni&type=tcp#char-TJ-user"
|
||||||
if got != want {
|
if got != want {
|
||||||
t.Fatalf("C3-Trojan mismatch.\n got: %q\nwant: %q", got, want)
|
t.Fatalf("C3-Trojan mismatch.\n got: %q\nwant: %q", got, want)
|
||||||
}
|
}
|
||||||
@@ -168,7 +168,7 @@ func TestChar_C3_ShadowsocksExternalProxy(t *testing.T) {
|
|||||||
}
|
}
|
||||||
s := &SubService{}
|
s := &SubService{}
|
||||||
got := s.genShadowsocksLink(in, "user")
|
got := s.genShadowsocksLink(in, "user")
|
||||||
want := "ss://2022-blake3-aes-256-gcm:inboundpw:clientpw@ss.example.com:8443?fp=chrome&security=tls&sni=ss.sni&type=tcp#char-SS"
|
want := "ss://2022-blake3-aes-256-gcm:inboundpw:clientpw@ss.example.com:8443?fp=chrome&security=tls&sni=ss.sni&type=tcp#char-SS-user"
|
||||||
if got != want {
|
if got != want {
|
||||||
t.Fatalf("C3-SS mismatch.\n got: %q\nwant: %q", got, want)
|
t.Fatalf("C3-SS mismatch.\n got: %q\nwant: %q", got, want)
|
||||||
}
|
}
|
||||||
|
|||||||
+29
-14
@@ -49,13 +49,17 @@ type SUBController struct {
|
|||||||
subEnableRouting bool
|
subEnableRouting bool
|
||||||
subRoutingRules string
|
subRoutingRules string
|
||||||
subHideSettings bool
|
subHideSettings bool
|
||||||
subPath string
|
|
||||||
subJsonPath string
|
subIncyEnableRouting bool
|
||||||
subClashPath string
|
subIncyRoutingRules string
|
||||||
jsonEnabled bool
|
|
||||||
clashEnabled bool
|
subPath string
|
||||||
subEncrypt bool
|
subJsonPath string
|
||||||
updateInterval string
|
subClashPath string
|
||||||
|
jsonEnabled bool
|
||||||
|
clashEnabled bool
|
||||||
|
subEncrypt bool
|
||||||
|
updateInterval string
|
||||||
|
|
||||||
subService *SubService
|
subService *SubService
|
||||||
subJsonService *SubJsonService
|
subJsonService *SubJsonService
|
||||||
@@ -89,6 +93,8 @@ func NewSUBController(
|
|||||||
subEnableRouting bool,
|
subEnableRouting bool,
|
||||||
subRoutingRules string,
|
subRoutingRules string,
|
||||||
subHideSettings bool,
|
subHideSettings bool,
|
||||||
|
subIncyEnableRouting bool,
|
||||||
|
subIncyRoutingRules string,
|
||||||
) *SUBController {
|
) *SUBController {
|
||||||
sub := NewSubService(remarkTemplate)
|
sub := NewSubService(remarkTemplate)
|
||||||
a := &SUBController{
|
a := &SUBController{
|
||||||
@@ -99,13 +105,17 @@ func NewSUBController(
|
|||||||
subEnableRouting: subEnableRouting,
|
subEnableRouting: subEnableRouting,
|
||||||
subRoutingRules: subRoutingRules,
|
subRoutingRules: subRoutingRules,
|
||||||
subHideSettings: subHideSettings,
|
subHideSettings: subHideSettings,
|
||||||
subPath: subPath,
|
|
||||||
subJsonPath: jsonPath,
|
subIncyEnableRouting: subIncyEnableRouting,
|
||||||
subClashPath: clashPath,
|
subIncyRoutingRules: subIncyRoutingRules,
|
||||||
jsonEnabled: jsonEnabled,
|
|
||||||
clashEnabled: clashEnabled,
|
subPath: subPath,
|
||||||
subEncrypt: encrypt,
|
subJsonPath: jsonPath,
|
||||||
updateInterval: update,
|
subClashPath: clashPath,
|
||||||
|
jsonEnabled: jsonEnabled,
|
||||||
|
clashEnabled: clashEnabled,
|
||||||
|
subEncrypt: encrypt,
|
||||||
|
updateInterval: update,
|
||||||
|
|
||||||
subService: sub,
|
subService: sub,
|
||||||
subJsonService: NewSubJsonService(jsonMux, jsonRules, jsonFinalMask, sub),
|
subJsonService: NewSubJsonService(jsonMux, jsonRules, jsonFinalMask, sub),
|
||||||
@@ -183,6 +193,11 @@ func (a *SUBController) subs(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
a.ApplyCommonHeaders(c, header, a.updateInterval, a.subTitle, a.subSupportUrl, profileUrl, a.subAnnounce, a.subEnableRouting, a.subRoutingRules, a.subHideSettings)
|
a.ApplyCommonHeaders(c, header, a.updateInterval, a.subTitle, a.subSupportUrl, profileUrl, a.subAnnounce, a.subEnableRouting, a.subRoutingRules, a.subHideSettings)
|
||||||
|
|
||||||
|
if a.subIncyEnableRouting && a.subIncyRoutingRules != "" {
|
||||||
|
result.WriteString(a.subIncyRoutingRules)
|
||||||
|
result.WriteString("\n")
|
||||||
|
}
|
||||||
|
|
||||||
if a.subEncrypt {
|
if a.subEncrypt {
|
||||||
c.String(200, base64.StdEncoding.EncodeToString([]byte(result.String())))
|
c.String(200, base64.StdEncoding.EncodeToString([]byte(result.String())))
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -83,8 +83,8 @@ func TestBuildEndpointLinks_ParamForm(t *testing.T) {
|
|||||||
func(dest string, port int) string { return fmt.Sprintf("vless://uid@%s", joinHostPort(dest, port)) },
|
func(dest string, port int) string { return fmt.Sprintf("vless://uid@%s", joinHostPort(dest, port)) },
|
||||||
func(e ShareEndpoint) string { return s.genRemark(in, "user", e.Remark, "") },
|
func(e ShareEndpoint) string { return s.genRemark(in, "user", e.Remark, "") },
|
||||||
)
|
)
|
||||||
want := "vless://uid@a.example.com:8443?fp=chrome&security=tls&sni=a.sni&type=tcp#ib-A\n" +
|
want := "vless://uid@a.example.com:8443?fp=chrome&security=tls&sni=a.sni&type=tcp#ib-A-user\n" +
|
||||||
"vless://uid@b.example.com:80?security=none&type=tcp#ib-B"
|
"vless://uid@b.example.com:80?security=none&type=tcp#ib-B-user"
|
||||||
if got != want {
|
if got != want {
|
||||||
t.Fatalf("N3 mismatch.\n got: %q\nwant: %q", got, want)
|
t.Fatalf("N3 mismatch.\n got: %q\nwant: %q", got, want)
|
||||||
}
|
}
|
||||||
@@ -105,8 +105,8 @@ func TestBuildEndpointVmessLinks(t *testing.T) {
|
|||||||
externalProxyToEndpoint(map[string]any{"forceTls": "none", "dest": "b.example.com", "port": float64(80), "remark": "B"}),
|
externalProxyToEndpoint(map[string]any{"forceTls": "none", "dest": "b.example.com", "port": float64(80), "remark": "B"}),
|
||||||
}
|
}
|
||||||
got := s.buildEndpointVmessLinks(eps, baseObj, in, "user", "tcp")
|
got := s.buildEndpointVmessLinks(eps, baseObj, in, "user", "tcp")
|
||||||
want := "vmess://ewogICJhZGQiOiAiYS5leGFtcGxlLmNvbSIsCiAgImFscG4iOiAiaDIiLAogICJmcCI6ICJjaHJvbWUiLAogICJpZCI6ICJ1aWQiLAogICJuZXQiOiAidGNwIiwKICAicG9ydCI6IDg0NDMsCiAgInBzIjogImliLUEiLAogICJzY3kiOiAiYXV0byIsCiAgInNuaSI6ICJhLnNuaSIsCiAgInRscyI6ICJ0bHMiLAogICJ0eXBlIjogIm5vbmUiLAogICJ2IjogIjIiCn0=\n" +
|
want := "vmess://ewogICJhZGQiOiAiYS5leGFtcGxlLmNvbSIsCiAgImFscG4iOiAiaDIiLAogICJmcCI6ICJjaHJvbWUiLAogICJpZCI6ICJ1aWQiLAogICJuZXQiOiAidGNwIiwKICAicG9ydCI6IDg0NDMsCiAgInBzIjogImliLUEtdXNlciIsCiAgInNjeSI6ICJhdXRvIiwKICAic25pIjogImEuc25pIiwKICAidGxzIjogInRscyIsCiAgInR5cGUiOiAibm9uZSIsCiAgInYiOiAiMiIKfQ==\n" +
|
||||||
"vmess://ewogICJhZGQiOiAiYi5leGFtcGxlLmNvbSIsCiAgImlkIjogInVpZCIsCiAgIm5ldCI6ICJ0Y3AiLAogICJwb3J0IjogODAsCiAgInBzIjogImliLUIiLAogICJzY3kiOiAiYXV0byIsCiAgInRscyI6ICJub25lIiwKICAidHlwZSI6ICJub25lIiwKICAidiI6ICIyIgp9"
|
"vmess://ewogICJhZGQiOiAiYi5leGFtcGxlLmNvbSIsCiAgImlkIjogInVpZCIsCiAgIm5ldCI6ICJ0Y3AiLAogICJwb3J0IjogODAsCiAgInBzIjogImliLUItdXNlciIsCiAgInNjeSI6ICJhdXRvIiwKICAidGxzIjogIm5vbmUiLAogICJ0eXBlIjogIm5vbmUiLAogICJ2IjogIjIiCn0="
|
||||||
if got != want {
|
if got != want {
|
||||||
t.Fatalf("N4 mismatch.\n got: %q\nwant: %q", got, want)
|
t.Fatalf("N4 mismatch.\n got: %q\nwant: %q", got, want)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package sub
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||||
|
)
|
||||||
|
|
||||||
|
// A single getSubs entry can hold several links (one per host of an inbound)
|
||||||
|
// joined by newlines. BuildPageData must split them into one entry per link, with
|
||||||
|
// the email replicated, so the subpage renders one row per host instead of
|
||||||
|
// collapsing them onto a single mangled line.
|
||||||
|
func TestBuildPageData_SplitsMultiHostLinks(t *testing.T) {
|
||||||
|
s := &SubService{}
|
||||||
|
subs := []string{
|
||||||
|
"vless://a@h1:443?type=tcp#DE-john@x\nvless://a@h2:443?type=tcp#DE-john@x\nvless://a@h3:443?type=tcp#DE-john@x",
|
||||||
|
"vless://b@h:443?type=tcp#FR-alice@x",
|
||||||
|
}
|
||||||
|
emails := []string{"john@x", "alice@x"}
|
||||||
|
|
||||||
|
page := s.BuildPageData("s1", "", xray.ClientTraffic{}, 0, subs, emails, "", "", "", "/", "", "")
|
||||||
|
|
||||||
|
if len(page.Result) != 4 {
|
||||||
|
t.Fatalf("Result len = %d, want 4 (3 host links + 1 single link)", len(page.Result))
|
||||||
|
}
|
||||||
|
for i, link := range page.Result {
|
||||||
|
if strings.Contains(link, "\n") {
|
||||||
|
t.Fatalf("Result[%d] still multi-line: %q", i, link)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
wantEmails := []string{"john@x", "john@x", "john@x", "alice@x"}
|
||||||
|
if !reflect.DeepEqual(page.Emails, wantEmails) {
|
||||||
|
t.Fatalf("Emails = %v, want %v", page.Emails, wantEmails)
|
||||||
|
}
|
||||||
|
}
|
||||||
+101
-39
@@ -6,7 +6,6 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
"unicode"
|
|
||||||
|
|
||||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||||
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
|
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
|
||||||
@@ -25,6 +24,7 @@ type remarkContext struct {
|
|||||||
inbound *model.Inbound
|
inbound *model.Inbound
|
||||||
hostRemark string
|
hostRemark string
|
||||||
transport string
|
transport string
|
||||||
|
security string
|
||||||
}
|
}
|
||||||
|
|
||||||
// configName is the display name for a link: always the inbound's own remark.
|
// configName is the display name for a link: always the inbound's own remark.
|
||||||
@@ -71,6 +71,7 @@ var uiTokenMap = map[string]string{
|
|||||||
"USAGE_PERCENTAGE": "USAGE_PERCENTAGE",
|
"USAGE_PERCENTAGE": "USAGE_PERCENTAGE",
|
||||||
"PROTOCOL": "PROTOCOL",
|
"PROTOCOL": "PROTOCOL",
|
||||||
"TRANSPORT": "TRANSPORT",
|
"TRANSPORT": "TRANSPORT",
|
||||||
|
"SECURITY": "SECURITY",
|
||||||
}
|
}
|
||||||
|
|
||||||
// translateUISingleBrackets converts user-friendly single-brace tokens to the
|
// translateUISingleBrackets converts user-friendly single-brace tokens to the
|
||||||
@@ -226,6 +227,8 @@ func remarkVarValue(token string, ctx remarkContext) string {
|
|||||||
return ""
|
return ""
|
||||||
case "TRANSPORT":
|
case "TRANSPORT":
|
||||||
return ctx.transport
|
return ctx.transport
|
||||||
|
case "SECURITY":
|
||||||
|
return strings.ToUpper(ctx.security)
|
||||||
case "TIME_LEFT":
|
case "TIME_LEFT":
|
||||||
return timeLeftLabel(st.ExpiryTime)
|
return timeLeftLabel(st.ExpiryTime)
|
||||||
case "JALALI_EXPIRE_DATE":
|
case "JALALI_EXPIRE_DATE":
|
||||||
@@ -458,52 +461,107 @@ func (s *SubService) lookupClient(inbound *model.Inbound, email string) model.Cl
|
|||||||
return model.Client{Email: email}
|
return model.Client{Email: email}
|
||||||
}
|
}
|
||||||
|
|
||||||
// usageInfoTokens are the per-client status tokens. On every link of a
|
var usageInfoTokens = map[string]bool{
|
||||||
// subscription except the client's first, these (and the decoration leading
|
"TRAFFIC_USED": true, "TRAFFIC_LEFT": true, "TRAFFIC_TOTAL": true,
|
||||||
// into them) are dropped, so the traffic/expiry info shows once instead of on
|
"TRAFFIC_USED_BYTES": true, "TRAFFIC_LEFT_BYTES": true, "TRAFFIC_TOTAL_BYTES": true,
|
||||||
// every server.
|
"UP": true, "DOWN": true, "DAYS_LEFT": true, "EXPIRE_DATE": true, "EXPIRE_UNIX": true,
|
||||||
var usageInfoTokens = []string{
|
"STATUS": true, "STATUS_EMOJI": true, "USAGE_PERCENTAGE": true, "TIME_LEFT": true,
|
||||||
"TRAFFIC_USED", "TRAFFIC_LEFT", "TRAFFIC_TOTAL",
|
"JALALI_EXPIRE_DATE": true,
|
||||||
"TRAFFIC_USED_BYTES", "TRAFFIC_LEFT_BYTES", "TRAFFIC_TOTAL_BYTES",
|
|
||||||
"UP", "DOWN", "DAYS_LEFT", "EXPIRE_DATE", "EXPIRE_UNIX", "STATUS",
|
|
||||||
"STATUS_EMOJI", "USAGE_PERCENTAGE", "TIME_LEFT", "JALALI_EXPIRE_DATE",
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// nameOnlyTemplate returns template with the trailing per-client info part
|
var connectionTokens = map[string]bool{
|
||||||
// removed: everything from the first usage token (and the decoration — emojis,
|
"PROTOCOL": true,
|
||||||
// spaces, separators — leading into it) onward is dropped, leaving the config
|
"TRANSPORT": true,
|
||||||
// name. Returns "" when the template is info-only.
|
"SECURITY": true,
|
||||||
func nameOnlyTemplate(template string) string {
|
}
|
||||||
idx := -1
|
|
||||||
for _, tok := range usageInfoTokens {
|
var displayRemoveTokens = mergeTokenSets(usageInfoTokens, connectionTokens)
|
||||||
if i := strings.Index(template, "{{"+tok+"}}"); i >= 0 && (idx < 0 || i < idx) {
|
|
||||||
idx = i
|
func mergeTokenSets(sets ...map[string]bool) map[string]bool {
|
||||||
|
out := make(map[string]bool)
|
||||||
|
for _, set := range sets {
|
||||||
|
for tok := range set {
|
||||||
|
out[tok] = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if idx < 0 {
|
return out
|
||||||
return template
|
}
|
||||||
|
|
||||||
|
func filterRemarkTemplate(template string, remove map[string]bool) string {
|
||||||
|
segments := strings.Split(template, "|")
|
||||||
|
kept := make([]string, 0, len(segments))
|
||||||
|
for _, seg := range segments {
|
||||||
|
if out := filterRemarkSegment(seg, remove); out != "" {
|
||||||
|
kept = append(kept, out)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return strings.TrimRightFunc(template[:idx], func(r rune) bool {
|
return strings.Join(kept, "|")
|
||||||
return r != '}' && !unicode.IsLetter(r) && !unicode.IsDigit(r)
|
}
|
||||||
})
|
|
||||||
|
func filterRemarkSegment(seg string, remove map[string]bool) string {
|
||||||
|
locs := remarkVarRe.FindAllStringSubmatchIndex(seg, -1)
|
||||||
|
hasRemove := false
|
||||||
|
for _, loc := range locs {
|
||||||
|
if remove[seg[loc[2]:loc[3]]] {
|
||||||
|
hasRemove = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !hasRemove {
|
||||||
|
return strings.TrimSpace(seg)
|
||||||
|
}
|
||||||
|
runs := make([]string, 0, 2)
|
||||||
|
runStart, leftRemoved := 0, false
|
||||||
|
for _, loc := range locs {
|
||||||
|
if !remove[seg[loc[2]:loc[3]]] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
runs = appendKeptRun(runs, seg[runStart:loc[0]], leftRemoved, true)
|
||||||
|
runStart, leftRemoved = loc[1], true
|
||||||
|
}
|
||||||
|
runs = appendKeptRun(runs, seg[runStart:], leftRemoved, false)
|
||||||
|
return strings.Join(runs, " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
func appendKeptRun(runs []string, run string, leftRemoved, rightRemoved bool) []string {
|
||||||
|
locs := remarkVarRe.FindAllStringSubmatchIndex(run, -1)
|
||||||
|
if len(locs) == 0 {
|
||||||
|
return runs
|
||||||
|
}
|
||||||
|
start, end := 0, len(run)
|
||||||
|
if leftRemoved {
|
||||||
|
start = locs[0][0]
|
||||||
|
}
|
||||||
|
if rightRemoved {
|
||||||
|
end = locs[len(locs)-1][1]
|
||||||
|
}
|
||||||
|
if frag := strings.TrimSpace(run[start:end]); frag != "" {
|
||||||
|
runs = append(runs, frag)
|
||||||
|
}
|
||||||
|
return runs
|
||||||
}
|
}
|
||||||
|
|
||||||
// effectiveTemplate picks which template to expand for one body link: the full
|
|
||||||
// template (with the per-client info) for a client's first link, and the
|
|
||||||
// name-only template for every link thereafter — so the info shows once. Only
|
|
||||||
// called in the subscription-body context (displays bypass the template).
|
|
||||||
func (s *SubService) effectiveTemplate(email string) string {
|
func (s *SubService) effectiveTemplate(email string) string {
|
||||||
translated := translateUISingleBrackets(s.remarkTemplate)
|
translated := translateUISingleBrackets(s.remarkTemplate)
|
||||||
if s.usageShown == nil {
|
if s.usageShown == nil {
|
||||||
s.usageShown = map[string]bool{}
|
s.usageShown = map[string]bool{}
|
||||||
}
|
}
|
||||||
if s.usageShown[email] {
|
if s.usageShown[email] {
|
||||||
return nameOnlyTemplate(translated)
|
return filterRemarkTemplate(translated, usageInfoTokens)
|
||||||
}
|
}
|
||||||
s.usageShown[email] = true
|
s.usageShown[email] = true
|
||||||
return translated
|
return translated
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func inboundSecurity(inbound *model.Inbound) string {
|
||||||
|
if inbound == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
stream := unmarshalStreamSettings(inbound.StreamSettings)
|
||||||
|
security, _ := stream["security"].(string)
|
||||||
|
return security
|
||||||
|
}
|
||||||
|
|
||||||
// genTemplatedRemark expands the remark template for one client. hostRemark is
|
// genTemplatedRemark expands the remark template for one client. hostRemark is
|
||||||
// the host endpoint's remark (empty for a plain inbound); it backs the {{HOST}}
|
// the host endpoint's remark (empty for a plain inbound); it backs the {{HOST}}
|
||||||
// token only and never substitutes the inbound remark as the config name.
|
// token only and never substitutes the inbound remark as the config name.
|
||||||
@@ -514,23 +572,27 @@ func (s *SubService) genTemplatedRemark(inbound *model.Inbound, client model.Cli
|
|||||||
inbound: inbound,
|
inbound: inbound,
|
||||||
hostRemark: hostRemark,
|
hostRemark: hostRemark,
|
||||||
transport: transport,
|
transport: transport,
|
||||||
|
security: inboundSecurity(inbound),
|
||||||
|
}
|
||||||
|
var tmpl string
|
||||||
|
if s.subscriptionBody {
|
||||||
|
tmpl = s.effectiveTemplate(client.Email)
|
||||||
|
} else {
|
||||||
|
tmpl = filterRemarkTemplate(translateUISingleBrackets(s.remarkTemplate), displayRemoveTokens)
|
||||||
}
|
}
|
||||||
tmpl := s.effectiveTemplate(client.Email)
|
|
||||||
// Fall back to the config name when the template is empty or expands to
|
|
||||||
// nothing (e.g. an all-unlimited template whose only segments dropped out).
|
|
||||||
if out := expandRemarkVars(tmpl, ctx); strings.TrimSpace(out) != "" {
|
if out := expandRemarkVars(tmpl, ctx); strings.TrimSpace(out) != "" {
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
return ctx.configName()
|
return ctx.configName()
|
||||||
}
|
}
|
||||||
|
|
||||||
// genHostRemark builds one host endpoint's remark for a specific client. The
|
// genHostRemark builds one host endpoint's remark for a specific client. With a
|
||||||
// config name is always the inbound's own remark; the host's remark is surfaced
|
// remark template set it is template-driven (body shows the full template on the
|
||||||
// only through the {{HOST}} token. In the subscription body the rest of the
|
// first link and the name-only part thereafter; displays render the name-only
|
||||||
// remark template still applies; displays show just the config name.
|
// part). With no template it falls back to inbound, host and email joined by "-".
|
||||||
func (s *SubService) genHostRemark(inbound *model.Inbound, client model.Client, hostRemark string, transport string) string {
|
func (s *SubService) genHostRemark(inbound *model.Inbound, client model.Client, hostRemark string, transport string) string {
|
||||||
if !s.subscriptionBody {
|
if s.remarkTemplate != "" {
|
||||||
return remarkContext{inbound: inbound, hostRemark: hostRemark}.configName()
|
return s.genTemplatedRemark(inbound, client, hostRemark, transport)
|
||||||
}
|
}
|
||||||
return s.genTemplatedRemark(inbound, client, hostRemark, transport)
|
return fallbackRemark(inbound.Remark, hostRemark, client.Email)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -164,15 +164,15 @@ func hostRemarkService(template string) (*SubService, *model.Inbound, model.Clie
|
|||||||
return s, inbound, client
|
return s, inbound, client
|
||||||
}
|
}
|
||||||
|
|
||||||
// The config name is always the inbound's own remark; the host endpoint's remark
|
// With no template configured, genHostRemark falls back to the inbound remark,
|
||||||
// never substitutes it (it is reachable only through {{HOST}}).
|
// host and email joined by "-".
|
||||||
func TestGenHostRemark_ConfigNameUsesInbound(t *testing.T) {
|
func TestGenHostRemark_NoTemplate_Fallback(t *testing.T) {
|
||||||
s, inbound, client := hostRemarkService("") // no template → config name only
|
s, inbound, client := hostRemarkService("")
|
||||||
if got := s.genHostRemark(inbound, client, "Relay", ""); got != "DE" {
|
if got := s.genHostRemark(inbound, client, "Relay", ""); got != "DE-Relay-john@example.com" {
|
||||||
t.Fatalf("genHostRemark = %q, want %q (inbound remark, host ignored)", got, "DE")
|
t.Fatalf("genHostRemark = %q, want %q", got, "DE-Relay-john@example.com")
|
||||||
}
|
}
|
||||||
if got := s.genHostRemark(inbound, client, "", ""); got != "DE" {
|
if got := s.genHostRemark(inbound, client, "", ""); got != "DE-john@example.com" {
|
||||||
t.Fatalf("genHostRemark (no host remark) = %q, want %q", got, "DE")
|
t.Fatalf("genHostRemark (no host remark) = %q, want %q", got, "DE-john@example.com")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -206,12 +206,11 @@ func TestGenRemark_GlobalTemplate(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// With no template, genRemark composes the fallback model and adds no suffix.
|
func TestGenRemark_NoTemplate_AppendsEmail(t *testing.T) {
|
||||||
func TestGenRemark_NoTemplate_NoSuffix(t *testing.T) {
|
|
||||||
s, inbound, _ := hostRemarkService("")
|
s, inbound, _ := hostRemarkService("")
|
||||||
got := s.genRemark(inbound, "john@example.com", "Relay", "")
|
got := s.genRemark(inbound, "john@example.com", "Relay", "")
|
||||||
if got != "DE-Relay" {
|
if got != "DE-Relay-john@example.com" {
|
||||||
t.Fatalf("genRemark = %q, want %q (no suffix)", got, "DE-Relay")
|
t.Fatalf("genRemark = %q, want %q", got, "DE-Relay-john@example.com")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -232,43 +231,158 @@ func TestUsageOnFirstLinkOnly(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Outside the subscription body (panel link/QR displays, sub info page) the
|
|
||||||
// template is bypassed entirely — links show just the config name, with no
|
|
||||||
// per-client email or usage info.
|
|
||||||
func TestRemarkInDisplayContext(t *testing.T) {
|
func TestRemarkInDisplayContext(t *testing.T) {
|
||||||
s, inbound, client := hostRemarkService("{{INBOUND}}|📊{{TRAFFIC_LEFT}}|⏳{{DAYS_LEFT}}D")
|
s, inbound, client := hostRemarkService("{{INBOUND}}-{{EMAIL}}|📊{{TRAFFIC_LEFT}}|⏳{{DAYS_LEFT}}D")
|
||||||
s.subscriptionBody = false
|
s.subscriptionBody = false
|
||||||
// A host link in a display shows only the config name — the inbound's remark,
|
const want = "DE-john@example.com"
|
||||||
// with no per-client email or usage info and the host remark ignored.
|
if got := s.genHostRemark(inbound, client, "CDN", ""); got != want {
|
||||||
if got := s.genHostRemark(inbound, client, "CDN", ""); got != "DE" {
|
t.Fatalf("display host link = %q, want %q", got, want)
|
||||||
t.Fatalf("display host link = %q, want config name %q", got, "DE")
|
|
||||||
}
|
}
|
||||||
// With no host remark, the config name is likewise the inbound's own remark.
|
if got := s.genHostRemark(inbound, client, "", ""); got != want {
|
||||||
if got := s.genHostRemark(inbound, client, "", ""); got != "DE" {
|
t.Fatalf("display host link (no host) = %q, want %q", got, want)
|
||||||
t.Fatalf("display host link (no host) = %q, want %q", got, "DE")
|
|
||||||
}
|
}
|
||||||
// genRemark (non-host) likewise drops the template in display context.
|
if got := s.genRemark(inbound, client.Email, "", ""); got != want {
|
||||||
if got := s.genRemark(inbound, client.Email, "", ""); got != "DE" {
|
t.Fatalf("display genRemark = %q, want %q", got, want)
|
||||||
t.Fatalf("display genRemark = %q, want %q", got, "DE")
|
}
|
||||||
|
s2, inbound2, client2 := hostRemarkService("{{INBOUND}}-{{HOST}}|📊{{TRAFFIC_LEFT}}")
|
||||||
|
s2.subscriptionBody = false
|
||||||
|
if got := s2.genHostRemark(inbound2, client2, "CDN", ""); got != "DE-CDN" {
|
||||||
|
t.Fatalf("display host link with HOST token = %q, want %q", got, "DE-CDN")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// nameOnlyTemplate drops the info part (and its leading decoration), keeping name.
|
func TestFilterRemarkTemplate_BodyRepeat(t *testing.T) {
|
||||||
func TestNameOnlyTemplate(t *testing.T) {
|
|
||||||
cases := map[string]string{
|
cases := map[string]string{
|
||||||
"{{INBOUND}}|📊{{TRAFFIC_LEFT}}|⏳{{DAYS_LEFT}}D": "{{INBOUND}}", // the default → name only
|
"{{INBOUND}}|📊{{TRAFFIC_LEFT}}|{{PROTOCOL}}-{{TRANSPORT}}-{{SECURITY}}": "{{INBOUND}}|{{PROTOCOL}}-{{TRANSPORT}}-{{SECURITY}}",
|
||||||
"{{EMAIL}} {{INBOUND}} ⏳{{DAYS_LEFT}}": "{{EMAIL}} {{INBOUND}}", // multi-token name survives the trim
|
"{{INBOUND}}|📊{{TRAFFIC_LEFT}}|⏳{{DAYS_LEFT}}D": "{{INBOUND}}",
|
||||||
"{{INBOUND}} | {{STATUS}}": "{{INBOUND}}",
|
"{{INBOUND}} {{PROTOCOL}}|📊{{TRAFFIC_LEFT}}": "{{INBOUND}} {{PROTOCOL}}",
|
||||||
"{{INBOUND}}-{{EMAIL}}": "{{INBOUND}}-{{EMAIL}}", // no info tokens → unchanged
|
"{{INBOUND}}-{{EMAIL}}": "{{INBOUND}}-{{EMAIL}}",
|
||||||
"{{TRAFFIC_LEFT}}": "", // info only → empty
|
"{{TRAFFIC_LEFT}}|{{SECURITY}}": "{{SECURITY}}",
|
||||||
|
"{{INBOUND}}|📊{{TRAFFIC_LEFT}} {{PROTOCOL}}": "{{INBOUND}}|{{PROTOCOL}}",
|
||||||
|
"{{INBOUND}}|📊{{TRAFFIC_LEFT}}|{{EMAIL}}": "{{INBOUND}}|{{EMAIL}}",
|
||||||
|
"{{INBOUND}}|📊{{TRAFFIC_LEFT}}|⏳{{DAYS_LEFT}}D{{PROTOCOL}}{{TRANSPORT}}{{SECURITY}}": "{{INBOUND}}|{{PROTOCOL}}{{TRANSPORT}}{{SECURITY}}",
|
||||||
|
"{{EMAIL}} {{TRAFFIC_USED}}5h": "{{EMAIL}}",
|
||||||
|
"{{PROTOCOL}} {{TRAFFIC_LEFT}}GB": "{{PROTOCOL}}",
|
||||||
|
"{{EMAIL}}-{{TRAFFIC_LEFT}}D-{{HOST}}": "{{EMAIL}} {{HOST}}",
|
||||||
|
"{{EMAIL}} 📊{{TRAFFIC_LEFT}} {{PROTOCOL}}": "{{EMAIL}} {{PROTOCOL}}",
|
||||||
}
|
}
|
||||||
for tmpl, want := range cases {
|
for tmpl, want := range cases {
|
||||||
if got := nameOnlyTemplate(tmpl); got != want {
|
if got := filterRemarkTemplate(tmpl, usageInfoTokens); got != want {
|
||||||
t.Errorf("nameOnlyTemplate(%q) = %q, want %q", tmpl, got, want)
|
t.Errorf("filterRemarkTemplate(%q, usage) = %q, want %q", tmpl, got, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestFilterRemarkTemplate_Display(t *testing.T) {
|
||||||
|
cases := map[string]string{
|
||||||
|
"{{INBOUND}}-{{EMAIL}}|📊{{TRAFFIC_LEFT}}|{{PROTOCOL}}": "{{INBOUND}}-{{EMAIL}}",
|
||||||
|
"{{INBOUND}} {{PROTOCOL}}": "{{INBOUND}}",
|
||||||
|
"{{EMAIL}} {{INBOUND}} ⏳{{DAYS_LEFT}}": "{{EMAIL}} {{INBOUND}}",
|
||||||
|
"{{INBOUND}} | {{STATUS}}": "{{INBOUND}}",
|
||||||
|
"{{INBOUND}}-{{EMAIL}}": "{{INBOUND}}-{{EMAIL}}",
|
||||||
|
"{{TRAFFIC_LEFT}}": "",
|
||||||
|
"{{INBOUND}}|📊{{TRAFFIC_LEFT}}|{{HOST}}": "{{INBOUND}}|{{HOST}}",
|
||||||
|
"{{EMAIL}} ⏳{{DAYS_LEFT}}D {{HOST}}": "{{EMAIL}} {{HOST}}",
|
||||||
|
"{{INBOUND}} {{TRAFFIC_LEFT}} {{EMAIL}}": "{{INBOUND}} {{EMAIL}}",
|
||||||
|
}
|
||||||
|
for tmpl, want := range cases {
|
||||||
|
if got := filterRemarkTemplate(tmpl, displayRemoveTokens); got != want {
|
||||||
|
t.Errorf("filterRemarkTemplate(%q, display) = %q, want %q", tmpl, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConnectionTokensOnEveryBodyLink(t *testing.T) {
|
||||||
|
s := &SubService{
|
||||||
|
remarkTemplate: "{{INBOUND}}|📊{{TRAFFIC_LEFT}}|{{PROTOCOL}} {{TRANSPORT}} {{SECURITY}}",
|
||||||
|
subscriptionBody: true,
|
||||||
|
usageShown: map[string]bool{},
|
||||||
|
}
|
||||||
|
inbound := &model.Inbound{
|
||||||
|
Remark: "DE",
|
||||||
|
Protocol: "vless",
|
||||||
|
StreamSettings: `{"network":"ws","security":"tls"}`,
|
||||||
|
ClientStats: []xray.ClientTraffic{{Email: "john@x", Enable: true, Total: 100 * gb, Up: 30 * gb}},
|
||||||
|
}
|
||||||
|
client := model.Client{Email: "john@x"}
|
||||||
|
first := s.genTemplatedRemark(inbound, client, "", "ws")
|
||||||
|
second := s.genTemplatedRemark(inbound, client, "", "ws")
|
||||||
|
for _, want := range []string{"VLESS", "ws", "TLS"} {
|
||||||
|
if !strings.Contains(first, want) {
|
||||||
|
t.Fatalf("first body link %q missing %q", first, want)
|
||||||
|
}
|
||||||
|
if !strings.Contains(second, want) {
|
||||||
|
t.Fatalf("repeat body link %q missing connection token %q", second, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.ContainsAny(second, "📊") || strings.Contains(second, "GB") {
|
||||||
|
t.Fatalf("repeat body link must drop the usage block: %q", second)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConnectionTokensMixedIntoUsageSegment(t *testing.T) {
|
||||||
|
s := &SubService{
|
||||||
|
remarkTemplate: "{{INBOUND}}-{{EMAIL}}|📊{{TRAFFIC_LEFT}}|⏳{{DAYS_LEFT}}D {{PROTOCOL}} {{TRANSPORT}} {{SECURITY}}",
|
||||||
|
subscriptionBody: true,
|
||||||
|
usageShown: map[string]bool{},
|
||||||
|
}
|
||||||
|
inbound := &model.Inbound{
|
||||||
|
Remark: "DE",
|
||||||
|
Protocol: "vless",
|
||||||
|
StreamSettings: `{"network":"grpc","security":"reality"}`,
|
||||||
|
ClientStats: []xray.ClientTraffic{{Email: "john@x", Enable: true, Total: 100 * gb, Up: 30 * gb}},
|
||||||
|
}
|
||||||
|
client := model.Client{Email: "john@x"}
|
||||||
|
_ = s.genTemplatedRemark(inbound, client, "", "grpc")
|
||||||
|
second := s.genTemplatedRemark(inbound, client, "", "grpc")
|
||||||
|
for _, want := range []string{"VLESS", "grpc", "REALITY"} {
|
||||||
|
if !strings.Contains(second, want) {
|
||||||
|
t.Fatalf("repeat body link %q missing connection token %q", second, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Contains(second, "GB") || strings.ContainsRune(second, '⏳') {
|
||||||
|
t.Fatalf("repeat body link must drop the usage block: %q", second)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConnectionTokensDisplayContextUnchanged(t *testing.T) {
|
||||||
|
s := &SubService{
|
||||||
|
remarkTemplate: "{{INBOUND}}|📊{{TRAFFIC_LEFT}}|{{PROTOCOL}}",
|
||||||
|
subscriptionBody: false,
|
||||||
|
}
|
||||||
|
inbound := &model.Inbound{
|
||||||
|
Remark: "DE",
|
||||||
|
Protocol: "vless",
|
||||||
|
StreamSettings: `{"network":"ws","security":"tls"}`,
|
||||||
|
ClientStats: []xray.ClientTraffic{{Email: "john@x", Enable: true, Total: 100 * gb, Up: 30 * gb}},
|
||||||
|
}
|
||||||
|
if got := s.genTemplatedRemark(inbound, model.Client{Email: "john@x"}, "", "ws"); got != "DE" {
|
||||||
|
t.Fatalf("display remark = %q, want DE (connection after usage stripped outside the body)", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIdentityTokensEverywhere(t *testing.T) {
|
||||||
|
const tmpl = "{{INBOUND}}|📊{{TRAFFIC_LEFT}}|{{EMAIL}}"
|
||||||
|
inbound := &model.Inbound{
|
||||||
|
Remark: "DE",
|
||||||
|
Protocol: "vless",
|
||||||
|
StreamSettings: `{"network":"ws","security":"tls"}`,
|
||||||
|
ClientStats: []xray.ClientTraffic{{Email: "john@x", Enable: true, Total: 100 * gb, Up: 30 * gb}},
|
||||||
|
}
|
||||||
|
client := model.Client{Email: "john@x"}
|
||||||
|
|
||||||
|
body := &SubService{remarkTemplate: tmpl, subscriptionBody: true, usageShown: map[string]bool{}}
|
||||||
|
_ = body.genTemplatedRemark(inbound, client, "", "ws") // first link consumes the usage block
|
||||||
|
if second := body.genTemplatedRemark(inbound, client, "", "ws"); !strings.Contains(second, "john@x") {
|
||||||
|
t.Fatalf("repeat body link %q must keep the identity token", second)
|
||||||
|
}
|
||||||
|
|
||||||
|
display := &SubService{remarkTemplate: tmpl, subscriptionBody: false}
|
||||||
|
if got := display.genTemplatedRemark(inbound, client, "", "ws"); !strings.Contains(got, "john@x") {
|
||||||
|
t.Fatalf("display remark %q must keep the identity token", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// statsForClient resolves usage from the per-request statsByEmail map when the
|
// statsForClient resolves usage from the per-request statsByEmail map when the
|
||||||
// link's own inbound doesn't carry the client's (globally unique) traffic row —
|
// link's own inbound doesn't carry the client's (globally unique) traffic row —
|
||||||
// the multi-inbound case that made {{TRAFFIC_LEFT}} show the full quota (#5443).
|
// the multi-inbound case that made {{TRAFFIC_LEFT}} show the full quota (#5443).
|
||||||
@@ -379,6 +493,7 @@ func TestExpandNewTokensInTemplate(t *testing.T) {
|
|||||||
stats: stats,
|
stats: stats,
|
||||||
inbound: inbound,
|
inbound: inbound,
|
||||||
transport: "ws",
|
transport: "ws",
|
||||||
|
security: "reality",
|
||||||
}
|
}
|
||||||
|
|
||||||
cases := []struct{ tmpl, want string }{
|
cases := []struct{ tmpl, want string }{
|
||||||
@@ -386,6 +501,7 @@ func TestExpandNewTokensInTemplate(t *testing.T) {
|
|||||||
{"{{USAGE_PERCENTAGE}}", "50.0%"},
|
{"{{USAGE_PERCENTAGE}}", "50.0%"},
|
||||||
{"{{PROTOCOL}}", "VLESS"},
|
{"{{PROTOCOL}}", "VLESS"},
|
||||||
{"{{TRANSPORT}}", "ws"},
|
{"{{TRANSPORT}}", "ws"},
|
||||||
|
{"{{SECURITY}}", "REALITY"},
|
||||||
{"{{STATUS_EMOJI}} {{INBOUND}}", "✅ DE"},
|
{"{{STATUS_EMOJI}} {{INBOUND}}", "✅ DE"},
|
||||||
}
|
}
|
||||||
for _, c := range cases {
|
for _, c := range cases {
|
||||||
@@ -395,6 +511,32 @@ func TestExpandNewTokensInTemplate(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestInboundSecurity(t *testing.T) {
|
||||||
|
cases := []struct{ stream, want string }{
|
||||||
|
{`{"network":"ws","security":"tls"}`, "tls"},
|
||||||
|
{`{"network":"tcp","security":"reality"}`, "reality"},
|
||||||
|
{`{"network":"tcp","security":"none"}`, "none"},
|
||||||
|
{`{"network":"tcp"}`, ""},
|
||||||
|
{"", ""},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
if got := inboundSecurity(&model.Inbound{StreamSettings: c.stream}); got != c.want {
|
||||||
|
t.Errorf("inboundSecurity(%q) = %q, want %q", c.stream, got, c.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := inboundSecurity(nil); got != "" {
|
||||||
|
t.Errorf("inboundSecurity(nil) = %q, want empty", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGenTemplatedRemark_SecurityFromStream(t *testing.T) {
|
||||||
|
s := &SubService{remarkTemplate: "{{INBOUND}} {{SECURITY}}", subscriptionBody: true}
|
||||||
|
inbound := &model.Inbound{Remark: "DE", StreamSettings: `{"network":"tcp","security":"reality"}`}
|
||||||
|
if got := s.genTemplatedRemark(inbound, model.Client{Email: "a@x"}, "", "tcp"); got != "DE REALITY" {
|
||||||
|
t.Fatalf("genTemplatedRemark SECURITY = %q, want %q", got, "DE REALITY")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestTranslateUISingleBrackets(t *testing.T) {
|
func TestTranslateUISingleBrackets(t *testing.T) {
|
||||||
cases := []struct{ in, want string }{
|
cases := []struct{ in, want string }{
|
||||||
{"{EMAIL}", "{{EMAIL}}"},
|
{"{EMAIL}", "{{EMAIL}}"},
|
||||||
@@ -421,6 +563,7 @@ func TestExpandRemarkVars_SingleBracketUI(t *testing.T) {
|
|||||||
stats: stats,
|
stats: stats,
|
||||||
inbound: inbound,
|
inbound: inbound,
|
||||||
transport: "ws",
|
transport: "ws",
|
||||||
|
security: "tls",
|
||||||
}
|
}
|
||||||
cases := []struct{ tmpl, want string }{
|
cases := []struct{ tmpl, want string }{
|
||||||
{"{EMAIL}", "alice@test.com"},
|
{"{EMAIL}", "alice@test.com"},
|
||||||
@@ -431,6 +574,7 @@ func TestExpandRemarkVars_SingleBracketUI(t *testing.T) {
|
|||||||
{"{USAGE_PERCENTAGE}", "50.0%"},
|
{"{USAGE_PERCENTAGE}", "50.0%"},
|
||||||
{"{PROTOCOL}", "VLESS"},
|
{"{PROTOCOL}", "VLESS"},
|
||||||
{"{TRANSPORT}", "ws"},
|
{"{TRANSPORT}", "ws"},
|
||||||
|
{"{SECURITY}", "TLS"},
|
||||||
}
|
}
|
||||||
for _, c := range cases {
|
for _, c := range cases {
|
||||||
if got := expandRemarkVars(c.tmpl, ctx); got != c.want {
|
if got := expandRemarkVars(c.tmpl, ctx); got != c.want {
|
||||||
|
|||||||
+28
-21
@@ -1634,31 +1634,25 @@ func cloneStringMap(source map[string]string) map[string]string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// genRemark builds the remark for a non-host link (raw default / legacy
|
// genRemark builds the remark for a non-host link (raw default / legacy
|
||||||
// externalProxy / synthetic JSON-Clash entry). In the subscription body a set
|
// externalProxy / synthetic JSON-Clash entry). A set remark template drives it
|
||||||
// remark template takes over; otherwise (and in every display context) the
|
// in both the body and display contexts (genTemplatedRemark renders the
|
||||||
// remark is just the config name (inbound remark, then extra).
|
// name-only part on displays); with no template it falls back to the inbound
|
||||||
|
// remark, extra and email joined by "-".
|
||||||
func (s *SubService) genRemark(inbound *model.Inbound, email string, extra string, transport string) string {
|
func (s *SubService) genRemark(inbound *model.Inbound, email string, extra string, transport string) string {
|
||||||
if s.remarkTemplate != "" && s.subscriptionBody {
|
if s.remarkTemplate != "" {
|
||||||
return s.genTemplatedRemark(inbound, s.lookupClient(inbound, email), extra, transport)
|
return s.genTemplatedRemark(inbound, s.lookupClient(inbound, email), extra, transport)
|
||||||
}
|
}
|
||||||
// Sub info page + panel link/QR displays: just the config name (no template,
|
return fallbackRemark(inbound.Remark, extra, email)
|
||||||
// so no per-client email/usage leaks into the shown remark).
|
|
||||||
return fallbackRemark(inbound.Remark, extra)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// fallbackRemark is the minimal remark used only when no template is configured
|
func fallbackRemark(parts ...string) string {
|
||||||
// (an operator explicitly cleared it): the inbound remark and the host/extra
|
out := make([]string, 0, len(parts))
|
||||||
// remark joined by "-", skipping empties. The configurable remark model was
|
for _, p := range parts {
|
||||||
// removed in favour of the template, whose default already includes the email.
|
if p != "" {
|
||||||
func fallbackRemark(inboundRemark, extra string) string {
|
out = append(out, p)
|
||||||
switch {
|
}
|
||||||
case inboundRemark == "":
|
|
||||||
return extra
|
|
||||||
case extra == "":
|
|
||||||
return inboundRemark
|
|
||||||
default:
|
|
||||||
return inboundRemark + "-" + extra
|
|
||||||
}
|
}
|
||||||
|
return strings.Join(out, "-")
|
||||||
}
|
}
|
||||||
|
|
||||||
// findClientStats returns the inbound's traffic record for email, if present.
|
// findClientStats returns the inbound's traffic record for email, if present.
|
||||||
@@ -2343,6 +2337,19 @@ func (s *SubService) BuildPageData(subId string, hostHeader string, traffic xray
|
|||||||
datepicker = "gregorian"
|
datepicker = "gregorian"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pageLinks := make([]string, 0, len(subs))
|
||||||
|
pageEmails := make([]string, 0, len(subs))
|
||||||
|
for i, sub := range subs {
|
||||||
|
email := ""
|
||||||
|
if i < len(emails) {
|
||||||
|
email = emails[i]
|
||||||
|
}
|
||||||
|
for _, link := range splitLinkLines(sub) {
|
||||||
|
pageLinks = append(pageLinks, link)
|
||||||
|
pageEmails = append(pageEmails, email)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return PageData{
|
return PageData{
|
||||||
Host: hostHeader,
|
Host: hostHeader,
|
||||||
BasePath: basePath,
|
BasePath: basePath,
|
||||||
@@ -2364,8 +2371,8 @@ func (s *SubService) BuildPageData(subId string, hostHeader string, traffic xray
|
|||||||
SubClashUrl: subClashURL,
|
SubClashUrl: subClashURL,
|
||||||
SubTitle: subTitle,
|
SubTitle: subTitle,
|
||||||
SubSupportUrl: subSupportUrl,
|
SubSupportUrl: subSupportUrl,
|
||||||
Result: subs,
|
Result: pageLinks,
|
||||||
Emails: emails,
|
Emails: pageEmails,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+12
-1
@@ -175,6 +175,16 @@ func (s *Server) initRouter() (*gin.Engine, error) {
|
|||||||
SubHideSettings = false
|
SubHideSettings = false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
SubIncyEnableRouting, err := s.settingService.GetSubIncyEnableRouting()
|
||||||
|
if err != nil {
|
||||||
|
SubIncyEnableRouting = false
|
||||||
|
}
|
||||||
|
|
||||||
|
SubIncyRoutingRules, err := s.settingService.GetSubIncyRoutingRules()
|
||||||
|
if err != nil {
|
||||||
|
SubIncyRoutingRules = ""
|
||||||
|
}
|
||||||
|
|
||||||
// set per-request localizer from headers/cookies
|
// set per-request localizer from headers/cookies
|
||||||
engine.Use(locale.LocalizerMiddleware())
|
engine.Use(locale.LocalizerMiddleware())
|
||||||
|
|
||||||
@@ -232,7 +242,8 @@ func (s *Server) initRouter() (*gin.Engine, error) {
|
|||||||
s.sub = NewSUBController(
|
s.sub = NewSUBController(
|
||||||
g, LinksPath, JsonPath, ClashPath, subJsonEnable, subClashEnable, Encrypt, RemarkTemplate, SubUpdates,
|
g, LinksPath, JsonPath, ClashPath, subJsonEnable, subClashEnable, Encrypt, RemarkTemplate, SubUpdates,
|
||||||
SubJsonMux, SubJsonRules, SubJsonFinalMask, SubClashEnableRouting, SubClashRules, SubTitle, SubSupportUrl,
|
SubJsonMux, SubJsonRules, SubJsonFinalMask, SubClashEnableRouting, SubClashRules, SubTitle, SubSupportUrl,
|
||||||
SubProfileUrl, SubAnnounce, SubEnableRouting, SubRoutingRules, SubHideSettings)
|
SubProfileUrl, SubAnnounce, SubEnableRouting, SubRoutingRules, SubHideSettings,
|
||||||
|
SubIncyEnableRouting, SubIncyRoutingRules)
|
||||||
|
|
||||||
return engine, nil
|
return engine, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,271 @@
|
|||||||
|
package tunnelmonitor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||||
|
"github.com/mhsanaei/3x-ui/v3/internal/util/netproxy"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
defaultHealthURL = "https://www.cloudflare.com/cdn-cgi/trace"
|
||||||
|
defaultInterval = 30 * time.Second
|
||||||
|
defaultTimeout = 10 * time.Second
|
||||||
|
defaultFailureThreshold = 3
|
||||||
|
defaultCooldown = 5 * time.Minute
|
||||||
|
)
|
||||||
|
|
||||||
|
// Config controls the optional tunnel health monitor.
|
||||||
|
type Config struct {
|
||||||
|
Enabled bool
|
||||||
|
URL string
|
||||||
|
ProxyURL string
|
||||||
|
Interval time.Duration
|
||||||
|
Timeout time.Duration
|
||||||
|
FailureThreshold int
|
||||||
|
Cooldown time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
// RecoveryFunc performs recovery after the monitor reaches the configured
|
||||||
|
// failure threshold. The panel wires this to an Xray core restart.
|
||||||
|
type RecoveryFunc func(context.Context) error
|
||||||
|
|
||||||
|
// Monitor periodically probes a URL and triggers recovery after repeated
|
||||||
|
// failures. It is intentionally independent from panel settings/UI so it can be
|
||||||
|
// enabled safely through service environment variables first.
|
||||||
|
type Monitor struct {
|
||||||
|
cfg Config
|
||||||
|
client *http.Client
|
||||||
|
recover RecoveryFunc
|
||||||
|
failures int
|
||||||
|
lastRecovery time.Time
|
||||||
|
now func() time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultConfig returns disabled-by-default monitor settings.
|
||||||
|
func DefaultConfig() Config {
|
||||||
|
return Config{
|
||||||
|
Enabled: false,
|
||||||
|
URL: defaultHealthURL,
|
||||||
|
Interval: defaultInterval,
|
||||||
|
Timeout: defaultTimeout,
|
||||||
|
FailureThreshold: defaultFailureThreshold,
|
||||||
|
Cooldown: defaultCooldown,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConfigFromEnv builds Config from XUI_TUNNEL_HEALTH_* environment variables.
|
||||||
|
//
|
||||||
|
// Supported variables:
|
||||||
|
// - XUI_TUNNEL_HEALTH_MONITOR=true
|
||||||
|
// - XUI_TUNNEL_HEALTH_URL=https://www.cloudflare.com/cdn-cgi/trace
|
||||||
|
// - XUI_TUNNEL_HEALTH_PROXY=socks5://127.0.0.1:1080
|
||||||
|
// - XUI_TUNNEL_HEALTH_INTERVAL=30s
|
||||||
|
// - XUI_TUNNEL_HEALTH_TIMEOUT=10s
|
||||||
|
// - XUI_TUNNEL_HEALTH_FAILURES=3
|
||||||
|
// - XUI_TUNNEL_HEALTH_COOLDOWN=5m
|
||||||
|
func ConfigFromEnv() Config {
|
||||||
|
cfg := DefaultConfig()
|
||||||
|
|
||||||
|
cfg.Enabled = parseBool(os.Getenv("XUI_TUNNEL_HEALTH_MONITOR"))
|
||||||
|
cfg.URL = firstNonEmpty(os.Getenv("XUI_TUNNEL_HEALTH_URL"), cfg.URL)
|
||||||
|
cfg.ProxyURL = strings.TrimSpace(os.Getenv("XUI_TUNNEL_HEALTH_PROXY"))
|
||||||
|
cfg.Interval = parseDurationEnv("XUI_TUNNEL_HEALTH_INTERVAL", cfg.Interval)
|
||||||
|
cfg.Timeout = parseDurationEnv("XUI_TUNNEL_HEALTH_TIMEOUT", cfg.Timeout)
|
||||||
|
cfg.Cooldown = parseDurationEnv("XUI_TUNNEL_HEALTH_COOLDOWN", cfg.Cooldown)
|
||||||
|
cfg.FailureThreshold = parseIntEnv("XUI_TUNNEL_HEALTH_FAILURES", cfg.FailureThreshold)
|
||||||
|
|
||||||
|
return cfg.Normalize()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normalize applies safe bounds and defaults.
|
||||||
|
func (c Config) Normalize() Config {
|
||||||
|
if strings.TrimSpace(c.URL) == "" {
|
||||||
|
c.URL = defaultHealthURL
|
||||||
|
}
|
||||||
|
c.URL = strings.TrimSpace(c.URL)
|
||||||
|
c.ProxyURL = strings.TrimSpace(c.ProxyURL)
|
||||||
|
|
||||||
|
if c.Interval < time.Second {
|
||||||
|
c.Interval = defaultInterval
|
||||||
|
}
|
||||||
|
if c.Timeout < time.Second {
|
||||||
|
c.Timeout = defaultTimeout
|
||||||
|
}
|
||||||
|
if c.FailureThreshold < 1 {
|
||||||
|
c.FailureThreshold = defaultFailureThreshold
|
||||||
|
}
|
||||||
|
if c.Cooldown < time.Second {
|
||||||
|
c.Cooldown = defaultCooldown
|
||||||
|
}
|
||||||
|
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
// New creates a monitor with an HTTP client based on cfg.
|
||||||
|
func New(cfg Config, recover RecoveryFunc) (*Monitor, error) {
|
||||||
|
cfg = cfg.Normalize()
|
||||||
|
|
||||||
|
client, err := netproxy.NewHTTPClient(cfg.ProxyURL, cfg.Timeout)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return newWithClient(cfg, client, recover), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func newWithClient(cfg Config, client *http.Client, recover RecoveryFunc) *Monitor {
|
||||||
|
cfg = cfg.Normalize()
|
||||||
|
if client == nil {
|
||||||
|
client = &http.Client{Timeout: cfg.Timeout}
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Monitor{
|
||||||
|
cfg: cfg,
|
||||||
|
client: client,
|
||||||
|
recover: recover,
|
||||||
|
now: time.Now,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run starts the monitor loop until ctx is cancelled.
|
||||||
|
func (m *Monitor) Run(ctx context.Context) {
|
||||||
|
if m == nil || !m.cfg.Enabled {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Info("Tunnel health monitor enabled: ", m.cfg.URL)
|
||||||
|
|
||||||
|
ticker := time.NewTicker(m.cfg.Interval)
|
||||||
|
defer ticker.Stop()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
logger.Info("Tunnel health monitor stopped")
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
recovered, err := m.Step(ctx)
|
||||||
|
if err != nil {
|
||||||
|
logger.Warning("Tunnel health monitor check failed: ", err)
|
||||||
|
}
|
||||||
|
if recovered {
|
||||||
|
logger.Warning("Tunnel health monitor triggered Xray restart")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step performs one probe and maybe triggers recovery.
|
||||||
|
func (m *Monitor) Step(ctx context.Context) (bool, error) {
|
||||||
|
if m == nil {
|
||||||
|
return false, errors.New("nil monitor")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := m.probe(ctx); err != nil {
|
||||||
|
m.failures++
|
||||||
|
|
||||||
|
if m.failures < m.cfg.FailureThreshold {
|
||||||
|
return false, fmt.Errorf("probe failed %d/%d: %w", m.failures, m.cfg.FailureThreshold, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
now := m.now()
|
||||||
|
if !m.lastRecovery.IsZero() && now.Sub(m.lastRecovery) < m.cfg.Cooldown {
|
||||||
|
m.failures = m.cfg.FailureThreshold
|
||||||
|
return false, fmt.Errorf("probe failed %d/%d; recovery cooldown active: %w", m.failures, m.cfg.FailureThreshold, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if m.recover == nil {
|
||||||
|
m.failures = m.cfg.FailureThreshold
|
||||||
|
return false, errors.New("recovery function is not configured")
|
||||||
|
}
|
||||||
|
|
||||||
|
if recErr := m.recover(ctx); recErr != nil {
|
||||||
|
return false, fmt.Errorf("recovery failed after probe error %v: %w", err, recErr)
|
||||||
|
}
|
||||||
|
|
||||||
|
m.lastRecovery = now
|
||||||
|
m.failures = 0
|
||||||
|
return true, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if m.failures > 0 {
|
||||||
|
logger.Info("Tunnel health monitor recovered after successful probe")
|
||||||
|
}
|
||||||
|
m.failures = 0
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Monitor) probe(ctx context.Context) error {
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, m.cfg.URL, nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := m.client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
|
||||||
|
|
||||||
|
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusBadRequest {
|
||||||
|
return fmt.Errorf("unexpected HTTP status %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseBool(value string) bool {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(value)) {
|
||||||
|
case "1", "true", "yes", "y", "on", "enable", "enabled":
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseDurationEnv(name string, fallback time.Duration) time.Duration {
|
||||||
|
value := strings.TrimSpace(os.Getenv(name))
|
||||||
|
if value == "" {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
d, err := time.ParseDuration(value)
|
||||||
|
if err != nil {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
return d
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseIntEnv(name string, fallback int) int {
|
||||||
|
value := strings.TrimSpace(os.Getenv(name))
|
||||||
|
if value == "" {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
n, err := strconv.Atoi(value)
|
||||||
|
if err != nil {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
func firstNonEmpty(value string, fallback string) string {
|
||||||
|
value = strings.TrimSpace(value)
|
||||||
|
if value == "" {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
}
|
||||||
@@ -0,0 +1,454 @@
|
|||||||
|
package tunnelmonitor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||||
|
"github.com/op/go-logging"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMain(m *testing.M) {
|
||||||
|
logger.InitLogger(logging.ERROR)
|
||||||
|
m.Run()
|
||||||
|
}
|
||||||
|
|
||||||
|
type roundTripFunc func(*http.Request) (*http.Response, error)
|
||||||
|
|
||||||
|
func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||||
|
return f(req)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMonitorRestartsAfterFailureThreshold(t *testing.T) {
|
||||||
|
cfg := Config{
|
||||||
|
Enabled: true,
|
||||||
|
URL: "http://example.test",
|
||||||
|
Interval: time.Minute,
|
||||||
|
Timeout: time.Second,
|
||||||
|
FailureThreshold: 2,
|
||||||
|
Cooldown: time.Minute,
|
||||||
|
}
|
||||||
|
|
||||||
|
client := &http.Client{
|
||||||
|
Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||||
|
return nil, errors.New("tunnel down")
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
|
||||||
|
restarts := 0
|
||||||
|
monitor := newWithClient(cfg, client, func(ctx context.Context) error {
|
||||||
|
restarts++
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
monitor.now = func() time.Time {
|
||||||
|
return time.Unix(100, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
if recovered, _ := monitor.Step(context.Background()); recovered {
|
||||||
|
t.Fatal("first failure must not trigger recovery")
|
||||||
|
}
|
||||||
|
|
||||||
|
if recovered, _ := monitor.Step(context.Background()); !recovered {
|
||||||
|
t.Fatal("second consecutive failure should trigger recovery")
|
||||||
|
}
|
||||||
|
|
||||||
|
if restarts != 1 {
|
||||||
|
t.Fatalf("expected 1 recovery, got %d", restarts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMonitorRespectsRecoveryCooldown(t *testing.T) {
|
||||||
|
cfg := Config{
|
||||||
|
Enabled: true,
|
||||||
|
URL: "http://example.test",
|
||||||
|
Interval: time.Minute,
|
||||||
|
Timeout: time.Second,
|
||||||
|
FailureThreshold: 1,
|
||||||
|
Cooldown: time.Minute,
|
||||||
|
}
|
||||||
|
|
||||||
|
client := &http.Client{
|
||||||
|
Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||||
|
return nil, errors.New("tunnel down")
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Unix(100, 0)
|
||||||
|
restarts := 0
|
||||||
|
|
||||||
|
monitor := newWithClient(cfg, client, func(ctx context.Context) error {
|
||||||
|
restarts++
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
monitor.now = func() time.Time {
|
||||||
|
return now
|
||||||
|
}
|
||||||
|
|
||||||
|
recovered, _ := monitor.Step(context.Background())
|
||||||
|
if !recovered {
|
||||||
|
t.Fatal("first failure should trigger recovery when threshold is 1")
|
||||||
|
}
|
||||||
|
|
||||||
|
recovered, _ = monitor.Step(context.Background())
|
||||||
|
if recovered {
|
||||||
|
t.Fatal("cooldown should suppress immediate second recovery")
|
||||||
|
}
|
||||||
|
|
||||||
|
if restarts != 1 {
|
||||||
|
t.Fatalf("expected 1 recovery during cooldown, got %d", restarts)
|
||||||
|
}
|
||||||
|
|
||||||
|
now = now.Add(time.Minute + time.Second)
|
||||||
|
|
||||||
|
recovered, _ = monitor.Step(context.Background())
|
||||||
|
if !recovered {
|
||||||
|
t.Fatal("recovery should be allowed after cooldown")
|
||||||
|
}
|
||||||
|
|
||||||
|
if restarts != 2 {
|
||||||
|
t.Fatalf("expected 2 recoveries after cooldown, got %d", restarts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMonitorSuccessResetsFailures(t *testing.T) {
|
||||||
|
cfg := Config{
|
||||||
|
Enabled: true,
|
||||||
|
URL: "http://example.test",
|
||||||
|
Interval: time.Minute,
|
||||||
|
Timeout: time.Second,
|
||||||
|
FailureThreshold: 2,
|
||||||
|
Cooldown: time.Minute,
|
||||||
|
}
|
||||||
|
|
||||||
|
fail := true
|
||||||
|
client := &http.Client{
|
||||||
|
Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||||
|
if fail {
|
||||||
|
return nil, errors.New("tunnel down")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &http.Response{
|
||||||
|
StatusCode: http.StatusOK,
|
||||||
|
Body: http.NoBody,
|
||||||
|
}, nil
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
|
||||||
|
restarts := 0
|
||||||
|
monitor := newWithClient(cfg, client, func(ctx context.Context) error {
|
||||||
|
restarts++
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
_, _ = monitor.Step(context.Background())
|
||||||
|
|
||||||
|
fail = false
|
||||||
|
if recovered, err := monitor.Step(context.Background()); recovered || err != nil {
|
||||||
|
t.Fatalf("successful probe should not recover or fail, recovered=%v err=%v", recovered, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fail = true
|
||||||
|
if recovered, _ := monitor.Step(context.Background()); recovered {
|
||||||
|
t.Fatal("failure after success should be counted as first failure again")
|
||||||
|
}
|
||||||
|
|
||||||
|
if restarts != 0 {
|
||||||
|
t.Fatalf("expected no recovery, got %d", restarts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigFromEnvParsesValues(t *testing.T) {
|
||||||
|
t.Setenv("XUI_TUNNEL_HEALTH_MONITOR", "true")
|
||||||
|
t.Setenv("XUI_TUNNEL_HEALTH_URL", "https://example.com/health")
|
||||||
|
t.Setenv("XUI_TUNNEL_HEALTH_PROXY", "socks5://127.0.0.1:1080")
|
||||||
|
t.Setenv("XUI_TUNNEL_HEALTH_INTERVAL", "15s")
|
||||||
|
t.Setenv("XUI_TUNNEL_HEALTH_TIMEOUT", "3s")
|
||||||
|
t.Setenv("XUI_TUNNEL_HEALTH_FAILURES", "4")
|
||||||
|
t.Setenv("XUI_TUNNEL_HEALTH_COOLDOWN", "2m")
|
||||||
|
|
||||||
|
cfg := ConfigFromEnv()
|
||||||
|
|
||||||
|
if !cfg.Enabled {
|
||||||
|
t.Fatal("expected monitor to be enabled")
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.URL != "https://example.com/health" {
|
||||||
|
t.Fatalf("unexpected URL: %s", cfg.URL)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !strings.HasPrefix(cfg.ProxyURL, "socks5://") {
|
||||||
|
t.Fatalf("unexpected proxy URL: %s", cfg.ProxyURL)
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.Interval != 15*time.Second {
|
||||||
|
t.Fatalf("unexpected interval: %s", cfg.Interval)
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.Timeout != 3*time.Second {
|
||||||
|
t.Fatalf("unexpected timeout: %s", cfg.Timeout)
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.FailureThreshold != 4 {
|
||||||
|
t.Fatalf("unexpected threshold: %d", cfg.FailureThreshold)
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.Cooldown != 2*time.Minute {
|
||||||
|
t.Fatalf("unexpected cooldown: %s", cfg.Cooldown)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func failingClient() *http.Client {
|
||||||
|
return &http.Client{
|
||||||
|
Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||||
|
return nil, errors.New("tunnel down")
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func statusClient(code int) *http.Client {
|
||||||
|
return &http.Client{
|
||||||
|
Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||||
|
return &http.Response{StatusCode: code, Body: http.NoBody}, nil
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProbeStatusCodeClassification(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
status int
|
||||||
|
healthy bool
|
||||||
|
}{
|
||||||
|
{199, false},
|
||||||
|
{200, true},
|
||||||
|
{204, true},
|
||||||
|
{301, true},
|
||||||
|
{399, true},
|
||||||
|
{400, false},
|
||||||
|
{404, false},
|
||||||
|
{500, false},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range cases {
|
||||||
|
cfg := Config{
|
||||||
|
Enabled: true,
|
||||||
|
URL: "http://example.test",
|
||||||
|
Interval: time.Minute,
|
||||||
|
Timeout: time.Second,
|
||||||
|
FailureThreshold: 100,
|
||||||
|
Cooldown: time.Minute,
|
||||||
|
}
|
||||||
|
|
||||||
|
monitor := newWithClient(cfg, statusClient(tc.status), func(ctx context.Context) error {
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
recovered, err := monitor.Step(context.Background())
|
||||||
|
if recovered {
|
||||||
|
t.Fatalf("status %d: unexpected recovery", tc.status)
|
||||||
|
}
|
||||||
|
if tc.healthy && err != nil {
|
||||||
|
t.Fatalf("status %d: expected healthy probe, got error %v", tc.status, err)
|
||||||
|
}
|
||||||
|
if !tc.healthy && err == nil {
|
||||||
|
t.Fatalf("status %d: expected failure, got nil error", tc.status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeClampsBounds(t *testing.T) {
|
||||||
|
got := Config{
|
||||||
|
URL: " ",
|
||||||
|
Interval: 0,
|
||||||
|
Timeout: 500 * time.Millisecond,
|
||||||
|
FailureThreshold: 0,
|
||||||
|
Cooldown: 0,
|
||||||
|
}.Normalize()
|
||||||
|
|
||||||
|
if got.URL != defaultHealthURL {
|
||||||
|
t.Fatalf("URL not defaulted: %q", got.URL)
|
||||||
|
}
|
||||||
|
if got.Interval != defaultInterval {
|
||||||
|
t.Fatalf("Interval not clamped: %s", got.Interval)
|
||||||
|
}
|
||||||
|
if got.Timeout != defaultTimeout {
|
||||||
|
t.Fatalf("Timeout not clamped: %s", got.Timeout)
|
||||||
|
}
|
||||||
|
if got.FailureThreshold != defaultFailureThreshold {
|
||||||
|
t.Fatalf("FailureThreshold not clamped: %d", got.FailureThreshold)
|
||||||
|
}
|
||||||
|
if got.Cooldown != defaultCooldown {
|
||||||
|
t.Fatalf("Cooldown not clamped: %s", got.Cooldown)
|
||||||
|
}
|
||||||
|
|
||||||
|
valid := Config{
|
||||||
|
URL: "https://example.com/health",
|
||||||
|
Interval: 15 * time.Second,
|
||||||
|
Timeout: 3 * time.Second,
|
||||||
|
FailureThreshold: 5,
|
||||||
|
Cooldown: 2 * time.Minute,
|
||||||
|
}.Normalize()
|
||||||
|
|
||||||
|
if valid.URL != "https://example.com/health" ||
|
||||||
|
valid.Interval != 15*time.Second ||
|
||||||
|
valid.Timeout != 3*time.Second ||
|
||||||
|
valid.FailureThreshold != 5 ||
|
||||||
|
valid.Cooldown != 2*time.Minute {
|
||||||
|
t.Fatalf("valid config was mutated: %+v", valid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewRejectsUnsupportedProxyScheme(t *testing.T) {
|
||||||
|
m, err := New(Config{ProxyURL: "ftp://127.0.0.1:21"}, func(ctx context.Context) error {
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err == nil || m != nil {
|
||||||
|
t.Fatalf("expected error and nil monitor for bad scheme, got m=%v err=%v", m, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
m, err = New(Config{}, func(ctx context.Context) error {
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil || m == nil {
|
||||||
|
t.Fatalf("expected a valid monitor for empty proxy, got m=%v err=%v", m, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMonitorRecoveryErrorDoesNotArmCooldown(t *testing.T) {
|
||||||
|
cfg := Config{
|
||||||
|
Enabled: true,
|
||||||
|
URL: "http://example.test",
|
||||||
|
Interval: time.Minute,
|
||||||
|
Timeout: time.Second,
|
||||||
|
FailureThreshold: 1,
|
||||||
|
Cooldown: time.Minute,
|
||||||
|
}
|
||||||
|
|
||||||
|
attempts := 0
|
||||||
|
monitor := newWithClient(cfg, failingClient(), func(ctx context.Context) error {
|
||||||
|
attempts++
|
||||||
|
return errors.New("restart failed")
|
||||||
|
})
|
||||||
|
monitor.now = func() time.Time {
|
||||||
|
return time.Unix(100, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
recovered, err := monitor.Step(context.Background())
|
||||||
|
if recovered || err == nil {
|
||||||
|
t.Fatalf("failed recovery must report recovered=false with an error, got recovered=%v err=%v", recovered, err)
|
||||||
|
}
|
||||||
|
if !monitor.lastRecovery.IsZero() {
|
||||||
|
t.Fatal("a failed recovery must not arm the cooldown")
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := monitor.Step(context.Background()); err == nil {
|
||||||
|
t.Fatal("expected error on the second failing step")
|
||||||
|
}
|
||||||
|
if attempts != 2 {
|
||||||
|
t.Fatalf("recovery should be retried (no cooldown) after a failure, attempts=%d", attempts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMonitorNilRecoverStaysBounded(t *testing.T) {
|
||||||
|
cfg := Config{
|
||||||
|
Enabled: true,
|
||||||
|
URL: "http://example.test",
|
||||||
|
Interval: time.Minute,
|
||||||
|
Timeout: time.Second,
|
||||||
|
FailureThreshold: 2,
|
||||||
|
Cooldown: time.Minute,
|
||||||
|
}
|
||||||
|
|
||||||
|
monitor := newWithClient(cfg, failingClient(), nil)
|
||||||
|
|
||||||
|
for i := 0; i < 5; i++ {
|
||||||
|
recovered, _ := monitor.Step(context.Background())
|
||||||
|
if recovered {
|
||||||
|
t.Fatal("a nil recovery func must never report recovery")
|
||||||
|
}
|
||||||
|
if monitor.failures > cfg.FailureThreshold {
|
||||||
|
t.Fatalf("failures must stay capped at threshold %d, got %d", cfg.FailureThreshold, monitor.failures)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMonitorFailuresCappedDuringCooldown(t *testing.T) {
|
||||||
|
cfg := Config{
|
||||||
|
Enabled: true,
|
||||||
|
URL: "http://example.test",
|
||||||
|
Interval: time.Minute,
|
||||||
|
Timeout: time.Second,
|
||||||
|
FailureThreshold: 2,
|
||||||
|
Cooldown: time.Minute,
|
||||||
|
}
|
||||||
|
|
||||||
|
restarts := 0
|
||||||
|
monitor := newWithClient(cfg, failingClient(), func(ctx context.Context) error {
|
||||||
|
restarts++
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
monitor.now = func() time.Time {
|
||||||
|
return time.Unix(100, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
monitor.Step(context.Background())
|
||||||
|
if recovered, _ := monitor.Step(context.Background()); !recovered {
|
||||||
|
t.Fatal("expected recovery once the threshold is reached")
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 0; i < 6; i++ {
|
||||||
|
monitor.Step(context.Background())
|
||||||
|
if monitor.failures > cfg.FailureThreshold {
|
||||||
|
t.Fatalf("failures must never exceed threshold %d during cooldown, got %d", cfg.FailureThreshold, monitor.failures)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if restarts != 1 {
|
||||||
|
t.Fatalf("cooldown should suppress further recoveries, restarts=%d", restarts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMonitorRunStopsOnContextCancel(t *testing.T) {
|
||||||
|
cfg := Config{
|
||||||
|
Enabled: true,
|
||||||
|
URL: "http://example.test",
|
||||||
|
Timeout: time.Second,
|
||||||
|
FailureThreshold: 1,
|
||||||
|
Cooldown: time.Hour,
|
||||||
|
}
|
||||||
|
|
||||||
|
recovered := make(chan struct{})
|
||||||
|
var once sync.Once
|
||||||
|
monitor := newWithClient(cfg, failingClient(), func(ctx context.Context) error {
|
||||||
|
once.Do(func() { close(recovered) })
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
monitor.cfg.Interval = 5 * time.Millisecond
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
monitor.Run(ctx)
|
||||||
|
close(done)
|
||||||
|
}()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-recovered:
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
cancel()
|
||||||
|
t.Fatal("Run did not trigger recovery within the deadline")
|
||||||
|
}
|
||||||
|
|
||||||
|
cancel()
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("Run did not return after context cancellation")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -248,6 +248,7 @@ type bulkAdjustRequest struct {
|
|||||||
Emails []string `json:"emails"`
|
Emails []string `json:"emails"`
|
||||||
AddDays int `json:"addDays"`
|
AddDays int `json:"addDays"`
|
||||||
AddBytes int64 `json:"addBytes"`
|
AddBytes int64 `json:"addBytes"`
|
||||||
|
Flow string `json:"flow"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *ClientController) bulkAdjust(c *gin.Context) {
|
func (a *ClientController) bulkAdjust(c *gin.Context) {
|
||||||
@@ -256,7 +257,7 @@ func (a *ClientController) bulkAdjust(c *gin.Context) {
|
|||||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
result, needRestart, err := a.clientService.BulkAdjust(&a.inboundService, req.Emails, req.AddDays, req.AddBytes)
|
result, needRestart, err := a.clientService.BulkAdjust(&a.inboundService, req.Emails, req.AddDays, req.AddBytes, req.Flow)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -2,9 +2,9 @@ package controller
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"embed"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
htmlpkg "html"
|
htmlpkg "html"
|
||||||
|
"io/fs"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -16,10 +16,10 @@ import (
|
|||||||
"github.com/mhsanaei/3x-ui/v3/internal/web/session"
|
"github.com/mhsanaei/3x-ui/v3/internal/web/session"
|
||||||
)
|
)
|
||||||
|
|
||||||
var distFS embed.FS
|
var distFS fs.FS
|
||||||
|
|
||||||
func SetDistFS(fs embed.FS) {
|
func SetDistFS(fsys fs.FS) {
|
||||||
distFS = fs
|
distFS = fsys
|
||||||
}
|
}
|
||||||
|
|
||||||
var distPageBuildTime = time.Now()
|
var distPageBuildTime = time.Now()
|
||||||
@@ -30,7 +30,7 @@ var distPageBuildTime = time.Now()
|
|||||||
// produced at frontend build time by scripts/build-openapi.mjs and
|
// produced at frontend build time by scripts/build-openapi.mjs and
|
||||||
// embedded into the binary via the dist FS.
|
// embedded into the binary via the dist FS.
|
||||||
func ServeOpenAPISpec(c *gin.Context) {
|
func ServeOpenAPISpec(c *gin.Context) {
|
||||||
body, err := distFS.ReadFile("dist/openapi.json")
|
body, err := fs.ReadFile(distFS, "dist/openapi.json")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusNotFound, gin.H{"success": false, "msg": "openapi.json not found"})
|
c.JSON(http.StatusNotFound, gin.H{"success": false, "msg": "openapi.json not found"})
|
||||||
return
|
return
|
||||||
@@ -72,7 +72,7 @@ func withServerBasePath(spec []byte, basePath string) ([]byte, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func serveDistPage(c *gin.Context, name string) {
|
func serveDistPage(c *gin.Context, name string) {
|
||||||
body, err := distFS.ReadFile("dist/" + name)
|
body, err := fs.ReadFile(distFS, "dist/"+name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.String(http.StatusInternalServerError, "missing embedded page: %s", name)
|
c.String(http.StatusInternalServerError, "missing embedded page: %s", name)
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -318,6 +318,7 @@ func (a *NodeController) probe(c *gin.Context) {
|
|||||||
func (a *NodeController) updatePanel(c *gin.Context) {
|
func (a *NodeController) updatePanel(c *gin.Context) {
|
||||||
var req struct {
|
var req struct {
|
||||||
Ids []int `json:"ids"`
|
Ids []int `json:"ids"`
|
||||||
|
Dev bool `json:"dev"`
|
||||||
}
|
}
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||||
@@ -327,7 +328,7 @@ func (a *NodeController) updatePanel(c *gin.Context) {
|
|||||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), fmt.Errorf("no nodes selected"))
|
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), fmt.Errorf("no nodes selected"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
results, err := a.nodeService.UpdatePanels(req.Ids)
|
results, err := a.nodeService.UpdatePanels(req.Ids, req.Dev)
|
||||||
jsonMsgObj(c, I18nWeb(c, "pages.nodes.toasts.updateStarted"), results, err)
|
jsonMsgObj(c, I18nWeb(c, "pages.nodes.toasts.updateStarted"), results, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -69,6 +69,7 @@ func (a *ServerController) initRouter(g *gin.RouterGroup) {
|
|||||||
g.POST("/restartXrayService", a.restartXrayService)
|
g.POST("/restartXrayService", a.restartXrayService)
|
||||||
g.POST("/installXray/:version", a.installXray)
|
g.POST("/installXray/:version", a.installXray)
|
||||||
g.POST("/updatePanel", a.updatePanel)
|
g.POST("/updatePanel", a.updatePanel)
|
||||||
|
g.POST("/setUpdateChannel", a.setUpdateChannel)
|
||||||
g.POST("/updateGeofile", a.updateGeofile)
|
g.POST("/updateGeofile", a.updateGeofile)
|
||||||
g.POST("/updateGeofile/:fileName", a.updateGeofile)
|
g.POST("/updateGeofile/:fileName", a.updateGeofile)
|
||||||
g.POST("/logs/:count", a.getLogs)
|
g.POST("/logs/:count", a.getLogs)
|
||||||
@@ -205,12 +206,36 @@ func (a *ServerController) installXray(c *gin.Context) {
|
|||||||
jsonMsg(c, I18nWeb(c, "pages.index.xraySwitchVersionPopover"), err)
|
jsonMsg(c, I18nWeb(c, "pages.index.xraySwitchVersionPopover"), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// updatePanel starts a panel self-update to the latest release.
|
// updatePanel starts a panel self-update. With no "dev" form value it follows
|
||||||
|
// this panel's own channel setting; an explicit "dev" (sent by the master node
|
||||||
|
// updater) overrides it for this run.
|
||||||
func (a *ServerController) updatePanel(c *gin.Context) {
|
func (a *ServerController) updatePanel(c *gin.Context) {
|
||||||
err := a.panelService.StartUpdate()
|
devParam := c.PostForm("dev")
|
||||||
|
var err error
|
||||||
|
if devParam == "" {
|
||||||
|
err = a.panelService.StartUpdate()
|
||||||
|
} else {
|
||||||
|
dev, perr := strconv.ParseBool(devParam)
|
||||||
|
if perr != nil {
|
||||||
|
jsonMsg(c, "invalid data", perr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err = a.panelService.StartUpdateChannel(dev)
|
||||||
|
}
|
||||||
jsonMsg(c, I18nWeb(c, "pages.index.panelUpdateStartedPopover"), err)
|
jsonMsg(c, I18nWeb(c, "pages.index.panelUpdateStartedPopover"), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// setUpdateChannel toggles whether self-update tracks the rolling dev release.
|
||||||
|
func (a *ServerController) setUpdateChannel(c *gin.Context) {
|
||||||
|
dev, err := strconv.ParseBool(c.PostForm("dev"))
|
||||||
|
if err != nil {
|
||||||
|
jsonMsg(c, "invalid data", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err = a.settingService.SetDevChannelEnable(dev)
|
||||||
|
jsonMsg(c, I18nWeb(c, "pages.index.updateChannelChanged"), err)
|
||||||
|
}
|
||||||
|
|
||||||
// updateGeofile updates the specified geo file for Xray.
|
// updateGeofile updates the specified geo file for Xray.
|
||||||
func (a *ServerController) updateGeofile(c *gin.Context) {
|
func (a *ServerController) updateGeofile(c *gin.Context) {
|
||||||
fileName := c.Param("fileName")
|
fileName := c.Param("fileName")
|
||||||
|
|||||||
@@ -88,6 +88,10 @@ func (a *SettingController) updateSetting(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
oldTwoFactor, twoFactorErr := a.settingService.GetTwoFactorEnable()
|
oldTwoFactor, twoFactorErr := a.settingService.GetTwoFactorEnable()
|
||||||
oldPanelOutbound, _ := a.settingService.GetPanelOutbound()
|
oldPanelOutbound, _ := a.settingService.GetPanelOutbound()
|
||||||
|
oldTgEnable, _ := a.settingService.GetTgbotEnabled()
|
||||||
|
oldTgToken, _ := a.settingService.GetTgBotToken()
|
||||||
|
oldTgChatId, _ := a.settingService.GetTgBotChatId()
|
||||||
|
oldTgAPIServer, _ := a.settingService.GetTgBotAPIServer()
|
||||||
err := a.settingService.UpdateAllSetting(allSetting)
|
err := a.settingService.UpdateAllSetting(allSetting)
|
||||||
if err == nil && twoFactorErr == nil && !oldTwoFactor && allSetting.TwoFactorEnable {
|
if err == nil && twoFactorErr == nil && !oldTwoFactor && allSetting.TwoFactorEnable {
|
||||||
if bumpErr := a.userService.BumpLoginEpoch(); bumpErr != nil {
|
if bumpErr := a.userService.BumpLoginEpoch(); bumpErr != nil {
|
||||||
@@ -102,6 +106,16 @@ func (a *SettingController) updateSetting(c *gin.Context) {
|
|||||||
logger.Warning("apply panel outbound change failed:", applyErr)
|
logger.Warning("apply panel outbound change failed:", applyErr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// UpdateAllSetting already restored a redacted-blank token, so allSetting.TgBotToken is the effective value to compare.
|
||||||
|
if err == nil && reloadTgbotFunc != nil {
|
||||||
|
tgChanged := oldTgEnable != allSetting.TgBotEnable ||
|
||||||
|
(allSetting.TgBotEnable && (oldTgToken != allSetting.TgBotToken ||
|
||||||
|
oldTgChatId != allSetting.TgBotChatId ||
|
||||||
|
oldTgAPIServer != allSetting.TgBotAPIServer))
|
||||||
|
if tgChanged {
|
||||||
|
reloadTgbotFunc()
|
||||||
|
}
|
||||||
|
}
|
||||||
jsonMsg(c, I18nWeb(c, "pages.settings.toasts.modifySettings"), err)
|
jsonMsg(c, I18nWeb(c, "pages.settings.toasts.modifySettings"), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -252,6 +266,11 @@ var testTgFunc func() error
|
|||||||
// SetTestTgFunc registers the function used to test Telegram sending.
|
// SetTestTgFunc registers the function used to test Telegram sending.
|
||||||
func SetTestTgFunc(fn func() error) { testTgFunc = fn }
|
func SetTestTgFunc(fn func() error) { testTgFunc = fn }
|
||||||
|
|
||||||
|
// reloadTgbotFunc is wired from the web layer; importing tgbot here would be a circular dependency.
|
||||||
|
var reloadTgbotFunc func()
|
||||||
|
|
||||||
|
func SetReloadTgbotFunc(fn func()) { reloadTgbotFunc = fn }
|
||||||
|
|
||||||
// emailService is set from web layer.
|
// emailService is set from web layer.
|
||||||
var emailService *email.EmailService
|
var emailService *email.EmailService
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ package controller
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"path"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/mhsanaei/3x-ui/v3/internal/web/entity"
|
"github.com/mhsanaei/3x-ui/v3/internal/web/entity"
|
||||||
"github.com/mhsanaei/3x-ui/v3/internal/web/middleware"
|
"github.com/mhsanaei/3x-ui/v3/internal/web/middleware"
|
||||||
@@ -57,6 +59,85 @@ func (a *XUIController) panelSPA(c *gin.Context) {
|
|||||||
serveDistPage(c, "index.html")
|
serveDistPage(c, "index.html")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// HandleNoRoutePanelSPA serves the React shell for client-side routes that were
|
||||||
|
// not explicitly registered in Gin. It intentionally runs from engine.NoRoute
|
||||||
|
// instead of a /panel/*path wildcard so explicit JSON/API routes keep their
|
||||||
|
// normal routing semantics.
|
||||||
|
func (a *XUIController) HandleNoRoutePanelSPA(c *gin.Context) bool {
|
||||||
|
if !isPanelSPAFallbackRequest(c) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
if !session.IsLogin(c) {
|
||||||
|
if isAjax(c) {
|
||||||
|
pureJsonMsg(c, http.StatusUnauthorized, false, I18nWeb(c, "pages.login.loginAgain"))
|
||||||
|
} else {
|
||||||
|
c.Header("Cache-Control", "no-store")
|
||||||
|
c.Redirect(http.StatusTemporaryRedirect, c.GetString("base_path"))
|
||||||
|
}
|
||||||
|
c.Abort()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
a.panelSPA(c)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func isPanelSPAFallbackRequest(c *gin.Context) bool {
|
||||||
|
if c.Request.Method != http.MethodGet {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if !acceptsHTML(c.GetHeader("Accept")) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
basePath := c.GetString("base_path")
|
||||||
|
if basePath == "" {
|
||||||
|
basePath = "/"
|
||||||
|
}
|
||||||
|
panelPath := strings.TrimRight(basePath, "/") + "/panel"
|
||||||
|
|
||||||
|
reqPath := c.Request.URL.Path
|
||||||
|
if reqPath != panelPath && !strings.HasPrefix(reqPath, panelPath+"/") {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
if reqPath == panelPath+"/csrf-token" || strings.HasPrefix(reqPath, panelPath+"/csrf-token/") {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if reqPath == panelPath+"/api" || strings.HasPrefix(reqPath, panelPath+"/api/") {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if isStaticAssetPath(reqPath) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
var staticAssetExts = map[string]struct{}{
|
||||||
|
".js": {}, ".mjs": {}, ".cjs": {}, ".css": {}, ".map": {}, ".json": {},
|
||||||
|
".png": {}, ".jpg": {}, ".jpeg": {}, ".gif": {}, ".svg": {}, ".ico": {},
|
||||||
|
".webp": {}, ".avif": {}, ".woff": {}, ".woff2": {}, ".ttf": {}, ".eot": {},
|
||||||
|
".otf": {}, ".wasm": {}, ".txt": {}, ".xml": {}, ".webmanifest": {},
|
||||||
|
}
|
||||||
|
|
||||||
|
func isStaticAssetPath(reqPath string) bool {
|
||||||
|
ext := strings.ToLower(path.Ext(reqPath))
|
||||||
|
if ext == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
_, ok := staticAssetExts[ext]
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|
||||||
|
func acceptsHTML(accept string) bool {
|
||||||
|
if accept == "" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
accept = strings.ToLower(accept)
|
||||||
|
return strings.Contains(accept, "text/html") || strings.Contains(accept, "*/*")
|
||||||
|
}
|
||||||
|
|
||||||
// csrfToken returns the session CSRF token to authenticated SPA clients.
|
// csrfToken returns the session CSRF token to authenticated SPA clients.
|
||||||
// The endpoint is GET (a safe method) so it bypasses CSRFMiddleware itself,
|
// The endpoint is GET (a safe method) so it bypasses CSRFMiddleware itself,
|
||||||
// but checkLogin still gates the response — anonymous callers get 401/redirect.
|
// but checkLogin still gates the response — anonymous callers get 401/redirect.
|
||||||
|
|||||||
@@ -0,0 +1,228 @@
|
|||||||
|
package controller
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"testing/fstest"
|
||||||
|
|
||||||
|
"github.com/gin-contrib/sessions"
|
||||||
|
"github.com/gin-contrib/sessions/cookie"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||||
|
"github.com/mhsanaei/3x-ui/v3/internal/web/locale"
|
||||||
|
"github.com/mhsanaei/3x-ui/v3/internal/web/session"
|
||||||
|
)
|
||||||
|
|
||||||
|
func newSPAFallbackTestEngine(t *testing.T) *gin.Engine {
|
||||||
|
return newSPAFallbackTestEngineWithBasePath(t, "/admin-random/")
|
||||||
|
}
|
||||||
|
|
||||||
|
func newSPAFallbackTestEngineWithBasePath(t *testing.T, basePath string) *gin.Engine {
|
||||||
|
t.Helper()
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
|
||||||
|
oldDistFS := distFS
|
||||||
|
SetDistFS(fstest.MapFS{
|
||||||
|
"dist/index.html": {Data: []byte(`<!doctype html><html><head></head><body>spa shell</body></html>`)},
|
||||||
|
})
|
||||||
|
t.Cleanup(func() { SetDistFS(oldDistFS) })
|
||||||
|
|
||||||
|
engine := gin.New()
|
||||||
|
engine.Use(sessions.Sessions("3x-ui", cookie.NewStore([]byte("spa-fallback-test-secret"))))
|
||||||
|
engine.Use(func(c *gin.Context) {
|
||||||
|
c.Set("base_path", basePath)
|
||||||
|
c.Set("I18n", func(_ locale.I18nType, key string, _ ...string) string { return key })
|
||||||
|
if c.GetHeader("X-Test-Login") == "1" {
|
||||||
|
session.SetAPIAuthUser(c, &model.User{Id: 1, Username: "test"})
|
||||||
|
}
|
||||||
|
c.Next()
|
||||||
|
})
|
||||||
|
|
||||||
|
ctrl := NewXUIController(engine.Group(basePath))
|
||||||
|
engine.NoRoute(func(c *gin.Context) {
|
||||||
|
if ctrl.HandleNoRoutePanelSPA(c) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.AbortWithStatus(http.StatusNotFound)
|
||||||
|
})
|
||||||
|
return engine
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPanelSPAFallbackServesRootBasePath(t *testing.T) {
|
||||||
|
engine := newSPAFallbackTestEngineWithBasePath(t, "/")
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/panel/hosts", nil)
|
||||||
|
req.Header.Set("Accept", "text/html")
|
||||||
|
req.Header.Set("X-Test-Login", "1")
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
engine.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
if !strings.Contains(w.Body.String(), "spa shell") {
|
||||||
|
t.Fatalf("body does not contain SPA shell: %s", w.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPanelSPAFallbackServesAuthenticatedClientRoutes(t *testing.T) {
|
||||||
|
engine := newSPAFallbackTestEngine(t)
|
||||||
|
|
||||||
|
for _, target := range []string{
|
||||||
|
"/admin-random/panel/hosts",
|
||||||
|
"/admin-random/panel/some/future/route",
|
||||||
|
} {
|
||||||
|
t.Run(target, func(t *testing.T) {
|
||||||
|
req := httptest.NewRequest(http.MethodGet, target, nil)
|
||||||
|
req.Header.Set("Accept", "text/html")
|
||||||
|
req.Header.Set("X-Test-Login", "1")
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
engine.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
if ct := w.Header().Get("Content-Type"); !strings.Contains(ct, "text/html") {
|
||||||
|
t.Fatalf("Content-Type = %q, want text/html", ct)
|
||||||
|
}
|
||||||
|
if !strings.Contains(w.Body.String(), "spa shell") {
|
||||||
|
t.Fatalf("body does not contain SPA shell: %s", w.Body.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPanelSPAFallbackPreservesAuthSemantics(t *testing.T) {
|
||||||
|
engine := newSPAFallbackTestEngine(t)
|
||||||
|
|
||||||
|
t.Run("browser redirects to login", func(t *testing.T) {
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/admin-random/panel/hosts", nil)
|
||||||
|
req.Header.Set("Accept", "text/html")
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
engine.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusTemporaryRedirect {
|
||||||
|
t.Fatalf("status = %d, want 307", w.Code)
|
||||||
|
}
|
||||||
|
if loc := w.Header().Get("Location"); loc != "/admin-random/" {
|
||||||
|
t.Fatalf("Location = %q, want /admin-random/", loc)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("ajax gets json unauthorized", func(t *testing.T) {
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/admin-random/panel/hosts", nil)
|
||||||
|
req.Header.Set("Accept", "text/html")
|
||||||
|
req.Header.Set("X-Requested-With", "XMLHttpRequest")
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
engine.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("status = %d, want 401", w.Code)
|
||||||
|
}
|
||||||
|
if ct := w.Header().Get("Content-Type"); !strings.Contains(ct, "application/json") {
|
||||||
|
t.Fatalf("Content-Type = %q, want application/json", ct)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPanelSPAFallbackExclusions(t *testing.T) {
|
||||||
|
engine := newSPAFallbackTestEngine(t)
|
||||||
|
|
||||||
|
for _, tc := range []struct {
|
||||||
|
target string
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
{target: "/admin-random/panel/api", want: http.StatusNotFound},
|
||||||
|
{target: "/admin-random/panel/api/unknown", want: http.StatusNotFound},
|
||||||
|
{target: "/admin-random/panel/csrf-token/", want: http.StatusMovedPermanently},
|
||||||
|
{target: "/admin-random/panel/missing.js", want: http.StatusNotFound},
|
||||||
|
} {
|
||||||
|
t.Run(tc.target, func(t *testing.T) {
|
||||||
|
req := httptest.NewRequest(http.MethodGet, tc.target, nil)
|
||||||
|
req.Header.Set("Accept", "text/html")
|
||||||
|
req.Header.Set("X-Test-Login", "1")
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
engine.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
if w.Code != tc.want {
|
||||||
|
t.Fatalf("status = %d, want %d; body=%s", w.Code, tc.want, w.Body.String())
|
||||||
|
}
|
||||||
|
if strings.Contains(w.Body.String(), "spa shell") {
|
||||||
|
t.Fatalf("excluded route was served by SPA fallback: %s", w.Body.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPanelCSRFTokenRemainsExplicit(t *testing.T) {
|
||||||
|
engine := newSPAFallbackTestEngine(t)
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/admin-random/panel/csrf-token", nil)
|
||||||
|
req.Header.Set("Accept", "text/html")
|
||||||
|
req.Header.Set("X-Test-Login", "1")
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
engine.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
if ct := w.Header().Get("Content-Type"); !strings.Contains(ct, "application/json") {
|
||||||
|
t.Fatalf("Content-Type = %q, want application/json", ct)
|
||||||
|
}
|
||||||
|
if strings.Contains(w.Body.String(), "spa shell") {
|
||||||
|
t.Fatalf("csrf-token was served by SPA fallback: %s", w.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPanelSPAFallbackPredicate(t *testing.T) {
|
||||||
|
oldDistFS := distFS
|
||||||
|
SetDistFS(fstest.MapFS{})
|
||||||
|
t.Cleanup(func() { SetDistFS(oldDistFS) })
|
||||||
|
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
method string
|
||||||
|
path string
|
||||||
|
accept string
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{name: "panel root", method: http.MethodGet, path: "/admin-random/panel", accept: "text/html", want: true},
|
||||||
|
{name: "panel descendant", method: http.MethodGet, path: "/admin-random/panel/hosts", accept: "*/*", want: true},
|
||||||
|
{name: "empty accept", method: http.MethodGet, path: "/admin-random/panel/future", want: true},
|
||||||
|
{name: "post excluded", method: http.MethodPost, path: "/admin-random/panel/hosts", accept: "text/html"},
|
||||||
|
{name: "json accept excluded", method: http.MethodGet, path: "/admin-random/panel/hosts", accept: "application/json"},
|
||||||
|
{name: "api root excluded", method: http.MethodGet, path: "/admin-random/panel/api", accept: "text/html"},
|
||||||
|
{name: "api descendant excluded", method: http.MethodGet, path: "/admin-random/panel/api/unknown", accept: "text/html"},
|
||||||
|
{name: "csrf excluded", method: http.MethodGet, path: "/admin-random/panel/csrf-token", accept: "text/html"},
|
||||||
|
{name: "csrf descendant excluded", method: http.MethodGet, path: "/admin-random/panel/csrf-token/", accept: "text/html"},
|
||||||
|
{name: "file excluded", method: http.MethodGet, path: "/admin-random/panel/missing.css", accept: "text/html"},
|
||||||
|
{name: "outside panel excluded", method: http.MethodGet, path: "/admin-random/hosts", accept: "text/html"},
|
||||||
|
{name: "dotted email route param served", method: http.MethodGet, path: "/admin-random/panel/clients/user@example.com", accept: "text/html", want: true},
|
||||||
|
{name: "dotted version route param served", method: http.MethodGet, path: "/admin-random/panel/sub/1.2.3", accept: "text/html", want: true},
|
||||||
|
{name: "uppercase asset extension excluded", method: http.MethodGet, path: "/admin-random/panel/app.JS", accept: "text/html"},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||||
|
c.Set("base_path", "/admin-random/")
|
||||||
|
req := httptest.NewRequest(tc.method, tc.path, nil)
|
||||||
|
if tc.accept != "" {
|
||||||
|
req.Header.Set("Accept", tc.accept)
|
||||||
|
}
|
||||||
|
c.Request = req
|
||||||
|
|
||||||
|
if got := isPanelSPAFallbackRequest(c); got != tc.want {
|
||||||
|
t.Fatalf("isPanelSPAFallbackRequest() = %v, want %v", got, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -77,6 +77,8 @@ type AllSetting struct {
|
|||||||
SubAnnounce string `json:"subAnnounce" form:"subAnnounce"` // Subscription announce
|
SubAnnounce string `json:"subAnnounce" form:"subAnnounce"` // Subscription announce
|
||||||
SubEnableRouting bool `json:"subEnableRouting" form:"subEnableRouting"` // Enable routing for subscription
|
SubEnableRouting bool `json:"subEnableRouting" form:"subEnableRouting"` // Enable routing for subscription
|
||||||
SubRoutingRules string `json:"subRoutingRules" form:"subRoutingRules"` // Subscription global routing rules (Only for Happ)
|
SubRoutingRules string `json:"subRoutingRules" form:"subRoutingRules"` // Subscription global routing rules (Only for Happ)
|
||||||
|
SubIncyEnableRouting bool `json:"subIncyEnableRouting" form:"subIncyEnableRouting"` // Enable routing injection for the Incy client
|
||||||
|
SubIncyRoutingRules string `json:"subIncyRoutingRules" form:"subIncyRoutingRules"` // Incy routing deep-link injected into the subscription body (Only for Incy)
|
||||||
SubListen string `json:"subListen" form:"subListen"` // Subscription server listen IP
|
SubListen string `json:"subListen" form:"subListen"` // Subscription server listen IP
|
||||||
SubPort int `json:"subPort" form:"subPort" validate:"gte=1,lte=65535"` // Subscription server port
|
SubPort int `json:"subPort" form:"subPort" validate:"gte=1,lte=65535"` // Subscription server port
|
||||||
SubPath string `json:"subPath" form:"subPath"` // Base path for subscription URLs
|
SubPath string `json:"subPath" form:"subPath"` // Base path for subscription URLs
|
||||||
|
|||||||
@@ -538,9 +538,14 @@ func (r *Remote) RestartXray(ctx context.Context) error {
|
|||||||
|
|
||||||
// UpdatePanel asks the node to run its own official self-updater (update.sh)
|
// UpdatePanel asks the node to run its own official self-updater (update.sh)
|
||||||
// and restart onto the latest release. The node returns as soon as the job is
|
// and restart onto the latest release. The node returns as soon as the job is
|
||||||
// launched; the new version surfaces on the next heartbeat.
|
// launched; the new version surfaces on the next heartbeat. When dev is true the
|
||||||
func (r *Remote) UpdatePanel(ctx context.Context) error {
|
// node is moved to the rolling dev channel instead of the latest stable release.
|
||||||
_, err := r.do(ctx, http.MethodPost, "panel/api/server/updatePanel", nil)
|
func (r *Remote) UpdatePanel(ctx context.Context, dev bool) error {
|
||||||
|
var body any
|
||||||
|
if dev {
|
||||||
|
body = url.Values{"dev": {"true"}}
|
||||||
|
}
|
||||||
|
_, err := r.do(ctx, http.MethodPost, "panel/api/server/updatePanel", body)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -242,6 +242,22 @@ type bulkAdjustEntry struct {
|
|||||||
newTotal int64
|
newTotal int64
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// bulkFlowClear is the directive that strips the XTLS flow from every selected
|
||||||
|
// client. The vision values are the only positive flows xray accepts.
|
||||||
|
const bulkFlowClear = "none"
|
||||||
|
|
||||||
|
// bulkFlowAllowed whitelists the flow directives BulkAdjust accepts. Anything
|
||||||
|
// outside this set is treated as "" (leave flow untouched) so a malformed or
|
||||||
|
// hostile value can never be injected into a client's settings. The dropdown in
|
||||||
|
// ClientBulkAdjustModal.tsx offers the same set ("" / "none" / TLS_FLOW_CONTROL);
|
||||||
|
// keep the two in sync.
|
||||||
|
var bulkFlowAllowed = map[string]struct{}{
|
||||||
|
"": {},
|
||||||
|
bulkFlowClear: {},
|
||||||
|
"xtls-rprx-vision": {},
|
||||||
|
"xtls-rprx-vision-udp443": {},
|
||||||
|
}
|
||||||
|
|
||||||
// BulkAdjust shifts ExpiryTime by addDays (days) and TotalGB by addBytes
|
// BulkAdjust shifts ExpiryTime by addDays (days) and TotalGB by addBytes
|
||||||
// for every email in the list. Clients whose corresponding field is
|
// for every email in the list. Clients whose corresponding field is
|
||||||
// unlimited (0) are skipped — bulk extend should not accidentally
|
// unlimited (0) are skipped — bulk extend should not accidentally
|
||||||
@@ -250,12 +266,17 @@ type bulkAdjustEntry struct {
|
|||||||
// Like BulkDelete, the work is grouped by inbound so each inbound's
|
// Like BulkDelete, the work is grouped by inbound so each inbound's
|
||||||
// settings JSON is parsed and written exactly once regardless of how
|
// settings JSON is parsed and written exactly once regardless of how
|
||||||
// many target emails it contains.
|
// many target emails it contains.
|
||||||
func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string, addDays int, addBytes int64) (BulkAdjustResult, bool, error) {
|
func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string, addDays int, addBytes int64, flow string) (BulkAdjustResult, bool, error) {
|
||||||
result := BulkAdjustResult{}
|
result := BulkAdjustResult{}
|
||||||
if len(emails) == 0 {
|
if len(emails) == 0 {
|
||||||
return result, false, nil
|
return result, false, nil
|
||||||
}
|
}
|
||||||
if addDays == 0 && addBytes == 0 {
|
flow = strings.TrimSpace(flow)
|
||||||
|
if _, ok := bulkFlowAllowed[flow]; !ok {
|
||||||
|
flow = "" // ignore unknown directives — "" means "leave flow untouched"
|
||||||
|
}
|
||||||
|
adjustFlow := flow != ""
|
||||||
|
if addDays == 0 && addBytes == 0 && !adjustFlow {
|
||||||
return result, false, common.NewError("no adjustment specified")
|
return result, false, common.NewError("no adjustment specified")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -342,7 +363,7 @@ func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string,
|
|||||||
entry.newTotal = next
|
entry.newTotal = next
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if entry.applyExpiry || entry.applyTotal {
|
if entry.applyExpiry || entry.applyTotal || adjustFlow {
|
||||||
plan[email] = entry
|
plan[email] = entry
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -379,11 +400,19 @@ func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string,
|
|||||||
}
|
}
|
||||||
|
|
||||||
needRestart := false
|
needRestart := false
|
||||||
|
flowHonored := map[string]bool{}
|
||||||
|
flowIneligible := map[string]bool{}
|
||||||
for inboundId, ibEmails := range emailsByInbound {
|
for inboundId, ibEmails := range emailsByInbound {
|
||||||
ibRes := s.bulkAdjustInboundClients(inboundSvc, inboundId, ibEmails, plan)
|
ibRes := s.bulkAdjustInboundClients(inboundSvc, inboundId, ibEmails, plan, flow)
|
||||||
if ibRes.needRestart {
|
if ibRes.needRestart {
|
||||||
needRestart = true
|
needRestart = true
|
||||||
}
|
}
|
||||||
|
for email := range ibRes.flowHonored {
|
||||||
|
flowHonored[email] = true
|
||||||
|
}
|
||||||
|
for email := range ibRes.flowIneligible {
|
||||||
|
flowIneligible[email] = true
|
||||||
|
}
|
||||||
for email, reason := range ibRes.perEmailSkipped {
|
for email, reason := range ibRes.perEmailSkipped {
|
||||||
if _, already := skippedReasons[email]; !already {
|
if _, already := skippedReasons[email]; !already {
|
||||||
skippedReasons[email] = reason
|
skippedReasons[email] = reason
|
||||||
@@ -391,6 +420,7 @@ func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
adjusted := map[string]struct{}{}
|
||||||
for email, entry := range plan {
|
for email, entry := range plan {
|
||||||
if _, skipped := skippedReasons[email]; skipped {
|
if _, skipped := skippedReasons[email]; skipped {
|
||||||
continue
|
continue
|
||||||
@@ -402,27 +432,49 @@ func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string,
|
|||||||
if entry.applyTotal {
|
if entry.applyTotal {
|
||||||
updates["total"] = entry.newTotal
|
updates["total"] = entry.newTotal
|
||||||
}
|
}
|
||||||
if len(updates) == 0 {
|
if len(updates) > 0 {
|
||||||
continue
|
if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).Updates(updates).Error; err != nil {
|
||||||
}
|
if _, already := skippedReasons[email]; !already {
|
||||||
if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).Updates(updates).Error; err != nil {
|
skippedReasons[email] = err.Error()
|
||||||
if _, already := skippedReasons[email]; !already {
|
}
|
||||||
skippedReasons[email] = err.Error()
|
continue
|
||||||
}
|
}
|
||||||
continue
|
|
||||||
}
|
}
|
||||||
result.Adjusted++
|
// Counted when expiry/total changed, or a flow directive was honored
|
||||||
|
// for this client (flow lives in the inbound JSON, not ClientTraffic).
|
||||||
|
if len(updates) > 0 || flowHonored[email] {
|
||||||
|
adjusted[email] = struct{}{}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
result.Adjusted = len(adjusted)
|
||||||
|
|
||||||
for email, reason := range skippedReasons {
|
for email, reason := range skippedReasons {
|
||||||
result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: reason})
|
result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: reason})
|
||||||
}
|
}
|
||||||
|
// Report a flow directive that no inbound could carry — only when it was not
|
||||||
|
// honored anywhere and the client has no other (expiry/total) skip reason.
|
||||||
|
// The expiry/total part, if any, has already been applied and counted above.
|
||||||
|
for email := range flowIneligible {
|
||||||
|
if flowHonored[email] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, already := skippedReasons[email]; already {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: "flow not supported on inbound"})
|
||||||
|
}
|
||||||
return result, needRestart, nil
|
return result, needRestart, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type bulkInboundAdjustResult struct {
|
type bulkInboundAdjustResult struct {
|
||||||
perEmailSkipped map[string]string
|
perEmailSkipped map[string]string
|
||||||
needRestart bool
|
flowHonored map[string]bool
|
||||||
|
// flowIneligible is tracked apart from perEmailSkipped: a flow directive
|
||||||
|
// that an inbound cannot carry must not suppress the expiry/total write for
|
||||||
|
// the same client (which would diverge the inbound JSON / ClientRecord from
|
||||||
|
// ClientTraffic). It only feeds the final Skipped report.
|
||||||
|
flowIneligible map[string]bool
|
||||||
|
needRestart bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// bulkAdjustInboundClients applies expiry/total deltas to multiple clients
|
// bulkAdjustInboundClients applies expiry/total deltas to multiple clients
|
||||||
@@ -436,8 +488,9 @@ func (s *ClientService) bulkAdjustInboundClients(
|
|||||||
inboundId int,
|
inboundId int,
|
||||||
emails []string,
|
emails []string,
|
||||||
plan map[string]*bulkAdjustEntry,
|
plan map[string]*bulkAdjustEntry,
|
||||||
|
flow string,
|
||||||
) bulkInboundAdjustResult {
|
) bulkInboundAdjustResult {
|
||||||
res := bulkInboundAdjustResult{perEmailSkipped: map[string]string{}}
|
res := bulkInboundAdjustResult{perEmailSkipped: map[string]string{}, flowHonored: map[string]bool{}, flowIneligible: map[string]bool{}}
|
||||||
|
|
||||||
defer lockInbound(inboundId).Unlock()
|
defer lockInbound(inboundId).Unlock()
|
||||||
|
|
||||||
@@ -469,8 +522,15 @@ func (s *ClientService) bulkAdjustInboundClients(
|
|||||||
wantedEmails[email] = struct{}{}
|
wantedEmails[email] = struct{}{}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Flow eligibility is a property of the inbound (protocol + transport), so
|
||||||
|
// resolve it once. Clearing flow is always allowed; setting a vision flow
|
||||||
|
// is only honored on an inbound that can carry it.
|
||||||
|
flowEligible := flow == bulkFlowClear ||
|
||||||
|
inboundCanEnableTlsFlow(string(oldInbound.Protocol), oldInbound.StreamSettings, oldInbound.Settings)
|
||||||
|
|
||||||
interfaceClients, _ := settings["clients"].([]any)
|
interfaceClients, _ := settings["clients"].([]any)
|
||||||
foundEmails := map[string]bool{}
|
foundEmails := map[string]bool{}
|
||||||
|
flowChanged := false
|
||||||
nowMs := time.Now().Unix() * 1000
|
nowMs := time.Now().Unix() * 1000
|
||||||
for i, client := range interfaceClients {
|
for i, client := range interfaceClients {
|
||||||
c, ok := client.(map[string]any)
|
c, ok := client.(map[string]any)
|
||||||
@@ -488,6 +548,23 @@ func (s *ClientService) bulkAdjustInboundClients(
|
|||||||
if entry.applyTotal {
|
if entry.applyTotal {
|
||||||
c["totalGB"] = entry.newTotal
|
c["totalGB"] = entry.newTotal
|
||||||
}
|
}
|
||||||
|
if flow != "" {
|
||||||
|
if flowEligible {
|
||||||
|
want := ""
|
||||||
|
if flow != bulkFlowClear {
|
||||||
|
want = flow
|
||||||
|
}
|
||||||
|
if cur, _ := c["flow"].(string); cur != want {
|
||||||
|
c["flow"] = want
|
||||||
|
flowChanged = true
|
||||||
|
}
|
||||||
|
res.flowHonored[targetEmail] = true
|
||||||
|
} else {
|
||||||
|
// Record separately so this never suppresses the expiry/total
|
||||||
|
// write for the same client (see flowIneligible doc).
|
||||||
|
res.flowIneligible[targetEmail] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
c["updated_at"] = nowMs
|
c["updated_at"] = nowMs
|
||||||
interfaceClients[i] = c
|
interfaceClients[i] = c
|
||||||
foundEmails[targetEmail] = true
|
foundEmails[targetEmail] = true
|
||||||
@@ -513,6 +590,13 @@ func (s *ClientService) bulkAdjustInboundClients(
|
|||||||
}
|
}
|
||||||
oldInbound.Settings = string(newSettings)
|
oldInbound.Settings = string(newSettings)
|
||||||
|
|
||||||
|
// A flow change rewrites the user's xray config, which the lightweight
|
||||||
|
// UpdateUser push below does not carry. Local nodes reload via restart;
|
||||||
|
// remote nodes get a full reconcile (MarkNodeDirty) instead of a per-user push.
|
||||||
|
if flowChanged && oldInbound.NodeID == nil {
|
||||||
|
res.needRestart = true
|
||||||
|
}
|
||||||
|
|
||||||
markDirty := false
|
markDirty := false
|
||||||
if oldInbound.NodeID != nil {
|
if oldInbound.NodeID != nil {
|
||||||
rt, push, dirty, perr := inboundSvc.nodePushPlan(oldInbound)
|
rt, push, dirty, perr := inboundSvc.nodePushPlan(oldInbound)
|
||||||
@@ -525,6 +609,10 @@ func (s *ClientService) bulkAdjustInboundClients(
|
|||||||
if dirty {
|
if dirty {
|
||||||
markDirty = true
|
markDirty = true
|
||||||
}
|
}
|
||||||
|
if flowChanged {
|
||||||
|
markDirty = true
|
||||||
|
push = false
|
||||||
|
}
|
||||||
// Large batches collapse into one reconcile push rather than M updates.
|
// Large batches collapse into one reconcile push rather than M updates.
|
||||||
if push && len(foundEmails) > nodeBulkPushThreshold {
|
if push && len(foundEmails) > nodeBulkPushThreshold {
|
||||||
markDirty = true
|
markDirty = true
|
||||||
|
|||||||
@@ -0,0 +1,217 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||||
|
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||||
|
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||||
|
)
|
||||||
|
|
||||||
|
// mkInboundStream is mkInbound with explicit stream settings, needed to make an
|
||||||
|
// inbound flow-eligible (VLESS + tcp + reality/tls).
|
||||||
|
func mkInboundStream(t *testing.T, port int, proto model.Protocol, settings, stream string) *model.Inbound {
|
||||||
|
t.Helper()
|
||||||
|
ib := &model.Inbound{
|
||||||
|
Tag: string(proto) + "-stream-" + emailSafe(port),
|
||||||
|
Enable: true,
|
||||||
|
Port: port,
|
||||||
|
Protocol: proto,
|
||||||
|
Settings: settings,
|
||||||
|
StreamSettings: stream,
|
||||||
|
}
|
||||||
|
if err := database.GetDB().Create(ib).Error; err != nil {
|
||||||
|
t.Fatalf("create inbound %d: %v", port, err)
|
||||||
|
}
|
||||||
|
return ib
|
||||||
|
}
|
||||||
|
|
||||||
|
func emailSafe(port int) string {
|
||||||
|
return string(rune('a'+port%26)) + string(rune('a'+(port/26)%26))
|
||||||
|
}
|
||||||
|
|
||||||
|
func flowOf(t *testing.T, svc *ClientService, email string) string {
|
||||||
|
t.Helper()
|
||||||
|
rec, err := svc.GetRecordByEmail(nil, email)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GetRecordByEmail(%q): %v", email, err)
|
||||||
|
}
|
||||||
|
return rec.Flow
|
||||||
|
}
|
||||||
|
|
||||||
|
const realityStream = `{"network":"tcp","security":"reality"}`
|
||||||
|
const wsStream = `{"network":"ws","security":"none"}`
|
||||||
|
|
||||||
|
// TestBulkAdjust_FlowSetAndClear covers the happy path: a vision flow is applied
|
||||||
|
// on an eligible VLESS inbound and later cleared with the "none" directive. Both
|
||||||
|
// transitions are real config changes, so they must request a restart.
|
||||||
|
func TestBulkAdjust_FlowSetAndClear(t *testing.T) {
|
||||||
|
setupBulkDB(t)
|
||||||
|
svc := &ClientService{}
|
||||||
|
inboundSvc := &InboundService{}
|
||||||
|
|
||||||
|
clients := []model.Client{
|
||||||
|
{Email: "f1@x", ID: "11111111-1111-1111-1111-111111111111", SubID: "f1", Enable: true},
|
||||||
|
{Email: "f2@x", ID: "22222222-2222-2222-2222-222222222222", SubID: "f2", Enable: true},
|
||||||
|
}
|
||||||
|
ib := mkInboundStream(t, 30001, model.VLESS, clientsSettings(t, clients), realityStream)
|
||||||
|
if err := svc.SyncInbound(nil, ib.Id, clients); err != nil {
|
||||||
|
t.Fatalf("seed: %v", err)
|
||||||
|
}
|
||||||
|
emails := emailsOf(clients)
|
||||||
|
|
||||||
|
// Set vision flow.
|
||||||
|
res, restart, err := svc.BulkAdjust(inboundSvc, emails, 0, 0, "xtls-rprx-vision-udp443")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("BulkAdjust set: %v", err)
|
||||||
|
}
|
||||||
|
if res.Adjusted != 2 {
|
||||||
|
t.Fatalf("expected 2 adjusted, got %d (skipped=%v)", res.Adjusted, res.Skipped)
|
||||||
|
}
|
||||||
|
if !restart {
|
||||||
|
t.Fatalf("setting flow should request a restart")
|
||||||
|
}
|
||||||
|
for _, e := range emails {
|
||||||
|
if got := flowOf(t, svc, e); got != "xtls-rprx-vision-udp443" {
|
||||||
|
t.Fatalf("%s flow = %q, want xtls-rprx-vision-udp443", e, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Setting the same flow again is a no-op: honored (counted) but no restart.
|
||||||
|
if _, restart2, err := svc.BulkAdjust(inboundSvc, emails, 0, 0, "xtls-rprx-vision-udp443"); err != nil {
|
||||||
|
t.Fatalf("BulkAdjust idempotent: %v", err)
|
||||||
|
} else if restart2 {
|
||||||
|
t.Fatalf("re-setting identical flow should not request a restart")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clear flow.
|
||||||
|
cres, crestart, err := svc.BulkAdjust(inboundSvc, emails, 0, 0, "none")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("BulkAdjust clear: %v", err)
|
||||||
|
}
|
||||||
|
if cres.Adjusted != 2 {
|
||||||
|
t.Fatalf("expected 2 cleared, got %d (skipped=%v)", cres.Adjusted, cres.Skipped)
|
||||||
|
}
|
||||||
|
if !crestart {
|
||||||
|
t.Fatalf("clearing flow should request a restart")
|
||||||
|
}
|
||||||
|
for _, e := range emails {
|
||||||
|
if got := flowOf(t, svc, e); got != "" {
|
||||||
|
t.Fatalf("%s flow = %q, want empty after clear", e, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestBulkAdjust_FlowIneligibleSkipped verifies a vision flow is refused on an
|
||||||
|
// inbound that cannot carry it (ws transport), reported as skipped, and the
|
||||||
|
// client's flow is left untouched.
|
||||||
|
func TestBulkAdjust_FlowIneligibleSkipped(t *testing.T) {
|
||||||
|
setupBulkDB(t)
|
||||||
|
svc := &ClientService{}
|
||||||
|
inboundSvc := &InboundService{}
|
||||||
|
|
||||||
|
clients := []model.Client{
|
||||||
|
{Email: "ws1@x", ID: "33333333-3333-3333-3333-333333333333", SubID: "ws1", Enable: true},
|
||||||
|
}
|
||||||
|
ib := mkInboundStream(t, 30101, model.VLESS, clientsSettings(t, clients), wsStream)
|
||||||
|
if err := svc.SyncInbound(nil, ib.Id, clients); err != nil {
|
||||||
|
t.Fatalf("seed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
res, restart, err := svc.BulkAdjust(inboundSvc, []string{"ws1@x"}, 0, 0, "xtls-rprx-vision")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("BulkAdjust: %v", err)
|
||||||
|
}
|
||||||
|
if res.Adjusted != 0 {
|
||||||
|
t.Fatalf("ineligible inbound should adjust nothing, got %d", res.Adjusted)
|
||||||
|
}
|
||||||
|
if restart {
|
||||||
|
t.Fatalf("no change should not request a restart")
|
||||||
|
}
|
||||||
|
if len(res.Skipped) != 1 || res.Skipped[0].Email != "ws1@x" {
|
||||||
|
t.Fatalf("expected ws1@x in skipped, got %v", res.Skipped)
|
||||||
|
}
|
||||||
|
if got := flowOf(t, svc, "ws1@x"); got != "" {
|
||||||
|
t.Fatalf("flow should stay empty on ineligible inbound, got %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestBulkAdjust_NoDirectiveErrors guards the relaxed precondition: with no
|
||||||
|
// days, traffic, or flow set there is nothing to do.
|
||||||
|
func TestBulkAdjust_NoDirectiveErrors(t *testing.T) {
|
||||||
|
setupBulkDB(t)
|
||||||
|
svc := &ClientService{}
|
||||||
|
inboundSvc := &InboundService{}
|
||||||
|
|
||||||
|
if _, _, err := svc.BulkAdjust(inboundSvc, []string{"any@x"}, 0, 0, ""); err == nil {
|
||||||
|
t.Fatalf("expected error when no adjustment is specified")
|
||||||
|
}
|
||||||
|
// An unknown flow directive is ignored (treated as ""), so it also errors.
|
||||||
|
if _, _, err := svc.BulkAdjust(inboundSvc, []string{"any@x"}, 0, 0, "bogus-flow"); err == nil {
|
||||||
|
t.Fatalf("unknown flow should be ignored and error like an empty directive")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestBulkAdjust_DaysApplyDespiteIneligibleFlow is the regression for the review
|
||||||
|
// blocker: when a client on a flow-ineligible inbound is adjusted with BOTH a
|
||||||
|
// days/traffic delta AND a flow directive, the days/traffic change must still be
|
||||||
|
// persisted to ClientTraffic (not just the inbound JSON / ClientRecord) and the
|
||||||
|
// client must count as adjusted, while the unhonored flow is reported separately.
|
||||||
|
func TestBulkAdjust_DaysApplyDespiteIneligibleFlow(t *testing.T) {
|
||||||
|
setupBulkDB(t)
|
||||||
|
svc := &ClientService{}
|
||||||
|
inboundSvc := &InboundService{}
|
||||||
|
|
||||||
|
const day = int64(24 * 60 * 60 * 1000)
|
||||||
|
const gb = int64(1) << 30
|
||||||
|
baseExpiry := time.Now().UnixMilli() + 30*day
|
||||||
|
baseTotal := 10 * gb
|
||||||
|
|
||||||
|
clients := []model.Client{
|
||||||
|
{Email: "mix@x", ID: "44444444-4444-4444-4444-444444444444", SubID: "mix", Enable: true, ExpiryTime: baseExpiry, TotalGB: baseTotal},
|
||||||
|
}
|
||||||
|
ib := mkInboundStream(t, 30201, model.VLESS, clientsSettings(t, clients), wsStream)
|
||||||
|
if err := svc.SyncInbound(nil, ib.Id, clients); err != nil {
|
||||||
|
t.Fatalf("seed: %v", err)
|
||||||
|
}
|
||||||
|
// ClientTraffic is the store the enforcement job reads; seed it to match.
|
||||||
|
if err := database.GetDB().Create(&xray.ClientTraffic{Email: "mix@x", Enable: true, ExpiryTime: baseExpiry, Total: baseTotal}).Error; err != nil {
|
||||||
|
t.Fatalf("seed traffic: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
res, _, err := svc.BulkAdjust(inboundSvc, []string{"mix@x"}, 7, gb, "xtls-rprx-vision")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("BulkAdjust: %v", err)
|
||||||
|
}
|
||||||
|
if res.Adjusted != 1 {
|
||||||
|
t.Fatalf("days/traffic should still be applied: Adjusted=%d skipped=%v", res.Adjusted, res.Skipped)
|
||||||
|
}
|
||||||
|
if len(res.Skipped) != 1 || res.Skipped[0].Email != "mix@x" {
|
||||||
|
t.Fatalf("expected mix@x reported for the unhonored flow, got %v", res.Skipped)
|
||||||
|
}
|
||||||
|
|
||||||
|
wantExpiry := baseExpiry + 7*day
|
||||||
|
wantTotal := baseTotal + gb
|
||||||
|
|
||||||
|
// ClientRecord (inbound-derived) advanced.
|
||||||
|
if rec, err := svc.GetRecordByEmail(nil, "mix@x"); err != nil {
|
||||||
|
t.Fatalf("record: %v", err)
|
||||||
|
} else if rec.ExpiryTime != wantExpiry || rec.TotalGB != wantTotal {
|
||||||
|
t.Fatalf("ClientRecord not advanced: expiry=%d total=%d", rec.ExpiryTime, rec.TotalGB)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClientTraffic advanced in lockstep — no divergence.
|
||||||
|
var ct xray.ClientTraffic
|
||||||
|
if err := database.GetDB().Where("email = ?", "mix@x").First(&ct).Error; err != nil {
|
||||||
|
t.Fatalf("traffic row: %v", err)
|
||||||
|
}
|
||||||
|
if ct.ExpiryTime != wantExpiry || ct.Total != wantTotal {
|
||||||
|
t.Fatalf("ClientTraffic diverged: expiry=%d total=%d, want expiry=%d total=%d", ct.ExpiryTime, ct.Total, wantExpiry, wantTotal)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Flow left untouched on the ineligible inbound.
|
||||||
|
if got := flowOf(t, svc, "mix@x"); got != "" {
|
||||||
|
t.Fatalf("flow should stay empty on ineligible inbound, got %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||||
|
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||||
|
)
|
||||||
|
|
||||||
|
// EffectiveFlowsByEmails resolves intended flow for many clients in one batched
|
||||||
|
// query, taking the flow_override of the lowest inbound_id and skipping emails
|
||||||
|
// with no non-empty flow anywhere.
|
||||||
|
func TestEffectiveFlowsByEmails(t *testing.T) {
|
||||||
|
dbDir := t.TempDir()
|
||||||
|
t.Setenv("XUI_DB_FOLDER", dbDir)
|
||||||
|
if err := database.InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
|
||||||
|
t.Fatalf("InitDB: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = database.CloseDB() })
|
||||||
|
db := database.GetDB()
|
||||||
|
|
||||||
|
const vision = "xtls-rprx-vision"
|
||||||
|
|
||||||
|
// vis@x: attached to inbound 20 (empty flow) and 10 (Vision) — lowest
|
||||||
|
// inbound_id (10) wins, so the empty override on 20 must not mask it.
|
||||||
|
// plain@x: only an empty flow_override anywhere — absent from the result.
|
||||||
|
mkClient := func(id int, email string) {
|
||||||
|
if err := db.Create(&model.ClientRecord{Id: id, Email: email, Enable: true}).Error; err != nil {
|
||||||
|
t.Fatalf("create client %s: %v", email, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mkLink := func(clientID, inboundID int, flow string) {
|
||||||
|
if err := db.Create(&model.ClientInbound{ClientId: clientID, InboundId: inboundID, FlowOverride: flow}).Error; err != nil {
|
||||||
|
t.Fatalf("link %d/%d: %v", clientID, inboundID, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mkClient(1, "vis@x")
|
||||||
|
mkClient(2, "plain@x")
|
||||||
|
mkLink(1, 20, "") // higher inbound_id, empty
|
||||||
|
mkLink(1, 10, vision) // lower inbound_id, Vision
|
||||||
|
mkLink(2, 30, "") // only empty override
|
||||||
|
|
||||||
|
cs := &ClientService{}
|
||||||
|
got, err := cs.EffectiveFlowsByEmails(nil, []string{"vis@x", "plain@x", "missing@x"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("EffectiveFlowsByEmails: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if got["vis@x"] != vision {
|
||||||
|
t.Errorf("vis@x = %q, want %q (lowest inbound_id flow_override)", got["vis@x"], vision)
|
||||||
|
}
|
||||||
|
if v, ok := got["plain@x"]; ok {
|
||||||
|
t.Errorf("plain@x present (%q); want absent (no non-empty flow anywhere)", v)
|
||||||
|
}
|
||||||
|
if v, ok := got["missing@x"]; ok {
|
||||||
|
t.Errorf("missing@x present (%q); want absent (unknown client)", v)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Empty input is a no-op (no query).
|
||||||
|
if m, err := cs.EffectiveFlowsByEmails(nil, nil); err != nil || len(m) != 0 {
|
||||||
|
t.Errorf("empty input: got %v err %v, want empty map", m, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -787,9 +787,12 @@ func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inbo
|
|||||||
delStat = traffic != nil
|
delStat = traffic != nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The runtime user is scoped to this inbound's tag + email, so the push plan
|
||||||
|
// is resolved independently of emailShared — a sibling inbound still carrying
|
||||||
|
// the email must not suppress removing the user from this inbound's Xray.
|
||||||
var rt runtime.Runtime
|
var rt runtime.Runtime
|
||||||
var push bool
|
var push bool
|
||||||
if len(email) > 0 && !emailShared && (oldInbound.NodeID != nil || needApiDel) {
|
if len(email) > 0 && (oldInbound.NodeID != nil || needApiDel) {
|
||||||
r, p, dirty, perr := inboundSvc.nodePushPlan(oldInbound)
|
r, p, dirty, perr := inboundSvc.nodePushPlan(oldInbound)
|
||||||
if perr != nil {
|
if perr != nil {
|
||||||
return false, perr
|
return false, perr
|
||||||
@@ -828,8 +831,10 @@ func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inbo
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Apply the runtime delete after commit — outside the serialized writer so a
|
// Apply the runtime delete after commit — outside the serialized writer so a
|
||||||
// slow node call can't stall traffic accounting.
|
// slow node call can't stall traffic accounting. Independent of emailShared:
|
||||||
if len(email) > 0 && !emailShared {
|
// Xray users are keyed by inbound tag, so the user must be removed from this
|
||||||
|
// inbound's runtime even when the same email survives in another inbound.
|
||||||
|
if len(email) > 0 {
|
||||||
if oldInbound.NodeID == nil {
|
if oldInbound.NodeID == nil {
|
||||||
// Local inbound: a disabled client isn't in the running Xray, so only
|
// Local inbound: a disabled client isn't in the running Xray, so only
|
||||||
// a live one (needApiDel) needs an API removal.
|
// a live one (needApiDel) needs an API removal.
|
||||||
|
|||||||
@@ -49,6 +49,44 @@ func (s *ClientService) EffectiveFlow(tx *gorm.DB, recordId int) (string, error)
|
|||||||
return flows[0], nil
|
return flows[0], nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// EffectiveFlowsByEmails resolves the intended flow (non-empty flow_override,
|
||||||
|
// lowest inbound_id first — same rule as EffectiveFlow) for many clients in one
|
||||||
|
// query, keyed by email. Emails absent from the result carry no flow anywhere.
|
||||||
|
// Batched so flow restoration on an inbound with many clients is O(1) queries
|
||||||
|
// instead of O(clients). Used to restore a stripped flow onto an inbound that
|
||||||
|
// has just become flow-eligible.
|
||||||
|
func (s *ClientService) EffectiveFlowsByEmails(tx *gorm.DB, emails []string) (map[string]string, error) {
|
||||||
|
if tx == nil {
|
||||||
|
tx = database.GetDB()
|
||||||
|
}
|
||||||
|
out := make(map[string]string, len(emails))
|
||||||
|
if len(emails) == 0 {
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
type row struct {
|
||||||
|
Email string
|
||||||
|
Flow string `gorm:"column:flow_override"`
|
||||||
|
}
|
||||||
|
for _, batch := range chunkStrings(emails, sqlInChunk) {
|
||||||
|
var rows []row
|
||||||
|
err := tx.Table("client_inbounds").
|
||||||
|
Select("clients.email AS email, client_inbounds.flow_override AS flow_override").
|
||||||
|
Joins("JOIN clients ON clients.id = client_inbounds.client_id").
|
||||||
|
Where("clients.email IN ? AND client_inbounds.flow_override <> ?", batch, "").
|
||||||
|
Order("client_inbounds.inbound_id ASC").
|
||||||
|
Scan(&rows).Error
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for _, r := range rows {
|
||||||
|
if _, seen := out[r.Email]; !seen { // ordered by inbound_id ASC → first = lowest
|
||||||
|
out[r.Email] = r.Flow
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
func (s *ClientService) GetInboundIdsForEmail(tx *gorm.DB, email string) ([]int, error) {
|
func (s *ClientService) GetInboundIdsForEmail(tx *gorm.DB, email string) ([]int, error) {
|
||||||
if tx == nil {
|
if tx == nil {
|
||||||
tx = database.GetDB()
|
tx = database.GetDB()
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Deleting a client that is attached to more than one inbound must still remove
|
||||||
|
// the user from the running runtime of the inbound being deleted from. The
|
||||||
|
// runtime user is keyed by inbound tag, so a sibling inbound still carrying the
|
||||||
|
// same email (emailShared) must not suppress the per-inbound runtime removal —
|
||||||
|
// otherwise the deleted user keeps connecting on that inbound until Xray
|
||||||
|
// restart (#5543).
|
||||||
|
func TestDelInboundClientByEmail_SharedEmailStillRemovesFromRuntime(t *testing.T) {
|
||||||
|
setupBulkDB(t)
|
||||||
|
nodeID, fake := setupNodeRuntime(t)
|
||||||
|
|
||||||
|
shared := []model.Client{{ID: uuid.NewString(), Email: "shared@x", Enable: true}}
|
||||||
|
ibA := nodeInbound(t, nodeID, 31001, shared)
|
||||||
|
nodeInbound(t, nodeID, 31002, shared)
|
||||||
|
|
||||||
|
svc := &ClientService{}
|
||||||
|
inboundSvc := &InboundService{}
|
||||||
|
|
||||||
|
if _, err := svc.DelInboundClientByEmail(inboundSvc, ibA.Id, "shared@x", false); err != nil {
|
||||||
|
t.Fatalf("DelInboundClientByEmail: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if got := fake.deleteUser.Load(); got != 1 {
|
||||||
|
t.Fatalf("shared-email delete dispatched %d DeleteUser RPCs, want 1 (must remove from the deleted inbound's runtime despite the sibling inbound) (#5543)", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1065,6 +1065,14 @@ func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound,
|
|||||||
logger.Warning("Shadowsocks inbound", inbound.Id, "method change resized keys; regenerated mismatched client PSK(s)")
|
logger.Warning("Shadowsocks inbound", inbound.Id, "method change resized keys; regenerated mismatched client PSK(s)")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Re-gate Vision flow now that the new stream/encryption is known: if this
|
||||||
|
// VLESS inbound just became flow-eligible (e.g. vlessenc was enabled on an
|
||||||
|
// XHTTP inbound), restore Vision for clients whose intended flow is Vision
|
||||||
|
// but was stripped while the inbound was ineligible.
|
||||||
|
if restored, changed := s.restoreVisionFlowForEligibleInbound(tx, inbound.Settings, inbound.StreamSettings, inbound.Protocol); changed {
|
||||||
|
inbound.Settings = restored
|
||||||
|
}
|
||||||
|
|
||||||
oldInbound.Total = inbound.Total
|
oldInbound.Total = inbound.Total
|
||||||
oldInbound.Remark = inbound.Remark
|
oldInbound.Remark = inbound.Remark
|
||||||
oldInbound.SubSortIndex = inbound.SubSortIndex
|
oldInbound.SubSortIndex = inbound.SubSortIndex
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
|
||||||
|
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
const visionFlow = "xtls-rprx-vision"
|
||||||
|
|
||||||
|
// restoreVisionFlowForEligibleInbound re-adds the XTLS Vision flow to a VLESS
|
||||||
|
// inbound's clients that lost it earlier.
|
||||||
|
//
|
||||||
|
// clientWithInboundFlow strips Vision from a client whenever the target inbound
|
||||||
|
// is not flow-eligible at write time (e.g. an XHTTP inbound before its vlessenc
|
||||||
|
// encryption is set). Nothing restored the flow when the inbound later became
|
||||||
|
// eligible — an inbound edit stores its settings verbatim and never re-gates the
|
||||||
|
// clients — so enabling encryption on an existing XHTTP inbound left every
|
||||||
|
// client without flow, and the share links/subscriptions dropped it.
|
||||||
|
//
|
||||||
|
// This runs on the now-final inbound settings: when the inbound IS flow-eligible
|
||||||
|
// it sets flow=Vision on each client that currently has no flow but whose
|
||||||
|
// intended flow (its flow_override on a sibling inbound, via EffectiveFlowsByEmails)
|
||||||
|
// is Vision. It never invents a flow for a client that has none anywhere, and it
|
||||||
|
// never overwrites an explicit non-empty flow. Returns the rewritten settings
|
||||||
|
// JSON and whether anything changed.
|
||||||
|
func (s *InboundService) restoreVisionFlowForEligibleInbound(tx *gorm.DB, settings, streamSettings string, protocol model.Protocol) (string, bool) {
|
||||||
|
if protocol != model.VLESS {
|
||||||
|
return settings, false
|
||||||
|
}
|
||||||
|
if !inboundCanEnableTlsFlow(string(protocol), streamSettings, settings) {
|
||||||
|
return settings, false
|
||||||
|
}
|
||||||
|
var parsed map[string]any
|
||||||
|
if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
|
||||||
|
return settings, false
|
||||||
|
}
|
||||||
|
clients, ok := parsed["clients"].([]any)
|
||||||
|
if !ok || len(clients) == 0 {
|
||||||
|
return settings, false
|
||||||
|
}
|
||||||
|
// Collect empty-flow clients, then resolve their intended flow in one query.
|
||||||
|
emails := make([]string, 0, len(clients))
|
||||||
|
for i := range clients {
|
||||||
|
cm, ok := clients[i].(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if flow, _ := cm["flow"].(string); flow != "" {
|
||||||
|
continue // respect an explicit flow (Vision or otherwise)
|
||||||
|
}
|
||||||
|
if email, _ := cm["email"].(string); email != "" {
|
||||||
|
emails = append(emails, email)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(emails) == 0 {
|
||||||
|
return settings, false
|
||||||
|
}
|
||||||
|
intended, err := s.clientService.EffectiveFlowsByEmails(tx, emails)
|
||||||
|
if err != nil {
|
||||||
|
return settings, false
|
||||||
|
}
|
||||||
|
changed := false
|
||||||
|
for i := range clients {
|
||||||
|
cm, ok := clients[i].(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if flow, _ := cm["flow"].(string); flow != "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
email, _ := cm["email"].(string)
|
||||||
|
if intended[email] != visionFlow {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
cm["flow"] = visionFlow
|
||||||
|
clients[i] = cm
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
if !changed {
|
||||||
|
return settings, false
|
||||||
|
}
|
||||||
|
out, err := json.MarshalIndent(parsed, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return settings, false
|
||||||
|
}
|
||||||
|
return string(out), true
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||||
|
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||||
|
)
|
||||||
|
|
||||||
|
// restoreVisionFlowForEligibleInbound must re-add Vision to a client whose flow
|
||||||
|
// was stripped while the XHTTP inbound was not yet vlessenc-encrypted, but only
|
||||||
|
// when the client's intended flow (its flow_override on a sibling) is Vision,
|
||||||
|
// only on now-eligible inbounds, and never overwriting an explicit flow.
|
||||||
|
func TestRestoreVisionFlowForEligibleInbound(t *testing.T) {
|
||||||
|
dbDir := t.TempDir()
|
||||||
|
t.Setenv("XUI_DB_FOLDER", dbDir)
|
||||||
|
if err := database.InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
|
||||||
|
t.Fatalf("InitDB: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = database.CloseDB() })
|
||||||
|
db := database.GetDB()
|
||||||
|
|
||||||
|
const vision = "xtls-rprx-vision"
|
||||||
|
const realityStream = `{"network":"tcp","security":"reality"}`
|
||||||
|
const xhttpEnc = `{"network":"xhttp","security":"reality"}`
|
||||||
|
const encSettings = `"decryption":"mlkem768x25519plus.native.0rtt.KEY","encryption":"mlkem768x25519plus.native.0rtt.KEY"`
|
||||||
|
|
||||||
|
cs := &ClientService{}
|
||||||
|
ibSvc := &InboundService{}
|
||||||
|
|
||||||
|
// Sibling reality inbound where the client legitimately has Vision.
|
||||||
|
sibling := &model.Inbound{
|
||||||
|
Tag: "sib", Enable: true, Port: 51001, Protocol: model.VLESS, StreamSettings: realityStream,
|
||||||
|
Settings: `{"clients":[{"id":"u1","email":"keep@x","flow":"` + vision + `","subId":"s1","enable":true}]}`,
|
||||||
|
}
|
||||||
|
if err := db.Create(sibling).Error; err != nil {
|
||||||
|
t.Fatalf("create sibling: %v", err)
|
||||||
|
}
|
||||||
|
keep, _ := ibSvc.GetClients(sibling)
|
||||||
|
if err := cs.SyncInbound(nil, sibling.Id, keep); err != nil {
|
||||||
|
t.Fatalf("sync sibling: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A client with no intended Vision anywhere — must NOT be touched.
|
||||||
|
other := &model.Inbound{
|
||||||
|
Tag: "oth", Enable: true, Port: 51002, Protocol: model.VLESS, StreamSettings: realityStream,
|
||||||
|
Settings: `{"clients":[{"id":"u2","email":"none@x","subId":"s2","enable":true}]}`,
|
||||||
|
}
|
||||||
|
if err := db.Create(other).Error; err != nil {
|
||||||
|
t.Fatalf("create other: %v", err)
|
||||||
|
}
|
||||||
|
oc, _ := ibSvc.GetClients(other)
|
||||||
|
if err := cs.SyncInbound(nil, other.Id, oc); err != nil {
|
||||||
|
t.Fatalf("sync other: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The now-eligible XHTTP inbound: keep@x has empty flow (was stripped),
|
||||||
|
// none@x has empty flow (no Vision anywhere), set@x has an explicit empty
|
||||||
|
// stays empty unless intended Vision.
|
||||||
|
target := `{` + encSettings + `,"clients":[` +
|
||||||
|
`{"id":"u1","email":"keep@x","flow":"","subId":"s1","enable":true},` +
|
||||||
|
`{"id":"u2","email":"none@x","flow":"","subId":"s2","enable":true}` +
|
||||||
|
`]}`
|
||||||
|
|
||||||
|
out, changed := ibSvc.restoreVisionFlowForEligibleInbound(nil, target, xhttpEnc, model.VLESS)
|
||||||
|
if !changed {
|
||||||
|
t.Fatal("expected changed=true")
|
||||||
|
}
|
||||||
|
var parsed map[string]any
|
||||||
|
if err := json.Unmarshal([]byte(out), &parsed); err != nil {
|
||||||
|
t.Fatalf("parse out: %v", err)
|
||||||
|
}
|
||||||
|
flows := map[string]string{}
|
||||||
|
for _, c := range parsed["clients"].([]any) {
|
||||||
|
cm := c.(map[string]any)
|
||||||
|
flows[cm["email"].(string)], _ = cm["flow"].(string)
|
||||||
|
}
|
||||||
|
if flows["keep@x"] != vision {
|
||||||
|
t.Errorf("keep@x flow = %q, want Vision (intended on sibling)", flows["keep@x"])
|
||||||
|
}
|
||||||
|
if flows["none@x"] != "" {
|
||||||
|
t.Errorf("none@x flow = %q, want empty (no Vision intent)", flows["none@x"])
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ineligible inbound (xhttp without encryption) must be a no-op.
|
||||||
|
noenc := `{"clients":[{"id":"u1","email":"keep@x","flow":"","subId":"s1","enable":true}]}`
|
||||||
|
if _, ch := ibSvc.restoreVisionFlowForEligibleInbound(nil, noenc, `{"network":"xhttp","security":"reality"}`, model.VLESS); ch {
|
||||||
|
t.Error("ineligible xhttp (no vlessenc) must not change")
|
||||||
|
}
|
||||||
|
// Non-VLESS must be a no-op.
|
||||||
|
if _, ch := ibSvc.restoreVisionFlowForEligibleInbound(nil, target, xhttpEnc, model.VMESS); ch {
|
||||||
|
t.Error("non-VLESS must not change")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -253,4 +253,45 @@ func (s *InboundService) MigrationRequirements() {
|
|||||||
func (s *InboundService) MigrateDB() {
|
func (s *InboundService) MigrateDB() {
|
||||||
s.MigrationRequirements()
|
s.MigrationRequirements()
|
||||||
s.MigrationRemoveOrphanedTraffics()
|
s.MigrationRemoveOrphanedTraffics()
|
||||||
|
s.MigrationRestoreVisionFlow()
|
||||||
|
}
|
||||||
|
|
||||||
|
// MigrationRestoreVisionFlow repairs VLESS inbounds whose clients lost their
|
||||||
|
// XTLS Vision flow because the inbound was not flow-eligible when the client was
|
||||||
|
// written (e.g. an XHTTP inbound whose vlessenc encryption was enabled only
|
||||||
|
// later). For each now-eligible inbound it restores flow=xtls-rprx-vision on
|
||||||
|
// clients whose intended flow (their flow_override on a sibling inbound) is
|
||||||
|
// Vision. Idempotent: once a client carries the flow it is skipped, so this is a
|
||||||
|
// no-op on healthy installs and on subsequent boots.
|
||||||
|
func (s *InboundService) MigrationRestoreVisionFlow() {
|
||||||
|
db := database.GetDB()
|
||||||
|
var inbounds []*model.Inbound
|
||||||
|
if err := db.Model(&model.Inbound{}).
|
||||||
|
Where("protocol = ?", model.VLESS).
|
||||||
|
Find(&inbounds).Error; err != nil {
|
||||||
|
logger.Warning("MigrationRestoreVisionFlow: load inbounds failed:", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, ib := range inbounds {
|
||||||
|
restored, changed := s.restoreVisionFlowForEligibleInbound(nil, ib.Settings, ib.StreamSettings, ib.Protocol)
|
||||||
|
if !changed {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
clients, err := s.GetClients(&model.Inbound{Settings: restored})
|
||||||
|
if err != nil {
|
||||||
|
logger.Warning("MigrationRestoreVisionFlow: parse clients for inbound", ib.Id, "failed:", err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
err = db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
if e := tx.Model(&model.Inbound{}).Where("id = ?", ib.Id).Update("settings", restored).Error; e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
return s.clientService.SyncInbound(tx, ib.Id, clients)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
logger.Warning("MigrationRestoreVisionFlow: update inbound", ib.Id, "failed:", err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
logger.Info("MigrationRestoreVisionFlow: restored XTLS Vision flow on inbound", ib.Id)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -637,7 +637,7 @@ type NodeUpdateResult struct {
|
|||||||
// UpdatePanels triggers the official self-updater on each given node. Only
|
// UpdatePanels triggers the official self-updater on each given node. Only
|
||||||
// enabled, online nodes are eligible — an offline node can't be reached, so it
|
// enabled, online nodes are eligible — an offline node can't be reached, so it
|
||||||
// is reported as skipped rather than silently dropped.
|
// is reported as skipped rather than silently dropped.
|
||||||
func (s *NodeService) UpdatePanels(ids []int) ([]NodeUpdateResult, error) {
|
func (s *NodeService) UpdatePanels(ids []int, dev bool) ([]NodeUpdateResult, error) {
|
||||||
mgr := runtime.GetManager()
|
mgr := runtime.GetManager()
|
||||||
if mgr == nil {
|
if mgr == nil {
|
||||||
return nil, fmt.Errorf("runtime manager unavailable")
|
return nil, fmt.Errorf("runtime manager unavailable")
|
||||||
@@ -662,7 +662,7 @@ func (s *NodeService) UpdatePanels(ids []int) ([]NodeUpdateResult, error) {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||||
updErr := remote.UpdatePanel(ctx)
|
updErr := remote.UpdatePanel(ctx, dev)
|
||||||
cancel()
|
cancel()
|
||||||
if updErr != nil {
|
if updErr != nil {
|
||||||
res.Error = updErr.Error()
|
res.Error = updErr.Error()
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -25,17 +26,27 @@ import (
|
|||||||
type PanelService struct{}
|
type PanelService struct{}
|
||||||
|
|
||||||
// PanelUpdateInfo contains the current and latest available panel versions.
|
// PanelUpdateInfo contains the current and latest available panel versions.
|
||||||
|
// On the dev channel the version fields carry a "dev+<sha>" label and the commit
|
||||||
|
// fields hold the short SHAs that drive the update-available decision.
|
||||||
type PanelUpdateInfo struct {
|
type PanelUpdateInfo struct {
|
||||||
|
Channel string `json:"channel"`
|
||||||
CurrentVersion string `json:"currentVersion"`
|
CurrentVersion string `json:"currentVersion"`
|
||||||
LatestVersion string `json:"latestVersion"`
|
LatestVersion string `json:"latestVersion"`
|
||||||
|
CurrentCommit string `json:"currentCommit,omitempty"`
|
||||||
|
LatestCommit string `json:"latestCommit,omitempty"`
|
||||||
UpdateAvailable bool `json:"updateAvailable"`
|
UpdateAvailable bool `json:"updateAvailable"`
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
const (
|
||||||
panelUpdaterURL = "https://raw.githubusercontent.com/MHSanaei/3x-ui/main/update.sh"
|
panelUpdaterURL = "https://raw.githubusercontent.com/MHSanaei/3x-ui/main/update.sh"
|
||||||
maxPanelUpdaterBytes = 2 << 20
|
maxPanelUpdaterBytes = 2 << 20
|
||||||
|
// devReleaseTag is the fixed-tag rolling pre-release the CI force-moves to the
|
||||||
|
// newest main commit; the dev update channel installs from it.
|
||||||
|
devReleaseTag = "dev-latest"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var releaseCommitRegex = regexp.MustCompile(`(?i)commit=([0-9a-f]{7,40})`)
|
||||||
|
|
||||||
func (s *PanelService) RestartPanel(delay time.Duration) error {
|
func (s *PanelService) RestartPanel(delay time.Duration) error {
|
||||||
go func() {
|
go func() {
|
||||||
time.Sleep(delay)
|
time.Sleep(delay)
|
||||||
@@ -58,22 +69,72 @@ func (s *PanelService) RestartPanel(delay time.Duration) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetUpdateInfo checks GitHub for the latest 3x-ui release.
|
// GetUpdateInfo checks GitHub for the latest 3x-ui release. When the dev channel
|
||||||
|
// is enabled on a dev build it compares commits against the rolling dev release;
|
||||||
|
// otherwise it compares versions against the latest stable tag.
|
||||||
func (s *PanelService) GetUpdateInfo() (*PanelUpdateInfo, error) {
|
func (s *PanelService) GetUpdateInfo() (*PanelUpdateInfo, error) {
|
||||||
|
if devChannelActive() {
|
||||||
|
return getDevUpdateInfo()
|
||||||
|
}
|
||||||
latest, err := fetchLatestPanelVersion()
|
latest, err := fetchLatestPanelVersion()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
current := config.GetVersion()
|
current := config.GetVersion()
|
||||||
return &PanelUpdateInfo{
|
return &PanelUpdateInfo{
|
||||||
|
Channel: "stable",
|
||||||
CurrentVersion: current,
|
CurrentVersion: current,
|
||||||
LatestVersion: latest,
|
LatestVersion: latest,
|
||||||
UpdateAvailable: isNewerVersion(latest, current),
|
UpdateAvailable: isNewerVersion(latest, current),
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// StartUpdate starts the official updater outside of the current web request.
|
// devChannelActive reports whether self-update should track the rolling dev
|
||||||
|
// release. It requires both the opt-in setting and a dev build, so a stable
|
||||||
|
// binary with the toggle left on never cross-grades to the dev channel.
|
||||||
|
func devChannelActive() bool {
|
||||||
|
if !config.IsDevBuild() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
enabled, err := (&service.SettingService{}).GetDevChannelEnable()
|
||||||
|
return err == nil && enabled
|
||||||
|
}
|
||||||
|
|
||||||
|
// getDevUpdateInfo compares the running commit against the commit recorded in the
|
||||||
|
// rolling dev release.
|
||||||
|
func getDevUpdateInfo() (*PanelUpdateInfo, error) {
|
||||||
|
release, err := fetchPanelRelease(devReleaseTag)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
latestCommit := extractReleaseCommit(release)
|
||||||
|
if latestCommit == "" {
|
||||||
|
return nil, fmt.Errorf("dev release commit is unknown")
|
||||||
|
}
|
||||||
|
currentCommit := config.GetBuildCommit()
|
||||||
|
return &PanelUpdateInfo{
|
||||||
|
Channel: "dev",
|
||||||
|
CurrentVersion: config.GetVersion(),
|
||||||
|
CurrentCommit: shortCommit(currentCommit),
|
||||||
|
LatestCommit: shortCommit(latestCommit),
|
||||||
|
LatestVersion: "dev+" + shortCommit(latestCommit),
|
||||||
|
UpdateAvailable: !commitsEqual(currentCommit, latestCommit),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// StartUpdate starts the official updater using this panel's own channel setting.
|
||||||
func (s *PanelService) StartUpdate() error {
|
func (s *PanelService) StartUpdate() error {
|
||||||
|
return s.startUpdate(devChannelActive())
|
||||||
|
}
|
||||||
|
|
||||||
|
// StartUpdateChannel runs the updater against an explicitly chosen channel,
|
||||||
|
// overriding the local dev-channel setting. Used by the master node updater so
|
||||||
|
// a node can be moved to the dev channel from the central panel.
|
||||||
|
func (s *PanelService) StartUpdateChannel(dev bool) error {
|
||||||
|
return s.startUpdate(dev)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PanelService) startUpdate(useDev bool) error {
|
||||||
if runtime.GOOS != "linux" {
|
if runtime.GOOS != "linux" {
|
||||||
return fmt.Errorf("panel web update is supported only on Linux installations")
|
return fmt.Errorf("panel web update is supported only on Linux installations")
|
||||||
}
|
}
|
||||||
@@ -89,6 +150,10 @@ func (s *PanelService) StartUpdate() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
mainFolder, serviceFolder := resolveUpdateFolders()
|
mainFolder, serviceFolder := resolveUpdateFolders()
|
||||||
|
updateTag := ""
|
||||||
|
if useDev {
|
||||||
|
updateTag = devReleaseTag
|
||||||
|
}
|
||||||
updateScript := fmt.Sprintf("set -e; trap 'rm -f %s' EXIT; %s %s", shellQuote(scriptPath), shellQuote(bash), shellQuote(scriptPath))
|
updateScript := fmt.Sprintf("set -e; trap 'rm -f %s' EXIT; %s %s", shellQuote(scriptPath), shellQuote(bash), shellQuote(scriptPath))
|
||||||
|
|
||||||
if systemdRun, err := exec.LookPath("systemd-run"); err == nil {
|
if systemdRun, err := exec.LookPath("systemd-run"); err == nil {
|
||||||
@@ -97,6 +162,7 @@ func (s *PanelService) StartUpdate() error {
|
|||||||
"--unit", unitName,
|
"--unit", unitName,
|
||||||
"--setenv", "XUI_MAIN_FOLDER="+mainFolder,
|
"--setenv", "XUI_MAIN_FOLDER="+mainFolder,
|
||||||
"--setenv", "XUI_SERVICE="+serviceFolder,
|
"--setenv", "XUI_SERVICE="+serviceFolder,
|
||||||
|
"--setenv", "XUI_UPDATE_TAG="+updateTag,
|
||||||
bash, "-lc", updateScript,
|
bash, "-lc", updateScript,
|
||||||
)
|
)
|
||||||
out, err := cmd.CombinedOutput()
|
out, err := cmd.CombinedOutput()
|
||||||
@@ -118,6 +184,7 @@ func (s *PanelService) StartUpdate() error {
|
|||||||
cmd.Env = append(os.Environ(),
|
cmd.Env = append(os.Environ(),
|
||||||
"XUI_MAIN_FOLDER="+mainFolder,
|
"XUI_MAIN_FOLDER="+mainFolder,
|
||||||
"XUI_SERVICE="+serviceFolder,
|
"XUI_SERVICE="+serviceFolder,
|
||||||
|
"XUI_UPDATE_TAG="+updateTag,
|
||||||
)
|
)
|
||||||
setDetachedProcess(cmd)
|
setDetachedProcess(cmd)
|
||||||
if err := cmd.Start(); err != nil {
|
if err := cmd.Start(); err != nil {
|
||||||
@@ -170,26 +237,88 @@ func downloadPanelUpdater() (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func fetchLatestPanelVersion() (string, error) {
|
func fetchLatestPanelVersion() (string, error) {
|
||||||
client := (&service.SettingService{}).NewProxiedHTTPClient(10 * time.Second)
|
release, err := fetchPanelRelease("")
|
||||||
resp, err := client.Get("https://api.github.com/repos/MHSanaei/3x-ui/releases/latest")
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
|
||||||
return "", fmt.Errorf("GitHub API returned status %d: %s", resp.StatusCode, resp.Status)
|
|
||||||
}
|
|
||||||
|
|
||||||
var release service.Release
|
|
||||||
if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
if release.TagName == "" {
|
if release.TagName == "" {
|
||||||
return "", fmt.Errorf("latest panel release tag is empty")
|
return "", fmt.Errorf("latest panel release tag is empty")
|
||||||
}
|
}
|
||||||
return release.TagName, nil
|
return release.TagName, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// fetchPanelRelease fetches a release from GitHub. An empty tag resolves the
|
||||||
|
// latest stable release; a non-empty tag (e.g. dev-latest) resolves that tag.
|
||||||
|
func fetchPanelRelease(tag string) (*service.Release, error) {
|
||||||
|
url := "https://api.github.com/repos/MHSanaei/3x-ui/releases/latest"
|
||||||
|
if tag != "" {
|
||||||
|
url = "https://api.github.com/repos/MHSanaei/3x-ui/releases/tags/" + tag
|
||||||
|
}
|
||||||
|
client := (&service.SettingService{}).NewProxiedHTTPClient(10 * time.Second)
|
||||||
|
resp, err := client.Get(url)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return nil, fmt.Errorf("GitHub API returned status %d: %s", resp.StatusCode, resp.Status)
|
||||||
|
}
|
||||||
|
|
||||||
|
var release service.Release
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &release, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// extractReleaseCommit reads the build commit recorded in the dev release: first
|
||||||
|
// the `commit=<sha>` marker the CI writes into the body, falling back to the
|
||||||
|
// tag's target commit.
|
||||||
|
func extractReleaseCommit(release *service.Release) string {
|
||||||
|
if m := releaseCommitRegex.FindStringSubmatch(release.Body); m != nil {
|
||||||
|
return strings.ToLower(m[1])
|
||||||
|
}
|
||||||
|
if isCommitSHA(release.TargetCommitish) {
|
||||||
|
return strings.ToLower(release.TargetCommitish)
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func isCommitSHA(s string) bool {
|
||||||
|
s = strings.TrimSpace(s)
|
||||||
|
if len(s) < 7 || len(s) > 40 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, r := range s {
|
||||||
|
if (r < '0' || r > '9') && (r < 'a' || r > 'f') && (r < 'A' || r > 'F') {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func shortCommit(sha string) string {
|
||||||
|
sha = strings.TrimSpace(sha)
|
||||||
|
if len(sha) > 8 {
|
||||||
|
return sha[:8]
|
||||||
|
}
|
||||||
|
return sha
|
||||||
|
}
|
||||||
|
|
||||||
|
// commitsEqual compares a short (injected) commit against a full release commit
|
||||||
|
// by prefix, so an 8-char build stamp matches the 40-char release SHA.
|
||||||
|
func commitsEqual(a, b string) bool {
|
||||||
|
a = strings.ToLower(strings.TrimSpace(a))
|
||||||
|
b = strings.ToLower(strings.TrimSpace(b))
|
||||||
|
if a == "" || b == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if len(a) > len(b) {
|
||||||
|
a, b = b, a
|
||||||
|
}
|
||||||
|
return strings.HasPrefix(b, a)
|
||||||
|
}
|
||||||
|
|
||||||
func resolveUpdateFolders() (string, string) {
|
func resolveUpdateFolders() (string, string) {
|
||||||
mainFolder := os.Getenv("XUI_MAIN_FOLDER")
|
mainFolder := os.Getenv("XUI_MAIN_FOLDER")
|
||||||
if mainFolder == "" {
|
if mainFolder == "" {
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
package panel
|
package panel
|
||||||
|
|
||||||
import "testing"
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
|
||||||
|
)
|
||||||
|
|
||||||
func TestIsNewerVersion(t *testing.T) {
|
func TestIsNewerVersion(t *testing.T) {
|
||||||
cases := []struct {
|
cases := []struct {
|
||||||
@@ -39,3 +43,67 @@ func TestShellQuote(t *testing.T) {
|
|||||||
t.Fatalf("unexpected quote result with single quote: %s", got)
|
t.Fatalf("unexpected quote result with single quote: %s", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestExtractReleaseCommit(t *testing.T) {
|
||||||
|
full := "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b"
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
release service.Release
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "from body marker",
|
||||||
|
release: service.Release{Body: "Rolling build\n\ncommit=" + full + "\nbuilt=2026-06-24T00:00:00Z"},
|
||||||
|
want: full,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "body marker is case-insensitive and wins over target",
|
||||||
|
release: service.Release{Body: "COMMIT=" + full, TargetCommitish: "deadbeef"},
|
||||||
|
want: full,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "fallback to target commit sha",
|
||||||
|
release: service.Release{Body: "no marker here", TargetCommitish: full},
|
||||||
|
want: full,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "branch target is not a commit",
|
||||||
|
release: service.Release{Body: "no marker", TargetCommitish: "main"},
|
||||||
|
want: "",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
if got := extractReleaseCommit(&tc.release); got != tc.want {
|
||||||
|
t.Fatalf("%s: extractReleaseCommit = %q, want %q", tc.name, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCommitsEqual(t *testing.T) {
|
||||||
|
full := "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b"
|
||||||
|
cases := []struct {
|
||||||
|
a, b string
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{"1a2b3c4d", full, true}, // injected 8-char prefix matches full release sha
|
||||||
|
{full, "1a2b3c4d", true}, // order independent
|
||||||
|
{"1A2B3C4D", full, true}, // case insensitive
|
||||||
|
{"deadbeef", full, false}, // different commit
|
||||||
|
{"", full, false}, // empty current never matches
|
||||||
|
{"1a2b3c4d", "", false}, // empty latest never matches
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
if got := commitsEqual(tc.a, tc.b); got != tc.want {
|
||||||
|
t.Fatalf("commitsEqual(%q, %q) = %v, want %v", tc.a, tc.b, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestShortCommit(t *testing.T) {
|
||||||
|
if got := shortCommit("1a2b3c4d5e6f7a8b"); got != "1a2b3c4d" {
|
||||||
|
t.Fatalf("shortCommit truncation = %q, want %q", got, "1a2b3c4d")
|
||||||
|
}
|
||||||
|
if got := shortCommit("abc"); got != "abc" {
|
||||||
|
t.Fatalf("shortCommit short input = %q, want %q", got, "abc")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -117,7 +117,10 @@ type Status struct {
|
|||||||
|
|
||||||
// Release represents information about a software release from GitHub.
|
// Release represents information about a software release from GitHub.
|
||||||
type Release struct {
|
type Release struct {
|
||||||
TagName string `json:"tag_name"` // The tag name of the release
|
TagName string `json:"tag_name"` // The tag name of the release
|
||||||
|
Body string `json:"body"` // The release notes; the dev channel reads its commit from here
|
||||||
|
TargetCommitish string `json:"target_commitish"` // The branch/commit the tag points at
|
||||||
|
Prerelease bool `json:"prerelease"` // Whether this is a pre-release
|
||||||
}
|
}
|
||||||
|
|
||||||
// ServerService provides business logic for server monitoring and management.
|
// ServerService provides business logic for server monitoring and management.
|
||||||
@@ -375,6 +378,53 @@ func getPublicIP(url string) string {
|
|||||||
return ipString
|
return ipString
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var publicIPv4Services = []string{
|
||||||
|
"https://api4.ipify.org",
|
||||||
|
"https://ipv4.icanhazip.com",
|
||||||
|
"https://v4.api.ipinfo.io/ip",
|
||||||
|
"https://ipv4.myexternalip.com/raw",
|
||||||
|
"https://4.ident.me",
|
||||||
|
"https://check-host.net/ip",
|
||||||
|
}
|
||||||
|
|
||||||
|
var publicIPv6Services = []string{
|
||||||
|
"https://api6.ipify.org",
|
||||||
|
"https://ipv6.icanhazip.com",
|
||||||
|
"https://v6.api.ipinfo.io/ip",
|
||||||
|
"https://ipv6.myexternalip.com/raw",
|
||||||
|
"https://6.ident.me",
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolvePublicIPs caches the public IPv4/IPv6 addresses on first use. Guarded
|
||||||
|
// by s.mu because the bot's ServerService may call it from sendBackup while a
|
||||||
|
// status report runs concurrently.
|
||||||
|
func (s *ServerService) resolvePublicIPs() {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
|
||||||
|
if s.cachedIPv4 == "" {
|
||||||
|
for _, ip4Service := range publicIPv4Services {
|
||||||
|
s.cachedIPv4 = getPublicIP(ip4Service)
|
||||||
|
if s.cachedIPv4 != "N/A" {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if s.cachedIPv6 == "" && !s.noIPv6 {
|
||||||
|
for _, ip6Service := range publicIPv6Services {
|
||||||
|
s.cachedIPv6 = getPublicIP(ip6Service)
|
||||||
|
if s.cachedIPv6 != "N/A" {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if s.cachedIPv6 == "N/A" {
|
||||||
|
s.noIPv6 = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (s *ServerService) GetStatus(lastStatus *Status) *Status {
|
func (s *ServerService) GetStatus(lastStatus *Status) *Status {
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
status := &Status{
|
status := &Status{
|
||||||
@@ -536,45 +586,7 @@ func (s *ServerService) GetStatus(lastStatus *Status) *Status {
|
|||||||
logger.Warning("get udp connections failed:", err)
|
logger.Warning("get udp connections failed:", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// IP fetching with caching
|
s.resolvePublicIPs()
|
||||||
showIp4ServiceLists := []string{
|
|
||||||
"https://api4.ipify.org",
|
|
||||||
"https://ipv4.icanhazip.com",
|
|
||||||
"https://v4.api.ipinfo.io/ip",
|
|
||||||
"https://ipv4.myexternalip.com/raw",
|
|
||||||
"https://4.ident.me",
|
|
||||||
"https://check-host.net/ip",
|
|
||||||
}
|
|
||||||
showIp6ServiceLists := []string{
|
|
||||||
"https://api6.ipify.org",
|
|
||||||
"https://ipv6.icanhazip.com",
|
|
||||||
"https://v6.api.ipinfo.io/ip",
|
|
||||||
"https://ipv6.myexternalip.com/raw",
|
|
||||||
"https://6.ident.me",
|
|
||||||
}
|
|
||||||
|
|
||||||
if s.cachedIPv4 == "" {
|
|
||||||
for _, ip4Service := range showIp4ServiceLists {
|
|
||||||
s.cachedIPv4 = getPublicIP(ip4Service)
|
|
||||||
if s.cachedIPv4 != "N/A" {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if s.cachedIPv6 == "" && !s.noIPv6 {
|
|
||||||
for _, ip6Service := range showIp6ServiceLists {
|
|
||||||
s.cachedIPv6 = getPublicIP(ip6Service)
|
|
||||||
if s.cachedIPv6 != "N/A" {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if s.cachedIPv6 == "N/A" {
|
|
||||||
s.noIPv6 = true
|
|
||||||
}
|
|
||||||
|
|
||||||
status.PublicIP.IPv4 = s.cachedIPv4
|
status.PublicIP.IPv4 = s.cachedIPv4
|
||||||
status.PublicIP.IPv6 = s.cachedIPv6
|
status.PublicIP.IPv6 = s.cachedIPv6
|
||||||
|
|
||||||
@@ -592,7 +604,7 @@ func (s *ServerService) GetStatus(lastStatus *Status) *Status {
|
|||||||
status.Xray.ErrorMsg = s.xrayService.GetXrayResult()
|
status.Xray.ErrorMsg = s.xrayService.GetXrayResult()
|
||||||
}
|
}
|
||||||
status.Xray.Version = s.xrayService.GetXrayVersion()
|
status.Xray.Version = s.xrayService.GetXrayVersion()
|
||||||
status.PanelVersion = config.GetVersion()
|
status.PanelVersion = config.GetReportedVersion()
|
||||||
if guid, err := s.settingService.GetPanelGuid(); err == nil {
|
if guid, err := s.settingService.GetPanelGuid(); err == nil {
|
||||||
status.PanelGuid = guid
|
status.PanelGuid = guid
|
||||||
}
|
}
|
||||||
@@ -1282,11 +1294,12 @@ func (s *ServerService) GetDb() ([]byte, error) {
|
|||||||
|
|
||||||
// BackupFilename returns the filename for a database backup, named after the
|
// BackupFilename returns the filename for a database backup, named after the
|
||||||
// panel's address so a downloaded or Telegram-sent backup identifies the server
|
// panel's address so a downloaded or Telegram-sent backup identifies the server
|
||||||
// it came from. requestHost is the browser's address (the getDb handler passes
|
// it came from. requestHost is the browser's address: the getDb handler passes
|
||||||
// c.Request.Host, matching the host shown in the panel title); it is preferred
|
// c.Request.Host so a panel download is named after whatever address the user
|
||||||
// when present, otherwise the configured web domain and then the server's public
|
// reached the panel with, no Listen Domain needed. The Telegram bot has no
|
||||||
// IP are used. The extension is .dump on PostgreSQL and .db on SQLite; the base
|
// request and passes "", falling back to the configured Listen Domain (webDomain)
|
||||||
// falls back to "x-ui" when no address is known.
|
// and then the public IP. The extension is .dump on PostgreSQL and .db on SQLite;
|
||||||
|
// the base falls back to "x-ui" when no address is known.
|
||||||
func (s *ServerService) BackupFilename(requestHost string) string {
|
func (s *ServerService) BackupFilename(requestHost string) string {
|
||||||
ext := ".db"
|
ext := ".db"
|
||||||
if database.IsPostgres() {
|
if database.IsPostgres() {
|
||||||
@@ -1296,9 +1309,12 @@ func (s *ServerService) BackupFilename(requestHost string) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// backupHost picks the address used to name backup files: the browser's request
|
// backupHost picks the address used to name backup files: the browser's request
|
||||||
// host (port stripped, the same value the panel title shows) when available,
|
// host (port stripped) when available, otherwise the configured Listen Domain
|
||||||
// otherwise the configured web domain and then the cached public IP (IPv4 before
|
// (webDomain) and then the resolved public IP (IPv4 before IPv6), reduced to safe
|
||||||
// IPv6), reduced to safe filename characters.
|
// filename characters. The public IP is resolved directly rather than read from
|
||||||
|
// LastStatus so callers whose ServerService never runs the status ticker —
|
||||||
|
// notably the Telegram bot — still get a real address instead of the "x-ui"
|
||||||
|
// fallback.
|
||||||
func (s *ServerService) backupHost(requestHost string) string {
|
func (s *ServerService) backupHost(requestHost string) string {
|
||||||
host := extractHostname(strings.TrimSpace(requestHost))
|
host := extractHostname(strings.TrimSpace(requestHost))
|
||||||
if host == "" {
|
if host == "" {
|
||||||
@@ -1307,12 +1323,11 @@ func (s *ServerService) backupHost(requestHost string) string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if host == "" {
|
if host == "" {
|
||||||
if st := s.LastStatus(); st != nil {
|
s.resolvePublicIPs()
|
||||||
if ip := st.PublicIP.IPv4; ip != "" && ip != "N/A" {
|
if ip := s.cachedIPv4; ip != "" && ip != "N/A" {
|
||||||
host = ip
|
host = ip
|
||||||
} else if ip := st.PublicIP.IPv6; ip != "" && ip != "N/A" {
|
} else if ip := s.cachedIPv6; ip != "" && ip != "N/A" {
|
||||||
host = ip
|
host = ip
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return sanitizeBackupHost(host)
|
return sanitizeBackupHost(host)
|
||||||
@@ -2049,11 +2064,34 @@ func (s *ServerService) GetNewVlessEnc() (any, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
auths := parseVlessEncAuths(out.String())
|
||||||
|
auths = append(auths, deriveVlessEncModes(auths)...)
|
||||||
|
|
||||||
return map[string]any{
|
return map[string]any{
|
||||||
"auths": parseVlessEncAuths(out.String()),
|
"auths": auths,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func deriveVlessEncModes(auths []map[string]string) []map[string]string {
|
||||||
|
var extra []map[string]string
|
||||||
|
for _, a := range auths {
|
||||||
|
for _, mode := range []string{"xorpub", "random"} {
|
||||||
|
dec := strings.Replace(a["decryption"], ".native.", "."+mode+".", 1)
|
||||||
|
enc := strings.Replace(a["encryption"], ".native.", "."+mode+".", 1)
|
||||||
|
if dec == a["decryption"] && enc == a["encryption"] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
extra = append(extra, map[string]string{
|
||||||
|
"id": a["id"] + "_" + mode,
|
||||||
|
"label": a["label"] + " (" + mode + ")",
|
||||||
|
"decryption": dec,
|
||||||
|
"encryption": enc,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return extra
|
||||||
|
}
|
||||||
|
|
||||||
func parseVlessEncAuths(output string) []map[string]string {
|
func parseVlessEncAuths(output string) []map[string]string {
|
||||||
lines := strings.Split(output, "\n")
|
lines := strings.Split(output, "\n")
|
||||||
var auths []map[string]string
|
var auths []map[string]string
|
||||||
|
|||||||
@@ -80,3 +80,31 @@ Authentication: X25519, not Post-Quantum
|
|||||||
t.Fatalf("encryption = %q, want client", auths[0]["encryption"])
|
t.Fatalf("encryption = %q, want client", auths[0]["encryption"])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestDeriveVlessEncModes(t *testing.T) {
|
||||||
|
base := []map[string]string{
|
||||||
|
{
|
||||||
|
"id": "x25519",
|
||||||
|
"label": "X25519, not Post-Quantum",
|
||||||
|
"decryption": "mlkem768x25519plus.native.600s.server-key",
|
||||||
|
"encryption": "mlkem768x25519plus.native.0rtt.client-key",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
derived := deriveVlessEncModes(base)
|
||||||
|
if len(derived) != 2 {
|
||||||
|
t.Fatalf("expected 2 derived blocks, got %d", len(derived))
|
||||||
|
}
|
||||||
|
if derived[0]["id"] != "x25519_xorpub" {
|
||||||
|
t.Errorf("id = %q, want x25519_xorpub", derived[0]["id"])
|
||||||
|
}
|
||||||
|
if derived[0]["decryption"] != "mlkem768x25519plus.xorpub.600s.server-key" {
|
||||||
|
t.Errorf("decryption = %q", derived[0]["decryption"])
|
||||||
|
}
|
||||||
|
if derived[0]["encryption"] != "mlkem768x25519plus.xorpub.0rtt.client-key" {
|
||||||
|
t.Errorf("encryption = %q", derived[0]["encryption"])
|
||||||
|
}
|
||||||
|
if derived[1]["id"] != "x25519_random" {
|
||||||
|
t.Errorf("id = %q, want x25519_random", derived[1]["id"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
|
"github.com/mhsanaei/3x-ui/v3/internal/config"
|
||||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||||
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||||
@@ -55,7 +56,7 @@ var defaultValueMap = map[string]string{
|
|||||||
"pageSize": "25",
|
"pageSize": "25",
|
||||||
"expireDiff": "0",
|
"expireDiff": "0",
|
||||||
"trafficDiff": "0",
|
"trafficDiff": "0",
|
||||||
"remarkTemplate": "{{INBOUND}}|📊{{TRAFFIC_LEFT}}|⏳{{DAYS_LEFT}}D",
|
"remarkTemplate": "{{INBOUND}}-{{EMAIL}}|📊{{TRAFFIC_LEFT}}|⏳{{DAYS_LEFT}}D",
|
||||||
"timeLocation": "Local",
|
"timeLocation": "Local",
|
||||||
"tgBotEnable": "false",
|
"tgBotEnable": "false",
|
||||||
"tgBotToken": "",
|
"tgBotToken": "",
|
||||||
@@ -78,6 +79,8 @@ var defaultValueMap = map[string]string{
|
|||||||
"subEnableRouting": "false",
|
"subEnableRouting": "false",
|
||||||
"subRoutingRules": "",
|
"subRoutingRules": "",
|
||||||
"subHideSettings": "false",
|
"subHideSettings": "false",
|
||||||
|
"subIncyEnableRouting": "false",
|
||||||
|
"subIncyRoutingRules": "",
|
||||||
"subListen": "",
|
"subListen": "",
|
||||||
"subPort": "2096",
|
"subPort": "2096",
|
||||||
"subPath": "/sub/",
|
"subPath": "/sub/",
|
||||||
@@ -107,6 +110,7 @@ var defaultValueMap = map[string]string{
|
|||||||
"restartXrayOnClientDisable": "true",
|
"restartXrayOnClientDisable": "true",
|
||||||
"xrayOutboundTestUrl": "https://www.google.com/generate_204",
|
"xrayOutboundTestUrl": "https://www.google.com/generate_204",
|
||||||
"panelOutbound": "",
|
"panelOutbound": "",
|
||||||
|
"devChannelEnable": "false",
|
||||||
|
|
||||||
// LDAP defaults
|
// LDAP defaults
|
||||||
"ldapEnable": "false",
|
"ldapEnable": "false",
|
||||||
@@ -709,6 +713,14 @@ func (s *SettingService) GetSubHideSettings() (bool, error) {
|
|||||||
return s.getBool("subHideSettings")
|
return s.getBool("subHideSettings")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *SettingService) GetSubIncyEnableRouting() (bool, error) {
|
||||||
|
return s.getBool("subIncyEnableRouting")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SettingService) GetSubIncyRoutingRules() (string, error) {
|
||||||
|
return s.getString("subIncyRoutingRules")
|
||||||
|
}
|
||||||
|
|
||||||
func (s *SettingService) GetSubListen() (string, error) {
|
func (s *SettingService) GetSubListen() (string, error) {
|
||||||
return s.getString("subListen")
|
return s.getString("subListen")
|
||||||
}
|
}
|
||||||
@@ -845,6 +857,16 @@ func (s *SettingService) SetRestartXrayOnClientDisable(value bool) error {
|
|||||||
return s.setBool("restartXrayOnClientDisable", value)
|
return s.setBool("restartXrayOnClientDisable", value)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetDevChannelEnable reports whether the panel self-update tracks the rolling
|
||||||
|
// per-commit dev release instead of the latest stable tag.
|
||||||
|
func (s *SettingService) GetDevChannelEnable() (bool, error) {
|
||||||
|
return s.getBool("devChannelEnable")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SettingService) SetDevChannelEnable(value bool) error {
|
||||||
|
return s.setBool("devChannelEnable", value)
|
||||||
|
}
|
||||||
|
|
||||||
// GetIpLimitEnable reports whether the IP-limit feature is available. Always
|
// GetIpLimitEnable reports whether the IP-limit feature is available. Always
|
||||||
// true since the panel enforces limits via the core's online-stats API; on an
|
// true since the panel enforces limits via the core's online-stats API; on an
|
||||||
// older core the job falls back to access-log parsing and warns there when the
|
// older core the job falls back to access-log parsing and warns there when the
|
||||||
@@ -1199,25 +1221,27 @@ func (s *SettingService) BuildSubURIBase(host string) string {
|
|||||||
func (s *SettingService) GetDefaultSettings(host string) (any, error) {
|
func (s *SettingService) GetDefaultSettings(host string) (any, error) {
|
||||||
type settingFunc func() (any, error)
|
type settingFunc func() (any, error)
|
||||||
settings := map[string]settingFunc{
|
settings := map[string]settingFunc{
|
||||||
"expireDiff": func() (any, error) { return s.GetExpireDiff() },
|
"expireDiff": func() (any, error) { return s.GetExpireDiff() },
|
||||||
"trafficDiff": func() (any, error) { return s.GetTrafficDiff() },
|
"trafficDiff": func() (any, error) { return s.GetTrafficDiff() },
|
||||||
"pageSize": func() (any, error) { return s.GetPageSize() },
|
"pageSize": func() (any, error) { return s.GetPageSize() },
|
||||||
"defaultCert": func() (any, error) { return s.GetCertFile() },
|
"defaultCert": func() (any, error) { return s.GetCertFile() },
|
||||||
"defaultKey": func() (any, error) { return s.GetKeyFile() },
|
"defaultKey": func() (any, error) { return s.GetKeyFile() },
|
||||||
"tgBotEnable": func() (any, error) { return s.GetTgbotEnabled() },
|
"tgBotEnable": func() (any, error) { return s.GetTgbotEnabled() },
|
||||||
"subThemeDir": func() (any, error) { return s.GetSubThemeDir() },
|
"subThemeDir": func() (any, error) { return s.GetSubThemeDir() },
|
||||||
"subEnable": func() (any, error) { return s.GetSubEnable() },
|
"subEnable": func() (any, error) { return s.GetSubEnable() },
|
||||||
"subJsonEnable": func() (any, error) { return s.GetSubJsonEnable() },
|
"subJsonEnable": func() (any, error) { return s.GetSubJsonEnable() },
|
||||||
"subClashEnable": func() (any, error) { return s.GetSubClashEnable() },
|
"subClashEnable": func() (any, error) { return s.GetSubClashEnable() },
|
||||||
"subTitle": func() (any, error) { return s.GetSubTitle() },
|
"subTitle": func() (any, error) { return s.GetSubTitle() },
|
||||||
"subURI": func() (any, error) { return s.GetSubURI() },
|
"subURI": func() (any, error) { return s.GetSubURI() },
|
||||||
"subJsonURI": func() (any, error) { return s.GetSubJsonURI() },
|
"subJsonURI": func() (any, error) { return s.GetSubJsonURI() },
|
||||||
"subClashURI": func() (any, error) { return s.GetSubClashURI() },
|
"subClashURI": func() (any, error) { return s.GetSubClashURI() },
|
||||||
"datepicker": func() (any, error) { return s.GetDatepicker() },
|
"datepicker": func() (any, error) { return s.GetDatepicker() },
|
||||||
"ipLimitEnable": func() (any, error) { return s.GetIpLimitEnable() },
|
"ipLimitEnable": func() (any, error) { return s.GetIpLimitEnable() },
|
||||||
"accessLogEnable": func() (any, error) { return s.GetAccessLogEnable() },
|
"accessLogEnable": func() (any, error) { return s.GetAccessLogEnable() },
|
||||||
"webDomain": func() (any, error) { return s.GetWebDomain() },
|
"webDomain": func() (any, error) { return s.GetWebDomain() },
|
||||||
"subDomain": func() (any, error) { return s.GetSubDomain() },
|
"subDomain": func() (any, error) { return s.GetSubDomain() },
|
||||||
|
"devChannelEnable": func() (any, error) { return s.GetDevChannelEnable() },
|
||||||
|
"isDevBuild": func() (any, error) { return config.IsDevBuild(), nil },
|
||||||
}
|
}
|
||||||
|
|
||||||
result := make(map[string]any)
|
result := make(map[string]any)
|
||||||
|
|||||||
@@ -346,7 +346,7 @@ func TestBulkOpsPostgresScale(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
t0 := time.Now()
|
t0 := time.Now()
|
||||||
if _, _, err := svc.BulkAdjust(inboundSvc, emailsM, 7, 1<<30); err != nil {
|
if _, _, err := svc.BulkAdjust(inboundSvc, emailsM, 7, 1<<30, ""); err != nil {
|
||||||
t.Fatalf("BulkAdjust: %v", err)
|
t.Fatalf("BulkAdjust: %v", err)
|
||||||
}
|
}
|
||||||
adjustDur := time.Since(t0)
|
adjustDur := time.Since(t0)
|
||||||
|
|||||||
@@ -153,6 +153,11 @@
|
|||||||
"currentPanelVersion": "إصدار البانل الحالي",
|
"currentPanelVersion": "إصدار البانل الحالي",
|
||||||
"latestPanelVersion": "أحدث إصدار للبانل",
|
"latestPanelVersion": "أحدث إصدار للبانل",
|
||||||
"panelUpToDate": "البانل محدث لآخر إصدار",
|
"panelUpToDate": "البانل محدث لآخر إصدار",
|
||||||
|
"devChannel": "قناة التطوير",
|
||||||
|
"devChannelWarning": "تتابع نسخ التطوير كل كومِت على main وليست إصدارات مستقرة — لا يوجد رجوع تلقائي لإصدار أقدم.",
|
||||||
|
"currentCommit": "الكومِت الحالي",
|
||||||
|
"latestCommit": "أحدث كومِت",
|
||||||
|
"updateChannelChanged": "تم تغيير قناة التحديث",
|
||||||
"upToDate": "محدث",
|
"upToDate": "محدث",
|
||||||
"xrayStatusUnknown": "مش معروف",
|
"xrayStatusUnknown": "مش معروف",
|
||||||
"xrayStatusRunning": "شغالة",
|
"xrayStatusRunning": "شغالة",
|
||||||
@@ -402,10 +407,16 @@
|
|||||||
"sniffingDomainsExcluded": "النطاقات المستثناة",
|
"sniffingDomainsExcluded": "النطاقات المستثناة",
|
||||||
"decryption": "فك التشفير",
|
"decryption": "فك التشفير",
|
||||||
"encryption": "التشفير",
|
"encryption": "التشفير",
|
||||||
"vlessAuthX25519": "مصادقة X25519",
|
"vlessAuthX25519": "X25519 (native)",
|
||||||
"vlessAuthMlkem768": "مصادقة ML-KEM-768",
|
"vlessAuthMlkem768": "ML-KEM-768 (native)",
|
||||||
|
"vlessAuthX25519Xorpub": "X25519 (xorpub)",
|
||||||
|
"vlessAuthX25519Random": "X25519 (random)",
|
||||||
|
"vlessAuthMlkem768Xorpub": "ML-KEM-768 (xorpub)",
|
||||||
|
"vlessAuthMlkem768Random": "ML-KEM-768 (random)",
|
||||||
"vlessAuthCustom": "مخصص",
|
"vlessAuthCustom": "مخصص",
|
||||||
"vlessAuthSelected": "المحدد: {auth}",
|
"vlessAuthSelected": "المحدد: {auth}",
|
||||||
|
"vlessAuthGenerate": "إنشاء المفاتيح",
|
||||||
|
"vlessAuthGenerateButton": "إنشاء",
|
||||||
"advanced": {
|
"advanced": {
|
||||||
"title": "أقسام JSON للاتصال الوارد",
|
"title": "أقسام JSON للاتصال الوارد",
|
||||||
"subtitle": "JSON الكامل للاتصال الوارد ومحررات مخصصة لـ settings و sniffing و streamSettings.",
|
"subtitle": "JSON الكامل للاتصال الوارد ومحررات مخصصة لـ settings و sniffing و streamSettings.",
|
||||||
@@ -968,6 +979,7 @@
|
|||||||
"upToDate": "محدّث",
|
"upToDate": "محدّث",
|
||||||
"updateConfirmTitle": "تحديث {count} عقدة إلى أحدث إصدار؟",
|
"updateConfirmTitle": "تحديث {count} عقدة إلى أحدث إصدار؟",
|
||||||
"updateConfirmContent": "كل عقدة محددة ستنزّل أحدث إصدار وتعيد التشغيل عليه. يتم تحديث العقد المفعّلة والمتصلة فقط.",
|
"updateConfirmContent": "كل عقدة محددة ستنزّل أحدث إصدار وتعيد التشغيل عليه. يتم تحديث العقد المفعّلة والمتصلة فقط.",
|
||||||
|
"updateDevChannel": "التحديث إلى قناة التطوير (أحدث كومِت)",
|
||||||
"testConnection": "اختبار الاتصال",
|
"testConnection": "اختبار الاتصال",
|
||||||
"connectionOk": "الاتصال شغال ({ms} ms)",
|
"connectionOk": "الاتصال شغال ({ms} ms)",
|
||||||
"connectionFailed": "فشل الاتصال",
|
"connectionFailed": "فشل الاتصال",
|
||||||
@@ -1130,6 +1142,10 @@
|
|||||||
"subRoutingRulesDesc": "قواعد التوجيه العامة لعميل VPN. (فقط لـ Happ)",
|
"subRoutingRulesDesc": "قواعد التوجيه العامة لعميل VPN. (فقط لـ Happ)",
|
||||||
"subHideSettings": "إخفاء إعدادات الخادم",
|
"subHideSettings": "إخفاء إعدادات الخادم",
|
||||||
"subHideSettingsDesc": "إخفاء إمكانية عرض وتعديل إعدادات الخادم في عميل VPN. (فقط لـ Happ)",
|
"subHideSettingsDesc": "إخفاء إمكانية عرض وتعديل إعدادات الخادم في عميل VPN. (فقط لـ Happ)",
|
||||||
|
"subIncyEnableRouting": "تفعيل التوجيه",
|
||||||
|
"subIncyEnableRoutingDesc": "حقن ملف تعريف التوجيه في محتوى الاشتراك لعميل Incy. (فقط لـ Incy)",
|
||||||
|
"subIncyRoutingRules": "قواعد التوجيه",
|
||||||
|
"subIncyRoutingRulesDesc": "رابط توجيه Incy المُضاف إلى محتوى الاشتراك، مثل incy://routing/onadd/<base64>. (فقط لـ Incy)",
|
||||||
"subClashEnableRouting": "تفعيل التوجيه",
|
"subClashEnableRouting": "تفعيل التوجيه",
|
||||||
"subClashEnableRoutingDesc": "تضمين قواعد توجيه Clash/Mihomo العامة في اشتراكات YAML المُنشأة.",
|
"subClashEnableRoutingDesc": "تضمين قواعد توجيه Clash/Mihomo العامة في اشتراكات YAML المُنشأة.",
|
||||||
"subClashRoutingRules": "قواعد التوجيه العامة",
|
"subClashRoutingRules": "قواعد التوجيه العامة",
|
||||||
@@ -1806,7 +1822,8 @@
|
|||||||
"groups": {
|
"groups": {
|
||||||
"client": "العميل",
|
"client": "العميل",
|
||||||
"traffic": "حركة المرور",
|
"traffic": "حركة المرور",
|
||||||
"time": "الوقت والحالة"
|
"time": "الوقت والحالة",
|
||||||
|
"connection": "الاتصال"
|
||||||
},
|
},
|
||||||
"descEMAIL": "بريد العميل",
|
"descEMAIL": "بريد العميل",
|
||||||
"descINBOUND": "ملاحظة الوارد نفسه (اسم الإعداد)",
|
"descINBOUND": "ملاحظة الوارد نفسه (اسم الإعداد)",
|
||||||
@@ -1825,11 +1842,18 @@
|
|||||||
"descUP": "حركة مرور الرفع",
|
"descUP": "حركة مرور الرفع",
|
||||||
"descDOWN": "حركة مرور التنزيل",
|
"descDOWN": "حركة مرور التنزيل",
|
||||||
"descSTATUS": "نشط / منتهٍ / معطّل / مستنفد",
|
"descSTATUS": "نشط / منتهٍ / معطّل / مستنفد",
|
||||||
|
"descSTATUS_EMOJI": "الحالة كرمز تعبيري (✅ ⏳ 🚫)",
|
||||||
"descDAYS_LEFT": "الأيام حتى الانتهاء (مخفية إذا كانت غير محدودة)",
|
"descDAYS_LEFT": "الأيام حتى الانتهاء (مخفية إذا كانت غير محدودة)",
|
||||||
|
"descTIME_LEFT": "الوقت المتبقي (مثال: 12d 4h 30m)",
|
||||||
|
"descUSAGE_PERCENTAGE": "حركة المرور المستخدمة كنسبة مئوية (مخفية إذا كانت غير محدودة)",
|
||||||
"descEXPIRE_DATE": "تاريخ الانتهاء (YYYY-MM-DD)",
|
"descEXPIRE_DATE": "تاريخ الانتهاء (YYYY-MM-DD)",
|
||||||
|
"descJALALI_EXPIRE_DATE": "تاريخ الانتهاء بالتقويم الجلالي (YYYY/MM/DD)",
|
||||||
"descEXPIRE_UNIX": "الانتهاء كطابع زمني Unix (بالثواني)",
|
"descEXPIRE_UNIX": "الانتهاء كطابع زمني Unix (بالثواني)",
|
||||||
"descCREATED_UNIX": "وقت الإنشاء كطابع زمني Unix (بالثواني)",
|
"descCREATED_UNIX": "وقت الإنشاء كطابع زمني Unix (بالثواني)",
|
||||||
"descRESET_DAYS": "فترة إعادة تعيين حركة المرور بالأيام"
|
"descRESET_DAYS": "فترة إعادة تعيين حركة المرور بالأيام",
|
||||||
|
"descPROTOCOL": "بروتوكول الوارد (VLESS، VMess، Trojan، …)",
|
||||||
|
"descTRANSPORT": "شبكة النقل (tcp، ws، grpc، …)",
|
||||||
|
"descSECURITY": "أمان النقل (TLS، REALITY، NONE)"
|
||||||
},
|
},
|
||||||
"toasts": {
|
"toasts": {
|
||||||
"list": "فشل تحميل المضيفات",
|
"list": "فشل تحميل المضيفات",
|
||||||
@@ -2062,4 +2086,4 @@
|
|||||||
"statusDown": "غير متصل",
|
"statusDown": "غير متصل",
|
||||||
"statusUp": "متصل"
|
"statusUp": "متصل"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -153,6 +153,11 @@
|
|||||||
"currentPanelVersion": "Current panel version",
|
"currentPanelVersion": "Current panel version",
|
||||||
"latestPanelVersion": "Latest panel version",
|
"latestPanelVersion": "Latest panel version",
|
||||||
"panelUpToDate": "Panel is up to date",
|
"panelUpToDate": "Panel is up to date",
|
||||||
|
"devChannel": "Dev channel",
|
||||||
|
"devChannelWarning": "Dev builds track every commit on main and aren't stable releases — there is no automatic downgrade.",
|
||||||
|
"currentCommit": "Current commit",
|
||||||
|
"latestCommit": "Latest commit",
|
||||||
|
"updateChannelChanged": "Update channel changed",
|
||||||
"upToDate": "Up to date",
|
"upToDate": "Up to date",
|
||||||
"xrayStatusUnknown": "Unknown",
|
"xrayStatusUnknown": "Unknown",
|
||||||
"xrayStatusRunning": "Running",
|
"xrayStatusRunning": "Running",
|
||||||
@@ -402,10 +407,16 @@
|
|||||||
"sniffingDomainsExcluded": "Domains excluded",
|
"sniffingDomainsExcluded": "Domains excluded",
|
||||||
"decryption": "Decryption",
|
"decryption": "Decryption",
|
||||||
"encryption": "Encryption",
|
"encryption": "Encryption",
|
||||||
"vlessAuthX25519": "X25519 auth",
|
"vlessAuthX25519": "X25519 (native)",
|
||||||
"vlessAuthMlkem768": "ML-KEM-768 auth",
|
"vlessAuthMlkem768": "ML-KEM-768 (native)",
|
||||||
|
"vlessAuthX25519Xorpub": "X25519 (xorpub)",
|
||||||
|
"vlessAuthX25519Random": "X25519 (random)",
|
||||||
|
"vlessAuthMlkem768Xorpub": "ML-KEM-768 (xorpub)",
|
||||||
|
"vlessAuthMlkem768Random": "ML-KEM-768 (random)",
|
||||||
"vlessAuthCustom": "Custom",
|
"vlessAuthCustom": "Custom",
|
||||||
"vlessAuthSelected": "Selected: {auth}",
|
"vlessAuthSelected": "Selected: {auth}",
|
||||||
|
"vlessAuthGenerate": "Generate keys",
|
||||||
|
"vlessAuthGenerateButton": "Generate",
|
||||||
"advanced": {
|
"advanced": {
|
||||||
"title": "Inbound JSON sections",
|
"title": "Inbound JSON sections",
|
||||||
"subtitle": "Full inbound JSON and focused editors for settings, sniffing, and streamSettings.",
|
"subtitle": "Full inbound JSON and focused editors for settings, sniffing, and streamSettings.",
|
||||||
@@ -831,9 +842,12 @@
|
|||||||
"bulkDeleteConfirmContent": "Each selected client is removed from every attached inbound and its traffic record is dropped. This cannot be undone.",
|
"bulkDeleteConfirmContent": "Each selected client is removed from every attached inbound and its traffic record is dropped. This cannot be undone.",
|
||||||
"bulkAdjustTitle": "Adjust {count} clients",
|
"bulkAdjustTitle": "Adjust {count} clients",
|
||||||
"bulkAdjustHint": "Positive values extend, negative values reduce. Clients with unlimited expiry or traffic are skipped for that field.",
|
"bulkAdjustHint": "Positive values extend, negative values reduce. Clients with unlimited expiry or traffic are skipped for that field.",
|
||||||
"bulkAdjustNothing": "Set days or traffic before applying.",
|
"bulkAdjustNothing": "Set days, traffic, or flow before applying.",
|
||||||
"addDays": "Add days",
|
"addDays": "Add days",
|
||||||
"addTrafficGB": "Add traffic (GB)",
|
"addTrafficGB": "Add traffic (GB)",
|
||||||
|
"bulkFlow": "Set flow",
|
||||||
|
"bulkFlowNoChange": "No change",
|
||||||
|
"bulkFlowDisable": "Disable (clear flow)",
|
||||||
"delDepleted": "Delete depleted",
|
"delDepleted": "Delete depleted",
|
||||||
"delDepletedConfirmTitle": "Delete depleted clients?",
|
"delDepletedConfirmTitle": "Delete depleted clients?",
|
||||||
"delDepletedConfirmContent": "Removes every client whose traffic quota is exhausted or whose expiry has passed. This cannot be undone.",
|
"delDepletedConfirmContent": "Removes every client whose traffic quota is exhausted or whose expiry has passed. This cannot be undone.",
|
||||||
@@ -986,7 +1000,8 @@
|
|||||||
"groups": {
|
"groups": {
|
||||||
"client": "Client",
|
"client": "Client",
|
||||||
"traffic": "Traffic",
|
"traffic": "Traffic",
|
||||||
"time": "Time & status"
|
"time": "Time & status",
|
||||||
|
"connection": "Connection"
|
||||||
},
|
},
|
||||||
"descEMAIL": "Client email",
|
"descEMAIL": "Client email",
|
||||||
"descINBOUND": "Inbound's own remark (the config name)",
|
"descINBOUND": "Inbound's own remark (the config name)",
|
||||||
@@ -1005,11 +1020,18 @@
|
|||||||
"descUP": "Upload traffic",
|
"descUP": "Upload traffic",
|
||||||
"descDOWN": "Download traffic",
|
"descDOWN": "Download traffic",
|
||||||
"descSTATUS": "active / expired / disabled / depleted",
|
"descSTATUS": "active / expired / disabled / depleted",
|
||||||
|
"descSTATUS_EMOJI": "Status as an emoji (✅ ⏳ 🚫)",
|
||||||
"descDAYS_LEFT": "Days until expiry (hidden if unlimited)",
|
"descDAYS_LEFT": "Days until expiry (hidden if unlimited)",
|
||||||
|
"descTIME_LEFT": "Remaining time (e.g. 12d 4h 30m)",
|
||||||
|
"descUSAGE_PERCENTAGE": "Used traffic as a percentage (hidden if unlimited)",
|
||||||
"descEXPIRE_DATE": "Expiry date (YYYY-MM-DD)",
|
"descEXPIRE_DATE": "Expiry date (YYYY-MM-DD)",
|
||||||
|
"descJALALI_EXPIRE_DATE": "Expiry date in the Jalali calendar (YYYY/MM/DD)",
|
||||||
"descEXPIRE_UNIX": "Expiry as a Unix timestamp (seconds)",
|
"descEXPIRE_UNIX": "Expiry as a Unix timestamp (seconds)",
|
||||||
"descCREATED_UNIX": "Creation time as a Unix timestamp (seconds)",
|
"descCREATED_UNIX": "Creation time as a Unix timestamp (seconds)",
|
||||||
"descRESET_DAYS": "Traffic reset period in days"
|
"descRESET_DAYS": "Traffic reset period in days",
|
||||||
|
"descPROTOCOL": "Inbound protocol (VLESS, VMess, Trojan, …)",
|
||||||
|
"descTRANSPORT": "Transport network (tcp, ws, grpc, …)",
|
||||||
|
"descSECURITY": "Transport security (TLS, REALITY, NONE)"
|
||||||
},
|
},
|
||||||
"toasts": {
|
"toasts": {
|
||||||
"list": "Failed to load hosts",
|
"list": "Failed to load hosts",
|
||||||
@@ -1076,6 +1098,7 @@
|
|||||||
"upToDate": "Up to date",
|
"upToDate": "Up to date",
|
||||||
"updateConfirmTitle": "Update {count} node(s) to the latest version?",
|
"updateConfirmTitle": "Update {count} node(s) to the latest version?",
|
||||||
"updateConfirmContent": "Each selected node downloads the latest release and restarts onto it. Only enabled, online nodes are updated.",
|
"updateConfirmContent": "Each selected node downloads the latest release and restarts onto it. Only enabled, online nodes are updated.",
|
||||||
|
"updateDevChannel": "Update to Dev channel (latest commit)",
|
||||||
"testConnection": "Test Connection",
|
"testConnection": "Test Connection",
|
||||||
"connectionOk": "Connection OK ({ms} ms)",
|
"connectionOk": "Connection OK ({ms} ms)",
|
||||||
"connectionFailed": "Connection failed",
|
"connectionFailed": "Connection failed",
|
||||||
@@ -1240,6 +1263,10 @@
|
|||||||
"subRoutingRulesDesc": "Global routing rules for the VPN client. (Only for Happ)",
|
"subRoutingRulesDesc": "Global routing rules for the VPN client. (Only for Happ)",
|
||||||
"subHideSettings": "Hide server settings",
|
"subHideSettings": "Hide server settings",
|
||||||
"subHideSettingsDesc": "Hide the ability to view and edit server configurations in the VPN client. (Only for Happ)",
|
"subHideSettingsDesc": "Hide the ability to view and edit server configurations in the VPN client. (Only for Happ)",
|
||||||
|
"subIncyEnableRouting": "Enable routing",
|
||||||
|
"subIncyEnableRoutingDesc": "Inject a routing profile into the subscription body for the Incy client. (Only for Incy)",
|
||||||
|
"subIncyRoutingRules": "Routing rules",
|
||||||
|
"subIncyRoutingRulesDesc": "Incy routing deep-link added to the subscription body, e.g. incy://routing/onadd/<base64>. (Only for Incy)",
|
||||||
"subClashEnableRouting": "Enable routing",
|
"subClashEnableRouting": "Enable routing",
|
||||||
"subClashEnableRoutingDesc": "Include global Clash/Mihomo routing rules in generated YAML subscriptions.",
|
"subClashEnableRoutingDesc": "Include global Clash/Mihomo routing rules in generated YAML subscriptions.",
|
||||||
"subClashRoutingRules": "Global routing rules",
|
"subClashRoutingRules": "Global routing rules",
|
||||||
@@ -2062,4 +2089,4 @@
|
|||||||
"statusDown": "DOWN",
|
"statusDown": "DOWN",
|
||||||
"statusUp": "UP"
|
"statusUp": "UP"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -153,6 +153,11 @@
|
|||||||
"currentPanelVersion": "Versión actual del panel",
|
"currentPanelVersion": "Versión actual del panel",
|
||||||
"latestPanelVersion": "Última versión del panel",
|
"latestPanelVersion": "Última versión del panel",
|
||||||
"panelUpToDate": "El panel está actualizado",
|
"panelUpToDate": "El panel está actualizado",
|
||||||
|
"devChannel": "Canal de desarrollo",
|
||||||
|
"devChannelWarning": "Las compilaciones de desarrollo siguen cada commit en main y no son versiones estables; no hay reversión automática.",
|
||||||
|
"currentCommit": "Commit actual",
|
||||||
|
"latestCommit": "Último commit",
|
||||||
|
"updateChannelChanged": "Canal de actualización cambiado",
|
||||||
"upToDate": "Actualizado",
|
"upToDate": "Actualizado",
|
||||||
"xrayStatusUnknown": "Desconocido",
|
"xrayStatusUnknown": "Desconocido",
|
||||||
"xrayStatusRunning": "En ejecución",
|
"xrayStatusRunning": "En ejecución",
|
||||||
@@ -402,10 +407,16 @@
|
|||||||
"sniffingDomainsExcluded": "Dominios excluidos",
|
"sniffingDomainsExcluded": "Dominios excluidos",
|
||||||
"decryption": "Descifrado",
|
"decryption": "Descifrado",
|
||||||
"encryption": "Cifrado",
|
"encryption": "Cifrado",
|
||||||
"vlessAuthX25519": "Autenticación X25519",
|
"vlessAuthX25519": "X25519 (native)",
|
||||||
"vlessAuthMlkem768": "Autenticación ML-KEM-768",
|
"vlessAuthMlkem768": "ML-KEM-768 (native)",
|
||||||
|
"vlessAuthX25519Xorpub": "X25519 (xorpub)",
|
||||||
|
"vlessAuthX25519Random": "X25519 (random)",
|
||||||
|
"vlessAuthMlkem768Xorpub": "ML-KEM-768 (xorpub)",
|
||||||
|
"vlessAuthMlkem768Random": "ML-KEM-768 (random)",
|
||||||
"vlessAuthCustom": "Personalizado",
|
"vlessAuthCustom": "Personalizado",
|
||||||
"vlessAuthSelected": "Seleccionado: {auth}",
|
"vlessAuthSelected": "Seleccionado: {auth}",
|
||||||
|
"vlessAuthGenerate": "Generar claves",
|
||||||
|
"vlessAuthGenerateButton": "Generar",
|
||||||
"advanced": {
|
"advanced": {
|
||||||
"title": "Secciones JSON del inbound",
|
"title": "Secciones JSON del inbound",
|
||||||
"subtitle": "JSON completo del inbound y editores específicos para settings, sniffing y streamSettings.",
|
"subtitle": "JSON completo del inbound y editores específicos para settings, sniffing y streamSettings.",
|
||||||
@@ -968,6 +979,7 @@
|
|||||||
"upToDate": "Actualizado",
|
"upToDate": "Actualizado",
|
||||||
"updateConfirmTitle": "¿Actualizar {count} nodo(s) a la última versión?",
|
"updateConfirmTitle": "¿Actualizar {count} nodo(s) a la última versión?",
|
||||||
"updateConfirmContent": "Cada nodo seleccionado descarga la última versión y se reinicia con ella. Solo se actualizan los nodos habilitados y en línea.",
|
"updateConfirmContent": "Cada nodo seleccionado descarga la última versión y se reinicia con ella. Solo se actualizan los nodos habilitados y en línea.",
|
||||||
|
"updateDevChannel": "Actualizar al canal de desarrollo (último commit)",
|
||||||
"testConnection": "Probar conexión",
|
"testConnection": "Probar conexión",
|
||||||
"connectionOk": "Conexión correcta ({ms} ms)",
|
"connectionOk": "Conexión correcta ({ms} ms)",
|
||||||
"connectionFailed": "Conexión fallida",
|
"connectionFailed": "Conexión fallida",
|
||||||
@@ -1130,6 +1142,10 @@
|
|||||||
"subRoutingRulesDesc": "Reglas de enrutamiento globales para el cliente VPN. (Solo para Happ)",
|
"subRoutingRulesDesc": "Reglas de enrutamiento globales para el cliente VPN. (Solo para Happ)",
|
||||||
"subHideSettings": "Ocultar configuración del servidor",
|
"subHideSettings": "Ocultar configuración del servidor",
|
||||||
"subHideSettingsDesc": "Ocultar la posibilidad de ver y editar las configuraciones del servidor en el cliente VPN. (Solo para Happ)",
|
"subHideSettingsDesc": "Ocultar la posibilidad de ver y editar las configuraciones del servidor en el cliente VPN. (Solo para Happ)",
|
||||||
|
"subIncyEnableRouting": "Habilitar enrutamiento",
|
||||||
|
"subIncyEnableRoutingDesc": "Inyectar un perfil de enrutamiento en el cuerpo de la suscripción para el cliente Incy. (Solo para Incy)",
|
||||||
|
"subIncyRoutingRules": "Reglas de enrutamiento",
|
||||||
|
"subIncyRoutingRulesDesc": "Enlace de enrutamiento de Incy añadido al cuerpo de la suscripción, p. ej. incy://routing/onadd/<base64>. (Solo para Incy)",
|
||||||
"subClashEnableRouting": "Habilitar enrutamiento",
|
"subClashEnableRouting": "Habilitar enrutamiento",
|
||||||
"subClashEnableRoutingDesc": "Incluir reglas globales de enrutamiento Clash/Mihomo en las suscripciones YAML generadas.",
|
"subClashEnableRoutingDesc": "Incluir reglas globales de enrutamiento Clash/Mihomo en las suscripciones YAML generadas.",
|
||||||
"subClashRoutingRules": "Reglas globales de enrutamiento",
|
"subClashRoutingRules": "Reglas globales de enrutamiento",
|
||||||
@@ -1806,7 +1822,8 @@
|
|||||||
"groups": {
|
"groups": {
|
||||||
"client": "Cliente",
|
"client": "Cliente",
|
||||||
"traffic": "Tráfico",
|
"traffic": "Tráfico",
|
||||||
"time": "Tiempo y estado"
|
"time": "Tiempo y estado",
|
||||||
|
"connection": "Conexión"
|
||||||
},
|
},
|
||||||
"descEMAIL": "Email del cliente",
|
"descEMAIL": "Email del cliente",
|
||||||
"descINBOUND": "Notas del propio inbound (nombre de la configuración)",
|
"descINBOUND": "Notas del propio inbound (nombre de la configuración)",
|
||||||
@@ -1825,11 +1842,18 @@
|
|||||||
"descUP": "Tráfico de subida",
|
"descUP": "Tráfico de subida",
|
||||||
"descDOWN": "Tráfico de bajada",
|
"descDOWN": "Tráfico de bajada",
|
||||||
"descSTATUS": "activo / expirado / deshabilitado / agotado",
|
"descSTATUS": "activo / expirado / deshabilitado / agotado",
|
||||||
|
"descSTATUS_EMOJI": "Estado como emoji (✅ ⏳ 🚫)",
|
||||||
"descDAYS_LEFT": "Días hasta la expiración (oculto si es ilimitado)",
|
"descDAYS_LEFT": "Días hasta la expiración (oculto si es ilimitado)",
|
||||||
|
"descTIME_LEFT": "Tiempo restante (p. ej. 12d 4h 30m)",
|
||||||
|
"descUSAGE_PERCENTAGE": "Tráfico usado en porcentaje (oculto si es ilimitado)",
|
||||||
"descEXPIRE_DATE": "Fecha de expiración (AAAA-MM-DD)",
|
"descEXPIRE_DATE": "Fecha de expiración (AAAA-MM-DD)",
|
||||||
|
"descJALALI_EXPIRE_DATE": "Fecha de expiración en el calendario Jalali (AAAA/MM/DD)",
|
||||||
"descEXPIRE_UNIX": "Expiración como marca de tiempo Unix (segundos)",
|
"descEXPIRE_UNIX": "Expiración como marca de tiempo Unix (segundos)",
|
||||||
"descCREATED_UNIX": "Hora de creación como marca de tiempo Unix (segundos)",
|
"descCREATED_UNIX": "Hora de creación como marca de tiempo Unix (segundos)",
|
||||||
"descRESET_DAYS": "Periodo de reinicio de tráfico en días"
|
"descRESET_DAYS": "Periodo de reinicio de tráfico en días",
|
||||||
|
"descPROTOCOL": "Protocolo del inbound (VLESS, VMess, Trojan, …)",
|
||||||
|
"descTRANSPORT": "Red de transporte (tcp, ws, grpc, …)",
|
||||||
|
"descSECURITY": "Seguridad del transporte (TLS, REALITY, NONE)"
|
||||||
},
|
},
|
||||||
"toasts": {
|
"toasts": {
|
||||||
"list": "Error al cargar los hosts",
|
"list": "Error al cargar los hosts",
|
||||||
@@ -2062,4 +2086,4 @@
|
|||||||
"statusDown": "CAÍDO",
|
"statusDown": "CAÍDO",
|
||||||
"statusUp": "ACTIVO"
|
"statusUp": "ACTIVO"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -153,6 +153,11 @@
|
|||||||
"currentPanelVersion": "نسخه فعلی پنل",
|
"currentPanelVersion": "نسخه فعلی پنل",
|
||||||
"latestPanelVersion": "آخرین نسخه پنل",
|
"latestPanelVersion": "آخرین نسخه پنل",
|
||||||
"panelUpToDate": "پنل بهروز است",
|
"panelUpToDate": "پنل بهروز است",
|
||||||
|
"devChannel": "کانال توسعه (Dev)",
|
||||||
|
"devChannelWarning": "بیلدهای توسعه هر کامیت روی main را دنبال میکنند و نسخهٔ پایدار نیستند — بازگشت خودکار به نسخهٔ قبلی وجود ندارد.",
|
||||||
|
"currentCommit": "کامیت فعلی",
|
||||||
|
"latestCommit": "آخرین کامیت",
|
||||||
|
"updateChannelChanged": "کانال بهروزرسانی تغییر کرد",
|
||||||
"upToDate": "بهروز",
|
"upToDate": "بهروز",
|
||||||
"xrayStatusUnknown": "ناشناخته",
|
"xrayStatusUnknown": "ناشناخته",
|
||||||
"xrayStatusRunning": "در حال اجرا",
|
"xrayStatusRunning": "در حال اجرا",
|
||||||
@@ -402,10 +407,16 @@
|
|||||||
"sniffingDomainsExcluded": "دامنههای مستثنا",
|
"sniffingDomainsExcluded": "دامنههای مستثنا",
|
||||||
"decryption": "رمزگشایی",
|
"decryption": "رمزگشایی",
|
||||||
"encryption": "رمزنگاری",
|
"encryption": "رمزنگاری",
|
||||||
"vlessAuthX25519": "احراز X25519",
|
"vlessAuthX25519": "X25519 (native)",
|
||||||
"vlessAuthMlkem768": "احراز ML-KEM-768",
|
"vlessAuthMlkem768": "ML-KEM-768 (native)",
|
||||||
|
"vlessAuthX25519Xorpub": "X25519 (xorpub)",
|
||||||
|
"vlessAuthX25519Random": "X25519 (random)",
|
||||||
|
"vlessAuthMlkem768Xorpub": "ML-KEM-768 (xorpub)",
|
||||||
|
"vlessAuthMlkem768Random": "ML-KEM-768 (random)",
|
||||||
"vlessAuthCustom": "سفارشی",
|
"vlessAuthCustom": "سفارشی",
|
||||||
"vlessAuthSelected": "انتخابشده: {auth}",
|
"vlessAuthSelected": "انتخابشده: {auth}",
|
||||||
|
"vlessAuthGenerate": "تولید کلیدها",
|
||||||
|
"vlessAuthGenerateButton": "تولید",
|
||||||
"advanced": {
|
"advanced": {
|
||||||
"title": "بخشهای JSON اینباند",
|
"title": "بخشهای JSON اینباند",
|
||||||
"subtitle": "JSON کامل اینباند و ویرایشگرهای جداگانه برای settings، sniffing و streamSettings.",
|
"subtitle": "JSON کامل اینباند و ویرایشگرهای جداگانه برای settings، sniffing و streamSettings.",
|
||||||
@@ -968,6 +979,7 @@
|
|||||||
"upToDate": "بهروز",
|
"upToDate": "بهروز",
|
||||||
"updateConfirmTitle": "{count} نود به آخرین نسخه بهروزرسانی شوند؟",
|
"updateConfirmTitle": "{count} نود به آخرین نسخه بهروزرسانی شوند؟",
|
||||||
"updateConfirmContent": "هر نود انتخابشده آخرین نسخه را دانلود و روی آن ریاستارت میشود. فقط نودهای فعال و آنلاین بهروزرسانی میشوند.",
|
"updateConfirmContent": "هر نود انتخابشده آخرین نسخه را دانلود و روی آن ریاستارت میشود. فقط نودهای فعال و آنلاین بهروزرسانی میشوند.",
|
||||||
|
"updateDevChannel": "بهروزرسانی به کانال دِو (آخرین کامیت)",
|
||||||
"testConnection": "تست اتصال",
|
"testConnection": "تست اتصال",
|
||||||
"connectionOk": "اتصال موفق ({ms} میلیثانیه)",
|
"connectionOk": "اتصال موفق ({ms} میلیثانیه)",
|
||||||
"connectionFailed": "اتصال ناموفق",
|
"connectionFailed": "اتصال ناموفق",
|
||||||
@@ -1132,6 +1144,10 @@
|
|||||||
"subRoutingRulesDesc": "قوانین مسیریابی سراسری برای کلاینت VPN. (فقط برای Happ)",
|
"subRoutingRulesDesc": "قوانین مسیریابی سراسری برای کلاینت VPN. (فقط برای Happ)",
|
||||||
"subHideSettings": "پنهان کردن تنظیمات سرور",
|
"subHideSettings": "پنهان کردن تنظیمات سرور",
|
||||||
"subHideSettingsDesc": "پنهان کردن توانایی مشاهده و ویرایش پیکربندی سرور در کلاینت VPN. (فقط برای Happ)",
|
"subHideSettingsDesc": "پنهان کردن توانایی مشاهده و ویرایش پیکربندی سرور در کلاینت VPN. (فقط برای Happ)",
|
||||||
|
"subIncyEnableRouting": "فعالسازی مسیریابی",
|
||||||
|
"subIncyEnableRoutingDesc": "تزریق پروفایل مسیریابی به بدنه اشتراک برای کلاینت Incy. (فقط برای Incy)",
|
||||||
|
"subIncyRoutingRules": "قوانین مسیریابی",
|
||||||
|
"subIncyRoutingRulesDesc": "لینک مسیریابی Incy که به بدنه اشتراک افزوده میشود، مثلاً incy://routing/onadd/<base64>. (فقط برای Incy)",
|
||||||
"subClashEnableRouting": "فعالسازی مسیریابی",
|
"subClashEnableRouting": "فعالسازی مسیریابی",
|
||||||
"subClashEnableRoutingDesc": "قوانین مسیریابی سراسری Clash/Mihomo را در اشتراکهای YAML تولیدشده وارد کن.",
|
"subClashEnableRoutingDesc": "قوانین مسیریابی سراسری Clash/Mihomo را در اشتراکهای YAML تولیدشده وارد کن.",
|
||||||
"subClashRoutingRules": "قوانین مسیریابی سراسری",
|
"subClashRoutingRules": "قوانین مسیریابی سراسری",
|
||||||
@@ -1806,7 +1822,8 @@
|
|||||||
"groups": {
|
"groups": {
|
||||||
"client": "کاربر",
|
"client": "کاربر",
|
||||||
"traffic": "ترافیک",
|
"traffic": "ترافیک",
|
||||||
"time": "زمان و وضعیت"
|
"time": "زمان و وضعیت",
|
||||||
|
"connection": "اتصال"
|
||||||
},
|
},
|
||||||
"descEMAIL": "ایمیل کاربر",
|
"descEMAIL": "ایمیل کاربر",
|
||||||
"descINBOUND": "نام خود اینباند (نام کانفیگ)",
|
"descINBOUND": "نام خود اینباند (نام کانفیگ)",
|
||||||
@@ -1825,11 +1842,18 @@
|
|||||||
"descUP": "ترافیک آپلود",
|
"descUP": "ترافیک آپلود",
|
||||||
"descDOWN": "ترافیک دانلود",
|
"descDOWN": "ترافیک دانلود",
|
||||||
"descSTATUS": "فعال / منقضیشده / غیرفعال / مصرفشده",
|
"descSTATUS": "فعال / منقضیشده / غیرفعال / مصرفشده",
|
||||||
|
"descSTATUS_EMOJI": "وضعیت بهصورت ایموجی (✅ ⏳ 🚫)",
|
||||||
"descDAYS_LEFT": "روزهای باقیمانده تا انقضا (در صورت نامحدود بودن پنهان میشود)",
|
"descDAYS_LEFT": "روزهای باقیمانده تا انقضا (در صورت نامحدود بودن پنهان میشود)",
|
||||||
|
"descTIME_LEFT": "زمان باقیمانده (مثلاً 12d 4h 30m)",
|
||||||
|
"descUSAGE_PERCENTAGE": "ترافیک مصرفشده به درصد (در صورت نامحدود بودن پنهان میشود)",
|
||||||
"descEXPIRE_DATE": "تاریخ انقضا (YYYY-MM-DD)",
|
"descEXPIRE_DATE": "تاریخ انقضا (YYYY-MM-DD)",
|
||||||
|
"descJALALI_EXPIRE_DATE": "تاریخ انقضا در تقویم جلالی (YYYY/MM/DD)",
|
||||||
"descEXPIRE_UNIX": "انقضا بهصورت مهر زمانی Unix (ثانیه)",
|
"descEXPIRE_UNIX": "انقضا بهصورت مهر زمانی Unix (ثانیه)",
|
||||||
"descCREATED_UNIX": "زمان ایجاد بهصورت مهر زمانی Unix (ثانیه)",
|
"descCREATED_UNIX": "زمان ایجاد بهصورت مهر زمانی Unix (ثانیه)",
|
||||||
"descRESET_DAYS": "دورهٔ بازنشانی ترافیک به روز"
|
"descRESET_DAYS": "دورهٔ بازنشانی ترافیک به روز",
|
||||||
|
"descPROTOCOL": "پروتکل اینباند (VLESS، VMess، Trojan، …)",
|
||||||
|
"descTRANSPORT": "شبکهٔ انتقال (tcp، ws، grpc، …)",
|
||||||
|
"descSECURITY": "امنیت انتقال (TLS، REALITY، NONE)"
|
||||||
},
|
},
|
||||||
"toasts": {
|
"toasts": {
|
||||||
"list": "بارگذاری میزبانها ناموفق",
|
"list": "بارگذاری میزبانها ناموفق",
|
||||||
@@ -2062,4 +2086,4 @@
|
|||||||
"statusDown": "قطع",
|
"statusDown": "قطع",
|
||||||
"statusUp": "وصل"
|
"statusUp": "وصل"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -153,6 +153,11 @@
|
|||||||
"currentPanelVersion": "Versi panel saat ini",
|
"currentPanelVersion": "Versi panel saat ini",
|
||||||
"latestPanelVersion": "Versi panel terbaru",
|
"latestPanelVersion": "Versi panel terbaru",
|
||||||
"panelUpToDate": "Panel sudah terbaru",
|
"panelUpToDate": "Panel sudah terbaru",
|
||||||
|
"devChannel": "Kanal dev",
|
||||||
|
"devChannelWarning": "Build dev mengikuti setiap commit di main dan bukan rilis stabil — tidak ada penurunan versi otomatis.",
|
||||||
|
"currentCommit": "Commit saat ini",
|
||||||
|
"latestCommit": "Commit terbaru",
|
||||||
|
"updateChannelChanged": "Kanal pembaruan diubah",
|
||||||
"upToDate": "Terbaru",
|
"upToDate": "Terbaru",
|
||||||
"xrayStatusUnknown": "Tidak diketahui",
|
"xrayStatusUnknown": "Tidak diketahui",
|
||||||
"xrayStatusRunning": "Berjalan",
|
"xrayStatusRunning": "Berjalan",
|
||||||
@@ -402,10 +407,16 @@
|
|||||||
"sniffingDomainsExcluded": "Domain yang dikecualikan",
|
"sniffingDomainsExcluded": "Domain yang dikecualikan",
|
||||||
"decryption": "Dekripsi",
|
"decryption": "Dekripsi",
|
||||||
"encryption": "Enkripsi",
|
"encryption": "Enkripsi",
|
||||||
"vlessAuthX25519": "Auth X25519",
|
"vlessAuthX25519": "X25519 (native)",
|
||||||
"vlessAuthMlkem768": "Auth ML-KEM-768",
|
"vlessAuthMlkem768": "ML-KEM-768 (native)",
|
||||||
|
"vlessAuthX25519Xorpub": "X25519 (xorpub)",
|
||||||
|
"vlessAuthX25519Random": "X25519 (random)",
|
||||||
|
"vlessAuthMlkem768Xorpub": "ML-KEM-768 (xorpub)",
|
||||||
|
"vlessAuthMlkem768Random": "ML-KEM-768 (random)",
|
||||||
"vlessAuthCustom": "Khusus",
|
"vlessAuthCustom": "Khusus",
|
||||||
"vlessAuthSelected": "Dipilih: {auth}",
|
"vlessAuthSelected": "Dipilih: {auth}",
|
||||||
|
"vlessAuthGenerate": "Buat kunci",
|
||||||
|
"vlessAuthGenerateButton": "Buat",
|
||||||
"advanced": {
|
"advanced": {
|
||||||
"title": "Bagian JSON inbound",
|
"title": "Bagian JSON inbound",
|
||||||
"subtitle": "JSON inbound lengkap dan editor fokus untuk settings, sniffing, dan streamSettings.",
|
"subtitle": "JSON inbound lengkap dan editor fokus untuk settings, sniffing, dan streamSettings.",
|
||||||
@@ -968,6 +979,7 @@
|
|||||||
"upToDate": "Terbaru",
|
"upToDate": "Terbaru",
|
||||||
"updateConfirmTitle": "Perbarui {count} node ke versi terbaru?",
|
"updateConfirmTitle": "Perbarui {count} node ke versi terbaru?",
|
||||||
"updateConfirmContent": "Setiap node terpilih mengunduh rilis terbaru dan memulai ulang. Hanya node aktif dan online yang diperbarui.",
|
"updateConfirmContent": "Setiap node terpilih mengunduh rilis terbaru dan memulai ulang. Hanya node aktif dan online yang diperbarui.",
|
||||||
|
"updateDevChannel": "Perbarui ke kanal dev (commit terbaru)",
|
||||||
"testConnection": "Tes Koneksi",
|
"testConnection": "Tes Koneksi",
|
||||||
"connectionOk": "Koneksi OK ({ms} ms)",
|
"connectionOk": "Koneksi OK ({ms} ms)",
|
||||||
"connectionFailed": "Koneksi gagal",
|
"connectionFailed": "Koneksi gagal",
|
||||||
@@ -1130,6 +1142,10 @@
|
|||||||
"subRoutingRulesDesc": "Aturan routing global untuk klien VPN. (Hanya untuk Happ)",
|
"subRoutingRulesDesc": "Aturan routing global untuk klien VPN. (Hanya untuk Happ)",
|
||||||
"subHideSettings": "Sembunyikan pengaturan server",
|
"subHideSettings": "Sembunyikan pengaturan server",
|
||||||
"subHideSettingsDesc": "Menyembunyikan kemampuan untuk melihat dan mengedit konfigurasi server di klien VPN. (Hanya untuk Happ)",
|
"subHideSettingsDesc": "Menyembunyikan kemampuan untuk melihat dan mengedit konfigurasi server di klien VPN. (Hanya untuk Happ)",
|
||||||
|
"subIncyEnableRouting": "Aktifkan perutean",
|
||||||
|
"subIncyEnableRoutingDesc": "Menyuntikkan profil perutean ke dalam body langganan untuk klien Incy. (Hanya untuk Incy)",
|
||||||
|
"subIncyRoutingRules": "Aturan routing",
|
||||||
|
"subIncyRoutingRulesDesc": "Tautan perutean Incy yang ditambahkan ke body langganan, mis. incy://routing/onadd/<base64>. (Hanya untuk Incy)",
|
||||||
"subClashEnableRouting": "Aktifkan routing",
|
"subClashEnableRouting": "Aktifkan routing",
|
||||||
"subClashEnableRoutingDesc": "Sertakan aturan routing global Clash/Mihomo dalam langganan YAML yang dibuat.",
|
"subClashEnableRoutingDesc": "Sertakan aturan routing global Clash/Mihomo dalam langganan YAML yang dibuat.",
|
||||||
"subClashRoutingRules": "Aturan routing global",
|
"subClashRoutingRules": "Aturan routing global",
|
||||||
@@ -1806,7 +1822,8 @@
|
|||||||
"groups": {
|
"groups": {
|
||||||
"client": "Klien",
|
"client": "Klien",
|
||||||
"traffic": "Trafik",
|
"traffic": "Trafik",
|
||||||
"time": "Waktu & status"
|
"time": "Waktu & status",
|
||||||
|
"connection": "Koneksi"
|
||||||
},
|
},
|
||||||
"descEMAIL": "Email klien",
|
"descEMAIL": "Email klien",
|
||||||
"descINBOUND": "Catatan inbound itu sendiri (nama konfigurasi)",
|
"descINBOUND": "Catatan inbound itu sendiri (nama konfigurasi)",
|
||||||
@@ -1825,11 +1842,18 @@
|
|||||||
"descUP": "Trafik unggah",
|
"descUP": "Trafik unggah",
|
||||||
"descDOWN": "Trafik unduh",
|
"descDOWN": "Trafik unduh",
|
||||||
"descSTATUS": "aktif / kedaluwarsa / nonaktif / habis",
|
"descSTATUS": "aktif / kedaluwarsa / nonaktif / habis",
|
||||||
|
"descSTATUS_EMOJI": "Status sebagai emoji (✅ ⏳ 🚫)",
|
||||||
"descDAYS_LEFT": "Hari hingga kedaluwarsa (disembunyikan jika tanpa batas)",
|
"descDAYS_LEFT": "Hari hingga kedaluwarsa (disembunyikan jika tanpa batas)",
|
||||||
|
"descTIME_LEFT": "Waktu tersisa (mis. 12d 4h 30m)",
|
||||||
|
"descUSAGE_PERCENTAGE": "Trafik terpakai dalam persentase (disembunyikan jika tanpa batas)",
|
||||||
"descEXPIRE_DATE": "Tanggal kedaluwarsa (YYYY-MM-DD)",
|
"descEXPIRE_DATE": "Tanggal kedaluwarsa (YYYY-MM-DD)",
|
||||||
|
"descJALALI_EXPIRE_DATE": "Tanggal kedaluwarsa dalam kalender Jalali (YYYY/MM/DD)",
|
||||||
"descEXPIRE_UNIX": "Kedaluwarsa sebagai timestamp Unix (detik)",
|
"descEXPIRE_UNIX": "Kedaluwarsa sebagai timestamp Unix (detik)",
|
||||||
"descCREATED_UNIX": "Waktu pembuatan sebagai timestamp Unix (detik)",
|
"descCREATED_UNIX": "Waktu pembuatan sebagai timestamp Unix (detik)",
|
||||||
"descRESET_DAYS": "Periode reset trafik dalam hari"
|
"descRESET_DAYS": "Periode reset trafik dalam hari",
|
||||||
|
"descPROTOCOL": "Protokol inbound (VLESS, VMess, Trojan, …)",
|
||||||
|
"descTRANSPORT": "Jaringan transport (tcp, ws, grpc, …)",
|
||||||
|
"descSECURITY": "Keamanan transport (TLS, REALITY, NONE)"
|
||||||
},
|
},
|
||||||
"toasts": {
|
"toasts": {
|
||||||
"list": "Gagal memuat host",
|
"list": "Gagal memuat host",
|
||||||
@@ -2062,4 +2086,4 @@
|
|||||||
"statusDown": "MATI",
|
"statusDown": "MATI",
|
||||||
"statusUp": "AKTIF"
|
"statusUp": "AKTIF"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -153,6 +153,11 @@
|
|||||||
"currentPanelVersion": "現在のパネルバージョン",
|
"currentPanelVersion": "現在のパネルバージョン",
|
||||||
"latestPanelVersion": "最新のパネルバージョン",
|
"latestPanelVersion": "最新のパネルバージョン",
|
||||||
"panelUpToDate": "パネルは最新です",
|
"panelUpToDate": "パネルは最新です",
|
||||||
|
"devChannel": "開発チャンネル",
|
||||||
|
"devChannelWarning": "開発ビルドは main の各コミットを追跡し、安定版ではありません。自動ダウングレードはありません。",
|
||||||
|
"currentCommit": "現在のコミット",
|
||||||
|
"latestCommit": "最新のコミット",
|
||||||
|
"updateChannelChanged": "更新チャンネルを変更しました",
|
||||||
"upToDate": "最新",
|
"upToDate": "最新",
|
||||||
"xrayStatusUnknown": "不明",
|
"xrayStatusUnknown": "不明",
|
||||||
"xrayStatusRunning": "実行中",
|
"xrayStatusRunning": "実行中",
|
||||||
@@ -402,10 +407,16 @@
|
|||||||
"sniffingDomainsExcluded": "除外するドメイン",
|
"sniffingDomainsExcluded": "除外するドメイン",
|
||||||
"decryption": "復号",
|
"decryption": "復号",
|
||||||
"encryption": "暗号化",
|
"encryption": "暗号化",
|
||||||
"vlessAuthX25519": "X25519 認証",
|
"vlessAuthX25519": "X25519 (native)",
|
||||||
"vlessAuthMlkem768": "ML-KEM-768 認証",
|
"vlessAuthMlkem768": "ML-KEM-768 (native)",
|
||||||
|
"vlessAuthX25519Xorpub": "X25519 (xorpub)",
|
||||||
|
"vlessAuthX25519Random": "X25519 (random)",
|
||||||
|
"vlessAuthMlkem768Xorpub": "ML-KEM-768 (xorpub)",
|
||||||
|
"vlessAuthMlkem768Random": "ML-KEM-768 (random)",
|
||||||
"vlessAuthCustom": "カスタム",
|
"vlessAuthCustom": "カスタム",
|
||||||
"vlessAuthSelected": "選択中: {auth}",
|
"vlessAuthSelected": "選択中: {auth}",
|
||||||
|
"vlessAuthGenerate": "鍵を生成",
|
||||||
|
"vlessAuthGenerateButton": "生成",
|
||||||
"advanced": {
|
"advanced": {
|
||||||
"title": "インバウンド JSON セクション",
|
"title": "インバウンド JSON セクション",
|
||||||
"subtitle": "インバウンド全体の JSON と、settings、sniffing、streamSettings 用の専用エディター。",
|
"subtitle": "インバウンド全体の JSON と、settings、sniffing、streamSettings 用の専用エディター。",
|
||||||
@@ -968,6 +979,7 @@
|
|||||||
"upToDate": "最新",
|
"upToDate": "最新",
|
||||||
"updateConfirmTitle": "{count} 個のノードを最新バージョンに更新しますか?",
|
"updateConfirmTitle": "{count} 個のノードを最新バージョンに更新しますか?",
|
||||||
"updateConfirmContent": "選択した各ノードは最新リリースをダウンロードして再起動します。有効かつオンラインのノードのみが更新されます。",
|
"updateConfirmContent": "選択した各ノードは最新リリースをダウンロードして再起動します。有効かつオンラインのノードのみが更新されます。",
|
||||||
|
"updateDevChannel": "開発チャンネルに更新(最新コミット)",
|
||||||
"testConnection": "接続テスト",
|
"testConnection": "接続テスト",
|
||||||
"connectionOk": "接続OK ({ms} ms)",
|
"connectionOk": "接続OK ({ms} ms)",
|
||||||
"connectionFailed": "接続に失敗しました",
|
"connectionFailed": "接続に失敗しました",
|
||||||
@@ -1130,6 +1142,10 @@
|
|||||||
"subRoutingRulesDesc": "VPNクライアントのグローバルルーティングルール。(Happのみ)",
|
"subRoutingRulesDesc": "VPNクライアントのグローバルルーティングルール。(Happのみ)",
|
||||||
"subHideSettings": "サーバー設定を非表示",
|
"subHideSettings": "サーバー設定を非表示",
|
||||||
"subHideSettingsDesc": "VPNクライアントでサーバー設定の表示・編集機能を非表示にします。(Happのみ)",
|
"subHideSettingsDesc": "VPNクライアントでサーバー設定の表示・編集機能を非表示にします。(Happのみ)",
|
||||||
|
"subIncyEnableRouting": "ルーティングを有効化",
|
||||||
|
"subIncyEnableRoutingDesc": "Incyクライアント用に、サブスクリプション本文へルーティングプロファイルを挿入します。(Incyのみ)",
|
||||||
|
"subIncyRoutingRules": "ルーティングルール",
|
||||||
|
"subIncyRoutingRulesDesc": "サブスクリプション本文に追加するIncyルーティングのディープリンク。例: incy://routing/onadd/<base64>。(Incyのみ)",
|
||||||
"subClashEnableRouting": "ルーティングを有効化",
|
"subClashEnableRouting": "ルーティングを有効化",
|
||||||
"subClashEnableRoutingDesc": "生成されたYAMLサブスクリプションにClash/Mihomoのグローバルルーティングルールを含めます。",
|
"subClashEnableRoutingDesc": "生成されたYAMLサブスクリプションにClash/Mihomoのグローバルルーティングルールを含めます。",
|
||||||
"subClashRoutingRules": "グローバルルーティングルール",
|
"subClashRoutingRules": "グローバルルーティングルール",
|
||||||
@@ -1806,7 +1822,8 @@
|
|||||||
"groups": {
|
"groups": {
|
||||||
"client": "クライアント",
|
"client": "クライアント",
|
||||||
"traffic": "トラフィック",
|
"traffic": "トラフィック",
|
||||||
"time": "時刻とステータス"
|
"time": "時刻とステータス",
|
||||||
|
"connection": "接続"
|
||||||
},
|
},
|
||||||
"descEMAIL": "クライアントのメール",
|
"descEMAIL": "クライアントのメール",
|
||||||
"descINBOUND": "インバウンド自身の備考(設定名)",
|
"descINBOUND": "インバウンド自身の備考(設定名)",
|
||||||
@@ -1825,11 +1842,18 @@
|
|||||||
"descUP": "アップロードトラフィック",
|
"descUP": "アップロードトラフィック",
|
||||||
"descDOWN": "ダウンロードトラフィック",
|
"descDOWN": "ダウンロードトラフィック",
|
||||||
"descSTATUS": "active / expired / disabled / depleted",
|
"descSTATUS": "active / expired / disabled / depleted",
|
||||||
|
"descSTATUS_EMOJI": "絵文字で表したステータス(✅ ⏳ 🚫)",
|
||||||
"descDAYS_LEFT": "有効期限までの日数(無制限の場合は非表示)",
|
"descDAYS_LEFT": "有効期限までの日数(無制限の場合は非表示)",
|
||||||
|
"descTIME_LEFT": "残り時間(例:12d 4h 30m)",
|
||||||
|
"descUSAGE_PERCENTAGE": "使用済みトラフィックの割合(無制限の場合は非表示)",
|
||||||
"descEXPIRE_DATE": "有効期限(YYYY-MM-DD)",
|
"descEXPIRE_DATE": "有効期限(YYYY-MM-DD)",
|
||||||
|
"descJALALI_EXPIRE_DATE": "ジャラーリー暦の有効期限(YYYY/MM/DD)",
|
||||||
"descEXPIRE_UNIX": "有効期限の Unix タイムスタンプ(秒)",
|
"descEXPIRE_UNIX": "有効期限の Unix タイムスタンプ(秒)",
|
||||||
"descCREATED_UNIX": "作成時刻の Unix タイムスタンプ(秒)",
|
"descCREATED_UNIX": "作成時刻の Unix タイムスタンプ(秒)",
|
||||||
"descRESET_DAYS": "トラフィックリセット周期(日数)"
|
"descRESET_DAYS": "トラフィックリセット周期(日数)",
|
||||||
|
"descPROTOCOL": "インバウンドのプロトコル(VLESS、VMess、Trojan など)",
|
||||||
|
"descTRANSPORT": "トランスポートネットワーク(tcp、ws、grpc など)",
|
||||||
|
"descSECURITY": "トランスポートのセキュリティ(TLS、REALITY、NONE)"
|
||||||
},
|
},
|
||||||
"toasts": {
|
"toasts": {
|
||||||
"list": "ホストの読み込みに失敗しました",
|
"list": "ホストの読み込みに失敗しました",
|
||||||
@@ -2062,4 +2086,4 @@
|
|||||||
"statusDown": "ダウン",
|
"statusDown": "ダウン",
|
||||||
"statusUp": "アップ"
|
"statusUp": "アップ"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -153,6 +153,11 @@
|
|||||||
"currentPanelVersion": "Versão atual do painel",
|
"currentPanelVersion": "Versão atual do painel",
|
||||||
"latestPanelVersion": "Última versão do painel",
|
"latestPanelVersion": "Última versão do painel",
|
||||||
"panelUpToDate": "O painel está atualizado",
|
"panelUpToDate": "O painel está atualizado",
|
||||||
|
"devChannel": "Canal de desenvolvimento",
|
||||||
|
"devChannelWarning": "As builds de desenvolvimento acompanham cada commit na main e não são versões estáveis — não há downgrade automático.",
|
||||||
|
"currentCommit": "Commit atual",
|
||||||
|
"latestCommit": "Último commit",
|
||||||
|
"updateChannelChanged": "Canal de atualização alterado",
|
||||||
"upToDate": "Atualizado",
|
"upToDate": "Atualizado",
|
||||||
"xrayStatusUnknown": "Desconhecido",
|
"xrayStatusUnknown": "Desconhecido",
|
||||||
"xrayStatusRunning": "Em execução",
|
"xrayStatusRunning": "Em execução",
|
||||||
@@ -402,10 +407,16 @@
|
|||||||
"sniffingDomainsExcluded": "Domínios excluídos",
|
"sniffingDomainsExcluded": "Domínios excluídos",
|
||||||
"decryption": "Descriptografia",
|
"decryption": "Descriptografia",
|
||||||
"encryption": "Criptografia",
|
"encryption": "Criptografia",
|
||||||
"vlessAuthX25519": "Autenticação X25519",
|
"vlessAuthX25519": "X25519 (native)",
|
||||||
"vlessAuthMlkem768": "Autenticação ML-KEM-768",
|
"vlessAuthMlkem768": "ML-KEM-768 (native)",
|
||||||
|
"vlessAuthX25519Xorpub": "X25519 (xorpub)",
|
||||||
|
"vlessAuthX25519Random": "X25519 (random)",
|
||||||
|
"vlessAuthMlkem768Xorpub": "ML-KEM-768 (xorpub)",
|
||||||
|
"vlessAuthMlkem768Random": "ML-KEM-768 (random)",
|
||||||
"vlessAuthCustom": "Personalizado",
|
"vlessAuthCustom": "Personalizado",
|
||||||
"vlessAuthSelected": "Selecionado: {auth}",
|
"vlessAuthSelected": "Selecionado: {auth}",
|
||||||
|
"vlessAuthGenerate": "Gerar chaves",
|
||||||
|
"vlessAuthGenerateButton": "Gerar",
|
||||||
"advanced": {
|
"advanced": {
|
||||||
"title": "Seções JSON do inbound",
|
"title": "Seções JSON do inbound",
|
||||||
"subtitle": "JSON completo do inbound e editores específicos para settings, sniffing e streamSettings.",
|
"subtitle": "JSON completo do inbound e editores específicos para settings, sniffing e streamSettings.",
|
||||||
@@ -968,6 +979,7 @@
|
|||||||
"upToDate": "Atualizado",
|
"upToDate": "Atualizado",
|
||||||
"updateConfirmTitle": "Atualizar {count} nó(s) para a versão mais recente?",
|
"updateConfirmTitle": "Atualizar {count} nó(s) para a versão mais recente?",
|
||||||
"updateConfirmContent": "Cada nó selecionado baixa a versão mais recente e reinicia nela. Apenas nós ativos e online são atualizados.",
|
"updateConfirmContent": "Cada nó selecionado baixa a versão mais recente e reinicia nela. Apenas nós ativos e online são atualizados.",
|
||||||
|
"updateDevChannel": "Atualizar para o canal de desenvolvimento (último commit)",
|
||||||
"testConnection": "Testar conexão",
|
"testConnection": "Testar conexão",
|
||||||
"connectionOk": "Conexão OK ({ms} ms)",
|
"connectionOk": "Conexão OK ({ms} ms)",
|
||||||
"connectionFailed": "Falha na conexão",
|
"connectionFailed": "Falha na conexão",
|
||||||
@@ -1130,6 +1142,10 @@
|
|||||||
"subRoutingRulesDesc": "Regras de roteamento globais para o cliente VPN. (Apenas para Happ)",
|
"subRoutingRulesDesc": "Regras de roteamento globais para o cliente VPN. (Apenas para Happ)",
|
||||||
"subHideSettings": "Ocultar configurações do servidor",
|
"subHideSettings": "Ocultar configurações do servidor",
|
||||||
"subHideSettingsDesc": "Ocultar a capacidade de visualizar e editar as configurações do servidor no cliente VPN. (Apenas para Happ)",
|
"subHideSettingsDesc": "Ocultar a capacidade de visualizar e editar as configurações do servidor no cliente VPN. (Apenas para Happ)",
|
||||||
|
"subIncyEnableRouting": "Ativar roteamento",
|
||||||
|
"subIncyEnableRoutingDesc": "Injetar um perfil de roteamento no corpo da assinatura para o cliente Incy. (Apenas para Incy)",
|
||||||
|
"subIncyRoutingRules": "Regras de roteamento",
|
||||||
|
"subIncyRoutingRulesDesc": "Link de roteamento do Incy adicionado ao corpo da assinatura, ex. incy://routing/onadd/<base64>. (Apenas para Incy)",
|
||||||
"subClashEnableRouting": "Ativar roteamento",
|
"subClashEnableRouting": "Ativar roteamento",
|
||||||
"subClashEnableRoutingDesc": "Incluir regras globais de roteamento Clash/Mihomo nas assinaturas YAML geradas.",
|
"subClashEnableRoutingDesc": "Incluir regras globais de roteamento Clash/Mihomo nas assinaturas YAML geradas.",
|
||||||
"subClashRoutingRules": "Regras globais de roteamento",
|
"subClashRoutingRules": "Regras globais de roteamento",
|
||||||
@@ -1806,7 +1822,8 @@
|
|||||||
"groups": {
|
"groups": {
|
||||||
"client": "Cliente",
|
"client": "Cliente",
|
||||||
"traffic": "Tráfego",
|
"traffic": "Tráfego",
|
||||||
"time": "Tempo e status"
|
"time": "Tempo e status",
|
||||||
|
"connection": "Conexão"
|
||||||
},
|
},
|
||||||
"descEMAIL": "Email do cliente",
|
"descEMAIL": "Email do cliente",
|
||||||
"descINBOUND": "Observação da própria entrada (nome da configuração)",
|
"descINBOUND": "Observação da própria entrada (nome da configuração)",
|
||||||
@@ -1825,11 +1842,18 @@
|
|||||||
"descUP": "Tráfego de upload",
|
"descUP": "Tráfego de upload",
|
||||||
"descDOWN": "Tráfego de download",
|
"descDOWN": "Tráfego de download",
|
||||||
"descSTATUS": "ativo / expirado / desativado / esgotado",
|
"descSTATUS": "ativo / expirado / desativado / esgotado",
|
||||||
|
"descSTATUS_EMOJI": "Status como emoji (✅ ⏳ 🚫)",
|
||||||
"descDAYS_LEFT": "Dias até a expiração (oculto se ilimitado)",
|
"descDAYS_LEFT": "Dias até a expiração (oculto se ilimitado)",
|
||||||
|
"descTIME_LEFT": "Tempo restante (ex.: 12d 4h 30m)",
|
||||||
|
"descUSAGE_PERCENTAGE": "Tráfego usado como porcentagem (oculto se ilimitado)",
|
||||||
"descEXPIRE_DATE": "Data de expiração (AAAA-MM-DD)",
|
"descEXPIRE_DATE": "Data de expiração (AAAA-MM-DD)",
|
||||||
|
"descJALALI_EXPIRE_DATE": "Data de expiração no calendário Jalali (AAAA/MM/DD)",
|
||||||
"descEXPIRE_UNIX": "Expiração como timestamp Unix (segundos)",
|
"descEXPIRE_UNIX": "Expiração como timestamp Unix (segundos)",
|
||||||
"descCREATED_UNIX": "Data de criação como timestamp Unix (segundos)",
|
"descCREATED_UNIX": "Data de criação como timestamp Unix (segundos)",
|
||||||
"descRESET_DAYS": "Período de redefinição de tráfego em dias"
|
"descRESET_DAYS": "Período de redefinição de tráfego em dias",
|
||||||
|
"descPROTOCOL": "Protocolo da entrada (VLESS, VMess, Trojan, …)",
|
||||||
|
"descTRANSPORT": "Rede de transporte (tcp, ws, grpc, …)",
|
||||||
|
"descSECURITY": "Segurança do transporte (TLS, REALITY, NONE)"
|
||||||
},
|
},
|
||||||
"toasts": {
|
"toasts": {
|
||||||
"list": "Falha ao carregar os hosts",
|
"list": "Falha ao carregar os hosts",
|
||||||
@@ -2062,4 +2086,4 @@
|
|||||||
"statusDown": "INATIVO",
|
"statusDown": "INATIVO",
|
||||||
"statusUp": "ATIVO"
|
"statusUp": "ATIVO"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -153,6 +153,11 @@
|
|||||||
"currentPanelVersion": "Текущая версия панели",
|
"currentPanelVersion": "Текущая версия панели",
|
||||||
"latestPanelVersion": "Последняя версия панели",
|
"latestPanelVersion": "Последняя версия панели",
|
||||||
"panelUpToDate": "Панель обновлена",
|
"panelUpToDate": "Панель обновлена",
|
||||||
|
"devChannel": "Канал разработки",
|
||||||
|
"devChannelWarning": "Сборки разработки отслеживают каждый коммит в main и не являются стабильными релизами — автоматического отката нет.",
|
||||||
|
"currentCommit": "Текущий коммит",
|
||||||
|
"latestCommit": "Последний коммит",
|
||||||
|
"updateChannelChanged": "Канал обновления изменён",
|
||||||
"upToDate": "Обновлено",
|
"upToDate": "Обновлено",
|
||||||
"xrayStatusUnknown": "Неизвестно",
|
"xrayStatusUnknown": "Неизвестно",
|
||||||
"xrayStatusRunning": "Запущен",
|
"xrayStatusRunning": "Запущен",
|
||||||
@@ -402,10 +407,16 @@
|
|||||||
"sniffingDomainsExcluded": "Исключённые домены",
|
"sniffingDomainsExcluded": "Исключённые домены",
|
||||||
"decryption": "Расшифрование",
|
"decryption": "Расшифрование",
|
||||||
"encryption": "Шифрование",
|
"encryption": "Шифрование",
|
||||||
"vlessAuthX25519": "Аутентификация X25519",
|
"vlessAuthX25519": "X25519 (native)",
|
||||||
"vlessAuthMlkem768": "Аутентификация ML-KEM-768",
|
"vlessAuthMlkem768": "ML-KEM-768 (native)",
|
||||||
|
"vlessAuthX25519Xorpub": "X25519 (xorpub)",
|
||||||
|
"vlessAuthX25519Random": "X25519 (random)",
|
||||||
|
"vlessAuthMlkem768Xorpub": "ML-KEM-768 (xorpub)",
|
||||||
|
"vlessAuthMlkem768Random": "ML-KEM-768 (random)",
|
||||||
"vlessAuthCustom": "Свой",
|
"vlessAuthCustom": "Свой",
|
||||||
"vlessAuthSelected": "Выбрано: {auth}",
|
"vlessAuthSelected": "Выбрано: {auth}",
|
||||||
|
"vlessAuthGenerate": "Генерация ключей",
|
||||||
|
"vlessAuthGenerateButton": "Сгенерировать",
|
||||||
"advanced": {
|
"advanced": {
|
||||||
"title": "Разделы JSON входящего",
|
"title": "Разделы JSON входящего",
|
||||||
"subtitle": "Полный JSON входящего и отдельные редакторы для settings, sniffing и streamSettings.",
|
"subtitle": "Полный JSON входящего и отдельные редакторы для settings, sniffing и streamSettings.",
|
||||||
@@ -968,6 +979,7 @@
|
|||||||
"upToDate": "Актуально",
|
"upToDate": "Актуально",
|
||||||
"updateConfirmTitle": "Обновить {count} узлов до последней версии?",
|
"updateConfirmTitle": "Обновить {count} узлов до последней версии?",
|
||||||
"updateConfirmContent": "Каждый выбранный узел загрузит последний релиз и перезапустится. Обновляются только включённые узлы в сети.",
|
"updateConfirmContent": "Каждый выбранный узел загрузит последний релиз и перезапустится. Обновляются только включённые узлы в сети.",
|
||||||
|
"updateDevChannel": "Обновить до канала разработки (последний коммит)",
|
||||||
"testConnection": "Проверить соединение",
|
"testConnection": "Проверить соединение",
|
||||||
"connectionOk": "Соединение в порядке ({ms} мс)",
|
"connectionOk": "Соединение в порядке ({ms} мс)",
|
||||||
"connectionFailed": "Не удалось подключиться",
|
"connectionFailed": "Не удалось подключиться",
|
||||||
@@ -1130,6 +1142,10 @@
|
|||||||
"subRoutingRulesDesc": "Глобальные правила маршрутизации для VPN-клиента. (Только для Happ)",
|
"subRoutingRulesDesc": "Глобальные правила маршрутизации для VPN-клиента. (Только для Happ)",
|
||||||
"subHideSettings": "Скрыть настройки сервера",
|
"subHideSettings": "Скрыть настройки сервера",
|
||||||
"subHideSettingsDesc": "Скрыть возможность просмотра и редактирования конфигурации сервера в VPN-клиенте. (Только для Happ)",
|
"subHideSettingsDesc": "Скрыть возможность просмотра и редактирования конфигурации сервера в VPN-клиенте. (Только для Happ)",
|
||||||
|
"subIncyEnableRouting": "Включить маршрутизацию",
|
||||||
|
"subIncyEnableRoutingDesc": "Внедрять профиль маршрутизации в тело подписки для клиента Incy. (Только для Incy)",
|
||||||
|
"subIncyRoutingRules": "Правила маршрутизации",
|
||||||
|
"subIncyRoutingRulesDesc": "Ссылка маршрутизации Incy, добавляемая в тело подписки, напр. incy://routing/onadd/<base64>. (Только для Incy)",
|
||||||
"subClashEnableRouting": "Включить маршрутизацию",
|
"subClashEnableRouting": "Включить маршрутизацию",
|
||||||
"subClashEnableRoutingDesc": "Добавлять глобальные правила маршрутизации Clash/Mihomo в сгенерированные YAML-подписки.",
|
"subClashEnableRoutingDesc": "Добавлять глобальные правила маршрутизации Clash/Mihomo в сгенерированные YAML-подписки.",
|
||||||
"subClashRoutingRules": "Глобальные правила маршрутизации",
|
"subClashRoutingRules": "Глобальные правила маршрутизации",
|
||||||
@@ -1806,7 +1822,8 @@
|
|||||||
"groups": {
|
"groups": {
|
||||||
"client": "Клиент",
|
"client": "Клиент",
|
||||||
"traffic": "Трафик",
|
"traffic": "Трафик",
|
||||||
"time": "Время и статус"
|
"time": "Время и статус",
|
||||||
|
"connection": "Подключение"
|
||||||
},
|
},
|
||||||
"descEMAIL": "Email клиента",
|
"descEMAIL": "Email клиента",
|
||||||
"descINBOUND": "Собственное примечание входящего (имя конфигурации)",
|
"descINBOUND": "Собственное примечание входящего (имя конфигурации)",
|
||||||
@@ -1825,11 +1842,18 @@
|
|||||||
"descUP": "Исходящий трафик",
|
"descUP": "Исходящий трафик",
|
||||||
"descDOWN": "Входящий трафик",
|
"descDOWN": "Входящий трафик",
|
||||||
"descSTATUS": "активен / истёк / отключён / исчерпан",
|
"descSTATUS": "активен / истёк / отключён / исчерпан",
|
||||||
|
"descSTATUS_EMOJI": "Статус в виде эмодзи (✅ ⏳ 🚫)",
|
||||||
"descDAYS_LEFT": "Дней до окончания (скрыто при безлимите)",
|
"descDAYS_LEFT": "Дней до окончания (скрыто при безлимите)",
|
||||||
|
"descTIME_LEFT": "Оставшееся время (например, 12d 4h 30m)",
|
||||||
|
"descUSAGE_PERCENTAGE": "Использованный трафик в процентах (скрыт при безлимите)",
|
||||||
"descEXPIRE_DATE": "Дата окончания (ГГГГ-ММ-ДД)",
|
"descEXPIRE_DATE": "Дата окончания (ГГГГ-ММ-ДД)",
|
||||||
|
"descJALALI_EXPIRE_DATE": "Дата окончания по календарю Jalali (ГГГГ/ММ/ДД)",
|
||||||
"descEXPIRE_UNIX": "Окончание в виде Unix-метки времени (секунды)",
|
"descEXPIRE_UNIX": "Окончание в виде Unix-метки времени (секунды)",
|
||||||
"descCREATED_UNIX": "Время создания в виде Unix-метки времени (секунды)",
|
"descCREATED_UNIX": "Время создания в виде Unix-метки времени (секунды)",
|
||||||
"descRESET_DAYS": "Период сброса трафика в днях"
|
"descRESET_DAYS": "Период сброса трафика в днях",
|
||||||
|
"descPROTOCOL": "Протокол входящего (VLESS, VMess, Trojan, …)",
|
||||||
|
"descTRANSPORT": "Транспортная сеть (tcp, ws, grpc, …)",
|
||||||
|
"descSECURITY": "Безопасность транспорта (TLS, REALITY, NONE)"
|
||||||
},
|
},
|
||||||
"toasts": {
|
"toasts": {
|
||||||
"list": "Не удалось загрузить хосты",
|
"list": "Не удалось загрузить хосты",
|
||||||
@@ -2062,4 +2086,4 @@
|
|||||||
"statusDown": "НЕДОСТУПЕН",
|
"statusDown": "НЕДОСТУПЕН",
|
||||||
"statusUp": "РАБОТАЕТ"
|
"statusUp": "РАБОТАЕТ"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -153,6 +153,11 @@
|
|||||||
"currentPanelVersion": "Mevcut panel sürümü",
|
"currentPanelVersion": "Mevcut panel sürümü",
|
||||||
"latestPanelVersion": "Panelin en son sürümü",
|
"latestPanelVersion": "Panelin en son sürümü",
|
||||||
"panelUpToDate": "Panel güncel",
|
"panelUpToDate": "Panel güncel",
|
||||||
|
"devChannel": "Geliştirme kanalı",
|
||||||
|
"devChannelWarning": "Geliştirme yapıları main üzerindeki her commit'i izler ve kararlı sürüm değildir — otomatik geri alma yoktur.",
|
||||||
|
"currentCommit": "Geçerli commit",
|
||||||
|
"latestCommit": "Son commit",
|
||||||
|
"updateChannelChanged": "Güncelleme kanalı değiştirildi",
|
||||||
"upToDate": "Güncel",
|
"upToDate": "Güncel",
|
||||||
"xrayStatusUnknown": "Bilinmiyor",
|
"xrayStatusUnknown": "Bilinmiyor",
|
||||||
"xrayStatusRunning": "Çalışıyor",
|
"xrayStatusRunning": "Çalışıyor",
|
||||||
@@ -402,10 +407,16 @@
|
|||||||
"sniffingDomainsExcluded": "Hariç tutulan alan adları",
|
"sniffingDomainsExcluded": "Hariç tutulan alan adları",
|
||||||
"decryption": "Şifre Çözme",
|
"decryption": "Şifre Çözme",
|
||||||
"encryption": "Şifreleme",
|
"encryption": "Şifreleme",
|
||||||
"vlessAuthX25519": "X25519 Kimlik Doğrulama",
|
"vlessAuthX25519": "X25519 (native)",
|
||||||
"vlessAuthMlkem768": "ML-KEM-768 Kimlik Doğrulama",
|
"vlessAuthMlkem768": "ML-KEM-768 (native)",
|
||||||
|
"vlessAuthX25519Xorpub": "X25519 (xorpub)",
|
||||||
|
"vlessAuthX25519Random": "X25519 (random)",
|
||||||
|
"vlessAuthMlkem768Xorpub": "ML-KEM-768 (xorpub)",
|
||||||
|
"vlessAuthMlkem768Random": "ML-KEM-768 (random)",
|
||||||
"vlessAuthCustom": "Özel",
|
"vlessAuthCustom": "Özel",
|
||||||
"vlessAuthSelected": "Seçili: {auth}",
|
"vlessAuthSelected": "Seçili: {auth}",
|
||||||
|
"vlessAuthGenerate": "Anahtar oluştur",
|
||||||
|
"vlessAuthGenerateButton": "Oluştur",
|
||||||
"advanced": {
|
"advanced": {
|
||||||
"title": "Gelen Bağlantı JSON Bölümleri",
|
"title": "Gelen Bağlantı JSON Bölümleri",
|
||||||
"subtitle": "Tam gelen bağlantı JSON'u ve settings, sniffing, streamSettings için odaklanmış düzenleyiciler.",
|
"subtitle": "Tam gelen bağlantı JSON'u ve settings, sniffing, streamSettings için odaklanmış düzenleyiciler.",
|
||||||
@@ -968,6 +979,7 @@
|
|||||||
"upToDate": "Güncel",
|
"upToDate": "Güncel",
|
||||||
"updateConfirmTitle": "{count} düğüm en son sürüme güncellensin mi?",
|
"updateConfirmTitle": "{count} düğüm en son sürüme güncellensin mi?",
|
||||||
"updateConfirmContent": "Seçilen her düğüm en son sürümü indirir ve yeniden başlatılır. Yalnızca etkin ve çevrimiçi düğümler güncellenir.",
|
"updateConfirmContent": "Seçilen her düğüm en son sürümü indirir ve yeniden başlatılır. Yalnızca etkin ve çevrimiçi düğümler güncellenir.",
|
||||||
|
"updateDevChannel": "Dev kanalına güncelle (son commit)",
|
||||||
"testConnection": "Bağlantıyı Test Et",
|
"testConnection": "Bağlantıyı Test Et",
|
||||||
"connectionOk": "Bağlantı tamam ({ms} ms)",
|
"connectionOk": "Bağlantı tamam ({ms} ms)",
|
||||||
"connectionFailed": "Bağlantı başarısız",
|
"connectionFailed": "Bağlantı başarısız",
|
||||||
@@ -1130,6 +1142,10 @@
|
|||||||
"subRoutingRulesDesc": "VPN istemcisi için genel yönlendirme kuralları. (Yalnızca Happ için)",
|
"subRoutingRulesDesc": "VPN istemcisi için genel yönlendirme kuralları. (Yalnızca Happ için)",
|
||||||
"subHideSettings": "Sunucu ayarlarını gizle",
|
"subHideSettings": "Sunucu ayarlarını gizle",
|
||||||
"subHideSettingsDesc": "VPN istemcisinde sunucu yapılandırmalarını görüntüleme ve düzenleme özelliğini gizleyin. (Yalnızca Happ için)",
|
"subHideSettingsDesc": "VPN istemcisinde sunucu yapılandırmalarını görüntüleme ve düzenleme özelliğini gizleyin. (Yalnızca Happ için)",
|
||||||
|
"subIncyEnableRouting": "Yönlendirmeyi etkinleştir",
|
||||||
|
"subIncyEnableRoutingDesc": "Incy istemcisi için abonelik gövdesine bir yönlendirme profili ekleyin. (Yalnızca Incy için)",
|
||||||
|
"subIncyRoutingRules": "Yönlendirme kuralları",
|
||||||
|
"subIncyRoutingRulesDesc": "Abonelik gövdesine eklenen Incy yönlendirme bağlantısı, örn. incy://routing/onadd/<base64>. (Yalnızca Incy için)",
|
||||||
"subClashEnableRouting": "Yönlendirmeyi Etkinleştir",
|
"subClashEnableRouting": "Yönlendirmeyi Etkinleştir",
|
||||||
"subClashEnableRoutingDesc": "Oluşturulan YAML aboneliklerine genel Clash/Mihomo yönlendirme kurallarını ekler.",
|
"subClashEnableRoutingDesc": "Oluşturulan YAML aboneliklerine genel Clash/Mihomo yönlendirme kurallarını ekler.",
|
||||||
"subClashRoutingRules": "Genel Yönlendirme Kuralları",
|
"subClashRoutingRules": "Genel Yönlendirme Kuralları",
|
||||||
@@ -1806,7 +1822,8 @@
|
|||||||
"groups": {
|
"groups": {
|
||||||
"client": "Kullanıcı",
|
"client": "Kullanıcı",
|
||||||
"traffic": "Trafik",
|
"traffic": "Trafik",
|
||||||
"time": "Zaman ve durum"
|
"time": "Zaman ve durum",
|
||||||
|
"connection": "Bağlantı"
|
||||||
},
|
},
|
||||||
"descEMAIL": "Kullanıcı e-postası",
|
"descEMAIL": "Kullanıcı e-postası",
|
||||||
"descINBOUND": "Gelen bağlantının kendi açıklaması (yapılandırma adı)",
|
"descINBOUND": "Gelen bağlantının kendi açıklaması (yapılandırma adı)",
|
||||||
@@ -1825,11 +1842,18 @@
|
|||||||
"descUP": "Yükleme trafiği",
|
"descUP": "Yükleme trafiği",
|
||||||
"descDOWN": "İndirme trafiği",
|
"descDOWN": "İndirme trafiği",
|
||||||
"descSTATUS": "aktif / süresi dolmuş / devre dışı / tükenmiş",
|
"descSTATUS": "aktif / süresi dolmuş / devre dışı / tükenmiş",
|
||||||
|
"descSTATUS_EMOJI": "Emoji olarak durum (✅ ⏳ 🚫)",
|
||||||
"descDAYS_LEFT": "Süre dolana kadar kalan gün (sınırsızsa gizlenir)",
|
"descDAYS_LEFT": "Süre dolana kadar kalan gün (sınırsızsa gizlenir)",
|
||||||
|
"descTIME_LEFT": "Kalan süre (örn. 12d 4h 30m)",
|
||||||
|
"descUSAGE_PERCENTAGE": "Kullanılan trafik yüzde olarak (sınırsızsa gizlenir)",
|
||||||
"descEXPIRE_DATE": "Son kullanma tarihi (YYYY-AA-GG)",
|
"descEXPIRE_DATE": "Son kullanma tarihi (YYYY-AA-GG)",
|
||||||
|
"descJALALI_EXPIRE_DATE": "Celali takvimine göre son kullanma tarihi (YYYY/MM/DD)",
|
||||||
"descEXPIRE_UNIX": "Son kullanma Unix zaman damgası olarak (saniye)",
|
"descEXPIRE_UNIX": "Son kullanma Unix zaman damgası olarak (saniye)",
|
||||||
"descCREATED_UNIX": "Oluşturulma zamanı Unix zaman damgası olarak (saniye)",
|
"descCREATED_UNIX": "Oluşturulma zamanı Unix zaman damgası olarak (saniye)",
|
||||||
"descRESET_DAYS": "Trafik sıfırlama periyodu (gün)"
|
"descRESET_DAYS": "Trafik sıfırlama periyodu (gün)",
|
||||||
|
"descPROTOCOL": "Gelen bağlantı protokolü (VLESS, VMess, Trojan, …)",
|
||||||
|
"descTRANSPORT": "Taşıma ağı (tcp, ws, grpc, …)",
|
||||||
|
"descSECURITY": "Taşıma güvenliği (TLS, REALITY, NONE)"
|
||||||
},
|
},
|
||||||
"toasts": {
|
"toasts": {
|
||||||
"list": "Host'lar yüklenemedi",
|
"list": "Host'lar yüklenemedi",
|
||||||
@@ -2062,4 +2086,4 @@
|
|||||||
"statusDown": "ÇEVRİMDIŞI",
|
"statusDown": "ÇEVRİMDIŞI",
|
||||||
"statusUp": "ÇEVRİMİÇİ"
|
"statusUp": "ÇEVRİMİÇİ"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -153,6 +153,11 @@
|
|||||||
"currentPanelVersion": "Поточна версія панелі",
|
"currentPanelVersion": "Поточна версія панелі",
|
||||||
"latestPanelVersion": "Остання версія панелі",
|
"latestPanelVersion": "Остання версія панелі",
|
||||||
"panelUpToDate": "Панель оновлено",
|
"panelUpToDate": "Панель оновлено",
|
||||||
|
"devChannel": "Канал розробки",
|
||||||
|
"devChannelWarning": "Збірки розробки відстежують кожен коміт у main і не є стабільними релізами — автоматичного відкату немає.",
|
||||||
|
"currentCommit": "Поточний коміт",
|
||||||
|
"latestCommit": "Останній коміт",
|
||||||
|
"updateChannelChanged": "Канал оновлення змінено",
|
||||||
"upToDate": "Оновлено",
|
"upToDate": "Оновлено",
|
||||||
"xrayStatusUnknown": "Невідомо",
|
"xrayStatusUnknown": "Невідомо",
|
||||||
"xrayStatusRunning": "Запущено",
|
"xrayStatusRunning": "Запущено",
|
||||||
@@ -402,10 +407,16 @@
|
|||||||
"sniffingDomainsExcluded": "Виключені домени",
|
"sniffingDomainsExcluded": "Виключені домени",
|
||||||
"decryption": "Розшифрування",
|
"decryption": "Розшифрування",
|
||||||
"encryption": "Шифрування",
|
"encryption": "Шифрування",
|
||||||
"vlessAuthX25519": "Автентифікація X25519",
|
"vlessAuthX25519": "X25519 (native)",
|
||||||
"vlessAuthMlkem768": "Автентифікація ML-KEM-768",
|
"vlessAuthMlkem768": "ML-KEM-768 (native)",
|
||||||
|
"vlessAuthX25519Xorpub": "X25519 (xorpub)",
|
||||||
|
"vlessAuthX25519Random": "X25519 (random)",
|
||||||
|
"vlessAuthMlkem768Xorpub": "ML-KEM-768 (xorpub)",
|
||||||
|
"vlessAuthMlkem768Random": "ML-KEM-768 (random)",
|
||||||
"vlessAuthCustom": "Користувацький",
|
"vlessAuthCustom": "Користувацький",
|
||||||
"vlessAuthSelected": "Вибрано: {auth}",
|
"vlessAuthSelected": "Вибрано: {auth}",
|
||||||
|
"vlessAuthGenerate": "Генерація ключів",
|
||||||
|
"vlessAuthGenerateButton": "Згенерувати",
|
||||||
"advanced": {
|
"advanced": {
|
||||||
"title": "Розділи JSON вхідного",
|
"title": "Розділи JSON вхідного",
|
||||||
"subtitle": "Повний JSON вхідного та окремі редактори для settings, sniffing і streamSettings.",
|
"subtitle": "Повний JSON вхідного та окремі редактори для settings, sniffing і streamSettings.",
|
||||||
@@ -968,6 +979,7 @@
|
|||||||
"upToDate": "Актуально",
|
"upToDate": "Актуально",
|
||||||
"updateConfirmTitle": "Оновити {count} вузлів до останньої версії?",
|
"updateConfirmTitle": "Оновити {count} вузлів до останньої версії?",
|
||||||
"updateConfirmContent": "Кожен вибраний вузол завантажить останній реліз і перезапуститься. Оновлюються лише увімкнені вузли в мережі.",
|
"updateConfirmContent": "Кожен вибраний вузол завантажить останній реліз і перезапуститься. Оновлюються лише увімкнені вузли в мережі.",
|
||||||
|
"updateDevChannel": "Оновити до каналу розробки (останній коміт)",
|
||||||
"testConnection": "Перевірити з'єднання",
|
"testConnection": "Перевірити з'єднання",
|
||||||
"connectionOk": "З'єднання в порядку ({ms} мс)",
|
"connectionOk": "З'єднання в порядку ({ms} мс)",
|
||||||
"connectionFailed": "Помилка з'єднання",
|
"connectionFailed": "Помилка з'єднання",
|
||||||
@@ -1130,6 +1142,10 @@
|
|||||||
"subRoutingRulesDesc": "Глобальні правила маршрутизації для VPN-клієнта. (Тільки для Happ)",
|
"subRoutingRulesDesc": "Глобальні правила маршрутизації для VPN-клієнта. (Тільки для Happ)",
|
||||||
"subHideSettings": "Приховати налаштування сервера",
|
"subHideSettings": "Приховати налаштування сервера",
|
||||||
"subHideSettingsDesc": "Приховати можливість перегляду та редагування конфігурації сервера у VPN-клієнті. (Тільки для Happ)",
|
"subHideSettingsDesc": "Приховати можливість перегляду та редагування конфігурації сервера у VPN-клієнті. (Тільки для Happ)",
|
||||||
|
"subIncyEnableRouting": "Увімкнути маршрутизацію",
|
||||||
|
"subIncyEnableRoutingDesc": "Вставляти профіль маршрутизації в тіло підписки для клієнта Incy. (Тільки для Incy)",
|
||||||
|
"subIncyRoutingRules": "Правила маршрутизації",
|
||||||
|
"subIncyRoutingRulesDesc": "Посилання маршрутизації Incy, що додається в тіло підписки, напр. incy://routing/onadd/<base64>. (Тільки для Incy)",
|
||||||
"subClashEnableRouting": "Увімкнути маршрутизацію",
|
"subClashEnableRouting": "Увімкнути маршрутизацію",
|
||||||
"subClashEnableRoutingDesc": "Додавати глобальні правила маршрутизації Clash/Mihomo до згенерованих YAML-підписок.",
|
"subClashEnableRoutingDesc": "Додавати глобальні правила маршрутизації Clash/Mihomo до згенерованих YAML-підписок.",
|
||||||
"subClashRoutingRules": "Глобальні правила маршрутизації",
|
"subClashRoutingRules": "Глобальні правила маршрутизації",
|
||||||
@@ -1806,7 +1822,8 @@
|
|||||||
"groups": {
|
"groups": {
|
||||||
"client": "Клієнт",
|
"client": "Клієнт",
|
||||||
"traffic": "Трафік",
|
"traffic": "Трафік",
|
||||||
"time": "Час і статус"
|
"time": "Час і статус",
|
||||||
|
"connection": "З'єднання"
|
||||||
},
|
},
|
||||||
"descEMAIL": "Email клієнта",
|
"descEMAIL": "Email клієнта",
|
||||||
"descINBOUND": "Власна примітка вхідного (назва конфігурації)",
|
"descINBOUND": "Власна примітка вхідного (назва конфігурації)",
|
||||||
@@ -1825,11 +1842,18 @@
|
|||||||
"descUP": "Вихідний трафік",
|
"descUP": "Вихідний трафік",
|
||||||
"descDOWN": "Вхідний трафік",
|
"descDOWN": "Вхідний трафік",
|
||||||
"descSTATUS": "active / expired / disabled / depleted",
|
"descSTATUS": "active / expired / disabled / depleted",
|
||||||
|
"descSTATUS_EMOJI": "Статус у вигляді емодзі (✅ ⏳ 🚫)",
|
||||||
"descDAYS_LEFT": "Днів до закінчення (прихований, якщо безлімітний)",
|
"descDAYS_LEFT": "Днів до закінчення (прихований, якщо безлімітний)",
|
||||||
|
"descTIME_LEFT": "Залишок часу (напр. 12d 4h 30m)",
|
||||||
|
"descUSAGE_PERCENTAGE": "Використаний трафік у відсотках (прихований, якщо безлімітний)",
|
||||||
"descEXPIRE_DATE": "Дата закінчення (YYYY-MM-DD)",
|
"descEXPIRE_DATE": "Дата закінчення (YYYY-MM-DD)",
|
||||||
|
"descJALALI_EXPIRE_DATE": "Дата закінчення за календарем Jalali (YYYY/MM/DD)",
|
||||||
"descEXPIRE_UNIX": "Закінчення як мітка часу Unix (секунди)",
|
"descEXPIRE_UNIX": "Закінчення як мітка часу Unix (секунди)",
|
||||||
"descCREATED_UNIX": "Час створення як мітка часу Unix (секунди)",
|
"descCREATED_UNIX": "Час створення як мітка часу Unix (секунди)",
|
||||||
"descRESET_DAYS": "Період скидання трафіку в днях"
|
"descRESET_DAYS": "Період скидання трафіку в днях",
|
||||||
|
"descPROTOCOL": "Протокол вхідного (VLESS, VMess, Trojan, …)",
|
||||||
|
"descTRANSPORT": "Транспортна мережа (tcp, ws, grpc, …)",
|
||||||
|
"descSECURITY": "Безпека транспорту (TLS, REALITY, NONE)"
|
||||||
},
|
},
|
||||||
"toasts": {
|
"toasts": {
|
||||||
"list": "Не вдалося завантажити хости",
|
"list": "Не вдалося завантажити хости",
|
||||||
@@ -2062,4 +2086,4 @@
|
|||||||
"statusDown": "НЕДОСТУПНО",
|
"statusDown": "НЕДОСТУПНО",
|
||||||
"statusUp": "ДОСТУПНО"
|
"statusUp": "ДОСТУПНО"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -153,6 +153,11 @@
|
|||||||
"currentPanelVersion": "Phiên bản panel hiện tại",
|
"currentPanelVersion": "Phiên bản panel hiện tại",
|
||||||
"latestPanelVersion": "Phiên bản panel mới nhất",
|
"latestPanelVersion": "Phiên bản panel mới nhất",
|
||||||
"panelUpToDate": "Panel đã được cập nhật",
|
"panelUpToDate": "Panel đã được cập nhật",
|
||||||
|
"devChannel": "Kênh phát triển",
|
||||||
|
"devChannelWarning": "Bản dev bám theo từng commit trên main và không phải bản ổn định — không có hạ cấp tự động.",
|
||||||
|
"currentCommit": "Commit hiện tại",
|
||||||
|
"latestCommit": "Commit mới nhất",
|
||||||
|
"updateChannelChanged": "Đã đổi kênh cập nhật",
|
||||||
"upToDate": "Đã cập nhật",
|
"upToDate": "Đã cập nhật",
|
||||||
"xrayStatusUnknown": "Không xác định",
|
"xrayStatusUnknown": "Không xác định",
|
||||||
"xrayStatusRunning": "Đang chạy",
|
"xrayStatusRunning": "Đang chạy",
|
||||||
@@ -402,10 +407,16 @@
|
|||||||
"sniffingDomainsExcluded": "Tên miền bị loại trừ",
|
"sniffingDomainsExcluded": "Tên miền bị loại trừ",
|
||||||
"decryption": "Giải mã",
|
"decryption": "Giải mã",
|
||||||
"encryption": "Mã hóa",
|
"encryption": "Mã hóa",
|
||||||
"vlessAuthX25519": "Xác thực X25519",
|
"vlessAuthX25519": "X25519 (native)",
|
||||||
"vlessAuthMlkem768": "Xác thực ML-KEM-768",
|
"vlessAuthMlkem768": "ML-KEM-768 (native)",
|
||||||
|
"vlessAuthX25519Xorpub": "X25519 (xorpub)",
|
||||||
|
"vlessAuthX25519Random": "X25519 (random)",
|
||||||
|
"vlessAuthMlkem768Xorpub": "ML-KEM-768 (xorpub)",
|
||||||
|
"vlessAuthMlkem768Random": "ML-KEM-768 (random)",
|
||||||
"vlessAuthCustom": "Tùy chỉnh",
|
"vlessAuthCustom": "Tùy chỉnh",
|
||||||
"vlessAuthSelected": "Đã chọn: {auth}",
|
"vlessAuthSelected": "Đã chọn: {auth}",
|
||||||
|
"vlessAuthGenerate": "Tạo khóa",
|
||||||
|
"vlessAuthGenerateButton": "Tạo",
|
||||||
"advanced": {
|
"advanced": {
|
||||||
"title": "Các phần JSON của inbound",
|
"title": "Các phần JSON của inbound",
|
||||||
"subtitle": "JSON inbound đầy đủ và các trình chỉnh sửa riêng cho settings, sniffing và streamSettings.",
|
"subtitle": "JSON inbound đầy đủ và các trình chỉnh sửa riêng cho settings, sniffing và streamSettings.",
|
||||||
@@ -968,6 +979,7 @@
|
|||||||
"upToDate": "Mới nhất",
|
"upToDate": "Mới nhất",
|
||||||
"updateConfirmTitle": "Cập nhật {count} node lên phiên bản mới nhất?",
|
"updateConfirmTitle": "Cập nhật {count} node lên phiên bản mới nhất?",
|
||||||
"updateConfirmContent": "Mỗi node đã chọn sẽ tải bản phát hành mới nhất và khởi động lại. Chỉ các node đang bật và trực tuyến được cập nhật.",
|
"updateConfirmContent": "Mỗi node đã chọn sẽ tải bản phát hành mới nhất và khởi động lại. Chỉ các node đang bật và trực tuyến được cập nhật.",
|
||||||
|
"updateDevChannel": "Cập nhật lên kênh phát triển (commit mới nhất)",
|
||||||
"testConnection": "Kiểm tra kết nối",
|
"testConnection": "Kiểm tra kết nối",
|
||||||
"connectionOk": "Kết nối OK ({ms} ms)",
|
"connectionOk": "Kết nối OK ({ms} ms)",
|
||||||
"connectionFailed": "Kết nối thất bại",
|
"connectionFailed": "Kết nối thất bại",
|
||||||
@@ -1130,6 +1142,10 @@
|
|||||||
"subRoutingRulesDesc": "Quy tắc định tuyến toàn cầu cho client VPN. (Chỉ dành cho Happ)",
|
"subRoutingRulesDesc": "Quy tắc định tuyến toàn cầu cho client VPN. (Chỉ dành cho Happ)",
|
||||||
"subHideSettings": "Ẩn cài đặt máy chủ",
|
"subHideSettings": "Ẩn cài đặt máy chủ",
|
||||||
"subHideSettingsDesc": "Ẩn khả năng xem và chỉnh sửa cấu hình máy chủ trong ứng dụng khách VPN. (Chỉ dành cho Happ)",
|
"subHideSettingsDesc": "Ẩn khả năng xem và chỉnh sửa cấu hình máy chủ trong ứng dụng khách VPN. (Chỉ dành cho Happ)",
|
||||||
|
"subIncyEnableRouting": "Bật định tuyến",
|
||||||
|
"subIncyEnableRoutingDesc": "Chèn hồ sơ định tuyến vào nội dung đăng ký cho ứng dụng Incy. (Chỉ dành cho Incy)",
|
||||||
|
"subIncyRoutingRules": "Quy tắc định tuyến",
|
||||||
|
"subIncyRoutingRulesDesc": "Liên kết định tuyến Incy được thêm vào nội dung đăng ký, ví dụ incy://routing/onadd/<base64>. (Chỉ dành cho Incy)",
|
||||||
"subClashEnableRouting": "Bật định tuyến",
|
"subClashEnableRouting": "Bật định tuyến",
|
||||||
"subClashEnableRoutingDesc": "Bao gồm quy tắc định tuyến Clash/Mihomo toàn cầu trong các đăng ký YAML được tạo.",
|
"subClashEnableRoutingDesc": "Bao gồm quy tắc định tuyến Clash/Mihomo toàn cầu trong các đăng ký YAML được tạo.",
|
||||||
"subClashRoutingRules": "Quy tắc định tuyến toàn cầu",
|
"subClashRoutingRules": "Quy tắc định tuyến toàn cầu",
|
||||||
@@ -1806,7 +1822,8 @@
|
|||||||
"groups": {
|
"groups": {
|
||||||
"client": "Khách hàng",
|
"client": "Khách hàng",
|
||||||
"traffic": "Lưu lượng",
|
"traffic": "Lưu lượng",
|
||||||
"time": "Thời gian & trạng thái"
|
"time": "Thời gian & trạng thái",
|
||||||
|
"connection": "Kết nối"
|
||||||
},
|
},
|
||||||
"descEMAIL": "Email khách hàng",
|
"descEMAIL": "Email khách hàng",
|
||||||
"descINBOUND": "Ghi chú của chính inbound (tên cấu hình)",
|
"descINBOUND": "Ghi chú của chính inbound (tên cấu hình)",
|
||||||
@@ -1825,11 +1842,18 @@
|
|||||||
"descUP": "Lưu lượng tải lên",
|
"descUP": "Lưu lượng tải lên",
|
||||||
"descDOWN": "Lưu lượng tải xuống",
|
"descDOWN": "Lưu lượng tải xuống",
|
||||||
"descSTATUS": "active / expired / disabled / depleted",
|
"descSTATUS": "active / expired / disabled / depleted",
|
||||||
|
"descSTATUS_EMOJI": "Trạng thái dạng biểu tượng cảm xúc (✅ ⏳ 🚫)",
|
||||||
"descDAYS_LEFT": "Số ngày đến khi hết hạn (ẩn nếu không giới hạn)",
|
"descDAYS_LEFT": "Số ngày đến khi hết hạn (ẩn nếu không giới hạn)",
|
||||||
|
"descTIME_LEFT": "Thời gian còn lại (ví dụ 12d 4h 30m)",
|
||||||
|
"descUSAGE_PERCENTAGE": "Lưu lượng đã dùng tính theo phần trăm (ẩn nếu không giới hạn)",
|
||||||
"descEXPIRE_DATE": "Ngày hết hạn (YYYY-MM-DD)",
|
"descEXPIRE_DATE": "Ngày hết hạn (YYYY-MM-DD)",
|
||||||
|
"descJALALI_EXPIRE_DATE": "Ngày hết hạn theo lịch Jalali (YYYY/MM/DD)",
|
||||||
"descEXPIRE_UNIX": "Hết hạn dạng dấu thời gian Unix (giây)",
|
"descEXPIRE_UNIX": "Hết hạn dạng dấu thời gian Unix (giây)",
|
||||||
"descCREATED_UNIX": "Thời điểm tạo dạng dấu thời gian Unix (giây)",
|
"descCREATED_UNIX": "Thời điểm tạo dạng dấu thời gian Unix (giây)",
|
||||||
"descRESET_DAYS": "Chu kỳ đặt lại lưu lượng tính theo ngày"
|
"descRESET_DAYS": "Chu kỳ đặt lại lưu lượng tính theo ngày",
|
||||||
|
"descPROTOCOL": "Giao thức inbound (VLESS, VMess, Trojan, …)",
|
||||||
|
"descTRANSPORT": "Mạng truyền tải (tcp, ws, grpc, …)",
|
||||||
|
"descSECURITY": "Bảo mật truyền tải (TLS, REALITY, NONE)"
|
||||||
},
|
},
|
||||||
"toasts": {
|
"toasts": {
|
||||||
"list": "Không tải được danh sách host",
|
"list": "Không tải được danh sách host",
|
||||||
@@ -2062,4 +2086,4 @@
|
|||||||
"statusDown": "NGỪNG HOẠT ĐỘNG",
|
"statusDown": "NGỪNG HOẠT ĐỘNG",
|
||||||
"statusUp": "HOẠT ĐỘNG"
|
"statusUp": "HOẠT ĐỘNG"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -153,6 +153,11 @@
|
|||||||
"currentPanelVersion": "当前面板版本",
|
"currentPanelVersion": "当前面板版本",
|
||||||
"latestPanelVersion": "最新面板版本",
|
"latestPanelVersion": "最新面板版本",
|
||||||
"panelUpToDate": "面板已是最新",
|
"panelUpToDate": "面板已是最新",
|
||||||
|
"devChannel": "开发通道",
|
||||||
|
"devChannelWarning": "开发版会跟踪 main 的每次提交,并非稳定版本,且无法自动降级。",
|
||||||
|
"currentCommit": "当前提交",
|
||||||
|
"latestCommit": "最新提交",
|
||||||
|
"updateChannelChanged": "更新通道已切换",
|
||||||
"upToDate": "已是最新",
|
"upToDate": "已是最新",
|
||||||
"xrayStatusUnknown": "未知",
|
"xrayStatusUnknown": "未知",
|
||||||
"xrayStatusRunning": "运行中",
|
"xrayStatusRunning": "运行中",
|
||||||
@@ -402,10 +407,16 @@
|
|||||||
"sniffingDomainsExcluded": "排除的域名",
|
"sniffingDomainsExcluded": "排除的域名",
|
||||||
"decryption": "解密",
|
"decryption": "解密",
|
||||||
"encryption": "加密",
|
"encryption": "加密",
|
||||||
"vlessAuthX25519": "X25519 认证",
|
"vlessAuthX25519": "X25519 (native)",
|
||||||
"vlessAuthMlkem768": "ML-KEM-768 认证",
|
"vlessAuthMlkem768": "ML-KEM-768 (native)",
|
||||||
|
"vlessAuthX25519Xorpub": "X25519 (xorpub)",
|
||||||
|
"vlessAuthX25519Random": "X25519 (random)",
|
||||||
|
"vlessAuthMlkem768Xorpub": "ML-KEM-768 (xorpub)",
|
||||||
|
"vlessAuthMlkem768Random": "ML-KEM-768 (random)",
|
||||||
"vlessAuthCustom": "自定义",
|
"vlessAuthCustom": "自定义",
|
||||||
"vlessAuthSelected": "已选择:{auth}",
|
"vlessAuthSelected": "已选择:{auth}",
|
||||||
|
"vlessAuthGenerate": "生成密钥",
|
||||||
|
"vlessAuthGenerateButton": "生成",
|
||||||
"advanced": {
|
"advanced": {
|
||||||
"title": "入站 JSON 部分",
|
"title": "入站 JSON 部分",
|
||||||
"subtitle": "完整入站 JSON 以及针对 settings、sniffing 和 streamSettings 的专用编辑器。",
|
"subtitle": "完整入站 JSON 以及针对 settings、sniffing 和 streamSettings 的专用编辑器。",
|
||||||
@@ -968,6 +979,7 @@
|
|||||||
"upToDate": "已是最新",
|
"upToDate": "已是最新",
|
||||||
"updateConfirmTitle": "将 {count} 个节点更新到最新版本?",
|
"updateConfirmTitle": "将 {count} 个节点更新到最新版本?",
|
||||||
"updateConfirmContent": "每个所选节点会下载最新版本并重启。仅更新已启用且在线的节点。",
|
"updateConfirmContent": "每个所选节点会下载最新版本并重启。仅更新已启用且在线的节点。",
|
||||||
|
"updateDevChannel": "更新到开发通道(最新提交)",
|
||||||
"testConnection": "测试连接",
|
"testConnection": "测试连接",
|
||||||
"connectionOk": "连接正常 ({ms} ms)",
|
"connectionOk": "连接正常 ({ms} ms)",
|
||||||
"connectionFailed": "连接失败",
|
"connectionFailed": "连接失败",
|
||||||
@@ -1130,6 +1142,10 @@
|
|||||||
"subRoutingRulesDesc": "VPN 用户端的全域路由规则。(仅限 Happ)",
|
"subRoutingRulesDesc": "VPN 用户端的全域路由规则。(仅限 Happ)",
|
||||||
"subHideSettings": "隐藏服务器设置",
|
"subHideSettings": "隐藏服务器设置",
|
||||||
"subHideSettingsDesc": "在 VPN 客户端中隐藏查看和编辑服务器配置的功能。(仅限 Happ)",
|
"subHideSettingsDesc": "在 VPN 客户端中隐藏查看和编辑服务器配置的功能。(仅限 Happ)",
|
||||||
|
"subIncyEnableRouting": "启用路由",
|
||||||
|
"subIncyEnableRoutingDesc": "为 Incy 客户端将路由配置注入订阅内容中。(仅限 Incy)",
|
||||||
|
"subIncyRoutingRules": "路由规则",
|
||||||
|
"subIncyRoutingRulesDesc": "添加到订阅内容的 Incy 路由深层链接,例如 incy://routing/onadd/<base64>。(仅限 Incy)",
|
||||||
"subClashEnableRouting": "启用路由",
|
"subClashEnableRouting": "启用路由",
|
||||||
"subClashEnableRoutingDesc": "在生成的 YAML 订阅中包含 Clash/Mihomo 全局路由规则。",
|
"subClashEnableRoutingDesc": "在生成的 YAML 订阅中包含 Clash/Mihomo 全局路由规则。",
|
||||||
"subClashRoutingRules": "全局路由规则",
|
"subClashRoutingRules": "全局路由规则",
|
||||||
@@ -1806,7 +1822,8 @@
|
|||||||
"groups": {
|
"groups": {
|
||||||
"client": "客户端",
|
"client": "客户端",
|
||||||
"traffic": "流量",
|
"traffic": "流量",
|
||||||
"time": "时间与状态"
|
"time": "时间与状态",
|
||||||
|
"connection": "连接"
|
||||||
},
|
},
|
||||||
"descEMAIL": "客户端邮箱",
|
"descEMAIL": "客户端邮箱",
|
||||||
"descINBOUND": "入站本身的备注(配置名称)",
|
"descINBOUND": "入站本身的备注(配置名称)",
|
||||||
@@ -1825,11 +1842,18 @@
|
|||||||
"descUP": "上传流量",
|
"descUP": "上传流量",
|
||||||
"descDOWN": "下载流量",
|
"descDOWN": "下载流量",
|
||||||
"descSTATUS": "active / expired / disabled / depleted",
|
"descSTATUS": "active / expired / disabled / depleted",
|
||||||
|
"descSTATUS_EMOJI": "以表情符号显示状态(✅ ⏳ 🚫)",
|
||||||
"descDAYS_LEFT": "距到期天数(无限制时隐藏)",
|
"descDAYS_LEFT": "距到期天数(无限制时隐藏)",
|
||||||
|
"descTIME_LEFT": "剩余时间(例如 12d 4h 30m)",
|
||||||
|
"descUSAGE_PERCENTAGE": "已用流量百分比(无限制时隐藏)",
|
||||||
"descEXPIRE_DATE": "到期日期(YYYY-MM-DD)",
|
"descEXPIRE_DATE": "到期日期(YYYY-MM-DD)",
|
||||||
|
"descJALALI_EXPIRE_DATE": "Jalali(波斯)历的到期日期(YYYY/MM/DD)",
|
||||||
"descEXPIRE_UNIX": "到期时间的 Unix 时间戳(秒)",
|
"descEXPIRE_UNIX": "到期时间的 Unix 时间戳(秒)",
|
||||||
"descCREATED_UNIX": "创建时间的 Unix 时间戳(秒)",
|
"descCREATED_UNIX": "创建时间的 Unix 时间戳(秒)",
|
||||||
"descRESET_DAYS": "流量重置周期(天)"
|
"descRESET_DAYS": "流量重置周期(天)",
|
||||||
|
"descPROTOCOL": "入站协议(VLESS、VMess、Trojan……)",
|
||||||
|
"descTRANSPORT": "传输网络(tcp、ws、grpc……)",
|
||||||
|
"descSECURITY": "传输安全(TLS、REALITY、NONE)"
|
||||||
},
|
},
|
||||||
"toasts": {
|
"toasts": {
|
||||||
"list": "加载主机失败",
|
"list": "加载主机失败",
|
||||||
@@ -2062,4 +2086,4 @@
|
|||||||
"statusDown": "断开",
|
"statusDown": "断开",
|
||||||
"statusUp": "恢复"
|
"statusUp": "恢复"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -153,6 +153,11 @@
|
|||||||
"currentPanelVersion": "目前面板版本",
|
"currentPanelVersion": "目前面板版本",
|
||||||
"latestPanelVersion": "最新面板版本",
|
"latestPanelVersion": "最新面板版本",
|
||||||
"panelUpToDate": "面板已是最新",
|
"panelUpToDate": "面板已是最新",
|
||||||
|
"devChannel": "開發通道",
|
||||||
|
"devChannelWarning": "開發版會追蹤 main 的每次提交,並非穩定版本,且無法自動降級。",
|
||||||
|
"currentCommit": "目前提交",
|
||||||
|
"latestCommit": "最新提交",
|
||||||
|
"updateChannelChanged": "更新通道已切換",
|
||||||
"upToDate": "已是最新",
|
"upToDate": "已是最新",
|
||||||
"xrayStatusUnknown": "未知",
|
"xrayStatusUnknown": "未知",
|
||||||
"xrayStatusRunning": "運行中",
|
"xrayStatusRunning": "運行中",
|
||||||
@@ -402,10 +407,16 @@
|
|||||||
"sniffingDomainsExcluded": "排除的網域",
|
"sniffingDomainsExcluded": "排除的網域",
|
||||||
"decryption": "解密",
|
"decryption": "解密",
|
||||||
"encryption": "加密",
|
"encryption": "加密",
|
||||||
"vlessAuthX25519": "X25519 認證",
|
"vlessAuthX25519": "X25519 (native)",
|
||||||
"vlessAuthMlkem768": "ML-KEM-768 認證",
|
"vlessAuthMlkem768": "ML-KEM-768 (native)",
|
||||||
|
"vlessAuthX25519Xorpub": "X25519 (xorpub)",
|
||||||
|
"vlessAuthX25519Random": "X25519 (random)",
|
||||||
|
"vlessAuthMlkem768Xorpub": "ML-KEM-768 (xorpub)",
|
||||||
|
"vlessAuthMlkem768Random": "ML-KEM-768 (random)",
|
||||||
"vlessAuthCustom": "自訂",
|
"vlessAuthCustom": "自訂",
|
||||||
"vlessAuthSelected": "已選擇:{auth}",
|
"vlessAuthSelected": "已選擇:{auth}",
|
||||||
|
"vlessAuthGenerate": "生成密鑰",
|
||||||
|
"vlessAuthGenerateButton": "生成",
|
||||||
"advanced": {
|
"advanced": {
|
||||||
"title": "入站 JSON 部分",
|
"title": "入站 JSON 部分",
|
||||||
"subtitle": "完整入站 JSON 以及針對 settings、sniffing 和 streamSettings 的專用編輯器。",
|
"subtitle": "完整入站 JSON 以及針對 settings、sniffing 和 streamSettings 的專用編輯器。",
|
||||||
@@ -968,6 +979,7 @@
|
|||||||
"upToDate": "已是最新",
|
"upToDate": "已是最新",
|
||||||
"updateConfirmTitle": "將 {count} 個節點更新到最新版本?",
|
"updateConfirmTitle": "將 {count} 個節點更新到最新版本?",
|
||||||
"updateConfirmContent": "每個所選節點會下載最新版本並重新啟動。僅更新已啟用且在線的節點。",
|
"updateConfirmContent": "每個所選節點會下載最新版本並重新啟動。僅更新已啟用且在線的節點。",
|
||||||
|
"updateDevChannel": "更新到開發通道(最新提交)",
|
||||||
"testConnection": "測試連線",
|
"testConnection": "測試連線",
|
||||||
"connectionOk": "連線正常 ({ms} ms)",
|
"connectionOk": "連線正常 ({ms} ms)",
|
||||||
"connectionFailed": "連線失敗",
|
"connectionFailed": "連線失敗",
|
||||||
@@ -1130,6 +1142,10 @@
|
|||||||
"subRoutingRulesDesc": "VPN 用戶端的全域路由規則。(僅限 Happ)",
|
"subRoutingRulesDesc": "VPN 用戶端的全域路由規則。(僅限 Happ)",
|
||||||
"subHideSettings": "隱藏伺服器設定",
|
"subHideSettings": "隱藏伺服器設定",
|
||||||
"subHideSettingsDesc": "在 VPN 用戶端中隱藏查看和編輯伺服器配置的功能。(僅限 Happ)",
|
"subHideSettingsDesc": "在 VPN 用戶端中隱藏查看和編輯伺服器配置的功能。(僅限 Happ)",
|
||||||
|
"subIncyEnableRouting": "啟用路由",
|
||||||
|
"subIncyEnableRoutingDesc": "為 Incy 用戶端將路由設定檔注入訂閱內容中。(僅限 Incy)",
|
||||||
|
"subIncyRoutingRules": "路由規則",
|
||||||
|
"subIncyRoutingRulesDesc": "加入訂閱內容的 Incy 路由深層連結,例如 incy://routing/onadd/<base64>。(僅限 Incy)",
|
||||||
"subClashEnableRouting": "啟用路由",
|
"subClashEnableRouting": "啟用路由",
|
||||||
"subClashEnableRoutingDesc": "在產生的 YAML 訂閱中包含 Clash/Mihomo 全域路由規則。",
|
"subClashEnableRoutingDesc": "在產生的 YAML 訂閱中包含 Clash/Mihomo 全域路由規則。",
|
||||||
"subClashRoutingRules": "全域路由規則",
|
"subClashRoutingRules": "全域路由規則",
|
||||||
@@ -1806,7 +1822,8 @@
|
|||||||
"groups": {
|
"groups": {
|
||||||
"client": "客戶端",
|
"client": "客戶端",
|
||||||
"traffic": "流量",
|
"traffic": "流量",
|
||||||
"time": "時間與狀態"
|
"time": "時間與狀態",
|
||||||
|
"connection": "連線"
|
||||||
},
|
},
|
||||||
"descEMAIL": "客戶端電子郵件",
|
"descEMAIL": "客戶端電子郵件",
|
||||||
"descINBOUND": "入站本身的備註(配置名稱)",
|
"descINBOUND": "入站本身的備註(配置名稱)",
|
||||||
@@ -1825,11 +1842,18 @@
|
|||||||
"descUP": "上傳流量",
|
"descUP": "上傳流量",
|
||||||
"descDOWN": "下載流量",
|
"descDOWN": "下載流量",
|
||||||
"descSTATUS": "active / expired / disabled / depleted",
|
"descSTATUS": "active / expired / disabled / depleted",
|
||||||
|
"descSTATUS_EMOJI": "以表情符號表示的狀態(✅ ⏳ 🚫)",
|
||||||
"descDAYS_LEFT": "距到期天數(無限制時隱藏)",
|
"descDAYS_LEFT": "距到期天數(無限制時隱藏)",
|
||||||
|
"descTIME_LEFT": "剩餘時間(例如 12d 4h 30m)",
|
||||||
|
"descUSAGE_PERCENTAGE": "已用流量百分比(無限制時隱藏)",
|
||||||
"descEXPIRE_DATE": "到期日期(YYYY-MM-DD)",
|
"descEXPIRE_DATE": "到期日期(YYYY-MM-DD)",
|
||||||
|
"descJALALI_EXPIRE_DATE": "Jalali 曆的到期日期(YYYY/MM/DD)",
|
||||||
"descEXPIRE_UNIX": "到期時間(Unix 時間戳記,秒)",
|
"descEXPIRE_UNIX": "到期時間(Unix 時間戳記,秒)",
|
||||||
"descCREATED_UNIX": "建立時間(Unix 時間戳記,秒)",
|
"descCREATED_UNIX": "建立時間(Unix 時間戳記,秒)",
|
||||||
"descRESET_DAYS": "流量重置週期(天)"
|
"descRESET_DAYS": "流量重置週期(天)",
|
||||||
|
"descPROTOCOL": "入站協定(VLESS、VMess、Trojan…)",
|
||||||
|
"descTRANSPORT": "傳輸網路(tcp、ws、grpc…)",
|
||||||
|
"descSECURITY": "傳輸安全(TLS、REALITY、NONE)"
|
||||||
},
|
},
|
||||||
"toasts": {
|
"toasts": {
|
||||||
"list": "載入 Host 失敗",
|
"list": "載入 Host 失敗",
|
||||||
@@ -2062,4 +2086,4 @@
|
|||||||
"statusDown": "中斷",
|
"statusDown": "中斷",
|
||||||
"statusUp": "恢復"
|
"statusUp": "恢復"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+27
-1
@@ -264,8 +264,12 @@ func (s *Server) initRouter() (*gin.Engine, error) {
|
|||||||
c.JSON(http.StatusOK, gin.H{})
|
c.JSON(http.StatusOK, gin.H{})
|
||||||
})
|
})
|
||||||
|
|
||||||
// Add a catch-all route to handle undefined paths and return 404
|
// Let unknown panel document routes fall back to the SPA shell, while every
|
||||||
|
// non-SPA miss still returns a hard 404.
|
||||||
engine.NoRoute(func(c *gin.Context) {
|
engine.NoRoute(func(c *gin.Context) {
|
||||||
|
if s.panel.HandleNoRoutePanelSPA(c) {
|
||||||
|
return
|
||||||
|
}
|
||||||
c.AbortWithStatus(http.StatusNotFound)
|
c.AbortWithStatus(http.StatusNotFound)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -619,6 +623,28 @@ func (s *Server) start(restartXray bool, startTgBot bool) (err error) {
|
|||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
|
controller.SetReloadTgbotFunc(func() {
|
||||||
|
enabled, err := s.settingService.GetTgbotEnabled()
|
||||||
|
if err != nil || !enabled {
|
||||||
|
if s.tgbotService.IsRunning() {
|
||||||
|
s.tgbotService.Stop()
|
||||||
|
}
|
||||||
|
if s.bus != nil {
|
||||||
|
s.bus.Unsubscribe("tg-notifier")
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Start() stops any previous receiver first, so it is safe whether or not the bot is already running.
|
||||||
|
tgBot := s.tgbotService.NewTgbot()
|
||||||
|
if startErr := tgBot.Start(i18nFS); startErr != nil {
|
||||||
|
logger.Warning("reload Telegram bot failed:", startErr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if s.bus != nil {
|
||||||
|
s.bus.Subscribe("tg-notifier", s.tgbotService.HandleEvent)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
s.startTask(restartXray)
|
s.startTask(restartXray)
|
||||||
|
|
||||||
if startTgBot {
|
if startTgBot {
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
@@ -18,6 +19,7 @@ import (
|
|||||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||||
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||||
"github.com/mhsanaei/3x-ui/v3/internal/sub"
|
"github.com/mhsanaei/3x-ui/v3/internal/sub"
|
||||||
|
"github.com/mhsanaei/3x-ui/v3/internal/tunnelmonitor"
|
||||||
"github.com/mhsanaei/3x-ui/v3/internal/util/crypto"
|
"github.com/mhsanaei/3x-ui/v3/internal/util/crypto"
|
||||||
"github.com/mhsanaei/3x-ui/v3/internal/util/sys"
|
"github.com/mhsanaei/3x-ui/v3/internal/util/sys"
|
||||||
"github.com/mhsanaei/3x-ui/v3/internal/web"
|
"github.com/mhsanaei/3x-ui/v3/internal/web"
|
||||||
@@ -91,7 +93,7 @@ func runWebServer() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
sigCh := make(chan os.Signal, 1)
|
sigCh := make(chan os.Signal, 8)
|
||||||
// Trap shutdown signals
|
// Trap shutdown signals
|
||||||
signal.Notify(sigCh, syscall.SIGHUP, syscall.SIGTERM, sys.SIGUSR1, os.Interrupt)
|
signal.Notify(sigCh, syscall.SIGHUP, syscall.SIGTERM, sys.SIGUSR1, os.Interrupt)
|
||||||
global.SetRestartHook(func() {
|
global.SetRestartHook(func() {
|
||||||
@@ -100,6 +102,27 @@ func runWebServer() {
|
|||||||
default:
|
default:
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
var stopTunnelHealthMonitor context.CancelFunc
|
||||||
|
monitorCfg := tunnelmonitor.ConfigFromEnv()
|
||||||
|
if monitorCfg.Enabled {
|
||||||
|
if monitorCfg.ProxyURL == "" {
|
||||||
|
logger.Warning("Tunnel health monitor enabled without XUI_TUNNEL_HEALTH_PROXY: the probe measures host connectivity, not the xray tunnel, so failures will restart xray without fixing host network issues")
|
||||||
|
}
|
||||||
|
|
||||||
|
monitorCtx, cancel := context.WithCancel(context.Background())
|
||||||
|
stopTunnelHealthMonitor = cancel
|
||||||
|
|
||||||
|
monitor, err := tunnelmonitor.New(monitorCfg, func(_ context.Context) error {
|
||||||
|
logger.Warning("Tunnel health monitor threshold reached, restarting xray-core")
|
||||||
|
return server.RestartXray()
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
logger.Warning("Tunnel health monitor disabled: ", err)
|
||||||
|
} else {
|
||||||
|
go monitor.Run(monitorCtx)
|
||||||
|
}
|
||||||
|
}
|
||||||
for {
|
for {
|
||||||
sig := <-sigCh
|
sig := <-sigCh
|
||||||
|
|
||||||
@@ -142,6 +165,10 @@ func runWebServer() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
default:
|
default:
|
||||||
|
if stopTunnelHealthMonitor != nil {
|
||||||
|
stopTunnelHealthMonitor()
|
||||||
|
}
|
||||||
|
|
||||||
// --- FIX FOR TELEGRAM BOT CONFLICT (409) on full shutdown ---
|
// --- FIX FOR TELEGRAM BOT CONFLICT (409) on full shutdown ---
|
||||||
tgbot.StopBot()
|
tgbot.StopBot()
|
||||||
// ------------------------------------------------------------
|
// ------------------------------------------------------------
|
||||||
|
|||||||
@@ -895,9 +895,16 @@ update_x-ui() {
|
|||||||
|
|
||||||
echo -e "${green}Downloading new x-ui version...${plain}"
|
echo -e "${green}Downloading new x-ui version...${plain}"
|
||||||
|
|
||||||
tag_version=$(${curl_bin} -Ls "https://api.github.com/repos/MHSanaei/3x-ui/releases/latest" 2> /dev/null | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
|
# XUI_UPDATE_TAG lets the panel target a specific release tag (e.g. the
|
||||||
if [[ ! -n "$tag_version" ]]; then
|
# rolling dev-latest pre-release). Empty keeps the default latest-stable flow.
|
||||||
_fail "ERROR: Failed to fetch x-ui version, it may be due to GitHub API restrictions, please try it later"
|
if [[ -n "${XUI_UPDATE_TAG}" ]]; then
|
||||||
|
tag_version="${XUI_UPDATE_TAG}"
|
||||||
|
echo -e "${green}Using update tag: ${tag_version}${plain}"
|
||||||
|
else
|
||||||
|
tag_version=$(${curl_bin} -Ls "https://api.github.com/repos/MHSanaei/3x-ui/releases/latest" 2> /dev/null | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
|
||||||
|
if [[ ! -n "$tag_version" ]]; then
|
||||||
|
_fail "ERROR: Failed to fetch x-ui version, it may be due to GitHub API restrictions, please try it later"
|
||||||
|
fi
|
||||||
fi
|
fi
|
||||||
echo -e "Got x-ui latest version: ${tag_version}, beginning the installation..."
|
echo -e "Got x-ui latest version: ${tag_version}, beginning the installation..."
|
||||||
${curl_bin} -fLRo ${xui_folder}-linux-$(arch).tar.gz https://github.com/MHSanaei/3x-ui/releases/download/${tag_version}/x-ui-linux-$(arch).tar.gz 2> /dev/null
|
${curl_bin} -fLRo ${xui_folder}-linux-$(arch).tar.gz https://github.com/MHSanaei/3x-ui/releases/download/${tag_version}/x-ui-linux-$(arch).tar.gz 2> /dev/null
|
||||||
|
|||||||
@@ -155,6 +155,24 @@ update() {
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
update_dev() {
|
||||||
|
confirm "This will update x-ui to the latest DEV commit (the rolling 'dev-latest' build, not a stable release). Your data is preserved. Continue?" "y"
|
||||||
|
if [[ $? != 0 ]]; then
|
||||||
|
LOGE "Cancelled"
|
||||||
|
if [[ $# == 0 ]]; then
|
||||||
|
before_show_menu
|
||||||
|
fi
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
# XUI_UPDATE_TAG tells update.sh to install the dev-latest pre-release
|
||||||
|
# instead of the latest stable tag.
|
||||||
|
XUI_UPDATE_TAG="dev-latest" bash <(curl -Ls https://raw.githubusercontent.com/MHSanaei/3x-ui/main/update.sh)
|
||||||
|
if [[ $? == 0 ]]; then
|
||||||
|
LOGI "Dev update is complete, Panel has automatically restarted "
|
||||||
|
before_show_menu
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
update_menu() {
|
update_menu() {
|
||||||
echo -e "${yellow}Updating Menu${plain}"
|
echo -e "${yellow}Updating Menu${plain}"
|
||||||
confirm "This function will update the menu to the latest changes." "y"
|
confirm "This function will update the menu to the latest changes." "y"
|
||||||
@@ -3104,6 +3122,7 @@ show_usage() {
|
|||||||
│ ${blue}x-ui log${plain} - Check logs │
|
│ ${blue}x-ui log${plain} - Check logs │
|
||||||
│ ${blue}x-ui banlog${plain} - Check Fail2ban ban logs │
|
│ ${blue}x-ui banlog${plain} - Check Fail2ban ban logs │
|
||||||
│ ${blue}x-ui update${plain} - Update │
|
│ ${blue}x-ui update${plain} - Update │
|
||||||
|
│ ${blue}x-ui update-dev${plain} - Update to Dev channel (latest) │
|
||||||
│ ${blue}x-ui update-all-geofiles${plain} - Update all geo files │
|
│ ${blue}x-ui update-all-geofiles${plain} - Update all geo files │
|
||||||
│ ${blue}x-ui migrateDB [file]${plain} - Convert .db <-> .dump (SQLite) │
|
│ ${blue}x-ui migrateDB [file]${plain} - Convert .db <-> .dump (SQLite) │
|
||||||
│ ${blue}x-ui legacy${plain} - Legacy version │
|
│ ${blue}x-ui legacy${plain} - Legacy version │
|
||||||
@@ -3115,46 +3134,46 @@ show_usage() {
|
|||||||
show_menu() {
|
show_menu() {
|
||||||
echo -e "
|
echo -e "
|
||||||
╔────────────────────────────────────────────────╗
|
╔────────────────────────────────────────────────╗
|
||||||
│ ${green}3X-UI Panel Management Script${plain} │
|
│ ${green}3X-UI Panel Management Script${plain} │
|
||||||
│ ${green}0.${plain} Exit Script │
|
│ ${green}0.${plain} Exit Script │
|
||||||
│────────────────────────────────────────────────│
|
│────────────────────────────────────────────────│
|
||||||
│ ${green}1.${plain} Install │
|
│ ${green}1.${plain} Install │
|
||||||
│ ${green}2.${plain} Update │
|
│ ${green}2.${plain} Update │
|
||||||
│ ${green}3.${plain} Update Menu │
|
│ ${green}3.${plain} Update to Dev Channel (latest commit) │
|
||||||
│ ${green}4.${plain} Legacy Version │
|
│ ${green}4.${plain} Update Menu │
|
||||||
│ ${green}5.${plain} Uninstall │
|
│ ${green}5.${plain} Legacy Version │
|
||||||
|
│ ${green}6.${plain} Uninstall │
|
||||||
│────────────────────────────────────────────────│
|
│────────────────────────────────────────────────│
|
||||||
│ ${green}6.${plain} Reset Username & Password │
|
│ ${green}7.${plain} Reset Username & Password │
|
||||||
│ ${green}7.${plain} Reset Web Base Path │
|
│ ${green}8.${plain} Reset Web Base Path │
|
||||||
│ ${green}8.${plain} Reset Settings │
|
│ ${green}9.${plain} Reset Settings │
|
||||||
│ ${green}9.${plain} Change Port │
|
│ ${green}10.${plain} Change Port │
|
||||||
│ ${green}10.${plain} View Current Settings │
|
│ ${green}11.${plain} View Current Settings │
|
||||||
│────────────────────────────────────────────────│
|
│────────────────────────────────────────────────│
|
||||||
│ ${green}11.${plain} Start │
|
│ ${green}12.${plain} Start │
|
||||||
│ ${green}12.${plain} Stop │
|
│ ${green}13.${plain} Stop │
|
||||||
│ ${green}13.${plain} Restart │
|
│ ${green}14.${plain} Restart │
|
||||||
| ${green}14.${plain} Restart Xray │
|
| ${green}15.${plain} Restart Xray │
|
||||||
│ ${green}15.${plain} Check Status │
|
│ ${green}16.${plain} Check Status │
|
||||||
│ ${green}16.${plain} Logs Management │
|
│ ${green}17.${plain} Logs Management │
|
||||||
│────────────────────────────────────────────────│
|
│────────────────────────────────────────────────│
|
||||||
│ ${green}17.${plain} Enable Autostart │
|
│ ${green}18.${plain} Enable Autostart │
|
||||||
│ ${green}18.${plain} Disable Autostart │
|
│ ${green}19.${plain} Disable Autostart │
|
||||||
│────────────────────────────────────────────────│
|
│────────────────────────────────────────────────│
|
||||||
│ ${green}19.${plain} SSL Certificate Management │
|
│ ${green}20.${plain} SSL Certificate Management │
|
||||||
│ ${green}20.${plain} Cloudflare SSL Certificate │
|
│ ${green}21.${plain} Cloudflare SSL Certificate │
|
||||||
│ ${green}21.${plain} IP Limit Management │
|
│ ${green}22.${plain} IP Limit Management │
|
||||||
│ ${green}22.${plain} Firewall Management │
|
│ ${green}23.${plain} Firewall Management │
|
||||||
│ ${green}23.${plain} SSH Port Forwarding Management │
|
│ ${green}24.${plain} SSH Port Forwarding Management │
|
||||||
|
│ ${green}25.${plain} PostgreSQL Management │
|
||||||
│────────────────────────────────────────────────│
|
│────────────────────────────────────────────────│
|
||||||
│ ${green}24.${plain} Enable BBR │
|
│ ${green}26.${plain} Enable BBR │
|
||||||
│ ${green}25.${plain} Update Geo Files │
|
│ ${green}27.${plain} Update Geo Files │
|
||||||
│ ${green}26.${plain} Speedtest by Ookla │
|
│ ${green}28.${plain} Speedtest by Ookla │
|
||||||
│────────────────────────────────────────────────│
|
|
||||||
│ ${green}27.${plain} PostgreSQL Management │
|
|
||||||
╚────────────────────────────────────────────────╝
|
╚────────────────────────────────────────────────╝
|
||||||
"
|
"
|
||||||
show_status
|
show_status
|
||||||
echo && read -rp "Please enter your selection [0-27]: " num
|
echo && read -rp "Please enter your selection [0-28]: " num
|
||||||
|
|
||||||
case "${num}" in
|
case "${num}" in
|
||||||
0)
|
0)
|
||||||
@@ -3167,82 +3186,85 @@ show_menu() {
|
|||||||
check_install && update
|
check_install && update
|
||||||
;;
|
;;
|
||||||
3)
|
3)
|
||||||
check_install && update_menu
|
check_install && update_dev
|
||||||
;;
|
;;
|
||||||
4)
|
4)
|
||||||
check_install && legacy_version
|
check_install && update_menu
|
||||||
;;
|
;;
|
||||||
5)
|
5)
|
||||||
check_install && uninstall
|
check_install && legacy_version
|
||||||
;;
|
;;
|
||||||
6)
|
6)
|
||||||
check_install && reset_user
|
check_install && uninstall
|
||||||
;;
|
;;
|
||||||
7)
|
7)
|
||||||
check_install && reset_webbasepath
|
check_install && reset_user
|
||||||
;;
|
;;
|
||||||
8)
|
8)
|
||||||
check_install && reset_config
|
check_install && reset_webbasepath
|
||||||
;;
|
;;
|
||||||
9)
|
9)
|
||||||
check_install && set_port
|
check_install && reset_config
|
||||||
;;
|
;;
|
||||||
10)
|
10)
|
||||||
check_install && check_config
|
check_install && set_port
|
||||||
;;
|
;;
|
||||||
11)
|
11)
|
||||||
check_install && start
|
check_install && check_config
|
||||||
;;
|
;;
|
||||||
12)
|
12)
|
||||||
check_install && stop
|
check_install && start
|
||||||
;;
|
;;
|
||||||
13)
|
13)
|
||||||
check_install && restart
|
check_install && stop
|
||||||
;;
|
;;
|
||||||
14)
|
14)
|
||||||
check_install && restart_xray
|
check_install && restart
|
||||||
;;
|
;;
|
||||||
15)
|
15)
|
||||||
check_install && status
|
check_install && restart_xray
|
||||||
;;
|
;;
|
||||||
16)
|
16)
|
||||||
check_install && show_log
|
check_install && status
|
||||||
;;
|
;;
|
||||||
17)
|
17)
|
||||||
check_install && enable
|
check_install && show_log
|
||||||
;;
|
;;
|
||||||
18)
|
18)
|
||||||
check_install && disable
|
check_install && enable
|
||||||
;;
|
;;
|
||||||
19)
|
19)
|
||||||
ssl_cert_issue_main
|
check_install && disable
|
||||||
;;
|
;;
|
||||||
20)
|
20)
|
||||||
ssl_cert_issue_CF
|
ssl_cert_issue_main
|
||||||
;;
|
;;
|
||||||
21)
|
21)
|
||||||
iplimit_main
|
ssl_cert_issue_CF
|
||||||
;;
|
;;
|
||||||
22)
|
22)
|
||||||
firewall_menu
|
iplimit_main
|
||||||
;;
|
;;
|
||||||
23)
|
23)
|
||||||
SSH_port_forwarding
|
firewall_menu
|
||||||
;;
|
;;
|
||||||
24)
|
24)
|
||||||
bbr_menu
|
SSH_port_forwarding
|
||||||
;;
|
;;
|
||||||
25)
|
25)
|
||||||
update_geo
|
|
||||||
;;
|
|
||||||
26)
|
|
||||||
run_speedtest
|
|
||||||
;;
|
|
||||||
27)
|
|
||||||
postgresql_menu
|
postgresql_menu
|
||||||
;;
|
;;
|
||||||
|
26)
|
||||||
|
bbr_menu
|
||||||
|
;;
|
||||||
|
27)
|
||||||
|
update_geo
|
||||||
|
;;
|
||||||
|
28)
|
||||||
|
run_speedtest
|
||||||
|
;;
|
||||||
*)
|
*)
|
||||||
LOGE "Please enter the correct number [0-27]"
|
LOGE "Please enter the correct number [0-28]"
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
}
|
}
|
||||||
@@ -3285,6 +3307,9 @@ if [[ $# > 0 ]]; then
|
|||||||
"update")
|
"update")
|
||||||
check_install 0 && update 0
|
check_install 0 && update 0
|
||||||
;;
|
;;
|
||||||
|
"update-dev")
|
||||||
|
check_install 0 && update_dev 0
|
||||||
|
;;
|
||||||
"legacy")
|
"legacy")
|
||||||
check_install 0 && legacy_version 0
|
check_install 0 && legacy_version 0
|
||||||
;;
|
;;
|
||||||
|
|||||||
Reference in New Issue
Block a user