Compare commits

..

56 Commits

Author SHA1 Message Date
MHSanaei 09617f04f5 feat(panel): let a sponsor slot start at a scheduled time
sponsors.json only had an end date, so a booked placement had to be
added to the file on the day it started. An optional `from` now hides
a sponsor (and its logo) until that instant; entries without it show
immediately as before.
2026-09-27 16:32:45 +02:00
MHSanaei 044e2926a0 fix(amneziawg): let the wrapped bind build peer endpoints
resolvingBind.ParseEndpoint resolved a hostname and then built a
StdNetEndpoint itself. That matches StdNetBind, the default bind on
Linux, but on Windows the default is WinRingBind, whose Send refuses any
endpoint it did not parse ("endpoint type does not correspond with bind
type"). Every handshake initiation failed there, so no AmneziaWG tunnel,
inbound or outbound, could come up on the Windows builds. ParseEndpoint
now hands the resolved literal to the wrapped bind's own parser, which
returns the endpoint type that bind sends to; StdNetBind and pinnedBind
build the same StdNetEndpoint as before.

The resolvingBind tests now read endpoints through the Endpoint
interface instead of asserting StdNetEndpoint, which had pinned the bug.
2026-09-27 16:14:45 +02:00
MHSanaei 75f3702dd3 fix(amneziawg): fall back to a free egress port when 64900 is refused
The panel's SOCKS5 egress for AmneziaWG outbounds bound the fixed
127.0.0.1:64900, and every generated socks bridge dialed that constant.
64900 sits inside Windows' dynamic port range, where the OS can reserve
whole blocks (this host excludes 64885-64984), so on the Windows builds
release.yml ships the listener could stay down and every AmneziaWG
outbound with it. Listen now tries 64900 first and falls back to any
free loopback port; bridges, the outbound probe and the port-conflict
check use EgressPort(), the port actually held. Bridges are generated
apart from the listener, so BuildSocksBridge records the port it wrote
and the AmneziaWG job requests an Xray restart while the listener holds
a different one. Where 64900 is free nothing changes.

The job's restart request is two lines of wiring no test reaches; the
staleness it acts on is pinned by
TestBridgesStaleUntilRegeneratedForTheBoundPort.
2026-09-27 16:09:54 +02:00
MHSanaei 8f47b53879 style(settings): fold the Happ settings into four tabs
Seven tabs, several holding one or two settings, made the page hard to
scan. The encrypted-links switch moves above the tabs under
auto-detection, the colour profile joins the banners under Appearance &
Theme, and Android per-app proxy joins Network & TUN Engine. The QR
modal's settings link no longer needs a happTab selector, and the three
orphaned tab-label keys are dropped from every locale.
2026-09-27 16:06:42 +02:00
MHSanaei a33b2341e9 style(clients): put Traffic Reset and Auto renewal on one row
The renewal block took a full-width column, pushing Traffic Reset onto
its own line. Each now gets a half-width column like the other fields,
with its follow-up inputs stacked under it.
2026-09-27 16:06:36 +02:00
MHSanaei 3fc3992a46 fix(nodetoken): stop refusing every node-token key file on Windows
FileKeySource rejected any key file whose mode had group or other bits,
but Windows has no such bits: Stat reports every writable file as 0666.
On the Windows builds release.yml ships, the key file therefore never
loaded, not even one written 0600, and only XUI_NODE_TOKEN_KEY could
supply a key. The mode check now applies off Windows only, the stance
the DB permission tests already take; there the file's NTFS ACL guards
it, and env-vars.mdx says so in all four locales.

The load test is split so the half that must hold everywhere, an
owner-only file loading, also runs on Windows, and the rejection half
asserts the exact error instead of any error.
2026-09-27 15:55:42 +02:00
MHSanaei ff322f901a fix(panel): skip the proxy env forwarding test on Windows
Windows env var names are case-insensitive, so https_proxy and
HTTPS_PROXY resolve to the same variable there and updateProxyEnvVars
forwards it under both names. The helper only runs on Linux - startUpdate
refuses every other platform - so the test's case-sensitive expectations
only hold, and only matter, on Linux.
2026-09-27 15:32:22 +02:00
MHSanaei 249b38e156 fix(logger): reuse the open log rotator when InitLogger runs again
Every InitLogger call built a new lumberjack rotator and dropped the old
one without closing it, leaking a handle on 3xui.log per call, and
loggers still writing through an old rotator kept it alive. On Windows
the open handles block deleting the file, so
TestInitLoggerConcurrentWithLogging failed its t.TempDir cleanup there.
InitLogger now reuses the open rotator for the same path and closes it
only when the path changes, and the test closes the logger it opened.
Neither half is enough alone: with only one of them the test stays red
on Windows.
2026-09-27 15:32:20 +02:00
MHSanaei 18b337d131 fix(database): close the pool a second InitDB replaces
InitDB assigned the new pool over the old one without closing it. The
panel's own restore flows call CloseDB first, but any other re-init
leaked the replaced pool and its handle on the database file. On Windows
that handle blocks deleting the file, which is why the four GetApiToken
CLI tests failed their t.TempDir cleanup there: dbtest.InitDB opened the
store, then GetApiToken's own InitDB replaced it. InitDB now closes the
previous pool itself; sql.DB.Close is idempotent, so the restore flows
behave as before.
2026-09-27 15:32:17 +02:00
MHSanaei f6a1a3bbd1 chore(git): check out every text file with LF, not only Go and scripts
.gitattributes forced LF only for Go, shell, generated files, snapshots
and deploy YAML, so a Windows clone with core.autocrlf=true got CRLF
everywhere else. On that working copy `make format-check` flags 198
frontend files, `msw-worker-check` sees mockServiceWorker.js differ from
the installed copy, and TestAnalystContextNamesRealCIJobs and
TestReviewNamesRealCIJobsAndGates find no ci.yml job at all, while Linux
CI stays green. `* text=auto eol=lf` extends 5c5a5096 to every text
file. No committed blob changes: the index already holds LF everywhere,
and binary detection still leaves the 50 binary files alone.

An existing Windows clone applies it with a fresh checkout on a clean
tree: `git rm -rq --cached . && git reset -q --hard HEAD`.
2026-09-27 15:17:34 +02:00
MHSanaei a579357343 refactor(logger): choose the console backend with build tags
The runtime.GOOS switch compiled the syslog branch into Windows builds,
where go-logging's syslog stub always returns an error. staticcheck
therefore reported SA4023 at logger.go:95 on every Windows lint run,
keeping `make lint-go` red on a clean main there while Linux CI never
saw it. console_windows.go and console_other.go now pick the backend at
build time, with each platform's behaviour unchanged.

No test can observe build-tag selection: `golangci-lint run` on Windows
goes from 1 issue to 0, and `GOOS=linux golangci-lint run
./internal/logger/...` stays clean.
2026-09-27 15:05:01 +02:00
pcxzs 7aa5fc085f feat(tgbot): access levels and /start account binding (#6518)
* feat(tgbot): gate the bot behind three user levels

Every Telegram account that found the bot could run /help, /status and
/usage, and tap any client button it could forge: nothing separated an
account no admin had bound from a customer.

Each update now resolves to stranger, client or admin, and commands are
allowlisted per level so a command added later stays admin-only until it
is listed. A stranger may run /start and /id only, and /start answers with
the ChatID an admin needs to bind it; a stranger's callbacks are answered
and dropped. Client detection reads the same tgId lookup as
clientOwnedByTgUser, so the level gate and the ownership check agree.

The bot also ignores everything outside private chats: authorization keys
on the sender while wizard state keys on the chat, and the two are the
same identity only in a private chat.

* feat(tgbot): bind Telegram accounts through /start deep links

Linking a customer meant the customer sending /id and an admin copying
the ChatID into the client by hand, which does not scale past a few
customers and is easy to get wrong.

The admin client card now offers an invite link, t.me/<bot>?start=<subId>,
and the first account to open it is bound through the existing
SetClientTelegramUserID. A subId already grants the subscription, so
binding gives the holder nothing the token did not. A subscription that
spans several clients binds all of them, and is refused if any part
belongs to another account; re-opening your own link is idempotent.
Unknown and already-claimed tokens share one reply, so the link cannot
be used to probe for valid subIds.

* fix(tgbot): harden invite claims after review

Review of the access-level and binding change found five problems:

- Concurrent claims of one link all read the client as unbound, all bound
  and all were told so, while only the last write held. Resolving and
  binding now share one lock, and a bind that fails part-way through a
  multi-client subscription undoes the bindings it already made.
- A subId has no minimum strength and the bot needs only its public
  username, so /start was an unthrottled guessing oracle. Non-admin claim
  attempts are capped at five per account per hour, the first refused one
  notifies the admins, and the Subscription ID field now says it doubles
  as the bot invite code.
- levelOf expanded every inbound's client JSON on every non-admin update.
  It now reads the indexed tg_id column of the clients table.
- A button tapped in a group chat was dropped unanswered and kept
  spinning, with nothing logged. It is answered now, and each ignored chat
  is logged once.
- The subId was pasted raw into the t.me link, so '#' or '&' truncated it
  and Telegram rejects anything outside A-Za-z0-9_-. The payload is now
  base64url, and a subId too long for the 64-character limit is refused.

* fix(tgbot): answer group chats again and make the claim race test bite

ignoredChat dropped every non-private chat because wizard state was
keyed by chat while authorization keyed on the sender. #6604 on main
re-keyed that state by (chat, user) so admins can drive the bot from a
group, so after the merge the drop only took the whole bot away from
those admins, report keyboards sent to a group included. The level gate
already keys on the sender, so group chats need no special case.

TestConcurrentClaimsBindOnlyOneAccount passed with inviteClaimMu
removed: the first claimant took the pool's idle connection and bound
before the rest had opened theirs, so no two ever raced. It now holds
the inbound write the binds need until every claimant has resolved,
and fails without the lock ("6 accounts told they bound").

TestCommandAllowed restated the commandsByLevel map; TestGateCommand
drives the same allowlist through gateCommand. TestIgnoredChat goes
with the code it pinned.

* docs(tgbot): document access levels and invite links

The command table still said /help and /status answer anyone. An
account no admin has linked now reaches only /start and /id, and a
customer is linked through the client card's Invite Link, whose token
is the Subscription ID. Updated in en, fa, ru and zh.

---------

Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
2026-09-27 13:33:29 +02:00
mrchatam 6f40a75909 feat(inbound): excludeFromSub hides links without disabling (#6463)
* feat(inbound): excludeFromSub hides links without disabling

Add a per-inbound flag that omits subscription output while keeping the
inbound enabled for Xray, auth, and traffic accounting. Fixes #6435.

* fix(inbound): excludeFromSub review follow-ups

gofumpt model.go, sync docs OpenAPI, keep excludeFromSub master-authored
on node mirror, and exercise the legacy add-column migration path in tests.

* fix(sub): keep excluded inbounds' clients in the usage header

The excludeFromSub filter sat in getInboundsBySubId's SQL, so an excluded
inbound's clients never reached seenEmails in the raw, Clash or JSON
renderer. A client that lives only on a hidden inbound (one client per
inbound sharing a subId) dropped out of the Subscription-Userinfo usage,
quota and expiry and out of the info-node state, while the inbound kept
serving it and counting its traffic.

The query returns every enabled inbound again; each renderer skips an
excluded inbound's links but still counts its clients, the same rule the
Clash renderer already applies to external links it cannot express.

---------

Co-authored-by: mrchatam <mrchatam@users.noreply.github.com>
Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
2026-09-27 12:26:37 +02:00
MHSanaei 12d51d7195 perf(tests): copy a migrated template DB instead of migrating per test
Most tests opened a throwaway panel DB with database.InitDB, which runs the
full AutoMigrate + seed on an empty file every time: ~230ms, and ~850ms under
-race because GORM's reflection-heavy migration is what the detector slows
most. internal/web/service does this in ~550 of its 830 tests, so the CI race
job spent ~10 of its ~14.6 minutes re-migrating empty databases.

internal/database/dbtest.InitDB migrates once per test process, then hands
each test its own copy of that file (~130ms under -race) and registers the
CloseDB cleanup. The copy then goes through InitDB like a panel restart, so
every test still starts from the state a fresh install has. Tests that reopen
an existing file, migrate a hand-built legacy DB or target Postgres keep
calling database.InitDB.

Locally under -race: internal/web/service 626s (last CI run) -> 114s,
internal/sub 246s -> 35s.
2026-09-27 03:04:50 +02:00
mrchatam 33a469315a feat(clients): preserve traffic counters in portable export/import (#6469)
* feat(clients): preserve traffic counters in portable export/import

ExportAll now attaches client_traffics up/down (plus resetCount and
last-seen fields) on each portable payload, and ImportClients restores
them only for newly created emails so skipped/existing clients keep
their live counters. Fixes #5858.

* fix(clients): restore imported traffic only onto rows the import created

Review of the portable-traffic export/import (#5858) found four defects:

- An orphan's restored row was hand-built, dropping reset_weekday and
  forcing enable=true; a row kept by a keepTraffic delete kept the old
  client's limits. depletedClientsClause then matched a weekly-renewing
  over-quota orphan and DelDepleted deleted it. Orphan rows now go
  through AddClientStat, whose upsert refreshes config and keeps counters,
  so the unused traffic.total field is dropped from the export.
- Created clients were inferred from Skipped emails, so a duplicate email
  in the file left the created copy with zero counters. bulkCreate now
  reports which payloads inserted a record, and only those are restored.
- Each client took its own serialized-writer commit: 2000 clients spent
  3.66s instead of 0.52s. Counters now apply in batched transactions
  (0.51s).
- importClients discarded needRestart when the late restore step failed
  after clients were committed; it now flags and notifies first, as
  create already does.

The /clients/export and /clients/import API docs now describe traffic.

* fix(groups): keep imported traffic out of group totals

Group totals keep a deleted client's usage (#5675), and the portable
import restores that same usage onto the re-created client. Export,
delete, re-import therefore counted it twice in ListGroups, and a fresh
panel showed the migrated usage as consumption of its groups.

Restored counters are usage from before the import, so the import now
shifts each group's baseline up by what it restored, in the same
transaction. A group total no longer moves at import time; only traffic
consumed afterwards counts. The baseline shift reuses the #5675 helper,
now signed.

---------

Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-09-27 02:48:40 +02:00
MHSanaei ac43b19cfa chore(ci): stop release and CodeQL runs on PRs, drop deploy smoke tests
The release matrix (7 Linux cross-builds + a CGO Windows build) ran on every
PR and on every branch push, so a PR from a repo branch built everything
twice. Release binaries now build only on main (dev channel) and version
tags; any other branch can still be built via workflow_dispatch.

CodeQL keeps its push-to-main and weekly scans but no longer runs per PR.

The deploy smoke workflow fired on every Release completion only to skip
its jobs; deploy/test/smoke-noninteractive.sh stays for manual runs.
2026-09-27 02:44:14 +02:00
DIMFLIX 0ef94b686e feat(tgbot): add /broadcast to relay an admin message to all clients (#6510)
* feat(tgbot): add /broadcast to relay an admin message to all clients

Admins had no way to reach every client at once: notifications only
cover exhausted quotas, so an operator had to copy a message to each
client chat by hand. Add an admin-only /broadcast flow to the bot:

- /broadcast asks for a message; any message the admin sends — text,
  rich text, photo, video, file, sticker or a whole album — becomes the
  broadcast by reference (admin chat + message ids), and a preview
  self-copy shows the admin exactly what recipients will get while
  rejecting content Telegram cannot copy before the run starts.
- The draft references the original instead of parsing its content, so
  copyMessage/copyMessages deliver everything 1:1 on behalf of the bot
  with no forward header (the admin's identity stays private), no
  caption length pitfalls, and future Telegram message types work
  without new parsing.
- A media group arrives as separate updates; its ids are buffered with
  a short debounce, sorted, and delivered as one copyMessages call so
  recipients see the original album.
- Delivery runs in a background goroutine (common.GoRecover): sequential
  sends with a small pause, 429 retry_after honored per recipient,
  failures counted without stopping the run, progress edited into one
  card at most every 25 sends or 3 seconds, a cancel button checked
  between sends, and a final delivered/failed/skipped summary. The
  summary is edited into the card (only sent separately if the card is
  gone), so it is never duplicated.
- Recipients repeat the notifyExhausted walk: clients with a linked
  tg_id, deduplicated, admins excluded — they already receive the
  reports. The message content is never logged.

New i18n keys are added to all 13 locales.

* fix(tgbot): harden broadcast composition per review

- Key the composition per admin chat instead of one process-wide draft:
  two admins can now compose at once without dropping each other's
  drafts, and one admin's /broadcast no longer wipes another chat's
  half-collected album.
- Bind each preview card to its own draft via a random token carried in
  the confirm callback, so a stale Send tap is answered with an error
  instead of delivering a newer, unapproved draft.
- Ignore non-admin senders while a chat composes: the awaiting state is
  keyed by chat id, and in a group that chat is shared.
- Check the cancel flag inside the flood-control retry loop, so a 429
  with a long retry_after no longer holds the single broadcast slot
  after the admin cancelled.
- Scale the per-recipient pause by the copied batch size, so an album
  keeps the same per-second ceiling as a single message.
- Trim the comment blocks that exceeded the two-line cap.

* fix(tgbot): reset broadcast state on stop and classify 403 as skipped

- Clear compositions and cancel the active run from StopBot, next to the
  per-chat draft resets: an album debounce timer, a confirmable token or
  a held runner slot must not outlive the receiver that created them.
- Sleep flood-control waits in 5 s slices and re-check cancel and bot
  state between them, so a minutes-long retry_after no longer parks the
  single-runner slot after the admin cancelled or the bot stopped.
- Count Telegram 403 (the chat never started the bot, or blocked it) as
  skipped instead of failed, log it at debug rather than one warning per
  recipient, and append one line to the summary naming the reason.
- Trim the remaining comment blocks over the two-line cap.

* fix(tgbot): count unreachable recipients in broadcast progress throttle

The progress card refresh was keyed on sent+failed, which a 403 does not
advance since unreachable chats were split out of the failure count. A
streak of unreachable recipients while that sum sat on a multiple of
broadcastProgressEvery (0 included, so from the very first recipient)
edited the card once per chat, doubling the request rate the send delay
is sized for and defeating the throttle. Count processed recipients.

* fix(tgbot): key broadcast compositions by admin, not chat

After #6604 moved conversation state to the admin (chatUser), the
broadcast draft map stayed keyed by chat. Two admins composing in one
group then shared a slot: the second admin's message dropped the first
admin's draft, whose Send tap answered "went wrong" while only the other
draft could go out - the same class #6604 fixed for the add-client
wizard. Drafts, album buffers and confirm tokens now live under the
admin who ran /broadcast.

The router now hands handleBroadcastInput only the admin whose own
/broadcast is awaiting input, so its sender re-check and the test that
fed it a non-admin message directly (an input no route can deliver)
are removed.

---------

Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
2026-09-27 01:43:32 +02:00
DIMFLIX 71e38367c1 feat(sub): add Incy app-management parameters (#6650)
* feat(sub): add Incy app-management parameters

The panel already pushes a set of Happ headers, but INCY documents its own
lowercase header names and its own value domains, so a Happ-shaped payload gets
ignored by the client (per-app mode is bypass|proxy, not on|bypass, and
per-app-proxy-enable has no Happ counterpart at all). Add a sibling Incy path
that emits exactly the documented headers.

Covered, per https://docs.incy.cc/en/app-management/:
- profile-description, sort-order, support-email, announce-url, premium-url
- banner text/button/URL and the two hex colours
- hide-url, hide-check, no-limit-enabled
- per-app split tunnelling (enable/mode/list)
- TCP fragmentation (enable/length/interval/packets)
- UDP noise packets (enable/type/packet/delay)
- DoH pre-resolution (enable/domain/IP)

Each string setting is tri-state: an empty value omits the header, so an
untouched panel never overrides the subscriber's own choice in the app. Values
are validated against the documented domains and dropped when they do not
match, and non-ASCII text is base64-wrapped the way the docs require for
Cyrillic. INCY identifies itself as INCY/<version>/<platform>, which gates the
headers behind the same auto-detect switch the Happ path uses.

Headers the panel already emits for every client (Profile-Title, Support-Url,
Profile-Web-Page-Url, Announce, Profile-Update-Interval, Subscription-Userinfo)
and Incy's routing line are left as they are.

The Premium API (theme, defaultPingProtocol, fallbackHosts, ...) is a separate
encrypted endpoint and stays out of scope here.

* fix(sub): keep Incy per-app list entries separate on the wire

The Incy settings textarea takes one package per line, as Incy documents for
per-app-proxy-list, but the header path ran the value through
sanitizeHeaderValue, which deletes CR/LF. "com.google.chrome\norg.telegram.messenger"
reached the client as the single bogus package
"com.google.chromeorg.telegram.messenger", so per-app split tunnelling silently
matched no app. Join comma- or line-separated entries as CSV instead.

Also drop three tests that could not fail: TestIncyExcludesHappOnlyHeaders
(ApplyIncyHeaders has no path that emits Happ headers, and the non-Happ UA
gate is already pinned by TestApplyHappHeaders_Gating) and two UI tests that
only asserted updateSetting received the key the JSX passes it.

---------

Co-authored-by: DIMFLIX <dimflix@users.noreply.github.com>
Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
2026-09-27 01:06:17 +02:00
mrchatam bd9ccde1f4 feat(sub): make external subscription fetch User-Agent configurable (#6613)
* feat(sub): make external subscription fetch User-Agent configurable

Some providers reject fetches that do not send a known client User-Agent.
Expose externalSubUserAgent as a panel setting (default v2rayNG/1.8.5)
and use it when fetching client external subscription URLs.

Fixes #6383

* ci: retrigger frontend after npm registry maintenance

The frontend job failed solely on `npm audit` while registry.npmjs.org
returned 503 (Service Under Maintenance). Lint, typecheck, vitest, vite
build, and storybook all passed. Local `npm audit --omit=dev
--audit-level=high` now reports 0 vulnerabilities.

* fix(sub): fall back to the default UA when the DB is not initialised

externalSubUserAgent read the setting through SettingService.getSetting,
which calls Model() on database.GetDB() and panics on a nil *gorm.DB.
The fetch path's other DB read, service.ExternalSubscriptionHwid, already
treats a nil DB as unreachable and sends no header; the new UA lookup
did not, so any fetch before InitDB panicked instead of sending the
historical v2rayNG/1.8.5.

Production initialises the DB before the sub server starts, but the
internal/sub fetch tests run without one: under make test-go's
-shuffle=on, whenever one of them ran before the first InitDB test the
panic aborted the whole package. Reproduced deterministically with
go test -run '^TestDoFetchSubscriptionLinks_RejectsOversizedBody$'.

---------

Co-authored-by: mrchatam <mrchatam@users.noreply.github.com>
Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
2026-09-26 23:36:33 +02:00
Jack 9672249edb feat(clients): add calendar weekly renewal and schedule previews (#6524)
* feat(clients): add calendar weekly renewal and schedule previews

Expose fixed-day, calendar-weekly, calendar-monthly, and disabled renewal
through one shared selector in individual and bulk client forms. Store the
weekly weekday separately (Monday 1 through Sunday 7) and use panel-local
calendar dates rather than a fixed 168-hour duration. Resolve skipped or
repeated midnights to the first valid instant of the selected date, and skip
an entirely nonexistent calendar date rather than changing the weekday.

Reuse the existing renewal writer and share its boundary alignment and
per-period catch-up calculation with an authenticated, read-only preview.
Keep monthly precedence for legacy records, fixed-day interval semantics,
maximum renewal allowances, first-use durations, and operator-disabled
settings unchanged. Selecting a mode does not rewrite an existing cutoff;
an unset calendar cutoff requires an explicit action to choose the first.
The last-valid-second preview uses the stored exclusive expiry, even when
the billing calculation aligns a legacy last-second cutoff up to midnight.

Carry weekly schedules through client persistence, paging, enable toggles,
inbound settings, and node traffic reconciliation. Migrate missing or nullable
weekday columns to disabled by default without altering existing limits, and
include the new isolated-schema PostgreSQL regression in the live CI gate.

Regenerate API contracts and reference documentation, add lifecycle and form
regressions, and document timezone, quota-reset, and upgrade considerations.
All participating nodes must be upgraded before weekly mode is enabled;
older binaries ignore the new field. Independent periodic traffic resets and
the optional month-end subscription-header display are not changed.

* fix(clients): validate renewal schedules across inbound write paths

Reject conflicting weekly/interval/monthly schedules and out-of-range
weekdays on inbound creation and edits, legacy one-client apply paths,
record/link synchronization, and traffic metadata writes. Validate imported
traffic snapshots as well, before any inbound or client is persisted, so
an inbound API cannot create a client that the clients page cannot toggle.

Merge a weekly-related schedule as one timestamp-selected tuple rather
than filling its zero fields from another renewal mode. Preserve empty
migration snapshots and the existing non-weekly monthly/interval merge
semantics. Renewal caps, counters, credentials, and deadlines are unchanged.

Add regressions for nine write paths, unchanged records and runtime calls
after rejection, valid inbound clients remaining editable, and duplicate
record merges between individually valid renewal modes.

* docs(clients): clarify depleted-client deletion risks on downgrade

Explain in English and Chinese that older versions not only stop weekly
renewal: their depleted-client cleanup can delete a weekly-only client once
its expiry or quota is exhausted. This is conditional on cleanup, not an
automatic deletion caused by downgrade itself.

Recommend backing up and converting weekly schedules to a mode supported
by every participating version before rollback, and avoiding cleanup while
mixed versions or unconverted clients remain. Merely disabling weekly
renewal does not restore the old binary's missing purge protection.

* fix(clients): bound weekly renewal date searches

Limit the search for a valid weekly calendar date to eight candidates so
an unusual timezone cannot monopolize the single traffic writer. Exhaustion
returns the original instant, allowing the existing catch-up forward-progress
guard to stop without advancing expiry, consuming an allowance, resetting
traffic, or falling back to a fixed-duration schedule that can drift.

Reject a non-future calendar suggestion in the read-only preview instead of
offering an immediately expired initial cutoff. Also report failed weekly
catch-up as a search error when allowances remain, not as cap exhaustion.
Existing preview errors use the form's current warning; no API schema or
locale changes are needed.

Exercise exhaustion with a synthetic valid TZif containing twelve skipped
Sundays. This fault-injection case was red without the bound; it is not a
claim that a production IANA timezone was observed hanging. Keep the Havana
and Apia regressions for real skipped/repeated midnights and absent dates.

* fix(tests): isolate weekly renewal preview timezone

Stop the weekly search regression from replacing process-global time.Local.
CI caught that assignment and its cleanup racing with background timer reads
through time.Now, even though the top-level tests do not use t.Parallel.

Pass the timezone and current instant into the unchanged preview calculation.
The public service still validates the request and resolves the panel timezone;
API responses, renewal accounting, and persisted client data are unchanged.

Use fixed dates for both suggestion and catch-up exhaustion, removing the
test's dependency on today's date and its unnecessary database setup. Keep a
bounded-lifetime background clock reader to expose future global-timezone
mutations under the existing race gate rather than disabling that check.

* ci: retrigger PR checks

Create an empty commit to request a fresh pull-request CI run after release dependency downloads failed with network errors.

No source, dependency, or workflow changes are included. Retry the existing checks without bypassing them.

* ci: retry PR checks and record deferred download hardening

Request another CI run after the amd64 release job compiled successfully but failed during dependency fetching with exit code 4 (network failure).

Record possible follow-up improvements for the Linux release fetch helper:
- Print each download URL and destination, and preserve error details.
- Reuse the existing curl configuration with up to five retries; add connection and per-attempt timeouts and a bounded retry window.
- Download to a temporary file and promote it to the final filename only after a successful, non-empty transfer. Keep the job failing if downloads ultimately fail.
- Validate successful downloads, recovery after a temporary failure, and correct failure after persistent errors before shipping such a change.

These improvements are intentionally deferred, not implemented or tested by this commit. This commit is empty: renewal logic, dependencies, workflow configuration, check requirements, and TLS verification remain unchanged.

---------

Co-authored-by: JacktheRanger <219502738+JacktheRanger@users.noreply.github.com>
2026-09-26 22:59:23 +02:00
NgaiYeanCoi 5e15120cec feat(happ): add routing editor, optional ad blocking, and LAN bypass preset (#6545)
* feat(happ): make ad blocking optional in routing presets

Add an independent AdBlock toggle for Iran, China, and global presets, applied only when generating routing rules. Update the China preset to Bypass-CN and cover preset behavior and localized controls.

* feat: add visual routing editor with JSON support and localization updates

- Implemented a new modal for editing routing profiles with basic and advanced tabs.
- Added functionality to load, parse, and generate routing profiles in JSON format.
- Enhanced user experience with validation and error handling for JSON input.
- Updated translations for Russian, Turkish, Ukrainian, Vietnamese, Chinese (Simplified and Traditional) to include new routing editor terms.
- Created helper functions for managing routing profiles and generating deep links.
- Added unit tests for routing editor functionalities and JSON handling.

* feat: update routing editor to preserve null lists in profiles and enhance validation messages
2026-09-26 22:57:01 +02:00
MHSanaei 94fa317e76 chore(gen): regenerate types for addrFamily
Regenerate frontend/src/generated/types.ts and zod.ts to include the new addrFamily enum type, produced by tools/openapigen from Go struct changes.
2026-09-26 22:46:04 +02:00
Kirill Rudenko 788b76c544 fix(amneziawg): sniff the relay with routeOnly; scope the v6 egress to IPv6 (#6654)
* fix(amneziawg): sniff the relay with routeOnly

The embedded AmneziaWG relay sniffed without routeOnly, so a sniffed SNI
replaced the dial target. Telegram's FakeTLS recovery dials
194.221.250.50:443 with SNI www.google.com; the rewrite sent it to real
Google and the client looped on "TLS hash mismatch", stuck on "Connecting".

Sniffing here exists only so domain routing rules can match; routeOnly
keeps that and dials the IP the peer resolved. Fake-pool targets are
still rewritten (the dispatcher ignores routeOnly for fakedns).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(amneziawg): send only IPv6 targets through the peer's v6 egress

The per-peer IPv6 egress rule matched every flow of that peer, but its
freedom outbound binds a v6 sendThrough and cannot dial an IPv4 target, so
IPv4 DNS and any other unsniffed IPv4 traffic of such a peer failed.
Sniffed TLS/HTTP only worked because the sniffed domain replaced the IP;
with routeOnly on the relay that no longer happens.

Limiting the rule to ::/0 keeps the peer's IPv6 identity for IPv6 targets
and lets IPv4 targets take the regular outbound.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Kirill Rudenko <rudenko@npp-energy.ru>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-09-26 22:04:08 +02:00
SERGE BLCHV 6ac0c88084 fix(xray): hot-apply Hysteria client changes without replacing the inbound (#6606)
* fix(xray): hot-apply Hysteria client changes without replacing the inbound

diffInboundUsers only allowed per-user AlterInbound ops for vless, vmess
and trojan. For a hysteria inbound every client add/remove/update became
DelInbound + AddInbound: the UDP listener was recreated and all QUIC
sessions of that inbound were lost. quic-go sends no stateless reset, so
every connected client stalled until its idle timeout (30s by default)
after each unrelated client mutation.

XrayAPI.AddUser already builds a hysteria account and Xray-core's
hysteria server implements AddUser/RemoveUser, so adding the protocol to
userDiffableProtocols is sufficient.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test(xray): say which branch each drop-guard protocol takes

With hysteria in userDiffableProtocols its dropped client reaches the
guard through the per-user diff, so the test named for protocols the
diff cannot handle no longer described its hysteria case.

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
2026-09-26 22:03:43 +02:00
Kirill Rudenko 6ab718f813 fix(sub): make Happ require auth on its local SOCKS/HTTP proxy (#6628)
Happ ships its local SOCKS5 (127.0.0.1:10808) and HTTP inbounds with
authorization disabled by default. Any app on the same device can then
connect to that proxy, bypassing Android's per-app VPN routing, and learn
the VPN server address - the leak publicly described in March-April 2026
for Happ, v2rayNG and other VLESS clients. Happ fixed its Xray API
exposure, but the unauthenticated local proxy remained.

Happ exposes a standard subscription header for this (no Provider ID
required): socks-auth-mode / http-auth-mode = auto|manual|from-json|
disable. A new subscription setting, subHappLocalProxyAuth (default
"auto"), sends both headers to Happ clients. Like every other Happ header
it is emitted only when Happ auto-detect is enabled and the User-Agent is
Happ, so panels that never opted into the Happ integration see no change.
An empty value sends nothing and keeps the client's own setting.

Verified on Happ Android 4.4.1 (Xray 26.7.28): a subscription carrying
socks-auth-mode manual + a test user/password switched the client's
Inbounds screen to Manual with those credentials on "refresh subscription",
and "auto" switched it to Auto with generated credentials.

Co-authored-by: Kirill Rudenko <rudenko@npp-energy.ru>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-09-26 22:03:20 +02:00
Kirill Rudenko 8979072bd9 fix(amneziawg): bound S1-S3 by the receive buffer, reject overlapping H (#6642)
* fix(amneziawg): bound S1-S3 by the receive buffer, reject overlapping H

The native AmneziaWG validator, both Zod schemas, both forms and the docs now
follow the rules amneziawg-go actually enforces.

S1-S3. A padded handshake message is 148+S1, 92+S2 or 64+S3 bytes
(device/send.go). The peer reads each datagram into a [MaxMessageSize]byte
buffer, where MaxMessageSize = MaxSegmentSize (device/pools.go,
constants.go). MaxSegmentSize is 65535 on Linux/Android, 2016 on Windows and
1700 on iOS (device/queueconstants_*.go). The limits are therefore
S1 <= 1552, S2 <= 1608 and S3 <= 1636. Before, S1/S2 allowed 65535, which
iOS peers silently drop, and S3 was capped at 64, a number inherited from the
coinman-dev/3ax-ui port in #6105 with no stated reason. That cap blocked real
configs such as Amnezia Premium's S3=1045. RandomTrailers only tops a packet
up to 500 bytes (DefaultUdpWindow), so it never pushes a message past these
limits.

H1-H4. amneziawg-go refuses the whole device when the header ranges overlap
("headers must not overlap", device/uapi.go mergeWithDevice), and so does the
kernel module (src/netlink.c). The panel did not check this, so an inbound
with overlapping ranges saved and then failed to apply. A blank H is never
sent, so the engine keeps its default, WireGuard's own type 1-4; the check
treats blank fields that way. The docs said 1-4 "must not be used". They are
valid and are the engine default, only unobfuscated without a
HeaderProtectionKey. The docs also said amneziawg-go rejects S1+56 == S2. It
does not (IpcSet accepts it). The panel keeps that rule as a fingerprint
guard, and the docs now say so.

Tests: the new params_test cases and the Zod bounds fail on the old code.
TestValidatedObfuscationAlwaysApplies runs every accepted set through a real
amneziawg-go IpcSet and now covers overlap, blank-H defaults, H=1-4, the
exact S bounds and the full Amnezia Premium set. Before this fix it failed
with "headers must not overlap".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(amneziawg): bound only inbound padding by the iOS receive buffer

The 1700-byte iOS buffer limits what an inbound's clients can receive,
but ValidateObfuscation also runs for outbounds, and the Xray template
save re-validates every AmneziaWG outbound. An outbound whose remote
server uses S1 above 1552 would have blocked every Xray settings save,
though its values come from that server and are received on Linux.

ValidateObfuscation keeps amneziawg-go's uint16 UAPI width for S1-S3;
ValidateServerObfuscation adds the receive-buffer bounds and is what
inbounds call. The outbound schema and form follow the same split.

---------

Co-authored-by: Kirill Rudenko <rudenko@npp-energy.ru>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-09-26 22:02:49 +02:00
Xinny Lin f3b100282a fix: allow IPv4 and IPv6 inbounds to share a port (#6603)
* fix: distinguish IPv4 and IPv6 listen conflicts

* fix(ports): let an IPv4 address share a port only with a v6only wildcard

xray listens on tcp/udp, and Go opens every wildcard listen, 0.0.0.0
included, as one dual-stack socket unless sockopt.v6only is set. Treating
:: and 0.0.0.0 as separate families let the panel save pairs the core
then fails to bind, and it broke main's own TestListenOverlaps.

listenOverlaps now takes the inbound's sockopt.v6only: a wildcard claims
both families, or only IPv6 with v6only, so :: with v6only may share its
port with an IPv4 address while a plain :: or 0.0.0.0 still may not.

---------

Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
2026-09-26 22:02:22 +02:00
Roman Chesnakov bd01f923fb fix(tgbot): unstick the add-client wizard's inbound picker (#6621)
* fix(tgbot): unstick the add-client wizard's inbound picker

Tapping "➕ Новый клиент" always sent the "choose inbound" message,
even when the button list ended up empty after protocol filtering.
getInboundsAddClient checked len(inbounds)==0 before filtering but
never re-checked after, so an admin whose every inbound was excluded
got a message with nothing to tap and no further feedback.

WireGuard and AmneziaWG were excluded outright too, a holdover from
the wizard's original 2025 implementation, before
defaultWireguardClients
and defaultAmneziaWGClients existed. Both now auto-generate a keypair +
AllowedIPs for a client with none set, and the subscription server
already emits wireguard:// and vpn:// share links for them, so both
inbound types flow through the same generic Create path as VLESS/Trojan
already used by the bot. Mixed/HTTP/Tunnel stay excluded: they have no
per-client model in this codebase.

- getInboundsAddClient now returns getInboundsFailed when the button
  list is empty after filtering, instead of sending an unusable keyboard
- WireGuard/AmneziaWG removed from the exclusion list in both
  getInboundsAddClient and getInboundsAttachPicker
- the previously duplicated excludedProtocols map is now a single
  package-level addClientExcludedProtocols shared by both functions

* test(tgbot): pin which inbounds the add-client picker offers

The picker change had no test. One drives a database holding WireGuard,
AmneziaWG, VLESS and Mixed inbounds and wants the first three offered;
the other holds only Mixed, HTTP and Tunnel and wants getInboundsFailed
instead of an empty keyboard. Both fail on the previous picker.

---------

Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
2026-09-26 22:01:56 +02:00
mrchatam b3a5be9da4 fix(amneziawg): stop AAAA fallback on v4-only tunnels and expose I2–I5 (#6611)
* fix(amneziawg): stop AAAA fallback on v4-only tunnels and expose I2–I5

Gate tunnel DNS queries to address families the device can actually dial,
reject undialable literal IPs early, and surface I2–I5 on the outbound form.

Fixes #6570

* ci: retrigger frontend after npm registry maintenance

The frontend job failed solely on `npm audit` while registry.npmjs.org
returned 503 (Service Under Maintenance). Lint, typecheck, vitest, vite
build, and storybook all passed. Local `npm audit --omit=dev
--audit-level=high` now reports 0 vulnerabilities.

* style(amneziawg): keep the tunnel DNS family comments to two lines

CLAUDE.md caps a comment block at two lines.

---------

Co-authored-by: mrchatam <mrchatam@users.noreply.github.com>
Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
2026-09-26 22:01:04 +02:00
mrchatam 8f1201553e fix(ip-limit): CAS-retry inbound_client_ips merges under Postgres (#6612)
* fix(ip-limit): CAS-retry inbound_client_ips merges under Postgres

Two writers RMW the same ips JSON blob; on PostgreSQL a lost update drops
remote IPs that partitionLiveIps only sees through that blob (#6587).
Compare-and-set on the previous blob with re-merge on miss, matching the
repo's conditional Where+RowsAffected pattern.

Fixes #6587

* ci: retrigger frontend after npm registry maintenance

The frontend job failed solely on `npm audit` while registry.npmjs.org
returned 503 (Service Under Maintenance). Lint, typecheck, vitest, vite
build, and storybook all passed. Local `npm audit --omit=dev
--audit-level=high` now reports 0 vulnerabilities.

* test(ip-limit): cover the scan's CAS against a mid-scan node sync

The job-side compare-and-set had no test of its own. A write injected
between the scan's read and its update now has to keep the node's remote
IP; main's blind Save drops it. Also keeps the new comments to two lines,
as CLAUDE.md requires.

---------

Co-authored-by: mrchatam <mrchatam@users.noreply.github.com>
Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
2026-09-26 22:00:40 +02:00
sdhfsl d42e2133c7 fix(sub): keep serverDescription literal in external link fragments (#6580)
* fix(panel): accept 2FA codes from adjacent TOTP windows

CheckUser compared only gotp.Now(), so a code submitted at the end of
its 30s window (or with slight client/server clock drift) failed with
'invalid 2fa code', while the immediate retry in the next window
succeeded. Accept current +/-1 window, the standard TOTP skew
tolerance.

Fixes MHSanaei/3x-ui#6535

* fix(panel): share TOTP skew tolerance with VerifyTwoFactorCode

Move the +/-1 window helper to internal/util/totp so both 2FA
acceptance points use it: login (CheckUser) and disable/rebind plus
username/password changes (VerifyTwoFactorCode). Also shrink comments
to the 2-line house rule and anchor the unit test mid-window to avoid
a step-boundary flake.

Addresses review on #6546 (MEDIUM + 2 LOWs).

* fix(sub): keep serverDescription literal in external link fragments

Client external links escaped the whole remark, turning
?serverDescription=<base64> into %3F...%2F... so Happ lost its
subtitle. Split on ?serverDescription= like appendQueryAndFragment
(#6488): escape only the display name, keep a clean base64 tail
literal, fall back to full escaping otherwise.

Fixes MHSanaei/3x-ui#6575

* refactor(sub): share one serverDescription fragment split across link paths

#6488 fixed the split in appendQueryAndFragment and #6575 was the same
bug on the external-link path, which had its own copy. Both now call
escapeLinkFragment with their own escaper, so a later change to the tail
check cannot reach one path and miss the other.

---------

Co-authored-by: sdhfsl <sdhfsl@users.noreply.github.com>
Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
2026-09-26 22:00:09 +02:00
sdhfsl a2ca023336 fix(sub): send panel guid as X-HWID on outbound subscription fetch (#6579)
* fix(panel): accept 2FA codes from adjacent TOTP windows

CheckUser compared only gotp.Now(), so a code submitted at the end of
its 30s window (or with slight client/server clock drift) failed with
'invalid 2fa code', while the immediate retry in the next window
succeeded. Accept current +/-1 window, the standard TOTP skew
tolerance.

Fixes MHSanaei/3x-ui#6535

* fix(panel): share TOTP skew tolerance with VerifyTwoFactorCode

Move the +/-1 window helper to internal/util/totp so both 2FA
acceptance points use it: login (CheckUser) and disable/rebind plus
username/password changes (VerifyTwoFactorCode). Also shrink comments
to the 2-line house rule and anchor the unit test mid-window to avoid
a step-boundary flake.

Addresses review on #6546 (MEDIUM + 2 LOWs).

* fix(sub): send panel guid as X-HWID on outbound subscription fetch

Outbound subscriptions hit the same HWID-limited donor 404 as client
external links (#6559/#6567). Identify this panel with GetPanelGuid
plus X-Device-OS, honoring the externalSubSendHwid opt-out.

Fixes MHSanaei/3x-ui#6574

* fix(sub): send the external-subscription X-HWID from outbound fetches too

The outbound fetch used panelGuid while client external links send the
externalSubHwid id from #6567, so an HWID-limited provider counted one
panel as two devices. It also re-added the externalSubSendHwid opt-out
that #6567 dropped.

Move the id into service.ExternalSubscriptionHwid, keeping the
externalSubHwid row so existing installs keep their slot, and send it
from both paths. The outbound test now fails on the panelGuid version.

---------

Co-authored-by: sdhfsl <sdhfsl@users.noreply.github.com>
Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
2026-09-26 21:59:29 +02:00
MHSanaei 3fe92df7ad docs: adopt correct-fix-over-small-fix and TDD policy
Replace the "smallest fix" rule with a "correct fix over small fix" policy: fix root causes properly, regardless of size, while still disallowing speculative additions. Add a dedicated TDD section (red-green-refactor, fake-test prohibitions) to CLAUDE.md and CONTRIBUTING.md, consolidating prior scattered testing guidance. Also promote jackc/pgx/v5 from an indirect to a direct go.mod dependency.
2026-09-26 21:58:25 +02:00
mrchatam 169cd86e00 fix(sub): never use X-Real-IP as the subscription host (#6608)
ResolveRequest and the panel's resolveHost fell back to X-Real-IP for the host when a trusted proxy sent no X-Forwarded-Host. X-Real-IP names the visitor, so behind nginx with only that header set, subscription and exported links advertised the subscriber's own public IP as the server.

The host now comes from a trusted X-Forwarded-Host, else the dialed request Host. X-Real-IP stays a client-IP source only.

Fixes #6589.
2026-09-26 21:13:46 +02:00
n0ctal 66df77665f test(database): give each package its own schema when tests run on PostgreSQL (#6594)
With XUI_DB_TYPE=postgres every test package shared one database and worked in public. Go runs package test binaries concurrently, so migrations raced and rows a previous run left behind leaked into the next.

testpg.IsolatePackage creates a schema for the calling package, puts it first on search_path and drops it when the package finishes. It returns at once unless XUI_DB_TYPE is postgres. internal/web/service's TestMain adopts it.
2026-09-26 21:13:42 +02:00
mrchatam c54c28d92d fix(sub): drop legacy freedom.domainStrategy from JSON sub template (#6609)
The JSON-subscription template still set settings.domainStrategy on its freedom outbound, the placement #6515 moved off everywhere else, so xray-core migrated it to sockopt with a deprecation warning on every load. AsIs is the core default when the key is absent, so dropping it changes nothing else.

Fixes #6482.
2026-09-26 21:13:39 +02:00
SakikoTogawa 5d41e65a3c fix(sub): preserve external VLESS encryption in Clash subscriptions (#6576)
* fix(sub): preserve external VLESS encryption in Clash subscriptions

Copy non-empty, non-none encryption from parsed external VLESS settings,
matching local proxy export. This prevents merged Clash/Mihomo subscriptions
from losing the encryption parameters of externally added nodes.

Cover encryption normalization and omission, plus merged YAML from pasted
links and HTTPS subscriptions containing plain or Base64 share-link lists.

Validation: regression cases fail before the fix and pass after it; the full
subscription package and go build ./... pass. Four unrelated packages still
fail on Windows, with the same failures reproduced using the original code.

Refs: MHSanaei/3x-ui#6572

* test(nodes): wait for chart effects in history panel assertions

The DOM can commit its accessible labels before Sparkline updates the refs used by uPlot range callbacks. Wait for the existing assertions together so the test does not read the empty-data range.

Reproduced the original CI failure locally on attempt 5. The fixed test passed 12 consecutive runs; lint, format and TypeScript checks pass. The full frontend suite passed 1607 of 1608 tests, including Storybook. The unrelated input-number guard fails on Windows because execFileSync cannot launch the extensionless oxlint shim (ENOENT); invoking oxlint.cmd reports all three expected diagnostics.
2026-09-26 20:31:50 +02:00
Matt Van Horn 0dec3d65ba fix(sub): preserve per-inbound tunnel identity in subscriptions (#6653)
matchingClients primed the per-request link cache with the shared clients rows, whose wg_* columns hold whichever WireGuard/AmneziaWG inbound synced last. A client on several such inbounds (one per node) therefore got the same tunnel address and keys in every subscription profile.

Membership, subId, enable, quota and expiry still come from the normalized tables. For WireGuard and AmneziaWG the tunnel identity (keys, AllowedIPs, keepalive) is now overlaid from this inbound's own settings, the source clientsForLinkExport already uses for direct links. A member with no settings entry, or malformed settings, yields no link for that inbound rather than another inbound's credentials.

Fixes #6641.
2026-09-26 20:31:47 +02:00
libmur-dev 07ee638a50 fix(sub): emit Hysteria certificate pin for Mihomo (#6651)
buildHysteriaProxy dropped pinnedPeerCertSha256 from Clash/Mihomo YAML although the raw share link already carries it as pinSHA256, so Mihomo rejected a self-signed Hysteria2 certificate whenever allowInsecure was off.

Emit the first valid SHA-256 pin as Mihomo's fingerprint field in its colon-separated form, honouring an external endpoint's override. client-fingerprint stays the uTLS setting. Mihomo accepts a single fingerprint, so of several pins the first valid one wins.

Refs #4683.
2026-09-26 20:31:42 +02:00
sdhfsl ee2ff48c81 fix(tgbot): scope the add-client wizard to the admin, not the chat (#6604)
Two admins in one group chat shared one draft and one wizard step: clientDrafts and userStateStore were keyed by chat id alone, so the second admin's wizard opened on the first one's email and limits, and whichever of them tapped a control last decided what the other created.

Key both stores by (chat, user) instead. A private chat is unaffected: its two ids are equal, so the key matches what the chat alone used to be. A message with no sender (a channel post) keys to user 0, which no admin holds.

Fixes #6593.
2026-09-26 20:31:39 +02:00
n0ctal 3b9ca47a4e fix(database): keep the legacy tag cleanup from colliding with an existing tag (#6592)
* fix(database): avoid legacy inbound tag cleanup collisions

* test(database): assert the legacy tag cleanup keeps the migration green

The collision guard's test asserted only that the colliding tag was left
alone, which an unguarded cleanup also produces: the UPDATE fails on the
unique index and the row is unchanged either way. The cleanup shares a
transaction with every other requirement, so that failure rolls all of
them back on every boot and only reaches the log. Assert the call itself
succeeds, which is what actually distinguishes the two.

---------

Co-authored-by: n0ctal <n0ctal@users.noreply.github.com>
2026-09-26 20:30:25 +02:00
n0ctal c0c0136037 fix(hwid): serialize the device-limit write with its trim (#6591)
setClientLimitHwidByEmail wrote clients.limit_hwid and then trimmed client_hwids as two independent statements. A traffic-cycle Save that read the record before the limit changed could write the stale value back after it, and a failed trim committed the new limit anyway.

Both halves now run inside runSerializedTx, the transaction the traffic writer already owns. setClientLimitHwidByEmailTx and clearClientHwidsBySubIDTx refuse a handle that is not that transaction (errClientHwidWriteNotSerialized) instead of falling back to the shared handle. Client delete moves onto the same writer, and BulkCreate withdraws a re-created client's tombstone before applying its optional HWID limit.

TestSetClientLimitHwidIsSerializedWithSyncInbound holds a stale traffic-cycle Save open across the limit change and fails without the serialization (limit_hwid = 5, want 1).
2026-09-26 20:30:22 +02:00
n0ctal d86a3def85 fix(ip-limit): append fail2ban lines only after the scan commits (#6590)
updateInboundClientIps wrote the [LIMIT_IP] lines that drive the jail
while the scan's transaction was still open, and marked the addresses in
bannedSeen at the same time. A commit failure after that point rolls the
database back but takes nothing back from the log: fail2ban proceeds to
ban addresses the panel never recorded, and the in-memory bannedSeen
entry makes the next scan skip them, so the rollback is never repaired.

Selection stays inside the transaction. processObserved now collects one
pendingBan per enforced client and publishes after the commit succeeds,
disconnecting only the clients whose lines actually reached the log. The
Xray disconnects already ran after the commit for the same reason.

Recording moved with the write rather than with the decision:
selectAdvancedSinceLastBan no longer mutates anything, and
recordBannedSeen runs once a line is on disk. It also runs for clients
with nothing to ban, because that is the pass that forgets addresses a
client no longer exceeds its limit with - pruning used to be a side
effect of the filter, and skipping it left a stale entry that suppressed
the next legitimate ban.

The log file is opened once per scan instead of once per client, the
write error is checked instead of discarded, and Close is reported.

updateInboundClientIps no longer reports shouldCleanLog, because the
only thing that set it was the ban branch that moved out; processObserved
sets it when a publication actually happens. disAllowedIps went with the
write it served.

Tests: a transaction failed at COMMIT through a deferred foreign key
leaves no line and no bannedSeen entry; a publication that cannot open
the log leaves the address retryable; a client returning under its limit
has its entry forgotten, so going over again is banned a second time; a
committed over-limit scan publishes and reports; and writeBanLines
surfaces a write error rather than swallowing it.
2026-09-26 20:30:18 +02:00
MHSanaei dcaadd4857 fix(panel): validate sponsor logo name before any file or network use
The public /sponsors/logo/:name route only accepted names matching an
active sponsor's logo, which was already regex-filtered, but that guard
was indirect. Checking sponsorLogoRe on the name itself makes the
path/URL safety local and clears CodeQL alerts #113 (go/request-forgery)
and #114 (go/path-injection).
2026-09-26 12:40:31 +02:00
MHSanaei fd7b3559bc feat(panel): add sponsor slots fed from sponsors.sanaei.dev
Monthly sponsor placements need to change without cutting a panel
release. Panels now read 3X/sponsors.json from the MHSanaei/sponsors
repo (GitHub Pages on sponsors.sanaei.dev) and show active sponsors in
four slots: an overview banner, a rotating sidebar card (max three), the
login page and a new Sponsors page that also lists open placements.

An entry shows only while enable is not false and until is in the
future; links must be https and logos are png/webp/jpg by name only.
The list is cached for an hour and the last good copy survives upstream
failures; logos are proxied through /sponsors/logo/:name with failures
cached, so CSP stays 'self' and admin browsers never reach a third
party. Admins can hide a slot for 24h. Under XUI_DEBUG the panel reads
a sibling ../sponsors/3X checkout so edits can be previewed before push.
2026-09-26 03:31:51 +02:00
MHSanaei 89e200ead4 fix(frontend): key geo entries by page position and clear test-suite noise
Zod 4: use the `error` param instead of the deprecated `message`.
lint:deprecated missed these because tsgolint's no-deprecated does not
resolve object-literal properties on a `string | Params` union.

Geodata: key geo entry rows by page position. antd deprecates rowKey's
index argument, and kind:value repeats within a page because the reader
drops domain attributes (22 pairs in geosite_IR.dat, 108 in geosite_RU).

Nord/PIA: the "All cities/regions" option used a null value, which antd
warns on. Map it through a sentinel at the Select boundary so form state
stays null, with tests that fail when the sentinel is not mapped back.

Tests:
- Run the oxlint guard through node; .bin/oxlint is a sh shim Windows
  cannot spawn, and the swallowed error left both guard cases vacuous.
- Start unit workers with --no-experimental-webstorage; msw's localStorage
  probe made Node 25+ warn once per forked worker.
- Set IS_REACT_ACT_ENVIRONMENT, which RTL never sets with globals: false,
  and settle the async updates it exposed inside act(). The row-cells
  memo test now fails when memo is removed.
- Disable antd's click wave in Storybook; it re-rendered inside the next
  story's act() and tripped "not configured to support act".
- Assert InboundFormModal's validation log instead of leaking it, and
  give the rule-form test a well-formed clients/list response.
2026-09-25 21:21:03 +02:00
MHSanaei a03228c455 ci: update Claude workflow model settings
Use Claude Opus 5.5 with high effort for issue analysis and PR reviews.
2026-09-25 19:19:50 +02:00
MHSanaei 86302d2f2d chore(deps): update toolchains and dependencies
Raise the frontend baseline to Node 26/npm 11 and refresh contributor documentation. Update frontend, documentation-site, and Go dependencies with regenerated lockfiles and module checksums.
2026-09-25 17:39:38 +02:00
Farhan Zare 95f19b192f fix(nodes): stop a restarting panel from reporting itself as down
Adding a node fails right after that node's panel restarts. nodes/add
probes the node's /panel/api/server/status first, and that endpoint
returns whatever the @2s ticker last sampled - nil until the first tick
lands, so the master reads a healthy panel as unreachable and rejects it
with "Add node (remote returned success=false: )", an error whose
message is empty because the node answered success with a null obj.

The window is far wider than one tick: GetStatus resolved the public
IPv4/IPv6 addresses inline and held s.mu across every lookup, so a box
with no IPv6 route spent 3s per service - about 15s of nil status after
each restart, and the same stall on a fresh panel's first sample.

- status now answers from CurrentStatus, which samples on demand when
  the ticker has not run yet instead of returning a null obj
- the public-IP lookups run in the background and outside s.mu, so a
  status sample never waits on them
- probe tells "no status yet" apart from a genuine success=false, so the
  master's error says something when it meets an older node
2026-09-18 13:25:24 +03:00
BlindMaster24 1c0ce80e8e fix(ci): keep a refused Claude credential from reddening a pull request (#6585)
* fix(ci): keep a refused Claude credential from reddening a PR

An expired subscription ends the claude-code-action step with exit 0, so the
classifier that exists for "the API refused this run" never sees it -- its
condition is a failed step -- and the final "posted nothing" step reddens the
pull request although nothing is wrong with the repository.

Verified against five real runs (35159059540, 35184688775, 35185722358,
35186543654, 35187380192): step 8 success, step 10 found no cause, step 11
failure, transcript {"error":"oauth_org_not_allowed"} plus a result entry with
api_error_status 403. A usage-limited run carries 429 and a rejected
rate_limit_event, and a real review carries is_error false with no status, so
the 401/403 test fires on the refused credential alone.

* fix(ci): stop a refused credential reddening the issue analysis

The same exit-0 refusal reaches this workflow's "posted no reply" check, which
fails for the same reason and shows up as seven failed runs in a day. It never
attaches to a pull request -- the trigger excludes them -- so this is the same
step and the same 401/403 transcript test applied where the refusal lands.

Reported only as a warning annotation: nothing was analysed, and there is no
comment worth posting about a credential the maintainer has to renew.
2026-09-17 10:54:12 +03:00
n0ctal f8db7f6c29 fix(nodes): say which half of node mTLS failed, and say it as an error (#6565)
* fix(nodes): say which half of node mTLS failed, and say it as an error

A configured client CA bundle that will not parse produced the same
warning as a settings read that failed, and both read as though mTLS
were merely unavailable. It is not: the node API silently stops
accepting client certificates, callers fall back to a bearer token or
lose their only credential, and the one line saying so is a warning at
boot.

Report it at error level, and distinguish the two causes rather than
attributing a storage fault to the operator's certificate bundle.
NodeMtlsClientCAPool now tags the parse failure with
ErrNodeMtlsTrustBundleInvalid; its message text is unchanged, so
anything matching on the existing string still matches.

Startup is deliberately left alone. Refusing to boot was considered and
rejected: the bundle is one of two equal credentials here, a panel that
will not start takes the proxies and the subscription server with it,
and bundles written before the stricter validation landed in #6188 are
already stored, editable only through the panel that would no longer
come up.

The tests pin the tag on an unusable bundle and its absence on an unset
one; without the tag the first goes red.

* test(nodes): drop a duplicate node mTLS trust-bundle test

TestNodeMtlsClientCAPoolLeavesUnsetBundleUntagged asserted only that an
unset nodeMtlsClientCAPem yields (nil, nil). That path returns before the
line the sentinel change touched, so the test was green with and without
ErrNodeMtlsTrustBundleInvalid, and TestNodeMtlsClientCAPool already pins
the same two assertions on the same fixture. A test that passes either way
certifies nothing and then gets cited as coverage for the sentinel.

TestNodeMtlsClientCAPoolTagsAnInvalidBundle, which does go red without the
sentinel, stays as the regression guard.

---------

Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-09-16 12:30:44 +02:00
sdhfsl 536f9a6338 fix(tgbot): localize QR caption via I18nBot (#6564)
* fix(panel): accept 2FA codes from adjacent TOTP windows

CheckUser compared only gotp.Now(), so a code submitted at the end of
its 30s window (or with slight client/server clock drift) failed with
'invalid 2fa code', while the immediate retry in the next window
succeeded. Accept current +/-1 window, the standard TOTP skew
tolerance.

Fixes MHSanaei/3x-ui#6535

* fix(panel): share TOTP skew tolerance with VerifyTwoFactorCode

Move the +/-1 window helper to internal/util/totp so both 2FA
acceptance points use it: login (CheckUser) and disable/rebind plus
username/password changes (VerifyTwoFactorCode). Also shrink comments
to the 2-line house rule and anchor the unit test mid-window to avoid
a step-boundary flake.

Addresses review on #6546 (MEDIUM + 2 LOWs).

* fix(tgbot): localize QR caption via I18nBot

sendClientQRLinks hardcoded English 'QRCode for client <email>:',
bypassing I18nBot, so non-English bot languages (e.g. ru-RU) still
got English. Add tgbot.answers.qrCodeForClient key with Email param
in all 13 locales and route the caption through I18nBot.

Fixes MHSanaei/3x-ui#6562

* fix(tgbot): repair locale JSON syntax, harden QR i18n test

- Add missing separators so all 13 locale files parse again.
- Rewrite the regression test to read the real shipped files
  (fails on malformed JSON or missing key).
- Add TestTgbotLocalesQrKeyValid covering every locale file.

* chore(tgbot): drop QR caption tests that cannot catch the bug

TestQRCodeForClientLocalizes never calls sendClientQRLinks: it registers
two messages in a synthetic bundle and asserts on I18nBot, a passthrough
to go-i18n. With the tgbot_client.go line reverted to the hardcoded
English caption, both it and TestTgbotLocalesQrKeyValid still pass, so
neither certifies the fix.

The malformed-locale class they were added for is already pinned twice:
the discord package's TestMain loads every translation file through
locale.InitLocalizer and panics on invalid JSON, and
frontend/src/test/i18n-dead-keys.test.ts parses all 13 locales and
checks each carries the en-US key set. Both go red on the #6564 syntax
error this PR first shipped.

---------

Co-authored-by: sdhfsl <sdhfsl@users.noreply.github.com>
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-09-16 12:23:42 +02:00
sdhfsl d59b77bcdb fix(sub): send stable X-HWID on external subscription fetch (#6567)
* fix(panel): accept 2FA codes from adjacent TOTP windows

CheckUser compared only gotp.Now(), so a code submitted at the end of
its 30s window (or with slight client/server clock drift) failed with
'invalid 2fa code', while the immediate retry in the next window
succeeded. Accept current +/-1 window, the standard TOTP skew
tolerance.

Fixes MHSanaei/3x-ui#6535

* fix(panel): share TOTP skew tolerance with VerifyTwoFactorCode

Move the +/-1 window helper to internal/util/totp so both 2FA
acceptance points use it: login (CheckUser) and disable/rebind plus
username/password changes (VerifyTwoFactorCode). Also shrink comments
to the 2-line house rule and anchor the unit test mid-window to avoid
a step-boundary flake.

Addresses review on #6546 (MEDIUM + 2 LOWs).

* fix(sub): send stable X-HWID on external subscription fetch

A Master panel fetching a donor subscription sent no X-HWID, so an
HWID-limited donor rejected it with 404. Identify this panel with a
stable per-installation id (persisted in settings), occupying exactly
one donor device slot.

Fixes MHSanaei/3x-ui#6559

* fix(sub): address review on external X-HWID

- Serialize first-time id creation with a mutex so concurrent
  first fetches cannot mint two UUIDs.
- Fix goimports grouping for the new third-party import.
- Add externalSubSendHwid opt-out (default send); document it.
- Cover header send/omit with httptest in TestFetchSendsStableHwid.

* fix(sub): drop the SQL-only X-HWID opt-out

The externalSubSendHwid opt-out added in 227ed818 had no settings
field, CLI flag or docs, so an operator could only reach it by editing
the settings table by hand, while every cache-miss fetch paid a query
for it. CLAUDE.md rules out config knobs on a one-header fix.

Also drop the test assertions that only restated the 3x-ui-server-
prefix constant; TestFetchSendsStableHwid still goes red without the
header.

---------

Co-authored-by: sdhfsl <sdhfsl@users.noreply.github.com>
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-09-16 12:16:26 +02:00
Sanaei 17e89db979 feat(hosts): add a cipher suites override and accept custom suites
The inbound TLS form offered cipherSuites as a closed single-choice list,
but xray reads the value as a colon-separated list and accepts any name Go
knows, so several suites or one missing from the list could not be set.
Both the inbound and the new host field now use a tag picker that keeps
the stored value as the colon-joined string xray expects; old single
values open unchanged.

A host's cipher suites replace the inbound's in the JSON subscription
stream, and a blank field inherits them. Share links and Clash carry no
cipher suite parameter, so their output is unchanged.
2026-09-16 11:56:20 +02:00
Sanaei 040d01c5dc fix(clients): list HWID devices when the HWID limit is 0
EnforceHwidForSubID returned before recording anything when a sub had no
limit, so the panel's HWID Devices list stayed empty for every unlimited
client. Devices are now upserted on the (sub_id, hwid_hash) index without
enforcement or X-Hwid-* headers; the write is best-effort and only logs on
failure, so tracking can never deny a subscription nothing restricts.
2026-09-16 11:50:49 +02:00
Sanaei b78dd82869 fix(nodes): chart node net throughput in KB/s, not percent
The node history panel passed its Net Up / Net Down series to Sparkline
without valueMax or yFormatter, so they inherited the percentage defaults:
a fixed 0-100 scale and a "%" label. Any node above 100 KB/s drew off the
top of the chart and every axis tick and tooltip read as a percentage.

A Sparkline fed non-percentage data has to declare its own scale and unit;
every other call site already did, only the two node net series did not.
2026-09-16 11:48:55 +02:00
345 changed files with 19443 additions and 3238 deletions
+3 -6
View File
@@ -1,6 +1,3 @@
*.sh text eol=lf # LF in every checkout, Windows included: format-check, the msw worker check and
frontend/src/generated/** text eol=lf # tests that parse repo files compare bytes, so a CRLF working copy fails them.
frontend/public/openapi.json text eol=lf * text=auto eol=lf
frontend/src/test/__snapshots__/** text eol=lf
*.go text eol=lf
deploy/**/*.yaml text eol=lf
+2 -2
View File
@@ -100,8 +100,8 @@ question it already answers.
subtests and `t.Helper()` on helpers. An assertion must pin the exact value, subtests and `t.Helper()` on helpers. An assertion must pin the exact value,
typed error or emitted string — `err != nil` and `len(x) > 0` are findings, typed error or emitted string — `err != nil` and `len(x) > 0` are findings,
not nits. Prefer real dependencies: a throwaway DB via not nits. Prefer real dependencies: a throwaway DB via
`database.InitDB(filepath.Join(t.TempDir(), "x-ui.db"))` with `t.Cleanup`, and `dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))`
`httptest` for HTTP. `internal/sub`'s `initSubDB(t)` is the template. (`internal/database/dbtest`), and `httptest` for HTTP. `internal/sub`'s `initSubDB(t)` is the template.
A test must FAIL without its fix; one that passes either way certifies A test must FAIL without its fix; one that passes either way certifies
nothing and then gets cited as proof the fix works. nothing and then gets cited as proof the fix works.
+5 -5
View File
@@ -83,12 +83,12 @@ jobs:
- name: PostgreSQL schema and migration tests - name: PostgreSQL schema and migration tests
run: | run: |
set -o pipefail set -o pipefail
go test ./internal/database -run '^(TestHostAutoMigrateCreatesColumns_Postgres|TestMigrate_Postgres)$' -count=1 -v | tee /tmp/postgres-schema.log go test ./internal/database -run '^(TestHostAutoMigrateCreatesColumns_Postgres|TestMigrate_Postgres|TestClientWeeklyRenewMigration_Postgres)$' -count=1 -v | tee /tmp/postgres-schema.log
# Both must pass. Counting, not SKIP-matching: renaming either test would # All must pass. Counting, not SKIP-matching: renaming a test would
# otherwise leave this step green while testing nothing. # otherwise leave this step green while testing nothing.
passed=$(grep -c -- '--- PASS' /tmp/postgres-schema.log || true) passed=$(grep -c -- '^--- PASS' /tmp/postgres-schema.log || true)
if [ "$passed" -lt 2 ]; then if [ "$passed" -lt 3 ]; then
echo "expected 2 passing PostgreSQL schema tests, got $passed" >&2 echo "expected at least 3 passing PostgreSQL schema tests, got $passed" >&2
exit 1 exit 1
fi fi
+19 -3
View File
@@ -44,8 +44,8 @@ jobs:
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
allowed_non_write_users: "*" allowed_non_write_users: "*"
claude_args: | claude_args: |
--model claude-opus-5 --model claude-opus-5-5
--effort xhigh --effort medium
--max-turns 300 --max-turns 300
--allowedTools "Bash(gh label list:*),Bash(gh issue view:*),Bash(gh issue list:*),Bash(gh issue comment ${{ github.event.issue.number }}:*),Bash(gh issue edit ${{ github.event.issue.number }} --add-label:*),Bash(gh issue edit ${{ github.event.issue.number }} --remove-label:*),Bash(gh issue edit ${{ github.event.issue.number }} --title:*),Bash(gh issue close ${{ github.event.issue.number }}:*),Bash(gh search issues:*),Bash(gh search commits:*),Bash(gh search prs:*),Bash(gh pr view:*),Bash(gh pr diff:*),Bash(gh pr list:*),Bash(gh release list:*),Bash(gh release view:*),Bash(git log:*),Bash(git show:*),Bash(git blame:*),Bash(git ls-tree:*),Bash(git tag:*),Read,Glob,Grep,Write(//tmp/**),Edit(//tmp/**)" --allowedTools "Bash(gh label list:*),Bash(gh issue view:*),Bash(gh issue list:*),Bash(gh issue comment ${{ github.event.issue.number }}:*),Bash(gh issue edit ${{ github.event.issue.number }} --add-label:*),Bash(gh issue edit ${{ github.event.issue.number }} --remove-label:*),Bash(gh issue edit ${{ github.event.issue.number }} --title:*),Bash(gh issue close ${{ github.event.issue.number }}:*),Bash(gh search issues:*),Bash(gh search commits:*),Bash(gh search prs:*),Bash(gh pr view:*),Bash(gh pr diff:*),Bash(gh pr list:*),Bash(gh release list:*),Bash(gh release view:*),Bash(git log:*),Bash(git show:*),Bash(git blame:*),Bash(git ls-tree:*),Bash(git tag:*),Read,Glob,Grep,Write(//tmp/**),Edit(//tmp/**)"
--disallowedTools "Read(//**/.git/**),Edit(//**/.git/**)" --disallowedTools "Read(//**/.git/**),Edit(//**/.git/**)"
@@ -437,8 +437,24 @@ jobs:
path: ${{ runner.temp }}/claude-execution-output.json path: ${{ runner.temp }}/claude-execution-output.json
if-no-files-found: ignore if-no-files-found: ignore
retention-days: 7 retention-days: 7
- name: Fail if the analysis posted no reply # A refused credential ends the action with exit 0, so the step below cannot
# tell it from a reply that landed: the transcript is the only place it appears.
- name: Report an analysis the credential refused
id: refused
if: ${{ !cancelled() }} if: ${{ !cancelled() }}
env:
TRANSCRIPT: ${{ runner.temp }}/claude-execution-output.json
ISSUE: ${{ github.event.issue.number }}
run: |
set -euo pipefail
[ -f "$TRANSCRIPT" ] || exit 0
jq -e 'any(.[]; .type == "result" and ((.api_error_status // 0) == 401 or (.api_error_status // 0) == 403))' "$TRANSCRIPT" >/dev/null 2>&1 \
|| jq -e 'any(.[]; ((.error // "") | test("^(oauth_|authentication_|invalid_api_key)")))' "$TRANSCRIPT" >/dev/null 2>&1 \
|| exit 0
echo "skipped=true" >> "$GITHUB_OUTPUT"
echo "::warning::No analysis of #${ISSUE}: the Claude credential was refused, so this issue was not examined."
- name: Fail if the analysis posted no reply
if: ${{ !cancelled() && steps.refused.outputs.skipped != 'true' }}
env: env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
REPO: ${{ github.repository }} REPO: ${{ github.repository }}
+18 -3
View File
@@ -118,8 +118,8 @@ jobs:
# allowedTools only pre-approves; it denies nothing. Only the deny list # allowedTools only pre-approves; it denies nothing. Only the deny list
# stops the review executing what it just checked out, or delegating. # stops the review executing what it just checked out, or delegating.
claude_args: | claude_args: |
--model claude-opus-5 --model claude-opus-5-5
--effort xhigh --effort medium
--max-turns 300 --max-turns 300
--allowedTools "mcp__github_inline_comment__create_inline_comment,Bash(gh api:*),Bash(gh pr view:*),Bash(gh pr diff:*),Bash(gh pr comment ${{ env.PR }}:*),Bash(grep:*),Bash(rg:*),Bash(ls:*),Bash(find:*),Bash(sed:*),Bash(git log:*),Bash(git show:*),Bash(git diff:*),Bash(git blame:*),Bash(go doc:*),Bash(go env:*),Read,Glob,Grep,WebFetch,WebSearch" --allowedTools "mcp__github_inline_comment__create_inline_comment,Bash(gh api:*),Bash(gh pr view:*),Bash(gh pr diff:*),Bash(gh pr comment ${{ env.PR }}:*),Bash(grep:*),Bash(rg:*),Bash(ls:*),Bash(find:*),Bash(sed:*),Bash(git log:*),Bash(git show:*),Bash(git diff:*),Bash(git blame:*),Bash(go doc:*),Bash(go env:*),Read,Glob,Grep,WebFetch,WebSearch"
--disallowedTools "Agent,Bash(go build:*),Bash(go run:*),Bash(go test:*),Bash(go generate:*),Bash(go install:*),Bash(make:*),Bash(npm:*),Bash(npx:*),Bash(pnpm:*),Bash(yarn:*),Bash(node:*),Bash(bash:*),Bash(sh:*),Bash(docker:*),Bash(chmod:*),Edit,Write,NotebookEdit" --disallowedTools "Agent,Bash(go build:*),Bash(go run:*),Bash(go test:*),Bash(go generate:*),Bash(go install:*),Bash(make:*),Bash(npm:*),Bash(npx:*),Bash(pnpm:*),Bash(yarn:*),Bash(node:*),Bash(bash:*),Bash(sh:*),Bash(docker:*),Bash(chmod:*),Edit,Write,NotebookEdit"
@@ -228,10 +228,25 @@ jobs:
echo "skipped=true" >> "$GITHUB_OUTPUT" echo "skipped=true" >> "$GITHUB_OUTPUT"
echo "::notice::No review of #${PR}: ${reason}." echo "::notice::No review of #${PR}: ${reason}."
gh pr comment "$PR" --repo "$REPO" --body "No review ran on this head: ${reason}. Nothing in this pull request was examined. A maintainer can ask for one with \`@claude review\`." gh pr comment "$PR" --repo "$REPO" --body "No review ran on this head: ${reason}. Nothing in this pull request was examined. A maintainer can ask for one with \`@claude review\`."
# A refused credential ends the action with exit 0, so the step above never
# sees it: the transcript is the only place that refusal appears.
- name: Report a review the credential refused
id: refused
if: ${{ !cancelled() }}
env:
TRANSCRIPT: ${{ runner.temp }}/claude-execution-output.json
run: |
set -euo pipefail
[ -f "$TRANSCRIPT" ] || exit 0
jq -e 'any(.[]; .type == "result" and ((.api_error_status // 0) == 401 or (.api_error_status // 0) == 403))' "$TRANSCRIPT" >/dev/null 2>&1 \
|| jq -e 'any(.[]; ((.error // "") | test("^(oauth_|authentication_|invalid_api_key)")))' "$TRANSCRIPT" >/dev/null 2>&1 \
|| exit 0
echo "skipped=true" >> "$GITHUB_OUTPUT"
echo "::warning::No review of #${PR}: the Claude credential was refused, so nothing in this pull request was examined."
# updated_at, not created_at: a re-review may edit its earlier comment. # updated_at, not created_at: a re-review may edit its earlier comment.
# --paginate prints one jq count per page, so the pages are summed. # --paginate prints one jq count per page, so the pages are summed.
- name: Fail if the review posted nothing - name: Fail if the review posted nothing
if: ${{ !cancelled() && steps.pinned-sha.outcome == 'success' && steps.reviewed.outputs.done != 'true' && steps.throttled.outputs.skipped != 'true' }} if: ${{ !cancelled() && steps.pinned-sha.outcome == 'success' && steps.reviewed.outputs.done != 'true' && steps.throttled.outputs.skipped != 'true' && steps.refused.outputs.skipped != 'true' }}
env: env:
HEAD_SHA: ${{ steps.pinned-sha.outputs.sha }} HEAD_SHA: ${{ steps.pinned-sha.outputs.sha }}
STARTED_AT: ${{ steps.started.outputs.at }} STARTED_AT: ${{ steps.started.outputs.at }}
-8
View File
@@ -11,12 +11,6 @@ on:
- "go.mod" - "go.mod"
- "go.sum" - "go.sum"
- "frontend/**" - "frontend/**"
pull_request:
paths:
- "**.go"
- "go.mod"
- "go.sum"
- "frontend/**"
schedule: schedule:
- cron: "18 2 * * 2" - cron: "18 2 * * 2"
@@ -24,8 +18,6 @@ jobs:
analyze: analyze:
name: Analyze (${{ matrix.language }}) name: Analyze (${{ matrix.language }})
runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }} runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }}
env:
CODEQL_ACTION_FILE_COVERAGE_ON_PRS: true
permissions: permissions:
security-events: write security-events: write
packages: read packages: read
+3 -12
View File
@@ -2,9 +2,11 @@ name: Release 3X-UI
on: on:
workflow_dispatch: workflow_dispatch:
# Only main (dev channel) and version tags ship binaries; build any other
# branch on demand via workflow_dispatch.
push: push:
branches: branches:
- "**" - main
tags: tags:
- "v*.*.*" - "v*.*.*"
paths: paths:
@@ -17,17 +19,6 @@ on:
- "x-ui.service.arch" - "x-ui.service.arch"
- "x-ui.service.rhel" - "x-ui.service.rhel"
- ".github/workflows/release.yml" - ".github/workflows/release.yml"
pull_request:
paths:
- "**.go"
- "go.mod"
- "go.sum"
- "**.sh"
- "frontend/**"
- "x-ui.service.debian"
- "x-ui.service.arch"
- "x-ui.service.rhel"
- ".github/workflows/release.yml"
jobs: jobs:
build: build:
-69
View File
@@ -1,69 +0,0 @@
name: Deploy Smoke Tests
# Container smoke test for the unattended (cloud-init) install path.
# Runs when the install/deploy assets change on a branch push or PR, and
# again after a release-tag build finishes uploading its assets — passing the
# tag as an explicit version, so the green result verifies the release
# actually being shipped. That job deliberately runs the script from the
# default branch rather than checking out the tag: workflow_run executes in
# main's cache scope, so executing checked-out code there is a cache-poisoning
# surface (CodeQL actions/cache-poisoning/poisonable-step), and users pipe
# main's install.sh anyway.
# Tag pushes must NOT trigger the unpinned job directly: at that moment
# releases/latest still points at the previous release (#5756), and a `paths`
# filter alone cannot exclude them because a brand-new tag ref has no diff
# base, so it runs on every tag push.
on:
push:
branches:
- "**"
paths:
- "install.sh"
- "deploy/**"
- ".github/workflows/smoke.yml"
pull_request:
paths:
- "install.sh"
- "deploy/**"
- ".github/workflows/smoke.yml"
workflow_run:
workflows: ["Release 3X-UI"]
types: [completed]
permissions:
contents: read
jobs:
noninteractive-install:
if: github.event_name != 'workflow_run'
strategy:
fail-fast: false
matrix:
runner: [ubuntu-latest, ubuntu-24.04-arm]
runs-on: ${{ matrix.runner }}
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
- name: Non-interactive install smoke test
run: bash deploy/test/smoke-noninteractive.sh
release-tag-install:
if: >-
github.event_name == 'workflow_run' &&
github.event.workflow_run.conclusion == 'success' &&
github.event.workflow_run.event == 'push' &&
startsWith(github.event.workflow_run.head_branch, 'v') &&
contains(github.event.workflow_run.head_branch, '.')
strategy:
fail-fast: false
matrix:
runner: [ubuntu-latest, ubuntu-24.04-arm]
runs-on: ${{ matrix.runner }}
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
- name: Pinned release install smoke test
env:
XUI_SMOKE_VERSION: ${{ github.event.workflow_run.head_branch }}
run: bash deploy/test/smoke-noninteractive.sh "$XUI_SMOKE_VERSION"
+1 -1
View File
@@ -1 +1 @@
24 26
+48 -15
View File
@@ -75,11 +75,18 @@ file locations when it can answer in one hop.
share-link or install-command output changes. share-link or install-command output changes.
## Hard rules (non-negotiable) ## Hard rules (non-negotiable)
- Fix size must match bug size. Find the root cause, then make the SMALLEST - Correct fix over small fix. Find the root cause and fix it the right way, however
change that removes it — a one-line guard beats a new subsystem. A small bug much code that takes. Size the change by what the correct fix needs, never by
does not earn new columns, jobs, abstractions, config knobs or helper layers. line count: when the right fix spans many files, or needs a migration, a shared
If a fix genuinely needs new architecture, say so and get agreement first; helper or a new abstraction, write it. A guard that hides the symptom while the
never ship it unasked next to the fix. cause survives is the wrong fix, however small. Two limits remain:
- Everything added must be something the correct fix needs. No speculative
knobs, unused extension points or "while I was here" rewrites. Unrelated
refactors and cleanups go in their own commit.
- Stop and ask only when the right fix needs a decision the code cannot answer:
a deliberate user-visible behaviour change, or two sound designs with a real
trade-off. Ask with a recommendation. Size alone is never a reason to stop,
defer or ship a smaller patch.
- Comments in committed Go/TS: 2 lines MAX per comment block. Make the name - Comments in committed Go/TS: 2 lines MAX per comment block. Make the name
carry the meaning first and rename rather than annotate; spend the 2 lines on carry the meaning first and rename rather than annotate; spend the 2 lines on
the *why* a name cannot hold — an invariant, an issue number, a non-obvious the *why* a name cannot hold — an invariant, an issue number, a non-obvious
@@ -113,19 +120,45 @@ file locations when it can answer in one hop.
explaining the why. Types in use: `fix`, `feat`, `chore`, `refactor`, `perf`, explaining the why. Types in use: `fix`, `feat`, `chore`, `refactor`, `perf`,
`docs`, `style`. `docs`, `style`.
## Tests: TDD, and only tests that can fail (Go and frontend)
- Work red → green → refactor.
- Bug: turn the reproduction into a test first, and watch it fail for the
reported reason.
- Feature: write the test for the first behaviour before writing its code.
- Then write the code that makes it pass, and refactor with the suite green.
If a test was written after the code, prove it anyway: revert the code, watch
the test go red, then restore. A test that passes either way is worse than no
test. It certifies nothing, and then gets cited as proof the fix works.
- Every test must name the failure it catches. When no test can reach a change
(workflow YAML, pure wiring, layout), say so and name the command that
demonstrates it. Never write a stand-in test.
- Fake tests are forbidden. Delete any you write or meet in the code you touch:
- tests of a getter, a constant, a rename, a pure map lookup, or an input the
function can never receive;
- tests that restate the implementation, such as recomputing the expected
value with the same formula or asserting that a mock was called exactly the
way the code calls it;
- mocking the unit under test, or mocking so much around it that the real
code path never runs;
- assertions too weak to fail: `err != nil`, `len > 0`, `toBeDefined()`, or
`not.toThrow()` alone;
- golden files or snapshots regenerated to match whatever the code now outputs;
- extra cases that exercise no distinct branch, and tests written to raise
coverage.
One real test that drives the bug through the actual code path beats five
that restate the code.
## Go conventions ## Go conventions
- Stdlib `testing` only (no testify). Table-driven, `t.Run` subtests, - Stdlib `testing` only (no testify). Table-driven, `t.Run` subtests,
`t.Helper()` on helpers. Assert the exact value / typed error / emitted `t.Helper()` on helpers. Assert the exact value / typed error / emitted
string, never just `err != nil`. Prefer real deps over mocks: throwaway DB via string, never just `err != nil`. Prefer real deps over mocks: throwaway DB via
`database.InitDB(filepath.Join(t.TempDir(), "x-ui.db"))` + `dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))`
`t.Cleanup(func() { _ = database.CloseDB() })`; `httptest` for HTTP. (`internal/database/dbtest`: copies a once-migrated template and registers
`internal/sub`'s `initSubDB(t)` is the template. `CloseDB` cleanup; a fresh `database.InitDB` costs ~7x more, ~850ms under
- A test must fail without its fix. Write it, revert the fix, watch it go red, `-race`); `httptest` for HTTP. Keep `database.InitDB` for reopening a file or
restore. A test that passes either way is worse than no test: it certifies migrating a hand-built legacy DB. `internal/sub`'s `initSubDB(t)` is the template.
nothing and then gets cited as proof the fix works.
- Test what can actually break. No test for a getter, a constant, a rename, a
pure map lookup, or inputs the function can never receive. One real test that
drives the bug through the actual code path beats five that restate the code.
- Code must pass `golangci-lint run` (gofumpt + goimports formatting): `make lint`. - Code must pass `golangci-lint run` (gofumpt + goimports formatting): `make lint`.
- Postgres, xray-gRPC-e2e and scale tests `t.Skip` unless `XUI_TEST_PG_DSN`, - Postgres, xray-gRPC-e2e and scale tests `t.Skip` unless `XUI_TEST_PG_DSN`,
`XUI_DB_TYPE`+`XUI_DB_DSN`, `XRAY_E2E_BINARY` or `XUI_SCALE_TEST` is set — a `XUI_DB_TYPE`+`XUI_DB_DSN`, `XRAY_E2E_BINARY` or `XUI_SCALE_TEST` is set — a
@@ -136,7 +169,7 @@ file locations when it can answer in one hop.
- TS strict; `@typescript-eslint/no-explicit-any` is an error. Zod schemas in - TS strict; `@typescript-eslint/no-explicit-any` is an error. Zod schemas in
`src/schemas/` are the source of truth; infer types with `z.infer`, never `src/schemas/` are the source of truth; infer types with `z.infer`, never
hand-write. Do not edit `src/generated/`. hand-write. Do not edit `src/generated/`.
- Node 24 (`.nvmrc`) — `make gen` imports `.ts` directly and needs its type - Node 26 (`.nvmrc`) — `make gen` imports `.ts` directly and needs its type
stripping; Node 22 dies with `ERR_UNKNOWN_FILE_EXTENSION`. `npm test` includes stripping; Node 22 dies with `ERR_UNKNOWN_FILE_EXTENSION`. `npm test` includes
a headless-Chromium Storybook project, so run a headless-Chromium Storybook project, so run
`npx playwright install --with-deps chromium` once or `make verify` fails. `npx playwright install --with-deps chromium` once or `make verify` fails.
+8 -2
View File
@@ -5,7 +5,7 @@ Thanks for taking the time to contribute to 3x-ui. This guide gets a development
## Prerequisites ## Prerequisites
- **Go 1.27+** (the version pinned in `go.mod`) - **Go 1.27+** (the version pinned in `go.mod`)
- **Node.js 24 LTS** (the version pinned in `.nvmrc`) and npm 10+ (for the React frontend) - **Node.js 26** (the version pinned in `.nvmrc`) and npm 11+ (for the React frontend)
- **Git** - **Git**
- **A C compiler** — required by the CGo SQLite driver (`github.com/mattn/go-sqlite3`). Linux and macOS already ship one; for Windows see below. - **A C compiler** — required by the CGo SQLite driver (`github.com/mattn/go-sqlite3`). Linux and macOS already ship one; for Windows see below.
@@ -243,11 +243,17 @@ For deeper notes on the frontend toolchain see [`frontend/README.md`](frontend/R
Tests live next to the code (`foo.go` ↔ `foo_test.go`); frontend specs and golden fixtures live in `frontend/src/test/`. Tests live next to the code (`foo.go` ↔ `foo_test.go`); frontend specs and golden fixtures live in `frontend/src/test/`.
### Test first, and only tests that can fail
- **Red → green → refactor.** Write the test before the code. For a bug, the test reproduces the report; for a feature, it covers the first behaviour. Watch it fail, write the code that makes it pass, then refactor with the suite green.
- **Every test catches a named failure.** Don't test getters, constants or renames. Don't restate the implementation, mock the unit under test, write assertions too weak to fail, or regenerate snapshots to match whatever the code now outputs.
- **Fix the root cause the right way**, even when that takes more code. A small patch that hides the symptom is not a fix.
### Go conventions ### Go conventions
- **Stdlib `testing` only** — no testify. Table-driven with `t.Run` subtests and `t.Helper()` on helpers. - **Stdlib `testing` only** — no testify. Table-driven with `t.Run` subtests and `t.Helper()` on helpers.
- **Assert the contract, not internals.** Pin the exact value / typed error / emitted string — not `err != nil` or `len > 0`. A test that still passes when the behavior is broken is worse than no test. - **Assert the contract, not internals.** Pin the exact value / typed error / emitted string — not `err != nil` or `len > 0`. A test that still passes when the behavior is broken is worse than no test.
- **Real dependencies over mocks.** Get a throwaway DB with `database.InitDB(filepath.Join(t.TempDir(), "x-ui.db"))` + `t.Cleanup(func() { _ = database.CloseDB() })` (Windows-safe), and use `httptest` servers for HTTP. The `internal/sub` suite's `initSubDB(t)` is the template. - **Real dependencies over mocks.** Get a throwaway DB with `dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))` from `internal/database/dbtest`: it copies a once-migrated template (migrating from scratch per test is ~7x slower, worst under `-race`) and closes the DB before `t.TempDir` cleanup (Windows-safe). Keep `database.InitDB` for reopening an existing file or migrating a hand-built legacy DB. Use `httptest` servers for HTTP. The `internal/sub` suite's `initSubDB(t)` is the template.
### Running ### Running
+2 -4
View File
@@ -9,6 +9,7 @@ import (
"github.com/mhsanaei/3x-ui/v3/internal/config" "github.com/mhsanaei/3x-ui/v3/internal/config"
"github.com/mhsanaei/3x-ui/v3/internal/database" "github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
"github.com/mhsanaei/3x-ui/v3/internal/database/model" "github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/web/service/panel" "github.com/mhsanaei/3x-ui/v3/internal/web/service/panel"
) )
@@ -16,10 +17,7 @@ import (
func newTokenCLIEnv(t *testing.T) { func newTokenCLIEnv(t *testing.T) {
t.Helper() t.Helper()
t.Setenv("XUI_DB_FOLDER", t.TempDir()) t.Setenv("XUI_DB_FOLDER", t.TempDir())
if err := database.InitDB(config.GetDBPath()); err != nil { dbtest.InitDB(t, config.GetDBPath())
t.Fatalf("init db: %v", err)
}
t.Cleanup(func() { _ = database.CloseDB() })
} }
func tokenNames(t *testing.T) []string { func tokenNames(t *testing.T) []string {
+3 -3
View File
@@ -292,7 +292,7 @@ node heartbeat every 5s, periodic traffic resets (hourly/daily/weekly/monthly).
├── install.sh / update.sh / x-ui.sh # VPS install + management CLI ├── install.sh / update.sh / x-ui.sh # VPS install + management CLI
├── x-ui.service.* / x-ui.rc # systemd units (debian/rhel/arch) + rc script ├── x-ui.service.* / x-ui.rc # systemd units (debian/rhel/arch) + rc script
├── windows_files/ # Windows service support ├── windows_files/ # Windows service support
└── .github/workflows/ # CI: ci.yml, codeql.yml, docker.yml, release.yml, smoke.yml, └── .github/workflows/ # CI: ci.yml, codeql.yml, docker.yml, release.yml,
# mutation.yml, cleanup_caches.yml, claude-pr-review.yml, # mutation.yml, cleanup_caches.yml, claude-pr-review.yml,
# claude-issue-analyst.yml # claude-issue-analyst.yml
``` ```
@@ -565,7 +565,7 @@ golangci-lint run # full lint (gofumpt + goimports formatting)
go run main.go # run the panel locally (serves embedded dist if built) go run main.go # run the panel locally (serves embedded dist if built)
``` ```
**Frontend (`cd frontend`, Node 24 — see `.nvmrc`):** **Frontend (`cd frontend`, Node 26 — see `.nvmrc`):**
```bash ```bash
npm install npm install
@@ -583,7 +583,7 @@ root → `go build ./...` / `go run main.go`.
**Docker:** `docker compose up -d` (uses `Dockerfile` + `DockerEntrypoint.sh`). **Docker:** `docker compose up -d` (uses `Dockerfile` + `DockerEntrypoint.sh`).
**CI** (`.github/workflows/`): `ci.yml` (build/test/lint), `codeql.yml` (security scan), **CI** (`.github/workflows/`): `ci.yml` (build/test/lint), `codeql.yml` (security scan),
`smoke.yml` (smoke tests), `mutation.yml` (mutation testing), `docker.yml` + `release.yml` `mutation.yml` (mutation testing), `docker.yml` + `release.yml`
(multi-arch image + release builds), `cleanup_caches.yml`, `claude-pr-review.yml` (PR review (multi-arch image + release builds), `cleanup_caches.yml`, `claude-pr-review.yml` (PR review
only - it changes no code), `claude-issue-analyst.yml` (issue triage). only - it changes no code), `claude-issue-analyst.yml` (issue triage).
+3 -3
View File
@@ -43,10 +43,10 @@ value defeats the point, since DPI can fingerprint it over time.
| ------------ | ---------------------------------------------------------------------------- | | ------------ | ---------------------------------------------------------------------------- |
| **Jc** | Number of junk packets sent before the handshake. | | **Jc** | Number of junk packets sent before the handshake. |
| **Jmin/Jmax** | Size range (bytes) for those junk packets. `Jmin` must not exceed `Jmax`. | | **Jmin/Jmax** | Size range (bytes) for those junk packets. `Jmin` must not exceed `Jmax`. |
| **S1/S2** | Padding added to the handshake init/response packets. `S1 + 56` must not equal `S2` — amneziawg-go rejects a value that would make both packets the same size. | | **S1/S2** | Padding added to the handshake init/response packets, `0`-`1552` / `0`-`1608`: the packets are `148 + S1` and `92 + S2` bytes and must fit the 1700-byte receive buffer amneziawg-go uses on iOS. The panel also rejects `S1 + 56 = S2`, which would give both packets the same size on the wire (amneziawg-go itself accepts it). An AmneziaWG outbound takes the remote server's values as they are, up to `65535`. |
| **S3** | Cookie-reply padding, `0`-`64`. | | **S3** | Cookie-reply padding, `0`-`1636`: the reply is `64 + S3` bytes and must fit the 1700-byte receive buffer amneziawg-go uses on iOS. An outbound, as with S1/S2, takes the remote server's value up to `65535`. |
| **S4** | Transport (data) packet padding, `0`-`32`. | | **S4** | Transport (data) packet padding, `0`-`32`. |
| **H1-H4** | Magic header values that replace WireGuard's standard message-type bytes. Each is a single integer or a `low-high` range; `1`-`4` are reserved (real WireGuard message types) and must not be used. | | **H1-H4** | Header values that replace WireGuard's message-type field. Each is a single integer or a `low-high` range, and the four must not overlap — amneziawg-go and the kernel module refuse the whole device otherwise. `1`-`4` are WireGuard's own types and the engine default for a blank field: valid, but without a HeaderProtectionKey the type field then reads like plain WireGuard. |
| **I1-I5** | Optional signature packets — random bytes prepended before the handshake, e.g. `<r 148>`. Generated sets fill `I1` only, matching Amnezia's own generator. | | **I1-I5** | Optional signature packets — random bytes prepended before the handshake, e.g. `<r 148>`. Generated sets fill `I1` only, matching Amnezia's own generator. |
| **HeaderProtectionKey** | A base64 32-byte key for the 3.0 header-protection mechanism. Must match on every client config; blank disables it. | | **HeaderProtectionKey** | A base64 32-byte key for the 3.0 header-protection mechanism. Must match on every client config; blank disables it. |
| **ContentPaddingAddition** | A single integer or `low-high` byte range of extra padding on content packets. Kept `<= 64` by the generator so a 1420-MTU tunnel doesn't fragment. | | **ContentPaddingAddition** | A single integer or `low-high` byte range of extra padding on content packets. Kept `<= 64` by the generator so a 1420-MTU tunnel doesn't fragment. |
+63 -1
View File
@@ -20,7 +20,7 @@ inbounds** at once, with per-client traffic accounting.
| **Limit IP** | all (except TUIC) | Max simultaneous source IPs (enforced via Fail2ban). | | **Limit IP** | all (except TUIC) | Max simultaneous source IPs (enforced via Fail2ban). |
| **Total (GB)** | all (except TUIC) | Traffic quota; the client is disabled when exhausted (for TUIC, limits are set at the inbound level). | | **Total (GB)** | all (except TUIC) | Traffic quota; the client is disabled when exhausted (for TUIC, limits are set at the inbound level). |
| **Expiry** | all | Date after which the client stops working. | | **Expiry** | all | Date after which the client stops working. |
| **Reset** | all | Auto-renew period in **days** (rolls the quota over). | | **Auto renewal** | all | Disabled, fixed interval in days, calendar weekly, or calendar monthly. |
| **Telegram ID**| all | Links the client to a Telegram user for self-service/notifications.| | **Telegram ID**| all | Links the client to a Telegram user for self-service/notifications.|
| **Sub ID** | all | Subscription identifier grouping this client's links. | | **Sub ID** | all | Subscription identifier grouping this client's links. |
| **Group** | all | Optional client group for organization and bulk filtering. | | **Group** | all | Optional client group for organization and bulk filtering. |
@@ -42,6 +42,68 @@ inbounds** at once, with per-client traffic accounting.
- **Online status** and **last-online** times are tracked per client (and per - **Online status** and **last-online** times are tracked per client (and per
node in multi-node setups). node in multi-node setups).
## Automatic renewal
The individual and bulk-create forms offer one renewal mode at a time:
| Mode | API fields | Schedule |
| --- | --- | --- |
| Disabled | `reset=0`, `resetDay=0`, `resetWeekday=0` | The expiry is not renewed. |
| Fixed interval | `reset=N`, other two fields `0` | Add exactly N × 24 hours to the previous cutoff. |
| Calendar weekly | `resetWeekday=1..7`, other two fields `0` | Renew at panel-local midnight on Monday (1) through Sunday (7). |
| Calendar monthly | `resetDay=1..31`, `resetWeekday=0` | Renew at panel-local midnight on that day; missing dates clamp to the month's last day without losing the configured day. |
Calendar weeks stay on the selected weekday across daylight-saving changes;
they are not equivalent to a fixed seven-day interval. A skipped midnight uses
the first valid instant of that date; a repeated midnight uses the first one.
If a timezone skips the entire selected date, the next matching week is used.
Existing monthly clients
that also have `reset` set retain monthly precedence. The API rejects weekly
renewal combined with a positive `reset` or `resetDay`.
For a full calendar month, select **monthly, day 1** and set the initial cutoff
to the next month's first midnight. For example, `2030-09-01 00:00:00` is valid
through `2030-08-31 23:59:59`. Day 31 renews at the **start** of the 31st and is
not the same schedule. The existing optional month-end subscription-header
display remains a separate setting and is not enabled by this form.
The preview uses the panel's timezone and the same calendar/catch-up calculation
as automatic renewal. It shows the cutoff, last valid second, next expiry, and
allowances needed. It is informational: it does not save, activate, reserve, or
guarantee a future renewal. When no expiry is set, auto-renewal cannot run; an
explicit button can set the first calendar cutoff. Selecting a mode alone never
rewrites an existing expiry. First-use clients keep their initial duration, and
their calendar dates are available after activation.
For legacy last-second calendar cutoffs, the renewal boundary includes the
existing free alignment to the following midnight. The last-valid-second
preview still uses the **stored expiry**, not that alignment: an exclusive
`23:59:59` cutoff is valid through `23:59:58`. Use a next-midnight cutoff for
full-day validity; the preview itself does not repair the initial expiry.
`resetMax=0` means unlimited renewals. A positive limit counts **each elapsed
period**, including offline catch-up, not each scheduler tick or attached inbound.
If the remaining allowances cannot reach a future cutoff, the client stays
expired and its traffic is not reset. Operator-disabled clients stay disabled.
Renewal already resets client traffic. The separate **periodic traffic reset**
does not move the expiry and is unchanged; keep it disabled unless you intend an
additional reset. Quarterly, yearly, and every-N-week/month schedules are not
part of these modes.
<Callout type="warn">
Upgrade the main panel and every participating node before enabling weekly
renewal. Older versions ignore `resetWeekday`; a weekly-only client would not
auto-renew and, after its expiry or quota is exhausted, can be deleted by
**delete depleted clients** because older versions lack the weekly protection.
Back up the database and convert weekly schedules to a renewal mode supported
by every participating version before downgrading. Merely disabling weekly
renewal does not protect a depleted client from deletion. Avoid depleted-client
cleanup while a mixed-version fleet or unconverted weekly clients remain.
Database upgrades default this new field to `0` and preserve existing limits
and dates.
</Callout>
## Share links and external links ## Share links and external links
Every client has share links and a QR code for its inbounds, plus a combined Every client has share links and a QR code for its inbounds, plus a combined
@@ -53,13 +53,22 @@ Additional commands:
| Command | Who | Action | | Command | Who | Action |
| ------------------ | ------ | ------------------------------------------------------------ | | ------------------ | ------ | ------------------------------------------------------------ |
| `/start`, `/help` | anyone | Greeting and the menu of inline buttons | | `/start` | anyone | Greeting and the menu of inline buttons; an unlinked account gets only its Telegram ID |
| `/status` | anyone | Confirm the bot is alive | | `/help` | both | The menu of inline buttons |
| `/status` | both | Confirm the bot is alive |
| `/id` | anyone | Show your Telegram numeric ID | | `/id` | anyone | Show your Telegram numeric ID |
| `/usage <arg>` | both | Admins search clients; users look up their own usage | | `/usage <arg>` | both | Admins search clients; users look up their own usage |
| `/inbound <remark>`| admin | Show an inbound's details | | `/inbound <remark>`| admin | Show an inbound's details |
| `/restart` | admin | Restart Xray | | `/restart` | admin | Restart Xray |
A user is a Telegram account linked to at least one client. Any other account
can run only `/start` and `/id`; the bot ignores its other commands and
button taps. To link a customer, tap **Invite Link** on the client's card in the bot and
send them the `t.me` link: the first account to open it is linked to every
client that shares that Subscription ID. The Subscription ID is the invite code,
so keep it long and random. Each account gets five claim attempts an hour, and
admins are notified when one runs out.
Admins also get inline-button flows for server usage, sorted traffic reports, Admins also get inline-button flows for server usage, sorted traffic reports,
resetting traffic, DB backups, ban logs, listing inbounds/clients, online resetting traffic, DB backups, ban logs, listing inbounds/clients, online
clients, "depleting soon", and a full **add-client** wizard. Regular users get clients, "depleting soon", and a full **add-client** wizard. Regular users get
@@ -22,6 +22,12 @@ _openapi:
this — the middleware short-circuits CSRF for authenticated API this — the middleware short-circuits CSRF for authenticated API
requests. requests.
url: '#mint-a-csrf-token-for-the-current-session-the-spa-replays-it-in-the-x-csrf-token-header-on-unsafe-requests-bearer-token-callers-can-skip-this--the-middleware-short-circuits-csrf-for-authenticated-api-requests' url: '#mint-a-csrf-token-for-the-current-session-the-spa-replays-it-in-the-x-csrf-token-header-on-unsafe-requests-bearer-token-callers-can-skip-this--the-middleware-short-circuits-csrf-for-authenticated-api-requests'
- depth: 2
title: Public. Active paid sponsor placements read from the project
sponsors.json (cached for 1h); entries outside their from/until window
are dropped. Logos are proxied by the panel at /sponsors/logo/{name}.
Used by the login page and panel sponsor slots.
url: '#public-active-paid-sponsor-placements-read-from-the-project-sponsorsjson-cached-for-1h-entries-outside-their-fromuntil-window-are-dropped-logos-are-proxied-by-the-panel-at-sponsorslogoname-used-by-the-login-page-and-panel-sponsor-slots'
- depth: 2 - depth: 2
title: Returns whether 2FA is enabled on the panel — used by the login page to title: Returns whether 2FA is enabled on the panel — used by the login page to
decide whether to show the OTP field. decide whether to show the OTP field.
@@ -39,6 +45,11 @@ _openapi:
this — the middleware short-circuits CSRF for authenticated API this — the middleware short-circuits CSRF for authenticated API
requests. requests.
id: mint-a-csrf-token-for-the-current-session-the-spa-replays-it-in-the-x-csrf-token-header-on-unsafe-requests-bearer-token-callers-can-skip-this--the-middleware-short-circuits-csrf-for-authenticated-api-requests id: mint-a-csrf-token-for-the-current-session-the-spa-replays-it-in-the-x-csrf-token-header-on-unsafe-requests-bearer-token-callers-can-skip-this--the-middleware-short-circuits-csrf-for-authenticated-api-requests
- content: Public. Active paid sponsor placements read from the project
sponsors.json (cached for 1h); entries outside their from/until window
are dropped. Logos are proxied by the panel at /sponsors/logo/{name}.
Used by the login page and panel sponsor slots.
id: public-active-paid-sponsor-placements-read-from-the-project-sponsorsjson-cached-for-1h-entries-outside-their-fromuntil-window-are-dropped-logos-are-proxied-by-the-panel-at-sponsorslogoname-used-by-the-login-page-and-panel-sponsor-slots
- content: Returns whether 2FA is enabled on the panel — used by the login page to - content: Returns whether 2FA is enabled on the panel — used by the login page to
decide whether to show the OTP field. decide whether to show the OTP field.
id: returns-whether-2fa-is-enabled-on-the-panel--used-by-the-login-page-to-decide-whether-to-show-the-otp-field id: returns-whether-2fa-is-enabled-on-the-panel--used-by-the-login-page-to-decide-whether-to-show-the-otp-field
@@ -54,7 +65,7 @@ export default function Layout(props) {
return ( return (
<> <>
{props.children} {props.children}
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/login","method":"post"},{"path":"/logout","method":"post"},{"path":"/csrf-token","method":"get"},{"path":"/getTwoFactorEnable","method":"post"}]} showTitle /> <Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/login","method":"post"},{"path":"/logout","method":"post"},{"path":"/csrf-token","method":"get"},{"path":"/sponsors","method":"get"},{"path":"/getTwoFactorEnable","method":"post"}]} showTitle />
</> </>
); );
} }
+54 -27
View File
@@ -37,6 +37,9 @@ _openapi:
call. Body is JSON. Per-protocol secrets are generated server-side when call. Body is JSON. Per-protocol secrets are generated server-side when
omitted, so callers can send only the universal fields. omitted, so callers can send only the universal fields.
url: '#create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields' url: '#create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields'
- depth: 2
title: Preview client auto-renewal dates without saving or resetting anything.
url: '#preview-client-auto-renewal-dates-without-saving-or-resetting-anything'
- depth: 2 - depth: 2
title: Update an existing client by email. Changes propagate to every attached title: Update an existing client by email. Changes propagate to every attached
inbound. Body is the JSON client payload — supply the full set of fields inbound. Body is the JSON client payload — supply the full set of fields
@@ -78,21 +81,27 @@ _openapi:
Returns the deleted count. Cannot be undone. Returns the deleted count. Cannot be undone.
url: '#delete-every-client-that-is-not-attached-to-any-inbound-along-with-its-traffic-record-ip-log-hwid-devices-and-external-links-useful-for-clearing-clients-left-unattached-after-their-inbounds-were-removed-returns-the-deleted-count-cannot-be-undone' url: '#delete-every-client-that-is-not-attached-to-any-inbound-along-with-its-traffic-record-ip-log-hwid-devices-and-external-links-useful-for-clearing-clients-left-unattached-after-their-inbounds-were-removed-returns-the-deleted-count-cannot-be-undone'
- depth: 2 - depth: 2
title: Return every client as a {client, inboundIds} array — the same shape title: Return every client as a {client, inboundIds, traffic} array — the shape
/bulkCreate and /import accept — so the payload round-trips straight /import accepts — so the payload round-trips straight back through
back through /import. Clients with no inbound attachment are included /import. traffic carries the usage counters (up, down, resetCount,
with an empty inboundIds list. The UI shows this in a CodeMirror viewer lastOnline, lastSubFetch) and is omitted for a client with no traffic
(copy / download); programmatic callers get the array in obj. row; the quota itself stays in client.totalGB. Clients with no inbound
url: '#return-every-client-as-a-client-inboundids-array--the-same-shape-bulkcreate-and-import-accept--so-the-payload-round-trips-straight-back-through-import-clients-with-no-inbound-attachment-are-included-with-an-empty-inboundids-list-the-ui-shows-this-in-a-codemirror-viewer-copy--download-programmatic-callers-get-the-array-in-obj' attachment are included with an empty inboundIds list. The UI shows this
in a CodeMirror viewer (copy / download); programmatic callers get the
array in obj.
url: '#return-every-client-as-a-client-inboundids-traffic-array--the-shape-import-accepts--so-the-payload-round-trips-straight-back-through-import-traffic-carries-the-usage-counters-up-down-resetcount-lastonline-lastsubfetch-and-is-omitted-for-a-client-with-no-traffic-row-the-quota-itself-stays-in-clienttotalgb-clients-with-no-inbound-attachment-are-included-with-an-empty-inboundids-list-the-ui-shows-this-in-a-codemirror-viewer-copy--download-programmatic-callers-get-the-array-in-obj'
- depth: 2 - depth: 2
title: 'Import clients from a JSON body { "data": "<json>" }, where data is a title: 'Import clients from a JSON body { "data": "<json>" }, where data is a
string-encoded array produced by /export ([{client, inboundIds}]). Items string-encoded array produced by /export ([{client, inboundIds,
with inboundIds are created and attached to those inbounds; items with traffic}]). Items with inboundIds are created and attached to those
an empty inboundIds list are restored as unattached client records. inbounds; items with an empty inboundIds list are restored as unattached
Existing emails are never overwritten — they are returned in skipped. client records. An optional traffic object restores the usage counters,
Triggers a single Xray restart at the end if any target inbound was only for clients this import creates. Existing emails are never
running.' overwritten — they are returned in skipped, and their live counters are
url: '#import-clients-from-a-json-body--data-json--where-data-is-a-string-encoded-array-produced-by-export-client-inboundids-items-with-inboundids-are-created-and-attached-to-those-inbounds-items-with-an-empty-inboundids-list-are-restored-as-unattached-client-records-existing-emails-are-never-overwritten--they-are-returned-in-skipped-triggers-a-single-xray-restart-at-the-end-if-any-target-inbound-was-running' left untouched. Triggers a single Xray restart at the end if any target
inbound was running; a failure while restoring counters still reports
success=false after the clients were created.'
url: '#import-clients-from-a-json-body--data-json--where-data-is-a-string-encoded-array-produced-by-export-client-inboundids-traffic-items-with-inboundids-are-created-and-attached-to-those-inbounds-items-with-an-empty-inboundids-list-are-restored-as-unattached-client-records-an-optional-traffic-object-restores-the-usage-counters-only-for-clients-this-import-creates-existing-emails-are-never-overwritten--they-are-returned-in-skipped-and-their-live-counters-are-left-untouched-triggers-a-single-xray-restart-at-the-end-if-any-target-inbound-was-running-a-failure-while-restoring-counters-still-reports-successfalse-after-the-clients-were-created'
- depth: 2 - depth: 2
title: 'Shift expiry and/or traffic quota for many clients in one call. title: 'Shift expiry and/or traffic quota for many clients in one call.
addDays/addBytes may be negative. Clients with unlimited expiry addDays/addBytes may be negative. Clients with unlimited expiry
@@ -317,6 +326,8 @@ _openapi:
call. Body is JSON. Per-protocol secrets are generated server-side call. Body is JSON. Per-protocol secrets are generated server-side
when omitted, so callers can send only the universal fields. when omitted, so callers can send only the universal fields.
id: create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields id: create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
- content: Preview client auto-renewal dates without saving or resetting anything.
id: preview-client-auto-renewal-dates-without-saving-or-resetting-anything
- content: Update an existing client by email. Changes propagate to every attached - content: Update an existing client by email. Changes propagate to every attached
inbound. Body is the JSON client payload — supply the full set of inbound. Body is the JSON client payload — supply the full set of
fields you want to keep (the server replaces the row, it does not fields you want to keep (the server replaces the row, it does not
@@ -351,20 +362,26 @@ _openapi:
clearing clients left unattached after their inbounds were removed. clearing clients left unattached after their inbounds were removed.
Returns the deleted count. Cannot be undone. Returns the deleted count. Cannot be undone.
id: delete-every-client-that-is-not-attached-to-any-inbound-along-with-its-traffic-record-ip-log-hwid-devices-and-external-links-useful-for-clearing-clients-left-unattached-after-their-inbounds-were-removed-returns-the-deleted-count-cannot-be-undone id: delete-every-client-that-is-not-attached-to-any-inbound-along-with-its-traffic-record-ip-log-hwid-devices-and-external-links-useful-for-clearing-clients-left-unattached-after-their-inbounds-were-removed-returns-the-deleted-count-cannot-be-undone
- content: Return every client as a {client, inboundIds} array — the same shape - content: Return every client as a {client, inboundIds, traffic} array — the
/bulkCreate and /import accept — so the payload round-trips straight shape /import accepts — so the payload round-trips straight back
back through /import. Clients with no inbound attachment are included through /import. traffic carries the usage counters (up, down,
with an empty inboundIds list. The UI shows this in a CodeMirror resetCount, lastOnline, lastSubFetch) and is omitted for a client with
viewer (copy / download); programmatic callers get the array in obj. no traffic row; the quota itself stays in client.totalGB. Clients with
id: return-every-client-as-a-client-inboundids-array--the-same-shape-bulkcreate-and-import-accept--so-the-payload-round-trips-straight-back-through-import-clients-with-no-inbound-attachment-are-included-with-an-empty-inboundids-list-the-ui-shows-this-in-a-codemirror-viewer-copy--download-programmatic-callers-get-the-array-in-obj no inbound attachment are included with an empty inboundIds list. The
UI shows this in a CodeMirror viewer (copy / download); programmatic
callers get the array in obj.
id: return-every-client-as-a-client-inboundids-traffic-array--the-shape-import-accepts--so-the-payload-round-trips-straight-back-through-import-traffic-carries-the-usage-counters-up-down-resetcount-lastonline-lastsubfetch-and-is-omitted-for-a-client-with-no-traffic-row-the-quota-itself-stays-in-clienttotalgb-clients-with-no-inbound-attachment-are-included-with-an-empty-inboundids-list-the-ui-shows-this-in-a-codemirror-viewer-copy--download-programmatic-callers-get-the-array-in-obj
- content: 'Import clients from a JSON body { "data": "<json>" }, where data is a - content: 'Import clients from a JSON body { "data": "<json>" }, where data is a
string-encoded array produced by /export ([{client, inboundIds}]). string-encoded array produced by /export ([{client, inboundIds,
Items with inboundIds are created and attached to those inbounds; traffic}]). Items with inboundIds are created and attached to those
items with an empty inboundIds list are restored as unattached client inbounds; items with an empty inboundIds list are restored as
records. Existing emails are never overwritten — they are returned in unattached client records. An optional traffic object restores the
skipped. Triggers a single Xray restart at the end if any target usage counters, only for clients this import creates. Existing emails
inbound was running.' are never overwritten — they are returned in skipped, and their live
id: import-clients-from-a-json-body--data-json--where-data-is-a-string-encoded-array-produced-by-export-client-inboundids-items-with-inboundids-are-created-and-attached-to-those-inbounds-items-with-an-empty-inboundids-list-are-restored-as-unattached-client-records-existing-emails-are-never-overwritten--they-are-returned-in-skipped-triggers-a-single-xray-restart-at-the-end-if-any-target-inbound-was-running counters are left untouched. Triggers a single Xray restart at the end
if any target inbound was running; a failure while restoring counters
still reports success=false after the clients were created.'
id: import-clients-from-a-json-body--data-json--where-data-is-a-string-encoded-array-produced-by-export-client-inboundids-traffic-items-with-inboundids-are-created-and-attached-to-those-inbounds-items-with-an-empty-inboundids-list-are-restored-as-unattached-client-records-an-optional-traffic-object-restores-the-usage-counters-only-for-clients-this-import-creates-existing-emails-are-never-overwritten--they-are-returned-in-skipped-and-their-live-counters-are-left-untouched-triggers-a-single-xray-restart-at-the-end-if-any-target-inbound-was-running-a-failure-while-restoring-counters-still-reports-successfalse-after-the-clients-were-created
- content: 'Shift expiry and/or traffic quota for many clients in one call. - content: 'Shift expiry and/or traffic quota for many clients in one call.
addDays/addBytes may be negative. Clients with unlimited expiry addDays/addBytes may be negative. Clients with unlimited expiry
(expiryTime=0) or unlimited traffic (totalGB=0) are skipped for the (expiryTime=0) or unlimited traffic (totalGB=0) are skipped for the
@@ -592,6 +609,16 @@ _openapi:
one per line. `limitHwid` is applied only when every inbound one per line. `limitHwid` is applied only when every inbound
succeeded, so re-run the call after fixing the failure. succeeded, so re-run the call after fixing the failure.
heading: create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields heading: create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
- content: Uses the same calendar and catch-up calculation as auto-renew in the
panel timezone. resetWeekday is 1 (Monday) to 7 (Sunday), 0 disables
weekly mode; it cannot be combined with positive reset or resetDay.
Existing resetDay takes precedence over reset. With expiryTime=0,
calendar modes suggest a first cutoff but do not activate renewal.
Negative expiryTime waits for first-use activation. resetMax and
resetCount simulate the existing per-period allowance limit; the
preview is informational and does not reserve an allowance or
guarantee node availability.
heading: preview-client-auto-renewal-dates-without-saving-or-resetting-anything
- content: 'The inbounds are applied concurrently and independently: one that - content: 'The inbounds are applied concurrently and independently: one that
fails no longer stops the others. Every inbound error names the fails no longer stops the others. Every inbound error names the
inbound it came from (`inbound 7: <message>`), and several failures inbound it came from (`inbound 7: <message>`), and several failures
@@ -638,7 +665,7 @@ export default function Layout(props) {
return ( return (
<> <>
{props.children} {props.children}
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/clients/list","method":"get"},{"path":"/panel/api/clients/list/paged","method":"get"},{"path":"/panel/api/clients/get/{email}","method":"get"},{"path":"/panel/api/clients/get/tgId/{tgId}","method":"get"},{"path":"/panel/api/clients/add","method":"post"},{"path":"/panel/api/clients/update/{email}","method":"post"},{"path":"/panel/api/clients/del/{email}","method":"post"},{"path":"/panel/api/clients/{email}/attach","method":"post"},{"path":"/panel/api/clients/{email}/detach","method":"post"},{"path":"/panel/api/clients/{email}/externalLinks","method":"post"},{"path":"/panel/api/clients/resetAllTraffics","method":"post"},{"path":"/panel/api/clients/delDepleted","method":"post"},{"path":"/panel/api/clients/delOrphans","method":"post"},{"path":"/panel/api/clients/export","method":"get"},{"path":"/panel/api/clients/import","method":"post"},{"path":"/panel/api/clients/bulkAdjust","method":"post"},{"path":"/panel/api/clients/bulkEnable","method":"post"},{"path":"/panel/api/clients/bulkDisable","method":"post"},{"path":"/panel/api/clients/bulkDel","method":"post"},{"path":"/panel/api/clients/bulkCreate","method":"post"},{"path":"/panel/api/clients/groups/bulkAdd","method":"post"},{"path":"/panel/api/clients/groups/bulkRemove","method":"post"},{"path":"/panel/api/clients/bulkAttach","method":"post"},{"path":"/panel/api/clients/bulkDetach","method":"post"},{"path":"/panel/api/clients/bulkResetTraffic","method":"post"},{"path":"/panel/api/clients/groups","method":"get"},{"path":"/panel/api/clients/groups/{name}/emails","method":"get"},{"path":"/panel/api/clients/groups/create","method":"post"},{"path":"/panel/api/clients/groups/rename","method":"post"},{"path":"/panel/api/clients/groups/delete","method":"post"},{"path":"/panel/api/clients/groups/resetTraffic","method":"post"},{"path":"/panel/api/clients/resetTraffic/{email}","method":"post"},{"path":"/panel/api/clients/updateTraffic/{email}","method":"post"},{"path":"/panel/api/clients/ips/{email}","method":"post"},{"path":"/panel/api/clients/clearIps/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"delete"},{"path":"/panel/api/clients/hwids/{email}/{id}","method":"delete"},{"path":"/panel/api/clients/onlines","method":"post"},{"path":"/panel/api/clients/onlinesByGuid","method":"post"},{"path":"/panel/api/clients/clientIpsByGuid","method":"post"},{"path":"/panel/api/clients/activeInbounds","method":"post"},{"path":"/panel/api/clients/lastOnline","method":"post"},{"path":"/panel/api/clients/traffic/{email}","method":"get"},{"path":"/panel/api/clients/subLinks/{subId}","method":"get"},{"path":"/panel/api/clients/happLink/{id}","method":"post"},{"path":"/panel/api/clients/links/{email}","method":"get"}]} showTitle /> <Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/clients/list","method":"get"},{"path":"/panel/api/clients/list/paged","method":"get"},{"path":"/panel/api/clients/get/{email}","method":"get"},{"path":"/panel/api/clients/get/tgId/{tgId}","method":"get"},{"path":"/panel/api/clients/add","method":"post"},{"path":"/panel/api/clients/renewalPreview","method":"post"},{"path":"/panel/api/clients/update/{email}","method":"post"},{"path":"/panel/api/clients/del/{email}","method":"post"},{"path":"/panel/api/clients/{email}/attach","method":"post"},{"path":"/panel/api/clients/{email}/detach","method":"post"},{"path":"/panel/api/clients/{email}/externalLinks","method":"post"},{"path":"/panel/api/clients/resetAllTraffics","method":"post"},{"path":"/panel/api/clients/delDepleted","method":"post"},{"path":"/panel/api/clients/delOrphans","method":"post"},{"path":"/panel/api/clients/export","method":"get"},{"path":"/panel/api/clients/import","method":"post"},{"path":"/panel/api/clients/bulkAdjust","method":"post"},{"path":"/panel/api/clients/bulkEnable","method":"post"},{"path":"/panel/api/clients/bulkDisable","method":"post"},{"path":"/panel/api/clients/bulkDel","method":"post"},{"path":"/panel/api/clients/bulkCreate","method":"post"},{"path":"/panel/api/clients/groups/bulkAdd","method":"post"},{"path":"/panel/api/clients/groups/bulkRemove","method":"post"},{"path":"/panel/api/clients/bulkAttach","method":"post"},{"path":"/panel/api/clients/bulkDetach","method":"post"},{"path":"/panel/api/clients/bulkResetTraffic","method":"post"},{"path":"/panel/api/clients/groups","method":"get"},{"path":"/panel/api/clients/groups/{name}/emails","method":"get"},{"path":"/panel/api/clients/groups/create","method":"post"},{"path":"/panel/api/clients/groups/rename","method":"post"},{"path":"/panel/api/clients/groups/delete","method":"post"},{"path":"/panel/api/clients/groups/resetTraffic","method":"post"},{"path":"/panel/api/clients/resetTraffic/{email}","method":"post"},{"path":"/panel/api/clients/updateTraffic/{email}","method":"post"},{"path":"/panel/api/clients/ips/{email}","method":"post"},{"path":"/panel/api/clients/clearIps/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"delete"},{"path":"/panel/api/clients/hwids/{email}/{id}","method":"delete"},{"path":"/panel/api/clients/onlines","method":"post"},{"path":"/panel/api/clients/onlinesByGuid","method":"post"},{"path":"/panel/api/clients/clientIpsByGuid","method":"post"},{"path":"/panel/api/clients/activeInbounds","method":"post"},{"path":"/panel/api/clients/lastOnline","method":"post"},{"path":"/panel/api/clients/traffic/{email}","method":"get"},{"path":"/panel/api/clients/subLinks/{subId}","method":"get"},{"path":"/panel/api/clients/happLink/{id}","method":"post"},{"path":"/panel/api/clients/links/{email}","method":"get"}]} showTitle />
</> </>
); );
} }
+1 -1
View File
@@ -42,7 +42,7 @@ default. Encryption at rest is opt-in and fails closed: with any mode other than
| Variable | Default | Description | | Variable | Default | Description |
| ------------------------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ------------------------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `NODE_TOKEN_ENCRYPTION` | `off` | `off`, `migration` (reads accept plaintext or ciphertext, writes encrypt), or `required` (same writes, startup fails without a key). Note the missing `XUI_` prefix. | | `NODE_TOKEN_ENCRYPTION` | `off` | `off`, `migration` (reads accept plaintext or ciphertext, writes encrypt), or `required` (same writes, startup fails without a key). Note the missing `XUI_` prefix. |
| `XUI_NODE_TOKEN_KEY_FILE` | `/etc/x-ui/node_token_key.json` | JSON keyring, mode `0600` or stricter. Loaded first. | | `XUI_NODE_TOKEN_KEY_FILE` | `/etc/x-ui/node_token_key.json` | JSON keyring, mode `0600` or stricter (not checked on Windows, where NTFS permissions protect it). Loaded first. |
| `XUI_NODE_TOKEN_KEY` | — | A single base64 32-byte key, read only when the key file fails to load. Its key id is fixed to `env`, so it cannot rotate. | | `XUI_NODE_TOKEN_KEY` | — | A single base64 32-byte key, read only when the key file fails to load. Its key id is fixed to `env`, so it cannot rotate. |
The key file names the active key plus every older key still needed to decrypt: The key file names the active key plus every older key still needed to decrypt:
@@ -53,13 +53,22 @@ icon: Send
| فرمان | چه کسی | عملکرد | | فرمان | چه کسی | عملکرد |
| ------------------ | ------ | ------------------------------------------------------------ | | ------------------ | ------ | ------------------------------------------------------------ |
| `/start`، `/help` | همه | پیام خوش‌آمدگویی و منوی دکمه‌های درون‌خطی | | `/start` | همه | پیام خوش‌آمدگویی و منوی دکمه‌های درون‌خطی؛ حساب متصل‌نشده فقط شناسه‌ی Telegram خود را می‌گیرد |
| `/status` | همه | تأیید فعال بودن ربات | | `/help` | هر دو | منوی دکمه‌های درون‌خطی |
| `/status` | هر دو | تأیید فعال بودن ربات |
| `/id` | همه | نمایش شناسه‌ی عددی Telegram شما | | `/id` | همه | نمایش شناسه‌ی عددی Telegram شما |
| `/usage <arg>` | هر دو | ادمین‌ها کلاینت‌ها را جست‌وجو می‌کنند؛ کاربران مصرف خود را می‌بینند | | `/usage <arg>` | هر دو | ادمین‌ها کلاینت‌ها را جست‌وجو می‌کنند؛ کاربران مصرف خود را می‌بینند |
| `/inbound <remark>`| ادمین | نمایش جزئیات یک ورودی | | `/inbound <remark>`| ادمین | نمایش جزئیات یک ورودی |
| `/restart` | ادمین | راه‌اندازی مجدد Xray | | `/restart` | ادمین | راه‌اندازی مجدد Xray |
کاربر یعنی حساب Telegramی که دست‌کم به یک کلاینت متصل است. هر حساب دیگری فقط
`/start` و `/id` را می‌تواند اجرا کند و ربات فرمان‌ها و دکمه‌های دیگر آن را نادیده
می‌گیرد. برای اتصال یک مشتری، در کارت کلاینت در ربات روی **لینک دعوت** بزنید و لینک `t.me`
را برایش بفرستید: نخستین حسابی که آن را باز کند به همه‌ی کلاینت‌هایی که آن شناسه
اشتراک را دارند متصل می‌شود. شناسه اشتراک همان کد دعوت است، پس آن را طولانی و
تصادفی نگه دارید. هر حساب در هر ساعت پنج بار می‌تواند تلاش کند و پس از آن به
ادمین‌ها اطلاع داده می‌شود.
ادمین‌ها همچنین جریان‌های دکمه‌ی درون‌خطی برای مصرف سرور، گزارش‌های ترافیک مرتب‌شده، ادمین‌ها همچنین جریان‌های دکمه‌ی درون‌خطی برای مصرف سرور، گزارش‌های ترافیک مرتب‌شده،
بازنشانی ترافیک، پشتیبان‌گیری از DB، گزارش‌های مسدودسازی، فهرست کردن ورودی‌ها/کلاینت‌ها، بازنشانی ترافیک، پشتیبان‌گیری از DB، گزارش‌های مسدودسازی، فهرست کردن ورودی‌ها/کلاینت‌ها،
کلاینت‌های آنلاین، «به‌زودی تمام‌شونده» و یک جادوگر کامل **افزودن کلاینت** را در اختیار دارند. کلاینت‌های آنلاین، «به‌زودی تمام‌شونده» و یک جادوگر کامل **افزودن کلاینت** را در اختیار دارند.
+1 -1
View File
@@ -42,7 +42,7 @@ icon: Variable
| Variable | Default | Description | | Variable | Default | Description |
| ------------------------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ------------------------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `NODE_TOKEN_ENCRYPTION` | `off` | ‏`off`، `migration` (خواندن هم متن ساده و هم متن رمزشده را می‌پذیرد، نوشتن همیشه رمز می‌کند) یا `required` (نوشتن یکسان، اما بدون کلید اجرا شکست می‌خورد). به نبودِ پیشوند `XUI_` توجه کنید. | | `NODE_TOKEN_ENCRYPTION` | `off` | ‏`off`، `migration` (خواندن هم متن ساده و هم متن رمزشده را می‌پذیرد، نوشتن همیشه رمز می‌کند) یا `required` (نوشتن یکسان، اما بدون کلید اجرا شکست می‌خورد). به نبودِ پیشوند `XUI_` توجه کنید. |
| `XUI_NODE_TOKEN_KEY_FILE` | `/etc/x-ui/node_token_key.json` | حلقه‌کلید JSON با دسترسی `0600` یا محدودتر. نخست همین بارگذاری می‌شود. | | `XUI_NODE_TOKEN_KEY_FILE` | `/etc/x-ui/node_token_key.json` | حلقه‌کلید JSON با دسترسی `0600` یا محدودتر (در ویندوز بررسی نمی‌شود و مجوزهای NTFS از آن محافظت می‌کنند). نخست همین بارگذاری می‌شود. |
| `XUI_NODE_TOKEN_KEY` | — | یک کلید ۳۲ بایتی base64 که فقط هنگام شکست بارگذاری فایل کلید خوانده می‌شود. شناسه‌ی کلید آن ثابت و برابر `env` است، پس امکان چرخش ندارد. | | `XUI_NODE_TOKEN_KEY` | — | یک کلید ۳۲ بایتی base64 که فقط هنگام شکست بارگذاری فایل کلید خوانده می‌شود. شناسه‌ی کلید آن ثابت و برابر `env` است، پس امکان چرخش ندارد. |
فایل کلید، کلید فعال به‌همراه هر کلید قدیمی‌ای را که هنوز برای رمزگشایی لازم است نام می‌برد: فایل کلید، کلید فعال به‌همراه هر کلید قدیمی‌ای را که هنوز برای رمزگشایی لازم است نام می‌برد:
@@ -55,13 +55,23 @@ chat ID** (через запятую). Сохраните, затем напиш
| Команда | Кому | Действие | | Команда | Кому | Действие |
| ------------------ | ------ | ------------------------------------------------------------ | | ------------------ | ------ | ------------------------------------------------------------ |
| `/start`, `/help` | всем | Приветствие и меню встроенных кнопок | | `/start` | всем | Приветствие и меню встроенных кнопок; непривязанный аккаунт получает только свой Telegram ID |
| `/status` | всем | Подтверждает, что бот работает | | `/help` | обоим | Меню встроенных кнопок |
| `/status` | обоим | Подтверждает, что бот работает |
| `/id` | всем | Показывает ваш числовой Telegram ID | | `/id` | всем | Показывает ваш числовой Telegram ID |
| `/usage <arg>` | обоим | Администраторы ищут клиентов; пользователи смотрят свой расход | | `/usage <arg>` | обоим | Администраторы ищут клиентов; пользователи смотрят свой расход |
| `/inbound <remark>`| админ | Показывает сведения о входящем подключении | | `/inbound <remark>`| админ | Показывает сведения о входящем подключении |
| `/restart` | админ | Перезапускает Xray | | `/restart` | админ | Перезапускает Xray |
Пользователь — это аккаунт Telegram, привязанный хотя бы к одному клиенту. Любой
другой аккаунт может выполнять только `/start` и `/id`; остальные его команды и
нажатия кнопок бот игнорирует. Чтобы привязать клиента, нажмите
**Ссылка-приглашение** в карточке клиента в боте и отправьте ему ссылку `t.me`: первый
открывший её аккаунт привязывается ко всем клиентам с этим ID подписки. ID
подписки служит кодом приглашения, поэтому делайте его длинным и случайным.
У каждого аккаунта пять попыток в час, после чего администраторы получают
уведомление.
Администраторам также доступны сценарии со встроенными кнопками: использование Администраторам также доступны сценарии со встроенными кнопками: использование
сервера, отсортированные отчёты по трафику, сброс трафика, резервные копии БД, сервера, отсортированные отчёты по трафику, сброс трафика, резервные копии БД,
журналы блокировок, список входящих подключений/клиентов, онлайн-клиенты, журналы блокировок, список входящих подключений/клиентов, онлайн-клиенты,
+1 -1
View File
@@ -43,7 +43,7 @@ API-токены узлов — и сохранённый токен PIA — п
| Variable | Default | Description | | Variable | Default | Description |
| ------------------------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ------------------------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `NODE_TOKEN_ENCRYPTION` | `off` | `off`, `migration` (чтение принимает открытый текст или шифротекст, запись всегда шифрует) или `required` (запись та же, но без ключа запуск не удастся). Префикса `XUI_` здесь нет. | | `NODE_TOKEN_ENCRYPTION` | `off` | `off`, `migration` (чтение принимает открытый текст или шифротекст, запись всегда шифрует) или `required` (запись та же, но без ключа запуск не удастся). Префикса `XUI_` здесь нет. |
| `XUI_NODE_TOKEN_KEY_FILE` | `/etc/x-ui/node_token_key.json` | JSON-связка ключей с правами `0600` или строже. Загружается первой. | | `XUI_NODE_TOKEN_KEY_FILE` | `/etc/x-ui/node_token_key.json` | JSON-связка ключей с правами `0600` или строже (в Windows не проверяется: файл защищают права NTFS). Загружается первой. |
| `XUI_NODE_TOKEN_KEY` | — | Один 32-байтный ключ в base64, читается только при неудачной загрузке файла ключей. Его идентификатор фиксирован (`env`), поэтому ротация невозможна. | | `XUI_NODE_TOKEN_KEY` | — | Один 32-байтный ключ в base64, читается только при неудачной загрузке файла ключей. Его идентификатор фиксирован (`env`), поэтому ротация невозможна. |
Файл ключей задаёт активный ключ и все прежние ключи, ещё нужные для расшифровки: Файл ключей задаёт активный ключ и все прежние ключи, ещё нужные для расшифровки:
+53 -1
View File
@@ -19,7 +19,7 @@ icon: Users
| **Limit IP** | 全部(TUIC 除外) | 最大同时连接的源 IP 数量(通过 Fail2ban 强制执行)。 | | **Limit IP** | 全部(TUIC 除外) | 最大同时连接的源 IP 数量(通过 Fail2ban 强制执行)。 |
| **Total (GB)** | 全部(TUIC 除外) | 流量配额;用尽后客户端将被禁用(对于 TUIC,限制在入站级别设置)。 | | **Total (GB)** | 全部(TUIC 除外) | 流量配额;用尽后客户端将被禁用(对于 TUIC,限制在入站级别设置)。 |
| **Expiry** | 全部 | 该日期之后客户端停止工作。 | | **Expiry** | 全部 | 该日期之后客户端停止工作。 |
| **Reset** | 全部 | 以**天**为单位的自动续期周期(滚动重置配额)。 | | **自动续期** | 全部 | 关闭、固定天数、日历每周或日历每月。 |
| **Telegram ID**| 全部 | 将客户端关联到 Telegram 用户,用于自助服务/通知。 | | **Telegram ID**| 全部 | 将客户端关联到 Telegram 用户,用于自助服务/通知。 |
| **Sub ID** | 全部 | 用于对该客户端链接分组的订阅标识符。 | | **Sub ID** | 全部 | 用于对该客户端链接分组的订阅标识符。 |
| **Group** | 全部 | 可选的客户端分组,便于组织管理和批量筛选。 | | **Group** | 全部 | 可选的客户端分组,便于组织管理和批量筛选。 |
@@ -39,6 +39,58 @@ icon: Users
并从该客户端的操作中清除它们。 并从该客户端的操作中清除它们。
- 系统会按客户端(在多节点部署中还会按节点)跟踪**在线状态**和**最后在线**时间。 - 系统会按客户端(在多节点部署中还会按节点)跟踪**在线状态**和**最后在线**时间。
## 自动续期
单个客户端和批量创建表单使用统一的续期模式选择:
| 模式 | API 字段 | 续期规则 |
| --- | --- | --- |
| 关闭 | `reset=0`、`resetDay=0`、`resetWeekday=0` | 不自动延长到期时间。 |
| 固定天数 | `reset=N`,另两个字段为 `0` | 从上次截止时间增加 N × 24 小时。 |
| 日历每周 | `resetWeekday=1..7`,另两个字段为 `0` | 在面板时区每周一(1)至周日(7)的零点续期。 |
| 日历每月 | `resetDay=1..31`、`resetWeekday=0` | 在面板时区指定日的零点续期;短月取月末,之后仍按原配置日续期。 |
日历每周跨夏令时仍保持指定星期,不等于固定 7 天。若零点不存在,使用
该日期第一个有效时刻;零点重复时取第一次。若时区跳过整天,则使用
下一周的同一星期。旧配置同时填写
`reset` 和 `resetDay` 时继续以每月续期为准。API 不允许每周续期与正数
`reset` 或 `resetDay` 同时启用。
整自然月应选**每月、1 日**,首次截止时间设置为下月 1 日零点。例如
`2030-09-01 00:00:00` 表示有效至 `2030-08-31 23:59:59`。
31 日表示在 31 日**开始时**续期,并不是同一边界。订阅头原有的可选
月末显示设置仍独立存在,本表单不会自动开启它。
日期预览使用面板时区和后端实际续期的同一套计算,显示截止时间、最后
有效秒、下次到期时间及需要消耗的续期次数。预览不会保存、激活或预留
续期,也不保证未来一定续期。未设到期时间时自动续期无法运行,可以
明确点击按钮设置首次日历截止时间;仅选择模式不会修改已有到期时间。
“首次使用后开始”保留原来的初始天数,激活后才能确定日历日期。
旧配置以最后一秒为日历截止时间时,续期边界包含原有的不计次数向下个
零点对齐规则。但最后有效秒仍按**已存储的到期时间**计算,不会假装
初始时间已被修改:排他截止时间 `23:59:59` 实际有效至 `23:59:58`。
整天有效应使用下一个零点,预览本身不会修复首次截止时间。
最大续期次数 `resetMax=0` 表示不限次数。正数上限按**每个经过的周期**
计数,包括离线补续,不按定时任务执行次数或关联入站数量计数。剩余
次数不足以续到未来时,客户端继续过期且不会重置流量;手动禁用的
客户端保持禁用。
自动续期本身会重置客户端流量。独立的**定期流量重置**不延长到期时间,
这次未改变其规则;除非需要额外重置,否则保持关闭。本次不包含季度、
年度和每 N 周/月的续期。
<Callout type="warn">
启用每周续期前,需要升级主面板及所有参与节点。旧版本会忽略
`resetWeekday`,仅配置每周的客户端将无法自动续期,且在到期或流量
耗尽后,可能被**删除已耗尽客户端**操作删除,因为旧版没有每周续期
的清理保护。降级前应备份数据库,并将每周配置转换为所有参与版本
都支持的续期模式;仅关闭每周续期并不能防止耗尽后的删除。存在
混合版本或尚未转换的每周客户端时,应避免执行耗尽客户端清理。
数据库升级默认将新字段设为 `0`,保留已有日期和限制。
</Callout>
## 分享链接与外部链接 ## 分享链接与外部链接
每个客户端都有针对其各入站的分享链接和二维码,外加一个合并的 每个客户端都有针对其各入站的分享链接和二维码,外加一个合并的
@@ -51,13 +51,20 @@ icon: Send
| 命令 | 适用对象 | 作用 | | 命令 | 适用对象 | 作用 |
| ------------------ | ------ | ------------------------------------------------------------ | | ------------------ | ------ | ------------------------------------------------------------ |
| `/start`、`/help` | 任何人 | 问候语以及内联按钮菜单 | | `/start` | 任何人 | 问候语以及内联按钮菜单;未绑定的账号只会收到自己的 Telegram ID |
| `/status` | 任何人 | 确认机器人在线 | | `/help` | 两者 | 内联按钮菜单 |
| `/status` | 两者 | 确认机器人在线 |
| `/id` | 任何人 | 显示你的 Telegram 数字 ID | | `/id` | 任何人 | 显示你的 Telegram 数字 ID |
| `/usage <arg>` | 两者 | 管理员可搜索客户端;用户则查询自己的用量 | | `/usage <arg>` | 两者 | 管理员可搜索客户端;用户则查询自己的用量 |
| `/inbound <remark>`| 管理员 | 显示某个入站的详情 | | `/inbound <remark>`| 管理员 | 显示某个入站的详情 |
| `/restart` | 管理员 | 重启 Xray | | `/restart` | 管理员 | 重启 Xray |
用户是指至少绑定了一个客户端的 Telegram 账号。其他账号只能使用 `/start` 和
`/id`,机器人会忽略它们的其他命令和按钮点击。要绑定客户,请在机器人的客户端卡片上点击
**邀请链接**,并把 `t.me` 链接发给对方:第一个打开该链接的账号会绑定到共用该订阅
ID 的所有客户端。订阅 ID 就是邀请码,因此请保持其足够长且随机。每个账号每小时
可尝试五次,用完后会通知管理员。
管理员还可通过内联按钮使用一系列功能:服务器用量、按流量排序的报告、 管理员还可通过内联按钮使用一系列功能:服务器用量、按流量排序的报告、
重置流量、数据库备份、封禁日志、列出入站/客户端、在线客户端、 重置流量、数据库备份、封禁日志、列出入站/客户端、在线客户端、
“即将耗尽”,以及完整的**添加客户端**向导。普通用户则可以使用按钮查看 “即将耗尽”,以及完整的**添加客户端**向导。普通用户则可以使用按钮查看
+1 -1
View File
@@ -40,7 +40,7 @@ icon: Variable
| Variable | Default | Description | | Variable | Default | Description |
| ------------------------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ------------------------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `NODE_TOKEN_ENCRYPTION` | `off` | `off`、`migration`(读取时接受明文或密文,写入一律加密)或 `required`(写入相同,但缺少密钥时启动失败)。注意此处没有 `XUI_` 前缀。 | | `NODE_TOKEN_ENCRYPTION` | `off` | `off`、`migration`(读取时接受明文或密文,写入一律加密)或 `required`(写入相同,但缺少密钥时启动失败)。注意此处没有 `XUI_` 前缀。 |
| `XUI_NODE_TOKEN_KEY_FILE` | `/etc/x-ui/node_token_key.json` | JSON 密钥环,权限须为 `0600` 或更严格。优先加载。 | | `XUI_NODE_TOKEN_KEY_FILE` | `/etc/x-ui/node_token_key.json` | JSON 密钥环,权限须为 `0600` 或更严格(Windows 上不检查,由 NTFS 权限保护)。优先加载。 |
| `XUI_NODE_TOKEN_KEY` | — | 单个 base64 编码的 32 字节密钥,仅在密钥文件加载失败时读取。其密钥 ID 固定为 `env`,因此无法轮换。 | | `XUI_NODE_TOKEN_KEY` | — | 单个 base64 编码的 32 字节密钥,仅在密钥文件加载失败时读取。其密钥 ID 固定为 `env`,因此无法轮换。 |
密钥文件同时记录活动密钥和所有仍需用于解密的旧密钥: 密钥文件同时记录活动密钥和所有仍需用于解密的旧密钥:
+11 -11
View File
@@ -18,14 +18,14 @@
"test:watch": "vitest" "test:watch": "vitest"
}, },
"dependencies": { "dependencies": {
"fumadocs-core": "^16.15.11", "fumadocs-core": "^16.15.14",
"fumadocs-docgen": "^3.1.1", "fumadocs-docgen": "^3.1.1",
"fumadocs-mdx": "^15.4.1", "fumadocs-mdx": "^15.4.5",
"fumadocs-openapi": "^11.4.3", "fumadocs-openapi": "^12.0.3",
"fumadocs-ui": "^16.15.11", "fumadocs-ui": "^16.15.14",
"lucide-react": "^1.46.0", "lucide-react": "^1.48.0",
"mermaid": "^12.0.0", "mermaid": "^12.0.0",
"next": "16.3.5", "next": "16.3.6",
"next-themes": "^0.4.6", "next-themes": "^0.4.6",
"react": "^19.3.0", "react": "^19.3.0",
"react-dom": "^19.3.0", "react-dom": "^19.3.0",
@@ -37,15 +37,15 @@
"devDependencies": { "devDependencies": {
"@tailwindcss/postcss": "^4.3.3", "@tailwindcss/postcss": "^4.3.3",
"@types/mdx": "^2.0.14", "@types/mdx": "^2.0.14",
"@types/node": "^26.5.1", "@types/node": "^26.6.2",
"@types/react": "^19.3.0", "@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0", "@types/react-dom": "^19.3.0",
"oxfmt": "0.68.0", "oxfmt": "0.70.0",
"oxlint": "1.83.0", "oxlint": "1.85.0",
"postcss": "^8.5.28", "postcss": "^8.5.28",
"tailwindcss": "^4.3.3", "tailwindcss": "^4.3.3",
"typescript": "7.0.2", "typescript": "7.0.2",
"vitest": "^5.0.1" "vitest": "^5.0.2"
}, },
"packageManager": "pnpm@12.4.2" "packageManager": "pnpm@12.6.0"
} }
+497 -484
View File
File diff suppressed because it is too large Load Diff
+5 -5
View File
@@ -12,16 +12,16 @@ minimumReleaseAgeExclude:
- mermaid@11.17.0 - mermaid@11.17.0
- lucide-react@1.33.0 - lucide-react@1.33.0
- postcss@8.5.26 - postcss@8.5.26
- fumadocs-mdx@15.3.0 || 15.4.1 - fumadocs-mdx@15.3.0 || 15.4.1 || 15.4.5
- '@fumadocs/api-docs@0.2.7 || 0.2.9' - '@fumadocs/api-docs@0.2.7 || 0.2.9'
- '@types/node@26.4.1' - '@types/node@26.4.1'
- fumadocs-core@16.15.5 || 16.15.11 - fumadocs-core@16.15.5 || 16.15.11
- fumadocs-openapi@11.4.0 || 11.4.3 - fumadocs-openapi@11.4.0 || 11.4.3 || 12.0.3
- fumadocs-ui@16.15.5 || 16.15.11 - fumadocs-ui@16.15.5 || 16.15.11
- '@fumadocs/tailwind@0.1.2' - '@fumadocs/tailwind@0.1.2'
- '@fumari/image-size@0.1.1' - '@fumari/image-size@0.1.1'
- '@fumari/stf@1.1.1' - '@fumari/stf@1.1.1'
- '@vitest/mocker@5.0.1' - '@vitest/mocker@5.0.1 || 5.0.2'
- '@vitest/spy@5.0.1' - '@vitest/spy@5.0.1 || 5.0.2'
- fumadocs-docgen@3.1.1 - fumadocs-docgen@3.1.1
- vitest@5.0.1 - vitest@5.0.1 || 5.0.2
+621 -5
View File
@@ -69,6 +69,9 @@
"minimum": 0, "minimum": 0,
"type": "integer" "type": "integer"
}, },
"externalSubUserAgent": {
"type": "string"
},
"externalTrafficInformEnable": { "externalTrafficInformEnable": {
"type": "boolean" "type": "boolean"
}, },
@@ -288,6 +291,9 @@
"subHappFallbackUrl": { "subHappFallbackUrl": {
"type": "string" "type": "string"
}, },
"subHappLocalProxyAuth": {
"type": "string"
},
"subHappNewUrl": { "subHappNewUrl": {
"type": "string" "type": "string"
}, },
@@ -336,12 +342,97 @@
"subHideSettings": { "subHideSettings": {
"type": "boolean" "type": "boolean"
}, },
"subIncyAnnounceUrl": {
"type": "string"
},
"subIncyAppAutoDetect": {
"description": "Incy client customization settings (app-management). A \"\" value omits\nthe header so the subscriber's own app setting is left alone.",
"type": "boolean"
},
"subIncyBannerBgColor": {
"type": "string"
},
"subIncyBannerButtonColor": {
"type": "string"
},
"subIncyBannerButtonText": {
"type": "string"
},
"subIncyBannerButtonUrl": {
"type": "string"
},
"subIncyBannerText": {
"type": "string"
},
"subIncyEnableRouting": { "subIncyEnableRouting": {
"type": "boolean" "type": "boolean"
}, },
"subIncyFragmentInterval": {
"type": "string"
},
"subIncyFragmentLength": {
"type": "string"
},
"subIncyFragmentPackets": {
"type": "string"
},
"subIncyFragmentationEnable": {
"type": "string"
},
"subIncyHideCheck": {
"type": "string"
},
"subIncyHideUrl": {
"type": "string"
},
"subIncyNoLimitEnabled": {
"type": "string"
},
"subIncyNoisesDelay": {
"type": "string"
},
"subIncyNoisesEnable": {
"type": "string"
},
"subIncyNoisesPacket": {
"type": "string"
},
"subIncyNoisesType": {
"type": "string"
},
"subIncyPerAppEnable": {
"type": "string"
},
"subIncyPerAppList": {
"type": "string"
},
"subIncyPerAppMode": {
"type": "string"
},
"subIncyPremiumUrl": {
"type": "string"
},
"subIncyProfileDescription": {
"type": "string"
},
"subIncyResolveDnsDomain": {
"type": "string"
},
"subIncyResolveDnsIp": {
"type": "string"
},
"subIncyResolveEnable": {
"type": "string"
},
"subIncyRoutingRules": { "subIncyRoutingRules": {
"type": "string" "type": "string"
}, },
"subIncySortOrder": {
"type": "string"
},
"subIncySupportEmail": {
"type": "string"
},
"subInfoNodeEnable": { "subInfoNodeEnable": {
"type": "boolean" "type": "boolean"
}, },
@@ -519,6 +610,7 @@
"discordMemory", "discordMemory",
"discordRunTime", "discordRunTime",
"expireDiff", "expireDiff",
"externalSubUserAgent",
"externalTrafficInformEnable", "externalTrafficInformEnable",
"externalTrafficInformURI", "externalTrafficInformURI",
"happLinkEnable", "happLinkEnable",
@@ -586,6 +678,7 @@
"subHappExcludeApns", "subHappExcludeApns",
"subHappExcludeRoutes", "subHappExcludeRoutes",
"subHappFallbackUrl", "subHappFallbackUrl",
"subHappLocalProxyAuth",
"subHappNewUrl", "subHappNewUrl",
"subHappNoLimit", "subHappNoLimit",
"subHappNotificationExpire", "subHappNotificationExpire",
@@ -602,8 +695,36 @@
"subHappTunMode", "subHappTunMode",
"subHappTunType", "subHappTunType",
"subHideSettings", "subHideSettings",
"subIncyAnnounceUrl",
"subIncyAppAutoDetect",
"subIncyBannerBgColor",
"subIncyBannerButtonColor",
"subIncyBannerButtonText",
"subIncyBannerButtonUrl",
"subIncyBannerText",
"subIncyEnableRouting", "subIncyEnableRouting",
"subIncyFragmentInterval",
"subIncyFragmentLength",
"subIncyFragmentPackets",
"subIncyFragmentationEnable",
"subIncyHideCheck",
"subIncyHideUrl",
"subIncyNoLimitEnabled",
"subIncyNoisesDelay",
"subIncyNoisesEnable",
"subIncyNoisesPacket",
"subIncyNoisesType",
"subIncyPerAppEnable",
"subIncyPerAppList",
"subIncyPerAppMode",
"subIncyPremiumUrl",
"subIncyProfileDescription",
"subIncyResolveDnsDomain",
"subIncyResolveDnsIp",
"subIncyResolveEnable",
"subIncyRoutingRules", "subIncyRoutingRules",
"subIncySortOrder",
"subIncySupportEmail",
"subInfoNodeEnable", "subInfoNodeEnable",
"subJsonAlwaysArray", "subJsonAlwaysArray",
"subJsonAutoDetect", "subJsonAutoDetect",
@@ -700,6 +821,9 @@
"minimum": 0, "minimum": 0,
"type": "integer" "type": "integer"
}, },
"externalSubUserAgent": {
"type": "string"
},
"externalTrafficInformEnable": { "externalTrafficInformEnable": {
"type": "boolean" "type": "boolean"
}, },
@@ -943,6 +1067,9 @@
"subHappFallbackUrl": { "subHappFallbackUrl": {
"type": "string" "type": "string"
}, },
"subHappLocalProxyAuth": {
"type": "string"
},
"subHappNewUrl": { "subHappNewUrl": {
"type": "string" "type": "string"
}, },
@@ -991,12 +1118,97 @@
"subHideSettings": { "subHideSettings": {
"type": "boolean" "type": "boolean"
}, },
"subIncyAnnounceUrl": {
"type": "string"
},
"subIncyAppAutoDetect": {
"description": "Incy client customization settings (app-management). A \"\" value omits\nthe header so the subscriber's own app setting is left alone.",
"type": "boolean"
},
"subIncyBannerBgColor": {
"type": "string"
},
"subIncyBannerButtonColor": {
"type": "string"
},
"subIncyBannerButtonText": {
"type": "string"
},
"subIncyBannerButtonUrl": {
"type": "string"
},
"subIncyBannerText": {
"type": "string"
},
"subIncyEnableRouting": { "subIncyEnableRouting": {
"type": "boolean" "type": "boolean"
}, },
"subIncyFragmentInterval": {
"type": "string"
},
"subIncyFragmentLength": {
"type": "string"
},
"subIncyFragmentPackets": {
"type": "string"
},
"subIncyFragmentationEnable": {
"type": "string"
},
"subIncyHideCheck": {
"type": "string"
},
"subIncyHideUrl": {
"type": "string"
},
"subIncyNoLimitEnabled": {
"type": "string"
},
"subIncyNoisesDelay": {
"type": "string"
},
"subIncyNoisesEnable": {
"type": "string"
},
"subIncyNoisesPacket": {
"type": "string"
},
"subIncyNoisesType": {
"type": "string"
},
"subIncyPerAppEnable": {
"type": "string"
},
"subIncyPerAppList": {
"type": "string"
},
"subIncyPerAppMode": {
"type": "string"
},
"subIncyPremiumUrl": {
"type": "string"
},
"subIncyProfileDescription": {
"type": "string"
},
"subIncyResolveDnsDomain": {
"type": "string"
},
"subIncyResolveDnsIp": {
"type": "string"
},
"subIncyResolveEnable": {
"type": "string"
},
"subIncyRoutingRules": { "subIncyRoutingRules": {
"type": "string" "type": "string"
}, },
"subIncySortOrder": {
"type": "string"
},
"subIncySupportEmail": {
"type": "string"
},
"subInfoNodeEnable": { "subInfoNodeEnable": {
"type": "boolean" "type": "boolean"
}, },
@@ -1174,6 +1386,7 @@
"discordMemory", "discordMemory",
"discordRunTime", "discordRunTime",
"expireDiff", "expireDiff",
"externalSubUserAgent",
"externalTrafficInformEnable", "externalTrafficInformEnable",
"externalTrafficInformURI", "externalTrafficInformURI",
"happLinkEnable", "happLinkEnable",
@@ -1249,6 +1462,7 @@
"subHappExcludeApns", "subHappExcludeApns",
"subHappExcludeRoutes", "subHappExcludeRoutes",
"subHappFallbackUrl", "subHappFallbackUrl",
"subHappLocalProxyAuth",
"subHappNewUrl", "subHappNewUrl",
"subHappNoLimit", "subHappNoLimit",
"subHappNotificationExpire", "subHappNotificationExpire",
@@ -1265,8 +1479,36 @@
"subHappTunMode", "subHappTunMode",
"subHappTunType", "subHappTunType",
"subHideSettings", "subHideSettings",
"subIncyAnnounceUrl",
"subIncyAppAutoDetect",
"subIncyBannerBgColor",
"subIncyBannerButtonColor",
"subIncyBannerButtonText",
"subIncyBannerButtonUrl",
"subIncyBannerText",
"subIncyEnableRouting", "subIncyEnableRouting",
"subIncyFragmentInterval",
"subIncyFragmentLength",
"subIncyFragmentPackets",
"subIncyFragmentationEnable",
"subIncyHideCheck",
"subIncyHideUrl",
"subIncyNoLimitEnabled",
"subIncyNoisesDelay",
"subIncyNoisesEnable",
"subIncyNoisesPacket",
"subIncyNoisesType",
"subIncyPerAppEnable",
"subIncyPerAppList",
"subIncyPerAppMode",
"subIncyPremiumUrl",
"subIncyProfileDescription",
"subIncyResolveDnsDomain",
"subIncyResolveDnsIp",
"subIncyResolveEnable",
"subIncyRoutingRules", "subIncyRoutingRules",
"subIncySortOrder",
"subIncySupportEmail",
"subInfoNodeEnable", "subInfoNodeEnable",
"subJsonAlwaysArray", "subJsonAlwaysArray",
"subJsonAutoDetect", "subJsonAutoDetect",
@@ -1523,13 +1765,17 @@
"type": "integer" "type": "integer"
}, },
"resetDay": { "resetDay": {
"description": "Calendar renewal day 1-31, 0 = interval mode", "description": "Calendar renewal day 1-31, 0 disables monthly renewal",
"type": "integer" "type": "integer"
}, },
"resetMax": { "resetMax": {
"description": "Max auto-renew count, 0 = unlimited", "description": "Max auto-renew count, 0 = unlimited",
"type": "integer" "type": "integer"
}, },
"resetWeekday": {
"description": "Calendar weekday 1-7 (Mon-Sun), 0 disables weekly renewal",
"type": "integer"
},
"reverse": { "reverse": {
"allOf": [ "allOf": [
{ {
@@ -1592,6 +1838,7 @@
"reset", "reset",
"resetDay", "resetDay",
"resetMax", "resetMax",
"resetWeekday",
"security", "security",
"subId", "subId",
"tgId", "tgId",
@@ -1743,6 +1990,9 @@
"resetMax": { "resetMax": {
"type": "integer" "type": "integer"
}, },
"resetWeekday": {
"type": "integer"
},
"reverse": {}, "reverse": {},
"secret": { "secret": {
"type": "string" "type": "string"
@@ -1798,6 +2048,7 @@
"reset", "reset",
"resetDay", "resetDay",
"resetMax", "resetMax",
"resetWeekday",
"reverse", "reverse",
"secret", "secret",
"security", "security",
@@ -1811,6 +2062,97 @@
], ],
"type": "object" "type": "object"
}, },
"ClientRenewalPreview": {
"properties": {
"canRenew": {
"example": true,
"type": "boolean"
},
"delayedStart": {
"example": false,
"type": "boolean"
},
"nextExpiry": {
"example": "2030-02-01T00:00:00Z",
"type": "string"
},
"renewAt": {
"example": "2030-01-01T00:00:00Z",
"type": "string"
},
"renewals": {
"example": 1,
"type": "integer"
},
"suggestedExpiry": {
"example": "2030-01-01T00:00:00Z",
"type": "string"
},
"suggestedExpiryTime": {
"example": 1893456000000,
"format": "int64",
"type": "integer"
},
"timeZone": {
"example": "UTC",
"type": "string"
},
"validThrough": {
"example": "2029-12-31T23:59:59Z",
"type": "string"
}
},
"required": [
"canRenew",
"delayedStart",
"nextExpiry",
"renewAt",
"renewals",
"suggestedExpiry",
"suggestedExpiryTime",
"timeZone",
"validThrough"
],
"type": "object"
},
"ClientRenewalPreviewRequest": {
"properties": {
"expiryTime": {
"example": 1893456000000,
"format": "int64",
"type": "integer"
},
"reset": {
"example": 0,
"type": "integer"
},
"resetCount": {
"example": 0,
"type": "integer"
},
"resetDay": {
"example": 1,
"type": "integer"
},
"resetMax": {
"example": 0,
"type": "integer"
},
"resetWeekday": {
"example": 0,
"type": "integer"
}
},
"required": [
"expiryTime",
"reset",
"resetCount",
"resetDay",
"resetMax",
"resetWeekday"
],
"type": "object"
},
"ClientReverse": { "ClientReverse": {
"properties": { "properties": {
"tag": { "tag": {
@@ -1881,6 +2223,10 @@
"example": 0, "example": 0,
"type": "integer" "type": "integer"
}, },
"resetWeekday": {
"example": 0,
"type": "integer"
},
"subId": { "subId": {
"example": "abcd1234", "example": "abcd1234",
"type": "string" "type": "string"
@@ -1915,6 +2261,7 @@
"reset", "reset",
"resetDay", "resetDay",
"resetMax", "resetMax",
"resetWeekday",
"subId", "subId",
"totalGB", "totalGB",
"updatedAt" "updatedAt"
@@ -1970,7 +2317,7 @@
"type": "integer" "type": "integer"
}, },
"resetDay": { "resetDay": {
"description": "ResetDay renews on that day of each calendar month instead of every\nReset days; 0 keeps the interval behaviour.", "description": "ResetDay renews on that day of each calendar month instead of every\nReset days; 0 disables monthly renewal.",
"example": 0, "example": 0,
"type": "integer" "type": "integer"
}, },
@@ -1979,6 +2326,11 @@
"example": 0, "example": 0,
"type": "integer" "type": "integer"
}, },
"resetWeekday": {
"description": "ResetWeekday renews weekly at panel-local midnight: 1 Monday through 7 Sunday.",
"example": 0,
"type": "integer"
},
"subId": { "subId": {
"example": "i7tvdpeffi0hvvf1", "example": "i7tvdpeffi0hvvf1",
"type": "string" "type": "string"
@@ -2011,6 +2363,7 @@
"resetCount", "resetCount",
"resetDay", "resetDay",
"resetMax", "resetMax",
"resetWeekday",
"subId", "subId",
"total", "total",
"up", "up",
@@ -2301,6 +2654,9 @@
}, },
"type": "array" "type": "array"
}, },
"cipherSuites": {
"type": "string"
},
"createdAt": { "createdAt": {
"format": "int64", "format": "int64",
"type": "integer" "type": "integer"
@@ -2434,6 +2790,7 @@
"address", "address",
"allowInsecure", "allowInsecure",
"alpn", "alpn",
"cipherSuites",
"createdAt", "createdAt",
"echConfigList", "echConfigList",
"excludeFromSubTypes", "excludeFromSubTypes",
@@ -2478,6 +2835,9 @@
}, },
"type": "array" "type": "array"
}, },
"cipherSuites": {
"type": "string"
},
"echConfigList": { "echConfigList": {
"type": "string" "type": "string"
}, },
@@ -2604,6 +2964,7 @@
"required": [ "required": [
"allowInsecure", "allowInsecure",
"alpn", "alpn",
"cipherSuites",
"echConfigList", "echConfigList",
"excludeFromSubTypes", "excludeFromSubTypes",
"finalMask", "finalMask",
@@ -2693,6 +3054,11 @@
"example": true, "example": true,
"type": "boolean" "type": "boolean"
}, },
"excludeFromSub": {
"description": "Whether to omit this inbound from subscription output while keeping it operational",
"example": false,
"type": "boolean"
},
"expiryTime": { "expiryTime": {
"description": "Expiration timestamp", "description": "Expiration timestamp",
"format": "int64", "format": "int64",
@@ -2816,6 +3182,7 @@
"disableFlow", "disableFlow",
"down", "down",
"enable", "enable",
"excludeFromSub",
"expiryTime", "expiryTime",
"id", "id",
"lastTrafficResetTime", "lastTrafficResetTime",
@@ -4127,6 +4494,90 @@
], ],
"type": "object" "type": "object"
}, },
"Sponsor": {
"description": "Sponsor is one paid placement published in the repo's sponsors.json.",
"properties": {
"enable": {
"example": true,
"nullable": true,
"type": "boolean"
},
"from": {
"example": "2026-10-01T00:00:00Z",
"format": "date-time",
"nullable": true,
"type": "string"
},
"id": {
"example": "acme-2026-10",
"type": "string"
},
"link": {
"example": "https://acme.example/?utm_source=3x-ui",
"type": "string"
},
"logo": {
"example": "/sponsors/logo/acme.png",
"type": "string"
},
"name": {
"example": "Acme VPS",
"type": "string"
},
"slots": {
"items": {
"type": "string"
},
"type": "array"
},
"text": {
"additionalProperties": {
"type": "string"
},
"type": "object"
},
"title": {
"additionalProperties": {
"type": "string"
},
"type": "object"
},
"until": {
"example": "2026-11-01T00:00:00Z",
"format": "date-time",
"type": "string"
}
},
"required": [
"id",
"link",
"name",
"slots",
"text",
"title",
"until"
],
"type": "object"
},
"SponsorList": {
"description": "SponsorList is the active sponsor set plus the contact link for new sponsors.",
"properties": {
"contact": {
"example": "https://t.me/example",
"type": "string"
},
"sponsors": {
"items": {
"$ref": "#/components/schemas/Sponsor"
},
"type": "array"
}
},
"required": [
"sponsors"
],
"type": "object"
},
"SubBalancer": { "SubBalancer": {
"description": "SubBalancer is one extra JSON-subscription config document whose members are\nthe selected inbounds' proxy outbounds. SortOrder shares SubSortIndex semantics.", "description": "SubBalancer is one extra JSON-subscription config document whose members are\nthe selected inbounds' proxy outbounds. SortOrder shares SubSortIndex semantics.",
"properties": { "properties": {
@@ -4579,6 +5030,60 @@
} }
} }
}, },
"/sponsors": {
"get": {
"tags": [
"Authentication"
],
"summary": "Public. Active paid sponsor placements read from the project sponsors.json (cached for 1h); entries outside their from/until window are dropped. Logos are proxied by the panel at /sponsors/logo/{name}. Used by the login page and panel sponsor slots.",
"operationId": "get_sponsors",
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {
"$ref": "#/components/schemas/SponsorList"
}
}
},
"example": {
"success": true,
"obj": {
"contact": "https://t.me/example",
"sponsors": [
{
"enable": true,
"from": "2026-10-01T00:00:00Z",
"id": "acme-2026-10",
"link": "https://acme.example/?utm_source=3x-ui",
"logo": "/sponsors/logo/acme.png",
"name": "Acme VPS",
"slots": [
""
],
"text": {},
"title": {},
"until": "2026-11-01T00:00:00Z"
}
]
}
}
}
}
}
}
}
},
"/getTwoFactorEnable": { "/getTwoFactorEnable": {
"post": { "post": {
"tags": [ "tags": [
@@ -4660,6 +5165,7 @@
"resetCount": 0, "resetCount": 0,
"resetDay": 0, "resetDay": 0,
"resetMax": 0, "resetMax": 0,
"resetWeekday": 0,
"subId": "i7tvdpeffi0hvvf1", "subId": "i7tvdpeffi0hvvf1",
"total": 10737418240, "total": 10737418240,
"up": 1048576, "up": 1048576,
@@ -4669,6 +5175,7 @@
"disableFlow": false, "disableFlow": false,
"down": 0, "down": 0,
"enable": true, "enable": true,
"excludeFromSub": false,
"expiryTime": 0, "expiryTime": 0,
"fallbackParent": null, "fallbackParent": null,
"id": 1, "id": 1,
@@ -7894,6 +8401,7 @@
"reset": 0, "reset": 0,
"resetDay": 0, "resetDay": 0,
"resetMax": 0, "resetMax": 0,
"resetWeekday": 0,
"subId": "abcd1234", "subId": "abcd1234",
"totalGB": 53687091200, "totalGB": 53687091200,
"traffic": null, "traffic": null,
@@ -8086,6 +8594,97 @@
} }
} }
}, },
"/panel/api/clients/renewalPreview": {
"post": {
"tags": [
"Clients"
],
"summary": "Preview client auto-renewal dates without saving or resetting anything.",
"operationId": "post_panel_api_clients_renewalPreview",
"description": "Uses the same calendar and catch-up calculation as auto-renew in the panel timezone. resetWeekday is 1 (Monday) to 7 (Sunday), 0 disables weekly mode; it cannot be combined with positive reset or resetDay. Existing resetDay takes precedence over reset. With expiryTime=0, calendar modes suggest a first cutoff but do not activate renewal. Negative expiryTime waits for first-use activation. resetMax and resetCount simulate the existing per-period allowance limit; the preview is informational and does not reserve an allowance or guarantee node availability.",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"expiryTime": {
"type": "integer",
"description": "Current cutoff in Unix milliseconds; 0 unlimited, negative first-use duration."
},
"reset": {
"type": "integer",
"description": "Fixed interval in days; 0 disabled."
},
"resetDay": {
"type": "integer",
"description": "Monthly calendar day 1-31; 0 disabled."
},
"resetWeekday": {
"type": "integer",
"description": "Weekly calendar day 1-7 (Monday-Sunday); 0 disabled."
},
"resetMax": {
"type": "integer",
"description": "Maximum renewals; 0 unlimited."
},
"resetCount": {
"type": "integer",
"description": "Renewals already consumed; defaults to 0."
}
},
"required": [
"expiryTime",
"reset",
"resetDay",
"resetWeekday",
"resetMax",
"resetCount"
]
}
}
}
},
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {
"$ref": "#/components/schemas/ClientRenewalPreview"
}
}
},
"example": {
"success": true,
"obj": {
"canRenew": true,
"delayedStart": false,
"nextExpiry": "2030-02-01T00:00:00Z",
"renewAt": "2030-01-01T00:00:00Z",
"renewals": 1,
"suggestedExpiry": "2030-01-01T00:00:00Z",
"suggestedExpiryTime": 1893456000000,
"timeZone": "UTC",
"validThrough": "2029-12-31T23:59:59Z"
}
}
}
}
}
}
}
},
"/panel/api/clients/update/{email}": { "/panel/api/clients/update/{email}": {
"post": { "post": {
"tags": [ "tags": [
@@ -8545,7 +9144,7 @@
"tags": [ "tags": [
"Clients" "Clients"
], ],
"summary": "Return every client as a {client, inboundIds} array — the same shape /bulkCreate and /import accept — so the payload round-trips straight back through /import. Clients with no inbound attachment are included with an empty inboundIds list. The UI shows this in a CodeMirror viewer (copy / download); programmatic callers get the array in obj.", "summary": "Return every client as a {client, inboundIds, traffic} array — the shape /import accepts — so the payload round-trips straight back through /import. traffic carries the usage counters (up, down, resetCount, lastOnline, lastSubFetch) and is omitted for a client with no traffic row; the quota itself stays in client.totalGB. Clients with no inbound attachment are included with an empty inboundIds list. The UI shows this in a CodeMirror viewer (copy / download); programmatic callers get the array in obj.",
"operationId": "get_panel_api_clients_export", "operationId": "get_panel_api_clients_export",
"responses": { "responses": {
"200": { "200": {
@@ -8580,7 +9179,13 @@
"inboundIds": [ "inboundIds": [
7, 7,
9 9
] ],
"traffic": {
"up": 1048576,
"down": 2097152,
"resetCount": 0,
"lastOnline": 1735680000000
}
} }
] ]
} }
@@ -8595,7 +9200,7 @@
"tags": [ "tags": [
"Clients" "Clients"
], ],
"summary": "Import clients from a JSON body { \"data\": \"<json>\" }, where data is a string-encoded array produced by /export ([{client, inboundIds}]). Items with inboundIds are created and attached to those inbounds; items with an empty inboundIds list are restored as unattached client records. Existing emails are never overwritten — they are returned in skipped. Triggers a single Xray restart at the end if any target inbound was running.", "summary": "Import clients from a JSON body { \"data\": \"<json>\" }, where data is a string-encoded array produced by /export ([{client, inboundIds, traffic}]). Items with inboundIds are created and attached to those inbounds; items with an empty inboundIds list are restored as unattached client records. An optional traffic object restores the usage counters, only for clients this import creates. Existing emails are never overwritten — they are returned in skipped, and their live counters are left untouched. Triggers a single Xray restart at the end if any target inbound was running; a failure while restoring counters still reports success=false after the clients were created.",
"operationId": "post_panel_api_clients_import", "operationId": "post_panel_api_clients_import",
"requestBody": { "requestBody": {
"required": true, "required": true,
@@ -10145,6 +10750,7 @@
"resetCount": 0, "resetCount": 0,
"resetDay": 0, "resetDay": 0,
"resetMax": 0, "resetMax": 0,
"resetWeekday": 0,
"subId": "i7tvdpeffi0hvvf1", "subId": "i7tvdpeffi0hvvf1",
"total": 10737418240, "total": 10737418240,
"up": 1048576, "up": 1048576,
@@ -11268,6 +11874,7 @@
"alpn": [ "alpn": [
"" ""
], ],
"cipherSuites": "",
"echConfigList": "", "echConfigList": "",
"excludeFromSubTypes": [ "excludeFromSubTypes": [
"" ""
@@ -11362,6 +11969,7 @@
"alpn": [ "alpn": [
"" ""
], ],
"cipherSuites": "",
"echConfigList": "", "echConfigList": "",
"excludeFromSubTypes": [ "excludeFromSubTypes": [
"" ""
@@ -11459,6 +12067,7 @@
"alpn": [ "alpn": [
"" ""
], ],
"cipherSuites": "",
"echConfigList": "", "echConfigList": "",
"excludeFromSubTypes": [ "excludeFromSubTypes": [
"" ""
@@ -11609,6 +12218,7 @@
"alpn": [ "alpn": [
"" ""
], ],
"cipherSuites": "",
"createdAt": 0, "createdAt": 0,
"echConfigList": "", "echConfigList": "",
"excludeFromSubTypes": [ "excludeFromSubTypes": [
@@ -11730,6 +12340,7 @@
"alpn": [ "alpn": [
"" ""
], ],
"cipherSuites": "",
"createdAt": 0, "createdAt": 0,
"echConfigList": "", "echConfigList": "",
"excludeFromSubTypes": [ "excludeFromSubTypes": [
@@ -11981,6 +12592,7 @@
"alpn": [ "alpn": [
"" ""
], ],
"cipherSuites": "",
"createdAt": 0, "createdAt": 0,
"echConfigList": "", "echConfigList": "",
"excludeFromSubTypes": [ "excludeFromSubTypes": [
@@ -15512,6 +16124,7 @@
"resetCount": 0, "resetCount": 0,
"resetDay": 0, "resetDay": 0,
"resetMax": 0, "resetMax": 0,
"resetWeekday": 0,
"subId": "i7tvdpeffi0hvvf1", "subId": "i7tvdpeffi0hvvf1",
"total": 10737418240, "total": 10737418240,
"up": 1048576, "up": 1048576,
@@ -15594,6 +16207,7 @@
"resetCount": 0, "resetCount": 0,
"resetDay": 0, "resetDay": 0,
"resetMax": 0, "resetMax": 0,
"resetWeekday": 0,
"subId": "i7tvdpeffi0hvvf1", "subId": "i7tvdpeffi0hvvf1",
"total": 10737418240, "total": 10737418240,
"up": 1048576, "up": 1048576,
@@ -15640,6 +16254,7 @@
"resetCount": 0, "resetCount": 0,
"resetDay": 0, "resetDay": 0,
"resetMax": 0, "resetMax": 0,
"resetWeekday": 0,
"subId": "i7tvdpeffi0hvvf1", "subId": "i7tvdpeffi0hvvf1",
"total": 10737418240, "total": 10737418240,
"up": 1048576, "up": 1048576,
@@ -15649,6 +16264,7 @@
"disableFlow": false, "disableFlow": false,
"down": 0, "down": 0,
"enable": true, "enable": true,
"excludeFromSub": false,
"expiryTime": 0, "expiryTime": 0,
"fallbackParent": null, "fallbackParent": null,
"id": 1, "id": 1,
+3 -1
View File
@@ -26,7 +26,9 @@ export const withTheme: Decorator = (Story, context) => {
document.documentElement.removeAttribute('data-theme'); document.documentElement.removeAttribute('data-theme');
}, [dark]); }, [dark]);
return ( return (
<ConfigProvider theme={buildAntdThemeConfig(dark, false)}> // The click wave outlives its story and re-renders from a ResizeObserver
// inside the next story's act(), tripping React's act-environment warning.
<ConfigProvider theme={buildAntdThemeConfig(dark, false)} wave={{ disabled: true }}>
<div style={{ padding: 24, minWidth: 320 }}> <div style={{ padding: 24, minWidth: 320 }}>
<Story /> <Story />
</div> </div>
+1164 -830
View File
File diff suppressed because it is too large Load Diff
+18 -18
View File
@@ -5,8 +5,8 @@
"type": "module", "type": "module",
"description": "3x-ui panel frontend (React 19 + Ant Design 6 + Vite 8).", "description": "3x-ui panel frontend (React 19 + Ant Design 6 + Vite 8).",
"engines": { "engines": {
"node": ">=24.0.0", "node": ">=26.0.0",
"npm": ">=10.0.0" "npm": ">=11.0.0"
}, },
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
@@ -39,9 +39,9 @@
"@codemirror/theme-one-dark": "^6.1.3", "@codemirror/theme-one-dark": "^6.1.3",
"@hookform/resolvers": "^5.9.1", "@hookform/resolvers": "^5.9.1",
"@noble/hashes": "^2.4.0", "@noble/hashes": "^2.4.0",
"@tanstack/react-query": "^5.102.8", "@tanstack/react-query": "^5.103.2",
"@tanstack/react-query-devtools": "^5.102.8", "@tanstack/react-query-devtools": "^5.103.2",
"antd": "^6.6.4", "antd": "^6.6.5",
"codemirror": "^6.0.2", "codemirror": "^6.0.2",
"dayjs": "^1.11.23", "dayjs": "^1.11.23",
"i18next": "^26.4.2", "i18next": "^26.4.2",
@@ -50,9 +50,9 @@
"react": "^19.3.0", "react": "^19.3.0",
"react-dom": "^19.3.0", "react-dom": "^19.3.0",
"react-hook-form": "^7.88.0", "react-hook-form": "^7.88.0",
"react-i18next": "^17.0.14", "react-i18next": "^17.0.15",
"react-router": "^8.3.1", "react-router": "^8.4.0",
"swagger-ui-react": "^5.32.15", "swagger-ui-react": "^5.33.0",
"uplot": "^1.6.32", "uplot": "^1.6.32",
"zod": "^4.6.5" "zod": "^4.6.5"
}, },
@@ -67,20 +67,20 @@
"@types/react-dom": "^19.3.0", "@types/react-dom": "^19.3.0",
"@types/swagger-ui-react": "^5.18.0", "@types/swagger-ui-react": "^5.18.0",
"@vitejs/plugin-react": "^6.1.1", "@vitejs/plugin-react": "^6.1.1",
"@vitest/browser-playwright": "5.0.0", "@vitest/browser-playwright": "5.0.2",
"@vitest/coverage-v8": "^5.0.0", "@vitest/coverage-v8": "^5.0.2",
"husky": "^9.1.7", "husky": "^9.1.7",
"jsdom": "^30.0.1", "jsdom": "^30.1.1",
"lint-staged": "^17.5.1", "lint-staged": "^17.5.1",
"msw": "^2.15.0", "msw": "^2.15.0",
"oxfmt": "0.68.0", "oxfmt": "0.70.0",
"oxlint": "1.83.0", "oxlint": "1.85.0",
"oxlint-tsgolint": "^7.0.2001", "oxlint-tsgolint": "^7.0.2003",
"playwright": "^1.63.0", "playwright": "^1.63.0",
"storybook": "^10.6.0", "storybook": "^10.6.0",
"typescript": "7.0.2", "typescript": "7.0.2",
"vite": "8.3.0", "vite": "8.3.1",
"vitest": "^5.0.0" "vitest": "^5.0.2"
}, },
"overrides": { "overrides": {
"dompurify": "^3.4.11", "dompurify": "^3.4.11",
@@ -98,8 +98,8 @@
}, },
"@storybook/addon-vitest": { "@storybook/addon-vitest": {
"vitest": "^5.0.0", "vitest": "^5.0.0",
"@vitest/browser-playwright": "5.0.0", "@vitest/browser-playwright": "^5.0.0",
"@vitest/browser": "5.0.0" "@vitest/browser": "^5.0.0"
} }
}, },
"allowScripts": { "allowScripts": {
+621 -5
View File
@@ -69,6 +69,9 @@
"minimum": 0, "minimum": 0,
"type": "integer" "type": "integer"
}, },
"externalSubUserAgent": {
"type": "string"
},
"externalTrafficInformEnable": { "externalTrafficInformEnable": {
"type": "boolean" "type": "boolean"
}, },
@@ -288,6 +291,9 @@
"subHappFallbackUrl": { "subHappFallbackUrl": {
"type": "string" "type": "string"
}, },
"subHappLocalProxyAuth": {
"type": "string"
},
"subHappNewUrl": { "subHappNewUrl": {
"type": "string" "type": "string"
}, },
@@ -336,12 +342,97 @@
"subHideSettings": { "subHideSettings": {
"type": "boolean" "type": "boolean"
}, },
"subIncyAnnounceUrl": {
"type": "string"
},
"subIncyAppAutoDetect": {
"description": "Incy client customization settings (app-management). A \"\" value omits\nthe header so the subscriber's own app setting is left alone.",
"type": "boolean"
},
"subIncyBannerBgColor": {
"type": "string"
},
"subIncyBannerButtonColor": {
"type": "string"
},
"subIncyBannerButtonText": {
"type": "string"
},
"subIncyBannerButtonUrl": {
"type": "string"
},
"subIncyBannerText": {
"type": "string"
},
"subIncyEnableRouting": { "subIncyEnableRouting": {
"type": "boolean" "type": "boolean"
}, },
"subIncyFragmentInterval": {
"type": "string"
},
"subIncyFragmentLength": {
"type": "string"
},
"subIncyFragmentPackets": {
"type": "string"
},
"subIncyFragmentationEnable": {
"type": "string"
},
"subIncyHideCheck": {
"type": "string"
},
"subIncyHideUrl": {
"type": "string"
},
"subIncyNoLimitEnabled": {
"type": "string"
},
"subIncyNoisesDelay": {
"type": "string"
},
"subIncyNoisesEnable": {
"type": "string"
},
"subIncyNoisesPacket": {
"type": "string"
},
"subIncyNoisesType": {
"type": "string"
},
"subIncyPerAppEnable": {
"type": "string"
},
"subIncyPerAppList": {
"type": "string"
},
"subIncyPerAppMode": {
"type": "string"
},
"subIncyPremiumUrl": {
"type": "string"
},
"subIncyProfileDescription": {
"type": "string"
},
"subIncyResolveDnsDomain": {
"type": "string"
},
"subIncyResolveDnsIp": {
"type": "string"
},
"subIncyResolveEnable": {
"type": "string"
},
"subIncyRoutingRules": { "subIncyRoutingRules": {
"type": "string" "type": "string"
}, },
"subIncySortOrder": {
"type": "string"
},
"subIncySupportEmail": {
"type": "string"
},
"subInfoNodeEnable": { "subInfoNodeEnable": {
"type": "boolean" "type": "boolean"
}, },
@@ -519,6 +610,7 @@
"discordMemory", "discordMemory",
"discordRunTime", "discordRunTime",
"expireDiff", "expireDiff",
"externalSubUserAgent",
"externalTrafficInformEnable", "externalTrafficInformEnable",
"externalTrafficInformURI", "externalTrafficInformURI",
"happLinkEnable", "happLinkEnable",
@@ -586,6 +678,7 @@
"subHappExcludeApns", "subHappExcludeApns",
"subHappExcludeRoutes", "subHappExcludeRoutes",
"subHappFallbackUrl", "subHappFallbackUrl",
"subHappLocalProxyAuth",
"subHappNewUrl", "subHappNewUrl",
"subHappNoLimit", "subHappNoLimit",
"subHappNotificationExpire", "subHappNotificationExpire",
@@ -602,8 +695,36 @@
"subHappTunMode", "subHappTunMode",
"subHappTunType", "subHappTunType",
"subHideSettings", "subHideSettings",
"subIncyAnnounceUrl",
"subIncyAppAutoDetect",
"subIncyBannerBgColor",
"subIncyBannerButtonColor",
"subIncyBannerButtonText",
"subIncyBannerButtonUrl",
"subIncyBannerText",
"subIncyEnableRouting", "subIncyEnableRouting",
"subIncyFragmentInterval",
"subIncyFragmentLength",
"subIncyFragmentPackets",
"subIncyFragmentationEnable",
"subIncyHideCheck",
"subIncyHideUrl",
"subIncyNoLimitEnabled",
"subIncyNoisesDelay",
"subIncyNoisesEnable",
"subIncyNoisesPacket",
"subIncyNoisesType",
"subIncyPerAppEnable",
"subIncyPerAppList",
"subIncyPerAppMode",
"subIncyPremiumUrl",
"subIncyProfileDescription",
"subIncyResolveDnsDomain",
"subIncyResolveDnsIp",
"subIncyResolveEnable",
"subIncyRoutingRules", "subIncyRoutingRules",
"subIncySortOrder",
"subIncySupportEmail",
"subInfoNodeEnable", "subInfoNodeEnable",
"subJsonAlwaysArray", "subJsonAlwaysArray",
"subJsonAutoDetect", "subJsonAutoDetect",
@@ -700,6 +821,9 @@
"minimum": 0, "minimum": 0,
"type": "integer" "type": "integer"
}, },
"externalSubUserAgent": {
"type": "string"
},
"externalTrafficInformEnable": { "externalTrafficInformEnable": {
"type": "boolean" "type": "boolean"
}, },
@@ -943,6 +1067,9 @@
"subHappFallbackUrl": { "subHappFallbackUrl": {
"type": "string" "type": "string"
}, },
"subHappLocalProxyAuth": {
"type": "string"
},
"subHappNewUrl": { "subHappNewUrl": {
"type": "string" "type": "string"
}, },
@@ -991,12 +1118,97 @@
"subHideSettings": { "subHideSettings": {
"type": "boolean" "type": "boolean"
}, },
"subIncyAnnounceUrl": {
"type": "string"
},
"subIncyAppAutoDetect": {
"description": "Incy client customization settings (app-management). A \"\" value omits\nthe header so the subscriber's own app setting is left alone.",
"type": "boolean"
},
"subIncyBannerBgColor": {
"type": "string"
},
"subIncyBannerButtonColor": {
"type": "string"
},
"subIncyBannerButtonText": {
"type": "string"
},
"subIncyBannerButtonUrl": {
"type": "string"
},
"subIncyBannerText": {
"type": "string"
},
"subIncyEnableRouting": { "subIncyEnableRouting": {
"type": "boolean" "type": "boolean"
}, },
"subIncyFragmentInterval": {
"type": "string"
},
"subIncyFragmentLength": {
"type": "string"
},
"subIncyFragmentPackets": {
"type": "string"
},
"subIncyFragmentationEnable": {
"type": "string"
},
"subIncyHideCheck": {
"type": "string"
},
"subIncyHideUrl": {
"type": "string"
},
"subIncyNoLimitEnabled": {
"type": "string"
},
"subIncyNoisesDelay": {
"type": "string"
},
"subIncyNoisesEnable": {
"type": "string"
},
"subIncyNoisesPacket": {
"type": "string"
},
"subIncyNoisesType": {
"type": "string"
},
"subIncyPerAppEnable": {
"type": "string"
},
"subIncyPerAppList": {
"type": "string"
},
"subIncyPerAppMode": {
"type": "string"
},
"subIncyPremiumUrl": {
"type": "string"
},
"subIncyProfileDescription": {
"type": "string"
},
"subIncyResolveDnsDomain": {
"type": "string"
},
"subIncyResolveDnsIp": {
"type": "string"
},
"subIncyResolveEnable": {
"type": "string"
},
"subIncyRoutingRules": { "subIncyRoutingRules": {
"type": "string" "type": "string"
}, },
"subIncySortOrder": {
"type": "string"
},
"subIncySupportEmail": {
"type": "string"
},
"subInfoNodeEnable": { "subInfoNodeEnable": {
"type": "boolean" "type": "boolean"
}, },
@@ -1174,6 +1386,7 @@
"discordMemory", "discordMemory",
"discordRunTime", "discordRunTime",
"expireDiff", "expireDiff",
"externalSubUserAgent",
"externalTrafficInformEnable", "externalTrafficInformEnable",
"externalTrafficInformURI", "externalTrafficInformURI",
"happLinkEnable", "happLinkEnable",
@@ -1249,6 +1462,7 @@
"subHappExcludeApns", "subHappExcludeApns",
"subHappExcludeRoutes", "subHappExcludeRoutes",
"subHappFallbackUrl", "subHappFallbackUrl",
"subHappLocalProxyAuth",
"subHappNewUrl", "subHappNewUrl",
"subHappNoLimit", "subHappNoLimit",
"subHappNotificationExpire", "subHappNotificationExpire",
@@ -1265,8 +1479,36 @@
"subHappTunMode", "subHappTunMode",
"subHappTunType", "subHappTunType",
"subHideSettings", "subHideSettings",
"subIncyAnnounceUrl",
"subIncyAppAutoDetect",
"subIncyBannerBgColor",
"subIncyBannerButtonColor",
"subIncyBannerButtonText",
"subIncyBannerButtonUrl",
"subIncyBannerText",
"subIncyEnableRouting", "subIncyEnableRouting",
"subIncyFragmentInterval",
"subIncyFragmentLength",
"subIncyFragmentPackets",
"subIncyFragmentationEnable",
"subIncyHideCheck",
"subIncyHideUrl",
"subIncyNoLimitEnabled",
"subIncyNoisesDelay",
"subIncyNoisesEnable",
"subIncyNoisesPacket",
"subIncyNoisesType",
"subIncyPerAppEnable",
"subIncyPerAppList",
"subIncyPerAppMode",
"subIncyPremiumUrl",
"subIncyProfileDescription",
"subIncyResolveDnsDomain",
"subIncyResolveDnsIp",
"subIncyResolveEnable",
"subIncyRoutingRules", "subIncyRoutingRules",
"subIncySortOrder",
"subIncySupportEmail",
"subInfoNodeEnable", "subInfoNodeEnable",
"subJsonAlwaysArray", "subJsonAlwaysArray",
"subJsonAutoDetect", "subJsonAutoDetect",
@@ -1523,13 +1765,17 @@
"type": "integer" "type": "integer"
}, },
"resetDay": { "resetDay": {
"description": "Calendar renewal day 1-31, 0 = interval mode", "description": "Calendar renewal day 1-31, 0 disables monthly renewal",
"type": "integer" "type": "integer"
}, },
"resetMax": { "resetMax": {
"description": "Max auto-renew count, 0 = unlimited", "description": "Max auto-renew count, 0 = unlimited",
"type": "integer" "type": "integer"
}, },
"resetWeekday": {
"description": "Calendar weekday 1-7 (Mon-Sun), 0 disables weekly renewal",
"type": "integer"
},
"reverse": { "reverse": {
"allOf": [ "allOf": [
{ {
@@ -1592,6 +1838,7 @@
"reset", "reset",
"resetDay", "resetDay",
"resetMax", "resetMax",
"resetWeekday",
"security", "security",
"subId", "subId",
"tgId", "tgId",
@@ -1743,6 +1990,9 @@
"resetMax": { "resetMax": {
"type": "integer" "type": "integer"
}, },
"resetWeekday": {
"type": "integer"
},
"reverse": {}, "reverse": {},
"secret": { "secret": {
"type": "string" "type": "string"
@@ -1798,6 +2048,7 @@
"reset", "reset",
"resetDay", "resetDay",
"resetMax", "resetMax",
"resetWeekday",
"reverse", "reverse",
"secret", "secret",
"security", "security",
@@ -1811,6 +2062,97 @@
], ],
"type": "object" "type": "object"
}, },
"ClientRenewalPreview": {
"properties": {
"canRenew": {
"example": true,
"type": "boolean"
},
"delayedStart": {
"example": false,
"type": "boolean"
},
"nextExpiry": {
"example": "2030-02-01T00:00:00Z",
"type": "string"
},
"renewAt": {
"example": "2030-01-01T00:00:00Z",
"type": "string"
},
"renewals": {
"example": 1,
"type": "integer"
},
"suggestedExpiry": {
"example": "2030-01-01T00:00:00Z",
"type": "string"
},
"suggestedExpiryTime": {
"example": 1893456000000,
"format": "int64",
"type": "integer"
},
"timeZone": {
"example": "UTC",
"type": "string"
},
"validThrough": {
"example": "2029-12-31T23:59:59Z",
"type": "string"
}
},
"required": [
"canRenew",
"delayedStart",
"nextExpiry",
"renewAt",
"renewals",
"suggestedExpiry",
"suggestedExpiryTime",
"timeZone",
"validThrough"
],
"type": "object"
},
"ClientRenewalPreviewRequest": {
"properties": {
"expiryTime": {
"example": 1893456000000,
"format": "int64",
"type": "integer"
},
"reset": {
"example": 0,
"type": "integer"
},
"resetCount": {
"example": 0,
"type": "integer"
},
"resetDay": {
"example": 1,
"type": "integer"
},
"resetMax": {
"example": 0,
"type": "integer"
},
"resetWeekday": {
"example": 0,
"type": "integer"
}
},
"required": [
"expiryTime",
"reset",
"resetCount",
"resetDay",
"resetMax",
"resetWeekday"
],
"type": "object"
},
"ClientReverse": { "ClientReverse": {
"properties": { "properties": {
"tag": { "tag": {
@@ -1881,6 +2223,10 @@
"example": 0, "example": 0,
"type": "integer" "type": "integer"
}, },
"resetWeekday": {
"example": 0,
"type": "integer"
},
"subId": { "subId": {
"example": "abcd1234", "example": "abcd1234",
"type": "string" "type": "string"
@@ -1915,6 +2261,7 @@
"reset", "reset",
"resetDay", "resetDay",
"resetMax", "resetMax",
"resetWeekday",
"subId", "subId",
"totalGB", "totalGB",
"updatedAt" "updatedAt"
@@ -1970,7 +2317,7 @@
"type": "integer" "type": "integer"
}, },
"resetDay": { "resetDay": {
"description": "ResetDay renews on that day of each calendar month instead of every\nReset days; 0 keeps the interval behaviour.", "description": "ResetDay renews on that day of each calendar month instead of every\nReset days; 0 disables monthly renewal.",
"example": 0, "example": 0,
"type": "integer" "type": "integer"
}, },
@@ -1979,6 +2326,11 @@
"example": 0, "example": 0,
"type": "integer" "type": "integer"
}, },
"resetWeekday": {
"description": "ResetWeekday renews weekly at panel-local midnight: 1 Monday through 7 Sunday.",
"example": 0,
"type": "integer"
},
"subId": { "subId": {
"example": "i7tvdpeffi0hvvf1", "example": "i7tvdpeffi0hvvf1",
"type": "string" "type": "string"
@@ -2011,6 +2363,7 @@
"resetCount", "resetCount",
"resetDay", "resetDay",
"resetMax", "resetMax",
"resetWeekday",
"subId", "subId",
"total", "total",
"up", "up",
@@ -2301,6 +2654,9 @@
}, },
"type": "array" "type": "array"
}, },
"cipherSuites": {
"type": "string"
},
"createdAt": { "createdAt": {
"format": "int64", "format": "int64",
"type": "integer" "type": "integer"
@@ -2434,6 +2790,7 @@
"address", "address",
"allowInsecure", "allowInsecure",
"alpn", "alpn",
"cipherSuites",
"createdAt", "createdAt",
"echConfigList", "echConfigList",
"excludeFromSubTypes", "excludeFromSubTypes",
@@ -2478,6 +2835,9 @@
}, },
"type": "array" "type": "array"
}, },
"cipherSuites": {
"type": "string"
},
"echConfigList": { "echConfigList": {
"type": "string" "type": "string"
}, },
@@ -2604,6 +2964,7 @@
"required": [ "required": [
"allowInsecure", "allowInsecure",
"alpn", "alpn",
"cipherSuites",
"echConfigList", "echConfigList",
"excludeFromSubTypes", "excludeFromSubTypes",
"finalMask", "finalMask",
@@ -2693,6 +3054,11 @@
"example": true, "example": true,
"type": "boolean" "type": "boolean"
}, },
"excludeFromSub": {
"description": "Whether to omit this inbound from subscription output while keeping it operational",
"example": false,
"type": "boolean"
},
"expiryTime": { "expiryTime": {
"description": "Expiration timestamp", "description": "Expiration timestamp",
"format": "int64", "format": "int64",
@@ -2816,6 +3182,7 @@
"disableFlow", "disableFlow",
"down", "down",
"enable", "enable",
"excludeFromSub",
"expiryTime", "expiryTime",
"id", "id",
"lastTrafficResetTime", "lastTrafficResetTime",
@@ -4127,6 +4494,90 @@
], ],
"type": "object" "type": "object"
}, },
"Sponsor": {
"description": "Sponsor is one paid placement published in the repo's sponsors.json.",
"properties": {
"enable": {
"example": true,
"nullable": true,
"type": "boolean"
},
"from": {
"example": "2026-10-01T00:00:00Z",
"format": "date-time",
"nullable": true,
"type": "string"
},
"id": {
"example": "acme-2026-10",
"type": "string"
},
"link": {
"example": "https://acme.example/?utm_source=3x-ui",
"type": "string"
},
"logo": {
"example": "/sponsors/logo/acme.png",
"type": "string"
},
"name": {
"example": "Acme VPS",
"type": "string"
},
"slots": {
"items": {
"type": "string"
},
"type": "array"
},
"text": {
"additionalProperties": {
"type": "string"
},
"type": "object"
},
"title": {
"additionalProperties": {
"type": "string"
},
"type": "object"
},
"until": {
"example": "2026-11-01T00:00:00Z",
"format": "date-time",
"type": "string"
}
},
"required": [
"id",
"link",
"name",
"slots",
"text",
"title",
"until"
],
"type": "object"
},
"SponsorList": {
"description": "SponsorList is the active sponsor set plus the contact link for new sponsors.",
"properties": {
"contact": {
"example": "https://t.me/example",
"type": "string"
},
"sponsors": {
"items": {
"$ref": "#/components/schemas/Sponsor"
},
"type": "array"
}
},
"required": [
"sponsors"
],
"type": "object"
},
"SubBalancer": { "SubBalancer": {
"description": "SubBalancer is one extra JSON-subscription config document whose members are\nthe selected inbounds' proxy outbounds. SortOrder shares SubSortIndex semantics.", "description": "SubBalancer is one extra JSON-subscription config document whose members are\nthe selected inbounds' proxy outbounds. SortOrder shares SubSortIndex semantics.",
"properties": { "properties": {
@@ -4579,6 +5030,60 @@
} }
} }
}, },
"/sponsors": {
"get": {
"tags": [
"Authentication"
],
"summary": "Public. Active paid sponsor placements read from the project sponsors.json (cached for 1h); entries outside their from/until window are dropped. Logos are proxied by the panel at /sponsors/logo/{name}. Used by the login page and panel sponsor slots.",
"operationId": "get_sponsors",
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {
"$ref": "#/components/schemas/SponsorList"
}
}
},
"example": {
"success": true,
"obj": {
"contact": "https://t.me/example",
"sponsors": [
{
"enable": true,
"from": "2026-10-01T00:00:00Z",
"id": "acme-2026-10",
"link": "https://acme.example/?utm_source=3x-ui",
"logo": "/sponsors/logo/acme.png",
"name": "Acme VPS",
"slots": [
""
],
"text": {},
"title": {},
"until": "2026-11-01T00:00:00Z"
}
]
}
}
}
}
}
}
}
},
"/getTwoFactorEnable": { "/getTwoFactorEnable": {
"post": { "post": {
"tags": [ "tags": [
@@ -4660,6 +5165,7 @@
"resetCount": 0, "resetCount": 0,
"resetDay": 0, "resetDay": 0,
"resetMax": 0, "resetMax": 0,
"resetWeekday": 0,
"subId": "i7tvdpeffi0hvvf1", "subId": "i7tvdpeffi0hvvf1",
"total": 10737418240, "total": 10737418240,
"up": 1048576, "up": 1048576,
@@ -4669,6 +5175,7 @@
"disableFlow": false, "disableFlow": false,
"down": 0, "down": 0,
"enable": true, "enable": true,
"excludeFromSub": false,
"expiryTime": 0, "expiryTime": 0,
"fallbackParent": null, "fallbackParent": null,
"id": 1, "id": 1,
@@ -7894,6 +8401,7 @@
"reset": 0, "reset": 0,
"resetDay": 0, "resetDay": 0,
"resetMax": 0, "resetMax": 0,
"resetWeekday": 0,
"subId": "abcd1234", "subId": "abcd1234",
"totalGB": 53687091200, "totalGB": 53687091200,
"traffic": null, "traffic": null,
@@ -8086,6 +8594,97 @@
} }
} }
}, },
"/panel/api/clients/renewalPreview": {
"post": {
"tags": [
"Clients"
],
"summary": "Preview client auto-renewal dates without saving or resetting anything.",
"operationId": "post_panel_api_clients_renewalPreview",
"description": "Uses the same calendar and catch-up calculation as auto-renew in the panel timezone. resetWeekday is 1 (Monday) to 7 (Sunday), 0 disables weekly mode; it cannot be combined with positive reset or resetDay. Existing resetDay takes precedence over reset. With expiryTime=0, calendar modes suggest a first cutoff but do not activate renewal. Negative expiryTime waits for first-use activation. resetMax and resetCount simulate the existing per-period allowance limit; the preview is informational and does not reserve an allowance or guarantee node availability.",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"expiryTime": {
"type": "integer",
"description": "Current cutoff in Unix milliseconds; 0 unlimited, negative first-use duration."
},
"reset": {
"type": "integer",
"description": "Fixed interval in days; 0 disabled."
},
"resetDay": {
"type": "integer",
"description": "Monthly calendar day 1-31; 0 disabled."
},
"resetWeekday": {
"type": "integer",
"description": "Weekly calendar day 1-7 (Monday-Sunday); 0 disabled."
},
"resetMax": {
"type": "integer",
"description": "Maximum renewals; 0 unlimited."
},
"resetCount": {
"type": "integer",
"description": "Renewals already consumed; defaults to 0."
}
},
"required": [
"expiryTime",
"reset",
"resetDay",
"resetWeekday",
"resetMax",
"resetCount"
]
}
}
}
},
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {
"$ref": "#/components/schemas/ClientRenewalPreview"
}
}
},
"example": {
"success": true,
"obj": {
"canRenew": true,
"delayedStart": false,
"nextExpiry": "2030-02-01T00:00:00Z",
"renewAt": "2030-01-01T00:00:00Z",
"renewals": 1,
"suggestedExpiry": "2030-01-01T00:00:00Z",
"suggestedExpiryTime": 1893456000000,
"timeZone": "UTC",
"validThrough": "2029-12-31T23:59:59Z"
}
}
}
}
}
}
}
},
"/panel/api/clients/update/{email}": { "/panel/api/clients/update/{email}": {
"post": { "post": {
"tags": [ "tags": [
@@ -8545,7 +9144,7 @@
"tags": [ "tags": [
"Clients" "Clients"
], ],
"summary": "Return every client as a {client, inboundIds} array — the same shape /bulkCreate and /import accept — so the payload round-trips straight back through /import. Clients with no inbound attachment are included with an empty inboundIds list. The UI shows this in a CodeMirror viewer (copy / download); programmatic callers get the array in obj.", "summary": "Return every client as a {client, inboundIds, traffic} array — the shape /import accepts — so the payload round-trips straight back through /import. traffic carries the usage counters (up, down, resetCount, lastOnline, lastSubFetch) and is omitted for a client with no traffic row; the quota itself stays in client.totalGB. Clients with no inbound attachment are included with an empty inboundIds list. The UI shows this in a CodeMirror viewer (copy / download); programmatic callers get the array in obj.",
"operationId": "get_panel_api_clients_export", "operationId": "get_panel_api_clients_export",
"responses": { "responses": {
"200": { "200": {
@@ -8580,7 +9179,13 @@
"inboundIds": [ "inboundIds": [
7, 7,
9 9
] ],
"traffic": {
"up": 1048576,
"down": 2097152,
"resetCount": 0,
"lastOnline": 1735680000000
}
} }
] ]
} }
@@ -8595,7 +9200,7 @@
"tags": [ "tags": [
"Clients" "Clients"
], ],
"summary": "Import clients from a JSON body { \"data\": \"<json>\" }, where data is a string-encoded array produced by /export ([{client, inboundIds}]). Items with inboundIds are created and attached to those inbounds; items with an empty inboundIds list are restored as unattached client records. Existing emails are never overwritten — they are returned in skipped. Triggers a single Xray restart at the end if any target inbound was running.", "summary": "Import clients from a JSON body { \"data\": \"<json>\" }, where data is a string-encoded array produced by /export ([{client, inboundIds, traffic}]). Items with inboundIds are created and attached to those inbounds; items with an empty inboundIds list are restored as unattached client records. An optional traffic object restores the usage counters, only for clients this import creates. Existing emails are never overwritten — they are returned in skipped, and their live counters are left untouched. Triggers a single Xray restart at the end if any target inbound was running; a failure while restoring counters still reports success=false after the clients were created.",
"operationId": "post_panel_api_clients_import", "operationId": "post_panel_api_clients_import",
"requestBody": { "requestBody": {
"required": true, "required": true,
@@ -10145,6 +10750,7 @@
"resetCount": 0, "resetCount": 0,
"resetDay": 0, "resetDay": 0,
"resetMax": 0, "resetMax": 0,
"resetWeekday": 0,
"subId": "i7tvdpeffi0hvvf1", "subId": "i7tvdpeffi0hvvf1",
"total": 10737418240, "total": 10737418240,
"up": 1048576, "up": 1048576,
@@ -11268,6 +11874,7 @@
"alpn": [ "alpn": [
"" ""
], ],
"cipherSuites": "",
"echConfigList": "", "echConfigList": "",
"excludeFromSubTypes": [ "excludeFromSubTypes": [
"" ""
@@ -11362,6 +11969,7 @@
"alpn": [ "alpn": [
"" ""
], ],
"cipherSuites": "",
"echConfigList": "", "echConfigList": "",
"excludeFromSubTypes": [ "excludeFromSubTypes": [
"" ""
@@ -11459,6 +12067,7 @@
"alpn": [ "alpn": [
"" ""
], ],
"cipherSuites": "",
"echConfigList": "", "echConfigList": "",
"excludeFromSubTypes": [ "excludeFromSubTypes": [
"" ""
@@ -11609,6 +12218,7 @@
"alpn": [ "alpn": [
"" ""
], ],
"cipherSuites": "",
"createdAt": 0, "createdAt": 0,
"echConfigList": "", "echConfigList": "",
"excludeFromSubTypes": [ "excludeFromSubTypes": [
@@ -11730,6 +12340,7 @@
"alpn": [ "alpn": [
"" ""
], ],
"cipherSuites": "",
"createdAt": 0, "createdAt": 0,
"echConfigList": "", "echConfigList": "",
"excludeFromSubTypes": [ "excludeFromSubTypes": [
@@ -11981,6 +12592,7 @@
"alpn": [ "alpn": [
"" ""
], ],
"cipherSuites": "",
"createdAt": 0, "createdAt": 0,
"echConfigList": "", "echConfigList": "",
"excludeFromSubTypes": [ "excludeFromSubTypes": [
@@ -15512,6 +16124,7 @@
"resetCount": 0, "resetCount": 0,
"resetDay": 0, "resetDay": 0,
"resetMax": 0, "resetMax": 0,
"resetWeekday": 0,
"subId": "i7tvdpeffi0hvvf1", "subId": "i7tvdpeffi0hvvf1",
"total": 10737418240, "total": 10737418240,
"up": 1048576, "up": 1048576,
@@ -15594,6 +16207,7 @@
"resetCount": 0, "resetCount": 0,
"resetDay": 0, "resetDay": 0,
"resetMax": 0, "resetMax": 0,
"resetWeekday": 0,
"subId": "i7tvdpeffi0hvvf1", "subId": "i7tvdpeffi0hvvf1",
"total": 10737418240, "total": 10737418240,
"up": 1048576, "up": 1048576,
@@ -15640,6 +16254,7 @@
"resetCount": 0, "resetCount": 0,
"resetDay": 0, "resetDay": 0,
"resetMax": 0, "resetMax": 0,
"resetWeekday": 0,
"subId": "i7tvdpeffi0hvvf1", "subId": "i7tvdpeffi0hvvf1",
"total": 10737418240, "total": 10737418240,
"up": 1048576, "up": 1048576,
@@ -15649,6 +16264,7 @@
"disableFlow": false, "disableFlow": false,
"down": 0, "down": 0,
"enable": true, "enable": true,
"excludeFromSub": false,
"expiryTime": 0, "expiryTime": 0,
"fallbackParent": null, "fallbackParent": null,
"id": 1, "id": 1,
+4
View File
@@ -196,6 +196,10 @@ export async function httpRequest(
return { ok: true, status: res.status, statusText: res.statusText, data: parsed }; return { ok: true, status: res.status, statusText: res.statusText, data: parsed };
} }
export function withBasePath(path: string): string {
return basePathPrefix + path;
}
export function setupHttp(): void { export function setupHttp(): void {
let basePath: string | null | undefined = window.X_UI_BASE_PATH; let basePath: string | null | undefined = window.X_UI_BASE_PATH;
if (!basePath) { if (!basePath) {
@@ -0,0 +1,23 @@
import { useQuery } from '@tanstack/react-query';
import { HttpUtil } from '@/utils';
import { keys } from '@/api/queryKeys';
import type { SponsorList } from '@/generated/types';
const EMPTY: SponsorList = { sponsors: [] };
async function fetchSponsors(): Promise<SponsorList> {
const msg = await HttpUtil.get<SponsorList>('/sponsors', undefined, { silent: true });
if (!msg?.success || !msg.obj) return EMPTY;
return { contact: msg.obj.contact, sponsors: msg.obj.sponsors ?? [] };
}
export function useSponsorsQuery() {
const query = useQuery({
queryKey: keys.sponsors(),
queryFn: fetchSponsors,
staleTime: 60 * 60 * 1000,
retry: false,
});
return { data: query.data ?? EMPTY, fetched: query.isFetched };
}
+1
View File
@@ -1,4 +1,5 @@
export const keys = { export const keys = {
sponsors: () => ['sponsors'] as const,
server: { server: {
status: () => ['server', 'status'] as const, status: () => ['server', 'status'] as const,
fail2banStatus: () => ['server', 'fail2banStatus'] as const, fail2banStatus: () => ['server', 'fail2banStatus'] as const,
@@ -13,6 +13,7 @@ import {
ClusterOutlined, ClusterOutlined,
CodeOutlined, CodeOutlined,
CopyOutlined, CopyOutlined,
CrownOutlined,
DashboardOutlined, DashboardOutlined,
DatabaseOutlined, DatabaseOutlined,
DiscordOutlined, DiscordOutlined,
@@ -418,6 +419,12 @@ export default function CommandPalette() {
keywords: ['api', 'api docs', 'swagger', 'rest api', 'endpoints'], keywords: ['api', 'api docs', 'swagger', 'rest api', 'endpoints'],
icon: <ApiOutlined />, icon: <ApiOutlined />,
}, },
{
path: '/sponsors',
title: t('menu.sponsors'),
keywords: ['sponsors', 'sponsor', 'partners'],
icon: <CrownOutlined />,
},
]; ];
pages pages
@@ -0,0 +1,39 @@
import { Select } from 'antd';
import type { SelectProps } from 'antd';
import { TLS_CIPHER_OPTION } from '@/schemas/primitives';
const CIPHER_SUITE_OPTIONS = Object.values(TLS_CIPHER_OPTION).map((v) => ({ value: v, label: v }));
type CipherSuitesSelectProps = Omit<
SelectProps<string[]>,
'value' | 'onChange' | 'mode' | 'options'
> & {
// Injected by FormField:
value?: string;
onChange?: (value: string) => void;
};
// xray splits cipherSuites on ':' into a list, so the picker edits tags while
// the stored value stays the single colon-joined string xray reads.
export default function CipherSuitesSelect({
value = '',
onChange,
...rest
}: CipherSuitesSelectProps) {
const suites = value
.split(':')
.map((s) => s.trim())
.filter(Boolean);
return (
<Select
allowClear
tokenSeparators={[':', ',']}
{...rest}
mode="tags"
options={CIPHER_SUITE_OPTIONS}
value={suites}
onChange={(next) => onChange?.(next.join(':'))}
/>
);
}
+1
View File
@@ -3,6 +3,7 @@ export { default as JsonEditor } from './JsonEditor';
export { default as HeaderMapEditor } from './HeaderMapEditor'; export { default as HeaderMapEditor } from './HeaderMapEditor';
export { default as GoRegexInput, validateGoRegex } from './GoRegexInput'; export { default as GoRegexInput, validateGoRegex } from './GoRegexInput';
export { default as SelectAllClearButtons } from './SelectAllClearButtons'; export { default as SelectAllClearButtons } from './SelectAllClearButtons';
export { default as CipherSuitesSelect } from './CipherSuitesSelect';
export { default as RemarkTemplateField } from './RemarkTemplateField'; export { default as RemarkTemplateField } from './RemarkTemplateField';
export { default as RemarkVarPicker } from './RemarkVarPicker'; export { default as RemarkVarPicker } from './RemarkVarPicker';
export { default as CustomSockoptList } from '../../lib/xray/forms/transport/CustomSockoptList'; export { default as CustomSockoptList } from '../../lib/xray/forms/transport/CustomSockoptList';
@@ -24,6 +24,10 @@ import type { GeoCategory, GeoEntry, GeoFile, GeoKind } from '@/generated/types'
import './GeoBrowserModal.css'; import './GeoBrowserModal.css';
const ENTRY_PAGE_SIZE = 100; const ENTRY_PAGE_SIZE = 100;
// Attributes are dropped server-side, so kind:value repeats within real
// geosite categories; the page position is the only unique row key.
type GeoEntryRow = GeoEntry & { position: number };
const CATEGORY_SCROLL_HEIGHT = 438; const CATEGORY_SCROLL_HEIGHT = 438;
const ENTRY_FILTER_DELAY = 500; const ENTRY_FILTER_DELAY = 500;
@@ -224,7 +228,12 @@ export default function GeoBrowserModal({
[t], [t],
); );
const entryColumns: ColumnsType<GeoEntry> = useMemo( const entryRows: GeoEntryRow[] = useMemo(
() => (entriesQuery.data?.items ?? []).map((entry, position) => ({ ...entry, position })),
[entriesQuery.data],
);
const entryColumns: ColumnsType<GeoEntryRow> = useMemo(
() => [ () => [
{ {
dataIndex: 'kind', dataIndex: 'kind',
@@ -391,9 +400,9 @@ export default function GeoBrowserModal({
<Table <Table
size="small" size="small"
showHeader={false} showHeader={false}
rowKey={(entry, index) => `${entry.value}-${index}`} rowKey="position"
columns={entryColumns} columns={entryColumns}
dataSource={entriesQuery.data?.items ?? []} dataSource={entryRows}
loading={entriesQuery.isLoading} loading={entriesQuery.isLoading}
locale={{ locale={{
emptyText: entriesQuery.isError emptyText: entriesQuery.isError
@@ -0,0 +1,216 @@
.sponsor-card {
position: relative;
display: flex;
align-items: stretch;
min-width: 0;
border: 1px solid var(--ant-color-border-secondary);
border-radius: var(--ant-border-radius-lg, 8px);
background: var(--bg-card, var(--ant-color-fill-quaternary));
transition:
border-color 0.2s,
background 0.2s;
}
.sponsor-card:hover {
border-color: var(--ant-color-primary);
}
.sponsor-main {
display: flex;
flex: 1;
align-items: center;
gap: 12px;
min-width: 0;
padding: 12px 16px;
color: var(--ant-color-text);
text-decoration: none;
}
.sponsor-main:hover,
.sponsor-main:focus-visible {
color: var(--ant-color-text);
outline: none;
}
.sponsor-logo {
flex: 0 0 auto;
width: 40px;
height: 40px;
border-radius: 8px;
object-fit: contain;
background: var(--ant-color-bg-elevated);
}
.sponsor-logo-fallback {
display: inline-flex;
align-items: center;
justify-content: center;
font-weight: 600;
font-size: 18px;
color: var(--ant-color-primary);
background: var(--ant-color-primary-bg);
}
.sponsor-body {
display: flex;
flex: 1;
flex-direction: column;
gap: 2px;
min-width: 0;
}
.sponsor-head {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.sponsor-tag {
flex: 0 0 auto;
padding: 0 6px;
border: 1px solid var(--ant-color-border);
border-radius: 4px;
font-size: 11px;
line-height: 18px;
color: var(--ant-color-text-tertiary);
}
.sponsor-title {
overflow: hidden;
font-weight: 600;
white-space: nowrap;
text-overflow: ellipsis;
}
.sponsor-text {
font-size: 13px;
color: var(--ant-color-text-secondary);
}
.sponsor-visit {
flex: 0 0 auto;
font-size: 13px;
color: var(--ant-color-primary);
white-space: nowrap;
}
.sponsor-close {
flex: 0 0 auto;
align-self: flex-start;
width: 28px;
height: 28px;
margin: 6px 6px 0 0;
padding: 0;
border: none;
border-radius: 6px;
background: transparent;
color: var(--ant-color-text-tertiary);
cursor: pointer;
}
.sponsor-close:hover,
.sponsor-close:focus-visible {
color: var(--ant-color-text);
background: var(--ant-color-fill-tertiary);
outline: none;
}
[dir='rtl'] .sponsor-close {
margin: 6px 0 0 6px;
}
.sponsor-card-compact .sponsor-main {
gap: 10px;
padding: 8px 10px;
}
.sponsor-card-compact .sponsor-logo {
width: 32px;
height: 32px;
}
.sponsor-card-compact .sponsor-head {
flex-direction: column;
align-items: flex-start;
gap: 2px;
}
.sponsor-card-compact .sponsor-title {
display: -webkit-box;
max-width: 100%;
font-size: 13px;
white-space: normal;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
.sponsor-card-compact .sponsor-text {
display: -webkit-box;
overflow: hidden;
font-size: 12px;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
.sponsor-card-compact .sponsor-close {
width: 22px;
height: 22px;
margin: 4px 4px 0 0;
font-size: 11px;
}
.sponsor-card-card {
height: 100%;
}
.sponsor-card-card .sponsor-main {
flex-direction: column;
align-items: flex-start;
padding: 16px;
}
.sponsor-card-card .sponsor-logo {
width: 56px;
height: 56px;
}
.sponsor-card-card .sponsor-visit {
margin-top: auto;
}
.sponsor-card-icon {
justify-content: center;
padding: 6px;
border-color: transparent;
background: transparent;
}
.sponsor-card-icon .sponsor-logo {
width: 32px;
height: 32px;
}
@media (max-width: 576px) {
.sponsor-card-banner .sponsor-main {
flex-wrap: wrap;
padding: 10px 12px;
}
.sponsor-card-banner .sponsor-visit {
flex-basis: 100%;
padding-inline-start: 52px;
}
}
.sponsor-card-card {
transition:
border-color 0.2s,
transform 0.2s,
box-shadow 0.2s;
}
.sponsor-card-card:hover {
transform: translateY(-2px);
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
}
@@ -0,0 +1,73 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, within } from 'storybook/test';
import type { Sponsor } from '@/generated/types';
import SponsorCard from './SponsorCard';
const sponsor: Sponsor = {
id: 'acme-2026-10',
name: 'Acme VPS',
slots: ['dashboard', 'sidebar', 'page', 'login'],
until: '2099-01-01T00:00:00Z',
title: { en: 'Acme VPS — fast NVMe servers', fa: 'سرورهای سریع Acme' },
text: { en: 'Deploy 3X-UI in 60 seconds. 20% off for panel users.' },
link: 'https://acme.example/?utm_source=3x-ui',
};
const meta = {
title: 'Sponsor/SponsorCard',
component: SponsorCard,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'Paid sponsor placement fed by the project sponsors.json. Always labelled as a sponsor; links open in a new tab with rel="sponsored".',
},
},
},
argTypes: {
sponsor: { description: 'Sponsor entry from GET /sponsors.' },
variant: {
description: 'banner (dashboard), compact (sidebar/login) or card (Sponsors page).',
},
iconOnly: { description: 'Logo-only rendering for the collapsed sidebar rail.' },
onClose: { description: 'When set, shows a close button (temporary dismiss).' },
},
args: { sponsor },
} satisfies Meta<typeof SponsorCard>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Banner: Story = {
args: { variant: 'banner', onClose: () => {} },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await expect(canvas.getByText('Sponsor')).toBeInTheDocument();
await expect(canvas.getByRole('link')).toHaveAttribute('rel', 'noopener noreferrer sponsored');
},
};
export const Compact: Story = {
args: { variant: 'compact', onClose: () => {} },
render: (args) => (
<div style={{ width: 204 }}>
<SponsorCard {...args} />
</div>
),
};
export const Card: Story = {
args: { variant: 'card' },
render: (args) => (
<div style={{ width: 320 }}>
<SponsorCard {...args} />
</div>
),
};
export const IconOnly: Story = {
args: { iconOnly: true },
};
@@ -0,0 +1,101 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { CloseOutlined, ExportOutlined } from '@ant-design/icons';
import { withBasePath } from '@/api/http-init';
import type { Sponsor } from '@/generated/types';
import { pickLocale } from '@/lib/sponsors';
import './SponsorCard.css';
export type SponsorCardVariant = 'banner' | 'compact' | 'card';
export interface SponsorCardProps {
sponsor: Sponsor;
variant?: SponsorCardVariant;
iconOnly?: boolean;
onClose?: () => void;
}
function SponsorLogo({ sponsor }: { sponsor: Sponsor }) {
const [failedSrc, setFailedSrc] = useState('');
if (sponsor.logo && failedSrc !== sponsor.logo) {
return (
<img
className="sponsor-logo"
src={withBasePath(sponsor.logo)}
alt=""
loading="lazy"
onError={() => setFailedSrc(sponsor.logo ?? '')}
/>
);
}
return (
<span className="sponsor-logo sponsor-logo-fallback" aria-hidden="true">
{sponsor.name.slice(0, 1).toUpperCase()}
</span>
);
}
export default function SponsorCard({
sponsor,
variant = 'banner',
iconOnly = false,
onClose,
}: SponsorCardProps) {
const { t, i18n } = useTranslation();
const lang = i18n.resolvedLanguage || i18n.language || 'en';
const title = pickLocale(sponsor.title, lang) || sponsor.name;
const text = pickLocale(sponsor.text, lang);
const tag = t('pages.sponsors.tag');
if (iconOnly) {
return (
<a
className="sponsor-card sponsor-card-icon"
href={sponsor.link}
target="_blank"
rel="noopener noreferrer sponsored"
title={`${tag} · ${title}`}
aria-label={`${tag}: ${title}`}
>
<SponsorLogo sponsor={sponsor} />
</a>
);
}
return (
<div className={`sponsor-card sponsor-card-${variant}`}>
<a
className="sponsor-main"
href={sponsor.link}
target="_blank"
rel="noopener noreferrer sponsored"
>
<SponsorLogo sponsor={sponsor} />
<span className="sponsor-body" dir="auto">
<span className="sponsor-head">
<span className="sponsor-tag">{tag}</span>
<span className="sponsor-title">{title}</span>
</span>
{text && <span className="sponsor-text">{text}</span>}
</span>
{variant !== 'compact' && (
<span className="sponsor-visit">
{t('pages.sponsors.visit')} <ExportOutlined />
</span>
)}
</a>
{onClose && (
<button
type="button"
className="sponsor-close"
aria-label={t('close')}
title={t('close')}
onClick={onClose}
>
<CloseOutlined />
</button>
)}
</div>
);
}
@@ -0,0 +1,60 @@
import { useEffect, useState } from 'react';
import { useSponsorsQuery } from '@/api/queries/useSponsorsQuery';
import {
dismissSponsor,
isSponsorDismissed,
sponsorsForSlot,
type SponsorSlot as Slot,
} from '@/lib/sponsors';
import SponsorCard, { type SponsorCardVariant } from './SponsorCard';
const ROTATE_MS = 30_000;
interface SponsorSlotProps {
slot: Slot;
variant?: SponsorCardVariant;
iconOnly?: boolean;
rotate?: boolean;
className?: string;
}
export default function SponsorSlot({
slot,
variant = 'banner',
iconOnly,
rotate,
className,
}: SponsorSlotProps) {
const { data } = useSponsorsQuery();
const [, setDismissTick] = useState(0);
const [index, setIndex] = useState(0);
// Re-filtered each render so a close (dismissTick bump) re-reads localStorage.
const visible = sponsorsForSlot(data.sponsors, slot).filter(
(s) => !isSponsorDismissed(s.id, slot),
);
useEffect(() => {
if (!rotate || visible.length < 2) return;
const timer = window.setInterval(() => setIndex((i) => i + 1), ROTATE_MS);
return () => window.clearInterval(timer);
}, [rotate, visible.length]);
if (visible.length === 0) return null;
const sponsor = visible[(rotate ? index : 0) % visible.length];
return (
<div className={className}>
<SponsorCard
sponsor={sponsor}
variant={variant}
iconOnly={iconOnly}
onClose={() => {
dismissSponsor(sponsor.id, slot);
setDismissTick((n) => n + 1);
}}
/>
</div>
);
}
+121
View File
@@ -13,6 +13,7 @@ export const EXAMPLES: Record<string, unknown> = {
"discordMemory": 0, "discordMemory": 0,
"discordRunTime": "", "discordRunTime": "",
"expireDiff": 0, "expireDiff": 0,
"externalSubUserAgent": "",
"externalTrafficInformEnable": false, "externalTrafficInformEnable": false,
"externalTrafficInformURI": "", "externalTrafficInformURI": "",
"happLinkEnable": false, "happLinkEnable": false,
@@ -80,6 +81,7 @@ export const EXAMPLES: Record<string, unknown> = {
"subHappExcludeApns": false, "subHappExcludeApns": false,
"subHappExcludeRoutes": "", "subHappExcludeRoutes": "",
"subHappFallbackUrl": "", "subHappFallbackUrl": "",
"subHappLocalProxyAuth": "",
"subHappNewUrl": "", "subHappNewUrl": "",
"subHappNoLimit": false, "subHappNoLimit": false,
"subHappNotificationExpire": false, "subHappNotificationExpire": false,
@@ -96,8 +98,36 @@ export const EXAMPLES: Record<string, unknown> = {
"subHappTunMode": "", "subHappTunMode": "",
"subHappTunType": "", "subHappTunType": "",
"subHideSettings": false, "subHideSettings": false,
"subIncyAnnounceUrl": "",
"subIncyAppAutoDetect": false,
"subIncyBannerBgColor": "",
"subIncyBannerButtonColor": "",
"subIncyBannerButtonText": "",
"subIncyBannerButtonUrl": "",
"subIncyBannerText": "",
"subIncyEnableRouting": false, "subIncyEnableRouting": false,
"subIncyFragmentInterval": "",
"subIncyFragmentLength": "",
"subIncyFragmentPackets": "",
"subIncyFragmentationEnable": "",
"subIncyHideCheck": "",
"subIncyHideUrl": "",
"subIncyNoLimitEnabled": "",
"subIncyNoisesDelay": "",
"subIncyNoisesEnable": "",
"subIncyNoisesPacket": "",
"subIncyNoisesType": "",
"subIncyPerAppEnable": "",
"subIncyPerAppList": "",
"subIncyPerAppMode": "",
"subIncyPremiumUrl": "",
"subIncyProfileDescription": "",
"subIncyResolveDnsDomain": "",
"subIncyResolveDnsIp": "",
"subIncyResolveEnable": "",
"subIncyRoutingRules": "", "subIncyRoutingRules": "",
"subIncySortOrder": "",
"subIncySupportEmail": "",
"subInfoNodeEnable": false, "subInfoNodeEnable": false,
"subJsonAlwaysArray": false, "subJsonAlwaysArray": false,
"subJsonAutoDetect": false, "subJsonAutoDetect": false,
@@ -162,6 +192,7 @@ export const EXAMPLES: Record<string, unknown> = {
"discordMemory": 0, "discordMemory": 0,
"discordRunTime": "", "discordRunTime": "",
"expireDiff": 0, "expireDiff": 0,
"externalSubUserAgent": "",
"externalTrafficInformEnable": false, "externalTrafficInformEnable": false,
"externalTrafficInformURI": "", "externalTrafficInformURI": "",
"happLinkEnable": false, "happLinkEnable": false,
@@ -237,6 +268,7 @@ export const EXAMPLES: Record<string, unknown> = {
"subHappExcludeApns": false, "subHappExcludeApns": false,
"subHappExcludeRoutes": "", "subHappExcludeRoutes": "",
"subHappFallbackUrl": "", "subHappFallbackUrl": "",
"subHappLocalProxyAuth": "",
"subHappNewUrl": "", "subHappNewUrl": "",
"subHappNoLimit": false, "subHappNoLimit": false,
"subHappNotificationExpire": false, "subHappNotificationExpire": false,
@@ -253,8 +285,36 @@ export const EXAMPLES: Record<string, unknown> = {
"subHappTunMode": "", "subHappTunMode": "",
"subHappTunType": "", "subHappTunType": "",
"subHideSettings": false, "subHideSettings": false,
"subIncyAnnounceUrl": "",
"subIncyAppAutoDetect": false,
"subIncyBannerBgColor": "",
"subIncyBannerButtonColor": "",
"subIncyBannerButtonText": "",
"subIncyBannerButtonUrl": "",
"subIncyBannerText": "",
"subIncyEnableRouting": false, "subIncyEnableRouting": false,
"subIncyFragmentInterval": "",
"subIncyFragmentLength": "",
"subIncyFragmentPackets": "",
"subIncyFragmentationEnable": "",
"subIncyHideCheck": "",
"subIncyHideUrl": "",
"subIncyNoLimitEnabled": "",
"subIncyNoisesDelay": "",
"subIncyNoisesEnable": "",
"subIncyNoisesPacket": "",
"subIncyNoisesType": "",
"subIncyPerAppEnable": "",
"subIncyPerAppList": "",
"subIncyPerAppMode": "",
"subIncyPremiumUrl": "",
"subIncyProfileDescription": "",
"subIncyResolveDnsDomain": "",
"subIncyResolveDnsIp": "",
"subIncyResolveEnable": "",
"subIncyRoutingRules": "", "subIncyRoutingRules": "",
"subIncySortOrder": "",
"subIncySupportEmail": "",
"subInfoNodeEnable": false, "subInfoNodeEnable": false,
"subJsonAlwaysArray": false, "subJsonAlwaysArray": false,
"subJsonAutoDetect": false, "subJsonAutoDetect": false,
@@ -369,6 +429,7 @@ export const EXAMPLES: Record<string, unknown> = {
"reset": 0, "reset": 0,
"resetDay": 0, "resetDay": 0,
"resetMax": 0, "resetMax": 0,
"resetWeekday": 0,
"reverse": null, "reverse": null,
"secret": "ee1234567890abcdef1234567890abcd7777772e636c6f7564666c6172652e636f6d", "secret": "ee1234567890abcdef1234567890abcd7777772e636c6f7564666c6172652e636f6d",
"security": "", "security": "",
@@ -408,6 +469,7 @@ export const EXAMPLES: Record<string, unknown> = {
"reset": 0, "reset": 0,
"resetDay": 0, "resetDay": 0,
"resetMax": 0, "resetMax": 0,
"resetWeekday": 0,
"subId": "abcd1234", "subId": "abcd1234",
"totalGB": 53687091200, "totalGB": 53687091200,
"traffic": null, "traffic": null,
@@ -457,6 +519,7 @@ export const EXAMPLES: Record<string, unknown> = {
"reset": 0, "reset": 0,
"resetDay": 0, "resetDay": 0,
"resetMax": 0, "resetMax": 0,
"resetWeekday": 0,
"reverse": null, "reverse": null,
"secret": "", "secret": "",
"security": "", "security": "",
@@ -468,6 +531,25 @@ export const EXAMPLES: Record<string, unknown> = {
"updatedAt": 0, "updatedAt": 0,
"uuid": "" "uuid": ""
}, },
"ClientRenewalPreview": {
"canRenew": true,
"delayedStart": false,
"nextExpiry": "2030-02-01T00:00:00Z",
"renewAt": "2030-01-01T00:00:00Z",
"renewals": 1,
"suggestedExpiry": "2030-01-01T00:00:00Z",
"suggestedExpiryTime": 1893456000000,
"timeZone": "UTC",
"validThrough": "2029-12-31T23:59:59Z"
},
"ClientRenewalPreviewRequest": {
"expiryTime": 1893456000000,
"reset": 0,
"resetCount": 0,
"resetDay": 1,
"resetMax": 0,
"resetWeekday": 0
},
"ClientReverse": { "ClientReverse": {
"tag": "" "tag": ""
}, },
@@ -487,6 +569,7 @@ export const EXAMPLES: Record<string, unknown> = {
"reset": 0, "reset": 0,
"resetDay": 0, "resetDay": 0,
"resetMax": 0, "resetMax": 0,
"resetWeekday": 0,
"subId": "abcd1234", "subId": "abcd1234",
"totalGB": 53687091200, "totalGB": 53687091200,
"traffic": null, "traffic": null,
@@ -505,6 +588,7 @@ export const EXAMPLES: Record<string, unknown> = {
"resetCount": 0, "resetCount": 0,
"resetDay": 0, "resetDay": 0,
"resetMax": 0, "resetMax": 0,
"resetWeekday": 0,
"subId": "i7tvdpeffi0hvvf1", "subId": "i7tvdpeffi0hvvf1",
"total": 10737418240, "total": 10737418240,
"up": 1048576, "up": 1048576,
@@ -591,6 +675,7 @@ export const EXAMPLES: Record<string, unknown> = {
"alpn": [ "alpn": [
"" ""
], ],
"cipherSuites": "",
"createdAt": 0, "createdAt": 0,
"echConfigList": "", "echConfigList": "",
"excludeFromSubTypes": [ "excludeFromSubTypes": [
@@ -636,6 +721,7 @@ export const EXAMPLES: Record<string, unknown> = {
"alpn": [ "alpn": [
"" ""
], ],
"cipherSuites": "",
"echConfigList": "", "echConfigList": "",
"excludeFromSubTypes": [ "excludeFromSubTypes": [
"" ""
@@ -700,6 +786,7 @@ export const EXAMPLES: Record<string, unknown> = {
"resetCount": 0, "resetCount": 0,
"resetDay": 0, "resetDay": 0,
"resetMax": 0, "resetMax": 0,
"resetWeekday": 0,
"subId": "i7tvdpeffi0hvvf1", "subId": "i7tvdpeffi0hvvf1",
"total": 10737418240, "total": 10737418240,
"up": 1048576, "up": 1048576,
@@ -709,6 +796,7 @@ export const EXAMPLES: Record<string, unknown> = {
"disableFlow": false, "disableFlow": false,
"down": 0, "down": 0,
"enable": true, "enable": true,
"excludeFromSub": false,
"expiryTime": 0, "expiryTime": 0,
"fallbackParent": null, "fallbackParent": null,
"id": 1, "id": 1,
@@ -1017,6 +1105,39 @@ export const EXAMPLES: Record<string, unknown> = {
"key": "", "key": "",
"value": "" "value": ""
}, },
"Sponsor": {
"enable": true,
"from": "2026-10-01T00:00:00Z",
"id": "acme-2026-10",
"link": "https://acme.example/?utm_source=3x-ui",
"logo": "/sponsors/logo/acme.png",
"name": "Acme VPS",
"slots": [
""
],
"text": {},
"title": {},
"until": "2026-11-01T00:00:00Z"
},
"SponsorList": {
"contact": "https://t.me/example",
"sponsors": [
{
"enable": true,
"from": "2026-10-01T00:00:00Z",
"id": "acme-2026-10",
"link": "https://acme.example/?utm_source=3x-ui",
"logo": "/sponsors/logo/acme.png",
"name": "Acme VPS",
"slots": [
""
],
"text": {},
"title": {},
"until": "2026-11-01T00:00:00Z"
}
]
},
"SubBalancer": { "SubBalancer": {
"createdAt": 1710000000000, "createdAt": 1710000000000,
"enabled": true, "enabled": true,
+453 -2
View File
@@ -43,6 +43,9 @@ export const SCHEMAS: Record<string, unknown> = {
"minimum": 0, "minimum": 0,
"type": "integer" "type": "integer"
}, },
"externalSubUserAgent": {
"type": "string"
},
"externalTrafficInformEnable": { "externalTrafficInformEnable": {
"type": "boolean" "type": "boolean"
}, },
@@ -262,6 +265,9 @@ export const SCHEMAS: Record<string, unknown> = {
"subHappFallbackUrl": { "subHappFallbackUrl": {
"type": "string" "type": "string"
}, },
"subHappLocalProxyAuth": {
"type": "string"
},
"subHappNewUrl": { "subHappNewUrl": {
"type": "string" "type": "string"
}, },
@@ -310,12 +316,97 @@ export const SCHEMAS: Record<string, unknown> = {
"subHideSettings": { "subHideSettings": {
"type": "boolean" "type": "boolean"
}, },
"subIncyAnnounceUrl": {
"type": "string"
},
"subIncyAppAutoDetect": {
"description": "Incy client customization settings (app-management). A \"\" value omits\nthe header so the subscriber's own app setting is left alone.",
"type": "boolean"
},
"subIncyBannerBgColor": {
"type": "string"
},
"subIncyBannerButtonColor": {
"type": "string"
},
"subIncyBannerButtonText": {
"type": "string"
},
"subIncyBannerButtonUrl": {
"type": "string"
},
"subIncyBannerText": {
"type": "string"
},
"subIncyEnableRouting": { "subIncyEnableRouting": {
"type": "boolean" "type": "boolean"
}, },
"subIncyFragmentInterval": {
"type": "string"
},
"subIncyFragmentLength": {
"type": "string"
},
"subIncyFragmentPackets": {
"type": "string"
},
"subIncyFragmentationEnable": {
"type": "string"
},
"subIncyHideCheck": {
"type": "string"
},
"subIncyHideUrl": {
"type": "string"
},
"subIncyNoLimitEnabled": {
"type": "string"
},
"subIncyNoisesDelay": {
"type": "string"
},
"subIncyNoisesEnable": {
"type": "string"
},
"subIncyNoisesPacket": {
"type": "string"
},
"subIncyNoisesType": {
"type": "string"
},
"subIncyPerAppEnable": {
"type": "string"
},
"subIncyPerAppList": {
"type": "string"
},
"subIncyPerAppMode": {
"type": "string"
},
"subIncyPremiumUrl": {
"type": "string"
},
"subIncyProfileDescription": {
"type": "string"
},
"subIncyResolveDnsDomain": {
"type": "string"
},
"subIncyResolveDnsIp": {
"type": "string"
},
"subIncyResolveEnable": {
"type": "string"
},
"subIncyRoutingRules": { "subIncyRoutingRules": {
"type": "string" "type": "string"
}, },
"subIncySortOrder": {
"type": "string"
},
"subIncySupportEmail": {
"type": "string"
},
"subInfoNodeEnable": { "subInfoNodeEnable": {
"type": "boolean" "type": "boolean"
}, },
@@ -493,6 +584,7 @@ export const SCHEMAS: Record<string, unknown> = {
"discordMemory", "discordMemory",
"discordRunTime", "discordRunTime",
"expireDiff", "expireDiff",
"externalSubUserAgent",
"externalTrafficInformEnable", "externalTrafficInformEnable",
"externalTrafficInformURI", "externalTrafficInformURI",
"happLinkEnable", "happLinkEnable",
@@ -560,6 +652,7 @@ export const SCHEMAS: Record<string, unknown> = {
"subHappExcludeApns", "subHappExcludeApns",
"subHappExcludeRoutes", "subHappExcludeRoutes",
"subHappFallbackUrl", "subHappFallbackUrl",
"subHappLocalProxyAuth",
"subHappNewUrl", "subHappNewUrl",
"subHappNoLimit", "subHappNoLimit",
"subHappNotificationExpire", "subHappNotificationExpire",
@@ -576,8 +669,36 @@ export const SCHEMAS: Record<string, unknown> = {
"subHappTunMode", "subHappTunMode",
"subHappTunType", "subHappTunType",
"subHideSettings", "subHideSettings",
"subIncyAnnounceUrl",
"subIncyAppAutoDetect",
"subIncyBannerBgColor",
"subIncyBannerButtonColor",
"subIncyBannerButtonText",
"subIncyBannerButtonUrl",
"subIncyBannerText",
"subIncyEnableRouting", "subIncyEnableRouting",
"subIncyFragmentInterval",
"subIncyFragmentLength",
"subIncyFragmentPackets",
"subIncyFragmentationEnable",
"subIncyHideCheck",
"subIncyHideUrl",
"subIncyNoLimitEnabled",
"subIncyNoisesDelay",
"subIncyNoisesEnable",
"subIncyNoisesPacket",
"subIncyNoisesType",
"subIncyPerAppEnable",
"subIncyPerAppList",
"subIncyPerAppMode",
"subIncyPremiumUrl",
"subIncyProfileDescription",
"subIncyResolveDnsDomain",
"subIncyResolveDnsIp",
"subIncyResolveEnable",
"subIncyRoutingRules", "subIncyRoutingRules",
"subIncySortOrder",
"subIncySupportEmail",
"subInfoNodeEnable", "subInfoNodeEnable",
"subJsonAlwaysArray", "subJsonAlwaysArray",
"subJsonAutoDetect", "subJsonAutoDetect",
@@ -674,6 +795,9 @@ export const SCHEMAS: Record<string, unknown> = {
"minimum": 0, "minimum": 0,
"type": "integer" "type": "integer"
}, },
"externalSubUserAgent": {
"type": "string"
},
"externalTrafficInformEnable": { "externalTrafficInformEnable": {
"type": "boolean" "type": "boolean"
}, },
@@ -917,6 +1041,9 @@ export const SCHEMAS: Record<string, unknown> = {
"subHappFallbackUrl": { "subHappFallbackUrl": {
"type": "string" "type": "string"
}, },
"subHappLocalProxyAuth": {
"type": "string"
},
"subHappNewUrl": { "subHappNewUrl": {
"type": "string" "type": "string"
}, },
@@ -965,12 +1092,97 @@ export const SCHEMAS: Record<string, unknown> = {
"subHideSettings": { "subHideSettings": {
"type": "boolean" "type": "boolean"
}, },
"subIncyAnnounceUrl": {
"type": "string"
},
"subIncyAppAutoDetect": {
"description": "Incy client customization settings (app-management). A \"\" value omits\nthe header so the subscriber's own app setting is left alone.",
"type": "boolean"
},
"subIncyBannerBgColor": {
"type": "string"
},
"subIncyBannerButtonColor": {
"type": "string"
},
"subIncyBannerButtonText": {
"type": "string"
},
"subIncyBannerButtonUrl": {
"type": "string"
},
"subIncyBannerText": {
"type": "string"
},
"subIncyEnableRouting": { "subIncyEnableRouting": {
"type": "boolean" "type": "boolean"
}, },
"subIncyFragmentInterval": {
"type": "string"
},
"subIncyFragmentLength": {
"type": "string"
},
"subIncyFragmentPackets": {
"type": "string"
},
"subIncyFragmentationEnable": {
"type": "string"
},
"subIncyHideCheck": {
"type": "string"
},
"subIncyHideUrl": {
"type": "string"
},
"subIncyNoLimitEnabled": {
"type": "string"
},
"subIncyNoisesDelay": {
"type": "string"
},
"subIncyNoisesEnable": {
"type": "string"
},
"subIncyNoisesPacket": {
"type": "string"
},
"subIncyNoisesType": {
"type": "string"
},
"subIncyPerAppEnable": {
"type": "string"
},
"subIncyPerAppList": {
"type": "string"
},
"subIncyPerAppMode": {
"type": "string"
},
"subIncyPremiumUrl": {
"type": "string"
},
"subIncyProfileDescription": {
"type": "string"
},
"subIncyResolveDnsDomain": {
"type": "string"
},
"subIncyResolveDnsIp": {
"type": "string"
},
"subIncyResolveEnable": {
"type": "string"
},
"subIncyRoutingRules": { "subIncyRoutingRules": {
"type": "string" "type": "string"
}, },
"subIncySortOrder": {
"type": "string"
},
"subIncySupportEmail": {
"type": "string"
},
"subInfoNodeEnable": { "subInfoNodeEnable": {
"type": "boolean" "type": "boolean"
}, },
@@ -1148,6 +1360,7 @@ export const SCHEMAS: Record<string, unknown> = {
"discordMemory", "discordMemory",
"discordRunTime", "discordRunTime",
"expireDiff", "expireDiff",
"externalSubUserAgent",
"externalTrafficInformEnable", "externalTrafficInformEnable",
"externalTrafficInformURI", "externalTrafficInformURI",
"happLinkEnable", "happLinkEnable",
@@ -1223,6 +1436,7 @@ export const SCHEMAS: Record<string, unknown> = {
"subHappExcludeApns", "subHappExcludeApns",
"subHappExcludeRoutes", "subHappExcludeRoutes",
"subHappFallbackUrl", "subHappFallbackUrl",
"subHappLocalProxyAuth",
"subHappNewUrl", "subHappNewUrl",
"subHappNoLimit", "subHappNoLimit",
"subHappNotificationExpire", "subHappNotificationExpire",
@@ -1239,8 +1453,36 @@ export const SCHEMAS: Record<string, unknown> = {
"subHappTunMode", "subHappTunMode",
"subHappTunType", "subHappTunType",
"subHideSettings", "subHideSettings",
"subIncyAnnounceUrl",
"subIncyAppAutoDetect",
"subIncyBannerBgColor",
"subIncyBannerButtonColor",
"subIncyBannerButtonText",
"subIncyBannerButtonUrl",
"subIncyBannerText",
"subIncyEnableRouting", "subIncyEnableRouting",
"subIncyFragmentInterval",
"subIncyFragmentLength",
"subIncyFragmentPackets",
"subIncyFragmentationEnable",
"subIncyHideCheck",
"subIncyHideUrl",
"subIncyNoLimitEnabled",
"subIncyNoisesDelay",
"subIncyNoisesEnable",
"subIncyNoisesPacket",
"subIncyNoisesType",
"subIncyPerAppEnable",
"subIncyPerAppList",
"subIncyPerAppMode",
"subIncyPremiumUrl",
"subIncyProfileDescription",
"subIncyResolveDnsDomain",
"subIncyResolveDnsIp",
"subIncyResolveEnable",
"subIncyRoutingRules", "subIncyRoutingRules",
"subIncySortOrder",
"subIncySupportEmail",
"subInfoNodeEnable", "subInfoNodeEnable",
"subJsonAlwaysArray", "subJsonAlwaysArray",
"subJsonAutoDetect", "subJsonAutoDetect",
@@ -1497,13 +1739,17 @@ export const SCHEMAS: Record<string, unknown> = {
"type": "integer" "type": "integer"
}, },
"resetDay": { "resetDay": {
"description": "Calendar renewal day 1-31, 0 = interval mode", "description": "Calendar renewal day 1-31, 0 disables monthly renewal",
"type": "integer" "type": "integer"
}, },
"resetMax": { "resetMax": {
"description": "Max auto-renew count, 0 = unlimited", "description": "Max auto-renew count, 0 = unlimited",
"type": "integer" "type": "integer"
}, },
"resetWeekday": {
"description": "Calendar weekday 1-7 (Mon-Sun), 0 disables weekly renewal",
"type": "integer"
},
"reverse": { "reverse": {
"allOf": [ "allOf": [
{ {
@@ -1566,6 +1812,7 @@ export const SCHEMAS: Record<string, unknown> = {
"reset", "reset",
"resetDay", "resetDay",
"resetMax", "resetMax",
"resetWeekday",
"security", "security",
"subId", "subId",
"tgId", "tgId",
@@ -1717,6 +1964,9 @@ export const SCHEMAS: Record<string, unknown> = {
"resetMax": { "resetMax": {
"type": "integer" "type": "integer"
}, },
"resetWeekday": {
"type": "integer"
},
"reverse": {}, "reverse": {},
"secret": { "secret": {
"type": "string" "type": "string"
@@ -1772,6 +2022,7 @@ export const SCHEMAS: Record<string, unknown> = {
"reset", "reset",
"resetDay", "resetDay",
"resetMax", "resetMax",
"resetWeekday",
"reverse", "reverse",
"secret", "secret",
"security", "security",
@@ -1785,6 +2036,97 @@ export const SCHEMAS: Record<string, unknown> = {
], ],
"type": "object" "type": "object"
}, },
"ClientRenewalPreview": {
"properties": {
"canRenew": {
"example": true,
"type": "boolean"
},
"delayedStart": {
"example": false,
"type": "boolean"
},
"nextExpiry": {
"example": "2030-02-01T00:00:00Z",
"type": "string"
},
"renewAt": {
"example": "2030-01-01T00:00:00Z",
"type": "string"
},
"renewals": {
"example": 1,
"type": "integer"
},
"suggestedExpiry": {
"example": "2030-01-01T00:00:00Z",
"type": "string"
},
"suggestedExpiryTime": {
"example": 1893456000000,
"format": "int64",
"type": "integer"
},
"timeZone": {
"example": "UTC",
"type": "string"
},
"validThrough": {
"example": "2029-12-31T23:59:59Z",
"type": "string"
}
},
"required": [
"canRenew",
"delayedStart",
"nextExpiry",
"renewAt",
"renewals",
"suggestedExpiry",
"suggestedExpiryTime",
"timeZone",
"validThrough"
],
"type": "object"
},
"ClientRenewalPreviewRequest": {
"properties": {
"expiryTime": {
"example": 1893456000000,
"format": "int64",
"type": "integer"
},
"reset": {
"example": 0,
"type": "integer"
},
"resetCount": {
"example": 0,
"type": "integer"
},
"resetDay": {
"example": 1,
"type": "integer"
},
"resetMax": {
"example": 0,
"type": "integer"
},
"resetWeekday": {
"example": 0,
"type": "integer"
}
},
"required": [
"expiryTime",
"reset",
"resetCount",
"resetDay",
"resetMax",
"resetWeekday"
],
"type": "object"
},
"ClientReverse": { "ClientReverse": {
"properties": { "properties": {
"tag": { "tag": {
@@ -1855,6 +2197,10 @@ export const SCHEMAS: Record<string, unknown> = {
"example": 0, "example": 0,
"type": "integer" "type": "integer"
}, },
"resetWeekday": {
"example": 0,
"type": "integer"
},
"subId": { "subId": {
"example": "abcd1234", "example": "abcd1234",
"type": "string" "type": "string"
@@ -1889,6 +2235,7 @@ export const SCHEMAS: Record<string, unknown> = {
"reset", "reset",
"resetDay", "resetDay",
"resetMax", "resetMax",
"resetWeekday",
"subId", "subId",
"totalGB", "totalGB",
"updatedAt" "updatedAt"
@@ -1944,7 +2291,7 @@ export const SCHEMAS: Record<string, unknown> = {
"type": "integer" "type": "integer"
}, },
"resetDay": { "resetDay": {
"description": "ResetDay renews on that day of each calendar month instead of every\nReset days; 0 keeps the interval behaviour.", "description": "ResetDay renews on that day of each calendar month instead of every\nReset days; 0 disables monthly renewal.",
"example": 0, "example": 0,
"type": "integer" "type": "integer"
}, },
@@ -1953,6 +2300,11 @@ export const SCHEMAS: Record<string, unknown> = {
"example": 0, "example": 0,
"type": "integer" "type": "integer"
}, },
"resetWeekday": {
"description": "ResetWeekday renews weekly at panel-local midnight: 1 Monday through 7 Sunday.",
"example": 0,
"type": "integer"
},
"subId": { "subId": {
"example": "i7tvdpeffi0hvvf1", "example": "i7tvdpeffi0hvvf1",
"type": "string" "type": "string"
@@ -1985,6 +2337,7 @@ export const SCHEMAS: Record<string, unknown> = {
"resetCount", "resetCount",
"resetDay", "resetDay",
"resetMax", "resetMax",
"resetWeekday",
"subId", "subId",
"total", "total",
"up", "up",
@@ -2275,6 +2628,9 @@ export const SCHEMAS: Record<string, unknown> = {
}, },
"type": "array" "type": "array"
}, },
"cipherSuites": {
"type": "string"
},
"createdAt": { "createdAt": {
"format": "int64", "format": "int64",
"type": "integer" "type": "integer"
@@ -2408,6 +2764,7 @@ export const SCHEMAS: Record<string, unknown> = {
"address", "address",
"allowInsecure", "allowInsecure",
"alpn", "alpn",
"cipherSuites",
"createdAt", "createdAt",
"echConfigList", "echConfigList",
"excludeFromSubTypes", "excludeFromSubTypes",
@@ -2452,6 +2809,9 @@ export const SCHEMAS: Record<string, unknown> = {
}, },
"type": "array" "type": "array"
}, },
"cipherSuites": {
"type": "string"
},
"echConfigList": { "echConfigList": {
"type": "string" "type": "string"
}, },
@@ -2578,6 +2938,7 @@ export const SCHEMAS: Record<string, unknown> = {
"required": [ "required": [
"allowInsecure", "allowInsecure",
"alpn", "alpn",
"cipherSuites",
"echConfigList", "echConfigList",
"excludeFromSubTypes", "excludeFromSubTypes",
"finalMask", "finalMask",
@@ -2667,6 +3028,11 @@ export const SCHEMAS: Record<string, unknown> = {
"example": true, "example": true,
"type": "boolean" "type": "boolean"
}, },
"excludeFromSub": {
"description": "Whether to omit this inbound from subscription output while keeping it operational",
"example": false,
"type": "boolean"
},
"expiryTime": { "expiryTime": {
"description": "Expiration timestamp", "description": "Expiration timestamp",
"format": "int64", "format": "int64",
@@ -2790,6 +3156,7 @@ export const SCHEMAS: Record<string, unknown> = {
"disableFlow", "disableFlow",
"down", "down",
"enable", "enable",
"excludeFromSub",
"expiryTime", "expiryTime",
"id", "id",
"lastTrafficResetTime", "lastTrafficResetTime",
@@ -4101,6 +4468,90 @@ export const SCHEMAS: Record<string, unknown> = {
], ],
"type": "object" "type": "object"
}, },
"Sponsor": {
"description": "Sponsor is one paid placement published in the repo's sponsors.json.",
"properties": {
"enable": {
"example": true,
"nullable": true,
"type": "boolean"
},
"from": {
"example": "2026-10-01T00:00:00Z",
"format": "date-time",
"nullable": true,
"type": "string"
},
"id": {
"example": "acme-2026-10",
"type": "string"
},
"link": {
"example": "https://acme.example/?utm_source=3x-ui",
"type": "string"
},
"logo": {
"example": "/sponsors/logo/acme.png",
"type": "string"
},
"name": {
"example": "Acme VPS",
"type": "string"
},
"slots": {
"items": {
"type": "string"
},
"type": "array"
},
"text": {
"additionalProperties": {
"type": "string"
},
"type": "object"
},
"title": {
"additionalProperties": {
"type": "string"
},
"type": "object"
},
"until": {
"example": "2026-11-01T00:00:00Z",
"format": "date-time",
"type": "string"
}
},
"required": [
"id",
"link",
"name",
"slots",
"text",
"title",
"until"
],
"type": "object"
},
"SponsorList": {
"description": "SponsorList is the active sponsor set plus the contact link for new sponsors.",
"properties": {
"contact": {
"example": "https://t.me/example",
"type": "string"
},
"sponsors": {
"items": {
"$ref": "#/components/schemas/Sponsor"
},
"type": "array"
}
},
"required": [
"sponsors"
],
"type": "object"
},
"SubBalancer": { "SubBalancer": {
"description": "SubBalancer is one extra JSON-subscription config document whose members are\nthe selected inbounds' proxy outbounds. SortOrder shares SubSortIndex semantics.", "description": "SubBalancer is one extra JSON-subscription config document whose members are\nthe selected inbounds' proxy outbounds. SortOrder shares SubSortIndex semantics.",
"properties": { "properties": {
+107
View File
@@ -3,6 +3,7 @@ export type GeoKind = string;
export type OnlineAPISupport = number; export type OnlineAPISupport = number;
export type ProcessState = string; export type ProcessState = string;
export type Protocol = string; export type Protocol = string;
export type addrFamily = number;
export type staticEgressResolver = string; export type staticEgressResolver = string;
export type trafficLocalApplyAction = number; export type trafficLocalApplyAction = number;
export type transportBits = number; export type transportBits = number;
@@ -20,6 +21,7 @@ export interface AllSetting {
discordMemory: number; discordMemory: number;
discordRunTime: string; discordRunTime: string;
expireDiff: number; expireDiff: number;
externalSubUserAgent: string;
externalTrafficInformEnable: boolean; externalTrafficInformEnable: boolean;
externalTrafficInformURI: string; externalTrafficInformURI: string;
happLinkEnable: boolean; happLinkEnable: boolean;
@@ -87,6 +89,7 @@ export interface AllSetting {
subHappExcludeApns: boolean; subHappExcludeApns: boolean;
subHappExcludeRoutes: string; subHappExcludeRoutes: string;
subHappFallbackUrl: string; subHappFallbackUrl: string;
subHappLocalProxyAuth: string;
subHappNewUrl: string; subHappNewUrl: string;
subHappNoLimit: boolean; subHappNoLimit: boolean;
subHappNotificationExpire: boolean; subHappNotificationExpire: boolean;
@@ -103,8 +106,36 @@ export interface AllSetting {
subHappTunMode: string; subHappTunMode: string;
subHappTunType: string; subHappTunType: string;
subHideSettings: boolean; subHideSettings: boolean;
subIncyAnnounceUrl: string;
subIncyAppAutoDetect: boolean;
subIncyBannerBgColor: string;
subIncyBannerButtonColor: string;
subIncyBannerButtonText: string;
subIncyBannerButtonUrl: string;
subIncyBannerText: string;
subIncyEnableRouting: boolean; subIncyEnableRouting: boolean;
subIncyFragmentInterval: string;
subIncyFragmentLength: string;
subIncyFragmentPackets: string;
subIncyFragmentationEnable: string;
subIncyHideCheck: string;
subIncyHideUrl: string;
subIncyNoLimitEnabled: string;
subIncyNoisesDelay: string;
subIncyNoisesEnable: string;
subIncyNoisesPacket: string;
subIncyNoisesType: string;
subIncyPerAppEnable: string;
subIncyPerAppList: string;
subIncyPerAppMode: string;
subIncyPremiumUrl: string;
subIncyProfileDescription: string;
subIncyResolveDnsDomain: string;
subIncyResolveDnsIp: string;
subIncyResolveEnable: string;
subIncyRoutingRules: string; subIncyRoutingRules: string;
subIncySortOrder: string;
subIncySupportEmail: string;
subInfoNodeEnable: boolean; subInfoNodeEnable: boolean;
subJsonAlwaysArray: boolean; subJsonAlwaysArray: boolean;
subJsonAutoDetect: boolean; subJsonAutoDetect: boolean;
@@ -170,6 +201,7 @@ export interface AllSettingView {
discordMemory: number; discordMemory: number;
discordRunTime: string; discordRunTime: string;
expireDiff: number; expireDiff: number;
externalSubUserAgent: string;
externalTrafficInformEnable: boolean; externalTrafficInformEnable: boolean;
externalTrafficInformURI: string; externalTrafficInformURI: string;
happLinkEnable: boolean; happLinkEnable: boolean;
@@ -245,6 +277,7 @@ export interface AllSettingView {
subHappExcludeApns: boolean; subHappExcludeApns: boolean;
subHappExcludeRoutes: string; subHappExcludeRoutes: string;
subHappFallbackUrl: string; subHappFallbackUrl: string;
subHappLocalProxyAuth: string;
subHappNewUrl: string; subHappNewUrl: string;
subHappNoLimit: boolean; subHappNoLimit: boolean;
subHappNotificationExpire: boolean; subHappNotificationExpire: boolean;
@@ -261,8 +294,36 @@ export interface AllSettingView {
subHappTunMode: string; subHappTunMode: string;
subHappTunType: string; subHappTunType: string;
subHideSettings: boolean; subHideSettings: boolean;
subIncyAnnounceUrl: string;
subIncyAppAutoDetect: boolean;
subIncyBannerBgColor: string;
subIncyBannerButtonColor: string;
subIncyBannerButtonText: string;
subIncyBannerButtonUrl: string;
subIncyBannerText: string;
subIncyEnableRouting: boolean; subIncyEnableRouting: boolean;
subIncyFragmentInterval: string;
subIncyFragmentLength: string;
subIncyFragmentPackets: string;
subIncyFragmentationEnable: string;
subIncyHideCheck: string;
subIncyHideUrl: string;
subIncyNoLimitEnabled: string;
subIncyNoisesDelay: string;
subIncyNoisesEnable: string;
subIncyNoisesPacket: string;
subIncyNoisesType: string;
subIncyPerAppEnable: string;
subIncyPerAppList: string;
subIncyPerAppMode: string;
subIncyPremiumUrl: string;
subIncyProfileDescription: string;
subIncyResolveDnsDomain: string;
subIncyResolveDnsIp: string;
subIncyResolveEnable: string;
subIncyRoutingRules: string; subIncyRoutingRules: string;
subIncySortOrder: string;
subIncySupportEmail: string;
subInfoNodeEnable: boolean; subInfoNodeEnable: boolean;
subJsonAlwaysArray: boolean; subJsonAlwaysArray: boolean;
subJsonAutoDetect: boolean; subJsonAutoDetect: boolean;
@@ -364,6 +425,7 @@ export interface Client {
reset: number; reset: number;
resetDay: number; resetDay: number;
resetMax: number; resetMax: number;
resetWeekday: number;
reverse?: ClientReverse | null; reverse?: ClientReverse | null;
secret?: string; secret?: string;
security: string; security: string;
@@ -415,6 +477,7 @@ export interface ClientRecord {
reset: number; reset: number;
resetDay: number; resetDay: number;
resetMax: number; resetMax: number;
resetWeekday: number;
reverse: unknown; reverse: unknown;
secret: string; secret: string;
security: string; security: string;
@@ -427,6 +490,27 @@ export interface ClientRecord {
uuid: string; uuid: string;
} }
export interface ClientRenewalPreview {
canRenew: boolean;
delayedStart: boolean;
nextExpiry: string;
renewAt: string;
renewals: number;
suggestedExpiry: string;
suggestedExpiryTime: number;
timeZone: string;
validThrough: string;
}
export interface ClientRenewalPreviewRequest {
expiryTime: number;
reset: number;
resetCount: number;
resetDay: number;
resetMax: number;
resetWeekday: number;
}
export interface ClientReverse { export interface ClientReverse {
tag: string; tag: string;
} }
@@ -444,6 +528,7 @@ export interface ClientSlim {
reset: number; reset: number;
resetDay: number; resetDay: number;
resetMax: number; resetMax: number;
resetWeekday: number;
subId: string; subId: string;
totalGB: number; totalGB: number;
traffic?: ClientTraffic | null; traffic?: ClientTraffic | null;
@@ -463,6 +548,7 @@ export interface ClientTraffic {
resetCount: number; resetCount: number;
resetDay: number; resetDay: number;
resetMax: number; resetMax: number;
resetWeekday: number;
subId: string; subId: string;
total: number; total: number;
up: number; up: number;
@@ -537,6 +623,7 @@ export interface Host {
address: string; address: string;
allowInsecure: boolean; allowInsecure: boolean;
alpn: string[]; alpn: string[];
cipherSuites: string;
createdAt: number; createdAt: number;
echConfigList: string; echConfigList: string;
excludeFromSubTypes: string[]; excludeFromSubTypes: string[];
@@ -573,6 +660,7 @@ export interface Host {
export interface HostGroup { export interface HostGroup {
allowInsecure: boolean; allowInsecure: boolean;
alpn: string[]; alpn: string[];
cipherSuites: string;
echConfigList: string; echConfigList: string;
excludeFromSubTypes: string[]; excludeFromSubTypes: string[];
finalMask: string; finalMask: string;
@@ -617,6 +705,7 @@ export interface Inbound {
disableFlow: boolean; disableFlow: boolean;
down: number; down: number;
enable: boolean; enable: boolean;
excludeFromSub: boolean;
expiryTime: number; expiryTime: number;
fallbackParent?: FallbackParentInfo | null; fallbackParent?: FallbackParentInfo | null;
id: number; id: number;
@@ -937,6 +1026,24 @@ export interface Setting {
value: string; value: string;
} }
export interface Sponsor {
enable?: boolean | null;
from?: string | null;
id: string;
link: string;
logo?: string;
name: string;
slots: string[];
text: Record<string, string>;
title: Record<string, string>;
until: string;
}
export interface SponsorList {
contact?: string;
sponsors: Sponsor[];
}
export interface SubBalancer { export interface SubBalancer {
createdAt: number; createdAt: number;
enabled: boolean; enabled: boolean;
+113
View File
@@ -12,6 +12,9 @@ export type ProcessState = z.infer<typeof ProcessStateSchema>;
export const ProtocolSchema = z.string(); export const ProtocolSchema = z.string();
export type Protocol = z.infer<typeof ProtocolSchema>; export type Protocol = z.infer<typeof ProtocolSchema>;
export const addrFamilySchema = z.number().int();
export type addrFamily = z.infer<typeof addrFamilySchema>;
export const staticEgressResolverSchema = z.string(); export const staticEgressResolverSchema = z.string();
export type staticEgressResolver = z.infer<typeof staticEgressResolverSchema>; export type staticEgressResolver = z.infer<typeof staticEgressResolverSchema>;
@@ -34,6 +37,7 @@ export const AllSettingSchema = z.object({
discordMemory: z.number().int().min(0).max(100), discordMemory: z.number().int().min(0).max(100),
discordRunTime: z.string(), discordRunTime: z.string(),
expireDiff: z.number().int().min(0), expireDiff: z.number().int().min(0),
externalSubUserAgent: z.string(),
externalTrafficInformEnable: z.boolean(), externalTrafficInformEnable: z.boolean(),
externalTrafficInformURI: z.string(), externalTrafficInformURI: z.string(),
happLinkEnable: z.boolean(), happLinkEnable: z.boolean(),
@@ -101,6 +105,7 @@ export const AllSettingSchema = z.object({
subHappExcludeApns: z.boolean(), subHappExcludeApns: z.boolean(),
subHappExcludeRoutes: z.string(), subHappExcludeRoutes: z.string(),
subHappFallbackUrl: z.string(), subHappFallbackUrl: z.string(),
subHappLocalProxyAuth: z.string(),
subHappNewUrl: z.string(), subHappNewUrl: z.string(),
subHappNoLimit: z.boolean(), subHappNoLimit: z.boolean(),
subHappNotificationExpire: z.boolean(), subHappNotificationExpire: z.boolean(),
@@ -117,8 +122,36 @@ export const AllSettingSchema = z.object({
subHappTunMode: z.string(), subHappTunMode: z.string(),
subHappTunType: z.string(), subHappTunType: z.string(),
subHideSettings: z.boolean(), subHideSettings: z.boolean(),
subIncyAnnounceUrl: z.string(),
subIncyAppAutoDetect: z.boolean(),
subIncyBannerBgColor: z.string(),
subIncyBannerButtonColor: z.string(),
subIncyBannerButtonText: z.string(),
subIncyBannerButtonUrl: z.string(),
subIncyBannerText: z.string(),
subIncyEnableRouting: z.boolean(), subIncyEnableRouting: z.boolean(),
subIncyFragmentInterval: z.string(),
subIncyFragmentLength: z.string(),
subIncyFragmentPackets: z.string(),
subIncyFragmentationEnable: z.string(),
subIncyHideCheck: z.string(),
subIncyHideUrl: z.string(),
subIncyNoLimitEnabled: z.string(),
subIncyNoisesDelay: z.string(),
subIncyNoisesEnable: z.string(),
subIncyNoisesPacket: z.string(),
subIncyNoisesType: z.string(),
subIncyPerAppEnable: z.string(),
subIncyPerAppList: z.string(),
subIncyPerAppMode: z.string(),
subIncyPremiumUrl: z.string(),
subIncyProfileDescription: z.string(),
subIncyResolveDnsDomain: z.string(),
subIncyResolveDnsIp: z.string(),
subIncyResolveEnable: z.string(),
subIncyRoutingRules: z.string(), subIncyRoutingRules: z.string(),
subIncySortOrder: z.string(),
subIncySupportEmail: z.string(),
subInfoNodeEnable: z.boolean(), subInfoNodeEnable: z.boolean(),
subJsonAlwaysArray: z.boolean(), subJsonAlwaysArray: z.boolean(),
subJsonAutoDetect: z.boolean(), subJsonAutoDetect: z.boolean(),
@@ -185,6 +218,7 @@ export const AllSettingViewSchema = z.object({
discordMemory: z.number().int().min(0).max(100), discordMemory: z.number().int().min(0).max(100),
discordRunTime: z.string(), discordRunTime: z.string(),
expireDiff: z.number().int().min(0), expireDiff: z.number().int().min(0),
externalSubUserAgent: z.string(),
externalTrafficInformEnable: z.boolean(), externalTrafficInformEnable: z.boolean(),
externalTrafficInformURI: z.string(), externalTrafficInformURI: z.string(),
happLinkEnable: z.boolean(), happLinkEnable: z.boolean(),
@@ -260,6 +294,7 @@ export const AllSettingViewSchema = z.object({
subHappExcludeApns: z.boolean(), subHappExcludeApns: z.boolean(),
subHappExcludeRoutes: z.string(), subHappExcludeRoutes: z.string(),
subHappFallbackUrl: z.string(), subHappFallbackUrl: z.string(),
subHappLocalProxyAuth: z.string(),
subHappNewUrl: z.string(), subHappNewUrl: z.string(),
subHappNoLimit: z.boolean(), subHappNoLimit: z.boolean(),
subHappNotificationExpire: z.boolean(), subHappNotificationExpire: z.boolean(),
@@ -276,8 +311,36 @@ export const AllSettingViewSchema = z.object({
subHappTunMode: z.string(), subHappTunMode: z.string(),
subHappTunType: z.string(), subHappTunType: z.string(),
subHideSettings: z.boolean(), subHideSettings: z.boolean(),
subIncyAnnounceUrl: z.string(),
subIncyAppAutoDetect: z.boolean(),
subIncyBannerBgColor: z.string(),
subIncyBannerButtonColor: z.string(),
subIncyBannerButtonText: z.string(),
subIncyBannerButtonUrl: z.string(),
subIncyBannerText: z.string(),
subIncyEnableRouting: z.boolean(), subIncyEnableRouting: z.boolean(),
subIncyFragmentInterval: z.string(),
subIncyFragmentLength: z.string(),
subIncyFragmentPackets: z.string(),
subIncyFragmentationEnable: z.string(),
subIncyHideCheck: z.string(),
subIncyHideUrl: z.string(),
subIncyNoLimitEnabled: z.string(),
subIncyNoisesDelay: z.string(),
subIncyNoisesEnable: z.string(),
subIncyNoisesPacket: z.string(),
subIncyNoisesType: z.string(),
subIncyPerAppEnable: z.string(),
subIncyPerAppList: z.string(),
subIncyPerAppMode: z.string(),
subIncyPremiumUrl: z.string(),
subIncyProfileDescription: z.string(),
subIncyResolveDnsDomain: z.string(),
subIncyResolveDnsIp: z.string(),
subIncyResolveEnable: z.string(),
subIncyRoutingRules: z.string(), subIncyRoutingRules: z.string(),
subIncySortOrder: z.string(),
subIncySupportEmail: z.string(),
subInfoNodeEnable: z.boolean(), subInfoNodeEnable: z.boolean(),
subJsonAlwaysArray: z.boolean(), subJsonAlwaysArray: z.boolean(),
subJsonAutoDetect: z.boolean(), subJsonAutoDetect: z.boolean(),
@@ -383,6 +446,7 @@ export const ClientSchema = z.object({
reset: z.number().int(), reset: z.number().int(),
resetDay: z.number().int(), resetDay: z.number().int(),
resetMax: z.number().int(), resetMax: z.number().int(),
resetWeekday: z.number().int(),
reverse: z.lazy(() => ClientReverseSchema).nullable().optional(), reverse: z.lazy(() => ClientReverseSchema).nullable().optional(),
secret: z.string().optional(), secret: z.string().optional(),
security: z.string(), security: z.string(),
@@ -437,6 +501,7 @@ export const ClientRecordSchema = z.object({
reset: z.number().int(), reset: z.number().int(),
resetDay: z.number().int(), resetDay: z.number().int(),
resetMax: z.number().int(), resetMax: z.number().int(),
resetWeekday: z.number().int(),
reverse: z.unknown(), reverse: z.unknown(),
secret: z.string(), secret: z.string(),
security: z.string(), security: z.string(),
@@ -450,6 +515,29 @@ export const ClientRecordSchema = z.object({
}); });
export type ClientRecord = z.infer<typeof ClientRecordSchema>; export type ClientRecord = z.infer<typeof ClientRecordSchema>;
export const ClientRenewalPreviewSchema = z.object({
canRenew: z.boolean(),
delayedStart: z.boolean(),
nextExpiry: z.string(),
renewAt: z.string(),
renewals: z.number().int(),
suggestedExpiry: z.string(),
suggestedExpiryTime: z.number().int(),
timeZone: z.string(),
validThrough: z.string(),
});
export type ClientRenewalPreview = z.infer<typeof ClientRenewalPreviewSchema>;
export const ClientRenewalPreviewRequestSchema = z.object({
expiryTime: z.number().int(),
reset: z.number().int(),
resetCount: z.number().int(),
resetDay: z.number().int(),
resetMax: z.number().int(),
resetWeekday: z.number().int(),
});
export type ClientRenewalPreviewRequest = z.infer<typeof ClientRenewalPreviewRequestSchema>;
export const ClientReverseSchema = z.object({ export const ClientReverseSchema = z.object({
tag: z.string(), tag: z.string(),
}); });
@@ -468,6 +556,7 @@ export const ClientSlimSchema = z.object({
reset: z.number().int(), reset: z.number().int(),
resetDay: z.number().int(), resetDay: z.number().int(),
resetMax: z.number().int(), resetMax: z.number().int(),
resetWeekday: z.number().int(),
subId: z.string(), subId: z.string(),
totalGB: z.number().int(), totalGB: z.number().int(),
traffic: z.lazy(() => ClientTrafficSchema).nullable().optional(), traffic: z.lazy(() => ClientTrafficSchema).nullable().optional(),
@@ -488,6 +577,7 @@ export const ClientTrafficSchema = z.object({
resetCount: z.number().int(), resetCount: z.number().int(),
resetDay: z.number().int(), resetDay: z.number().int(),
resetMax: z.number().int(), resetMax: z.number().int(),
resetWeekday: z.number().int(),
subId: z.string(), subId: z.string(),
total: z.number().int(), total: z.number().int(),
up: z.number().int(), up: z.number().int(),
@@ -573,6 +663,7 @@ export const HostSchema = z.object({
address: z.string(), address: z.string(),
allowInsecure: z.boolean(), allowInsecure: z.boolean(),
alpn: z.array(z.string()), alpn: z.array(z.string()),
cipherSuites: z.string(),
createdAt: z.number().int(), createdAt: z.number().int(),
echConfigList: z.string(), echConfigList: z.string(),
excludeFromSubTypes: z.array(z.string()), excludeFromSubTypes: z.array(z.string()),
@@ -610,6 +701,7 @@ export type Host = z.infer<typeof HostSchema>;
export const HostGroupSchema = z.object({ export const HostGroupSchema = z.object({
allowInsecure: z.boolean(), allowInsecure: z.boolean(),
alpn: z.array(z.string()), alpn: z.array(z.string()),
cipherSuites: z.string(),
echConfigList: z.string(), echConfigList: z.string(),
excludeFromSubTypes: z.array(z.string()), excludeFromSubTypes: z.array(z.string()),
finalMask: z.string(), finalMask: z.string(),
@@ -656,6 +748,7 @@ export const InboundSchema = z.object({
disableFlow: z.boolean(), disableFlow: z.boolean(),
down: z.number().int(), down: z.number().int(),
enable: z.boolean(), enable: z.boolean(),
excludeFromSub: z.boolean(),
expiryTime: z.number().int(), expiryTime: z.number().int(),
fallbackParent: z.lazy(() => FallbackParentInfoSchema).nullable().optional(), fallbackParent: z.lazy(() => FallbackParentInfoSchema).nullable().optional(),
id: z.number().int(), id: z.number().int(),
@@ -996,6 +1089,26 @@ export const SettingSchema = z.object({
}); });
export type Setting = z.infer<typeof SettingSchema>; export type Setting = z.infer<typeof SettingSchema>;
export const SponsorSchema = z.object({
enable: z.boolean().nullable().optional(),
from: z.string().nullable().optional(),
id: z.string(),
link: z.string(),
logo: z.string().optional(),
name: z.string(),
slots: z.array(z.string()),
text: z.record(z.string(), z.string()),
title: z.record(z.string(), z.string()),
until: z.string(),
});
export type Sponsor = z.infer<typeof SponsorSchema>;
export const SponsorListSchema = z.object({
contact: z.string().optional(),
sponsors: z.array(z.lazy(() => SponsorSchema)),
});
export type SponsorList = z.infer<typeof SponsorListSchema>;
export const SubBalancerSchema = z.object({ export const SubBalancerSchema = z.object({
createdAt: z.number().int(), createdAt: z.number().int(),
enabled: z.boolean(), enabled: z.boolean(),
+1
View File
@@ -696,6 +696,7 @@ export function useClients(options: UseClientsOptions = {}) {
tgId: Number(base.tgId) || 0, tgId: Number(base.tgId) || 0,
reset: Number(base.reset) || 0, reset: Number(base.reset) || 0,
resetDay: Number(base.resetDay) || 0, resetDay: Number(base.resetDay) || 0,
resetWeekday: Number(base.resetWeekday) || 0,
resetMax: Number(base.resetMax) || 0, resetMax: Number(base.resetMax) || 0,
trafficReset: base.trafficReset || 'never', trafficReset: base.trafficReset || 'never',
trafficResetDay: Number(base.trafficResetDay) || 1, trafficResetDay: Number(base.trafficResetDay) || 1,
+1
View File
@@ -14,6 +14,7 @@ const TITLE_KEYS: Record<string, string> = {
'/outbound': 'menu.outbounds', '/outbound': 'menu.outbounds',
'/routing': 'menu.routing', '/routing': 'menu.routing',
'/api-docs': 'menu.apiDocs', '/api-docs': 'menu.apiDocs',
'/sponsors': 'menu.sponsors',
}; };
export function usePageTitle() { export function usePageTitle() {
+4
View File
@@ -247,6 +247,10 @@
padding: 8px 8px 12px; padding: 8px 8px 12px;
} }
.sider-sponsor {
margin-bottom: 6px;
}
.sidebar-pin { .sidebar-pin {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
+13
View File
@@ -11,6 +11,7 @@ import {
CloudServerOutlined, CloudServerOutlined,
ClusterOutlined, ClusterOutlined,
CodeOutlined, CodeOutlined,
CrownOutlined,
DashboardOutlined, DashboardOutlined,
DatabaseOutlined, DatabaseOutlined,
DiscordOutlined, DiscordOutlined,
@@ -43,6 +44,7 @@ import { formatPanelVersion } from '@/lib/panel-version';
import { pauseAnimationsUntilLeave, useTheme } from '@/hooks/useTheme'; import { pauseAnimationsUntilLeave, useTheme } from '@/hooks/useTheme';
import { useAllSettings } from '@/api/queries/useAllSettings'; import { useAllSettings } from '@/api/queries/useAllSettings';
import { useCommandPalette } from '@/components/command-palette/useCommandPalette'; import { useCommandPalette } from '@/components/command-palette/useCommandPalette';
import SponsorSlot from '@/components/sponsor/SponsorSlot';
import './AppSidebar.css'; import './AppSidebar.css';
const DONATE_URL = 'https://donate.sanaei.dev/'; const DONATE_URL = 'https://donate.sanaei.dev/';
@@ -68,6 +70,7 @@ type IconName =
| 'cluster' | 'cluster'
| 'hosts' | 'hosts'
| 'logout' | 'logout'
| 'sponsors'
| 'apidocs' | 'apidocs'
| 'outbound' | 'outbound'
| 'routing'; | 'routing';
@@ -82,6 +85,7 @@ const iconByName: Record<IconName, ComponentType> = {
cluster: ClusterOutlined, cluster: ClusterOutlined,
hosts: GlobalOutlined, hosts: GlobalOutlined,
logout: LogoutOutlined, logout: LogoutOutlined,
sponsors: CrownOutlined,
apidocs: ApiOutlined, apidocs: ApiOutlined,
outbound: ExportOutlined, outbound: ExportOutlined,
routing: SwapOutlined, routing: SwapOutlined,
@@ -232,6 +236,7 @@ export default function AppSidebar() {
{ key: '/settings', icon: 'setting', title: t('menu.settings') }, { key: '/settings', icon: 'setting', title: t('menu.settings') },
{ key: '/xray', icon: 'tool', title: t('menu.xray') }, { key: '/xray', icon: 'tool', title: t('menu.xray') },
{ key: '/api-docs', icon: 'apidocs', title: t('menu.apiDocs') }, { key: '/api-docs', icon: 'apidocs', title: t('menu.apiDocs') },
{ key: '/sponsors', icon: 'sponsors', title: t('menu.sponsors') },
{ key: LOGOUT_KEY, icon: 'logout', title: t('logout') }, { key: LOGOUT_KEY, icon: 'logout', title: t('logout') },
], ],
[t], [t],
@@ -447,6 +452,13 @@ export default function AppSidebar() {
onClick={onMenuClick} onClick={onMenuClick}
/> />
<div className="sider-footer"> <div className="sider-footer">
<SponsorSlot
slot="sidebar"
variant="compact"
iconOnly={railCollapsed}
rotate
className="sider-sponsor"
/>
<VersionBadge version={panelVersion} collapsed={railCollapsed} /> <VersionBadge version={panelVersion} collapsed={railCollapsed} />
</div> </div>
</Layout.Sider> </Layout.Sider>
@@ -532,6 +544,7 @@ export default function AppSidebar() {
}} }}
/> />
<div className="drawer-footer"> <div className="drawer-footer">
<SponsorSlot slot="sidebar" variant="compact" rotate className="sider-sponsor" />
<VersionBadge version={panelVersion} /> <VersionBadge version={panelVersion} />
</div> </div>
</Drawer> </Drawer>
+62
View File
@@ -0,0 +1,62 @@
import type { Sponsor } from '@/generated/types';
export type SponsorSlot = 'dashboard' | 'sidebar' | 'page' | 'login';
const DISMISS_KEY = 'xui.sponsor.dismissed';
export const SPONSOR_DISMISS_MS = 24 * 60 * 60 * 1000;
export function pickLocale(map: Record<string, string> | undefined, lang: string): string {
if (!map) return '';
const short = lang.split('-')[0].toLowerCase();
return map[lang] || map[short] || map.en || '';
}
export function sponsorsForSlot(sponsors: Sponsor[], slot: SponsorSlot): Sponsor[] {
return sponsors.filter((s) => s.slots.includes(slot));
}
function readDismissed(): Record<string, number> {
try {
const parsed: unknown = JSON.parse(localStorage.getItem(DISMISS_KEY) || '{}');
return parsed && typeof parsed === 'object' ? (parsed as Record<string, number>) : {};
} catch {
return {};
}
}
export function isSponsorDismissed(id: string, slot: SponsorSlot, now = Date.now()): boolean {
const at = readDismissed()[`${id}:${slot}`];
return typeof at === 'number' && now - at < SPONSOR_DISMISS_MS;
}
export function dismissSponsor(id: string, slot: SponsorSlot, now = Date.now()) {
const next = Object.fromEntries(
Object.entries(readDismissed()).filter(([, at]) => now - at < SPONSOR_DISMISS_MS),
);
next[`${id}:${slot}`] = now;
try {
localStorage.setItem(DISMISS_KEY, JSON.stringify(next));
} catch {}
}
// Mirrors the backend: dashboard/login show one sponsor, the sidebar rotates up to three.
export const SLOT_CAPACITY: Partial<Record<SponsorSlot, number>> = {
dashboard: 1,
login: 1,
sidebar: 3,
};
export interface PlacementStatus {
count: number;
capacity?: number;
takenUntil?: string;
}
// When full, a place frees up once enough bookings end to drop below capacity.
export function placementStatus(sponsors: Sponsor[], slot: SponsorSlot): PlacementStatus {
const booked = sponsorsForSlot(sponsors, slot);
const capacity = SLOT_CAPACITY[slot];
if (!capacity || booked.length < capacity) return { count: booked.length, capacity };
const ends = booked.map((s) => s.until).sort((a, b) => Date.parse(a) - Date.parse(b));
return { count: booked.length, capacity, takenUntil: ends[booked.length - capacity] };
}
@@ -54,6 +54,7 @@ export interface RawInboundRow {
shareAddrStrategy?: string; shareAddrStrategy?: string;
shareAddr?: string; shareAddr?: string;
subSortIndex?: number; subSortIndex?: number;
excludeFromSub?: boolean;
disableFlow?: boolean; disableFlow?: boolean;
clientStats?: unknown; clientStats?: unknown;
} }
@@ -83,6 +84,7 @@ export interface WireInboundPayload {
shareAddrStrategy: ShareAddrStrategy; shareAddrStrategy: ShareAddrStrategy;
shareAddr: string; shareAddr: string;
subSortIndex: number; subSortIndex: number;
excludeFromSub: boolean;
disableFlow: boolean; disableFlow: boolean;
} }
@@ -219,6 +221,7 @@ export function rawInboundToFormValues(row: RawInboundRow): InboundFormValues {
shareAddrStrategy: coerceShareAddrStrategy(row.shareAddrStrategy), shareAddrStrategy: coerceShareAddrStrategy(row.shareAddrStrategy),
shareAddr: row.shareAddr ?? '', shareAddr: row.shareAddr ?? '',
subSortIndex: row.subSortIndex == null || row.subSortIndex === 0 ? 1 : row.subSortIndex, subSortIndex: row.subSortIndex == null || row.subSortIndex === 0 ? 1 : row.subSortIndex,
excludeFromSub: row.excludeFromSub ?? false,
disableFlow: row.disableFlow ?? false, disableFlow: row.disableFlow ?? false,
protocol, protocol,
settings, settings,
@@ -387,6 +390,7 @@ export function formValuesToWirePayload(values: InboundFormValues): WireInboundP
shareAddrStrategy: values.shareAddrStrategy, shareAddrStrategy: values.shareAddrStrategy,
shareAddr: values.shareAddr, shareAddr: values.shareAddr,
subSortIndex: values.subSortIndex, subSortIndex: values.subSortIndex,
excludeFromSub: values.excludeFromSub,
disableFlow: values.disableFlow, disableFlow: values.disableFlow,
}; };
if (values.nodeId != null) payload.nodeId = values.nodeId; if (values.nodeId != null) payload.nodeId = values.nodeId;
+3
View File
@@ -44,6 +44,7 @@ export type DBInboundInit = Partial<{
shareAddrStrategy: string; shareAddrStrategy: string;
shareAddr: string; shareAddr: string;
subSortIndex: number; subSortIndex: number;
excludeFromSub: boolean;
disableFlow: boolean; disableFlow: boolean;
originNodeGuid: string; originNodeGuid: string;
fallbackParent: FallbackParentRef | null; fallbackParent: FallbackParentRef | null;
@@ -93,6 +94,7 @@ export class DBInbound {
shareAddrStrategy: string; shareAddrStrategy: string;
shareAddr: string; shareAddr: string;
subSortIndex: number; subSortIndex: number;
excludeFromSub: boolean;
disableFlow: boolean; disableFlow: boolean;
originNodeGuid: string; originNodeGuid: string;
fallbackParent: FallbackParentRef | null; fallbackParent: FallbackParentRef | null;
@@ -124,6 +126,7 @@ export class DBInbound {
this.shareAddrStrategy = 'node'; this.shareAddrStrategy = 'node';
this.shareAddr = ''; this.shareAddr = '';
this.subSortIndex = 1; this.subSortIndex = 1;
this.excludeFromSub = false;
this.disableFlow = false; this.disableFlow = false;
this.originNodeGuid = ''; this.originNodeGuid = '';
this.fallbackParent = null; this.fallbackParent = null;
+31
View File
@@ -66,6 +66,7 @@ export class AllSetting {
restartXrayOnClientDisable = true; restartXrayOnClientDisable = true;
subCertFile = ''; subCertFile = '';
subKeyFile = ''; subKeyFile = '';
externalSubUserAgent = 'v2rayNG/1.8.5';
subUpdates = 12; subUpdates = 12;
subEncrypt = true; subEncrypt = true;
subURI = ''; subURI = '';
@@ -104,6 +105,36 @@ export class AllSetting {
subHappAutoConnectType = 'lowestdelay'; subHappAutoConnectType = 'lowestdelay';
subHappPerAppMode = 'off'; subHappPerAppMode = 'off';
subHappPerAppList = ''; subHappPerAppList = '';
subHappLocalProxyAuth = 'auto';
subIncyAppAutoDetect = false;
subIncyProfileDescription = '';
subIncySortOrder = '';
subIncySupportEmail = '';
subIncyAnnounceUrl = '';
subIncyPremiumUrl = '';
subIncyBannerText = '';
subIncyBannerButtonText = '';
subIncyBannerButtonUrl = '';
subIncyBannerBgColor = '';
subIncyBannerButtonColor = '';
subIncyHideUrl = '';
subIncyHideCheck = '';
subIncyNoLimitEnabled = '';
subIncyPerAppEnable = '';
subIncyPerAppMode = '';
subIncyPerAppList = '';
subIncyFragmentationEnable = '';
subIncyFragmentLength = '';
subIncyFragmentInterval = '';
subIncyFragmentPackets = '';
subIncyNoisesEnable = '';
subIncyNoisesType = '';
subIncyNoisesPacket = '';
subIncyNoisesDelay = '';
subIncyResolveEnable = '';
subIncyResolveDnsDomain = '';
subIncyResolveDnsIp = '';
timeLocation = 'Local'; timeLocation = 'Local';
+56 -3
View File
@@ -236,6 +236,13 @@ export const sections: readonly Section[] = [
'Mint a CSRF token for the current session. The SPA replays it in the X-CSRF-Token header on unsafe requests. Bearer-token callers can skip this — the middleware short-circuits CSRF for authenticated API requests.', 'Mint a CSRF token for the current session. The SPA replays it in the X-CSRF-Token header on unsafe requests. Bearer-token callers can skip this — the middleware short-circuits CSRF for authenticated API requests.',
response: '{\n "success": true,\n "obj": "csrf-token-string"\n}', response: '{\n "success": true,\n "obj": "csrf-token-string"\n}',
}, },
{
method: 'GET',
path: '/sponsors',
summary:
'Public. Active paid sponsor placements read from the project sponsors.json (cached for 1h); entries outside their from/until window are dropped. Logos are proxied by the panel at /sponsors/logo/{name}. Used by the login page and panel sponsor slots.',
responseSchema: 'SponsorList',
},
{ {
method: 'POST', method: 'POST',
path: '/getTwoFactorEnable', path: '/getTwoFactorEnable',
@@ -1162,6 +1169,52 @@ export const sections: readonly Section[] = [
body: '{\n "client": {\n "email": "alice@example.com",\n "totalGB": 53687091200,\n "expiryTime": 1735689600000,\n "tgId": 0,\n "limitIp": 0,\n "limitHwid": 0,\n "enable": true\n },\n "inboundIds": [3, 5]\n}', body: '{\n "client": {\n "email": "alice@example.com",\n "totalGB": 53687091200,\n "expiryTime": 1735689600000,\n "tgId": 0,\n "limitIp": 0,\n "limitHwid": 0,\n "enable": true\n },\n "inboundIds": [3, 5]\n}',
response: '{\n "success": true,\n "msg": "Client added"\n}', response: '{\n "success": true,\n "msg": "Client added"\n}',
}, },
{
method: 'POST',
path: '/panel/api/clients/renewalPreview',
summary: 'Preview client auto-renewal dates without saving or resetting anything.',
description:
'Uses the same calendar and catch-up calculation as auto-renew in the panel timezone. resetWeekday is 1 (Monday) to 7 (Sunday), 0 disables weekly mode; it cannot be combined with positive reset or resetDay. Existing resetDay takes precedence over reset. With expiryTime=0, calendar modes suggest a first cutoff but do not activate renewal. Negative expiryTime waits for first-use activation. resetMax and resetCount simulate the existing per-period allowance limit; the preview is informational and does not reserve an allowance or guarantee node availability.',
params: [
{
name: 'expiryTime',
in: 'body (json)',
type: 'integer',
desc: 'Current cutoff in Unix milliseconds; 0 unlimited, negative first-use duration.',
},
{
name: 'reset',
in: 'body (json)',
type: 'integer',
desc: 'Fixed interval in days; 0 disabled.',
},
{
name: 'resetDay',
in: 'body (json)',
type: 'integer',
desc: 'Monthly calendar day 1-31; 0 disabled.',
},
{
name: 'resetWeekday',
in: 'body (json)',
type: 'integer',
desc: 'Weekly calendar day 1-7 (Monday-Sunday); 0 disabled.',
},
{
name: 'resetMax',
in: 'body (json)',
type: 'integer',
desc: 'Maximum renewals; 0 unlimited.',
},
{
name: 'resetCount',
in: 'body (json)',
type: 'integer',
desc: 'Renewals already consumed; defaults to 0.',
},
],
responseSchema: 'ClientRenewalPreview',
},
{ {
method: 'POST', method: 'POST',
path: '/panel/api/clients/update/:email', path: '/panel/api/clients/update/:email',
@@ -1276,15 +1329,15 @@ export const sections: readonly Section[] = [
method: 'GET', method: 'GET',
path: '/panel/api/clients/export', path: '/panel/api/clients/export',
summary: summary:
'Return every client as a {client, inboundIds} array — the same shape /bulkCreate and /import accept — so the payload round-trips straight back through /import. Clients with no inbound attachment are included with an empty inboundIds list. The UI shows this in a CodeMirror viewer (copy / download); programmatic callers get the array in obj.', 'Return every client as a {client, inboundIds, traffic} array — the shape /import accepts — so the payload round-trips straight back through /import. traffic carries the usage counters (up, down, resetCount, lastOnline, lastSubFetch) and is omitted for a client with no traffic row; the quota itself stays in client.totalGB. Clients with no inbound attachment are included with an empty inboundIds list. The UI shows this in a CodeMirror viewer (copy / download); programmatic callers get the array in obj.',
response: response:
'{\n "success": true,\n "obj": [\n {\n "client": {\n "email": "alice@example.com",\n "id": "...",\n "totalGB": 53687091200,\n "expiryTime": 0,\n "limitHwid": 2,\n "enable": true,\n "subId": "..."\n },\n "inboundIds": [7, 9]\n }\n ]\n}', '{\n "success": true,\n "obj": [\n {\n "client": {\n "email": "alice@example.com",\n "id": "...",\n "totalGB": 53687091200,\n "expiryTime": 0,\n "limitHwid": 2,\n "enable": true,\n "subId": "..."\n },\n "inboundIds": [7, 9],\n "traffic": {\n "up": 1048576,\n "down": 2097152,\n "resetCount": 0,\n "lastOnline": 1735680000000\n }\n }\n ]\n}',
}, },
{ {
method: 'POST', method: 'POST',
path: '/panel/api/clients/import', path: '/panel/api/clients/import',
summary: summary:
'Import clients from a JSON body { "data": "<json>" }, where data is a string-encoded array produced by /export ([{client, inboundIds}]). Items with inboundIds are created and attached to those inbounds; items with an empty inboundIds list are restored as unattached client records. Existing emails are never overwritten — they are returned in skipped. Triggers a single Xray restart at the end if any target inbound was running.', 'Import clients from a JSON body { "data": "<json>" }, where data is a string-encoded array produced by /export ([{client, inboundIds, traffic}]). Items with inboundIds are created and attached to those inbounds; items with an empty inboundIds list are restored as unattached client records. An optional traffic object restores the usage counters, only for clients this import creates. Existing emails are never overwritten — they are returned in skipped, and their live counters are left untouched. Triggers a single Xray restart at the end if any target inbound was running; a failure while restoring counters still reports success=false after the clients were created.',
body: '{\n "data": "[{\\"client\\":{\\"email\\":\\"alice@example.com\\",\\"enable\\":true},\\"inboundIds\\":[7]}]"\n}', body: '{\n "data": "[{\\"client\\":{\\"email\\":\\"alice@example.com\\",\\"enable\\":true},\\"inboundIds\\":[7]}]"\n}',
response: response:
'{\n "success": true,\n "obj": {\n "created": 2,\n "skipped": [\n { "email": "alice@example.com", "reason": "email already in use: alice@example.com" }\n ]\n }\n}', '{\n "success": true,\n "obj": {\n "created": 2,\n "skipped": [\n { "email": "alice@example.com", "reason": "email already in use: alice@example.com" }\n ]\n }\n}',
@@ -25,6 +25,7 @@ import { DateTimePicker, SelectAllClearButtons } from '@/components/form';
import { FormField } from '@/components/form/rhf'; import { FormField } from '@/components/form/rhf';
import { useClients, type InboundOption } from '@/hooks/useClients'; import { useClients, type InboundOption } from '@/hooks/useClients';
import { useFail2banStatusQuery, getLimitIpNotice } from '@/api/queries/useFail2banStatusQuery'; import { useFail2banStatusQuery, getLimitIpNotice } from '@/api/queries/useFail2banStatusQuery';
import ClientRenewalFields from './ClientRenewalFields';
import { ClientBulkAddFormSchema, type ClientBulkAddFormValues } from '@/schemas/client'; import { ClientBulkAddFormSchema, type ClientBulkAddFormValues } from '@/schemas/client';
const FLOW_OPTIONS = Object.values(TLS_FLOW_CONTROL); const FLOW_OPTIONS = Object.values(TLS_FLOW_CONTROL);
@@ -57,6 +58,7 @@ const EMPTY: ClientBulkAddFormValues = {
expiryTime: 0, expiryTime: 0,
reset: 0, reset: 0,
resetDay: 0, resetDay: 0,
resetWeekday: 0,
resetMax: 0, resetMax: 0,
trafficReset: 'never' as const, trafficReset: 'never' as const,
trafficResetDay: 1, trafficResetDay: 1,
@@ -215,6 +217,7 @@ export default function ClientBulkAddModal({
expiryTime: current.expiryTime, expiryTime: current.expiryTime,
reset: Number(current.reset) || 0, reset: Number(current.reset) || 0,
resetDay: Number(current.resetDay) || 0, resetDay: Number(current.resetDay) || 0,
resetWeekday: Number(current.resetWeekday) || 0,
resetMax: Number(current.resetMax) || 0, resetMax: Number(current.resetMax) || 0,
trafficReset: current.trafficReset || 'never', trafficReset: current.trafficReset || 'never',
trafficResetDay: Number(current.trafficResetDay) || 1, trafficResetDay: Number(current.trafficResetDay) || 1,
@@ -437,32 +440,13 @@ export default function ClientBulkAddModal({
</Form.Item> </Form.Item>
)} )}
<FormField <ClientRenewalFields
name="reset" active={open}
label={t('pages.clients.renew')} delayedStart={delayedStart}
tooltip={t('pages.clients.renewDesc')} expiryTime={expiryTime}
transform={{ output: (v) => Number(v) || 0 }} bulk
> setExpiry={(expiry) => methods.setValue('expiryTime', expiry)}
<InputNumber min={0} /> />
</FormField>
<FormField
name="resetDay"
label={t('pages.clients.renewOnDay')}
tooltip={t('pages.clients.renewOnDayDesc')}
transform={{ output: (v) => Number(v) || 0 }}
>
<InputNumber min={0} max={31} />
</FormField>
<FormField
name="resetMax"
label={t('pages.clients.renewMax')}
tooltip={t('pages.clients.renewMaxDesc')}
transform={{ output: (v) => Number(v) || 0 }}
>
<InputNumber min={0} />
</FormField>
<FormField name="trafficReset" label={t('pages.inbounds.periodicTrafficResetTitle')}> <FormField name="trafficReset" label={t('pages.inbounds.periodicTrafficResetTitle')}>
<Select <Select
+26 -35
View File
@@ -48,6 +48,7 @@ import type {
ExternalLinkInput, ExternalLinkInput,
} from '@/hooks/useClients'; } from '@/hooks/useClients';
import { useFail2banStatusQuery, getLimitIpNotice } from '@/api/queries/useFail2banStatusQuery'; import { useFail2banStatusQuery, getLimitIpNotice } from '@/api/queries/useFail2banStatusQuery';
import ClientRenewalFields from './ClientRenewalFields';
import { ClientFormSchema, ClientCreateFormSchema, type ClientFormValues } from '@/schemas/client'; import { ClientFormSchema, ClientCreateFormSchema, type ClientFormValues } from '@/schemas/client';
import './ClientFormModal.css'; import './ClientFormModal.css';
@@ -155,6 +156,7 @@ const EMPTY: Values = {
delayedDays: 0, delayedDays: 0,
reset: 0, reset: 0,
resetDay: 0, resetDay: 0,
resetWeekday: 0,
resetMax: 0, resetMax: 0,
trafficReset: 'never' as const, trafficReset: 'never' as const,
trafficResetDay: 1, trafficResetDay: 1,
@@ -259,6 +261,7 @@ export default function ClientFormModal({
const methods = useForm<Values>({ defaultValues: EMPTY }); const methods = useForm<Values>({ defaultValues: EMPTY });
const inboundIds = useWatch({ control: methods.control, name: 'inboundIds' }); const inboundIds = useWatch({ control: methods.control, name: 'inboundIds' });
const delayedStart = useWatch({ control: methods.control, name: 'delayedStart' }); const delayedStart = useWatch({ control: methods.control, name: 'delayedStart' });
const delayedDays = useWatch({ control: methods.control, name: 'delayedDays' });
const expiryDate = useWatch({ control: methods.control, name: 'expiryDate' }); const expiryDate = useWatch({ control: methods.control, name: 'expiryDate' });
const enable = useWatch({ control: methods.control, name: 'enable' }); const enable = useWatch({ control: methods.control, name: 'enable' });
const flow = useWatch({ control: methods.control, name: 'flow' }); const flow = useWatch({ control: methods.control, name: 'flow' });
@@ -366,6 +369,7 @@ export default function ClientFormModal({
totalGB: bytesToGB(client.totalGB || 0), totalGB: bytesToGB(client.totalGB || 0),
reset: Number(client.reset) || 0, reset: Number(client.reset) || 0,
resetDay: Number(client.resetDay) || 0, resetDay: Number(client.resetDay) || 0,
resetWeekday: Number(client.resetWeekday) || 0,
resetMax: Number(client.resetMax) || 0, resetMax: Number(client.resetMax) || 0,
trafficReset: (client.trafficReset as ClientFormValues['trafficReset']) || 'never', trafficReset: (client.trafficReset as ClientFormValues['trafficReset']) || 'never',
trafficResetDay: Number(client.trafficResetDay) || 1, trafficResetDay: Number(client.trafficResetDay) || 1,
@@ -663,6 +667,7 @@ export default function ClientFormModal({
delayedDays: values.delayedDays, delayedDays: values.delayedDays,
reset: values.reset, reset: values.reset,
resetDay: values.resetDay, resetDay: values.resetDay,
resetWeekday: values.resetWeekday,
resetMax: values.resetMax, resetMax: values.resetMax,
trafficReset: values.trafficReset, trafficReset: values.trafficReset,
trafficResetDay: values.trafficResetDay, trafficResetDay: values.trafficResetDay,
@@ -696,6 +701,7 @@ export default function ClientFormModal({
expiryTime, expiryTime,
reset: Number(values.reset) || 0, reset: Number(values.reset) || 0,
resetDay: Number(values.resetDay) || 0, resetDay: Number(values.resetDay) || 0,
resetWeekday: Number(values.resetWeekday) || 0,
resetMax: Number(values.resetMax) || 0, resetMax: Number(values.resetMax) || 0,
trafficReset: values.trafficReset || 'never', trafficReset: values.trafficReset || 'never',
trafficResetDay: Number(values.trafficResetDay) || 1, trafficResetDay: Number(values.trafficResetDay) || 1,
@@ -985,37 +991,10 @@ export default function ClientFormModal({
/> />
</Form.Item> </Form.Item>
</Col> </Col>
<Col xs={12} md={6}> </Row>
<FormField
name="reset" <Row gutter={16}>
label={t('pages.clients.renewDays')} <Col xs={24} md={12}>
tooltip={t('pages.clients.renewDesc')}
transform={{ output: (v) => Number(v) || 0 }}
>
<InputNumber min={0} style={{ width: '100%' }} />
</FormField>
</Col>
<Col xs={12} md={6}>
<FormField
name="resetDay"
label={t('pages.clients.renewOnDay')}
tooltip={t('pages.clients.renewOnDayDesc')}
transform={{ output: (v) => Number(v) || 0 }}
>
<InputNumber min={0} max={31} style={{ width: '100%' }} />
</FormField>
</Col>
<Col xs={12} md={6}>
<FormField
name="resetMax"
label={t('pages.clients.renewMax')}
tooltip={t('pages.clients.renewMaxDesc')}
transform={{ output: (v) => Number(v) || 0 }}
>
<InputNumber min={0} style={{ width: '100%' }} />
</FormField>
</Col>
<Col xs={12} md={6}>
<FormField <FormField
name="trafficReset" name="trafficReset"
label={t('pages.inbounds.periodicTrafficResetTitle')} label={t('pages.inbounds.periodicTrafficResetTitle')}
@@ -1027,9 +1006,7 @@ export default function ClientFormModal({
}))} }))}
/> />
</FormField> </FormField>
</Col>
{trafficReset === 'monthly' && ( {trafficReset === 'monthly' && (
<Col xs={12} md={6}>
<FormField <FormField
name="trafficResetDay" name="trafficResetDay"
label={t('pages.inbounds.periodicTrafficResetDay')} label={t('pages.inbounds.periodicTrafficResetDay')}
@@ -1037,8 +1014,19 @@ export default function ClientFormModal({
> >
<InputNumber min={1} max={31} style={{ width: '100%' }} /> <InputNumber min={1} max={31} style={{ width: '100%' }} />
</FormField> </FormField>
</Col>
)} )}
</Col>
<Col xs={24} md={12}>
<ClientRenewalFields
active={open}
delayedStart={delayedStart}
expiryTime={
delayedStart ? -86400000 * (delayedDays || 0) : expiryDate || 0
}
resetCount={client?.traffic?.resetCount || 0}
setExpiry={(expiry) => methods.setValue('expiryDate', expiry)}
/>
</Col>
</Row> </Row>
<Row gutter={16}> <Row gutter={16}>
@@ -1164,7 +1152,10 @@ export default function ClientFormModal({
</Space.Compact> </Space.Compact>
</Form.Item> </Form.Item>
<Form.Item label={t('pages.clients.subId')}> <Form.Item
label={t('pages.clients.subId')}
tooltip={t('pages.clients.subIdDesc')}
>
<Space.Compact style={{ display: 'flex' }}> <Space.Compact style={{ display: 'flex' }}>
<Input <Input
value={subId} value={subId}
+1 -1
View File
@@ -50,7 +50,7 @@ type QrVariant = 'standard' | 'happ';
type HappError = 'too_long' | 'unavailable' | null; type HappError = 'too_long' | 'unavailable' | null;
const HAPP_CRYPT5_PREFIX = 'happ://crypt5/'; const HAPP_CRYPT5_PREFIX = 'happ://crypt5/';
const HAPP_SETTINGS_PATH = '/settings?subscriptionTab=happ&happTab=links#subscription'; const HAPP_SETTINGS_PATH = '/settings?subscriptionTab=happ#subscription';
// QrPanel encodes at error level L; QR version 40 holds 2953 UTF-8 bytes at that level. // QrPanel encodes at error level L; QR version 40 holds 2953 UTF-8 bytes at that level.
const HAPP_QR_MAX_BYTES = 2953; const HAPP_QR_MAX_BYTES = 2953;
const UTF8_ENCODER = new TextEncoder(); const UTF8_ENCODER = new TextEncoder();
@@ -0,0 +1,197 @@
import { useEffect, useId, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useFormContext, useWatch } from 'react-hook-form';
import { useQuery } from '@tanstack/react-query';
import { Button, Form, InputNumber, Select, Space, Typography } from 'antd';
import { FormField } from '@/components/form/rhf';
import { ClientRenewalPreviewSchema } from '@/generated/zod';
import { HttpUtil } from '@/utils';
import type { ClientFormValues } from '@/schemas/client';
type RenewalFields = Pick<ClientFormValues, 'reset' | 'resetDay' | 'resetWeekday' | 'resetMax'>;
type RenewalMode = 'none' | 'interval' | 'weekly' | 'monthly';
export default function ClientRenewalFields({
active,
expiryTime,
resetCount = 0,
bulk = false,
delayedStart = false,
setExpiry,
}: {
active: boolean;
expiryTime: number;
resetCount?: number;
bulk?: boolean;
delayedStart?: boolean;
setExpiry: (expiry: number) => void;
}) {
const { t, i18n } = useTranslation();
const formId = useId();
const modeId = 'client-renewal-mode-' + formId;
const { control, setValue } = useFormContext<RenewalFields>();
const [reset, resetDay, resetWeekday, resetMax] = useWatch({
control,
name: ['reset', 'resetDay', 'resetWeekday', 'resetMax'],
});
const mode: RenewalMode =
resetDay > 0 ? 'monthly' : resetWeekday > 0 ? 'weekly' : reset > 0 ? 'interval' : 'none';
const request = useMemo(
() => ({
expiryTime,
reset: reset || 0,
resetDay: resetDay || 0,
resetWeekday: resetWeekday || 0,
resetMax: resetMax || 0,
resetCount,
}),
[expiryTime, reset, resetDay, resetWeekday, resetMax, resetCount],
);
const [debounced, setDebounced] = useState(request);
useEffect(() => {
const timer = setTimeout(() => setDebounced(request), 250);
return () => clearTimeout(timer);
}, [request]);
const query = useQuery({
queryKey: ['clients', 'renewalPreview', debounced],
enabled: active && mode !== 'none' && request === debounced,
retry: false,
queryFn: async () => {
const msg = await HttpUtil.post('/panel/api/clients/renewalPreview', debounced, {
headers: { 'Content-Type': 'application/json' },
silent: true,
});
if (!msg?.success) throw new Error(msg?.msg || 'Renewal preview failed');
return ClientRenewalPreviewSchema.parse(msg.obj);
},
});
const preview = request === debounced ? query.data : undefined;
const weekdayFormatter = new Intl.DateTimeFormat(i18n.language, {
weekday: 'long',
timeZone: 'UTC',
});
function changeMode(next: RenewalMode) {
setValue('reset', next === 'interval' ? Math.max(1, reset || 0) : 0);
setValue('resetDay', next === 'monthly' ? Math.max(1, resetDay || 0) : 0);
setValue('resetWeekday', next === 'weekly' ? Math.max(1, resetWeekday || 0) : 0);
}
return (
<>
<Form.Item label={t('pages.clients.renewMode')} htmlFor={modeId}>
<Select
id={modeId}
value={mode}
onChange={changeMode}
options={[
{ value: 'none', label: t('pages.clients.renewModeNone') },
{ value: 'interval', label: t('pages.clients.renewModeInterval') },
{ value: 'weekly', label: t('pages.clients.renewModeWeekly') },
{ value: 'monthly', label: t('pages.clients.renewModeMonthly') },
]}
/>
</Form.Item>
{mode === 'interval' && (
<FormField
name="reset"
label={bulk ? t('pages.clients.renew') : t('pages.clients.renewDays')}
tooltip={t('pages.clients.renewDesc')}
transform={{ output: (v) => Number(v) || 1 }}
>
<InputNumber id={'client-renewal-interval-' + formId} min={1} style={{ width: '100%' }} />
</FormField>
)}
{mode === 'monthly' && (
<FormField
name="resetDay"
label={t('pages.clients.renewOnDay')}
tooltip={t('pages.clients.renewOnDayDesc')}
transform={{ output: (v) => Number(v) || 1 }}
>
<InputNumber
id={'client-renewal-day-' + formId}
min={1}
max={31}
style={{ width: '100%' }}
/>
</FormField>
)}
{mode === 'weekly' && (
<FormField name="resetWeekday" label={t('pages.clients.renewWeekday')}>
<Select
id={'client-renewal-weekday-' + formId}
options={Array.from({ length: 7 }, (_, i) => ({
value: i + 1,
label: weekdayFormatter.format(new Date(Date.UTC(2026, 0, i + 5))),
}))}
/>
</FormField>
)}
{mode !== 'none' && (
<>
<FormField
name="resetMax"
label={t('pages.clients.renewMax')}
tooltip={t('pages.clients.renewMaxDesc')}
transform={{ output: (v) => Number(v) || 0 }}
>
<InputNumber min={0} style={{ width: '100%' }} />
</FormField>
<Typography.Paragraph type="secondary">
{t('pages.clients.renewScheduleDesc')}
</Typography.Paragraph>
{query.isError && request === debounced && (
<Typography.Paragraph type="warning">
{t('pages.clients.renewPreviewError')}
</Typography.Paragraph>
)}
{preview && (
<Space orientation="vertical" size={4} style={{ marginBottom: 16 }}>
<Typography.Text>
{t('pages.clients.renewPreview', { zone: preview.timeZone })}
</Typography.Text>
{delayedStart || preview.delayedStart ? (
<Typography.Text type="secondary">
{t('pages.clients.renewFirstUse')}
</Typography.Text>
) : expiryTime === 0 ? (
<>
<Typography.Text type="warning">
{t('pages.clients.renewNeedsExpiry')}
</Typography.Text>
{preview.suggestedExpiryTime > 0 && (
<Button onClick={() => setExpiry(preview.suggestedExpiryTime)}>
{t('pages.clients.renewSetExpiry')}: {preview.suggestedExpiry}
</Button>
)}
</>
) : (
<>
<Typography.Text>
{t('pages.clients.renewAt')}: {preview.renewAt}
</Typography.Text>
<Typography.Text>
{t('pages.clients.renewValidThrough')}: {preview.validThrough}
</Typography.Text>
{preview.nextExpiry && (
<Typography.Text>
{t('pages.clients.renewNextExpiry')}: {preview.nextExpiry}
</Typography.Text>
)}
<Typography.Text>
{t('pages.clients.renewPeriods', { count: preview.renewals })}
</Typography.Text>
{!preview.canRenew && (
<Typography.Text type="warning">
{t('pages.clients.renewUnavailable')}
</Typography.Text>
)}
</>
)}
</Space>
)}
</>
)}
</>
);
}
@@ -17,6 +17,7 @@ import type { HostRecord } from '@/api/queries/useHostsQuery';
import { BulkAddHostSchema, type BulkAddHostValues } from '@/schemas/api/host'; import { BulkAddHostSchema, type BulkAddHostValues } from '@/schemas/api/host';
import type { InboundOption } from '@/schemas/client'; import type { InboundOption } from '@/schemas/client';
import { ALPN_OPTION, UTLS_FINGERPRINT } from '@/schemas/primitives'; import { ALPN_OPTION, UTLS_FINGERPRINT } from '@/schemas/primitives';
import { CipherSuitesSelect } from '@/components/form';
import { FormField, rhfZodValidate } from '@/components/form/rhf'; import { FormField, rhfZodValidate } from '@/components/form/rhf';
import { useNodesQuery } from '@/api/queries/useNodesQuery'; import { useNodesQuery } from '@/api/queries/useNodesQuery';
import { useMediaQuery } from '@/hooks/useMediaQuery'; import { useMediaQuery } from '@/hooks/useMediaQuery';
@@ -56,6 +57,7 @@ function defaultsFor(host: HostRecord | null): FormShape {
path: host?.path ?? '', path: host?.path ?? '',
alpn: (host?.alpn as BulkAddHostValues['alpn']) ?? [], alpn: (host?.alpn as BulkAddHostValues['alpn']) ?? [],
fingerprint: host?.fingerprint as BulkAddHostValues['fingerprint'], fingerprint: host?.fingerprint as BulkAddHostValues['fingerprint'],
cipherSuites: host?.cipherSuites ?? '',
overrideSniFromAddress: host?.overrideSniFromAddress ?? false, overrideSniFromAddress: host?.overrideSniFromAddress ?? false,
keepSniBlank: host?.keepSniBlank ?? false, keepSniBlank: host?.keepSniBlank ?? false,
pinnedPeerCertSha256: host?.pinnedPeerCertSha256 ?? [], pinnedPeerCertSha256: host?.pinnedPeerCertSha256 ?? [],
@@ -332,6 +334,12 @@ export default function HostFormModal({
<FormField name="alpn" label={t('pages.hosts.fields.alpn')}> <FormField name="alpn" label={t('pages.hosts.fields.alpn')}>
<Select mode="multiple" allowClear options={alpnOptions} /> <Select mode="multiple" allowClear options={alpnOptions} />
</FormField> </FormField>
<FormField
name="cipherSuites"
label={t('pages.inbounds.form.cipherSuites')}
>
<CipherSuitesSelect />
</FormField>
<FormField name="pinnedPeerCertSha256" label={t('pages.hosts.fields.pins')}> <FormField name="pinnedPeerCertSha256" label={t('pages.hosts.fields.pins')}>
<Select mode="tags" allowClear tokenSeparators={[',']} /> <Select mode="tags" allowClear tokenSeparators={[',']} />
</FormField> </FormField>
@@ -700,6 +700,17 @@ export default function InboundFormModal({
<InputNumber /> <InputNumber />
</FormField> </FormField>
<FormField
name="excludeFromSub"
valueProp="checked"
label={labelWithHint(
t('pages.inbounds.form.excludeFromSub'),
t('pages.inbounds.form.excludeFromSubHelp'),
)}
>
<Switch />
</FormField>
{protocol === Protocols.VLESS && ( {protocol === Protocols.VLESS && (
<FormField <FormField
name="disableFlow" name="disableFlow"
@@ -103,13 +103,13 @@ export default function AmneziawgFields({
<InputNumber min={0} style={{ width: '100%' }} /> <InputNumber min={0} style={{ width: '100%' }} />
</FormField> </FormField>
<FormField name={['settings', 'server', 's1']} label={t('pages.xray.amneziawg.s1')}> <FormField name={['settings', 'server', 's1']} label={t('pages.xray.amneziawg.s1')}>
<InputNumber min={0} style={{ width: '100%' }} /> <InputNumber min={0} max={1552} style={{ width: '100%' }} />
</FormField> </FormField>
<FormField name={['settings', 'server', 's2']} label={t('pages.xray.amneziawg.s2')}> <FormField name={['settings', 'server', 's2']} label={t('pages.xray.amneziawg.s2')}>
<InputNumber min={0} style={{ width: '100%' }} /> <InputNumber min={0} max={1608} style={{ width: '100%' }} />
</FormField> </FormField>
<FormField name={['settings', 'server', 's3']} label={t('pages.xray.amneziawg.s3')}> <FormField name={['settings', 'server', 's3']} label={t('pages.xray.amneziawg.s3')}>
<InputNumber min={0} max={64} style={{ width: '100%' }} /> <InputNumber min={0} max={1636} style={{ width: '100%' }} />
</FormField> </FormField>
<FormField name={['settings', 'server', 's4']} label={t('pages.xray.amneziawg.s4')}> <FormField name={['settings', 'server', 's4']} label={t('pages.xray.amneziawg.s4')}>
<InputNumber min={0} max={32} style={{ width: '100%' }} /> <InputNumber min={0} max={32} style={{ width: '100%' }} />
@@ -8,11 +8,11 @@ import {
} from '@ant-design/icons'; } from '@ant-design/icons';
import { useFieldArray, useFormContext, useWatch } from 'react-hook-form'; import { useFieldArray, useFormContext, useWatch } from 'react-hook-form';
import { CipherSuitesSelect } from '@/components/form';
import { FormField } from '@/components/form/rhf'; import { FormField } from '@/components/form/rhf';
import { import {
ALPN_OPTION, ALPN_OPTION,
DOMAIN_STRATEGY_OPTION, DOMAIN_STRATEGY_OPTION,
TLS_CIPHER_OPTION,
TLS_VERSION_OPTION, TLS_VERSION_OPTION,
USAGE_OPTION, USAGE_OPTION,
UTLS_FINGERPRINT, UTLS_FINGERPRINT,
@@ -240,12 +240,7 @@ export default function TlsForm({
name={['streamSettings', 'tlsSettings', 'cipherSuites']} name={['streamSettings', 'tlsSettings', 'cipherSuites']}
label={t('pages.inbounds.form.cipherSuites')} label={t('pages.inbounds.form.cipherSuites')}
> >
<Select <CipherSuitesSelect placeholder={t('pages.inbounds.form.autoOption')} />
options={[
{ value: '', label: t('pages.inbounds.form.autoOption') },
...Object.entries(TLS_CIPHER_OPTION).map(([k, v]) => ({ value: v, label: k })),
]}
/>
</FormField> </FormField>
<Form.Item label={t('pages.inbounds.form.minMaxVersion')}> <Form.Item label={t('pages.inbounds.form.minMaxVersion')}>
<Space.Compact block> <Space.Compact block>
+3
View File
@@ -22,6 +22,7 @@ import { useStatusQuery } from '@/api/queries/useStatusQuery';
import { useMediaQuery } from '@/hooks/useMediaQuery'; import { useMediaQuery } from '@/hooks/useMediaQuery';
import AppSidebar from '@/layouts/AppSidebar'; import AppSidebar from '@/layouts/AppSidebar';
import { LazyMount } from '@/components/utility'; import { LazyMount } from '@/components/utility';
import SponsorSlot from '@/components/sponsor/SponsorSlot';
import { setMessageInstance } from '@/utils/messageBus'; import { setMessageInstance } from '@/utils/messageBus';
import OverviewActionBar from './OverviewActionBar'; import OverviewActionBar from './OverviewActionBar';
import VitalTile from './VitalTile'; import VitalTile from './VitalTile';
@@ -213,6 +214,8 @@ export default function IndexPage() {
onOpenVersionSwitch={() => setVersionOpen(true)} onOpenVersionSwitch={() => setVersionOpen(true)}
/> />
<SponsorSlot slot="dashboard" />
{health && ( {health && (
<div className="ov-health" style={{ color: health.color }}> <div className="ov-health" style={{ color: health.color }}>
<span className="ov-health-mark" /> <span className="ov-health-mark" />
+4
View File
@@ -411,3 +411,7 @@
.submit-row { .submit-row {
margin-bottom: 0; margin-bottom: 0;
} }
.login-sponsor {
margin-top: 20px;
}
+2
View File
@@ -26,6 +26,7 @@ import { FormProvider, useForm } from 'react-hook-form';
import { HttpUtil, LanguageManager } from '@/utils'; import { HttpUtil, LanguageManager } from '@/utils';
import { FormField, rhfZodValidate } from '@/components/form/rhf'; import { FormField, rhfZodValidate } from '@/components/form/rhf';
import { setMessageInstance } from '@/utils/messageBus'; import { setMessageInstance } from '@/utils/messageBus';
import SponsorSlot from '@/components/sponsor/SponsorSlot';
import { pauseAnimationsUntilLeave, useTheme } from '@/hooks/useTheme'; import { pauseAnimationsUntilLeave, useTheme } from '@/hooks/useTheme';
import { LoginFormSchema, TwoFactorCodeSchema, type LoginFormValues } from '@/schemas/login'; import { LoginFormSchema, TwoFactorCodeSchema, type LoginFormValues } from '@/schemas/login';
import './LoginPage.css'; import './LoginPage.css';
@@ -247,6 +248,7 @@ export default function LoginPage() {
</Form.Item> </Form.Item>
</Form> </Form>
</FormProvider> </FormProvider>
<SponsorSlot slot="login" variant="compact" className="login-sponsor" />
</div> </div>
)} )}
</div> </div>
@@ -25,6 +25,8 @@ interface ApiMsg<T = unknown> {
const REFRESH_MS = 15000; const REFRESH_MS = 15000;
const formatKbps = (v: number) => v.toLocaleString(undefined, { maximumFractionDigits: 1 });
export default function NodeHistoryPanel({ node, bucket = 30 }: NodeHistoryPanelProps) { export default function NodeHistoryPanel({ node, bucket = 30 }: NodeHistoryPanelProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const [cpuPoints, setCpuPoints] = useState<number[]>([]); const [cpuPoints, setCpuPoints] = useState<number[]>([]);
@@ -51,7 +53,7 @@ export default function NodeHistoryPanel({ node, bucket = 30 }: NodeHistoryPanel
}; };
// cpu/mem are percentages (clamp 0-100); net throughput is bytes/sec shown // cpu/mem are percentages (clamp 0-100); net throughput is bytes/sec shown
// as KB/s (no upper clamp, the sparkline auto-scales). // as KB/s, which must opt out of Sparkline's 0-100 "%" defaults.
const fetchSeries = async (metric: string, kind: 'pct' | 'rate') => { const fetchSeries = async (metric: string, kind: 'pct' | 'rate') => {
try { try {
const url = `/panel/api/nodes/history/${node.id}/${metric}/${bucket}`; const url = `/panel/api/nodes/history/${node.id}/${metric}/${bucket}`;
@@ -148,6 +150,8 @@ export default function NodeHistoryPanel({ node, bucket = 30 }: NodeHistoryPanel
fillOpacity={0.18} fillOpacity={0.18}
markerRadius={2.6} markerRadius={2.6}
showTooltip showTooltip
valueMax={null}
yFormatter={formatKbps}
/> />
</div> </div>
<div className="series"> <div className="series">
@@ -164,6 +168,8 @@ export default function NodeHistoryPanel({ node, bucket = 30 }: NodeHistoryPanel
fillOpacity={0.18} fillOpacity={0.18}
markerRadius={2.6} markerRadius={2.6}
showTooltip showTooltip
valueMax={null}
yFormatter={formatKbps}
/> />
</div> </div>
</div> </div>
@@ -0,0 +1,204 @@
import { useId, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Alert, Input, Modal, Space, Tabs, Typography } from 'antd';
import JsonEditor from '@/components/form/JsonEditor';
import type { HappRoutingProfile } from '@/schemas/happRouting';
import {
buildHappRoutingDeeplink,
loadHappRouting,
parseHappRoutingJson,
parseHappRoutingList,
type HappRoutingListKey,
} from './happRoutingEditor';
interface HappRoutingEditorModalProps {
input: string;
onCancel: () => void;
onGenerate: (deeplink: string) => void;
}
const basicFields: { key: HappRoutingListKey; label: string; placeholder: string }[] = [
{
key: 'DirectSites',
label: 'subHappDirectDomains',
placeholder: 'domain:ir\ndomain:cn\nexample.local',
},
{
key: 'ProxySites',
label: 'subHappProxyDomains',
placeholder: 'geosite:google\nyoutube.com',
},
{
key: 'BlockSites',
label: 'subHappBlockDomains',
placeholder: 'geosite:category-ads-all\nanalytics.google.com',
},
{
key: 'DirectIp',
label: 'subHappDirectIPs',
placeholder: 'geoip:ir\n192.168.0.0/16\n10.0.0.0/8',
},
{
key: 'ProxyIp',
label: 'subHappProxyIPs',
placeholder: '1.1.1.1/32\n8.8.8.8/32',
},
{
key: 'BlockIp',
label: 'subHappBlockIPs',
placeholder: 'geoip:phishing\n0.0.0.0/8',
},
];
type BasicBuffers = Record<HappRoutingListKey, string>;
function basicBuffers(profile: HappRoutingProfile | null): BasicBuffers {
return {
DirectSites: profile?.DirectSites?.join('\n') ?? '',
ProxySites: profile?.ProxySites?.join('\n') ?? '',
BlockSites: profile?.BlockSites?.join('\n') ?? '',
DirectIp: profile?.DirectIp?.join('\n') ?? '',
ProxyIp: profile?.ProxyIp?.join('\n') ?? '',
BlockIp: profile?.BlockIp?.join('\n') ?? '',
};
}
function mergeBasicRules(profile: HappRoutingProfile, buffers: BasicBuffers): HappRoutingProfile {
const next = { ...profile };
// Only replace edited lists; absent lists and all other profile fields must survive unchanged.
for (const { key } of basicFields) {
if (buffers[key] !== (profile[key]?.join('\n') ?? '')) {
next[key] = parseHappRoutingList(buffers[key]);
}
}
return next;
}
const loadErrorKeys = {
off: 'subHappEditorLoadOff',
remote: 'subHappEditorLoadRemote',
invalid: 'subHappEditorLoadInvalid',
};
export default function HappRoutingEditorModal({
input,
onCancel,
onGenerate,
}: HappRoutingEditorModalProps) {
const { t } = useTranslation();
const fieldId = useId();
const [loaded] = useState(() => loadHappRouting(input));
const [profile, setProfile] = useState(() => (loaded.success ? loaded.profile : null));
const [activeTab, setActiveTab] = useState('basic');
// Keep raw buffers while typing so trailing newlines and temporarily invalid JSON are not lost.
const [buffers, setBuffers] = useState(() => basicBuffers(profile));
const [jsonText, setJsonText] = useState(() => (profile ? JSON.stringify(profile, null, 2) : ''));
const advancedProfile = activeTab === 'advanced' ? parseHappRoutingJson(jsonText) : null;
const invalidJson = activeTab === 'advanced' && advancedProfile === null;
const switchTab = (nextTab: string) => {
if (!profile || nextTab === activeTab) return;
if (nextTab === 'advanced') {
const next = mergeBasicRules(profile, buffers);
setProfile(next);
setJsonText(JSON.stringify(next, null, 2));
} else {
if (!advancedProfile) return;
setProfile(advancedProfile);
setBuffers(basicBuffers(advancedProfile));
}
setActiveTab(nextTab);
};
const generate = () => {
if (!loaded.success || !profile) return;
const next = activeTab === 'advanced' ? advancedProfile : mergeBasicRules(profile, buffers);
if (next) onGenerate(buildHappRoutingDeeplink(next, loaded.mode));
};
return (
<Modal
title={t('pages.settings.subHappModalTitle')}
open
onCancel={onCancel}
onOk={generate}
okText={t('pages.settings.subHappBuildDeeplink')}
okButtonProps={{ disabled: !loaded.success || invalidJson }}
width={650}
>
<Space orientation="vertical" style={{ width: '100%', marginTop: 12 }} size="middle">
{!loaded.success ? (
<Alert type="error" showIcon title={t(`pages.settings.${loadErrorKeys[loaded.error]}`)} />
) : loaded.isNew ? (
<Alert type="info" showIcon title={t('pages.settings.subHappEditorNew')} />
) : null}
{loaded.success ? (
<Tabs
activeKey={activeTab}
onChange={switchTab}
destroyOnHidden
items={[
{
key: 'basic',
label: t('pages.settings.subHappEditorBasic'),
disabled: invalidJson,
children: (
<Space orientation="vertical" style={{ width: '100%' }} size="middle">
<Typography.Text type="secondary" id={`${fieldId}-hint`}>
{t('pages.settings.subHappEditorListHint')}
</Typography.Text>
{basicFields.map(({ key, label, placeholder }) => (
<div key={key}>
<label
htmlFor={`${fieldId}-${key}`}
style={{ display: 'block', fontWeight: 600, marginBottom: 4 }}
>
{t(`pages.settings.${label}`)}
</label>
<Input.TextArea
id={`${fieldId}-${key}`}
aria-describedby={`${fieldId}-hint`}
rows={2}
value={buffers[key]}
placeholder={placeholder}
onChange={(event) =>
setBuffers((previous) => ({ ...previous, [key]: event.target.value }))
}
/>
</div>
))}
</Space>
),
},
{
key: 'advanced',
label: t('pages.settings.subHappEditorAdvanced'),
children: (
<Space orientation="vertical" style={{ width: '100%' }} size="middle">
<Typography.Text type="secondary">
{t('pages.settings.subHappEditorAdvancedHint')}
</Typography.Text>
{invalidJson ? (
<Alert
type="error"
showIcon
title={t('pages.settings.subHappEditorInvalidJson')}
/>
) : null}
<JsonEditor
value={jsonText}
onChange={setJsonText}
minHeight="320px"
maxHeight="50vh"
/>
</Space>
),
},
]}
/>
) : null}
</Space>
</Modal>
);
}
@@ -1,19 +1,17 @@
import { useState } from 'react'; import { useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Button, Input, Modal, Select, Space, Switch, Tabs, message } from 'antd'; import { Button, Input, Select, Space, Switch, Tabs, message } from 'antd';
import { import {
BranchesOutlined, BranchesOutlined,
BuildOutlined, BuildOutlined,
CloudSyncOutlined, CloudSyncOutlined,
DesktopOutlined, DesktopOutlined,
LinkOutlined,
MobileOutlined,
NotificationOutlined,
ThunderboltOutlined, ThunderboltOutlined,
} from '@ant-design/icons'; } from '@ant-design/icons';
import type { AllSetting } from '@/models/setting'; import type { AllSetting } from '@/models/setting';
import { SettingListItem } from '@/components/ui'; import { SettingListItem } from '@/components/ui';
import { buildHappPresetDeeplink, parseList, toBase64Utf8 } from './happPresets'; import { buildHappPresetDeeplink } from './happPresets';
import HappRoutingEditorModal from './HappRoutingEditorModal';
import { catTabLabel } from './catTabLabel'; import { catTabLabel } from './catTabLabel';
interface HappSettingsContentProps { interface HappSettingsContentProps {
@@ -21,7 +19,6 @@ interface HappSettingsContentProps {
updateSetting: (patch: Partial<AllSetting>) => void; updateSetting: (patch: Partial<AllSetting>) => void;
isMobile: boolean; isMobile: boolean;
remoteSourceBadge: (val: string) => React.ReactNode; remoteSourceBadge: (val: string) => React.ReactNode;
defaultActiveTab?: 'routing' | 'links';
} }
export default function HappSettingsContent({ export default function HappSettingsContent({
@@ -29,41 +26,22 @@ export default function HappSettingsContent({
updateSetting, updateSetting,
isMobile, isMobile,
remoteSourceBadge, remoteSourceBadge,
defaultActiveTab = 'routing',
}: HappSettingsContentProps) { }: HappSettingsContentProps) {
const { t } = useTranslation(); const { t } = useTranslation();
// Generator choices stay local until Apply updates the draft; page Save persists it.
const [selectedPreset, setSelectedPreset] = useState<string>('iran-bypass'); const [selectedPreset, setSelectedPreset] = useState<string>('iran-bypass');
const [includeAdblock, setIncludeAdblock] = useState(false);
const [isModalOpen, setIsModalOpen] = useState(false); const [isModalOpen, setIsModalOpen] = useState(false);
const [directDomains, setDirectDomains] = useState('');
const [proxyDomains, setProxyDomains] = useState('');
const [blockDomains, setBlockDomains] = useState('');
const [directIPs, setDirectIPs] = useState('');
const [proxyIPs, setProxyIPs] = useState('');
const [blockIPs, setBlockIPs] = useState('');
const applyPreset = () => { const applyPreset = () => {
const payload = buildHappPresetDeeplink(selectedPreset); const payload = buildHappPresetDeeplink(selectedPreset, includeAdblock);
if (payload) { if (payload) {
updateSetting({ subRoutingRules: payload }); updateSetting({ subRoutingRules: payload });
message.success(t('pages.settings.subHappPresetApplied')); message.success(t('pages.settings.subHappPresetApplied'));
} }
}; };
const handleBuildDeeplink = () => { const handleBuildDeeplink = (deeplink: string) => {
const profile = {
Name: 'Custom Rules',
GlobalProxy: 'true',
DirectSites: parseList(directDomains),
DirectIp: parseList(directIPs),
ProxySites: parseList(proxyDomains),
ProxyIp: parseList(proxyIPs),
BlockSites: parseList(blockDomains),
BlockIp: parseList(blockIPs),
DomainStrategy: 'IPIfNonMatch',
};
const deeplink = 'happ://routing/onadd/' + toBase64Utf8(JSON.stringify(profile));
updateSetting({ subRoutingRules: deeplink }); updateSetting({ subRoutingRules: deeplink });
setIsModalOpen(false); setIsModalOpen(false);
message.success(t('pages.settings.subHappDeeplinkGenerated')); message.success(t('pages.settings.subHappDeeplinkGenerated'));
@@ -82,17 +60,27 @@ export default function HappSettingsContent({
/> />
</SettingListItem> </SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.happLinkEnable')}
description={t('pages.settings.happLinkEnableDesc')}
>
<Switch
checked={allSetting.happLinkEnable}
onChange={(v) => updateSetting({ happLinkEnable: v })}
/>
</SettingListItem>
<Tabs <Tabs
type="card" type="card"
size="small" size="small"
defaultActiveKey={defaultActiveTab}
items={[ items={[
{ {
key: 'routing', key: 'routing',
label: ( label: catTabLabel(
<span> <BranchesOutlined />,
<BranchesOutlined /> {!isMobile && t('pages.settings.subHappGroupRouting')} t('pages.settings.subHappGroupRouting'),
</span> isMobile,
), ),
children: ( children: (
<> <>
@@ -112,21 +100,31 @@ export default function HappSettingsContent({
title={t('pages.settings.subHappPresets')} title={t('pages.settings.subHappPresets')}
description={t('pages.settings.subHappPresetsDesc')} description={t('pages.settings.subHappPresetsDesc')}
> >
<Space orientation="horizontal" style={{ width: '100%' }}> <Space orientation="horizontal" wrap style={{ width: '100%' }}>
<Select <Select
aria-label={t('pages.settings.subHappPresets')}
value={selectedPreset} value={selectedPreset}
style={{ minWidth: 170 }} style={{ minWidth: 170 }}
onChange={setSelectedPreset} onChange={setSelectedPreset}
options={[ options={[
{ value: 'iran-bypass', label: t('pages.settings.subHappPresetIran') }, { value: 'iran-bypass', label: t('pages.settings.subHappPresetIran') },
{ value: 'china-direct', label: t('pages.settings.subHappPresetChina') }, { value: 'china-direct', label: t('pages.settings.subHappPresetChina') },
{ value: 'adblock', label: t('pages.settings.subHappPresetAdblock') },
{ value: 'global', label: t('pages.settings.subHappPresetGlobal') }, { value: 'global', label: t('pages.settings.subHappPresetGlobal') },
{ value: 'lan-bypass', label: t('pages.settings.subHappPresetLocal') },
{ value: 'off', label: t('pages.settings.subHappPresetOff') }, { value: 'off', label: t('pages.settings.subHappPresetOff') },
]} ]}
/> />
<Space size="small">
<Switch
aria-label={t('pages.settings.subHappIncludeAdblock')}
checked={includeAdblock}
disabled={selectedPreset === 'off'}
onChange={setIncludeAdblock}
/>
<span>{t('pages.settings.subHappIncludeAdblock')}</span>
</Space>
<Button type="primary" onClick={applyPreset}> <Button type="primary" onClick={applyPreset}>
{t('pages.settings.subHappPresets')} {t('pages.settings.subHappApplyPreset')}
</Button> </Button>
</Space> </Space>
</SettingListItem> </SettingListItem>
@@ -180,27 +178,11 @@ export default function HappSettingsContent({
), ),
}, },
{ {
key: 'links', key: 'appearance',
label: catTabLabel(<LinkOutlined />, t('pages.settings.subHappGroupLinks'), isMobile), label: catTabLabel(
children: ( <DesktopOutlined />,
<SettingListItem t('pages.settings.subHappGroupThemes'),
paddings="small" isMobile,
title={t('pages.settings.happLinkEnable')}
description={t('pages.settings.happLinkEnableDesc')}
>
<Switch
checked={allSetting.happLinkEnable}
onChange={(v) => updateSetting({ happLinkEnable: v })}
/>
</SettingListItem>
),
},
{
key: 'banners',
label: (
<span>
<NotificationOutlined /> {!isMobile && t('pages.settings.subHappGroupBanners')}
</span>
), ),
children: ( children: (
<> <>
@@ -292,15 +274,59 @@ export default function HappSettingsContent({
onChange={(v) => updateSetting({ subHappNotificationExpire: v })} onChange={(v) => updateSetting({ subHappNotificationExpire: v })}
/> />
</SettingListItem> </SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subHappColorProfile')}
description={t('pages.settings.subHappColorProfileDesc')}
>
<Space orientation="vertical" style={{ width: '100%' }}>
<Input
value={allSetting.subHappColorProfile}
placeholder='{"serverRowBackgroundColor":"#21003D67"} or resetcolors'
onChange={(e) => updateSetting({ subHappColorProfile: e.target.value })}
/>
<Space wrap size="small">
<Button
size="small"
onClick={() => updateSetting({ subHappColorProfile: 'resetcolors' })}
>
{t('reset')}
</Button>
<Button
size="small"
onClick={() =>
updateSetting({
subHappColorProfile:
'{"serverRowBackgroundColor":"#21003D67","cardBackgroundColor":"#120023B3"}',
})
}
>
Violet
</Button>
<Button
size="small"
onClick={() =>
updateSetting({
subHappColorProfile:
'{"serverRowBackgroundColor":"#002B3667","cardBackgroundColor":"#001F27B3"}',
})
}
>
Turquoise
</Button>
</Space>
</Space>
</SettingListItem>
</> </>
), ),
}, },
{ {
key: 'network', key: 'network',
label: ( label: catTabLabel(
<span> <ThunderboltOutlined />,
<ThunderboltOutlined /> {!isMobile && t('pages.settings.subHappGroupNetwork')} t('pages.settings.subHappGroupNetwork'),
</span> isMobile,
), ),
children: ( children: (
<> <>
@@ -382,6 +408,23 @@ export default function HappSettingsContent({
/> />
</SettingListItem> </SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subHappLocalProxyAuth')}
description={t('pages.settings.subHappLocalProxyAuthDesc')}
>
<Select
value={allSetting.subHappLocalProxyAuth ?? 'auto'}
style={{ width: '100%' }}
onChange={(v) => updateSetting({ subHappLocalProxyAuth: v })}
options={[
{ value: 'auto', label: t('pages.settings.subHappLocalProxyAuthAuto') },
{ value: 'disable', label: t('pages.settings.subHappLocalProxyAuthDisable') },
{ value: '', label: t('pages.settings.subHappLocalProxyAuthUnset') },
]}
/>
</SettingListItem>
<SettingListItem <SettingListItem
paddings="small" paddings="small"
title={t('pages.settings.subHappAutoConnect')} title={t('pages.settings.subHappAutoConnect')}
@@ -412,70 +455,45 @@ export default function HappSettingsContent({
]} ]}
/> />
</SettingListItem> </SettingListItem>
</>
),
},
{
key: 'themes',
label: (
<span>
<DesktopOutlined /> {!isMobile && t('pages.settings.subHappGroupThemes')}
</span>
),
children: (
<>
<SettingListItem <SettingListItem
paddings="small" paddings="small"
title={t('pages.settings.subHappColorProfile')} title={t('pages.settings.subHappPerAppMode')}
description={t('pages.settings.subHappColorProfileDesc')} description={t('pages.settings.subHappPerAppModeDesc')}
> >
<Space orientation="vertical" style={{ width: '100%' }}> <Select
<Input value={allSetting.subHappPerAppMode || 'off'}
value={allSetting.subHappColorProfile} style={{ width: '100%' }}
placeholder='{"serverRowBackgroundColor":"#21003D67"} or resetcolors' onChange={(v) => updateSetting({ subHappPerAppMode: v })}
onChange={(e) => updateSetting({ subHappColorProfile: e.target.value })} options={[
{ value: 'off', label: t('pages.settings.subHappPerAppOff') },
{ value: 'on', label: t('pages.settings.subHappPerAppOn') },
{ value: 'bypass', label: t('pages.settings.subHappPerAppBypass') },
]}
/> />
<Space wrap size="small"> </SettingListItem>
<Button
size="small" <SettingListItem
onClick={() => updateSetting({ subHappColorProfile: 'resetcolors' })} paddings="small"
title={t('pages.settings.subHappPerAppList')}
description={t('pages.settings.subHappPerAppListDesc')}
> >
{t('reset')} <Input.TextArea
</Button> value={allSetting.subHappPerAppList}
<Button rows={4}
size="small" placeholder="org.telegram.messenger, com.google.android.youtube"
onClick={() => onChange={(e) => updateSetting({ subHappPerAppList: e.target.value })}
updateSetting({ />
subHappColorProfile:
'{"serverRowBackgroundColor":"#21003D67","cardBackgroundColor":"#120023B3"}',
})
}
>
Violet
</Button>
<Button
size="small"
onClick={() =>
updateSetting({
subHappColorProfile:
'{"serverRowBackgroundColor":"#002B3667","cardBackgroundColor":"#001F27B3"}',
})
}
>
Turquoise
</Button>
</Space>
</Space>
</SettingListItem> </SettingListItem>
</> </>
), ),
}, },
{ {
key: 'failover', key: 'failover',
label: ( label: catTabLabel(
<span> <CloudSyncOutlined />,
<CloudSyncOutlined /> {!isMobile && t('pages.settings.subHappGroupFailover')} t('pages.settings.subHappGroupFailover'),
</span> isMobile,
), ),
children: ( children: (
<> <>
@@ -528,127 +546,17 @@ export default function HappSettingsContent({
</> </>
), ),
}, },
{
key: 'android',
label: (
<span>
<MobileOutlined /> {!isMobile && t('pages.settings.subHappGroupAndroid')}
</span>
),
children: (
<>
<SettingListItem
paddings="small"
title={t('pages.settings.subHappPerAppMode')}
description={t('pages.settings.subHappPerAppModeDesc')}
>
<Select
value={allSetting.subHappPerAppMode || 'off'}
style={{ width: '100%' }}
onChange={(v) => updateSetting({ subHappPerAppMode: v })}
options={[
{ value: 'off', label: t('pages.settings.subHappPerAppOff') },
{ value: 'on', label: t('pages.settings.subHappPerAppOn') },
{ value: 'bypass', label: t('pages.settings.subHappPerAppBypass') },
]}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subHappPerAppList')}
description={t('pages.settings.subHappPerAppListDesc')}
>
<Input.TextArea
value={allSetting.subHappPerAppList}
rows={4}
placeholder="org.telegram.messenger, com.google.android.youtube"
onChange={(e) => updateSetting({ subHappPerAppList: e.target.value })}
/>
</SettingListItem>
</>
),
},
]} ]}
/> />
<Modal {/* Mount per opening so canceled edits are discarded and the latest parent draft is loaded. */}
title={t('pages.settings.subHappModalTitle')} {isModalOpen ? (
open={isModalOpen} <HappRoutingEditorModal
input={allSetting.subRoutingRules}
onCancel={() => setIsModalOpen(false)} onCancel={() => setIsModalOpen(false)}
onOk={handleBuildDeeplink} onGenerate={handleBuildDeeplink}
okText={t('pages.settings.subHappBuildDeeplink')}
width={650}
>
<Space orientation="vertical" style={{ width: '100%', marginTop: 12 }} size="middle">
<div>
<div style={{ fontWeight: 600, marginBottom: 4 }}>
{t('pages.settings.subHappDirectDomains')}
</div>
<Input.TextArea
rows={2}
value={directDomains}
placeholder="domain:ir, domain:cn, example.local"
onChange={(e) => setDirectDomains(e.target.value)}
/> />
</div> ) : null}
<div>
<div style={{ fontWeight: 600, marginBottom: 4 }}>
{t('pages.settings.subHappProxyDomains')}
</div>
<Input.TextArea
rows={2}
value={proxyDomains}
placeholder="geosite:google, youtube.com"
onChange={(e) => setProxyDomains(e.target.value)}
/>
</div>
<div>
<div style={{ fontWeight: 600, marginBottom: 4 }}>
{t('pages.settings.subHappBlockDomains')}
</div>
<Input.TextArea
rows={2}
value={blockDomains}
placeholder="geosite:category-ads-all, analytics.google.com"
onChange={(e) => setBlockDomains(e.target.value)}
/>
</div>
<div>
<div style={{ fontWeight: 600, marginBottom: 4 }}>
{t('pages.settings.subHappDirectIPs')}
</div>
<Input.TextArea
rows={2}
value={directIPs}
placeholder="geoip:ir, 192.168.0.0/16, 10.0.0.0/8"
onChange={(e) => setDirectIPs(e.target.value)}
/>
</div>
<div>
<div style={{ fontWeight: 600, marginBottom: 4 }}>
{t('pages.settings.subHappProxyIPs')}
</div>
<Input.TextArea
rows={2}
value={proxyIPs}
placeholder="1.1.1.1/32, 8.8.8.8/32"
onChange={(e) => setProxyIPs(e.target.value)}
/>
</div>
<div>
<div style={{ fontWeight: 600, marginBottom: 4 }}>
{t('pages.settings.subHappBlockIPs')}
</div>
<Input.TextArea
rows={2}
value={blockIPs}
placeholder="geoip:phishing, 0.0.0.0/8"
onChange={(e) => setBlockIPs(e.target.value)}
/>
</div>
</Space>
</Modal>
</> </>
); );
} }
@@ -0,0 +1,488 @@
import { useTranslation } from 'react-i18next';
import { Input, Select, Switch, Tabs } from 'antd';
import {
AppstoreOutlined,
BranchesOutlined,
NotificationOutlined,
SafetyOutlined,
ThunderboltOutlined,
} from '@ant-design/icons';
import type { AllSetting } from '@/models/setting';
import { SettingListItem } from '@/components/ui';
import { catTabLabel } from './catTabLabel';
interface IncySettingsContentProps {
allSetting: AllSetting;
updateSetting: (patch: Partial<AllSetting>) => void;
isMobile: boolean;
remoteSourceBadge: (val: string) => React.ReactNode;
}
// Incy documents every switch as `1`/`0`; an empty value omits the header so
// the subscriber's own app choice wins.
const onOff = (t: (key: string) => string) => [
{ value: '', label: t('pages.settings.subIncyNotSet') },
{ value: '1', label: t('pages.settings.subIncyOn') },
{ value: '0', label: t('pages.settings.subIncyOff') },
];
export default function IncySettingsContent({
allSetting,
updateSetting,
isMobile,
remoteSourceBadge,
}: IncySettingsContentProps) {
const { t } = useTranslation();
return (
<>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyAppAutoDetect')}
description={t('pages.settings.subIncyAppAutoDetectDesc')}
>
<Switch
checked={allSetting.subIncyAppAutoDetect}
onChange={(v) => updateSetting({ subIncyAppAutoDetect: v })}
/>
</SettingListItem>
<Tabs
type="card"
size="small"
items={[
{
key: 'app',
label: catTabLabel(<AppstoreOutlined />, t('pages.settings.subIncyGroupApp'), isMobile),
children: (
<>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyProfileDescription')}
description={t('pages.settings.subIncyProfileDescriptionDesc')}
>
<Input
value={allSetting.subIncyProfileDescription}
maxLength={200}
onChange={(e) => updateSetting({ subIncyProfileDescription: e.target.value })}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncySortOrder')}
description={t('pages.settings.subIncySortOrderDesc')}
>
<Select
value={allSetting.subIncySortOrder}
style={{ width: '100%' }}
onChange={(v) => updateSetting({ subIncySortOrder: v })}
options={[
{ value: '', label: t('pages.settings.subIncyNotSet') },
{ value: 'none', label: t('pages.settings.subIncySortNone') },
{ value: 'ping', label: t('pages.settings.subIncySortPing') },
{ value: 'name', label: t('pages.settings.subIncySortName') },
]}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncySupportEmail')}
description={t('pages.settings.subIncySupportEmailDesc')}
>
<Input
value={allSetting.subIncySupportEmail}
placeholder="support@example.com"
onChange={(e) => updateSetting({ subIncySupportEmail: e.target.value })}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyAnnounceUrl')}
description={t('pages.settings.subIncyAnnounceUrlDesc')}
>
<Input
value={allSetting.subIncyAnnounceUrl}
placeholder="https://t.me/your_channel"
onChange={(e) => updateSetting({ subIncyAnnounceUrl: e.target.value })}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyPremiumUrl')}
description={t('pages.settings.subIncyPremiumUrlDesc')}
>
<Input
value={allSetting.subIncyPremiumUrl}
placeholder="https://example.com/buy"
onChange={(e) => updateSetting({ subIncyPremiumUrl: e.target.value })}
/>
</SettingListItem>
</>
),
},
{
key: 'banners',
label: catTabLabel(
<NotificationOutlined />,
t('pages.settings.subIncyGroupBanners'),
isMobile,
),
children: (
<>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyBannerText')}
description={t('pages.settings.subIncyBannerTextDesc')}
>
<Input
value={allSetting.subIncyBannerText}
onChange={(e) => updateSetting({ subIncyBannerText: e.target.value })}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyBannerButtonText')}
description={t('pages.settings.subIncyBannerButtonTextDesc')}
>
<Input
value={allSetting.subIncyBannerButtonText}
onChange={(e) => updateSetting({ subIncyBannerButtonText: e.target.value })}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyBannerButtonUrl')}
description={t('pages.settings.subIncyBannerButtonUrlDesc')}
>
<Input
value={allSetting.subIncyBannerButtonUrl}
placeholder="https://example.com/sale"
onChange={(e) => updateSetting({ subIncyBannerButtonUrl: e.target.value })}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyBannerBgColor')}
description={t('pages.settings.subIncyBannerBgColorDesc')}
>
<Input
value={allSetting.subIncyBannerBgColor}
placeholder="#E53E3E"
onChange={(e) => updateSetting({ subIncyBannerBgColor: e.target.value })}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyBannerButtonColor')}
description={t('pages.settings.subIncyBannerButtonColorDesc')}
>
<Input
value={allSetting.subIncyBannerButtonColor}
placeholder="#38A169"
onChange={(e) => updateSetting({ subIncyBannerButtonColor: e.target.value })}
/>
</SettingListItem>
</>
),
},
{
key: 'privacy',
label: catTabLabel(
<SafetyOutlined />,
t('pages.settings.subIncyGroupPrivacy'),
isMobile,
),
children: (
<>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyHideUrl')}
description={t('pages.settings.subIncyHideUrlDesc')}
>
<Select
value={allSetting.subIncyHideUrl}
style={{ width: '100%' }}
onChange={(v) => updateSetting({ subIncyHideUrl: v })}
options={onOff(t)}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyHideCheck')}
description={t('pages.settings.subIncyHideCheckDesc')}
>
<Select
value={allSetting.subIncyHideCheck}
style={{ width: '100%' }}
onChange={(v) => updateSetting({ subIncyHideCheck: v })}
options={onOff(t)}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyNoLimit')}
description={t('pages.settings.subIncyNoLimitDesc')}
>
<Select
value={allSetting.subIncyNoLimitEnabled}
style={{ width: '100%' }}
onChange={(v) => updateSetting({ subIncyNoLimitEnabled: v })}
options={onOff(t)}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyPerAppEnable')}
description={t('pages.settings.subIncyPerAppEnableDesc')}
>
<Select
value={allSetting.subIncyPerAppEnable}
style={{ width: '100%' }}
onChange={(v) => updateSetting({ subIncyPerAppEnable: v })}
options={onOff(t)}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyPerAppMode')}
description={t('pages.settings.subIncyPerAppModeDesc')}
>
<Select
value={allSetting.subIncyPerAppMode}
style={{ width: '100%' }}
onChange={(v) => updateSetting({ subIncyPerAppMode: v })}
options={[
{ value: '', label: t('pages.settings.subIncyNotSet') },
{ value: 'proxy', label: t('pages.settings.subIncyPerAppModeProxy') },
{ value: 'bypass', label: t('pages.settings.subIncyPerAppModeBypass') },
]}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyPerAppList')}
description={t('pages.settings.subIncyPerAppListDesc')}
>
<Input.TextArea
value={allSetting.subIncyPerAppList}
rows={4}
placeholder={
'com.google.chrome\norg.telegram.messenger\n\nor https://.../apps.txt'
}
onChange={(e) => updateSetting({ subIncyPerAppList: e.target.value })}
/>
</SettingListItem>
</>
),
},
{
key: 'network',
label: catTabLabel(
<ThunderboltOutlined />,
t('pages.settings.subIncyGroupNetwork'),
isMobile,
),
children: (
<>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyFragmentationEnable')}
description={t('pages.settings.subIncyFragmentationEnableDesc')}
>
<Select
value={allSetting.subIncyFragmentationEnable}
style={{ width: '100%' }}
onChange={(v) => updateSetting({ subIncyFragmentationEnable: v })}
options={onOff(t)}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyFragmentLength')}
description={t('pages.settings.subIncyFragmentLengthDesc')}
>
<Input
value={allSetting.subIncyFragmentLength}
placeholder="10-30"
onChange={(e) => updateSetting({ subIncyFragmentLength: e.target.value })}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyFragmentInterval')}
description={t('pages.settings.subIncyFragmentIntervalDesc')}
>
<Input
value={allSetting.subIncyFragmentInterval}
placeholder="20-40"
onChange={(e) => updateSetting({ subIncyFragmentInterval: e.target.value })}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyFragmentPackets')}
description={t('pages.settings.subIncyFragmentPacketsDesc')}
>
<Select
value={allSetting.subIncyFragmentPackets}
style={{ width: '100%' }}
onChange={(v) => updateSetting({ subIncyFragmentPackets: v })}
options={[
{ value: '', label: t('pages.settings.subIncyNotSet') },
{ value: 'tlshello', label: 'tlshello' },
{ value: '1-3', label: '1-3' },
{ value: '1', label: '1' },
{ value: 'all', label: 'all' },
]}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyNoisesEnable')}
description={t('pages.settings.subIncyNoisesEnableDesc')}
>
<Select
value={allSetting.subIncyNoisesEnable}
style={{ width: '100%' }}
onChange={(v) => updateSetting({ subIncyNoisesEnable: v })}
options={onOff(t)}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyNoisesType')}
description={t('pages.settings.subIncyNoisesTypeDesc')}
>
<Select
value={allSetting.subIncyNoisesType}
style={{ width: '100%' }}
onChange={(v) => updateSetting({ subIncyNoisesType: v })}
options={[
{ value: '', label: t('pages.settings.subIncyNotSet') },
{ value: 'rand', label: 'rand' },
{ value: 'str', label: 'str' },
{ value: 'hex', label: 'hex' },
]}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyNoisesPacket')}
description={t('pages.settings.subIncyNoisesPacketDesc')}
>
<Input
value={allSetting.subIncyNoisesPacket}
placeholder="10-20"
onChange={(e) => updateSetting({ subIncyNoisesPacket: e.target.value })}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyNoisesDelay')}
description={t('pages.settings.subIncyNoisesDelayDesc')}
>
<Input
value={allSetting.subIncyNoisesDelay}
placeholder="10-50"
onChange={(e) => updateSetting({ subIncyNoisesDelay: e.target.value })}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyResolveEnable')}
description={t('pages.settings.subIncyResolveEnableDesc')}
>
<Select
value={allSetting.subIncyResolveEnable}
style={{ width: '100%' }}
onChange={(v) => updateSetting({ subIncyResolveEnable: v })}
options={onOff(t)}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyResolveDnsDomain')}
description={t('pages.settings.subIncyResolveDnsDomainDesc')}
>
<Input
value={allSetting.subIncyResolveDnsDomain}
placeholder="https://common.dot.dns.yandex.net/dns-query"
onChange={(e) => updateSetting({ subIncyResolveDnsDomain: e.target.value })}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyResolveDnsIp')}
description={t('pages.settings.subIncyResolveDnsIpDesc')}
>
<Input
value={allSetting.subIncyResolveDnsIp}
placeholder="77.88.8.8"
onChange={(e) => updateSetting({ subIncyResolveDnsIp: e.target.value })}
/>
</SettingListItem>
</>
),
},
{
key: 'routing',
label: catTabLabel(
<BranchesOutlined />,
t('pages.settings.subIncyGroupRouting'),
isMobile,
),
children: (
<>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyEnableRouting')}
description={t('pages.settings.subIncyEnableRoutingDesc')}
>
<Switch
checked={allSetting.subIncyEnableRouting}
onChange={(v) => updateSetting({ subIncyEnableRouting: v })}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyRoutingRules')}
badge={remoteSourceBadge(allSetting.subIncyRoutingRules)}
description={t('pages.settings.subIncyRoutingRulesDesc')}
>
<Input.TextArea
value={allSetting.subIncyRoutingRules}
placeholder="incy://routing/onadd/... or https://.../DEFAULT.JSON"
onChange={(e) => updateSetting({ subIncyRoutingRules: e.target.value })}
/>
</SettingListItem>
</>
),
},
]}
/>
</>
);
}
@@ -19,6 +19,7 @@ import { useMediaQuery } from '@/hooks/useMediaQuery';
import { catTabLabel } from './catTabLabel'; import { catTabLabel } from './catTabLabel';
import { sanitizePath, normalizePath } from './uriPath'; import { sanitizePath, normalizePath } from './uriPath';
import HappSettingsContent from './HappSettingsContent'; import HappSettingsContent from './HappSettingsContent';
import IncySettingsContent from './IncySettingsContent';
import { remoteSourceBadge } from './subscriptionShared'; import { remoteSourceBadge } from './subscriptionShared';
interface SubscriptionGeneralTabProps { interface SubscriptionGeneralTabProps {
@@ -247,6 +248,26 @@ export default function SubscriptionGeneralTab({
onChange={onNumber((v) => updateSetting({ subUpdates: v }))} onChange={onNumber((v) => updateSetting({ subUpdates: v }))}
/> />
</SettingListItem> </SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.externalSubUserAgent')}
badge={
<DefaultSettingTag
settingKey="externalSubUserAgent"
value={allSetting.externalSubUserAgent}
/>
}
description={t('pages.settings.externalSubUserAgentDesc')}
>
<Input
value={allSetting.externalSubUserAgent}
placeholder="v2rayNG/1.8.5"
maxLength={512}
allowClear
onChange={(e) => updateSetting({ externalSubUserAgent: e.target.value })}
/>
</SettingListItem>
</> </>
), ),
}, },
@@ -393,8 +414,6 @@ export default function SubscriptionGeneralTab({
updateSetting={updateSetting} updateSetting={updateSetting}
isMobile={isMobile} isMobile={isMobile}
remoteSourceBadge={remoteSourceBadge} remoteSourceBadge={remoteSourceBadge}
// QR settings links select the link control; ordinary Happ visits still start on routing.
defaultActiveTab={searchParams.get('happTab') === 'links' ? 'links' : 'routing'}
/> />
), ),
}, },
@@ -435,30 +454,12 @@ export default function SubscriptionGeneralTab({
key: '7', key: '7',
label: catTabLabel(<CompassOutlined />, 'Incy', isMobile), label: catTabLabel(<CompassOutlined />, 'Incy', isMobile),
children: ( children: (
<> <IncySettingsContent
<SettingListItem allSetting={allSetting}
paddings="small" updateSetting={updateSetting}
title={t('pages.settings.subIncyEnableRouting')} isMobile={isMobile}
description={t('pages.settings.subIncyEnableRoutingDesc')} remoteSourceBadge={remoteSourceBadge}
>
<Switch
checked={allSetting.subIncyEnableRouting}
onChange={(v) => updateSetting({ subIncyEnableRouting: v })}
/> />
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subIncyRoutingRules')}
badge={remoteSourceBadge(allSetting.subIncyRoutingRules)}
description={t('pages.settings.subIncyRoutingRulesDesc')}
>
<Input.TextArea
value={allSetting.subIncyRoutingRules}
placeholder="incy://routing/onadd/... or https://.../DEFAULT.JSON"
onChange={(e) => updateSetting({ subIncyRoutingRules: e.target.value })}
/>
</SettingListItem>
</>
), ),
}, },
]} ]}
+64 -34
View File
@@ -7,16 +7,11 @@ export function toBase64Utf8(str: string): string {
); );
} }
// Splits multiline or comma-separated string into clean unique token arrays.
export function parseList(input: string): string[] {
return input
.split(/[\n,]+/)
.map((s) => s.trim())
.filter(Boolean);
}
// Build standard Happ routing deeplink or special state for curated presets. // Build standard Happ routing deeplink or special state for curated presets.
export function buildHappPresetDeeplink(preset: string): string { export function buildHappPresetDeeplink(preset: string, includeAdblock = false): string {
// Ad blocking is opt-in for each generated profile, independent of the base routing rules.
const blockSites = includeAdblock ? ['geosite:category-ads-all'] : [];
switch (preset) { switch (preset) {
case 'off': case 'off':
return 'happ://routing/off'; return 'happ://routing/off';
@@ -27,9 +22,20 @@ export function buildHappPresetDeeplink(preset: string): string {
JSON.stringify({ JSON.stringify({
Name: 'Iran Bypass', Name: 'Iran Bypass',
GlobalProxy: 'true', GlobalProxy: 'true',
DirectSites: ['domain:ir', 'regexp:.*\\.ir$'], RouteOrder: 'block-proxy-direct',
DirectIp: ['geoip:ir', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16'], DirectSites: ['geosite:private', 'domain:ir', 'geosite:category-ir'],
BlockSites: ['geosite:category-ads-all'], DirectIp: [
'geoip:ir',
'geoip:private',
'127.0.0.0/8',
'10.0.0.0/8',
'172.16.0.0/12',
'192.168.0.0/16',
'169.254.0.0/16',
'224.0.0.0/4',
'255.255.255.255',
],
BlockSites: blockSites,
BlockIp: [], BlockIp: [],
ProxySites: [], ProxySites: [],
ProxyIp: [], ProxyIp: [],
@@ -42,32 +48,38 @@ export function buildHappPresetDeeplink(preset: string): string {
'happ://routing/onadd/' + 'happ://routing/onadd/' +
toBase64Utf8( toBase64Utf8(
JSON.stringify({ JSON.stringify({
Name: 'China Direct', Name: 'Bypass-CN',
GlobalProxy: 'true', GlobalProxy: 'true',
DirectSites: ['geosite:cn', 'geosite:geolocation-cn'], RouteOrder: 'block-proxy-direct',
DirectIp: ['geoip:cn', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16'], RemoteDNSType: 'DoH',
BlockSites: ['geosite:category-ads-all'], RemoteDNSDomain: 'https://cloudflare-dns.com/dns-query',
BlockIp: [], RemoteDNSIP: '1.1.1.1',
DomesticDNSType: 'DoH',
DomesticDNSDomain: 'https://dns.alidns.com/dns-query',
DomesticDNSIP: '223.5.5.5',
DnsHosts: {
'cloudflare-dns.com': '1.1.1.1',
'dns.alidns.com': '223.5.5.5',
},
DirectSites: ['geosite:private', 'geosite:cn', 'geosite:geolocation-cn'],
DirectIp: [
'geoip:cn',
'geoip:private',
'127.0.0.0/8',
'10.0.0.0/8',
'172.16.0.0/12',
'192.168.0.0/16',
'169.254.0.0/16',
'224.0.0.0/4',
'255.255.255.255',
],
ProxySites: [], ProxySites: [],
ProxyIp: [], ProxyIp: [],
DomainStrategy: 'IPIfNonMatch', BlockSites: blockSites,
}),
)
);
case 'adblock':
return (
'happ://routing/onadd/' +
toBase64Utf8(
JSON.stringify({
Name: 'AdBlock',
GlobalProxy: 'true',
DirectSites: [],
DirectIp: ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16'],
BlockSites: ['geosite:category-ads-all'],
BlockIp: [], BlockIp: [],
ProxySites: [],
ProxyIp: [],
DomainStrategy: 'IPIfNonMatch', DomainStrategy: 'IPIfNonMatch',
FakeDNS: 'false',
UseChunkFiles: 'true',
}), }),
) )
); );
@@ -80,7 +92,25 @@ export function buildHappPresetDeeplink(preset: string): string {
GlobalProxy: 'true', GlobalProxy: 'true',
DirectSites: [], DirectSites: [],
DirectIp: [], DirectIp: [],
BlockSites: [], BlockSites: blockSites,
BlockIp: [],
ProxySites: [],
ProxyIp: [],
DomainStrategy: 'AsIs',
}),
)
);
// LAN bypass has its own identity so applying it does not overwrite the Global profile.
case 'lan-bypass':
return (
'happ://routing/onadd/' +
toBase64Utf8(
JSON.stringify({
Name: 'Global Bypass Local Network',
GlobalProxy: 'true',
DirectSites: ['geosite:private'],
DirectIp: ['geoip:private'],
BlockSites: blockSites,
BlockIp: [], BlockIp: [],
ProxySites: [], ProxySites: [],
ProxyIp: [], ProxyIp: [],
@@ -0,0 +1,90 @@
import { HappRoutingProfileSchema, type HappRoutingProfile } from '@/schemas/happRouting';
import { toBase64Utf8 } from './happPresets';
import { isRemoteRoutingSource } from './subscriptionShared';
export type HappRoutingMode = 'add' | 'onadd';
export type HappRoutingListKey =
| 'DirectSites'
| 'DirectIp'
| 'ProxySites'
| 'ProxyIp'
| 'BlockSites'
| 'BlockIp';
export type HappRoutingLoadResult =
| { success: true; profile: HappRoutingProfile; mode: HappRoutingMode; isNew: boolean }
| { success: false; error: 'off' | 'remote' | 'invalid' };
export function parseHappRoutingJson(input: string): HappRoutingProfile | null {
try {
const value: unknown = JSON.parse(input);
const result = HappRoutingProfileSchema.safeParse(value);
// Keep the validated input object; schema output can discard some unknown extension keys.
return result.success ? (value as HappRoutingProfile) : null;
} catch {
return null;
}
}
export function loadHappRouting(input: string): HappRoutingLoadResult {
const source = input.trim();
if (!source) {
return {
success: true,
profile: {
Name: 'Custom Rules',
GlobalProxy: 'true',
DirectSites: [],
DirectIp: [],
ProxySites: [],
ProxyIp: [],
BlockSites: [],
BlockIp: [],
DomainStrategy: 'IPIfNonMatch',
},
mode: 'onadd',
isNew: true,
};
}
if (source === 'happ://routing/off') return { success: false, error: 'off' };
if (isRemoteRoutingSource(source)) return { success: false, error: 'remote' };
if (source.startsWith('{')) {
const profile = parseHappRoutingJson(source);
return profile
? { success: true, profile, mode: 'onadd', isNew: false }
: { success: false, error: 'invalid' };
}
const match = /^happ:\/\/routing\/(onadd|add)\/([A-Za-z0-9+/_-]+={0,2})$/.exec(source);
if (!match) return { success: false, error: 'invalid' };
try {
const binary = atob(match[2].replace(/-/g, '+').replace(/_/g, '/'));
// Decode UTF-8 strictly so malformed bytes cannot silently change profile names or rules.
const json = new TextDecoder('utf-8', { fatal: true }).decode(
Uint8Array.from(binary, (character) => character.charCodeAt(0)),
);
const profile = parseHappRoutingJson(json);
return profile
? { success: true, profile, mode: match[1] as HappRoutingMode, isNew: false }
: { success: false, error: 'invalid' };
} catch {
return { success: false, error: 'invalid' };
}
}
export function buildHappRoutingDeeplink(
profile: HappRoutingProfile,
mode: HappRoutingMode = 'onadd',
): string {
return `happ://routing/${mode}/` + toBase64Utf8(JSON.stringify(profile));
}
export function parseHappRoutingList(input: string): string[] {
// Commas can belong to regexp rules, so the editor uses one rule per line.
return input
.split(/\r?\n/)
.map((entry) => entry.trim())
.filter(Boolean);
}
@@ -0,0 +1,142 @@
.sponsors-page .ant-layout,
.sponsors-page .ant-layout-content,
.sponsors-page .content-shell {
background: transparent;
}
.sponsors-page .content-area {
padding: 24px;
}
.sponsors-inner {
max-width: 1200px;
}
.sponsors-header {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 16px;
margin-bottom: 24px;
}
.sponsors-page .sponsors-title {
margin: 0 0 4px;
}
.sponsors-title-icon {
color: #faad14;
}
.sponsors-page .sponsors-section-title {
margin: 32px 0 12px;
color: var(--ant-color-text-secondary);
font-weight: 600;
letter-spacing: 0.3px;
}
.sponsors-yourbrand {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 8px;
height: 100%;
min-height: 170px;
padding: 16px;
border: 1.5px dashed var(--ant-color-border);
border-radius: var(--ant-border-radius-lg, 8px);
background: transparent;
}
.sponsors-yourbrand.is-large {
align-items: center;
min-height: 0;
padding: 40px 24px;
text-align: center;
background: var(--bg-card, transparent);
}
.sponsors-yourbrand-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 56px;
height: 56px;
border-radius: 8px;
font-size: 22px;
color: var(--ant-color-primary);
background: var(--ant-color-primary-bg);
}
.sponsors-yourbrand-title {
font-weight: 600;
font-size: 15px;
color: var(--ant-color-text);
}
.sponsors-yourbrand-text {
max-width: 420px;
margin-bottom: 4px;
font-size: 13px;
color: var(--ant-color-text-secondary);
}
.sponsors-yourbrand:not(.is-large) .ant-btn {
margin-top: auto;
}
.sponsors-placement {
display: flex;
gap: 12px;
height: 100%;
padding: 14px 16px;
border: 1px solid var(--ant-color-border-secondary);
border-radius: var(--ant-border-radius-lg, 8px);
background: var(--bg-card, transparent);
}
.sponsors-placement-icon {
display: inline-flex;
flex: 0 0 auto;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
border-radius: 8px;
font-size: 17px;
color: var(--ant-color-primary);
background: var(--ant-color-primary-bg);
}
.sponsors-placement-title {
font-weight: 600;
color: var(--ant-color-text);
}
.sponsors-placement-body {
min-width: 0;
}
.sponsors-placement-status {
display: flex;
flex-wrap: wrap;
gap: 4px;
margin-top: 8px;
}
.sponsors-placement-status .ant-tag {
margin: 0;
}
.sponsors-placement-desc {
font-size: 13px;
color: var(--ant-color-text-secondary);
}
@media (max-width: 768px) {
.sponsors-page .content-area {
padding: 12px;
padding-top: 64px;
}
}
@@ -0,0 +1,176 @@
import { useMemo } from 'react';
import type { ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Col, ConfigProvider, Layout, Row, Spin, Tag, Typography } from 'antd';
import {
CrownOutlined,
DashboardOutlined,
LoginOutlined,
MenuUnfoldOutlined,
PlusOutlined,
} from '@ant-design/icons';
import { useTheme } from '@/hooks/useTheme';
import AppSidebar from '@/layouts/AppSidebar';
import { useSponsorsQuery } from '@/api/queries/useSponsorsQuery';
import SponsorCard from '@/components/sponsor/SponsorCard';
import { IntlUtil } from '@/utils';
import { useDatepicker } from '@/hooks/useDatepicker';
import { placementStatus, sponsorsForSlot, type SponsorSlot } from '@/lib/sponsors';
import './SponsorsPage.css';
function BecomeButton({ contact, block }: { contact?: string; block?: boolean }) {
const { t } = useTranslation();
if (!contact) return null;
return (
<Button
type="primary"
icon={<CrownOutlined />}
href={contact}
target="_blank"
rel="noopener noreferrer"
block={block}
>
{t('pages.sponsors.become')}
</Button>
);
}
function YourBrandCard({ contact, large }: { contact?: string; large?: boolean }) {
const { t } = useTranslation();
return (
<div className={`sponsors-yourbrand${large ? ' is-large' : ''}`}>
<span className="sponsors-yourbrand-icon">
<PlusOutlined />
</span>
<div className="sponsors-yourbrand-title">{t('pages.sponsors.yourBrand')}</div>
<div className="sponsors-yourbrand-text">{t('pages.sponsors.yourBrandText')}</div>
<BecomeButton contact={contact} />
</div>
);
}
export default function SponsorsPage() {
const { t } = useTranslation();
const { isDark, isUltra, antdThemeConfig } = useTheme();
const { data, fetched } = useSponsorsQuery();
const sponsors = sponsorsForSlot(data.sponsors, 'page');
const { datepicker } = useDatepicker();
const placements: { slot: SponsorSlot; icon: ReactNode; title: string; desc: string }[] = [
{
slot: 'dashboard',
icon: <DashboardOutlined />,
title: t('pages.sponsors.placementDashboard'),
desc: t('pages.sponsors.placementDashboardDesc'),
},
{
slot: 'sidebar',
icon: <MenuUnfoldOutlined />,
title: t('pages.sponsors.placementSidebar'),
desc: t('pages.sponsors.placementSidebarDesc'),
},
{
slot: 'login',
icon: <LoginOutlined />,
title: t('pages.sponsors.placementLogin'),
desc: t('pages.sponsors.placementLoginDesc'),
},
{
slot: 'page',
icon: <CrownOutlined />,
title: t('pages.sponsors.placementPage'),
desc: t('pages.sponsors.placementPageDesc'),
},
];
const pageClass = useMemo(() => {
const classes = ['sponsors-page'];
if (isDark) classes.push('is-dark');
if (isUltra) classes.push('is-ultra');
return classes.join(' ');
}, [isDark, isUltra]);
return (
<ConfigProvider theme={antdThemeConfig}>
<Layout className={pageClass}>
<AppSidebar />
<Layout className="content-shell">
<Layout.Content className="content-area">
<div className="sponsors-inner">
<div className="sponsors-header">
<div>
<Typography.Title level={3} className="sponsors-title">
<CrownOutlined className="sponsors-title-icon" /> {t('pages.sponsors.title')}
</Typography.Title>
<Typography.Text type="secondary">{t('pages.sponsors.intro')}</Typography.Text>
</div>
<BecomeButton contact={data.contact} />
</div>
<Spin spinning={!fetched} delay={200}>
{sponsors.length === 0 ? (
fetched && <YourBrandCard contact={data.contact} large />
) : (
<Row gutter={[16, 16]}>
{sponsors.map((sponsor) => (
<Col key={sponsor.id} xs={24} sm={12} xl={8}>
<SponsorCard sponsor={sponsor} variant="card" />
</Col>
))}
{data.contact && (
<Col xs={24} sm={12} xl={8}>
<YourBrandCard contact={data.contact} />
</Col>
)}
</Row>
)}
</Spin>
<Typography.Title level={5} className="sponsors-section-title">
{t('pages.sponsors.placements')}
</Typography.Title>
<Row gutter={[16, 16]}>
{placements.map((p) => {
const status = placementStatus(data.sponsors, p.slot);
return (
<Col key={p.slot} xs={24} sm={12} xl={6}>
<div className="sponsors-placement">
<span className="sponsors-placement-icon">{p.icon}</span>
<div className="sponsors-placement-body">
<div className="sponsors-placement-title">{p.title}</div>
<div className="sponsors-placement-desc">{p.desc}</div>
<div className="sponsors-placement-status">
{status.takenUntil ? (
<Tag color="orange">
{t('pages.sponsors.takenUntil', {
date: IntlUtil.formatDate(status.takenUntil, datepicker),
})}
</Tag>
) : (
<Tag color="green">{t('pages.sponsors.available')}</Tag>
)}
{status.count > 0 && !status.takenUntil && (
<Tag>
{t('pages.sponsors.activeCount', {
count:
status.capacity && status.capacity > 1
? `${status.count}/${status.capacity}`
: status.count,
})}
</Tag>
)}
</div>
</div>
</div>
</Col>
);
})}
</Row>
</div>
</Layout.Content>
</Layout>
</Layout>
</ConfigProvider>
);
}
@@ -70,15 +70,19 @@ export default function AmneziawgFields() {
<ObfNumber name="jc" label={t('pages.xray.amneziawg.jc')} min={0} /> <ObfNumber name="jc" label={t('pages.xray.amneziawg.jc')} min={0} />
<ObfNumber name="jmin" label={t('pages.xray.amneziawg.jmin')} min={0} /> <ObfNumber name="jmin" label={t('pages.xray.amneziawg.jmin')} min={0} />
<ObfNumber name="jmax" label={t('pages.xray.amneziawg.jmax')} min={0} /> <ObfNumber name="jmax" label={t('pages.xray.amneziawg.jmax')} min={0} />
<ObfNumber name="s1" label={t('pages.xray.amneziawg.s1')} min={0} /> <ObfNumber name="s1" label={t('pages.xray.amneziawg.s1')} min={0} max={65535} />
<ObfNumber name="s2" label={t('pages.xray.amneziawg.s2')} min={0} /> <ObfNumber name="s2" label={t('pages.xray.amneziawg.s2')} min={0} max={65535} />
<ObfNumber name="s3" label={t('pages.xray.amneziawg.s3')} min={0} max={64} /> <ObfNumber name="s3" label={t('pages.xray.amneziawg.s3')} min={0} max={65535} />
<ObfNumber name="s4" label={t('pages.xray.amneziawg.s4')} min={0} max={32} /> <ObfNumber name="s4" label={t('pages.xray.amneziawg.s4')} min={0} max={32} />
<ObfText name="h1" label={t('pages.xray.amneziawg.h1')} placeholder="100-800" /> <ObfText name="h1" label={t('pages.xray.amneziawg.h1')} placeholder="100-800" />
<ObfText name="h2" label={t('pages.xray.amneziawg.h2')} placeholder="900-1600" /> <ObfText name="h2" label={t('pages.xray.amneziawg.h2')} placeholder="900-1600" />
<ObfText name="h3" label={t('pages.xray.amneziawg.h3')} placeholder="1700-2400" /> <ObfText name="h3" label={t('pages.xray.amneziawg.h3')} placeholder="1700-2400" />
<ObfText name="h4" label={t('pages.xray.amneziawg.h4')} placeholder="2500-3200" /> <ObfText name="h4" label={t('pages.xray.amneziawg.h4')} placeholder="2500-3200" />
<ObfText name="i1" label={t('pages.xray.amneziawg.i1')} placeholder="<r 64>" /> <ObfText name="i1" label={t('pages.xray.amneziawg.i1')} placeholder="<r 64>" />
<ObfText name="i2" label={t('pages.xray.amneziawg.i2')} placeholder="<r 64>" />
<ObfText name="i3" label={t('pages.xray.amneziawg.i3')} placeholder="<r 64>" />
<ObfText name="i4" label={t('pages.xray.amneziawg.i4')} placeholder="<r 64>" />
<ObfText name="i5" label={t('pages.xray.amneziawg.i5')} placeholder="<r 64>" />
<ObfText <ObfText
name="contentPaddingAddition" name="contentPaddingAddition"
label={t('pages.xray.amneziawg.contentPaddingAddition')} label={t('pages.xray.amneziawg.contentPaddingAddition')}
@@ -86,6 +86,13 @@ const EMPTY: NordFormValues = {
serverId: null, serverId: null,
}; };
// antd warns on a null option value, so "All Cities" is a sentinel mapped back to null.
const ALL_CITIES = '__all__';
const allCitiesTransform = {
input: (value: unknown) => value ?? ALL_CITIES,
output: (value: unknown) => (value === ALL_CITIES ? null : value),
};
function loadLevel(load: number): 'low' | 'medium' | 'high' { function loadLevel(load: number): 'low' | 'medium' | 'high' {
if (load < 30) return 'low'; if (load < 30) return 'low';
if (load < 70) return 'medium'; if (load < 70) return 'medium';
@@ -452,12 +459,16 @@ export default function NordModal({
</FormField> </FormField>
{cities.length > 0 && ( {cities.length > 0 && (
<FormField name="cityId" label={t('pages.xray.outbound.city')}> <FormField
name="cityId"
label={t('pages.xray.outbound.city')}
transform={allCitiesTransform}
>
<Select <Select
data-testid="nord-city-select" data-testid="nord-city-select"
showSearch={{ optionFilterProp: 'label' }} showSearch={{ optionFilterProp: 'label' }}
options={[ options={[
{ value: null, label: t('pages.xray.outbound.allCities') }, { value: ALL_CITIES, label: t('pages.xray.outbound.allCities') },
...cities.map((c) => ({ value: c.id, label: c.name })), ...cities.map((c) => ({ value: c.id, label: c.name })),
]} ]}
/> />
+13 -2
View File
@@ -73,6 +73,13 @@ const EMPTY: PiaFormValues = {
hostname: null, hostname: null,
}; };
// antd warns on a null option value, so "All Regions" is a sentinel mapped back to null.
const ALL_REGIONS = '__all__';
const allRegionsTransform = {
input: (value: unknown) => value ?? ALL_REGIONS,
output: (value: unknown) => (value === ALL_REGIONS ? null : value),
};
function piaHostnameOf(outbound: PiaOutboundRow): string { function piaHostnameOf(outbound: PiaOutboundRow): string {
if (typeof outbound.piaHostname === 'string' && outbound.piaHostname.trim()) { if (typeof outbound.piaHostname === 'string' && outbound.piaHostname.trim()) {
return outbound.piaHostname.trim(); return outbound.piaHostname.trim();
@@ -389,12 +396,16 @@ export default function PiaModal({
</FormField> </FormField>
{regions.length > 0 && ( {regions.length > 0 && (
<FormField name="regionId" label={t('pages.xray.pia.region')}> <FormField
name="regionId"
label={t('pages.xray.pia.region')}
transform={allRegionsTransform}
>
<Select <Select
data-testid="pia-region-select" data-testid="pia-region-select"
showSearch={{ optionFilterProp: 'label' }} showSearch={{ optionFilterProp: 'label' }}
options={[ options={[
{ value: null, label: t('pages.xray.pia.allRegions') }, { value: ALL_REGIONS, label: t('pages.xray.pia.allRegions') },
...regions.map((r) => ({ value: r.id, label: r.name })), ...regions.map((r) => ({ value: r.id, label: r.name })),
]} ]}
/> />
+2
View File
@@ -13,6 +13,7 @@ const HostsPage = lazy(() => import('@/pages/hosts/HostsPage'));
const SettingsPage = lazy(() => import('@/pages/settings/SettingsPage')); const SettingsPage = lazy(() => import('@/pages/settings/SettingsPage'));
const XrayPage = lazy(() => import('@/pages/xray/XrayPage')); const XrayPage = lazy(() => import('@/pages/xray/XrayPage'));
const ApiDocsPage = lazy(() => import('@/pages/api-docs/ApiDocsPage')); const ApiDocsPage = lazy(() => import('@/pages/api-docs/ApiDocsPage'));
const SponsorsPage = lazy(() => import('@/pages/sponsors/SponsorsPage'));
function withSuspense(node: React.ReactNode) { function withSuspense(node: React.ReactNode) {
return ( return (
@@ -51,6 +52,7 @@ const routes: RouteObject[] = [
{ path: 'outbound', element: withSuspense(<XrayPage />) }, { path: 'outbound', element: withSuspense(<XrayPage />) },
{ path: 'routing', element: withSuspense(<XrayPage />) }, { path: 'routing', element: withSuspense(<XrayPage />) },
{ path: 'api-docs', element: withSuspense(<ApiDocsPage />) }, { path: 'api-docs', element: withSuspense(<ApiDocsPage />) },
{ path: 'sponsors', element: withSuspense(<SponsorsPage />) },
], ],
}, },
]; ];
+2
View File
@@ -35,6 +35,7 @@ export const HostFormSchema = z.object({
(val) => (val === '' ? undefined : val), (val) => (val === '' ? undefined : val),
UtlsFingerprintSchema.optional(), UtlsFingerprintSchema.optional(),
), ),
cipherSuites: z.string().default(''),
overrideSniFromAddress: z.boolean().default(false), overrideSniFromAddress: z.boolean().default(false),
keepSniBlank: z.boolean().default(false), keepSniBlank: z.boolean().default(false),
pinnedPeerCertSha256: z.array(z.string()).default([]), pinnedPeerCertSha256: z.array(z.string()).default([]),
@@ -87,6 +88,7 @@ export const HostRecordSchema = z
path: z.string().optional(), path: z.string().optional(),
alpn: z.array(z.string()).nullish(), alpn: z.array(z.string()).nullish(),
fingerprint: z.string().optional(), fingerprint: z.string().optional(),
cipherSuites: z.string().optional(),
overrideSniFromAddress: z.boolean().optional(), overrideSniFromAddress: z.boolean().optional(),
keepSniBlank: z.boolean().optional(), keepSniBlank: z.boolean().optional(),
pinnedPeerCertSha256: z.array(z.string()).nullish(), pinnedPeerCertSha256: z.array(z.string()).nullish(),
+5 -2
View File
@@ -41,6 +41,7 @@ export const ClientRecordSchema = z
enable: z.boolean().optional(), enable: z.boolean().optional(),
reset: z.number().optional(), reset: z.number().optional(),
resetDay: z.number().optional(), resetDay: z.number().optional(),
resetWeekday: z.number().optional(),
resetMax: z.number().optional(), resetMax: z.number().optional(),
trafficReset: z.string().optional(), trafficReset: z.string().optional(),
trafficResetDay: z.number().optional(), trafficResetDay: z.number().optional(),
@@ -328,6 +329,7 @@ export const ClientFormSchema = z.object({
delayedDays: z.number().int().min(0), delayedDays: z.number().int().min(0),
reset: z.number().int().min(0), reset: z.number().int().min(0),
resetDay: z.number().int().min(0).max(31), resetDay: z.number().int().min(0).max(31),
resetWeekday: z.number().int().min(0).max(7),
resetMax: z.number().int().min(0), resetMax: z.number().int().min(0),
trafficReset: z.enum(['never', 'hourly', 'daily', 'weekly', 'monthly']), trafficReset: z.enum(['never', 'hourly', 'daily', 'weekly', 'monthly']),
trafficResetDay: z.number().int().min(1).max(31), trafficResetDay: z.number().int().min(1).max(31),
@@ -360,7 +362,7 @@ export const ClientBulkAdjustFormSchema = z
(v.limitHwid !== undefined && v.limitHwid !== null) || (v.limitHwid !== undefined && v.limitHwid !== null) ||
(v.adTag !== undefined && v.adTag.trim() !== ''), (v.adTag !== undefined && v.adTag.trim() !== ''),
{ {
message: 'pages.clients.bulkAdjustNothing', error: 'pages.clients.bulkAdjustNothing',
}, },
) )
.refine( .refine(
@@ -370,7 +372,7 @@ export const ClientBulkAdjustFormSchema = z
return /^[0-9a-fA-F]{32}$/.test(tag); return /^[0-9a-fA-F]{32}$/.test(tag);
}, },
{ {
message: 'pages.inbounds.form.mtgAdTagInvalid', error: 'pages.inbounds.form.mtgAdTagInvalid',
path: ['adTag'], path: ['adTag'],
}, },
); );
@@ -392,6 +394,7 @@ export const ClientBulkAddFormSchema = z.object({
expiryTime: z.number(), expiryTime: z.number(),
reset: z.number().int().min(0), reset: z.number().int().min(0),
resetDay: z.number().int().min(0).max(31), resetDay: z.number().int().min(0).max(31),
resetWeekday: z.number().int().min(0).max(7),
resetMax: z.number().int().min(0), resetMax: z.number().int().min(0),
trafficReset: z.enum(['never', 'hourly', 'daily', 'weekly', 'monthly']).optional(), trafficReset: z.enum(['never', 'hourly', 'daily', 'weekly', 'monthly']).optional(),
trafficResetDay: z.number().int().min(1).max(31).optional(), trafficResetDay: z.number().int().min(1).max(31).optional(),
+2 -1
View File
@@ -52,7 +52,7 @@ const InboundTlsSettingsSchema = TlsStreamSettingsSchema.extend({
.array(InboundTlsCertSchema) .array(InboundTlsCertSchema)
.default([]) .default([])
.refine((certificates) => certificates.some((cert) => cert.usage !== 'verify'), { .refine((certificates) => certificates.some((cert) => cert.usage !== 'verify'), {
message: 'pages.inbounds.form.tlsServerCertificateRequired', error: 'pages.inbounds.form.tlsServerCertificateRequired',
}), }),
}); });
@@ -81,6 +81,7 @@ export const InboundDbFieldsSchema = z.object({
shareAddrStrategy: ShareAddrStrategySchema.default('node'), shareAddrStrategy: ShareAddrStrategySchema.default('node'),
shareAddr: z.string().default(''), shareAddr: z.string().default(''),
subSortIndex: z.number().int().default(1), subSortIndex: z.number().int().default(1),
excludeFromSub: z.boolean().default(false),
disableFlow: z.boolean().default(false), disableFlow: z.boolean().default(false),
}); });
export type InboundDbFields = z.infer<typeof InboundDbFieldsSchema>; export type InboundDbFields = z.infer<typeof InboundDbFieldsSchema>;
+16
View File
@@ -0,0 +1,16 @@
import { z } from 'zod';
// Extensions belong to the Happ client and must survive a trip through this editor.
export const HappRoutingProfileSchema = z
.object({
// The backend treats null lists as absent; preserve them until explicitly edited.
DirectSites: z.array(z.string()).nullish(),
DirectIp: z.array(z.string()).nullish(),
ProxySites: z.array(z.string()).nullish(),
ProxyIp: z.array(z.string()).nullish(),
BlockSites: z.array(z.string()).nullish(),
BlockIp: z.array(z.string()).nullish(),
})
.catchall(z.unknown());
export type HappRoutingProfile = z.infer<typeof HappRoutingProfileSchema>;
@@ -71,9 +71,9 @@ export const AmneziawgServerSchema = z.object({
jc: clearedToDefault(z.number().int().min(0).max(4294967295).default(5)), jc: clearedToDefault(z.number().int().min(0).max(4294967295).default(5)),
jmin: clearedToDefault(z.number().int().min(0).max(4294967295).default(10)), jmin: clearedToDefault(z.number().int().min(0).max(4294967295).default(10)),
jmax: clearedToDefault(z.number().int().min(0).max(4294967295).default(50)), jmax: clearedToDefault(z.number().int().min(0).max(4294967295).default(50)),
s1: clearedToDefault(z.number().int().min(0).max(65535).default(30)), s1: clearedToDefault(z.number().int().min(0).max(1552).default(30)),
s2: clearedToDefault(z.number().int().min(0).max(65535).default(45)), s2: clearedToDefault(z.number().int().min(0).max(1608).default(45)),
s3: clearedToDefault(z.number().int().min(0).max(64).default(10)), s3: clearedToDefault(z.number().int().min(0).max(1636).default(10)),
s4: clearedToDefault(z.number().int().min(0).max(32).default(5)), s4: clearedToDefault(z.number().int().min(0).max(32).default(5)),
h1: z.string().default(''), h1: z.string().default(''),
h2: z.string().default(''), h2: z.string().default(''),
@@ -22,9 +22,10 @@ export const AmneziaWGOutboundSettingsSchema = z.object({
jc: z.number().int().min(0).default(0), jc: z.number().int().min(0).default(0),
jmin: z.number().int().min(0).default(40), jmin: z.number().int().min(0).default(40),
jmax: z.number().int().min(0).default(100), jmax: z.number().int().min(0).default(100),
s1: z.number().int().min(0).default(15), // The remote server sets S1-S3; only amneziawg-go's uint16 UAPI width bounds them here.
s2: z.number().int().min(0).default(80), s1: z.number().int().min(0).max(65535).default(15),
s3: z.number().int().min(0).max(64).default(12), s2: z.number().int().min(0).max(65535).default(80),
s3: z.number().int().min(0).max(65535).default(12),
s4: z.number().int().min(0).max(32).default(12), s4: z.number().int().min(0).max(32).default(12),
h1: z.string().default(''), h1: z.string().default(''),
h2: z.string().default(''), h2: z.string().default(''),
+30
View File
@@ -72,6 +72,7 @@ export const AllSettingSchema = z
restartXrayOnClientDisable: z.boolean().optional(), restartXrayOnClientDisable: z.boolean().optional(),
subCertFile: z.string().optional(), subCertFile: z.string().optional(),
subKeyFile: z.string().optional(), subKeyFile: z.string().optional(),
externalSubUserAgent: z.string().max(512).optional(),
subUpdates: z.number().int().min(0).max(525600).optional(), subUpdates: z.number().int().min(0).max(525600).optional(),
subEncrypt: z.boolean().optional(), subEncrypt: z.boolean().optional(),
subURI: z.string().optional(), subURI: z.string().optional(),
@@ -109,6 +110,35 @@ export const AllSettingSchema = z
subHappAutoConnectType: z.string().optional(), subHappAutoConnectType: z.string().optional(),
subHappPerAppMode: z.string().optional(), subHappPerAppMode: z.string().optional(),
subHappPerAppList: z.string().optional(), subHappPerAppList: z.string().optional(),
subHappLocalProxyAuth: z.string().optional(),
subIncyAppAutoDetect: z.boolean().optional(),
subIncyProfileDescription: z.string().optional(),
subIncySortOrder: z.string().optional(),
subIncySupportEmail: z.string().optional(),
subIncyAnnounceUrl: z.string().optional(),
subIncyPremiumUrl: z.string().optional(),
subIncyBannerText: z.string().optional(),
subIncyBannerButtonText: z.string().optional(),
subIncyBannerButtonUrl: z.string().optional(),
subIncyBannerBgColor: z.string().optional(),
subIncyBannerButtonColor: z.string().optional(),
subIncyHideUrl: z.string().optional(),
subIncyHideCheck: z.string().optional(),
subIncyNoLimitEnabled: z.string().optional(),
subIncyPerAppEnable: z.string().optional(),
subIncyPerAppMode: z.string().optional(),
subIncyPerAppList: z.string().optional(),
subIncyFragmentationEnable: z.string().optional(),
subIncyFragmentLength: z.string().optional(),
subIncyFragmentInterval: z.string().optional(),
subIncyFragmentPackets: z.string().optional(),
subIncyNoisesEnable: z.string().optional(),
subIncyNoisesType: z.string().optional(),
subIncyNoisesPacket: z.string().optional(),
subIncyNoisesDelay: z.string().optional(),
subIncyResolveEnable: z.string().optional(),
subIncyResolveDnsDomain: z.string().optional(),
subIncyResolveDnsIp: z.string().optional(),
timeLocation: z.string().optional(), timeLocation: z.string().optional(),
ldapEnable: z.boolean().optional(), ldapEnable: z.boolean().optional(),
ldapHost: z.string().optional(), ldapHost: z.string().optional(),
+2 -2
View File
@@ -33,12 +33,12 @@ export const SubBalancerFormSchema = z.object({
.record( .record(
z.string(), z.string(),
z z
.number({ message: 'pages.settings.subBalancers.errWeightPositive' }) .number({ error: 'pages.settings.subBalancers.errWeightPositive' })
.positive('pages.settings.subBalancers.errWeightPositive'), .positive('pages.settings.subBalancers.errWeightPositive'),
) )
.optional(), .optional(),
sortOrder: z sortOrder: z
.number({ message: 'pages.settings.subBalancers.errSortOrder' }) .number({ error: 'pages.settings.subBalancers.errSortOrder' })
.int('pages.settings.subBalancers.errSortOrder') .int('pages.settings.subBalancers.errSortOrder')
.min(1, 'pages.settings.subBalancers.errSortOrder'), .min(1, 'pages.settings.subBalancers.errSortOrder'),
enabled: z.boolean(), enabled: z.boolean(),
+2 -2
View File
@@ -132,7 +132,7 @@ export const BalancerFormSchema = z.object({
.string() .string()
.trim() .trim()
.min(1, 'pages.xray.balancerTagRequired') .min(1, 'pages.xray.balancerTagRequired')
.refine((val) => !val.startsWith('_bl_'), { message: 'pages.xray.balancer.reservedPrefix' }), .refine((val) => !val.startsWith('_bl_'), { error: 'pages.xray.balancer.reservedPrefix' }),
strategy: BalancerStrategyTypeSchema.default('random'), strategy: BalancerStrategyTypeSchema.default('random'),
selector: z.array(z.string()).min(1, 'pages.xray.balancerSelectorRequired'), selector: z.array(z.string()).min(1, 'pages.xray.balancerSelectorRequired'),
fallbackTag: z.string().default(''), fallbackTag: z.string().default(''),
@@ -143,7 +143,7 @@ export const OutboundTagSchema = z
.string() .string()
.trim() .trim()
.min(1, 'pages.xray.outboundTagRequired') .min(1, 'pages.xray.outboundTagRequired')
.refine((val) => !val.startsWith('_bl_'), { message: 'pages.xray.balancer.reservedPrefix' }); .refine((val) => !val.startsWith('_bl_'), { error: 'pages.xray.balancer.reservedPrefix' });
export type BalancerFormValues = z.infer<typeof BalancerFormSchema>; export type BalancerFormValues = z.infer<typeof BalancerFormSchema>;
export type RuleFormValues = z.infer<typeof RuleFormSchema>; export type RuleFormValues = z.infer<typeof RuleFormSchema>;
+6 -3
View File
@@ -5,7 +5,8 @@
.settings-page, .settings-page,
.nodes-page, .nodes-page,
.groups-page, .groups-page,
.api-docs-page { .api-docs-page,
.sponsors-page {
--bg-page: #e6e8ec; --bg-page: #e6e8ec;
--bg-card: #ffffff; --bg-card: #ffffff;
min-height: 100vh; min-height: 100vh;
@@ -19,7 +20,8 @@
.settings-page.is-dark, .settings-page.is-dark,
.nodes-page.is-dark, .nodes-page.is-dark,
.groups-page.is-dark, .groups-page.is-dark,
.api-docs-page.is-dark { .api-docs-page.is-dark,
.sponsors-page.is-dark {
--bg-page: #1a1b1f; --bg-page: #1a1b1f;
--bg-card: #23252b; --bg-card: #23252b;
} }
@@ -31,7 +33,8 @@
.settings-page.is-dark.is-ultra, .settings-page.is-dark.is-ultra,
.nodes-page.is-dark.is-ultra, .nodes-page.is-dark.is-ultra,
.groups-page.is-dark.is-ultra, .groups-page.is-dark.is-ultra,
.api-docs-page.is-dark.is-ultra { .api-docs-page.is-dark.is-ultra,
.sponsors-page.is-dark.is-ultra {
--bg-page: #000; --bg-page: #000;
--bg-card: #101013; --bg-card: #101013;
} }
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { AmneziawgServerSchema } from '@/schemas/protocols/inbound/amneziawg'; import { AmneziawgServerSchema } from '@/schemas/protocols/inbound/amneziawg';
import { AmneziaWGOutboundSettingsSchema } from '@/schemas/protocols/outbound/amneziawg';
// AntD InputNumber emits null when cleared; a cleared numeric field must // AntD InputNumber emits null when cleared; a cleared numeric field must
// refill its schema default instead of failing validation and blocking the save. // refill its schema default instead of failing validation and blocking the save.
@@ -33,27 +34,27 @@ describe('AmneziawgServerSchema cleared numeric fields', () => {
}); });
}); });
// The form must reject what amneziawg-go's UAPI parsers reject (device/uapi.go: // The form must reject what cannot apply or be received: jc/jmin/jmax past uint32 (device/uapi.go),
// jc/jmin/jmax uint32, s1-s4 uint16), or the save silently outlives the apply. // S1-S3 past amneziawg-go's 1700-byte iOS receive buffer, S4 past 32 (MTU headroom).
describe('AmneziawgServerSchema obfuscation bounds', () => { describe('AmneziawgServerSchema obfuscation bounds', () => {
const overWidth: Array<[string, number]> = [ const overWidth: Array<[string, number]> = [
['s1', 65536], ['s1', 1553],
['s2', 70000], ['s2', 1609],
['s3', 65], ['s3', 1637],
['s4', 33], ['s4', 33],
['jc', 4294967296], ['jc', 4294967296],
['jmin', 4294967296], ['jmin', 4294967296],
['jmax', 5000000000], ['jmax', 5000000000],
]; ];
it.each(overWidth)('rejects %s above the width amneziawg-go parses', (field, value) => { it.each(overWidth)('rejects %s past what amneziawg-go can apply or receive', (field, value) => {
expect(AmneziawgServerSchema.safeParse({ [field]: value }).success).toBe(false); expect(AmneziawgServerSchema.safeParse({ [field]: value }).success).toBe(false);
}); });
const atLimit: Array<[string, number]> = [ const atLimit: Array<[string, number]> = [
['s1', 65535], ['s1', 1552],
['s2', 65535], ['s2', 1608],
['s3', 64], ['s3', 1636],
['s4', 32], ['s4', 32],
['jc', 4294967295], ['jc', 4294967295],
]; ];
@@ -69,3 +70,15 @@ describe('AmneziawgServerSchema obfuscation bounds', () => {
} }
}); });
}); });
// An outbound's S values come from the remote server and are received on Linux,
// so only amneziawg-go's uint16 UAPI width bounds them, not the iOS buffer.
describe('AmneziaWGOutboundSettingsSchema padding bounds', () => {
it.each(['s1', 's2', 's3'])('accepts %s past the inbound iOS cap', (field) => {
expect(AmneziaWGOutboundSettingsSchema.safeParse({ [field]: 2000 }).success).toBe(true);
});
it.each(['s1', 's2', 's3'])('rejects %s past uint16', (field) => {
expect(AmneziaWGOutboundSettingsSchema.safeParse({ [field]: 65536 }).success).toBe(false);
});
});
+13 -10
View File
@@ -1,4 +1,4 @@
import { fireEvent, screen } from '@testing-library/react'; import { act, fireEvent, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router'; import { MemoryRouter } from 'react-router';
import { afterEach, expect, test, vi } from 'vitest'; import { afterEach, expect, test, vi } from 'vitest';
@@ -13,16 +13,19 @@ afterEach(() => {
localStorage.clear(); localStorage.clear();
}); });
function renderSidebar() { // rc-menu registers its items in a microtask after render; settle it inside act().
return renderWithProviders( async function renderSidebar() {
const view = renderWithProviders(
<MemoryRouter> <MemoryRouter>
<AppSidebar /> <AppSidebar />
</MemoryRouter>, </MemoryRouter>,
); );
await act(async () => {});
return view;
} }
test('keeps the sidebar expanded after pinning it from the header and restores the choice', () => { test('keeps the sidebar expanded after pinning it from the header and restores the choice', async () => {
const first = renderSidebar(); const first = await renderSidebar();
const sidebar = first.container.querySelector('.ant-layout-sider'); const sidebar = first.container.querySelector('.ant-layout-sider');
const sidebarRoot = first.container.querySelector('.ant-sidebar'); const sidebarRoot = first.container.querySelector('.ant-sidebar');
@@ -42,7 +45,7 @@ test('keeps the sidebar expanded after pinning it from the header and restores t
first.unmount(); first.unmount();
const second = renderSidebar(); const second = await renderSidebar();
const restoredSidebar = second.container.querySelector('.ant-layout-sider'); const restoredSidebar = second.container.querySelector('.ant-layout-sider');
const restoredSidebarRoot = second.container.querySelector('.ant-sidebar'); const restoredSidebarRoot = second.container.querySelector('.ant-sidebar');
@@ -51,8 +54,8 @@ test('keeps the sidebar expanded after pinning it from the header and restores t
expect(screen.getByRole('button', { name: 'Pin sidebar' })).not.toBeNull(); expect(screen.getByRole('button', { name: 'Pin sidebar' })).not.toBeNull();
}); });
test('returns to the compact rail after unpinning', () => { test('returns to the compact rail after unpinning', async () => {
const view = renderSidebar(); const view = await renderSidebar();
const sidebar = view.container.querySelector('.ant-layout-sider'); const sidebar = view.container.querySelector('.ant-layout-sider');
const sidebarRoot = view.container.querySelector('.ant-sidebar'); const sidebarRoot = view.container.querySelector('.ant-sidebar');
@@ -66,8 +69,8 @@ test('returns to the compact rail after unpinning', () => {
expect(localStorage.getItem('sidebar-pinned')).toBe('false'); expect(localStorage.getItem('sidebar-pinned')).toBe('false');
}); });
test('labels the palette shortcut with the modifier the platform actually uses', () => { test('labels the palette shortcut with the modifier the platform actually uses', async () => {
const view = renderSidebar(); const view = await renderSidebar();
const chip = view.container.querySelector('.sidebar-command-kbd'); const chip = view.container.querySelector('.sidebar-command-kbd');
expect(chip?.textContent).toBe('CtrlK'); expect(chip?.textContent).toBe('CtrlK');
}); });
@@ -0,0 +1,34 @@
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
import { CipherSuitesSelect } from '@/components/form';
function renderSelect(value: string) {
const onChange = vi.fn();
render(<CipherSuitesSelect aria-label="cipher suites" value={value} onChange={onChange} />);
return onChange;
}
describe('CipherSuitesSelect', () => {
it('shows each colon-separated suite as its own tag', () => {
renderSelect('TLS_AES_256_GCM_SHA384:MY_CUSTOM_SUITE');
expect(screen.getByText('TLS_AES_256_GCM_SHA384')).toBeTruthy();
expect(screen.getByText('MY_CUSTOM_SUITE')).toBeTruthy();
});
it('stores a typed custom suite joined with colons after the existing one', () => {
const onChange = renderSelect('TLS_AES_256_GCM_SHA384');
const input = screen.getByRole('combobox', { name: 'cipher suites' });
fireEvent.change(input, { target: { value: 'MY_CUSTOM_SUITE' } });
fireEvent.keyDown(input, { key: 'Enter', code: 'Enter', keyCode: 13 });
expect(onChange).toHaveBeenLastCalledWith('TLS_AES_256_GCM_SHA384:MY_CUSTOM_SUITE');
});
it('stores an empty string once every suite is removed', () => {
const onChange = renderSelect('TLS_AES_256_GCM_SHA384');
const remove = document.querySelector('.ant-select-selection-item-remove');
expect(remove).not.toBeNull();
fireEvent.click(remove as Element);
expect(onChange).toHaveBeenLastCalledWith('');
});
});
@@ -0,0 +1,113 @@
import { expect, it, vi } from 'vitest';
import { fireEvent, screen, waitFor } from '@testing-library/react';
import ClientBulkAddModal from '@/pages/clients/ClientBulkAddModal';
import { HttpUtil, Msg } from '@/utils';
import { chooseSelectOption, renderWithProviders } from './test-utils';
const { bulkCreate } = vi.hoisted(() => ({ bulkCreate: vi.fn() }));
vi.mock('@/hooks/useClients', () => ({ useClients: () => ({ bulkCreate }) }));
it('keeps bulk renewal disabled by default and requires explicit cutoff selection without changing first-use duration', async () => {
bulkCreate.mockResolvedValue(new Msg(true, '', { created: 1, skipped: [] }));
const post = vi.spyOn(HttpUtil, 'post').mockImplementation(async (url, body) => {
if (url !== '/panel/api/clients/renewalPreview')
return new Msg(true, '', { datepicker: 'gregorian' });
const request = body as { expiryTime: number };
return new Msg(true, '', {
timeZone: 'Asia/Taipei',
renewAt: '',
validThrough: '',
nextExpiry: '',
suggestedExpiryTime: 1893427200000,
suggestedExpiry: '2030-01-01T00:00:00+08:00',
renewals: 0,
canRenew: false,
delayedStart: request.expiryTime < 0,
});
});
async function submit() {
const button = document.querySelector('.ant-modal-footer .ant-btn-primary');
if (!button) throw new Error('Create button missing');
await waitFor(() => expect(button.classList.contains('ant-btn-loading')).toBe(false));
fireEvent.click(button);
}
try {
renderWithProviders(
<ClientBulkAddModal
open
inbounds={[{ id: 1, protocol: 'vless', tag: 'calendar' }]}
onOpenChange={() => {}}
/>,
);
fireEvent.click(screen.getByRole('button', { name: 'Select all' }));
const mode = screen.getByLabelText('Auto renewal');
expect(mode.closest('.ant-select')?.textContent).toContain('Disabled');
expect(post.mock.calls.some(([url]) => url === '/panel/api/clients/renewalPreview')).toBe(
false,
);
await submit();
await waitFor(() =>
expect(bulkCreate).toHaveBeenCalledWith([
expect.objectContaining({
client: expect.objectContaining({
reset: 0,
resetDay: 0,
resetWeekday: 0,
expiryTime: 0,
}),
}),
]),
);
chooseSelectOption(mode.id, 'Calendar weekly');
await waitFor(() => expect(document.body.textContent).toContain('An expiry must be set'));
await submit();
await waitFor(() =>
expect(bulkCreate).toHaveBeenLastCalledWith([
expect.objectContaining({
client: expect.objectContaining({
reset: 0,
resetDay: 0,
resetWeekday: 1,
expiryTime: 0,
}),
}),
]),
);
fireEvent.click(screen.getByRole('button', { name: /Set first cycle cutoff/ }));
await submit();
await waitFor(() =>
expect(bulkCreate).toHaveBeenLastCalledWith([
expect.objectContaining({
client: expect.objectContaining({ resetWeekday: 1, expiryTime: 1893427200000 }),
}),
]),
);
const label = Array.from(document.querySelectorAll('.ant-form-item-label label')).find(
(el) => el.textContent === 'Start After First Use',
);
const toggle = label?.closest('.ant-form-item')?.querySelector('[role="switch"]');
if (!toggle) throw new Error('First-use switch missing');
fireEvent.click(toggle);
const daysLabel = Array.from(document.querySelectorAll('.ant-form-item-label label')).find(
(el) => el.textContent === 'Duration (days)',
);
const daysInput = daysLabel?.closest('.ant-form-item')?.querySelector('input');
if (!daysInput) throw new Error('First-use days input missing');
fireEvent.change(daysInput, { target: { value: '7' } });
await waitFor(() =>
expect(document.body.textContent).toContain('Dates are available after first-use activation'),
);
expect(screen.queryByRole('button', { name: /Set first cycle cutoff/ })).toBeNull();
await submit();
await waitFor(() =>
expect(bulkCreate).toHaveBeenLastCalledWith([
expect.objectContaining({
client: expect.objectContaining({ resetWeekday: 1, expiryTime: -604800000 }),
}),
]),
);
} finally {
post.mockRestore();
}
});
@@ -0,0 +1,109 @@
import { expect, it, vi } from 'vitest';
import { fireEvent, screen, waitFor } from '@testing-library/react';
import ClientFormModal from '@/pages/clients/ClientFormModal';
import { HttpUtil, Msg } from '@/utils';
import { chooseSelectOption, renderWithProviders } from './test-utils';
it('preserves monthly clients, previews backend dates, and saves exclusive weekly or disabled modes', async () => {
const post = vi.spyOn(HttpUtil, 'post').mockResolvedValue(
new Msg(true, '', {
timeZone: 'Asia/Taipei',
renewAt: '2030-01-01T00:00:00+08:00',
validThrough: '2029-12-31T23:59:59+08:00',
nextExpiry: '2030-02-01T00:00:00+08:00',
suggestedExpiryTime: 1893427200000,
suggestedExpiry: '2030-01-01T00:00:00+08:00',
renewals: 1,
canRenew: true,
delayedStart: false,
}),
);
const save = vi.fn().mockResolvedValue(new Msg(true, '', null));
async function submit() {
const button = document.querySelector('.ant-modal-footer .ant-btn-primary');
if (!button) throw new Error('Save button missing');
await waitFor(() => expect(button.classList.contains('ant-btn-loading')).toBe(false));
fireEvent.click(button);
}
try {
renderWithProviders(
<ClientFormModal
open
mode="edit"
client={{
email: 'monthly@example.com',
uuid: '11111111-1111-1111-1111-111111111111',
subId: 'calendar-sub',
enable: true,
expiryTime: 1893427200000,
resetDay: 1,
reset: 7,
resetMax: 3,
traffic: { resetCount: 2 },
}}
attachedIds={[1]}
inbounds={[{ id: 1, protocol: 'vless', tag: 'calendar' }]}
save={save}
onOpenChange={() => {}}
/>,
);
const mode = screen.getByLabelText('Auto renewal');
expect(mode.closest('.ant-select')?.textContent).toContain('Calendar monthly');
await waitFor(() => expect(document.body.textContent).toContain('2029-12-31T23:59:59+08:00'));
expect(post).toHaveBeenCalledWith(
'/panel/api/clients/renewalPreview',
expect.objectContaining({ resetMax: 3, resetCount: 2 }),
expect.anything(),
);
await submit();
await waitFor(() =>
expect(save).toHaveBeenCalledWith(
expect.objectContaining({
reset: 7,
resetDay: 1,
resetWeekday: 0,
expiryTime: 1893427200000,
}),
expect.anything(),
),
);
chooseSelectOption(mode.id, 'Calendar weekly');
const weekday = screen.getByLabelText('Renew on weekday');
chooseSelectOption(weekday.id, 'Sunday');
await waitFor(() =>
expect(post).toHaveBeenCalledWith(
'/panel/api/clients/renewalPreview',
expect.objectContaining({ reset: 0, resetDay: 0, resetWeekday: 7 }),
expect.anything(),
),
);
await submit();
await waitFor(() =>
expect(save).toHaveBeenCalledWith(
expect.objectContaining({
reset: 0,
resetDay: 0,
resetWeekday: 7,
expiryTime: 1893427200000,
}),
expect.anything(),
),
);
chooseSelectOption(mode.id, 'Disabled');
await submit();
await waitFor(() =>
expect(save).toHaveBeenCalledWith(
expect.objectContaining({
reset: 0,
resetDay: 0,
resetWeekday: 0,
expiryTime: 1893427200000,
}),
expect.anything(),
),
);
} finally {
post.mockRestore();
}
});
+17 -6
View File
@@ -116,6 +116,11 @@ function renderSubject(overrides: Partial<SubjectProps> = {}) {
}; };
} }
// Opening fetches sub links with no visible loading state; settle it inside act().
async function settleSubLinks() {
await act(async () => {});
}
function selectVariant(name: 'Standard' | 'Happ') { function selectVariant(name: 'Standard' | 'Happ') {
fireEvent.click(screen.getByRole('radio', { name: name === 'Happ' ? /Happ/ : name })); fireEvent.click(screen.getByRole('radio', { name: name === 'Happ' ? /Happ/ : name }));
} }
@@ -129,8 +134,9 @@ describe('ClientQrModal Happ presentation', () => {
vi.mocked(HttpUtil.post).mockReset(); vi.mocked(HttpUtil.post).mockReset();
}); });
it('opens on Standard without generating a Happ link', () => { it('opens on Standard without generating a Happ link', async () => {
renderSubject(); renderSubject();
await settleSubLinks();
expect((screen.getByRole('radio', { name: 'Standard' }) as HTMLInputElement).checked).toBe( expect((screen.getByRole('radio', { name: 'Standard' }) as HTMLInputElement).checked).toBe(
true, true,
@@ -139,8 +145,9 @@ describe('ClientQrModal Happ presentation', () => {
expect(HttpUtil.post).not.toHaveBeenCalled(); expect(HttpUtil.post).not.toHaveBeenCalled();
}); });
it('names the Happ option as an encrypted link', () => { it('names the Happ option as an encrypted link', async () => {
renderSubject(); renderSubject();
await settleSubLinks();
expect(screen.getByRole('radio', { name: HAPP_OPTION_LABEL })).toBeTruthy(); expect(screen.getByRole('radio', { name: HAPP_OPTION_LABEL })).toBeTruthy();
}); });
@@ -148,7 +155,7 @@ describe('ClientQrModal Happ presentation', () => {
it.each([ it.each([
['missing', undefined], ['missing', undefined],
['false', false], ['false', false],
])('marks the selectable Happ option as locked when the gate is %s', (_name, gate) => { ])('marks the selectable Happ option as locked when the gate is %s', async (_name, gate) => {
const subSettings: TestSubSettings = { const subSettings: TestSubSettings = {
enable: SUB_SETTINGS.enable, enable: SUB_SETTINGS.enable,
subURI: SUB_SETTINGS.subURI, subURI: SUB_SETTINGS.subURI,
@@ -158,6 +165,7 @@ describe('ClientQrModal Happ presentation', () => {
if (gate !== undefined) subSettings.happLinkEnable = gate; if (gate !== undefined) subSettings.happLinkEnable = gate;
renderSubject({ subSettings }); renderSubject({ subSettings });
await settleSubLinks();
const standard = screen.getByRole('radio', { name: 'Standard' }) as HTMLInputElement; const standard = screen.getByRole('radio', { name: 'Standard' }) as HTMLInputElement;
const happ = screen.getByRole('radio', { name: /Happ Encrypted Link/ }) as HTMLInputElement; const happ = screen.getByRole('radio', { name: /Happ Encrypted Link/ }) as HTMLInputElement;
@@ -176,7 +184,7 @@ describe('ClientQrModal Happ presentation', () => {
['false', false], ['false', false],
])( ])(
'replaces the blank Happ content with a persistent empty state when the gate is %s', 'replaces the blank Happ content with a persistent empty state when the gate is %s',
(_name, gate) => { async (_name, gate) => {
const subSettings: TestSubSettings = { const subSettings: TestSubSettings = {
enable: SUB_SETTINGS.enable, enable: SUB_SETTINGS.enable,
subURI: SUB_SETTINGS.subURI, subURI: SUB_SETTINGS.subURI,
@@ -186,6 +194,7 @@ describe('ClientQrModal Happ presentation', () => {
if (gate !== undefined) subSettings.happLinkEnable = gate; if (gate !== undefined) subSettings.happLinkEnable = gate;
renderSubject({ subSettings }); renderSubject({ subSettings });
await settleSubLinks();
const standard = screen.getByRole('radio', { name: 'Standard' }) as HTMLInputElement; const standard = screen.getByRole('radio', { name: 'Standard' }) as HTMLInputElement;
const happ = screen.getByRole('radio', { name: /Happ Encrypted Link/ }) as HTMLInputElement; const happ = screen.getByRole('radio', { name: /Happ Encrypted Link/ }) as HTMLInputElement;
@@ -222,8 +231,9 @@ describe('ClientQrModal Happ presentation', () => {
expect(screen.queryByRole('tooltip')).toBeNull(); expect(screen.queryByRole('tooltip')).toBeNull();
}); });
it('closes the QR modal and deep-links to Happ settings without generating', () => { it('closes the QR modal and deep-links to Happ settings without generating', async () => {
const view = renderSubject({ subSettings: { ...SUB_SETTINGS, happLinkEnable: false } }); const view = renderSubject({ subSettings: { ...SUB_SETTINGS, happLinkEnable: false } });
await settleSubLinks();
selectVariant('Happ'); selectVariant('Happ');
fireEvent.click(screen.getByRole('button', { name: 'Go to Settings' })); fireEvent.click(screen.getByRole('button', { name: 'Go to Settings' }));
@@ -231,7 +241,7 @@ describe('ClientQrModal Happ presentation', () => {
expect(view.onOpenChange).toHaveBeenCalledOnce(); expect(view.onOpenChange).toHaveBeenCalledOnce();
expect(view.onOpenChange).toHaveBeenCalledWith(false); expect(view.onOpenChange).toHaveBeenCalledWith(false);
expect(screen.getByTestId('location').textContent).toBe( expect(screen.getByTestId('location').textContent).toBe(
'/settings?subscriptionTab=happ&happTab=links#subscription', '/settings?subscriptionTab=happ#subscription',
); );
expect(HttpUtil.post).not.toHaveBeenCalled(); expect(HttpUtil.post).not.toHaveBeenCalled();
}); });
@@ -411,6 +421,7 @@ describe('ClientQrModal Happ presentation', () => {
view.update({ open: false }); view.update({ open: false });
view.update({ open: true }); view.update({ open: true });
await settleSubLinks();
expect((screen.getByRole('radio', { name: 'Standard' }) as HTMLInputElement).checked).toBe( expect((screen.getByRole('radio', { name: 'Standard' }) as HTMLInputElement).checked).toBe(
true, true,
@@ -18,7 +18,16 @@ describe('client enable toggle', () => {
const email = 'scheduled@example.com'; const email = 'scheduled@example.com';
vi.spyOn(HttpUtil, 'get').mockResolvedValue( vi.spyOn(HttpUtil, 'get').mockResolvedValue(
new Msg(true, '', { new Msg(true, '', {
client: { email, enable: !enable, trafficReset: 'monthly', trafficResetDay: 15 }, client: {
email,
enable: !enable,
trafficReset: 'monthly',
trafficResetDay: 15,
reset: 0,
resetDay: 0,
resetWeekday: 7,
resetMax: 3,
},
inboundIds: [], inboundIds: [],
}), }),
); );
@@ -44,7 +53,16 @@ describe('client enable toggle', () => {
expect(HttpUtil.get).toHaveBeenCalledWith('/panel/api/clients/get/scheduled%40example.com'); expect(HttpUtil.get).toHaveBeenCalledWith('/panel/api/clients/get/scheduled%40example.com');
expect(post).toHaveBeenCalledWith( expect(post).toHaveBeenCalledWith(
'/panel/api/clients/update/scheduled%40example.com', '/panel/api/clients/update/scheduled%40example.com',
expect.objectContaining({ email, enable, trafficReset: 'monthly', trafficResetDay: 15 }), expect.objectContaining({
email,
enable,
trafficReset: 'monthly',
trafficResetDay: 15,
reset: 0,
resetDay: 0,
resetWeekday: 7,
resetMax: 3,
}),
{ headers: { 'Content-Type': 'application/json' } }, { headers: { 'Content-Type': 'application/json' } },
); );
}, },
@@ -1,5 +1,5 @@
import { useState } from 'react'; import { useState } from 'react';
import { render, screen } from '@testing-library/react'; import { act, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event'; import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest'; import { describe, expect, it, vi } from 'vitest';
@@ -58,8 +58,9 @@ describe('clients table row cells', () => {
expect(afterFirstRender).toBeGreaterThan(0); expect(afterFirstRender).toBeGreaterThan(0);
// Three simulated traffic pushes: the parent re-renders, the props do not change. // Three simulated traffic pushes: the parent re-renders, the props do not change.
act(() => {
for (let i = 0; i < 3; i++) bump(); for (let i = 0; i < 3; i++) bump();
await Promise.resolve(); });
expect(reads.count).toBe(afterFirstRender); expect(reads.count).toBe(afterFirstRender);
}); });
@@ -113,7 +114,9 @@ describe('clients table row cells', () => {
</Harness>, </Harness>,
); );
act(() => {
for (let i = 0; i < 3; i++) bump(); for (let i = 0; i < 3; i++) bump();
});
// Queried by position rather than label: the suite loads the real en-US // Queried by position rather than label: the suite loads the real en-US
// bundle, so the aria-labels are translated strings, not keys. Order is // bundle, so the aria-labels are translated strings, not keys. Order is

Some files were not shown because too many files have changed in this diff Show More