mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-07-24 13:36:24 +00:00
892c06c8bc
* fix(xray): block private-range egress in default freedom finalRules (#6037)
With domainStrategy AsIs the router never resolves domains, so a domain
with a private A record (e.g. 127-0-0-1.nip.io) sails past the
geoip:private routing block and freedom's allow-all finalRules let it
reach loopback services such as the xray gRPC API and metrics listener.
Prepend a block rule for geoip:private to the default template and add
the FreedomFinalRulesPrivateEgressBlock seeder so existing installs
still carrying the stock allow-only (or legacy private-only-allow)
finalRules are upgraded in place; customized rules are left untouched.
* fix(sub): version-gate unencrypted-outbound drops in outbound subscriptions (#6033)
Commit d38c912d taught CheckXrayConfig to keep unencrypted vless/trojan
outbounds when the running core predates the v26.7.11 rejection, but
filterOutboundsRejectedByCore still consulted the embedded validator
unconditionally, so outbound subscriptions kept silently dropping those
outbounds even on downgraded cores.
Apply the same shouldSkipLegacyUnencryptedOutboundRejection gate when
filtering fetched subscription outbounds.
* fix(xray): resolve geodata assets before building outbound configs (#5928)
Saving routing or template settings validates each outbound through the
embedded config loader, and a freedom outbound whose finalRules
reference geoip:private opens geoip.dat during that build. Unlike
ApplyRoutingConfig, ValidateOutboundConfig and AddOutbound never pointed
the in-process loader at the bin folder, so xray-core resolved the file
relative to the panel executable and saving failed with
'stat /usr/local/x-ui/geoip.dat: no such file or directory'.
Call ensureXrayAssetLocation before both build paths.
* fix(api): use a real i18n key in the client get handler (#5911)
The client fetch endpoint localized its error prefix with the bare key
'get', which exists in no translation file, so every lookup of a deleted
client's email logged 'message "get" not found in language ...' noise
alongside the expected record-not-found warning. Reuse the same
pages.inbounds.toasts.obtain key the sibling list handler uses.
* fix(sub): carry host record Host header and path into Clash/JSON output (#5944)
The raw-link path overrides the host/path share params from a Host
record via applyEndpointHostPath, but the Clash and JSON renderers read
the transport settings object, which applyHostStreamOverrides never
touched — so a Host record's WebSocket Host header (and path) silently
vanished from Clash/Mihomo and JSON subscriptions whenever the inbound's
own ws settings left them empty.
Inject hostHeader/path into the ws/httpupgrade/xhttp settings of the
per-host stream, mirroring the raw-link override.
* fix(metrics): accept Unicode outbound tags in the observatory (#5972)
The observatory validator whitelisted ASCII word characters, so any
outbound whose tag carries a flag emoji or other non-ASCII text was
silently dropped from the metrics snapshot, delay history, and health
notifications. The history store is an in-process map, so the strict
charset bought nothing.
Validate tags as non-empty, bounded, control-character-free UTF-8
instead, keeping spaces and emoji while still rejecting garbage input on
the query path.
* fix(database): default sqlite to WAL to stop background-job lock storms (#6057, #6068)
With journal_mode=DELETE every write serializes the whole database and
blocks readers, so under normal multi-job load (traffic sampling, node
sync, mtproto reconcile) transactions regularly outwaited the 10s busy
timeout and jobs failed with 'database is locked'.
Move to WAL by default: readers no longer block writers and vice versa,
which removes the observed contention while writer-writer access still
serializes safely. The single-file-at-rest property is preserved where
it matters — Checkpoint() now issues wal_checkpoint(TRUNCATE), so panel
and Telegram backups read a complete main file, and sqlite folds the WAL
back into the db on clean shutdown. XUI_DB_JOURNAL_MODE=DELETE restores
the previous behavior for setups that copy the live file directly.
* fix(database): strip finalmask.tcp from REALITY inbounds on upgrade (#6038)
validateFinalMaskRealityCombo blocks saving finalmask.tcp together with
REALITY because that combination crashes Xray-core 26.7.11 on the first
connection (XTLS/Xray-core#6453), but it only runs on add/update. An
inbound saved before the validator existed sailed through the upgrade
untouched and took the core down at boot.
Add the InboundRealityFinalmaskTcpStrip seeder: one-time scan that
removes finalmask.tcp from REALITY inbounds (other finalmask transports
survive), so upgraded panels start cleanly.
* fix(xray): stop deleting hand-written direct routing rules on save (#6056)
The DNS allow-rule sync recognized 'its' rules purely by shape
(type=field, ip, port, outboundTag=direct, nothing else), so any manual
rule of that shape — e.g. routing a LAN CIDR to a NAS port over direct —
was silently stripped on every settings save.
Mark managed rules with ruleTag=xui-dns-allow (round-tripped untouched
by both xray-core and the Routing tab editor) and only strip rules that
carry the tag. Untagged legacy managed rules are adopted when their
exact ip-set/port matches a currently configured private DNS endpoint;
anything else is left alone. A stale pre-tag managed rule whose DNS
server was removed now lingers until deleted manually — the safe side of
the trade against eating user rules.
* fix(clients): resolve email lookups through client_inbounds after a move (#6059)
GetClientInboundByEmail trusted the client_traffics.inbound_id pointer
whenever that inbound still existed, but a client moved between inbounds
leaves the row pointing at its old (still existing) inbound. The lookup
then searched the wrong inbound's clients and failed with 'Client Not
Found In Inbound For Email', which broke the Telegram bot's link and QR
generation for moved clients.
When the pointed-at inbound no longer carries the email, re-resolve
through the authoritative client_inbounds link to the inbound that
actually hosts the client.
* fix(nodes): replicate inbound fallbacks to nodes (#5963)
Fallbacks live in the inbound_fallbacks table and were only merged into
settings by the master's local config builder; the runtime inbound
pushed to nodes rebuilt settings without them, and the reconcile job
additionally fingerprinted the raw DB row, so fallback edits neither
reached nodes nor triggered a re-push.
Inject settings.fallbacks in buildRuntimeInboundForAPI (mirroring the
local builder, gated on inboundCanHostFallbacks) and make ReconcileNode
push and fingerprint that same runtime-built payload, aligning the
interactive and reconcile paths.
* fix(database): survive PostgreSQL outages without a runaway restart loop (#6023)
A PostgreSQL that was down or still starting made InitDB fail instantly;
the process exited with a generic startup error and systemd restarted it
every 5s forever, flooding the journal.
Retry the initial postgres connection with backoff (~70s total) and log
the real driver error on every attempt, and cap the systemd units with
StartLimitIntervalSec/StartLimitBurst so a persistently unreachable
database stops the unit instead of looping indefinitely.
* fix(xray): force a full restart when REALITY stream settings change (#6010)
A changed inbound is normally hot-swapped over gRPC as RemoveInbound +
AddInbound, but xray-core does not reliably rebuild a REALITY listener's
authenticator on a runtime re-add — key or shortId edits appeared
applied yet clients kept authenticating against the old parameters until
someone restarted the core manually, on nodes in particular.
Treat any non-client change to an inbound that uses (or starts using)
REALITY as not hot-appliable so the panel restarts the core instead.
Client-only edits on REALITY inbounds keep flowing through the per-user
AlterInbound path and still avoid restarts.
* feat(sub): allow insecure TLS for outbound subscription fetches (#6067)
An outbound subscription served over HTTPS with a self-signed or
private-CA certificate could never be fetched: the fetch client had no
TLS options, so refreshes died with 'x509: certificate signed by unknown
authority' and there was nothing the admin could toggle.
Add a per-subscription 'Allow insecure' switch (persisted as
allow_insecure, default off) that sets InsecureSkipVerify on the fetch
transport — including when the fetch is routed through the panel egress
proxy. The SSRF-guarded dialer and redirect re-validation stay in force
either way.
* fix(reality): send PROXY protocol header in the target scanner when xver is set (#6082)
The REALITY target scanner always probed with a plain TLS handshake, so
a target fronted by an Nginx listener that requires the PROXY protocol
(matching the inbound's xver>=1) reset the connection and the panel
reported a false 'TLS handshake failed'.
Thread the inbound's xver into the scan request and, when it is >=1,
lead with the matching PROXY protocol header (v1 for xver 1, binary v2
for xver 2) built from the dialed connection's own address pair. Batch
candidate scans against public sites are unaffected (xver 0).
* fix(frontend): default sockopt fields when editing a stored inbound (#5956)
Opening an existing inbound ran rawInboundToFormValues over the raw DB
row, and only xhttpSettings was re-parsed through its Zod schema to fill
defaults. A sockopt object saved before the TProxy control existed has
no tproxy key, so the Select rendered blank; picking Off didn't help
because the wire normalizer drops tproxy=off, recreating the missing
key on the next edit.
Re-parse streamSettings.sockopt through SockoptStreamSettingsSchema on
load, mirroring the xhttpSettings handling, so absent keys (tproxy,
tcpcongestion, …) get their schema defaults every time the form opens.
364 lines
14 KiB
TypeScript
364 lines
14 KiB
TypeScript
import type { InboundFormValues, ShareAddrStrategy, TrafficReset } from '@/schemas/forms/inbound-form';
|
|
import type { InboundSettings } from '@/schemas/protocols/inbound';
|
|
import {
|
|
HysteriaClientSchema,
|
|
MtprotoClientSchema,
|
|
ShadowsocksClientSchema,
|
|
TrojanClientSchema,
|
|
VlessClientSchema,
|
|
VmessClientSchema,
|
|
WireguardClientSchema,
|
|
} from '@/schemas/protocols/inbound';
|
|
import type { StreamSettings } from '@/schemas/api/inbound';
|
|
import type { Sniffing } from '@/schemas/primitives';
|
|
import type { z } from 'zod';
|
|
import { normalizeStreamSettingsForWire } from '@/lib/xray/stream-wire-normalize';
|
|
import { canEnableSniffing } from '@/lib/xray/protocol-capabilities';
|
|
import { SockoptStreamSettingsSchema } from '@/schemas/protocols/stream/sockopt';
|
|
import { XHttpStreamSettingsSchema, XHttpXmuxSchema } from '@/schemas/protocols/stream/xhttp';
|
|
|
|
const XMUX_DEFAULTS = XHttpXmuxSchema.parse({});
|
|
|
|
// Plain-data adapter between the panel's stored inbound row shape and
|
|
// the typed InboundFormValues that Form.useForm<T> carries inside
|
|
// InboundFormModal. No dependency on the legacy Inbound/DBInbound
|
|
// classes — the modal hands the raw row in, takes typed values out, and
|
|
// on submit calls formValuesToWirePayload() to get a payload ready to
|
|
// POST to /panel/api/inbounds/add or /update/:id.
|
|
|
|
export interface RawInboundRow {
|
|
port?: number;
|
|
listen?: string;
|
|
protocol?: string;
|
|
tag?: string;
|
|
settings?: unknown;
|
|
streamSettings?: unknown;
|
|
sniffing?: unknown;
|
|
up?: number;
|
|
down?: number;
|
|
total?: number;
|
|
remark?: string;
|
|
enable?: boolean;
|
|
expiryTime?: number;
|
|
trafficReset?: string;
|
|
lastTrafficResetTime?: number;
|
|
nodeId?: number | null;
|
|
shareAddrStrategy?: string;
|
|
shareAddr?: string;
|
|
subSortIndex?: number;
|
|
clientStats?: unknown;
|
|
}
|
|
|
|
// The wire payload — settings/streamSettings/sniffing arrive as JSON
|
|
// strings, mirroring what the Go endpoints expect (xray-core wants the
|
|
// nested config slices as strings to round-trip through its loader).
|
|
export interface WireInboundPayload {
|
|
up: number;
|
|
down: number;
|
|
total: number;
|
|
remark: string;
|
|
enable: boolean;
|
|
expiryTime: number;
|
|
trafficReset: TrafficReset;
|
|
lastTrafficResetTime: number;
|
|
listen: string;
|
|
port: number;
|
|
protocol: string;
|
|
settings: string;
|
|
streamSettings: string;
|
|
sniffing: string;
|
|
tag: string;
|
|
clientStats?: unknown;
|
|
nodeId?: number;
|
|
shareAddrStrategy: ShareAddrStrategy;
|
|
shareAddr: string;
|
|
subSortIndex: number;
|
|
}
|
|
|
|
function coerceJsonObject(value: unknown): Record<string, unknown> {
|
|
if (value == null) return {};
|
|
if (typeof value === 'object' && !Array.isArray(value)) {
|
|
return value as Record<string, unknown>;
|
|
}
|
|
if (typeof value !== 'string') return {};
|
|
const trimmed = value.trim();
|
|
if (trimmed === '') return {};
|
|
try {
|
|
const parsed = JSON.parse(trimmed);
|
|
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
|
? (parsed as Record<string, unknown>)
|
|
: {};
|
|
} catch {
|
|
return {};
|
|
}
|
|
}
|
|
|
|
const TRAFFIC_RESETS: TrafficReset[] = ['never', 'hourly', 'daily', 'weekly', 'monthly'];
|
|
const SHARE_ADDR_STRATEGIES: ShareAddrStrategy[] = ['node', 'listen', 'custom'];
|
|
|
|
function coerceTrafficReset(v: unknown): TrafficReset {
|
|
return typeof v === 'string' && (TRAFFIC_RESETS as string[]).includes(v)
|
|
? (v as TrafficReset)
|
|
: 'never';
|
|
}
|
|
|
|
function coerceShareAddrStrategy(v: unknown): ShareAddrStrategy {
|
|
return typeof v === 'string' && (SHARE_ADDR_STRATEGIES as string[]).includes(v)
|
|
? (v as ShareAddrStrategy)
|
|
: 'node';
|
|
}
|
|
|
|
// Network values that map to a required `${network}Settings` key in
|
|
// NetworkSettingsSchema. Older saved inbounds may be missing the per-
|
|
// network sub-object (the legacy panel sometimes emitted streamSettings
|
|
// without it, and an earlier panel-side prune wrongly stripped empty
|
|
// `tcpSettings: {}` out of the wire payload). Reseat an empty object
|
|
// here so InboundFormSchema.safeParse doesn't blow up at edit time.
|
|
const NETWORK_SETTINGS_KEY: Record<string, string> = {
|
|
tcp: 'tcpSettings',
|
|
kcp: 'kcpSettings',
|
|
ws: 'wsSettings',
|
|
grpc: 'grpcSettings',
|
|
httpupgrade: 'httpupgradeSettings',
|
|
xhttp: 'xhttpSettings',
|
|
hysteria: 'hysteriaSettings',
|
|
};
|
|
|
|
function healStreamNetworkKey(stream: Record<string, unknown>): void {
|
|
if (typeof stream.method === 'string' && stream.method !== '') {
|
|
stream.network = stream.method;
|
|
}
|
|
delete stream.method;
|
|
const network = typeof stream.network === 'string' ? stream.network : '';
|
|
const key = NETWORK_SETTINGS_KEY[network];
|
|
if (!key) return;
|
|
if (stream[key] == null || typeof stream[key] !== 'object') {
|
|
stream[key] = {};
|
|
}
|
|
}
|
|
|
|
function tlsCerts(stream: Record<string, unknown>): Record<string, unknown>[] {
|
|
const tls = stream.tlsSettings as { certificates?: unknown } | undefined;
|
|
return Array.isArray(tls?.certificates) ? tls.certificates as Record<string, unknown>[] : [];
|
|
}
|
|
|
|
function synthesizeTlsCertUseFile(stream: Record<string, unknown>): void {
|
|
for (const c of tlsCerts(stream)) {
|
|
if (typeof c.useFile === 'boolean') continue;
|
|
const hasFile = !!c.certificateFile || !!c.keyFile;
|
|
const hasInline =
|
|
(Array.isArray(c.certificate) && c.certificate.length > 0) ||
|
|
(Array.isArray(c.key) && c.key.length > 0);
|
|
c.useFile = hasFile || !hasInline;
|
|
}
|
|
}
|
|
|
|
function stripTlsCertUseFile(stream: Record<string, unknown>): void {
|
|
for (const c of tlsCerts(stream)) delete c.useFile;
|
|
}
|
|
|
|
export function rawInboundToFormValues(row: RawInboundRow): InboundFormValues {
|
|
const protocol = (row.protocol || 'vless') as InboundSettings['protocol'];
|
|
const settings = coerceJsonObject(row.settings) as InboundSettings['settings'];
|
|
const rawStream = coerceJsonObject(row.streamSettings);
|
|
const streamSettings = Object.keys(rawStream).length > 0
|
|
? (rawStream as StreamSettings)
|
|
: undefined;
|
|
if (streamSettings) {
|
|
healStreamNetworkKey(streamSettings as unknown as Record<string, unknown>);
|
|
synthesizeTlsCertUseFile(streamSettings as unknown as Record<string, unknown>);
|
|
const streamRecord = streamSettings as unknown as Record<string, unknown>;
|
|
const xh = streamRecord.xhttpSettings;
|
|
if (xh && typeof xh === 'object' && !Array.isArray(xh)) {
|
|
const parsed = XHttpStreamSettingsSchema.safeParse(xh);
|
|
const xhttp = (parsed.success ? parsed.data : xh) as Record<string, unknown>;
|
|
streamRecord.xhttpSettings = xhttp;
|
|
const xmux = xhttp.xmux;
|
|
if (xmux && typeof xmux === 'object' && !Array.isArray(xmux)) {
|
|
xhttp.enableXmux = true;
|
|
xhttp.xmux = { ...XMUX_DEFAULTS, ...(xmux as Record<string, unknown>) };
|
|
}
|
|
}
|
|
const so = streamRecord.sockopt;
|
|
if (so && typeof so === 'object' && !Array.isArray(so)) {
|
|
const parsed = SockoptStreamSettingsSchema.safeParse(so);
|
|
if (parsed.success) {
|
|
streamRecord.sockopt = { ...(so as Record<string, unknown>), ...parsed.data };
|
|
}
|
|
}
|
|
}
|
|
const sniffing = coerceJsonObject(row.sniffing) as unknown as Sniffing;
|
|
|
|
return {
|
|
remark: row.remark ?? '',
|
|
enable: row.enable ?? true,
|
|
port: row.port ?? 0,
|
|
listen: row.listen ?? '',
|
|
tag: row.tag ?? '',
|
|
expiryTime: row.expiryTime ?? 0,
|
|
sniffing,
|
|
streamSettings,
|
|
up: row.up ?? 0,
|
|
down: row.down ?? 0,
|
|
total: row.total ?? 0,
|
|
trafficReset: coerceTrafficReset(row.trafficReset),
|
|
lastTrafficResetTime: row.lastTrafficResetTime ?? 0,
|
|
nodeId: row.nodeId ?? null,
|
|
shareAddrStrategy: coerceShareAddrStrategy(row.shareAddrStrategy),
|
|
shareAddr: row.shareAddr ?? '',
|
|
subSortIndex: Math.max(1, row.subSortIndex ?? 1),
|
|
protocol,
|
|
settings,
|
|
} as InboundFormValues;
|
|
}
|
|
|
|
// Recursively strip undefined leaves from the wire payload. Empty arrays
|
|
// and empty objects are PRESERVED — legacy XrayCommonClass.toJson() kept
|
|
// shells like `tcpSettings: {}` so xray-core picks up its built-in
|
|
// defaults, and stripping them led the FE to lose required-but-empty
|
|
// arrays (vless clients, wireguard peers, etc.) which the Go side then
|
|
// serialized back as `null`. Primitive values (including 0, false, '')
|
|
// are kept verbatim.
|
|
export function pruneEmpty(value: unknown): unknown {
|
|
if (Array.isArray(value)) {
|
|
return value.map(pruneEmpty);
|
|
}
|
|
if (value !== null && typeof value === 'object') {
|
|
const out: Record<string, unknown> = {};
|
|
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
|
|
const p = pruneEmpty(v);
|
|
if (p === undefined) continue;
|
|
out[k] = p;
|
|
}
|
|
return out;
|
|
}
|
|
return value;
|
|
}
|
|
|
|
// Per-protocol client field whitelist — the Zod schemas in
|
|
// schemas/protocols/inbound/<proto>.ts define which keys a given
|
|
// protocol's clients accept on the wire. When a global client is created
|
|
// the panel may persist cross-protocol fields on the same row (`auth` for
|
|
// hysteria, `password` for trojan, `security` for vmess, etc.); rendering
|
|
// those inside a vless inbound's settings.clients is confusing and rides
|
|
// dead weight in the wire payload. Parsing through the protocol's schema
|
|
// gives us the canonical projection.
|
|
function clientSchemaForProtocol(protocol: string): z.ZodType | null {
|
|
switch (protocol) {
|
|
case 'vless': return VlessClientSchema;
|
|
case 'vmess': return VmessClientSchema;
|
|
case 'trojan': return TrojanClientSchema;
|
|
case 'shadowsocks': return ShadowsocksClientSchema;
|
|
case 'hysteria': return HysteriaClientSchema;
|
|
case 'wireguard': return WireguardClientSchema;
|
|
case 'mtproto': return MtprotoClientSchema;
|
|
default: return null;
|
|
}
|
|
}
|
|
|
|
export function normalizeClients(protocol: string, clients: unknown): unknown {
|
|
const schema = clientSchemaForProtocol(protocol);
|
|
if (!schema || !Array.isArray(clients)) return clients;
|
|
return clients.map((c) => {
|
|
const parsed = schema.safeParse(c);
|
|
return parsed.success ? parsed.data : c;
|
|
});
|
|
}
|
|
|
|
// Sniffing normalizer matching the legacy Sniffing.toJson(): when
|
|
// disabled the payload is the bare `{ enabled: false }` regardless of
|
|
// what the form holds; when enabled, only non-default fields ride.
|
|
export function normalizeSniffing(s: Sniffing | undefined): Record<string, unknown> {
|
|
if (!s || !s.enabled) return { enabled: false };
|
|
const out: Record<string, unknown> = {
|
|
enabled: true,
|
|
destOverride: s.destOverride,
|
|
};
|
|
if (s.metadataOnly) out.metadataOnly = true;
|
|
if (s.routeOnly) out.routeOnly = true;
|
|
if (s.ipsExcluded?.length) out.ipsExcluded = s.ipsExcluded;
|
|
if (s.domainsExcluded?.length) out.domainsExcluded = s.domainsExcluded;
|
|
return out;
|
|
}
|
|
|
|
// Drops cosmetic empty-array keys that legacy XrayCommonClass.toJson()
|
|
// explicitly skipped (fallbacks/finalmask). Mutates the pruned settings
|
|
// objects in place; called AFTER pruneEmpty so we can lean on the
|
|
// already-shallow shape.
|
|
export function dropLegacyOptionalEmpties(
|
|
settings: Record<string, unknown>,
|
|
stream: Record<string, unknown> | undefined,
|
|
): void {
|
|
// VLESS/Trojan emit `fallbacks` only when non-empty.
|
|
const fb = settings.fallbacks;
|
|
if (Array.isArray(fb) && fb.length === 0) delete settings.fallbacks;
|
|
|
|
if (stream) {
|
|
// StreamSettings emits `finalmask` only when at least one transport
|
|
// mask exists (legacy `hasFinalMask`). Drop the whole block when all
|
|
// sub-fields are empty; otherwise drop only the empty sub-arrays so
|
|
// the wire payload doesn't carry a stray `"tcp": []` next to a
|
|
// populated UDP mask list (and vice versa).
|
|
const fm = stream.finalmask as { tcp?: unknown[]; udp?: unknown[]; quicParams?: unknown } | undefined;
|
|
if (fm && typeof fm === 'object') {
|
|
const hasTcp = Array.isArray(fm.tcp) && fm.tcp.length > 0;
|
|
const hasUdp = Array.isArray(fm.udp) && fm.udp.length > 0;
|
|
const hasQuic = fm.quicParams != null;
|
|
if (!hasTcp && !hasUdp && !hasQuic) {
|
|
delete stream.finalmask;
|
|
} else {
|
|
if (!hasTcp) delete fm.tcp;
|
|
if (!hasUdp) delete fm.udp;
|
|
}
|
|
}
|
|
|
|
// Hysteria's per-client auth lives in settings.clients[*].auth; the
|
|
// streamSettings.hysteriaSettings.auth slot is a holdover from older
|
|
// hysteria builds and serves no purpose on the inbound side, so an
|
|
// empty value shouldn't ride along in the JSON payload.
|
|
const hs = stream.hysteriaSettings as { auth?: string } | undefined;
|
|
if (hs && typeof hs === 'object' && (hs.auth === '' || hs.auth == null)) {
|
|
delete hs.auth;
|
|
}
|
|
}
|
|
}
|
|
|
|
export function formValuesToWirePayload(values: InboundFormValues): WireInboundPayload {
|
|
const settingsPruned = (pruneEmpty(values.settings ?? {}) ?? {}) as Record<string, unknown>;
|
|
if (Array.isArray(settingsPruned.clients)) {
|
|
settingsPruned.clients = normalizeClients(values.protocol, settingsPruned.clients);
|
|
}
|
|
let streamPruned = values.streamSettings
|
|
? ((pruneEmpty(values.streamSettings) ?? {}) as Record<string, unknown>)
|
|
: undefined;
|
|
if (streamPruned) {
|
|
streamPruned = normalizeStreamSettingsForWire(streamPruned, { side: 'inbound' });
|
|
stripTlsCertUseFile(streamPruned);
|
|
}
|
|
dropLegacyOptionalEmpties(settingsPruned, streamPruned);
|
|
const payload: WireInboundPayload = {
|
|
up: values.up,
|
|
down: values.down,
|
|
total: values.total,
|
|
remark: values.remark,
|
|
enable: values.enable,
|
|
expiryTime: values.expiryTime,
|
|
trafficReset: values.trafficReset,
|
|
lastTrafficResetTime: values.lastTrafficResetTime,
|
|
listen: values.listen,
|
|
port: values.port,
|
|
protocol: values.protocol,
|
|
settings: JSON.stringify(settingsPruned),
|
|
streamSettings: streamPruned ? JSON.stringify(streamPruned) : '',
|
|
// mtproto is mtg-served, not Xray, so sniffing never applies — emit empty
|
|
// rather than the default { enabled: false } so the row carries no sniffing.
|
|
sniffing: canEnableSniffing({ protocol: values.protocol }) ? JSON.stringify(normalizeSniffing(values.sniffing)) : '',
|
|
tag: values.tag,
|
|
shareAddrStrategy: values.shareAddrStrategy,
|
|
shareAddr: values.shareAddr,
|
|
subSortIndex: values.subSortIndex,
|
|
};
|
|
if (values.nodeId != null) payload.nodeId = values.nodeId;
|
|
return payload;
|
|
}
|