Move to TypeScript 7 and the oxc toolchain (oxlint + oxfmt) (#6262)

* chore(frontend,docs): move to TypeScript 7 and replace ESLint with oxlint

TypeScript 7 is the native Go port and ships no programmatic compiler
API, so typescript-eslint cannot run at all: it peer-pins
typescript >=4.8.4 <6.1.0 (canary too) and hard-crashes with
"typescript-eslint does not support TS 7.0". Upstream support is
tracked in typescript-eslint#10940 and targets TS >=7.1.

Rather than wait, or carry Microsoft's side-by-side alias (which keeps
a second TS 6 install alive purely to feed the linter), both projects
move to oxlint, which never depended on the TypeScript API.

Typecheck drops from ~9.7s to ~2.2s and 167 packages leave frontend/.

oxlint has no no-restricted-syntax, so the #6121/#6127 cleared-
InputNumber guard is reimplemented as a JS plugin in
frontend/tools/oxlint/. It was verified to still fire in
pages/settings/** and pages/xray/** and to stay exempt in *Modal.tsx.

The type-aware @deprecated sweep survives too, as
`npm run lint:deprecated`: oxlint's type-aware mode runs on
oxlint-tsgolint, which drives the TS 7 typescript-go checker, so the
TS 7 move is what makes it possible.

Behaviour is preserved rather than tightened. jsx-a11y/prefer-tag-over-role
is off in both configs because it was never part of the recommended sets
ESLint actually ran, and oxlint honours the existing eslint-disable
comments, so no source churn was needed.

Two real fixes fell out of the stricter linting:
- outbound-link-parser.test.ts used `out?.streamSettings` behind an `as`
  cast, which hid the optional chain from ESLint and would throw on a
  null parse; the rest of the file already used `out!`.
- InputAddon's conditional role/tabIndex/onKeyDown is genuinely
  accessible but oxlint cannot evaluate it, so it gets a scoped disable.

* chore(docs): replace Prettier with oxfmt

oxfmt is the oxc project's Prettier-compatible formatter, so this pairs
with the oxlint move and drops the last JS-based tool from the docs
toolchain.

The swap is behaviour-preserving. Running Prettier and oxfmt over the
same files, with the existing .prettierrc.json settings migrated via
`oxfmt --migrate=prettier`, produces byte-identical output on every
file. (Comparing them outside the project directory is misleading:
Prettier silently falls back to its defaults when it cannot find its
config, which looks like a mismatch but is not one.)

The 18 files reformatted here were already failing `pnpm format:check`
before this change — Prettier wanted the exact same edits. The check is
not part of docs-ci.yml, which is why the drift went unnoticed.

.prettierignore becomes ignorePatterns in .oxfmtrc.json, keeping the
deliberate MDX exclusion: reflowing MDX prose merges headings into
paragraphs and collapses lists inside Steps/Callout components. Both
that and the generated fumadocs-openapi reference output were verified
untouched.

oxfmt is pinned to 0.63.0 rather than latest. pnpm 11's built-in
minimumReleaseAge policy rejects same-day releases, and 0.64.0 would
have made pnpm silently append 20 waiver lines to pnpm-workspace.yaml.

* style(frontend): adopt oxfmt and format src

frontend/ has never had a formatter, so this reformats 344 of 497 files
in src/. The change is purely whitespace, quoting and line wrapping —
no logic is touched. It is kept in its own commit so it does not bury
the TypeScript 7 / oxlint migration or the git blame for the code
itself.

Settings match docs/ and the code as it was already written: single
quotes, semicolons, trailing commas, 2-space indent, 100 columns. That
was measured rather than assumed — src/ was already uniformly
single-quoted and 2-space indented, with p90 line length at 75.

Formatting is scoped to src/ (mirroring `oxlint src`) and
.oxfmtrc.json ignores src/generated. Both matter: `make gen-check`
compares src/generated and public/openapi.json, and
`make msw-worker-check` byte-compares public/mockServiceWorker.js
against the installed MSW runtime, so reformatting any of them breaks
the gate.

Reflowing also moves `eslint-disable-next-line` comments off the line
they guard, which broke two suppressions that had been silently
correct before:
- clone-inbound-modal.test.tsx: the object literal became multi-line,
  leaving `} as any;` four lines below its no-explicit-any disable.
- ClientsPage.tsx: the useMemo dependency array moved onto its own
  line, out from under its exhaustive-deps disable.
Both comments were relocated onto the line they actually guard, and
verified to still suppress by removing them and watching the errors
return.

* ci: enforce formatting in CI and make verify

Adding oxfmt in the previous two commits gave both projects a formatter
but nothing that checks it, which is how docs/ had already drifted to 18
unformatted files: docs-ci.yml runs typecheck, lint, test and build, but
never format:check, so Prettier's complaints were only ever visible to
whoever ran it by hand.

Wire `format:check` into the frontend job in ci.yml and the docs job in
docs-ci.yml, and add a `format-check` target to `make verify` so the
local gate keeps mirroring CI as the Makefile header promises.

Verified the step actually bites rather than passing vacuously: adding
a badly formatted line to a source file in each project makes both
`make format-check` and `pnpm format:check` fail, and reverting it makes
them pass again.

No workflow referenced ESLint or Prettier by name — they all invoke the
package scripts — so the tooling swap needed no other CI changes.

* ci: trigger CI on Makefile changes

The path filters listed **.go, go.mod, go.sum, frontend/**, .nvmrc and
ci.yml itself, but not the Makefile — so a change to the canonical task
runner that ci.yml is meant to mirror could land without any job
running. The previous commit, which edits both, only triggers because
it happens to touch ci.yml too.

* fix(frontend): replace deprecated Ant Design 6 APIs in the geo components

`npm run lint:deprecated` reported five uses of props Ant Design 6 has
deprecated. All five are gone, and the matching runtime warnings no
longer appear in the test output.

Tag `bordered={false}` becomes `variant="filled"` and Space `direction`
becomes `orientation`; both are the one-to-one replacements named in
antd's own deprecation messages, and `direction`/`orientation` share the
same Orientation type.

Input `addonAfter` is the one that is not a rename. It becomes a
`Space.Compact block` wrapping the Input and the browse Button, which is
antd's documented migration. `block` keeps the field filling its form
row as the addon did. Note this is a deliberate visual change: the
button used to be a borderless `type="text"` icon sitting inside the
addon's grey box, and is now a regular button whose border joins the
input. The tooltip, aria-label, ref, id and onBlur wiring are unchanged,
so the react-hook-form binding in RuleFormModal and the existing tests
still address it the same way.

Only these five were deprecated. The other `bordered` props in the tree
sit on QRCode, Table, Descriptions and Alert, where the prop is not
deprecated, and these were the only two Space `direction` uses in the
codebase.

* fix(frontend): restore lint rules lost in the oxlint migration, and test the guard

Addresses the review on #6262.

The frontend config re-enabled only no-explicit-any and no-unused-vars
and left the rest of tseslint's recommended set to oxlint's correctness
category. It does not cover all of it. Confirmed by linting one probe
file against both configs: docs/ (which enumerates the rules) reports
all nine, frontend/ reported four. So ban-ts-comment,
no-empty-object-type, no-namespace, no-require-imports and
no-unsafe-function-type had silently stopped being enforced — a `//
@ts-ignore` or a `namespace` block would have landed unflagged. The ten
rules are now mirrored from docs/.oxlintrc.json, and src/ still passes.

The #6121/#6127 guard was 57 lines of hand-written AST walking with no
test. It now has one: fixtures for the three banned shapes plus an
onNumber()-wrapped control, asserting the rule fires three times and
that .oxlintrc.json still wires it to the right paths. Verified it fails
for the right reason by making walk() enumerate nothing, which is the
silent-death mode the review described — the traversal depends on
Object.keys() seeing AST children as own enumerable properties.

The fixtures deliberately violate the rule, so their oxlint config is
named guard.oxlintrc.json rather than .oxlintrc.json: oxlint discovers
nested configs by directory, which would otherwise turn the fixtures
into three lint errors. The test passes it explicitly with -c.

Also from the review:
- lint and format now cover tools/ as well as src/, so the one piece of
  hand-written lint logic in the repo is no longer the least covered
  file in it.
- lint-staged runs oxfmt before oxlint --fix. Formatting became a hard
  CI gate in this PR while the hook only ran the linter, so a commit
  could pass the hook and fail CI on formatting alone.
- .oxfmtrc.json ignores public/, so the artefacts that make gen-check
  and make msw-worker-check byte-compare stay safe even if oxfmt is
  invoked without a path argument.
- The MDX and generated-reference rationales that .prettierignore
  carried are back as comments in docs/.oxfmtrc.json — oxlint and oxfmt
  both accept JSONC, so relocating them was unnecessary.

Not applied: the review also suggested restoring ../internal/web/dist to
the ignore lists. Both tools reject `..` patterns outright ("patterns
are resolved within the config file's directory"), and being outside
frontend/ it is unreachable anyway.
This commit is contained in:
Sanaei
2026-08-19 15:36:27 +02:00
committed by GitHub
parent 380aff4d82
commit 92fb94d856
388 changed files with 19613 additions and 14133 deletions
@@ -34,21 +34,29 @@ export default function CloneInboundModal({
const [targets, setTargets] = useState<number[]>([LOCAL_PANEL]);
const [submitting, setSubmitting] = useState(false);
const targetOptions = useMemo(() => [
{ value: LOCAL_PANEL, label: t('pages.inbounds.localPanel'), disabled: false },
...(nodes || []).filter((n) => n.enable).map((n) => ({
value: n.id,
// Only online nodes are deployable targets: nodes report `unknown`
// until their first heartbeat, and the backend refuses any status
// other than online.
label: `${n.name}${n.status === 'online' ? '' : ` (${n.status || 'offline'})`}`,
disabled: n.status !== 'online',
})),
], [nodes, t]);
const targetOptions = useMemo(
() => [
{ value: LOCAL_PANEL, label: t('pages.inbounds.localPanel'), disabled: false },
...(nodes || [])
.filter((n) => n.enable)
.map((n) => ({
value: n.id,
// Only online nodes are deployable targets: nodes report `unknown`
// until their first heartbeat, and the backend refuses any status
// other than online.
label: `${n.name}${n.status === 'online' ? '' : ` (${n.status || 'offline'})`}`,
disabled: n.status !== 'online',
})),
],
[nodes, t],
);
// "Select all" must not pick targets the user can't pick manually —
// offline nodes are disabled options in the dropdown.
const selectableOptions = useMemo(() => targetOptions.filter((o) => !o.disabled), [targetOptions]);
const selectableOptions = useMemo(
() => targetOptions.filter((o) => !o.disabled),
[targetOptions],
);
// Reset the selection when the dialog OPENS: pre-select the source
// inbound's own node when it is a selectable target, otherwise the local
@@ -75,17 +83,23 @@ export default function CloneInboundModal({
for (const target of targets) {
const msg = await HttpUtil.post(
'/panel/api/inbounds/add',
buildClonePayload(dbInbound, pickClonePort(portsInUse.get(target)), target === LOCAL_PANEL ? null : target),
buildClonePayload(
dbInbound,
pickClonePort(portsInUse.get(target)),
target === LOCAL_PANEL ? null : target,
),
{ silent: true },
);
results.push({ ok: !!msg?.success, reason: msg?.success ? '' : (msg?.msg || '') });
results.push({ ok: !!msg?.success, reason: msg?.success ? '' : msg?.msg || '' });
}
const okCount = results.filter((r) => r.ok).length;
const failed = results.length - okCount;
if (failed === 0) {
messageApi.success(okCount === 1
? t('pages.inbounds.toasts.inboundCreateSuccess')
: t('pages.inbounds.toasts.clonedMany', { count: okCount }));
messageApi.success(
okCount === 1
? t('pages.inbounds.toasts.inboundCreateSuccess')
: t('pages.inbounds.toasts.clonedMany', { count: okCount }),
);
} else {
const firstError = results.find((r) => !r.ok)?.reason ?? '';
const base = t('pages.inbounds.toasts.clonedMixed', { ok: okCount, failed });
@@ -114,11 +128,7 @@ export default function CloneInboundModal({
<Typography.Paragraph type="secondary">
{t('pages.inbounds.cloneConfirmContent')}
</Typography.Paragraph>
<SelectAllClearButtons
options={selectableOptions}
value={targets}
onChange={setTargets}
/>
<SelectAllClearButtons options={selectableOptions} value={targets} onChange={setTargets} />
<Select
aria-label={t('pages.inbounds.deployTo')}
mode="multiple"
+427 -293
View File
@@ -101,7 +101,9 @@ export default function InboundsPage() {
const [modal, modalContextHolder] = Modal.useModal();
const [messageApi, messageContextHolder] = message.useMessage();
useEffect(() => { setMessageInstance(messageApi); }, [messageApi]);
useEffect(() => {
setMessageInstance(messageApi);
}, [messageApi]);
const { nodes: nodesList, fetched: nodesFetched } = useNodesQuery();
const nodesById = useMemo(() => {
@@ -177,94 +179,129 @@ export default function InboundsPage() {
const [promptInitial, setPromptInitial] = useState('');
const [promptJson, setPromptJson] = useState(false);
const [promptLoading, setPromptLoading] = useState(false);
const [promptHandler, setPromptHandler] = useState<((value: string) => Promise<boolean | void> | boolean | void) | null>(null);
const [promptHandler, setPromptHandler] = useState<
((value: string) => Promise<boolean | void> | boolean | void) | null
>(null);
const hostOverrideFor = useCallback((dbInbound: DBInbound | null) => {
if (!dbInbound || dbInbound.nodeId == null) return '';
return nodesById.get(dbInbound.nodeId)?.address || '';
}, [nodesById]);
const hostOverrideFor = useCallback(
(dbInbound: DBInbound | null) => {
if (!dbInbound || dbInbound.nodeId == null) return '';
return nodesById.get(dbInbound.nodeId)?.address || '';
},
[nodesById],
);
const infoNodeAddress = useMemo(() => hostOverrideFor(infoDbInbound), [infoDbInbound, hostOverrideFor]);
const infoNodeAddress = useMemo(
() => hostOverrideFor(infoDbInbound),
[infoDbInbound, hostOverrideFor],
);
const qrNodeAddress = useMemo(() => hostOverrideFor(qrDbInbound), [qrDbInbound, hostOverrideFor]);
const openText = useCallback((opts: { title: string; content: string; fileName?: string; json?: boolean; tabs?: TextModalTab[] }) => {
setTextTitle(opts.title);
setTextContent(opts.content);
setTextFileName(opts.fileName || '');
setTextJson(opts.json || false);
setTextTabs(opts.tabs);
setTextOpen(true);
}, []);
const openText = useCallback(
(opts: {
title: string;
content: string;
fileName?: string;
json?: boolean;
tabs?: TextModalTab[];
}) => {
setTextTitle(opts.title);
setTextContent(opts.content);
setTextFileName(opts.fileName || '');
setTextJson(opts.json || false);
setTextTabs(opts.tabs);
setTextOpen(true);
},
[],
);
const openPrompt = useCallback((opts: {
title: string;
okText?: string;
type?: 'textarea' | 'input';
value?: string;
json?: boolean;
confirm: (value: string) => Promise<boolean | void> | boolean | void;
}) => {
setPromptTitle(opts.title);
setPromptOkText(opts.okText || t('confirm'));
setPromptType(opts.type || 'textarea');
setPromptInitial(opts.value || '');
setPromptJson(opts.json || false);
setPromptHandler(() => opts.confirm);
setPromptOpen(true);
}, [t]);
const openPrompt = useCallback(
(opts: {
title: string;
okText?: string;
type?: 'textarea' | 'input';
value?: string;
json?: boolean;
confirm: (value: string) => Promise<boolean | void> | boolean | void;
}) => {
setPromptTitle(opts.title);
setPromptOkText(opts.okText || t('confirm'));
setPromptType(opts.type || 'textarea');
setPromptInitial(opts.value || '');
setPromptJson(opts.json || false);
setPromptHandler(() => opts.confirm);
setPromptOpen(true);
},
[t],
);
const onPromptConfirm = useCallback(async (value: string) => {
if (!promptHandler) {
setPromptOpen(false);
return;
}
setPromptLoading(true);
try {
const ok = await promptHandler(value);
if (ok !== false) setPromptOpen(false);
} finally {
setPromptLoading(false);
}
}, [promptHandler]);
const onPromptConfirm = useCallback(
async (value: string) => {
if (!promptHandler) {
setPromptOpen(false);
return;
}
setPromptLoading(true);
try {
const ok = await promptHandler(value);
if (ok !== false) setPromptOpen(false);
} finally {
setPromptLoading(false);
}
},
[promptHandler],
);
const projectChildThroughMaster = useCallback((child: DBInbound, master: DBInbound): DBInbound => {
const projected = JSON.parse(JSON.stringify(child)) as DBInbound;
projected.listen = master.listen;
projected.port = master.port;
const masterStream = coerceInboundJsonField(master.streamSettings) as Record<string, unknown>;
const childStream = { ...(coerceInboundJsonField(child.streamSettings) as Record<string, unknown>) };
childStream.security = masterStream.security;
childStream.tlsSettings = masterStream.tlsSettings;
childStream.realitySettings = masterStream.realitySettings;
childStream.externalProxy = masterStream.externalProxy;
projected.streamSettings = JSON.stringify(childStream);
const Ctor = child.constructor as new (data: DBInbound) => DBInbound;
return new Ctor(projected);
}, []);
const projectChildThroughMaster = useCallback(
(child: DBInbound, master: DBInbound): DBInbound => {
const projected = JSON.parse(JSON.stringify(child)) as DBInbound;
projected.listen = master.listen;
projected.port = master.port;
const masterStream = coerceInboundJsonField(master.streamSettings) as Record<string, unknown>;
const childStream = {
...(coerceInboundJsonField(child.streamSettings) as Record<string, unknown>),
};
childStream.security = masterStream.security;
childStream.tlsSettings = masterStream.tlsSettings;
childStream.realitySettings = masterStream.realitySettings;
childStream.externalProxy = masterStream.externalProxy;
projected.streamSettings = JSON.stringify(childStream);
const Ctor = child.constructor as new (data: DBInbound) => DBInbound;
return new Ctor(projected);
},
[],
);
const checkFallback = useCallback((dbInbound: DBInbound): DBInbound => {
const parent = dbInbound?.fallbackParent;
if (parent?.masterId) {
const master = dbInbounds.find((ib) => ib.id === parent.masterId);
if (master) return projectChildThroughMaster(dbInbound, master);
}
if (!dbInbound?.listen?.startsWith?.('@')) return dbInbound;
for (const candidate of dbInbounds) {
if (candidate.id === dbInbound.id) continue;
if (!['trojan', 'vless'].includes(candidate.protocol)) continue;
const candStream = coerceInboundJsonField(candidate.streamSettings) as { network?: string };
if (candStream.network !== 'tcp') continue;
const candSettings = coerceInboundJsonField(candidate.settings) as { fallbacks?: { dest?: string }[] };
const fallbacks = candSettings.fallbacks || [];
if (!fallbacks.find((f) => f.dest === dbInbound.listen)) continue;
return projectChildThroughMaster(dbInbound, candidate);
}
return dbInbound;
}, [dbInbounds, projectChildThroughMaster]);
const checkFallback = useCallback(
(dbInbound: DBInbound): DBInbound => {
const parent = dbInbound?.fallbackParent;
if (parent?.masterId) {
const master = dbInbounds.find((ib) => ib.id === parent.masterId);
if (master) return projectChildThroughMaster(dbInbound, master);
}
if (!dbInbound?.listen?.startsWith?.('@')) return dbInbound;
for (const candidate of dbInbounds) {
if (candidate.id === dbInbound.id) continue;
if (!['trojan', 'vless'].includes(candidate.protocol)) continue;
const candStream = coerceInboundJsonField(candidate.streamSettings) as { network?: string };
if (candStream.network !== 'tcp') continue;
const candSettings = coerceInboundJsonField(candidate.settings) as {
fallbacks?: { dest?: string }[];
};
const fallbacks = candSettings.fallbacks || [];
if (!fallbacks.find((f) => f.dest === dbInbound.listen)) continue;
return projectChildThroughMaster(dbInbound, candidate);
}
return dbInbound;
},
[dbInbounds, projectChildThroughMaster],
);
const findClientIndex = useCallback((dbInbound: DBInbound, client: ClientMatchTarget | null) => {
if (!client) return 0;
const settings = coerceInboundJsonField(dbInbound.settings) as { clients?: ClientMatchTarget[] };
const settings = coerceInboundJsonField(dbInbound.settings) as {
clients?: ClientMatchTarget[];
};
const clients = settings.clients || [];
const idx = clients.findIndex((c) => {
if (!c) return false;
@@ -279,53 +316,76 @@ export default function InboundsPage() {
return idx >= 0 ? idx : 0;
}, []);
const exportInboundLinks = useCallback((dbInbound: DBInbound) => {
const projected = checkFallback(dbInbound);
const genInput = {
inbound: inboundFromDb(projected),
remark: projected.remark,
hostOverride: hostOverrideFor(dbInbound),
fallbackHostname: preferPublicHost(window.location.hostname, subSettings.publicHost),
};
const content = genInboundLinks(genInput);
const tabs: TextModalTab[] | undefined = projected.isWireguard
? [
{ key: 'config', label: t('pages.clients.config'), content },
{ key: 'links', label: t('pages.clients.tabLinks'), content: genWireguardLinks(genInput) },
]
: undefined;
openText({
title: t('pages.inbounds.exportLinksTitle'),
content,
fileName: projected.remark || 'inbound',
tabs,
});
}, [checkFallback, hostOverrideFor, subSettings.publicHost, openText, t]);
const exportInboundLinks = useCallback(
(dbInbound: DBInbound) => {
const projected = checkFallback(dbInbound);
const genInput = {
inbound: inboundFromDb(projected),
remark: projected.remark,
hostOverride: hostOverrideFor(dbInbound),
fallbackHostname: preferPublicHost(window.location.hostname, subSettings.publicHost),
};
const content = genInboundLinks(genInput);
const tabs: TextModalTab[] | undefined = projected.isWireguard
? [
{ key: 'config', label: t('pages.clients.config'), content },
{
key: 'links',
label: t('pages.clients.tabLinks'),
content: genWireguardLinks(genInput),
},
]
: undefined;
openText({
title: t('pages.inbounds.exportLinksTitle'),
content,
fileName: projected.remark || 'inbound',
tabs,
});
},
[checkFallback, hostOverrideFor, subSettings.publicHost, openText, t],
);
const exportInboundClipboard = useCallback((dbInbound: DBInbound) => {
openText({ title: t('pages.inbounds.inboundJsonTitle'), content: JSON.stringify(dbInbound, null, 2), json: true });
}, [openText, t]);
const exportInboundClipboard = useCallback(
(dbInbound: DBInbound) => {
openText({
title: t('pages.inbounds.inboundJsonTitle'),
content: JSON.stringify(dbInbound, null, 2),
json: true,
});
},
[openText, t],
);
const exportInboundSubs = useCallback((dbInbound: DBInbound) => {
const settings = coerceInboundJsonField(dbInbound.settings) as { clients?: { subId?: string }[] };
const clients = settings.clients || [];
const subLinks: string[] = [];
for (const c of clients) {
if (c.subId && subSettings.subURI) {
subLinks.push(subSettings.subURI + c.subId);
const exportInboundSubs = useCallback(
(dbInbound: DBInbound) => {
const settings = coerceInboundJsonField(dbInbound.settings) as {
clients?: { subId?: string }[];
};
const clients = settings.clients || [];
const subLinks: string[] = [];
for (const c of clients) {
if (c.subId && subSettings.subURI) {
subLinks.push(subSettings.subURI + c.subId);
}
}
}
openText({
title: t('pages.inbounds.exportSubsTitle'),
content: [...new Set(subLinks)].join('\n'),
fileName: `${dbInbound.remark || 'inbound'}-Subs`,
});
}, [subSettings, openText, t]);
openText({
title: t('pages.inbounds.exportSubsTitle'),
content: [...new Set(subLinks)].join('\n'),
fileName: `${dbInbound.remark || 'inbound'}-Subs`,
});
},
[subSettings, openText, t],
);
const exportAllLinks = useCallback(async () => {
const msg = await HttpUtil.get('/panel/api/inbounds/allLinks');
const links = msg?.success && Array.isArray(msg.obj) ? (msg.obj as string[]) : [];
openText({ title: t('pages.inbounds.exportAllLinksTitle'), content: links.join('\r\n'), fileName: t('pages.inbounds.exportAllLinksFileName') });
openText({
title: t('pages.inbounds.exportAllLinksTitle'),
content: links.join('\r\n'),
fileName: t('pages.inbounds.exportAllLinksFileName'),
});
}, [openText, t]);
const exportAllSubs = useCallback(async () => {
@@ -342,7 +402,11 @@ export default function InboundsPage() {
}
}
}
openText({ title: t('pages.inbounds.exportAllSubsTitle'), content: [...new Set(out)].join('\r\n'), fileName: t('pages.inbounds.exportAllSubsFileName') });
openText({
title: t('pages.inbounds.exportAllSubsTitle'),
content: [...new Set(out)].join('\r\n'),
fileName: t('pages.inbounds.exportAllSubsFileName'),
});
}, [dbInbounds, hydrateInbound, subSettings, openText, t]);
const importInbound = useCallback(() => {
@@ -375,186 +439,250 @@ export default function InboundsPage() {
setFormOpen(true);
}, []);
const confirmDelete = useCallback((dbInbound: DBInbound) => {
modal.confirm({
title: t('pages.inbounds.deleteConfirmTitle', { remark: dbInbound.remark }),
content: t('pages.inbounds.deleteConfirmContent'),
okText: t('delete'),
okType: 'danger',
cancelText: t('cancel'),
onOk: async () => {
const msg = await HttpUtil.post(`/panel/api/inbounds/del/${dbInbound.id}`);
if (msg?.success) await refresh();
},
});
}, [modal, refresh, t]);
const confirmDelete = useCallback(
(dbInbound: DBInbound) => {
modal.confirm({
title: t('pages.inbounds.deleteConfirmTitle', { remark: dbInbound.remark }),
content: t('pages.inbounds.deleteConfirmContent'),
okText: t('delete'),
okType: 'danger',
cancelText: t('cancel'),
onOk: async () => {
const msg = await HttpUtil.post(`/panel/api/inbounds/del/${dbInbound.id}`);
if (msg?.success) await refresh();
},
});
},
[modal, refresh, t],
);
const confirmBulkDelete = useCallback((ids: number[]) => new Promise<boolean>((resolve) => {
if (ids.length === 0) {
resolve(false);
return;
}
modal.confirm({
title: t('pages.inbounds.bulkDeleteConfirmTitle', { count: ids.length }),
content: t('pages.inbounds.bulkDeleteConfirmContent'),
okText: t('delete'),
okType: 'danger',
cancelText: t('cancel'),
onOk: async () => {
const msg = await HttpUtil.post('/panel/api/inbounds/bulkDel', { ids }, { headers: { 'Content-Type': 'application/json' } });
const obj = (msg?.obj ?? {}) as { deleted?: number; skipped?: { id: number; reason: string }[] };
const ok = obj.deleted ?? 0;
const skipped = obj.skipped ?? [];
if (msg?.success && skipped.length === 0) {
messageApi.success(t('pages.inbounds.toasts.bulkDeleted', { count: ok }));
} else {
const firstError = skipped[0]?.reason ?? msg?.msg ?? '';
const base = t('pages.inbounds.toasts.bulkDeletedMixed', { ok, failed: skipped.length });
messageApi.warning(firstError ? `${base}${firstError}` : base);
const confirmBulkDelete = useCallback(
(ids: number[]) =>
new Promise<boolean>((resolve) => {
if (ids.length === 0) {
resolve(false);
return;
}
await refresh();
resolve(true);
},
onCancel: () => resolve(false),
});
}), [modal, refresh, t, messageApi]);
const confirmResetTraffic = useCallback((dbInbound: DBInbound) => {
modal.confirm({
title: t('pages.inbounds.resetConfirmTitle', { remark: dbInbound.remark }),
content: t('pages.inbounds.resetConfirmContent'),
okText: t('reset'),
cancelText: t('cancel'),
onOk: async () => {
const msg = await HttpUtil.post(`/panel/api/inbounds/${dbInbound.id}/resetTraffic`);
if (msg?.success) await refresh();
},
});
}, [modal, refresh, t]);
const confirmDelAllClients = useCallback((dbInbound: DBInbound) => {
const count = clientCount[dbInbound.id]?.clients || 0;
modal.confirm({
title: t('pages.inbounds.delAllClientsConfirmTitle', { remark: dbInbound.remark, count }),
content: t('pages.inbounds.delAllClientsConfirmContent'),
okText: t('delete'),
okType: 'danger',
cancelText: t('cancel'),
onOk: async () => {
const msg = await HttpUtil.post(`/panel/api/inbounds/${dbInbound.id}/delAllClients`);
if (msg?.success) await refresh();
},
});
}, [modal, refresh, t, clientCount]);
const confirmClone = useCallback((dbInbound: DBInbound) => {
// Node-eligible protocol with at least one deployable node → open the
// target picker; anything else keeps the original one-click local clone.
if (NODE_ELIGIBLE_PROTOCOLS[dbInbound.protocol] && (nodesList || []).some((n) => n.enable && n.status === 'online')) {
setCloneSource(dbInbound);
setCloneOpen(true);
return;
}
modal.confirm({
title: t('pages.inbounds.cloneConfirmTitle', { remark: dbInbound.remark }),
content: t('pages.inbounds.cloneConfirmContent'),
okText: t('pages.inbounds.clone'),
cancelText: t('cancel'),
onOk: async () => {
const msg = await HttpUtil.post(
'/panel/api/inbounds/add',
buildClonePayload(dbInbound, RandomUtil.randomInteger(10000, 60000), null),
);
if (msg?.success) await refresh();
},
});
}, [modal, nodesList, refresh, t]);
const onGeneralAction = useCallback((key: GeneralAction) => {
switch (key) {
case 'import': importInbound(); break;
case 'export': exportAllLinks(); break;
case 'subs': exportAllSubs(); break;
case 'resetInbounds':
modal.confirm({
title: t('pages.inbounds.resetAllTrafficTitle'),
okText: t('reset'),
title: t('pages.inbounds.bulkDeleteConfirmTitle', { count: ids.length }),
content: t('pages.inbounds.bulkDeleteConfirmContent'),
okText: t('delete'),
okType: 'danger',
cancelText: t('cancel'),
onOk: async () => {
const msg = await HttpUtil.post('/panel/api/inbounds/resetAllTraffics');
if (msg?.success) await refresh();
const msg = await HttpUtil.post(
'/panel/api/inbounds/bulkDel',
{ ids },
{ headers: { 'Content-Type': 'application/json' } },
);
const obj = (msg?.obj ?? {}) as {
deleted?: number;
skipped?: { id: number; reason: string }[];
};
const ok = obj.deleted ?? 0;
const skipped = obj.skipped ?? [];
if (msg?.success && skipped.length === 0) {
messageApi.success(t('pages.inbounds.toasts.bulkDeleted', { count: ok }));
} else {
const firstError = skipped[0]?.reason ?? msg?.msg ?? '';
const base = t('pages.inbounds.toasts.bulkDeletedMixed', {
ok,
failed: skipped.length,
});
messageApi.warning(firstError ? `${base}${firstError}` : base);
}
await refresh();
resolve(true);
},
onCancel: () => resolve(false),
});
break;
default:
messageApi.info(`General action "${key}" — coming in a later 5f subphase`);
}
}, [modal, importInbound, exportAllLinks, exportAllSubs, refresh, messageApi, t]);
}),
[modal, refresh, t, messageApi],
);
const onRowAction = useCallback(async ({ key, dbInbound }: { key: RowAction; dbInbound: DBInbound }) => {
// Actions that touch per-client secrets (uuid, password, flow, ...) need
// the full payload that the slim list view does not ship. Hydrate first
// and then operate on the rehydrated record.
const hydratingKeys: RowAction[] = ['edit', 'showInfo', 'qrcode', 'export', 'subs', 'clipboard', 'clone', 'attachClients', 'addToGroup'];
let target = dbInbound;
if (hydratingKeys.includes(key)) {
const hydrated = await hydrateInbound(dbInbound.id);
if (hydrated) target = hydrated;
}
switch (key) {
case 'edit':
openEdit(target);
break;
case 'showInfo':
setInfoDbInbound(checkFallback(target));
setInfoClientIndex(findClientIndex(target, null));
setInfoOpen(true);
break;
case 'qrcode':
setQrDbInbound(checkFallback(target));
setQrOpen(true);
break;
case 'export':
exportInboundLinks(target);
break;
case 'subs':
exportInboundSubs(target);
break;
case 'clipboard':
exportInboundClipboard(target);
break;
case 'delete':
confirmDelete(target);
break;
case 'resetTraffic':
confirmResetTraffic(target);
break;
case 'delAllClients':
confirmDelAllClients(target);
break;
case 'attachClients':
setAttachSource(target);
setAttachOpen(true);
break;
case 'attachExisting':
setAttachExistingTarget(target);
setAttachExistingOpen(true);
break;
case 'detachClients':
setDetachSource(target);
setDetachOpen(true);
break;
case 'addToGroup':
setGroupSource(target);
setGroupOpen(true);
break;
case 'clone':
confirmClone(target);
break;
default:
messageApi.info(`Action "${key}" — coming in a later 5f subphase`);
}
}, [hydrateInbound, openEdit, checkFallback, findClientIndex, exportInboundLinks, exportInboundSubs, exportInboundClipboard, confirmDelete, confirmResetTraffic, confirmDelAllClients, confirmClone, messageApi]);
const confirmResetTraffic = useCallback(
(dbInbound: DBInbound) => {
modal.confirm({
title: t('pages.inbounds.resetConfirmTitle', { remark: dbInbound.remark }),
content: t('pages.inbounds.resetConfirmContent'),
okText: t('reset'),
cancelText: t('cancel'),
onOk: async () => {
const msg = await HttpUtil.post(`/panel/api/inbounds/${dbInbound.id}/resetTraffic`);
if (msg?.success) await refresh();
},
});
},
[modal, refresh, t],
);
const confirmDelAllClients = useCallback(
(dbInbound: DBInbound) => {
const count = clientCount[dbInbound.id]?.clients || 0;
modal.confirm({
title: t('pages.inbounds.delAllClientsConfirmTitle', { remark: dbInbound.remark, count }),
content: t('pages.inbounds.delAllClientsConfirmContent'),
okText: t('delete'),
okType: 'danger',
cancelText: t('cancel'),
onOk: async () => {
const msg = await HttpUtil.post(`/panel/api/inbounds/${dbInbound.id}/delAllClients`);
if (msg?.success) await refresh();
},
});
},
[modal, refresh, t, clientCount],
);
const confirmClone = useCallback(
(dbInbound: DBInbound) => {
// Node-eligible protocol with at least one deployable node → open the
// target picker; anything else keeps the original one-click local clone.
if (
NODE_ELIGIBLE_PROTOCOLS[dbInbound.protocol] &&
(nodesList || []).some((n) => n.enable && n.status === 'online')
) {
setCloneSource(dbInbound);
setCloneOpen(true);
return;
}
modal.confirm({
title: t('pages.inbounds.cloneConfirmTitle', { remark: dbInbound.remark }),
content: t('pages.inbounds.cloneConfirmContent'),
okText: t('pages.inbounds.clone'),
cancelText: t('cancel'),
onOk: async () => {
const msg = await HttpUtil.post(
'/panel/api/inbounds/add',
buildClonePayload(dbInbound, RandomUtil.randomInteger(10000, 60000), null),
);
if (msg?.success) await refresh();
},
});
},
[modal, nodesList, refresh, t],
);
const onGeneralAction = useCallback(
(key: GeneralAction) => {
switch (key) {
case 'import':
importInbound();
break;
case 'export':
exportAllLinks();
break;
case 'subs':
exportAllSubs();
break;
case 'resetInbounds':
modal.confirm({
title: t('pages.inbounds.resetAllTrafficTitle'),
okText: t('reset'),
cancelText: t('cancel'),
onOk: async () => {
const msg = await HttpUtil.post('/panel/api/inbounds/resetAllTraffics');
if (msg?.success) await refresh();
},
});
break;
default:
messageApi.info(`General action "${key}" — coming in a later 5f subphase`);
}
},
[modal, importInbound, exportAllLinks, exportAllSubs, refresh, messageApi, t],
);
const onRowAction = useCallback(
async ({ key, dbInbound }: { key: RowAction; dbInbound: DBInbound }) => {
// Actions that touch per-client secrets (uuid, password, flow, ...) need
// the full payload that the slim list view does not ship. Hydrate first
// and then operate on the rehydrated record.
const hydratingKeys: RowAction[] = [
'edit',
'showInfo',
'qrcode',
'export',
'subs',
'clipboard',
'clone',
'attachClients',
'addToGroup',
];
let target = dbInbound;
if (hydratingKeys.includes(key)) {
const hydrated = await hydrateInbound(dbInbound.id);
if (hydrated) target = hydrated;
}
switch (key) {
case 'edit':
openEdit(target);
break;
case 'showInfo':
setInfoDbInbound(checkFallback(target));
setInfoClientIndex(findClientIndex(target, null));
setInfoOpen(true);
break;
case 'qrcode':
setQrDbInbound(checkFallback(target));
setQrOpen(true);
break;
case 'export':
exportInboundLinks(target);
break;
case 'subs':
exportInboundSubs(target);
break;
case 'clipboard':
exportInboundClipboard(target);
break;
case 'delete':
confirmDelete(target);
break;
case 'resetTraffic':
confirmResetTraffic(target);
break;
case 'delAllClients':
confirmDelAllClients(target);
break;
case 'attachClients':
setAttachSource(target);
setAttachOpen(true);
break;
case 'attachExisting':
setAttachExistingTarget(target);
setAttachExistingOpen(true);
break;
case 'detachClients':
setDetachSource(target);
setDetachOpen(true);
break;
case 'addToGroup':
setGroupSource(target);
setGroupOpen(true);
break;
case 'clone':
confirmClone(target);
break;
default:
messageApi.info(`Action "${key}" — coming in a later 5f subphase`);
}
},
[
hydrateInbound,
openEdit,
checkFallback,
findClientIndex,
exportInboundLinks,
exportInboundSubs,
exportInboundClipboard,
confirmDelete,
confirmResetTraffic,
confirmDelAllClients,
confirmClone,
messageApi,
],
);
return (
<ConfigProvider theme={antdThemeConfig}>
@@ -573,7 +701,11 @@ export default function InboundsPage() {
status="error"
title={t('somethingWentWrong')}
subTitle={fetchError}
extra={<Button type="primary" onClick={refresh}>{t('refresh')}</Button>}
extra={
<Button type="primary" onClick={refresh}>
{t('refresh')}
</Button>
}
/>
) : (
<Row gutter={[isMobile ? 8 : 16, 12]}>
@@ -627,7 +759,9 @@ export default function InboundsPage() {
hasActiveNode={showNodeInfo}
onAddInbound={onAddInbound}
onGeneralAction={onGeneralAction}
onRowAction={({ key, dbInbound }) => onRowAction({ key, dbInbound: dbInbound as unknown as DBInbound })}
onRowAction={({ key, dbInbound }) =>
onRowAction({ key, dbInbound: dbInbound as unknown as DBInbound })
}
onBulkDelete={confirmBulkDelete}
/>
</Col>
@@ -37,7 +37,9 @@ export default function AddClientsToGroupModal({
const list = Array.isArray(msg?.obj) ? (msg.obj as Array<{ name?: string }>) : [];
setGroups(list.map((g) => g?.name || '').filter(Boolean));
})();
return () => { cancelled = true; };
return () => {
cancelled = true;
};
}, [open]);
return (
@@ -45,7 +47,9 @@ export default function AddClientsToGroupModal({
open={open}
count={emails.length}
groups={groups}
onOpenChange={(o) => { if (!o) onClose(); }}
onOpenChange={(o) => {
if (!o) onClose();
}}
onSubmit={async (group) => {
const msg = await HttpUtil.post(
'/panel/api/clients/groups/bulkAdd',
@@ -129,7 +129,9 @@ export default function AttachClientsModal({
const skipped = result.skipped?.length ?? 0;
const errors = result.errors?.length ?? 0;
if (errors > 0) {
messageApi.warning(t('pages.inbounds.attachClientsResultMixed', { attached, skipped, errors }));
messageApi.warning(
t('pages.inbounds.attachClientsResultMixed', { attached, skipped, errors }),
);
} else {
messageApi.success(t('pages.inbounds.attachClientsResult', { attached, skipped }));
}
@@ -151,7 +153,9 @@ export default function AttachClientsModal({
}}
okText={t('pages.inbounds.attachClients')}
cancelText={t('cancel')}
title={t('pages.inbounds.attachClientsTitle', { remark: formatInboundLabel(source?.tag, source?.remark) })}
title={t('pages.inbounds.attachClientsTitle', {
remark: formatInboundLabel(source?.tag, source?.remark),
})}
width={680}
>
{messageContextHolder}
@@ -113,14 +113,19 @@ export default function AttachExistingClientsModal({
width: 150,
ellipsis: true,
render: (group: string) =>
group ? <Tag color="geekblue">{group}</Tag> : <span style={{ color: 'rgba(0,0,0,0.45)' }}></span>,
group ? (
<Tag color="geekblue">{group}</Tag>
) : (
<span style={{ color: 'rgba(0,0,0,0.45)' }}></span>
),
},
{
title: t('enable'),
key: 'status',
width: 140,
render: (_v, row) => {
if (row.alreadyAttached) return <Tag color="default">{t('pages.inbounds.attachExistingStatusAttached')}</Tag>;
if (row.alreadyAttached)
return <Tag color="default">{t('pages.inbounds.attachExistingStatusAttached')}</Tag>;
return row.enable ? (
<Tag color="success">{t('enable')}</Tag>
) : (
@@ -150,7 +155,9 @@ export default function AttachExistingClientsModal({
const skipped = result.skipped?.length ?? 0;
const errors = result.errors?.length ?? 0;
if (errors > 0) {
messageApi.warning(t('pages.inbounds.attachClientsResultMixed', { attached, skipped, errors }));
messageApi.warning(
t('pages.inbounds.attachClientsResultMixed', { attached, skipped, errors }),
);
} else {
messageApi.success(t('pages.inbounds.attachClientsResult', { attached, skipped }));
}
@@ -171,7 +178,9 @@ export default function AttachExistingClientsModal({
okButtonProps={{ disabled: selectedEmails.length === 0, loading: saving }}
okText={t('pages.inbounds.attachClients')}
cancelText={t('cancel')}
title={t('pages.inbounds.attachExistingTitle', { remark: formatInboundLabel(target?.tag, target?.remark) })}
title={t('pages.inbounds.attachExistingTitle', {
remark: formatInboundLabel(target?.tag, target?.remark),
})}
width={680}
>
{messageContextHolder}
@@ -116,7 +116,9 @@ export default function DetachClientsModal({
const skipped = result.skipped?.length ?? 0;
const errors = result.errors?.length ?? 0;
if (errors > 0) {
messageApi.warning(t('pages.inbounds.detachClientsResultMixed', { detached, skipped, errors }));
messageApi.warning(
t('pages.inbounds.detachClientsResultMixed', { detached, skipped, errors }),
);
} else {
messageApi.success(t('pages.inbounds.detachClientsResult', { detached, skipped }));
}
@@ -1,6 +1,11 @@
import { useTranslation } from 'react-i18next';
import { Button, Card, Col, Empty, Input, InputNumber, Row, Select, Space } from 'antd';
import { ArrowDownOutlined, ArrowUpOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import {
ArrowDownOutlined,
ArrowUpOutlined,
DeleteOutlined,
PlusOutlined,
} from '@ant-design/icons';
import type { FallbackRow } from '@/schemas/forms/inbound-form';
@@ -33,7 +38,9 @@ export default function FallbacksCard({
<Button
size="small"
onClick={addAllFallbacks}
disabled={fallbackChildOptions.length === 0 || fallbacks.length >= fallbackChildOptions.length}
disabled={
fallbackChildOptions.length === 0 || fallbacks.length >= fallbackChildOptions.length
}
title={t('pages.inbounds.form.addAllFallbackTooltip')}
>
{t('pages.inbounds.form.addAll')}
@@ -92,7 +99,12 @@ export default function FallbacksCard({
title={t('pages.inbounds.form.moveDown')}
icon={<ArrowDownOutlined />}
/>
<Button aria-label={t('delete')} danger onClick={() => removeFallback(idx)} icon={<DeleteOutlined />} />
<Button
aria-label={t('delete')}
danger
onClick={() => removeFallback(idx)}
icon={<DeleteOutlined />}
/>
</Space.Compact>
<Row gutter={[8, 8]}>
<Col xs={24} sm={12}>
@@ -19,10 +19,7 @@ import { Controller, FormProvider, useForm, useWatch } from 'react-hook-form';
import { HttpUtil, NumberFormatter, RandomUtil, SizeFormatter, Wireguard } from '@/utils';
import type { RealityScanResult } from '@/generated/types';
import {
rawInboundToFormValues,
formValuesToWirePayload,
} from '@/lib/xray/inbound-form-adapter';
import { rawInboundToFormValues, formValuesToWirePayload } from '@/lib/xray/inbound-form-adapter';
import { createDefaultInboundSettings } from '@/lib/xray/inbound-defaults';
import { composeInboundTag, isAutoInboundTag, type InboundTagInput } from '@/lib/xray/inbound-tag';
import {
@@ -87,7 +84,6 @@ import SniffingTab from './SniffingTab';
import type { DBInbound } from '@/models/dbinbound';
import type { NodeRecord } from '@/api/queries/useNodesQuery';
/* Render a field label with a hover tooltip icon instead of an `extra` help line below. */
const labelWithHint = (label: string, hint: string) => (
<span>
@@ -100,7 +96,8 @@ const labelWithHint = (label: string, hint: string) => (
const PROTOCOL_OPTIONS = Object.values(Protocols).map((p) => ({ value: p, label: p }));
const SHARE_ADDR_STRATEGIES = ['node', 'listen', 'custom'] as const;
const SHARE_ADDR_HOSTNAME_RE = /^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)*$/;
const SHARE_ADDR_HOSTNAME_RE =
/^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)*$/;
function isValidShareAddrInput(value: string): boolean {
const v = value.trim();
@@ -152,11 +149,8 @@ function tabForValidationPath(path: PropertyKey[]): string {
if (path[0] === 'settings') return 'protocol';
if (path[0] === 'sniffing') return 'sniffing';
if (path[0] === 'streamSettings') {
if (
path[1] === 'security'
|| path[1] === 'realitySettings'
|| path[1] === 'tlsSettings'
) return 'security';
if (path[1] === 'security' || path[1] === 'realitySettings' || path[1] === 'tlsSettings')
return 'security';
return 'stream';
}
return 'basic';
@@ -201,13 +195,20 @@ function buildAddModeValues(): InboundFormValues {
*/
function newStreamSlice(n: string): Record<string, unknown> {
switch (n) {
case 'tcp': return TcpStreamSettingsSchema.parse({ header: { type: 'none' } });
case 'kcp': return KcpStreamSettingsSchema.parse({});
case 'ws': return WsStreamSettingsSchema.parse({});
case 'grpc': return GrpcStreamSettingsSchema.parse({});
case 'httpupgrade': return HttpUpgradeStreamSettingsSchema.parse({});
case 'xhttp': return XHttpStreamSettingsSchema.parse({});
default: return {};
case 'tcp':
return TcpStreamSettingsSchema.parse({ header: { type: 'none' } });
case 'kcp':
return KcpStreamSettingsSchema.parse({});
case 'ws':
return WsStreamSettingsSchema.parse({});
case 'grpc':
return GrpcStreamSettingsSchema.parse({});
case 'httpupgrade':
return HttpUpgradeStreamSettingsSchema.parse({});
case 'xhttp':
return XHttpStreamSettingsSchema.parse({});
default:
return {};
}
}
@@ -272,9 +273,9 @@ export default function InboundFormModal({
* picker and the per-network sub-forms are hidden.
*/
const hasSelectableTransport =
protocol !== Protocols.HYSTERIA
&& protocol !== Protocols.WIREGUARD
&& protocol !== Protocols.TUNNEL;
protocol !== Protocols.HYSTERIA &&
protocol !== Protocols.WIREGUARD &&
protocol !== Protocols.TUNNEL;
const wPort = useWatch({ control, name: 'port' });
const wListen = (useWatch({ control, name: 'listen' }) ?? '') as string;
@@ -297,9 +298,9 @@ export default function InboundFormModal({
settings: { network: wSsNetwork, allowedNetwork: wTunnelNetwork, udp: mixedUdpOn },
});
const isFallbackHost =
(protocol === Protocols.VLESS || protocol === Protocols.TROJAN)
&& network === 'tcp'
&& (security === 'tls' || security === 'reality');
(protocol === Protocols.VLESS || protocol === Protocols.TROJAN) &&
network === 'tcp' &&
(security === 'tls' || security === 'reality');
const {
genRealityKeypair,
@@ -318,8 +319,15 @@ export default function InboundFormModal({
setCertFromPanel,
clearCertFiles,
onSecurityChange,
} = useSecurityActions({ methods, setSaving, messageApi, modal, nodeId: typeof wNodeId === 'number' ? wNodeId : null, setScanResult, setScanning });
} = useSecurityActions({
methods,
setSaving,
messageApi,
modal,
nodeId: typeof wNodeId === 'number' ? wNodeId : null,
setScanResult,
setScanning,
});
const toggleSockopt = (on: boolean) => {
if (on) {
@@ -329,9 +337,10 @@ export default function InboundFormModal({
}
};
const wgSecretKey = useWatch({ control, name: 'settings.secretKey' });
const wgPubKey = typeof wgSecretKey === 'string' && wgSecretKey.length > 0
? Wireguard.generateKeypair(wgSecretKey).publicKey
: '';
const wgPubKey =
typeof wgSecretKey === 'string' && wgSecretKey.length > 0
? Wireguard.generateKeypair(wgSecretKey).publicKey
: '';
const regenInboundWg = () => {
const kp = Wireguard.generateKeypair();
@@ -344,8 +353,10 @@ export default function InboundFormModal({
) => {
if (block?.id === authId) return true;
const label = (block?.label || '').toLowerCase().replace(/[-_\s]/g, '');
if (authId === 'mlkem768') return label.includes('mlkem768') && !label.includes('xorpub') && !label.includes('random');
if (authId === 'x25519') return label.includes('x25519') && !label.includes('xorpub') && !label.includes('random');
if (authId === 'mlkem768')
return label.includes('mlkem768') && !label.includes('xorpub') && !label.includes('random');
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');
@@ -388,9 +399,8 @@ export default function InboundFormModal({
useEffect(() => {
if (!open) return;
const initial = mode === 'edit' && dbInbound
? rawInboundToFormValues(dbInbound)
: buildAddModeValues();
const initial =
mode === 'edit' && dbInbound ? rawInboundToFormValues(dbInbound) : buildAddModeValues();
methods.reset(initial);
setScanResult(null);
setActiveTab('basic');
@@ -404,9 +414,9 @@ export default function InboundFormModal({
});
lastWrittenTagRef.current = initialTag;
if (
mode === 'edit'
&& dbInbound
&& (dbInbound.protocol === Protocols.VLESS || dbInbound.protocol === Protocols.TROJAN)
mode === 'edit' &&
dbInbound &&
(dbInbound.protocol === Protocols.VLESS || dbInbound.protocol === Protocols.TROJAN)
) {
loadFallbacks(dbInbound.id);
} else {
@@ -479,10 +489,12 @@ export default function InboundFormModal({
tlsSettings: createHysteriaTlsSettingsWithDefaultCert(),
finalmask: {
tcp: [],
udp: [{
type: 'salamander',
settings: { password: RandomUtil.randomLowerAndNum(16) },
}],
udp: [
{
type: 'salamander',
settings: { password: RandomUtil.randomLowerAndNum(16) },
},
],
},
});
} else if (next === Protocols.WIREGUARD || next === Protocols.TUNNEL) {
@@ -520,16 +532,15 @@ export default function InboundFormModal({
setSaving(true);
try {
const payload = formValuesToWirePayload(parsed.data);
const url = mode === 'edit' && dbInbound
? `/panel/api/inbounds/update/${dbInbound.id}`
: '/panel/api/inbounds/add';
const url =
mode === 'edit' && dbInbound
? `/panel/api/inbounds/update/${dbInbound.id}`
: '/panel/api/inbounds/add';
const msg = await HttpUtil.post(url, payload);
if (msg?.success) {
if (isFallbackHost) {
const obj = msg.obj as { id?: number; Id?: number } | null;
const masterId = mode === 'edit'
? dbInbound!.id
: (obj?.id ?? obj?.Id ?? 0);
const masterId = mode === 'edit' ? dbInbound!.id : (obj?.id ?? obj?.Id ?? 0);
if (masterId) await saveFallbacks(masterId);
}
onSaved();
@@ -551,13 +562,10 @@ export default function InboundFormModal({
messageApi.error(formatInboundIssue(issue, methods.getValues(), t));
});
const title = mode === 'edit'
? t('pages.inbounds.modifyInbound')
: t('pages.inbounds.addInbound');
const title =
mode === 'edit' ? t('pages.inbounds.modifyInbound') : t('pages.inbounds.addInbound');
const okText = mode === 'edit'
? t('pages.clients.submitEdit')
: t('create');
const okText = mode === 'edit' ? t('pages.clients.submitEdit') : t('create');
const basicTab = (
<>
@@ -600,22 +608,28 @@ export default function InboundFormModal({
<FormField
name="shareAddrStrategy"
label={labelWithHint(t('pages.inbounds.form.shareAddrStrategy'), t('pages.inbounds.form.shareAddrStrategyHelp'))}
label={labelWithHint(
t('pages.inbounds.form.shareAddrStrategy'),
t('pages.inbounds.form.shareAddrStrategyHelp'),
)}
>
<Select
options={SHARE_ADDR_STRATEGIES
.filter((strategy) => strategy !== 'node' || nodeShareOptionAvailable)
.map((strategy) => ({
value: strategy,
label: t(`pages.inbounds.form.shareAddrStrategyOptions.${strategy}`),
}))}
options={SHARE_ADDR_STRATEGIES.filter(
(strategy) => strategy !== 'node' || nodeShareOptionAvailable,
).map((strategy) => ({
value: strategy,
label: t(`pages.inbounds.form.shareAddrStrategyOptions.${strategy}`),
}))}
/>
</FormField>
{shareAddrStrategy === 'custom' && (
<FormField
name="shareAddr"
label={labelWithHint(t('pages.inbounds.form.shareAddr'), t('pages.inbounds.form.shareAddrHelp'))}
label={labelWithHint(
t('pages.inbounds.form.shareAddr'),
t('pages.inbounds.form.shareAddrHelp'),
)}
rules={{
validate: (value) =>
isValidShareAddrInput(String(value ?? '')) || t('pages.inbounds.form.shareAddrHelp'),
@@ -627,7 +641,10 @@ export default function InboundFormModal({
<FormField
name="subSortIndex"
label={labelWithHint(t('pages.inbounds.form.subSortIndex'), t('pages.inbounds.form.subSortIndexHelp'))}
label={labelWithHint(
t('pages.inbounds.form.subSortIndex'),
t('pages.inbounds.form.subSortIndexHelp'),
)}
>
<InputNumber min={1} />
</FormField>
@@ -636,7 +653,10 @@ export default function InboundFormModal({
<FormField
name="disableFlow"
valueProp="checked"
label={labelWithHint(t('pages.inbounds.form.disableFlow'), t('pages.inbounds.form.disableFlowHelp'))}
label={labelWithHint(
t('pages.inbounds.form.disableFlow'),
t('pages.inbounds.form.disableFlowHelp'),
)}
>
<Switch />
</FormField>
@@ -716,7 +736,9 @@ export default function InboundFormModal({
const protocolTab = (
<>
{protocol === Protocols.WIREGUARD && <WireguardFields wgPubKey={wgPubKey} regenInboundWg={regenInboundWg} />}
{protocol === Protocols.WIREGUARD && (
<WireguardFields wgPubKey={wgPubKey} regenInboundWg={regenInboundWg} />
)}
{protocol === Protocols.TUN && <TunFields />}
@@ -729,11 +751,22 @@ export default function InboundFormModal({
{protocol === Protocols.SHADOWSOCKS && <ShadowsocksFields isSSWith2022={isSSWith2022} />}
{protocol === Protocols.VLESS && <VlessFields saving={saving} selectedVlessAuth={selectedVlessAuth} vlessAuthKind={vlessAuthKind} network={network} security={security} getNewVlessEnc={getNewVlessEnc} clearVlessEnc={clearVlessEnc} />}
{protocol === Protocols.VLESS && (
<VlessFields
saving={saving}
selectedVlessAuth={selectedVlessAuth}
vlessAuthKind={vlessAuthKind}
network={network}
security={security}
getNewVlessEnc={getNewVlessEnc}
clearVlessEnc={clearVlessEnc}
/>
)}
{isFallbackHost && fallbacksCard}
{(protocol === Protocols.VLESS || protocol === Protocols.TROJAN)
&& network === 'tcp' && !isFallbackHost && (
{(protocol === Protocols.VLESS || protocol === Protocols.TROJAN) &&
network === 'tcp' &&
!isFallbackHost && (
<Alert
className="mt-12"
type="info"
@@ -750,7 +783,14 @@ export default function InboundFormModal({
* FinalMask mkcp-legacy UDP mask when moving to mKCP (removed otherwise).
*/
const onNetworkChange = (next: string) => {
const ALL = ['tcpSettings', 'kcpSettings', 'wsSettings', 'grpcSettings', 'httpupgradeSettings', 'xhttpSettings'];
const ALL = [
'tcpSettings',
'kcpSettings',
'wsSettings',
'grpcSettings',
'httpupgradeSettings',
'xhttpSettings',
];
const current = (getV('streamSettings') as Record<string, unknown>) ?? {};
const cleaned: Record<string, unknown> = { ...current, network: next };
for (const k of ALL) {
@@ -773,7 +813,9 @@ export default function InboundFormModal({
} else {
const fm = cleaned.finalmask as Record<string, unknown> | undefined;
if (fm && Array.isArray(fm.udp)) {
const udp = (fm.udp as unknown[]).filter((m) => (m as { type?: string })?.type !== 'mkcp-legacy');
const udp = (fm.udp as unknown[]).filter(
(m) => (m as { type?: string })?.type !== 'mkcp-legacy',
);
cleaned.finalmask = { ...fm, udp };
}
}
@@ -914,10 +956,11 @@ export default function InboundFormModal({
label: t('pages.inbounds.advanced.all'),
children: (
<>
<div className="advanced-editor-meta">
{t('pages.inbounds.advanced.allHelp')}
</div>
<AdvancedAllEditor streamEnabled={streamEnabled} sniffingEnabled={sniffingSupported} />
<div className="advanced-editor-meta">{t('pages.inbounds.advanced.allHelp')}</div>
<AdvancedAllEditor
streamEnabled={streamEnabled}
sniffingEnabled={sniffingSupported}
/>
</>
),
},
@@ -940,44 +983,48 @@ export default function InboundFormModal({
),
},
...(streamEnabled
? [{
key: 'stream',
label: t('pages.inbounds.advanced.stream'),
children: (
<>
<div className="advanced-editor-meta">
{t('pages.inbounds.advanced.streamHelp')}{' '}
<code>{'{ streamSettings: { ... } }'}</code>.
</div>
<AdvancedSliceEditor
path="streamSettings"
wrapKey="streamSettings"
minHeight="320px"
maxHeight="540px"
/>
</>
),
}]
? [
{
key: 'stream',
label: t('pages.inbounds.advanced.stream'),
children: (
<>
<div className="advanced-editor-meta">
{t('pages.inbounds.advanced.streamHelp')}{' '}
<code>{'{ streamSettings: { ... } }'}</code>.
</div>
<AdvancedSliceEditor
path="streamSettings"
wrapKey="streamSettings"
minHeight="320px"
maxHeight="540px"
/>
</>
),
},
]
: []),
...(sniffingSupported
? [{
key: 'sniffing',
label: t('pages.inbounds.advanced.sniffing'),
children: (
<>
<div className="advanced-editor-meta">
{t('pages.inbounds.advanced.sniffingHelp')}{' '}
<code>{'{ sniffing: { ... } }'}</code>.
</div>
<AdvancedSliceEditor
path="sniffing"
wrapKey="sniffing"
minHeight="240px"
maxHeight="420px"
/>
</>
),
}]
? [
{
key: 'sniffing',
label: t('pages.inbounds.advanced.sniffing'),
children: (
<>
<div className="advanced-editor-meta">
{t('pages.inbounds.advanced.sniffingHelp')}{' '}
<code>{'{ sniffing: { ... } }'}</code>.
</div>
<AdvancedSliceEditor
path="sniffing"
wrapKey="sniffing"
minHeight="240px"
maxHeight="420px"
/>
</>
),
},
]
: []),
]}
/>
@@ -1010,33 +1057,75 @@ export default function InboundFormModal({
wrapperCol={{ sm: { span: 14 } }}
labelWrap
>
<Tabs activeKey={activeTab} onChange={setActiveTab} items={[
{ key: 'basic', label: t('pages.xray.basicTemplate'), children: basicTab, forceRender: true },
...(([
Protocols.VLESS,
Protocols.SHADOWSOCKS,
Protocols.HTTP,
Protocols.MIXED,
Protocols.TUNNEL,
Protocols.TUN,
Protocols.WIREGUARD,
Protocols.MTPROTO,
] as string[]).includes(protocol) || isFallbackHost
? [{ key: 'protocol', label: t('pages.inbounds.protocol'), children: protocolTab, forceRender: true }]
: []),
...(streamEnabled
? [
{ key: 'stream', label: t('pages.inbounds.streamTab'), children: streamTab, forceRender: true },
...(protocol !== Protocols.WIREGUARD && protocol !== Protocols.TUNNEL
? [{ key: 'security', label: t('pages.inbounds.securityTab'), children: securityTab, forceRender: true }]
: []),
]
: []),
...(sniffingSupported
? [{ key: 'sniffing', label: t('pages.inbounds.sniffingTab'), children: sniffingTab, forceRender: true }]
: []),
{ key: 'advanced', label: t('pages.xray.advancedTemplate'), children: advancedTab, forceRender: true },
]} />
<Tabs
activeKey={activeTab}
onChange={setActiveTab}
items={[
{
key: 'basic',
label: t('pages.xray.basicTemplate'),
children: basicTab,
forceRender: true,
},
...((
[
Protocols.VLESS,
Protocols.SHADOWSOCKS,
Protocols.HTTP,
Protocols.MIXED,
Protocols.TUNNEL,
Protocols.TUN,
Protocols.WIREGUARD,
Protocols.MTPROTO,
] as string[]
).includes(protocol) || isFallbackHost
? [
{
key: 'protocol',
label: t('pages.inbounds.protocol'),
children: protocolTab,
forceRender: true,
},
]
: []),
...(streamEnabled
? [
{
key: 'stream',
label: t('pages.inbounds.streamTab'),
children: streamTab,
forceRender: true,
},
...(protocol !== Protocols.WIREGUARD && protocol !== Protocols.TUNNEL
? [
{
key: 'security',
label: t('pages.inbounds.securityTab'),
children: securityTab,
forceRender: true,
},
]
: []),
]
: []),
...(sniffingSupported
? [
{
key: 'sniffing',
label: t('pages.inbounds.sniffingTab'),
children: sniffingTab,
forceRender: true,
},
]
: []),
{
key: 'advanced',
label: t('pages.xray.advancedTemplate'),
children: advancedTab,
forceRender: true,
},
]}
/>
</Form>
</FormProvider>
</Modal>
@@ -11,11 +11,7 @@ export default function SniffingTab() {
control={control}
name="sniffing"
render={({ field }) => (
<SniffingField
value={field.value}
onChange={field.onChange}
enableLabel={t('enable')}
/>
<SniffingField value={field.value} onChange={field.onChange} enableLabel={t('enable')} />
)}
/>
);
@@ -67,9 +67,10 @@ export function AdvancedSliceEditor({
setText(next);
try {
const parsed = JSON.parse(next);
const toWrite = wrapKey && parsed && typeof parsed === 'object' && !Array.isArray(parsed)
? (parsed as Record<string, unknown>)[wrapKey] ?? {}
: parsed;
const toWrite =
wrapKey && parsed && typeof parsed === 'object' && !Array.isArray(parsed)
? ((parsed as Record<string, unknown>)[wrapKey] ?? {})
: parsed;
setValue(path, toWrite);
lastEmitRef.current = JSON.stringify(wrapKey ? { [wrapKey]: toWrite } : toWrite, null, 2);
} catch {
@@ -146,7 +147,17 @@ export function AdvancedAllEditor({
setText(formStr);
lastEmitRef.current = formStr;
/* eslint-disable-next-line react-hooks/exhaustive-deps */
}, [wListen, wPort, wProtocol, wTag, wSettings, wSniffing, wStream, streamEnabled, sniffingEnabled]);
}, [
wListen,
wPort,
wProtocol,
wTag,
wSettings,
wSniffing,
wStream,
streamEnabled,
sniffingEnabled,
]);
return (
<JsonEditor
@@ -36,7 +36,11 @@ export function formatInboundIssue(issue: IssueLike, values: unknown, t: TFuncti
* Builds the single-line toast for a failed inbound save: the first issue,
* fully described, plus a "(+N more)" tail when several fields failed.
*/
export function formatInboundValidation(issues: IssueLike[], values: unknown, t: TFunction): string {
export function formatInboundValidation(
issues: IssueLike[],
values: unknown,
t: TFunction,
): string {
const first = formatInboundIssue(issues[0], values, t);
if (issues.length <= 1) return first;
return t('pages.inbounds.toasts.moreIssues', { message: first, count: issues.length - 1 });
@@ -16,10 +16,12 @@ export default function AccountsList() {
<Form.Item label={t('pages.inbounds.form.accounts')}>
<Button
size="small"
onClick={() => append({
user: RandomUtil.randomLowerAndNum(8),
pass: RandomUtil.randomLowerAndNum(12),
})}
onClick={() =>
append({
user: RandomUtil.randomLowerAndNum(8),
pass: RandomUtil.randomLowerAndNum(12),
})
}
>
<PlusOutlined /> {t('add')}
</Button>
@@ -13,9 +13,10 @@ export default function HysteriaFields() {
const masq = useWatch({ control, name: 'streamSettings.hysteriaSettings.masquerade' }) as
| { type?: string }
| undefined;
const masqType = useWatch({ control, name: 'streamSettings.hysteriaSettings.masquerade.type' }) as
| string
| undefined;
const masqType = useWatch({
control,
name: 'streamSettings.hysteriaSettings.masquerade.type',
}) as string | undefined;
return (
<>
<FormField
@@ -39,10 +40,15 @@ export default function HysteriaFields() {
'streamSettings.hysteriaSettings.masquerade',
checked
? {
type: '', dir: '', url: '',
rewriteHost: false, insecure: false,
content: '', headers: {}, statusCode: 0,
}
type: '',
dir: '',
url: '',
rewriteHost: false,
insecure: false,
content: '',
headers: {},
statusCode: 0,
}
: undefined,
)
}
@@ -50,10 +56,7 @@ export default function HysteriaFields() {
</Form.Item>
{masq && (
<>
<FormField
label={t('pages.inbounds.form.type')}
name={[...MASQ_PATH, 'type']}
>
<FormField label={t('pages.inbounds.form.type')} name={[...MASQ_PATH, 'type']}>
<Select
options={[
{ value: '', label: 'default (404 page)' },
@@ -65,10 +68,7 @@ export default function HysteriaFields() {
</FormField>
{masqType === 'proxy' && (
<>
<FormField
label={t('pages.inbounds.form.upstreamUrl')}
name={[...MASQ_PATH, 'url']}
>
<FormField label={t('pages.inbounds.form.upstreamUrl')} name={[...MASQ_PATH, 'url']}>
<Input placeholder="https://www.example.com" />
</FormField>
<FormField
@@ -88,10 +88,7 @@ export default function HysteriaFields() {
</>
)}
{masqType === 'file' && (
<FormField
label={t('pages.inbounds.form.directory')}
name={[...MASQ_PATH, 'dir']}
>
<FormField label={t('pages.inbounds.form.directory')} name={[...MASQ_PATH, 'dir']}>
<Input placeholder="/var/www/html" />
</FormField>
)}
@@ -103,16 +100,10 @@ export default function HysteriaFields() {
>
<InputNumber min={0} max={599} style={{ width: '100%' }} />
</FormField>
<FormField
label={t('pages.inbounds.form.body')}
name={[...MASQ_PATH, 'content']}
>
<FormField label={t('pages.inbounds.form.body')} name={[...MASQ_PATH, 'content']}>
<Input.TextArea autoSize={{ minRows: 3 }} />
</FormField>
<FormField
label={t('pages.inbounds.form.headers')}
name={[...MASQ_PATH, 'headers']}
>
<FormField label={t('pages.inbounds.form.headers')} name={[...MASQ_PATH, 'headers']}>
<HeaderMapEditor mode="v1" />
</FormField>
</>
@@ -17,11 +17,7 @@ export default function MixedFields({ mixedUdpOn }: { mixedUdpOn: boolean }) {
]}
/>
</FormField>
<FormField
name={['settings', 'udp']}
label="UDP"
valueProp="checked"
>
<FormField name={['settings', 'udp']} label="UDP" valueProp="checked">
<Switch />
</FormField>
{mixedUdpOn && (
@@ -8,7 +8,9 @@ import { useOutboundTags } from '@/api/queries/useOutboundTags';
export default function MtprotoFields() {
const { t } = useTranslation();
const { control } = useFormContext();
const routeThroughXray = useWatch({ control, name: 'settings.routeThroughXray' }) as boolean | undefined;
const routeThroughXray = useWatch({ control, name: 'settings.routeThroughXray' }) as
| boolean
| undefined;
const { data: outboundTags } = useOutboundTags();
return (
<>
@@ -26,7 +28,10 @@ export default function MtprotoFields() {
>
<Input placeholder="127.0.0.1" />
</FormField>
<FormField name={['settings', 'domainFronting', 'port']} label={t('pages.inbounds.form.mtgDomainFrontingPort')}>
<FormField
name={['settings', 'domainFronting', 'port']}
label={t('pages.inbounds.form.mtgDomainFrontingPort')}
>
<InputNumber min={0} max={65535} placeholder="443" style={{ width: '100%' }} />
</FormField>
<FormField
@@ -55,7 +60,11 @@ export default function MtprotoFields() {
]}
/>
</FormField>
<FormField name={['settings', 'debug']} label={t('pages.inbounds.form.mtgDebug')} valueProp="checked">
<FormField
name={['settings', 'debug']}
label={t('pages.inbounds.form.mtgDebug')}
valueProp="checked"
>
<Switch />
</FormField>
<FormField
@@ -23,9 +23,7 @@ export default function ShadowsocksFields({ isSSWith2022 }: ShadowsocksFieldsPro
setValue('settings.password', RandomUtil.randomShadowsocksPassword(v as string));
}}
>
<Select
options={SSMethodSchema.options.map((m) => ({ value: m, label: m }))}
/>
<Select options={SSMethodSchema.options.map((m) => ({ value: m, label: m }))} />
</FormField>
{isSSWith2022 && (
<Form.Item label={t('password')}>
@@ -57,11 +55,7 @@ export default function ShadowsocksFields({ isSSWith2022 }: ShadowsocksFieldsPro
]}
/>
</FormField>
<FormField
name={['settings', 'ivCheck']}
label="ivCheck"
valueProp="checked"
>
<FormField name={['settings', 'ivCheck']} label="ivCheck" valueProp="checked">
<Switch />
</FormField>
</>
@@ -8,13 +8,19 @@ export default function TunnelFields() {
const { t } = useTranslation();
return (
<>
<FormField name={['settings', 'rewriteAddress']} label={t('pages.inbounds.form.rewriteAddress')}>
<FormField
name={['settings', 'rewriteAddress']}
label={t('pages.inbounds.form.rewriteAddress')}
>
<Input />
</FormField>
<FormField name={['settings', 'rewritePort']} label={t('pages.inbounds.form.rewritePort')}>
<InputNumber min={0} max={65535} />
</FormField>
<FormField name={['settings', 'allowedNetwork']} label={t('pages.inbounds.form.allowedNetwork')}>
<FormField
name={['settings', 'allowedNetwork']}
label={t('pages.inbounds.form.allowedNetwork')}
>
<Select
options={[
{ value: 'tcp,udp', label: 'TCP, UDP' },
@@ -56,7 +56,9 @@ export default function VlessFields({
<Button type="primary" loading={saving} onClick={() => getNewVlessEnc(authKind)}>
{t('pages.inbounds.vlessAuthGenerateButton')}
</Button>
<Button danger onClick={clearVlessEnc}>{t('clear')}</Button>
<Button danger onClick={clearVlessEnc}>
{t('clear')}
</Button>
</Space>
<Typography.Text type="secondary" className="vless-auth-state">
{t('pages.inbounds.vlessAuthSelected', { auth: selectedVlessAuth })}
@@ -37,7 +37,10 @@ export default function WireguardFields({ wgPubKey, regenInboundWg }: WireguardF
>
<Switch />
</FormField>
<FormField name={['settings', 'domainStrategy']} label={t('pages.xray.wireguard.domainStrategy')}>
<FormField
name={['settings', 'domainStrategy']}
label={t('pages.xray.wireguard.domainStrategy')}
>
<Select
allowClear
options={[
@@ -49,7 +49,9 @@ export default function RealityTargetScannerModal({
render: (target: string, row) => (
<Tooltip title={row.ip ? `${target}${row.ip}` : target}>
<div style={{ lineHeight: 1.25 }}>
<div style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{target}</div>
<div style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{target}
</div>
{row.ip ? <div style={{ color: '#999', fontSize: 12 }}>{row.ip}</div> : null}
</div>
</Tooltip>
@@ -1,7 +1,19 @@
import { useState } from 'react';
import { useFormContext } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { Alert, Button, Collapse, Descriptions, Divider, Form, Input, InputNumber, Select, Space, Switch } from 'antd';
import {
Alert,
Button,
Collapse,
Descriptions,
Divider,
Form,
Input,
InputNumber,
Select,
Space,
Switch,
} from 'antd';
import { RadarChartOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
@@ -52,9 +64,10 @@ export default function RealityForm({
* worth reading, so subject/issuer stay visible and only the verdict is added.
*/
const certSummary = (r: RealityScanResult) => {
const who = r.certSubject && r.certIssuer
? `${r.certSubject} (${r.certIssuer})`
: r.certSubject || r.certIssuer;
const who =
r.certSubject && r.certIssuer
? `${r.certSubject} (${r.certIssuer})`
: r.certSubject || r.certIssuer;
if (!who) return '—';
return r.certValid ? who : `${who}${t('pages.inbounds.form.scanCertInvalid')}`;
};
@@ -73,16 +86,17 @@ export default function RealityForm({
>
<Switch />
</FormField>
<FormField name={['streamSettings', 'realitySettings', 'xver']} label={t('pages.inbounds.form.xver')}>
<FormField
name={['streamSettings', 'realitySettings', 'xver']}
label={t('pages.inbounds.form.xver')}
>
<InputNumber min={0} />
</FormField>
<FormField
name={['streamSettings', 'realitySettings', 'settings', 'fingerprint']}
label="uTLS"
>
<Select
options={Object.values(UTLS_FINGERPRINT).map((fp) => ({ value: fp, label: fp }))}
/>
<Select options={Object.values(UTLS_FINGERPRINT).map((fp) => ({ value: fp, label: fp }))} />
</FormField>
<Form.Item
label={t('pages.inbounds.form.target')}
@@ -101,7 +115,11 @@ export default function RealityForm({
>
<Input style={{ flex: 1 }} placeholder="example.com:443" />
</FormField>
<Button icon={<RadarChartOutlined />} loading={scanning} onClick={() => scanRealityTarget()}>
<Button
icon={<RadarChartOutlined />}
loading={scanning}
onClick={() => scanRealityTarget()}
>
{t('pages.inbounds.form.scan')}
</Button>
<Button icon={<SearchOutlined />} onClick={() => setScannerOpen(true)}>
@@ -119,7 +137,7 @@ export default function RealityForm({
? t('pages.inbounds.form.scanFeasible')
: scanResult.reason || t('pages.inbounds.form.scanNotFeasible')
}
description={(
description={
<>
{scanResult.privateTarget && (
<div style={{ marginBottom: 8 }}>{t('pages.inbounds.form.scanPrivateNote')}</div>
@@ -137,14 +155,16 @@ export default function RealityForm({
{certSummary(scanResult)}
</Descriptions.Item>
<Descriptions.Item label={t('pages.inbounds.form.scanCertExpiry')}>
{scanResult.notAfter ? dayjs(scanResult.notAfter).format('YYYY-MM-DD HH:mm') : '—'}
{scanResult.notAfter
? dayjs(scanResult.notAfter).format('YYYY-MM-DD HH:mm')
: '—'}
</Descriptions.Item>
<Descriptions.Item label={t('pages.inbounds.form.scanLatency')}>
{scanResult.latencyMs > 0 ? `${scanResult.latencyMs} ms` : '—'}
</Descriptions.Item>
</Descriptions>
</>
)}
}
/>
</Form.Item>
)}
@@ -188,13 +208,14 @@ export default function RealityForm({
</FormField>
<Form.Item label={t('pages.inbounds.form.shortIds')}>
<Space.Compact block style={{ display: 'flex' }}>
<FormField
name={['streamSettings', 'realitySettings', 'shortIds']}
noStyle
>
<FormField name={['streamSettings', 'realitySettings', 'shortIds']} noStyle>
<Select mode="tags" tokenSeparators={[',']} style={{ flex: 1 }} />
</FormField>
<Button aria-label={t('regenerate')} icon={<ReloadOutlined />} onClick={randomizeShortIds} />
<Button
aria-label={t('regenerate')}
icon={<ReloadOutlined />}
onClick={randomizeShortIds}
/>
</Space.Compact>
</Form.Item>
<Form.Item
@@ -202,13 +223,14 @@ export default function RealityForm({
tooltip={t('pages.inbounds.form.spiderXHint')}
>
<Space.Compact block style={{ display: 'flex' }}>
<FormField
name={['streamSettings', 'realitySettings', 'settings', 'spiderX']}
noStyle
>
<FormField name={['streamSettings', 'realitySettings', 'settings', 'spiderX']} noStyle>
<Input style={{ flex: 1 }} />
</FormField>
<Button aria-label={t('regenerate')} icon={<ReloadOutlined />} onClick={randomizeSpiderX} />
<Button
aria-label={t('regenerate')}
icon={<ReloadOutlined />}
onClick={randomizeSpiderX}
/>
</Space.Compact>
</Form.Item>
<FormField
@@ -228,7 +250,9 @@ export default function RealityForm({
<Button type="primary" loading={saving} onClick={genRealityKeypair}>
{t('pages.inbounds.form.getNewCert')}
</Button>
<Button danger onClick={clearRealityKeypair}>{t('clear')}</Button>
<Button danger onClick={clearRealityKeypair}>
{t('clear')}
</Button>
</Space>
</Form.Item>
<FormField
@@ -248,7 +272,9 @@ export default function RealityForm({
<Button type="primary" loading={saving} onClick={genMldsa65}>
{t('pages.inbounds.form.getNewSeed')}
</Button>
<Button danger onClick={clearMldsa65}>{t('clear')}</Button>
<Button danger onClick={clearMldsa65}>
{t('clear')}
</Button>
</Space>
</Form.Item>
<FormField
@@ -1,6 +1,11 @@
import { useTranslation } from 'react-i18next';
import { Button, Form, Input, InputNumber, Radio, Select, Space, Switch } from 'antd';
import { CloudDownloadOutlined, FileProtectOutlined, MinusOutlined, PlusOutlined } from '@ant-design/icons';
import {
CloudDownloadOutlined,
FileProtectOutlined,
MinusOutlined,
PlusOutlined,
} from '@ant-design/icons';
import { useFieldArray, useFormContext, useWatch } from 'react-hook-form';
import { FormField } from '@/components/form/rhf';
@@ -40,11 +45,24 @@ interface CertRowProps {
clearCertFiles: (certName: number) => void;
}
function CertRow({ index, total, saving, onRemove, setCertFromPanel, clearCertFiles }: CertRowProps) {
function CertRow({
index,
total,
saving,
onRemove,
setCertFromPanel,
clearCertFiles,
}: CertRowProps) {
const { t } = useTranslation();
const { control } = useFormContext();
const useFile = useWatch({ control, name: `streamSettings.tlsSettings.certificates.${index}.useFile` });
const usage = useWatch({ control, name: `streamSettings.tlsSettings.certificates.${index}.usage` });
const useFile = useWatch({
control,
name: `streamSettings.tlsSettings.certificates.${index}.useFile`,
});
const usage = useWatch({
control,
name: `streamSettings.tlsSettings.certificates.${index}.usage`,
});
return (
<div>
<FormField
@@ -52,12 +70,8 @@ function CertRow({ index, total, saving, onRemove, setCertFromPanel, clearCertFi
label={`${t('certificate')} ${index + 1}`}
>
<Radio.Group buttonStyle="solid">
<Radio.Button value={true}>
{t('pages.inbounds.certificatePath')}
</Radio.Button>
<Radio.Button value={false}>
{t('pages.inbounds.certificateContent')}
</Radio.Button>
<Radio.Button value={true}>{t('pages.inbounds.certificatePath')}</Radio.Button>
<Radio.Button value={false}>{t('pages.inbounds.certificateContent')}</Radio.Button>
</Radio.Group>
</FormField>
{total > 1 && (
@@ -83,11 +97,7 @@ function CertRow({ index, total, saving, onRemove, setCertFromPanel, clearCertFi
</FormField>
<Form.Item label=" ">
<Space>
<Button
type="primary"
loading={saving}
onClick={() => setCertFromPanel(index)}
>
<Button type="primary" loading={saving} onClick={() => setCertFromPanel(index)}>
{t('pages.inbounds.setDefaultCert')}
</Button>
<Button danger onClick={() => clearCertFiles(index)}>
@@ -156,7 +166,10 @@ function EchSockoptSection() {
const on = !!echSockopt;
return (
<>
<Form.Item label={t('pages.inbounds.form.echSockopt')} tooltip={t('pages.inbounds.form.echSockoptTip')}>
<Form.Item
label={t('pages.inbounds.form.echSockopt')}
tooltip={t('pages.inbounds.form.echSockoptTip')}
>
<Switch
checked={on}
onChange={(v) =>
@@ -223,7 +236,10 @@ export default function TlsForm({
<FormField name={['streamSettings', 'tlsSettings', 'serverName']} label="SNI">
<Input placeholder={t('pages.inbounds.form.serverNameIndication')} />
</FormField>
<FormField name={['streamSettings', 'tlsSettings', 'cipherSuites']} label={t('pages.inbounds.form.cipherSuites')}>
<FormField
name={['streamSettings', 'tlsSettings', 'cipherSuites']}
label={t('pages.inbounds.form.cipherSuites')}
>
<Select
options={[
{ value: '', label: t('pages.inbounds.form.autoOption') },
@@ -247,10 +263,7 @@ export default function TlsForm({
</FormField>
</Space.Compact>
</Form.Item>
<FormField
name={['streamSettings', 'tlsSettings', 'settings', 'fingerprint']}
label="uTLS"
>
<FormField name={['streamSettings', 'tlsSettings', 'settings', 'fingerprint']} label="uTLS">
<Select
options={[
{ value: '', label: 'None' },
@@ -308,17 +321,19 @@ export default function TlsForm({
aria-label={t('add')}
type="primary"
size="small"
onClick={() => append({
useFile: true,
certificateFile: '',
keyFile: '',
certificate: [],
key: [],
ocspStapling: 0,
oneTimeLoading: false,
usage: 'encipherment',
buildChain: false,
})}
onClick={() =>
append({
useFile: true,
certificateFile: '',
keyFile: '',
certificate: [],
key: [],
ocspStapling: 0,
oneTimeLoading: false,
usage: 'encipherment',
buildChain: false,
})
}
>
<PlusOutlined />
</Button>
@@ -342,7 +357,10 @@ export default function TlsForm({
<Input placeholder="/path/to/sslkeylog.txt" />
</FormField>
<EchSockoptSection />
<FormField name={['streamSettings', 'tlsSettings', 'echServerKeys']} label={t('pages.inbounds.form.echKey')}>
<FormField
name={['streamSettings', 'tlsSettings', 'echServerKeys']}
label={t('pages.inbounds.form.echKey')}
>
<Input />
</FormField>
<FormField
@@ -356,7 +374,9 @@ export default function TlsForm({
<Button type="primary" loading={saving} onClick={getNewEchCert}>
{t('pages.inbounds.form.getNewEchCert')}
</Button>
<Button danger onClick={clearEchCert}>{t('clear')}</Button>
<Button danger onClick={clearEchCert}>
{t('clear')}
</Button>
</Space>
</Form.Item>
<Form.Item
@@ -15,16 +15,10 @@ export default function HttpUpgradeForm() {
>
<Switch />
</FormField>
<FormField
name={['streamSettings', 'httpupgradeSettings', 'host']}
label={t('host')}
>
<FormField name={['streamSettings', 'httpupgradeSettings', 'host']} label={t('host')}>
<Input />
</FormField>
<FormField
name={['streamSettings', 'httpupgradeSettings', 'path']}
label={t('path')}
>
<FormField name={['streamSettings', 'httpupgradeSettings', 'path']} label={t('path')}>
<Input />
</FormField>
<FormField
@@ -10,13 +10,22 @@ export default function KcpForm() {
<FormField name={['streamSettings', 'kcpSettings', 'mtu']} label="MTU">
<InputNumber min={576} max={1460} />
</FormField>
<FormField name={['streamSettings', 'kcpSettings', 'tti']} label={t('pages.inbounds.form.ttiMs')}>
<FormField
name={['streamSettings', 'kcpSettings', 'tti']}
label={t('pages.inbounds.form.ttiMs')}
>
<InputNumber min={10} max={100} />
</FormField>
<FormField name={['streamSettings', 'kcpSettings', 'uplinkCapacity']} label={t('pages.inbounds.form.uplinkMbps')}>
<FormField
name={['streamSettings', 'kcpSettings', 'uplinkCapacity']}
label={t('pages.inbounds.form.uplinkMbps')}
>
<InputNumber min={0} />
</FormField>
<FormField name={['streamSettings', 'kcpSettings', 'downlinkCapacity']} label={t('pages.inbounds.form.downlinkMbps')}>
<FormField
name={['streamSettings', 'kcpSettings', 'downlinkCapacity']}
label={t('pages.inbounds.form.downlinkMbps')}
>
<InputNumber min={0} />
</FormField>
<FormField
@@ -29,20 +29,20 @@ export default function RawForm() {
'streamSettings.tcpSettings.header',
v
? {
type: 'http',
request: {
version: '1.1',
method: 'GET',
path: ['/'],
headers: {},
},
response: {
version: '1.1',
status: '200',
reason: 'OK',
headers: {},
},
}
type: 'http',
request: {
version: '1.1',
method: 'GET',
path: ['/'],
headers: {},
},
response: {
version: '1.1',
status: '200',
reason: 'OK',
headers: {},
},
}
: { type: 'none' },
);
}}
@@ -37,7 +37,9 @@ export default function SockoptForm({
const sockTrusted = useWatch({ control, name: 'streamSettings.sockopt.trustedXForwardedFor' });
const transportAcceptPP = useWatch({
control,
name: transportField ? `streamSettings.${transportField}.acceptProxyProtocol` : 'streamSettings.__noTransportProxyField',
name: transportField
? `streamSettings.${transportField}.acceptProxyProtocol`
: 'streamSettings.__noTransportProxyField',
});
/* Presets write the same sockopt fields the user could set by hand below,
@@ -103,7 +105,10 @@ export default function SockoptForm({
onChange={(v) => applyRealClientIpPreset(v as RealClientIpPreset)}
options={[
{ value: 'off', label: t('pages.inbounds.form.realClientIpPresetOff') },
{ value: 'cloudflare', label: t('pages.inbounds.form.realClientIpPresetCloudflare') },
{
value: 'cloudflare',
label: t('pages.inbounds.form.realClientIpPresetCloudflare'),
},
{ value: 'proxy', label: t('pages.inbounds.form.realClientIpPresetProxyProtocol') },
]}
/>
@@ -124,7 +129,10 @@ export default function SockoptForm({
title={t('pages.inbounds.form.realClientIpProxyProtocolTransportWarn')}
/>
)}
<FormField name={['streamSettings', 'sockopt', 'mark']} label={t('pages.inbounds.form.routeMark')}>
<FormField
name={['streamSettings', 'sockopt', 'mark']}
label={t('pages.inbounds.form.routeMark')}
>
<InputNumber min={0} />
</FormField>
<FormField
@@ -139,7 +147,10 @@ export default function SockoptForm({
>
<InputNumber min={0} />
</FormField>
<FormField name={['streamSettings', 'sockopt', 'tcpMaxSeg']} label={t('pages.inbounds.form.tcpMaxSeg')}>
<FormField
name={['streamSettings', 'sockopt', 'tcpMaxSeg']}
label={t('pages.inbounds.form.tcpMaxSeg')}
>
<InputNumber min={0} />
</FormField>
<FormField
@@ -22,12 +22,29 @@ function antdValidatorToRhf(fn: (rule: unknown, value: unknown) => Promise<void>
export default function XhttpForm() {
const { t } = useTranslation();
const { control, getValues, setValue } = useFormContext();
const xhttpMode = useWatch({ control, name: 'streamSettings.xhttpSettings.mode' }) as string | undefined;
const xhttpObfsMode = !!useWatch({ control, name: 'streamSettings.xhttpSettings.xPaddingObfsMode' });
const xhttpSessionIDPlacement = useWatch({ control, name: 'streamSettings.xhttpSettings.sessionIDPlacement' }) as string | undefined;
const xhttpSessionIDTable = useWatch({ control, name: 'streamSettings.xhttpSettings.sessionIDTable' });
const xhttpSeqPlacement = useWatch({ control, name: 'streamSettings.xhttpSettings.seqPlacement' }) as string | undefined;
const xhttpUplinkPlacement = useWatch({ control, name: 'streamSettings.xhttpSettings.uplinkDataPlacement' }) as string | undefined;
const xhttpMode = useWatch({ control, name: 'streamSettings.xhttpSettings.mode' }) as
| string
| undefined;
const xhttpObfsMode = !!useWatch({
control,
name: 'streamSettings.xhttpSettings.xPaddingObfsMode',
});
const xhttpSessionIDPlacement = useWatch({
control,
name: 'streamSettings.xhttpSettings.sessionIDPlacement',
}) as string | undefined;
const xhttpSessionIDTable = useWatch({
control,
name: 'streamSettings.xhttpSettings.sessionIDTable',
});
const xhttpSeqPlacement = useWatch({
control,
name: 'streamSettings.xhttpSettings.seqPlacement',
}) as string | undefined;
const xhttpUplinkPlacement = useWatch({
control,
name: 'streamSettings.xhttpSettings.uplinkDataPlacement',
}) as string | undefined;
const enableXmux = !!useWatch({ control, name: 'streamSettings.xhttpSettings.enableXmux' });
function onXmuxToggle(checked: boolean) {
@@ -60,7 +77,10 @@ export default function XhttpForm() {
<FormField name={['streamSettings', 'xhttpSettings', 'path']} label={t('path')}>
<Input />
</FormField>
<FormField name={['streamSettings', 'xhttpSettings', 'mode']} label={t('pages.inbounds.info.mode')}>
<FormField
name={['streamSettings', 'xhttpSettings', 'mode']}
label={t('pages.inbounds.info.mode')}
>
<Select
style={{ width: '50%' }}
options={(['auto', 'packet-up', 'stream-up', 'stream-one'] as const).map((m) => ({
@@ -29,44 +29,45 @@ export function useInboundFallbacks(dbInbound: DBInbound | null, dbInbounds: DBI
return;
}
setFallbacks(
(msg.obj as {
childId: number;
name?: string;
alpn?: string;
path?: string;
dest?: string;
xver?: number;
}[])
.map((r) => ({
rowKey: `fb-${++fallbackKeyRef.current}`,
childId: r.childId && r.childId > 0 ? r.childId : null,
name: r.name || '',
alpn: r.alpn || '',
path: r.path || '',
dest: r.dest || '',
xver: r.xver || 0,
})),
(
msg.obj as {
childId: number;
name?: string;
alpn?: string;
path?: string;
dest?: string;
xver?: number;
}[]
).map((r) => ({
rowKey: `fb-${++fallbackKeyRef.current}`,
childId: r.childId && r.childId > 0 ? r.childId : null,
name: r.name || '',
alpn: r.alpn || '',
path: r.path || '',
dest: r.dest || '',
xver: r.xver || 0,
})),
);
};
const saveFallbacks = async (masterId: number) => {
if (!masterId) return true;
const payload = {
fallbacks: fallbacks.filter((c) => c.childId || (c.dest ?? '').trim()).map((c, i) => ({
childId: c.childId,
name: c.name,
alpn: c.alpn,
path: c.path,
dest: c.dest,
xver: Number(c.xver) || 0,
sortOrder: i,
})),
fallbacks: fallbacks
.filter((c) => c.childId || (c.dest ?? '').trim())
.map((c, i) => ({
childId: c.childId,
name: c.name,
alpn: c.alpn,
path: c.path,
dest: c.dest,
xver: Number(c.xver) || 0,
sortOrder: i,
})),
};
const msg = await HttpUtil.post(
`/panel/api/inbounds/${masterId}/fallbacks`,
payload,
{ headers: { 'Content-Type': 'application/json' } },
);
const msg = await HttpUtil.post(`/panel/api/inbounds/${masterId}/fallbacks`, payload, {
headers: { 'Content-Type': 'application/json' },
});
return !!msg?.success;
};
@@ -104,30 +105,35 @@ export function useInboundFallbacks(dbInbound: DBInbound | null, dbInbounds: DBI
};
const addFallback = () => {
setFallbacks((prev) => [...prev, {
rowKey: `fb-${++fallbackKeyRef.current}`,
childId: null,
name: '',
alpn: '',
path: '',
dest: '',
xver: 0,
}]);
setFallbacks((prev) => [
...prev,
{
rowKey: `fb-${++fallbackKeyRef.current}`,
childId: null,
name: '',
alpn: '',
path: '',
dest: '',
xver: 0,
},
]);
};
const updateFallback = (rowKey: string, patch: Partial<FallbackRow>) => {
setFallbacks((prev) => prev.map((r) => {
if (r.rowKey !== rowKey) return r;
// When the picker selects a new child inbound and the row hasn't
// been hand-edited yet (sni/alpn/path/dest all blank, xver = 0),
// pull the SNI/ALPN/Path defaults off that child. Operators who
// intentionally typed values keep them — we only fill the empties.
if (typeof patch.childId === 'number' && patch.childId !== r.childId) {
const isPristine = !r.name && !r.alpn && !r.path && !r.dest && r.xver === 0;
if (isPristine) return { ...r, ...patch, ...deriveFallbackDefaults(patch.childId) };
}
return { ...r, ...patch };
}));
setFallbacks((prev) =>
prev.map((r) => {
if (r.rowKey !== rowKey) return r;
// When the picker selects a new child inbound and the row hasn't
// been hand-edited yet (sni/alpn/path/dest all blank, xver = 0),
// pull the SNI/ALPN/Path defaults off that child. Operators who
// intentionally typed values keep them — we only fill the empties.
if (typeof patch.childId === 'number' && patch.childId !== r.childId) {
const isPristine = !r.name && !r.alpn && !r.path && !r.dest && r.xver === 0;
if (isPristine) return { ...r, ...patch, ...deriveFallbackDefaults(patch.childId) };
}
return { ...r, ...patch };
}),
);
};
const removeFallback = (idx: number) => {
@@ -31,7 +31,15 @@ interface UseSecurityActionsArgs {
* writes the result back into the form. Lifted out of InboundFormModal so
* the modal body stays focused on orchestration.
*/
export function useSecurityActions({ methods, setSaving, messageApi, modal, nodeId, setScanResult, setScanning }: UseSecurityActionsArgs) {
export function useSecurityActions({
methods,
setSaving,
messageApi,
modal,
nodeId,
setScanResult,
setScanning,
}: UseSecurityActionsArgs) {
const { t } = useTranslation();
const setValue = methods.setValue as unknown as (name: string, value: unknown) => void;
const getValues = methods.getValues as unknown as (name?: string) => unknown;
@@ -94,7 +102,9 @@ export function useSecurityActions({ methods, setSaving, messageApi, modal, node
};
const scanRealityTarget = async (allowPrivate = false) => {
const target = ((getValues('streamSettings.realitySettings.target') as string | undefined) ?? '').trim();
const target = (
(getValues('streamSettings.realitySettings.target') as string | undefined) ?? ''
).trim();
if (!target) {
messageApi.warning(t('pages.inbounds.form.realityTargetRequired'));
return;
@@ -105,7 +115,8 @@ export function useSecurityActions({ methods, setSaving, messageApi, modal, node
* must too — a fronting proxy answers a bare target name with its default
* certificate, which then reads as an untrusted target.
*/
const serverNames = (getValues('streamSettings.realitySettings.serverNames') as string[] | undefined) ?? [];
const serverNames =
(getValues('streamSettings.realitySettings.serverNames') as string[] | undefined) ?? [];
const sni = (serverNames.find((n) => typeof n === 'string' && n.trim() !== '') ?? '').trim();
setScanning(true);
try {
@@ -128,7 +139,9 @@ export function useSecurityActions({ methods, setSaving, messageApi, modal, node
if (r.privateTarget && !allowPrivate) {
modal.confirm({
title: t('pages.inbounds.form.scanPrivateConfirmTitle'),
content: t('pages.inbounds.form.scanPrivateConfirmContent', { target: r.target || target }),
content: t('pages.inbounds.form.scanPrivateConfirmContent', {
target: r.target || target,
}),
okText: t('confirm'),
cancelText: t('cancel'),
onOk: () => scanRealityTarget(true),
@@ -163,15 +176,15 @@ export function useSecurityActions({ methods, setSaving, messageApi, modal, node
const randomizeShortIds = () => {
setValue(
'streamSettings.realitySettings.shortIds',
RandomUtil.randomShortIds().split(',').map((s) => s.trim()).filter(Boolean),
RandomUtil.randomShortIds()
.split(',')
.map((s) => s.trim())
.filter(Boolean),
);
};
const randomizeSpiderX = () => {
setValue(
'streamSettings.realitySettings.settings.spiderX',
`/${RandomUtil.randomSeq(15)}`,
);
setValue('streamSettings.realitySettings.settings.spiderX', `/${RandomUtil.randomSeq(15)}`);
};
const getNewEchCert = async () => {
@@ -206,7 +219,9 @@ export function useSecurityActions({ methods, setSaving, messageApi, modal, node
}>;
const first = certs[0];
const certFile = first?.certificateFile?.trim() ?? '';
const certContent = Array.isArray(first?.certificate) ? first.certificate.join('\n').trim() : '';
const certContent = Array.isArray(first?.certificate)
? first.certificate.join('\n').trim()
: '';
if (!certFile && !certContent) {
messageApi.warning(t('pages.inbounds.setDefaultCertEmpty'));
return;
@@ -220,9 +235,10 @@ export function useSecurityActions({ methods, setSaving, messageApi, modal, node
}
const hashes = (msg.obj as string[] | undefined) ?? [];
if (hashes.length === 0) return;
const current = (getValues(
'streamSettings.tlsSettings.settings.pinnedPeerCertSha256',
) as string[] | undefined) ?? [];
const current =
(getValues('streamSettings.tlsSettings.settings.pinnedPeerCertSha256') as
| string[]
| undefined) ?? [];
const merged = Array.from(new Set([...current, ...hashes]));
setValue('streamSettings.tlsSettings.settings.pinnedPeerCertSha256', merged);
} finally {
@@ -236,7 +252,9 @@ export function useSecurityActions({ methods, setSaving, messageApi, modal, node
* hold the cert file (a CDN front / external endpoint).
*/
const pinFromRemote = async () => {
const server = ((getValues('streamSettings.tlsSettings.serverName') as string | undefined) ?? '').trim();
const server = (
(getValues('streamSettings.tlsSettings.serverName') as string | undefined) ?? ''
).trim();
if (!server) {
messageApi.warning(t('pages.inbounds.form.pinFromRemoteNoSni'));
return;
@@ -257,9 +275,10 @@ export function useSecurityActions({ methods, setSaving, messageApi, modal, node
}
const hashes = (msg.obj as string[] | undefined) ?? [];
if (hashes.length === 0) return;
const current = (getValues(
'streamSettings.tlsSettings.settings.pinnedPeerCertSha256',
) as string[] | undefined) ?? [];
const current =
(getValues('streamSettings.tlsSettings.settings.pinnedPeerCertSha256') as
| string[]
| undefined) ?? [];
const merged = Array.from(new Set([...current, ...hashes]));
setValue('streamSettings.tlsSettings.settings.pinnedPeerCertSha256', merged);
} finally {
@@ -274,9 +293,10 @@ export function useSecurityActions({ methods, setSaving, messageApi, modal, node
* Node-assigned inbounds run on the node, so their cert files must be the
* node's own paths (fetched through the central panel), not this panel's.
*/
const msg = typeof nodeId === 'number'
? await HttpUtil.get(`/panel/api/nodes/webCert/${nodeId}`, undefined, { silent: true })
: await HttpUtil.post('/panel/api/setting/all', undefined, { silent: true });
const msg =
typeof nodeId === 'number'
? await HttpUtil.get(`/panel/api/nodes/webCert/${nodeId}`, undefined, { silent: true })
: await HttpUtil.post('/panel/api/setting/all', undefined, { silent: true });
if (!msg?.success) {
messageApi.warning(msg?.msg || t('pages.inbounds.setDefaultCertEmpty'));
return;
@@ -290,24 +310,15 @@ export function useSecurityActions({ methods, setSaving, messageApi, modal, node
`streamSettings.tlsSettings.certificates.${certName}.certificateFile`,
obj.webCertFile ?? '',
);
setValue(
`streamSettings.tlsSettings.certificates.${certName}.keyFile`,
obj.webKeyFile ?? '',
);
setValue(`streamSettings.tlsSettings.certificates.${certName}.keyFile`, obj.webKeyFile ?? '');
} finally {
setSaving(false);
}
};
const clearCertFiles = (certName: number) => {
setValue(
`streamSettings.tlsSettings.certificates.${certName}.certificateFile`,
'',
);
setValue(
`streamSettings.tlsSettings.certificates.${certName}.keyFile`,
'',
);
setValue(`streamSettings.tlsSettings.certificates.${certName}.certificateFile`, '');
setValue(`streamSettings.tlsSettings.certificates.${certName}.keyFile`, '');
};
const onSecurityChange = async (next: string) => {
@@ -323,7 +334,10 @@ export function useSecurityActions({ methods, setSaving, messageApi, modal, node
const reality = RealityStreamSettingsSchema.parse({}) as Record<string, unknown>;
reality.target = '';
reality.serverNames = [];
reality.shortIds = RandomUtil.randomShortIds().split(',').map((s) => s.trim()).filter(Boolean);
reality.shortIds = RandomUtil.randomShortIds()
.split(',')
.map((s) => s.trim())
.filter(Boolean);
cleaned.realitySettings = reality;
}
setValue('streamSettings', cleaned);
@@ -190,7 +190,9 @@
color: var(--ant-color-primary);
text-decoration: underline;
text-decoration-color: color-mix(in srgb, var(--ant-color-primary) 40%, transparent);
transition: background 120ms ease, text-decoration-color 120ms ease;
transition:
background 120ms ease,
text-decoration-color 120ms ease;
}
.link-panel-anchor:hover {
File diff suppressed because it is too large Load Diff
+29 -10
View File
@@ -27,7 +27,11 @@ function readHeader(headers: unknown, name: string): string {
const needle = name.toLowerCase();
if (Array.isArray(headers)) {
for (const h of headers) {
if (h && typeof h === 'object' && String((h as { name?: string }).name ?? '').toLowerCase() === needle) {
if (
h &&
typeof h === 'object' &&
String((h as { name?: string }).name ?? '').toLowerCase() === needle
) {
return String((h as { value?: unknown }).value ?? '');
}
}
@@ -46,20 +50,22 @@ function readHeader(headers: unknown, name: string): string {
function readNetworkHost(stream: Record<string, unknown>, network: string): string | null {
switch (network) {
case 'tcp': {
const tcp = stream.tcpSettings as { header?: { request?: { headers?: unknown } } } | undefined;
const tcp = stream.tcpSettings as
| { header?: { request?: { headers?: unknown } } }
| undefined;
return readHeader(tcp?.header?.request?.headers, 'host');
}
case 'ws': {
const ws = stream.wsSettings as { host?: string; headers?: unknown } | undefined;
return (ws?.host && ws.host.length > 0) ? ws.host : readHeader(ws?.headers, 'host');
return ws?.host && ws.host.length > 0 ? ws.host : readHeader(ws?.headers, 'host');
}
case 'httpupgrade': {
const hu = stream.httpupgradeSettings as { host?: string; headers?: unknown } | undefined;
return (hu?.host && hu.host.length > 0) ? hu.host : readHeader(hu?.headers, 'host');
return hu?.host && hu.host.length > 0 ? hu.host : readHeader(hu?.headers, 'host');
}
case 'xhttp': {
const xh = stream.xhttpSettings as { host?: string; headers?: unknown } | undefined;
return (xh?.host && xh.host.length > 0) ? xh.host : readHeader(xh?.headers, 'host');
return xh?.host && xh.host.length > 0 ? xh.host : readHeader(xh?.headers, 'host');
}
default:
return null;
@@ -90,13 +96,17 @@ export function buildInboundInfo(dbInbound: DBInboundLike): InboundInfo {
const security = (stream.security as string | undefined) ?? 'none';
const clients = Array.isArray(settings.clients) ? (settings.clients as ClientSetting[]) : [];
const xhttpSettings = stream.xhttpSettings as { mode?: string } | undefined;
const grpcSettings = stream.grpcSettings as { multiMode?: boolean; serviceName?: string } | undefined;
const grpcSettings = stream.grpcSettings as
| { multiMode?: boolean; serviceName?: string }
| undefined;
let serverName = '';
if (security === 'tls') {
const tls = stream.tlsSettings as { sni?: string; serverName?: string } | undefined;
serverName = tls?.sni ?? tls?.serverName ?? '';
} else if (security === 'reality') {
const reality = stream.realitySettings as { serverNames?: string[]; serverName?: string } | undefined;
const reality = stream.realitySettings as
| { serverNames?: string[]; serverName?: string }
| undefined;
if (Array.isArray(reality?.serverNames)) {
serverName = reality.serverNames.join(', ');
} else if (reality?.serverName) {
@@ -158,7 +168,12 @@ export function statsColor(stats: ClientStats, trafficDiff: number) {
export function formatIpInfo(record: unknown) {
if (record == null) return '';
if (typeof record === 'string' || typeof record === 'number') return String(record);
const r = record as { ip?: string; IP?: string; timestamp?: number | string; Timestamp?: number | string };
const r = record as {
ip?: string;
IP?: string;
timestamp?: number | string;
Timestamp?: number | string;
};
const ip = r.ip || r.IP || '';
const ts = r.timestamp || r.Timestamp || 0;
if (!ip) return String(record);
@@ -166,8 +181,12 @@ export function formatIpInfo(record: unknown) {
const date = new Date(Number(ts) * 1000);
const timeStr = date
.toLocaleString('en-GB', {
year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
})
.replace(',', '');
+119 -67
View File
@@ -80,11 +80,12 @@ export default function InboundList({
else if (nodeFilter !== 'all') list = list.filter((ib) => ib.nodeId === nodeFilter);
const q = searchKey.trim().toLowerCase();
if (!q) return list;
return list.filter((ib) => (
(ib.remark || '').toLowerCase().includes(q)
|| String(ib.port).includes(q)
|| (ib.protocol || '').toLowerCase().includes(q)
));
return list.filter(
(ib) =>
(ib.remark || '').toLowerCase().includes(q) ||
String(ib.port).includes(q) ||
(ib.protocol || '').toLowerCase().includes(q),
);
}, [dbInbounds, nodeFilter, searchKey]);
const onSwitchEnable = useCallback(async (dbInbound: DBInboundRecord, next: boolean) => {
@@ -113,17 +114,23 @@ export default function InboundList({
const toggleSelect = useCallback((id: number, checked: boolean) => {
setSelectedRowKeys((prev) => {
const next = new Set(prev);
if (checked) next.add(id); else next.delete(id);
if (checked) next.add(id);
else next.delete(id);
return Array.from(next);
});
}, []);
const selectAll = useCallback((checked: boolean) => {
setSelectedRowKeys(checked ? visibleInbounds.map((i) => i.id) : []);
}, [visibleInbounds]);
const selectAll = useCallback(
(checked: boolean) => {
setSelectedRowKeys(checked ? visibleInbounds.map((i) => i.id) : []);
},
[visibleInbounds],
);
const allSelected = visibleInbounds.length > 0 && selectedRowKeys.length === visibleInbounds.length;
const someSelected = selectedRowKeys.length > 0 && selectedRowKeys.length < visibleInbounds.length;
const allSelected =
visibleInbounds.length > 0 && selectedRowKeys.length === visibleInbounds.length;
const someSelected =
selectedRowKeys.length > 0 && selectedRowKeys.length < visibleInbounds.length;
const handleBulkDelete = useCallback(async () => {
const ok = await onBulkDelete(selectedRowKeys);
@@ -159,9 +166,19 @@ export default function InboundList({
{ key: 'import', icon: <ImportOutlined />, label: t('pages.inbounds.importInbound') },
{ key: 'export', icon: <ExportOutlined />, label: t('pages.inbounds.export') },
...(subEnable
? [{ key: 'subs', icon: <ExportOutlined />, label: `${t('pages.inbounds.export')}${t('pages.settings.subSettings')}` }]
? [
{
key: 'subs',
icon: <ExportOutlined />,
label: `${t('pages.inbounds.export')}${t('pages.settings.subSettings')}`,
},
]
: []),
{ key: 'resetInbounds', icon: <ReloadOutlined />, label: t('pages.inbounds.resetAllTraffic') },
{
key: 'resetInbounds',
icon: <ReloadOutlined />,
label: t('pages.inbounds.resetAllTraffic'),
},
],
onClick: ({ key }) => onGeneralAction(key as GeneralAction),
};
@@ -169,13 +186,22 @@ export default function InboundList({
return (
<Card
hoverable
title={(
title={
<Space>
<Button type="primary" onClick={onAddInbound} icon={<PlusOutlined />} aria-label={t('pages.inbounds.addInbound')}>
<Button
type="primary"
onClick={onAddInbound}
icon={<PlusOutlined />}
aria-label={t('pages.inbounds.addInbound')}
>
{!isMobile && t('pages.inbounds.addInbound')}
</Button>
<Dropdown trigger={['click']} menu={generalActionsMenu}>
<Button type="primary" icon={<MenuOutlined />} aria-label={t('pages.inbounds.generalActions')}>
<Button
type="primary"
icon={<MenuOutlined />}
aria-label={t('pages.inbounds.generalActions')}
>
{!isMobile && t('pages.inbounds.generalActions')}
</Button>
</Dropdown>
@@ -201,16 +227,26 @@ export default function InboundList({
/>
{selectedRowKeys.length > 0 && (
<>
<Tag color="blue" closable onClose={() => setSelectedRowKeys([])} style={{ marginInlineEnd: 0 }}>
<Tag
color="blue"
closable
onClose={() => setSelectedRowKeys([])}
style={{ marginInlineEnd: 0 }}
>
{t('pages.inbounds.selectedCount', { count: selectedRowKeys.length })}
</Tag>
<Button danger icon={<DeleteOutlined />} onClick={handleBulkDelete} aria-label={t('delete')}>
<Button
danger
icon={<DeleteOutlined />}
onClick={handleBulkDelete}
aria-label={t('delete')}
>
{!isMobile && t('delete')}
</Button>
</>
)}
</Space>
)}
}
>
<Space orientation="vertical" style={{ width: '100%' }}>
{isMobile ? (
@@ -222,57 +258,73 @@ export default function InboundList({
</div>
) : (
<>
<div className="card-bulk-bar">
<Checkbox
checked={allSelected}
indeterminate={someSelected}
onChange={(e) => selectAll(e.target.checked)}
>
{t('pages.inbounds.selectAll')}
</Checkbox>
{selectedRowKeys.length > 0 && (
<span className="bulk-count">{selectedRowKeys.length}</span>
)}
</div>
{visibleInbounds.map((record) => (
<div key={record.id} className={`inbound-card${selectedRowKeys.includes(record.id) ? ' is-selected' : ''}`}>
<div className="card-head">
<Checkbox
checked={selectedRowKeys.includes(record.id)}
onChange={(e) => toggleSelect(record.id, e.target.checked)}
/>
<span className="card-id">#{record.id}</span>
<span className="tag-name">{record.remark}</span>
<div className="card-actions">
<Tooltip title={t('pages.inbounds.inboundInfo')}>
<InfoCircleOutlined
className="row-action-trigger"
role="button"
tabIndex={0}
aria-label={t('pages.inbounds.inboundInfo')}
onClick={() => setStatsRecord(record)}
onKeyDown={activateOnKey(() => setStatsRecord(record))}
/>
</Tooltip>
<Switch
checked={record.enable}
size="small"
onChange={(next) => onSwitchEnable(record, next)}
<div className="card-bulk-bar">
<Checkbox
checked={allSelected}
indeterminate={someSelected}
onChange={(e) => selectAll(e.target.checked)}
>
{t('pages.inbounds.selectAll')}
</Checkbox>
{selectedRowKeys.length > 0 && (
<span className="bulk-count">{selectedRowKeys.length}</span>
)}
</div>
{visibleInbounds.map((record) => (
<div
key={record.id}
className={`inbound-card${selectedRowKeys.includes(record.id) ? ' is-selected' : ''}`}
>
<div className="card-head">
<Checkbox
checked={selectedRowKeys.includes(record.id)}
onChange={(e) => toggleSelect(record.id, e.target.checked)}
/>
<Dropdown
trigger={['click']}
placement="bottomRight"
menu={{
items: buildRowActionsMenu({ record, subEnable, t, isMobile: true, hasClients: (clientCount[record.id]?.clients || 0) > 0 }),
onClick: ({ key }) => onRowAction({ key: key as RowAction, dbInbound: record }),
}}
>
<Button type="text" size="small" className="row-action-trigger" icon={<MoreOutlined />} aria-label={t('more')} />
</Dropdown>
<span className="card-id">#{record.id}</span>
<span className="tag-name">{record.remark}</span>
<div className="card-actions">
<Tooltip title={t('pages.inbounds.inboundInfo')}>
<InfoCircleOutlined
className="row-action-trigger"
role="button"
tabIndex={0}
aria-label={t('pages.inbounds.inboundInfo')}
onClick={() => setStatsRecord(record)}
onKeyDown={activateOnKey(() => setStatsRecord(record))}
/>
</Tooltip>
<Switch
checked={record.enable}
size="small"
onChange={(next) => onSwitchEnable(record, next)}
/>
<Dropdown
trigger={['click']}
placement="bottomRight"
menu={{
items: buildRowActionsMenu({
record,
subEnable,
t,
isMobile: true,
hasClients: (clientCount[record.id]?.clients || 0) > 0,
}),
onClick: ({ key }) =>
onRowAction({ key: key as RowAction, dbInbound: record }),
}}
>
<Button
type="text"
size="small"
className="row-action-trigger"
icon={<MoreOutlined />}
aria-label={t('more')}
/>
</Dropdown>
</div>
</div>
</div>
</div>
))}
))}
</>
)}
</div>
@@ -17,7 +17,11 @@ interface InboundSpeedTagProps {
}
// Blue "↑ up / ↓ down" rate tag, optionally with a stacked breakdown tooltip.
export function InboundSpeedTag({ speed, withTooltip = false, tableCell = false }: InboundSpeedTagProps) {
export function InboundSpeedTag({
speed,
withTooltip = false,
tableCell = false,
}: InboundSpeedTagProps) {
const tag = (
<Tag
color="blue"
@@ -25,19 +29,18 @@ export function InboundSpeedTag({ speed, withTooltip = false, tableCell = false
style={tableCell ? SPEED_TAG_STYLE : undefined}
>
{SizeFormatter.speedFormat(speed.up)}
{' / '}
{SizeFormatter.speedFormat(speed.down)}
{' / '} {SizeFormatter.speedFormat(speed.down)}
</Tag>
);
if (!withTooltip) return tag;
return (
<Tooltip
title={(
title={
<div>
<div> {SizeFormatter.speedFormat(speed.up)}</div>
<div> {SizeFormatter.speedFormat(speed.down)}</div>
</div>
)}
}
>
{tag}
</Tooltip>
@@ -55,36 +55,32 @@ export default function InboundStatsModal({
<div className="stat-row">
<span className="stat-label">{t('pages.inbounds.protocol')}</span>
<Tag color="purple">{record.protocol}</Tag>
{(record.isWireguard || record.isHysteria) && (
<Tag color="green">UDP</Tag>
)}
{record.isSS && (() => {
const stream = readStreamHints(record.streamSettings);
return (
<>
<Tag color="green">{shadowsocksNetworkLabel(record.settings)}</Tag>
{stream.isTls && <Tag color="blue">TLS</Tag>}
</>
);
})()}
{record.isTunnel && (
<Tag color="green">{tunnelNetworkLabel(record.settings)}</Tag>
)}
{record.isMixed && (
<Tag color="green">{mixedNetworkLabel(record.settings)}</Tag>
)}
{(record.isVMess || record.isVLess || record.isTrojan) && (() => {
const stream = readStreamHints(record.streamSettings);
const l4 = networkL4(stream.network);
return (
<>
<Tag color="green">{networkLabel(stream.network)}</Tag>
{l4 && <Tag color="green">{l4}</Tag>}
{stream.isTls && <Tag color="blue">TLS</Tag>}
{stream.isReality && <Tag color="blue">Reality</Tag>}
</>
);
})()}
{(record.isWireguard || record.isHysteria) && <Tag color="green">UDP</Tag>}
{record.isSS &&
(() => {
const stream = readStreamHints(record.streamSettings);
return (
<>
<Tag color="green">{shadowsocksNetworkLabel(record.settings)}</Tag>
{stream.isTls && <Tag color="blue">TLS</Tag>}
</>
);
})()}
{record.isTunnel && <Tag color="green">{tunnelNetworkLabel(record.settings)}</Tag>}
{record.isMixed && <Tag color="green">{mixedNetworkLabel(record.settings)}</Tag>}
{(record.isVMess || record.isVLess || record.isTrojan) &&
(() => {
const stream = readStreamHints(record.streamSettings);
const l4 = networkL4(stream.network);
return (
<>
<Tag color="green">{networkLabel(stream.network)}</Tag>
{l4 && <Tag color="green">{l4}</Tag>}
{stream.isTls && <Tag color="blue">TLS</Tag>}
{stream.isReality && <Tag color="blue">Reality</Tag>}
</>
);
})()}
</div>
<div className="stat-row">
<span className="stat-label">{t('pages.inbounds.port')}</span>
@@ -107,8 +103,7 @@ export default function InboundStatsModal({
<div className="stat-row">
<span className="stat-label">{t('pages.inbounds.traffic')}</span>
<Tag color={ColorUtils.usageColor(record.up + record.down, trafficDiff, record.total)}>
{SizeFormatter.sizeFormat(record.up + record.down)} /
{' '}
{SizeFormatter.sizeFormat(record.up + record.down)} /{' '}
{record.total > 0 ? SizeFormatter.sizeFormat(record.total) : <InfinityIcon />}
</Tag>
</div>
@@ -125,15 +120,23 @@ export default function InboundStatsModal({
{clientCount[record.id] && (
<div className="stat-row">
<span className="stat-label">{t('clients')}</span>
<Tag color="green" className="client-count-tag">{clientCount[record.id].clients}</Tag>
<Tag color="green" className="client-count-tag">
{clientCount[record.id].clients}
</Tag>
{clientCount[record.id].online.length > 0 && (
<Tag color="blue">{clientCount[record.id].online.length} {t('online')}</Tag>
<Tag color="blue">
{clientCount[record.id].online.length} {t('online')}
</Tag>
)}
{clientCount[record.id].depleted.length > 0 && (
<Tag color="red">{clientCount[record.id].depleted.length} {t('depleted')}</Tag>
<Tag color="red">
{clientCount[record.id].depleted.length} {t('depleted')}
</Tag>
)}
{clientCount[record.id].expiring.length > 0 && (
<Tag color="orange">{clientCount[record.id].expiring.length} {t('depletingSoon')}</Tag>
<Tag color="orange">
{clientCount[record.id].expiring.length} {t('depletingSoon')}
</Tag>
)}
</div>
)}
@@ -144,7 +147,9 @@ export default function InboundStatsModal({
{IntlUtil.formatRelativeTime(record.expiryTime)}
</Tag>
) : (
<Tag color="purple"><InfinityIcon /></Tag>
<Tag color="purple">
<InfinityIcon />
</Tag>
)}
</div>
</div>
+69 -11
View File
@@ -26,7 +26,19 @@ interface RowActionsMenuProps {
isMobile?: boolean;
}
export function buildRowActionsMenu({ record, subEnable, t, isMobile, hasClients }: { record: DBInboundRecord; subEnable: boolean; t: (k: string) => string; isMobile?: boolean; hasClients?: boolean }): MenuProps['items'] {
export function buildRowActionsMenu({
record,
subEnable,
t,
isMobile,
hasClients,
}: {
record: DBInboundRecord;
subEnable: boolean;
t: (k: string) => string;
isMobile?: boolean;
hasClients?: boolean;
}): MenuProps['items'] {
const items: MenuProps['items'] = [];
if (isMobile) {
items.push({ key: 'edit', icon: <EditOutlined />, label: t('edit') });
@@ -44,20 +56,53 @@ export function buildRowActionsMenu({ record, subEnable, t, isMobile, hasClients
});
}
} else {
items.push({ key: 'showInfo', icon: <InfoCircleOutlined />, label: t('pages.inbounds.inboundInfo') });
items.push({
key: 'showInfo',
icon: <InfoCircleOutlined />,
label: t('pages.inbounds.inboundInfo'),
});
}
items.push({ key: 'clipboard', icon: <CopyOutlined />, label: t('pages.inbounds.exportInbound') });
items.push({ key: 'resetTraffic', icon: <RetweetOutlined />, label: t('pages.inbounds.resetTraffic') });
items.push({
key: 'clipboard',
icon: <CopyOutlined />,
label: t('pages.inbounds.exportInbound'),
});
items.push({
key: 'resetTraffic',
icon: <RetweetOutlined />,
label: t('pages.inbounds.resetTraffic'),
});
items.push({ key: 'clone', icon: <BlockOutlined />, label: t('pages.inbounds.clone') });
if (isInboundMultiUser(record)) {
items.push({ key: 'attachExisting', icon: <UsergroupAddOutlined />, label: t('pages.inbounds.attachExistingClients') });
items.push({
key: 'attachExisting',
icon: <UsergroupAddOutlined />,
label: t('pages.inbounds.attachExistingClients'),
});
}
if (isInboundMultiUser(record) && hasClients) {
items.push({ key: 'attachClients', icon: <UsergroupAddOutlined />, label: t('pages.inbounds.attachClients') });
items.push({ key: 'detachClients', icon: <UsergroupDeleteOutlined />, label: t('pages.inbounds.detachClients') });
items.push({ key: 'addToGroup', icon: <TagsOutlined />, label: t('pages.inbounds.addClientsToGroup') });
items.push({
key: 'attachClients',
icon: <UsergroupAddOutlined />,
label: t('pages.inbounds.attachClients'),
});
items.push({
key: 'detachClients',
icon: <UsergroupDeleteOutlined />,
label: t('pages.inbounds.detachClients'),
});
items.push({
key: 'addToGroup',
icon: <TagsOutlined />,
label: t('pages.inbounds.addClientsToGroup'),
});
items.push({ type: 'divider' });
items.push({ key: 'delAllClients', icon: <UsergroupDeleteOutlined />, danger: true, label: t('pages.inbounds.delAllClients') });
items.push({
key: 'delAllClients',
icon: <UsergroupDeleteOutlined />,
danger: true,
label: t('pages.inbounds.delAllClients'),
});
} else {
items.push({ type: 'divider' });
}
@@ -69,7 +114,14 @@ export function RowActionsCell({ record, subEnable, hasClients, onClick }: RowAc
const { t } = useTranslation();
return (
<div className="action-buttons">
<Button type="text" size="small" style={{ fontSize: 16 }} icon={<EditOutlined />} aria-label={t('edit')} onClick={() => onClick('edit')} />
<Button
type="text"
size="small"
style={{ fontSize: 16 }}
icon={<EditOutlined />}
aria-label={t('edit')}
onClick={() => onClick('edit')}
/>
<Dropdown
trigger={['click']}
menu={{
@@ -77,7 +129,13 @@ export function RowActionsCell({ record, subEnable, hasClients, onClick }: RowAc
onClick: ({ key }) => onClick(key as RowAction),
}}
>
<Button type="text" size="small" style={{ fontSize: 16 }} icon={<MoreOutlined />} aria-label={t('more')} />
<Button
type="text"
size="small"
style={{ fontSize: 16 }}
icon={<MoreOutlined />}
aria-label={t('more')}
/>
</Dropdown>
</div>
);
+21 -6
View File
@@ -20,9 +20,12 @@ export function networkLabel(network: string): string {
const n = (network || '').toLowerCase();
if (!n) return 'TCP';
switch (n) {
case 'httpupgrade': return 'HTTPUpgrade';
case 'splithttp': return 'SplitHTTP';
case 'xhttp': return 'XHTTP';
case 'httpupgrade':
return 'HTTPUpgrade';
case 'splithttp':
return 'SplitHTTP';
case 'xhttp':
return 'XHTTP';
}
return n.toUpperCase();
}
@@ -42,7 +45,11 @@ export function networkL4(network: string): 'UDP' | '' {
// the L4 transport list independent of streamSettings. Returns a
// comma-separated label.
export function commaNetworkLabel(raw: string): string {
const parts = (raw || 'tcp').toLowerCase().split(',').map((p) => p.trim()).filter(Boolean);
const parts = (raw || 'tcp')
.toLowerCase()
.split(',')
.map((p) => p.trim())
.filter(Boolean);
if (parts.length === 0) return 'TCP';
return parts.map(networkLabel).join(',');
}
@@ -62,8 +69,16 @@ export function mixedNetworkLabel(settings: unknown): string {
return st.udp ? 'TCP,UDP' : 'TCP';
}
export function readSettings(settings: unknown): { method?: string; network?: string; allowedNetwork?: string } {
return coerceInboundJsonField(settings) as { method?: string; network?: string; allowedNetwork?: string };
export function readSettings(settings: unknown): {
method?: string;
network?: string;
allowedNetwork?: string;
} {
return coerceInboundJsonField(settings) as {
method?: string;
network?: string;
allowedNetwork?: string;
};
}
export function isInboundMultiUser(record: { protocol: string; settings: unknown }): boolean {
@@ -10,7 +10,11 @@ import type { NodeRecord } from '@/api/queries/useNodesQuery';
import { coerceInboundJsonField } from '@/models/dbinbound';
import { RowActionsCell } from './RowActions';
import { SPEED_COLUMN_WIDTH, SPEED_TAG_CLASS_NAME, SPEED_TAG_STYLE } from '@/components/utility/speedTagStyle';
import {
SPEED_COLUMN_WIDTH,
SPEED_TAG_CLASS_NAME,
SPEED_TAG_STYLE,
} from '@/components/utility/speedTagStyle';
import { InboundSpeedTag, isActiveSpeed } from './InboundSpeedTag';
import {
readStreamHints,
@@ -53,27 +57,24 @@ export function useInboundColumns({
const { datepicker } = useDatepicker();
return useMemo(() => {
const compareText = (a: string | undefined | null, b: string | undefined | null) => (
(a || '').localeCompare(b || '', undefined, { numeric: true, sensitivity: 'base' })
);
const compareText = (a: string | undefined | null, b: string | undefined | null) =>
(a || '').localeCompare(b || '', undefined, { numeric: true, sensitivity: 'base' });
const nodeName = (record: DBInboundRecord) => {
if (record.nodeId == null) return t('pages.inbounds.localPanel');
return nodesById.get(record.nodeId)?.name || `node #${record.nodeId}`;
};
const clientTotal = (record: DBInboundRecord) => (
(clientCount[record.id] || fallbackClientCount(record))?.clients ?? 0
);
const clientTotal = (record: DBInboundRecord) =>
(clientCount[record.id] || fallbackClientCount(record))?.clients ?? 0;
const speedTotal = (record: DBInboundRecord) => {
const speed = inboundSpeed[record.id];
return speed ? speed.up + speed.down : 0;
};
const expirySortValue = (record: DBInboundRecord) => (
record.expiryTime > 0 ? record.expiryTime : Number.MAX_SAFE_INTEGER
);
const expirySortValue = (record: DBInboundRecord) =>
record.expiryTime > 0 ? record.expiryTime : Number.MAX_SAFE_INTEGER;
const fallbackClientCount = (record: DBInboundRecord): ClientCountEntry | null => {
const settings = coerceInboundJsonField(record.settings) as {
@@ -126,10 +127,7 @@ export function useInboundColumns({
align: 'center',
width: 80,
render: (_, record) => (
<Switch
checked={record.enable}
onChange={(next) => onSwitchEnable(record, next)}
/>
<Switch checked={record.enable} onChange={(next) => onSwitchEnable(record, next)} />
),
},
];
@@ -160,9 +158,7 @@ export function useInboundColumns({
if (!node) {
return <Tag color="orange">node #{record.nodeId}</Tag>;
}
return (
<Tag color={node.status === 'online' ? 'blue' : 'red'}>{node.name}</Tag>
);
return <Tag color={node.status === 'online' ? 'blue' : 'red'}>{node.name}</Tag>;
},
});
}
@@ -198,24 +194,68 @@ export function useInboundColumns({
width: 190,
sorter: (a, b) => compareText(a.protocol, b.protocol),
render: (_, record) => {
const tags: ReactElement[] = [<Tag key="p" color="purple">{record.protocol}</Tag>];
const tags: ReactElement[] = [
<Tag key="p" color="purple">
{record.protocol}
</Tag>,
];
if (record.isWireguard || record.isHysteria) {
tags.push(<Tag key="n" color="green">UDP</Tag>);
tags.push(
<Tag key="n" color="green">
UDP
</Tag>,
);
} else if (record.isSS) {
const stream = readStreamHints(record.streamSettings);
tags.push(<Tag key="n" color="green">{shadowsocksNetworkLabel(record.settings)}</Tag>);
if (stream.isTls) tags.push(<Tag key="tls" color="blue">TLS</Tag>);
tags.push(
<Tag key="n" color="green">
{shadowsocksNetworkLabel(record.settings)}
</Tag>,
);
if (stream.isTls)
tags.push(
<Tag key="tls" color="blue">
TLS
</Tag>,
);
} else if (record.isTunnel) {
tags.push(<Tag key="n" color="green">{tunnelNetworkLabel(record.settings)}</Tag>);
tags.push(
<Tag key="n" color="green">
{tunnelNetworkLabel(record.settings)}
</Tag>,
);
} else if (record.isMixed) {
tags.push(<Tag key="n" color="green">{mixedNetworkLabel(record.settings)}</Tag>);
tags.push(
<Tag key="n" color="green">
{mixedNetworkLabel(record.settings)}
</Tag>,
);
} else if (record.isVMess || record.isVLess || record.isTrojan) {
const stream = readStreamHints(record.streamSettings);
tags.push(<Tag key="n" color="green">{networkLabel(stream.network)}</Tag>);
tags.push(
<Tag key="n" color="green">
{networkLabel(stream.network)}
</Tag>,
);
const l4 = networkL4(stream.network);
if (l4) tags.push(<Tag key="l4" color="green">{l4}</Tag>);
if (stream.isTls) tags.push(<Tag key="tls" color="blue">TLS</Tag>);
if (stream.isReality) tags.push(<Tag key="reality" color="blue">Reality</Tag>);
if (l4)
tags.push(
<Tag key="l4" color="green">
{l4}
</Tag>,
);
if (stream.isTls)
tags.push(
<Tag key="tls" color="blue">
TLS
</Tag>,
);
if (stream.isReality)
tags.push(
<Tag key="reality" color="blue">
Reality
</Tag>,
);
}
return <div className="protocol-tags">{tags}</div>;
},
@@ -231,57 +271,97 @@ export function useInboundColumns({
if (!cc) return null;
return (
<>
<Tag className="client-count-tag" style={{ margin: 0, marginRight: 4, padding: '0 2px' }}>
<Tag
className="client-count-tag"
style={{ margin: 0, marginRight: 4, padding: '0 2px' }}
>
<TeamOutlined /> {cc.clients}
</Tag>
{cc.active.length > 0 ? (
<Popover
title={t('subscription.active')}
content={(
content={
<div className="client-email-list">
{cc.active.map((e) => <div key={e}>{e}</div>)}
{cc.active.map((e) => (
<div key={e}>{e}</div>
))}
</div>
)}
}
>
<Tag color="green" className="client-count-tag" style={{ margin: 0, marginRight: 4, padding: '0 2px' }}>{cc.active.length}</Tag>
<Tag
color="green"
className="client-count-tag"
style={{ margin: 0, marginRight: 4, padding: '0 2px' }}
>
{cc.active.length}
</Tag>
</Popover>
) : (
<Tag color="green" className="client-count-tag" style={{ margin: 0, marginRight: 4, padding: '0 2px' }}>0</Tag>
<Tag
color="green"
className="client-count-tag"
style={{ margin: 0, marginRight: 4, padding: '0 2px' }}
>
0
</Tag>
)}
{cc.deactive.length > 0 && (
<Popover
title={t('disabled')}
content={(
content={
<div className="client-email-list">
{cc.deactive.map((e) => <div key={e}>{e}</div>)}
{cc.deactive.map((e) => (
<div key={e}>{e}</div>
))}
</div>
)}
}
>
<Tag className="client-count-tag" style={{ margin: 0, marginRight: 4, padding: '0 2px' }}>{cc.deactive.length}</Tag>
<Tag
className="client-count-tag"
style={{ margin: 0, marginRight: 4, padding: '0 2px' }}
>
{cc.deactive.length}
</Tag>
</Popover>
)}
{cc.depleted.length > 0 && (
<Popover
title={t('depleted')}
content={(
content={
<div className="client-email-list">
{cc.depleted.map((e) => <div key={e}>{e}</div>)}
{cc.depleted.map((e) => (
<div key={e}>{e}</div>
))}
</div>
)}
}
>
<Tag color="red" className="client-count-tag" style={{ margin: 0, marginRight: 4, padding: '0 2px' }}>{cc.depleted.length}</Tag>
<Tag
color="red"
className="client-count-tag"
style={{ margin: 0, marginRight: 4, padding: '0 2px' }}
>
{cc.depleted.length}
</Tag>
</Popover>
)}
{cc.online.length > 0 && (
<Popover
title={t('online')}
content={(
content={
<div className="client-email-list">
{cc.online.map((e) => <div key={e}>{e}</div>)}
{cc.online.map((e) => (
<div key={e}>{e}</div>
))}
</div>
)}
}
>
<Tag color="blue" className="client-count-tag" style={{ margin: 0, padding: '0 2px' }}>{cc.online.length}</Tag>
<Tag
color="blue"
className="client-count-tag"
style={{ margin: 0, padding: '0 2px' }}
>
{cc.online.length}
</Tag>
</Popover>
)}
</>
@@ -293,10 +373,10 @@ export function useInboundColumns({
key: 'traffic',
align: 'center',
width: 140,
sorter: (a, b) => (a.up + a.down) - (b.up + b.down),
sorter: (a, b) => a.up + a.down - (b.up + b.down),
render: (_, record) => (
<Popover
content={(
content={
<table cellPadding={2}>
<tbody>
<tr>
@@ -311,11 +391,10 @@ export function useInboundColumns({
)}
</tbody>
</table>
)}
}
>
<Tag color={ColorUtils.usageColor(record.up + record.down, trafficDiff, record.total)}>
{SizeFormatter.sizeFormat(record.up + record.down)} /
{' '}
{SizeFormatter.sizeFormat(record.up + record.down)} /{' '}
{record.total > 0 ? SizeFormatter.sizeFormat(record.total) : <InfinityIcon />}
</Tag>
</Popover>
@@ -330,7 +409,11 @@ export function useInboundColumns({
render: (_, record) => {
const speed = inboundSpeed[record.id];
if (!isActiveSpeed(speed)) {
return <Tag color="default" className={SPEED_TAG_CLASS_NAME} style={SPEED_TAG_STYLE}></Tag>;
return (
<Tag color="default" className={SPEED_TAG_CLASS_NAME} style={SPEED_TAG_STYLE}>
</Tag>
);
}
return <InboundSpeedTag speed={speed} withTooltip tableCell />;
},
@@ -345,17 +428,38 @@ export function useInboundColumns({
if (record.expiryTime > 0) {
return (
<Popover content={IntlUtil.formatDate(record.expiryTime, datepicker)}>
<Tag color={ColorUtils.usageColor(Date.now(), expireDiff, record._expiryTime)} style={{ minWidth: 50 }}>
<Tag
color={ColorUtils.usageColor(Date.now(), expireDiff, record._expiryTime)}
style={{ minWidth: 50 }}
>
{IntlUtil.formatRelativeTime(record.expiryTime)}
</Tag>
</Popover>
);
}
return <Tag color="purple"><InfinityIcon /></Tag>;
return (
<Tag color="purple">
<InfinityIcon />
</Tag>
);
},
},
);
return cols;
}, [t, hasAnyRemark, hasAnySubSortIndex, hasActiveNode, nodesById, clientCount, inboundSpeed, subEnable, expireDiff, trafficDiff, datepicker, onRowAction, onSwitchEnable]);
}, [
t,
hasAnyRemark,
hasAnySubSortIndex,
hasActiveNode,
nodesById,
clientCount,
inboundSpeed,
subEnable,
expireDiff,
trafficDiff,
datepicker,
onRowAction,
onSwitchEnable,
]);
}
+36 -16
View File
@@ -57,7 +57,10 @@ export default function QrCodeModal({
useEffect(() => {
if (!open || !dbInbound) return;
const inbound = inboundFromDb(dbInbound);
const fallbackHostname = preferPublicHost(window.location.hostname, subSettings?.publicHost ?? '');
const fallbackHostname = preferPublicHost(
window.location.hostname,
subSettings?.publicHost ?? '',
);
if (inbound.protocol === Protocols.WIREGUARD) {
const peerRemark = client?.email
? `${dbInbound.remark}-${client.email}`
@@ -110,7 +113,11 @@ export default function QrCodeModal({
items.push({ key: 'sub', header: t('subscription.title'), value: subLink });
}
if (subJsonLink) {
items.push({ key: 'sub-json', header: `${t('subscription.title')} (JSON)`, value: subJsonLink });
items.push({
key: 'sub-json',
header: `${t('subscription.title')} (JSON)`,
value: subJsonLink,
});
}
links.forEach((link, idx) => {
items.push({ key: `l${idx}`, header: link.remark || `Link ${idx + 1}`, value: link.link });
@@ -123,25 +130,31 @@ export default function QrCodeModal({
downloadName: `peer-${idx + 1}.conf`,
});
if (wireguardLinks[idx]) {
items.push({ key: `wl${idx}`, header: `Peer ${idx + 1} link`, value: wireguardLinks[idx], showQr: false });
items.push({
key: `wl${idx}`,
header: `Peer ${idx + 1} link`,
value: wireguardLinks[idx],
showQr: false,
});
}
});
return items;
}, [subLink, subJsonLink, links, wireguardConfigs, wireguardLinks, t]);
const collapseItems: CollapseProps['items'] = useMemo(
() => qrItems.map((item) => ({
key: item.key,
label: item.header,
children: (
<QrPanel
value={item.value}
remark={item.header}
downloadName={item.downloadName || ''}
showQr={item.showQr !== false && !isPostQuantumLink(item.value)}
/>
),
})),
() =>
qrItems.map((item) => ({
key: item.key,
label: item.header,
children: (
<QrPanel
value={item.value}
remark={item.header}
downloadName={item.downloadName || ''}
showQr={item.showQr !== false && !isPostQuantumLink(item.value)}
/>
),
})),
[qrItems],
);
@@ -154,7 +167,14 @@ export default function QrCodeModal({
}, [open, qrItems]);
return (
<Modal open={open} onCancel={onClose} title={t('qrCode')} footer={null} width={420} destroyOnHidden>
<Modal
open={open}
onCancel={onClose}
title={t('qrCode')}
footer={null}
width={420}
destroyOnHidden
>
{dbInbound && collapseItems && collapseItems.length > 0 && (
<Collapse
ghost
+19 -4
View File
@@ -38,7 +38,10 @@ async function svgToPngBlob(svgEl: SVGSVGElement | null, size: number): Promise<
URL.revokeObjectURL(url);
canvas.toBlob((blob) => resolve(blob), 'image/png');
};
img.onerror = () => { URL.revokeObjectURL(url); resolve(null); };
img.onerror = () => {
URL.revokeObjectURL(url);
resolve(null);
};
img.src = url;
});
}
@@ -95,18 +98,30 @@ export default function QrPanel({
<div className="qr-panel">
{messageContextHolder}
<div className="qr-panel-header">
<Tag color="green" className="qr-remark">{remark}</Tag>
<Tag color="green" className="qr-remark">
{remark}
</Tag>
<Tooltip title={t('copy')}>
<Button size="small" icon={<CopyOutlined />} aria-label={t('copy')} onClick={copy} />
</Tooltip>
{showQr && (
<Tooltip title={t('downloadImage')}>
<Button size="small" icon={<PictureOutlined />} aria-label={t('downloadImage')} onClick={downloadImage} />
<Button
size="small"
icon={<PictureOutlined />}
aria-label={t('downloadImage')}
onClick={downloadImage}
/>
</Tooltip>
)}
{downloadName && (
<Tooltip title={t('download')}>
<Button size="small" icon={<DownloadOutlined />} aria-label={t('download')} onClick={download} />
<Button
size="small"
icon={<DownloadOutlined />}
aria-label={t('download')}
onClick={download}
/>
</Tooltip>
)}
</div>
+126 -42
View File
@@ -35,7 +35,10 @@ type DBInboundInstance = InstanceType<typeof DBInbound>;
// while recent, so returning to the page shows the last throughput immediately
// and the next poll refreshes it.
const SPEED_CACHE_TTL_MS = 15000;
let inboundSpeedCache: { at: number; data: Record<number, InboundSpeedEntry> } = { at: 0, data: {} };
let inboundSpeedCache: { at: number; data: Record<number, InboundSpeedEntry> } = {
at: 0,
data: {},
};
interface TrafficDelta {
Tag: string;
@@ -86,7 +89,9 @@ async function fetchOnlineClientsByGuid(): Promise<Record<string, string[]>> {
const msg = await HttpUtil.post('/panel/api/clients/onlinesByGuid', undefined, { silent: true });
if (!msg?.success) throw new Error(msg?.msg || 'Failed to fetch onlinesByGuid');
const validated = parseMsg(msg, OnlineByNodeSchema, 'clients/onlinesByGuid');
return (validated.obj && typeof validated.obj === 'object') ? (validated.obj as Record<string, string[]>) : {};
return validated.obj && typeof validated.obj === 'object'
? (validated.obj as Record<string, string[]>)
: {};
}
// Inbound tags that carried traffic recently, grouped by node (local = key 0).
@@ -97,7 +102,9 @@ async function fetchActiveInboundsByNode(): Promise<Record<string, string[]>> {
const msg = await HttpUtil.post('/panel/api/clients/activeInbounds', undefined, { silent: true });
if (!msg?.success) throw new Error(msg?.msg || 'Failed to fetch activeInbounds');
const validated = parseMsg(msg, ActiveInboundsByNodeSchema, 'clients/activeInbounds');
return (validated.obj && typeof validated.obj === 'object') ? (validated.obj as Record<string, string[]>) : {};
return validated.obj && typeof validated.obj === 'object'
? (validated.obj as Record<string, string[]>)
: {};
}
function toGuidOnlineMap(data: Record<string, string[]>): Map<string, Set<string>> {
@@ -113,11 +120,13 @@ async function fetchLastOnlineMap(): Promise<Record<string, number>> {
const msg = await HttpUtil.post('/panel/api/clients/lastOnline', undefined, { silent: true });
if (!msg?.success) throw new Error(msg?.msg || 'Failed to fetch lastOnline');
const validated = parseMsg(msg, LastOnlineMapSchema, 'clients/lastOnline');
return (validated.obj && typeof validated.obj === 'object') ? validated.obj : {};
return validated.obj && typeof validated.obj === 'object' ? validated.obj : {};
}
async function fetchDefaultSettings(): Promise<DefaultsPayload> {
const msg = await HttpUtil.post('/panel/api/setting/defaultSettings', undefined, { silent: true });
const msg = await HttpUtil.post('/panel/api/setting/defaultSettings', undefined, {
silent: true,
});
if (!msg?.success) throw new Error(msg?.msg || 'Failed to fetch defaults');
const validated = parseMsg(msg, DefaultsPayloadSchema, 'setting/defaultSettings');
return validated.obj ?? {};
@@ -170,14 +179,25 @@ export function useInbounds() {
const pageSize = defaults.pageSize ?? 0;
const datepicker = (defaults.datepicker as 'gregorian' | 'jalalian') || 'gregorian';
const subSettings: SubSettings = useMemo(() => ({
enable: !!defaults.subEnable,
subTitle: defaults.subTitle || '',
subURI: defaults.subURI || '',
subJsonURI: defaults.subJsonURI || '',
subJsonEnable: !!defaults.subJsonEnable,
publicHost: defaults.subDomain || defaults.webDomain || '',
}), [defaults.subEnable, defaults.subTitle, defaults.subURI, defaults.subJsonURI, defaults.subJsonEnable, defaults.subDomain, defaults.webDomain]);
const subSettings: SubSettings = useMemo(
() => ({
enable: !!defaults.subEnable,
subTitle: defaults.subTitle || '',
subURI: defaults.subURI || '',
subJsonURI: defaults.subJsonURI || '',
subJsonEnable: !!defaults.subJsonEnable,
publicHost: defaults.subDomain || defaults.webDomain || '',
}),
[
defaults.subEnable,
defaults.subTitle,
defaults.subURI,
defaults.subJsonURI,
defaults.subJsonEnable,
defaults.subDomain,
defaults.webDomain,
],
);
useEffect(() => {
if (defaults.datepicker) setDatepicker(datepicker);
@@ -224,9 +244,22 @@ export function useInbounds() {
const [lastOnlineMap, setLastOnlineMap] = useState<Record<string, number>>({});
const rollupClients = useCallback(
(dbInbound: DBInboundInstance, inbound: { clients?: { email?: string; enable?: boolean; comment?: string }[] }): ClientRollup => {
(
dbInbound: DBInboundInstance,
inbound: { clients?: { email?: string; enable?: boolean; comment?: string }[] },
): ClientRollup => {
const clientStats = Array.isArray((dbInbound as { clientStats?: unknown }).clientStats)
? (dbInbound as unknown as { clientStats: { email: string; total: number; up: number; down: number; expiryTime: number }[] }).clientStats
? (
dbInbound as unknown as {
clientStats: {
email: string;
total: number;
up: number;
down: number;
expiryTime: number;
}[];
}
).clientStats
: [];
const clients = inbound?.clients || [];
const active: string[] = [];
@@ -241,17 +274,22 @@ export function useInbounds() {
// inbound. Local inbounds carry the panel's own GUID (filled server-side);
// a node-managed inbound carries its origin node's GUID, or falls back to
// the master-local synthetic id for an old-build node without one (#4983).
const guid = dbInbound.originNodeGuid || (dbInbound.nodeId != null ? `node:${dbInbound.nodeId}` : '');
const guid =
dbInbound.originNodeGuid || (dbInbound.nodeId != null ? `node:${dbInbound.nodeId}` : '');
const nodeOnline = onlineByGuidRef.current.get(guid);
// A node absent from the active map reports no per-inbound activity, so
// leave its inbounds ungated. When present, only mark a client online on
// this inbound if its tag actually carried traffic — that's what stops a
// multi-inbound client lighting up every inbound it's attached to.
const activeForNode = activeByGuidRef.current.get(guid);
const inboundActive = activeForNode === undefined || !dbInbound.tag || activeForNode.has(dbInbound.tag);
const inboundActive =
activeForNode === undefined || !dbInbound.tag || activeForNode.has(dbInbound.tag);
if (dbInbound.enable) {
const statsByEmail = new Map<string, { email: string; total: number; up: number; down: number; expiryTime: number }>();
const statsByEmail = new Map<
string,
{ email: string; total: number; up: number; down: number; expiryTime: number }
>();
for (const stats of clientStats) {
if (stats.email) statsByEmail.set(stats.email.toLowerCase(), stats);
}
@@ -259,7 +297,8 @@ export function useInbounds() {
if (client.comment && client.email) comments.set(client.email, client.comment);
if (!client.email) continue;
const stats = statsByEmail.get(client.email.toLowerCase());
const exhausted = stats != null && stats.total > 0 && stats.up + stats.down >= stats.total;
const exhausted =
stats != null && stats.total > 0 && stats.up + stats.down >= stats.total;
const expired = stats != null && stats.expiryTime > 0 && stats.expiryTime <= now;
if (expired || exhausted) {
depleted.push(client.email);
@@ -326,7 +365,11 @@ export function useInbounds() {
method?: string;
clients?: Array<{ email?: string; enable?: boolean; comment?: string }>;
};
if (row.protocol === Protocols.SHADOWSOCKS && !isSSMultiUser({ protocol: row.protocol, settings })) continue;
if (
row.protocol === Protocols.SHADOWSOCKS &&
!isSSMultiUser({ protocol: row.protocol, settings })
)
continue;
counts[row.id] = rollupClients(dbInbound, { clients: settings.clients });
}
}
@@ -360,7 +403,9 @@ export function useInbounds() {
if (lastOnlineQuery.data) setLastOnlineMap(lastOnlineQuery.data);
}, [lastOnlineQuery.data]);
const fetched = (slimQuery.data !== undefined || slimQuery.isError) && (defaultsQuery.data !== undefined || defaultsQuery.isError);
const fetched =
(slimQuery.data !== undefined || slimQuery.isError) &&
(defaultsQuery.data !== undefined || defaultsQuery.isError);
const fetchErrorSource = slimQuery.error || defaultsQuery.error;
const fetchError = fetchErrorSource ? (fetchErrorSource as Error).message : '';
@@ -385,22 +430,25 @@ export function useInbounds() {
// uuid/password/flow/etc.) and swaps it into the cached list. Use this
// before opening edit / info / qr / export / clone flows — refresh() loads
// the slim list which doesn't carry per-client secrets.
const hydrateInbound = useCallback(async (id: number) => {
const msg = await HttpUtil.get(`/panel/api/inbounds/get/${id}`);
if (!msg?.success || !msg.obj) return null;
const validated = parseMsg(msg, InboundDetailSchema, `inbounds/get/${id}`);
if (!validated.obj) return null;
const dbInbound = new DBInbound(validated.obj) as DBInboundInstance;
setDbInbounds((prev) => {
const next = prev.map((row) => (
(row as unknown as { id: number }).id === id ? dbInbound : row
));
dbInboundsRef.current = next;
return next;
});
rebuildClientCount();
return dbInbound;
}, [rebuildClientCount]);
const hydrateInbound = useCallback(
async (id: number) => {
const msg = await HttpUtil.get(`/panel/api/inbounds/get/${id}`);
if (!msg?.success || !msg.obj) return null;
const validated = parseMsg(msg, InboundDetailSchema, `inbounds/get/${id}`);
if (!validated.obj) return null;
const dbInbound = new DBInbound(validated.obj) as DBInboundInstance;
setDbInbounds((prev) => {
const next = prev.map((row) =>
(row as unknown as { id: number }).id === id ? dbInbound : row,
);
dbInboundsRef.current = next;
return next;
});
rebuildClientCount();
return dbInbound;
},
[rebuildClientCount],
);
const applyTrafficEvent = useCallback(
(payload: unknown) => {
@@ -470,19 +518,34 @@ export function useInbounds() {
if (!payload || typeof payload !== 'object') return;
const p = payload as {
inbounds?: { id: number; up?: number; down?: number; total?: number; enable?: boolean }[];
clients?: { email: string; up?: number; down?: number; total?: number; expiryTime?: number; enable?: boolean }[];
clients?: {
email: string;
up?: number;
down?: number;
total?: number;
expiryTime?: number;
enable?: boolean;
}[];
};
let touched = false;
if (Array.isArray(p.inbounds) && p.inbounds.length > 0) {
const byId = new Map<number, { id: number; up?: number; down?: number; total?: number; enable?: boolean }>();
const byId = new Map<
number,
{ id: number; up?: number; down?: number; total?: number; enable?: boolean }
>();
for (const row of p.inbounds) {
if (row && row.id != null) byId.set(row.id, row);
}
for (const ib of dbInboundsRef.current) {
const upd = byId.get((ib as unknown as { id: number }).id);
if (!upd) continue;
const ibRec = ib as unknown as { up: number; down: number; total: number; enable: boolean };
const ibRec = ib as unknown as {
up: number;
down: number;
total: number;
enable: boolean;
};
if (typeof upd.up === 'number') ibRec.up = upd.up;
if (typeof upd.down === 'number') ibRec.down = upd.down;
if (typeof upd.total === 'number') ibRec.total = upd.total;
@@ -492,12 +555,33 @@ export function useInbounds() {
}
if (Array.isArray(p.clients) && p.clients.length > 0) {
const byEmail = new Map<string, { email: string; up?: number; down?: number; total?: number; expiryTime?: number; enable?: boolean }>();
const byEmail = new Map<
string,
{
email: string;
up?: number;
down?: number;
total?: number;
expiryTime?: number;
enable?: boolean;
}
>();
for (const row of p.clients) {
if (row && row.email) byEmail.set(row.email, row);
}
for (const ib of dbInboundsRef.current) {
const stats = (ib as unknown as { clientStats: { email: string; up: number; down: number; total: number; expiryTime: number; enable: boolean }[] }).clientStats;
const stats = (
ib as unknown as {
clientStats: {
email: string;
up: number;
down: number;
total: number;
expiryTime: number;
enable: boolean;
}[];
}
).clientStats;
if (!Array.isArray(stats)) continue;
for (let i = 0; i < stats.length; i++) {
const stat = stats[i];