mirror of
https://github.com/Ed1s0nZ/CyberStrikeAI.git
synced 2026-11-23 04:41:41 +01:00
fix(update): switch versions without interrupting sign-in
This commit is contained in:
1 parent
f3997c48eb
commit
5d98f5d805
23 files changed
+463
-241
No files matched your search
@@ -1,9 +1,9 @@
|
||||
name: Self-update
|
||||
on:
|
||||
push:
|
||||
paths: ['internal/update/**', 'internal/workflow/**', 'internal/config/**', 'internal/handler/**', 'internal/mcp/**', 'cmd/server/**', 'web/static/js/**', 'web/static/css/style.css', 'web/templates/index.html', 'upgrade.sh', 'run.sh', 'go.mod', 'go.sum', '.gitignore', '.github/workflows/self-update.yml']
|
||||
paths: ['internal/update/**', 'internal/app/update_restart*', 'internal/security/auth*', 'internal/workflow/**', 'internal/config/**', 'internal/handler/**', 'internal/mcp/**', 'cmd/server/**', 'web/static/js/**', 'web/static/i18n/**', 'web/static/css/style.css', 'web/templates/index.html', 'upgrade.sh', 'run.sh', 'go.mod', 'go.sum', '.gitignore', '.github/workflows/self-update.yml']
|
||||
pull_request:
|
||||
paths: ['internal/update/**', 'internal/workflow/**', 'internal/config/**', 'internal/handler/**', 'internal/mcp/**', 'cmd/server/**', 'web/static/js/**', 'web/static/css/style.css', 'web/templates/index.html', 'upgrade.sh', 'run.sh', 'go.mod', 'go.sum', '.gitignore', '.github/workflows/self-update.yml']
|
||||
paths: ['internal/update/**', 'internal/app/update_restart*', 'internal/security/auth*', 'internal/workflow/**', 'internal/config/**', 'internal/handler/**', 'internal/mcp/**', 'cmd/server/**', 'web/static/js/**', 'web/static/i18n/**', 'web/static/css/style.css', 'web/templates/index.html', 'upgrade.sh', 'run.sh', 'go.mod', 'go.sum', '.gitignore', '.github/workflows/self-update.yml']
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
@@ -23,7 +23,7 @@ jobs:
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
- run: go test -race ./internal/update ./internal/config ./internal/handler ./cmd/server ./internal/workflow
|
||||
- run: go test -race ./internal/update ./internal/app ./internal/security ./internal/config ./internal/handler ./cmd/server ./internal/workflow
|
||||
- run: go build ./...
|
||||
- name: Frontend regression tests
|
||||
shell: bash
|
||||
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
)
|
||||
|
||||
func main() {
|
||||
updateSessions := app.TakeUpdateSessionHandoff()
|
||||
var configPath = flag.String("config", "config.yaml", "Path to the configuration file")
|
||||
var httpsBootstrap = flag.Bool("https", false, "Enable HTTPS for the main site; uses an in-memory self-signed certificate when no cert/key is configured")
|
||||
var httpBootstrap = flag.Bool("http", false, "Force plain HTTP for the main site, overriding TLS settings in the configuration file")
|
||||
@@ -160,6 +161,7 @@ func main() {
|
||||
if err != nil {
|
||||
log.Fatal("应用初始化失败", "error", err)
|
||||
}
|
||||
application.RestoreUpdateSessions(updateSessions)
|
||||
|
||||
// 在后台监听信号
|
||||
go func() {
|
||||
|
||||
@@ -153,7 +153,7 @@ match the files on disk, recovery refuses to overwrite them.
|
||||
### Switching to the new binary
|
||||
|
||||
On macOS and Linux, when started from the `cyberstrike-ai` binary alongside its config, the console
|
||||
sends `restart: true` by default. After a successful build and binary swap, the service closes its
|
||||
sends `restart: true` as soon as you click **One-Click Update**. After a successful build and binary swap, the service closes its
|
||||
application resources and executes the new binary with the same PID, arguments, environment and
|
||||
working directory. Installations that cannot switch in place return `400` on an explicit restart
|
||||
request. CLI updates and REST updates without `restart: true` only replace files on disk.
|
||||
@@ -163,11 +163,12 @@ the binary identity captured at startup (size + nanosecond mtime) with what is o
|
||||
update, a rollback or a CLI run swapped the file without a restart, `needsRestart` is true,
|
||||
`binaryBuiltAt` says when it was built, and the console grows a persistent banner with **Restart now**
|
||||
(`POST /api/system/update/restart`; `409 nothing_pending` when there is nothing to activate, `409`
|
||||
while a job runs, `400` when unavailable). The console uses the `autoRestart` field as its default.
|
||||
while a job runs, `400` when unavailable). The console checks `canRestart` before requesting automatic activation.
|
||||
|
||||
**The page reloads automatically.** The console polls the session validation endpoint every two
|
||||
seconds for the new boot marker. Sessions live in memory, so users sign in again after the switch.
|
||||
Leaving the console stops the polling.
|
||||
seconds for the new boot marker. When both versions support session handoff, existing sessions keep
|
||||
their original expiration and permissions are loaded from the current RBAC store. The first upgrade
|
||||
from an older version may still require sign-in. Leaving the console stops the polling.
|
||||
|
||||
## Adding a Business Module
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ Server `POST /api/auth/login` returns `{ token, expires_at }`. There is **no ref
|
||||
| Local check | Re-check `expires_at` + `GET /api/auth/validate` every 30s |
|
||||
| Server probe | Immediate probe when DevTools panel becomes visible |
|
||||
| Unreachable | Show warning; keep token during transient outage |
|
||||
| 401/403 | Clear token (server restart clears in-memory sessions) |
|
||||
| 401/403 | Clear token and require re-authentication |
|
||||
| Before Send | `ensureAuthReady()` before SSE |
|
||||
| Permissions | `optional_host_permissions` — request origin on Validate |
|
||||
|
||||
|
||||
@@ -189,9 +189,9 @@ SQLite 热备份时最好先停止服务,或至少复制 `*.db`、`*.db-wal`
|
||||
并被页面标出,装好 go 后再点一次「一键更新」即补编译。
|
||||
细节见 [开发者指南](developer-guide.md) 的「一键更新」一节。
|
||||
|
||||
在 macOS/Linux 上,从配置文件同目录的 `cyberstrike-ai` 启动时,控制台默认在构建成功后自动切换到新二进制。
|
||||
构建期间旧服务继续提供服务;切换时连接会短暂中断,页面在新服务应答后自动刷新(内存中的登录会话需重新登录)。
|
||||
这一步不依赖 systemd 或 launchd;长期部署仍建议用守护进程做开机自启和异常恢复。取消自动切换、或在命令行换过
|
||||
在 macOS/Linux 上,从配置文件同目录的 `cyberstrike-ai` 启动时,点击「一键更新」后,控制台在构建成功时自动切换到新二进制。
|
||||
构建期间旧服务继续提供服务;切换时连接会短暂中断,页面在新服务应答后自动刷新并沿用仍然有效的登录会话。
|
||||
这一步不依赖 systemd 或 launchd;长期部署仍建议用守护进程做开机自启和异常恢复。通过 API 或命令行换过
|
||||
二进制后,可以在支持自动切换的安装上用控制台的「立即重启服务」启用磁盘上的版本。
|
||||
|
||||
更新源是 `config.yaml` `update` 段里的**一个仓库地址**(`repo`),也可以直接在控制台「一键更新」页填写保存:
|
||||
|
||||
@@ -143,17 +143,17 @@ update:
|
||||
|
||||
### 切换到新二进制
|
||||
|
||||
macOS/Linux 上,从配置文件同目录的 `cyberstrike-ai` 启动时,控制台默认发送 `restart: true`。
|
||||
macOS/Linux 上,从配置文件同目录的 `cyberstrike-ai` 启动时,点击「一键更新」直接发送 `restart: true`,无需二次确认。
|
||||
只有成功构建并换入二进制才会切换:服务先关闭应用资源,再用相同 PID、启动参数、环境和工作目录执行新二进制。
|
||||
不支持的启动方式不提供自动切换;REST 显式请求重启时返回 `400`。REST 不传该字段和 CLI 更新都只换磁盘文件。
|
||||
|
||||
**待生效状态是持久的、可补重启。** 状态接口对比"启动时记下的二进制身份(大小 + 纳秒 mtime)"与磁盘
|
||||
现值:更新、回滚或 CLI 换过二进制而没重启时,`needsRestart` 为真、`binaryBuiltAt` 给出构建时间,
|
||||
控制台顶部出现常驻横幅与「立即重启服务」(`POST /api/system/update/restart`;没有待生效版本时
|
||||
`409 nothing_pending`、有任务在跑 `409`、不支持时 `400`)。控制台根据 `autoRestart` 决定默认值。
|
||||
`409 nothing_pending`、有任务在跑 `409`、不支持时 `400`)。控制台根据 `canRestart` 决定能否自动切换。
|
||||
|
||||
**重启后页面自动刷新。** 控制台每 2 秒通过会话验证接口探测服务启动标记,收到新标记才刷新。
|
||||
现有登录会话保存在内存中,切换后需要重新登录。离开控制台则停止探测。
|
||||
支持会话交接的两个版本之间切换时,有效登录保持原来的到期时间,权限从新进程的 RBAC 存储重新加载。首次从旧版升级时可能需要重新登录。离开控制台则停止探测。
|
||||
|
||||
## 数据库
|
||||
|
||||
|
||||
@@ -705,6 +705,17 @@ func (a *App) Run() error {
|
||||
return a.RunWithContext(context.Background())
|
||||
}
|
||||
|
||||
// RestoreUpdateSessions consumes the handoff before the new HTTP listener starts.
|
||||
func (a *App) RestoreUpdateSessions(handoff *os.File) {
|
||||
if handoff == nil {
|
||||
return
|
||||
}
|
||||
defer handoff.Close()
|
||||
if err := a.auth.RestoreRestartSessions(handoff); err != nil {
|
||||
a.logger.Warn("无法恢复更新前的登录会话", zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
// RunWithContext 启动应用,支持通过 context 取消来优雅关闭
|
||||
func (a *App) RunWithContext(ctx context.Context) error {
|
||||
// 启动MCP服务器(如果启用)
|
||||
|
||||
@@ -2,4 +2,8 @@
|
||||
|
||||
package app
|
||||
|
||||
import "os"
|
||||
|
||||
func TakeUpdateSessionHandoff() *os.File { return nil }
|
||||
|
||||
func (a *App) updateRestart(string) func() (func(), error) { return nil }
|
||||
@@ -4,8 +4,12 @@ package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"cyberstrike-ai/internal/update"
|
||||
|
||||
@@ -13,6 +17,47 @@ import (
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
const updateSessionsEnv = "CYBERSTRIKE_UPDATE_SESSIONS_FD"
|
||||
|
||||
// TakeUpdateSessionHandoff claims the descriptor left by an in-place exec.
|
||||
// Do this before startup runs any subprocesses.
|
||||
func TakeUpdateSessionHandoff() *os.File {
|
||||
value := os.Getenv(updateSessionsEnv)
|
||||
if value == "" {
|
||||
return nil
|
||||
}
|
||||
_ = os.Unsetenv(updateSessionsEnv)
|
||||
pid, rawFD, ok := strings.Cut(value, ":")
|
||||
fd, err := strconv.Atoi(rawFD)
|
||||
if !ok || pid != strconv.Itoa(os.Getpid()) || err != nil || fd < 3 {
|
||||
return nil
|
||||
}
|
||||
var stat unix.Stat_t
|
||||
if err := unix.Fstat(fd, &stat); err != nil || stat.Mode&unix.S_IFMT != unix.S_IFREG || stat.Nlink != 0 {
|
||||
return nil
|
||||
}
|
||||
unix.CloseOnExec(fd)
|
||||
return os.NewFile(uintptr(fd), "update-sessions")
|
||||
}
|
||||
|
||||
func writeUpdateSessionHandoff(payload []byte) (*os.File, error) {
|
||||
f, err := os.CreateTemp("", "cyberstrike-update-sessions-*")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// The private file has no path by the time it contains session data.
|
||||
if err = os.Remove(f.Name()); err == nil {
|
||||
if _, err = f.Write(payload); err == nil {
|
||||
_, err = f.Seek(0, io.SeekStart)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
_ = f.Close()
|
||||
return nil, err
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// updateRestart only replaces the executable this instance was started from.
|
||||
// For example, go run and installs with a separate config directory must not
|
||||
// start a different executable just because the updater wrote one there.
|
||||
@@ -49,7 +94,33 @@ func (a *App) updateRestart(root string) func() (func(), error) {
|
||||
a.Shutdown()
|
||||
// Keep the same PID, arguments, environment and working directory.
|
||||
// This works both in a terminal and under an existing supervisor.
|
||||
if err := unix.Exec(path, os.Args, os.Environ()); err != nil {
|
||||
exec := func(payload []byte) error {
|
||||
env := os.Environ()
|
||||
if len(payload) != 0 {
|
||||
f, err := writeUpdateSessionHandoff(payload)
|
||||
if err == nil {
|
||||
fd := f.Fd()
|
||||
// Prevent a concurrent subprocess from inheriting the descriptor.
|
||||
syscall.ForkLock.Lock()
|
||||
defer syscall.ForkLock.Unlock()
|
||||
defer f.Close()
|
||||
_, err = unix.FcntlInt(fd, unix.F_SETFD, 0)
|
||||
if err == nil {
|
||||
env = append(env, fmt.Sprintf("%s=%d:%d", updateSessionsEnv, os.Getpid(), fd))
|
||||
return unix.Exec(path, os.Args, env)
|
||||
}
|
||||
}
|
||||
a.logger.Warn("无法交接登录会话,继续切换版本", zap.Error(err))
|
||||
}
|
||||
return unix.Exec(path, os.Args, env)
|
||||
}
|
||||
var err error
|
||||
if a.auth != nil {
|
||||
err = a.auth.HandoffSessions(exec)
|
||||
} else {
|
||||
err = exec(nil)
|
||||
}
|
||||
if err != nil {
|
||||
a.logger.Error("无法启动更新后的二进制", zap.Error(err))
|
||||
_ = a.logger.Sync()
|
||||
os.Exit(1)
|
||||
|
||||
@@ -13,16 +13,19 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"cyberstrike-ai/internal/database"
|
||||
"cyberstrike-ai/internal/security"
|
||||
"cyberstrike-ai/internal/update"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func TestStandaloneUpdateRestartExecsReplacement(t *testing.T) {
|
||||
func copyRestartTestBinary(t *testing.T, binary string) {
|
||||
t.Helper()
|
||||
self, err := os.Executable()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
root := t.TempDir()
|
||||
binary := filepath.Join(root, update.Binary)
|
||||
src, err := os.Open(self)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -39,6 +42,12 @@ func TestStandaloneUpdateRestartExecsReplacement(t *testing.T) {
|
||||
if copyErr != nil {
|
||||
t.Fatal(copyErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStandaloneUpdateRestartExecsReplacement(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
binary := filepath.Join(root, update.Binary)
|
||||
copyRestartTestBinary(t, binary)
|
||||
replacement := filepath.Join(root, "next")
|
||||
if err := os.WriteFile(replacement, []byte("#!/bin/sh\nprintf 'replacement:%s:%s:%s:%s\\n' \"$$\" \"$PWD\" \"$CSAI_RESTART_TEST\" \"$1\"\n"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -64,6 +73,83 @@ func TestStandaloneUpdateRestartExecsReplacement(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateRestartExecsWithLiveSessions(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
binary := filepath.Join(root, update.Binary)
|
||||
copyRestartTestBinary(t, binary)
|
||||
copyRestartTestBinary(t, filepath.Join(root, "next"))
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, binary, "-test.run=^TestUpdateSessionHandoffChild$")
|
||||
cmd.Dir = root
|
||||
cmd.Env = []string{"CSAI_RESTART_TEST=handoff"}
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil || !strings.Contains(string(out), "session handoff verified") {
|
||||
t.Fatalf("session handoff helper: %v\n%s", err, out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateSessionHandoffChild(t *testing.T) {
|
||||
if os.Getenv("CSAI_RESTART_TEST") != "handoff" {
|
||||
return
|
||||
}
|
||||
handoff := TakeUpdateSessionHandoff()
|
||||
db, err := database.NewDB("test.db", zap.NewNop())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a := App{auth: security.NewAuthManager(12), db: db}
|
||||
defer a.Shutdown()
|
||||
password, err := a.auth.AttachRBACStore(db)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if token := os.Getenv("CSAI_RESTART_TEST_TOKEN"); token != "" {
|
||||
if handoff == nil || os.Getenv(updateSessionsEnv) != "" {
|
||||
t.Fatal("replacement did not claim the private handoff")
|
||||
}
|
||||
a.RestoreUpdateSessions(handoff)
|
||||
session, ok := a.auth.ValidateToken(token)
|
||||
if !ok || session.Token != token || session.UserID != "admin" || !session.Permissions["update:apply"] ||
|
||||
session.ExpiresAt.Format(time.RFC3339Nano) != os.Getenv("CSAI_RESTART_TEST_EXPIRY") {
|
||||
t.Fatal("replacement lost login, permissions or original expiration")
|
||||
}
|
||||
if _, ok := a.auth.ValidateToken(os.Getenv("CSAI_RESTART_TEST_REVOKED")); ok {
|
||||
t.Fatal("replacement accepted a logged-out session")
|
||||
}
|
||||
fmt.Println("session handoff verified")
|
||||
return
|
||||
}
|
||||
|
||||
token, expires, err := a.auth.Authenticate("admin", password)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
revoked, _, err := a.auth.Authenticate("admin", password)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a.auth.RevokeToken(revoked)
|
||||
// The test replacement needs the original client credentials to exercise validation.
|
||||
t.Setenv("CSAI_RESTART_TEST_TOKEN", token)
|
||||
t.Setenv("CSAI_RESTART_TEST_EXPIRY", expires.Format(time.RFC3339Nano))
|
||||
t.Setenv("CSAI_RESTART_TEST_REVOKED", revoked)
|
||||
|
||||
prepare := a.updateRestart(".")
|
||||
if prepare == nil {
|
||||
t.Fatal("standalone install did not offer restart")
|
||||
}
|
||||
if err := os.Rename("next", update.Binary); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
restart, err := prepare()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
restart()
|
||||
t.Fatal("exec returned instead of switching executables")
|
||||
}
|
||||
|
||||
func TestUpdateRestartChild(t *testing.T) {
|
||||
if os.Getenv("CSAI_RESTART_TEST") != "standalone" {
|
||||
return
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"strings"
|
||||
@@ -28,15 +29,20 @@ type Session struct {
|
||||
Permissions map[string]bool
|
||||
PermissionScopes map[string]string
|
||||
Scope string
|
||||
userUpdatedAt time.Time
|
||||
}
|
||||
|
||||
type sessionDigest = [sha256.Size]byte
|
||||
|
||||
func tokenDigest(token string) sessionDigest { return sha256.Sum256([]byte(token)) }
|
||||
|
||||
// AuthManager manages password-based authentication and session lifecycle.
|
||||
type AuthManager struct {
|
||||
sessionDuration time.Duration
|
||||
db *database.DB
|
||||
|
||||
mu sync.RWMutex
|
||||
sessions map[string]Session
|
||||
sessions map[sessionDigest]Session
|
||||
// Changes when cached authorization is revoked, including while a login
|
||||
// is resolving access outside mu.
|
||||
accessVersion uint64
|
||||
@@ -50,7 +56,7 @@ func NewAuthManager(sessionDurationHours int) *AuthManager {
|
||||
|
||||
return &AuthManager{
|
||||
sessionDuration: time.Duration(sessionDurationHours) * time.Hour,
|
||||
sessions: make(map[string]Session),
|
||||
sessions: make(map[sessionDigest]Session),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,7 +117,9 @@ func (a *AuthManager) publishSession(session Session, version uint64) bool {
|
||||
if a.accessVersion != version {
|
||||
return false
|
||||
}
|
||||
a.sessions[session.Token] = session
|
||||
digest := tokenDigest(session.Token)
|
||||
session.Token = ""
|
||||
a.sessions[digest] = session
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -144,21 +152,30 @@ func (a *AuthManager) authenticateSession(username, password string) (Session, e
|
||||
if err != nil {
|
||||
return Session{}, err
|
||||
}
|
||||
if !access.User.Enabled || access.User.PasswordHash != user.PasswordHash {
|
||||
return Session{}, ErrInvalidPassword
|
||||
}
|
||||
session := sessionForAccess(access, expiresAt)
|
||||
session.Token = token
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func sessionForAccess(access *database.RBACAccess, expiresAt time.Time) Session {
|
||||
roleIDs := make([]string, 0, len(access.Roles))
|
||||
for _, role := range access.Roles {
|
||||
roleIDs = append(roleIDs, role.ID)
|
||||
}
|
||||
return Session{
|
||||
Token: token,
|
||||
ExpiresAt: expiresAt,
|
||||
UserID: user.ID,
|
||||
Username: user.Username,
|
||||
DisplayName: user.DisplayName,
|
||||
UserID: access.User.ID,
|
||||
Username: access.User.Username,
|
||||
DisplayName: access.User.DisplayName,
|
||||
Roles: roleIDs,
|
||||
Permissions: access.Permissions,
|
||||
PermissionScopes: access.PermissionScopes,
|
||||
Scope: access.Scope,
|
||||
}, nil
|
||||
userUpdatedAt: access.User.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func (s Session) ScopeFor(permission string) string {
|
||||
@@ -174,8 +191,9 @@ func (a *AuthManager) ValidateToken(token string) (Session, bool) {
|
||||
return Session{}, false
|
||||
}
|
||||
|
||||
digest := tokenDigest(token)
|
||||
a.mu.RLock()
|
||||
session, ok := a.sessions[token]
|
||||
session, ok := a.sessions[digest]
|
||||
a.mu.RUnlock()
|
||||
if !ok {
|
||||
return Session{}, false
|
||||
@@ -183,11 +201,12 @@ func (a *AuthManager) ValidateToken(token string) (Session, bool) {
|
||||
|
||||
if time.Now().After(session.ExpiresAt) {
|
||||
a.mu.Lock()
|
||||
delete(a.sessions, token)
|
||||
delete(a.sessions, digest)
|
||||
a.mu.Unlock()
|
||||
return Session{}, false
|
||||
}
|
||||
|
||||
session.Token = token
|
||||
return session, true
|
||||
}
|
||||
|
||||
@@ -247,7 +266,7 @@ func (a *AuthManager) RevokeToken(token string) {
|
||||
}
|
||||
|
||||
a.mu.Lock()
|
||||
delete(a.sessions, token)
|
||||
delete(a.sessions, tokenDigest(token))
|
||||
a.mu.Unlock()
|
||||
}
|
||||
|
||||
@@ -289,7 +308,7 @@ func (a *AuthManager) RevokeRoleSessions(roleID string) {
|
||||
func (a *AuthManager) RevokeAllSessions() {
|
||||
a.mu.Lock()
|
||||
a.accessVersion++
|
||||
a.sessions = make(map[string]Session)
|
||||
a.sessions = make(map[sessionDigest]Session)
|
||||
a.mu.Unlock()
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"cyberstrike-ai/internal/database"
|
||||
)
|
||||
|
||||
type restartSession struct {
|
||||
Digest sessionDigest
|
||||
UserID string
|
||||
ExpiresAt time.Time
|
||||
UserUpdatedAt time.Time
|
||||
}
|
||||
|
||||
// HandoffSessions runs the update exec with the session map locked. A logout or
|
||||
// revocation cannot complete in the old process after its token is handed off.
|
||||
// The payload contains token digests only, and is passed through a private descriptor.
|
||||
func (a *AuthManager) HandoffSessions(exec func([]byte) error) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
now := time.Now()
|
||||
var active []restartSession
|
||||
for digest, s := range a.sessions {
|
||||
if s.ExpiresAt.After(now) {
|
||||
active = append(active, restartSession{digest, s.UserID, s.ExpiresAt, s.userUpdatedAt})
|
||||
}
|
||||
}
|
||||
if len(active) == 0 {
|
||||
return exec(nil)
|
||||
}
|
||||
payload, err := json.Marshal(active)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return exec(payload)
|
||||
}
|
||||
|
||||
// RestoreRestartSessions is called before the replacement starts serving.
|
||||
// Rebuild access from the current RBAC store and keep the original expiration.
|
||||
func (a *AuthManager) RestoreRestartSessions(r io.Reader) error {
|
||||
var saved []restartSession
|
||||
if err := json.NewDecoder(r).Decode(&saved); err != nil {
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if a.db == nil {
|
||||
return errors.New("authentication store is not configured")
|
||||
}
|
||||
accessByUser := make(map[string]*database.RBACAccess)
|
||||
restored := make(map[sessionDigest]Session, len(saved))
|
||||
now := time.Now()
|
||||
for _, entry := range saved {
|
||||
if !entry.ExpiresAt.After(now) {
|
||||
continue
|
||||
}
|
||||
access, loaded := accessByUser[entry.UserID]
|
||||
if !loaded {
|
||||
var err error
|
||||
access, err = a.db.ResolveRBACAccess(entry.UserID)
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
accessByUser[entry.UserID] = access
|
||||
}
|
||||
if access == nil || !access.User.Enabled || !access.User.UpdatedAt.Equal(entry.UserUpdatedAt) {
|
||||
continue
|
||||
}
|
||||
restored[entry.Digest] = sessionForAccess(access, entry.ExpiresAt)
|
||||
}
|
||||
a.sessions = restored
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"cyberstrike-ai/internal/database"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func TestRestartHandoffRejectsExpiredAndChangedAccounts(t *testing.T) {
|
||||
db, err := database.NewDB(filepath.Join(t.TempDir(), "auth.db"), zap.NewNop())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
old := NewAuthManager(12)
|
||||
password, err := old.AttachRBACStore(db)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token, _, err := old.Authenticate("admin", password)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
digest := tokenDigest("expired-token")
|
||||
expired := old.sessions[tokenDigest(token)]
|
||||
expired.ExpiresAt = time.Now().Add(-time.Second)
|
||||
old.sessions[digest] = expired
|
||||
|
||||
var handoff []byte
|
||||
if err := old.HandoffSessions(func(payload []byte) error {
|
||||
handoff = payload
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(handoff) == 0 || bytes.Contains(handoff, []byte(token)) {
|
||||
t.Fatal("handoff must contain only the digest of the active token")
|
||||
}
|
||||
next := NewAuthManager(12)
|
||||
if _, err := next.AttachRBACStore(db); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := next.RestoreRestartSessions(bytes.NewReader(handoff)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(next.sessions) != 1 {
|
||||
t.Fatalf("restored %d sessions, want exactly the unexpired session", len(next.sessions))
|
||||
}
|
||||
|
||||
// Simulate a password change committed to the store before revocation reached the old map.
|
||||
if err := old.UpdateUserPassword("admin", "changed-test-password"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := next.RestoreRestartSessions(bytes.NewReader(handoff)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := next.ValidateToken(token); ok {
|
||||
t.Fatal("restored a session issued before the account changed")
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ func TestRevokeRoleSessionsMatchesSnapshotAndPreservesOthers(t *testing.T) {
|
||||
{Token: "admin", UserID: "admin", Roles: []string{"admin"}},
|
||||
} {
|
||||
session.ExpiresAt = time.Now().Add(time.Hour)
|
||||
a.sessions[session.Token] = session
|
||||
a.sessions[tokenDigest(session.Token)] = session
|
||||
}
|
||||
a.RevokeRoleSessions(" ")
|
||||
if len(a.sessions) != 4 {
|
||||
|
||||
@@ -47221,25 +47221,6 @@ html[data-theme="dark"] { --tool-blocked-color: #f4bc62; }
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
.update-restart-choice {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
font-size: 13px;
|
||||
color: var(--text-primary);
|
||||
cursor: pointer;
|
||||
margin: 4px 0;
|
||||
}
|
||||
|
||||
.update-restart-choice input {
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.update-restart-preview {
|
||||
border-left: 3px solid var(--border-color);
|
||||
padding-left: 10px;
|
||||
}
|
||||
|
||||
.update-blocker-list {
|
||||
margin: 6px 0 0;
|
||||
padding-left: 18px;
|
||||
|
||||
@@ -147,13 +147,8 @@
|
||||
"blockedLocalEdits": "{{n}} من ملفّات مصدر المنتج معدّلة محلّيًا ولن يستبدلها التحديث: أودِعها أو تراجع عنها أوّلًا.",
|
||||
"blockedDiverged": "السجلّ المحلّي متقدّم بمقدار {{ahead}} إيداع ومتأخّر بمقدار {{behind}}: هذا دمج وليس تنزيلًا، لذا عالجه يدويًا.",
|
||||
"blockedNoUpdate": "مصدر التحديث لا يحتوي على أيّ شيء أحدث من هذا الجهاز (اضغط على التحقّق من التحديثات إن لم تكن قد راجعت بعد).",
|
||||
"restartChoiceLabel": "التبديل تلقائيًا إلى الإصدار الجديد",
|
||||
"restartNotWired": "لا تدعم طريقة التشغيل الحالية التبديل التلقائي. بعد استبدال الملف التنفيذي، أعد تشغيل الخدمة بالطريقة المعتادة في بيئتك.",
|
||||
"confirmRestartYes": "تظلّ الخدمة متاحة أثناء البناء، ثم تعيد التشغيل لفترة وجيزة للتبديل إلى الإصدار الجديد. تُعاد الصفحة تلقائيًا.",
|
||||
"confirmRestartNo": "يستمر الإصدار القديم في العمل إلى أن تعيد تشغيل الخدمة.",
|
||||
"confirmApply": "على وشك التنفيذ: التحديث من {{repo}} إلى {{target}} ({{n}} إيداع جديد، هذا الجهاز عند {{commit}}) -> إعادة بناء الملف الثنائي -> نسخ القديم احتياطيًا واستبداله.",
|
||||
"confirmBuildPending": "على وشك التنفيذ: بناء الملف الثنائي المفقود للمصدر الموجود بالفعل (هذا الجهاز عند {{commit}}) -> إعادة البناء -> نسخ القديم احتياطيًا واستبدال الملف الثنائي القديم.",
|
||||
"applyAccepted": "بدأ التحديث (المهمّة {{id}})؛ يتحدّث التقدّم كلّ 1.5 ثانية.",
|
||||
"localChangesTitle": "التغييرات المحلّية",
|
||||
"localChangesHint": "تُحفظ الملفّات المعلّمة كمحتوى محلّي كما هي تمامًا؛ أمّا الملفّات المعلّمة كمصدر منتج فتمنع التحديث التلقائي.",
|
||||
"noLocalChanges": "شجرة العمل نظيفة: لا يوجد ملفّ متتبَّع معدّل أو محذوف.",
|
||||
@@ -182,7 +177,7 @@
|
||||
"restartRequestedToast": "جارٍ تبديل الإصدار. تُعاد الصفحة عند عودة الخدمة.",
|
||||
"restartFailed": "فشل طلب إعادة التشغيل: {{reason}}",
|
||||
"restartOverlayTitle": "جارٍ إعادة تشغيل الخدمة…",
|
||||
"restartOverlayBody": "تُعاد الصفحة عند عودة الخدمة. ستحتاج إلى تسجيل الدخول مرة أخرى.",
|
||||
"restartOverlayBody": "ستُعاد الصفحة تلقائيًا عندما يصبح الإصدار الجديد جاهزًا.",
|
||||
"restartOverlaySlowRunning": "لا تزال الخدمة تستجيب بوصفها العملية القديمة - يبدو أنّ إعادة التشغيل لم تحدث. استخدم الزرّ أدناه لمعاينة الحالة الحالية.",
|
||||
"restartOverlaySlowDown": "لم تعد الخدمة بعد. ستواصل الصفحة المحاولة. راجع سجلّات الخدمة إذا استمر الانقطاع.",
|
||||
"restartOverlayRefresh": "تحديث هذه الصفحة",
|
||||
|
||||
@@ -147,13 +147,8 @@
|
||||
"blockedLocalEdits": "{{n}} product source files are edited locally and an update will not overwrite them: commit or revert them first.",
|
||||
"blockedDiverged": "Local history is {{ahead}} commits ahead and {{behind}} behind: that is a merge, not a download, so handle it by hand.",
|
||||
"blockedNoUpdate": "The update source has nothing newer than this machine (press Check for updates if you have not looked yet).",
|
||||
"restartChoiceLabel": "Switch to the new version automatically",
|
||||
"restartNotWired": "This installation cannot switch versions automatically. Restart the service through your deployment setup after the binary is replaced.",
|
||||
"confirmRestartYes": "The service stays available during the build, then briefly restarts to switch versions. This page reloads automatically.",
|
||||
"confirmRestartNo": "The old version keeps running until you restart the service.",
|
||||
"confirmApply": "About to run: update from {{repo}} to {{target}} ({{n}} new commits, this machine is at {{commit}}) -> rebuild the binary -> back up and replace the old one.",
|
||||
"confirmBuildPending": "About to run: build the missing binary for the source already in place (this machine is at {{commit}}) -> rebuild -> back up and replace the old binary.",
|
||||
"applyAccepted": "Update started (job {{id}}); progress refreshes every 1.5 seconds.",
|
||||
"localChangesTitle": "Local changes",
|
||||
"localChangesHint": "Files marked local content are kept exactly as they are; files marked product source block the automatic update.",
|
||||
"noLocalChanges": "Working tree clean: no tracked file is modified or deleted.",
|
||||
@@ -182,7 +177,7 @@
|
||||
"restartRequestedToast": "Switching versions. This page reloads when the service is back.",
|
||||
"restartFailed": "Restart request failed: {{reason}}",
|
||||
"restartOverlayTitle": "Restarting the service…",
|
||||
"restartOverlayBody": "This page reloads when the service is back. You will need to sign in again.",
|
||||
"restartOverlayBody": "This page will reload automatically when the new version is ready.",
|
||||
"restartOverlaySlowRunning": "The service is still answering as the old process - the restart does not seem to have happened. Use the button below to look at the current state.",
|
||||
"restartOverlaySlowDown": "The service is taking longer to come back. This page will keep trying. Check the service logs if it remains unavailable.",
|
||||
"restartOverlayRefresh": "Refresh this page",
|
||||
|
||||
@@ -147,13 +147,8 @@
|
||||
"blockedLocalEdits": "{{n}} файлов исходного кода изменены локально, и обновление не будет их перезаписывать: сначала закоммитьте или отмените изменения.",
|
||||
"blockedDiverged": "Локальная история впереди на {{ahead}} коммитов и отстаёт на {{behind}}: это слияние, а не загрузка, разберитесь вручную.",
|
||||
"blockedNoUpdate": "В источнике обновлений нет ничего новее этой машины (нажмите «Проверить обновления», если ещё не смотрели).",
|
||||
"restartChoiceLabel": "Автоматически перейти на новую версию",
|
||||
"restartNotWired": "Этот способ запуска не поддерживает автоматический переход. После замены файла перезапустите службу штатным способом.",
|
||||
"confirmRestartYes": "Во время сборки служба продолжит работу. Для перехода она кратковременно перезапустится, и страница обновится сама.",
|
||||
"confirmRestartNo": "Старая версия продолжит работать до перезапуска службы.",
|
||||
"confirmApply": "Сейчас будет выполнено: обновление из {{repo}} до {{target}} ({{n}} новых коммитов, эта машина на {{commit}}) -> пересборка бинарного файла -> резервная копия и замена старого.",
|
||||
"confirmBuildPending": "Сейчас будет выполнено: сборка недостающего бинарного файла для уже установленных исходников (эта машина на {{commit}}) -> пересборка -> резервная копия и замена старого бинарного файла.",
|
||||
"applyAccepted": "Обновление запущено (задача {{id}}); ход обновляется каждые 1,5 секунды.",
|
||||
"localChangesTitle": "Локальные изменения",
|
||||
"localChangesHint": "Файлы, помеченные как локальное содержимое, сохраняются как есть; файлы, помеченные как исходный код продукта, блокируют автоматическое обновление.",
|
||||
"noLocalChanges": "Рабочее дерево чистое: ни один отслеживаемый файл не изменён и не удалён.",
|
||||
@@ -182,7 +177,7 @@
|
||||
"restartRequestedToast": "Переключаем версию. Страница обновится, когда служба снова будет доступна.",
|
||||
"restartFailed": "Не удалось запросить перезапуск: {{reason}}",
|
||||
"restartOverlayTitle": "Перезапуск службы…",
|
||||
"restartOverlayBody": "Страница обновится, когда служба снова будет доступна. Потребуется войти заново.",
|
||||
"restartOverlayBody": "Когда новая версия будет готова, страница обновится автоматически.",
|
||||
"restartOverlaySlowRunning": "Служба по-прежнему отвечает старым процессом — перезапуск, похоже, не произошёл. Нажмите кнопку ниже, чтобы увидеть текущее состояние.",
|
||||
"restartOverlaySlowDown": "Служба пока недоступна. Страница продолжит попытки. Если служба долго не отвечает, проверьте её журналы.",
|
||||
"restartOverlayRefresh": "Обновить страницу",
|
||||
|
||||
@@ -147,13 +147,8 @@
|
||||
"blockedLocalEdits": "有 {{n}} 个产品源码文件被本地改过,自动更新不会覆盖它们:先提交或还原。",
|
||||
"blockedDiverged": "本地领先 {{ahead}} 个提交、落后 {{behind}} 个提交:这是合并而不是下载,请先手工处理。",
|
||||
"blockedNoUpdate": "更新源没有比本机更新的提交(还没查过就先点「检查更新」)。",
|
||||
"restartChoiceLabel": "更新成功后自动切换到新版本",
|
||||
"restartNotWired": "当前启动方式不支持自动切换。换入二进制后,请通过部署方式重启服务。",
|
||||
"confirmRestartYes": "构建期间服务照常运行;新版本就绪后会短暂重启,页面随后自动刷新。",
|
||||
"confirmRestartNo": "构建完成后仍运行旧版本,待你重启再切换。",
|
||||
"confirmApply": "将要执行:从更新源 {{repo}} 更新到 {{target}}({{n}} 个新提交,本机当前 {{commit}})→ 重新编译二进制 → 备份并替换旧二进制。",
|
||||
"confirmBuildPending": "将要执行:为已经就位的源码补上二进制(本机当前 {{commit}})→ 重新编译 → 备份并替换旧二进制。",
|
||||
"applyAccepted": "更新已开始(任务 {{id}}),进度每 1.5 秒刷新一次。",
|
||||
"localChangesTitle": "本机改动",
|
||||
"localChangesHint": "标为「本机内容」的文件更新后原样保留;标为「产品源码」的文件会阻止自动更新。",
|
||||
"noLocalChanges": "工作树干净:没有被修改或被删除的受跟踪文件。",
|
||||
@@ -182,7 +177,7 @@
|
||||
"restartRequestedToast": "正在切换版本,服务恢复后页面会自动刷新。",
|
||||
"restartFailed": "重启请求失败:{{reason}}",
|
||||
"restartOverlayTitle": "正在重启服务…",
|
||||
"restartOverlayBody": "服务恢复后页面会自动刷新。当前登录会话会结束,请重新登录。",
|
||||
"restartOverlayBody": "切换完成后,页面会自动恢复。",
|
||||
"restartOverlaySlowRunning": "服务仍在以旧进程应答——重启似乎没有发生。可点下方按钮刷新页面查看当前状态。",
|
||||
"restartOverlaySlowDown": "服务仍未恢复,页面会继续重试。如果长时间无法连接,请检查服务日志。",
|
||||
"restartOverlayRefresh": "立即刷新页面",
|
||||
|
||||
@@ -91,7 +91,7 @@ test('every control the update page disables by state carries the marker the gat
|
||||
console,
|
||||
escapeHtml: (v) => String(v),
|
||||
updateT: (key) => key,
|
||||
renderUpdateRestartChoice: () => '',
|
||||
renderUpdateSwitchHint: () => '',
|
||||
renderUpdateChangesTable: () => '<div class="update-changes"></div>',
|
||||
isUpdateJobRunning: () => true,
|
||||
updateApplyBlockers: (status) => (status.blockingChanges || []).length ? ['blocked'] : [],
|
||||
|
||||
@@ -14,7 +14,7 @@ const ru = JSON.parse(fs.readFileSync('web/static/i18n/ru-RU.json', 'utf8'));
|
||||
|
||||
// The only handlers this console is allowed to wire into markup.
|
||||
const HANDLES = ['startUpdateApply', 'checkForUpdates', 'rollbackUpdate',
|
||||
'updateRestartChoiceChanged', 'loadUpdateConsole',
|
||||
'loadUpdateConsole',
|
||||
'saveUpdateSource', 'previewAdoptSource', 'confirmAdoptSource',
|
||||
'startRestartNow', 'refreshUpdatePage'];
|
||||
|
||||
@@ -168,8 +168,6 @@ function harness(options) {
|
||||
const el = {
|
||||
id,
|
||||
innerHTML: '',
|
||||
checked: id === 'update-restart-choice' &&
|
||||
/id="update-restart-choice" checked/.test(nodes.get('update-console')?.innerHTML || ''),
|
||||
insertAdjacentHTML(_pos, html) { this.innerHTML = html + this.innerHTML; },
|
||||
};
|
||||
// 控制台住在系统设置页的「一键更新」分区里:页面和分区都得是 active,它才算在前台。
|
||||
@@ -228,6 +226,8 @@ function harness(options) {
|
||||
String,
|
||||
Date,
|
||||
Math,
|
||||
URLSearchParams,
|
||||
authToken: 'test-session',
|
||||
escapeHtml(text) {
|
||||
const div = sandbox.document.createElement('div');
|
||||
div.textContent = text;
|
||||
@@ -302,6 +302,9 @@ function harness(options) {
|
||||
});
|
||||
},
|
||||
fetch(url, reqOpts = {}) {
|
||||
if (url === '/api/system/update/job') {
|
||||
return sandbox.apiFetch(url, reqOpts);
|
||||
}
|
||||
fetchProbes.push({ url, opts: reqOpts });
|
||||
const answer = probeQueue.length > 1 ? probeQueue.shift() : (probeQueue[0] || 'ok');
|
||||
if (answer === 'down') {
|
||||
@@ -328,6 +331,7 @@ function harness(options) {
|
||||
location: {
|
||||
pathname: '/',
|
||||
hash: '',
|
||||
search: opts.search || '',
|
||||
replaced: [],
|
||||
reloads: 0,
|
||||
replace(target) { this.replaced.push(target); },
|
||||
@@ -340,12 +344,11 @@ function harness(options) {
|
||||
vm.runInContext(`
|
||||
this.api = {
|
||||
loadUpdateConsole, checkForUpdates, startUpdateApply, rollbackUpdate,
|
||||
updateRestartChoiceChanged, pollUpdateJob, renderUpdateConsole, stopUpdatePolling,
|
||||
pollUpdateJob, renderUpdateConsole, stopUpdatePolling,
|
||||
startRestartNow
|
||||
};
|
||||
this.vars = {
|
||||
setBusy(v) { updateBusy = v; },
|
||||
getRestartChoice() { return updateRestartChoice; },
|
||||
getPollTimer() { return updatePollTimer; },
|
||||
getCheckDone() { return updateCheck.done; },
|
||||
autoCheckDone() { return updateAutoCheckDone; },
|
||||
@@ -436,7 +439,7 @@ test('the console lives inside the settings page as its own section', () => {
|
||||
'settings-section-update must live inside page-settings');
|
||||
assert.match(template, /id="settings-section-update"[\s\S]{0,700}?id="update-console"/);
|
||||
assert.match(template, /id="update-console"/);
|
||||
assert.match(template, /<script src="\/static\/js\/update\.js\?v=\{\{\.Version\}\}"><\/script>/);
|
||||
assert.match(template, /<script src="\/static\/js\/update\.js\?v=\{\{\.Version\}\}-auto-switch"><\/script>/);
|
||||
assert.match(template, /<div class="settings-section-header update-section-head">/);
|
||||
assert.match(template, /<h3 data-i18n="update\.title">/);
|
||||
|
||||
@@ -473,7 +476,7 @@ test('the update console has its own stylesheet section', () => {
|
||||
assert.ok(block.includes('.update-console'), 'the .update-* section must follow its own section header');
|
||||
['.update-console', '.update-section-head', '.update-section-title', '.update-facts', '.update-chip-ok', '.update-chip-warn',
|
||||
'.update-chip-danger', '.update-error', '.update-check-failed', '.update-step-list', '.update-table',
|
||||
'.update-restart-choice', '.update-blocker-list', '.update-apply-btn:disabled'].forEach(sel => {
|
||||
'.update-blocker-list', '.update-apply-btn:disabled'].forEach(sel => {
|
||||
assert.ok(sheet.includes(sel), sel + ' must be defined');
|
||||
});
|
||||
// Every class the console emits has to be styled or be an existing shared one: a hook name
|
||||
@@ -749,8 +752,6 @@ test('a tree that only owes a build still offers the button, and says it is a bu
|
||||
await h.flush();
|
||||
const apply = h.calls.find(c => c.method === 'POST' && c.url === '/api/system/update/apply');
|
||||
assert.ok(apply, 'the retry must reach the server: ' + h.calls.map(c => c.method + ' ' + c.url));
|
||||
assert.match(h.confirms[h.confirms.length - 1], /补上二进制/,
|
||||
'the confirm dialog describes a build, not "0 new commits"');
|
||||
const success = h.toasts.filter(t => t.type === 'success' && /补编译完成/.test(t.msg)).pop();
|
||||
assert.ok(success, 'a finished build retry is announced as a build: ' + JSON.stringify(h.toasts));
|
||||
assert.deepEqual(h.toasts.filter(t => t.type === 'success' && /a1b2c3d → a1b2c3d/.test(t.msg)), [],
|
||||
@@ -789,7 +790,7 @@ test('a pending build with no toolchain fails with the server sentence, never a
|
||||
'the server sentence must be shown: ' + JSON.stringify(h.toasts));
|
||||
});
|
||||
|
||||
test('applying posts {"restart":false} and then reads the job every 1.5 seconds', async () => {
|
||||
test('applying reads the job every 1.5 seconds', async () => {
|
||||
// This test is about the poll cadence and the final re-read, so the job finishes without
|
||||
// having asked for a restart; the restart hand-off has its own test below.
|
||||
const plainSucceededJob = Object.assign({}, succeededJob, { restartRequested: false });
|
||||
@@ -822,7 +823,7 @@ test('applying posts {"restart":false} and then reads the job every 1.5 seconds'
|
||||
|
||||
const apply = h.calls.find(c => c.method === 'POST' && c.url === '/api/system/update/apply');
|
||||
assert.ok(apply, 'no apply was posted: ' + h.calls.map(c => c.method + ' ' + c.url));
|
||||
assert.deepEqual(JSON.parse(apply.body), { restart: false },
|
||||
assert.deepEqual(JSON.parse(apply.body), { restart: true },
|
||||
'the body is one object carrying a restart boolean, not a positional bag');
|
||||
assert.equal(h.liveTimers().length, 1, 'exactly one poller: ' + JSON.stringify(h.timers.map(t => t.ms)));
|
||||
assert.equal(h.liveTimers()[0].ms, 1500, 'progress must be read every 1.5 seconds');
|
||||
@@ -887,72 +888,25 @@ test('a failing job shows the server message with its item list, and never claim
|
||||
assert.equal(h.toasts[h.toasts.length - 1].type, 'error');
|
||||
});
|
||||
|
||||
test('the restart tick only appears when the process can actually be restarted', async () => {
|
||||
const off = await harness({ canRestart: false });
|
||||
assert.doesNotMatch(off.html(), /id="update-restart-choice"/,
|
||||
'offering a promise the platform cannot keep is a lie');
|
||||
assert.match(off.html(), /当前启动方式不支持自动切换/);
|
||||
|
||||
const on = await harness({
|
||||
canRestart: true,
|
||||
// No job to adopt: a running job would (correctly) block the second click, and this test
|
||||
// is about what the checkbox does to the body, not about the block.
|
||||
responses: { 'GET /api/system/update/job': [{ status: 200, body: { job: null } }] },
|
||||
});
|
||||
assert.match(on.html(), /<input type="checkbox" id="update-restart-choice"[^>]*onchange="updateRestartChoiceChanged\(this\.checked\)">/);
|
||||
assert.ok(!/id="update-restart-choice" checked/.test(on.html()),
|
||||
'with nothing supervising the process, the tick must default to off: ticking it would just stop the platform');
|
||||
|
||||
const standalone = await harness({
|
||||
canRestart: true,
|
||||
flags: { autoRestart: true, supervised: false },
|
||||
responses: { 'GET /api/system/update/job': [{ status: 200, body: { job: { ...runningJob, restartRequested: true } } }] },
|
||||
});
|
||||
assert.match(standalone.html(), /id="update-restart-choice" checked/,
|
||||
'the standalone executable supports automatic activation');
|
||||
await standalone.api.startUpdateApply();
|
||||
assert.deepEqual(JSON.parse(standalone.calls.find(c => c.url === '/api/system/update/apply').body), { restart: true });
|
||||
// Once the operator decides for themselves, the default stops second-guessing them.
|
||||
standalone.sandbox.document.getElementById('update-restart-choice').checked = false;
|
||||
standalone.fire('updateRestartChoiceChanged', { checked: false });
|
||||
assert.ok(!/id="update-restart-choice" checked/.test(standalone.html()));
|
||||
|
||||
on.calls.length = 0;
|
||||
on.fire('startUpdateApply');
|
||||
await on.flush();
|
||||
assert.deepEqual(JSON.parse(on.calls.find(c => c.url === '/api/system/update/apply').body), { restart: false });
|
||||
|
||||
// Tick it through the rendered onchange, exactly as a browser does (the element is already
|
||||
// checked when change fires), then apply again.
|
||||
on.vars.setBusy(false);
|
||||
on.nodes.get('update-restart-choice').checked = true;
|
||||
on.fire('updateRestartChoiceChanged', { checked: true });
|
||||
assert.equal(on.vars.getRestartChoice(), true);
|
||||
assert.match(on.html(), /id="update-restart-choice" checked/, 'the tick must survive the repaint');
|
||||
|
||||
on.calls.length = 0;
|
||||
on.vars.setBusy(false);
|
||||
on.fire('startUpdateApply');
|
||||
await on.flush();
|
||||
assert.deepEqual(JSON.parse(on.calls.find(c => c.url === '/api/system/update/apply').body), { restart: true },
|
||||
'the restart flag that goes out is the checkbox, not a guess');
|
||||
});
|
||||
|
||||
test('the confirm dialog says what the update will do, and cancelling posts nothing', async () => {
|
||||
const h = await harness();
|
||||
h.setConfirm(false);
|
||||
h.calls.length = 0;
|
||||
h.toasts.length = 0;
|
||||
h.fire('startUpdateApply');
|
||||
await h.flush();
|
||||
assert.equal(h.confirms.length, 1, 'the operator must be asked before the tree moves');
|
||||
assert.match(h.confirms[0], /重新编译/, 'the confirm must say the binary gets rebuilt: ' + h.confirms[0]);
|
||||
assert.match(h.confirms[0], /二进制/);
|
||||
assert.match(h.confirms[0], /github\.com\/AIPentest\/CyberStrikeAI/, 'the confirm must name the repository being fetched');
|
||||
assert.match(h.confirms[0], /a1b2c3d/, 'the confirm must name where this machine is now');
|
||||
assert.doesNotMatch(h.confirms[0], /\{\{/, 'the confirm went out un-interpolated: ' + h.confirms[0]);
|
||||
assert.deepEqual(h.calls.map(c => c.method + ' ' + c.url), [], 'a cancelled update must not POST');
|
||||
assert.deepEqual(h.toasts, [], 'a cancelled update must not be reported as anything');
|
||||
test('one click requests automatic activation when supported, with no prompt or start toast', async () => {
|
||||
for (const canRestart of [true, false]) {
|
||||
const h = await harness({
|
||||
canRestart,
|
||||
confirm: false,
|
||||
responses: { 'GET /api/system/update/job': [{
|
||||
status: 200, body: { job: { ...runningJob, restartRequested: canRestart } },
|
||||
}] },
|
||||
});
|
||||
assert.match(h.html(), canRestart ? /页面随后自动刷新/ : /当前启动方式不支持自动切换/);
|
||||
assert.doesNotMatch(h.html(), /id="update-restart-choice"/);
|
||||
h.fire('startUpdateApply');
|
||||
await h.flush();
|
||||
const apply = h.calls.filter(c => c.url === '/api/system/update/apply');
|
||||
assert.equal(apply.length, 1);
|
||||
assert.deepEqual(JSON.parse(apply[0].body), { restart: canRestart });
|
||||
assert.deepEqual(h.confirms, []);
|
||||
assert.deepEqual(h.toasts, []);
|
||||
}
|
||||
});
|
||||
|
||||
test('a second apply is refused with 409 and the running job is adopted', async () => {
|
||||
@@ -971,7 +925,7 @@ test('a second apply is refused with 409 and the running job is adopted', async
|
||||
await h.flush();
|
||||
const apply = h.calls.find(c => c.url === '/api/system/update/apply');
|
||||
assert.equal(apply.method, 'POST');
|
||||
assert.deepEqual(JSON.parse(apply.body), { restart: false });
|
||||
assert.deepEqual(JSON.parse(apply.body), { restart: true });
|
||||
assert.match(h.html(), /正在编译二进制/, 'the job the server named must be shown, not swallowed');
|
||||
assert.match(h.html(), /upd-7/);
|
||||
assert.match(h.toasts[h.toasts.length - 1].msg, /已有一次更新在进行中/);
|
||||
@@ -1132,13 +1086,13 @@ test('server strings cannot become markup, in text or in an attribute', async ()
|
||||
// Every emitted handler must still be executable as written: an injection into an attribute
|
||||
// would break the statement instead.
|
||||
const found = h.extractHandlers(html);
|
||||
assert.ok(found.onclick.length && found.onchange.length, 'handlers must still render under hostile data');
|
||||
assert.ok(found.onclick.length, 'handlers must still render under hostile data');
|
||||
found.onclick.concat(found.onchange).forEach(text => {
|
||||
assert.doesNotMatch(text, /"/, 'handler text carries a raw quote: ' + text);
|
||||
assert.equal(typeof vm.runInContext('(function(){' + text + '})', h.sandbox), 'function',
|
||||
'the emitted handler is not valid JS: ' + text);
|
||||
});
|
||||
['startUpdateApply', 'checkForUpdates', 'rollbackUpdate', 'updateRestartChoiceChanged']
|
||||
['startUpdateApply', 'checkForUpdates', 'rollbackUpdate']
|
||||
.forEach(name => assert.ok(found.onclick.concat(found.onchange).some(t => t.startsWith(name + '(')),
|
||||
name + ' must stay wired'));
|
||||
});
|
||||
@@ -1183,6 +1137,7 @@ test('opening the page schedules exactly one deferred remote check', async () =>
|
||||
const checks = h.calls.filter(c => c.method === 'POST' && c.url === '/api/system/update/check');
|
||||
assert.strictEqual(checks.length, 1, 'the deferred timer must ask the remote exactly once');
|
||||
assert.match(h.html(), /3/, 'the answer must be on screen without another click');
|
||||
assert.deepEqual(h.toasts, [], 'a background check should not pop up a success message');
|
||||
|
||||
// Re-entering the page in the same session does not go back to the remote again.
|
||||
h.api.loadUpdateConsole();
|
||||
@@ -1317,7 +1272,7 @@ test('adopt previews first, and confirming carries the counts into the dialog',
|
||||
assert.match(h.confirms[0], /42/, 'the dialog counts what will happen');
|
||||
const adopt = h.calls.find(c => c.url === '/api/system/update/adopt' && c.method === 'POST' && c.body && c.body.includes('"confirm":true'));
|
||||
assert.ok(adopt, 'confirming must post to adopt');
|
||||
assert.deepEqual(JSON.parse(adopt.body), { confirm: true, restart: false });
|
||||
assert.deepEqual(JSON.parse(adopt.body), { confirm: true, restart: true });
|
||||
assert.ok(h.vars.getPollTimer(), 'the job it started must be polled');
|
||||
});
|
||||
|
||||
@@ -1452,17 +1407,15 @@ test('a restart that does not come back says so instead of spinning forever', as
|
||||
|
||||
test('an update that asked for a restart hands the page to the watchdog instead of reporting a failed poll', async () => {
|
||||
const h = await harness({
|
||||
flags: { supervised: true },
|
||||
search: '?view=ops',
|
||||
responses: {
|
||||
'GET /api/system/update/job': [
|
||||
{ status: 200, body: { job: runningJob } },
|
||||
{ status: 200, body: { job: { ...runningJob, restartRequested: true } } },
|
||||
{ status: 200, body: { job: succeededJob } },
|
||||
],
|
||||
},
|
||||
probes: ['unauthorized'],
|
||||
probes: ['bad gateway', { status: 200, bootID: 'new' }],
|
||||
});
|
||||
// In a real browser the pre-ticked box makes this true; the harness reads the element.
|
||||
h.sandbox.document.getElementById('update-restart-choice').checked = true;
|
||||
h.fire('startUpdateApply');
|
||||
await h.flush();
|
||||
const apply = h.calls.find(c => c.url === '/api/system/update/apply');
|
||||
@@ -1477,10 +1430,14 @@ test('an update that asked for a restart hands the page to the watchdog instead
|
||||
assert.deepEqual(h.toasts.filter(t => t.type === 'error'), [],
|
||||
'the process going away by request is not a polling failure to complain about');
|
||||
assert.ok(h.vars.restartPending());
|
||||
assert.doesNotMatch(h.html(), /立即刷新页面|重新登录/);
|
||||
|
||||
await h.tick();
|
||||
await h.flush();
|
||||
assert.deepEqual(h.location.replaced, [], 'a proxy error must not reload');
|
||||
await h.tick();
|
||||
assert.equal(h.probes.at(-1).opts.headers.Authorization, 'Bearer test-session');
|
||||
assert.equal(h.location.replaced.length, 1);
|
||||
assert.match(h.location.replaced[0], /view=ops&restarted=\d+#system-update$/);
|
||||
});
|
||||
|
||||
test('a job poll that dies while the restart is in flight is not a failure', async () => {
|
||||
@@ -1491,7 +1448,6 @@ test('a job poll that dies while the restart is in flight is not a failure', asy
|
||||
rejects: ['GET /api/system/update/job'],
|
||||
probes: ['unauthorized'],
|
||||
});
|
||||
h.sandbox.document.getElementById('update-restart-choice').checked = true;
|
||||
h.fire('startUpdateApply');
|
||||
await h.flush();
|
||||
assert.match(h.html(), /正在重启服务/, 'a dead poll while a restart is requested means the restart is in flight');
|
||||
|
||||
+45
-77
@@ -25,8 +25,7 @@ let updateCheck = { done: false, error: '' };
|
||||
let updateBusy = false; // 页面自己发着的动作请求(检查 / 启动更新 / 回滚 / 重启)
|
||||
let updateChecking = false; // 只影响「检查更新」按钮的措辞
|
||||
let updatePollTimer = null;
|
||||
let updateRestartChoice = false;
|
||||
let updateRestartChoiceSet = false; // 操作员本次会话手动改过之后,默认值不再顶掉他的选择
|
||||
let updatePollInFlight = null;
|
||||
let updateRestartExpected = false; // 更新结束后预计重启,构建阶段仍照常读进度
|
||||
let updateRestartPending = false; // 正在等待服务恢复
|
||||
let updateWatchdogTimer = null; // 重启守侧自己的定时器,跟任务进度轮询互不干扰
|
||||
@@ -76,8 +75,8 @@ function scheduleUpdateAutoCheck() {
|
||||
if (!status || !status.installed || isUpdateJobRunning()) return false;
|
||||
updateAutoCheckDone = true;
|
||||
setTimeout(() => {
|
||||
if (!isUpdateConsoleActive()) return;
|
||||
checkForUpdates();
|
||||
if (!isUpdateConsoleActive() || isUpdateJobRunning() || updateRestartPending) return;
|
||||
checkForUpdates({ quiet: true });
|
||||
}, 1200);
|
||||
return true;
|
||||
}
|
||||
@@ -123,8 +122,8 @@ function resetUpdateCheck() {
|
||||
// ok 不等于状态码:rollback 在"源码回了、二进制没回"这种半途情况下是按 202 回答并带着
|
||||
// error 字段的(handler 里的 statusForError 把 no_toolchain 归到 202),只信 resp.ok
|
||||
// 就会对着一次没做完的回滚播报成功。
|
||||
async function runUpdateRequest(method, url, body) {
|
||||
const resp = await apiFetch(url, {
|
||||
async function runUpdateRequest(method, url, body, request = apiFetch) {
|
||||
const resp = await request(url, {
|
||||
method: method,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
@@ -139,6 +138,20 @@ async function runUpdateRequest(method, url, body) {
|
||||
};
|
||||
}
|
||||
|
||||
// A proxy 401 or a dropped connection during the switch must not clear the session.
|
||||
function fetchDuringUpdate(url, options = {}) {
|
||||
const headers = { Accept: 'application/json', ...options.headers };
|
||||
if (typeof authToken === 'string' && authToken) headers.Authorization = 'Bearer ' + authToken;
|
||||
return fetch(url, {
|
||||
...options,
|
||||
credentials: 'same-origin',
|
||||
cache: 'no-store',
|
||||
redirect: 'error',
|
||||
headers,
|
||||
signal: typeof AbortSignal !== 'undefined' && AbortSignal.timeout ? AbortSignal.timeout(5000) : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchUpdateStatus() {
|
||||
const r = await runUpdateRequest('GET', '/api/system/update');
|
||||
if (!r.ok) throw new Error(r.error);
|
||||
@@ -146,22 +159,14 @@ async function fetchUpdateStatus() {
|
||||
status: r.data.status || {},
|
||||
job: r.data.job || null,
|
||||
canRestart: !!r.data.canRestart,
|
||||
// Old backends have no self-restart capability field.
|
||||
autoRestart: r.data.autoRestart ?? !!r.data.supervised,
|
||||
bootID: r.data.bootID || '',
|
||||
needsRestart: !!r.data.needsRestart,
|
||||
binaryBuiltAt: r.data.binaryBuiltAt || '',
|
||||
source: r.data.source || { repo: '', configured: false, defaultRepo: '' },
|
||||
};
|
||||
noteRestartDefault();
|
||||
return updateConsoleState;
|
||||
}
|
||||
|
||||
function noteRestartDefault() {
|
||||
if (updateRestartChoiceSet) return;
|
||||
updateRestartChoice = updateCanRestart() && updateConsoleState.autoRestart;
|
||||
}
|
||||
|
||||
// notify 只在平台真的载了 showNotification 时才动。它绝不能成为"操作看起来失败"的原因:
|
||||
// 请求已经成功了,为了播报一句去调一个页面上不存在的函数,会把成功炸成失败。
|
||||
function notify(message, type) {
|
||||
@@ -213,8 +218,6 @@ async function loadUpdateConsole() {
|
||||
return;
|
||||
}
|
||||
resetUpdateCheck();
|
||||
updateRestartChoiceSet = false;
|
||||
updateRestartChoice = false;
|
||||
updateActionError = ''; // 重新进页 = 干净画面,上一次动作的红字不跟过来
|
||||
const el = document.getElementById('update-console');
|
||||
if (!el) return;
|
||||
@@ -268,16 +271,7 @@ async function watchdogProbe() {
|
||||
let legacyUnauthorized = false;
|
||||
const previousBoot = updateConsoleState && updateConsoleState.bootID;
|
||||
try {
|
||||
const headers = { Accept: 'application/json' };
|
||||
if (typeof authToken === 'string' && authToken) headers.Authorization = 'Bearer ' + authToken;
|
||||
const resp = await fetch('/api/auth/validate', {
|
||||
method: 'GET',
|
||||
credentials: 'same-origin',
|
||||
cache: 'no-store',
|
||||
redirect: 'error',
|
||||
headers: headers,
|
||||
signal: typeof AbortSignal !== 'undefined' && AbortSignal.timeout ? AbortSignal.timeout(5000) : undefined,
|
||||
});
|
||||
const resp = await fetchDuringUpdate('/api/auth/validate');
|
||||
status = resp.status;
|
||||
bootID = resp.headers?.get('X-CyberStrike-Boot-ID') || '';
|
||||
if (status === 401 && !bootID) {
|
||||
@@ -293,7 +287,9 @@ async function watchdogProbe() {
|
||||
if (!isUpdateConsoleActive() || !updateWatchdogTimer) return;
|
||||
if ((bootID && bootID !== previousBoot && (status === 200 || status === 401)) || legacyUnauthorized) {
|
||||
stopUpdateWatchdog();
|
||||
location.replace(location.pathname + '?restarted=' + Date.now() + '#system-update');
|
||||
const params = new URLSearchParams(location.search);
|
||||
params.set('restarted', Date.now());
|
||||
location.replace(location.pathname + '?' + params + '#system-update');
|
||||
return;
|
||||
}
|
||||
if (updateRestartExpected && previousBoot && bootID === previousBoot && status === 200) {
|
||||
@@ -331,14 +327,21 @@ async function pollUpdateJob() {
|
||||
stopUpdatePolling();
|
||||
return;
|
||||
}
|
||||
const timer = updatePollTimer;
|
||||
if (!timer || updatePollInFlight === timer) return;
|
||||
updatePollInFlight = timer;
|
||||
// 传输层死亡(连接被拒、进程已经退出)是 reject 而不是带状态码的回应:两者在这里
|
||||
// 归一——重启进行中它就是"进程退了",否则才是要播报的读取失败。
|
||||
let r;
|
||||
try {
|
||||
r = await runUpdateRequest('GET', '/api/system/update/job');
|
||||
r = await runUpdateRequest('GET', '/api/system/update/job', undefined,
|
||||
updateRestartExpected ? fetchDuringUpdate : apiFetch);
|
||||
} catch (err) {
|
||||
r = { ok: false, error: err && err.message ? err.message : String(err) };
|
||||
} finally {
|
||||
if (updatePollInFlight === timer) updatePollInFlight = null;
|
||||
}
|
||||
if (timer !== updatePollTimer || !isUpdateConsoleActive()) return;
|
||||
if (!r.ok) {
|
||||
stopUpdatePolling();
|
||||
if (updateRestartExpected) {
|
||||
@@ -405,7 +408,7 @@ function reportFinishedJob(job) {
|
||||
// 动作
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function checkForUpdates() {
|
||||
async function checkForUpdates({ quiet = false } = {}) {
|
||||
await withUpdateBusy(async () => {
|
||||
updateChecking = true;
|
||||
renderUpdateConsole();
|
||||
@@ -429,6 +432,8 @@ async function checkForUpdates() {
|
||||
renderUpdateConsole();
|
||||
if (updateCheck.error) {
|
||||
notify(updateT(UPDATE_FAILURE_KEYS.check, { reason: updateCheck.error }), 'error');
|
||||
} else if (quiet) {
|
||||
return;
|
||||
} else if (status.updateAvailable) {
|
||||
notify(updateT('behindCount', { n: updateBehindCount(status) }), 'info');
|
||||
} else {
|
||||
@@ -462,32 +467,6 @@ function updateApplyBlockers(status, job) {
|
||||
return blockers;
|
||||
}
|
||||
|
||||
function updateRestartChoiceChanged(checked) {
|
||||
updateRestartChoice = !!checked;
|
||||
updateRestartChoiceSet = true; // 操作员自己决定过之后,服务端的默认值不再覆盖他
|
||||
renderUpdateConsole();
|
||||
}
|
||||
|
||||
// 勾选框是唯一的真相来源;模块里那份只是给轮询重绘用的记忆。
|
||||
function updateRestartRequested() {
|
||||
const box = document.getElementById('update-restart-choice');
|
||||
if (box && typeof box.checked === 'boolean') return box.checked;
|
||||
return updateRestartChoice;
|
||||
}
|
||||
|
||||
function updateConfirmText(status, restart) {
|
||||
// 补编译和"更新 N 个提交"是两件事:一句说"0 个新提交"的确认框会让人以为白点。
|
||||
const base = (!status.updateAvailable && status.buildPending)
|
||||
? updateT('confirmBuildPending', { commit: status.commit || '-' })
|
||||
: updateT('confirmApply', {
|
||||
repo: status.repo || '-',
|
||||
target: status.remoteCommit || '-',
|
||||
commit: status.commit || '-',
|
||||
n: updateBehindCount(status),
|
||||
});
|
||||
return base + ' ' + (restart ? updateT('confirmRestartYes') : updateT('confirmRestartNo'));
|
||||
}
|
||||
|
||||
async function startUpdateApply() {
|
||||
if (updateBusy) return;
|
||||
const status = updateStatusOf();
|
||||
@@ -498,14 +477,14 @@ async function startUpdateApply() {
|
||||
notify(blockers[0], 'error');
|
||||
return;
|
||||
}
|
||||
const restart = updateRestartRequested();
|
||||
if (!window.confirm(updateConfirmText(status, restart))) return;
|
||||
const restart = updateCanRestart();
|
||||
|
||||
await withUpdateBusy(async () => {
|
||||
const r = await runUpdateRequest('POST', '/api/system/update/apply', { restart: restart });
|
||||
if (r.status === 409 && r.data.job) {
|
||||
// 另一次更新真的在跑:把它的进度接下来并接着看,这才是"当前状态"。
|
||||
if (updateConsoleState) updateConsoleState.job = r.data.job;
|
||||
updateRestartExpected = !!r.data.job.restartRequested;
|
||||
renderUpdateConsole();
|
||||
startUpdatePolling();
|
||||
}
|
||||
@@ -513,7 +492,6 @@ async function startUpdateApply() {
|
||||
resetUpdateCheck();
|
||||
updateRestartExpected = restart;
|
||||
startUpdatePolling();
|
||||
notify(updateT('applyAccepted', { id: r.data.job_id || '-' }), 'success');
|
||||
await pollUpdateJob();
|
||||
}, 'apply');
|
||||
}
|
||||
@@ -607,7 +585,7 @@ async function previewAdoptSource() {
|
||||
|
||||
async function confirmAdoptSource() {
|
||||
if (updateBusy || !updateAdoptPlan) return;
|
||||
const restart = updateRestartRequested();
|
||||
const restart = updateCanRestart();
|
||||
const text = updateT('adoptConfirmText', {
|
||||
incoming: updateAdoptPlan.incoming,
|
||||
overwritten: updateAdoptPlan.overwrittenTotal,
|
||||
@@ -703,7 +681,7 @@ function renderAdoptBody() {
|
||||
parts.push(list(plan.overwritten, updateT('adoptOverwrittenTitle')));
|
||||
parts.push(list(plan.protected, updateT('adoptProtectedTitle')));
|
||||
parts.push('<div class="update-hint">' + escapeHtml(updateT('adoptBackupNote')) + '</div>');
|
||||
parts.push(renderUpdateRestartChoice());
|
||||
parts.push(renderUpdateSwitchHint());
|
||||
parts.push('<div class="update-actions"><button class="btn-primary update-adopt-confirm-btn"' + disabled +
|
||||
' data-require-permission="update:apply" onclick="confirmAdoptSource()">' +
|
||||
escapeHtml(updateT('adoptConfirmBtn')) + '</button></div>');
|
||||
@@ -788,18 +766,9 @@ function renderUpdateChangesTable(list) {
|
||||
'</tr></thead><tbody>' + rows + '</tbody></table>';
|
||||
}
|
||||
|
||||
function renderUpdateRestartChoice() {
|
||||
if (!updateCanRestart()) {
|
||||
// 后端没给重启钩子,勾选框就不该出现:勾一个不会被兑现的选项是骗人。
|
||||
return '<div class="update-hint">' + escapeHtml(updateT('restartNotWired')) + '</div>';
|
||||
}
|
||||
const preview = updateRestartChoice ? updateT('confirmRestartYes') : updateT('confirmRestartNo');
|
||||
return '<label class="update-restart-choice">' +
|
||||
'<input type="checkbox" id="update-restart-choice"' +
|
||||
(updateRestartChoice ? ' checked' : '') +
|
||||
' onchange="updateRestartChoiceChanged(this.checked)">' +
|
||||
'<span>' + escapeHtml(updateT('restartChoiceLabel')) + '</span></label>' +
|
||||
'<div class="update-hint update-restart-preview">' + escapeHtml(preview) + '</div>';
|
||||
function renderUpdateSwitchHint() {
|
||||
return '<div class="update-hint">' +
|
||||
escapeHtml(updateT(updateCanRestart() ? 'confirmRestartYes' : 'restartNotWired')) + '</div>';
|
||||
}
|
||||
|
||||
function renderUpdateApplyBody(status, job) {
|
||||
@@ -837,7 +806,7 @@ function renderUpdateApplyBody(status, job) {
|
||||
escapeHtml(updateChecking ? updateT('checking') : updateT('checkBtn')) + '</button>' +
|
||||
'</div>');
|
||||
|
||||
parts.push(renderUpdateRestartChoice());
|
||||
parts.push(renderUpdateSwitchHint());
|
||||
|
||||
if (blocked) {
|
||||
parts.push('<ul class="update-blocker-list">' + blockers.map(b =>
|
||||
@@ -999,10 +968,10 @@ function renderUpdateWatchdog() {
|
||||
if (updateWatchdogSlow) {
|
||||
parts.push('<div class="update-overlay-slow">' + escapeHtml(updateT(
|
||||
updateWatchdogSlow === 'running' ? 'restartOverlaySlowRunning' : 'restartOverlaySlowDown')) + '</div>');
|
||||
parts.push('<div class="update-overlay-actions">' +
|
||||
'<button class="btn-secondary" type="button" onclick="refreshUpdatePage()">' +
|
||||
escapeHtml(updateT('restartOverlayRefresh')) + '</button></div>');
|
||||
}
|
||||
parts.push('<div class="update-overlay-actions">' +
|
||||
'<button class="btn-secondary" type="button" onclick="refreshUpdatePage()">' +
|
||||
escapeHtml(updateT('restartOverlayRefresh')) + '</button></div>');
|
||||
parts.push('</div>');
|
||||
el.innerHTML = parts.join('');
|
||||
}
|
||||
@@ -1042,7 +1011,6 @@ window.startUpdateApply = startUpdateApply;
|
||||
window.startRestartNow = startRestartNow;
|
||||
window.refreshUpdatePage = refreshUpdatePage;
|
||||
window.rollbackUpdate = rollbackUpdate;
|
||||
window.updateRestartChoiceChanged = updateRestartChoiceChanged;
|
||||
window.stopUpdatePolling = stopUpdatePolling;
|
||||
window.renderUpdateConsole = renderUpdateConsole;
|
||||
window.saveUpdateSource = saveUpdateSource;
|
||||
|
||||
@@ -7097,7 +7097,7 @@
|
||||
<script src="/static/js/tasks.js?v=20261103-personal-integration"></script>
|
||||
<script src="/static/js/workflow-package-client.js"></script>
|
||||
<script src="/static/js/workflows.js"></script>
|
||||
<script src="/static/js/update.js?v={{.Version}}"></script>
|
||||
<script src="/static/js/update.js?v={{.Version}}-auto-switch"></script>
|
||||
<script src="/static/js/roles.js?v=20261103-personal-integration"></script>
|
||||
<script src="/static/js/rbac.js"></script>
|
||||
<script src="/static/js/c2.js?v=20261103-personal-integration"></script>
|
||||
|
||||
Reference in new issue
Block a user