fix: harden login session lifetime

This commit is contained in:
OpenClaw Agent
2026-09-22 04:39:10 +08:00
parent 2c8531d9b9
commit c37161db31
6 changed files with 73 additions and 28 deletions
+13 -17
View File
@@ -42,6 +42,7 @@ type Server struct {
SessionExpiry map[string]time.Time
SessionMu sync.RWMutex
SessionTimeout int
JWTSecret string
WebDAVRoot string
WebDAVFS webdav.FileSystem
Allow string
@@ -113,7 +114,7 @@ func account(r *http.Request, s *Server) *auth.Account {
if err != nil {
return s.Auth.Guest
}
username, err := auth.GetAccFromToken(c.Value)
username, err := auth.GetAccFromToken(c.Value, s.JWTSecret)
if err != nil {
return s.Auth.Guest
}
@@ -511,18 +512,8 @@ func (s *Server) exist(w http.ResponseWriter, r *http.Request) {
func (s *Server) session(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodDelete {
jwtValue, _ := r.Cookie("JWT")
userValue, _ := r.Cookie("user")
jwt := ""
user := ""
if jwtValue != nil {
jwt = jwtValue.Value
}
if userValue != nil {
user = userValue.Value
}
http.SetCookie(w, &http.Cookie{Name: "JWT", Value: jwt, Path: "/", MaxAge: -1})
http.SetCookie(w, &http.Cookie{Name: "user", Value: user, Path: "/", MaxAge: -1})
http.SetCookie(w, &http.Cookie{Name: "JWT", Value: "", Path: "/", MaxAge: -1, Expires: time.Unix(1, 0), HttpOnly: true, SameSite: http.SameSiteLaxMode})
http.SetCookie(w, &http.Cookie{Name: "user", Value: "", Path: "/", MaxAge: -1, Expires: time.Unix(1, 0), SameSite: http.SameSiteLaxMode})
w.WriteHeader(http.StatusNoContent)
return
}
@@ -540,14 +531,19 @@ func (s *Server) session(w http.ResponseWriter, r *http.Request) {
writeJSONError(w, http.StatusNotFound, "user or password is wrong")
return
}
token, err := auth.NewToken(a.Username, s.SessionTimeout)
timeout := s.SessionTimeout
if timeout <= 0 {
timeout = 30
}
token, err := auth.NewToken(a.Username, timeout, s.JWTSecret)
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "failed to create token")
return
}
expires := time.Now().Add(365 * 24 * time.Hour)
http.SetCookie(w, &http.Cookie{Name: "JWT", Value: token, Path: "/", Expires: expires, HttpOnly: true})
http.SetCookie(w, &http.Cookie{Name: "user", Value: a.Username, Path: "/", Expires: expires})
expires := time.Now().Add(time.Duration(timeout) * time.Minute)
secure := r.TLS != nil
http.SetCookie(w, &http.Cookie{Name: "JWT", Value: token, Path: "/", MaxAge: timeout * 60, Expires: expires, HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode})
http.SetCookie(w, &http.Cookie{Name: "user", Value: a.Username, Path: "/", MaxAge: timeout * 60, Expires: expires, Secure: secure, SameSite: http.SameSiteLaxMode})
w.WriteHeader(http.StatusCreated)
}