mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-09-28 10:12:07 +03:00
f6a1a3bbd1b7d5e90aad30eb7748b41393da0048
3625 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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
|
||
|
|
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. |
||
|
|
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> |
||
|
|
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> |
||
|
|
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. |
||
|
|
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> |
||
|
|
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. |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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 |
||
|
|
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. |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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> |
||
|
|
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). |
||
|
|
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. |
||
|
|
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). |
||
|
|
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. |
||
|
|
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. |
||
|
|
a03228c455 |
ci: update Claude workflow model settings
Use Claude Opus 5.5 with high effort for issue analysis and PR reviews. |
||
|
|
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. |
||
|
|
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 |
||
|
|
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.
|
||
|
|
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> |
||
|
|
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> |
||
|
|
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
|
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
7ef22f94c9 |
fix(logger): fix data race in InitLogger
Replace the package logger variable with an atomic.Pointer so InitLogger swapping the handle no longer races with concurrent Debug/Info/Warning/Error calls from other goroutines. Also guard fileRotate with a mutex, and add a regression test that reproduces the race under concurrent logging.v3.8.5 |
||
|
|
ec9fbae645 | v3.8.5 | ||
|
|
e26cf1d3ed |
feat(sub): redesign the subscription page around usage, tabs and app imports
The info page was a long key/value table followed by every link and two app dropdowns, and it rendered left-to-right even for Persian and Arabic. It now leads with a usage ring, the remaining quota and a stats grid, and splits the rest into Subscription / Apps / Configs tabs. - Status tells expired, data-used-up and disabled apart instead of one "Inactive", replacing the hard-coded English expiry chip. - The Apps tab keeps every Android and iOS app with its existing deep link, preselects the visitor's platform and adds Windows: Hiddify and Clash Verge Rev import directly, v2rayN copies the link. - fa-IR and ar-EG render right-to-left; URLs, IDs and sizes stay LTR. - The footer shows the support link and the client refresh interval, so subPageContext now carries subUpdates (also in ?format=info). - Status, days-left and app deep-link logic lives in subPageModel.ts, with unit tests pinning the deep links the page already shipped. |