* fix(nodetoken): make the corrupt-ciphertext test corrupt deterministically
The test replaced the last two characters of the base64 body with "AA", which
can decode to the very same bytes: the body is RawURLEncoding of a 31-byte
blob, so the final character carries only 2 significant bits and the decoded
value is unchanged whenever the tag's last byte is 0x00. Measured over 50000
encryptions, 170 of those edits corrupted nothing — about one run in three
hundred fails for a reason that has nothing to do with the codec.
Flipping a bit of the decoded blob always changes the ciphertext, so the test
now pins the fallback behavior instead of the encoder's tail padding.
* style(nodetoken): trim the helper comment to the two-line limit
CLAUDE.md caps a committed Go comment block at two lines; the why fits.
* docs: add Discord bot to READMEs, architecture, operations guides, and locales
* docs: address review feedback on Discord bot formatting, backup commands, and architecture
* docs(discord): fix Persian typo and literal arrows on fa/zh bot pages
Senior review of #6513, two LOW findings in the two new pages:
- fa/operations/discord-bot.mdx:30 spelled "developers" with Cyrillic
"де" in place of Persian "ده", rendering a mixed-script word.
- Both pages copied `$\rightarrow$` from the en page. The docs site has
no math plugin (nothing in source.config.ts, no remark-math
installed), so the built HTML shows the literal string
"$\rightarrow$" in every menu path. Replaced with a Unicode arrow on
fa and zh; en and ru have carried the same since #6486 and are left
for a separate change.
---------
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
* docs: add TUIC v5 to READMEs, guides, and protocol references
* docs: address review feedback on TUIC architecture, external links, and i18n parity
* docs(tuic): drop the Xray-routing claim and qualify Limit IP for TUIC
The README feature bullet in all seven locales credited the TUIC sidecar
with "seamless Xray routing". A TUIC inbound never enters the Xray config
(internal/web/service/xray.go skips model.TUIC) and the generated
tuic-server config carries no forwarding target, so decrypted TUIC
traffic egresses from the sidecar directly and Xray routing rules never
see it; docs/architecture.md in this same branch already says so. An
operator reading the bullet would expect geo blocking and outbound
selection to cover TUIC clients.
The client field table marks Total (GB) as inbound-level for TUIC but
left Limit IP at "all". The IP-limit job's only data source is Xray's
online-stats API (internal/web/job/check_client_ip_job.go), which TUIC
clients never reach, so a Limit IP set on a TUIC client is silently
unenforced. Qualify that row the same way in en, fa, ru and zh.
---------
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
newSocks5UDPSession only bounded the dial. The greeting, auth and UDP
ASSOCIATE reads on the control connection had no deadline, and they run
inline in UDPRelay.Handle -- on the peer's receive goroutine that delivers
decrypted packets into gVisor. A SOCKS5 server the kernel accepts for but
that never answers (a wedged Xray: its listen backlog still completes TCP
handshakes) therefore parked that goroutine, and every later packet from
the peer behind it, TCP included, for as long as Xray stayed wedged.
One deadline now covers the dial plus the whole exchange and is cleared
once the association is up, since after that the control connection is
only held open. The test drives the exchange against a listener that is
never accepted, which is exactly the hung-server shape.
This was the last of the three defects confirmed on the issue: the header
protection key that could not be cleared went with cfd596a4, the missing
PersistentKeepalive with 8f162994, and the manager lock inversion the same
thread flagged with e95fe80f. The session death the issue was opened for
is not a panel defect. The reporter's own capture on the host NIC shows
the client's packets stop reaching the VPS after the first burst, the
server never sees a second handshake initiation from it, and nothing the
panel sends is outside what a stock amneziawg-go 3.1 server sends (the
Apple client embeds the same library build). That is a client- or
path-side stop, which no server-side change can address.
Closes#6323
Saving the node form writes the grown selection and marks the node dirty
in one transaction. On the next tick ReconcileNode runs before the
snapshot merge, and its delete sweep treats a selected tag with no
central row as "deleted on the master" — so an inbound the operator just
ticked in the picker (or every unselected one, when switching the node
to "all") is deleted from the node before the import that would have
created its row ever runs.
Nothing on disk separates "pending import" from "deleted while the node
was unreachable", but the pre-adoption guard already expresses the
former: while inbounds_adopted_at is zero the sweep waits for a clean
sync to adopt. A save that grows the managed set now zeroes it again,
and the same clean sync re-stamps it, so the offline-delete sweep is
only deferred by one successful sync, not disabled.
The trade: an inbound deleted on the master while the node was
unreachable is re-imported instead of swept if the operator grows the
node's selection during that same outage. That is visible and
recoverable, where the previous behaviour destroyed a live inbound.
Closes#6329
* fix(link): restore mKCP seed and headerType on share-link import
applyTransport / applyTransportParams ignored kcp query params that
applyKcpShareParams emits, so re-imported outbounds lost seed and
header and could not talk to the inbound. Mirror those fields (plus
mtu/tti) into kcpSettings in both Go and TS importers.
Fixes#6476
* fix(link): restore mKCP header/seed via finalmask mkcp-legacy
* fix(link): split mKCP header and seed into separate masks on import
Both importers folded a share link's headerType and seed into one
mkcp-legacy mask {header, value}. xray-core's MkcpLegacy.Build ignores
value once header is set (and reads it as the fake DNS domain for
header=dns), so an imported outbound carried the header mask but no
AES-128-GCM seed while the emitting inbound has both, and could not
connect — the failure #6476 reports, now for every link carrying both
params. Emit one mask per field, seed first: the finalmask array's
first item is the innermost layer, which puts the header around the
cipher as legacy mKCP did.
Also bound mtu/tti to KCPConfig.Build's accepted ranges (mtu >= 21,
tti 10..1000, decimal digits only on both importers) so a pasted link
cannot fail the whole Xray config load, and look header types up as
own properties so a prototype key such as "constructor" is not mapped.
---------
Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
* feat(inbounds): show linked host remarks in inbound list
Join Host Group remarks from the existing hosts list onto each inbound
row client-side so multiple endpoints (IPv4/IPv6/CDN) are visible without
opening the inbound. Truncate long lists with a tooltip for the full set.
Fixes#6026
* fix(inbounds): skip disabled host groups in inbound list remarks
buildHostRemarksByInboundId joined every host group from /hosts/list
onto its inbounds, so a group toggled off on the Hosts page still read
as a live endpoint in the inbound remark cell and matched the search
box. A disabled group serves nothing: internal/sub/host_sub.go filters
it out of subscription output and withMtprotoHostEndpoints skips it for
MTProto share links. Skip it here the same way, and drop the unread
`truncated` field from formatHostRemarksLabel.
---------
Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
* fix(logs): standardize login and logout logs
* fix(logs): log the real username on login lines
The four login log lines logged safeUser, the HTML-escaped copy kept for
the Telegram and email notifiers, so an account named o"reilly<1> showed
up as o"reilly<1> on login but o\"reilly<1> on logout. %q
already neutralises control characters, so the log now carries
form.Username and safeUser feeds only the notifiers.
Resolves the pre-existing LOW left on PR #6484. TestLoginLogsRealUsername
drives the success, plain-failure, blocking and refused paths over HTTP
and fails on the escaped value.
Refs #6483
---------
Co-authored-by: Mapioe <Mapioe@users.noreply.github.com>
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
* fix(web): restart panel after ImportDB so subPath routes match (#6446)
ImportDB only restarted Xray, leaving the subscription HTTP server on
startup-registered paths. Schedule the same in-process restart hook used
by restartPanel so restored subPath (and related) routes take effect
without relying on a browser follow-up that can fail after session invalidation.
* fix(web): schedule the post-import panel restart once, via PanelService
ImportDB grew a private copy of PanelService.RestartPanel (same hook check,
same Windows bail-out, same SIGHUP fallback, already diverging in log
severity) while BackupModal kept POSTing restartPanel after a successful
import, so one restore bounced the panel and the public sub server twice
back to back. The service package cannot reuse PanelService (panel imports
service), so the importDB controller now calls the existing
RestartPanel(3s) after ImportDB succeeds, the duplicated helper is dropped,
and the browser follow-up is removed; it waits out the restart and reloads.
Test drives the importDB handler against a stub xray binary and fails when
no restart is scheduled through the global restart hook.
---------
Co-authored-by: mrchatam <mrchatam@users.noreply.github.com>
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
Carry the hydrated reset cycle and day into the enable update payload so toggling a client does not normalize its schedule to never. Cover both toggle directions with a regression test.
* feat(geodata): add standard source presets
Expose the existing geofile allowlist to the Geodata editor so administrators can configure the supported scheduled downloads without copying URLs manually
Tested with npm run test, npm run lint, npm run typecheck, npm run format:check, and go test ./internal/web/service ./internal/web/controller -run '^(TestStandardGeodataSources|TestGeodata)' -count=1
Assisted-by: OpenCode:openai/gpt-5.6-terra (mostly)
* fix(geodata): preserve custom source entries
Add missing standard sources instead of replacing existing custom entries.
Assisted-by: OpenCode:openai/gpt-5.6-terra (mostly)
* fix(sub): gate external Clash shadowsocks links like the inbound path
clashProxyFromExternal returned as soon as it had built the ss proxy, so an
ss:// link skipped applyTransport/applySecurity: a node whose tcp/http
obfuscation Clash cannot express was emitted anyway (mihomo then opens a plain
shadowsocks stream at a server that requires the header, and the node silently
never connects), and security=tls was silently stripped. The inbound path runs
both helpers for every protocol, so the two Clash importers disagreed about the
same node.
* fix(sub): count a dropped external link in the quota header
The client email that feeds AggregateTrafficByEmails was recorded only when a
proxy came out of the link, so a node Clash cannot represent also vanished from
the Subscription-Userinfo header of every other node in the same subscription —
the header reported another client's numbers as the whole subscription's. The
inactive-link branch already counted an email without a proxy; make that
unconditional so the header describes the subscribers, not the representable
subset of their nodes.
* docs(sub): describe clashProxyFromExternal by what it does, not by protocol
The protocol list in the doc comment went stale the moment the shadowsocks
branch stopped returning early, and it restated what the switch already says.
* fix(link): rebuild shadowsocks tcp/http obfuscation on import
genShadowsocksLink encodes tcp/http obfuscation only as the SIP002
plugin=obfs-local;obfs=http;obfs-host=... parameter, deleting type, headerType,
path and host in the process, because SIP002 clients ignore those and read
`plugin` alone. ParseLink read none of them, so importing a link the panel had
just exported produced a plain tcp outbound with header.type none: the
obfuscation the inbound requires was gone, and the client could not connect to
the very inbound the link came from.
The plugin is now mapped back onto the header it stands for. Credentials and
every other parameter are untouched, and other plugin values are left as they
were because Xray has no equivalent for them.
* fix(link): map the SIP002 plugin in both importers
The panel parses share links twice: link.ParseLink in Go, which the external
subscriptions use, and parseShadowsocksLink in outbound-link-parser.ts, which
the Add Outbound button calls. Mapping the plugin in Go alone left the UI path
still saving header.type none for a link the panel had exported itself, so one
panel answered the same link with two different outbounds.
The unencoded plugin=obfs-local;obfs=http;... form maps as well now: stdlib
drops any query pair whose value holds a literal semicolon, and that is the
shape clients which skip percent-encoding emit, so the raw query is read as a
fallback when the parsed parameter is missing.
* fix(link): read the vmess certificate checks on import
applyVmessTLSParams writes ech, vcn and pcs into the vmess share object, but
parseVmess only read sni, fp and alpn back. Importing a link the panel had just
exported therefore dropped all three: no pinned certificate, no verify-by-name,
no ECH. On a server whose certificate is only trusted through a pin, the
imported outbound falls back to public-CA verification against the system roots
and cannot connect to the inbound the link came from.
The url-param protocols already read the same three in applySecurity, and the
core takes pinnedPeerCertSha256 as one joined string there, so the vmess path
now fills them the same way.
* fix(frontend): read the vmess certificate checks on import
The panel parses share links twice: link.ParseLink in Go and
parseVmessLink in outbound-link-parser.ts, which is what the Add Outbound
button calls. Reading ech, vcn and pcs in Go alone would have made the two
sides disagree on one link, leaving the UI path — the one an operator uses by
hand — still dropping the pin the panel had just exported.
* refactor(tgbot): make the add-client expiry presets say what they do
The wizard's "Add N days" buttons were a copy of the renewal handler, whose
accumulate branch they cleared two lines later: the branch tested a value the
line above had just set to zero, so it was dead and only the "set N days from
first use" path was reachable. That reads as an accident, and the automated
review of #6499 flagged it twice.
The wizard keeps the term it sets, which is now the code: a create flow has no
expiry to add to, the custom keypad lands in this same case, and a corrected
number has to replace the one it follows. 0 stays the Unlimited button. The
renewal handler (reset_exp_c) genuinely adds to the client's remaining time and
is unchanged.
* refactor(tgbot): fold in the review of the expiry-preset change
The test now starts every row from a term a preset could have left, so each row
fails on its own under the accumulate semantics rather than depending on the row
before it, and it reuses the package's draft helpers instead of a second copy.
The wizard presets drop the "Add" verb they never honoured; the renewal
keyboard keeps it, where reset_exp_c really does add to the remaining time.
* fix(tgbot): keep the add-client draft with the chat that owns it
The wizard held one package-level draft for the whole bot. Its steps run on
the ten-goroutine worker pool, so two admins adding a client at the same time
wrote into the same form: whichever step ran last decided the email, the
limits and the attached inbounds of a client the other chat went on to
create, and the attach picker mutated one shared slice from several
goroutines at once as well.
Each chat now gets its own draft, reached only through the chat that owns it
and held for the duration of a step, so a client is created from the values
its own chat collected.
* fix(tgbot): take the wizard's draft lock only for the wizard
A queued report tap held one of the ten worker slots while it waited on the
chat's draft, and every chat that reached answerCallback grew the draft map
even when the admin gate rejected it. Both follow from acquiring the draft
before the gate; the wizard's own steps are the only callers that read it.
The draft is now looked up under the same admin-and-wizard check, addClient
takes the draft its caller locked instead of looking it up again, a submit
drops the entry, and StopBot clears the map with the conversation states.
A delayed-start expiry is stored as a negative duration, but the card checked
the disabled-client branch before the sign of that duration, so it printed the
epoch position (-2592000000 ms -> 1969-12-02) and labelled it an expire date.
The sign decides first now, which is how BuildClientDraftMessage in this file,
subscriptionExpiryFromClient and adjustTraffics already read the same value; the
Discord card is the one surface still reading it as unlimited, fixed in #6498.
`!inbounds` built a single embed with one field per inbound and sent it as
it was. Discord rejects the whole message past 25 fields, ten embeds or 6000
counted characters, so an operator holding more than 25 inbounds got no
answer at all, and a remark longer than ~252 runes broke the command on its
own — the `📍 ` prefix spends four units of the same 256-unit field name cap.
The failure left no trace either: the send error was discarded, so the
channel stayed empty and the log stayed quiet.
Fields are now capped by the same helper every other reply in the package
uses for its name and value limits, and packed into messages that fit those
caps, with the header leading only the first embed of each message. The caps
are counted the way Discord counts them, in UTF-16 units, and a page it
answers with a 429 is waited out once rather than dropping the pages behind
it.
The heartbeat goroutine wrote op 1 on its interval and ignored op 11, so a
connection that stopped being answered was never noticed. A half-open socket
is the case that matters: the kernel accepts the writes and the read loop
stays blocked, so the bot serves nothing for as long as the panel runs, and
nothing in the log says so. Discord asks clients to close and reconnect when
a heartbeat goes unacknowledged, which is what the ticker now does, letting
the existing reconnect loop take over.
The writeMu regression test's fake gateway answered no heartbeat at all,
which the new check reads as a dead socket; it now acknowledges them the way
Discord does and paces its op 1 flood, keeping its one-second window of
concurrent writes intact.
!usage printed Unlimited for any client whose expiry was not a positive
timestamp, but the panel stores "Start After First Use" as the duration
negated and converts it on the first traffic tick. Such a client does expire,
so the operator reading that embed was told the opposite of what the panel
and the Telegram bot already say, which both render the same value as days.
* feat(settings): allow customizing Reality scan candidate list
Persist a realityScanCandidates panel setting (defaulting to the previous
hardcoded list), expose it in General Settings with i18n, and have the
Find Targets scanner use it when the search box is empty.
Fixes#5847
* style(frontend): oxfmt realityScanCandidates in setting.ts
* Fix locale JSON syntax
This change removes the malformed duplicate key and missing comma in the Android per-app proxy translations across the bundled locale files. The JSON now parses correctly while preserving the translated labels for each language.
* docs(i18n): update Happ translations
Localize the remaining Happ subscription settings strings across the translation files and refine the English copy. This aligns the labels and descriptions with the current Happ behavior for notifications, TUN options, HWID enforcement, routing presets, and per-app proxy settings.
* refactor(reality): drop test-only scaffolding from the candidate setting
TestDefaultRealityScanCandidatesCSV compared the CSV against its own
initializer and a defaultValueMap lookup, and
TestRealityScanCandidateTokensFallsBackWithoutDB drove a no-database
state no production caller reaches (the only caller is the
scanRealityTargets handler, served after InitDB). The
s != nil && GetDB() != nil guard existed only for that second test.
None of them could fail except in lockstep with the code they restate.
* docs(api): describe the setting-driven scanRealityTargets fallback
An empty targets value now probes the realityScanCandidates setting,
but the endpoint summary, parameter description and handler comment
still promised the built-in seed list, so API consumers were told the
wrong target set. Regenerated openapi.json and synced the docs copy,
which also lacked the new AllSetting field in the settings reference.
---------
Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
* feat(discord): add Discord notification bot service, settings UI, and event subscriber
- internal/web/service/discord: implement lightweight Discord REST API v10 client and EventBus subscriber
- internal/web/service/setting: add discordBotEnable, discordBotToken, discordChannelId, discordEnabledEvents, discordCpu, discordMemory settings and secret protection
- internal/web/controller: register POST /panel/api/setting/testDiscord endpoint
- frontend: add Discord settings tab, notifications configuration, sidebar navigation, and command palette integration
- translation: add localization keys across all 13 locales
- tests: add comprehensive unit tests with httptest server and verify route/i18n contracts
* fix(discord): address PR review findings on concurrency, linting, i18n, and stories
- subscriber: eliminate unbounded goroutines, sending inline per EventBus contract
- discord: accept context.Context in SendMessage, SendEmbed, SendTest with http.NewRequestWithContext
- format: apply gofumpt to controller and entity struct alignments
- i18n: localize testDiscord controller responses across all 13 locales
- storybook: add DiscordNotifications.stories.tsx component story
* docs: add Discord bot setup and operations guide
- add docs/content/docs/en/operations/discord-bot.mdx with setup steps, event indicators, settings, and troubleshooting
- add docs/content/docs/ru/operations/discord-bot.mdx with localized instructions
- update operations/meta.json across en, ru, zh, fa
- link Discord bot from panel configuration overview
* feat(discord): add discordLang, discordRunTime, discordBotBackup settings and update settings UI
- internal/web/entity: add DiscordRunTime, DiscordBotBackup, DiscordLang fields to AllSetting
- internal/web/service/setting: add defaultValueMap entries, getters, and setters
- frontend: update AllSetting schema, model defaults, and generate OpenAPI / Zod contracts
- frontend: extract shared NotifyTimeField component and update DiscordTab with General and Notifications tabs
- translation: add localization keys across all 13 locales
* feat(discord): implement scheduled status reports and database backup attachments
- internal/web/service/discord: add SendMessageWithFiles supporting multipart uploads
- internal/web/service/discord: implement BuildReport and SendReport generating rich status embeds
- internal/web/service/discord: attach database backup (and config.json) when discordBotBackup is enabled
- internal/web/job: implement DiscordNotifyJob scheduled via robfig/cron
- internal/web/locale: add LocalizerFor and I18nForLang helpers
- internal/web/controller: trigger reloadDiscordFunc to dynamically reschedule cron upon setting changes
- internal/web/web: register and reschedule DiscordNotifyJob
- tests: comprehensive unit tests for multipart uploads, status reporting, and job execution
* feat(discord): add interactive bot commands via Gateway WebSocket and update documentation
- internal/web/service/discord/gateway: connect to Discord Gateway v10 via WebSocket (gorilla/websocket)
- internal/web/service/discord/gateway: handle heartbeat loop, reconnection, and command dispatch
- commands: implement !status, !report, !backup, !usage <email>, !inbounds, !restart, !help (with ! and / prefixes)
- internal/web/web: start/stop Gateway client with server and reload dynamically on setting updates
- docs: update operations guide (en, ru) with scheduled reports, backups, commands, and privileged intents
- tests: add end-to-end WebSocket Gateway test verifying command handling
* style(discord): fix goimports formatting and add 3x-ui to gitignore
* fix(discord): stop gateway panics, reconnect storms and proxy bypass
The Gateway client wrote to its websocket from both the heartbeat ticker
and the read loop answering server-requested op 1 heartbeats. gorilla
panics on concurrent writes and neither goroutine recovers, so a colliding
heartbeat took the whole panel process down; writes now share writeMu.
It also reconnected every 5s forever after close codes Discord marks
non-reconnectable (4004 bad token, 4010-4014, including 4014 when Message
Content Intent is off), re-identifying and logging a warning each time.
The loop now stops on those codes; the docs say to restart the panel.
The gateway dialed with websocket.DefaultDialer, bypassing the panel
egress proxy the REST client already uses, so where Discord is filtered
notifications arrived but commands never connected.
* fix(discord): deliver the scheduled report when the backup upload fails
SendReport posted the report embed and the x-ui.db/config.json attachments
in one multipart request. Once the database outgrows Discord's upload cap
(20 MiB by default) the request is rejected and the report embed is lost
with it on every run, leaving only a log warning. Send the embed first and
the attachments as a second message.
* chore(discord): delete tests that pass whether or not the code works
TestDiscordNotifyJob_NilServiceNoPanic and TestHandleEvent_NilDiscordService
feed a nil DiscordService that web.go never passes, and
TestDiscordNotifyJob_DisabledNoPanic passes with or without the enable
guard because Xray is not running under test.
* fix(discord): require admin user IDs for bot commands and honor discordLang
Any member who could post in the configured channel could run !backup
(the whole x-ui.db and config.json, even with discordBotBackup off),
!restart and !usage. Commands now run only for the Discord user IDs in
the new discordAdminIds setting; an empty list turns commands off.
discordLang was saved and offered in the UI, but nothing read it, so
every embed stayed English. The test message, alerts, the scheduled
report and command replies now render through I18nForLang in the chosen
language, with a discord section in all 13 locales. InitLocalizer takes
an fs.FS so tests load the real translation files.
---------
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
Reset all traffics and the sorted usage report replied with one Telegram
message per client. A panel with a few hundred clients therefore fired a
burst of sendMessage calls that trips Telegram's per-chat rate limit and
throttles the bot for every user, not just the admin who tapped.
Both reports are now assembled into one string and handed to
SendMsgToTgbot, which already pages long messages.
Two details the batching would otherwise lose: the reset report still
answers (with the reply keyboard removed) when the panel has no clients,
and both reports are HTML-escaped as a whole, because a single stray "<" in
a remark or an email now costs the ~15-client page it lands on instead of
one client's message.
* feat(clients): add stateless Happ link generator
Generate Happ provider links from the current effective subscription source without caching results. Reject unsafe provider responses and redact failure diagnostics.
* fix(clients): reject duplicate Happ provider fields
Parse Happ provider objects token by token so duplicate supported keys cannot be silently overwritten by encoding/json.
* feat(clients): expose on-demand Happ link API
Expose a no-store client endpoint backed by the Happ link generator and keep its generated OpenAPI contract synchronized.
* fix(openapi): exclude service interfaces from generated types
Keep dependency-injection interfaces out of the frontend API surface while preserving allowed response schemas.
* feat(clients): add stateless Happ QR presentation
Generate Happ links only for the active modal scope and retire late responses so Standard remains immediately available. Add focused component coverage and localized retry guidance across every locale.
* fix(clients): cover overlapping Happ generations
Prove the cancellation cleanup is required by resolving a retired request while its replacement remains pending. Also wait for Regenerate to leave loading state before exercising the existing action.
* fix(clients): harden Happ link handling
Validate generated responses before rendering and hide actions during unresolved requests. Strengthen route, redirect, timeout, and lint regression coverage with mutation-sensitive tests.
* fix(clients): gate Happ link generation behind operator opt-in
- add a fail-closed happLinkEnable setting
- enforce the gate before and after provider requests
- add locked Happ QR state with privacy disclosure and settings link
- cover backend, frontend, settings, and i18n regressions
* fix(frontend): guard oversized Happ QR codes
Keep valid long crypt5 links copyable while suppressing QR rendering and image actions above the encoder's UTF-8 byte limit. Add localized guidance and boundary coverage.
* fix(clients): log the sanitized transport error for Happ link failures
Every fail() call in HappService.Generate passed a string literal as the
detail, so the sanitizer written for provider errors only ever saw
constants, and an operator following the QR modal's "check Logs" hint
found nothing beyond reason=transport. Transport and body-read errors now
flow through sanitizeHappDetail, which also redacts cookie/session pairs.
Drop TestHappLinkEnableDefaultsOffWithoutPersistingRow: it pinned a getter
and its constant default, which the Generate gate test already drives.
* fix(frontend): size the Happ QR cap to level L and keep the QR modal mounted on close
HAPP_QR_MAX_BYTES was the level-M capacity (2331) while QrPanel encodes at
errorLevel "L", whose version-40 byte-mode capacity is 2953, so valid links
between 2332 and 2953 bytes lost their QR. The cap now matches the encoder
and a test renders the real QrPanel at the boundary.
Keying the modal content on `open` remounted it on every close, which cut
the Modal's exit transition and made the openSubId sync unreachable, so
`loading` never turned on for the subLinks fetch and a client without a
subscription link flashed noLinks on reopen. `open` leaves the key and the
sync block now also resets the Happ state.
* chore(clients): request Happ crypt5 links from api-v3
crypto.happ.su serves api-v2.php and api-v3.php side by side. Probed with
the same payloads, both take {"url"} over a JSON POST, answer
{"encrypted_link":"happ://crypt5/..."} of identical length with the same
crypt5 key marker, and fail the same way: 400 "No url provided.",
500 "Invalid URL format.", 405 on GET. Happ's own generator page is
branded "URL Encryption v3", so the panel follows it. The parser and the
link validator are unchanged.
* feat: add local generation of encrypted Happ links
- Implemented functionality to generate encrypted Happ links locally without network dependency.
- Added validation for URL length and format to ensure compliance with processing limits.
- Introduced new error handling for invalid URLs and control characters.
- Updated translations for various languages to reflect changes in Happ link generation.
- Created unit tests to validate the encryption process and ensure session keys and nonces are unique.
* fix(frontend): match the tuic memo deps to the non-optional subSettings
The Happ branch reads subSettings non-optionally in ClientQrModalContent
(happLinkEnable and the WireGuard/AmneziaWG publicHost memos), so React
Compiler infers subSettings.publicHost. The TUIC memo merged in from main
still listed subSettings?.publicHost, which fails oxlint's
preserve-manual-memoization rule and makes the compiler skip optimizing
the component. make verify stopped at lint-fe on the branch head.
* chore(happ): trim the pinned-key provenance comment to two lines
CLAUDE.md caps a comment block at two lines. The bare URL line repeated
the repository and file the next line already names, so it is folded
into that line (review LOW on happ_crypto.go).
---------
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
staleButtonServer increments its per-method map from the HTTP handler, which
httptest runs on one goroutine per connection. #6491's
TestAdminListReadersShareTheWriterLock is the first test to reach it from
several goroutines at once, so CI's race job flagged the helper's map rather
than the code under test.
#6493 was written against the if/else chain where every served link action
returned early, so its trailing answer ran only for an unrouted payload. #6489
had already turned that chain into a switch that falls through, so after the
merge every served link tap also got an error toast, while an unknown payload
still returned from the !ok branch unanswered.
Move the answer into the !ok branch, the one place nothing matched. This
turns TestClientLinkCallbackServesOwnClient and TestUnroutableCallbackIsAnswered
green again on main's go-test job.
* feat(sub): let the panel set the JSON subscription DNS servers
A baked routing profile (#6402) carries only the DNS its preset defines, so an
operator who wants their own resolvers has to override the whole profile or
patch the subscription behind a proxy.
Add the subJsonDns setting: either a full xray dns block or a bare array of
servers. It wins over the profile's DNS while leaving the profile's routing
rules intact, and reaches per-inbound, balancer and info-node documents alike.
The value is validated with xray's own schema (internal/xray/dnsconf): a block
the client could not load is rejected when the settings are saved and ignored
with a warning at request time, instead of being baked into every document.
Both the sub server and the settings API share that validator, so a stored
value can never be silently dropped.
xray's Build() is deliberately not used for validation: it resolves geosite
tokens from the geodata files and would reject valid configs whenever those
are absent from the panel's working directory.
* style(dnsconf): drop the ineffectual initial map assignment
golangci's ineffassign flagged the zero-value map whose value both paths
overwrite: the object branch now assigns the decoded map directly.
* docs(sub): scope the DNS setting to the documents it rewrites
The Routing header mirrored to Happ/INCY keeps the routing profile's own
resolvers, so the setting description and the header-source comment now say
so instead of claiming the profile's DNS is replaced everywhere.
Also trims two comments in the new dnsconf package to the repo's two-line cap.
Telegram keeps a tapped button in its loading state until the callback is
answered, and three paths dropped the tap without answering: a payload that
matched no case in the email-scoped switch, one that matched nothing in the
switch that follows it, and a button whose hash had aged out of the 20-minute
storage, which replied with a chat message only.
All three answer now. The email-scoped switch is reached only by an admin's
payload carrying arguments, and today an unknown action there falls out of the
switch into a return that tells the operator nothing.
The expired-hash path keeps the chat message as well, because
sendCallbackAnswerTgBot is a single unretried call while SendMsgToTgbot retries
connection errors, and after a panel restart that notice is the only
explanation the admin gets.
The draft is sent with ParseMode HTML but was written in Markdown, so every
card showed literal asterisks and backticks while the rest of the bot's
messages render properly. Its admin-supplied values (email, comment, TG id,
inbound remarks) were also interpolated raw, and a single '<' in any of them
makes Telegram reject the whole message as unparsable.
The wizard's own email and comment prompts echo those same draft values into
HTML-parsed messages and were escaped too: the card is deleted before the
prompt goes out, so a rejected prompt left the admin with an empty screen.
Start and Stop replace adminIds under tgBotMutex, but the report cron, the
backup job and every incoming callback (checkAdmin) read it unlocked. A
concurrent read of a slice header being replaced is not a benign race: it can
observe a torn header and iterate past the backing array. The readers now take
a snapshot under the same lock, and SendMsgToTgbot uses the existing IsRunning
accessor instead of reading the flag directly.
A non-admin tapping a subscription, individual-links or QR-links button was
served whatever email that button carried. Those keyboards outlive the chat
they were sent to (group chats, forwarded cards, a client whose tgId was
later revoked), so the email in the callback data cannot authorise itself.
The lookup the self-service usage command already performs now decides
whether the callback is served.
The gate also has to read the email at all: encodeQuery replaces any
callback payload past 64 chars with a hash, so for a client whose email is
long enough the non-admin path saw a bare hash and dropped the tap without a
word. The raw data is now decoded before the gate, which is the same decode
the admin path already performs, and an email the caller cannot prove is
answered with the generic error instead of silence.
* fix(link): preserve Shadowsocks TLS query params on import
Mirror trojan/vless stream parsing so Xray-native type/security/sni/alpn/fp
query params on ss:// links survive into streamSettings on both Go and TS importers.
Fixes#6094
* fix(link): drop extra blank line so oxfmt passes
---------
Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
When Authorization: Bearer is present but does not match (or is disabled),
respond with 401 Unauthorized so script authors can distinguish auth failure
from a wrong webBasePath. Requests with no Authorization header still get
404 masking; wrong base paths continue to 404 via NoRoute.
Fixes#6255
Co-authored-by: mrchatam <mrchatam@users.noreply.github.com>
Replaced the legacy starchart.cc widget with Star History chart and badge embeds in the main README and all localized variants. This keeps the star visual consistent and adds ranked/trending badges for easier repository context.
* feat(settings): add Block tab for JSON subscription routing rules
Expose the existing blackhole outbound in the subscription formats UI so
operators can add block domain/IP rules without editing subJsonRules by
hand. Scope Direct/Block helpers by outboundTag so the tabs keep separate
rule objects, and keep block rules ahead of direct for Xray match order.
* fix(settings): preserve rule order and clear foreign leftovers
Stop sorting the whole subJsonRules array on every write. Prepend block
defaults only when enabling Block. Clearing the last managed tag also
drops foreign-tag leftovers so the panel can reach an empty setting.
Fixes oxfmt on SubscriptionFormatsTab.
---------
Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
* fix(inbounds): allow negative subSortIndex for subscription order
Preserve explicitly set negative indices so primary inbounds can sort
ahead of the default without renumbering peers; keep 0/omitted → 1.
* fix(inbounds): gofumpt model.go and trim subSortIndex comments
---------
Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
* feat(reality): warn when target cert chain is too small for ML-DSA-65
Expose peer cert-chain DER size from the REALITY scanner and surface a UI
warning when ML-DSA-65 is enabled but the chain is under xray-core's 3500-byte
minimum, so silent fallback failures are easier to catch.
Fixes#5973
* fix(reality): gate scanner ML-DSA tag and sync docs OpenAPI
Only warn on short cert chains in the target scanner when ML-DSA-65 is
enabled. Copy frontend/public/openapi.json to docs/public/openapi.json
and fix oxfmt wrapping in the new test.
---------
Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
* fix(clients): preserve enable on portable import
Stop BulkCreate and orphan ImportClients from forcing enable=true, and
restate Enable=false after GORM Create (clients.enable default:true drops
the zero value). Interactive Create still defaults new clients to enabled.
Fixes#6478.
* fix(clients): respect enable=false on node mirror; omit enable defaults true
---------
Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
* feat(clients): show short HWID fingerprint in admin device list
Expose a 12-char prefix of the stored hwid_hash in the admin HWID list API and UI so admins can distinguish devices without querying the database. Full hashes and raw HWIDs remain unexposed.
Fixes#6359
* ci: retrigger release matrix after 386 dependency download flake
---------
Co-authored-by: mrchatam <mrchatam@users.noreply.github.com>
Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
* fix(clients): use EffectiveFlow in BulkAttach
Mirror Attach (#4834): seed wire clients from EffectiveFlowsByEmails so a zeroed clients.flow column does not drop Vision on bulk attach (#6432).
* test(clients): cover BulkAttach Vision flow when clients.flow is zeroed
Regression for #6432 — same scenario as TestAttach_PreservesVisionFlowWhenCanonicalColumnZeroed.
* fix(clients): only apply EffectiveFlow when present in BulkAttach
Avoid overwriting a non-empty clients.flow when EffectiveFlowsByEmails
has no entry for the email. Also drop the extra blank line that broke gofumpt.
---------
Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
* docs(readme): add 3X-UI Manager to Community Tools
* docs(readme): add the Community Tools entry to the localized READMEs
The section is mirrored in all seven READMEs, and #4114 added it to every one
of them in a single commit — adding the entry to the English file alone leaves
the other six readers with a silently shorter list.
Each line uses that file's own wording for "License" and for
inbounds/clients/nodes, matching the entry above it.
* fix(inbounds): serve fresh client UUIDs for list and allLinks (#6436)
Resolve clients from the clients table in inboundLinks and
backfillClientStats so /inbounds/list ClientStats and allLinks match
the running Xray identity when embedded settings JSON is stale.
* fix(sub): keep WG/AWG settings identity in link exports (#6436)
clientsForLinkExport uses the clients table for UUID-bearing protocols and
the inbound settings JSON for WireGuard/AmneziaWG so allLinks and per-client
QR links stay consistent without collapsing per-inbound tunnel keys.
* fix(sub): fall back to settings clients for link export (#6458)
Prefer ListClientsForInbound for UUID protocols, but when the clients
table is empty or unavailable fall back to GetClients so settings-only
inbounds (and share-link unit tests) still produce links. Keep WG/AWG
on settings identity.
---------
Co-authored-by: mrchatam <mrchatam@users.noreply.github.com>
Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
* fix(amneziawg): honor inbound listen when binding UDP socket
AmneziaWG inbounds ignored the listen field and always opened
awgconn.NewDefaultBind(), so multi-IP hosts replied from the primary
address and handshakes to a secondary IP never completed (#6367).
Carry Inbound.Listen on amneziawg.Instance, open a Bind pinned to that
address (wildcard when empty/0.0.0.0/::), and include listen in
addressFingerprint so edits rebuild the Device.
Fixes#6367
* fix(amneziawg): fall back to wildcard when listen is unusable
Invalid or non-local listen values no longer hard-fail inbound startup;
treat ::0/[::0] as wildcards and normalize listen in the bind fingerprint.
* fix(amneziawg): use ListenConfig.ListenPacket for noctx
---------
Co-authored-by: mrchatam <mrchatam@users.noreply.github.com>
Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
* feat(clients): add Generate button for WireGuard/AmneziaWG PresharedKey
Matches existing key regenerate controls on the client form. Value is
32 random bytes base64 via Wireguard.generatePresharedKey (same as
wg genpsk). Field stays optional.
Fixes#6343
* fix(clients): keep FormField for WireGuard PresharedKey generate
Restore RHF FormField (noStyle inside Space.Compact) so the regenerate
control matches inbound reality patterns and satisfies oxfmt.
---------
Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
* fix(clients): snap EOM 23:59:59 expiry to billing midnight without renew (#6300)
Inclusive end-of-month expiries share the next calendar billing boundary.
Normalize onto that midnight before the catch-up loop so the first charged
step is a full month and resetMax=1 is not spent on a one-second alignment.
* fix(clients): snap only the EOM 23:59:59 instant, not the whole prior day
The calendar renew guard was matching [boundary-1d, boundary), so a midday
expiry on the day before billing could be snapped past now with renewals=0
and left disabled until midnight. Narrow to [boundary-1s, boundary).
Also clear golangci (gofumpt/QF1001), trim comments to 2 lines, and pin that
midday expiry still charges for alignment.
---------
Co-authored-by: mrchatam <mrchatam@users.noreply.github.com>
Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
Go share-link importer dropped verifyPeerCertByName for VLESS/Trojan/SS
TLS while the TS parser and Hysteria2 path already kept it. Fixes#6477.
Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
This change bumps the frontend and Go dependency set to newer patch/minor releases, including Vite, react-hook-form, zod, and the x/* Go modules. It also fixes a compatibility issue in the settings UI by switching Ant Design's Space usage from the deprecated `direction` prop to the current `orientation` prop.