Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
faaa614cee | ||
|
|
9afd7d0067 | ||
|
|
8abb9d8a55 |
No files matched your search
@@ -1,5 +1,6 @@
|
|||||||
frontend/node_modules/
|
frontend/node_modules/
|
||||||
frontend/dist/
|
frontend/dist/
|
||||||
|
frontend/dist-demo/
|
||||||
frontend/*.tsbuildinfo
|
frontend/*.tsbuildinfo
|
||||||
frontend/vite.config.js
|
frontend/vite.config.js
|
||||||
frontend/vite.config.d.ts
|
frontend/vite.config.d.ts
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
# Sea vHost
|
# Sea vHost
|
||||||
|
|
||||||
36 单机实机测试从 [交付说明](docs/handover-2026-10-30.md) 开始。现有服务已启动,直接访问控制台;无需重新安装。标准安装包与干净源码包分别交付,文件清单及用途见 [安装工具说明](deploy/README.md)。
|
最新源码整理与文件管理更新见 [v0.1.0-rc.5 说明](docs/release-v0.1.0-rc.5.md)。
|
||||||
|
|
||||||
|
日常管理从 [操作说明](docs/hosting-operations.md) 开始;36 的早期重装记录见 [10-30 交付说明](docs/handover-2026-10-30.md),其中旧体验资源及空白向导状态属于历史记录。标准安装包与干净源码包分别交付,文件清单及用途见 [安装工具说明](deploy/README.md)。
|
||||||
|
|
||||||
Sea vHost 是面向 Debian + 宝塔 Linux 面板的多租户虚拟主机控制面,支持本机托管或主控主动连接多台被控。主控集中保存平台 MySQL 数据与调度状态,通过双向 TLS 调用被控的受限执行入口;被控使用本机宝塔 API 管理 Nginx 站点、FTP、MySQL、SSL、反向代理和运行环境,并用隔离代理管理固定根目录、目录权限和自有 Nginx 安全配置。
|
Sea vHost 是面向 Debian + 宝塔 Linux 面板的多租户虚拟主机控制面,支持本机托管或主控主动连接多台被控。主控集中保存平台 MySQL 数据与调度状态,通过双向 TLS 调用被控的受限执行入口;被控使用本机宝塔 API 管理 Nginx 站点、FTP、MySQL、SSL、反向代理和运行环境,并用隔离代理管理固定根目录、目录权限和自有 Nginx 安全配置。
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Stable internal IDs keep batch previews and retries consistent without exposing an extra form field.
|
||||||
|
func accountSlug(login string) string {
|
||||||
|
digest := sha256.Sum256([]byte(login))
|
||||||
|
return "u-" + hex.EncodeToString(digest[:10])
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"github.com/go-sql-driver/mysql"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"sea-vhost/internal/auth"
|
||||||
|
"sea-vhost/internal/config"
|
||||||
|
"sea-vhost/internal/isolation"
|
||||||
|
"sea-vhost/internal/panel"
|
||||||
|
"sea-vhost/internal/service"
|
||||||
|
"sea-vhost/internal/store"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestNamedAccountMySQL(t *testing.T) {
|
||||||
|
dsn := os.Getenv("SEA_TEST_MYSQL_DSN")
|
||||||
|
if dsn == "" {
|
||||||
|
t.Skip("disposable MySQL schema not supplied")
|
||||||
|
}
|
||||||
|
parsed, err := mysql.ParseDSN(dsn)
|
||||||
|
if err != nil || !strings.HasPrefix(parsed.DBName, "svh_cluster_test_") {
|
||||||
|
t.Fatal("refusing a non-test schema")
|
||||||
|
}
|
||||||
|
db, err := store.Open(dsn)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
ctx := context.Background()
|
||||||
|
must := func(err error) {
|
||||||
|
t.Helper()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
must(db.Migrate(ctx))
|
||||||
|
must(db.BootstrapAdmin(ctx, "identity-admin@example.invalid", "测试管理员", "identity-admin-password-123"))
|
||||||
|
admin, err := db.UserByLogin(ctx, "identity-admin@example.invalid")
|
||||||
|
must(err)
|
||||||
|
root := t.TempDir()
|
||||||
|
must(db.InitializeLocalNode(ctx, "hosts.example.invalid", root, "control.example.invalid"))
|
||||||
|
secret := "named-account-test-session-secret-at-least-thirty-two-characters"
|
||||||
|
projects := service.NewProjects(db, panel.NewMock(), isolation.Mock{Root: root}, "hosts.example.invalid", root, true, secret, "control.example.invalid")
|
||||||
|
server := New(config.Config{SessionSecret: secret, ManagementDomain: "control.example.invalid", CookieSecure: true, SessionTTL: time.Hour}, db, projects)
|
||||||
|
token, err := auth.NewSessionToken(secret)
|
||||||
|
must(err)
|
||||||
|
must(db.CreateSession(ctx, admin.ID, token, time.Now().Add(time.Hour)))
|
||||||
|
call := func(method, path string, body any, session string) *httptest.ResponseRecorder {
|
||||||
|
var buffer bytes.Buffer
|
||||||
|
must(json.NewEncoder(&buffer).Encode(body))
|
||||||
|
r := httptest.NewRequest(method, "https://control.example.invalid"+path, &buffer)
|
||||||
|
r.Header.Set("Origin", "https://control.example.invalid")
|
||||||
|
r.Header.Set("Content-Type", "application/json")
|
||||||
|
if session != "" {
|
||||||
|
r.AddCookie(&http.Cookie{Name: "sea_session", Value: session})
|
||||||
|
}
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
server.Handler().ServeHTTP(w, r)
|
||||||
|
return w
|
||||||
|
}
|
||||||
|
expect := func(w *httptest.ResponseRecorder, status int) {
|
||||||
|
t.Helper()
|
||||||
|
if w.Code != status {
|
||||||
|
t.Fatalf("HTTP %d want %d: %s", w.Code, status, w.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
input := map[string]any{"loginName": "customer01", "displayName": "测试用户", "email": "customer01@example.invalid", "password": "identity-user-password-123", "planId": 1}
|
||||||
|
created := call("POST", "/api/v1/admin/tenants", input, token)
|
||||||
|
expect(created, 201)
|
||||||
|
var value struct {
|
||||||
|
ID uint64 `json:"id"`
|
||||||
|
}
|
||||||
|
must(json.Unmarshal(created.Body.Bytes(), &value))
|
||||||
|
profile, err := db.AccountProfile(ctx, value.ID)
|
||||||
|
must(err)
|
||||||
|
if profile.LoginName != "customer01" || profile.Name != "测试用户" || profile.DisplayName != "测试用户" || profile.Slug != accountSlug("customer01") {
|
||||||
|
t.Fatalf("unexpected profile: %+v", profile)
|
||||||
|
}
|
||||||
|
for _, login := range []string{"customer01", "customer01@example.invalid"} {
|
||||||
|
expect(call("POST", "/api/v1/auth/login", map[string]string{"identifier": login, "password": "identity-user-password-123"}, ""), 200)
|
||||||
|
}
|
||||||
|
expect(call("POST", "/api/v1/auth/login", map[string]string{"identifier": "customer01", "password": "incorrect-password"}, ""), 401)
|
||||||
|
duplicate := map[string]any{"loginName": "customer01", "displayName": "重复用户", "email": "different@example.invalid", "password": "identity-user-password-123", "planId": 1}
|
||||||
|
expect(call("POST", "/api/v1/admin/tenants", duplicate, token), 422)
|
||||||
|
input["loginName"] = "another-user"
|
||||||
|
expect(call("POST", "/api/v1/admin/tenants", input, token), 422)
|
||||||
|
input["loginName"] = "bad@name"
|
||||||
|
expect(call("POST", "/api/v1/admin/tenants", input, token), 422)
|
||||||
|
list, err := db.ListTenants(ctx)
|
||||||
|
must(err)
|
||||||
|
if len(list) != 1 || list[0].LoginName != "customer01" {
|
||||||
|
t.Fatalf("unexpected user list: %+v", list)
|
||||||
|
}
|
||||||
|
profile.Email = "updated@example.invalid"
|
||||||
|
profile.Name = "修改名称"
|
||||||
|
profile.DisplayName = profile.Name
|
||||||
|
must(db.UpdateAccount(ctx, value.ID, profile))
|
||||||
|
updated, err := db.UserByLogin(ctx, "customer01")
|
||||||
|
must(err)
|
||||||
|
if updated.Email != profile.Email {
|
||||||
|
t.Fatal("email update failed")
|
||||||
|
}
|
||||||
|
_, err = db.UserByLogin(ctx, "customer01@example.invalid")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("old email still usable")
|
||||||
|
}
|
||||||
|
batch := batchRequest{Operation: "create_users", Rows: []batchRow{{LoginName: "batch-account", DisplayName: "批量用户", Email: "batch-account@example.invalid"}}}
|
||||||
|
preview, err := server.normalizeBatch(ctx, &batch)
|
||||||
|
must(err)
|
||||||
|
if len(preview) != 1 || !preview[0].Valid {
|
||||||
|
t.Fatalf("batch preview rejected: %+v", preview)
|
||||||
|
}
|
||||||
|
stable := batch.Rows[0].Slug
|
||||||
|
preview, err = server.normalizeBatch(ctx, &batch)
|
||||||
|
must(err)
|
||||||
|
if !preview[0].Valid || stable != batch.Rows[0].Slug {
|
||||||
|
t.Fatal("batch identity changed on retry")
|
||||||
|
}
|
||||||
|
result, err := server.performBatchRow(ctx, "create_users", batch.Rows[0])
|
||||||
|
must(err)
|
||||||
|
if result.Login != "batch-account" || result.Password == "" {
|
||||||
|
t.Fatal("batch credentials missing login account")
|
||||||
|
}
|
||||||
|
expect(call("POST", "/api/v1/auth/login", map[string]string{"identifier": result.Login, "password": result.Password}, ""), 200)
|
||||||
|
preview, err = server.normalizeBatch(ctx, &batch)
|
||||||
|
must(err)
|
||||||
|
if preview[0].Valid {
|
||||||
|
t.Fatal("duplicate batch account accepted")
|
||||||
|
}
|
||||||
|
t.Log("single creation, account/email login, password rejection, duplicate/invalid account rejection, stable batch identity, user listing and email update passed")
|
||||||
|
}
|
||||||
@@ -85,6 +85,7 @@ func (s *Server) adminTenants(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
var input struct {
|
var input struct {
|
||||||
Slug string `json:"slug"`
|
Slug string `json:"slug"`
|
||||||
|
LoginName string `json:"loginName"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
DisplayName string `json:"displayName"`
|
DisplayName string `json:"displayName"`
|
||||||
@@ -96,9 +97,18 @@ func (s *Server) adminTenants(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeError(w, http.StatusBadRequest, "请求格式错误")
|
writeError(w, http.StatusBadRequest, "请求格式错误")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
input.LoginName = strings.ToLower(strings.TrimSpace(input.LoginName))
|
||||||
|
if input.LoginName != "" {
|
||||||
|
if !tenantSlugPattern.MatchString(input.LoginName) {
|
||||||
|
writeError(w, 422, "登录账号应为 3–48 位小写字母、数字或连字符,首尾不能是连字符")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
input.Slug = accountSlug(input.LoginName)
|
||||||
|
input.Name = input.DisplayName
|
||||||
|
}
|
||||||
input.Slug = strings.ToLower(strings.TrimSpace(input.Slug))
|
input.Slug = strings.ToLower(strings.TrimSpace(input.Slug))
|
||||||
if !tenantSlugPattern.MatchString(input.Slug) || strings.TrimSpace(input.Name) == "" || len(input.Password) < 12 {
|
if !tenantSlugPattern.MatchString(input.Slug) || strings.TrimSpace(input.Name) == "" || (len(input.Password) < 12 || len(input.Password) > 72) {
|
||||||
writeError(w, http.StatusUnprocessableEntity, "用户标识、名称或密码不符合要求")
|
writeError(w, http.StatusUnprocessableEntity, "登录账号、显示名称或密码不符合要求")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
address, err := mail.ParseAddress(strings.TrimSpace(input.Email))
|
address, err := mail.ParseAddress(strings.TrimSpace(input.Email))
|
||||||
@@ -109,16 +119,16 @@ func (s *Server) adminTenants(w http.ResponseWriter, r *http.Request) {
|
|||||||
input.Name = strings.TrimSpace(input.Name)
|
input.Name = strings.TrimSpace(input.Name)
|
||||||
input.DisplayName = strings.TrimSpace(input.DisplayName)
|
input.DisplayName = strings.TrimSpace(input.DisplayName)
|
||||||
if len([]rune(input.Name)) > 120 || len([]rune(input.DisplayName)) < 2 || len([]rune(input.DisplayName)) > 80 || input.PlanID == 0 {
|
if len([]rune(input.Name)) > 120 || len([]rune(input.DisplayName)) < 2 || len([]rune(input.DisplayName)) > 80 || input.PlanID == 0 {
|
||||||
writeError(w, http.StatusUnprocessableEntity, "用户名称、管理员名称或套餐无效")
|
writeError(w, http.StatusUnprocessableEntity, "显示名称或套餐无效")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if _, err = s.store.Plan(r.Context(), input.PlanID); err != nil {
|
if _, err = s.store.Plan(r.Context(), input.PlanID); err != nil {
|
||||||
writeError(w, http.StatusUnprocessableEntity, "所选套餐不存在")
|
writeError(w, http.StatusUnprocessableEntity, "所选套餐不存在")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
id, err := s.store.CreateTenant(r.Context(), store.NewTenant{Slug: input.Slug, Name: input.Name, Email: strings.TrimSpace(input.Email), DisplayName: input.DisplayName, Password: input.Password, PlanID: input.PlanID, ExpiresAt: input.ExpiresAt})
|
id, err := s.store.CreateTenant(r.Context(), store.NewTenant{LoginName: input.LoginName, Slug: input.Slug, Name: input.Name, Email: strings.TrimSpace(input.Email), DisplayName: input.DisplayName, Password: input.Password, PlanID: input.PlanID, ExpiresAt: input.ExpiresAt})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeError(w, http.StatusUnprocessableEntity, "无法创建用户,请检查标识或邮箱是否重复")
|
writeError(w, http.StatusUnprocessableEntity, "无法创建用户,请检查登录账号或邮箱是否重复")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
user := currentUser(r)
|
user := currentUser(r)
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ import (
|
|||||||
type batchRow struct {
|
type batchRow struct {
|
||||||
Name string `json:"name,omitempty"`
|
Name string `json:"name,omitempty"`
|
||||||
Slug string `json:"slug,omitempty"`
|
Slug string `json:"slug,omitempty"`
|
||||||
|
LoginName string `json:"loginName,omitempty"`
|
||||||
Email string `json:"email,omitempty"`
|
Email string `json:"email,omitempty"`
|
||||||
DisplayName string `json:"displayName,omitempty"`
|
DisplayName string `json:"displayName,omitempty"`
|
||||||
Password string `json:"password,omitempty"`
|
Password string `json:"password,omitempty"`
|
||||||
@@ -128,6 +129,16 @@ func (s *Server) normalizeBatch(ctx context.Context, input *batchRequest) ([]bat
|
|||||||
var validation error
|
var validation error
|
||||||
switch input.Operation {
|
switch input.Operation {
|
||||||
case "create_users":
|
case "create_users":
|
||||||
|
row.LoginName = strings.ToLower(strings.TrimSpace(row.LoginName))
|
||||||
|
if row.LoginName != "" {
|
||||||
|
if !tenantSlugPattern.MatchString(row.LoginName) {
|
||||||
|
validation = errors.New("登录账号格式无效")
|
||||||
|
}
|
||||||
|
row.Slug = accountSlug(row.LoginName)
|
||||||
|
if row.Name == "" {
|
||||||
|
row.Name = row.DisplayName
|
||||||
|
}
|
||||||
|
}
|
||||||
row.Slug = strings.ToLower(strings.TrimSpace(row.Slug))
|
row.Slug = strings.ToLower(strings.TrimSpace(row.Slug))
|
||||||
row.Email = strings.ToLower(strings.TrimSpace(row.Email))
|
row.Email = strings.ToLower(strings.TrimSpace(row.Email))
|
||||||
row.Name = strings.TrimSpace(row.Name)
|
row.Name = strings.TrimSpace(row.Name)
|
||||||
@@ -150,17 +161,24 @@ func (s *Server) normalizeBatch(ctx context.Context, input *batchRequest) ([]bat
|
|||||||
}
|
}
|
||||||
key := "user:" + row.Email
|
key := "user:" + row.Email
|
||||||
slugKey := "slug:" + row.Slug
|
slugKey := "slug:" + row.Slug
|
||||||
if validation == nil && (seen[key] || seen[slugKey]) {
|
if validation == nil && (seen[key] || seen[slugKey] || (row.LoginName != "" && seen["login:"+row.LoginName])) {
|
||||||
validation = errors.New("同批邮箱或用户标识重复")
|
validation = errors.New("同批邮箱或用户标识重复")
|
||||||
}
|
}
|
||||||
seen[key] = true
|
seen[key] = true
|
||||||
seen[slugKey] = true
|
seen[slugKey] = true
|
||||||
|
if row.LoginName != "" {
|
||||||
|
seen["login:"+row.LoginName] = true
|
||||||
|
}
|
||||||
if validation == nil {
|
if validation == nil {
|
||||||
exists, e := s.store.AccountIdentityExists(ctx, row.Slug, row.Email)
|
exists, e := s.store.AccountIdentityExists(ctx, row.Slug, row.Email)
|
||||||
if e != nil {
|
if e != nil {
|
||||||
validation = errors.New("无法核对现有账号")
|
validation = errors.New("无法核对现有账号")
|
||||||
} else if exists {
|
} else if exists {
|
||||||
validation = errors.New("邮箱或用户标识已存在")
|
validation = errors.New("邮箱或用户标识已存在")
|
||||||
|
} else if row.LoginName != "" {
|
||||||
|
if exists, e = s.store.AccountIdentityExists(ctx, row.Slug, row.LoginName); e != nil || exists {
|
||||||
|
validation = errors.New("登录账号已存在或无法核对")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
preview.Label = row.Email
|
preview.Label = row.Email
|
||||||
@@ -610,9 +628,12 @@ func (s *Server) performBatchRow(ctx context.Context, operation string, row batc
|
|||||||
return result, err
|
return result, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
id, err := s.store.CreateTenant(ctx, store.NewTenant{Slug: row.Slug, Name: row.Name, Email: row.Email, DisplayName: row.DisplayName, Password: row.Password, PlanID: row.PlanID})
|
id, err := s.store.CreateTenant(ctx, store.NewTenant{LoginName: row.LoginName, Slug: row.Slug, Name: row.Name, Email: row.Email, DisplayName: row.DisplayName, Password: row.Password, PlanID: row.PlanID})
|
||||||
result.ResourceID = id
|
result.ResourceID = id
|
||||||
|
result.Login = row.LoginName
|
||||||
|
if result.Login == "" {
|
||||||
result.Login = row.Email
|
result.Login = row.Email
|
||||||
|
}
|
||||||
result.Password = row.Password
|
result.Password = row.Password
|
||||||
return result, err
|
return result, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -185,14 +185,18 @@ func (s *Server) downloadFile(w http.ResponseWriter, r *http.Request, root *node
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) uploadFile(w http.ResponseWriter, r *http.Request, tenantID uint64, root string) {
|
func (s *Server) uploadFile(w http.ResponseWriter, r *http.Request, tenantID uint64, root string) {
|
||||||
r.Body = http.MaxBytesReader(w, r.Body, s.cfg.UploadLimitBytes+1<<20)
|
r.Body = http.MaxBytesReader(w, r.Body, batchUploadLimit+1<<20)
|
||||||
if err := r.ParseMultipartForm(s.cfg.UploadLimitBytes); err != nil {
|
if err := r.ParseMultipartForm(1 << 20); err != nil {
|
||||||
writeError(w, http.StatusRequestEntityTooLarge, uploadLimitMessage(s.cfg.UploadLimitBytes))
|
writeError(w, http.StatusRequestEntityTooLarge, "上传请求过大:单批总量不超过 30 MB,单文件不超过 20 MB")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if r.MultipartForm != nil {
|
if r.MultipartForm != nil {
|
||||||
defer r.MultipartForm.RemoveAll()
|
defer r.MultipartForm.RemoveAll()
|
||||||
}
|
}
|
||||||
|
if r.FormValue("batch") == "true" || len(r.MultipartForm.File["file"]) > 1 {
|
||||||
|
s.uploadBatchFiles(w, r, tenantID, root)
|
||||||
|
return
|
||||||
|
}
|
||||||
source, header, err := r.FormFile("file")
|
source, header, err := r.FormFile("file")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeError(w, http.StatusBadRequest, "缺少上传文件")
|
writeError(w, http.StatusBadRequest, "缺少上传文件")
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ func (s *Server) adminAccount(w http.ResponseWriter, r *http.Request) {
|
|||||||
input.Email = strings.ToLower(strings.TrimSpace(input.Email))
|
input.Email = strings.ToLower(strings.TrimSpace(input.Email))
|
||||||
address, e := mail.ParseAddress(input.Email)
|
address, e := mail.ParseAddress(input.Email)
|
||||||
if input.Name == "" || len([]rune(input.Name)) > 120 || len([]rune(input.DisplayName)) < 2 || len([]rune(input.DisplayName)) > 80 || e != nil || address.Address != input.Email || len(input.Email) > 190 {
|
if input.Name == "" || len([]rune(input.Name)) > 120 || len([]rune(input.DisplayName)) < 2 || len([]rune(input.DisplayName)) > 80 || e != nil || address.Address != input.Email || len(input.Email) > 190 {
|
||||||
writeError(w, 422, "请检查用户名称、联系人姓名和登录邮箱")
|
writeError(w, 422, "请检查显示名称和登录邮箱")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
err = s.store.UpdateAccount(r.Context(), id, input)
|
err = s.store.UpdateAccount(r.Context(), id, input)
|
||||||
|
|||||||
@@ -1,14 +1,18 @@
|
|||||||
package httpapi
|
package httpapi
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"archive/tar"
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"compress/gzip"
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/go-sql-driver/mysql"
|
"github.com/go-sql-driver/mysql"
|
||||||
|
"mime/multipart"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"os"
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"sea-vhost/internal/auth"
|
"sea-vhost/internal/auth"
|
||||||
"sea-vhost/internal/config"
|
"sea-vhost/internal/config"
|
||||||
"sea-vhost/internal/isolation"
|
"sea-vhost/internal/isolation"
|
||||||
@@ -55,7 +59,7 @@ func TestResourceCRUDMySQL(t *testing.T) {
|
|||||||
secret := "crud-test-session-secret-at-least-thirty-two-characters"
|
secret := "crud-test-session-secret-at-least-thirty-two-characters"
|
||||||
native := &pendingStatePanel{Mock: panel.NewMock(), states: map[int64]bool{}}
|
native := &pendingStatePanel{Mock: panel.NewMock(), states: map[int64]bool{}}
|
||||||
projects := service.NewProjects(db, native, isolation.Mock{Root: root}, "hosts.example.invalid", root, true, secret, "control.example.invalid")
|
projects := service.NewProjects(db, native, isolation.Mock{Root: root}, "hosts.example.invalid", root, true, secret, "control.example.invalid")
|
||||||
server := New(config.Config{SessionSecret: secret, ManagementDomain: "control.example.invalid", CookieSecure: true, SessionTTL: time.Hour}, db, projects)
|
server := New(config.Config{SessionSecret: secret, ManagementDomain: "control.example.invalid", CookieSecure: true, SessionTTL: time.Hour, UploadLimitBytes: 20 << 20}, db, projects)
|
||||||
token, err := auth.NewSessionToken(secret)
|
token, err := auth.NewSessionToken(secret)
|
||||||
must(err)
|
must(err)
|
||||||
must(db.CreateSession(ctx, admin.ID, token, time.Now().Add(time.Hour)))
|
must(db.CreateSession(ctx, admin.ID, token, time.Now().Add(time.Hour)))
|
||||||
@@ -124,7 +128,7 @@ func TestResourceCRUDMySQL(t *testing.T) {
|
|||||||
p := &pythonInstallPanel{Mock: panel.NewMock()}
|
p := &pythonInstallPanel{Mock: panel.NewMock()}
|
||||||
isolator := pythonInstallIsolation{Mock: isolation.Mock{Root: root}, panel: p}
|
isolator := pythonInstallIsolation{Mock: isolation.Mock{Root: root}, panel: p}
|
||||||
svc := service.NewProjects(db, p, isolator, "hosts.example.invalid", root, true, secret, "control.example.invalid")
|
svc := service.NewProjects(db, p, isolator, "hosts.example.invalid", root, true, secret, "control.example.invalid")
|
||||||
api := New(config.Config{SessionSecret: secret, ManagementDomain: "control.example.invalid", CookieSecure: true, SessionTTL: time.Hour}, db, svc)
|
api := New(config.Config{SessionSecret: secret, ManagementDomain: "control.example.invalid", CookieSecure: true, SessionTTL: time.Hour, UploadLimitBytes: 20 << 20}, db, svc)
|
||||||
r := httptest.NewRequest("POST", "https://control.example.invalid/api/v1/admin/runtime-environments/Python/install", strings.NewReader(`{"version":"3.13.1"}`))
|
r := httptest.NewRequest("POST", "https://control.example.invalid/api/v1/admin/runtime-environments/Python/install", strings.NewReader(`{"version":"3.13.1"}`))
|
||||||
r.Header.Set("Origin", "https://control.example.invalid")
|
r.Header.Set("Origin", "https://control.example.invalid")
|
||||||
r.Header.Set("Content-Type", "application/json")
|
r.Header.Set("Content-Type", "application/json")
|
||||||
@@ -194,6 +198,129 @@ func TestResourceCRUDMySQL(t *testing.T) {
|
|||||||
created, err := projects.CreateManagedHost(scope.WithNode(ctx, 1), account, service.CreateProjectInput{NodeID: 1, PlanID: 1, Name: "crud-host", Runtime: "PHP", Version: "8.4", RunPath: "/public"})
|
created, err := projects.CreateManagedHost(scope.WithNode(ctx, 1), account, service.CreateProjectInput{NodeID: 1, PlanID: 1, Name: "crud-host", Runtime: "PHP", Version: "8.4", RunPath: "/public"})
|
||||||
must(err)
|
must(err)
|
||||||
id := created.Project.ID
|
id := created.Project.ID
|
||||||
|
|
||||||
|
t.Run("batch upload and archive formats", func(t *testing.T) {
|
||||||
|
must := func(err error) {
|
||||||
|
t.Helper()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
must(os.MkdirAll(created.Project.Path, 0770))
|
||||||
|
fresh, err := auth.NewSessionToken(secret)
|
||||||
|
must(err)
|
||||||
|
must(db.CreateSession(ctx, user.ID, fresh, time.Now().Add(time.Hour)))
|
||||||
|
upload := func(files map[string][]byte, overwrite bool, folder ...bool) *httptest.ResponseRecorder {
|
||||||
|
var body bytes.Buffer
|
||||||
|
writer := multipart.NewWriter(&body)
|
||||||
|
writer.WriteField("path", "")
|
||||||
|
writer.WriteField("batch", "true")
|
||||||
|
if overwrite {
|
||||||
|
writer.WriteField("overwrite", "true")
|
||||||
|
}
|
||||||
|
relative := []string{}
|
||||||
|
for name, data := range files {
|
||||||
|
relative = append(relative, name)
|
||||||
|
part, e := writer.CreateFormFile("file", name)
|
||||||
|
must(e)
|
||||||
|
_, e = part.Write(data)
|
||||||
|
must(e)
|
||||||
|
}
|
||||||
|
if len(folder) > 0 && folder[0] {
|
||||||
|
raw, e := json.Marshal(relative)
|
||||||
|
must(e)
|
||||||
|
must(writer.WriteField("relativePaths", string(raw)))
|
||||||
|
}
|
||||||
|
must(writer.Close())
|
||||||
|
request := httptest.NewRequest("POST", "https://control.example.invalid/api/v1/projects/"+strconv.FormatUint(id, 10)+"/files", &body)
|
||||||
|
request.Header.Set("Origin", "https://control.example.invalid")
|
||||||
|
request.Header.Set("Content-Type", writer.FormDataContentType())
|
||||||
|
request.AddCookie(&http.Cookie{Name: "sea_session", Value: fresh})
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
server.Handler().ServeHTTP(response, request)
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
expect(upload(map[string][]byte{"folder/a/index.php": []byte("alpha"), "folder/b/index.php": []byte("beta")}, false, true), 207)
|
||||||
|
for name, want := range map[string]string{"folder/a/index.php": "alpha", "folder/b/index.php": "beta"} {
|
||||||
|
raw, e := os.ReadFile(filepath.Join(created.Project.Path, name))
|
||||||
|
must(e)
|
||||||
|
if string(raw) != want {
|
||||||
|
t.Fatal("folder structure lost")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
expect(upload(map[string][]byte{"folder/../escape.txt": []byte("unsafe")}, false, true), 400)
|
||||||
|
if _, e := os.Stat(filepath.Join(created.Project.Path, "escape.txt")); !os.IsNotExist(e) {
|
||||||
|
t.Fatal("invalid folder path wrote a file")
|
||||||
|
}
|
||||||
|
valid := upload(map[string][]byte{"bulk-a.txt": []byte("alpha"), "bulk-b.txt": []byte("beta")}, false)
|
||||||
|
expect(valid, 207)
|
||||||
|
data, e := os.ReadFile(filepath.Join(created.Project.Path, "bulk-a.txt"))
|
||||||
|
must(e)
|
||||||
|
if string(data) != "alpha" {
|
||||||
|
t.Fatal("batch content mismatch")
|
||||||
|
}
|
||||||
|
conflict := upload(map[string][]byte{"bulk-a.txt": []byte("different"), "bulk-c.txt": []byte("gamma")}, false)
|
||||||
|
expect(conflict, 207)
|
||||||
|
var result struct {
|
||||||
|
Files []uploadItem `json:"files"`
|
||||||
|
}
|
||||||
|
must(json.Unmarshal(conflict.Body.Bytes(), &result))
|
||||||
|
success, duplicates := 0, 0
|
||||||
|
for _, item := range result.Files {
|
||||||
|
if item.Success {
|
||||||
|
success++
|
||||||
|
}
|
||||||
|
if item.Status == 409 {
|
||||||
|
duplicates++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if success != 1 || duplicates != 1 {
|
||||||
|
t.Fatalf("partial results: %+v", result.Files)
|
||||||
|
}
|
||||||
|
data, e = os.ReadFile(filepath.Join(created.Project.Path, "bulk-a.txt"))
|
||||||
|
must(e)
|
||||||
|
if string(data) != "alpha" {
|
||||||
|
t.Fatal("unconfirmed overwrite")
|
||||||
|
}
|
||||||
|
expect(upload(map[string][]byte{"bulk-a.txt": []byte("updated")}, true), 207)
|
||||||
|
expect(upload(map[string][]byte{"over-a.bin": make([]byte, 16<<20), "over-b.bin": make([]byte, 15<<20)}, false), 413)
|
||||||
|
if _, e = os.Stat(filepath.Join(created.Project.Path, "over-a.bin")); !os.IsNotExist(e) {
|
||||||
|
t.Fatal("oversized batch wrote a file")
|
||||||
|
}
|
||||||
|
expect(upload(map[string][]byte{"single-too-large.bin": make([]byte, (20<<20)+1)}, false), 413)
|
||||||
|
expect(upload(map[string][]byte{"exact-a.bin": make([]byte, 20<<20), "exact-b.bin": make([]byte, 10<<20)}, false), 207)
|
||||||
|
info, e := os.Stat(filepath.Join(created.Project.Path, "exact-a.bin"))
|
||||||
|
must(e)
|
||||||
|
if info.Size() != 20<<20 {
|
||||||
|
t.Fatal("boundary upload truncated")
|
||||||
|
}
|
||||||
|
for _, ext := range []string{".tar", ".tar.gz", ".tgz"} {
|
||||||
|
var raw bytes.Buffer
|
||||||
|
tw := tar.NewWriter(&raw)
|
||||||
|
must(tw.WriteHeader(&tar.Header{Name: "folder/index.txt", Mode: 0660, Size: 5}))
|
||||||
|
_, e = tw.Write([]byte("hello"))
|
||||||
|
must(e)
|
||||||
|
must(tw.Close())
|
||||||
|
content := raw.Bytes()
|
||||||
|
if ext != ".tar" {
|
||||||
|
var packed bytes.Buffer
|
||||||
|
gz := gzip.NewWriter(&packed)
|
||||||
|
_, e = gz.Write(content)
|
||||||
|
must(e)
|
||||||
|
must(gz.Close())
|
||||||
|
content = packed.Bytes()
|
||||||
|
}
|
||||||
|
name := "archive" + ext
|
||||||
|
expect(upload(map[string][]byte{name: content}, false), 207)
|
||||||
|
dest := "expanded" + strings.ReplaceAll(ext, ".", "-")
|
||||||
|
expect(call("POST", "/api/v1/projects/"+strconv.FormatUint(id, 10)+"/file-actions", map[string]string{"action": "extract", "path": name, "to": dest}, fresh), 204)
|
||||||
|
content, e = os.ReadFile(filepath.Join(created.Project.Path, dest, "folder/index.txt"))
|
||||||
|
must(e)
|
||||||
|
if string(content) != "hello" {
|
||||||
|
t.Fatal("archive content mismatch")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
pending, err := projects.CreateManagedHost(scope.WithNode(ctx, 1), 0, service.CreateProjectInput{NodeID: 1, PlanID: 1, Name: "pending-runtime", Runtime: "Node.js", Version: "v22.23.3", RunPath: "/"})
|
pending, err := projects.CreateManagedHost(scope.WithNode(ctx, 1), 0, service.CreateProjectInput{NodeID: 1, PlanID: 1, Name: "pending-runtime", Runtime: "Node.js", Version: "v22.23.3", RunPath: "/"})
|
||||||
must(err)
|
must(err)
|
||||||
if enabled, ok := native.states[pending.Project.PanelSiteID]; !ok || enabled {
|
if enabled, ok := native.states[pending.Project.PanelSiteID]; !ok || enabled {
|
||||||
@@ -314,7 +441,7 @@ func TestResourceCRUDMySQL(t *testing.T) {
|
|||||||
// Exercise the actual worker while the panel is busy, not just SQL flags.
|
// Exercise the actual worker while the panel is busy, not just SQL flags.
|
||||||
gatePanel := &busyPatchPanel{Mock: panel.NewMock(), entered: make(chan struct{})}
|
gatePanel := &busyPatchPanel{Mock: panel.NewMock(), entered: make(chan struct{})}
|
||||||
gateProjects := service.NewProjects(db, gatePanel, patchProbeIsolation{Mock: isolation.Mock{Root: root}}, "hosts.example.invalid", root, true, secret, "control.example.invalid")
|
gateProjects := service.NewProjects(db, gatePanel, patchProbeIsolation{Mock: isolation.Mock{Root: root}}, "hosts.example.invalid", root, true, secret, "control.example.invalid")
|
||||||
gateServer := New(config.Config{SessionSecret: secret, ManagementDomain: "control.example.invalid", CookieSecure: true, SessionTTL: time.Hour}, db, gateProjects)
|
gateServer := New(config.Config{SessionSecret: secret, ManagementDomain: "control.example.invalid", CookieSecure: true, SessionTTL: time.Hour, UploadLimitBytes: 20 << 20}, db, gateProjects)
|
||||||
busyJob, e := db.CreateRuntimeJob(scope.WithNode(ctx, 1), store.RuntimeJob{Action: "php_patch", Runtime: "PHP", FromVersion: "7.4.33", TargetVersion: "7.4.35"})
|
busyJob, e := db.CreateRuntimeJob(scope.WithNode(ctx, 1), store.RuntimeJob{Action: "php_patch", Runtime: "PHP", FromVersion: "7.4.33", TargetVersion: "7.4.35"})
|
||||||
must(e)
|
must(e)
|
||||||
workerCtx, stopWorker := context.WithCancel(ctx)
|
workerCtx, stopWorker := context.WithCancel(ctx)
|
||||||
|
|||||||
@@ -0,0 +1,183 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"mime/multipart"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
"path/filepath"
|
||||||
|
"sea-vhost/internal/nodefiles"
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
)
|
||||||
|
|
||||||
|
const batchUploadLimit int64 = 30 << 20
|
||||||
|
|
||||||
|
type uploadItem struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Size int64 `json:"size"`
|
||||||
|
Success bool `json:"success"`
|
||||||
|
Status int `json:"status"`
|
||||||
|
Error string `json:"error,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate the whole selection before any file is committed.
|
||||||
|
var errUploadPath = errors.New("文件夹相对路径无效、重复或包含系统保留目录")
|
||||||
|
|
||||||
|
func batchUploadNames(headers []*multipart.FileHeader, limit int64) ([]string, error) {
|
||||||
|
return batchUploadPaths(headers, limit, nil)
|
||||||
|
}
|
||||||
|
func batchUploadPaths(headers []*multipart.FileHeader, limit int64, relative []string) ([]string, error) {
|
||||||
|
if relative != nil && len(relative) != len(headers) {
|
||||||
|
return nil, errUploadPath
|
||||||
|
}
|
||||||
|
if len(headers) == 0 || len(headers) > 100 {
|
||||||
|
return nil, errors.New("每批请选择 1–100 个文件")
|
||||||
|
}
|
||||||
|
names := make([]string, len(headers))
|
||||||
|
seen := map[string]bool{}
|
||||||
|
var total int64
|
||||||
|
for i, h := range headers {
|
||||||
|
if h.Size < 0 || h.Size > limit {
|
||||||
|
return nil, errors.New(uploadLimitMessage(limit))
|
||||||
|
}
|
||||||
|
if h.Size > batchUploadLimit-total {
|
||||||
|
return nil, errors.New("单批上传总大小不能超过 30 MB")
|
||||||
|
}
|
||||||
|
total += h.Size
|
||||||
|
name := filepath.Base(strings.ReplaceAll(h.Filename, "\\", "/"))
|
||||||
|
if relative != nil {
|
||||||
|
name = relative[i]
|
||||||
|
if !utf8.ValidString(name) || len(name) > 1024 || strings.ContainsAny(name, "\\:\x00\r\n") || strings.HasPrefix(name, "/") || path.Clean(name) != name || nodefiles.IsProtectedPath(name) || path.Base(name) != filepath.Base(strings.ReplaceAll(h.Filename, "\\", "/")) {
|
||||||
|
return nil, errUploadPath
|
||||||
|
}
|
||||||
|
parts := strings.Split(name, "/")
|
||||||
|
if len(parts) > 32 {
|
||||||
|
return nil, errUploadPath
|
||||||
|
}
|
||||||
|
for _, part := range parts {
|
||||||
|
if part == "" || part == "." || part == ".." || len(part) > 255 {
|
||||||
|
return nil, errUploadPath
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if name == "." || name == ".." || name == "" || seen[name] {
|
||||||
|
return nil, errors.New("文件名无效或本批存在同名文件")
|
||||||
|
}
|
||||||
|
names[i] = name
|
||||||
|
seen[name] = true
|
||||||
|
}
|
||||||
|
for _, name := range names {
|
||||||
|
for parent := path.Dir(name); parent != "."; parent = path.Dir(parent) {
|
||||||
|
if seen[parent] {
|
||||||
|
return nil, errUploadPath
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return names, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) uploadBatchFiles(w http.ResponseWriter, r *http.Request, tenantID uint64, root string) {
|
||||||
|
headers := r.MultipartForm.File["file"]
|
||||||
|
limit := min(s.cfg.UploadLimitBytes, int64(20<<20))
|
||||||
|
var relative []string
|
||||||
|
if raw := r.FormValue("relativePaths"); raw != "" {
|
||||||
|
if len(raw) > 128<<10 || json.Unmarshal([]byte(raw), &relative) != nil || relative == nil {
|
||||||
|
writeError(w, 400, "文件夹路径列表无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
names, err := batchUploadPaths(headers, limit, relative)
|
||||||
|
if err != nil {
|
||||||
|
status := 413
|
||||||
|
if errors.Is(err, errUploadPath) {
|
||||||
|
status = 400
|
||||||
|
}
|
||||||
|
writeError(w, status, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
dir, err := safeProjectName(root, r.FormValue("path"))
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, 400, "路径无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
projectRoot, err := s.projects.OpenFiles(r.Context(), root)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, 404, "项目目录不存在")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer projectRoot.Close()
|
||||||
|
targets := make([]string, len(names))
|
||||||
|
overwrite := r.FormValue("overwrite") == "true"
|
||||||
|
var additional uint64
|
||||||
|
for i, name := range names {
|
||||||
|
targets[i], err = safeProjectName(root, path.Join(dir, name))
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, 400, "路径无效或包含系统保留文件")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
growth := uint64(headers[i].Size)
|
||||||
|
if old, e := projectRoot.Lstat(targets[i]); e == nil && old.Mode().IsRegular() {
|
||||||
|
if !overwrite {
|
||||||
|
growth = 0
|
||||||
|
} else if uint64(old.Size()) >= growth {
|
||||||
|
growth = 0
|
||||||
|
} else {
|
||||||
|
growth -= uint64(old.Size())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
additional += growth
|
||||||
|
}
|
||||||
|
if err = s.projects.CheckStorageWrite(r.Context(), tenantID, additional); err != nil {
|
||||||
|
writeFileQuotaError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
results := make([]uploadItem, 0, len(names))
|
||||||
|
for i, name := range names {
|
||||||
|
result := uploadItem{Name: name, Status: 422, Error: "上传失败,请刷新目录核对"}
|
||||||
|
flag := os.O_WRONLY | os.O_CREATE | os.O_EXCL
|
||||||
|
if overwrite {
|
||||||
|
flag = os.O_WRONLY | os.O_CREATE | os.O_TRUNC
|
||||||
|
}
|
||||||
|
source, e := headers[i].Open()
|
||||||
|
if e == nil {
|
||||||
|
if parent := path.Dir(filepath.ToSlash(targets[i])); parent != "." {
|
||||||
|
if mkdirErr := projectRoot.MkdirAll(parent, 0770); mkdirErr != nil {
|
||||||
|
source.Close()
|
||||||
|
s.logFile(r, tenantID, "file_operation", "文件夹上传创建子目录失败:"+name)
|
||||||
|
results = append(results, result)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
destination, openErr := projectRoot.OpenFile(targets[i], flag, 0660)
|
||||||
|
if openErr == nil {
|
||||||
|
written, copyErr := io.Copy(destination, io.LimitReader(source, limit+1))
|
||||||
|
if copyErr == nil && written == headers[i].Size && written <= limit {
|
||||||
|
e = destination.Close()
|
||||||
|
} else {
|
||||||
|
e = errors.New("upload truncated")
|
||||||
|
}
|
||||||
|
destination.Abort()
|
||||||
|
if e == nil {
|
||||||
|
result = uploadItem{Name: name, Size: written, Success: true, Status: 201}
|
||||||
|
s.logFile(r, tenantID, "upload", "批量上传文件:"+filepath.ToSlash(targets[i]))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
e = openErr
|
||||||
|
}
|
||||||
|
source.Close()
|
||||||
|
}
|
||||||
|
if !result.Success {
|
||||||
|
if errors.Is(e, os.ErrExist) {
|
||||||
|
result.Status = 409
|
||||||
|
result.Error = "同名文件已存在,未覆盖"
|
||||||
|
}
|
||||||
|
s.logFile(r, tenantID, "file_operation", "批量上传失败:"+name)
|
||||||
|
}
|
||||||
|
results = append(results, result)
|
||||||
|
}
|
||||||
|
writeJSON(w, 207, map[string]any{"files": results})
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"mime/multipart"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestBatchUploadLimitsBeforeWriting(t *testing.T) {
|
||||||
|
const mb = 1 << 20
|
||||||
|
for _, test := range []struct {
|
||||||
|
name string
|
||||||
|
files []*multipart.FileHeader
|
||||||
|
ok bool
|
||||||
|
}{
|
||||||
|
{"exact total", []*multipart.FileHeader{{Filename: "a", Size: 20 * mb}, {Filename: "b", Size: 10 * mb}}, true},
|
||||||
|
{"over total", []*multipart.FileHeader{{Filename: "a", Size: 20 * mb}, {Filename: "b", Size: 10*mb + 1}}, false},
|
||||||
|
{"over single", []*multipart.FileHeader{{Filename: "a", Size: 20*mb + 1}}, false},
|
||||||
|
{"duplicate normalized name", []*multipart.FileHeader{{Filename: "a"}, {Filename: "folder/a"}}, false},
|
||||||
|
{"empty", nil, false},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
_, err := batchUploadNames(test.files, 20*mb)
|
||||||
|
if (err == nil) != test.ok {
|
||||||
|
t.Fatalf("unexpected error %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
files := make([]*multipart.FileHeader, 101)
|
||||||
|
for i := range files {
|
||||||
|
files[i] = &multipart.FileHeader{Filename: "x"}
|
||||||
|
}
|
||||||
|
if _, err := batchUploadNames(files, 20*mb); err == nil {
|
||||||
|
t.Fatal("unbounded file count accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFolderUploadPathsAreRootedAndUnambiguous(t *testing.T) {
|
||||||
|
headers := []*multipart.FileHeader{{Filename: "index.php", Size: 5}, {Filename: "index.php", Size: 4}}
|
||||||
|
paths := []string{"site/a/index.php", "site/b/index.php"}
|
||||||
|
names, err := batchUploadPaths(headers, 20<<20, paths)
|
||||||
|
if err != nil || names[0] != paths[0] || names[1] != paths[1] {
|
||||||
|
t.Fatalf("folder paths lost: %v %v", names, err)
|
||||||
|
}
|
||||||
|
for _, name := range []string{"../index.php", "/index.php", "site/../index.php", "site//index.php", "site/./index.php", `site\index.php`, "C:/index.php", "site/.sea-runtime/index.php", "site/.sea-trash/index.php", "site/.user.ini/index.php", "site/other.php"} {
|
||||||
|
if _, err = batchUploadPaths(headers[:1], 20<<20, []string{name}); err == nil {
|
||||||
|
t.Errorf("unsafe path accepted: %q", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err = batchUploadPaths(headers, 20<<20, paths[:1]); err == nil {
|
||||||
|
t.Fatal("path count mismatch accepted")
|
||||||
|
}
|
||||||
|
conflicting := []*multipart.FileHeader{{Filename: "site"}, {Filename: "index.php"}}
|
||||||
|
if _, err = batchUploadPaths(conflicting, 20<<20, []string{"site", "site/index.php"}); err == nil {
|
||||||
|
t.Fatal("file/directory collision accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
package nodefiles
|
package nodefiles
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"archive/tar"
|
||||||
"archive/zip"
|
"archive/zip"
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"compress/gzip"
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
@@ -187,6 +189,13 @@ func advanced(root *os.Root, q Request, out *Response) error {
|
|||||||
if e != nil || len(data) > MaxFileBytes {
|
if e != nil || len(data) > MaxFileBytes {
|
||||||
return fs.ErrPermission
|
return fs.ErrPermission
|
||||||
}
|
}
|
||||||
|
lower := strings.ToLower(q.Path)
|
||||||
|
if strings.HasSuffix(lower, ".tar") || strings.HasSuffix(lower, ".tar.gz") || strings.HasSuffix(lower, ".tgz") {
|
||||||
|
if e = extractTar(root, stage, data, strings.HasSuffix(lower, ".gz") || strings.HasSuffix(lower, ".tgz"), budget); e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
z, e := zip.NewReader(bytes.NewReader(data), int64(len(data)))
|
z, e := zip.NewReader(bytes.NewReader(data), int64(len(data)))
|
||||||
if e != nil {
|
if e != nil {
|
||||||
return e
|
return e
|
||||||
@@ -421,3 +430,94 @@ func listTrash(root *os.Root, out *Response) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func newZipBudget() *uint64 { v := uint64(maxExpanded); return &v }
|
func newZipBudget() *uint64 { v := uint64(maxExpanded); return &v }
|
||||||
|
|
||||||
|
// TAR members are written into a private staging directory and published only on success.
|
||||||
|
func extractTar(root *os.Root, stage string, data []byte, compressed bool, budget uint64) error {
|
||||||
|
var input io.Reader = bytes.NewReader(data)
|
||||||
|
if compressed {
|
||||||
|
gz, err := gzip.NewReader(input)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer gz.Close()
|
||||||
|
input = gz
|
||||||
|
}
|
||||||
|
// Bound metadata, padding and decompression work as well as extracted file data.
|
||||||
|
limited := &io.LimitedReader{R: input, N: int64(maxExpanded) + (8 << 20)}
|
||||||
|
reader := tar.NewReader(limited)
|
||||||
|
if err := root.Mkdir(stage, 0770); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for count := 0; ; count++ {
|
||||||
|
header, err := reader.Next()
|
||||||
|
if err == io.EOF {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if count >= 10000 {
|
||||||
|
return fs.ErrPermission
|
||||||
|
}
|
||||||
|
name := strings.TrimSuffix(header.Name, "/")
|
||||||
|
for strings.HasPrefix(name, "./") {
|
||||||
|
name = strings.TrimPrefix(name, "./")
|
||||||
|
}
|
||||||
|
if (name == "." || name == "") && header.Typeflag == tar.TypeDir {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if name == "" || path.Clean(name) != name || !validName(name) || strings.HasPrefix(name, "/") || protected(name) || seen[name] {
|
||||||
|
return fs.ErrPermission
|
||||||
|
}
|
||||||
|
if header.Typeflag != tar.TypeDir && header.Typeflag != tar.TypeReg && header.Typeflag != tar.TypeRegA {
|
||||||
|
return fs.ErrPermission
|
||||||
|
}
|
||||||
|
for key := range header.PAXRecords {
|
||||||
|
if strings.HasPrefix(key, "GNU.sparse") {
|
||||||
|
return fs.ErrPermission
|
||||||
|
}
|
||||||
|
}
|
||||||
|
seen[name] = true
|
||||||
|
target := path.Join(stage, name)
|
||||||
|
if err = check(root, target); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if header.Typeflag == tar.TypeDir {
|
||||||
|
if err = root.MkdirAll(target, 0770); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if header.Size < 0 || uint64(header.Size) > budget {
|
||||||
|
return fs.ErrPermission
|
||||||
|
}
|
||||||
|
if err = root.MkdirAll(path.Dir(target), 0770); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
output, err := root.OpenFile(target, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0660)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
n, copyErr := io.Copy(output, io.LimitReader(reader, header.Size+1))
|
||||||
|
closeErr := output.Close()
|
||||||
|
if copyErr != nil {
|
||||||
|
return copyErr
|
||||||
|
}
|
||||||
|
if closeErr != nil {
|
||||||
|
return closeErr
|
||||||
|
}
|
||||||
|
if n != header.Size {
|
||||||
|
return io.ErrUnexpectedEOF
|
||||||
|
}
|
||||||
|
budget -= uint64(n)
|
||||||
|
}
|
||||||
|
_, err := io.Copy(io.Discard, limited)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if limited.N <= 0 {
|
||||||
|
return fs.ErrPermission
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
package nodefiles
|
package nodefiles
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"archive/tar"
|
||||||
"archive/zip"
|
"archive/zip"
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"compress/gzip"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -75,3 +77,65 @@ func TestExtractRejectsZipSlipSymlinksAndBombs(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestTarArchivesExtractSafely(t *testing.T) {
|
||||||
|
for _, extension := range []string{".tar", ".tar.gz", ".tgz"} {
|
||||||
|
t.Run(extension, func(t *testing.T) {
|
||||||
|
for _, name := range []string{"./folder/hello.txt", "../escape", "/escape", "link", "hard", ".user.ini"} {
|
||||||
|
dir := t.TempDir()
|
||||||
|
var raw bytes.Buffer
|
||||||
|
writer := tar.NewWriter(&raw)
|
||||||
|
kind := byte(tar.TypeReg)
|
||||||
|
size := int64(5)
|
||||||
|
if name == "link" {
|
||||||
|
kind = tar.TypeSymlink
|
||||||
|
size = 0
|
||||||
|
}
|
||||||
|
if name == "hard" {
|
||||||
|
kind = tar.TypeLink
|
||||||
|
size = 0
|
||||||
|
}
|
||||||
|
if err := writer.WriteHeader(&tar.Header{Name: name, Typeflag: kind, Linkname: "/etc/passwd", Mode: 0777, Size: size}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if size > 0 {
|
||||||
|
writer.Write([]byte("hello"))
|
||||||
|
}
|
||||||
|
writer.Close()
|
||||||
|
data := raw.Bytes()
|
||||||
|
if extension != ".tar" {
|
||||||
|
var compressed bytes.Buffer
|
||||||
|
gz := gzip.NewWriter(&compressed)
|
||||||
|
gz.Write(data)
|
||||||
|
gz.Close()
|
||||||
|
data = compressed.Bytes()
|
||||||
|
}
|
||||||
|
os.WriteFile(filepath.Join(dir, "archive"+extension), data, 0600)
|
||||||
|
out := Execute(dir, Request{Operation: "extract", Path: "archive" + extension, To: "expanded", Budget: 100})
|
||||||
|
if name == "./folder/hello.txt" {
|
||||||
|
if out.Error != "" {
|
||||||
|
t.Fatal(out.Error)
|
||||||
|
}
|
||||||
|
content, err := os.ReadFile(filepath.Join(dir, "expanded/folder/hello.txt"))
|
||||||
|
if err != nil || string(content) != "hello" {
|
||||||
|
t.Fatal("content mismatch")
|
||||||
|
}
|
||||||
|
// The archive mode must not restore executable or special permission bits.
|
||||||
|
info, _ := os.Stat(filepath.Join(dir, "expanded/folder/hello.txt"))
|
||||||
|
if info.Mode().Perm()&0111 != 0 {
|
||||||
|
t.Fatal("archive permissions trusted")
|
||||||
|
}
|
||||||
|
small := Execute(dir, Request{Operation: "extract", Path: "archive" + extension, To: "too-small", Budget: 4})
|
||||||
|
if small.Error == "" {
|
||||||
|
t.Fatal("quota ignored")
|
||||||
|
}
|
||||||
|
if _, err = os.Stat(filepath.Join(dir, "too-small")); !os.IsNotExist(err) {
|
||||||
|
t.Fatal("failed extraction was published")
|
||||||
|
}
|
||||||
|
} else if out.Error == "" {
|
||||||
|
t.Fatalf("unsafe member accepted: %s", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -237,6 +237,7 @@ type Activity struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type TenantSummary struct {
|
type TenantSummary struct {
|
||||||
|
LoginName string `json:"loginName"`
|
||||||
ID uint64 `json:"id"`
|
ID uint64 `json:"id"`
|
||||||
Slug string `json:"slug"`
|
Slug string `json:"slug"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
@@ -299,7 +300,7 @@ type AdminActivity struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type NewTenant struct {
|
type NewTenant struct {
|
||||||
Slug, Name, Email, DisplayName, Password string
|
Slug, Name, Email, DisplayName, Password, LoginName string
|
||||||
PlanID uint64
|
PlanID uint64
|
||||||
ExpiresAt *time.Time
|
ExpiresAt *time.Time
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import (
|
|||||||
// references cannot accidentally grant access to a different customer.
|
// references cannot accidentally grant access to a different customer.
|
||||||
type AccountProfile struct {
|
type AccountProfile struct {
|
||||||
ID uint64 `json:"id"`
|
ID uint64 `json:"id"`
|
||||||
|
LoginName string `json:"loginName"`
|
||||||
Slug string `json:"slug"`
|
Slug string `json:"slug"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
@@ -21,7 +22,7 @@ type AccountProfile struct {
|
|||||||
|
|
||||||
func (s *Store) AccountProfile(ctx context.Context, id uint64) (AccountProfile, error) {
|
func (s *Store) AccountProfile(ctx context.Context, id uint64) (AccountProfile, error) {
|
||||||
var p AccountProfile
|
var p AccountProfile
|
||||||
err := s.db.QueryRowContext(ctx, `SELECT t.id,t.slug,t.name,u.email,u.display_name,(SELECT COUNT(*) FROM projects WHERE owner_tenant_id=t.id) FROM tenants t JOIN users u ON u.tenant_id=t.id AND u.role='tenant' WHERE t.id=? AND t.resource_namespace=FALSE AND t.deleted_at IS NULL ORDER BY u.id LIMIT 1`, id).Scan(&p.ID, &p.Slug, &p.Name, &p.Email, &p.DisplayName, &p.ProjectCount)
|
err := s.db.QueryRowContext(ctx, `SELECT t.id,t.slug,t.name,u.email,u.display_name,COALESCE(u.login_name,u.email),(SELECT COUNT(*) FROM projects WHERE owner_tenant_id=t.id) FROM tenants t JOIN users u ON u.tenant_id=t.id AND u.role='tenant' WHERE t.id=? AND t.resource_namespace=FALSE AND t.deleted_at IS NULL ORDER BY u.id LIMIT 1`, id).Scan(&p.ID, &p.Slug, &p.Name, &p.Email, &p.DisplayName, &p.LoginName, &p.ProjectCount)
|
||||||
if errors.Is(err, sql.ErrNoRows) {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
err = ErrNotFound
|
err = ErrNotFound
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1971,7 +1971,7 @@ func (s *Store) CreatePlan(ctx context.Context, input NewPlan) (uint64, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) ListTenants(ctx context.Context) ([]TenantSummary, error) {
|
func (s *Store) ListTenants(ctx context.Context) ([]TenantSummary, error) {
|
||||||
rows, err := s.db.QueryContext(ctx, `SELECT t.id,t.slug,t.name,IF(t.status='active' AND COUNT(DISTINCT IF(u.role='tenant' AND u.status='active',u.id,NULL))>0,'active','suspended'),t.lifecycle_state,p.name,COUNT(DISTINCT IF(u.role='tenant',u.id,NULL)),COUNT(DISTINCT pr.id),t.expires_at,t.grace_until,t.purge_after,t.backup_purge_after,t.created_at FROM tenants t JOIN plans p ON p.id=t.plan_id LEFT JOIN users u ON u.tenant_id=t.id LEFT JOIN projects pr ON pr.owner_tenant_id=t.id WHERE t.resource_namespace=FALSE AND t.deleted_at IS NULL GROUP BY t.id ORDER BY t.id DESC`)
|
rows, err := s.db.QueryContext(ctx, `SELECT t.id,t.slug,t.name,IF(t.status='active' AND COUNT(DISTINCT IF(u.role='tenant' AND u.status='active',u.id,NULL))>0,'active','suspended'),t.lifecycle_state,p.name,COUNT(DISTINCT IF(u.role='tenant',u.id,NULL)),COUNT(DISTINCT pr.id),t.expires_at,t.grace_until,t.purge_after,t.backup_purge_after,t.created_at,COALESCE(MAX(IF(u.role='tenant',u.login_name,NULL)),'') FROM tenants t JOIN plans p ON p.id=t.plan_id LEFT JOIN users u ON u.tenant_id=t.id LEFT JOIN projects pr ON pr.owner_tenant_id=t.id WHERE t.resource_namespace=FALSE AND t.deleted_at IS NULL GROUP BY t.id ORDER BY t.id DESC`)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -1980,7 +1980,7 @@ func (s *Store) ListTenants(ctx context.Context) ([]TenantSummary, error) {
|
|||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var item TenantSummary
|
var item TenantSummary
|
||||||
var expires, grace, purge, backupPurge sql.NullTime
|
var expires, grace, purge, backupPurge sql.NullTime
|
||||||
if err := rows.Scan(&item.ID, &item.Slug, &item.Name, &item.Status, &item.LifecycleState, &item.PlanName, &item.UserCount, &item.ProjectCount, &expires, &grace, &purge, &backupPurge, &item.CreatedAt); err != nil {
|
if err := rows.Scan(&item.ID, &item.Slug, &item.Name, &item.Status, &item.LifecycleState, &item.PlanName, &item.UserCount, &item.ProjectCount, &expires, &grace, &purge, &backupPurge, &item.CreatedAt, &item.LoginName); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if expires.Valid {
|
if expires.Valid {
|
||||||
@@ -2283,6 +2283,10 @@ func (s *Store) AdminActivities(ctx context.Context, limit int) ([]AdminActivity
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) CreateTenant(ctx context.Context, input NewTenant) (uint64, error) {
|
func (s *Store) CreateTenant(ctx context.Context, input NewTenant) (uint64, error) {
|
||||||
|
loginName := strings.ToLower(strings.TrimSpace(input.LoginName))
|
||||||
|
if loginName == "" {
|
||||||
|
loginName = strings.ToLower(input.Email)
|
||||||
|
}
|
||||||
hash, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
|
hash, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
@@ -2305,7 +2309,7 @@ func (s *Store) CreateTenant(ctx context.Context, input NewTenant) (uint64, erro
|
|||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if _, err = tx.ExecContext(ctx, "INSERT INTO users(tenant_id,login_name,email,display_name,password_hash,role) VALUES (?,?,?,?,?,'tenant')", tenantID, strings.ToLower(input.Email), strings.ToLower(input.Email), input.DisplayName, string(hash)); err != nil {
|
if _, err = tx.ExecContext(ctx, "INSERT INTO users(tenant_id,login_name,email,display_name,password_hash,role) VALUES (?,?,?,?,?,'tenant')", tenantID, loginName, strings.ToLower(input.Email), input.DisplayName, string(hash)); err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
if err = tx.Commit(); err != nil {
|
if err = tx.Commit(); err != nil {
|
||||||
|
|||||||
@@ -135,7 +135,7 @@ server {
|
|||||||
|
|
||||||
root /opt/sea-vhost/web;
|
root /opt/sea-vhost/web;
|
||||||
index index.html;
|
index index.html;
|
||||||
client_max_body_size 21m;
|
client_max_body_size 31m;
|
||||||
|
|
||||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||||
add_header X-Content-Type-Options "nosniff" always;
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ server {
|
|||||||
|
|
||||||
root /opt/sea-vhost/web;
|
root /opt/sea-vhost/web;
|
||||||
index index.html;
|
index index.html;
|
||||||
client_max_body_size 21m;
|
client_max_body_size 31m;
|
||||||
|
|
||||||
add_header X-Content-Type-Options "nosniff" always;
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
add_header X-Frame-Options "DENY" always;
|
add_header X-Frame-Options "DENY" always;
|
||||||
|
|||||||
+1
-1
@@ -143,8 +143,8 @@ fi
|
|||||||
[[ -z "${security_backup}" ]] || rm -f -- "${security_backup}"
|
[[ -z "${security_backup}" ]] || rm -f -- "${security_backup}"
|
||||||
install -d -o root -g root -m 0755 /usr/local/libexec
|
install -d -o root -g root -m 0755 /usr/local/libexec
|
||||||
install -o root -g root -m 0755 "${build_dir}/bin/sea-vhost-run" /usr/local/libexec/sea-vhost-run
|
install -o root -g root -m 0755 "${build_dir}/bin/sea-vhost-run" /usr/local/libexec/sea-vhost-run
|
||||||
install -o root -g root -m 0750 "${build_dir}/bin/sea-vhost-scheduler" /opt/sea-vhost/bin/sea-vhost-scheduler
|
|
||||||
install -d -o root -g sea-vhost-control -m 0750 /opt/sea-vhost/bin
|
install -d -o root -g sea-vhost-control -m 0750 /opt/sea-vhost/bin
|
||||||
|
install -o root -g root -m 0750 "${build_dir}/bin/sea-vhost-scheduler" /opt/sea-vhost/bin/sea-vhost-scheduler
|
||||||
install -d -o root -g root -m 0755 /opt/sea-vhost/web
|
install -d -o root -g root -m 0755 /opt/sea-vhost/web
|
||||||
install -d -o sea-vhost -g sea-vhost-control -m 0700 /var/lib/sea-vhost
|
install -d -o sea-vhost -g sea-vhost-control -m 0700 /var/lib/sea-vhost
|
||||||
install -d -o sea-vhost-panel -g sea-vhost-panel-control -m 0700 /var/lib/sea-vhost-panel
|
install -d -o sea-vhost-panel -g sea-vhost-panel-control -m 0700 /var/lib/sea-vhost-panel
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ server {
|
|||||||
|
|
||||||
root /opt/sea-vhost/web;
|
root /opt/sea-vhost/web;
|
||||||
index index.html;
|
index index.html;
|
||||||
client_max_body_size 21m;
|
client_max_body_size 31m;
|
||||||
|
|
||||||
proxy_hide_header Content-Security-Policy;
|
proxy_hide_header Content-Security-Policy;
|
||||||
|
|
||||||
|
|||||||
+3
-2
@@ -1,12 +1,13 @@
|
|||||||
# Sea vHost 文档索引
|
# Sea vHost 文档索引
|
||||||
|
|
||||||
更新日期:2026-10-30。当前部署与功能状态从项目状态整理开始阅读;最新 SSO 策略与部署见 SSO 与界面验收。带日期的验收报告保留当时的环境和测试结果,不代表当前服务器重新检查通过。
|
更新日期:2026-11-15。最新变更见 [v0.1.0-rc.5](release-v0.1.0-rc.5.md)。当前部署与功能状态从项目状态整理开始阅读;最新 SSO 策略与部署见 SSO 与界面验收。带日期的验收报告保留当时的环境和测试结果,不代表当前服务器重新检查通过。
|
||||||
|
|
||||||
## 当前说明
|
## 当前说明
|
||||||
|
|
||||||
| 文档 | 用途 |
|
| 文档 | 用途 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| [36 实机测试交付](handover-2026-10-30.md) | 当前入口、交付文件、账号与历史夹具边界、实际测试操作顺序 |
|
| [v0.1.0-rc.5 变更与交付](release-v0.1.0-rc.5.md) | 账户、套餐、文件夹上传及解压更新与验证边界 |
|
||||||
|
| [36 实机测试交付](handover-2026-10-30.md) | 10-30 重装与交付历史、文件用途及旧体验资源边界 |
|
||||||
| [项目状态整理](project-status-2026-10-29.md) | 功能、正常操作流程、验证范围和剩余工作 |
|
| [项目状态整理](project-status-2026-10-29.md) | 功能、正常操作流程、验证范围和剩余工作 |
|
||||||
| [业务功能与按钮说明](business-actions.md) | 各页面操作用途、DNS 凭据/解析/证书的区别及业务表达缺口 |
|
| [业务功能与按钮说明](business-actions.md) | 各页面操作用途、DNS 凭据/解析/证书的区别及业务表达缺口 |
|
||||||
| [日常操作与管理端 API](hosting-operations.md) | 用户与主机开通、JSON 批量管理、网站、文件、计划任务、财务站对接 |
|
| [日常操作与管理端 API](hosting-operations.md) | 用户与主机开通、JSON 批量管理、网站、文件、计划任务、财务站对接 |
|
||||||
|
|||||||
@@ -1,5 +1,13 @@
|
|||||||
# 36 单机实机测试交付
|
# 36 单机实机测试交付
|
||||||
|
|
||||||
|
本文保留 2026-10-30 的交付与重装记录。后续已由用户初始化并继续开展业务测试;“空白安装向导”和下方旧体验账号均不能作为当前状态依据。最新变更及交付范围见 [v0.1.0-rc.5](release-v0.1.0-rc.5.md)。
|
||||||
|
|
||||||
|
## 2026-10-30 状态:已清理重装,等待用户初始化
|
||||||
|
|
||||||
|
2026-10-30 经用户确认,36 已清除 Sea vHost 的旧账号、三台主机及其站点、FTP、主机数据库和旧控制库,重新安装后停留在空白 Web 安装向导。控制台地址仍为 `https://host.ser888.cn/`,新应用数据库为 `sea_vhost`,尚无数据表或管理员;安装令牌及数据库密码由单独的私密交付信息提供,不进入源码包。重装前已验证完整备份,宝塔其他资源、控制台证书和已安装运行环境保留。
|
||||||
|
|
||||||
|
rc.4 修复全新安装时调度器程序先于目标目录安装的问题。已通过 19 项安装向导测试及 36 的实际清理安装、空库连接和待安装状态检查。下方账号与主机说明为重装前的历史验收记录,相关体验资源已清理,不代表当前可登录资源。
|
||||||
|
|
||||||
交付日期:2026-10-30。当前目标为 36 机器上的单机生产测试环境,不使用早期 202 机器的端口映射或临时域名。本次整理不重装、不清空业务数据库、不修改现有账号密码。
|
交付日期:2026-10-30。当前目标为 36 机器上的单机生产测试环境,不使用早期 202 机器的端口映射或临时域名。本次整理不重装、不清空业务数据库、不修改现有账号密码。
|
||||||
|
|
||||||
## Python 安装补充验收(rc.2)
|
## Python 安装补充验收(rc.2)
|
||||||
@@ -8,6 +16,12 @@
|
|||||||
|
|
||||||
待安装列表仅采用宝塔 Python 项目的 `sdk.streamline` 常用版本。Sea vHost 使用带官方 SHA-256 校验的源码构建,未修改宝塔 `btpyvm.py`;宝塔原生 XML 目录解析异常仍属于面板自身问题。本次实装仅覆盖 3.14.9,不代表全部 Python 分支已逐一安装。
|
待安装列表仅采用宝塔 Python 项目的 `sdk.streamline` 常用版本。Sea vHost 使用带官方 SHA-256 校验的源码构建,未修改宝塔 `btpyvm.py`;宝塔原生 XML 目录解析异常仍属于面板自身问题。本次实装仅覆盖 3.14.9,不代表全部 Python 分支已逐一安装。
|
||||||
|
|
||||||
|
## 用户导航与小屏补充验收(rc.3)
|
||||||
|
|
||||||
|
用户侧边栏保留“总览、域名、DNS API、操作日志”,用户计划任务入口移至总览工具区。总览每行仅保留“进入主机”,也可双击行进入;主机管理显示当前主机并可返回用户总览。主机内文件、数据库、FTP、图表和日志限定到当前主机,独立主机账号仍只管理自身。
|
||||||
|
|
||||||
|
前端 95 项回归通过。内置浏览器在 1280×900 与 390×844 检查列表及主机操作区;小屏操作列保留可达入口,表格操作按钮保持横向排列,主机详情按钮采用双列。36 线上双主机账号已验证进入指定主机、数据库与文件范围;本轮前端更新未修改账号、主机归属或后端程序。
|
||||||
|
|
||||||
## 直接开始使用
|
## 直接开始使用
|
||||||
|
|
||||||
- 控制台:<https://host.ser888.cn/>。
|
- 控制台:<https://host.ser888.cn/>。
|
||||||
|
|||||||
@@ -26,7 +26,7 @@
|
|||||||
"version": 1,
|
"version": 1,
|
||||||
"operation": "create_users",
|
"operation": "create_users",
|
||||||
"rows": [
|
"rows": [
|
||||||
{"slug":"customer01","name":"客户一","email":"customer01@vhost.ser888.cn","password":""}
|
{"loginName":"customer01","displayName":"客户一","email":"customer01@vhost.ser888.cn","password":""}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -39,7 +39,7 @@
|
|||||||
|
|
||||||
## 网站、文件、环境与日志
|
## 网站、文件、环境与日志
|
||||||
|
|
||||||
用户登录后,在“虚拟主机”的“选择虚拟主机”下拉框选择,选项为“主机名 · 显示名称”,再点击“网站管理”;选择同时决定本页的资源配置、运行目录、凭据和启停操作目标。“文件管理”和“资源图表”有各自的主机选择器,“操作日志”可按主机筛选;域名、FTP、数据库页面汇总该用户名下资源,并标明归属。独立主机账号只可管理自身,只有一台主机时不显示主机切换框。每个网站独立选择运行目录,主站默认 `/`,也可改为 `/public` 或其他主机内目录。目录必须位于主机根目录内。
|
用户侧边栏仅保留“总览、域名、DNS API、操作日志”。在总览主机列表点击“进入主机”,或双击主机行,进入该主机管理;页头显示目前主机,可“返回用户总览”后选择另一台。主机管理中提供资源配置、网站、文件、数据库、FTP、资源图表及该主机日志,均限定当前主机。账号权限不因进入主机而改变;独立主机账号直接进入自身管理,不提供返回用户总览。用户级计划任务入口保留在用户总览工具区,独立主机账号不可用。用户视图的域名与日志可查看名下主机汇总。每个网站独立选择运行目录,主站默认 `/`,也可改为 `/public` 或其他主机内目录。目录必须位于主机根目录内。
|
||||||
|
|
||||||
在网站的“运行环境”中可切换同语言的已安装版本;管理员对该主机开启“允许切换运行环境”后,才可跨语言切换。系统先停站并保留文件、数据库,完成后由使用者检查兼容性并手动启动或部署。运行环境的安装与组件补丁更新在管理员“环境配置”页提交,不同任务可排队、同节点串行,重复任务拒绝。
|
在网站的“运行环境”中可切换同语言的已安装版本;管理员对该主机开启“允许切换运行环境”后,才可跨语言切换。系统先停站并保留文件、数据库,完成后由使用者检查兼容性并手动启动或部署。运行环境的安装与组件补丁更新在管理员“环境配置”页提交,不同任务可排队、同节点串行,重复任务拒绝。
|
||||||
|
|
||||||
@@ -55,7 +55,7 @@ PHP 网站创建后即可上传程序。Node.js、Python、Go、Java 网站先
|
|||||||
|
|
||||||
日志可切换访问、Nginx 错误、程序运行和 PHP-FPM 类型,支持关键词筛选及下载 JSON。操作日志与网站访问日志分别展示。
|
日志可切换访问、Nginx 错误、程序运行和 PHP-FPM 类型,支持关键词筛选及下载 JSON。操作日志与网站访问日志分别展示。
|
||||||
|
|
||||||
“文件管理”支持目录、新建文本、重命名、移动、复制、ZIP 压缩/解压、删除至回收站与恢复。Web 上传默认上限 20 MiB;大文件使用 FTP。ZIP 解压限制总量和条目数,拒绝软链接、越界路径和系统保留目录。
|
“文件管理”支持目录、新建文本、重命名、移动、复制、ZIP 压缩,以及 ZIP/TAR/TAR.GZ/TGZ 解压、删除至回收站与恢复。Web 支持多文件批量上传与整文件夹上传,所选文件夹及子目录按相对路径保留(浏览器不包含空目录),不同目录中的同名文件可同时上传。每批最多 100 个文件、合计不超过 30 MiB,单文件不超过 20 MiB;大文件使用 FTP。批次先验证总量与目标路径,逐文件返回结果。同名文件保留,确认后仅重传冲突文件。解压发布到不存在的目标目录,总量不超过 256 MiB 和套餐剩余空间、条目不超过 10000;拒绝软链接、硬链接、特殊文件、越界路径和系统保留目录,失败时不发布部分解压结果。
|
||||||
|
|
||||||
“FTP”仅提供基本启停、查看凭据和随机重置密码。FTP 地址使用主机域名,TLS 策略依证书配置确定。
|
“FTP”仅提供基本启停、查看凭据和随机重置密码。FTP 地址使用主机域名,TLS 策略依证书配置确定。
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# Sea vHost v0.1.0-rc.5
|
||||||
|
|
||||||
|
整理日期:2026-11-15。本版汇总 rc.4 后的账户、套餐与文件管理改动,继续作为 Debian Linux amd64 单机实机测试版交付。
|
||||||
|
|
||||||
|
## 本版变化
|
||||||
|
|
||||||
|
- 用户创建统一填写登录账号、显示名称、邮箱和密码,内部标识自动生成;支持登录账号或邮箱登录,保留旧账号的登录方式。JSON 批量导入、预览和凭据导出同步支持登录账号。
|
||||||
|
- 创建主机和网站时预填可修改的随机名称。输入名称仍是显示名称,实际主机登录名、目录及服务账号由后端独立分配;本版没有合并这两套命名。
|
||||||
|
- 套餐的存储空间、数据库空间使用 MB,月流量使用 GB;按 1024 进制换算并取整后以 Bytes 提交,修复小数容量导致接口拒绝的问题。复制套餐保留实际容量。
|
||||||
|
- 普通生产构建始终连接后端并要求认证;演示站必须通过 `npm run build:demo` 显式构建,演示内容不进入正式控制台。
|
||||||
|
- 文件管理支持多文件及整文件夹上传:单批最多 100 个文件、合计 30 MiB,单文件仍为 20 MiB。文件夹保留相对目录,浏览器未提供的空目录不上传;不同目录下的同名文件可同时上传。
|
||||||
|
- 上传前检查大小、路径及套餐空间,逐文件返回结果;已有文件不自动覆盖,用户确认后仅重试冲突文件。管理站点 Nginx 请求体上限调整为 31 MiB,容纳 multipart 开销。
|
||||||
|
- 增加 TAR、TAR.GZ、TGZ 解压并保留 ZIP。解压至不存在的目标目录,限制条目数、解压总量和剩余空间,拒绝路径穿越、保留目录、软硬链接及特殊文件;失败不发布部分解压结果。
|
||||||
|
|
||||||
|
## 验证与边界
|
||||||
|
|
||||||
|
本次提交的本地验证:`go test ./...` 通过,前端 22 个测试文件共 105 项通过,安装向导 19 项通过,正式前端及六个 Linux amd64 服务程序构建通过(Go 1.27.3)。依赖临时 MySQL 的集成测试在未提供专用测试 DSN 时跳过,不能据此声称本轮重新完成了实机联调。
|
||||||
|
|
||||||
|
本版相关改动此前已部署到 36 环境:隔离 MySQL 测试库中的账户登录和资源 CRUD、批量/嵌套目录上传、容量边界和 TAR 解压已通过;已核对正式站及独立演示站静态资源、演示站 API 禁止访问和文件管理界面。浏览器文件夹选择器的完整上传交互未单独执行,以前端交互测试及真实后端 multipart 集成测试覆盖。
|
||||||
|
|
||||||
|
此前按要求开通的课堂账户和主机是服务器业务数据,不包含在仓库、源码包或部署包内。密钥、密码、会话、服务器配置及私有测试材料同样不随版本交付。历史实测记录代表当时结果,不作为本次重新安装或全功能复测的结论。
|
||||||
|
|
||||||
|
## 安装与升级
|
||||||
|
|
||||||
|
部署包为 `sea-vhost-linux-amd64.tar.gz`,配套 SHA-256 文件和 `runtime-manifest.json`;源码以仓库标签及单独的源码归档交付。部署包包含正式控制台,不包含演示站构建产物。
|
||||||
|
|
||||||
|
全新安装解压后运行 `bash deploy/install.sh`,通过交互安装及 Web 向导填写本机配置。已有环境按 [部署说明](deployment.md) 备份数据库、配置与程序后更新,保留现有业务数据;不要用清理重装代替更新。本版未新增数据库迁移。
|
||||||
|
|
||||||
|
日常文件操作和限制见 [操作说明](hosting-operations.md),账户与回收规则见 [资源管理](resource-management.md)。
|
||||||
@@ -12,7 +12,7 @@
|
|||||||
|
|
||||||
## 用户
|
## 用户
|
||||||
|
|
||||||
可以创建、查询、编辑用户名称、联系人和登录邮箱,以及启停、删除用户。修改登录邮箱会撤销已有用户会话。删除前必须解绑或转移所有主机,包括回收中的主机,并处理未完成的归属任务。删除后停止计划任务、撤销会话并保留内部审计关联;历史用户标识和邮箱保持占用,避免旧导入或外部引用被另一用户接管。批量启用及旧到期接口不能重新激活已删除用户。
|
创建用户填写登录账号、显示名称、邮箱和密码,内部用户标识自动生成。新用户可用登录账号或邮箱登录,原有用户仍保留原登录方式。可以查询、编辑显示名称和登录邮箱,以及启停、删除用户;登录账号在资料编辑页只读。修改登录邮箱会撤销已有用户会话。删除前必须解绑或转移所有主机,包括回收中的主机,并处理未完成的归属任务。删除后停止计划任务、撤销会话并保留内部审计关联;历史用户标识和邮箱保持占用,避免旧导入或外部引用被另一用户接管。批量启用及旧到期接口不能重新激活已删除用户。
|
||||||
|
|
||||||
## 节点
|
## 节点
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite --host 0.0.0.0",
|
"dev": "vite --host 0.0.0.0",
|
||||||
"build": "tsc -b && vite build",
|
"build": "tsc -b && vite build",
|
||||||
|
"build:demo": "tsc -b && vite build --mode demo --outDir dist-demo",
|
||||||
"preview": "vite preview --host 0.0.0.0",
|
"preview": "vite preview --host 0.0.0.0",
|
||||||
"test": "vitest run"
|
"test": "vitest run"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import '@testing-library/jest-dom/vitest';
|
import '@testing-library/jest-dom/vitest';
|
||||||
import {cleanup,fireEvent,render,screen,waitFor} from '@testing-library/react';
|
import {cleanup,fireEvent,render,screen,waitFor} from '@testing-library/react';
|
||||||
import {afterEach,expect,it,vi} from 'vitest';
|
import {afterEach,expect,it,vi} from 'vitest';
|
||||||
import {PlanForm,Plans,NetworkForm,AdminConsole} from './components/AdminConsole';
|
import {PlanForm,Plans,NetworkForm,AdminConsole,UserForm} from './components/AdminConsole';
|
||||||
|
import {HostProvisioning} from './components/HostProvisioning';
|
||||||
import {AdminDomains,DomainPolicyForm} from './components/AdminDomains';
|
import {AdminDomains,DomainPolicyForm} from './components/AdminDomains';
|
||||||
import {AdminLogs} from './components/AdminLogs';
|
import {AdminLogs} from './components/AdminLogs';
|
||||||
import {ResourceCenter} from './components/ResourceCenter';
|
import {ResourceCenter} from './components/ResourceCenter';
|
||||||
@@ -10,6 +11,55 @@ import {demoPlan} from './data';
|
|||||||
import {initialProjects} from './data';
|
import {initialProjects} from './data';
|
||||||
|
|
||||||
afterEach(()=>{cleanup();vi.restoreAllMocks()});
|
afterEach(()=>{cleanup();vi.restoreAllMocks()});
|
||||||
|
it('prefills an editable random host name independently for each opening',async()=>{
|
||||||
|
vi.spyOn(api,'nodes').mockResolvedValue({nodes:[]});
|
||||||
|
const first=render(<HostProvisioning users={[]} plans={[demoPlan]} onClose={vi.fn()} onComplete={vi.fn()}/>);
|
||||||
|
const name=(screen.getByLabelText('主机名称') as HTMLInputElement).value;
|
||||||
|
expect(name).toMatch(/^sv[0-9a-f]{10}$/);
|
||||||
|
fireEvent.change(screen.getByLabelText('主机名称'),{target:{value:'my-site'}});
|
||||||
|
expect(screen.getByLabelText('主机名称')).toHaveValue('my-site');first.unmount();
|
||||||
|
render(<HostProvisioning users={[]} plans={[demoPlan]} onClose={vi.fn()} onComplete={vi.fn()}/>);
|
||||||
|
expect(screen.getByLabelText('主机名称')).not.toHaveValue(name);
|
||||||
|
});
|
||||||
|
it('creates users with four visible fields and sends a real login account',async()=>{
|
||||||
|
const create=vi.fn().mockRejectedValue(new Error('账号已存在'));
|
||||||
|
render(<UserForm plans={[demoPlan]} onClose={vi.fn()} onCreate={create}/>);
|
||||||
|
expect(screen.queryByLabelText('用户标识')).not.toBeInTheDocument();
|
||||||
|
expect(screen.queryByLabelText('联系人姓名')).not.toBeInTheDocument();
|
||||||
|
for(const [label,value] of [['登录账号','customer01'],['显示名称','测试用户'],['登录邮箱','customer01@example.invalid'],['初始密码','test-password-123']])fireEvent.change(screen.getByLabelText(label),{target:{value}});
|
||||||
|
fireEvent.click(screen.getByRole('button',{name:'创建用户'}));
|
||||||
|
await waitFor(()=>expect(create).toHaveBeenCalledWith({loginName:'customer01',name:'测试用户',displayName:'测试用户',email:'customer01@example.invalid',password:'test-password-123',planId:demoPlan.id}));
|
||||||
|
expect(await screen.findByRole('alert')).toHaveTextContent('账号已存在');
|
||||||
|
});
|
||||||
|
it('creates small plans using MB capacities and GB traffic with integer byte payloads',async()=>{
|
||||||
|
const create=vi.fn().mockResolvedValue(undefined);
|
||||||
|
render(<PlanForm onCreate={create} onClose={vi.fn()}/>);
|
||||||
|
fireEvent.change(screen.getByLabelText('套餐名称'),{target:{value:'ClassHost'}});
|
||||||
|
fireEvent.change(screen.getByLabelText('存储空间(MB)'),{target:{value:'800'}});
|
||||||
|
fireEvent.change(screen.getByLabelText('数据库空间(MB)'),{target:{value:'100'}});
|
||||||
|
fireEvent.change(screen.getByLabelText('月流量(GB)'),{target:{value:'30'}});
|
||||||
|
fireEvent.click(screen.getByRole('button',{name:'创建套餐'}));
|
||||||
|
await waitFor(()=>expect(create).toHaveBeenCalledWith(expect.objectContaining({storageBytes:838860800,databaseBytes:104857600,bandwidthBytes:32212254720})));
|
||||||
|
fireEvent.change(screen.getByLabelText('存储空间(MB)'),{target:{value:'800.1'}});
|
||||||
|
fireEvent.change(screen.getByLabelText('数据库空间(MB)'),{target:{value:'100.1'}});
|
||||||
|
fireEvent.change(screen.getByLabelText('月流量(GB)'),{target:{value:'0.1'}});
|
||||||
|
fireEvent.click(screen.getByRole('button',{name:'创建套餐'}));
|
||||||
|
await waitFor(()=>expect(create).toHaveBeenCalledTimes(2));
|
||||||
|
expect(create.mock.calls[1][0]).toEqual(expect.objectContaining({storageBytes:838965658,databaseBytes:104962458,bandwidthBytes:107374182}));
|
||||||
|
});
|
||||||
|
it('keeps copied capacities exact and displays plan capacities in their configured units',async()=>{
|
||||||
|
const save=vi.fn().mockResolvedValue(undefined);
|
||||||
|
const plan={...demoPlan,storageBytes:838965658,databaseBytes:104962458,bandwidthBytes:107374182};
|
||||||
|
render(<Plans plans={[plan]} create={vi.fn()} save={save}/>);
|
||||||
|
expect(screen.getByText('800.1 MB')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('100.1 MB')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('0.1 GB')).toBeInTheDocument();
|
||||||
|
fireEvent.click(screen.getByRole('button',{name:'复制套餐 '+plan.name}));
|
||||||
|
expect(screen.getByLabelText('存储空间(MB)')).toHaveValue(plan.storageBytes/1024**2);
|
||||||
|
expect(screen.getByLabelText('数据库空间(MB)')).toHaveValue(plan.databaseBytes/1024**2);
|
||||||
|
fireEvent.click(screen.getByRole('button',{name:'保存为新套餐'}));
|
||||||
|
await waitFor(()=>expect(save).toHaveBeenCalledWith(expect.objectContaining({storageBytes:plan.storageBytes,databaseBytes:plan.databaseBytes,bandwidthBytes:plan.bandwidthBytes})));
|
||||||
|
});
|
||||||
it('retains a rejected plan form and explains the failure',async()=>{
|
it('retains a rejected plan form and explains the failure',async()=>{
|
||||||
const create=vi.fn().mockRejectedValue(new Error('套餐名称重复'));
|
const create=vi.fn().mockRejectedValue(new Error('套餐名称重复'));
|
||||||
render(<PlanForm onCreate={create} onClose={vi.fn()}/>);fireEvent.change(screen.getByLabelText('套餐名称'),{target:{value:'重复套餐'}});fireEvent.click(screen.getByRole('button',{name:'创建套餐'}));
|
render(<PlanForm onCreate={create} onClose={vi.fn()}/>);fireEvent.change(screen.getByLabelText('套餐名称'),{target:{value:'重复套餐'}});fireEvent.click(screen.getByRole('button',{name:'创建套餐'}));
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ it('requires preview before queueing users and only exposes credentials through
|
|||||||
const submit=vi.spyOn(api,'createBatch').mockResolvedValue({batch:job});vi.spyOn(api,'batch').mockResolvedValueOnce({batch:{...job,state:'running',secretsExpireAt:undefined}}).mockResolvedValue({batch:job});
|
const submit=vi.spyOn(api,'createBatch').mockResolvedValue({batch:job});vi.spyOn(api,'batch').mockResolvedValueOnce({batch:{...job,state:'running',secretsExpireAt:undefined}}).mockResolvedValue({batch:job});
|
||||||
render(<BatchComposer operation="create_users" users={[]} projects={[]} plans={[demoPlan]} onClose={vi.fn()} onChanged={vi.fn().mockResolvedValue(undefined)}/>);
|
render(<BatchComposer operation="create_users" users={[]} projects={[]} plans={[demoPlan]} onClose={vi.fn()} onChanged={vi.fn().mockResolvedValue(undefined)}/>);
|
||||||
expect(screen.getByRole('button',{name:/提交.*项任务/})).toBeDisabled();fireEvent.change(screen.getByLabelText('创建数量'),{target:{value:'1'}});fireEvent.change(screen.getByLabelText('名称前缀'),{target:{value:'ui-batch'}});
|
expect(screen.getByRole('button',{name:/提交.*项任务/})).toBeDisabled();fireEvent.change(screen.getByLabelText('创建数量'),{target:{value:'1'}});fireEvent.change(screen.getByLabelText('名称前缀'),{target:{value:'ui-batch'}});
|
||||||
fireEvent.click(screen.getByRole('button',{name:'验证并预览'}));await waitFor(()=>expect(preview).toHaveBeenCalled());expect(preview.mock.calls[0][1][0]).toMatchObject({slug:'ui-batch-0001',email:'ui-batch-0001@vhost.ser888.cn'});expect(preview.mock.calls[0][1][0].password).toBeUndefined();
|
fireEvent.click(screen.getByRole('button',{name:'验证并预览'}));await waitFor(()=>expect(preview).toHaveBeenCalled());expect(preview.mock.calls[0][1][0]).toMatchObject({loginName:'ui-batch-0001',email:'ui-batch-0001@vhost.ser888.cn'});expect(preview.mock.calls[0][1][0].password).toBeUndefined();
|
||||||
fireEvent.click(await screen.findByRole('button',{name:'提交 1 项任务'}));await waitFor(()=>expect(submit).toHaveBeenCalled());expect(submit.mock.calls[0][2]).toMatch(/^[0-9a-f]{32}$/);
|
fireEvent.click(await screen.findByRole('button',{name:'提交 1 项任务'}));await waitFor(()=>expect(submit).toHaveBeenCalled());expect(submit.mock.calls[0][2]).toMatch(/^[0-9a-f]{32}$/);
|
||||||
expect(await screen.findByText('正在保存任务结果…')).toBeInTheDocument();expect(screen.queryByText('批次凭据已过期')).not.toBeInTheDocument();
|
expect(await screen.findByText('正在保存任务结果…')).toBeInTheDocument();expect(screen.queryByText('批次凭据已过期')).not.toBeInTheDocument();
|
||||||
expect(await screen.findByRole('link',{name:'下载结果与凭据 JSON'},{timeout:5000})).toHaveAttribute('href','/api/v1/admin/batches/31/download');
|
expect(await screen.findByRole('link',{name:'下载结果与凭据 JSON'},{timeout:5000})).toHaveAttribute('href','/api/v1/admin/batches/31/download');
|
||||||
|
|||||||
+26
-12
@@ -1,5 +1,5 @@
|
|||||||
import '@testing-library/jest-dom/vitest';
|
import '@testing-library/jest-dom/vitest';
|
||||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
|
||||||
import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest';
|
import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest';
|
||||||
import {DNSCredentials} from './components/DNSCredentials';
|
import {DNSCredentials} from './components/DNSCredentials';
|
||||||
import { App } from './App';
|
import { App } from './App';
|
||||||
@@ -20,6 +20,8 @@ afterEach(() => {
|
|||||||
vi.restoreAllMocks();
|
vi.restoreAllMocks();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
function enterFirstHost(){fireEvent.click(screen.getByRole('button',{name:'进入主机 '+initialProjects[0].hostName}))}
|
||||||
|
|
||||||
describe('Sea vHost', () => {
|
describe('Sea vHost', () => {
|
||||||
it('opens the create project workflow', () => {
|
it('opens the create project workflow', () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
@@ -34,7 +36,8 @@ describe('Sea vHost', () => {
|
|||||||
|
|
||||||
it('lets a tenant configure a host-relative run directory', () => {
|
it('lets a tenant configure a host-relative run directory', () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
fireEvent.click(screen.getAllByRole('button', { name: '主站目录' })[0]);
|
enterFirstHost();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: '设置运行目录' }));
|
||||||
expect(screen.getByRole('dialog', { name: '设置运行目录' })).toBeInTheDocument();
|
expect(screen.getByRole('dialog', { name: '设置运行目录' })).toBeInTheDocument();
|
||||||
const input = screen.getByDisplayValue('/public');
|
const input = screen.getByDisplayValue('/public');
|
||||||
fireEvent.change(input, { target: { value: '/../etc' } });
|
fireEvent.change(input, { target: { value: '/../etc' } });
|
||||||
@@ -43,14 +46,16 @@ describe('Sea vHost', () => {
|
|||||||
|
|
||||||
it('opens file management for a selected project', async () => {
|
it('opens file management for a selected project', async () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
fireEvent.click(screen.getAllByRole('button', { name: '文件' })[0]);
|
enterFirstHost();
|
||||||
|
fireEvent.click(within(screen.getByLabelText('主导航')).getByRole('button',{name:'文件管理'}));
|
||||||
expect(screen.getByRole('heading', { name: '文件管理' })).toBeInTheDocument();
|
expect(screen.getByRole('heading', { name: '文件管理' })).toBeInTheDocument();
|
||||||
expect(screen.getByRole('combobox', { name: '选择虚拟主机' })).toHaveValue('1');
|
expect(screen.getByRole('combobox', { name: '选择虚拟主机' })).toHaveValue('1');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('adds another website with an independent runtime and directory', () => {
|
it('adds another website with an independent runtime and directory', () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]);
|
enterFirstHost();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: '网站管理' }));
|
||||||
expect(screen.getByRole('dialog', { name: '主机网站' })).toBeInTheDocument();
|
expect(screen.getByRole('dialog', { name: '主机网站' })).toBeInTheDocument();
|
||||||
fireEvent.click(screen.getByRole('button', { name: '新增网站' }));
|
fireEvent.click(screen.getByRole('button', { name: '新增网站' }));
|
||||||
fireEvent.change(screen.getByLabelText('网站名称'), { target: { value: 'docs-site' } });
|
fireEvent.change(screen.getByLabelText('网站名称'), { target: { value: 'docs-site' } });
|
||||||
@@ -64,7 +69,8 @@ describe('Sea vHost', () => {
|
|||||||
|
|
||||||
it('checks and deploys an uploaded language project before reporting it running', async () => {
|
it('checks and deploys an uploaded language project before reporting it running', async () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]);
|
enterFirstHost();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: '网站管理' }));
|
||||||
fireEvent.click(screen.getByRole('button', { name: '新增网站' }));
|
fireEvent.click(screen.getByRole('button', { name: '新增网站' }));
|
||||||
fireEvent.change(screen.getByLabelText('运行环境'), { target: { value: 'Node.js' } });
|
fireEvent.change(screen.getByLabelText('运行环境'), { target: { value: 'Node.js' } });
|
||||||
fireEvent.click(screen.getByRole('button', { name: '创建网站' }));
|
fireEvent.click(screen.getByRole('button', { name: '创建网站' }));
|
||||||
@@ -80,7 +86,8 @@ describe('Sea vHost', () => {
|
|||||||
|
|
||||||
it('installs a manual certificate without retaining the private key form', async () => {
|
it('installs a manual certificate without retaining the private key form', async () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]);
|
enterFirstHost();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: '网站管理' }));
|
||||||
fireEvent.click(screen.getByRole('button', { name: '安装证书 main-site' }));
|
fireEvent.click(screen.getByRole('button', { name: '安装证书 main-site' }));
|
||||||
expect(screen.getByText(/私钥仅用于本次请求/)).toBeInTheDocument();
|
expect(screen.getByText(/私钥仅用于本次请求/)).toBeInTheDocument();
|
||||||
fireEvent.change(screen.getByLabelText('证书链(PEM)'), { target: { value: '-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----' } });
|
fireEvent.change(screen.getByLabelText('证书链(PEM)'), { target: { value: '-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----' } });
|
||||||
@@ -91,7 +98,8 @@ describe('Sea vHost', () => {
|
|||||||
|
|
||||||
it('lets a tenant retry automatic certificate issuance for a managed site', async () => {
|
it('lets a tenant retry automatic certificate issuance for a managed site', async () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]);
|
enterFirstHost();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: '网站管理' }));
|
||||||
expect(screen.getByText(/SSL 已启用/)).toBeInTheDocument();
|
expect(screen.getByText(/SSL 已启用/)).toBeInTheDocument();
|
||||||
fireEvent.click(screen.getByRole('button', { name: 'HTTP-01 申请证书 main-site' }));
|
fireEvent.click(screen.getByRole('button', { name: 'HTTP-01 申请证书 main-site' }));
|
||||||
await waitFor(() => expect(screen.getByText(/SSL 已启用/)).toBeInTheDocument());
|
await waitFor(() => expect(screen.getByText(/SSL 已启用/)).toBeInTheDocument());
|
||||||
@@ -99,7 +107,8 @@ describe('Sea vHost', () => {
|
|||||||
|
|
||||||
it('lets a tenant explicitly disable SSL and automatic renewal', async () => {
|
it('lets a tenant explicitly disable SSL and automatic renewal', async () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]);
|
enterFirstHost();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: '网站管理' }));
|
||||||
fireEvent.click(screen.getByRole('button', { name: '关闭 SSL main-site' }));
|
fireEvent.click(screen.getByRole('button', { name: '关闭 SSL main-site' }));
|
||||||
fireEvent.click(screen.getByRole('button', { name: '确认继续' }));
|
fireEvent.click(screen.getByRole('button', { name: '确认继续' }));
|
||||||
await waitFor(() => expect(screen.getByText(/SSL 未启用/)).toBeInTheDocument());
|
await waitFor(() => expect(screen.getByText(/SSL 未启用/)).toBeInTheDocument());
|
||||||
@@ -108,7 +117,8 @@ describe('Sea vHost', () => {
|
|||||||
|
|
||||||
it('shows reusable FTP and database credentials', () => {
|
it('shows reusable FTP and database credentials', () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
fireEvent.click(screen.getAllByRole('button', { name: '凭据' })[0]);
|
enterFirstHost();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: '访问凭据' }));
|
||||||
expect(screen.getByRole('dialog', { name: '虚拟主机凭据' })).not.toHaveTextContent('FTP 与数据库密码已加密保存');
|
expect(screen.getByRole('dialog', { name: '虚拟主机凭据' })).not.toHaveTextContent('FTP 与数据库密码已加密保存');
|
||||||
expect(screen.getByText('demo-ftp-password')).toBeInTheDocument();
|
expect(screen.getByText('demo-ftp-password')).toBeInTheDocument();
|
||||||
expect(screen.getByText('demo-database-password')).toBeInTheDocument();
|
expect(screen.getByText('demo-database-password')).toBeInTheDocument();
|
||||||
@@ -116,7 +126,8 @@ describe('Sea vHost', () => {
|
|||||||
|
|
||||||
it('resets the independent host login password', async () => {
|
it('resets the independent host login password', async () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
fireEvent.click(screen.getAllByRole('button', { name: '凭据' })[0]);
|
enterFirstHost();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: '访问凭据' }));
|
||||||
fireEvent.click(screen.getByRole('button', { name: '重置主机密码' }));
|
fireEvent.click(screen.getByRole('button', { name: '重置主机密码' }));
|
||||||
fireEvent.click(screen.getByRole('button', { name: '确认继续' }));
|
fireEvent.click(screen.getByRole('button', { name: '确认继续' }));
|
||||||
expect(await screen.findByText('demo-host-password-reset')).toBeInTheDocument();
|
expect(await screen.findByText('demo-host-password-reset')).toBeInTheDocument();
|
||||||
@@ -124,7 +135,8 @@ describe('Sea vHost', () => {
|
|||||||
|
|
||||||
it('stops and deletes an additional website without deleting host files', async () => {
|
it('stops and deletes an additional website without deleting host files', async () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]);
|
enterFirstHost();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: '网站管理' }));
|
||||||
fireEvent.click(screen.getByRole('button', { name: '新增网站' }));
|
fireEvent.click(screen.getByRole('button', { name: '新增网站' }));
|
||||||
fireEvent.click(screen.getByRole('button', { name: '创建网站' }));
|
fireEvent.click(screen.getByRole('button', { name: '创建网站' }));
|
||||||
fireEvent.click(await screen.findByRole('button', { name: '停止 site-two' }));
|
fireEvent.click(await screen.findByRole('button', { name: '停止 site-two' }));
|
||||||
@@ -147,6 +159,7 @@ describe('Sea vHost', () => {
|
|||||||
|
|
||||||
it('opens encrypted credentials from the FTP resource page', () => {
|
it('opens encrypted credentials from the FTP resource page', () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
|
enterFirstHost();
|
||||||
fireEvent.click(screen.getByRole('button', { name: 'FTP' }));
|
fireEvent.click(screen.getByRole('button', { name: 'FTP' }));
|
||||||
fireEvent.click(screen.getByRole('button', { name: /查看 FTP 凭据 sv8c0a6d2f91/ }));
|
fireEvent.click(screen.getByRole('button', { name: /查看 FTP 凭据 sv8c0a6d2f91/ }));
|
||||||
expect(screen.getByRole('dialog', { name: '虚拟主机凭据' })).toHaveTextContent('demo-ftp-password');
|
expect(screen.getByRole('dialog', { name: '虚拟主机凭据' })).toHaveTextContent('demo-ftp-password');
|
||||||
@@ -154,6 +167,7 @@ describe('Sea vHost', () => {
|
|||||||
|
|
||||||
it('opens the mobile navigation and navigates to a resource page', () => {
|
it('opens the mobile navigation and navigates to a resource page', () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
|
enterFirstHost();
|
||||||
const menu = screen.getByRole('button', { name: '打开导航' });
|
const menu = screen.getByRole('button', { name: '打开导航' });
|
||||||
fireEvent.click(menu);
|
fireEvent.click(menu);
|
||||||
expect(menu).toHaveAttribute('aria-expanded', 'true');
|
expect(menu).toHaveAttribute('aria-expanded', 'true');
|
||||||
@@ -302,7 +316,7 @@ describe('宝塔站点迁移', () => {
|
|||||||
describe('主机账号边界', () => {
|
describe('主机账号边界', () => {
|
||||||
it('不显示用户级聚合用量和创建主机入口', () => {
|
it('不显示用户级聚合用量和创建主机入口', () => {
|
||||||
const noop = () => undefined;
|
const noop = () => undefined;
|
||||||
render(<Overview projects={[initialProjects[0]]} plan={demoPlan} usage={demoUsage} activities={[]} hostScoped canCreate={false} onCreate={noop} onToggle={noop} onFiles={noop} onRunPath={noop} onSites={noop} onCredentials={noop} />);
|
render(<Overview projects={[initialProjects[0]]} plan={demoPlan} usage={demoUsage} activities={[]} hostScoped canCreate={false} onCreate={noop} onEnterHost={noop} />);
|
||||||
expect(screen.queryByText('存储空间')).not.toBeInTheDocument();
|
expect(screen.queryByText('存储空间')).not.toBeInTheDocument();
|
||||||
expect(screen.queryByRole('button', { name: /创建虚拟主机/ })).not.toBeInTheDocument();
|
expect(screen.queryByRole('button', { name: /创建虚拟主机/ })).not.toBeInTheDocument();
|
||||||
expect(screen.queryByText('管理当前虚拟主机的网站、文件与访问凭据。')).not.toBeInTheDocument();
|
expect(screen.queryByText('管理当前虚拟主机的网站、文件与访问凭据。')).not.toBeInTheDocument();
|
||||||
|
|||||||
+23
-8
@@ -1,3 +1,4 @@
|
|||||||
|
import {randomHostName} from './hostName';
|
||||||
import {UserSchedules} from './components/UserSchedules';
|
import {UserSchedules} from './components/UserSchedules';
|
||||||
import {useLiveDashboard} from './useLiveDashboard';
|
import {useLiveDashboard} from './useLiveDashboard';
|
||||||
import {ResourceCharts} from './components/ResourceCharts';
|
import {ResourceCharts} from './components/ResourceCharts';
|
||||||
@@ -24,11 +25,14 @@ import { demoActivities, demoPlan, demoRuntimeVersions, demoUsage, initialProjec
|
|||||||
import type { ActivityEntry, APIProject, Plan, Project, ProjectDraft, ProjectStatus, Runtime, RuntimeCatalog, Usage } from './types';
|
import type { ActivityEntry, APIProject, Plan, Project, ProjectDraft, ProjectStatus, Runtime, RuntimeCatalog, Usage } from './types';
|
||||||
|
|
||||||
export function App() {
|
export function App() {
|
||||||
const apiMode = import.meta.env.VITE_API_MODE === 'true';
|
// Regular production builds always authenticate; the isolated demo requires an explicit build mode.
|
||||||
|
const apiMode = import.meta.env.MODE !== 'demo' && (!import.meta.env.DEV || import.meta.env.VITE_API_MODE === 'true');
|
||||||
const setupPreview = import.meta.env.DEV && new URLSearchParams(window.location.search).get('setup') === '1';
|
const setupPreview = import.meta.env.DEV && new URLSearchParams(window.location.search).get('setup') === '1';
|
||||||
const adminPreview = import.meta.env.DEV && new URLSearchParams(window.location.search).get('admin') === '1';
|
const adminPreview = import.meta.env.DEV && new URLSearchParams(window.location.search).get('admin') === '1';
|
||||||
const [page, setPage] = useState('overview');
|
const [page, setPage] = useState('overview');
|
||||||
const [projects, setProjects] = useState<Project[]>(initialProjects);
|
const [projects, setProjects] = useState<Project[]>(initialProjects);
|
||||||
|
const [managedProjectID, setManagedProjectID] = useState<number>();
|
||||||
|
useEffect(()=>{document.documentElement.scrollTop=0;document.body.scrollTop=0},[page,managedProjectID]);
|
||||||
const changingProjects=useRef(new Set<number>()),dashboardRevision=useRef(0);const [pendingProjectIDs,setPendingProjectIDs]=useState<number[]>([]);
|
const changingProjects=useRef(new Set<number>()),dashboardRevision=useRef(0);const [pendingProjectIDs,setPendingProjectIDs]=useState<number[]>([]);
|
||||||
const [fileProjectID, setFileProjectID] = useState<number>();
|
const [fileProjectID, setFileProjectID] = useState<number>();
|
||||||
const [runPathProject, setRunPathProject] = useState<Project>();
|
const [runPathProject, setRunPathProject] = useState<Project>();
|
||||||
@@ -53,6 +57,11 @@ export function App() {
|
|||||||
const [bootError, setBootError] = useState('');const [bootStatus,setBootStatus]=useState<number>();
|
const [bootError, setBootError] = useState('');const [bootStatus,setBootStatus]=useState<number>();
|
||||||
const [bootAttempt, setBootAttempt] = useState(0);
|
const [bootAttempt, setBootAttempt] = useState(0);
|
||||||
const [showSecurity, setShowSecurity] = useState(false);
|
const [showSecurity, setShowSecurity] = useState(false);
|
||||||
|
useEffect(()=>{
|
||||||
|
if(managedProjectID && !projects.some(project=>project.id===managedProjectID)){
|
||||||
|
setManagedProjectID(undefined);setPage('overview');setSitesProject(undefined);setRunPathProject(undefined);setCredentials(null);
|
||||||
|
}
|
||||||
|
},[managedProjectID,projects]);
|
||||||
|
|
||||||
const applyDashboard=useCallback((dashboard:Dashboard)=>{
|
const applyDashboard=useCallback((dashboard:Dashboard)=>{
|
||||||
setProjects(dashboard.projects.map(normalizeProject));setPlan(dashboard.plan);setUsage(dashboard.usage);setActivities(dashboard.activities);setHostScoped(dashboard.hostScoped);setDomainApproval(dashboard.domainApproval);setRootDomain(dashboard.rootDomain);setProjectRoot(dashboard.projectRoot);
|
setProjects(dashboard.projects.map(normalizeProject));setPlan(dashboard.plan);setUsage(dashboard.usage);setActivities(dashboard.activities);setHostScoped(dashboard.hostScoped);setDomainApproval(dashboard.domainApproval);setRootDomain(dashboard.rootDomain);setProjectRoot(dashboard.projectRoot);
|
||||||
@@ -127,7 +136,7 @@ export function App() {
|
|||||||
}
|
}
|
||||||
const project: Project = {
|
const project: Project = {
|
||||||
id: Math.max(0, ...projects.map(({ id }) => id)) + 1,
|
id: Math.max(0, ...projects.map(({ id }) => id)) + 1,
|
||||||
hostName: `svdemo${String(Math.max(0, ...projects.map(({ id }) => id)) + 1).padStart(6, '0')}`,
|
hostName: randomHostName(),
|
||||||
name: draft.name,
|
name: draft.name,
|
||||||
domain: '',
|
domain: '',
|
||||||
path: '',
|
path: '',
|
||||||
@@ -203,6 +212,12 @@ export function App() {
|
|||||||
if (apiMode) void api.runtimeCatalog(project.id).then(result => setRuntimeVersions(normalizeCatalog(result.versions))).catch(reason => notify(reason instanceof Error ? reason.message : '节点环境读取失败'));
|
if (apiMode) void api.runtimeCatalog(project.id).then(result => setRuntimeVersions(normalizeCatalog(result.versions))).catch(reason => notify(reason instanceof Error ? reason.message : '节点环境读取失败'));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const managedProject = hostScoped ? projects[0] : projects.find(project=>project.id===managedProjectID);
|
||||||
|
const hostView = hostScoped || !!managedProject;
|
||||||
|
const visibleProjects = hostView ? (managedProject ? [managedProject] : []) : projects;
|
||||||
|
function enterHost(project:Project){setManagedProjectID(project.id);setFileProjectID(project.id);setPage('projects')}
|
||||||
|
function leaveHost(){setManagedProjectID(undefined);setPage('overview');setSitesProject(undefined);setRunPathProject(undefined);setCredentials(null)}
|
||||||
|
|
||||||
if (adminPreview) return <AdminConsole user={{ id: 1, email: 'admin@ser888.cn', loginName: 'admin@ser888.cn', displayName: '平台管理员', role: 'admin', mfaEnabled: true }} tenants={[{ id: 1, slug: 'sea-demo', name: '示例用户', status: 'active', lifecycleState: 'active', planName: '标准套餐', userCount: 1, projectCount: 3, expiresAt: '2026-12-31T16:00:00Z', createdAt: '2026-10-01T08:00:00Z' }]} plans={[demoPlan]} pendingDomains={[{ id: 9, projectId: 1, siteId: 1, tenantName: '示例用户', hostName: 'sv8c0a6d2f91', projectName: '企业官网', siteName: '主站', domain: 'www.customer.example', kind: 'custom', status: 'pending', resolutionMode: 'cname', cnameTarget: 'sv8c0a6d2f91.vhost.ser888.cn', filingStatus: 'pending', sslStatus: 'pending', createdAt: '2026-10-22T08:00:00Z' }]} approval onApproval={async () => undefined} onReviewDomain={async () => undefined} onCreate={async () => undefined} onCreatePlan={async () => undefined} onSecurity={() => undefined} onLogout={() => undefined} />;
|
if (adminPreview) return <AdminConsole user={{ id: 1, email: 'admin@ser888.cn', loginName: 'admin@ser888.cn', displayName: '平台管理员', role: 'admin', mfaEnabled: true }} tenants={[{ id: 1, slug: 'sea-demo', name: '示例用户', status: 'active', lifecycleState: 'active', planName: '标准套餐', userCount: 1, projectCount: 3, expiresAt: '2026-12-31T16:00:00Z', createdAt: '2026-10-01T08:00:00Z' }]} plans={[demoPlan]} pendingDomains={[{ id: 9, projectId: 1, siteId: 1, tenantName: '示例用户', hostName: 'sv8c0a6d2f91', projectName: '企业官网', siteName: '主站', domain: 'www.customer.example', kind: 'custom', status: 'pending', resolutionMode: 'cname', cnameTarget: 'sv8c0a6d2f91.vhost.ser888.cn', filingStatus: 'pending', sslStatus: 'pending', createdAt: '2026-10-22T08:00:00Z' }]} approval onApproval={async () => undefined} onReviewDomain={async () => undefined} onCreate={async () => undefined} onCreatePlan={async () => undefined} onSecurity={() => undefined} onLogout={() => undefined} />;
|
||||||
if (setupPreview) return <InstallWizard preview />;
|
if (setupPreview) return <InstallWizard preview />;
|
||||||
if (apiMode && setupRequired === true) return <InstallWizard />;
|
if (apiMode && setupRequired === true) return <InstallWizard />;
|
||||||
@@ -212,17 +227,17 @@ export function App() {
|
|||||||
if (apiMode && user?.role === 'admin') return <><AdminConsole onPlansChanged={async()=>{setPlans((await api.plans()).plans)}} onImpersonate={async input=>{await api.startImpersonation(input);window.location.reload()}} user={user} tenants={tenants} plans={plans} pendingDomains={pendingDomains} approval={domainApproval} onApproval={async (enabled) => { await api.setDomainApproval(enabled); setDomainApproval(enabled); }} onReviewDomain={async (id, approved) => { await api.reviewDomain(id, approved); setPendingDomains((current) => current.filter((item) => item.id !== id)); }} onCreate={async (input) => { await api.createTenant(input); setTenants((await api.tenants()).tenants); }} onCreatePlan={async (input: PlanInput) => { await api.createPlan(input); setPlans((await api.plans()).plans); }} onSecurity={() => setShowSecurity(true)} onLogout={async () => { await api.logout(); window.location.reload(); }} />{showSecurity ? <SecurityModal onClose={() => setShowSecurity(false)} onSessionEnded={() => { setShowSecurity(false); setUser(null); }} /> : null}</>;
|
if (apiMode && user?.role === 'admin') return <><AdminConsole onPlansChanged={async()=>{setPlans((await api.plans()).plans)}} onImpersonate={async input=>{await api.startImpersonation(input);window.location.reload()}} user={user} tenants={tenants} plans={plans} pendingDomains={pendingDomains} approval={domainApproval} onApproval={async (enabled) => { await api.setDomainApproval(enabled); setDomainApproval(enabled); }} onReviewDomain={async (id, approved) => { await api.reviewDomain(id, approved); setPendingDomains((current) => current.filter((item) => item.id !== id)); }} onCreate={async (input) => { await api.createTenant(input); setTenants((await api.tenants()).tenants); }} onCreatePlan={async (input: PlanInput) => { await api.createPlan(input); setPlans((await api.plans()).plans); }} onSecurity={() => setShowSecurity(true)} onLogout={async () => { await api.logout(); window.location.reload(); }} />{showSecurity ? <SecurityModal onClose={() => setShowSecurity(false)} onSessionEnded={() => { setShowSecurity(false); setUser(null); }} /> : null}</>;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AppShell page={page === 'create' ? 'projects' : page} tenantName={user?.tenantName ?? '示例科技有限公司'} displayName={user?.displayName ?? '张三'} hostScoped={hostScoped} onNavigate={setPage} onLogout={()=>{void api.logout().then(()=>window.location.reload()).catch(reason=>notify(reason instanceof Error?reason.message:'退出失败'))}} onSecurity={() => user?.impersonating?notify('请先返回管理员后操作账号安全'):setShowSecurity(true)}>
|
<AppShell page={page === 'create'||page==='schedules' ? 'overview' : page} tenantName={user?.tenantName ?? '示例科技有限公司'} displayName={user?.displayName ?? '张三'} hostScoped={hostScoped} hostView={hostView} hostName={managedProject?.hostName} onBack={hostView&&!hostScoped?leaveHost:undefined} onNavigate={setPage} onLogout={()=>{void api.logout().then(()=>window.location.reload()).catch(reason=>notify(reason instanceof Error?reason.message:'退出失败'))}} onSecurity={() => user?.impersonating?notify('请先返回管理员后操作账号安全'):setShowSecurity(true)}>
|
||||||
{user?.impersonating?<ImpersonationBanner user={user}/>:null}
|
{user?.impersonating?<ImpersonationBanner user={user}/>:null}
|
||||||
{dashboardSync.error?<p className="resource-error" role="alert">状态刷新失败:{dashboardSync.error}。<button className="secondary" onClick={dashboardSync.refresh}>重新读取状态</button></p>:null}
|
{dashboardSync.error?<p className="resource-error" role="alert">状态刷新失败:{dashboardSync.error}。<button className="secondary" onClick={dashboardSync.refresh}>重新读取状态</button></p>:null}
|
||||||
{page === 'overview' ? <Overview onRefresh={apiMode?dashboardSync.refresh:undefined} refreshing={dashboardSync.refreshing} pendingProjectIDs={pendingProjectIDs} onLogs={() => setPage('logs')} projects={projects} plan={plan} usage={usage} activities={activities} hostScoped={hostScoped} canCreate={!apiMode} onCreate={() => setPage('create')} onToggle={toggleProject} onFiles={(id) => { setFileProjectID(id); setPage('files'); }} onRunPath={(project) => setRunPathProject(project)} onSites={(project)=>{setRuntimeVersions(normalizeCatalog({}));setSitesProject(project);if(apiMode) void api.runtimeCatalog(project.id).then(result=>setRuntimeVersions(normalizeCatalog(result.versions))).catch(reason=>notify(reason instanceof Error?reason.message:"节点环境读取失败"));else setRuntimeVersions(demoRuntimeVersions);}} onCredentials={(project) => void showCredentials(project)} /> : null}
|
{page === 'overview' ? <Overview onRefresh={apiMode?dashboardSync.refresh:undefined} refreshing={dashboardSync.refreshing} onLogs={() => setPage('logs')} onSchedules={!hostScoped?()=>setPage('schedules'):undefined} projects={projects} plan={plan} usage={usage} activities={activities} hostScoped={hostScoped} canCreate={!apiMode} onCreate={() => setPage('create')} onEnterHost={enterHost} /> : null}
|
||||||
{page === 'create' ? <CreateProject runtimeVersions={runtimeVersions} rootDomain={rootDomain} projectRoot={projectRoot} plan={plan} domainApproval={domainApproval} onCancel={() => setPage('overview')} onSubmit={createProject} /> : null}
|
{page === 'create' ? <CreateProject runtimeVersions={runtimeVersions} rootDomain={rootDomain} projectRoot={projectRoot} plan={plan} domainApproval={domainApproval} onCancel={() => setPage('overview')} onSubmit={createProject} /> : null}
|
||||||
{page==='schedules'&&!hostScoped?<UserSchedules projects={projects} live={apiMode}/>:null}
|
{page==='schedules'&&!hostScoped?<UserSchedules projects={projects} live={apiMode}/>:null}
|
||||||
{page==='metrics'?<ResourceCharts projects={projects} live={apiMode}/>:null}
|
{page==='metrics'?<ResourceCharts key={managedProject?.id} projects={visibleProjects} live={apiMode}/>:null}
|
||||||
{page === 'files' ? <FileManager projects={projects} initialProjectID={fileProjectID} live={apiMode} /> : null}
|
{page === 'files' ? <FileManager key={managedProject?.id} projects={visibleProjects} initialProjectID={fileProjectID} live={apiMode} /> : null}
|
||||||
{page === 'projects' ? <HostDetails onRefresh={apiMode?dashboardSync.refresh:undefined} refreshing={dashboardSync.refreshing} onToggle={toggleProject} pendingProjectIDs={pendingProjectIDs} hostScoped={hostScoped} projects={projects} plan={plan} usage={usage} live={apiMode} onRunPath={setRunPathProject} onSites={showSites} onCredentials={project => void showCredentials(project)} onFiles={id => { setFileProjectID(id); setPage('files'); }} /> : null}
|
{page === 'projects' ? <HostDetails key={managedProject?.id} onRefresh={apiMode?dashboardSync.refresh:undefined} refreshing={dashboardSync.refreshing} onToggle={toggleProject} pendingProjectIDs={pendingProjectIDs} hostScoped={hostScoped} projects={visibleProjects} plan={plan} usage={usage} live={apiMode} onRunPath={setRunPathProject} onSites={showSites} onCredentials={project => void showCredentials(project)} onFiles={id => { setFileProjectID(id); setPage('files'); }} /> : null}
|
||||||
{page === 'dns' && !hostScoped ? <DNSCredentials live={apiMode} /> : null}
|
{page === 'dns' && !hostScoped ? <DNSCredentials live={apiMode} /> : null}
|
||||||
{['domains', 'databases', 'ftp', 'logs'].includes(page) ? <ResourceCenter page={page} projects={projects} activities={activities} hostScoped={hostScoped} domainApproval={domainApproval} live={apiMode} onCredentials={showCredentialsByID} onNotify={notify} /> : null}
|
{['domains', 'databases', 'ftp', 'logs'].includes(page) ? <ResourceCenter key={`${managedProject?.id}:${page}`} page={page} projects={visibleProjects} projectID={managedProject?.id} activities={activities} hostScoped={hostView} domainApproval={domainApproval} live={apiMode} onCredentials={showCredentialsByID} onNotify={notify} /> : null}
|
||||||
{toast ? <div className="toast" role="status"><CheckIcon />{toast}</div> : null}
|
{toast ? <div className="toast" role="status"><CheckIcon />{toast}</div> : null}
|
||||||
{credentials ? <CredentialsModal credentials={credentials} onReset={user?.role !== 'host' ? resetHostPassword : undefined} onClose={() => { setCredentials(null); setCredentialProjectID(undefined); }} /> : null}
|
{credentials ? <CredentialsModal credentials={credentials} onReset={user?.role !== 'host' ? resetHostPassword : undefined} onClose={() => { setCredentials(null); setCredentialProjectID(undefined); }} /> : null}
|
||||||
{runPathProject ? <RunPathModal project={runPathProject} onClose={() => setRunPathProject(undefined)} onSubmit={updateRunPath} /> : null}
|
{runPathProject ? <RunPathModal project={runPathProject} onClose={() => setRunPathProject(undefined)} onSubmit={updateRunPath} /> : null}
|
||||||
|
|||||||
@@ -8,6 +8,47 @@ import {initialProjects} from './data';
|
|||||||
afterEach(()=>{cleanup();vi.restoreAllMocks()});
|
afterEach(()=>{cleanup();vi.restoreAllMocks()});
|
||||||
const listing=(name:string):FileListing=>({path:'',uploadLimit:20971520,entries:[{name,path:name,directory:false,size:10,modified:'2026-10-28T00:00:00Z'}]});
|
const listing=(name:string):FileListing=>({path:'',uploadLimit:20971520,entries:[{name,path:name,directory:false,size:10,modified:'2026-10-28T00:00:00Z'}]});
|
||||||
|
|
||||||
|
it('uploads folders without flattening duplicate basenames and retries conflicts by relative path',async()=>{
|
||||||
|
vi.spyOn(api,'files').mockResolvedValue(listing('index.txt'));
|
||||||
|
const a=new window.File(['a'],'index.php'),b=new window.File(['b'],'index.php');
|
||||||
|
Object.defineProperty(a,'webkitRelativePath',{value:'site/a/index.php'});Object.defineProperty(b,'webkitRelativePath',{value:'site/b/index.php'});
|
||||||
|
const upload=vi.spyOn(api,'uploadFiles').mockResolvedValueOnce({files:[{name:'site/a/index.php',size:1,success:true,status:201},{name:'site/b/index.php',size:0,success:false,status:409,error:'同名文件已存在'}]}).mockResolvedValueOnce({files:[{name:'site/b/index.php',size:1,success:true,status:201}]});
|
||||||
|
render(<FileManager projects={initialProjects}/>);await screen.findByText('index.txt');
|
||||||
|
const input=screen.getByLabelText('上传文件夹');expect(input).toHaveAttribute('webkitdirectory');expect(input).toHaveAttribute('multiple');
|
||||||
|
fireEvent.change(input,{target:{files:[a,b]}});
|
||||||
|
const dialog=await screen.findByRole('alertdialog',{name:'覆盖文件'});expect(dialog).toHaveTextContent('site/b/index.php');
|
||||||
|
fireEvent.click(within(dialog).getByRole('button',{name:'覆盖同名文件'}));
|
||||||
|
await waitFor(()=>expect(upload).toHaveBeenLastCalledWith(1,'',[b],true));
|
||||||
|
expect(await screen.findByText('上传完成:成功 2 个,失败或跳过 0 个')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('validates the whole batch before uploading and preserves the 20 MB single-file cap',async()=>{
|
||||||
|
vi.spyOn(api,'files').mockResolvedValue(listing('index.txt'));const upload=vi.spyOn(api,'uploadFiles').mockResolvedValue({files:[]});
|
||||||
|
render(<FileManager projects={initialProjects}/>);await screen.findByText('index.txt');
|
||||||
|
const input=screen.getByLabelText('批量上传文件');expect(input).toHaveAttribute('multiple');
|
||||||
|
const file=(name:string,size:number)=>{const out=new window.File(['x'],name);Object.defineProperty(out,'size',{value:size});return out};
|
||||||
|
fireEvent.change(input,{target:{files:[file('a',20*1024**2),file('b',10*1024**2+1)]}});
|
||||||
|
expect(await screen.findByRole('alert')).toHaveTextContent('单批上传总大小不能超过 30 MB');expect(upload).not.toHaveBeenCalled();
|
||||||
|
fireEvent.change(input,{target:{files:[file('a',20*1024**2+1)]}});expect(screen.getByRole('alert')).toHaveTextContent('单文件不能超过 20 MB');expect(upload).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
it('reports partial results and retries only conflicting files after explicit confirmation',async()=>{
|
||||||
|
vi.spyOn(api,'files').mockResolvedValue(listing('index.txt'));
|
||||||
|
const a=new window.File(['a'],'a.txt'),b=new window.File(['b'],'b.txt');
|
||||||
|
const upload=vi.spyOn(api,'uploadFiles').mockResolvedValueOnce({files:[{name:'a.txt',size:1,success:true,status:201},{name:'b.txt',size:0,success:false,status:409,error:'同名文件已存在'}]}).mockResolvedValueOnce({files:[{name:'b.txt',size:1,success:true,status:201}]});
|
||||||
|
render(<FileManager projects={initialProjects}/>);await screen.findByText('index.txt');
|
||||||
|
fireEvent.change(screen.getByLabelText('批量上传文件'),{target:{files:[a,b]}});
|
||||||
|
const dialog=await screen.findByRole('alertdialog',{name:'覆盖文件'});expect(upload).toHaveBeenCalledTimes(1);
|
||||||
|
fireEvent.click(within(dialog).getByRole('button',{name:'覆盖同名文件'}));
|
||||||
|
await waitFor(()=>expect(upload).toHaveBeenLastCalledWith(1,'',[b],true));
|
||||||
|
expect(await screen.findByText('上传完成:成功 2 个,失败或跳过 0 个')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
it('offers an explicit TAR.GZ extraction action with a correctly derived destination',async()=>{
|
||||||
|
vi.spyOn(api,'files').mockResolvedValue(listing('site.tar.gz'));const action=vi.spyOn(api,'fileAction').mockResolvedValue(undefined);
|
||||||
|
render(<FileManager projects={initialProjects}/>);fireEvent.click(await screen.findByRole('button',{name:'解压 site.tar.gz'}));
|
||||||
|
expect(screen.getByLabelText('目标路径')).toHaveValue('site-extracted');
|
||||||
|
fireEvent.click(screen.getByRole('button',{name:'执行操作'}));await waitFor(()=>expect(action).toHaveBeenCalledWith(1,'extract','site.tar.gz','site-extracted'));
|
||||||
|
});
|
||||||
|
|
||||||
it('does not present binary filenames as buttons that cannot do anything',async()=>{
|
it('does not present binary filenames as buttons that cannot do anything',async()=>{
|
||||||
vi.spyOn(api,'files').mockResolvedValue(listing('program.bin'));
|
vi.spyOn(api,'files').mockResolvedValue(listing('program.bin'));
|
||||||
render(<FileManager projects={initialProjects}/>);
|
render(<FileManager projects={initialProjects}/>);
|
||||||
|
|||||||
@@ -32,6 +32,13 @@ it('does not show a host switcher for a single-host login',()=>{
|
|||||||
expect(screen.queryByRole('combobox',{name:'选择虚拟主机'})).not.toBeInTheDocument();
|
expect(screen.queryByRole('combobox',{name:'选择虚拟主机'})).not.toBeInTheDocument();
|
||||||
expect(screen.getByRole('heading',{name:initialProjects[0].hostName})).toBeInTheDocument();
|
expect(screen.getByRole('heading',{name:initialProjects[0].hostName})).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
it('shows only the entered host databases even when the account resource response includes other hosts',async()=>{
|
||||||
|
const first=initialProjects[0],target=initialProjects[1];
|
||||||
|
vi.spyOn(api,'resources').mockResolvedValue({sites:[],domains:[],ftpAccounts:[],databases:[first,target].map(p=>({id:p.id,projectId:p.id,hostName:p.hostName,projectName:p.name,name:'db-'+p.hostName,username:p.hostName,sizeBytes:0,status:'active',createdAt:'2026-10-30T00:00:00Z'}))});
|
||||||
|
render(<ResourceCenter page="databases" projectID={target.id} projects={[target]} activities={[]} hostScoped live domainApproval onCredentials={vi.fn()} onNotify={vi.fn()}/>);
|
||||||
|
expect(await screen.findByText('db-'+target.hostName)).toBeInTheDocument();
|
||||||
|
expect(screen.queryByText('db-'+first.hostName)).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
it('loads and refreshes logs scoped to the signed-in host',async()=>{
|
it('loads and refreshes logs scoped to the signed-in host',async()=>{
|
||||||
const load=vi.spyOn(api,'activities').mockResolvedValue({activities:[{id:91,projectId:initialProjects[0].id,actor:'用户',action:'update',resourceType:'run_path',detail:'用户更新当前主机目录',success:true,createdAt:'2026-10-26T00:00:00Z'}]});
|
const load=vi.spyOn(api,'activities').mockResolvedValue({activities:[{id:91,projectId:initialProjects[0].id,actor:'用户',action:'update',resourceType:'run_path',detail:'用户更新当前主机目录',success:true,createdAt:'2026-10-26T00:00:00Z'}]});
|
||||||
render(<ResourceCenter page="logs" projects={initialProjects.slice(0,1)} activities={[]} hostScoped live domainApproval onCredentials={vi.fn()} onNotify={vi.fn()}/>);
|
render(<ResourceCenter page="logs" projects={initialProjects.slice(0,1)} activities={[]} hostScoped live domainApproval onCredentials={vi.fn()} onNotify={vi.fn()}/>);
|
||||||
|
|||||||
@@ -7,11 +7,30 @@ import {demoPlan,demoUsage} from './data';
|
|||||||
import {RunPathModal} from './components/RunPathModal';
|
import {RunPathModal} from './components/RunPathModal';
|
||||||
import {initialProjects} from './data';
|
import {initialProjects} from './data';
|
||||||
afterEach(()=>{cleanup();vi.restoreAllMocks();vi.unstubAllEnvs()});
|
afterEach(()=>{cleanup();vi.restoreAllMocks();vi.unstubAllEnvs()});
|
||||||
|
it('shows sample data only for an explicitly selected demo build without backend initialization',()=>{
|
||||||
|
vi.stubEnv('DEV',false);vi.stubEnv('MODE','demo');vi.stubEnv('VITE_API_MODE','true');
|
||||||
|
const setup=vi.spyOn(api,'setupStatus');const me=vi.spyOn(api,'me');
|
||||||
|
render(<App/>);
|
||||||
|
expect(screen.getByText('示例科技有限公司')).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole('heading',{name:'总览'})).toBeInTheDocument();
|
||||||
|
expect(setup).not.toHaveBeenCalled();expect(me).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
it('requires backend authentication in production even when the API build flag is missing',async()=>{
|
||||||
|
vi.stubEnv('DEV',false);vi.stubEnv('VITE_API_MODE',undefined);
|
||||||
|
const setup=vi.spyOn(api,'setupStatus').mockResolvedValue({required:false});
|
||||||
|
vi.spyOn(api,'me').mockRejectedValue(Object.assign(new Error('unauthorized'),{status:401}));
|
||||||
|
vi.spyOn(api,'oidcStatus').mockResolvedValue({enabled:false,userPasswordLogin:true,adminPasswordLogin:true});
|
||||||
|
render(<App/>);
|
||||||
|
expect(await screen.findByRole('heading',{name:'登录控制台'})).toBeInTheDocument();
|
||||||
|
expect(setup).toHaveBeenCalled();
|
||||||
|
expect(screen.queryByText('示例科技有限公司')).not.toBeInTheDocument();
|
||||||
|
expect(screen.queryByRole('button',{name:'创建虚拟主机'})).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
it('submits one state change during rapid clicks and shows the requested final state',async()=>{
|
it('submits one state change during rapid clicks and shows the requested final state',async()=>{
|
||||||
vi.stubEnv('VITE_API_MODE','true');vi.spyOn(api,'setupStatus').mockResolvedValue({required:false});vi.spyOn(api,'me').mockResolvedValue({user:{id:4,role:'tenant',displayName:'测试用户',tenantName:'测试账号'} as User});
|
vi.stubEnv('VITE_API_MODE','true');vi.spyOn(api,'setupStatus').mockResolvedValue({required:false});vi.spyOn(api,'me').mockResolvedValue({user:{id:4,role:'tenant',displayName:'测试用户',tenantName:'测试账号'} as User});
|
||||||
vi.spyOn(api,'dashboard').mockResolvedValue({plan:demoPlan,usage:demoUsage,activities:[],hostScoped:false,domainApproval:true,rootDomain:'vhost.ser888.cn',projectRoot:'/www/wwwroot/seavHost/vHost',projects:[{id:9,hostName:'sv9999999999',name:'主机',domain:'qa.vhost.ser888.cn',path:'/www/wwwroot/seavHost/vHost/sv9999999999',runPath:'/public',runtime:'PHP',version:'8.4',status:'stopped',sslStatus:'off',autoSSL:false,processLimit:10,createdAt:'2026-10-29T00:00:00Z'}]} as Dashboard);
|
vi.spyOn(api,'dashboard').mockResolvedValue({plan:demoPlan,usage:demoUsage,activities:[],hostScoped:false,domainApproval:true,rootDomain:'vhost.ser888.cn',projectRoot:'/www/wwwroot/seavHost/vHost',projects:[{id:9,hostName:'sv9999999999',name:'主机',domain:'qa.vhost.ser888.cn',path:'/www/wwwroot/seavHost/vHost/sv9999999999',runPath:'/public',runtime:'PHP',version:'8.4',status:'stopped',sslStatus:'off',autoSSL:false,processLimit:10,createdAt:'2026-10-29T00:00:00Z'}]} as Dashboard);
|
||||||
let finish!:()=>void;const pending=new Promise<void>(resolve=>{finish=resolve});const update=vi.spyOn(api,'setProjectState').mockReturnValue(pending);
|
let finish!:()=>void;const pending=new Promise<void>(resolve=>{finish=resolve});const update=vi.spyOn(api,'setProjectState').mockReturnValue(pending);
|
||||||
render(<App/>);const start=await screen.findByRole('button',{name:'启动'});fireEvent.click(start);fireEvent.click(start);expect(update).toHaveBeenCalledTimes(1);expect(screen.getByRole('button',{name:'处理中…'})).toBeDisabled();finish();await waitFor(()=>expect(screen.getByRole('button',{name:'停止'})).toBeEnabled());expect(update).toHaveBeenCalledWith(9,true);
|
render(<App/>);fireEvent.click(await screen.findByRole('button',{name:'进入主机 sv9999999999'}));const start=await screen.findByRole('button',{name:'启动主站'});fireEvent.click(start);fireEvent.click(start);expect(update).toHaveBeenCalledTimes(1);expect(screen.getByRole('button',{name:'处理中…'})).toBeDisabled();finish();await waitFor(()=>expect(screen.getByRole('button',{name:'停止主站'})).toBeEnabled());expect(update).toHaveBeenCalledWith(9,true);
|
||||||
});
|
});
|
||||||
it('keeps a rejected run directory visible with an inline reason',async()=>{
|
it('keeps a rejected run directory visible with an inline reason',async()=>{
|
||||||
render(<RunPathModal project={initialProjects[0]} onClose={vi.fn()} onSubmit={vi.fn().mockRejectedValue(new Error('目标目录不存在'))}/>);fireEvent.click(screen.getByRole('button',{name:'保存'}));expect(await screen.findByRole('alert')).toHaveTextContent('目标目录不存在');expect(screen.getByRole('button',{name:'保存'})).toBeEnabled();
|
render(<RunPathModal project={initialProjects[0]} onClose={vi.fn()} onSubmit={vi.fn().mockRejectedValue(new Error('目标目录不存在'))}/>);fireEvent.click(screen.getByRole('button',{name:'保存'}));expect(await screen.findByRole('alert')).toHaveTextContent('目标目录不存在');expect(screen.getByRole('button',{name:'保存'})).toBeEnabled();
|
||||||
|
|||||||
@@ -28,9 +28,9 @@ it('blocks account deletion while hosts remain and saves only after loading',asy
|
|||||||
const profile={id:4,slug:'customer',name:'用户甲',email:'qa@example.invalid',displayName:'联系人',projectCount:1};
|
const profile={id:4,slug:'customer',name:'用户甲',email:'qa@example.invalid',displayName:'联系人',projectCount:1};
|
||||||
vi.spyOn(api,'accountProfile').mockResolvedValue(profile);const update=vi.spyOn(api,'updateAccount').mockResolvedValue();
|
vi.spyOn(api,'accountProfile').mockResolvedValue(profile);const update=vi.spyOn(api,'updateAccount').mockResolvedValue();
|
||||||
render(<AccountEditor account={{id:4,slug:'customer'} as Tenant} onClose={vi.fn()} onChanged={vi.fn().mockResolvedValue(undefined)}/>);
|
render(<AccountEditor account={{id:4,slug:'customer'} as Tenant} onClose={vi.fn()} onChanged={vi.fn().mockResolvedValue(undefined)}/>);
|
||||||
await screen.findByLabelText('用户名称');expect(screen.getByRole('button',{name:'删除用户'})).toBeDisabled();
|
await screen.findByLabelText('显示名称');expect(screen.getByRole('button',{name:'删除用户'})).toBeDisabled();
|
||||||
fireEvent.change(screen.getByLabelText('用户名称'),{target:{value:'新名称'}});fireEvent.click(screen.getByRole('button',{name:'保存用户资料'}));
|
fireEvent.change(screen.getByLabelText('显示名称'),{target:{value:'新名称'}});fireEvent.click(screen.getByRole('button',{name:'保存用户资料'}));
|
||||||
await waitFor(()=>expect(update).toHaveBeenCalledWith(4,{...profile,name:'新名称'}));
|
await waitFor(()=>expect(update).toHaveBeenCalledWith(4,{...profile,name:'新名称',displayName:'新名称'}));
|
||||||
});
|
});
|
||||||
it('keeps local node transport and storage root immutable and disallows deletion',()=>{
|
it('keeps local node transport and storage root immutable and disallows deletion',()=>{
|
||||||
render(<NodeEditor node={{id:1,name:'本机节点',transport:'local',endpoint:'local',rootDomain:'vhost.ser888.cn',tenantRoot:'/www/wwwroot/seavHost/vHost',ftpCertificateDomain:'host.ser888.cn',enabled:true} as ControlNode} onClose={vi.fn()} onChanged={vi.fn()}/>);
|
render(<NodeEditor node={{id:1,name:'本机节点',transport:'local',endpoint:'local',rootDomain:'vhost.ser888.cn',tenantRoot:'/www/wwwroot/seavHost/vHost',ftpCertificateDomain:'host.ser888.cn',enabled:true} as ControlNode} onClose={vi.fn()} onChanged={vi.fn()}/>);
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import '@testing-library/jest-dom/vitest';
|
||||||
|
import {cleanup,fireEvent,render,screen,within} from '@testing-library/react';
|
||||||
|
import {afterEach,expect,it,vi} from 'vitest';
|
||||||
|
import {App} from './App';
|
||||||
|
import {initialProjects} from './data';
|
||||||
|
afterEach(()=>{cleanup();vi.restoreAllMocks()});
|
||||||
|
it('keeps only account navigation and preserves user schedules in the overview',()=>{
|
||||||
|
render(<App/>);
|
||||||
|
expect(within(screen.getByLabelText('主导航')).getAllByRole('button').map(item=>item.textContent)).toEqual(['总览','域名','DNS API','操作日志']);
|
||||||
|
expect(screen.getByRole('button',{name:'计划任务'})).toBeInTheDocument();
|
||||||
|
expect(screen.queryByRole('button',{name:'文件管理'})).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
it('enters the selected host, scopes its tools, and returns to the user overview',()=>{
|
||||||
|
render(<App/>);const host=initialProjects[1];
|
||||||
|
fireEvent.click(screen.getByRole('button',{name:'进入主机 '+host.hostName}));
|
||||||
|
expect(screen.getByRole('heading',{name:host.hostName})).toBeInTheDocument();
|
||||||
|
fireEvent.click(within(screen.getByLabelText('主导航')).getByRole('button',{name:'数据库'}));
|
||||||
|
expect(screen.getAllByText(host.hostName).length).toBeGreaterThan(0);
|
||||||
|
expect(screen.queryByText(initialProjects[0].hostName)).not.toBeInTheDocument();
|
||||||
|
fireEvent.click(within(screen.getByLabelText('主导航')).getByRole('button',{name:'文件管理'}));
|
||||||
|
expect(screen.getByRole('combobox',{name:'选择虚拟主机'}).querySelectorAll('option')).toHaveLength(1);
|
||||||
|
expect(screen.getByRole('combobox',{name:'选择虚拟主机'})).toHaveValue(String(host.id));
|
||||||
|
fireEvent.click(screen.getByRole('button',{name:'返回用户总览'}));
|
||||||
|
expect(screen.getAllByRole('button',{name:/^进入主机 /})).toHaveLength(initialProjects.length);
|
||||||
|
expect(screen.getByRole('heading',{name:'总览'})).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
it('supports double-clicking a host row without changing account identity',()=>{
|
||||||
|
render(<App/>);const host=initialProjects[2];
|
||||||
|
fireEvent.doubleClick(screen.getByRole('button',{name:'进入主机 '+host.hostName}).closest('tr')!);
|
||||||
|
expect(screen.getByRole('heading',{name:host.hostName})).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole('button',{name:'返回用户总览'})).toBeInTheDocument();
|
||||||
|
expect(screen.queryByRole('button',{name:'返回管理视图'})).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
+10
-3
@@ -12,12 +12,12 @@ export interface DomainResource { id: number; projectId: number; siteId: number;
|
|||||||
export interface FTPResource { enabled?:boolean; id: number; projectId: number; hostName: string; projectName: string; username: string; rootPath: string; createdAt: string; }
|
export interface FTPResource { enabled?:boolean; id: number; projectId: number; hostName: string; projectName: string; username: string; rootPath: string; createdAt: string; }
|
||||||
export interface DatabaseResource { id: number; projectId: number; hostName: string; projectName: string; name: string; username: string; sizeBytes: number; status: 'active' | 'quota_suspended'; createdAt: string; }
|
export interface DatabaseResource { id: number; projectId: number; hostName: string; projectName: string; name: string; username: string; sizeBytes: number; status: 'active' | 'quota_suspended'; createdAt: string; }
|
||||||
export interface ResourceInventory { domains: DomainResource[]; ftpAccounts: FTPResource[]; databases: DatabaseResource[]; sites: Site[]; }
|
export interface ResourceInventory { domains: DomainResource[]; ftpAccounts: FTPResource[]; databases: DatabaseResource[]; sites: Site[]; }
|
||||||
export interface Tenant { id: number; slug: string; name: string; status: string; lifecycleState?: 'active' | 'grace' | 'recycle' | 'purged'; planName: string; userCount: number; projectCount: number; expiresAt?: string; graceUntil?: string; purgeAfter?: string; backupPurgeAfter?: string; createdAt: string; }
|
export interface Tenant {loginName?:string; id: number; slug: string; name: string; status: string; lifecycleState?: 'active' | 'grace' | 'recycle' | 'purged'; planName: string; userCount: number; projectCount: number; expiresAt?: string; graceUntil?: string; purgeAfter?: string; backupPurgeAfter?: string; createdAt: string; }
|
||||||
export interface ControlNode {id:number;name:string;transport:"local"|"https";endpoint:string;rootDomain:string;tenantRoot:string;ftpCertificateDomain:string;enabled:boolean;lastSeenAt?:string;lastError:string}
|
export interface ControlNode {id:number;name:string;transport:"local"|"https";endpoint:string;rootDomain:string;tenantRoot:string;ftpCertificateDomain:string;enabled:boolean;lastSeenAt?:string;lastError:string}
|
||||||
export interface AccountProfile {id:number;slug:string;name:string;email:string;displayName:string;projectCount:number;}
|
export interface AccountProfile {loginName?:string;id:number;slug:string;name:string;email:string;displayName:string;projectCount:number;}
|
||||||
export interface AdminProject {allowRuntimeChange?:boolean;manualRecycledAt?:string;purgeAfter?:string;recycleError?:string;pendingOwnership?:{targetOwnerId:number|null;credentialMode:"preserve"|"reset";stopServices:boolean;expectedVersion:number}; ownerTenantId?:number|null;managementLocked?:boolean;ownershipVersion?:number;nodeId:number;planId:number;expiresAt?:string;lifecycleState?:string; id: number; tenantName: string; hostName: string; name: string; domain: string; path: string; runPath: string; runtime: string; version: string; status: string; sslStatus: string; siteCount: number; ipAddress?: string; dedicatedIp: boolean; httpPort: number; httpsPort: number; createdAt: string; }
|
export interface AdminProject {allowRuntimeChange?:boolean;manualRecycledAt?:string;purgeAfter?:string;recycleError?:string;pendingOwnership?:{targetOwnerId:number|null;credentialMode:"preserve"|"reset";stopServices:boolean;expectedVersion:number}; ownerTenantId?:number|null;managementLocked?:boolean;ownershipVersion?:number;nodeId:number;planId:number;expiresAt?:string;lifecycleState?:string; id: number; tenantName: string; hostName: string; name: string; domain: string; path: string; runPath: string; runtime: string; version: string; status: string; sslStatus: string; siteCount: number; ipAddress?: string; dedicatedIp: boolean; httpPort: number; httpsPort: number; createdAt: string; }
|
||||||
export type BatchOperation='create_users'|'create_hosts'|'assign_hosts'|'host_subscription'|'host_start'|'host_stop'|'host_password_reset'|'user_enable'|'user_disable';
|
export type BatchOperation='create_users'|'create_hosts'|'assign_hosts'|'host_subscription'|'host_start'|'host_stop'|'host_password_reset'|'user_enable'|'user_disable';
|
||||||
export interface BatchRow {credentialMode?:string;stopServices?:boolean;resumeOwnership?:boolean;name?:string;slug?:string;email?:string;displayName?:string;password?:string;accountId?:number;account?:string;owner?:string;tenantId?:number;hostId?:number;host?:string;ownershipVersion?:number;nodeId?:number;planId?:number;runtime?:string;version?:string;runPath?:string;expiresAt?:string|null;setExpiry?:boolean;autoSSL?:boolean;}
|
export interface BatchRow {loginName?:string;credentialMode?:string;stopServices?:boolean;resumeOwnership?:boolean;name?:string;slug?:string;email?:string;displayName?:string;password?:string;accountId?:number;account?:string;owner?:string;tenantId?:number;hostId?:number;host?:string;ownershipVersion?:number;nodeId?:number;planId?:number;runtime?:string;version?:string;runPath?:string;expiresAt?:string|null;setExpiry?:boolean;autoSSL?:boolean;}
|
||||||
export interface BatchPreviewRow {row:number;label:string;valid:boolean;detail:string;}
|
export interface BatchPreviewRow {row:number;label:string;valid:boolean;detail:string;}
|
||||||
export interface AdminBatchItem {id:number;batchId:number;row:number;label:string;state:string;resourceId?:number;detail:string;}
|
export interface AdminBatchItem {id:number;batchId:number;row:number;label:string;state:string;resourceId?:number;detail:string;}
|
||||||
export interface AdminBatch {id:number;administratorId:number;operation:BatchOperation;state:string;total:number;succeeded:number;failed:number;uncertain:number;pending:number;createdAt:string;finishedAt?:string;secretsExpireAt?:string;items?:AdminBatchItem[];}
|
export interface AdminBatch {id:number;administratorId:number;operation:BatchOperation;state:string;total:number;succeeded:number;failed:number;uncertain:number;pending:number;createdAt:string;finishedAt?:string;secretsExpireAt?:string;items?:AdminBatchItem[];}
|
||||||
@@ -35,6 +35,7 @@ export interface StartupSettings {entryFile:string;workDir:string;arguments:stri
|
|||||||
export interface WebsiteSettings {rewrite:string;redirectURL:string;redirectCode:number;forceHTTPS:boolean;index:string[];error404:string;error503:string;maintenance:boolean;}
|
export interface WebsiteSettings {rewrite:string;redirectURL:string;redirectCode:number;forceHTTPS:boolean;index:string[];error404:string;error503:string;maintenance:boolean;}
|
||||||
export interface HostMetric {sampledAt:string;cpuPercent:number;memoryBytes:number;processCount:number;storageBytes:number;databaseBytes:number;bandwidthBytes:number;}
|
export interface HostMetric {sampledAt:string;cpuPercent:number;memoryBytes:number;processCount:number;storageBytes:number;databaseBytes:number;bandwidthBytes:number;}
|
||||||
export interface FileEntry { name: string; path: string; directory: boolean; size: number; modified: string; }
|
export interface FileEntry { name: string; path: string; directory: boolean; size: number; modified: string; }
|
||||||
|
export interface UploadResult {name:string;size:number;success:boolean;status:number;error?:string}
|
||||||
export interface FileListing { path: string; entries: FileEntry[]; uploadLimit: number; }
|
export interface FileListing { path: string; entries: FileEntry[]; uploadLimit: number; }
|
||||||
export interface DatabaseSetup { host: string; port: number; name: string; user: string; password: string; }
|
export interface DatabaseSetup { host: string; port: number; name: string; user: string; password: string; }
|
||||||
export interface PanelSetup { url: string; apiKey: string; tlsInsecure: boolean; }
|
export interface PanelSetup { url: string; apiKey: string; tlsInsecure: boolean; }
|
||||||
@@ -193,6 +194,12 @@ export const api = {
|
|||||||
return response.text();
|
return response.text();
|
||||||
},
|
},
|
||||||
fileDownloadURL: (projectID: number, path: string) => fileURL(projectID, path, true),
|
fileDownloadURL: (projectID: number, path: string) => fileURL(projectID, path, true),
|
||||||
|
uploadFiles: async (projectID:number,path:string,files:File[],overwrite=false) => {
|
||||||
|
const body=new FormData();body.set('path',path);body.set('batch','true');body.set('overwrite',String(overwrite));if(files.some(file=>file.webkitRelativePath))body.set('relativePaths',JSON.stringify(files.map(file=>file.webkitRelativePath||file.name)));files.forEach(file=>body.append('file',file));
|
||||||
|
const response=await fetch(`/api/v1/projects/${projectID}/files`,{method:'POST',credentials:'same-origin',body});
|
||||||
|
if(!response.ok)throw await responseError(response);
|
||||||
|
return response.json() as Promise<{files:UploadResult[]}>;
|
||||||
|
},
|
||||||
uploadFile: async (projectID: number, path: string, file: File, overwrite = false) => {
|
uploadFile: async (projectID: number, path: string, file: File, overwrite = false) => {
|
||||||
const body = new FormData(); body.set('path', path); body.set('file', file); body.set('overwrite', String(overwrite));
|
const body = new FormData(); body.set('path', path); body.set('file', file); body.set('overwrite', String(overwrite));
|
||||||
const response = await fetch(`/api/v1/projects/${projectID}/files`, { method: 'POST', credentials: 'same-origin', body });
|
const response = await fetch(`/api/v1/projects/${projectID}/files`, { method: 'POST', credentials: 'same-origin', body });
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type {BatchOperation,BatchRow} from './api';
|
import type {BatchOperation,BatchRow} from './api';
|
||||||
|
|
||||||
const strings=new Set(['name','slug','email','displayName','password','account','owner','host','credentialMode','runtime','version','runPath']);
|
const strings=new Set(['loginName','name','slug','email','displayName','password','account','owner','host','credentialMode','runtime','version','runPath']);
|
||||||
const numbers=new Set(['accountId','tenantId','hostId','ownershipVersion','nodeId','planId']);
|
const numbers=new Set(['accountId','tenantId','hostId','ownershipVersion','nodeId','planId']);
|
||||||
const booleans=new Set(['stopServices','resumeOwnership','setExpiry','autoSSL']);
|
const booleans=new Set(['stopServices','resumeOwnership','setExpiry','autoSSL']);
|
||||||
|
|
||||||
@@ -28,7 +28,7 @@ export function parseBatchJSON(source:string,operation:BatchOperation):BatchRow[
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function batchTemplate(operation:BatchOperation){
|
export function batchTemplate(operation:BatchOperation){
|
||||||
const row:BatchRow=operation==='create_users'?{slug:'demo-0001',name:'示例用户',email:'demo-0001@vhost.ser888.cn',displayName:'示例用户',password:''}
|
const row:BatchRow=operation==='create_users'?{loginName:'demo-0001',email:'demo-0001@vhost.ser888.cn',displayName:'示例用户',password:''}
|
||||||
:operation==='create_hosts'?{name:'site-0001',owner:'',runtime:'PHP',version:'8.4',runPath:'/public',expiresAt:null,autoSSL:false}
|
:operation==='create_hosts'?{name:'site-0001',owner:'',runtime:'PHP',version:'8.4',runPath:'/public',expiresAt:null,autoSSL:false}
|
||||||
:operation==='user_enable'||operation==='user_disable'?{account:'demo-0001@vhost.ser888.cn'}
|
:operation==='user_enable'||operation==='user_disable'?{account:'demo-0001@vhost.ser888.cn'}
|
||||||
:operation==='assign_hosts'?{host:'sv0123456789',owner:'',credentialMode:'preserve',stopServices:true,resumeOwnership:false}
|
:operation==='assign_hosts'?{host:'sv0123456789',owner:'',credentialMode:'preserve',stopServices:true,resumeOwnership:false}
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ export function BatchComposer({operation,rows:selection=[],users,projects,plans,
|
|||||||
if(mode==='json'){if(!imported.length)throw new Error('请先导入 JSON 文件');return imported.map(record=>({...shared,...record}))}
|
if(mode==='json'){if(!imported.length)throw new Error('请先导入 JSON 文件');return imported.map(record=>({...shared,...record}))}
|
||||||
const max=operation==='create_users'?100:50;if(!Number.isInteger(count)||count<1||count>max||!Number.isInteger(start)||start<1||start>999999)throw new Error(`数量应为 1–${max},起始编号应为正整数`);
|
const max=operation==='create_users'?100:50;if(!Number.isInteger(count)||count<1||count>max||!Number.isInteger(start)||start<1||start>999999)throw new Error(`数量应为 1–${max},起始编号应为正整数`);
|
||||||
if(!/^[a-z0-9][a-z0-9-]{1,35}[a-z0-9]$/.test(prefix))throw new Error('名称前缀应为 3–37 位小写字母、数字或连字符');
|
if(!/^[a-z0-9][a-z0-9-]{1,35}[a-z0-9]$/.test(prefix))throw new Error('名称前缀应为 3–37 位小写字母、数字或连字符');
|
||||||
return Array.from({length:count},(_,index)=>{const serial=String(start+index).padStart(4,'0'),slug=`${prefix}-${serial}`;return operation==='create_users'?{slug,name:`${displayPrefix}${start+index}`,email:`${slug}@${emailDomain.trim()}`,displayName:`${displayPrefix}${start+index}`}:{...shared,name:slug}})
|
return Array.from({length:count},(_,index)=>{const serial=String(start+index).padStart(4,'0'),slug=`${prefix}-${serial}`;return operation==='create_users'?{loginName:slug,email:`${slug}@${emailDomain.trim()}`,displayName:`${displayPrefix}${start+index}`}:{...shared,name:slug}})
|
||||||
}
|
}
|
||||||
async function prepare(){setBusy(true);setError('');setPreview([]);try{const rows=buildRows();if(operation==='host_subscription'&&!plan&&!changeExpiry)throw new Error('请选择新套餐,或勾选修改到期时间');const result=await api.previewBatch(operation,rows);setPrepared(rows);setPreview(result.rows);setRequestKey(key())}catch(reason){setError(message(reason))}finally{setBusy(false)}}
|
async function prepare(){setBusy(true);setError('');setPreview([]);try{const rows=buildRows();if(operation==='host_subscription'&&!plan&&!changeExpiry)throw new Error('请选择新套餐,或勾选修改到期时间');const result=await api.previewBatch(operation,rows);setPrepared(rows);setPreview(result.rows);setRequestKey(key())}catch(reason){setError(message(reason))}finally{setBusy(false)}}
|
||||||
async function submit(){setBusy(true);setError('');try{const result=await api.createBatch(operation,prepared,requestKey);setJob(result.batch);setImported([]);setPrepared([])}catch(reason){setError(message(reason))}finally{setBusy(false)}}
|
async function submit(){setBusy(true);setError('');try{const result=await api.createBatch(operation,prepared,requestKey);setJob(result.batch);setImported([]);setPrepared([])}catch(reason){setError(message(reason))}finally{setBusy(false)}}
|
||||||
@@ -48,7 +48,7 @@ export function BatchComposer({operation,rows:selection=[],users,projects,plans,
|
|||||||
<fieldset className="batch-composer-fields" disabled={busy}><div className="batch-controls">
|
<fieldset className="batch-composer-fields" disabled={busy}><div className="batch-controls">
|
||||||
<label>输入方式<select value={mode} onChange={event=>{invalidate();setMode(event.target.value as typeof mode)}}>{creating?<option value="quantity">数量与名称前缀</option>:null}{selection.length?<option value="selection">已勾选的 {selection.length} 项</option>:null}<option value="json">JSON 模板导入</option></select></label>
|
<label>输入方式<select value={mode} onChange={event=>{invalidate();setMode(event.target.value as typeof mode)}}>{creating?<option value="quantity">数量与名称前缀</option>:null}{selection.length?<option value="selection">已勾选的 {selection.length} 项</option>:null}<option value="json">JSON 模板导入</option></select></label>
|
||||||
{mode==='quantity'?<><label>创建数量<input type="number" min="1" max={operation==='create_users'?100:50} value={count} onChange={e=>{invalidate();setCount(Number(e.target.value))}}/></label><label>名称前缀<input value={prefix} maxLength={37} onChange={e=>{invalidate();setPrefix(e.target.value)}}/></label><label>起始编号<input type="number" min="1" max="999999" value={start} onChange={e=>{invalidate();setStart(Number(e.target.value))}}/></label></>:null}
|
{mode==='quantity'?<><label>创建数量<input type="number" min="1" max={operation==='create_users'?100:50} value={count} onChange={e=>{invalidate();setCount(Number(e.target.value))}}/></label><label>名称前缀<input value={prefix} maxLength={37} onChange={e=>{invalidate();setPrefix(e.target.value)}}/></label><label>起始编号<input type="number" min="1" max="999999" value={start} onChange={e=>{invalidate();setStart(Number(e.target.value))}}/></label></>:null}
|
||||||
{operation==='create_users'&&mode==='quantity'?<><label>用户名称前缀<input value={displayPrefix} onChange={e=>{invalidate();setDisplayPrefix(e.target.value)}}/></label><label>登录邮箱后缀<input placeholder="vhost.ser888.cn" value={emailDomain} onChange={e=>{invalidate();setEmailDomain(e.target.value)}}/></label></>:null}
|
{operation==='create_users'&&mode==='quantity'?<><label>显示名称前缀<input value={displayPrefix} onChange={e=>{invalidate();setDisplayPrefix(e.target.value)}}/></label><label>登录邮箱后缀<input placeholder="vhost.ser888.cn" value={emailDomain} onChange={e=>{invalidate();setEmailDomain(e.target.value)}}/></label></>:null}
|
||||||
{operation==='create_hosts'||operation==='assign_hosts'?<label>{operation==='assign_hosts'?'目标用户':'绑定用户(可选)'}<select value={owner} onChange={e=>{invalidate();setOwner(Number(e.target.value))}}><option value="0">{operation==='assign_hosts'?'解绑用户,仅保留独立主机登录':'不绑定用户,独立主机账号登录'}</option>{users.filter(user=>user.status==='active').map(user=><option key={user.id} value={user.id}>{user.name} · {user.slug}</option>)}</select></label>:null}
|
{operation==='create_hosts'||operation==='assign_hosts'?<label>{operation==='assign_hosts'?'目标用户':'绑定用户(可选)'}<select value={owner} onChange={e=>{invalidate();setOwner(Number(e.target.value))}}><option value="0">{operation==='assign_hosts'?'解绑用户,仅保留独立主机登录':'不绑定用户,独立主机账号登录'}</option>{users.filter(user=>user.status==='active').map(user=><option key={user.id} value={user.id}>{user.name} · {user.slug}</option>)}</select></label>:null}
|
||||||
{operation==='assign_hosts'?<><label>凭据处理<select value={credentialMode} onChange={e=>{invalidate();setCredentialMode(e.target.value as 'preserve'|'reset')}}><option value="preserve">保留主机、FTP、数据库密码</option><option value="reset">随机重置三类密码</option></select></label><label className="batch-check"><input type="checkbox" checked={stopServices} onChange={e=>{invalidate();setStopServices(e.target.checked)}}/>变更前停止全部网站(默认)</label><label className="batch-check"><input type="checkbox" checked={resumeOwnership} onChange={e=>{invalidate();setResumeOwnership(e.target.checked)}}/>按原策略恢复未完成的归属变更</label></>:null}
|
{operation==='assign_hosts'?<><label>凭据处理<select value={credentialMode} onChange={e=>{invalidate();setCredentialMode(e.target.value as 'preserve'|'reset')}}><option value="preserve">保留主机、FTP、数据库密码</option><option value="reset">随机重置三类密码</option></select></label><label className="batch-check"><input type="checkbox" checked={stopServices} onChange={e=>{invalidate();setStopServices(e.target.checked)}}/>变更前停止全部网站(默认)</label><label className="batch-check"><input type="checkbox" checked={resumeOwnership} onChange={e=>{invalidate();setResumeOwnership(e.target.checked)}}/>按原策略恢复未完成的归属变更</label></>:null}
|
||||||
{operation==='create_hosts'?<><label>所属节点<select value={node} onChange={e=>{invalidate();setNode(Number(e.target.value))}}><option value="0" disabled>请选择节点</option>{nodes.map(item=><option value={item.id} key={item.id}>{item.name} · {item.rootDomain}</option>)}</select></label><label>运行环境<select value={runtime} onChange={e=>{invalidate();setRuntime(e.target.value as Runtime)}}>{Object.keys(catalog).map(name=><option key={name}>{name}</option>)}</select></label><label>运行版本<select aria-label="批量运行版本" value={version} onChange={e=>{invalidate();setVersion(e.target.value)}}>{(catalog[runtime]||[]).map(value=><option key={value}>{value}</option>)}</select></label><label>运行目录<input value={runPath} onChange={e=>{invalidate();setRunPath(e.target.value)}}/></label></>:null}
|
{operation==='create_hosts'?<><label>所属节点<select value={node} onChange={e=>{invalidate();setNode(Number(e.target.value))}}><option value="0" disabled>请选择节点</option>{nodes.map(item=><option value={item.id} key={item.id}>{item.name} · {item.rootDomain}</option>)}</select></label><label>运行环境<select value={runtime} onChange={e=>{invalidate();setRuntime(e.target.value as Runtime)}}>{Object.keys(catalog).map(name=><option key={name}>{name}</option>)}</select></label><label>运行版本<select aria-label="批量运行版本" value={version} onChange={e=>{invalidate();setVersion(e.target.value)}}>{(catalog[runtime]||[]).map(value=><option key={value}>{value}</option>)}</select></label><label>运行目录<input value={runPath} onChange={e=>{invalidate();setRunPath(e.target.value)}}/></label></>:null}
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ import {SystemScheduler} from './SystemScheduler';
|
|||||||
import { Activity, Boxes, ChevronDown, CloudCog, Cpu, Database, Globe2, KeyRound, LayoutGrid, LogOut, Menu, Mail, Network, Plus, Search, Server, Settings, ShieldCheck, UserRoundCog, UsersRound } from 'lucide-react';
|
import { Activity, Boxes, ChevronDown, CloudCog, Cpu, Database, Globe2, KeyRound, LayoutGrid, LogOut, Menu, Mail, Network, Plus, Search, Server, Settings, ShieldCheck, UserRoundCog, UsersRound } from 'lucide-react';
|
||||||
import { useCallback, useEffect, useState, type ReactNode } from 'react';
|
import { useCallback, useEffect, useState, type ReactNode } from 'react';
|
||||||
import { api, type AdminOverview, type AdminProject, type AdminSettings, type Credentials, type DomainResource, type PanelSite, type PlanInput, type Tenant, type User } from '../api';
|
import { api, type AdminOverview, type AdminProject, type AdminSettings, type Credentials, type DomainResource, type PanelSite, type PlanInput, type Tenant, type User } from '../api';
|
||||||
import { formatBytes } from '../format';
|
|
||||||
import type { Plan } from '../types';
|
import type { Plan } from '../types';
|
||||||
import { Brand } from './Brand';
|
import { Brand } from './Brand';
|
||||||
import { DNSCredentials } from './DNSCredentials';
|
import { DNSCredentials } from './DNSCredentials';
|
||||||
@@ -78,23 +77,72 @@ function Overview({ users, projects, domains, logs, navigate, review }: { users:
|
|||||||
|
|
||||||
function Users({users,query,setQuery,create,enter,bulk,refresh}:{refresh:()=>Promise<void>;users:Tenant[];query:string;setQuery:(value:string)=>void;create:()=>void;expiry:(id:number,value?:string)=>Promise<void>;enter?:(id:number)=>void;bulk:(selection:BatchSelection)=>void}){
|
function Users({users,query,setQuery,create,enter,bulk,refresh}:{refresh:()=>Promise<void>;users:Tenant[];query:string;setQuery:(value:string)=>void;create:()=>void;expiry:(id:number,value?:string)=>Promise<void>;enter?:(id:number)=>void;bulk:(selection:BatchSelection)=>void}){
|
||||||
const [editing,setEditing]=useState<Tenant>(),[deleting,setDeleting]=useState<Tenant>();
|
const [editing,setEditing]=useState<Tenant>(),[deleting,setDeleting]=useState<Tenant>();
|
||||||
const [selected,setSelected]=useState<number[]>([]);const list=users.filter(item=>`${item.name} ${item.slug}`.toLowerCase().includes(query.toLowerCase()));const ids=selected.filter(id=>users.some(item=>item.id===id));
|
const [selected,setSelected]=useState<number[]>([]);const list=users.filter(item=>`${item.name} ${item.slug} ${item.loginName||''}`.toLowerCase().includes(query.toLowerCase()));const ids=selected.filter(id=>users.some(item=>item.id===id));
|
||||||
const change=(id:number,checked:boolean)=>setSelected(current=>checked?[...new Set([...current,id])]:current.filter(value=>value!==id));
|
const change=(id:number,checked:boolean)=>setSelected(current=>checked?[...new Set([...current,id])]:current.filter(value=>value!==id));
|
||||||
const run=(operation:'user_enable'|'user_disable',targets=ids)=>bulk({operation,rows:targets.map(accountId=>({accountId}))});
|
const run=(operation:'user_enable'|'user_disable',targets=ids)=>bulk({operation,rows:targets.map(accountId=>({accountId}))});
|
||||||
return <><section className="admin-page"><Heading title="用户管理" description="用户可管理名下多台主机;每台主机可独立绑定或解绑用户。" action={<div className="row-actions"><button className="secondary" onClick={()=>bulk({operation:'create_users'})}>批量创建用户</button><button className="primary" onClick={create}><Plus size={16}/>新建用户</button></div>}/><div className="admin-toolbar"><SearchBox value={query} change={setQuery} placeholder="搜索用户名称或标识"/><span>共 {list.length} 个用户 · 已选 {ids.length} 个</span><button className="secondary" disabled={!ids.length} onClick={()=>run('user_enable')}>批量启用</button><button className="secondary" disabled={!ids.length} onClick={()=>run('user_disable')}>批量停用</button></div><Table><thead><tr><th><input type="checkbox" aria-label="选择全部用户" checked={list.length>0&&list.every(item=>ids.includes(item.id))} onChange={event=>setSelected(event.target.checked?list.map(item=>item.id):[])}/></th><th>用户</th><th>虚拟主机</th><th>状态</th><th>操作</th></tr></thead><tbody>{list.map(item=><tr key={item.id}><td><input type="checkbox" aria-label={'选择用户 '+item.slug} checked={ids.includes(item.id)} onChange={event=>change(item.id,event.target.checked)}/></td><td><b>{item.name}</b><small>{item.slug}</small></td><td>{item.projectCount}</td><td>{item.status==='active'?'正常':'已停用'}</td><td><div className="row-actions"><button className="table-link" aria-label={'编辑用户 '+item.slug} onClick={()=>setEditing(item)}>详情 / 编辑</button><button className="table-link" aria-label={'进入用户 '+item.slug} disabled={item.status!=='active'||!enter} onClick={()=>enter?.(item.id)}>进入用户</button><button className="table-link" aria-label={(item.status==='active'?'停用用户 ':'启用用户 ')+item.slug} onClick={()=>run(item.status==='active'?'user_disable':'user_enable',[item.id])}>{item.status==='active'?'停用':'启用'}</button><button className="table-link danger-text" aria-label={'删除用户 '+item.slug} disabled={item.projectCount>0} title={item.projectCount>0?'请先逐一解绑或转移全部主机,包括回收中的主机':undefined} onClick={()=>setDeleting(item)}>删除</button></div></td></tr>)}</tbody></Table></section>{deleting?<AccountEditor intent="delete" account={deleting} onClose={()=>setDeleting(undefined)} onChanged={refresh}/>:null}{editing?<AccountEditor account={editing} onClose={()=>setEditing(undefined)} onChanged={refresh}/>:null}</>;
|
return <><section className="admin-page"><Heading title="用户管理" description="用户可管理名下多台主机;每台主机可独立绑定或解绑用户。" action={<div className="row-actions"><button className="secondary" onClick={()=>bulk({operation:'create_users'})}>批量创建用户</button><button className="primary" onClick={create}><Plus size={16}/>新建用户</button></div>}/><div className="admin-toolbar"><SearchBox value={query} change={setQuery} placeholder="搜索用户名称或标识"/><span>共 {list.length} 个用户 · 已选 {ids.length} 个</span><button className="secondary" disabled={!ids.length} onClick={()=>run('user_enable')}>批量启用</button><button className="secondary" disabled={!ids.length} onClick={()=>run('user_disable')}>批量停用</button></div><Table><thead><tr><th><input type="checkbox" aria-label="选择全部用户" checked={list.length>0&&list.every(item=>ids.includes(item.id))} onChange={event=>setSelected(event.target.checked?list.map(item=>item.id):[])}/></th><th>用户</th><th>虚拟主机</th><th>状态</th><th>操作</th></tr></thead><tbody>{list.map(item=><tr key={item.id}><td><input type="checkbox" aria-label={'选择用户 '+item.slug} checked={ids.includes(item.id)} onChange={event=>change(item.id,event.target.checked)}/></td><td><b>{item.name}</b><small>{item.loginName||item.slug}</small></td><td>{item.projectCount}</td><td>{item.status==='active'?'正常':'已停用'}</td><td><div className="row-actions"><button className="table-link" aria-label={'编辑用户 '+item.slug} onClick={()=>setEditing(item)}>详情 / 编辑</button><button className="table-link" aria-label={'进入用户 '+item.slug} disabled={item.status!=='active'||!enter} onClick={()=>enter?.(item.id)}>进入用户</button><button className="table-link" aria-label={(item.status==='active'?'停用用户 ':'启用用户 ')+item.slug} onClick={()=>run(item.status==='active'?'user_disable':'user_enable',[item.id])}>{item.status==='active'?'停用':'启用'}</button><button className="table-link danger-text" aria-label={'删除用户 '+item.slug} disabled={item.projectCount>0} title={item.projectCount>0?'请先逐一解绑或转移全部主机,包括回收中的主机':undefined} onClick={()=>setDeleting(item)}>删除</button></div></td></tr>)}</tbody></Table></section>{deleting?<AccountEditor intent="delete" account={deleting} onClose={()=>setDeleting(undefined)} onChanged={refresh}/>:null}{editing?<AccountEditor account={editing} onClose={()=>setEditing(undefined)} onChanged={refresh}/>:null}</>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export function Plans({ plans, create,save,changed }: { plans: Plan[]; create: () => void;save:(input:PlanInput)=>Promise<void>;changed?:()=>Promise<void> }) {
|
export function Plans({ plans, create,save,changed }: { plans: Plan[]; create: () => void;save:(input:PlanInput)=>Promise<void>;changed?:()=>Promise<void> }) {
|
||||||
const [copy,setCopy]=useState<Plan>(),[removing,setRemoving]=useState<Plan>(),[confirmation,setConfirmation]=useState(''),[busy,setBusy]=useState(false),[error,setError]=useState(''),[hidden,setHidden]=useState<number[]>([]);
|
const [copy,setCopy]=useState<Plan>(),[removing,setRemoving]=useState<Plan>(),[confirmation,setConfirmation]=useState(''),[busy,setBusy]=useState(false),[error,setError]=useState(''),[hidden,setHidden]=useState<number[]>([]);
|
||||||
return <section className="admin-page"><Heading title="套餐管理" description="套餐按版本保存,已创建套餐配额只读;可复制套餐后调整额度,再为主机更换套餐,避免影响其他主机。" action={<button className="primary" onClick={create}><Plus size={16} />创建套餐</button>} /><div className="plan-cards">{plans.filter(p=>!hidden.includes(p.id)).map((plan) => <article key={plan.id}><header><span><Boxes size={19} /></span><h2>{plan.name}</h2></header><dl><div><dt>存储空间</dt><dd>{formatBytes(plan.storageBytes)}</dd></div><div><dt>数据库空间</dt><dd>{formatBytes(plan.databaseBytes)}</dd></div><div><dt>月流量</dt><dd>{formatBytes(plan.bandwidthBytes)}</dd></div><div><dt>HTTP / FTP 限速</dt><dd>{plan.bandwidthMbps ? `${plan.bandwidthMbps} Mbps` : '不限速'}</dd></div><div><dt>进程上限</dt><dd>{plan.processLimit}</dd></div><div><dt>每主机网站数</dt><dd>{plan.projectLimit}</dd></div><div><dt>FTP 账号</dt><dd>{plan.ftpLimit}</dd></div><div><dt>数据库</dt><dd>{plan.databaseLimit}</dd></div></dl><div className="row-actions"><button aria-label={'复制套餐 '+plan.name} onClick={()=>setCopy(plan)}>复制套餐</button><button aria-label={'删除套餐 '+plan.name} disabled={!!plan.deleteBlockedReason||plan.id===1} title={plan.deleteBlockedReason||(plan.id===1?'系统默认套餐不能删除':'删除未使用套餐')} onClick={()=>{setRemoving(plan);setConfirmation('');setError('')}}>删除</button></div>{plan.deleteBlockedReason||plan.id===1?<p className="field-hint">{plan.deleteBlockedReason||'系统默认套餐不能删除'}</p>:null}</article>)}</div>{copy?<PlanForm initial={copy} onClose={()=>setCopy(undefined)} onCreate={async input=>{await save(input);setCopy(undefined)}}/>:null}{removing?<ModalBackdrop><form className="tenant-modal" onSubmit={async e=>{e.preventDefault();if(busy||confirmation!==removing.name)return;setBusy(true);setError('');try{await api.deletePlan(removing.id,confirmation);setHidden(v=>[...v,removing.id]);setRemoving(undefined);await changed?.()}catch(e){setError(e instanceof Error?e.message:'删除套餐失败')}finally{setBusy(false)}}}><h2>删除未使用套餐</h2><p>仅允许删除未被主机或历史账号引用的套餐,此操作不能恢复。</p><label>输入套餐名称确认删除<input value={confirmation} onChange={e=>setConfirmation(e.target.value)} disabled={busy} placeholder={removing.name}/></label>{error?<p role="alert" className="form-error">{error}</p>:null}<div className="form-actions"><button type="button" disabled={busy} onClick={()=>setRemoving(undefined)}>取消</button><button className="primary danger-confirm" disabled={busy||confirmation!==removing.name}>{busy?'正在删除…':'确认删除套餐'}</button></div></form></ModalBackdrop>:null}</section>; }
|
return <section className="admin-page"><Heading title="套餐管理" description="套餐按版本保存,已创建套餐配额只读;可复制套餐后调整额度,再为主机更换套餐,避免影响其他主机。" action={<button className="primary" onClick={create}><Plus size={16} />创建套餐</button>} /><div className="plan-cards">{plans.filter(p=>!hidden.includes(p.id)).map((plan) => <article key={plan.id}><header><span><Boxes size={19} /></span><h2>{plan.name}</h2></header><dl><div><dt>存储空间</dt><dd>{`${(plan.storageBytes / planMB).toLocaleString('zh-CN', { maximumFractionDigits: 3 })} MB`}</dd></div><div><dt>数据库空间</dt><dd>{`${(plan.databaseBytes / planMB).toLocaleString('zh-CN', { maximumFractionDigits: 3 })} MB`}</dd></div><div><dt>月流量</dt><dd>{`${(plan.bandwidthBytes / planGB).toLocaleString('zh-CN', { maximumFractionDigits: 6 })} GB`}</dd></div><div><dt>HTTP / FTP 限速</dt><dd>{plan.bandwidthMbps ? `${plan.bandwidthMbps} Mbps` : '不限速'}</dd></div><div><dt>进程上限</dt><dd>{plan.processLimit}</dd></div><div><dt>每主机网站数</dt><dd>{plan.projectLimit}</dd></div><div><dt>FTP 账号</dt><dd>{plan.ftpLimit}</dd></div><div><dt>数据库</dt><dd>{plan.databaseLimit}</dd></div></dl><div className="row-actions"><button aria-label={'复制套餐 '+plan.name} onClick={()=>setCopy(plan)}>复制套餐</button><button aria-label={'删除套餐 '+plan.name} disabled={!!plan.deleteBlockedReason||plan.id===1} title={plan.deleteBlockedReason||(plan.id===1?'系统默认套餐不能删除':'删除未使用套餐')} onClick={()=>{setRemoving(plan);setConfirmation('');setError('')}}>删除</button></div>{plan.deleteBlockedReason||plan.id===1?<p className="field-hint">{plan.deleteBlockedReason||'系统默认套餐不能删除'}</p>:null}</article>)}</div>{copy?<PlanForm initial={copy} onClose={()=>setCopy(undefined)} onCreate={async input=>{await save(input);setCopy(undefined)}}/>:null}{removing?<ModalBackdrop><form className="tenant-modal" onSubmit={async e=>{e.preventDefault();if(busy||confirmation!==removing.name)return;setBusy(true);setError('');try{await api.deletePlan(removing.id,confirmation);setHidden(v=>[...v,removing.id]);setRemoving(undefined);await changed?.()}catch(e){setError(e instanceof Error?e.message:'删除套餐失败')}finally{setBusy(false)}}}><h2>删除未使用套餐</h2><p>仅允许删除未被主机或历史账号引用的套餐,此操作不能恢复。</p><label>输入套餐名称确认删除<input value={confirmation} onChange={e=>setConfirmation(e.target.value)} disabled={busy} placeholder={removing.name}/></label>{error?<p role="alert" className="form-error">{error}</p>:null}<div className="form-actions"><button type="button" disabled={busy} onClick={()=>setRemoving(undefined)}>取消</button><button className="primary danger-confirm" disabled={busy||confirmation!==removing.name}>{busy?'正在删除…':'确认删除套餐'}</button></div></form></ModalBackdrop>:null}</section>; }
|
||||||
|
|
||||||
function Lifecycle({projects,onManage}:{projects:AdminProject[];onManage:()=>void}){return <section className="admin-page"><Heading title="到期与回收" description="调度器自动处理到期和清理;恢复主机、修改套餐或到期时间请进入虚拟主机管理。宽限 3 天,回收 7 天,清理后的备份保留 14 天。" action={<button className="secondary" onClick={onManage}>管理主机 / 恢复</button>}/><Table><thead><tr><th>虚拟主机</th><th>用户 / 节点</th><th>当前阶段</th><th>到期时间</th></tr></thead><tbody>{projects.map(p=><tr key={p.id}><td>{p.hostName}</td><td>{p.tenantName} / #{p.nodeId}</td><td><LifecycleBadge state={p.lifecycleState as Tenant['lifecycleState']}/></td><td>{p.expiresAt?dateText(p.expiresAt):"长期使用"}</td></tr>)}</tbody></Table></section>}
|
function Lifecycle({projects,onManage}:{projects:AdminProject[];onManage:()=>void}){return <section className="admin-page"><Heading title="到期与回收" description="调度器自动处理到期和清理;恢复主机、修改套餐或到期时间请进入虚拟主机管理。宽限 3 天,回收 7 天,清理后的备份保留 14 天。" action={<button className="secondary" onClick={onManage}>管理主机 / 恢复</button>}/><Table><thead><tr><th>虚拟主机</th><th>用户 / 节点</th><th>当前阶段</th><th>到期时间</th></tr></thead><tbody>{projects.map(p=><tr key={p.id}><td>{p.hostName}</td><td>{p.tenantName} / #{p.nodeId}</td><td><LifecycleBadge state={p.lifecycleState as Tenant['lifecycleState']}/></td><td>{p.expiresAt?dateText(p.expiresAt):"长期使用"}</td></tr>)}</tbody></Table></section>}
|
||||||
|
|
||||||
function Table({ children }: { children: ReactNode }) { return <div className="admin-table-v2"><table>{children}</table></div>; }
|
function Table({ children }: { children: ReactNode }) { return <div className="admin-table-v2"><table>{children}</table></div>; }
|
||||||
|
|
||||||
function UserForm({ plans, onClose, onCreate }: { plans: Plan[]; onClose: () => void; onCreate: (input: Record<string, unknown>) => Promise<void> }) { const [busy, setBusy] = useState(false); const [error, setError] = useState(''); return <ModalBackdrop className="modal-backdrop"><form className="tenant-modal" onSubmit={async (event) => { event.preventDefault(); setBusy(true); const form = new FormData(event.currentTarget); try { await onCreate({ slug: form.get('slug'), name: form.get('name'), email: form.get('email'), displayName: form.get('displayName'), password: form.get('password'), planId: plans[0]?.id }); } catch (reason) { setError(reason instanceof Error ? reason.message : '创建失败'); setBusy(false); } }}><h2>创建用户</h2><p>创建登录账号后,可继续为该用户新增多个虚拟主机。</p><label>用户名称<input name="name" maxLength={120} required /></label><label>用户标识<input name="slug" pattern="[a-z0-9\-]{3,48}" required /></label><label>联系人姓名<input name="displayName" minLength={2} maxLength={80} required /></label><label>登录邮箱<input name="email" type="email" required /></label><label>初始密码<input name="password" type="password" minLength={12} required /></label>{error ? <p className="form-error">{error}</p> : null}<div className="form-actions"><button type="button" className="secondary" onClick={onClose}>取消</button><button className="primary" disabled={busy || !plans.length}>{busy ? '创建中…' : '创建用户'}</button></div></form></ModalBackdrop>; }
|
export function UserForm({ plans, onClose, onCreate }: { plans: Plan[]; onClose: () => void; onCreate: (input: Record<string, unknown>) => Promise<void> }) { const [busy, setBusy] = useState(false); const [error, setError] = useState(''); return <ModalBackdrop className="modal-backdrop"><form className="tenant-modal" onSubmit={async (event) => { event.preventDefault(); setBusy(true); const form = new FormData(event.currentTarget); try { await onCreate({ loginName: form.get('loginName'), name: form.get('displayName'), email: form.get('email'), displayName: form.get('displayName'), password: form.get('password'), planId: plans[0]?.id }); } catch (reason) { setError(reason instanceof Error ? reason.message : '创建失败'); setBusy(false); } }}><h2>创建用户</h2><p>创建登录账号后,可继续为该用户新增多个虚拟主机。</p><label>登录账号<input name="loginName" pattern="[a-z0-9][a-z0-9\-]{1,46}[a-z0-9]" minLength={3} maxLength={48} autoComplete="off" required /></label><label>显示名称<input name="displayName" minLength={2} maxLength={80} required /></label><label>登录邮箱<input name="email" type="email" required /></label><label>初始密码<input name="password" type="password" minLength={12} maxLength={72} required /></label>{error ? <p className="form-error" role="alert">{error}</p> : null}<div className="form-actions"><button type="button" className="secondary" onClick={onClose}>取消</button><button className="primary" disabled={busy || !plans.length}>{busy ? '创建中…' : '创建用户'}</button></div></form></ModalBackdrop>; }
|
||||||
export function PlanForm({ onClose, onCreate,initial }: { initial?:Plan; onClose: () => void; onCreate: (input: PlanInput) => Promise<void> }) { const [busy, setBusy] = useState(false);const [error,setError]=useState(''); return <ModalBackdrop className="modal-backdrop"><form className="tenant-modal plan-modal" onSubmit={async (event) => { event.preventDefault(); setBusy(true);setError(''); const form = new FormData(event.currentTarget); const gib = 1024 ** 3; try { await onCreate({ name: String(form.get('name')), storageBytes: Number(form.get('storageGB')) * gib, databaseBytes: Number(form.get('databaseGB')) * gib, bandwidthBytes: Number(form.get('bandwidthGB')) * gib, bandwidthMbps: Number(form.get('bandwidthMbps')), processLimit: Number(form.get('processLimit')), projectLimit: Number(form.get('projectLimit')), ftpLimit: Number(form.get('ftpLimit')), databaseLimit: Number(form.get('databaseLimit')) }); } catch(e){setError(e instanceof Error?e.message:'套餐保存失败')} finally { setBusy(false); } }}><h2>{initial?'复制资源套餐':'创建资源套餐'}</h2><label>套餐名称<input name="name" defaultValue={initial?initial.name+' 副本':''} maxLength={80} required /></label><div className="plan-form-grid">{[['storageGB', '存储空间(GB)', initial?initial.storageBytes/1024**3:50], ['databaseGB', '数据库空间(GB)', initial?initial.databaseBytes/1024**3:20], ['bandwidthGB', '月流量(GB)', initial?initial.bandwidthBytes/1024**3:500], ['bandwidthMbps', 'HTTP 每请求 / FTP 每会话限速(Mbps,0 不限)', initial?.bandwidthMbps??0], ['processLimit', '进程数', initial?.processLimit??100], ['projectLimit', '每主机网站数', initial?.projectLimit??10], ['ftpLimit', 'FTP 账号数', initial?.ftpLimit??10], ['databaseLimit', '数据库数', initial?.databaseLimit??10]].map(([name, label, value]) => <label key={String(name)}>{label}<input name={String(name)} type="number" step={String(name).endsWith('GB')?'any':1} min={name === 'bandwidthMbps' ? 0 : String(name).endsWith('GB')?1/1024:1} max={name === 'bandwidthMbps' ? 10000 : undefined} defaultValue={value} required /></label>)}</div>{error?<p className="form-error" role="alert">{error}</p>:null}<div className="form-actions"><button type="button" className="secondary" onClick={onClose}>取消</button><button className="primary" disabled={busy}>{busy ? '创建中…' : initial?'保存为新套餐':'创建套餐'}</button></div></form></ModalBackdrop>; }
|
const planMB = 1024 ** 2;
|
||||||
|
const planGB = 1024 ** 3;
|
||||||
|
|
||||||
|
export function PlanForm({ onClose, onCreate, initial }: { initial?: Plan; onClose: () => void; onCreate: (input: PlanInput) => Promise<void> }) {
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
const fields = [
|
||||||
|
{ name: 'storageMB', label: '存储空间(MB)', value: initial ? initial.storageBytes / planMB : 50 * 1024, min: 1, max: 1024 ** 3, capacity: true },
|
||||||
|
{ name: 'databaseMB', label: '数据库空间(MB)', value: initial ? initial.databaseBytes / planMB : 20 * 1024, min: 1, max: 1024 ** 3, capacity: true },
|
||||||
|
{ name: 'bandwidthGB', label: '月流量(GB)', value: initial ? initial.bandwidthBytes / planGB : 500, min: 1 / 1024, max: 1024 ** 2, capacity: true },
|
||||||
|
{ name: 'bandwidthMbps', label: 'HTTP 每请求 / FTP 每会话限速(Mbps,0 不限)', value: initial?.bandwidthMbps ?? 0, min: 0, max: 10000 },
|
||||||
|
{ name: 'processLimit', label: '进程数', value: initial?.processLimit ?? 100, min: 1, max: 100000 },
|
||||||
|
{ name: 'projectLimit', label: '每主机网站数', value: initial?.projectLimit ?? 10, min: 1, max: 10000 },
|
||||||
|
{ name: 'ftpLimit', label: 'FTP 账号数', value: initial?.ftpLimit ?? 10, min: 1, max: 10000 },
|
||||||
|
{ name: 'databaseLimit', label: '数据库数', value: initial?.databaseLimit ?? 10, min: 1, max: 10000 },
|
||||||
|
];
|
||||||
|
return <ModalBackdrop className="modal-backdrop"><form className="tenant-modal plan-modal" onSubmit={async (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
if (busy || !event.currentTarget.reportValidity()) return;
|
||||||
|
const form = new FormData(event.currentTarget);
|
||||||
|
setBusy(true);
|
||||||
|
setError('');
|
||||||
|
try {
|
||||||
|
const capacity = (name: string, unit: number) => {
|
||||||
|
const bytes = Math.round(Number(form.get(name)) * unit);
|
||||||
|
if (!Number.isSafeInteger(bytes) || bytes < planMB || bytes > 1024 ** 5) throw new Error('资源容量必须在 1 MB 至 1 PB 之间');
|
||||||
|
return bytes;
|
||||||
|
};
|
||||||
|
await onCreate({
|
||||||
|
name: String(form.get('name')),
|
||||||
|
storageBytes: capacity('storageMB', planMB),
|
||||||
|
databaseBytes: capacity('databaseMB', planMB),
|
||||||
|
bandwidthBytes: capacity('bandwidthGB', planGB),
|
||||||
|
bandwidthMbps: Number(form.get('bandwidthMbps')),
|
||||||
|
processLimit: Number(form.get('processLimit')),
|
||||||
|
projectLimit: Number(form.get('projectLimit')),
|
||||||
|
ftpLimit: Number(form.get('ftpLimit')),
|
||||||
|
databaseLimit: Number(form.get('databaseLimit')),
|
||||||
|
});
|
||||||
|
} catch (reason) {
|
||||||
|
setError(reason instanceof Error ? reason.message : '套餐保存失败');
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}}><h2>{initial ? '复制资源套餐' : '创建资源套餐'}</h2><label>套餐名称<input name="name" defaultValue={initial ? initial.name + ' 副本' : ''} maxLength={80} required /></label>
|
||||||
|
<div className="plan-form-grid">{fields.map(field => <label key={field.name}>{field.label}<input name={field.name} type="number" step={field.capacity ? 'any' : 1} min={field.min} max={field.max} defaultValue={field.value} required disabled={busy} /></label>)}</div>
|
||||||
|
{error ? <p className="form-error" role="alert">{error}</p> : null}
|
||||||
|
<div className="form-actions"><button type="button" className="secondary" disabled={busy} onClick={onClose}>取消</button><button className="primary" disabled={busy}>{busy ? '创建中…' : initial ? '保存为新套餐' : '创建套餐'}</button></div>
|
||||||
|
</form></ModalBackdrop>;
|
||||||
|
}
|
||||||
|
|
||||||
function AdoptionForm({users,plans,onClose,onComplete}:{users:Tenant[];plans:Plan[];onClose:()=>void;onComplete:()=>Promise<void>}){return <HostProvisioning adopt users={users} plans={plans} onClose={onClose} onComplete={onComplete}/>}
|
function AdoptionForm({users,plans,onClose,onComplete}:{users:Tenant[];plans:Plan[];onClose:()=>void;onComplete:()=>Promise<void>}){return <HostProvisioning adopt users={users} plans={plans} onClose={onClose} onComplete={onComplete}/>}
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { Building2, ChevronDown, Menu, UserRound,LogOut } from 'lucide-react';
|
import { ArrowLeft, Building2, ChevronDown, Menu, UserRound,LogOut } from 'lucide-react';
|
||||||
import { useState, type ReactNode } from 'react';
|
import { useState, type ReactNode } from 'react';
|
||||||
import { Brand } from './Brand';
|
import { Brand } from './Brand';
|
||||||
import { Sidebar } from './Sidebar';
|
import { Sidebar } from './Sidebar';
|
||||||
import {useNavigationOverlay} from './overlay';
|
import {useNavigationOverlay} from './overlay';
|
||||||
|
|
||||||
export function AppShell({ page, tenantName, displayName, hostScoped = false, onNavigate, onSecurity,onLogout, children }: { page: string; tenantName: string; displayName: string; hostScoped?: boolean; onNavigate: (page: string) => void; onSecurity: () => void;onLogout?:()=>void; children: ReactNode }) {
|
export function AppShell({ page, tenantName, displayName, hostScoped = false, hostView = false, hostName, onBack, onNavigate, onSecurity,onLogout, children }: { page: string; tenantName: string; displayName: string; hostScoped?: boolean; hostView?: boolean; hostName?:string; onBack?:()=>void; onNavigate: (page: string) => void; onSecurity: () => void;onLogout?:()=>void; children: ReactNode }) {
|
||||||
const [mobileNavOpen, setMobileNavOpen] = useState(false);
|
const [mobileNavOpen, setMobileNavOpen] = useState(false);
|
||||||
useNavigationOverlay(mobileNavOpen,setMobileNavOpen);
|
useNavigationOverlay(mobileNavOpen,setMobileNavOpen);
|
||||||
function navigate(pageName: string) {
|
function navigate(pageName: string) {
|
||||||
@@ -16,15 +16,15 @@ export function AppShell({ page, tenantName, displayName, hostScoped = false, on
|
|||||||
<header className="topbar">
|
<header className="topbar">
|
||||||
<button className="mobile-menu" aria-label={mobileNavOpen ? '关闭导航' : '打开导航'} aria-expanded={mobileNavOpen} onClick={() => setMobileNavOpen((value) => !value)}><Menu size={21} /></button>
|
<button className="mobile-menu" aria-label={mobileNavOpen ? '关闭导航' : '打开导航'} aria-expanded={mobileNavOpen} onClick={() => setMobileNavOpen((value) => !value)}><Menu size={21} /></button>
|
||||||
<Brand />
|
<Brand />
|
||||||
<div className="tenant-switch"><Building2 size={17} /><span>{tenantName}</span></div>
|
<div className="tenant-switch"><Building2 size={17} /><span>{hostView || hostScoped ? hostName : tenantName}</span></div>
|
||||||
<div className="top-actions">
|
<div className="top-actions">
|
||||||
{onLogout?<button className="icon-button" aria-label="退出登录" onClick={onLogout}><LogOut size={18}/></button>:null}
|
{onLogout?<button className="icon-button" aria-label="退出登录" onClick={onLogout}><LogOut size={18}/></button>:null}
|
||||||
<button className="user-menu" onClick={onSecurity} aria-label="账号安全"><span className="avatar"><UserRound size={17} /></span><span>{displayName}</span><ChevronDown size={15} /></button>
|
<button className="user-menu" onClick={onSecurity} aria-label="账号安全"><span className="avatar"><UserRound size={17} /></span><span>{displayName}</span><ChevronDown size={15} /></button>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
{mobileNavOpen ? <button className="mobile-nav-backdrop" aria-label="关闭导航" onClick={() => setMobileNavOpen(false)} /> : null}
|
{mobileNavOpen ? <button className="mobile-nav-backdrop" aria-label="关闭导航" onClick={() => setMobileNavOpen(false)} /> : null}
|
||||||
<div className={mobileNavOpen ? 'mobile-sidebar open' : 'mobile-sidebar'}><Sidebar page={page} hostScoped={hostScoped} onNavigate={navigate} /></div>
|
<div className={mobileNavOpen ? 'mobile-sidebar open' : 'mobile-sidebar'}><Sidebar page={page} hostScoped={hostScoped} hostView={hostView} onNavigate={navigate} /></div>
|
||||||
<main className="main-content">{children}</main>
|
<main className="main-content">{onBack ? <div className="host-context-bar"><span>目前主机 <b>{hostName}</b></span><button className="secondary" onClick={()=>{setMobileNavOpen(false);onBack()}}><ArrowLeft size={15}/>返回用户总览</button></div> : null}{children}</main>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import {randomHostName} from '../hostName';
|
||||||
import { ArrowLeft, Box, Database, HardDrive, Network, ShieldCheck } from 'lucide-react';
|
import { ArrowLeft, Box, Database, HardDrive, Network, ShieldCheck } from 'lucide-react';
|
||||||
import { useMemo, useState } from 'react';
|
import { useMemo, useState } from 'react';
|
||||||
import { formatBytes } from '../format';
|
import { formatBytes } from '../format';
|
||||||
@@ -18,7 +19,7 @@ interface CreateProjectProps {
|
|||||||
|
|
||||||
export function CreateProject({ runtimeVersions, rootDomain, projectRoot, plan, domainApproval, onCancel, onSubmit }: CreateProjectProps) {
|
export function CreateProject({ runtimeVersions, rootDomain, projectRoot, plan, domainApproval, onCancel, onSubmit }: CreateProjectProps) {
|
||||||
const initialRuntime = runtimes.find((runtime) => runtimeVersions[runtime]?.length) ?? 'PHP';
|
const initialRuntime = runtimes.find((runtime) => runtimeVersions[runtime]?.length) ?? 'PHP';
|
||||||
const [draft, setDraft] = useState<ProjectDraft>({ name: 'blog-demo', runtime: initialRuntime, version: runtimeVersions[initialRuntime]?.[0] ?? '', runPath: '/', customDomain: '', autoSSL: true });
|
const [draft, setDraft] = useState<ProjectDraft>(() => ({ name: randomHostName(), runtime: initialRuntime, version: runtimeVersions[initialRuntime]?.[0] ?? '', runPath: '/', customDomain: '', autoSSL: true }));
|
||||||
const safeName = useMemo(() => draft.name.toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, ''), [draft.name]);
|
const safeName = useMemo(() => draft.name.toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, ''), [draft.name]);
|
||||||
const assignedDomain = `<随机主机名>.${rootDomain}`;
|
const assignedDomain = `<随机主机名>.${rootDomain}`;
|
||||||
const root = `${projectRoot.replace(/\/+$/, '')}/<随机主机名>`;
|
const root = `${projectRoot.replace(/\/+$/, '')}/<随机主机名>`;
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ export function FileManager({ projects, initialProjectID, live = true }: { proje
|
|||||||
const previousInitialProject = useRef(initialProjectID);
|
const previousInitialProject = useRef(initialProjectID);
|
||||||
const [entries, setEntries] = useState<FileEntry[]>([]);
|
const [entries, setEntries] = useState<FileEntry[]>([]);
|
||||||
const [uploadLimit, setUploadLimit] = useState(20 * 1024 ** 2);
|
const [uploadLimit, setUploadLimit] = useState(20 * 1024 ** 2);
|
||||||
|
const [uploadStatus,setUploadStatus]=useState('');
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
const requestVersion = useRef(0);
|
const requestVersion = useRef(0);
|
||||||
@@ -27,6 +28,9 @@ export function FileManager({ projects, initialProjectID, live = true }: { proje
|
|||||||
async function showTrash(){const trashVersion=++trashRequest.current;const version=requestVersion.current;setBusy(true);setError('');try{const result=live?(await api.fileTrash(projectID)).entries:[];if(version===requestVersion.current&&trashVersion===trashRequest.current)setTrashEntries(result)}catch(e){if(version===requestVersion.current)setError(message(e,'读取回收站失败'))}finally{if(version===requestVersion.current)setBusy(false)}}
|
async function showTrash(){const trashVersion=++trashRequest.current;const version=requestVersion.current;setBusy(true);setError('');try{const result=live?(await api.fileTrash(projectID)).entries:[];if(version===requestVersion.current&&trashVersion===trashRequest.current)setTrashEntries(result)}catch(e){if(version===requestVersion.current)setError(message(e,'读取回收站失败'))}finally{if(version===requestVersion.current)setBusy(false)}}
|
||||||
async function perform(){if(!operation||busy)return;const target=operation.action==='mkdir'?operation.path:operation.to;if(entries.some(entry=>entry.path===target)){setError(operation.action==='move'&&operation.path===target?'源路径与目标路径不能相同':'目标已存在,请更换目标路径;原文件不会被覆盖');return}setBusy(true);setError('');try{if(live)await api.fileAction(projectID,operation.action,operation.path,operation.to);setOperation(null);if(trashEntries)await showTrash();await load()}catch(e){setError(message(e,'文件操作失败'))}finally{setBusy(false)}}
|
async function perform(){if(!operation||busy)return;const target=operation.action==='mkdir'?operation.path:operation.to;if(entries.some(entry=>entry.path===target)){setError(operation.action==='move'&&operation.path===target?'源路径与目标路径不能相同':'目标已存在,请更换目标路径;原文件不会被覆盖');return}setBusy(true);setError('');try{if(live)await api.fileAction(projectID,operation.action,operation.path,operation.to);setOperation(null);if(trashEntries)await showTrash();await load()}catch(e){setError(message(e,'文件操作失败'))}finally{setBusy(false)}}
|
||||||
const uploadRef = useRef<HTMLInputElement>(null);
|
const uploadRef = useRef<HTMLInputElement>(null);
|
||||||
|
const folderRef = useRef<HTMLInputElement>(null);
|
||||||
|
const [folderSupported,setFolderSupported]=useState(true);
|
||||||
|
useEffect(()=>{setFolderSupported('webkitdirectory' in document.createElement('input'))},[]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (initialProjectID && initialProjectID !== previousInitialProject.current && projects.some((project) => project.id === initialProjectID)) {
|
if (initialProjectID && initialProjectID !== previousInitialProject.current && projects.some((project) => project.id === initialProjectID)) {
|
||||||
@@ -59,21 +63,35 @@ export function FileManager({ projects, initialProjectID, live = true }: { proje
|
|||||||
finally { if (current()) setBusy(false); }
|
finally { if (current()) setBusy(false); }
|
||||||
}, [live, path, projectID]);
|
}, [live, path, projectID]);
|
||||||
|
|
||||||
useEffect(() => { trashRequest.current++;setTrashEntries(null); setEditor(null); setOperation(null); void load(); return () => { requestVersion.current++;trashRequest.current++; }; }, [load]);
|
useEffect(() => { trashRequest.current++;setTrashEntries(null); setEditor(null); setOperation(null); setUploadStatus(''); void load(); return () => { requestVersion.current++;trashRequest.current++; }; }, [load]);
|
||||||
|
|
||||||
async function upload(file: File) {
|
async function upload(files: File[]) {
|
||||||
if (file.size > uploadLimit) { setError(`单文件不能超过 ${formatBytes(uploadLimit)}`); return; }
|
if(busy||files.length===0)return;
|
||||||
if (!live) { setError('预览模式不会写入文件'); return; }
|
setError('');setUploadStatus('');
|
||||||
setBusy(true); setError('');
|
const reset=()=>{if(uploadRef.current)uploadRef.current.value='';if(folderRef.current)folderRef.current.value=''};
|
||||||
|
if(files.length>100){setError('每批最多上传 100 个文件');reset();return}
|
||||||
|
if(files.some(file=>file.size>uploadLimit)){setError(`单文件不能超过 ${formatBytes(uploadLimit)}`);reset();return}
|
||||||
|
if(files.reduce((sum,file)=>sum+file.size,0)>30*1024**2){setError('单批上传总大小不能超过 30 MB');reset();return}
|
||||||
|
if(new Set(files.map(uploadFilePath)).size!==files.length){setError('本批存在同名文件,请分批上传');reset();return}
|
||||||
|
if(!live){setError('演示模式不会写入文件');reset();return}
|
||||||
|
const context=currentContext.current;
|
||||||
|
setBusy(true);setUploadStatus(`正在上传 ${files.length} 个文件…`);
|
||||||
try {
|
try {
|
||||||
await api.uploadFile(projectID, path, file);
|
let results=(await api.uploadFiles(projectID,path,files)).files;
|
||||||
|
if(currentContext.current!==context)return;
|
||||||
|
const conflicts=results.filter(result=>!result.success&&result.status===409);
|
||||||
|
if(conflicts.length&&await confirm(`以下 ${conflicts.length} 个同名文件已存在,是否覆盖?\n${conflicts.map(file=>file.name).join('、')}`,{title:'覆盖文件',confirmLabel:'覆盖同名文件',danger:true})){
|
||||||
|
const names=new Set(conflicts.map(result=>result.name));
|
||||||
|
const retried=(await api.uploadFiles(projectID,path,files.filter(file=>names.has(uploadFilePath(file))),true)).files;
|
||||||
|
results=results.filter(result=>!names.has(result.name)).concat(retried);
|
||||||
|
}
|
||||||
|
if(currentContext.current!==context)return;
|
||||||
|
const failed=results.filter(result=>!result.success);
|
||||||
await load();
|
await load();
|
||||||
} catch (reason) {
|
setUploadStatus(`上传完成:成功 ${results.length-failed.length} 个,失败或跳过 ${failed.length} 个`);
|
||||||
if ((reason as { status?: number })?.status === 409 && await confirm('同名文件已存在,是否覆盖?',{title:'覆盖文件',confirmLabel:'覆盖文件',danger:true})) {
|
if(failed.length)setError(failed.map(result=>`${result.name}:${result.error||'上传失败'}`).join(';'));
|
||||||
try { await api.uploadFile(projectID, path, file, true); await load(); }
|
} catch(reason){if(currentContext.current===context){await load();setError(message(reason,'上传失败,请刷新目录核对文件'));setUploadStatus('')}}
|
||||||
catch (retryReason) { setError(message(retryReason, '上传失败')); }
|
finally{setBusy(false);reset()}
|
||||||
} else setError(message(reason, '上传失败'));
|
|
||||||
} finally { setBusy(false); if (uploadRef.current) uploadRef.current.value = ''; }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function edit(entry: FileEntry) {
|
async function edit(entry: FileEntry) {
|
||||||
@@ -111,13 +129,15 @@ export function FileManager({ projects, initialProjectID, live = true }: { proje
|
|||||||
return <div className="page file-page">{confirmation}
|
return <div className="page file-page">{confirmation}
|
||||||
<div className="page-heading"><h1>文件管理</h1></div>
|
<div className="page-heading"><h1>文件管理</h1></div>
|
||||||
<section className="file-panel">
|
<section className="file-panel">
|
||||||
<div className="file-toolbar"><select aria-label="选择虚拟主机" value={projectID} onChange={(event) => { setProjectID(Number(event.target.value)); setPath(''); setError(''); }} disabled={loading}>{projects.map((project) => <option key={project.id} value={project.id}>{project.name} · {project.domain}</option>)}</select><div className="file-actions"><button className="secondary" disabled={loading} onClick={()=>setOperation({action:"mkdir",path:joinPath(path,"new-directory"),to:""})}>新建目录</button><button className="secondary" disabled={loading} onClick={()=>void showTrash()}>回收站</button><button className="secondary" disabled={loading} onClick={() => {setError('');setEditor({ path: joinPath(path, 'new-file.txt'), content: '', isNew: true })}}><Plus size={15} />新建文本</button><button className="secondary" onClick={() => uploadRef.current?.click()} disabled={loading}><Upload size={15} />上传文件</button><button className="secondary" onClick={() => void emptyTrash()} disabled={loading}><Trash2 size={15} />清空回收站</button><input ref={uploadRef} type="file" hidden onChange={(event) => { const file = event.target.files?.[0]; if (file) void upload(file); }} /><button className="icon-button" onClick={() => void load()} disabled={loading} aria-label="刷新文件"><RefreshCw size={16} /></button></div></div>
|
<div className="file-toolbar"><select aria-label="选择虚拟主机" value={projectID} onChange={(event) => { setProjectID(Number(event.target.value)); setPath(''); setError(''); }} disabled={loading}>{projects.map((project) => <option key={project.id} value={project.id}>{project.name} · {project.domain}</option>)}</select><div className="file-actions"><button className="secondary" disabled={loading} onClick={()=>setOperation({action:"mkdir",path:joinPath(path,"new-directory"),to:""})}>新建目录</button><button className="secondary" disabled={loading} onClick={()=>void showTrash()}>回收站</button><button className="secondary" disabled={loading} onClick={() => {setError('');setEditor({ path: joinPath(path, 'new-file.txt'), content: '', isNew: true })}}><Plus size={15} />新建文本</button><button className="secondary" onClick={() => uploadRef.current?.click()} disabled={loading}><Upload size={15} />批量上传</button><button className="secondary" disabled={loading||!folderSupported} title={folderSupported?"保留所选文件夹及子目录结构":"当前浏览器不支持文件夹选择,请压缩后上传"} onClick={()=>folderRef.current?.click()}><Folder size={15}/>上传文件夹</button><button className="secondary" onClick={() => void emptyTrash()} disabled={loading}><Trash2 size={15} />清空回收站</button><input ref={uploadRef} aria-label="批量上传文件" type="file" multiple hidden onChange={(event) => {void upload(Array.from(event.target.files||[]))}} /><input ref={folderRef} aria-label="上传文件夹" type="file" multiple {...{webkitdirectory:''}} hidden onChange={event=>{const selected=Array.from(event.target.files||[]);if(!selected.length){setError('所选文件夹没有可上传文件;空目录不会被上传');return}void upload(selected)}} /><button className="icon-button" onClick={() => void load()} disabled={loading} aria-label="刷新文件"><RefreshCw size={16} /></button></div></div>
|
||||||
|
<p className="file-transfer-hint">单批最多 100 个文件、总大小 30 MB,单文件上限 {formatBytes(uploadLimit)};文件夹上传保留目录结构(不含空目录);支持解压 ZIP、TAR、TAR.GZ、TGZ。</p>
|
||||||
|
{uploadStatus?<p className="file-upload-status" role="status">{uploadStatus}</p>:null}
|
||||||
<div className="file-breadcrumb"><button disabled={loading} onClick={() => setPath('')}>根目录</button>{segments.map((segment, index) => <span key={`${segment}-${index}`}>/ <button disabled={loading} onClick={() => setPath(segments.slice(0, index + 1).join('/'))}>{segment}</button></span>)}</div>
|
<div className="file-breadcrumb"><button disabled={loading} onClick={() => setPath('')}>根目录</button>{segments.map((segment, index) => <span key={`${segment}-${index}`}>/ <button disabled={loading} onClick={() => setPath(segments.slice(0, index + 1).join('/'))}>{segment}</button></span>)}</div>
|
||||||
{error && !editor && !operation ? <p className="file-error" role="alert">{error}</p> : null}
|
{error && !editor && !operation ? <p className="file-error" role="alert">{error}</p> : null}
|
||||||
<div className="file-table" aria-busy={loading}><div className="file-row file-head"><span>名称</span><span>大小</span><span>修改时间</span><span>操作</span></div>{path ? <button disabled={loading} className="file-row file-parent" onClick={() => setPath(parentPath(path))}><span><ArrowLeft size={17} />返回上级</span><span>—</span><span>—</span><span /></button> : null}{visibleEntries.map((entry) => <div className="file-row" key={entry.path}>{entry.directory||isTextFile(entry)&&entry.size<=1024**2?<button className="file-name" onClick={()=>entry.directory?setPath(entry.path):void edit(entry)}>{entry.directory?<Folder size={18}/>:<File size={18}/>}<span>{entry.name}</span></button>:<span className="file-name" title={isTextFile(entry)?'超过 1 MB,请下载后编辑并重新上传':'此类型不支持在线编辑,请下载或使用 FTP 处理'}><File size={18}/><span>{entry.name}</span></span>}<span>{entry.directory ? '—' : formatBytes(entry.size)}</span><span>{formatDate(entry.modified)}</span><span className="file-row-actions">{!entry.directory && isTextFile(entry) && entry.size <= 1024 ** 2 ? <button onClick={() => void edit(entry)} aria-label={`编辑 ${entry.name}`}><Edit3 size={15} /></button> : null}{!entry.directory ? <a href={api.fileDownloadURL(projectID, entry.path)} aria-label={`下载 ${entry.name}`}><Download size={15} /></a> : null}<select aria-label={'更多操作 '+entry.name} value="" disabled={loading} onChange={e=>{const action=e.target.value;if(action)setOperation({action,path:entry.path,to:operationTarget(action,entry)})}}><option value="">更多</option><option value="move">重命名 / 移动</option><option value="copy">复制</option><option value="zip">压缩为 ZIP</option>{entry.name.toLowerCase().endsWith('.zip')?<option value="extract">解压 ZIP</option>:null}</select><button onClick={() => void trash(entry)} aria-label={`删除 ${entry.name}`}><Trash2 size={15} /></button></span></div>)}{!loading && !error && entries.length === 0 ? <div className="file-empty">目录为空</div> : null}{loading ? <div className="file-empty" role="status">正在读取…</div> : null}</div>
|
<div className="file-table" aria-busy={loading}><div className="file-row file-head"><span>名称</span><span>大小</span><span>修改时间</span><span>操作</span></div>{path ? <button disabled={loading} className="file-row file-parent" onClick={() => setPath(parentPath(path))}><span><ArrowLeft size={17} />返回上级</span><span>—</span><span>—</span><span /></button> : null}{visibleEntries.map((entry) => <div className="file-row" key={entry.path}>{entry.directory||isTextFile(entry)&&entry.size<=1024**2?<button className="file-name" onClick={()=>entry.directory?setPath(entry.path):void edit(entry)}>{entry.directory?<Folder size={18}/>:<File size={18}/>}<span>{entry.name}</span></button>:<span className="file-name" title={isTextFile(entry)?'超过 1 MB,请下载后编辑并重新上传':'此类型不支持在线编辑,请下载或使用 FTP 处理'}><File size={18}/><span>{entry.name}</span></span>}<span>{entry.directory ? '—' : formatBytes(entry.size)}</span><span>{formatDate(entry.modified)}</span><span className="file-row-actions">{!entry.directory && isTextFile(entry) && entry.size <= 1024 ** 2 ? <button onClick={() => void edit(entry)} aria-label={`编辑 ${entry.name}`}><Edit3 size={15} /></button> : null}{!entry.directory ? <a href={api.fileDownloadURL(projectID, entry.path)} aria-label={`下载 ${entry.name}`}><Download size={15} /></a> : null}{!entry.directory&&isArchive(entry)?<button onClick={()=>setOperation({action:'extract',path:entry.path,to:operationTarget('extract',entry)})} aria-label={'解压 '+entry.name}>解压</button>:null}<select aria-label={'更多操作 '+entry.name} value="" disabled={loading} onChange={e=>{const action=e.target.value;if(action)setOperation({action,path:entry.path,to:operationTarget(action,entry)})}}><option value="">更多</option><option value="move">重命名 / 移动</option><option value="copy">复制</option><option value="zip">压缩为 ZIP</option>{isArchive(entry)?<option value="extract">解压压缩包</option>:null}</select><button onClick={() => void trash(entry)} aria-label={`删除 ${entry.name}`}><Trash2 size={15} /></button></span></div>)}{!loading && !error && entries.length === 0 ? <div className="file-empty">目录为空</div> : null}{loading ? <div className="file-empty" role="status">正在读取…</div> : null}</div>
|
||||||
</section>
|
</section>
|
||||||
{trashEntries?<section className="file-panel"><h2>主机回收站</h2><button className="secondary" onClick={closeTrash}>关闭回收站</button>{!trashEntries.length?<p>回收站为空</p>:trashEntries.map(entry=><div className="file-row" key={entry.id}><span>{entry.originalPath}</span><span>{formatBytes(entry.size)}</span><span>{formatDate(entry.deletedAt)}</span><button onClick={()=>setOperation({action:'restore',path:entry.id,to:entry.originalPath})}>恢复 {entry.name}</button></div>)}</section>:null}
|
{trashEntries?<section className="file-panel"><h2>主机回收站</h2><button className="secondary" onClick={closeTrash}>关闭回收站</button>{!trashEntries.length?<p>回收站为空</p>:trashEntries.map(entry=><div className="file-row" key={entry.id}><span>{entry.originalPath}</span><span>{formatBytes(entry.size)}</span><span>{formatDate(entry.deletedAt)}</span><button onClick={()=>setOperation({action:'restore',path:entry.id,to:entry.originalPath})}>恢复 {entry.name}</button></div>)}</section>:null}
|
||||||
{operation?<ModalBackdrop className="modal-backdrop"><form className="file-editor" onSubmit={e=>{e.preventDefault();void perform()}}><h2>{{mkdir:'新建目录',move:'重命名 / 移动',copy:'复制',zip:'压缩 ZIP',extract:'解压 ZIP',restore:'恢复文件'}[operation.action]}</h2><p>路径均相对于当前主机根目录。目标必须不存在;复制、压缩和解压最多处理 256 MiB,并受套餐剩余空间限制。</p>{operation.action!=='restore'?<label>{operation.action==='mkdir'?'目录路径':'源路径'}<input disabled={busy} value={operation.path} readOnly={operation.action!=='mkdir'} required onChange={e=>setOperation({...operation,path:e.target.value})}/></label>:null}{operation.action!=='mkdir'?<label>目标路径<input disabled={busy} value={operation.to} required onChange={e=>setOperation({...operation,to:e.target.value})}/></label>:null}{error?<p className="form-error" role="alert">{error}</p>:null}<div className="form-actions"><button type="button" disabled={busy} onClick={()=>{setOperation(null);setError('')}}>取消</button><button className="primary" disabled={loading}>{busy?'正在处理…':'执行操作'}</button></div></form></ModalBackdrop>:null}
|
{operation?<ModalBackdrop className="modal-backdrop"><form className="file-editor" onSubmit={e=>{e.preventDefault();void perform()}}><h2>{{mkdir:'新建目录',move:'重命名 / 移动',copy:'复制',zip:'压缩 ZIP',extract:'解压压缩包',restore:'恢复文件'}[operation.action]}</h2><p>路径均相对于当前主机根目录。目标必须不存在;复制、压缩和解压最多处理 256 MiB,并受套餐剩余空间限制。</p>{operation.action!=='restore'?<label>{operation.action==='mkdir'?'目录路径':'源路径'}<input disabled={busy} value={operation.path} readOnly={operation.action!=='mkdir'} required onChange={e=>setOperation({...operation,path:e.target.value})}/></label>:null}{operation.action!=='mkdir'?<label>目标路径<input disabled={busy} value={operation.to} required onChange={e=>setOperation({...operation,to:e.target.value})}/></label>:null}{error?<p className="form-error" role="alert">{error}</p>:null}<div className="form-actions"><button type="button" disabled={busy} onClick={()=>{setOperation(null);setError('')}}>取消</button><button className="primary" disabled={loading}>{busy?'正在处理…':'执行操作'}</button></div></form></ModalBackdrop>:null}
|
||||||
{editor ? <ModalBackdrop className="modal-backdrop"><form className="file-editor" onSubmit={async (event) => { event.preventDefault(); if(busy)return; setBusy(true); setError(''); if (!live) { setEditor(null); setBusy(false); return; } try { await api.writeFile(projectID, editor.path, editor.content, !editor.isNew); setEditor(null); await load(); } catch (reason) { setError(message(reason, '保存失败')); } finally { setBusy(false); } }}><button type="button" className="modal-close" disabled={busy} onClick={() => {setEditor(null);setError('')}} aria-label="关闭编辑器"><X size={17} /></button><h2>{editor.isNew ? '新建文本文件' : '编辑文本文件'}</h2><label>主机内路径<input disabled={busy} required value={editor.path} readOnly={!editor.isNew} onChange={(event) => setEditor({ ...editor, path: event.target.value })} /></label><label>内容<textarea disabled={busy} spellCheck={false} value={editor.content} onChange={(event) => setEditor({ ...editor, content: event.target.value })} /></label>{error?<p className="form-error" role="alert">{error}</p>:null}<div className="form-actions"><button type="button" className="secondary" disabled={busy} onClick={() => {setEditor(null);setError('')}}>取消</button><button className="primary" disabled={loading}>{busy ? '保存中…' : '保存'}</button></div></form></ModalBackdrop> : null}
|
{editor ? <ModalBackdrop className="modal-backdrop"><form className="file-editor" onSubmit={async (event) => { event.preventDefault(); if(busy)return; setBusy(true); setError(''); if (!live) { setEditor(null); setBusy(false); return; } try { await api.writeFile(projectID, editor.path, editor.content, !editor.isNew); setEditor(null); await load(); } catch (reason) { setError(message(reason, '保存失败')); } finally { setBusy(false); } }}><button type="button" className="modal-close" disabled={busy} onClick={() => {setEditor(null);setError('')}} aria-label="关闭编辑器"><X size={17} /></button><h2>{editor.isNew ? '新建文本文件' : '编辑文本文件'}</h2><label>主机内路径<input disabled={busy} required value={editor.path} readOnly={!editor.isNew} onChange={(event) => setEditor({ ...editor, path: event.target.value })} /></label><label>内容<textarea disabled={busy} spellCheck={false} value={editor.content} onChange={(event) => setEditor({ ...editor, content: event.target.value })} /></label>{error?<p className="form-error" role="alert">{error}</p>:null}<div className="form-actions"><button type="button" className="secondary" disabled={busy} onClick={() => {setEditor(null);setError('')}}>取消</button><button className="primary" disabled={loading}>{busy ? '保存中…' : '保存'}</button></div></form></ModalBackdrop> : null}
|
||||||
</div>;
|
</div>;
|
||||||
}
|
}
|
||||||
@@ -125,7 +145,7 @@ export function FileManager({ projects, initialProjectID, live = true }: { proje
|
|||||||
function operationTarget(action:string,entry:FileEntry){
|
function operationTarget(action:string,entry:FileEntry){
|
||||||
if(action==='move')return entry.path;
|
if(action==='move')return entry.path;
|
||||||
if(action==='zip')return entry.path+'.zip';
|
if(action==='zip')return entry.path+'.zip';
|
||||||
if(action==='extract')return entry.path.replace(/\.zip$/i,'')+'-extracted';
|
if(action==='extract')return entry.path.replace(/\.(?:tar\.gz|tgz|tar|zip)$/i,'')+'-extracted';
|
||||||
const extension=entry.directory?-1:entry.name.lastIndexOf('.');
|
const extension=entry.directory?-1:entry.name.lastIndexOf('.');
|
||||||
return extension>0?entry.path.slice(0,-(entry.name.length-extension))+'-copy'+entry.name.slice(extension):entry.path+'-copy';
|
return extension>0?entry.path.slice(0,-(entry.name.length-extension))+'-copy'+entry.name.slice(extension):entry.path+'-copy';
|
||||||
}
|
}
|
||||||
@@ -140,3 +160,7 @@ function demoEntries(path: string): FileEntry[] {
|
|||||||
if (path) return [];
|
if (path) return [];
|
||||||
return [{ name: 'assets', path: 'assets', directory: true, size: 0, modified }, { name: 'index.php', path: 'index.php', directory: false, size: 1260, modified }, { name: 'README.md', path: 'README.md', directory: false, size: 860, modified }];
|
return [{ name: 'assets', path: 'assets', directory: true, size: 0, modified }, { name: 'index.php', path: 'index.php', directory: false, size: 1260, modified }, { name: 'README.md', path: 'README.md', directory: false, size: 860, modified }];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isArchive(entry:FileEntry){return !entry.directory&&/\.(?:zip|tar|tar\.gz|tgz)$/i.test(entry.name)}
|
||||||
|
|
||||||
|
function uploadFilePath(file:File){return file.webkitRelativePath||file.name}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import {randomHostName} from '../hostName';
|
||||||
import {ModalBackdrop} from './ModalBackdrop';
|
import {ModalBackdrop} from './ModalBackdrop';
|
||||||
import {useEffect,useState} from 'react';
|
import {useEffect,useState} from 'react';
|
||||||
import {api,type AdminProject,type ControlNode,type Credentials,type PanelSite,type Tenant} from '../api';
|
import {api,type AdminProject,type ControlNode,type Credentials,type PanelSite,type Tenant} from '../api';
|
||||||
@@ -5,6 +6,7 @@ import type {Plan,RuntimeCatalog,Runtime} from '../types';
|
|||||||
import {CredentialsModal} from './CredentialsModal';
|
import {CredentialsModal} from './CredentialsModal';
|
||||||
|
|
||||||
export function HostProvisioning({users,plans,adopt=false,onClose,onComplete}:{users:Tenant[];plans:Plan[];adopt?:boolean;onClose:()=>void;onComplete:()=>Promise<void>}){
|
export function HostProvisioning({users,plans,adopt=false,onClose,onComplete}:{users:Tenant[];plans:Plan[];adopt?:boolean;onClose:()=>void;onComplete:()=>Promise<void>}){
|
||||||
|
const [defaultName]=useState(randomHostName);
|
||||||
const [nodes,setNodes]=useState<ControlNode[]>([]);const [nodeId,setNodeId]=useState(0);const [versions,setVersions]=useState<RuntimeCatalog>({PHP:[],"Node.js":[],Python:[],Go:[],Java:[]});const [sites,setSites]=useState<PanelSite[]>([]);const [siteId,setSiteId]=useState(0);const [runtime,setRuntime]=useState<Runtime>('PHP');const [version,setVersion]=useState('');const [busy,setBusy]=useState(false);const [error,setError]=useState('');const [credentials,setCredentials]=useState<Credentials>();
|
const [nodes,setNodes]=useState<ControlNode[]>([]);const [nodeId,setNodeId]=useState(0);const [versions,setVersions]=useState<RuntimeCatalog>({PHP:[],"Node.js":[],Python:[],Go:[],Java:[]});const [sites,setSites]=useState<PanelSite[]>([]);const [siteId,setSiteId]=useState(0);const [runtime,setRuntime]=useState<Runtime>('PHP');const [version,setVersion]=useState('');const [busy,setBusy]=useState(false);const [error,setError]=useState('');const [credentials,setCredentials]=useState<Credentials>();
|
||||||
useEffect(()=>{let active=true;api.nodes().then(r=>{if(active){setNodes(r.nodes);setNodeId(r.nodes.find(n=>n.enabled)?.id||0)}}).catch(e=>{if(active)setError(e.message)});return()=>{active=false}},[]);
|
useEffect(()=>{let active=true;api.nodes().then(r=>{if(active){setNodes(r.nodes);setNodeId(r.nodes.find(n=>n.enabled)?.id||0)}}).catch(e=>{if(active)setError(e.message)});return()=>{active=false}},[]);
|
||||||
useEffect(()=>{let active=true;setVersions({PHP:[],"Node.js":[],Python:[],Go:[],Java:[]});setSites([]);setSiteId(0);setVersion('');if(!nodeId)return;setBusy(true);setError('');api.panelSites(nodeId).then(r=>{if(active){const catalog=Object.fromEntries((["PHP","Node.js","Python","Go","Java"] as Runtime[]).map(name=>[name,Array.isArray(r.versions?.[name])?r.versions[name]:[]])) as RuntimeCatalog;setVersions(catalog);setSites(Array.isArray(r.sites)?r.sites:[]);setRuntime('PHP');setVersion(catalog.PHP?.[0]||'')}}).catch(e=>{if(active)setError(e.message)}).finally(()=>{if(active)setBusy(false)});return()=>{active=false}},[nodeId]);
|
useEffect(()=>{let active=true;setVersions({PHP:[],"Node.js":[],Python:[],Go:[],Java:[]});setSites([]);setSiteId(0);setVersion('');if(!nodeId)return;setBusy(true);setError('');api.panelSites(nodeId).then(r=>{if(active){const catalog=Object.fromEntries((["PHP","Node.js","Python","Go","Java"] as Runtime[]).map(name=>[name,Array.isArray(r.versions?.[name])?r.versions[name]:[]])) as RuntimeCatalog;setVersions(catalog);setSites(Array.isArray(r.sites)?r.sites:[]);setRuntime('PHP');setVersion(catalog.PHP?.[0]||'')}}).catch(e=>{if(active)setError(e.message)}).finally(()=>{if(active)setBusy(false)});return()=>{active=false}},[nodeId]);
|
||||||
@@ -15,7 +17,7 @@ export function HostProvisioning({users,plans,adopt=false,onClose,onComplete}:{u
|
|||||||
<label>所属节点<select aria-label="所属节点" value={nodeId} required onChange={e=>setNodeId(Number(e.target.value))}><option value="0" disabled>请选择节点</option>{nodes.filter(n=>n.enabled).map(n=><option key={n.id} value={n.id}>{n.name} · {n.rootDomain}</option>)}</select></label>
|
<label>所属节点<select aria-label="所属节点" value={nodeId} required onChange={e=>setNodeId(Number(e.target.value))}><option value="0" disabled>请选择节点</option>{nodes.filter(n=>n.enabled).map(n=><option key={n.id} value={n.id}>{n.name} · {n.rootDomain}</option>)}</select></label>
|
||||||
<div className="plan-form-grid"><label>{adopt?'分配用户':'绑定用户(可选)'}<select name="tenantId" required={adopt}><option value={adopt?'':'0'}>{adopt?'请选择':'不绑定用户,独立主机账号登录'}</option>{users.filter(u=>u.status==='active').map(u=><option key={u.id} value={u.id}>{u.name}</option>)}</select></label><label>主机套餐<select name="planId" required><option value="">请选择</option>{plans.map(p=><option key={p.id} value={p.id}>{p.name}</option>)}</select></label></div>
|
<div className="plan-form-grid"><label>{adopt?'分配用户':'绑定用户(可选)'}<select name="tenantId" required={adopt}><option value={adopt?'':'0'}>{adopt?'请选择':'不绑定用户,独立主机账号登录'}</option>{users.filter(u=>u.status==='active').map(u=><option key={u.id} value={u.id}>{u.name}</option>)}</select></label><label>主机套餐<select name="planId" required><option value="">请选择</option>{plans.map(p=><option key={p.id} value={p.id}>{p.name}</option>)}</select></label></div>
|
||||||
{adopt?<label>待迁移站点<select value={siteId||''} required onChange={e=>setSiteId(Number(e.target.value))}><option value="">请选择</option>{sites.map(s=><option key={s.id} value={s.id}>{s.domain} · {s.path}</option>)}</select><small>原目录复制至主机根目录,接管成功前保留原文件。</small></label>:null}
|
{adopt?<label>待迁移站点<select value={siteId||''} required onChange={e=>setSiteId(Number(e.target.value))}><option value="">请选择</option>{sites.map(s=><option key={s.id} value={s.id}>{s.domain} · {s.path}</option>)}</select><small>原目录复制至主机根目录,接管成功前保留原文件。</small></label>:null}
|
||||||
<label>主机名称<input name="name" minLength={3} maxLength={50} pattern="[a-z0-9](?:[a-z0-9]|-){1,48}[a-z0-9]" required/></label>
|
<label>主机名称<input name="name" defaultValue={defaultName} minLength={3} maxLength={50} pattern="[a-z0-9](?:[a-z0-9]|-){1,48}[a-z0-9]" required/></label>
|
||||||
<div className="plan-form-grid"><label>运行环境<select value={runtime} onChange={e=>{setRuntime(e.target.value as Runtime);setVersion(versions[e.target.value as Runtime]?.[0]||'')}}>{Object.keys(versions).map(v=><option key={v}>{v}</option>)}</select></label><label>版本<select value={version} required onChange={e=>setVersion(e.target.value)}>{(versions[runtime]||[]).map(v=><option key={v}>{v}</option>)}</select></label></div>
|
<div className="plan-form-grid"><label>运行环境<select value={runtime} onChange={e=>{setRuntime(e.target.value as Runtime);setVersion(versions[e.target.value as Runtime]?.[0]||'')}}>{Object.keys(versions).map(v=><option key={v}>{v}</option>)}</select></label><label>版本<select value={version} required onChange={e=>setVersion(e.target.value)}>{(versions[runtime]||[]).map(v=><option key={v}>{v}</option>)}</select></label></div>
|
||||||
<label>运行目录<input name="runPath" defaultValue="/" required/><small>目录位于 {node?.tenantRoot}/随机主机名,默认域名为 随机主机名.{node?.rootDomain}</small></label>
|
<label>运行目录<input name="runPath" defaultValue="/" required/><small>目录位于 {node?.tenantRoot}/随机主机名,默认域名为 随机主机名.{node?.rootDomain}</small></label>
|
||||||
{!adopt?<label>到期时间<input name="expiresAt" type="datetime-local"/><small>留空表示长期使用;到期停用,宽限 3 天,回收保留 7 天,备份保留 14 天。</small></label>:null}
|
{!adopt?<label>到期时间<input name="expiresAt" type="datetime-local"/><small>留空表示长期使用;到期停用,宽限 3 天,回收保留 7 天,备份保留 14 天。</small></label>:null}
|
||||||
|
|||||||
@@ -9,23 +9,19 @@ const resourceLabels: Record<string, string> = { file: '文件管理', database:
|
|||||||
|
|
||||||
interface OverviewProps {
|
interface OverviewProps {
|
||||||
onRefresh?:()=>void;refreshing?:boolean;
|
onRefresh?:()=>void;refreshing?:boolean;
|
||||||
pendingProjectIDs?:number[];
|
onEnterHost:(project:Project)=>void;
|
||||||
|
onSchedules?:()=>void;
|
||||||
projects: Project[];
|
projects: Project[];
|
||||||
plan: Plan;
|
plan: Plan;
|
||||||
usage: Usage;
|
usage: Usage;
|
||||||
activities: ActivityEntry[];
|
activities: ActivityEntry[];
|
||||||
hostScoped: boolean;
|
hostScoped: boolean;
|
||||||
onCreate: () => void;
|
onCreate: () => void;
|
||||||
onToggle: (id: number) => void;
|
|
||||||
onFiles: (id: number) => void;
|
|
||||||
onRunPath: (project: Project) => void;
|
|
||||||
onSites: (project: Project) => void;
|
|
||||||
onCredentials: (project: Project) => void;
|
|
||||||
canCreate: boolean;
|
canCreate: boolean;
|
||||||
onLogs?: () => void;
|
onLogs?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Overview({ onRefresh,refreshing,pendingProjectIDs,projects, plan, usage, activities, hostScoped, onCreate, onToggle, onFiles, onRunPath, onSites, onCredentials, canCreate, onLogs }: OverviewProps) {
|
export function Overview({ onRefresh,refreshing,projects, plan, usage, activities, hostScoped, onCreate, onEnterHost, onSchedules, canCreate, onLogs }: OverviewProps) {
|
||||||
const resources = [
|
const resources = [
|
||||||
{ label: '存储空间', value: usage.storageBytes, limit: plan.storageBytes },
|
{ label: '存储空间', value: usage.storageBytes, limit: plan.storageBytes },
|
||||||
{ label: '本月流量', value: usage.bandwidthBytes, limit: plan.bandwidthBytes },
|
{ label: '本月流量', value: usage.bandwidthBytes, limit: plan.bandwidthBytes },
|
||||||
@@ -34,14 +30,14 @@ export function Overview({ onRefresh,refreshing,pendingProjectIDs,projects, plan
|
|||||||
];
|
];
|
||||||
return (
|
return (
|
||||||
<div className="page">
|
<div className="page">
|
||||||
<PageHeader title="总览" description={hostScoped ? '管理当前虚拟主机的网站、文件与访问凭据。' : '查看当前账号下的资源使用情况和业务概览。'} actions={onRefresh?<button className="secondary" disabled={refreshing} onClick={onRefresh}><RefreshCw size={15}/>{refreshing?'正在刷新…':'刷新状态'}</button>:null}/>
|
<PageHeader title="总览" actions={<div className="overview-actions">{onSchedules?<button className="secondary" onClick={onSchedules}>计划任务</button>:null}{onRefresh?<button className="secondary" disabled={refreshing} onClick={onRefresh}><RefreshCw size={15}/>{refreshing?'正在刷新…':'刷新状态'}</button>:null}</div>}/>
|
||||||
{!hostScoped ? <div className="metrics-grid">
|
{!hostScoped ? <div className="metrics-grid">
|
||||||
<MetricCard icon={HardDrive} label="存储空间" value={formatBytes(usage.storageBytes)} limit={formatBytes(plan.storageBytes)} percent={usagePercent(usage.storageBytes, plan.storageBytes)} />
|
<MetricCard icon={HardDrive} label="存储空间" value={formatBytes(usage.storageBytes)} limit={formatBytes(plan.storageBytes)} percent={usagePercent(usage.storageBytes, plan.storageBytes)} />
|
||||||
<MetricCard icon={Network} label="本月流量" value={formatBytes(usage.bandwidthBytes)} limit={formatBytes(plan.bandwidthBytes)} percent={usagePercent(usage.bandwidthBytes, plan.bandwidthBytes)} />
|
<MetricCard icon={Network} label="本月流量" value={formatBytes(usage.bandwidthBytes)} limit={formatBytes(plan.bandwidthBytes)} percent={usagePercent(usage.bandwidthBytes, plan.bandwidthBytes)} />
|
||||||
<MetricCard icon={Cpu} label="进程数量" value={String(usage.processCount)} limit={String(plan.processLimit)} percent={usagePercent(usage.processCount, plan.processLimit)} />
|
<MetricCard icon={Cpu} label="进程数量" value={String(usage.processCount)} limit={String(plan.processLimit)} percent={usagePercent(usage.processCount, plan.processLimit)} />
|
||||||
<MetricCard icon={Database} label="数据库大小" value={formatBytes(usage.databaseBytes)} limit={formatBytes(plan.databaseBytes)} percent={usagePercent(usage.databaseBytes, plan.databaseBytes)} />
|
<MetricCard icon={Database} label="数据库大小" value={formatBytes(usage.databaseBytes)} limit={formatBytes(plan.databaseBytes)} percent={usagePercent(usage.databaseBytes, plan.databaseBytes)} />
|
||||||
</div> : null}
|
</div> : null}
|
||||||
<ProjectTable pendingProjectIDs={pendingProjectIDs} projects={projects} canCreate={canCreate} onCreate={onCreate} onToggle={onToggle} onFiles={onFiles} onRunPath={onRunPath} onSites={onSites} onCredentials={onCredentials} />
|
<ProjectTable projects={projects} canCreate={canCreate} onCreate={onCreate} onEnterHost={onEnterHost} />
|
||||||
{!hostScoped ? <div className="lower-grid">
|
{!hostScoped ? <div className="lower-grid">
|
||||||
<section className="activity-panel">
|
<section className="activity-panel">
|
||||||
<div className="section-title"><h2>最近操作日志</h2>{onLogs?<button onClick={onLogs}>查看全部 <ArrowRight size={15} /></button>:null}</div>
|
<div className="section-title"><h2>最近操作日志</h2>{onLogs?<button onClick={onLogs}>查看全部 <ArrowRight size={15} /></button>:null}</div>
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import {formatBytes} from '../format';
|
|||||||
import {RuntimeMark} from './UI';
|
import {RuntimeMark} from './UI';
|
||||||
const statusLabels: Record<Project['status'], string> = { running: '运行中', stopped: '已停止', provisioning: '创建中', awaiting_upload: '待上传', failed: '创建失败', quota_suspended: '配额暂停' };
|
const statusLabels: Record<Project['status'], string> = { running: '运行中', stopped: '已停止', provisioning: '创建中', awaiting_upload: '待上传', failed: '创建失败', quota_suspended: '配额暂停' };
|
||||||
|
|
||||||
export function ProjectTable({pendingProjectIDs=[], projects, canCreate, onCreate, onToggle, onFiles, onRunPath, onSites, onCredentials }: {pendingProjectIDs?:number[]; projects: Project[]; canCreate: boolean; onCreate: () => void; onToggle: (id: number) => void; onFiles: (id: number) => void; onRunPath: (project: Project) => void; onSites: (project: Project) => void; onCredentials: (project: Project) => void }) {
|
export function ProjectTable({ projects, canCreate, onCreate, onEnterHost }: { projects: Project[]; canCreate: boolean; onCreate: () => void; onEnterHost: (project:Project)=>void }) {
|
||||||
const [query, setQuery] = useState('');
|
const [query, setQuery] = useState('');
|
||||||
const deferredQuery = useDeferredValue(query);
|
const deferredQuery = useDeferredValue(query);
|
||||||
const filtered = useMemo(() => {
|
const filtered = useMemo(() => {
|
||||||
@@ -23,19 +23,19 @@ export function ProjectTable({pendingProjectIDs=[], projects, canCreate, onCreat
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="table-scroll">
|
<div className="table-scroll">
|
||||||
<table>
|
<table className="user-host-table">
|
||||||
<thead><tr><th>#</th><th>域名(主机名 / 目录)</th><th>运行环境</th><th>状态</th><th>SSL 证书</th><th>本月流量</th><th>创建时间</th><th>操作</th></tr></thead>
|
<thead><tr><th>#</th><th>域名 / 主机</th><th>运行环境</th><th>状态</th><th>SSL 证书</th><th>本月流量</th><th>创建时间</th><th>操作</th></tr></thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{filtered.map((project, index) => (
|
{filtered.map((project, index) => (
|
||||||
<tr key={project.id}>
|
<tr key={project.id} title="双击进入主机管理" onDoubleClick={event=>{if(!(event.target as HTMLElement).closest('button,a,input,select'))onEnterHost(project)}}>
|
||||||
<td className="muted">{index + 1}</td>
|
<td className="muted">{index + 1}</td>
|
||||||
<td><b>{project.domain}</b><small>{project.name} · {project.hostName} · {project.path} · 发布 {project.runPath}</small></td>
|
<td><b>{project.domain}</b><small>{project.hostName} · {project.name}</small></td>
|
||||||
<td><RuntimeMark runtime={project.runtime}/>{project.runtime} {project.version}</td>
|
<td><RuntimeMark runtime={project.runtime}/>{project.runtime} {project.version}</td>
|
||||||
<td><span className={`status ${project.status}`}>{statusLabels[project.status]}</span></td>
|
<td><span className={`status ${project.status}`}>{statusLabels[project.status]}</span></td>
|
||||||
<td className={project.ssl ? 'success' : 'muted'}><LockKeyhole size={14} /> {project.ssl ? '已部署' : '未部署'}</td>
|
<td className={project.ssl ? 'success' : 'muted'}><LockKeyhole size={14} /> {project.ssl ? '已部署' : '未部署'}</td>
|
||||||
<td>{formatBytes(project.trafficGB*1024**3)}</td>
|
<td>{formatBytes(project.trafficGB*1024**3)}</td>
|
||||||
<td className="muted">{project.createdAt}</td>
|
<td className="muted">{project.createdAt}</td>
|
||||||
<td className="row-actions"><button title={pendingProjectIDs.includes(project.id)?'正在应用主站状态':!['running','stopped'].includes(project.status)?'主站尚未完成部署或已受配额限制':undefined} disabled={pendingProjectIDs.includes(project.id)||!['running', 'stopped'].includes(project.status)} onClick={() => onToggle(project.id)}>{pendingProjectIDs.includes(project.id)?'处理中…':project.status === 'running' ? '停止' : '启动'}</button><button onClick={() => onSites(project)}>网站</button><button onClick={() => onFiles(project.id)}>文件</button><button onClick={() => onCredentials(project)}>凭据</button><button disabled={['failed', 'provisioning'].includes(project.status)} onClick={() => onRunPath(project)}>主站目录</button></td>
|
<td><button className="host-enter-button" aria-label={'进入主机 '+project.hostName} onClick={() => onEnterHost(project)}>进入主机</button></td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
{filtered.length === 0 ? <tr><td colSpan={8} className="empty-row">没有匹配的虚拟主机</td></tr> : null}
|
{filtered.length === 0 ? <tr><td colSpan={8} className="empty-row">没有匹配的虚拟主机</td></tr> : null}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import type { ActivityEntry, Project, Site } from '../types';
|
|||||||
|
|
||||||
interface ResourceCenterProps {
|
interface ResourceCenterProps {
|
||||||
page: string;
|
page: string;
|
||||||
|
projectID?:number;
|
||||||
projects: Project[];
|
projects: Project[];
|
||||||
activities: ActivityEntry[];
|
activities: ActivityEntry[];
|
||||||
hostScoped: boolean;
|
hostScoped: boolean;
|
||||||
@@ -17,7 +18,7 @@ interface ResourceCenterProps {
|
|||||||
onNotify: (message: string) => void;
|
onNotify: (message: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ResourceCenter({ page, projects, activities, hostScoped, domainApproval, live, onCredentials, onNotify }: ResourceCenterProps) {
|
export function ResourceCenter({ page, projectID, projects, activities, hostScoped, domainApproval, live, onCredentials, onNotify }: ResourceCenterProps) {
|
||||||
const demoInventory = useMemo(() => inventoryFromProjects(projects), [projects]);
|
const demoInventory = useMemo(() => inventoryFromProjects(projects), [projects]);
|
||||||
const [inventory, setInventory] = useState<ResourceInventory>(()=>live?{sites:[],domains:[],ftpAccounts:[],databases:[]}:demoInventory);
|
const [inventory, setInventory] = useState<ResourceInventory>(()=>live?{sites:[],domains:[],ftpAccounts:[],databases:[]}:demoInventory);
|
||||||
const [busy, setBusy] = useState(live);
|
const [busy, setBusy] = useState(live);
|
||||||
@@ -40,9 +41,15 @@ export function ResourceCenter({ page, projects, activities, hostScoped, domainA
|
|||||||
return () => { active = false; };
|
return () => { active = false; };
|
||||||
}, [demoInventory, live, page,epoch]);
|
}, [demoInventory, live, page,epoch]);
|
||||||
|
|
||||||
if (page === 'domains') return <DomainPage onRefresh={reload} inventory={inventory} setInventory={setInventory} approval={domainApproval} live={live} busy={busy} error={error} onNotify={onNotify} />;
|
const visibleInventory = projectID ? {
|
||||||
if (page === 'databases') return <DatabasePage onRefresh={reload} items={inventory.databases} busy={busy} error={error} onCredentials={onCredentials} />;
|
sites:inventory.sites.filter(item=>item.projectId===projectID),
|
||||||
if (page === 'ftp') return <FTPPage pausedProjectIDs={projects.filter(p=>p.status==='quota_suspended').map(p=>p.id)} onRefresh={reload} items={inventory.ftpAccounts} busy={busy} error={error} onCredentials={onCredentials} live={live} onNotify={onNotify} onChanged={async()=>setInventory(await api.resources())}/>;
|
domains:inventory.domains.filter(item=>item.projectId===projectID),
|
||||||
|
databases:inventory.databases.filter(item=>item.projectId===projectID),
|
||||||
|
ftpAccounts:inventory.ftpAccounts.filter(item=>item.projectId===projectID),
|
||||||
|
} : inventory;
|
||||||
|
if (page === 'domains') return <DomainPage onRefresh={reload} inventory={visibleInventory} setInventory={setInventory} approval={domainApproval} live={live} busy={busy} error={error} onNotify={onNotify} />;
|
||||||
|
if (page === 'databases') return <DatabasePage onRefresh={reload} items={visibleInventory.databases} busy={busy} error={error} onCredentials={onCredentials} />;
|
||||||
|
if (page === 'ftp') return <FTPPage pausedProjectIDs={projects.filter(p=>p.status==='quota_suspended').map(p=>p.id)} onRefresh={reload} items={visibleInventory.ftpAccounts} busy={busy} error={error} onCredentials={onCredentials} live={live} onNotify={onNotify} onChanged={async()=>setInventory(await api.resources())}/>;
|
||||||
return <ActivityPage activities={activities} hostScoped={hostScoped} projects={projects} live={live} />;
|
return <ActivityPage activities={activities} hostScoped={hostScoped} projects={projects} live={live} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ export function AccountEditor({account,onClose,onChanged,intent='edit'}:{intent?
|
|||||||
useEffect(()=>{let active=true;setProfile(undefined);setError('');api.accountProfile(account.id).then(p=>{if(active)setProfile(p)}).catch(e=>{if(active)setError(message(e))});return()=>{active=false}},[account.id,retry]);
|
useEffect(()=>{let active=true;setProfile(undefined);setError('');api.accountProfile(account.id).then(p=>{if(active)setProfile(p)}).catch(e=>{if(active)setError(message(e))});return()=>{active=false}},[account.id,retry]);
|
||||||
async function save(){if(!profile)return;setBusy(true);setError('');try{await api.updateAccount(account.id,profile);await onChanged();onClose()}catch(e){setError(message(e))}finally{setBusy(false)}}
|
async function save(){if(!profile)return;setBusy(true);setError('');try{await api.updateAccount(account.id,profile);await onChanged();onClose()}catch(e){setError(message(e))}finally{setBusy(false)}}
|
||||||
async function remove(){if(!profile||!await confirm(`删除用户「${profile.name}」?登录权限将被撤销,用户标识和历史审计保留。名下主机必须先解绑或转移。`,{title:'删除用户',confirmLabel:'确认删除用户',danger:true}))return;setBusy(true);setError('');try{await api.deleteAccount(account.id,account.slug);await onChanged();onClose()}catch(e){setError(message(e))}finally{setBusy(false)}}
|
async function remove(){if(!profile||!await confirm(`删除用户「${profile.name}」?登录权限将被撤销,用户标识和历史审计保留。名下主机必须先解绑或转移。`,{title:'删除用户',confirmLabel:'确认删除用户',danger:true}))return;setBusy(true);setError('');try{await api.deleteAccount(account.id,account.slug);await onChanged();onClose()}catch(e){setError(message(e))}finally{setBusy(false)}}
|
||||||
return <><ModalBackdrop><section className="tenant-modal resource-editor"><h2>{intent==='delete'?'删除用户':'用户详情与编辑'}</h2><p>用户标识:<code>{account.slug}</code> · #{account.id}</p>{error?<p className="form-error" role="alert">{error}</p>:null}{profile?<>{intent==='edit'?<form onSubmit={e=>{e.preventDefault();void save()}}><fieldset disabled={busy}><label>用户名称<input required maxLength={120} value={profile.name} onChange={e=>setProfile({...profile,name:e.target.value})}/></label><label>联系人姓名<input required minLength={2} maxLength={80} value={profile.displayName} onChange={e=>setProfile({...profile,displayName:e.target.value})}/></label><label>登录邮箱<input type="email" required maxLength={190} value={profile.email} onChange={e=>setProfile({...profile,email:e.target.value})}/></label><p>关联主机:{profile.projectCount} 台</p><div className="form-actions"><button type="button" className="secondary" onClick={onClose}>关闭</button><button className="primary">{busy?'保存中…':'保存用户资料'}</button></div></fieldset></form>:null}<div className="resource-danger-zone"><p>删除前需逐一解绑或转移全部主机,包括回收中的主机。用户标识与日志保留。</p><button type="button" className="secondary danger-text" title={profile.projectCount>0?'需先逐一解绑或转移全部主机,包括回收中的主机':undefined} disabled={busy||profile.projectCount>0} onClick={()=>void remove()}>删除用户</button>{intent==='delete'?<button type="button" className="secondary" onClick={onClose}>取消</button>:null}</div></>:<><p>{error?'用户资料读取失败':'正在读取用户资料…'}</p><div className="form-actions"><button onClick={onClose}>关闭</button>{error?<button onClick={()=>setRetry(v=>v+1)}>重新读取</button>:null}</div></>}</section></ModalBackdrop>{confirmation}</>;
|
return <><ModalBackdrop><section className="tenant-modal resource-editor"><h2>{intent==='delete'?'删除用户':'用户详情与编辑'}</h2><p>用户标识:<code>{account.slug}</code> · #{account.id}</p>{error?<p className="form-error" role="alert">{error}</p>:null}{profile?<>{intent==='edit'?<form onSubmit={e=>{e.preventDefault();void save()}}><fieldset disabled={busy}><label>登录账号<input readOnly value={profile.loginName||profile.email}/></label><label>显示名称<input required minLength={2} maxLength={80} value={profile.displayName} onChange={e=>setProfile({...profile,name:e.target.value,displayName:e.target.value})}/></label><label>登录邮箱<input type="email" required maxLength={190} value={profile.email} onChange={e=>setProfile({...profile,email:e.target.value})}/></label><p>关联主机:{profile.projectCount} 台</p><div className="form-actions"><button type="button" className="secondary" onClick={onClose}>关闭</button><button className="primary">{busy?'保存中…':'保存用户资料'}</button></div></fieldset></form>:null}<div className="resource-danger-zone"><p>删除前需逐一解绑或转移全部主机,包括回收中的主机。用户标识与日志保留。</p><button type="button" className="secondary danger-text" title={profile.projectCount>0?'需先逐一解绑或转移全部主机,包括回收中的主机':undefined} disabled={busy||profile.projectCount>0} onClick={()=>void remove()}>删除用户</button>{intent==='delete'?<button type="button" className="secondary" onClick={onClose}>取消</button>:null}</div></>:<><p>{error?'用户资料读取失败':'正在读取用户资料…'}</p><div className="form-actions"><button onClick={onClose}>关闭</button>{error?<button onClick={()=>setRetry(v=>v+1)}>重新读取</button>:null}</div></>}</section></ModalBackdrop>{confirmation}</>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function HostEditor({host,onClose,onChanged,intent='edit'}:{intent?:'edit'|'recycle';host:AdminProject;onClose:()=>void;onChanged:()=>Promise<void>}){
|
export function HostEditor({host,onClose,onChanged,intent='edit'}:{intent?:'edit'|'recycle';host:AdminProject;onClose:()=>void;onChanged:()=>Promise<void>}){
|
||||||
|
|||||||
@@ -13,11 +13,12 @@ const items = [
|
|||||||
['logs', '操作日志', ScrollText],
|
['logs', '操作日志', ScrollText],
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export function Sidebar({ page, onNavigate, hostScoped = false }: { page: string; onNavigate: (page: string) => void; hostScoped?: boolean }) {
|
export function Sidebar({ page, onNavigate, hostScoped = false, hostView = false }: { page: string; onNavigate: (page: string) => void; hostScoped?: boolean; hostView?: boolean }) {
|
||||||
|
const hostNavigation = hostScoped || hostView;
|
||||||
return (
|
return (
|
||||||
<aside className="sidebar" aria-label="主导航">
|
<aside className="sidebar" aria-label="主导航">
|
||||||
<nav>
|
<nav>
|
||||||
{items.filter(([key]) => !(hostScoped && (key === 'overview'||key === 'dns'||key==='schedules'))).map(([key, label, Icon]) => (
|
{items.filter(([key]) => hostNavigation ? !['overview','dns','schedules'].includes(key) : ['overview','domains','dns','logs'].includes(key)).map(([key, label, Icon]) => (
|
||||||
<button key={key} aria-current={page === key ? "page" : undefined} className={page === key ? 'nav-item active' : 'nav-item'} onClick={() => onNavigate(key)}>
|
<button key={key} aria-current={page === key ? "page" : undefined} className={page === key ? 'nav-item active' : 'nav-item'} onClick={() => onNavigate(key)}>
|
||||||
<Icon size={19} aria-hidden="true" />
|
<Icon size={19} aria-hidden="true" />
|
||||||
<span>{label}</span>
|
<span>{label}</span>
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
export function randomHostName() {
|
||||||
|
return 'sv' + Array.from(crypto.getRandomValues(new Uint8Array(5)), value => value.toString(16).padStart(2, '0')).join('');
|
||||||
|
}
|
||||||
@@ -5320,3 +5320,5 @@ to {
|
|||||||
.sites-head > span:last-child {
|
.sites-head > span:last-child {
|
||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.file-transfer-hint, .file-upload-status { margin: 12px 16px; color: var(--text-muted, #7b899c); font-size: 12px; line-height: 1.6; }
|
||||||
@@ -34,6 +34,36 @@
|
|||||||
.sso-identity small { color: var(--muted); overflow-wrap: anywhere; }
|
.sso-identity small { color: var(--muted); overflow-wrap: anywhere; }
|
||||||
.sso-create-actions { display: grid; gap: 14px; margin-top: 14px; }
|
.sso-create-actions { display: grid; gap: 14px; margin-top: 14px; }
|
||||||
.sso-create-actions .text-button { background: none; border: none; color: var(--muted); }
|
.sso-create-actions .text-button { background: none; border: none; color: var(--muted); }
|
||||||
|
.host-context-bar { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:14px 32px; border-bottom:1px solid var(--line); background:var(--surface,#fff); color:var(--muted); font-size:13px; }
|
||||||
|
.host-context-bar > span { min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
||||||
|
.host-context-bar b { color:var(--ink); font-weight:600; }
|
||||||
|
.host-context-bar button { flex:0 0 auto; min-height:34px; white-space:nowrap; display:inline-flex; align-items:center; gap:6px; }
|
||||||
|
.overview-actions { display:flex; flex-wrap:nowrap; gap:10px; }
|
||||||
|
.overview-actions > button { white-space:nowrap; flex:0 0 auto; }
|
||||||
|
.table-panel .user-host-table { min-width:960px; }
|
||||||
|
.user-host-table td:nth-child(2) { max-width:300px; }
|
||||||
|
.user-host-table td:nth-child(2) :is(b,small) { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
||||||
|
.user-host-table td:last-child,.user-host-table th:last-child { position:sticky; right:0; width:116px; background:var(--surface,#fff); box-shadow:-8px 0 12px -12px #526580; z-index:1; white-space:nowrap; }
|
||||||
|
.user-host-table tbody tr:hover td:last-child { background:var(--surface-subtle,#fafcff); }
|
||||||
|
.host-enter-button { display:inline-flex; align-items:center; min-height:32px; padding:5px 10px; color:var(--blue-strong); border:1px solid var(--line); border-radius:6px; background:var(--surface,#fff); white-space:nowrap; }
|
||||||
|
.host-enter-button:hover { background:var(--blue-soft); border-color:var(--blue); }
|
||||||
|
.table-scroll td > .row-actions,.admin-table-v2 td > .row-actions { flex-wrap:nowrap; width:max-content; max-width:none; }
|
||||||
|
td.row-actions { display:table-cell; white-space:nowrap; }
|
||||||
|
.row-actions > button { flex-shrink:0; white-space:nowrap; }
|
||||||
|
.host-row-actions { display:flex; flex-wrap:nowrap; gap:12px; min-width:max-content; }
|
||||||
|
.host-row-actions .danger-text { border-left:1px solid var(--line); padding-left:12px; }
|
||||||
|
.sites-row .site-actions { flex-wrap:nowrap; min-width:0; max-width:100%; overflow-x:auto; overscroll-behavior-x:contain; scrollbar-width:thin; padding-bottom:5px; }
|
||||||
|
@media (max-width:700px) {
|
||||||
|
.host-context-bar { padding:12px 16px; gap:8px; }
|
||||||
|
.host-context-bar button { padding:6px 9px; font-size:12px; }
|
||||||
|
.host-actions { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:9px; }
|
||||||
|
.host-actions button { width:auto; justify-content:center; min-width:0; padding:9px 6px; white-space:nowrap; }
|
||||||
|
.host-info-card > header { flex-wrap:nowrap; gap:8px; }
|
||||||
|
.host-info-card > header > div { gap:7px; min-width:0; }
|
||||||
|
.host-info-card > header > div h2 { font-size:14px; overflow-wrap:anywhere; }
|
||||||
|
.host-info-card > header > button { flex-shrink:0; padding:7px 9px; white-space:nowrap; }
|
||||||
|
.table-panel .panel-toolbar { align-items:flex-start; }
|
||||||
|
}
|
||||||
@media (min-width: 980px) {
|
@media (min-width: 980px) {
|
||||||
.dns-credential-row { grid-template-columns: minmax(160px,1.2fr) 110px minmax(150px,1fr) 140px minmax(258px,auto); gap: 16px; }
|
.dns-credential-row { grid-template-columns: minmax(160px,1.2fr) 110px minmax(150px,1fr) 140px minmax(258px,auto); gap: 16px; }
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user