From 606d988839a1a77bb869960a853cfe34db78bda6 Mon Sep 17 00:00:00 2001 From: Sanaei Date: Wed, 25 Nov 2026 17:25:11 +0330 Subject: [PATCH] fix(settings): build the post-restart URL from the panel's own listener After Restart Panel the page guessed its next address from stored settings: https only when a certificate was configured, and on an IP entry the stored webPort. Behind a TLS-terminating proxy on a non-default port that sent the browser to http://host:port and onto the proxy's "plain HTTP request sent to HTTPS port" page; behind a published port it sent the browser to the panel's internal port. XUI_PORT and a certificate pair that does not load were not accounted for either. The restart call now answers with the listener that took it and the one the restarted panel opens, both computed where the truth is. The page follows a scheme or port change only where its own address matches the serving listener, so a proxy or port mapping keeps the address the browser reached it on. A panel reached directly by name now also follows a changed port instead of staying on the dead one. --- .../docs/en/reference/api/settings.mdx | 8 +- docs/public/openapi.json | 42 ++++++- frontend/public/openapi.json | 42 ++++++- frontend/src/generated/examples.ts | 6 + frontend/src/generated/schemas.ts | 28 +++++ frontend/src/generated/types.ts | 7 ++ frontend/src/generated/zod.ts | 8 ++ frontend/src/pages/api-docs/endpoints.ts | 3 + frontend/src/pages/settings/SettingsPage.tsx | 51 +------- frontend/src/pages/settings/restart-url.ts | 45 ++++++++ frontend/src/test/restart-url.test.ts | 56 +++++++++ .../web/controller/node_restart_auth_test.go | 109 ++++++++++++++++++ internal/web/controller/setting.go | 8 +- internal/web/entity/entity.go | 8 ++ internal/web/service/setting.go | 13 +++ internal/web/web.go | 12 +- tools/openapigen/main.go | 1 + 17 files changed, 386 insertions(+), 61 deletions(-) create mode 100644 frontend/src/pages/settings/restart-url.ts create mode 100644 frontend/src/test/restart-url.test.ts diff --git a/docs/content/docs/en/reference/api/settings.mdx b/docs/content/docs/en/reference/api/settings.mdx index 9a0c6f100..293212b12 100644 --- a/docs/content/docs/en/reference/api/settings.mdx +++ b/docs/content/docs/en/reference/api/settings.mdx @@ -112,7 +112,13 @@ _openapi: - content: Return the built-in default Xray JSON config template that ships with this panel version. id: return-the-built-in-default-xray-json-config-template-that-ships-with-this-panel-version - contents: [] + contents: + - content: The answer names the listener that took the call (port, tls) and the + one the restarted panel opens (nextPort, nextTls), with XUI_PORT and + an unloadable certificate pair already applied. A client reaching the + panel through a proxy or a port mapping compares port and tls with the + address it used, and follows a change only where they match. + heading: restart-the-entire-3x-ui-process-after-a-3-second-grace-period-the-connection-drops-immediately-the-panel-comes-back-online-5-10-seconds-later --- {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} diff --git a/docs/public/openapi.json b/docs/public/openapi.json index 76981ff63..463b0cb7b 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -4765,6 +4765,34 @@ ], "type": "object" }, + "PanelRestart": { + "description": "PanelRestart describes the listener that took the restart call and the one that follows.", + "properties": { + "nextPort": { + "example": 2053, + "type": "integer" + }, + "nextTls": { + "example": false, + "type": "boolean" + }, + "port": { + "example": 2053, + "type": "integer" + }, + "tls": { + "example": false, + "type": "boolean" + } + }, + "required": [ + "nextPort", + "nextTls", + "port", + "tls" + ], + "type": "object" + }, "PanelUpdateStatus": { "description": "PanelUpdateStatus reports the outcome of the most recently launched panel\nself-update. RunID lets the caller confirm this status belongs to the\nupdate it started rather than a stale result left over from an earlier\nrun; State is one of \"pending\", \"success\", or \"failed\". RunID is a decimal\nstring, not a JSON number: it's a formatted UnixNano timestamp, and\nJavaScript's number type can't represent that precisely (it exceeds\nNumber.MAX_SAFE_INTEGER), which would let two different runs round to the\nsame value on the wire and defeat the whole point of this field.", "properties": { @@ -15809,6 +15837,7 @@ ], "summary": "Restart the entire 3x-ui process after a 3-second grace period. The connection drops immediately; the panel comes back online ~5-10 seconds later.", "operationId": "post_panel_api_setting_restartPanel", + "description": "The answer names the listener that took the call (port, tls) and the one the restarted panel opens (nextPort, nextTls), with XUI_PORT and an unloadable certificate pair already applied. A client reaching the panel through a proxy or a port mapping compares port and tls with the address it used, and follows a change only where they match.", "responses": { "200": { "description": "Successful response", @@ -15823,7 +15852,18 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/PanelRestart" + } + } + }, + "example": { + "success": true, + "obj": { + "nextPort": 2053, + "nextTls": false, + "port": 2053, + "tls": false } } } diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index 76981ff63..463b0cb7b 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -4765,6 +4765,34 @@ ], "type": "object" }, + "PanelRestart": { + "description": "PanelRestart describes the listener that took the restart call and the one that follows.", + "properties": { + "nextPort": { + "example": 2053, + "type": "integer" + }, + "nextTls": { + "example": false, + "type": "boolean" + }, + "port": { + "example": 2053, + "type": "integer" + }, + "tls": { + "example": false, + "type": "boolean" + } + }, + "required": [ + "nextPort", + "nextTls", + "port", + "tls" + ], + "type": "object" + }, "PanelUpdateStatus": { "description": "PanelUpdateStatus reports the outcome of the most recently launched panel\nself-update. RunID lets the caller confirm this status belongs to the\nupdate it started rather than a stale result left over from an earlier\nrun; State is one of \"pending\", \"success\", or \"failed\". RunID is a decimal\nstring, not a JSON number: it's a formatted UnixNano timestamp, and\nJavaScript's number type can't represent that precisely (it exceeds\nNumber.MAX_SAFE_INTEGER), which would let two different runs round to the\nsame value on the wire and defeat the whole point of this field.", "properties": { @@ -15809,6 +15837,7 @@ ], "summary": "Restart the entire 3x-ui process after a 3-second grace period. The connection drops immediately; the panel comes back online ~5-10 seconds later.", "operationId": "post_panel_api_setting_restartPanel", + "description": "The answer names the listener that took the call (port, tls) and the one the restarted panel opens (nextPort, nextTls), with XUI_PORT and an unloadable certificate pair already applied. A client reaching the panel through a proxy or a port mapping compares port and tls with the address it used, and follows a change only where they match.", "responses": { "200": { "description": "Successful response", @@ -15823,7 +15852,18 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/PanelRestart" + } + } + }, + "example": { + "success": true, + "obj": { + "nextPort": 2053, + "nextTls": false, + "port": 2053, + "tls": false } } } diff --git a/frontend/src/generated/examples.ts b/frontend/src/generated/examples.ts index f4a55ffc1..93b98ec8b 100644 --- a/frontend/src/generated/examples.ts +++ b/frontend/src/generated/examples.ts @@ -1212,6 +1212,12 @@ export const EXAMPLES: Record = { "total": 0, "up": 0 }, + "PanelRestart": { + "nextPort": 2053, + "nextTls": false, + "port": 2053, + "tls": false + }, "PanelUpdateStatus": { "exitCode": 0, "finishedAt": 1735689612, diff --git a/frontend/src/generated/schemas.ts b/frontend/src/generated/schemas.ts index 5e9320253..4fcbe9d81 100644 --- a/frontend/src/generated/schemas.ts +++ b/frontend/src/generated/schemas.ts @@ -4739,6 +4739,34 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "PanelRestart": { + "description": "PanelRestart describes the listener that took the restart call and the one that follows.", + "properties": { + "nextPort": { + "example": 2053, + "type": "integer" + }, + "nextTls": { + "example": false, + "type": "boolean" + }, + "port": { + "example": 2053, + "type": "integer" + }, + "tls": { + "example": false, + "type": "boolean" + } + }, + "required": [ + "nextPort", + "nextTls", + "port", + "tls" + ], + "type": "object" + }, "PanelUpdateStatus": { "description": "PanelUpdateStatus reports the outcome of the most recently launched panel\nself-update. RunID lets the caller confirm this status belongs to the\nupdate it started rather than a stale result left over from an earlier\nrun; State is one of \"pending\", \"success\", or \"failed\". RunID is a decimal\nstring, not a JSON number: it's a formatted UnixNano timestamp, and\nJavaScript's number type can't represent that precisely (it exceeds\nNumber.MAX_SAFE_INTEGER), which would let two different runs round to the\nsame value on the wire and defeat the whole point of this field.", "properties": { diff --git a/frontend/src/generated/types.ts b/frontend/src/generated/types.ts index 3d851811d..306252fc3 100644 --- a/frontend/src/generated/types.ts +++ b/frontend/src/generated/types.ts @@ -1069,6 +1069,13 @@ export interface OutboundTraffics { up: number; } +export interface PanelRestart { + nextPort: number; + nextTls: boolean; + port: number; + tls: boolean; +} + export interface PanelUpdateStatus { exitCode: number; finishedAt: number; diff --git a/frontend/src/generated/zod.ts b/frontend/src/generated/zod.ts index 02164dac4..50e218939 100644 --- a/frontend/src/generated/zod.ts +++ b/frontend/src/generated/zod.ts @@ -1132,6 +1132,14 @@ export const OutboundTrafficsSchema = z.object({ }); export type OutboundTraffics = z.infer; +export const PanelRestartSchema = z.object({ + nextPort: z.number().int(), + nextTls: z.boolean(), + port: z.number().int(), + tls: z.boolean(), +}); +export type PanelRestart = z.infer; + export const PanelUpdateStatusSchema = z.object({ exitCode: z.number().int(), finishedAt: z.number().int(), diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts index 75bcb7af9..64baf3b73 100644 --- a/frontend/src/pages/api-docs/endpoints.ts +++ b/frontend/src/pages/api-docs/endpoints.ts @@ -2338,6 +2338,9 @@ export const sections: readonly Section[] = [ path: '/panel/api/setting/restartPanel', summary: 'Restart the entire 3x-ui process after a 3-second grace period. The connection drops immediately; the panel comes back online ~5-10 seconds later.', + description: + 'The answer names the listener that took the call (port, tls) and the one the restarted panel opens (nextPort, nextTls), with XUI_PORT and an unloadable certificate pair already applied. A client reaching the panel through a proxy or a port mapping compares port and tls with the address it used, and follows a change only where they match.', + responseSchema: 'PanelRestart', }, { method: 'POST', diff --git a/frontend/src/pages/settings/SettingsPage.tsx b/frontend/src/pages/settings/SettingsPage.tsx index c666bafd1..60e3a8d90 100644 --- a/frontend/src/pages/settings/SettingsPage.tsx +++ b/frontend/src/pages/settings/SettingsPage.tsx @@ -22,6 +22,7 @@ import { useTheme } from '@/hooks/useTheme'; import { useMediaQuery } from '@/hooks/useMediaQuery'; import { useAllSettings } from '@/api/queries/useAllSettings'; import { AllSettingSchema } from '@/schemas/setting'; +import { PanelRestartSchema } from '@/generated/zod'; import AppSidebar from '@/layouts/AppSidebar'; import GeneralTab from './GeneralTab'; import SecurityTab from './SecurityTab'; @@ -32,10 +33,12 @@ import WechatTab from './WechatTab'; import SubscriptionGeneralTab from './SubscriptionGeneralTab'; import SubscriptionFormatsTab from './SubscriptionFormatsTab'; import SubscriptionBalancersTab from './SubscriptionBalancersTab'; +import { panelUrlAfterRestart } from './restart-url'; import './SettingsPage.css'; interface ApiMsg { success?: boolean; + obj?: unknown; } const tabSlugs = [ @@ -50,22 +53,6 @@ const tabSlugs = [ 'subscription-balancers', ]; -function isIp(h: string): boolean { - if (typeof h !== 'string') return false; - const v4 = h.split('.'); - if (v4.length === 4 && v4.every((p) => /^\d{1,3}$/.test(p) && Number(p) <= 255)) return true; - if (!h.includes(':') || h.includes(':::')) return false; - const parts = h.split('::'); - if (parts.length > 2) return false; - const split = (s: string) => (s ? s.split(':').filter(Boolean) : []); - const head = split(parts[0]); - const tail = split(parts[1]); - const valid = (seg: string) => /^[0-9a-fA-F]{1,4}$/.test(seg); - if (![...head, ...tail].every(valid)) return false; - const groups = head.length + tail.length; - return parts.length === 2 ? groups < 8 : groups === 8; -} - function scrollTarget() { return document.getElementById('content-layout') as HTMLElement; } @@ -92,40 +79,11 @@ export default function SettingsPage() { savePayload, } = useAllSettings(); - const [entryHost] = useState(() => window.location.hostname); - const [entryPort] = useState(() => window.location.port); - const [entryIsIP] = useState(() => isIp(window.location.hostname)); - const [alertVisible, setAlertVisible] = useState(true); const location = useLocation(); const slug = location.hash.replace(/^#/, ''); const activeSlug = tabSlugs.includes(slug) ? slug : 'general'; - function rebuildUrlAfterRestart(): string { - const { webDomain, webPort, webBasePath, webCertFile, webKeyFile } = allSetting; - const newProtocol = webCertFile || webKeyFile ? 'https:' : 'http:'; - - let base = webBasePath ? webBasePath.replace(/^\//, '') : ''; - if (base && !base.endsWith('/')) base += '/'; - - if (!entryIsIP) { - const url = new URL(window.location.href); - url.pathname = `/${base}panel/settings`; - url.protocol = newProtocol; - return url.toString(); - } - - let finalHost = entryHost; - let finalPort = entryPort || ''; - if (webDomain && isIp(webDomain)) finalHost = webDomain; - if (webPort && Number(webPort) !== Number(entryPort)) finalPort = String(webPort); - - const url = new URL(`${newProtocol}//${finalHost}`); - if (finalPort) url.port = finalPort; - url.pathname = `/${base}panel/settings`; - return url.toString(); - } - async function onSave() { const result = AllSettingSchema.safeParse(allSetting); if (!result.success) { @@ -150,7 +108,8 @@ export default function SettingsPage() { try { const msg = (await HttpUtil.post('/panel/api/setting/restartPanel')) as ApiMsg; if (!msg?.success) return; - const target = rebuildUrlAfterRestart(); + const restart = PanelRestartSchema.safeParse(msg.obj); + const target = panelUrlAfterRestart(window.location.href, restart.data, allSetting); await PromiseUtil.waitForPanel(target); window.location.replace(target); } finally { diff --git a/frontend/src/pages/settings/restart-url.ts b/frontend/src/pages/settings/restart-url.ts new file mode 100644 index 000000000..ff417f3e3 --- /dev/null +++ b/frontend/src/pages/settings/restart-url.ts @@ -0,0 +1,45 @@ +import type { PanelRestart } from '@/generated/zod'; + +function isIp(h: string): boolean { + if (typeof h !== 'string') return false; + const v4 = h.split('.'); + if (v4.length === 4 && v4.every((p) => /^\d{1,3}$/.test(p) && Number(p) <= 255)) return true; + if (!h.includes(':') || h.includes(':::')) return false; + const parts = h.split('::'); + if (parts.length > 2) return false; + const split = (s: string) => (s ? s.split(':').filter(Boolean) : []); + const head = split(parts[0]); + const tail = split(parts[1]); + const valid = (seg: string) => /^[0-9a-fA-F]{1,4}$/.test(seg); + if (![...head, ...tail].every(valid)) return false; + const groups = head.length + tail.length; + return parts.length === 2 ? groups < 8 : groups === 8; +} + +interface RestartUrlSettings { + webBasePath?: string; + webDomain?: string; +} + +// Scheme and port follow the panel only where the browser's own match the listener that +// answered; a proxy or a published port in front of it keeps the address it was reached on. +export function panelUrlAfterRestart( + current: string, + restart: PanelRestart | undefined, + { webBasePath, webDomain }: RestartUrlSettings, +): string { + const url = new URL(current); + if (restart) { + const pageTls = url.protocol === 'https:'; + const pagePort = Number(url.port) || (pageTls ? 443 : 80); + if (pageTls === restart.tls) url.protocol = restart.nextTls ? 'https:' : 'http:'; + url.port = String(pagePort === restart.port ? restart.nextPort : pagePort); + } + if (isIp(url.hostname.replace(/^\[|\]$/g, '')) && webDomain && isIp(webDomain)) { + url.hostname = webDomain.includes(':') ? `[${webDomain}]` : webDomain; + } + let base = webBasePath ? webBasePath.replace(/^\//, '') : ''; + if (base && !base.endsWith('/')) base += '/'; + url.pathname = `/${base}panel/settings`; + return url.toString(); +} diff --git a/frontend/src/test/restart-url.test.ts b/frontend/src/test/restart-url.test.ts new file mode 100644 index 000000000..acd6d4e6e --- /dev/null +++ b/frontend/src/test/restart-url.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from 'vitest'; + +import { panelUrlAfterRestart } from '@/pages/settings/restart-url'; + +const plain2053 = { port: 2053, tls: false, nextPort: 2053, nextTls: false }; + +describe('panelUrlAfterRestart', () => { + it.each([ + { + name: 'a TLS-terminating proxy on its own port keeps its scheme and port', + current: 'https://panel.example.com:8443/panel/settings#security', + restart: plain2053, + want: 'https://panel.example.com:8443/panel/settings#security', + }, + { + name: 'reached directly, the panel turning TLS on moves the browser to https', + current: 'http://203.0.113.5:2053/panel/settings', + restart: { ...plain2053, nextTls: true }, + want: 'https://203.0.113.5:2053/panel/settings', + }, + { + name: 'reached directly by name, a new panel port is followed', + current: 'https://panel.example.com:2053/panel/settings', + restart: { port: 2053, tls: true, nextPort: 3000, nextTls: true }, + want: 'https://panel.example.com:3000/panel/settings', + }, + { + name: 'a published port that maps onto the panel port is kept', + current: 'http://203.0.113.5:8080/panel/settings', + restart: plain2053, + want: 'http://203.0.113.5:8080/panel/settings', + }, + { + name: 'an implicit port 80 stays 80 when the scheme changes under it', + current: 'http://203.0.113.5/panel/settings', + restart: { port: 80, tls: false, nextPort: 80, nextTls: true }, + want: 'https://203.0.113.5:80/panel/settings', + }, + { + name: 'without a listener answer only the path is rebuilt', + current: 'https://panel.example.com:8443/old/panel/settings', + restart: undefined, + settings: { webBasePath: '/new' }, + want: 'https://panel.example.com:8443/new/panel/settings', + }, + { + name: 'an IP entry follows a panel domain that is itself an IP', + current: 'http://203.0.113.5:2053/panel/settings', + restart: plain2053, + settings: { webDomain: '2001:db8::7' }, + want: 'http://[2001:db8::7]:2053/panel/settings', + }, + ])('$name', ({ current, restart, settings, want }) => { + expect(panelUrlAfterRestart(current, restart, settings ?? {})).toBe(want); + }); +}); diff --git a/internal/web/controller/node_restart_auth_test.go b/internal/web/controller/node_restart_auth_test.go index f00e74dc1..f3fbdb5a5 100644 --- a/internal/web/controller/node_restart_auth_test.go +++ b/internal/web/controller/node_restart_auth_test.go @@ -1,18 +1,29 @@ package controller import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" "crypto/tls" "crypto/x509" "encoding/json" + "encoding/pem" + "math/big" "net/http" "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strconv" "testing" "time" "github.com/mhsanaei/3x-ui/v3/internal/database" "github.com/mhsanaei/3x-ui/v3/internal/database/model" "github.com/mhsanaei/3x-ui/v3/internal/util/crypto" + "github.com/mhsanaei/3x-ui/v3/internal/web/entity" "github.com/mhsanaei/3x-ui/v3/internal/web/global" + "github.com/mhsanaei/3x-ui/v3/internal/web/service" ) func TestPanelRestartScopeAndDelayedHook(t *testing.T) { @@ -66,3 +77,101 @@ func TestPanelRestartScopeAndDelayedHook(t *testing.T) { } } } + +func writeLoadableKeyPair(t *testing.T) (certFile, keyFile string) { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + template := &x509.Certificate{SerialNumber: big.NewInt(1), NotAfter: time.Now().Add(time.Hour)} + certDER, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + keyDER, err := x509.MarshalPKCS8PrivateKey(key) + if err != nil { + t.Fatal(err) + } + certFile = filepath.Join(t.TempDir(), "panel.crt") + keyFile = filepath.Join(t.TempDir(), "panel.key") + for file, block := range map[string]*pem.Block{ + certFile: {Type: "CERTIFICATE", Bytes: certDER}, + keyFile: {Type: "PRIVATE KEY", Bytes: keyDER}, + } { + if err := os.WriteFile(file, pem.EncodeToMemory(block), 0o600); err != nil { + t.Fatal(err) + } + } + return certFile, keyFile +} + +// The settings page turns this answer into its post-restart URL. Guessing from stored +// settings sent a browser behind a TLS proxy to http:// and ignored XUI_PORT. +func TestPanelRestartReportsServingAndNextListener(t *testing.T) { + engine, auth := newAPIAuthTestEngine(t) + NewSettingController(engine.Group("/panel/api", auth.checkAPIAuth, auth.enforceTokenScope)) + global.SetRestartHook(func() {}) + t.Cleanup(func() { global.SetRestartHook(func() {}) }) + if err := database.GetDB().Create(&model.ApiToken{Name: "admin", Token: crypto.HashTokenSHA256("admin"), Enabled: true, Scope: model.ApiScopeAdmin}).Error; err != nil { + t.Fatal(err) + } + certFile, keyFile := writeLoadableKeyPair(t) + settings := service.SettingService{} + + for _, tc := range []struct { + name string + servingTLS bool + cert, key string + portOverride string + wantNextPort int + wantNextTLS bool + }{ + {name: "plain listener, nothing configured", wantNextPort: 3000}, + {name: "plain listener, key pair configured", cert: certFile, key: keyFile, wantNextPort: 3000, wantNextTLS: true}, + {name: "a certificate without its key stays plain", cert: certFile, wantNextPort: 3000}, + {name: "XUI_PORT outranks the stored port", portOverride: "8443", wantNextPort: 8443}, + {name: "TLS listener, key pair removed", servingTLS: true, wantNextPort: 3000}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("XUI_PORT", tc.portOverride) + if err := settings.SetPort(3000); err != nil { + t.Fatal(err) + } + if err := settings.SetCertFile(tc.cert); err != nil { + t.Fatal(err) + } + if err := settings.SetKeyFile(tc.key); err != nil { + t.Fatal(err) + } + server := httptest.NewUnstartedServer(engine) + if tc.servingTLS { + server.StartTLS() + } else { + server.Start() + } + t.Cleanup(server.Close) + u, _ := url.Parse(server.URL) + servingPort, _ := strconv.Atoi(u.Port()) + + req, _ := http.NewRequest(http.MethodPost, server.URL+"/panel/api/setting/restartPanel", nil) + req.Header.Set("Authorization", "Bearer admin") + res, err := server.Client().Do(req) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + var answer struct { + Success bool `json:"success"` + Obj entity.PanelRestart `json:"obj"` + } + if err := json.NewDecoder(res.Body).Decode(&answer); err != nil || !answer.Success { + t.Fatalf("status %d, success=%v, err=%v", res.StatusCode, answer.Success, err) + } + want := entity.PanelRestart{Port: servingPort, TLS: tc.servingTLS, NextPort: tc.wantNextPort, NextTLS: tc.wantNextTLS} + if answer.Obj != want { + t.Fatalf("restart answer = %+v, want %+v", answer.Obj, want) + } + }) + } +} diff --git a/internal/web/controller/setting.go b/internal/web/controller/setting.go index e9b71dce2..ca5c25fad 100644 --- a/internal/web/controller/setting.go +++ b/internal/web/controller/setting.go @@ -2,6 +2,7 @@ package controller import ( "errors" + "net" "net/http" "strconv" "strings" @@ -234,8 +235,13 @@ func (a *SettingController) updateUser(c *gin.Context) { // restartPanel restarts the panel service after a delay. func (a *SettingController) restartPanel(c *gin.Context) { + answer := entity.PanelRestart{TLS: c.Request.TLS != nil, NextTLS: a.settingService.DirectHTTPSConfigured()} + if addr, ok := c.Request.Context().Value(http.LocalAddrContextKey).(*net.TCPAddr); ok { + answer.Port = addr.Port + } + answer.NextPort, _ = a.settingService.GetListenPort() err := a.panelService.RestartPanel(time.Second * 3) - jsonMsg(c, I18nWeb(c, "pages.settings.restartPanelSuccess"), err) + jsonMsgObj(c, I18nWeb(c, "pages.settings.restartPanelSuccess"), answer, err) } // getDefaultXrayConfig retrieves the default Xray configuration. diff --git a/internal/web/entity/entity.go b/internal/web/entity/entity.go index 2f38bf18f..590ff3c97 100644 --- a/internal/web/entity/entity.go +++ b/internal/web/entity/entity.go @@ -20,6 +20,14 @@ type Msg struct { Obj any `json:"obj"` } +// PanelRestart describes the listener that took the restart call and the one that follows. +type PanelRestart struct { + Port int `json:"port" example:"2053"` + TLS bool `json:"tls" example:"false"` + NextPort int `json:"nextPort" example:"2053"` + NextTLS bool `json:"nextTls" example:"false"` +} + type AllSetting struct { WebListen string `json:"webListen" form:"webListen"` WebDomain string `json:"webDomain" form:"webDomain"` diff --git a/internal/web/service/setting.go b/internal/web/service/setting.go index f6ef749a1..ac05ff705 100644 --- a/internal/web/service/setting.go +++ b/internal/web/service/setting.go @@ -1,6 +1,7 @@ package service import ( + "crypto/tls" _ "embed" "encoding/json" "errors" @@ -759,6 +760,18 @@ func (s *SettingService) GetCertFile() (string, error) { return s.getString("webCertFile") } +// DirectHTTPSConfigured reports whether the next panel start serves TLS itself: +// the stored certificate and key must both be set and load as a pair. +func (s *SettingService) DirectHTTPSConfigured() bool { + certFile, certErr := s.GetCertFile() + keyFile, keyErr := s.GetKeyFile() + if certErr != nil || keyErr != nil || certFile == "" || keyFile == "" { + return false + } + _, err := tls.LoadX509KeyPair(certFile, keyFile) + return err == nil +} + func (s *SettingService) SetKeyFile(webKeyFile string) error { return s.setString("webKeyFile", webKeyFile) } diff --git a/internal/web/web.go b/internal/web/web.go index bac32b715..298ee8adf 100644 --- a/internal/web/web.go +++ b/internal/web/web.go @@ -159,16 +159,6 @@ func NewServer(subLinkProvider service.SubLinkProvider) *Server { } } -func (s *Server) isDirectHTTPSConfigured() bool { - certFile, certErr := s.settingService.GetCertFile() - keyFile, keyErr := s.settingService.GetKeyFile() - if certErr != nil || keyErr != nil || certFile == "" || keyFile == "" { - return false - } - _, err := tls.LoadX509KeyPair(certFile, keyFile) - return err == nil -} - // initRouter initializes Gin, registers middleware, templates, static // assets, controllers and returns the configured engine. func (s *Server) initRouter() (*gin.Engine, error) { @@ -181,7 +171,7 @@ func (s *Server) initRouter() (*gin.Engine, error) { } engine := gin.Default() - directHTTPS := s.isDirectHTTPSConfigured() + directHTTPS := s.settingService.DirectHTTPSConfigured() sendHSTS := directHTTPS && !config.IsSkipHSTS() engine.Use(middleware.SecurityHeadersMiddleware(sendHSTS)) diff --git a/tools/openapigen/main.go b/tools/openapigen/main.go index 35dc5e992..4eb76045d 100644 --- a/tools/openapigen/main.go +++ b/tools/openapigen/main.go @@ -74,6 +74,7 @@ func run(root, outDir string) error { "AllSetting", "AllSettingView", "HostGroup", + "PanelRestart", ), }, {