仰望星辰工作室

miaopanel

miaopanel/ internal/httpapi/settings.go 13.3 KB · 409 行 原始文件
1package httpapi
2
3import (
4 "context"
5 "crypto/x509"
6 "encoding/pem"
7 "errors"
8 "fmt"
9 "net"
10 "net/http"
11 "os"
12 "path/filepath"
13 "strconv"
14 "strings"
15 "time"
16
17 "github.com/miaopanel/miaopanel/internal/paneltls"
18 "github.com/miaopanel/miaopanel/internal/webserver"
19)
20
21// settingsPayload is what the settings page renders.
22type settingsPayload struct {
23 Entry string `json:"entry"`
24 SessionTTLMinutes int `json:"session_ttl_minutes"`
25 HTTPS bool `json:"https"`
26 AppDomain string `json:"app_domain"`
27 CertPath string `json:"cert_path"`
28 CertIssuer string `json:"cert_issuer"`
29 CertNotAfter int64 `json:"cert_not_after"`
30 CertSelfSigned bool `json:"cert_self_signed"`
31 Port string `json:"port"`
32 Version string `json:"version"`
33}
34
35func (s *Server) settingsSnapshot() settingsPayload {
36 issuer, notAfter, selfSigned := certificateInfo(s.cfg.HTTPSCert)
37 if s.cfg.HTTPSCert == "" {
38 issuer, notAfter, selfSigned = certificateInfo(filepath.Join(s.cfg.SelfSignedDir(), "panel.crt"))
39 }
40 return settingsPayload{
41 Entry: s.cfg.Entry,
42 SessionTTLMinutes: s.cfg.SessionTTLMinutes,
43 HTTPS: s.cfg.HTTPSEnabled(),
44 AppDomain: s.cfg.AppDomain,
45 CertPath: s.cfg.HTTPSCert,
46 CertIssuer: issuer,
47 CertNotAfter: notAfter,
48 CertSelfSigned: selfSigned,
49 Port: portOf(s.cfg.Addr),
50 Version: s.version,
51 }
52}
53
54func certificateInfo(certPath string) (string, int64, bool) {
55 if certPath == "" {
56 return "", 0, false
57 }
58 raw, err := os.ReadFile(certPath)
59 if err != nil {
60 return "", 0, false
61 }
62 block, _ := pem.Decode(raw)
63 if block == nil {
64 return "", 0, false
65 }
66 crt, err := x509.ParseCertificate(block.Bytes)
67 if err != nil {
68 return "", 0, false
69 }
70 return crt.Issuer.String(), crt.NotAfter.Unix(), crt.Issuer.String() == crt.Subject.String()
71}
72
73func portOf(addr string) string {
74 if i := strings.LastIndex(addr, ":"); i >= 0 {
75 return addr[i+1:]
76 }
77 return "8888"
78}
79
80// portSuffix is the ":8888" part of an app URL; empty for the default 443.
81func portSuffix(addr string) string {
82 port := portOf(addr)
83 if port == "" || port == "443" {
84 return ""
85 }
86 return ":" + port
87}
88
89func (s *Server) handleSettingsGet(w http.ResponseWriter, r *http.Request) {
90 writeOK(w, s.settingsSnapshot())
91}
92
93type entryReq struct {
94 Entry string `json:"entry"`
95}
96
97func (s *Server) handleSettingsEntry(w http.ResponseWriter, r *http.Request) {
98 var req entryReq
99 if err := decodeJSON(w, r, &req, 4<<10); err != nil {
100 writeErr(w, err)
101 return
102 }
103 entry := strings.ToLower(strings.Trim(strings.TrimSpace(req.Entry), "/"))
104 if !validEntry(entry) {
105 writeJSON(w, http.StatusBadRequest, Envelope{
106 Code: 400, Msg: "安全入口需为 4-32 位小写字母或数字",
107 })
108 return
109 }
110 started := time.Now()
111 old := s.cfg.Entry
112 s.cfg.Entry = entry
113 if err := s.cfg.Save(); err != nil {
114 s.cfg.Entry = old
115 writeErr(w, err)
116 return
117 }
118 s.setEntry(entry)
119 // Rotating the entry is a credential change: sessions obtained with the old
120 // entry (including Bearer tokens, which ignore the cookie Path) must die,
121 // not just look logged out in the browser.
122 if user, err := requireUser(r); err == nil {
123 _, _ = s.db.DeleteOtherSessions(r.Context(), user.ID, "")
124 }
125 s.audit(r, "settings", "entry", entry, "ok", started)
126 // The old cookie Path no longer matches, so the browser must re-login at
127 // the new prefix. The response tells the UI where to go.
128 writeOK(w, map[string]any{"entry": entry, "relogin": true})
129}
130
131func validEntry(entry string) bool {
132 if len(entry) < 4 || len(entry) > 32 {
133 return false
134 }
135 for _, c := range entry {
136 if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') {
137 continue
138 }
139 return false
140 }
141 // The SPA serves /assets and /api from the root handler; using one of them
142 // as the entry would shadow the frontend and lock the operator out.
143 switch entry {
144 case "assets", "api", "static", "favicon":
145 return false
146 }
147 return true
148}
149
150type sessionReq struct {
151 Minutes int `json:"minutes"`
152}
153
154func (s *Server) handleSettingsSession(w http.ResponseWriter, r *http.Request) {
155 var req sessionReq
156 if err := decodeJSON(w, r, &req, 4<<10); err != nil {
157 writeErr(w, err)
158 return
159 }
160 if req.Minutes < 1 || req.Minutes > 10080 {
161 writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: "登录有效期需在 1 到 10080 分钟之间"})
162 return
163 }
164 started := time.Now()
165 old := s.cfg.SessionTTLMinutes
166 s.cfg.SessionTTLMinutes = req.Minutes
167 if err := s.cfg.Save(); err != nil {
168 s.cfg.SessionTTLMinutes = old
169 writeErr(w, err)
170 return
171 }
172 s.audit(r, "settings", "session_ttl", strconv.Itoa(req.Minutes), "ok", started)
173 writeOK(w, s.settingsSnapshot())
174}
175
176type appAccessReq struct {
177 Domain string `json:"domain"`
178 Staging bool `json:"staging"`
179}
180
181// handleAppAccessEnable issues a publicly trusted certificate for the domain
182// the operator pointed at this server, so the mobile app can use real HTTPS
183// instead of a self signed certificate the system will not trust.
184func (s *Server) handleAppAccessEnable(w http.ResponseWriter, r *http.Request) {
185 if s.sslSvc == nil {
186 writeJSON(w, http.StatusServiceUnavailable, Envelope{Code: 503, Msg: "证书服务不可用"})
187 return
188 }
189 if s.tls == nil {
190 writeJSON(w, http.StatusServiceUnavailable, Envelope{Code: 503, Msg: "面板未启用 HTTPS,请先在配置中开启 https"})
191 return
192 }
193 var req appAccessReq
194 if err := decodeJSON(w, r, &req, 4<<10); err != nil {
195 writeErr(w, err)
196 return
197 }
198 domain := strings.ToLower(strings.TrimSpace(req.Domain))
199 domain = strings.TrimPrefix(strings.TrimPrefix(domain, "https://"), "http://")
200 domain = strings.TrimSuffix(domain, "/")
201 if !validDomainName(domain) {
202 writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: "请填写一个已解析到本机的域名,例如 panel.example.com"})
203 return
204 }
205
206 started := time.Now()
207 // Keep the challenge files outside DataDir: that directory is 0700 so the
208 // nginx worker cannot traverse into it, and the ACME probe would 403.
209 webRoot := filepath.Join(s.cfg.PanelDir, "acme-web")
210 outDir := filepath.Join(s.cfg.SelfSignedDir(), "domain")
211
212 // Detach from the request context: clicking refresh must not abort an
213 // issuance that Let's Encrypt has already started, otherwise the account
214 // burns rate limit for nothing. The ACME call keeps its own timeout.
215 issueCtx := context.WithoutCancel(r.Context())
216
217 // The HTTP-01 challenge must be reachable on port 80. Prefer a temporary
218 // listener; fall back to a throwaway nginx server block when nginx owns 80.
219 stop, err := s.startChallengeServer(issueCtx, domain, webRoot)
220 if err != nil {
221 writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: err.Error()})
222 return
223 }
224 defer stop()
225
226 result, err := s.sslSvc.IssuePanelCert(issueCtx, domain, webRoot, outDir, req.Staging)
227 if err != nil {
228 s.audit(r, "settings", "app_access", domain, "failed", started)
229 writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: friendlyACMEError(err)})
230 return
231 }
232
233 // A staging certificate is untrusted by design; use it only to prove the
234 // challenge path works, never to serve the panel.
235 if req.Staging {
236 s.audit(r, "settings", "app_access_staging", domain, "ok", started)
237 writeOK(w, map[string]any{
238 "domain": domain, "issuer": result.Issuer, "notAfter": result.NotAfter,
239 "daysLeft": result.DaysLeft, "url": "", "staging": true,
240 "message": "测试证书已签发,说明 80 端口通道正常。请取消「测试模式」再申请一次正式证书。",
241 })
242 return
243 }
244
245 certPath := filepath.Join(outDir, "fullchain.pem")
246 keyPath := filepath.Join(outDir, "privkey.pem")
247 oldCert, oldKey, oldDomain := s.cfg.HTTPSCert, s.cfg.HTTPSKey, s.cfg.AppDomain
248 s.cfg.HTTPSCert = certPath
249 s.cfg.HTTPSKey = keyPath
250 s.cfg.AppDomain = domain
251 if !containsFold(s.cfg.HTTPSHosts, domain) {
252 s.cfg.HTTPSHosts = append(s.cfg.HTTPSHosts, domain)
253 }
254 if err := s.cfg.Save(); err != nil {
255 s.cfg.HTTPSCert, s.cfg.HTTPSKey, s.cfg.AppDomain = oldCert, oldKey, oldDomain
256 writeErr(w, err)
257 return
258 }
259 if err := s.tls.Reload(certPath, keyPath); err != nil {
260 writeJSON(w, http.StatusInternalServerError, Envelope{
261 Code: 500, Msg: "证书已签发但加载失败:" + err.Error(),
262 })
263 return
264 }
265 s.audit(r, "settings", "app_access", domain, "ok", started)
266 writeOK(w, map[string]any{
267 "domain": domain,
268 "issuer": result.Issuer,
269 "notAfter": result.NotAfter,
270 "daysLeft": result.DaysLeft,
271 "url": "https://" + domain + portSuffix(s.cfg.Addr) + "/" + s.cfg.Entry + "/",
272 })
273}
274
275func (s *Server) handleAppAccessDisable(w http.ResponseWriter, r *http.Request) {
276 if s.tls == nil {
277 writeJSON(w, http.StatusServiceUnavailable, Envelope{Code: 503, Msg: "面板未启用 HTTPS"})
278 return
279 }
280 started := time.Now()
281 oldCert, oldKey, oldDomain := s.cfg.HTTPSCert, s.cfg.HTTPSKey, s.cfg.AppDomain
282 s.cfg.HTTPSCert = ""
283 s.cfg.HTTPSKey = ""
284 s.cfg.AppDomain = ""
285 if err := s.cfg.Save(); err != nil {
286 s.cfg.HTTPSCert, s.cfg.HTTPSKey, s.cfg.AppDomain = oldCert, oldKey, oldDomain
287 writeErr(w, err)
288 return
289 }
290 // Fall back to the self signed certificate so HTTPS keeps working.
291 hosts := paneltls.LocalHosts()
292 hosts = append(hosts, s.cfg.HTTPSHosts...)
293 if material, err := paneltls.Ensure(s.cfg.SelfSignedDir(), hosts); err == nil {
294 _ = s.tls.Reload(material.CertPath, material.KeyPath)
295 }
296 s.audit(r, "settings", "app_access_off", oldDomain, "ok", started)
297 writeOK(w, s.settingsSnapshot())
298}
299
300// friendlyACMEError turns the terse RFC 8555 payload into something an
301// operator can act on.
302func friendlyACMEError(err error) string {
303 msg := err.Error()
304 low := strings.ToLower(msg)
305 if strings.Contains(low, "ratelimited") || strings.Contains(low, "too many failed authorizations") {
306 return "该域名近期验证失败次数过多,Let's Encrypt 已临时拒绝签发(通常需等待 1 小时)。" +
307 "请先确认 80 端口能从公网访问,再用「测试模式」重试,避免继续消耗正式额度。原始信息:" + msg
308 }
309 return msg
310}
311
312func containsFold(list []string, want string) bool {
313 for _, v := range list {
314 if strings.EqualFold(strings.TrimSpace(v), want) {
315 return true
316 }
317 }
318 return false
319}
320
321func validDomainName(domain string) bool {
322 if len(domain) < 4 || len(domain) > 253 || !strings.Contains(domain, ".") {
323 return false
324 }
325 if strings.HasPrefix(domain, ".") || strings.HasSuffix(domain, ".") || strings.Contains(domain, "..") {
326 return false
327 }
328 for _, c := range domain {
329 if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '.' || c == '-' {
330 continue
331 }
332 return false
333 }
334 return true
335}
336
337// startChallengeServer makes http://<domain>/.well-known/acme-challenge/ work
338// for the duration of the issuance. Returns a stop function.
339func (s *Server) startChallengeServer(ctx context.Context, domain, webRoot string) (func(), error) {
340 challengeDir := filepath.Join(webRoot, ".well-known", "acme-challenge")
341 if err := os.MkdirAll(challengeDir, 0o755); err != nil {
342 return nil, fmt.Errorf("创建验证目录失败: %w", err)
343 }
344 // nginx runs as an unprivileged user; make sure it can actually walk down
345 // to the token file even if a previous umask created the dirs tighter.
346 for _, dir := range []string{webRoot, filepath.Join(webRoot, ".well-known"), challengeDir} {
347 _ = os.Chmod(dir, 0o755)
348 }
349 // A fixed probe file lets the operator verify the public path themselves
350 // while an issuance is running: http://<domain>/.well-known/acme-challenge/test.txt
351 _ = os.WriteFile(filepath.Join(challengeDir, "test.txt"), []byte("miaopanel-acme-ok"), 0o644)
352 s.logInfo("面板证书:验证目录 " + challengeDir)
353 if ln, err := net.Listen("tcp", ":80"); err == nil {
354 s.logInfo("面板证书:临时监听 80 端口处理 ACME 验证")
355 srv := &http.Server{
356 Handler: http.FileServer(http.Dir(webRoot)),
357 ReadHeaderTimeout: 10 * time.Second,
358 }
359 go func() { _ = srv.Serve(ln) }()
360 return func() {
361 shutdownCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
362 defer cancel()
363 _ = srv.Shutdown(shutdownCtx)
364 }, nil
365 } else {
366 s.logInfo("面板证书:80 端口被占用,改用 nginx 临时 vhost(" + err.Error() + ")")
367 }
368 // Port 80 is taken: borrow nginx until Let's Encrypt is done verifying.
369 if s.nginx == nil || !s.nginx.Available() {
370 return nil, errors.New("80 端口被占用且 nginx 不可用,无法完成域名验证")
371 }
372 confPath := filepath.Join(s.cfg.Nginx.VhostDir, "panel-acme.conf")
373 conf := fmt.Sprintf(`# MiaoPanel 临时 ACME 验证配置,申请结束后自动删除
374server {
375 listen 80;
376 server_name %s;
377 location ^~ /.well-known/acme-challenge/ {
378 root %s;
379 default_type text/plain;
380 }
381 location / {
382 return 404;
383 }
384}
385`, domain, webRoot)
386 // Never block the request forever on a stuck nginx -t or reload.
387 applyCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
388 defer cancel()
389 if err := s.nginx.Apply(applyCtx, &webserver.Render{
390 Files: map[string][]byte{confPath: []byte(conf)},
391 }); err != nil {
392 s.logInfo("面板证书:写入临时 nginx 配置失败:" + err.Error())
393 return nil, fmt.Errorf("写入临时 nginx 配置失败: %w", err)
394 }
395 s.logInfo("面板证书:已写入临时 nginx 配置 " + confPath)
396 return func() {
397 cleanupCtx, done := context.WithTimeout(context.Background(), 30*time.Second)
398 defer done()
399 _ = s.nginx.Apply(cleanupCtx, &webserver.Render{
400 Remove: []string{confPath},
401 })
402 }, nil
403}
404
405func (s *Server) logInfo(msg string) {
406 if s.log != nil {
407 s.log.Info(msg)
408 }
409}