9 Commits
  • feat(sub): add read-only HWID device-slot status endpoint (#6380)
    * feat(sub): add read-only HWID device-slot status endpoint
    
    Closes #6357
    
    A client with an HWID limit had no way to tell a subscriber how many device
    slots were left: /{subPath}/{subId} only exposes the gate as a boolean through
    X-Hwid-* headers on a 404, and ?format=info carries no limitHwid or registered
    count. Every "why can't I connect on my new phone" case therefore had to be
    answered by the operator by hand.
    
    GET /{subPath}/{subId}/hwid-status now returns the aggregate counters:
    
      {"active":true,"limit":2,"registered":1,"remaining":1,"full":false}
    
    - SELECT-only. It never registers an hwid, never touches last_seen and never
      calls the enforcement path, so asking about a slot cannot spend one.
    - Counters only: no hwid value or hash, no email, no device metadata, no IP,
      no User-Agent, and none of the X-Hwid-* gate headers.
    - The subscription id is already the bearer secret for /{subPath}/{subId}, so
      no admin token and no new auth mechanism.
    - Unknown and disabled subscriptions both answer a bare 404, with identical
      status, headers and body, so the route cannot be used to probe which
      subscription ids exist.
    - No HWID limit configured returns {"active":false,"limit":0,...}.
    - No schema change and no migration.
    
    Scoped to enabled clients exactly like effectiveHwidLimitForSubID, so the
    reported limit is always the limit the gate enforces on a shared sub_id, and
    remaining clamps at zero when the effective limit drops below the number of
    registered devices. A separate route leaves /{subPath}/{subId}, ?format=info
    and the JSON/Clash routes byte-for-byte unchanged.
    
    Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
    
    * fix(sub): document hwid-status as the bare object it returns
    
    The OpenAPI operation for GET /{subPath}/{subId}/hwid-status inherited the
    {success,msg,obj} panel envelope from build-openapi.mjs's default 200
    response, while the handler writes the HwidSlotStatus struct bare. A client
    generated from the spec would read `obj` and never find the counters, and
    the description prose contradicted the schema with a hand-written example.
    
    HwidSlotStatus now sits in openapigen's StructAllow with example: tags, the
    entry references the generated schema through a `responses` block, and
    build-openapi.mjs attaches the generated example to any `responses` entry
    that $refs a generated schema, so no example is hand-written. The HEAD
    variant the controller registers is documented like its siblings, and the
    summary follows the "path prefix is configured by subPath" wording now that
    fresh panels randomise the prefix.
    
    Regenerated frontend/public/openapi.json, docs/public/openapi.json and the
    subscription-server MDX. openapi-runtime-contracts.test.ts pins the bare
    schema, the generated example and the HEAD operation.
    
    ---------
    
    Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • docs(api): mark collection responses nullable (#6430)
    * docs(api): mark collection responses nullable
    
    Describe allLinks and panel log response objects as nullable string arrays so generated clients accept the existing nil-slice wire format. Pin both schemas with buildSpec regression assertions and regenerate the OpenAPI copies.
    
    * docs(api): include nullable Xray log responses
    
    Allow generated response arrays to opt into nullability while retaining their schema references and Go-derived examples. Apply this to Xray logs, whose nil slices already serialize as null, and pin the schema and example through buildSpec.
  • docs(api): align OpenAPI with runtime contracts (#6409)
    Document the cookie-authenticated WebSocket upgrade and its emitted envelopes without exporting pseudo-paths. Align REST response schemas, paged-client filters, and subscription HEAD operations with their runtime implementations, then regenerate frontend and docs artifacts.
  • fix(api-docs): generate request bodies for all encodings (#6296)
    * fix(api-docs): generate request bodies for all encodings
    
    The OpenAPI generator only recognized generic body parameters, so JSON, form, and multipart declarations disappeared into empty application/json objects. Generate the declared media type and schema, preserve optionality and conditional requirements, and encode repeated form arrays the way Gin expects. Correct the request metadata exposed by the complete schemas and keep the panel and docs specifications synchronized.
    
    * fix(api-docs): align alternative request schemas
    
    Keep non-empty constraints on the selected request-body alternative without rejecting empty values for the alternatives that panel requests also include. Allow null client IP lists because model serialization emits them while cleared rows await pruning.
    
    * fix(api-docs): send object urlencoded fields as JSON, document the inbound update body
    
    Four defects the request-body rework exposed or left behind:
    
    - An object-typed field in an x-www-form-urlencoded body got no encoding
      entry, so OpenAPI 3.0 serialized it form-style. Swagger "Try it out"
      and generated clients sent memberWeights=3&memberWeights=0.2 to
      /panel/api/sub-balancers, and parseSubBalancerForm json.Unmarshals the
      raw field, so every such call failed with "invalid memberWeights".
      Emit encoding.<name>.contentType = application/json instead.
    - bodyRequiredOneOf names were never checked against the declared body
      params: a typo emitted an anyOf branch requiring a property that does
      not exist — unsatisfiable — and make gen still passed. Throw now, and
      extend the requestSchema guard to reject bodyRequiredOneOf as well.
    - /panel/api/inbounds/update/:id advertised no request body although its
      own summary says the shape mirrors /add and updateInbound binds one.
      Both entries now share an inboundBody const so they cannot drift.
    - The mixed-locations error was the only buildOperation throw without
      the method and path, aborting make gen without naming the offender.
    
    Regenerated frontend/public/openapi.json and copied it to
    docs/public/openapi.json. No MDX regeneration: no summary changed.
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • Add per-client external link controls (#5650)
    * Add enable toggle for external client links
    
    * Document external link enable API fields
    
    * Extend external client link metadata
    
    * Fix external subscription cache status updates
    
    * fix(sub): address the review on per-client external link controls
    
    Blocking: the expiry filter dropped legacy rows. expiry_time was added
    without a default, so AutoMigrate makes it nullable and backfills NULL,
    and `expiry_time = 0 OR expiry_time > ?` is false for NULL under
    three-valued logic — every external link written before the upgrade
    vanished from all subscriptions. Add `default:0` on expiry_time and
    last_fetch_at, make the predicate NULL-tolerant, and backfill the NULLs
    a pre-fix build could already have written.
    
    Rework fetch-status recording. It ran inside the singleflight in-flight
    window, so every goroutine parked on the shared fetch waited for a DB
    write to commit on the public, unauthenticated subscription path — and
    because it was keyed on the row id, waiters and cache hits recorded
    nothing, leaving rows that lost the race stuck on "Not fetched yet"
    forever. fetchSubscriptionLinks now reports whether it did the network
    fetch and expandEntry records afterwards, off the serving path, keyed on
    kind+value so every row sharing the URL is stamped by the one fetch.
    Keying on value also closes the recycled-rowid hazard: saves delete and
    re-insert rows, and SQLite reuses rowids, so an in-flight write could
    land on an unrelated client's row. The write no longer discards its
    error either.
    
    Drop the inert id round-trip. The panel never sent it, and the byId
    branch was guarded by the exact kind+value equality that byKindValue
    already keys on, so it could not change an outcome. Matching on
    kind+value alone is what actually preserves fetch status across saves.
    
    Reject a negative expiryTime instead of storing a row that is silently
    invisible in every subscription — elsewhere a negative expiryTime means
    "a duration from first use", so an API caller reusing that convention
    got no error and no links.
    
    Drop the ~50 lines of .client-form-* / .client-inbounds-field CSS that
    no component renders; it is leftover from the WireGuard PR this one was
    split from.
    
    i18n: reuse the already-translated pages.inbounds.leaveBlankToNeverExpire
    instead of shipping an English duplicate under pages.clients, and
    translate namePrefix, lastFetchAt, lastFetchError and neverFetched into
    all 12 non-English locales.
    
    Cover the persistence path that had no test: the fetch-status writer over
    a real DB against a failing then a succeeding server, a cache hit writing
    nothing, and the negative-expiry rejection.
    
    ---------
    
    Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
  • feat(api-docs): generate OpenAPI components/schemas from Go structs
    A new emit_jsonschema.go walks the same allow-listed structs as the zod/types/examples emitters and writes generated/schemas.ts (SCHEMAS). build-openapi mounts it under components.schemas and points each typed response obj at a $ref instead of an untyped {} blob, so Swagger renders real models and openapi-generator can emit clients.
    
    Also add a vitest guard that safeParses every EXAMPLES entry against its generated zod schema, reviving the previously unused generated/zod.ts and catching drift between the example and schema emitters.
  • feat(api-docs): generate response examples from Go structs; fix SS2022 PSK regen (#4996)
    Stop hand-writing OpenAPI response examples, which kept drifting from the real payloads (clients/traffic missing fields, inbounds/list exposing userId which is json:"-", the fictional inbound-443 tag instead of the real in-<port>-<transport> form).
    
    tools/openapigen now emits frontend/src/generated/examples.ts: a per-struct example instance built from type defaults, validate oneof/min bounds, and example: struct tags, with nested-ref expansion and a cycle guard. build-openapi.mjs composes the {success,obj} envelope from it for any endpoint annotated with responseSchema (+ responseSchemaArray for lists); the hand-written response is dropped for those. Service DTOs InboundOption/ApiTokenView/ProbeResultUI are added to the walker.
    
    #4996: client password regeneration now produces a valid Shadowsocks 2022 PSK (correct base64 length per cipher) when an SS2022 inbound is attached, in both the single and bulk client forms; backend surfaces ssMethod on /inbounds/options so the UI can pick the right length.
    
    Also: Swagger UI persists the Authorization token across reloads (persistAuthorization).
  • refactor(frontend): port api-docs/endpoints to TypeScript
    endpoints.js was the only remaining JS file under src/. It's a pure data
    file describing every panel API surface for the in-panel Swagger docs;
    scripts/build-openapi.mjs reads it at build time to emit
    public/openapi.json.
    
    Convert it to endpoints.ts with explicit interfaces:
      HttpMethod, ParamLocation, ParamType,
      EndpointParam, Endpoint, SubscriptionHeader, Section
    
    Type-checking surfaced shapes the .js had silently accepted:
      - 'in' values beyond plain 'body' — 'body (form)', 'body (json)',
        'body (multipart)' for non-JSON request bodies
      - 'type' arrays — 'integer[]', 'object[]'
      - Subscription section's subHeader documenting response headers
    All four are now part of the union types so the existing data type-checks.
    
    Dead exports removed:
      - safeInlineHtml — unused since the docs page switched to Swagger UI
      - methodColors — unused
    
    Build pipeline:
      - scripts/build-openapi.mjs imports endpoints.ts directly
      - gen:api runs via Node 22's native --experimental-strip-types; no
        tsx/ts-node dependency added
      - --disable-warning=ExperimentalWarning silences just the strip-types
        notice while keeping deprecation warnings intact
  • feat(frontend): TanStack Query + React Router migration & in-panel API docs (#4541)
    * feat(frontend): introduce TanStack Query with status polling
    
    Wires @tanstack/react-query into every entry and migrates useStatus to
    useStatusQuery as the foundation for the multi-page MPA → SPA migration.
    
    - QueryProvider wraps each entry inside ThemeProvider, with devtools gated
      on import.meta.env.DEV
    - Shared queryClient: 30s staleTime, refetchOnWindowFocus, 1 retry
    - useStatusQuery preserves the { status, fetched, refresh } shape so
      IndexPage swaps in without further changes
    - refetchIntervalInBackground:false stops the 2s status poll when the
      panel tab is hidden, cutting idle traffic against the server
    
    * feat(frontend): collapse panel pages into a single React Router SPA
    
    Replaces the 7-entry MPA shell (index/clients/inbounds/nodes/settings/
    xray/api-docs HTML files) with one main.tsx + createBrowserRouter. The
    Go backend now serves the same index.html for every authenticated
    panel route; React Router reads the URL and mounts the page from cache
    on subsequent navigation — no more full reloads between tabs.
    
    Frontend
    - main.tsx: single bootstrap (setupAxios, i18n, ThemeProvider,
      QueryProvider, RouterProvider) replacing 7 near-duplicate entries
    - routes.tsx: declarative router with lazy()-loaded pages, basename
      derived from window.X_UI_BASE_PATH so panels at /secret/panel work
    - layouts/PanelLayout.tsx: shell mount-point for the WS → queryClient
      bridge so connection survives navigation
    - api/websocketBridge.ts: subscribes the singleton WebSocketClient to
      queryClient and dispatches invalidate/outbounds events to cached
      queries (page-level useWebSocket handlers stay until Phase 3 hooks
      migrate)
    - AppSidebar: navigates via useNavigate + useLocation instead of
      window.location.href; drops basePath/requestUri props
    - Pages: drop the unused basePath/requestUri locals exposed only for
      the old sidebar
    
    Build
    - vite.config: 9 rollup inputs → 3 (index, login, subpage). Dev proxy
      bypass collapses /panel/* to index.html and skips API prefixes
    - vendor-tanstack + vendor-router chunks added to manualChunks
    
    Backend
    - xui.go: 7 per-page HTML handlers → one panelSPA handler serving
      index.html for /, /inbounds, /clients, /nodes, /settings, /xray,
      /api-docs. The /panel/api, /panel/setting, /panel/xray sub-routers
      are untouched
    
    * feat(frontend): migrate useNodes to TanStack Query
    
    Splits the hand-rolled useNodes hook into useNodesQuery (server data +
    NodeRecord type + derived totals) and useNodeMutations (add/update/del/
    setEnable/probe/test). Mutations invalidate ['nodes'] on success, so
    the list refreshes without each call awaiting a manual refresh().
    
    NodesPage drops useWebSocket({ nodes: applyNodesEvent }) — the
    WebSocket → query bridge now forwards the 'nodes' push to
    setQueryData(['nodes', 'list']) once at the SPA root.
    
    InboundsPage and the inbound form/list components import NodeRecord
    from its new home next to the query hook.
    
    * feat(frontend): migrate useAllSetting to TanStack Query
    
    Replaces the hand-rolled fetch + dirty-tracking hook with useAllSettings
    backed by useQuery + useMutation. The draft (current edits) is kept in
    local state and reset whenever query.data lands. saveAll posts the
    draft via a mutation; on success, invalidating ['settings'] refetches
    and the useEffect resets the draft so saveDisabled flips back to true.
    
    staleTime: Infinity prevents refetchOnWindowFocus from clobbering
    in-flight edits — settings only change in response to this user's own
    save.
    
    setSpinning stays as a pass-through to a local flag so the existing
    restartPanel flow in SettingsPage keeps showing its spinner.
    
    * feat(frontend): route useInbounds fetches through TanStack Query
    
    Rewrites useInbounds so its four server fetches (slim list, default
    settings, online clients, last-online map) live in useQuery with
    staleTime: Infinity. The in-place WS merge logic for traffic and
    client_stats is preserved — applyTrafficEvent / applyClientStatsEvent
    still mutate the locally-mirrored dbInbounds so the panel doesn't
    refetch every 1-2 seconds when stats stream in.
    
    refresh() becomes a thin invalidateQueries on the three list keys,
    which mutations in the page already call after add/edit/del.
    
    The bridge now forwards the WebSocket 'inbounds' push to
    setQueryData(['inbounds', 'slim']), and InboundsPage drops its
    useEffect(fetchDefaultSettings → refresh) plus the invalidate /
    inbounds wiring on useWebSocket — both are owned by the bridge now.
    
    * feat(frontend): migrate useClients to TanStack Query
    
    Replaces 12 hand-rolled mutation callbacks and a tangle of useState +
    useRef + useEffect with one useQuery (paged list) + nine useMutation
    wrappers. The list query uses keepPreviousData so paging/filter
    changes don't blank the table mid-fetch.
    
    The setQuery shallow-compare logic is preserved for backward
    compatibility with ClientsPage's effect that rebuilds the params on
    every render. Internally setQuery only updates state when the params
    actually differ — Query's queryKey equality handles the rest.
    
    WS-driven applyTrafficEvent / applyClientStatsEvent now mutate the
    query cache via setQueryData(['clients', 'list', currentParams]) so
    per-second stats updates skip a full refetch. applyInvalidate is gone
    from the hook — the bridge owns coarse 'clients' invalidation.
    
    ClientsPage drops the invalidate handler from its useWebSocket
    subscription; auxiliary queries (inboundOptions, defaults, onlines)
    load via TanStack Query and are shared with useInbounds via the same
    query keys.
    
    * feat(frontend): route useXraySetting fetches through TanStack Query
    
    Keeps the bidirectional xraySetting ↔ templateSettings editor sync and
    the 1s dirty-tracking interval intact (those are local editor state,
    not server data). All seven server calls move:
    
    - config + traffic → useQuery on ['xray', 'config'] and
      ['xray', 'outboundsTraffic']
    - saveAll → useMutation that invalidates the config query
    - resetOutboundsTraffic → useMutation that invalidates the traffic
      query
    - restartXray → useMutation (fires the restart, then reads the
      result string)
    - resetToDefault → useMutation (fetch default config, push it into
      the editor via setTemplateSettings)
    
    The WebSocket 'outbounds' event already lands in
    keys.xray.outboundsTraffic() via the bridge, so XrayPage drops its
    useWebSocket({ outbounds: applyOutboundsEvent }) wiring entirely and
    the hook no longer exposes applyOutboundsEvent.
    
    A useEffect seeds xraySetting / templateSettings / tags / test URL
    from query data on first fetch and on every refetch, mirroring what
    the original fetchAll() did.
    
    * fix(frontend): restore per-route document titles in the SPA
    
    When the multi-entry MPA collapsed into a single index.html, every
    route inherited the static <title>3X-UI</title> from the shared shell,
    so every panel page showed "hostname - 3X-UI" instead of the original
    "hostname - Overview / Clients / Inbounds / ...".
    
    usePageTitle reads the current pathname and rewrites document.title
    on every navigation, matching the titles the deleted *.html files
    used to carry. Mounted in PanelLayout so it covers all panel routes
    without each page having to opt in.
    
    The startup applyDocumentTitle() call in main.tsx is gone — the hook
    sets the full "hostname - PageTitle" string itself.
    
    * feat(api-docs): expose OpenAPI spec + render Swagger UI in panel
    
    Replaces the hand-rolled API docs UI with industry-standard tooling so
    external integrations (Postman, Insomnia, openapi-generator) can
    consume the panel API without parsing endpoints.js by hand.
    
    Generator
    - frontend/scripts/build-openapi.mjs: walks the existing endpoints.js
      (still the single source of truth) and emits an OpenAPI 3.0.3 spec
      at frontend/public/openapi.json. Handles Gin :param → {param} path
      translation, body / query / path parameter splits, 200 + error
      response examples, and Bearer + cookie security schemes
    - npm run build now runs gen:api before vite build, so the spec is
      always in sync with what's documented
    
    Backend
    - web/controller/dist.go exposes ServeOpenAPISpec which streams the
      embedded dist/openapi.json with a short Cache-Control. Public
      endpoint (no auth) so Postman can fetch it without first logging in
    - web/web.go wires GET /panel/api/openapi.json before the auth-gated
      /panel/api router
    
    Panel
    - ApiDocsPage now renders swagger-ui-react fed by the basePath-aware
      openapi.json URL. Dark mode is overridden via CSS targeting the
      Swagger UI internals
    - CodeBlock / EndpointRow / EndpointSection are gone; the swagger-ui
      vendor chunk (134 KB gzipped) only loads on this lazy route, not on
      every panel page
    - vite.config: vendor-swagger manualChunk keeps the new dep out of
      the main vendor bundle
    
    For Postman: import http://<panel>/panel/api/openapi.json. Everything
    from /login + /panel/api/* shows up with auth, params, and examples.
    
    * style(api-docs): dark/ultra theme for Swagger UI
    
    Override every visual surface Swagger does not theme on its own:
    opblocks, tables, model boxes, form inputs, code blocks, modals,
    Servers dropdown, per-endpoint padlocks and expand chevrons. Replaces
    Swagger's default light-arrow chevron on selects with a light-fill SVG
    positioned at the corner so the dark background-color is visible.
    
    Also disables deepLinking to silence the noisy v4 underscore warning;
    not used in our panel.