Compare commits

...

10 commits

Author SHA1 Message Date
Hamed 5297fd3c84
perf(logging): aggregate disabled-client logs in Xray config generation (#7055)
Some checks are pending
CI / go-test (push) Waiting to run
CI / postgres-durable-first (push) Waiting to run
CI / postgres-migration (push) Waiting to run
CI / codegen (push) Waiting to run
CI / govulncheck (push) Waiting to run
CI / race (push) Waiting to run
CI / node-e2e (push) Waiting to run
CI / fuzz-smoke (push) Waiting to run
CI / golangci (push) Waiting to run
CI / shell-lint (push) Waiting to run
CI / frontend (push) Waiting to run
CodeQL Advanced / Analyze (${{ matrix.language }}) (autobuild, go) (push) Waiting to run
CodeQL Advanced / Analyze (${{ matrix.language }}) (none, actions) (push) Waiting to run
CodeQL Advanced / Analyze (${{ matrix.language }}) (none, javascript-typescript) (push) Waiting to run
Release 3X-UI / build (386) (push) Waiting to run
Release 3X-UI / build (amd64) (push) Waiting to run
Release 3X-UI / build (arm64) (push) Waiting to run
Release 3X-UI / build (armv5) (push) Waiting to run
Release 3X-UI / build (armv6) (push) Waiting to run
Release 3X-UI / build (armv7) (push) Waiting to run
Release 3X-UI / build (s390x) (push) Waiting to run
Release 3X-UI / Build for Windows (amd64) (push) Waiting to run
Release 3X-UI / Publish rolling dev release (push) Blocked by required conditions
GetXrayConfig logged one INFO line for every client whose traffic row is
disabled, on every config generation: each reconcile, restart and node
traffic sync, changed or not. With a few thousand expired clients that
flooded the journal and pushed everything else out of the panel's in-memory
log buffer. The line also said "Remove Inbound User", although nothing is
removed there; the client is only left out of the config being built.

A successful generation now writes one summary with the number of excluded
client entries and affected inbounds, and a failed one writes none. The
filter and the generated config are unchanged.

Closes #7054
2026-11-13 19:55:21 +01:00
Aleksey Fedorov 2fab6c3d50
perf(amneziawg): reuse relay buffers and bound the bridge connect time (#7043)
Every TCP connection through a built-in AmneziaWG inbound or outbound
allocated two fresh 32 KiB copy buffers, because io.Copy on a *net.TCPConn
goes through ReadFrom/WriteTo and ignores a caller's buffer. Under a stream
of short connections that is a lot of garbage. The relays now copy with
buffers from a sync.Pool; one side of each pair is always a userspace
netstack connection, so no kernel splice path is given up.

The connect to the local Xray bridge and its SOCKS5 handshake had no time
limit, so a bridge that accepted and never answered pinned the relay's
goroutines and descriptors forever. Both are now bounded at 10 s, and the
deadline is cleared once the handshake succeeds so the relayed connection
keeps its half-close behaviour.
2026-11-13 19:43:03 +01:00
Cheng Ho Ming, Eric 51f7ba47f7
feat(xray): drag to reorder DNS servers (#6959)
Xray queries DNS servers in list order, but the DNS table offered only Edit
and Delete, so changing a server's priority meant deleting and re-adding
servers.

Each row now has a grab handle that reorders by drag and drop, using the same
pointer hook and drop markers as the Routing rules table, and the row menu
gains Move up and Move down. Every path only reorders dns.servers; a server's
own fields are left as they are.
2026-11-13 17:25:38 +01:00
Nikan Zeyaei 166d5633cc
feat(frontend): confirm before stopping Xray and offer Start when it is stopped (#7104)
Stop sat next to Restart on the dashboard and fired on the first click. A
mis-click cut every proxy connection, and when the panel itself is reached
through that proxy the only way back was SSH (#7103).

Stop now opens a confirmation with Cancel focused. When Xray is stopped the
first button reads Start instead of Restart and Stop is disabled; in the
crashed state Stop stays enabled, because setting the manual-stop flag is
what halts the crash-recovery restart loop.

Closes #7103
2026-11-13 17:03:01 +01:00
Nikan Zeyaei 21aa662629
docs(nodes): note that updating an mTLS node needs a node-admin token (#6957)
A master that reaches a node over mTLS with no bearer token is treated as
node-sync, which cannot call /server/updatePanel, so "Update panel" on such a
node fails with HTTP 403. That is intended, but the multi-node guide said the
API token is "not needed in mTLS mode" (#6953).

The guide (en/fa/ru/zh) and the node form's mTLS hint (all 14 locales) now say
that updating the node from the master still needs a token with the
node-admin scope. No logic changes.

The CI workflow's path filter does not cover internal/web/translation or docs,
so only Docs CI ran on this head; the locale-dependent tests were run locally.
2026-11-13 16:54:30 +01:00
PluS98 3a28d130a7
fix(tgbot): keep backup files in the chat and the menu below them (#7092)
Every bot notice carries a Hide button, which deletes the message it sits on.
On a backup that message is the file itself: one tap, with no confirmation,
could remove the admin's only copy of the database. Backup files (the .db and
config.json, from the backup button, the scheduled job and the panel's
backup-to-Telegram endpoint) are now sent without a keyboard; other notices,
including the ban log file, keep Hide.

The backup button also left the menu above the files it sent, out of view at
the bottom of the chat. It now sends the Maintenance menu again below them and
removes the old one. A scheduled backup leaves the menu where it is.
2026-11-13 00:42:16 +01:00
Jay Hemnani 243b5c9da7
fix(sub): send the serverDescription tail only to clients that read it (#7108)
A Host Description is appended to every raw-subscription node name as a base64
`?serverDescription=` tail. Only Happ and INCY read it; v2rayN, v2rayNG,
OpenClash and the rest show it as part of the node name, and the only way out
was clearing the Description (#7105).

The raw subscription body now carries the tail only when the requesting
User-Agent is Happ or INCY, for the endpoint links and the Hysteria2 loop
alike. Copied links, QR codes and the panel's link export keep it, since the
server cannot tell which client they end up in.

Closes #7105
2026-11-13 00:24:13 +01:00
Aleksey Fedorov 7367ff75cd
fix(2fa): accept display forms of the TOTP secret and never panic on a bad one (#7113)
gotp decodes the stored secret with strict base32 and panics when that fails,
so a 2FA secret saved through the settings API in lower case, grouped by
spaces, or not base32 at all turned every login and every attempt to turn 2FA
off into an HTTP 500. An empty secret had the opposite problem: the login
check accepted the code of an empty HMAC key, which anyone can compute.

VerifyWithSkew now normalizes the secret and verifies nothing for an empty or
non-base32 one, so secrets already stored in a display form work again.
Turning 2FA on through the settings update stores the normalized secret and
refuses one no authenticator could match.
2026-11-13 00:13:13 +01:00
PluS98 8438981ef1
fix(hosts): let the Host form clear its SNI (#7095)
Removing the last SNI tag in Hosts → Edit Host and saving did nothing: the
submit fell back to the hidden legacy `sni` field, so the old name was sent
again and the backend rebuilt the pool from it. It came back on the next edit
and stayed in every share link built from that host.

The tag list is the only SNI input, so the primary SNI is now the first tag or
empty. The dynamic ECH helper read the same stale field and follows the list
too. Hosts saved with only the legacy field still load, because the form seeds
the tag list from it.
2026-11-13 00:01:07 +01:00
Benjamin Mitchell 7da8fd23be
fix(groups): preserve group traffic totals on global client reset (#7094)
Adjust group baselines before clearing client counters so group usage survives a global reset.
2026-11-12 23:36:22 +01:00
55 changed files with 1516 additions and 84 deletions

View file

@ -23,7 +23,7 @@ Provide the node's connection details:
| **Scheme** | `https` (default) or `http`. |
| **Address / Port**| The node panel's host and port. |
| **Base path** | The node's web base path. |
| **API token** | A Bearer token created on the node (not needed in mTLS mode). |
| **API token** | A Bearer token created on the node. Optional in mTLS mode, except for **Update panel** (needs `node-admin`). |
| **TLS verify** | `verify` (default), `skip`, `pin` (pin a cert SHA-256), or `mtls`. |
| **Inbound sync** | `all` inbounds, or `selected` by tag. |
| **Outbound tag** | Optionally reach the node **through** a named outbound (egress bridge).|
@ -64,6 +64,14 @@ next restart.
Set the node's TLS verify mode to `mtls`. The master now presents a client
certificate instead of an API token.
<Callout type="warn">
A node reached over mTLS without a token only has the `node-sync` scope, which
cannot run **Update panel** (the node answers HTTP 403, "this API token is not
permitted to access this endpoint"). To update such a node from the master,
create an API token with the `node-admin` scope on the node and paste it into
the master's **API token** field for that node. Keep TLS verify on `mtls`.
</Callout>
</Step>
</Steps>

View file

@ -20,7 +20,7 @@ icon: Boxes
| **Scheme** | `https` (پیش‌فرض) یا `http`. |
| **Address / Port**| میزبان و پورت پنل نود. |
| **Base path** | مسیر پایهٔ وب نود. |
| **API token** | یک توکن Bearer که روی نود ساخته می‌شود (در حالت mTLS لازم نیست). |
| **API token** | یک توکن Bearer که روی نود ساخته می‌شود (در حالت mTLS اختیاری است، به‌جز **به‌روزرسانی پنل** که به توکن `node-admin` نیاز دارد). |
| **TLS verify** | `verify` (پیش‌فرض)، `skip`، `pin` (پین‌کردن SHA-256 گواهی) یا `mtls`. |
| **Inbound sync** | همهٔ inboundها (`all`) یا انتخاب‌شده (`selected`) بر اساس تگ. |
| **Outbound tag** | به‌اختیار از طریق یک outbound نام‌دار به نود برسید (پل خروجی). |
@ -59,6 +59,14 @@ icon: Boxes
حالت TLS verify نود را روی `mtls` تنظیم کنید. اکنون مستر به‌جای یک توکن API یک
گواهی کلاینت ارائه می‌دهد.
<Callout type="warn">
نودی که بدون توکن و از طریق mTLS متصل شده فقط دامنهٔ `node-sync` را دارد و نمی‌تواند
**به‌روزرسانی پنل** را اجرا کند (نود پاسخ HTTP 403 با پیام
«this API token is not permitted to access this endpoint» می‌دهد). برای به‌روزرسانی
چنین نودی از مستر، روی نود یک توکن API با دامنهٔ `node-admin` بسازید و آن را در
فیلد **API token** همان نود در مستر وارد کنید. حالت TLS verify را روی `mtls` نگه دارید.
</Callout>
</Step>
</Steps>

View file

@ -24,7 +24,7 @@ API этого узла. Главная панель опрашивает каж
| **Схема** | `https` (по умолчанию) или `http`. |
| **Адрес / Порт** | Хост и порт панели узла. |
| **Базовый путь** | Веб-базовый путь узла. |
| **API-токен** | Bearer-токен, созданный на узле (не нужен в режиме mTLS). |
| **API-токен** | Bearer-токен, созданный на узле (в режиме mTLS необязателен, кроме **Обновления панели** — нужен `node-admin`). |
| **Проверка TLS** | `verify` (по умолчанию), `skip`, `pin` (закрепить SHA-256 сертификата) или `mtls`. |
| **Синхронизация inbound** | `all` (все) inbound-соединения или `selected` (выбранные) по тегу. |
| **Тег исходящего**| При необходимости обращаться к узлу **через** именованное исходящее соединение (мост исходящего трафика). |
@ -67,6 +67,15 @@ API этого узла. Главная панель опрашивает каж
Задайте на узле режим проверки TLS `mtls`. Теперь главная панель предъявляет
клиентский сертификат вместо API-токена.
<Callout type="warn">
Узел, подключённый по mTLS без токена, имеет только область `node-sync`, которая
не позволяет выполнить **Обновление панели** (узел отвечает HTTP 403,
«this API token is not permitted to access this endpoint»). Чтобы обновить такой
узел с главной панели, создайте на узле API-токен с областью `node-admin` и
вставьте его в поле **API-токен** этого узла на главной панели. Режим проверки
TLS оставьте `mtls`.
</Callout>
</Step>
</Steps>

View file

@ -20,7 +20,7 @@ icon: Boxes
| **Scheme** | `https`(默认)或 `http`。 |
| **Address / Port**| 节点面板的主机和端口。 |
| **Base path** | 节点的 Web 基础路径。 |
| **API token** | 在节点上创建的 Bearer 令牌(mTLS 模式下不需要)。 |
| **API token** | 在节点上创建的 Bearer 令牌(mTLS 模式下可选,但**更新面板**需要 `node-admin` 令牌)。 |
| **TLS verify** | `verify`(默认)、`skip`、`pin`(固定证书 SHA-256)或 `mtls`。 |
| **Inbound sync** | `all` 入站,或按标签 `selected`。 |
| **Outbound tag** | 可选地**通过**指定的出站到达节点(出口桥接)。 |
@ -53,6 +53,10 @@ icon: Boxes
### 将节点切换到 mTLS
将节点的 TLS 验证模式设置为 `mtls`。现在主控将出示客户端证书而非 API 令牌。
<Callout type="warn">
通过 mTLS 连接且未提供令牌的节点只具有 `node-sync` 权限范围,无法执行**更新面板**(节点返回 HTTP 403,“this API token is not permitted to access this endpoint”)。要从主控更新此类节点,请在节点上创建具有 `node-admin` 权限范围的 API 令牌,并将其填入主控中该节点的 **API token** 字段。TLS 验证模式保持为 `mtls`。
</Callout>
</Step>
</Steps>

View file

@ -121,8 +121,7 @@ export default function HostFormModal({
watchedSnis && watchedSnis.filter((s) => typeof s === 'string' && s.trim() !== '').length > 1,
);
const watchedSingleSni = useWatch({ control: methods.control, name: 'sni' }) ?? '';
const hostSni = (watchedSnis && watchedSnis.length > 0 ? watchedSnis[0] : '') || watchedSingleSni;
const hostSni = watchedSnis?.[0] ?? '';
const hostEchConfig = useWatch({ control: methods.control, name: 'echConfigList' }) ?? '';
const showTls = security === 'tls' || security === 'reality' || security === 'same';
const showTlsExtras = security === 'tls' || security === 'same';
@ -208,11 +207,10 @@ export default function HostFormModal({
const { enable, ...rest } = values;
const isDisabled = !enable;
const cleanedSnis = (rest.snis || []).map((s) => s.trim()).filter(Boolean);
const primarySni = cleanedSnis.length > 0 ? cleanedSnis[0] : rest.sni || '';
const payload: BulkAddHostValues = {
...rest,
hosts: (rest.hosts || []).filter((h) => h && h.trim() !== ''),
sni: primarySni,
sni: cleanedSnis[0] ?? '',
snis: cleanedSnis,
sniSharedRandom: cleanedSnis.length > 1 && Boolean(rest.sniSharedRandom),
isDisabled,

View file

@ -1,7 +1,7 @@
import { Fragment } from 'react';
import type { ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Tag, Tooltip } from 'antd';
import { Button, Modal, Tag, Tooltip } from 'antd';
import {
ApiOutlined,
ArrowUpOutlined,
@ -11,6 +11,7 @@ import {
CloudServerOutlined,
ControlOutlined,
FileTextOutlined,
PlayCircleOutlined,
PoweroffOutlined,
ReloadOutlined,
} from '@ant-design/icons';
@ -26,7 +27,7 @@ interface OverviewActionBarProps {
panelVersion: string;
latestVersion: string;
updateAvailable: boolean;
onStopXray: () => void;
onStopXray: () => void | Promise<void>;
onRestartXray: () => void;
onOpenLogs: () => void;
onOpenXrayLogs: () => void;
@ -45,6 +46,9 @@ interface BarAction {
text: string;
onClick: () => void;
primary?: boolean;
danger?: boolean;
disabled?: boolean;
hint?: string;
}
const XRAY_STATE_KEYS: Record<string, string> = {
@ -73,16 +77,18 @@ export default function OverviewActionBar({
onOpenVersionSwitch,
}: OverviewActionBarProps) {
const { t } = useTranslation();
const [modal, modalContextHolder] = Modal.useModal();
const stateText = t(XRAY_STATE_KEYS[status.xray.state] ?? 'pages.index.xrayStatusUnknown');
const hasVersion = !!status.xray.version && status.xray.version !== 'Unknown';
const size = isMobile ? ('small' as const) : ('middle' as const);
const isStopped = status.xray.state === 'stop';
const actionGroups: BarAction[][] = [
[
{
key: 'restart',
icon: <ReloadOutlined aria-hidden />,
text: t('pages.index.restartXray'),
icon: isStopped ? <PlayCircleOutlined aria-hidden /> : <ReloadOutlined aria-hidden />,
text: t(isStopped ? 'pages.index.startXray' : 'pages.index.restartXray'),
onClick: onRestartXray,
primary: true,
},
@ -90,7 +96,19 @@ export default function OverviewActionBar({
key: 'stop',
icon: <PoweroffOutlined aria-hidden />,
text: t('pages.index.stopXray'),
onClick: onStopXray,
danger: true,
disabled: isStopped,
hint: isStopped ? t('pages.index.stopXrayDisabledHint') : undefined,
onClick: () =>
modal.confirm({
title: t('pages.index.stopXrayConfirmTitle'),
content: t('pages.index.stopXrayConfirmContent'),
okText: t('pages.index.stopXrayConfirmOk'),
okType: 'danger',
cancelText: t('cancel'),
focusable: { autoFocusButton: 'cancel' },
onOk: onStopXray,
}),
},
],
[
@ -165,6 +183,7 @@ export default function OverviewActionBar({
return (
<div className="ov-bar">
{modalContextHolder}
{status.xray.errorMsg ? (
<Tooltip title={<span className="ov-error-detail">{status.xray.errorMsg}</span>}>
{statePill}
@ -204,18 +223,21 @@ export default function OverviewActionBar({
<Fragment key={group[0].key}>
{groupIndex > 0 && <span className="ov-bar-sep" />}
{group.map((action) => (
<Button
key={action.key}
type={action.primary ? undefined : 'text'}
color={action.primary ? 'primary' : undefined}
variant={action.primary ? 'outlined' : undefined}
size={size}
icon={action.icon}
aria-label={action.text}
onClick={action.onClick}
>
{isMobile ? undefined : action.text}
</Button>
<Tooltip key={action.key} title={action.hint}>
<Button
type={action.primary ? undefined : 'text'}
color={action.primary ? 'primary' : undefined}
variant={action.primary ? 'outlined' : undefined}
size={size}
danger={action.danger}
disabled={action.disabled}
icon={action.icon}
aria-label={action.text}
onClick={action.onClick}
>
{isMobile ? undefined : action.text}
</Button>
</Tooltip>
))}
</Fragment>
))}

View file

@ -27,6 +27,7 @@ import { selectTagRender } from '@/components/form';
import { onNumber } from '@/utils/onNumber';
import { SettingListItem } from '@/components/ui';
import { useMediaQuery } from '@/hooks/useMediaQuery';
import { usePointerRowReorder } from '@/hooks/usePointerRowReorder';
import { catTabLabel } from '@/pages/settings/catTabLabel';
import DnsServerModal from './DnsServerModal';
import type { DnsServerValue } from './DnsServerModal';
@ -52,6 +53,7 @@ export default function DnsTab({ templateSettings, setTemplateSettings }: DnsTab
const [editingServer, setEditingServer] = useState<DnsServerValue | null>(null);
const [editingIndex, setEditingIndex] = useState<number | null>(null);
const [presetsModalOpen, setPresetsModalOpen] = useState(false);
const serversContainerRef = useRef<HTMLDivElement>(null);
const dns = (templateSettings?.dns as DnsConfig | undefined) ?? null;
const dnsEnabled = !!dns;
@ -166,8 +168,33 @@ export default function DnsTab({ templateSettings, setTemplateSettings }: DnsTab
},
[mutate],
);
const moveServer = useCallback(
(from: number, to: number) => {
mutate((tt) => {
const servers = (tt.dns as DnsConfig | undefined)?.servers;
if (!servers) return;
const [moved] = servers.splice(from, 1);
servers.splice(to, 0, moved);
});
},
[mutate],
);
const dnsColumns = useDnsServerColumns({ openEditServer, deleteServer });
const { drag, onPointerDown: onHandlePointerDown } = usePointerRowReorder({
containerRef: serversContainerRef,
getRowKey: (row) => Number(row.dataset.rowKey),
onDrop: ({ from, to }) => moveServer(from, to),
});
const draggedIndex = drag?.from ?? null;
const dropTargetIndex = drag?.to ?? null;
const dnsColumns = useDnsServerColumns({
rowsLength: dnsServers.length,
onHandlePointerDown,
openEditServer,
moveServer,
deleteServer,
});
function openAddServer() {
setEditingServer(null);
@ -475,14 +502,21 @@ export default function DnsTab({ templateSettings, setTemplateSettings }: DnsTab
{t('pages.xray.dns.clearAll')}
</Button>
</Space>
<Table
columns={dnsColumns}
dataSource={dnsServers}
rowKey={(r) => r.key}
pagination={false}
size="small"
bordered
/>
<div ref={serversContainerRef}>
<Table
columns={dnsColumns}
dataSource={dnsServers}
rowKey={(r) => r.key}
rowClassName={(_r, i) => {
if (i === draggedIndex) return 'row-dragging';
if (i !== dropTargetIndex || draggedIndex == null) return '';
return i > draggedIndex ? 'drop-after' : 'drop-before';
}}
pagination={false}
size="small"
bordered
/>
</div>
</Space>
),
});
@ -517,7 +551,17 @@ export default function DnsTab({ templateSettings, setTemplateSettings }: DnsTab
return out;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [t, isMobile, dnsEnabled, dns, hostsList, dnsServers, fakeDnsList]);
}, [
t,
isMobile,
dnsEnabled,
dns,
hostsList,
dnsServers,
fakeDnsList,
draggedIndex,
dropTargetIndex,
]);
return (
<>

View file

@ -1,7 +1,14 @@
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Dropdown, Input, InputNumber, Space } from 'antd';
import { MoreOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import {
MoreOutlined,
EditOutlined,
DeleteOutlined,
ArrowUpOutlined,
ArrowDownOutlined,
HolderOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { onNumber } from '@/utils/onNumber';
@ -13,10 +20,16 @@ export type DnsServerRow = { key: number; server: DnsServerValue };
export type FakednsTableRow = { key: number; ipPool: string; poolSize: number };
export function useDnsServerColumns({
rowsLength,
onHandlePointerDown,
openEditServer,
moveServer,
deleteServer,
}: {
rowsLength: number;
onHandlePointerDown: (idx: number, ev: React.PointerEvent) => void;
openEditServer: (idx: number) => void;
moveServer: (from: number, to: number) => void;
deleteServer: (idx: number) => void;
}): ColumnsType<DnsServerRow> {
const { t } = useTranslation();
@ -29,6 +42,12 @@ export function useDnsServerColumns({
width: 60,
render: (_v, _record, index) => (
<Space size={6}>
<HolderOutlined
className="drag-handle"
title={t('pages.xray.routing.dragToReorder')}
aria-hidden="true"
onPointerDown={(ev: React.PointerEvent) => onHandlePointerDown(index, ev)}
/>
<span className="row-index">{index + 1}</span>
<Dropdown
trigger={['click']}
@ -43,6 +62,26 @@ export function useDnsServerColumns({
),
onClick: () => openEditServer(index),
},
{
key: 'up',
label: (
<>
<ArrowUpOutlined aria-hidden /> {t('pages.inbounds.form.moveUp')}
</>
),
disabled: index === 0,
onClick: () => moveServer(index, index - 1),
},
{
key: 'down',
label: (
<>
<ArrowDownOutlined aria-hidden /> {t('pages.inbounds.form.moveDown')}
</>
),
disabled: index === rowsLength - 1,
onClick: () => moveServer(index, index + 1),
},
{
key: 'del',
danger: true,
@ -85,7 +124,7 @@ export function useDnsServerColumns({
render: (_v, record) => <span className="muted">{expectedIPsFor(record.server)}</span>,
},
],
[t, openEditServer, deleteServer],
[t, rowsLength, onHandlePointerDown, openEditServer, moveServer, deleteServer],
);
}

View file

@ -1,10 +1,11 @@
import { useEffect, useState } from 'react';
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, screen } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, screen, within } from '@testing-library/react';
import DnsTab from '@/pages/xray/dns/DnsTab';
import type { SetTemplate, XraySettingsValue } from '@/hooks/useXraySetting';
import { renderWithProviders } from './test-utils';
import { installPointerEvents, pointAt } from './pointer-events';
function withHosts(hosts: Record<string, string>): XraySettingsValue {
return {
@ -152,3 +153,66 @@ describe('DnsTab', () => {
expect(latest().dns).not.toHaveProperty('script');
});
});
describe('DnsTab server reorder', () => {
beforeEach(installPointerEvents);
afterEach(() => vi.unstubAllGlobals());
const google = { address: '8.8.8.8', domains: ['geosite:google'] };
const rows = () => document.querySelectorAll<HTMLElement>('tr[data-row-key]');
const servers = () =>
JSON.parse(screen.getByTestId('settings').textContent || '{}').dns.servers as unknown[];
function openServers() {
function Harness() {
const [settings, setSettings] = useState<XraySettingsValue | null>({
dns: { servers: ['1.1.1.1', google, 'localhost'] },
} as unknown as XraySettingsValue);
return (
<>
<DnsTab templateSettings={settings} setTemplateSettings={setSettings} />
<output data-testid="settings">{JSON.stringify(settings)}</output>
</>
);
}
renderWithProviders(<Harness />);
fireEvent.click(screen.getByRole('tab', { name: 'DNS' }));
}
it.each([
{
dir: 'down',
from: 0,
to: 2,
marker: 'drop-after',
expected: [google, 'localhost', '1.1.1.1'],
},
{
dir: 'up',
from: 2,
to: 0,
marker: 'drop-before',
expected: ['localhost', '1.1.1.1', google],
},
])('drags a server $dir into the target slot', ({ from, to, marker, expected }) => {
openServers();
const handle = rows()[from].querySelector('.drag-handle');
if (!handle) throw new Error('missing drag handle');
pointAt(rows()[to]);
const pointer = { pointerId: 7, button: 0, clientX: 10, clientY: 32 };
fireEvent.pointerDown(handle, { ...pointer, clientY: 0 });
fireEvent.pointerMove(document, pointer);
expect(rows()[to].className).toContain(marker);
fireEvent.pointerUp(document, pointer);
expect(servers()).toEqual(expected);
});
it('moves a server from the row menu and disables Move up on the first row', async () => {
openServers();
fireEvent.click(within(rows()[0]).getByRole('button', { name: 'more' }));
const moveUp = await screen.findByRole('menuitem', { name: /Move up/ });
expect(moveUp.getAttribute('aria-disabled')).toBe('true');
fireEvent.click(screen.getByRole('menuitem', { name: /Move down/ }));
expect(servers()).toEqual([google, '1.1.1.1', 'localhost']);
});
});

View file

@ -0,0 +1,47 @@
import { fireEvent, screen, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { HostRecord } from '@/api/queries/useHostsQuery';
import HostFormModal from '@/pages/hosts/HostFormModal';
import { HttpUtil, Msg } from '@/utils';
import { renderWithProviders } from './test-utils';
const host = {
groupId: 'g1',
remark: 'DE WS',
inboundIds: [1],
hosts: ['cdn.example.com'],
security: 'same',
sni: 'dash.example.com',
snis: ['dash.example.com'],
} as HostRecord;
describe('Host form SNI', () => {
beforeEach(() => {
vi.spyOn(HttpUtil, 'get').mockResolvedValue(new Msg(true, '', []));
});
it('saves an empty SNI after the last SNI tag is removed', async () => {
const save = vi.fn().mockResolvedValue({ success: true });
renderWithProviders(
<HostFormModal
open
mode="edit"
host={host}
inboundOptions={[{ id: 1, remark: 'in', tag: 'in', protocol: 'vless' }]}
existingHosts={[host]}
save={save}
onOpenChange={() => {}}
/>,
);
const tag = await screen.findByTitle('dash.example.com');
const remove = tag.querySelector('.ant-select-selection-item-remove');
if (!remove) throw new Error('missing SNI tag remove button');
fireEvent.click(remove);
await waitFor(() => expect(screen.queryByTitle('dash.example.com')).toBeNull());
fireEvent.click(screen.getByRole('button', { name: 'Save' }));
await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
expect(save.mock.calls[0][0]).toMatchObject({ sni: '', snis: [] });
});
});

View file

@ -0,0 +1,89 @@
import { fireEvent, screen, waitFor } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { Status } from '@/models/status';
import OverviewActionBar from '@/pages/index/OverviewActionBar';
import { renderWithProviders } from './test-utils';
const noop = () => {};
function renderBar(
state: string,
{
onStopXray = noop,
onRestartXray = noop,
}: { onStopXray?: () => void; onRestartXray?: () => void } = {},
) {
const status = new Status();
status.xray.state = state;
renderWithProviders(
<OverviewActionBar
status={status}
isMobile={false}
accessLogEnable={false}
panelVersion="v3.10.1"
latestVersion="v3.10.1"
updateAvailable={false}
onStopXray={onStopXray}
onRestartXray={onRestartXray}
onOpenLogs={noop}
onOpenXrayLogs={noop}
onOpenAmneziaWGLogs={noop}
onOpenConfig={noop}
onOpenBackup={noop}
onOpenSystemHistory={noop}
onOpenXrayMetrics={noop}
onOpenPanelUpdate={noop}
onOpenVersionSwitch={noop}
/>,
);
}
// Stop used to fire on the first click, so a mis-click killed every proxy connection (#7103).
describe('OverviewActionBar stop confirmation', () => {
it('does not stop Xray until the dialog is confirmed', async () => {
const onStopXray = vi.fn();
renderBar('running', { onStopXray });
fireEvent.click(screen.getByRole('button', { name: 'Stop' }));
expect(await screen.findAllByText('Stop Xray?')).not.toHaveLength(0);
expect(onStopXray).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
expect(onStopXray).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('button', { name: 'Stop' }));
await waitFor(() =>
expect(screen.getAllByRole('button', { name: 'Stop Xray' })).not.toHaveLength(0),
);
fireEvent.click(screen.getAllByRole('button', { name: 'Stop Xray' }).at(-1)!);
await waitFor(() => expect(onStopXray).toHaveBeenCalledOnce());
});
});
// Stop on a stopped core only errors and sets the manual-stop flag. In the crash
// state Stop is the one dashboard control that halts the restart loop.
describe('OverviewActionBar start / disabled stop', () => {
it('offers Start and disables Stop when the core is stopped', () => {
const onRestartXray = vi.fn();
renderBar('stop', { onRestartXray });
expect(screen.queryByRole('button', { name: 'Restart' })).toBeNull();
expect((screen.getByRole('button', { name: 'Stop' }) as HTMLButtonElement).disabled).toBe(true);
fireEvent.click(screen.getByRole('button', { name: 'Start' }));
expect(onRestartXray).toHaveBeenCalledOnce();
});
it('keeps Restart and leaves Stop usable when the core errored', async () => {
const onStopXray = vi.fn();
renderBar('error', { onStopXray });
expect(screen.getByRole('button', { name: 'Restart' })).toBeTruthy();
const stop = screen.getByRole('button', { name: 'Stop' }) as HTMLButtonElement;
expect(stop.disabled).toBe(false);
fireEvent.click(stop);
fireEvent.click(await screen.findByRole('button', { name: 'Stop Xray' }));
await waitFor(() => expect(onStopXray).toHaveBeenCalledOnce());
});
});

View file

@ -469,8 +469,8 @@ func (s *socks5EgressServer) relayTCP(dev *Device, tag string, upstream net.Conn
return
}
done := make(chan struct{}, 2)
go func() { _, _ = io.Copy(tunnelConn, upstream); done <- struct{}{} }()
go func() { _, _ = io.Copy(upstream, tunnelConn); done <- struct{}{} }()
go func() { copyPooled(tunnelConn, upstream); done <- struct{}{} }()
go func() { copyPooled(upstream, tunnelConn); done <- struct{}{} }()
<-done
}

View file

@ -0,0 +1,5 @@
//go:build !race
package amneziawgnet
const raceEnabled = false

View file

@ -0,0 +1,5 @@
//go:build race
package amneziawgnet
const raceEnabled = true

View file

@ -68,13 +68,7 @@ func SocksInboundSettings(emails []string, password string) ([]byte, error) {
func (r SocksRelay) RelayTCP(conn *gonet.TCPConn, email string, dest netip.AddrPort) {
defer conn.Close()
auth := &proxy.Auth{User: email, Password: r.Password}
dialer, err := proxy.SOCKS5("tcp", r.Addr, auth, proxy.Direct)
if err != nil {
logger.Warningf("amneziawgnet: RelayTCP: build SOCKS5 dialer: %v", err)
return
}
upstream, err := dialer.Dial("tcp", dest.String())
upstream, err := r.dialUpstream(email, dest)
if err != nil {
logger.Warningf("amneziawgnet: RelayTCP: SOCKS5 CONNECT to %s as %q: %v", dest, email, err)
return
@ -84,6 +78,60 @@ func (r SocksRelay) RelayTCP(conn *gonet.TCPConn, email string, dest netip.AddrP
pipeBothWays(conn, upstream)
}
// dialUpstream bounds the bridge connect and SOCKS5 handshake so a silent core cannot pin the relay.
// It returns the raw *net.TCPConn with no deadline left: pipeBothWays needs its CloseWrite.
func (r SocksRelay) dialUpstream(email string, dest netip.AddrPort) (net.Conn, error) {
bridge := net.Dialer{Timeout: socks5ConnectTimeout}
conn, err := bridge.DialContext(context.Background(), "tcp", r.Addr)
if err != nil {
return nil, err
}
if err := conn.SetDeadline(time.Now().Add(socks5ConnectTimeout)); err != nil {
conn.Close()
return nil, err
}
auth := &proxy.Auth{User: email, Password: r.Password}
dialer, err := proxy.SOCKS5("tcp", r.Addr, auth, dialedConn{conn})
if err != nil {
conn.Close()
return nil, fmt.Errorf("build SOCKS5 dialer: %w", err)
}
upstream, err := dialer.Dial("tcp", dest.String())
if err != nil {
conn.Close()
return nil, err
}
if err := upstream.SetDeadline(time.Time{}); err != nil {
upstream.Close()
return nil, err
}
return upstream, nil
}
// dialedConn hands proxy.SOCKS5 a connection already made under the bound.
type dialedConn struct{ conn net.Conn }
func (d dialedConn) Dial(string, string) (net.Conn, error) { return d.conn, nil }
var socks5ConnectTimeout = 10 * time.Second
// relayBuffers recycles copy buffers: a fresh 32 KiB pair per relayed connection made a
// burst of short connections through AmneziaWG allocate and sweep gigabytes.
var relayBuffers = sync.Pool{New: func() any { b := make([]byte, 32*1024); return &b }}
// Wrappers hide ReadFrom/WriteTo, through which *net.TCPConn would copy with a buffer of its own.
type (
relayWriter struct{ io.Writer }
relayReader struct{ io.Reader }
)
// copyPooled copies src into dst with a pooled buffer.
func copyPooled(dst io.Writer, src io.Reader) {
buf := relayBuffers.Get().(*[]byte)
defer relayBuffers.Put(buf)
_, _ = io.CopyBuffer(relayWriter{dst}, relayReader{src}, *buf)
}
// halfCloseIdle bounds how long the surviving direction of a half-closed pair
// may sit idle, so a peer that vanished mid-transfer cannot pin it forever.
const halfCloseIdle = 2 * time.Minute
@ -121,7 +169,7 @@ func pipeBothWays(a, b net.Conn) {
// copy just signalled EOF to.
pipe := func(dst, src *guardedReader) {
defer wg.Done()
_, _ = io.Copy(dst.conn, src)
copyPooled(dst.conn, src)
if cw, ok := dst.conn.(closeWriter); ok {
_ = cw.CloseWrite()
} else {

View file

@ -0,0 +1,203 @@
package amneziawgnet
// Half-close through SocksRelay.RelayTCP needs the raw TCP conn to the bridge,
// not x/net/proxy's *socks.Conn wrapper, which has no CloseWrite.
import (
"bufio"
"context"
"errors"
"io"
"net"
"net/netip"
"testing"
"time"
"github.com/amnezia-vpn/amneziawg-go/v3/tun"
"github.com/amnezia-vpn/amneziawg-go/v3/tun/netstack"
"gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"
)
func hcListen(tb testing.TB) net.Listener {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
tb.Fatalf("listen: %v", err)
}
return ln
}
type hcNetstacks struct {
client *netstack.Net
ln *gonet.TCPListener
addr netip.AddrPort
close func()
}
func hcShuttle(src, dst tun.Device) {
batch := src.BatchSize()
bufs := make([][]byte, batch)
for i := range bufs {
bufs[i] = make([]byte, 65536)
}
sizes := make([]int, batch)
for {
n, err := src.Read(bufs, sizes, 0)
if err != nil {
return
}
out := make([][]byte, 0, n)
for i := 0; i < n; i++ {
out = append(out, bufs[i][:sizes[i]])
}
if _, err := dst.Write(out, 0); err != nil {
return
}
}
}
// hcNewNetstacks links a client stack to a server stack whose accepted conns are the
// *gonet.TCPConn the relay gets in production.
func hcNewNetstacks(tb testing.TB) *hcNetstacks {
ca := netip.MustParseAddr("10.77.0.1")
sa := netip.MustParseAddr("10.77.0.2")
ctun, cnet, err := netstack.CreateNetTUN([]netip.Addr{ca}, nil, 1420)
if err != nil {
tb.Fatalf("client netstack: %v", err)
}
stun, snet, err := netstack.CreateNetTUN([]netip.Addr{sa}, nil, 1420)
if err != nil {
tb.Fatalf("server netstack: %v", err)
}
go hcShuttle(ctun, stun)
go hcShuttle(stun, ctun)
addr := netip.AddrPortFrom(sa, 80)
ln, err := snet.ListenTCPAddrPort(addr)
if err != nil {
tb.Fatalf("server listen: %v", err)
}
return &hcNetstacks{client: cnet, ln: ln, addr: addr, close: func() {
_ = ln.Close()
_ = ctun.Close()
_ = stun.Close()
}}
}
func (n *hcNetstacks) pair(tb testing.TB) (client, server *gonet.TCPConn) {
ch := make(chan net.Conn, 1)
go func() {
c, err := n.ln.Accept()
if err != nil {
ch <- nil
return
}
ch <- c
}()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
client, err := n.client.DialContextTCPAddrPort(ctx, n.addr)
if err != nil {
tb.Fatalf("tunnel dial: %v", err)
}
s := <-ch
if s == nil {
tb.Fatal("tunnel accept failed")
}
return client, s.(*gonet.TCPConn)
}
// hcServeSocks answers one username/password SOCKS5 CONNECT (as Xray's inbound would),
// reads the 4-byte request, writes payload and half-closes.
func hcServeSocks(c net.Conn, payload []byte) error {
br := bufio.NewReader(c)
buf := make([]byte, 512)
read := func(n int) ([]byte, error) { _, err := io.ReadFull(br, buf[:n]); return buf[:n], err }
hdr, err := read(2)
if err != nil {
return err
}
if _, err := read(int(hdr[1])); err != nil {
return err
}
if _, err := c.Write([]byte{5, 2}); err != nil {
return err
}
v, err := read(2)
if err != nil {
return err
}
if _, err := read(int(v[1])); err != nil {
return err
}
pl, err := read(1)
if err != nil {
return err
}
if _, err := read(int(pl[0])); err != nil {
return err
}
if _, err := c.Write([]byte{1, 0}); err != nil {
return err
}
req, err := read(4)
if err != nil {
return err
}
alen := map[byte]int{1: 4, 4: 16}[req[3]]
if req[3] == 3 {
l, err := read(1)
if err != nil {
return err
}
alen = int(l[0])
}
if _, err := read(alen + 2); err != nil {
return err
}
if _, err := c.Write([]byte{5, 0, 0, 1, 0, 0, 0, 0, 0, 0}); err != nil {
return err
}
if _, err := read(4); err != nil {
return err
}
if _, err := c.Write(payload); err != nil {
return err
}
if tc, ok := c.(*net.TCPConn); ok {
return tc.CloseWrite()
}
return errors.New("not tcp")
}
// TestHCHalfCloseThroughRelayTCP: a client that sends its request and half-closes
// must still get the upstream's reply through SocksRelay.RelayTCP.
func TestHCHalfCloseThroughRelayTCP(t *testing.T) {
ns := hcNewNetstacks(t)
defer ns.close()
bridge := hcListen(t)
defer bridge.Close()
relay := SocksRelay{Addr: bridge.Addr().String(), Password: "x"}
reply := []byte("reply-after-half-close")
served := make(chan error, 1)
go func() {
c, err := bridge.Accept()
if err != nil {
served <- err
return
}
defer c.Close()
served <- hcServeSocks(c, reply)
}()
client, server := ns.pair(t)
defer client.Close()
done := make(chan struct{})
go func() { relay.RelayTCP(server, "bench@example", netip.MustParseAddrPort("192.0.2.1:443")); close(done) }()
_, _ = client.Write([]byte("ping"))
_ = client.CloseWrite()
_ = client.SetReadDeadline(time.Now().Add(5 * time.Second))
got, err := io.ReadAll(client)
<-done
srvErr := <-served
if string(got) != string(reply) {
t.Fatalf("client got %q (read err %v, bridge err %v), want %q: the half-close killed the upstream before its reply", got, err, srvErr, reply)
}
}

View file

@ -0,0 +1,198 @@
package amneziawgnet
import (
"errors"
"io"
"net"
"net/netip"
"runtime"
"testing"
"time"
)
// A burst of short connections through AmneziaWG used to allocate a fresh 32 KiB copy buffer
// per direction per connection (gigabytes per hour under churn); the pair must be reused.
func TestPipeBothWaysReusesCopyBuffersAcrossConnections(t *testing.T) {
if raceEnabled {
t.Skip("under -race sync.Pool drops a share of Puts at random")
}
payload := make([]byte, 16*1024)
sink := make([]byte, 16*1024)
ping := make([]byte, len("ping")) // the server goroutine's own buffer
relay := func() {
tunnelClient, tunnelSide := tcpPair(t)
upstreamSide, upstreamServer := tcpPair(t)
done := make(chan struct{})
go func() { pipeBothWays(tunnelSide, upstreamSide); close(done) }()
go func() {
_, _ = io.ReadFull(upstreamServer, ping)
_, _ = upstreamServer.Write(payload)
_ = upstreamServer.Close()
}()
_, _ = tunnelClient.Write([]byte("ping"))
_ = tunnelClient.(*net.TCPConn).CloseWrite()
if _, err := io.ReadFull(tunnelClient, sink); err != nil {
t.Fatalf("reply: %v", err)
}
<-done
}
for range 5 {
relay()
}
const conns = 100
var before, after runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&before)
for range conns {
relay()
}
runtime.ReadMemStats(&after)
perConn := (after.TotalAlloc - before.TotalAlloc) / conns
if perConn >= 32*1024 {
t.Fatalf("each relayed connection allocated %d bytes, want the copy buffers reused (< 32 KiB)", perConn)
}
}
// TestDialUpstreamGivesUpOnSilentBridge: a bridge that accepts but never answers (a hung
// Xray) must fail the CONNECT within its bound instead of pinning the relay.
func TestDialUpstreamGivesUpOnSilentBridge(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0") // never accepted: no greeting reply ever comes
if err != nil {
t.Fatalf("listen: %v", err)
}
t.Cleanup(func() { _ = ln.Close() })
saved := socks5ConnectTimeout
socks5ConnectTimeout = 150 * time.Millisecond
t.Cleanup(func() { socks5ConnectTimeout = saved })
relay := SocksRelay{Addr: ln.Addr().String(), Password: "x"}
done := make(chan error, 1)
go func() {
conn, err := relay.dialUpstream("peer@example", netip.MustParseAddrPort("192.0.2.1:443"))
if conn != nil {
_ = conn.Close()
}
done <- err
}()
select {
case err := <-done:
if err == nil {
t.Fatal("CONNECT succeeded through a bridge that never answered")
}
case <-time.After(2 * time.Second):
t.Fatal("dialUpstream still blocked 2s past the connect bound: a silent bridge pins the relay")
}
}
// TestDialUpstreamLeavesNoDeadlineAfterHandshake: the connect bound covers the handshake
// only, so writes and reads after it has passed still go through.
func TestDialUpstreamLeavesNoDeadlineAfterHandshake(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
t.Cleanup(func() { _ = ln.Close() })
saved := socks5ConnectTimeout
socks5ConnectTimeout = 150 * time.Millisecond
t.Cleanup(func() { socks5ConnectTimeout = saved })
served := make(chan error, 1)
go func() {
c, err := ln.Accept()
if err != nil {
served <- err
return
}
defer c.Close()
served <- serveSocks5Connect(c, []byte("ping"), []byte("late"))
}()
relay := SocksRelay{Addr: ln.Addr().String(), Password: "x"}
conn, err := relay.dialUpstream("peer@example", netip.MustParseAddrPort("192.0.2.1:443"))
if err != nil {
t.Fatalf("dialUpstream: %v", err)
}
defer conn.Close()
guard := time.AfterFunc(5*time.Second, func() { _ = conn.Close() })
defer guard.Stop()
time.Sleep(3 * socks5ConnectTimeout)
if _, err := conn.Write([]byte("ping")); err != nil {
t.Fatalf("write after the connect bound passed: %v (the handshake deadline leaked onto the relay)", err)
}
got := make([]byte, 4)
if _, err := io.ReadFull(conn, got); err != nil {
t.Fatalf("read after the connect bound passed: %v (the handshake deadline leaked onto the relay)", err)
}
if string(got) != "late" {
t.Fatalf("read %q, want %q", got, "late")
}
if err := <-served; err != nil {
t.Fatalf("fake bridge: %v", err)
}
}
// serveSocks5Connect answers one username/password SOCKS5 CONNECT, reads request, then writes reply.
func serveSocks5Connect(c net.Conn, request, reply []byte) error {
buf := make([]byte, 512)
read := func(n int) ([]byte, error) { _, err := io.ReadFull(c, buf[:n]); return buf[:n], err }
hdr, err := read(2) // VER NMETHODS
if err != nil {
return err
}
if _, err := read(int(hdr[1])); err != nil {
return err
}
if _, err := c.Write([]byte{5, 2}); err != nil { // username/password
return err
}
ver, err := read(2) // VER ULEN
if err != nil {
return err
}
if ver[0] != 1 {
return errors.New("bad auth version")
}
if _, err := read(int(ver[1])); err != nil {
return err
}
plen, err := read(1)
if err != nil {
return err
}
if _, err := read(int(plen[0])); err != nil {
return err
}
if _, err := c.Write([]byte{1, 0}); err != nil {
return err
}
req, err := read(4) // VER CMD RSV ATYP
if err != nil {
return err
}
addrLen := map[byte]int{1: 4, 4: 16}[req[3]]
if req[3] == 3 {
l, err := read(1)
if err != nil {
return err
}
addrLen = int(l[0])
}
if _, err := read(addrLen + 2); err != nil {
return err
}
if _, err := c.Write([]byte{5, 0, 0, 1, 0, 0, 0, 0, 0, 0}); err != nil {
return err
}
got, err := read(len(request))
if err != nil {
return err
}
if string(got) != string(request) {
return errors.New("bridge read an unexpected request")
}
_, err = c.Write(reply)
return err
}

View file

@ -502,6 +502,7 @@ func (a *SUBController) subs(c *gin.Context) {
scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c)
subReq := a.subService.ForRequest(host)
subReq.subscriptionBody = true
subReq.omitServerDescription = !IsHappClient(userAgent) && !IsIncyClient(userAgent)
subs, _, _, traffic, err := subReq.getSubs(subId)
if err != nil || subs == nil {
writeSubError(c, err)

View file

@ -803,6 +803,32 @@ func TestLegacyClashEndpointNormalizesShadowsocksCipher(t *testing.T) {
}
}
// #7105: only Happ and INCY read the tail; other clients show it in the node name.
func TestRawSubServerDescriptionByClient(t *testing.T) {
seedSubDB(t)
seedSubInbound(t, "s1", "vl", 4492, 1, `{"network":"tcp","security":"none","externalProxy":[{"forceTls":"same","dest":"a.example.com","port":443,"remark":"A","serverDescription":"Berlin"}]}`)
gin.SetMode(gin.TestMode)
cases := map[string]bool{"Happ/3.1": true, "INCY/1.0.0/ios": true, "v2rayN/7.10": false}
for userAgent, wantTail := range cases {
t.Run(userAgent, func(t *testing.T) {
router := gin.New()
NewSUBController(router.Group("/"), WithSUBEncryption(false))
req := httptest.NewRequest(http.MethodGet, "http://sub.example.com/sub/s1", nil)
req.Header.Set("User-Agent", userAgent)
resp := httptest.NewRecorder()
router.ServeHTTP(resp, req)
body := resp.Body.String()
if resp.Code != http.StatusOK || !strings.Contains(body, "vless") {
t.Fatalf("status=%d, body=%s", resp.Code, body)
}
if got := strings.Contains(body, "?serverDescription=QmVybGlu"); got != wantTail {
t.Fatalf("tail present = %v, want %v; body=%s", got, wantTail, body)
}
})
}
}
func TestIncyRoutingIsolatedFromHappHeaders(t *testing.T) {
seedSubDB(t)
seedSubInbound(t, "s1", "vl", 4492, 1, `{"network":"tcp","security":"none"}`)

View file

@ -136,7 +136,7 @@ func (s *SubService) buildEndpointLinks(
applyEndpointFinalMask(e, nextParams)
applyEndpointAllowInsecure(e, nextParams, securityToApply)
remark := makeRemark(e)
if e.ServerDescription != "" {
if e.ServerDescription != "" && !s.omitServerDescription {
remark = appendHappServerDescription(remark, e.ServerDescription)
}
links = append(links, buildLinkWithParamsAndSecurity(

View file

@ -52,6 +52,9 @@ func TestGenHysteriaLinkAppendsHostServerDescription(t *testing.T) {
if !strings.HasSuffix(got, "?serverDescription=V2ktRmk=") {
t.Fatalf("host serverDescription missing from fragment.\n got: %s\nwant suffix: ?serverDescription=V2ktRmk=", got)
}
if got := (&SubService{omitServerDescription: true}).genHysteriaLink(in, "user"); strings.Contains(got, "serverDescription") {
t.Fatalf("tail not omitted: %s", got)
}
})
}
}

View file

@ -46,6 +46,9 @@ type SubService struct {
// other context — the sub info page, the panel's link/QR displays — renders
// the name-only template, like Remnawave.
subscriptionBody bool
// omitServerDescription drops the ?serverDescription= tail, which only Happ
// and INCY read; other clients show it in the node name (#7105).
omitServerDescription bool
// usageShown emits info once per subscription identity, including twins.
// PrepareForRequest resets this per-request state.
usageShown map[string]bool
@ -1744,7 +1747,9 @@ func (s *SubService) genHysteriaLink(inbound *model.Inbound, email string) strin
// VLESS/Trojan/SS get the host's description through buildEndpointLinks;
// this loop renders the fragment itself, so add it here too (#6738).
remark := s.endpointRemark(inbound, email, ep, "quic")
remark = appendHappServerDescription(remark, externalProxyToEndpoint(ep).ServerDescription)
if !s.omitServerDescription {
remark = appendHappServerDescription(remark, externalProxyToEndpoint(ep).ServerDescription)
}
links = append(links, buildLinkWithParams(link, epParams, remark))
}
return strings.Join(links, "\n")

View file

@ -1,6 +1,8 @@
package totp
import (
"encoding/base32"
"strings"
"time"
"github.com/xlzd/gotp"
@ -10,9 +12,25 @@ import (
// Standard TOTP clock-drift tolerance, see MHSanaei/3x-ui#6535.
const SkewWindows = 1
// NormalizeSecret turns a base32 key as authenticator apps show it (lower case,
// grouped by spaces, padded) into the bare upper-case form gotp decodes.
func NormalizeSecret(secret string) string {
return strings.TrimRight(strings.ToUpper(strings.Join(strings.Fields(secret), "")), "=")
}
// ValidSecret reports whether secret is a non-empty base32 key once normalized.
func ValidSecret(secret string) bool {
key, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(NormalizeSecret(secret))
return err == nil && len(key) > 0
}
// VerifyWithSkew accepts the code for the current step plus/minus SkewWindows.
// An empty or non-base32 secret verifies nothing (gotp panics on the latter).
func VerifyWithSkew(secret, code string, now time.Time) bool {
totp := gotp.NewDefaultTOTP(secret)
if !ValidSecret(secret) {
return false
}
totp := gotp.NewDefaultTOTP(NormalizeSecret(secret))
for i := -SkewWindows; i <= SkewWindows; i++ {
if totp.AtTime(now.Add(time.Duration(i*30)*time.Second)) == code {
return true

View file

@ -32,3 +32,30 @@ func TestVerifyWithSkew(t *testing.T) {
t.Fatal("wrong code should not verify")
}
}
func TestVerifyWithSkewSecretForms(t *testing.T) {
const canonical = "JBSWY3DPEHPK3PXP"
now := time.Unix((time.Now().Unix()/30)*30+15, 0).UTC()
code := gotp.NewDefaultTOTP(canonical).AtTime(now)
cases := []struct {
name string
secret string
want bool
}{
{"canonical", canonical, true},
{"lower case", "jbswy3dpehpk3pxp", true},
{"grouped and padded", " jbsw y3dp ehpk 3pxp== ", true},
{"empty", "", false},
{"blank", " ", false},
{"not base32", "totp-secret", false},
{"base32 digits out of range", "JBSWY3DPEHPK3PX1", false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := VerifyWithSkew(c.secret, code, now); got != c.want {
t.Fatalf("VerifyWithSkew(%q) = %v, want %v", c.secret, got, c.want)
}
})
}
}

View file

@ -174,6 +174,40 @@ func TestGroupTotalsSurviveBulkClientReset(t *testing.T) {
}
}
func TestGroupTotalsSurviveGlobalClientReset(t *testing.T) {
initTrafficTestDB(t)
svc := &ClientService{}
seedGroupedClient(t, "alice", "reset", 100, 200)
seedGroupedClient(t, "bob", "unreset", 40, 60)
if err := svc.ResetGroupTraffic("reset"); err != nil {
t.Fatalf("ResetGroupTraffic: %v", err)
}
if _, err := svc.ResetAllTraffics(); err != nil {
t.Fatalf("ResetAllTraffics: %v", err)
}
if g := groupByName(t, svc, "unreset"); g.Up != 40 || g.Down != 60 || g.TrafficUsed != 100 {
t.Fatalf("global reset changed accumulated group usage: got %+v, want up=40 down=60 used=100", g)
}
var traffic xray.ClientTraffic
if err := database.GetDB().Where("email = ?", "alice").First(&traffic).Error; err != nil {
t.Fatalf("load alice traffic: %v", err)
}
if traffic.Up != 0 || traffic.Down != 0 {
t.Fatalf("client traffic not reset: up=%d down=%d", traffic.Up, traffic.Down)
}
if err := database.GetDB().Model(&traffic).
Updates(map[string]any{"up": 10, "down": 20}).Error; err != nil {
t.Fatalf("record new alice traffic: %v", err)
}
if g := groupByName(t, svc, "reset"); g.Up != 10 || g.Down != 20 || g.TrafficUsed != 30 {
t.Fatalf("global reset hid new group usage: got %+v, want up=10 down=20 used=30", g)
}
}
func TestGroupTotalsSurviveClientDelete(t *testing.T) {
initTrafficTestDB(t)
csvc := &ClientService{}

View file

@ -67,6 +67,14 @@ func adjustGroupBaselinesForRemovedTraffic(tx *gorm.DB, emails []string) error {
return shiftGroupBaselines(tx, emails, -1)
}
func adjustAllGroupBaselinesForRemovedTraffic(tx *gorm.DB) error {
totals, err := sumGroupTraffic(tx, "c.group_name <> ''")
if err != nil {
return err
}
return applyGroupBaselineShift(tx, totals, -1)
}
// adjustGroupBaselinesForRestoredTraffic shifts group baselines up by counters an
// import restored, so usage from before the import never enters a group total.
func adjustGroupBaselinesForRestoredTraffic(tx *gorm.DB, emails []string) error {
@ -92,6 +100,10 @@ func shiftGroupBaselines(tx *gorm.DB, emails []string, sign int64) error {
}
}
}
return applyGroupBaselineShift(tx, totals, sign)
}
func applyGroupBaselineShift(tx *gorm.DB, totals map[string]*groupCounters, sign int64) error {
for name, d := range totals {
if d.up == 0 && d.down == 0 {
continue

View file

@ -252,6 +252,9 @@ func (s *ClientService) ResetAllTraffics() (bool, error) {
if qErr != nil {
return qErr
}
if err := adjustAllGroupBaselinesForRemovedTraffic(tx); err != nil {
return err
}
if affected, qErr = zeroClientTraffics(tx, nil, keepOff); qErr != nil {
return qErr
}

View file

@ -4,6 +4,9 @@ import (
"path/filepath"
"strings"
"testing"
"time"
"github.com/xlzd/gotp"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
@ -74,3 +77,36 @@ func TestUserSettersRefuseNamesTheLoginRouteRefuses(t *testing.T) {
t.Fatalf("stored username = %q (%v), want it unchanged", stored.Username, err)
}
}
// A stored 2FA secret in a form gotp cannot decode made every login panic (HTTP 500).
func TestCheckUserTwoFactorSecretForms(t *testing.T) {
cases := []struct {
name, stored, codeSecret string
want bool
}{
{"canonical", "JBSWY3DPEHPK3PXP", "JBSWY3DPEHPK3PXP", true},
{"lower case", "jbswy3dpehpk3pxp", "JBSWY3DPEHPK3PXP", true},
{"not base32", "totp-secret", "JBSWY3DPEHPK3PXP", false},
{"empty secret", "", "", false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
svc := &UserService{}
if err := svc.UpdateFirstUser("admin", "s3cret-Pass"); err != nil {
t.Fatalf("UpdateFirstUser: %v", err)
}
if err := svc.settingService.SetTwoFactorEnable(true); err != nil {
t.Fatal(err)
}
if err := svc.settingService.SetTwoFactorToken(tc.stored); err != nil {
t.Fatal(err)
}
code := gotp.NewDefaultTOTP(tc.codeSecret).AtTime(time.Now())
user, err := svc.CheckUser("admin", "s3cret-Pass", code)
if got := err == nil && user != nil; got != tc.want {
t.Fatalf("CheckUser with stored secret %q: ok = %v (%v), want %v", tc.stored, got, err, tc.want)
}
})
}
}

View file

@ -1683,6 +1683,12 @@ func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting, clears
if err := s.preserveRedactedSecrets(allSetting, clears); err != nil {
return err
}
if allSetting.TwoFactorEnable {
if !totp.ValidSecret(allSetting.TwoFactorToken) {
return errors.New("two-factor secret must be a non-empty base32 key")
}
allSetting.TwoFactorToken = totp.NormalizeSecret(allSetting.TwoFactorToken)
}
if err := validateSettingsURLs(allSetting); err != nil {
return err
}

View file

@ -102,7 +102,7 @@ func TestUpdateAllSettingPreservesRedactedSecrets(t *testing.T) {
if err := s.saveSetting("twoFactorEnable", "true"); err != nil {
t.Fatal(err)
}
if err := s.saveSetting("twoFactorToken", "totp-secret"); err != nil {
if err := s.saveSetting("twoFactorToken", "JBSWY3DPEHPK3PXP"); err != nil {
t.Fatal(err)
}
if err := s.saveSetting("smtpPassword", "smtp-secret"); err != nil {
@ -126,7 +126,7 @@ func TestUpdateAllSettingPreservesRedactedSecrets(t *testing.T) {
if got, _ := s.GetLdapPassword(); got != "ldap-secret" {
t.Fatalf("ldap password = %q, want preserved secret", got)
}
if got, _ := s.GetTwoFactorToken(); got != "totp-secret" {
if got, _ := s.GetTwoFactorToken(); got != "JBSWY3DPEHPK3PXP" {
t.Fatalf("2fa token = %q, want preserved secret", got)
}
if got, _ := s.GetSmtpPassword(); got != "smtp-secret" {
@ -137,6 +137,44 @@ func TestUpdateAllSettingPreservesRedactedSecrets(t *testing.T) {
}
}
// Turning 2FA on stores the secret in the form the TOTP decoder takes, and refuses
// one that no authenticator code could ever match.
func TestUpdateAllSettingTwoFactorSecret(t *testing.T) {
cases := []struct {
name, stored, submitted, want string
wantErr bool
}{
{name: "canonical", submitted: "JBSWY3DPEHPK3PXP", want: "JBSWY3DPEHPK3PXP"},
{name: "lower case and grouped", submitted: "jbsw y3dp ehpk 3pxp", want: "JBSWY3DPEHPK3PXP"},
{name: "redacted keeps stored", stored: "ORIGINALSECRET234567", submitted: "", want: "ORIGINALSECRET234567"},
{name: "not base32", stored: "ORIGINALSECRET234567", submitted: "totp-secret", want: "ORIGINALSECRET234567", wantErr: true},
{name: "nothing stored", submitted: "", want: "", wantErr: true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
setupSettingTestDB(t)
s := &SettingService{}
if err := s.SetTwoFactorToken(tc.stored); err != nil {
t.Fatal(err)
}
view, err := s.GetAllSettingView()
if err != nil {
t.Fatal(err)
}
settings := &view.AllSetting
settings.TwoFactorEnable = true
settings.TwoFactorToken = tc.submitted
err = s.UpdateAllSetting(settings, SecretClears{})
if (err != nil) != tc.wantErr {
t.Fatalf("UpdateAllSetting error = %v, wantErr %v", err, tc.wantErr)
}
if got, _ := s.GetTwoFactorToken(); got != tc.want {
t.Fatalf("stored 2FA secret = %q, want %q", got, tc.want)
}
})
}
}
func TestUpdateAllSettingClearsFlaggedSecrets(t *testing.T) {
setupSettingTestDB(t)
s := &SettingService{}

View file

@ -0,0 +1,135 @@
package tgbot
import (
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"github.com/mymmrac/telego"
)
const testXrayConfig = `{"log":{}}`
// backupFixture gives GetDb and the config read real files in a throwaway folder.
func backupFixture(t *testing.T) (*Tgbot, func() []apiCall) {
t.Helper()
_, calls := newScreenTgbot(t, false)
t.Setenv("XUI_DB_FOLDER", t.TempDir())
binFolder := t.TempDir()
t.Setenv("XUI_BIN_FOLDER", binFolder)
if err := os.WriteFile(filepath.Join(binFolder, "config.json"), []byte(testXrayConfig), 0o600); err != nil {
t.Fatal(err)
}
tb := initReportDB(t)
setTestAdmins(t, 1)
tb.resolveScreenArt()
return tb, calls
}
func documentsOf(calls []apiCall) []apiCall {
var documents []apiCall
for _, call := range calls {
if call.Method == "sendDocument" {
documents = append(documents, call)
}
}
return documents
}
// A Hide button on a backup deleted the admin's only copy of the database with
// one tap, so neither delivery path may offer a way to delete the files.
func TestBackupFilesCarryNoHideButton(t *testing.T) {
for _, tc := range []struct {
name string
deliver func(tb *Tgbot)
}{
{"backup button", func(tb *Tgbot) {
tb.answerCallback(&telego.CallbackQuery{
ID: "q1", From: telego.User{ID: 1}, Data: cbBackup,
Message: &telego.Message{MessageID: 50, Chat: telego.Chat{ID: 1, Type: "private"}},
}, true)
}},
{"scheduled backup", func(tb *Tgbot) { tb.SendBackupToAdmins() }},
} {
t.Run(tc.name, func(t *testing.T) {
tb, calls := backupFixture(t)
tc.deliver(tb)
documents := documentsOf(calls())
if len(documents) != 2 {
t.Fatalf("documents = %d, want the database and config.json (calls: %v)", len(documents), methods(calls()))
}
dbName, _ := documents[0].Payload["filename"].(string)
if !strings.HasSuffix(dbName, ".db") || documents[1].Payload["filename"] != "config.json" {
t.Errorf("files = %q, %v; want a .db then config.json", dbName, documents[1].Payload["filename"])
}
for _, document := range documents {
if markup, ok := document.Payload["reply_markup"]; ok {
t.Errorf("%v carries a keyboard that can delete it: %v", document.Payload["filename"], markup)
}
}
})
}
}
// The files used to land under the menu and bury it, so the bot looked dead to
// an admin who stayed at the bottom of the chat.
func TestBackupButtonMovesTheMenuBelowTheFiles(t *testing.T) {
tb, calls := backupFixture(t)
const chatID int64 = 1
tb.screenCategory(chatID, "maintenance")
menu, ok := tb.screens().get(chatID)
if !ok {
t.Fatal("menu not tracked")
}
before := len(calls())
tb.answerCallback(&telego.CallbackQuery{
ID: "q1", From: telego.User{ID: 1}, Data: cbBackup,
Message: &telego.Message{MessageID: menu.msgID, Chat: telego.Chat{ID: chatID, Type: "private"}},
}, true)
got := calls()[before:]
want := []string{"answerCallbackQuery", "sendDocument", "sendDocument", "sendPhoto", "deleteMessage"}
if !reflect.DeepEqual(methods(got), want) {
t.Fatalf("calls = %v, want %v", methods(got), want)
}
if deleted := got[4].Payload["message_id"]; deleted != float64(menu.msgID) {
t.Errorf("deleted message %v, want the old menu %d", deleted, menu.msgID)
}
current, ok := tb.screens().get(chatID)
if !ok || current.msgID == menu.msgID || !hasButton(current.rows, cbBackup) {
t.Errorf("tracked screen = %+v, want a new maintenance menu", current)
}
}
// A scheduled backup arrives unprompted: it must not move a menu the admin may
// be using at that moment.
func TestScheduledBackupLeavesTheMenuInPlace(t *testing.T) {
tb, calls := backupFixture(t)
tb.screenCategory(1, "maintenance")
menu, _ := tb.screens().get(1)
before := len(calls())
tb.SendBackupToAdmins()
if got := methods(calls()[before:]); !reflect.DeepEqual(got, []string{"sendDocument", "sendDocument"}) {
t.Errorf("calls = %v, want only the two files", got)
}
if current, _ := tb.screens().get(1); current.msgID != menu.msgID {
t.Errorf("tracked menu moved from %d to %d", menu.msgID, current.msgID)
}
}
func hasButton(rows [][]telego.InlineKeyboardButton, data string) bool {
for _, row := range rows {
for _, button := range row {
if button.CallbackData == data {
return true
}
}
}
return false
}

View file

@ -129,9 +129,9 @@ func (t *Tgbot) dropNoticeFor(chatID int64, msgID int) {
}
}
// sendDocumentWithCaption uploads a file with its summary as caption: a document
// cannot hold a screen, so one message does the work of two.
func (t *Tgbot) sendDocumentWithCaption(chatID int64, data []byte, name, caption string) bool {
// sendBackupFile uploads a file with its summary as caption. It has no hide button:
// that button deletes the message, and this may be the admin's only copy.
func (t *Tgbot) sendBackupFile(chatID int64, data []byte, name, caption string) bool {
if liveBot() == nil || data == nil {
return false
}
@ -139,10 +139,9 @@ func (t *Tgbot) sendDocumentWithCaption(chatID int64, data []byte, name, caption
defer cancel()
_, err := liveBot().SendDocument(ctx, &telego.SendDocumentParams{
ChatID: tu.ID(chatID), MessageThreadID: adminTopic(chatID),
Document: tu.FileFromBytes(data, name),
Caption: caption,
ParseMode: "HTML",
ReplyMarkup: t.hideButton(),
Document: tu.FileFromBytes(data, name),
Caption: caption,
ParseMode: "HTML",
})
if err != nil {
logger.Warning("Failed to upload a file with a caption:", err)

View file

@ -96,7 +96,7 @@ func TestBackupArrivesAsOneMessageWithACaption(t *testing.T) {
notices.reset()
tb := initReportDB(t)
tb.sendDocumentWithCaption(1, []byte("db-bytes"), "x-ui.db", "host\nbackup time")
tb.sendBackupFile(1, []byte("db-bytes"), "x-ui.db", "host\nbackup time")
got := calls()
sends := 0

View file

@ -89,11 +89,11 @@ func (t *Tgbot) categoryRows(category string) [][]telego.InlineKeyboardButton {
// screenCategory draws one menu subject. The hint line names the subject, so a
// user who arrived through a notification can see where they are.
func (t *Tgbot) screenCategory(chatID int64, category string) {
func (t *Tgbot) screenCategory(chatID int64, category string, delivery ...screenDelivery) {
body := t.I18nBot("tgbot.messages.category_" + category)
rows := [][]telego.InlineKeyboardButton{}
rows = append(rows, t.categoryRows(category)...)
t.renderScreen(chatID, t.newScreen("main", body, rows...))
t.renderScreen(chatID, t.newScreen("main", body, rows...), delivery...)
}
// btn is where a localized label becomes a callback button; btn2 is btn with a

View file

@ -266,11 +266,11 @@ func (t *Tgbot) sendBackupScreen(chatID int64) {
// carries the backup and what it is for.
body := summary + "\n\n" + t.depleteReport()
caption := trimCaption(body, botCaptionLimit)
if t.sendDocumentWithCaption(chatID, dbData, t.serverService.BackupFilename(""), caption) {
if t.sendBackupFile(chatID, dbData, t.serverService.BackupFilename(""), caption) {
// The generated config travels with the DB on both backup paths: an
// operator restoring from the file would otherwise lose it silently.
if config, err := os.ReadFile(xray.GetConfigPath()); err == nil {
t.sendDocumentWithCaption(chatID, config, "config.json", "")
t.sendBackupFile(chatID, config, "config.json", "")
}
if rest := strings.TrimSpace(strings.TrimPrefix(body, caption)); rest != "" {
// Rare: the summary outgrew a caption. The file already landed.

View file

@ -60,7 +60,8 @@ func recordingServer(t *testing.T, failEdit bool, overrides ...map[string]any) (
if strings.HasPrefix(string(body), "{") {
// JSON payload: keep it as decoded.
} else {
payload = map[string]any{}
r.Body = io.NopCloser(bytes.NewReader(body))
payload = multipartPayload(r)
}
mu.Lock()
calls = append(calls, apiCall{Method: method, Payload: payload})
@ -139,6 +140,22 @@ func recordingServer(t *testing.T, failEdit bool, overrides ...map[string]any) (
}
}
// multipartPayload exposes an upload's form fields as a payload; the uploaded
// document's file name is under "filename".
func multipartPayload(r *http.Request) map[string]any {
payload := map[string]any{}
if r.ParseMultipartForm(1<<22) != nil {
return payload
}
for name, values := range r.MultipartForm.Value {
payload[name] = values[0]
}
if files := r.MultipartForm.File["document"]; len(files) > 0 {
payload["filename"] = files[0].Filename
}
return payload
}
// newScreenTgbot points the package bot at a recording server and clears the
// process-wide screen state the previous test may have left behind.
func newScreenTgbot(t *testing.T, failEdit bool) (*Tgbot, func() []apiCall) {

View file

@ -123,10 +123,10 @@ func (t *Tgbot) SendBackupToAdmins() {
if dbData == nil {
t.sendNotice(adminId, t.I18nBot("tgbot.messages.backupFailed"))
} else {
t.sendDocumentWithCaption(adminId, dbData, dbFilename, t.backupSummary())
t.sendBackupFile(adminId, dbData, dbFilename, t.backupSummary())
time.Sleep(500 * time.Millisecond)
if configErr == nil {
t.sendDocumentWithCaption(adminId, config, "config.json", "")
t.sendBackupFile(adminId, config, "config.json", "")
}
}
// Add delay between sends to avoid Telegram rate limits

View file

@ -1000,6 +1000,8 @@ func (t *Tgbot) answerCallback(callbackQuery *telego.CallbackQuery, isAdmin bool
case "bkp", "get_backup":
t.answerSilent(callbackQuery.ID)
t.sendBackupScreen(chatId)
// The files landed under the menu; bring it back below them so it stays in view.
t.screenCategory(chatId, "maintenance", screenSendNew)
case "ban", "get_banlogs":
t.answerSilent(callbackQuery.ID)
t.screenBanLogs(chatId)

View file

@ -204,6 +204,7 @@ func (s *XrayService) GetXrayConfig() (*xray.Config, error) {
if err != nil {
return nil, err
}
excludedClients, excludedInbounds := 0, 0
for _, inbound := range inbounds {
if !inbound.Enable {
continue
@ -248,10 +249,11 @@ func (s *XrayService) GetXrayConfig() (*xray.Config, error) {
finalClients := make([]any, 0, len(dbClients))
var wgPeers []any
excludedBefore := excludedClients
for i := range dbClients {
c := dbClients[i]
if enable, exists := enableMap[c.Email]; exists && !enable {
logger.Infof("Remove Inbound User %s due to expiration or traffic limit", c.Email)
excludedClients++
continue
}
if !c.Enable {
@ -320,6 +322,9 @@ func (s *XrayService) GetXrayConfig() (*xray.Config, error) {
}
finalClients = append(finalClients, entry)
}
if excludedClients > excludedBefore {
excludedInbounds++
}
var mutated bool
if inbound.Protocol == model.WireGuard {
@ -491,6 +496,9 @@ func (s *XrayService) GetXrayConfig() (*xray.Config, error) {
xrayConfig.RouterConfig = dropRefusedScript(xrayConfig.RouterConfig, "routing", routingScriptRefused)
xrayConfig.DNSConfig = dropRefusedScript(xrayConfig.DNSConfig, "dns", dnsScriptRefused)
if excludedClients > 0 {
logger.Infof("Xray config generated: excluded %d disabled client entries across %d inbounds", excludedClients, excludedInbounds)
}
return xrayConfig, nil
}

View file

@ -2,13 +2,167 @@ package service
import (
"encoding/json"
"fmt"
"strings"
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
func TestGetXrayConfig_AggregatesExcludedClientLogs(t *testing.T) {
for _, tc := range []struct {
name string
clients int
inbounds int
excluded int
affected int
shared bool
}{
{"2000 excluded entries", 2000, 5, 2000, 5, false},
{"mixed clients and inbounds", 8, 4, 3, 2, false},
{"no excluded entries", 8, 4, 0, 0, false},
{"shared client counts as two entries", 4, 2, 1, 2, true},
} {
t.Run(tc.name, func(t *testing.T) {
setupSettingTestDB(t)
ds := seedScaleDataset(t, tc.clients, tc.inbounds)
excluded := make(map[string]bool, tc.excluded)
for _, email := range ds.emails[:tc.excluded] {
excluded[email] = true
}
if tc.shared {
var record model.ClientRecord
if err := database.GetDB().Where("email = ?", ds.emails[0]).First(&record).Error; err != nil {
t.Fatal(err)
}
if err := database.GetDB().Create(&model.ClientInbound{ClientId: record.Id, InboundId: ds.inboundIds[1]}).Error; err != nil {
t.Fatal(err)
}
}
// Manual disablement is a separate filter and must not inflate the summary.
if tc.excluded < tc.clients {
disableClients(t, ds.emails[tc.clients-1])
}
svc := &XrayService{}
want, err := svc.GetXrayConfig()
if err != nil {
t.Fatal(err)
}
for i, tag := range ds.tags {
clients := make([]map[string]string, 0)
for _, client := range ds.perInbound[i] {
if !excluded[client.Email] && client.Email != ds.emails[tc.clients-1] {
clients = append(clients, map[string]string{"email": client.Email, "id": client.ID})
}
}
for k := range want.InboundConfigs {
if want.InboundConfigs[k].Tag == tag {
settings, err := json.MarshalIndent(map[string]any{"clients": clients}, "", " ")
if err != nil {
t.Fatal(err)
}
want.InboundConfigs[k].Settings = settings
}
}
}
wantJSON, err := json.Marshal(want)
if err != nil {
t.Fatal(err)
}
if tc.excluded > 0 {
if err := database.GetDB().Model(&xray.ClientTraffic{}).
Where("email IN ?", ds.emails[:tc.excluded]).Update("enable", false).Error; err != nil {
t.Fatal(err)
}
}
for generation := range 2 {
marker := fmt.Sprintf("%s generation %d", t.Name(), generation)
logger.Info(marker)
got, err := svc.GetXrayConfig()
if err != nil {
t.Fatal(err)
}
gotJSON, err := json.Marshal(got)
if err != nil {
t.Fatal(err)
}
if string(gotJSON) != string(wantJSON) {
t.Fatal("generated config changed beyond the expected client exclusions")
}
infoCount := 0
foundMarker := false
for _, line := range logger.GetLogs(10000, "DEBUG") {
if strings.HasSuffix(line, " INFO - "+marker) {
foundMarker = true
break
}
if strings.Contains(line, "Remove Inbound User") || strings.Contains(line, "@scale") {
t.Fatalf("per-client log emitted: %s", line)
}
for _, clients := range ds.perInbound {
for _, client := range clients {
if strings.Contains(line, client.ID) || strings.Contains(line, client.SubID) {
t.Error("client credential or subscription ID leaked into logs")
}
}
}
if strings.Contains(line, " INFO - ") {
infoCount++
entries := tc.excluded
if tc.shared {
entries++
}
message := fmt.Sprintf(" INFO - Xray config generated: excluded %d disabled client entries across %d inbounds", entries, tc.affected)
if !strings.HasSuffix(line, message) {
t.Errorf("unexpected INFO entry: %s", line)
}
}
}
wantCount := 0
if tc.excluded > 0 {
wantCount = 1
}
if !foundMarker || infoCount != wantCount {
t.Errorf("generation %d: marker found = %v, INFO entries = %d, want %d", generation, foundMarker, infoCount, wantCount)
}
}
})
}
}
func TestGetXrayConfig_FailureDoesNotLogExclusionSummary(t *testing.T) {
setupSettingTestDB(t)
ds := seedScaleDataset(t, 1, 1)
db := database.GetDB()
if err := db.Model(&xray.ClientTraffic{}).Where("email = ?", ds.emails[0]).Update("enable", false).Error; err != nil {
t.Fatal(err)
}
if err := db.Model(&model.Inbound{}).Where("id = ?", ds.inboundIds[0]).
Update("stream_settings", `{"network":"tcp","security":"tls","tlsSettings":{}}`).Error; err != nil {
t.Fatal(err)
}
if err := db.Migrator().DropTable(&model.InboundFallback{}); err != nil {
t.Fatal(err)
}
logger.Info(t.Name())
cfg, err := (&XrayService{}).GetXrayConfig()
if cfg != nil || err == nil || err.Error() != "no such table: inbound_fallbacks" {
t.Fatalf("GetXrayConfig = %v, %v; want missing fallback table failure", cfg, err)
}
for _, line := range logger.GetLogs(100, "DEBUG") {
if strings.HasSuffix(line, " INFO - "+t.Name()) {
return
}
if strings.Contains(line, "Xray config generated:") || strings.Contains(line, "Remove Inbound User") {
t.Fatalf("failed generation logged a successful summary or per-client removal: %s", line)
}
}
t.Fatal("log boundary not found")
}
func seedVlessInbound(t *testing.T, tag string, port int, clients []model.Client) {
t.Helper()
setupSettingTestDB(t)

View file

@ -3,13 +3,60 @@ package service
import (
"encoding/json"
"fmt"
"strings"
"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/logger"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
func BenchmarkGetXrayConfigDisabledClients(b *testing.B) {
b.Setenv("XUI_LOG_FOLDER", b.TempDir())
setupScaleDB(b)
b.Cleanup(logger.CloseLogger)
seedScaleDataset(b, 2000, 5)
db := database.GetDB()
// Fix the generated credentials and lifecycle values for before/after comparisons.
if err := db.Model(&model.ClientRecord{}).Where("id > 0").
Updates(map[string]any{"uuid": "11111111-1111-1111-1111-111111111111", "expiry_time": 0}).Error; err != nil {
b.Fatal(err)
}
if err := db.Model(&model.Inbound{}).Where("id > 0").Update("settings", `{"clients":[]}`).Error; err != nil {
b.Fatal(err)
}
if err := db.Model(&xray.ClientTraffic{}).Where("id > 0").
Updates(map[string]any{"enable": false, "expiry_time": 0}).Error; err != nil {
b.Fatal(err)
}
svc := &XrayService{}
b.ReportAllocs()
b.ResetTimer()
for range b.N {
if _, err := svc.GetXrayConfig(); err != nil {
b.Fatal(err)
}
}
b.StopTimer()
const marker = "disabled-client benchmark log boundary"
logger.Info(marker)
if _, err := svc.GetXrayConfig(); err != nil {
b.Fatal(err)
}
entries, bytes := 0, 0
for _, line := range logger.GetLogs(10000, "DEBUG") {
if strings.HasSuffix(line, " INFO - "+marker) {
break
}
entries++
bytes += len(line) + 1
}
b.ReportMetric(float64(entries), "logs/op")
b.ReportMetric(float64(bytes), "buffered-log-bytes/op")
}
// TestGetXrayConfigScale measures building the full Xray config (the path
// every restart/reconcile takes) and, separately, how much of the per-inbound
// settings rebuild is spent on indented vs plain JSON marshaling.

View file

@ -151,6 +151,11 @@
"xrayStatus": "Xray",
"stopXray": "إيقاف",
"restartXray": "إعادة تشغيل",
"startXray": "تشغيل",
"stopXrayDisabledHint": "Xray غير قيد التشغيل",
"stopXrayConfirmTitle": "إيقاف Xray؟",
"stopXrayConfirmContent": "سيؤدي إيقاف Xray إلى قطع جميع اتصالات البروكسي فورًا. هل تريد المتابعة؟",
"stopXrayConfirmOk": "إيقاف Xray",
"xraySwitch": "النسخة",
"xrayUpdates": "تحديثات Xray",
"xraySwitchClickDesk": "اختار بحذر، النسخ القديمة ممكن ما تتوافقش مع الإعدادات الحالية.",
@ -1194,7 +1199,7 @@
"tlsPin": "تثبيت الشهادة (SHA-256)",
"tlsSkip": "تخطّي التحقق",
"tlsMtls": "TLS متبادل (شهادة العميل)",
"mtlsFormHint": "يصادق هذا النود اللوحة باستخدام شهادة عميل. انسخ CA الخاص بهذه اللوحة من قسم mTLS النود إلى النود، واضبط CA الموثوق به، ثم أعد تشغيله.",
"mtlsFormHint": "يصادق هذا النود اللوحة باستخدام شهادة عميل. انسخ CA الخاص بهذه اللوحة من قسم mTLS النود إلى النود، واضبط CA الموثوق به، ثم أعد تشغيله. لا يزال تحديث لوحة هذا النود من هنا يتطلب رمز API بنطاق node-admin.",
"mtls": {
"title": "mTLS النود",
"intro": "يضيف TLS المتبادل عامل شهادة العميل فوق رمز API في الاتصالات بين النودات. وهو اختياري: اتركه فارغًا للاكتفاء بالمصادقة عبر الرمز.",

View file

@ -151,6 +151,11 @@
"xrayStatus": "Xray",
"stopXray": "Stop",
"restartXray": "Restart",
"startXray": "Start",
"stopXrayDisabledHint": "Xray is not running",
"stopXrayConfirmTitle": "Stop Xray?",
"stopXrayConfirmContent": "Stopping Xray will immediately interrupt all proxy connections. Are you sure you want to continue?",
"stopXrayConfirmOk": "Stop Xray",
"xraySwitch": "Version",
"xrayUpdates": "Xray Updates",
"xraySwitchClickDesk": "Choose carefully, as older versions may not be compatible with current configurations.",
@ -1315,7 +1320,7 @@
"tlsPin": "Pin certificate (SHA-256)",
"tlsSkip": "Skip verification",
"tlsMtls": "Mutual TLS (client certificate)",
"mtlsFormHint": "This node authenticates the panel with a client certificate. Copy this panel's CA from the Node mTLS section onto the node, set its Trusted parent CA, then restart it.",
"mtlsFormHint": "This node authenticates the panel with a client certificate. Copy this panel's CA from the Node mTLS section onto the node, set its Trusted parent CA, then restart it. Updating this node's panel from here still needs an API token with the node-admin scope.",
"mtls": {
"title": "Node mTLS",
"intro": "Mutual TLS adds a client-certificate factor on top of the API token for node-to-node calls. It is opt-in: leave it empty to keep token-only auth.",

View file

@ -151,6 +151,11 @@
"xrayStatus": "Xray",
"stopXray": "Detener",
"restartXray": "Reiniciar",
"startXray": "Iniciar",
"stopXrayDisabledHint": "Xray no se está ejecutando",
"stopXrayConfirmTitle": "¿Detener Xray?",
"stopXrayConfirmContent": "Detener Xray interrumpirá de inmediato todas las conexiones proxy. ¿Seguro que quieres continuar?",
"stopXrayConfirmOk": "Detener Xray",
"xraySwitch": "Versión",
"xrayUpdates": "Actualizaciones de Xray",
"xraySwitchClickDesk": "Elige sabiamente, ya que las versiones anteriores pueden no ser compatibles con las configuraciones actuales.",
@ -1194,7 +1199,7 @@
"tlsPin": "Fijar certificado (SHA-256)",
"tlsSkip": "Omitir verificación",
"tlsMtls": "TLS mutuo (certificado de cliente)",
"mtlsFormHint": "Este nodo autentica al panel con un certificado de cliente. Copia el CA de este panel desde la sección mTLS del nodo al nodo, configura su CA de confianza y luego reinícialo.",
"mtlsFormHint": "Este nodo autentica al panel con un certificado de cliente. Copia el CA de este panel desde la sección mTLS del nodo al nodo, configura su CA de confianza y luego reinícialo. Actualizar el panel de este nodo desde aquí sigue requiriendo un token de API con el alcance node-admin.",
"mtls": {
"title": "mTLS del nodo",
"intro": "TLS mutuo añade un factor de certificado de cliente además del token de API para las llamadas entre nodos. Es opcional: déjalo vacío para mantener solo la autenticación por token.",

View file

@ -151,6 +151,11 @@
"xrayStatus": "Xray",
"stopXray": "توقف",
"restartXray": "راه‌اندازی مجدد",
"startXray": "شروع",
"stopXrayDisabledHint": "Xray در حال اجرا نیست",
"stopXrayConfirmTitle": "Xray متوقف شود؟",
"stopXrayConfirmContent": "توقف Xray بلافاصله همه اتصالات پراکسی را قطع می‌کند. آیا مطمئن هستید؟",
"stopXrayConfirmOk": "توقف Xray",
"xraySwitch": "‌نسخه",
"xrayUpdates": "به‌روزرسانی‌های Xray",
"xraySwitchClickDesk": "لطفا بادقت انتخاب کنید. درصورت انتخاب نسخه قدیمی‌تر، امکان ناهماهنگی با پیکربندی فعلی وجود دارد",
@ -1194,7 +1199,7 @@
"tlsPin": "Pin گواهی (SHA-256)",
"tlsSkip": "رد کردن اعتبارسنجی",
"tlsMtls": "TLS متقابل (گواهی کلاینت)",
"mtlsFormHint": "این نود با یک گواهی کلاینت، پنل را احراز هویت می‌کند. CA این پنل را از بخش mTLS نود به نود کپی کنید، CA مورد اعتماد آن را تنظیم کنید و سپس آن را راه‌اندازی مجدد کنید.",
"mtlsFormHint": "این نود با یک گواهی کلاینت، پنل را احراز هویت می‌کند. CA این پنل را از بخش mTLS نود به نود کپی کنید، CA مورد اعتماد آن را تنظیم کنید و سپس آن را راه‌اندازی مجدد کنید. به‌روزرسانی پنل این نود از اینجا همچنان به یک توکن API با دامنهٔ node-admin نیاز دارد.",
"mtls": {
"title": "mTLS نود",
"intro": "TLS متقابل علاوه بر توکن API، یک عامل گواهی کلاینت برای ارتباط بین نودها اضافه می‌کند. اختیاری است: برای استفاده فقط از احراز هویت با توکن، آن را خالی بگذارید.",

View file

@ -151,6 +151,11 @@
"xrayStatus": "Xray",
"stopXray": "Hentikan",
"restartXray": "Mulai ulang",
"startXray": "Mulai",
"stopXrayDisabledHint": "Xray tidak berjalan",
"stopXrayConfirmTitle": "Hentikan Xray?",
"stopXrayConfirmContent": "Menghentikan Xray akan langsung memutus semua koneksi proxy. Yakin ingin melanjutkan?",
"stopXrayConfirmOk": "Hentikan Xray",
"xraySwitch": "Versi",
"xrayUpdates": "Pembaruan Xray",
"xraySwitchClickDesk": "Pilih dengan hati-hati, karena versi yang lebih lama mungkin tidak kompatibel dengan konfigurasi saat ini.",
@ -1194,7 +1199,7 @@
"tlsPin": "Pin sertifikat (SHA-256)",
"tlsSkip": "Lewati verifikasi",
"tlsMtls": "TLS mutual (sertifikat klien)",
"mtlsFormHint": "Node ini mengautentikasi panel dengan sertifikat klien. Salin CA panel ini dari bagian mTLS Node ke node, atur CA tepercayanya, lalu mulai ulang.",
"mtlsFormHint": "Node ini mengautentikasi panel dengan sertifikat klien. Salin CA panel ini dari bagian mTLS Node ke node, atur CA tepercayanya, lalu mulai ulang. Memperbarui panel node ini dari sini tetap memerlukan token API dengan cakupan node-admin.",
"mtls": {
"title": "mTLS Node",
"intro": "TLS mutual menambahkan faktor sertifikat klien di atas token API untuk panggilan antar-node. Bersifat opsional: biarkan kosong untuk tetap menggunakan autentikasi token saja.",

View file

@ -151,6 +151,11 @@
"xrayStatus": "Xray",
"stopXray": "停止",
"restartXray": "再起動",
"startXray": "開始",
"stopXrayDisabledHint": "Xray は実行されていません",
"stopXrayConfirmTitle": "Xray を停止しますか?",
"stopXrayConfirmContent": "Xray を停止すると、すべてのプロキシ接続が直ちに切断されます。続行しますか?",
"stopXrayConfirmOk": "Xray を停止",
"xraySwitch": "バージョン",
"xrayUpdates": "Xrayの更新",
"xraySwitchClickDesk": "慎重に選択してください。古いバージョンは現在の設定と互換性がない可能性があります。",
@ -1194,7 +1199,7 @@
"tlsPin": "証明書をピン留め(SHA-256)",
"tlsSkip": "検証をスキップ",
"tlsMtls": "相互 TLS(クライアント証明書)",
"mtlsFormHint": "このノードはクライアント証明書でパネルを認証します。「ノード mTLS」セクションからこのパネルの CA をノードにコピーし、信頼する CA を設定してから再起動してください。",
"mtlsFormHint": "このノードはクライアント証明書でパネルを認証します。「ノード mTLS」セクションからこのパネルの CA をノードにコピーし、信頼する CA を設定してから再起動してください。 ここからこのノードのパネルを更新するには、node-admin スコープの API トークンが引き続き必要です。",
"mtls": {
"title": "ノード mTLS",
"intro": "相互 TLS は、ノード間通信で API トークンに加えてクライアント証明書による認証を追加します。任意です。空のままにするとトークンのみの認証になります。",

View file

@ -151,6 +151,11 @@
"xrayStatus": "Xray",
"stopXray": "Parar",
"restartXray": "Reiniciar",
"startXray": "Iniciar",
"stopXrayDisabledHint": "O Xray não está em execução",
"stopXrayConfirmTitle": "Parar o Xray?",
"stopXrayConfirmContent": "Parar o Xray interromperá imediatamente todas as conexões de proxy. Tem certeza de que deseja continuar?",
"stopXrayConfirmOk": "Parar o Xray",
"xraySwitch": "Versão",
"xrayUpdates": "Atualizações do Xray",
"xraySwitchClickDesk": "Escolha com cuidado, pois versões mais antigas podem não ser compatíveis com as configurações atuais.",
@ -1194,7 +1199,7 @@
"tlsPin": "Fixar certificado (SHA-256)",
"tlsSkip": "Ignorar verificação",
"tlsMtls": "TLS mútuo (certificado de cliente)",
"mtlsFormHint": "Este nó autentica o painel com um certificado de cliente. Copie o CA deste painel na seção mTLS do nó para o nó, defina o CA confiável dele e reinicie-o.",
"mtlsFormHint": "Este nó autentica o painel com um certificado de cliente. Copie o CA deste painel na seção mTLS do nó para o nó, defina o CA confiável dele e reinicie-o. Atualizar o painel deste nó a partir daqui ainda exige um token de API com o escopo node-admin.",
"mtls": {
"title": "mTLS do nó",
"intro": "O TLS mútuo adiciona um fator de certificado de cliente além do token de API nas chamadas entre nós. É opcional: deixe vazio para manter apenas a autenticação por token.",

View file

@ -151,6 +151,11 @@
"xrayStatus": "Xray",
"stopXray": "Стоп",
"restartXray": "Перезапуск",
"startXray": "Запуск",
"stopXrayDisabledHint": "Xray не запущен",
"stopXrayConfirmTitle": "Остановить Xray?",
"stopXrayConfirmContent": "Остановка Xray немедленно разорвёт все прокси-соединения. Продолжить?",
"stopXrayConfirmOk": "Остановить Xray",
"xraySwitch": "Выбор версии",
"xrayUpdates": "Обновления Xray",
"xraySwitchClickDesk": "Важно: старые версии могут не поддерживать текущие настройки",
@ -1194,7 +1199,7 @@
"tlsPin": "Закрепить сертификат (SHA-256)",
"tlsSkip": "Пропустить проверку",
"tlsMtls": "Взаимный TLS (клиентский сертификат)",
"mtlsFormHint": "Этот узел аутентифицирует панель с помощью клиентского сертификата. Скопируйте CA этой панели из раздела «mTLS узла» на узел, задайте его доверенный CA и перезапустите узел.",
"mtlsFormHint": "Этот узел аутентифицирует панель с помощью клиентского сертификата. Скопируйте CA этой панели из раздела «mTLS узла» на узел, задайте его доверенный CA и перезапустите узел. Для обновления панели этого узла отсюда по-прежнему нужен API-токен с областью node-admin.",
"mtls": {
"title": "mTLS узла",
"intro": "Взаимный TLS добавляет фактор клиентского сертификата поверх API-токена для вызовов между узлами. Это необязательно: оставьте пустым, чтобы использовать только аутентификацию по токену.",

View file

@ -151,6 +151,11 @@
"xrayStatus": "Xray",
"stopXray": "Zastaviť",
"restartXray": "Reštartovať",
"startXray": "Spustiť",
"stopXrayDisabledHint": "Xray nebeží",
"stopXrayConfirmTitle": "Zastaviť Xray?",
"stopXrayConfirmContent": "Zastavenie Xray okamžite preruší všetky proxy spojenia. Naozaj chcete pokračovať?",
"stopXrayConfirmOk": "Zastaviť Xray",
"xraySwitch": "Verzia",
"xrayUpdates": "Aktualizácie Xray",
"xraySwitchClickDesk": "Verziu vyberajte opatrne. Staršie verzie nemusia podporovať aktuálnu konfiguráciu.",
@ -1315,7 +1320,7 @@
"tlsPin": "Pevný odtlačok certifikátu (SHA-256)",
"tlsSkip": "Vynechať overenie",
"tlsMtls": "Vzájomné TLS (klientsky certifikát)",
"mtlsFormHint": "Tento server overuje panel klientskym certifikátom. Skopírujte certifikačnú autoritu tohto panelu z časti mTLS serverov na vzdialený server, nastavte jeho dôveryhodnú nadradenú autoritu a potom ho reštartujte.",
"mtlsFormHint": "Tento server overuje panel klientskym certifikátom. Skopírujte certifikačnú autoritu tohto panelu z časti mTLS serverov na vzdialený server, nastavte jeho dôveryhodnú nadradenú autoritu a potom ho reštartujte. Aktualizácia panelu tohto servera odtiaľto stále vyžaduje API token s rozsahom node-admin.",
"mtls": {
"title": "mTLS serverov",
"intro": "Vzájomné TLS pridáva k tokenu API aj overenie klientskym certifikátom pri komunikácii medzi servermi. Je voliteľné. Prázdne nastavenie ponechá overenie iba tokenom.",

View file

@ -151,6 +151,11 @@
"xrayStatus": "Xray",
"stopXray": "Durdur",
"restartXray": "Yeniden Başlat",
"startXray": "Başlat",
"stopXrayDisabledHint": "Xray çalışmıyor",
"stopXrayConfirmTitle": "Xray durdurulsun mu?",
"stopXrayConfirmContent": "Xray'i durdurmak tüm proxy bağlantılarını anında keser. Devam etmek istediğinizden emin misiniz?",
"stopXrayConfirmOk": "Xray'i durdur",
"xraySwitch": "Sürüm",
"xrayUpdates": "Xray Güncellemeleri",
"xraySwitchClickDesk": "Dikkatli seçin, eski sürümler mevcut yapılandırmalarla uyumlu olmayabilir.",
@ -1194,7 +1199,7 @@
"tlsPin": "Sertifikayı Sabitle (SHA-256)",
"tlsSkip": "Doğrulamayı Atla",
"tlsMtls": "Karşılıklı TLS (istemci sertifikası)",
"mtlsFormHint": "Bu düğüm, paneli bir istemci sertifikasıyla doğrular. Düğüm mTLS bölümünden bu panelin CA’sını düğüme kopyalayın, güvenilen CA’sını ayarlayın ve ardından düğümü yeniden başlatın.",
"mtlsFormHint": "Bu düğüm, paneli bir istemci sertifikasıyla doğrular. Düğüm mTLS bölümünden bu panelin CA’sını düğüme kopyalayın, güvenilen CA’sını ayarlayın ve ardından düğümü yeniden başlatın. Bu düğümün panelini buradan güncellemek için yine de node-admin kapsamlı bir API belirteci gerekir.",
"mtls": {
"title": "Düğüm mTLS",
"intro": "Karşılıklı TLS, düğümler arası çağrılarda API belirtecinin yanına bir istemci sertifikası faktörü ekler. İsteğe bağlıdır: yalnızca belirteçle kimlik doğrulamayı sürdürmek için boş bırakın.",

View file

@ -151,6 +151,11 @@
"xrayStatus": "Xray",
"stopXray": "Стоп",
"restartXray": "Перезапуск",
"startXray": "Запуск",
"stopXrayDisabledHint": "Xray не запущено",
"stopXrayConfirmTitle": "Зупинити Xray?",
"stopXrayConfirmContent": "Зупинка Xray негайно розірве всі проксі-з'єднання. Продовжити?",
"stopXrayConfirmOk": "Зупинити Xray",
"xraySwitch": "Версія",
"xrayUpdates": "Оновлення Xray",
"xraySwitchClickDesk": "Вибирайте уважно, оскільки старіші версії можуть бути несумісними з поточними конфігураціями.",
@ -1194,7 +1199,7 @@
"tlsPin": "Закріпити сертифікат (SHA-256)",
"tlsSkip": "Пропустити перевірку",
"tlsMtls": "Взаємний TLS (клієнтський сертифікат)",
"mtlsFormHint": "Цей вузол автентифікує панель за допомогою клієнтського сертифіката. Скопіюйте CA цієї панелі з розділу «mTLS вузла» на вузол, задайте його довірений CA та перезапустіть вузол.",
"mtlsFormHint": "Цей вузол автентифікує панель за допомогою клієнтського сертифіката. Скопіюйте CA цієї панелі з розділу «mTLS вузла» на вузол, задайте його довірений CA та перезапустіть вузол. Для оновлення панелі цього вузла звідси все одно потрібен API-токен з областю node-admin.",
"mtls": {
"title": "mTLS вузла",
"intro": "Взаємний TLS додає фактор клієнтського сертифіката поверх API-токена для викликів між вузлами. Це необов’язково: залиште порожнім, щоб використовувати лише автентифікацію за токеном.",

View file

@ -151,6 +151,11 @@
"xrayStatus": "Xray",
"stopXray": "Dừng",
"restartXray": "Khởi động lại",
"startXray": "Khởi động",
"stopXrayDisabledHint": "Xray không chạy",
"stopXrayConfirmTitle": "Dừng Xray?",
"stopXrayConfirmContent": "Dừng Xray sẽ ngắt ngay lập tức mọi kết nối proxy. Bạn có chắc muốn tiếp tục?",
"stopXrayConfirmOk": "Dừng Xray",
"xraySwitch": "Phiên bản",
"xrayUpdates": "Cập nhật Xray",
"xraySwitchClickDesk": "Hãy lựa chọn thận trọng, vì các phiên bản cũ có thể không tương thích với các cấu hình hiện tại.",
@ -1194,7 +1199,7 @@
"tlsPin": "Ghim chứng chỉ (SHA-256)",
"tlsSkip": "Bỏ qua xác minh",
"tlsMtls": "TLS song phương (chứng chỉ máy khách)",
"mtlsFormHint": "Nút này xác thực bảng điều khiển bằng chứng chỉ máy khách. Sao chép CA của bảng điều khiển này từ mục mTLS nút sang nút, đặt CA tin cậy của nó, rồi khởi động lại.",
"mtlsFormHint": "Nút này xác thực bảng điều khiển bằng chứng chỉ máy khách. Sao chép CA của bảng điều khiển này từ mục mTLS nút sang nút, đặt CA tin cậy của nó, rồi khởi động lại. Cập nhật bảng điều khiển của nút này từ đây vẫn cần token API có phạm vi node-admin.",
"mtls": {
"title": "mTLS nút",
"intro": "TLS song phương bổ sung yếu tố chứng chỉ máy khách bên cạnh token API cho các lệnh gọi giữa các nút. Đây là tùy chọn: để trống để chỉ dùng xác thực bằng token.",

View file

@ -151,6 +151,11 @@
"xrayStatus": "Xray",
"stopXray": "停止",
"restartXray": "重启",
"startXray": "启动",
"stopXrayDisabledHint": "Xray 未运行",
"stopXrayConfirmTitle": "停止 Xray?",
"stopXrayConfirmContent": "停止 Xray 将立即中断所有代理连接。确定要继续吗?",
"stopXrayConfirmOk": "停止 Xray",
"xraySwitch": "版本",
"xrayUpdates": "Xray 更新",
"xraySwitchClickDesk": "请谨慎选择,因为较旧版本可能与当前配置不兼容",
@ -1194,7 +1199,7 @@
"tlsPin": "固定证书(SHA-256)",
"tlsSkip": "跳过校验",
"tlsMtls": "双向 TLS(客户端证书)",
"mtlsFormHint": "此节点使用客户端证书对面板进行认证。请从“节点 mTLS”区域复制本面板的 CA 到该节点,设置其受信任的 CA,然后重启该节点。",
"mtlsFormHint": "此节点使用客户端证书对面板进行认证。请从“节点 mTLS”区域复制本面板的 CA 到该节点,设置其受信任的 CA,然后重启该节点。 从这里更新此节点的面板仍需要具有 node-admin 权限范围的 API 令牌。",
"mtls": {
"title": "节点 mTLS",
"intro": "双向 TLS 在节点间调用的 API 令牌之上增加客户端证书认证。此为可选项:留空则仅使用令牌认证。",

View file

@ -151,6 +151,11 @@
"xrayStatus": "Xray",
"stopXray": "停止",
"restartXray": "重新啟動",
"startXray": "啟動",
"stopXrayDisabledHint": "Xray 未執行",
"stopXrayConfirmTitle": "停止 Xray?",
"stopXrayConfirmContent": "停止 Xray 將立即中斷所有代理連線。確定要繼續嗎?",
"stopXrayConfirmOk": "停止 Xray",
"xraySwitch": "版本",
"xrayUpdates": "Xray 更新",
"xraySwitchClickDesk": "請謹慎選擇,因為較舊版本可能與當前配置不相容",
@ -1194,7 +1199,7 @@
"tlsPin": "釘選憑證(SHA-256)",
"tlsSkip": "略過驗證",
"tlsMtls": "雙向 TLS(用戶端憑證)",
"mtlsFormHint": "此節點使用用戶端憑證對面板進行驗證。請從「節點 mTLS」區域複製本面板的 CA 到該節點,設定其受信任的 CA,然後重新啟動該節點。",
"mtlsFormHint": "此節點使用用戶端憑證對面板進行驗證。請從「節點 mTLS」區域複製本面板的 CA 到該節點,設定其受信任的 CA,然後重新啟動該節點。 從這裡更新此節點的面板仍需要具有 node-admin 權限範圍的 API 權杖。",
"mtls": {
"title": "節點 mTLS",
"intro": "雙向 TLS 在節點間呼叫的 API 權杖之上增加用戶端憑證驗證。此為選用項目:留空則僅使用權杖驗證。",