From faaa614cee6d5bef76a62690ecd2471985c376cc Mon Sep 17 00:00:00 2001 From: canglan Date: Sun, 15 Nov 2026 18:57:02 +0800 Subject: [PATCH] feat: add folder uploads and archives with simpler account and plan forms --- .gitignore | 1 + README.md | 4 +- backend/internal/httpapi/account_identity.go | 12 ++ .../account_identity_integration_test.go | 138 +++++++++++++ backend/internal/httpapi/admin.go | 20 +- backend/internal/httpapi/admin_batches.go | 27 ++- backend/internal/httpapi/files.go | 10 +- backend/internal/httpapi/resource_crud.go | 2 +- .../httpapi/resource_crud_integration_test.go | 133 ++++++++++++- backend/internal/httpapi/upload_batch.go | 183 ++++++++++++++++++ backend/internal/httpapi/upload_batch_test.go | 56 ++++++ backend/internal/nodefiles/operations.go | 100 ++++++++++ backend/internal/nodefiles/operations_test.go | 64 ++++++ backend/internal/store/models.go | 7 +- backend/internal/store/resource_crud.go | 3 +- backend/internal/store/store.go | 10 +- deploy/activate-production.sh | 2 +- deploy/activate-test.sh | 2 +- deploy/nginx/sea-vhost.conf | 2 +- docs/README.md | 5 +- docs/handover-2026-10-30.md | 4 +- docs/hosting-operations.md | 4 +- docs/release-v0.1.0-rc.5.md | 29 +++ docs/resource-management.md | 2 +- frontend/package.json | 1 + frontend/src/AdminActions.test.tsx | 52 ++++- frontend/src/AdminBatches.test.tsx | 2 +- frontend/src/App.tsx | 6 +- frontend/src/FileManager.test.tsx | 41 ++++ frontend/src/ProjectState.test.tsx | 19 ++ frontend/src/ResourceEditors.test.tsx | 6 +- frontend/src/api.ts | 13 +- frontend/src/batchJSON.ts | 4 +- frontend/src/components/AdminBatches.tsx | 4 +- frontend/src/components/AdminConsole.tsx | 60 +++++- frontend/src/components/CreateProject.tsx | 3 +- frontend/src/components/FileManager.tsx | 56 ++++-- frontend/src/components/HostProvisioning.tsx | 4 +- frontend/src/components/ResourceEditors.tsx | 2 +- frontend/src/hostName.ts | 3 + frontend/src/styles/components.css | 2 + 41 files changed, 1027 insertions(+), 71 deletions(-) create mode 100644 backend/internal/httpapi/account_identity.go create mode 100644 backend/internal/httpapi/account_identity_integration_test.go create mode 100644 backend/internal/httpapi/upload_batch.go create mode 100644 backend/internal/httpapi/upload_batch_test.go create mode 100644 docs/release-v0.1.0-rc.5.md create mode 100644 frontend/src/hostName.ts diff --git a/.gitignore b/.gitignore index d246cb1..807aeb9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ frontend/node_modules/ frontend/dist/ +frontend/dist-demo/ frontend/*.tsbuildinfo frontend/vite.config.js frontend/vite.config.d.ts diff --git a/README.md b/README.md index 50c5d85..dfef83a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ # 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 安全配置。 diff --git a/backend/internal/httpapi/account_identity.go b/backend/internal/httpapi/account_identity.go new file mode 100644 index 0000000..3a67273 --- /dev/null +++ b/backend/internal/httpapi/account_identity.go @@ -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]) +} diff --git a/backend/internal/httpapi/account_identity_integration_test.go b/backend/internal/httpapi/account_identity_integration_test.go new file mode 100644 index 0000000..7f9df63 --- /dev/null +++ b/backend/internal/httpapi/account_identity_integration_test.go @@ -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") +} diff --git a/backend/internal/httpapi/admin.go b/backend/internal/httpapi/admin.go index e2d70ce..5099c11 100644 --- a/backend/internal/httpapi/admin.go +++ b/backend/internal/httpapi/admin.go @@ -85,6 +85,7 @@ func (s *Server) adminTenants(w http.ResponseWriter, r *http.Request) { } var input struct { Slug string `json:"slug"` + LoginName string `json:"loginName"` Name string `json:"name"` Email string `json:"email"` DisplayName string `json:"displayName"` @@ -96,9 +97,18 @@ func (s *Server) adminTenants(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusBadRequest, "请求格式错误") 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)) - if !tenantSlugPattern.MatchString(input.Slug) || strings.TrimSpace(input.Name) == "" || len(input.Password) < 12 { - writeError(w, http.StatusUnprocessableEntity, "用户标识、名称或密码不符合要求") + if !tenantSlugPattern.MatchString(input.Slug) || strings.TrimSpace(input.Name) == "" || (len(input.Password) < 12 || len(input.Password) > 72) { + writeError(w, http.StatusUnprocessableEntity, "登录账号、显示名称或密码不符合要求") return } 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.DisplayName = strings.TrimSpace(input.DisplayName) 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 } if _, err = s.store.Plan(r.Context(), input.PlanID); err != nil { writeError(w, http.StatusUnprocessableEntity, "所选套餐不存在") 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 { - writeError(w, http.StatusUnprocessableEntity, "无法创建用户,请检查标识或邮箱是否重复") + writeError(w, http.StatusUnprocessableEntity, "无法创建用户,请检查登录账号或邮箱是否重复") return } user := currentUser(r) diff --git a/backend/internal/httpapi/admin_batches.go b/backend/internal/httpapi/admin_batches.go index d2eaa18..81c0afa 100644 --- a/backend/internal/httpapi/admin_batches.go +++ b/backend/internal/httpapi/admin_batches.go @@ -27,6 +27,7 @@ import ( type batchRow struct { Name string `json:"name,omitempty"` Slug string `json:"slug,omitempty"` + LoginName string `json:"loginName,omitempty"` Email string `json:"email,omitempty"` DisplayName string `json:"displayName,omitempty"` Password string `json:"password,omitempty"` @@ -128,6 +129,16 @@ func (s *Server) normalizeBatch(ctx context.Context, input *batchRequest) ([]bat var validation error switch input.Operation { 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.Email = strings.ToLower(strings.TrimSpace(row.Email)) row.Name = strings.TrimSpace(row.Name) @@ -150,17 +161,24 @@ func (s *Server) normalizeBatch(ctx context.Context, input *batchRequest) ([]bat } key := "user:" + row.Email 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("同批邮箱或用户标识重复") } seen[key] = true seen[slugKey] = true + if row.LoginName != "" { + seen["login:"+row.LoginName] = true + } if validation == nil { exists, e := s.store.AccountIdentityExists(ctx, row.Slug, row.Email) if e != nil { validation = errors.New("无法核对现有账号") } else if exists { 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 @@ -610,9 +628,12 @@ func (s *Server) performBatchRow(ctx context.Context, operation string, row batc 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.Login = row.Email + result.Login = row.LoginName + if result.Login == "" { + result.Login = row.Email + } result.Password = row.Password return result, err } diff --git a/backend/internal/httpapi/files.go b/backend/internal/httpapi/files.go index f1adcb7..0bbc79d 100644 --- a/backend/internal/httpapi/files.go +++ b/backend/internal/httpapi/files.go @@ -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) { - r.Body = http.MaxBytesReader(w, r.Body, s.cfg.UploadLimitBytes+1<<20) - if err := r.ParseMultipartForm(s.cfg.UploadLimitBytes); err != nil { - writeError(w, http.StatusRequestEntityTooLarge, uploadLimitMessage(s.cfg.UploadLimitBytes)) + r.Body = http.MaxBytesReader(w, r.Body, batchUploadLimit+1<<20) + if err := r.ParseMultipartForm(1 << 20); err != nil { + writeError(w, http.StatusRequestEntityTooLarge, "上传请求过大:单批总量不超过 30 MB,单文件不超过 20 MB") return } if r.MultipartForm != nil { 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") if err != nil { writeError(w, http.StatusBadRequest, "缺少上传文件") diff --git a/backend/internal/httpapi/resource_crud.go b/backend/internal/httpapi/resource_crud.go index 1410bf9..08ee001 100644 --- a/backend/internal/httpapi/resource_crud.go +++ b/backend/internal/httpapi/resource_crud.go @@ -54,7 +54,7 @@ func (s *Server) adminAccount(w http.ResponseWriter, r *http.Request) { input.Email = strings.ToLower(strings.TrimSpace(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 { - writeError(w, 422, "请检查用户名称、联系人姓名和登录邮箱") + writeError(w, 422, "请检查显示名称和登录邮箱") return } err = s.store.UpdateAccount(r.Context(), id, input) diff --git a/backend/internal/httpapi/resource_crud_integration_test.go b/backend/internal/httpapi/resource_crud_integration_test.go index 3bb427c..6c718da 100644 --- a/backend/internal/httpapi/resource_crud_integration_test.go +++ b/backend/internal/httpapi/resource_crud_integration_test.go @@ -1,14 +1,18 @@ package httpapi import ( + "archive/tar" "bytes" + "compress/gzip" "context" "encoding/json" "fmt" "github.com/go-sql-driver/mysql" + "mime/multipart" "net/http" "net/http/httptest" "os" + "path/filepath" "sea-vhost/internal/auth" "sea-vhost/internal/config" "sea-vhost/internal/isolation" @@ -55,7 +59,7 @@ func TestResourceCRUDMySQL(t *testing.T) { secret := "crud-test-session-secret-at-least-thirty-two-characters" 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") - 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) must(err) 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()} isolator := pythonInstallIsolation{Mock: isolation.Mock{Root: root}, panel: p} 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.Header.Set("Origin", "https://control.example.invalid") 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"}) must(err) 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: "/"}) must(err) 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. 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") - 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"}) must(e) workerCtx, stopWorker := context.WithCancel(ctx) diff --git a/backend/internal/httpapi/upload_batch.go b/backend/internal/httpapi/upload_batch.go new file mode 100644 index 0000000..0bd9724 --- /dev/null +++ b/backend/internal/httpapi/upload_batch.go @@ -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}) +} diff --git a/backend/internal/httpapi/upload_batch_test.go b/backend/internal/httpapi/upload_batch_test.go new file mode 100644 index 0000000..fe3f2db --- /dev/null +++ b/backend/internal/httpapi/upload_batch_test.go @@ -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") + } +} diff --git a/backend/internal/nodefiles/operations.go b/backend/internal/nodefiles/operations.go index 7fcd6b0..30c5859 100644 --- a/backend/internal/nodefiles/operations.go +++ b/backend/internal/nodefiles/operations.go @@ -1,8 +1,10 @@ package nodefiles import ( + "archive/tar" "archive/zip" "bytes" + "compress/gzip" "crypto/rand" "encoding/hex" "encoding/json" @@ -187,6 +189,13 @@ func advanced(root *os.Root, q Request, out *Response) error { if e != nil || len(data) > MaxFileBytes { 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))) if e != nil { return e @@ -421,3 +430,94 @@ func listTrash(root *os.Root, out *Response) error { } 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 +} diff --git a/backend/internal/nodefiles/operations_test.go b/backend/internal/nodefiles/operations_test.go index 51932da..e2d6485 100644 --- a/backend/internal/nodefiles/operations_test.go +++ b/backend/internal/nodefiles/operations_test.go @@ -1,8 +1,10 @@ package nodefiles import ( + "archive/tar" "archive/zip" "bytes" + "compress/gzip" "os" "path/filepath" "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) + } + } + }) + } +} diff --git a/backend/internal/store/models.go b/backend/internal/store/models.go index 68cd1fb..288d919 100644 --- a/backend/internal/store/models.go +++ b/backend/internal/store/models.go @@ -237,6 +237,7 @@ type Activity struct { } type TenantSummary struct { + LoginName string `json:"loginName"` ID uint64 `json:"id"` Slug string `json:"slug"` Name string `json:"name"` @@ -299,9 +300,9 @@ type AdminActivity struct { } type NewTenant struct { - Slug, Name, Email, DisplayName, Password string - PlanID uint64 - ExpiresAt *time.Time + Slug, Name, Email, DisplayName, Password, LoginName string + PlanID uint64 + ExpiresAt *time.Time } type TenantBackup struct { diff --git a/backend/internal/store/resource_crud.go b/backend/internal/store/resource_crud.go index 1654d66..bd18873 100644 --- a/backend/internal/store/resource_crud.go +++ b/backend/internal/store/resource_crud.go @@ -12,6 +12,7 @@ import ( // references cannot accidentally grant access to a different customer. type AccountProfile struct { ID uint64 `json:"id"` + LoginName string `json:"loginName"` Slug string `json:"slug"` Name string `json:"name"` Email string `json:"email"` @@ -21,7 +22,7 @@ type AccountProfile struct { func (s *Store) AccountProfile(ctx context.Context, id uint64) (AccountProfile, error) { 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) { err = ErrNotFound } diff --git a/backend/internal/store/store.go b/backend/internal/store/store.go index b075931..99595fc 100644 --- a/backend/internal/store/store.go +++ b/backend/internal/store/store.go @@ -1971,7 +1971,7 @@ func (s *Store) CreatePlan(ctx context.Context, input NewPlan) (uint64, 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 { return nil, err } @@ -1980,7 +1980,7 @@ func (s *Store) ListTenants(ctx context.Context) ([]TenantSummary, error) { for rows.Next() { var item TenantSummary 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 } 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) { + loginName := strings.ToLower(strings.TrimSpace(input.LoginName)) + if loginName == "" { + loginName = strings.ToLower(input.Email) + } hash, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost) if err != nil { return 0, err @@ -2305,7 +2309,7 @@ func (s *Store) CreateTenant(ctx context.Context, input NewTenant) (uint64, erro 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 } if err = tx.Commit(); err != nil { diff --git a/deploy/activate-production.sh b/deploy/activate-production.sh index 7b45015..ceedcd2 100755 --- a/deploy/activate-production.sh +++ b/deploy/activate-production.sh @@ -135,7 +135,7 @@ server { root /opt/sea-vhost/web; 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 X-Content-Type-Options "nosniff" always; diff --git a/deploy/activate-test.sh b/deploy/activate-test.sh index d034741..b6a8630 100755 --- a/deploy/activate-test.sh +++ b/deploy/activate-test.sh @@ -73,7 +73,7 @@ server { root /opt/sea-vhost/web; index index.html; - client_max_body_size 21m; + client_max_body_size 31m; add_header X-Content-Type-Options "nosniff" always; add_header X-Frame-Options "DENY" always; diff --git a/deploy/nginx/sea-vhost.conf b/deploy/nginx/sea-vhost.conf index e9cc9a3..c35f7f2 100644 --- a/deploy/nginx/sea-vhost.conf +++ b/deploy/nginx/sea-vhost.conf @@ -26,7 +26,7 @@ server { root /opt/sea-vhost/web; index index.html; - client_max_body_size 21m; + client_max_body_size 31m; proxy_hide_header Content-Security-Policy; diff --git a/docs/README.md b/docs/README.md index c0d53b3..e0829cf 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,12 +1,13 @@ # 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) | 功能、正常操作流程、验证范围和剩余工作 | | [业务功能与按钮说明](business-actions.md) | 各页面操作用途、DNS 凭据/解析/证书的区别及业务表达缺口 | | [日常操作与管理端 API](hosting-operations.md) | 用户与主机开通、JSON 批量管理、网站、文件、计划任务、财务站对接 | diff --git a/docs/handover-2026-10-30.md b/docs/handover-2026-10-30.md index 69997bb..d9f2e98 100644 --- a/docs/handover-2026-10-30.md +++ b/docs/handover-2026-10-30.md @@ -1,6 +1,8 @@ # 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`,尚无数据表或管理员;安装令牌及数据库密码由单独的私密交付信息提供,不进入源码包。重装前已验证完整备份,宝塔其他资源、控制台证书和已安装运行环境保留。 diff --git a/docs/hosting-operations.md b/docs/hosting-operations.md index a17da2f..6c787b3 100644 --- a/docs/hosting-operations.md +++ b/docs/hosting-operations.md @@ -26,7 +26,7 @@ "version": 1, "operation": "create_users", "rows": [ - {"slug":"customer01","name":"客户一","email":"customer01@vhost.ser888.cn","password":""} + {"loginName":"customer01","displayName":"客户一","email":"customer01@vhost.ser888.cn","password":""} ] } ``` @@ -55,7 +55,7 @@ PHP 网站创建后即可上传程序。Node.js、Python、Go、Java 网站先 日志可切换访问、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 策略依证书配置确定。 diff --git a/docs/release-v0.1.0-rc.5.md b/docs/release-v0.1.0-rc.5.md new file mode 100644 index 0000000..c8ab24a --- /dev/null +++ b/docs/release-v0.1.0-rc.5.md @@ -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)。 diff --git a/docs/resource-management.md b/docs/resource-management.md index 714afe4..ff7bcdb 100644 --- a/docs/resource-management.md +++ b/docs/resource-management.md @@ -12,7 +12,7 @@ ## 用户 -可以创建、查询、编辑用户名称、联系人和登录邮箱,以及启停、删除用户。修改登录邮箱会撤销已有用户会话。删除前必须解绑或转移所有主机,包括回收中的主机,并处理未完成的归属任务。删除后停止计划任务、撤销会话并保留内部审计关联;历史用户标识和邮箱保持占用,避免旧导入或外部引用被另一用户接管。批量启用及旧到期接口不能重新激活已删除用户。 +创建用户填写登录账号、显示名称、邮箱和密码,内部用户标识自动生成。新用户可用登录账号或邮箱登录,原有用户仍保留原登录方式。可以查询、编辑显示名称和登录邮箱,以及启停、删除用户;登录账号在资料编辑页只读。修改登录邮箱会撤销已有用户会话。删除前必须解绑或转移所有主机,包括回收中的主机,并处理未完成的归属任务。删除后停止计划任务、撤销会话并保留内部审计关联;历史用户标识和邮箱保持占用,避免旧导入或外部引用被另一用户接管。批量启用及旧到期接口不能重新激活已删除用户。 ## 节点 diff --git a/frontend/package.json b/frontend/package.json index 7848ce1..74b2719 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -6,6 +6,7 @@ "scripts": { "dev": "vite --host 0.0.0.0", "build": "tsc -b && vite build", + "build:demo": "tsc -b && vite build --mode demo --outDir dist-demo", "preview": "vite preview --host 0.0.0.0", "test": "vitest run" }, diff --git a/frontend/src/AdminActions.test.tsx b/frontend/src/AdminActions.test.tsx index 9566d99..5fdd384 100644 --- a/frontend/src/AdminActions.test.tsx +++ b/frontend/src/AdminActions.test.tsx @@ -1,7 +1,8 @@ import '@testing-library/jest-dom/vitest'; import {cleanup,fireEvent,render,screen,waitFor} from '@testing-library/react'; 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 {AdminLogs} from './components/AdminLogs'; import {ResourceCenter} from './components/ResourceCenter'; @@ -10,6 +11,55 @@ import {demoPlan} from './data'; import {initialProjects} from './data'; 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(); + 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(); + 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(); + 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(); + 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(); + 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()=>{ const create=vi.fn().mockRejectedValue(new Error('套餐名称重复')); render();fireEvent.change(screen.getByLabelText('套餐名称'),{target:{value:'重复套餐'}});fireEvent.click(screen.getByRole('button',{name:'创建套餐'})); diff --git a/frontend/src/AdminBatches.test.tsx b/frontend/src/AdminBatches.test.tsx index 0bffcff..a2bafe3 100644 --- a/frontend/src/AdminBatches.test.tsx +++ b/frontend/src/AdminBatches.test.tsx @@ -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}); render(); 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}$/); 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'); diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 107cf70..5a38717 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,3 +1,4 @@ +import {randomHostName} from './hostName'; import {UserSchedules} from './components/UserSchedules'; import {useLiveDashboard} from './useLiveDashboard'; import {ResourceCharts} from './components/ResourceCharts'; @@ -24,7 +25,8 @@ import { demoActivities, demoPlan, demoRuntimeVersions, demoUsage, initialProjec import type { ActivityEntry, APIProject, Plan, Project, ProjectDraft, ProjectStatus, Runtime, RuntimeCatalog, Usage } from './types'; 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 adminPreview = import.meta.env.DEV && new URLSearchParams(window.location.search).get('admin') === '1'; const [page, setPage] = useState('overview'); @@ -134,7 +136,7 @@ export function App() { } const project: Project = { 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, domain: '', path: '', diff --git a/frontend/src/FileManager.test.tsx b/frontend/src/FileManager.test.tsx index b733f43..bd0b24d 100644 --- a/frontend/src/FileManager.test.tsx +++ b/frontend/src/FileManager.test.tsx @@ -8,6 +8,47 @@ import {initialProjects} from './data'; 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'}]}); +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();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();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();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();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()=>{ vi.spyOn(api,'files').mockResolvedValue(listing('program.bin')); render(); diff --git a/frontend/src/ProjectState.test.tsx b/frontend/src/ProjectState.test.tsx index 4e7bb24..8befcce 100644 --- a/frontend/src/ProjectState.test.tsx +++ b/frontend/src/ProjectState.test.tsx @@ -7,6 +7,25 @@ import {demoPlan,demoUsage} from './data'; import {RunPathModal} from './components/RunPathModal'; import {initialProjects} from './data'; 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(); + 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(); + 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()=>{ 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); diff --git a/frontend/src/ResourceEditors.test.tsx b/frontend/src/ResourceEditors.test.tsx index afd9c4e..a54c104 100644 --- a/frontend/src/ResourceEditors.test.tsx +++ b/frontend/src/ResourceEditors.test.tsx @@ -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}; vi.spyOn(api,'accountProfile').mockResolvedValue(profile);const update=vi.spyOn(api,'updateAccount').mockResolvedValue(); render(); - await screen.findByLabelText('用户名称');expect(screen.getByRole('button',{name:'删除用户'})).toBeDisabled(); - fireEvent.change(screen.getByLabelText('用户名称'),{target:{value:'新名称'}});fireEvent.click(screen.getByRole('button',{name:'保存用户资料'})); - await waitFor(()=>expect(update).toHaveBeenCalledWith(4,{...profile,name:'新名称'})); + await screen.findByLabelText('显示名称');expect(screen.getByRole('button',{name:'删除用户'})).toBeDisabled(); + fireEvent.change(screen.getByLabelText('显示名称'),{target:{value:'新名称'}});fireEvent.click(screen.getByRole('button',{name:'保存用户资料'})); + await waitFor(()=>expect(update).toHaveBeenCalledWith(4,{...profile,name:'新名称',displayName:'新名称'})); }); it('keeps local node transport and storage root immutable and disallows deletion',()=>{ render(); diff --git a/frontend/src/api.ts b/frontend/src/api.ts index b962e44..a213713 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -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 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 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 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 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 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[];} @@ -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 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 UploadResult {name:string;size:number;success:boolean;status:number;error?:string} export interface FileListing { path: string; entries: FileEntry[]; uploadLimit: number; } export interface DatabaseSetup { host: string; port: number; name: string; user: string; password: string; } export interface PanelSetup { url: string; apiKey: string; tlsInsecure: boolean; } @@ -193,6 +194,12 @@ export const api = { return response.text(); }, 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) => { 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 }); diff --git a/frontend/src/batchJSON.ts b/frontend/src/batchJSON.ts index da41f65..35eb3a0 100644 --- a/frontend/src/batchJSON.ts +++ b/frontend/src/batchJSON.ts @@ -1,6 +1,6 @@ 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 booleans=new Set(['stopServices','resumeOwnership','setExpiry','autoSSL']); @@ -28,7 +28,7 @@ export function parseBatchJSON(source:string,operation:BatchOperation):BatchRow[ } 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==='user_enable'||operation==='user_disable'?{account:'demo-0001@vhost.ser888.cn'} :operation==='assign_hosts'?{host:'sv0123456789',owner:'',credentialMode:'preserve',stopServices:true,resumeOwnership:false} diff --git a/frontend/src/components/AdminBatches.tsx b/frontend/src/components/AdminBatches.tsx index ef3e147..95b4069 100644 --- a/frontend/src/components/AdminBatches.tsx +++ b/frontend/src/components/AdminBatches.tsx @@ -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}))} 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 位小写字母、数字或连字符'); - 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 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,
{mode==='quantity'?<>:null} - {operation==='create_users'&&mode==='quantity'?<>:null} + {operation==='create_users'&&mode==='quantity'?<>:null} {operation==='create_hosts'||operation==='assign_hosts'?:null} {operation==='assign_hosts'?<>:null} {operation==='create_hosts'?<>:null} diff --git a/frontend/src/components/AdminConsole.tsx b/frontend/src/components/AdminConsole.tsx index a18e258..5781f46 100644 --- a/frontend/src/components/AdminConsole.tsx +++ b/frontend/src/components/AdminConsole.tsx @@ -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 { 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 { formatBytes } from '../format'; import type { Plan } from '../types'; import { Brand } from './Brand'; 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;users:Tenant[];query:string;setQuery:(value:string)=>void;create:()=>void;expiry:(id:number,value?:string)=>Promise;enter?:(id:number)=>void;bulk:(selection:BatchSelection)=>void}){ const [editing,setEditing]=useState(),[deleting,setDeleting]=useState(); - const [selected,setSelected]=useState([]);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([]);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 run=(operation:'user_enable'|'user_disable',targets=ids)=>bulk({operation,rows:targets.map(accountId=>({accountId}))}); - return <>
}/>
共 {list.length} 个用户 · 已选 {ids.length} 个
{list.map(item=>)}
0&&list.every(item=>ids.includes(item.id))} onChange={event=>setSelected(event.target.checked?list.map(item=>item.id):[])}/>用户虚拟主机状态操作
change(item.id,event.target.checked)}/>{item.name}{item.slug}{item.projectCount}{item.status==='active'?'正常':'已停用'}
{deleting?setDeleting(undefined)} onChanged={refresh}/>:null}{editing?setEditing(undefined)} onChanged={refresh}/>:null}; + return <>
}/>
共 {list.length} 个用户 · 已选 {ids.length} 个
{list.map(item=>)}
0&&list.every(item=>ids.includes(item.id))} onChange={event=>setSelected(event.target.checked?list.map(item=>item.id):[])}/>用户虚拟主机状态操作
change(item.id,event.target.checked)}/>{item.name}{item.loginName||item.slug}{item.projectCount}{item.status==='active'?'正常':'已停用'}
{deleting?setDeleting(undefined)} onChanged={refresh}/>:null}{editing?setEditing(undefined)} onChanged={refresh}/>:null}; } export function Plans({ plans, create,save,changed }: { plans: Plan[]; create: () => void;save:(input:PlanInput)=>Promise;changed?:()=>Promise }) { const [copy,setCopy]=useState(),[removing,setRemoving]=useState(),[confirmation,setConfirmation]=useState(''),[busy,setBusy]=useState(false),[error,setError]=useState(''),[hidden,setHidden]=useState([]); - return
创建套餐} />
{plans.filter(p=>!hidden.includes(p.id)).map((plan) =>

{plan.name}

存储空间
{formatBytes(plan.storageBytes)}
数据库空间
{formatBytes(plan.databaseBytes)}
月流量
{formatBytes(plan.bandwidthBytes)}
HTTP / FTP 限速
{plan.bandwidthMbps ? `${plan.bandwidthMbps} Mbps` : '不限速'}
进程上限
{plan.processLimit}
每主机网站数
{plan.projectLimit}
FTP 账号
{plan.ftpLimit}
数据库
{plan.databaseLimit}
{plan.deleteBlockedReason||plan.id===1?

{plan.deleteBlockedReason||'系统默认套餐不能删除'}

:null}
)}
{copy?setCopy(undefined)} onCreate={async input=>{await save(input);setCopy(undefined)}}/>:null}{removing?
{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)}}}>

删除未使用套餐

仅允许删除未被主机或历史账号引用的套餐,此操作不能恢复。

{error?

{error}

:null}
:null}
; } + return
创建套餐} />
{plans.filter(p=>!hidden.includes(p.id)).map((plan) =>

{plan.name}

存储空间
{`${(plan.storageBytes / planMB).toLocaleString('zh-CN', { maximumFractionDigits: 3 })} MB`}
数据库空间
{`${(plan.databaseBytes / planMB).toLocaleString('zh-CN', { maximumFractionDigits: 3 })} MB`}
月流量
{`${(plan.bandwidthBytes / planGB).toLocaleString('zh-CN', { maximumFractionDigits: 6 })} GB`}
HTTP / FTP 限速
{plan.bandwidthMbps ? `${plan.bandwidthMbps} Mbps` : '不限速'}
进程上限
{plan.processLimit}
每主机网站数
{plan.projectLimit}
FTP 账号
{plan.ftpLimit}
数据库
{plan.databaseLimit}
{plan.deleteBlockedReason||plan.id===1?

{plan.deleteBlockedReason||'系统默认套餐不能删除'}

:null}
)}
{copy?setCopy(undefined)} onCreate={async input=>{await save(input);setCopy(undefined)}}/>:null}{removing?
{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)}}}>

删除未使用套餐

仅允许删除未被主机或历史账号引用的套餐,此操作不能恢复。

{error?

{error}

:null}
:null}
; } function Lifecycle({projects,onManage}:{projects:AdminProject[];onManage:()=>void}){return
管理主机 / 恢复}/>{projects.map(p=>)}
虚拟主机用户 / 节点当前阶段到期时间
{p.hostName}{p.tenantName} / #{p.nodeId}{p.expiresAt?dateText(p.expiresAt):"长期使用"}
} function Table({ children }: { children: ReactNode }) { return
{children}
; } -function UserForm({ plans, onClose, onCreate }: { plans: Plan[]; onClose: () => void; onCreate: (input: Record) => Promise }) { const [busy, setBusy] = useState(false); const [error, setError] = useState(''); return
{ 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); } }}>

创建用户

创建登录账号后,可继续为该用户新增多个虚拟主机。

{error ?

{error}

: null}
; } -export function PlanForm({ onClose, onCreate,initial }: { initial?:Plan; onClose: () => void; onCreate: (input: PlanInput) => Promise }) { const [busy, setBusy] = useState(false);const [error,setError]=useState(''); return
{ 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); } }}>

{initial?'复制资源套餐':'创建资源套餐'}

{[['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]) => )}
{error?

{error}

:null}
; } +export function UserForm({ plans, onClose, onCreate }: { plans: Plan[]; onClose: () => void; onCreate: (input: Record) => Promise }) { const [busy, setBusy] = useState(false); const [error, setError] = useState(''); return
{ 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); } }}>

创建用户

创建登录账号后,可继续为该用户新增多个虚拟主机。

{error ?

{error}

: null}
; } +const planMB = 1024 ** 2; +const planGB = 1024 ** 3; + +export function PlanForm({ onClose, onCreate, initial }: { initial?: Plan; onClose: () => void; onCreate: (input: PlanInput) => Promise }) { + 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
{ + 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); + } + }}>

{initial ? '复制资源套餐' : '创建资源套餐'}

+
{fields.map(field => )}
+ {error ?

{error}

: null} +
+
; +} function AdoptionForm({users,plans,onClose,onComplete}:{users:Tenant[];plans:Plan[];onClose:()=>void;onComplete:()=>Promise}){return } diff --git a/frontend/src/components/CreateProject.tsx b/frontend/src/components/CreateProject.tsx index 09dc82d..eeb462e 100644 --- a/frontend/src/components/CreateProject.tsx +++ b/frontend/src/components/CreateProject.tsx @@ -1,3 +1,4 @@ +import {randomHostName} from '../hostName'; import { ArrowLeft, Box, Database, HardDrive, Network, ShieldCheck } from 'lucide-react'; import { useMemo, useState } from 'react'; import { formatBytes } from '../format'; @@ -18,7 +19,7 @@ interface CreateProjectProps { export function CreateProject({ runtimeVersions, rootDomain, projectRoot, plan, domainApproval, onCancel, onSubmit }: CreateProjectProps) { const initialRuntime = runtimes.find((runtime) => runtimeVersions[runtime]?.length) ?? 'PHP'; - const [draft, setDraft] = useState({ name: 'blog-demo', runtime: initialRuntime, version: runtimeVersions[initialRuntime]?.[0] ?? '', runPath: '/', customDomain: '', autoSSL: true }); + const [draft, setDraft] = useState(() => ({ 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 assignedDomain = `<随机主机名>.${rootDomain}`; const root = `${projectRoot.replace(/\/+$/, '')}/<随机主机名>`; diff --git a/frontend/src/components/FileManager.tsx b/frontend/src/components/FileManager.tsx index 06cd78b..d748c44 100644 --- a/frontend/src/components/FileManager.tsx +++ b/frontend/src/components/FileManager.tsx @@ -13,6 +13,7 @@ export function FileManager({ projects, initialProjectID, live = true }: { proje const previousInitialProject = useRef(initialProjectID); const [entries, setEntries] = useState([]); const [uploadLimit, setUploadLimit] = useState(20 * 1024 ** 2); + const [uploadStatus,setUploadStatus]=useState(''); const [busy, setBusy] = useState(false); const [error, setError] = useState(''); 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 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(null); + const folderRef = useRef(null); + const [folderSupported,setFolderSupported]=useState(true); + useEffect(()=>{setFolderSupported('webkitdirectory' in document.createElement('input'))},[]); useEffect(() => { 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); } }, [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) { - if (file.size > uploadLimit) { setError(`单文件不能超过 ${formatBytes(uploadLimit)}`); return; } - if (!live) { setError('预览模式不会写入文件'); return; } - setBusy(true); setError(''); + async function upload(files: File[]) { + if(busy||files.length===0)return; + setError('');setUploadStatus(''); + 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 { - 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(); - } catch (reason) { - if ((reason as { status?: number })?.status === 409 && await confirm('同名文件已存在,是否覆盖?',{title:'覆盖文件',confirmLabel:'覆盖文件',danger:true})) { - try { await api.uploadFile(projectID, path, file, true); await load(); } - catch (retryReason) { setError(message(retryReason, '上传失败')); } - } else setError(message(reason, '上传失败')); - } finally { setBusy(false); if (uploadRef.current) uploadRef.current.value = ''; } + setUploadStatus(`上传完成:成功 ${results.length-failed.length} 个,失败或跳过 ${failed.length} 个`); + if(failed.length)setError(failed.map(result=>`${result.name}:${result.error||'上传失败'}`).join(';')); + } catch(reason){if(currentContext.current===context){await load();setError(message(reason,'上传失败,请刷新目录核对文件'));setUploadStatus('')}} + finally{setBusy(false);reset()} } async function edit(entry: FileEntry) { @@ -111,13 +129,15 @@ export function FileManager({ projects, initialProjectID, live = true }: { proje return
{confirmation}

文件管理

-
{ const file = event.target.files?.[0]; if (file) void upload(file); }} />
+
{void upload(Array.from(event.target.files||[]))}} />{const selected=Array.from(event.target.files||[]);if(!selected.length){setError('所选文件夹没有可上传文件;空目录不会被上传');return}void upload(selected)}} />
+

单批最多 100 个文件、总大小 30 MB,单文件上限 {formatBytes(uploadLimit)};文件夹上传保留目录结构(不含空目录);支持解压 ZIP、TAR、TAR.GZ、TGZ。

+ {uploadStatus?

{uploadStatus}

:null}
{segments.map((segment, index) => / )}
{error && !editor && !operation ?

{error}

: null} -
名称大小修改时间操作
{path ? : null}{visibleEntries.map((entry) =>
{entry.directory||isTextFile(entry)&&entry.size<=1024**2?:{entry.name}}{entry.directory ? '—' : formatBytes(entry.size)}{formatDate(entry.modified)}{!entry.directory && isTextFile(entry) && entry.size <= 1024 ** 2 ? : null}{!entry.directory ? : null}
)}{!loading && !error && entries.length === 0 ?
目录为空
: null}{loading ?
正在读取…
: null}
+
名称大小修改时间操作
{path ? : null}{visibleEntries.map((entry) =>
{entry.directory||isTextFile(entry)&&entry.size<=1024**2?:{entry.name}}{entry.directory ? '—' : formatBytes(entry.size)}{formatDate(entry.modified)}{!entry.directory && isTextFile(entry) && entry.size <= 1024 ** 2 ? : null}{!entry.directory ? : null}{!entry.directory&&isArchive(entry)?:null}
)}{!loading && !error && entries.length === 0 ?
目录为空
: null}{loading ?
正在读取…
: null}
{trashEntries?

主机回收站

{!trashEntries.length?

回收站为空

:trashEntries.map(entry=>
{entry.originalPath}{formatBytes(entry.size)}{formatDate(entry.deletedAt)}
)}
:null} - {operation?
{e.preventDefault();void perform()}}>

{{mkdir:'新建目录',move:'重命名 / 移动',copy:'复制',zip:'压缩 ZIP',extract:'解压 ZIP',restore:'恢复文件'}[operation.action]}

路径均相对于当前主机根目录。目标必须不存在;复制、压缩和解压最多处理 256 MiB,并受套餐剩余空间限制。

{operation.action!=='restore'?:null}{operation.action!=='mkdir'?:null}{error?

{error}

:null}
:null} + {operation?
{e.preventDefault();void perform()}}>

{{mkdir:'新建目录',move:'重命名 / 移动',copy:'复制',zip:'压缩 ZIP',extract:'解压压缩包',restore:'恢复文件'}[operation.action]}

路径均相对于当前主机根目录。目标必须不存在;复制、压缩和解压最多处理 256 MiB,并受套餐剩余空间限制。

{operation.action!=='restore'?:null}{operation.action!=='mkdir'?:null}{error?

{error}

:null}
:null} {editor ?
{ 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); } }}>

{editor.isNew ? '新建文本文件' : '编辑文本文件'}